[ONOS-4744] Leafref implementation and UT
Change-Id: I151797185e0bb1695c0640b667ae76ef87c4d4b0
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java
index 67c2e36..443c071 100644
--- a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/TreeWalkListener.java
@@ -49,6 +49,7 @@
 import org.onosproject.yangutils.parser.impl.listeners.KeyListener;
 import org.onosproject.yangutils.parser.impl.listeners.LeafListListener;
 import org.onosproject.yangutils.parser.impl.listeners.LeafListener;
+import org.onosproject.yangutils.parser.impl.listeners.LeafrefListener;
 import org.onosproject.yangutils.parser.impl.listeners.LengthRestrictionListener;
 import org.onosproject.yangutils.parser.impl.listeners.ListListener;
 import org.onosproject.yangutils.parser.impl.listeners.MandatoryListener;
@@ -56,16 +57,18 @@
 import org.onosproject.yangutils.parser.impl.listeners.MinElementsListener;
 import org.onosproject.yangutils.parser.impl.listeners.ModuleListener;
 import org.onosproject.yangutils.parser.impl.listeners.MustListener;
-import org.onosproject.yangutils.parser.impl.listeners.NotificationListener;
 import org.onosproject.yangutils.parser.impl.listeners.NamespaceListener;
+import org.onosproject.yangutils.parser.impl.listeners.NotificationListener;
 import org.onosproject.yangutils.parser.impl.listeners.OrganizationListener;
 import org.onosproject.yangutils.parser.impl.listeners.OutputListener;
+import org.onosproject.yangutils.parser.impl.listeners.PathListener;
 import org.onosproject.yangutils.parser.impl.listeners.PatternRestrictionListener;
 import org.onosproject.yangutils.parser.impl.listeners.PositionListener;
 import org.onosproject.yangutils.parser.impl.listeners.PrefixListener;
 import org.onosproject.yangutils.parser.impl.listeners.PresenceListener;
 import org.onosproject.yangutils.parser.impl.listeners.RangeRestrictionListener;
 import org.onosproject.yangutils.parser.impl.listeners.ReferenceListener;
+import org.onosproject.yangutils.parser.impl.listeners.RequireInstanceListener;
 import org.onosproject.yangutils.parser.impl.listeners.RevisionDateListener;
 import org.onosproject.yangutils.parser.impl.listeners.RevisionListener;
 import org.onosproject.yangutils.parser.impl.listeners.RpcListener;
@@ -81,9 +84,9 @@
 import org.onosproject.yangutils.parser.impl.listeners.VersionListener;
 import org.onosproject.yangutils.parser.impl.listeners.WhenListener;
 
-import static org.onosproject.yangutils.utils.UtilConstants.UNSUPPORTED_YANG_CONSTRUCT;
-import static org.onosproject.yangutils.utils.UtilConstants.CURRENTLY_UNSUPPORTED;
 import static org.onosproject.yangutils.parser.impl.parserutils.ListenerUtil.handleUnsupportedYangConstruct;
+import static org.onosproject.yangutils.utils.UtilConstants.CURRENTLY_UNSUPPORTED;
+import static org.onosproject.yangutils.utils.UtilConstants.UNSUPPORTED_YANG_CONSTRUCT;
 
 /**
  * Represents ANTLR generates parse-tree. ANTLR generates a parse-tree listener interface that responds to events
@@ -667,17 +670,17 @@
 
     @Override
     public void enterLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext ctx) {
-        // do nothing.
+        LeafrefListener.processLeafrefEntry(this, ctx);
     }
 
     @Override
     public void exitLeafrefSpecification(GeneratedYangParser.LeafrefSpecificationContext ctx) {
-        // do nothing.
+        LeafrefListener.processLeafrefExit(this, ctx);
     }
 
     @Override
     public void enterPathStatement(GeneratedYangParser.PathStatementContext ctx) {
-        handleUnsupportedYangConstruct(YangConstructType.PATH_DATA, ctx, CURRENTLY_UNSUPPORTED);
+        PathListener.processPathEntry(this, ctx);
     }
 
     @Override
@@ -687,7 +690,7 @@
 
     @Override
     public void enterRequireInstanceStatement(GeneratedYangParser.RequireInstanceStatementContext ctx) {
-        handleUnsupportedYangConstruct(YangConstructType.REQUIRE_INSTANCE_DATA, ctx, UNSUPPORTED_YANG_CONSTRUCT);
+        RequireInstanceListener.processRequireInstanceEntry(this, ctx);
     }
 
     @Override
@@ -1489,6 +1492,16 @@
     }
 
     @Override
+    public void enterRequireInstance(GeneratedYangParser.RequireInstanceContext ctx) {
+        // do nothing.
+    }
+
+    @Override
+    public void exitRequireInstance(GeneratedYangParser.RequireInstanceContext ctx) {
+        // do nothing.
+    }
+
+    @Override
     public void enterFraction(GeneratedYangParser.FractionContext ctx) {
         // TODO: implement the method.
     }
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;
             }
diff --git a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java
index e2097fc..2aaa563 100644
--- a/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java
+++ b/utils/yangutils/plugin/src/main/java/org/onosproject/yangutils/parser/impl/parserutils/ListenerUtil.java
@@ -18,28 +18,44 @@
 
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Date;
+import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.regex.Pattern;
 
 import org.antlr.v4.runtime.ParserRuleContext;
+import org.onosproject.yangutils.datamodel.YangAtomicPath;
+import org.onosproject.yangutils.datamodel.YangLeafRef;
 import org.onosproject.yangutils.datamodel.YangNodeIdentifier;
+import org.onosproject.yangutils.datamodel.YangPathPredicate;
+import org.onosproject.yangutils.datamodel.YangRelativePath;
 import org.onosproject.yangutils.datamodel.utils.YangConstructType;
 import org.onosproject.yangutils.parser.antlrgencode.GeneratedYangParser;
 import org.onosproject.yangutils.parser.exceptions.ParserException;
 
+import static org.onosproject.yangutils.datamodel.YangPathArgType.ABSOLUTE_PATH;
+import static org.onosproject.yangutils.datamodel.YangPathArgType.RELATIVE_PATH;
+import static org.onosproject.yangutils.datamodel.YangPathOperator.EQUALTO;
 import static org.onosproject.yangutils.utils.UtilConstants.ADD;
+import static org.onosproject.yangutils.utils.UtilConstants.ANCESTOR_ACCESSOR;
+import static org.onosproject.yangutils.utils.UtilConstants.ANCESTOR_ACCESSOR_IN_PATH;
 import static org.onosproject.yangutils.utils.UtilConstants.CARET;
+import static org.onosproject.yangutils.utils.UtilConstants.CHAR_OF_CLOSE_SQUARE_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.CHAR_OF_OPEN_SQUARE_BRACKET;
+import static org.onosproject.yangutils.utils.UtilConstants.CHAR_OF_SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.CLOSE_PARENTHESIS;
 import static org.onosproject.yangutils.utils.UtilConstants.COLON;
+import static org.onosproject.yangutils.utils.UtilConstants.CURRENT;
 import static org.onosproject.yangutils.utils.UtilConstants.CURRENTLY_UNSUPPORTED;
 import static org.onosproject.yangutils.utils.UtilConstants.EMPTY_STRING;
 import static org.onosproject.yangutils.utils.UtilConstants.FALSE;
 import static org.onosproject.yangutils.utils.UtilConstants.IDENTITYREF;
-import static org.onosproject.yangutils.utils.UtilConstants.INSTANCE_IDENTIFIER;
-import static org.onosproject.yangutils.utils.UtilConstants.LEAFREF;
+import static org.onosproject.yangutils.utils.UtilConstants.OPEN_SQUARE_BRACKET;
 import static org.onosproject.yangutils.utils.UtilConstants.QUOTES;
 import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
+import static org.onosproject.yangutils.utils.UtilConstants.SLASH_FOR_STRING;
 import static org.onosproject.yangutils.utils.UtilConstants.TRUE;
 import static org.onosproject.yangutils.utils.UtilConstants.YANG_FILE_ERROR;
 
@@ -52,6 +68,7 @@
     private static final String DATE_PATTERN = "[0-9]{4}-([0-9]{2}|[0-9])-([0-9]{2}|[0-9])";
     private static final String NON_NEGATIVE_INTEGER_PATTERN = "[0-9]+";
     private static final Pattern INTEGER_PATTERN = Pattern.compile("[-][0-9]+|[0-9]+");
+    private static final Pattern PATH_PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
     private static final String XML = "xml";
     private static final String ONE = "1";
     private static final int IDENTIFIER_LENGTH = 64;
@@ -115,6 +132,42 @@
     }
 
     /**
+     * Validates identifier and returns concatenated string if string contains plus symbol.
+     *
+     * @param identifier string from yang file
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return concatenated string after removing double quotes
+     */
+    public static String getValidIdentifierForLeafref(String identifier, YangConstructType yangConstruct,
+            ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        String identifierString = removeQuotesAndHandleConcat(identifier);
+        ParserException parserException;
+
+        if (identifierString.length() > IDENTIFIER_LENGTH) {
+            parserException = new ParserException("YANG file error : " + " identifier " + identifierString + " in " +
+                    YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() + " is " +
+                    "greater than 64 characters.");
+        } else if (!IDENTIFIER_PATTERN.matcher(identifierString).matches()) {
+            parserException = new ParserException("YANG file error : " + " identifier " + identifierString + " in " +
+                    YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() + " is not " +
+                    "valid.");
+        } else if (identifierString.toLowerCase().startsWith(XML)) {
+            parserException = new ParserException("YANG file error : " + " identifier " + identifierString + " in " +
+                    YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() +
+                    " must not start with (('X'|'x') ('M'|'m') ('L'|'l')).");
+        } else {
+            return identifierString;
+        }
+
+        parserException.setLine(ctx.getStart().getLine());
+        parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+        throw parserException;
+    }
+
+    /**
      * Validates the revision date.
      *
      * @param dateToValidate input revision date
@@ -307,6 +360,352 @@
     }
 
     /**
+     * Checks and return valid node identifier specific to nodes in leafref path.
+     *
+     * @param nodeIdentifierString string from yang file
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return valid node identifier
+     */
+    public static YangNodeIdentifier getValidNodeIdentifierForLeafref(String nodeIdentifierString,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        String tmpIdentifierString = removeQuotesAndHandleConcat(nodeIdentifierString);
+        String[] tmpData = tmpIdentifierString.split(Pattern.quote(COLON));
+        if (tmpData.length == 1) {
+            YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
+            checkForUnsupportedTypes(tmpData[0], yangConstruct, ctx);
+            nodeIdentifier.setName(getValidIdentifierForLeafref(tmpData[0], yangConstruct, ctx, yangLeafRef));
+            return nodeIdentifier;
+        } else if (tmpData.length == 2) {
+            YangNodeIdentifier nodeIdentifier = new YangNodeIdentifier();
+            nodeIdentifier.setPrefix(getValidIdentifierForLeafref(tmpData[0], yangConstruct, ctx, yangLeafRef));
+            nodeIdentifier.setName(getValidIdentifierForLeafref(tmpData[1], yangConstruct, ctx, yangLeafRef));
+            return nodeIdentifier;
+        } else {
+            ParserException parserException = new ParserException("YANG file error : " +
+                    YangConstructType.getYangConstructType(yangConstruct) + yangLeafRef.getPath() +
+                    " is not valid.");
+            parserException.setLine(ctx.getStart().getLine());
+            parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+            throw parserException;
+        }
+    }
+
+    /**
+     * Validates the path argument. It can be either absolute or relative path.
+     *
+     * @param pathString the path string from the path type
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     */
+    public static void validatePathArgument(String pathString, YangConstructType yangConstruct,
+            ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        String completePathString = removeQuotesAndHandleConcat(pathString);
+        yangLeafRef.setPath(completePathString);
+        if (completePathString.startsWith(SLASH)) {
+            yangLeafRef.setPathType(ABSOLUTE_PATH);
+            List<YangAtomicPath> yangAtomicPathListList = validateAbsolutePath(completePathString, yangConstruct, ctx,
+                    yangLeafRef);
+            yangLeafRef.setAtomicPath(yangAtomicPathListList);
+        } else if (completePathString.startsWith(ANCESTOR_ACCESSOR)) {
+            yangLeafRef.setPathType(RELATIVE_PATH);
+            validateRelativePath(completePathString, yangConstruct, ctx, yangLeafRef);
+        } else {
+            ParserException parserException = new ParserException("YANG file error : " +
+                    YangConstructType.getYangConstructType(yangConstruct) + yangLeafRef.getPath() +
+                    " does not follow valid path syntax");
+            parserException.setLine(ctx.getStart().getLine());
+            parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+            throw parserException;
+        }
+    }
+
+    /**
+     * Validates the relative path.
+     *
+     * @param completePathString the path string of relative path
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     */
+    private static void validateRelativePath(String completePathString, YangConstructType yangConstruct,
+            ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        YangRelativePath relativePath = new YangRelativePath();
+        int numberOfAncestors = 0;
+        while (completePathString.startsWith(ANCESTOR_ACCESSOR_IN_PATH)) {
+            completePathString = completePathString.replaceFirst(ANCESTOR_ACCESSOR_IN_PATH, EMPTY_STRING);
+            numberOfAncestors = numberOfAncestors + 1;
+        }
+        if (completePathString == null || completePathString.length() == 0) {
+            ParserException parserException = new ParserException("YANG file error : "
+                    + YangConstructType.getYangConstructType(yangConstruct) + yangLeafRef.getPath() +
+                    " does not follow valid path syntax");
+            parserException.setLine(ctx.getStart().getLine());
+            parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+            throw parserException;
+        }
+        relativePath.setAncestorNodeCount(numberOfAncestors);
+        List<YangAtomicPath> atomicPath = validateAbsolutePath(SLASH_FOR_STRING + completePathString,
+                yangConstruct,
+                ctx, yangLeafRef);
+        relativePath.setAtomicPathList(atomicPath);
+        yangLeafRef.setRelativePath(relativePath);
+    }
+
+    /**
+     * Validates the absolute path.
+     *
+     * @param completePathString the path string of absolute path
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return list of object of node in absolute path
+     */
+    private static List<YangAtomicPath> validateAbsolutePath(String completePathString,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        List<YangAtomicPath> absolutePathList = new LinkedList<>();
+        YangPathPredicate yangPathPredicate = new YangPathPredicate();
+        YangNodeIdentifier yangNodeIdentifier;
+
+        while (completePathString != null) {
+            String path = completePathString.replaceFirst(SLASH_FOR_STRING, EMPTY_STRING);
+            if (path == null || path.length() == 0) {
+                ParserException parserException = new ParserException("YANG file error : "
+                        + YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() +
+                        " does not follow valid path syntax");
+                parserException.setLine(ctx.getStart().getLine());
+                parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+                throw parserException;
+            }
+            String matchedPathPredicate;
+            String nodeIdentifier;
+            String[] differentiate = new String[2];
+            int forNodeIdentifier = path.indexOf(CHAR_OF_SLASH);
+            int forPathPredicate = path.indexOf(CHAR_OF_OPEN_SQUARE_BRACKET);
+
+            // Checks if path predicate is present for the node.
+            if ((forPathPredicate < forNodeIdentifier) && (forPathPredicate != -1)) {
+                List<String> pathPredicate = new ArrayList<>();
+                matchedPathPredicate = matchForPathPredicate(path);
+
+                if (matchedPathPredicate == null || matchedPathPredicate.length() == 0) {
+                    ParserException parserException = new ParserException("YANG file error : "
+                            + YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() +
+                            " does not follow valid path syntax");
+                    parserException.setLine(ctx.getStart().getLine());
+                    parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+                    throw parserException;
+                }
+                int indexOfMatchedFirstOpenBrace = path.indexOf(CHAR_OF_OPEN_SQUARE_BRACKET);
+                differentiate[0] = path.substring(0, indexOfMatchedFirstOpenBrace);
+                differentiate[1] = path.substring(indexOfMatchedFirstOpenBrace);
+                pathPredicate.add(matchedPathPredicate);
+                nodeIdentifier = differentiate[0];
+                // Starts adding all path predicates of a node into the list.
+                if (!differentiate[1].isEmpty()) {
+                    while (differentiate[1].startsWith(OPEN_SQUARE_BRACKET)) {
+                        matchedPathPredicate = matchForPathPredicate(differentiate[1]);
+                        if (matchedPathPredicate == null || matchedPathPredicate.length() == 0) {
+                            ParserException parserException = new ParserException(
+                                    "YANG file error : " + YangConstructType.getYangConstructType(yangConstruct) + " "
+                                            + yangLeafRef.getPath() +
+                                            " does not follow valid path syntax");
+                            parserException.setLine(ctx.getStart().getLine());
+                            parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+                            throw parserException;
+                        }
+                        pathPredicate.add(matchedPathPredicate);
+                        differentiate[1] = differentiate[1].substring(matchedPathPredicate.length());
+                    }
+                }
+
+                List<YangPathPredicate> pathPredicateList = validatePathPredicate(pathPredicate, yangConstruct, ctx,
+                        yangPathPredicate, yangLeafRef);
+                YangAtomicPath atomicPath = new YangAtomicPath();
+                yangNodeIdentifier = getValidNodeIdentifierForLeafref(nodeIdentifier, yangConstruct, ctx, yangLeafRef);
+                atomicPath.setNodeIdentifier(yangNodeIdentifier);
+                atomicPath.setPathPredicatesList(pathPredicateList);
+                absolutePathList.add(atomicPath);
+            } else {
+                if (path.contains(SLASH_FOR_STRING)) {
+                    nodeIdentifier = path.substring(0, path.indexOf(CHAR_OF_SLASH));
+                    differentiate[1] = path.substring(path.indexOf(CHAR_OF_SLASH));
+                } else {
+                    nodeIdentifier = path;
+                    differentiate[1] = null;
+                }
+                yangNodeIdentifier = getValidNodeIdentifierForLeafref(nodeIdentifier, yangConstruct, ctx, yangLeafRef);
+
+                YangAtomicPath atomicPath = new YangAtomicPath();
+                atomicPath.setNodeIdentifier(yangNodeIdentifier);
+                atomicPath.setPathPredicatesList(null);
+                absolutePathList.add(atomicPath);
+            }
+            if (differentiate[1] == null || differentiate[1].length() == 0) {
+                completePathString = null;
+            } else {
+                completePathString = differentiate[1];
+            }
+        }
+        return absolutePathList;
+    }
+
+    /**
+     * Validates path predicate in the absolute path's node.
+     *
+     * @param pathPredicate list of path predicates in the node of absolute path
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangPathPredicate instance of path predicate where it has to be set
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return list of object of path predicates in absolute path's node
+     */
+    private static List<YangPathPredicate> validatePathPredicate(List<String> pathPredicate,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangPathPredicate yangPathPredicate,
+            YangLeafRef yangLeafRef) {
+
+        Iterator<String> pathPredicateString = pathPredicate.iterator();
+        List<String> pathEqualityExpression = new ArrayList<>();
+
+        while (pathPredicateString.hasNext()) {
+            String pathPredicateForNode = pathPredicateString.next();
+            pathPredicateForNode = (pathPredicateForNode.substring(1)).trim();
+            pathPredicateForNode = pathPredicateForNode.substring(0,
+                    pathPredicateForNode.indexOf(CHAR_OF_CLOSE_SQUARE_BRACKET));
+            pathEqualityExpression.add(pathPredicateForNode);
+        }
+        List<YangPathPredicate> validatedPathPredicateList = validatePathEqualityExpression(pathEqualityExpression,
+                yangConstruct, ctx, yangPathPredicate, yangLeafRef);
+        return validatedPathPredicateList;
+    }
+
+    /**
+     * Validates the path equality expression.
+     *
+     * @param pathEqualityExpression list of path equality expression in the path predicates of the node
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangPathPredicate instance of path predicate where it has to be set
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return list of object of path predicates in absolute path's node
+     */
+    private static List<YangPathPredicate> validatePathEqualityExpression(List<String> pathEqualityExpression,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangPathPredicate yangPathPredicate,
+            YangLeafRef yangLeafRef) {
+
+        Iterator<String> pathEqualityExpressionString = pathEqualityExpression.iterator();
+        List<YangPathPredicate> yangPathPredicateList = new ArrayList<>();
+
+        while (pathEqualityExpressionString.hasNext()) {
+            String pathEqualityExpressionForNode = pathEqualityExpressionString.next();
+            String[] pathEqualityExpressionArray = pathEqualityExpressionForNode.split("[=]");
+
+            YangNodeIdentifier yangNodeIdentifierForPredicate;
+            YangRelativePath yangRelativePath;
+            yangNodeIdentifierForPredicate = getValidNodeIdentifierForLeafref(pathEqualityExpressionArray[0].trim(),
+                    yangConstruct, ctx, yangLeafRef);
+            yangRelativePath = validatePathKeyExpression(pathEqualityExpressionArray[1].trim(), yangConstruct, ctx,
+                    yangLeafRef);
+            yangPathPredicate.setNodeIdentifier(yangNodeIdentifierForPredicate);
+            yangPathPredicate.setPathOperator(EQUALTO);
+            yangPathPredicate.setRightRelativePath(yangRelativePath);
+            yangPathPredicateList.add(yangPathPredicate);
+        }
+        return yangPathPredicateList;
+    }
+
+    /**
+     * Validate the path key expression.
+     *
+     * @param rightRelativePath relative path in the path predicate
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return object of right relative path in path predicate
+     */
+    private static YangRelativePath validatePathKeyExpression(String rightRelativePath,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        YangRelativePath yangRelativePath = new YangRelativePath();
+        String[] relativePath = rightRelativePath.split(SLASH_FOR_STRING);
+        List<String> rightAbsolutePath = new ArrayList<>();
+        int accessAncestor = 0;
+        for (String path : relativePath) {
+            if (path.trim().equals(ANCESTOR_ACCESSOR)) {
+                accessAncestor = accessAncestor + 1;
+            } else {
+                rightAbsolutePath.add(path);
+            }
+        }
+        List<YangAtomicPath> atomicPathInRelativePath = validateRelativePathKeyExpression(rightAbsolutePath,
+                yangConstruct, ctx, yangLeafRef);
+        yangRelativePath.setAtomicPathList(atomicPathInRelativePath);
+        yangRelativePath.setAncestorNodeCount(accessAncestor);
+        return yangRelativePath;
+    }
+
+    /**
+     * Validates the relative path key expression.
+     *
+     * @param rightAbsolutePath absolute path nodes present in the relative path
+     * @param yangConstruct yang construct for creating error message
+     * @param ctx yang construct's context to get the line number and character position
+     * @param yangLeafRef instance of leafref where the path argument has to be set
+     * @return list of object of absolute path nodes present in the relative path
+     */
+    private static List<YangAtomicPath> validateRelativePathKeyExpression(List<String> rightAbsolutePath,
+            YangConstructType yangConstruct, ParserRuleContext ctx, YangLeafRef yangLeafRef) {
+
+        List<YangAtomicPath> atomicPathList = new ArrayList<>();
+        YangNodeIdentifier yangNodeIdentifier;
+
+        Iterator<String> nodes = rightAbsolutePath.iterator();
+        String currentInvocationFunction = nodes.next();
+        currentInvocationFunction = currentInvocationFunction.trim();
+        String[] currentFunction = currentInvocationFunction.split("[(]");
+
+        if (!(currentFunction[0].trim().equals(CURRENT)) || !(currentFunction[1].trim().equals(CLOSE_PARENTHESIS))) {
+            ParserException parserException = new ParserException("YANG file error : "
+                    + YangConstructType.getYangConstructType(yangConstruct) + " " + yangLeafRef.getPath() +
+                    " does not follow valid path syntax");
+            parserException.setLine(ctx.getStart().getLine());
+            parserException.setCharPosition(ctx.getStart().getCharPositionInLine());
+            throw parserException;
+        }
+
+        while (nodes.hasNext()) {
+            YangAtomicPath atomicPath = new YangAtomicPath();
+            String node = nodes.next();
+            yangNodeIdentifier = getValidNodeIdentifierForLeafref(node.trim(), yangConstruct, ctx, yangLeafRef);
+            atomicPath.setNodeIdentifier(yangNodeIdentifier);
+            atomicPathList.add(atomicPath);
+        }
+        return atomicPathList;
+    }
+
+    /**
+     * Validates the match for first path predicate in a given string.
+     *
+     * @param matchRequiredString string for which match has to be done
+     * @return the matched string
+     */
+    private static String matchForPathPredicate(String matchRequiredString) {
+
+        String matchedString = null;
+        java.util.regex.Matcher matcher = PATH_PREDICATE_PATTERN.matcher(matchRequiredString);
+        if (matcher.find()) {
+            matchedString = matcher.group(0);
+        }
+        return matchedString;
+    }
+
+    /**
      * Checks whether the type is an unsupported type.
      *
      * @param typeName name of the type
@@ -317,15 +716,9 @@
             YangConstructType yangConstruct, ParserRuleContext ctx) {
 
         if (yangConstruct == YangConstructType.TYPE_DATA) {
-            if (typeName.equalsIgnoreCase(LEAFREF)) {
-                handleUnsupportedYangConstruct(YangConstructType.LEAFREF_DATA,
-                        ctx, CURRENTLY_UNSUPPORTED);
-            } else if (typeName.equalsIgnoreCase(IDENTITYREF)) {
+            if (typeName.equalsIgnoreCase(IDENTITYREF)) {
                 handleUnsupportedYangConstruct(YangConstructType.IDENTITYREF_DATA,
                         ctx, CURRENTLY_UNSUPPORTED);
-            } else if (typeName.equalsIgnoreCase(INSTANCE_IDENTIFIER)) {
-                handleUnsupportedYangConstruct(YangConstructType.INSTANCE_IDENTIFIER_DATA,
-                        ctx, CURRENTLY_UNSUPPORTED);
             }
         }
     }