[ONOS-4744] Leafref implementation and UT
Change-Id: I151797185e0bb1695c0640b667ae76ef87c4d4b0
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafrefListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafrefListener.java
new file mode 100644
index 0000000..6ada8c5
--- /dev/null
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/LeafrefListener.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeaf;
+import org.onosproject.yangutils.datamodel.YangLeafList;
+import org.onosproject.yangutils.datamodel.YangLeafRef;
+import org.onosproject.yangutils.datamodel.YangNode;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.exceptions.DataModelException;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.linker.impl.YangResolutionInfoImpl;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.DataModelUtils.addResolutionInfo;
+import static org.onosproject.yangutils.datamodel.utils.ResolvableStatus.UNRESOLVED;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.LEAFREF_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.EXIT;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructExtendedListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_CURRENT_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.UNHANDLED_PARSED_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * type-body-stmts     = numerical-restrictions /
+ *                       decimal64-specification /
+ *                       string-restrictions /
+ *                       enum-specification /
+ *                       leafref-specification /
+ *                       identityref-specification /
+ *                       instance-identifier-specification /
+ *                       bits-specification /
+ *                       union-specification
+ *
+ * leafref-specification =
+ *                         ;; these stmts can appear in any order
+ *                        path-stmt stmtsep
+ *                        [require-instance-stmt stmtsep]
+ *
+ * ANTLR grammar rule
+ *
+ * typeBodyStatements : numericalRestrictions | stringRestrictions | enumSpecification
+ *                 | leafrefSpecification | identityrefSpecification | instanceIdentifierSpecification
+ *                 | bitsSpecification | unionSpecification;
+ *
+ * leafrefSpecification : (pathStatement (requireInstanceStatement)?) | ((requireInstanceStatement)? pathStatement);
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "leafref" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class LeafrefListener {
+
+    /**
+     * Creates a new leafref listener.
+     */
+    private LeafrefListener() {
+    }
+
+    /**
+     * It is called when parser receives an input matching the grammar rule
+     * (leafref), perform validations and updates the data model tree.
+     *
+     * @param listener listener's object
+     * @param ctx context object of the grammar rule
+     */
+    public static void processLeafrefEntry(TreeWalkListener listener,
+            GeneratedYangParser.LeafrefSpecificationContext ctx) {
+
+        // Check for stack to be non empty.
+        checkStackIsNotEmpty(listener, MISSING_HOLDER, LEAFREF_DATA, "", ENTRY);
+
+        int errorLine = ctx.getStart().getLine();
+        int errorPosition = ctx.getStart().getCharPositionInLine();
+
+        YangLeafRef<?> leafRef = new YangLeafRef<>();
+
+        Parsable typeData = listener.getParsedDataStack().pop();
+
+        if (!(typeData instanceof YangType)) {
+            throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAFREF_DATA,
+                    "", ENTRY));
+        }
+
+        YangType type = (YangType) typeData;
+        type.setDataTypeExtendedInfo(leafRef);
+
+        // Setting by default the value of require-instance as true.
+        leafRef.setRequireInstance(true);
+        Parsable tmpData = listener.getParsedDataStack().peek();
+
+        switch (tmpData.getYangConstructType()) {
+
+            case LEAF_DATA:
+
+                // Parent YANG node of leaf to be added in resolution information.
+                YangLeaf leaf = (YangLeaf) listener.getParsedDataStack().pop();
+                Parsable parentNodeOfLeaf = listener.getParsedDataStack().peek();
+                listener.getParsedDataStack().push(leaf);
+
+                // Verify parent node of leaf.
+                if (!(parentNodeOfLeaf instanceof YangNode)) {
+                    throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAFREF_DATA,
+                            "", ENTRY));
+                }
+
+                leafRef.setResolvableStatus(UNRESOLVED);
+
+                // Add resolution information to the list.
+                YangResolutionInfoImpl resolutionInfo = new YangResolutionInfoImpl<YangLeafRef>(leafRef,
+                        (YangNode) parentNodeOfLeaf, errorLine, errorPosition);
+                addToResolutionList(resolutionInfo);
+                break;
+
+            case LEAF_LIST_DATA:
+
+                // Parent YANG node of leaf-list to be added in resolution information.
+                YangLeafList leafList = (YangLeafList) listener.getParsedDataStack().pop();
+                Parsable parentNodeOfLeafList = listener.getParsedDataStack().peek();
+                listener.getParsedDataStack().push(leafList);
+
+                // Verify parent node of leaf-list.
+                if (!(parentNodeOfLeafList instanceof YangNode)) {
+                    throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAFREF_DATA,
+                            "", ENTRY));
+                }
+
+                leafRef.setResolvableStatus(UNRESOLVED);
+
+                // Add resolution information to the list.
+                YangResolutionInfoImpl resolutionInfoImpl = new YangResolutionInfoImpl<YangLeafRef>(leafRef,
+                        (YangNode) parentNodeOfLeafList, errorLine, errorPosition);
+                addToResolutionList(resolutionInfoImpl);
+                break;
+
+            case TYPEDEF_DATA:
+                /*
+                 * Do not add the leaf ref to resolution list. It needs to be
+                 * added to resolution list, when leaf/leaf list references to
+                 * this typedef. At this time that leaf/leaf-list becomes the
+                 * parent for the leafref.
+                 */
+                break;
+
+            default:
+                throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAFREF_DATA,
+                        "", ENTRY));
+        }
+        listener.getParsedDataStack().push(typeData);
+        listener.getParsedDataStack().push(leafRef);
+    }
+
+    /**
+     * It is called when parser exits from grammar rule (leafref), it performs
+     * validation and updates the data model tree.
+     *
+     * @param listener listener's object
+     * @param ctx context object of the grammar rule
+     */
+    public static void processLeafrefExit(TreeWalkListener listener,
+            GeneratedYangParser.LeafrefSpecificationContext ctx) {
+
+        // Check for stack to be non empty.
+        checkStackIsNotEmpty(listener, MISSING_CURRENT_HOLDER, LEAFREF_DATA, "", EXIT);
+
+        Parsable parsableType = listener.getParsedDataStack().pop();
+        if (!(parsableType instanceof YangLeafRef)) {
+            throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, LEAFREF_DATA,
+                    "", EXIT));
+        }
+    }
+
+    /**
+     * Adds to resolution list.
+     *
+     * @param resolutionInfo resolution information
+     */
+    private static void addToResolutionList(YangResolutionInfoImpl resolutionInfo) {
+
+        try {
+            addResolutionInfo(resolutionInfo);
+        } catch (DataModelException e) {
+            throw new ParserException(constructExtendedListenerErrorMessage(UNHANDLED_PARSED_DATA,
+                    LEAFREF_DATA, "", ENTRY, e.getMessage()));
+        }
+    }
+}
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java
index 05cfdb3..ebf9d97 100644
--- a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/ModuleListener.java
@@ -128,6 +128,8 @@
                     .peek()).resolveSelfFileLinking(ResolvableType.YANG_USES);
             ((YangReferenceResolver) listener.getParsedDataStack()
                     .peek()).resolveSelfFileLinking(ResolvableType.YANG_DERIVED_DATA_TYPE);
+            ((YangReferenceResolver) listener.getParsedDataStack()
+                    .peek()).resolveSelfFileLinking(ResolvableType.YANG_LEAFREF);
         } catch (DataModelException e) {
             LinkerException linkerException = new LinkerException(e.getMessage());
             linkerException.setLine(e.getLineNumber());
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PathListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PathListener.java
new file mode 100644
index 0000000..b02c6f4
--- /dev/null
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/PathListener.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeafRef;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.validatePathArgument;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.PATH_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ *  leafref-specification =
+ *                        ;; these stmts can appear in any order
+ *                        path-stmt stmtsep
+ *                        [require-instance-stmt stmtsep]
+ *
+ * path-stmt           = path-keyword sep path-arg-str stmtend
+ *
+ * ANTLR grammar rule
+ *
+ * leafrefSpecification : (pathStatement (requireInstanceStatement)?) | ((requireInstanceStatement)? pathStatement);
+ *
+ * pathStatement : PATH_KEYWORD path STMTEND;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "path" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class PathListener {
+
+    /**
+     * Creates a new path listener.
+     */
+    private PathListener() {
+    }
+
+    /**
+     * It is called when parser receives an input matching the grammar rule
+     * (path), performs validation and updates the data model tree.
+     *
+     * @param listener listener's object
+     * @param ctx context object of the grammar rule
+     */
+    public static void processPathEntry(TreeWalkListener listener,
+            GeneratedYangParser.PathStatementContext ctx) {
+
+        // Check for stack to be non empty.
+        checkStackIsNotEmpty(listener, MISSING_HOLDER, PATH_DATA, ctx.path().getText(), ENTRY);
+
+        Parsable curData = listener.getParsedDataStack().peek();
+
+        // Checks the holder of path as leafref, else throws error.
+        if (curData instanceof YangLeafRef) {
+
+            // Splitting the path argument and updating it in the datamodel tree.
+            validatePathArgument(ctx.path().getText(), PATH_DATA, ctx, (YangLeafRef) curData);
+        } else {
+            throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, PATH_DATA,
+                    ctx.path().getText(), ENTRY));
+        }
+    }
+}
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RequireInstanceListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RequireInstanceListener.java
new file mode 100644
index 0000000..21c7533
--- /dev/null
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/RequireInstanceListener.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.yangutils.parser.impl.listeners;
+
+import org.onosproject.yangutils.datamodel.YangLeafRef;
+import org.onosproject.yangutils.datamodel.YangType;
+import org.onosproject.yangutils.datamodel.utils.Parsable;
+import org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes;
+import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
+import org.onosproject.yangutils.parser.exceptions.ParserException;
+import org.onosproject.yangutils.parser.impl.TreeWalkListener;
+
+import static org.onosproject.yangutils.datamodel.utils.YangConstructType.REQUIRE_INSTANCE_DATA;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorMessageConstruction.constructListenerErrorMessage;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.getValidBooleanValue;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerValidation.checkStackIsNotEmpty;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.MISSING_HOLDER;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorLocation.ENTRY;
+import static org.onosproject.yangutils.parser.impl.parserutils.ListenerErrorType.INVALID_HOLDER;
+
+/*
+ * Reference: RFC6020 and YANG ANTLR Grammar
+ *
+ * ABNF grammar as per RFC6020
+ * require-instance-stmt = require-instance-keyword sep
+ *                            require-instance-arg-str stmtend
+ *
+ * require-instance-arg-str = < a string that matches the rule
+ *                            require-instance-arg >
+ *
+ * require-instance-arg = true-keyword / false-keyword
+ *
+ * ANTLR grammar rule
+ *
+ * requireInstanceStatement : REQUIRE_INSTANCE_KEYWORD requireInstance STMTEND;
+ *
+ * requireInstance : string;
+ */
+
+/**
+ * Represents listener based call back function corresponding to the
+ * "require-instance" rule defined in ANTLR grammar file for corresponding ABNF rule
+ * in RFC 6020.
+ */
+public final class RequireInstanceListener {
+
+    /**
+     * Creates a new require instance listener.
+     */
+    private RequireInstanceListener() {
+    }
+
+    /**
+     * It is called when parser receives an input matching the grammar rule
+     * (require-instance), performs validation and updates the data model tree.
+     *
+     * @param listener listener's object
+     * @param ctx context object of the grammar rule
+     */
+    public static void processRequireInstanceEntry(TreeWalkListener listener,
+            GeneratedYangParser.RequireInstanceStatementContext ctx) {
+
+        // Check for stack to be non empty.
+        checkStackIsNotEmpty(listener, MISSING_HOLDER, REQUIRE_INSTANCE_DATA, "", ENTRY);
+
+        Parsable curData = listener.getParsedDataStack().peek();
+
+        // Gets the status of require instance
+        boolean isRequireInstance = getValidBooleanValue(ctx.requireInstance().getText(), REQUIRE_INSTANCE_DATA, ctx);
+
+        // Checks the holder of require-instance as leafref or type, else throws error.
+        if (curData instanceof YangLeafRef) {
+
+            // Sets the require-instance status to leafref.
+            ((YangLeafRef) curData).setRequireInstance(isRequireInstance);
+        } else if (curData instanceof YangType) {
+
+            // Checks type should be instance-identifier, else throw error.
+            if (((YangType) curData).getDataType() == YangDataTypes.INSTANCE_IDENTIFIER) {
+
+                // Sets the require-instance status to instance-identifier type.
+                ((YangType) curData).setDataTypeExtendedInfo(isRequireInstance);
+            } else {
+                throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, REQUIRE_INSTANCE_DATA,
+                        ctx.getText(), ENTRY));
+            }
+        } else {
+            throw new ParserException(constructListenerErrorMessage(INVALID_HOLDER, REQUIRE_INSTANCE_DATA,
+                    ctx.getText(), ENTRY));
+        }
+    }
+}
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java
index b2223b8..2132324 100644
--- a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/SubModuleListener.java
@@ -133,6 +133,8 @@
                     .resolveSelfFileLinking(ResolvableType.YANG_USES);
             ((YangReferenceResolver) listener.getParsedDataStack().peek())
                     .resolveSelfFileLinking(ResolvableType.YANG_DERIVED_DATA_TYPE);
+            ((YangReferenceResolver) listener.getParsedDataStack().peek())
+                    .resolveSelfFileLinking(ResolvableType.YANG_LEAFREF);
         } catch (DataModelException e) {
             LinkerException linkerException = new LinkerException(e.getMessage());
             linkerException.setLine(e.getLineNumber());
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java
index 4043a8e..32955d5 100644
--- a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/listeners/TypeListener.java
@@ -101,6 +101,9 @@
         type.setNodeIdentifier(nodeIdentifier);
         type.setDataType(yangDataTypes);
 
+        // Set default require instance value as true for instance identifier.
+        setDefaultRequireInstanceForInstanceIdentifier(type);
+
         int errorLine = ctx.getStart().getLine();
         int errorPosition = ctx.getStart().getCharPositionInLine();
 
@@ -233,6 +236,18 @@
     }
 
     /**
+     * Sets the default require instance value as true when the type is instance identifier.
+     *
+     * @param type type to which the value has to be set
+     */
+    private static void setDefaultRequireInstanceForInstanceIdentifier(YangType<?> type) {
+
+        if (type.getDataType() == YangDataTypes.INSTANCE_IDENTIFIER) {
+            ((YangType<Boolean>) type).setDataTypeExtendedInfo(true);
+        }
+    }
+
+    /**
      * It is called when parser exits from grammar rule (type), it perform
      * validations and update the data model tree.
      *
@@ -291,7 +306,11 @@
                     parserException = new ParserException("YANG file error : a type bits" +
                             " must have atleast one bit statement.");
                     break;
-                // TODO : decimal64, identity ref, leafref
+                case LEAFREF:
+                    parserException = new ParserException("YANG file error : a type leafref" +
+                            " must have one path statement.");
+                    break;
+                // TODO : decimal64, identity ref
                 default:
                     return;
             }