Merge "BUG-994: do not use SchemaPath.getPath()"
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / impl / YangParserImpl.java
index 1a463447a9c9eac5ee0a57293ac760f50623240d..77d390f8f7a9aeb0742590d1e71e3aaadc92299d 100644 (file)
@@ -1,6 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
@@ -8,24 +7,28 @@
 package org.opendaylight.yangtools.yang.parser.impl;
 
 import static com.google.common.base.Preconditions.checkNotNull;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.fillAugmentTarget;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findBaseIdentity;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findModuleFromBuilders;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findModuleFromContext;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findSchemaNode;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.findSchemaNodeInModule;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.processAugmentation;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.setNodeAddedByUses;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapChildNode;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapChildNodes;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapGroupings;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapTypedefs;
-import static org.opendaylight.yangtools.yang.parser.util.ParserUtils.wrapUnknownNodes;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveType;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnion;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeUnionWithContext;
-import static org.opendaylight.yangtools.yang.parser.util.TypeUtils.resolveTypeWithContext;
-
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.fillAugmentTarget;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findBaseIdentity;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findModuleFromBuilders;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findModuleFromContext;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findSchemaNode;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.findSchemaNodeInModule;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.processAugmentation;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.setNodeAddedByUses;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapChildNode;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapChildNodes;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapGroupings;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapTypedefs;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.wrapUnknownNodes;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveType;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnion;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnionWithContext;
+import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeWithContext;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.HashBiMap;
+import com.google.common.io.ByteSource;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
@@ -42,7 +45,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
-
 import org.antlr.v4.runtime.ANTLRInputStream;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.tree.ParseTree;
@@ -51,6 +53,7 @@ import org.opendaylight.yangtools.antlrv4.code.gen.YangLexer;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.YangContext;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
@@ -68,39 +71,33 @@ import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuil
 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.ExtensionBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ChoiceCaseBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.DeviationBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ExtensionBuilder;
+import org.opendaylight.yangtools.yang.parser.builder.impl.GroupingUtils;
 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentitySchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.IdentityrefTypeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder.ModuleImpl;
+import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleImpl;
 import org.opendaylight.yangtools.yang.parser.builder.impl.UnionTypeBuilder;
-import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilder;
-import org.opendaylight.yangtools.yang.parser.util.Comparators;
-import org.opendaylight.yangtools.yang.parser.util.GroupingSort;
-import org.opendaylight.yangtools.yang.parser.util.GroupingUtils;
+import org.opendaylight.yangtools.yang.parser.builder.impl.UnknownSchemaNodeBuilderImpl;
+import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
 import org.opendaylight.yangtools.yang.parser.util.NamedByteArrayInputStream;
 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
 import org.opendaylight.yangtools.yang.parser.util.NamedInputStream;
-import org.opendaylight.yangtools.yang.parser.util.ParserUtils;
 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-import org.opendaylight.yangtools.yang.validator.YangModelBasicValidator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashBiMap;
-import com.google.common.io.ByteSource;
-
-
 public final class YangParserImpl implements YangContextParser {
     private static final Logger LOG = LoggerFactory.getLogger(YangParserImpl.class);
 
@@ -117,7 +114,8 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public SchemaContext parseFile(final File yangFile, final File directory) throws IOException, YangSyntaxErrorException {
+    public SchemaContext parseFile(final File yangFile, final File directory) throws IOException,
+    YangSyntaxErrorException {
         Preconditions.checkState(yangFile.exists(), yangFile + " does not exists");
         Preconditions.checkState(directory.exists(), directory + " does not exists");
         Preconditions.checkState(directory.isDirectory(), directory + " is not a directory");
@@ -126,7 +124,7 @@ public final class YangParserImpl implements YangContextParser {
         final String[] fileList = checkNotNull(directory.list(), directory + " not found or is not a directory");
 
         Map<ByteSource, File> sourceToFile = new LinkedHashMap<>();
-        ByteSource mainFileSource = ParserUtils.fileToByteSource(yangFile);
+        ByteSource mainFileSource = BuilderUtils.fileToByteSource(yangFile);
         sourceToFile.put(mainFileSource, yangFile);
 
         for (String fileName : fileList) {
@@ -135,7 +133,7 @@ public final class YangParserImpl implements YangContextParser {
             }
             File dependency = new File(directory, fileName);
             if (dependency.isFile()) {
-                sourceToFile.put(ParserUtils.fileToByteSource(dependency), dependency);
+                sourceToFile.put(BuilderUtils.fileToByteSource(dependency), dependency);
             }
         }
 
@@ -181,12 +179,13 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException, YangSyntaxErrorException {
+    public SchemaContext parseFiles(final Collection<File> yangFiles, final SchemaContext context) throws IOException,
+    YangSyntaxErrorException {
         if (yangFiles == null) {
             return resolveSchemaContext(Collections.<Module> emptySet());
         }
 
-        Collection<ByteSource> sources = ParserUtils.filesToByteSources(yangFiles);
+        Collection<ByteSource> sources = BuilderUtils.filesToByteSources(yangFiles);
         SchemaContext result = parseSources(sources, context);
         return result;
     }
@@ -195,7 +194,7 @@ public final class YangParserImpl implements YangContextParser {
     @Deprecated
     public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
         try {
-            Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
+            Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(yangModelStreams);
             return parseSources(sources).getModules();
         } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
@@ -203,7 +202,8 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
+    public SchemaContext parseSources(final Collection<ByteSource> sources) throws IOException,
+    YangSyntaxErrorException {
         Collection<Module> unsorted = parseYangModelSources(sources).values();
         Set<Module> sorted = new LinkedHashSet<>(
                 ModuleDependencySort.sort(unsorted.toArray(new Module[unsorted.size()])));
@@ -214,7 +214,7 @@ public final class YangParserImpl implements YangContextParser {
     @Deprecated
     public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, final SchemaContext context) {
         try {
-            Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
+            Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(yangModelStreams);
             return parseSources(sources, context).getModules();
         } catch (IOException | YangSyntaxErrorException e) {
             throw new YangParseException("Failed to parse yang data", e);
@@ -222,7 +222,8 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     @Override
-    public SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context) throws IOException, YangSyntaxErrorException {
+    public SchemaContext parseSources(final Collection<ByteSource> sources, final SchemaContext context)
+            throws IOException, YangSyntaxErrorException {
         if (sources == null) {
             return resolveSchemaContext(Collections.<Module> emptySet());
         }
@@ -303,16 +304,18 @@ public final class YangParserImpl implements YangContextParser {
 
     @Override
     public SchemaContext resolveSchemaContext(final Set<Module> modules) {
-        // after merging parse method with this one, add support for getting submodule sources.
+        // after merging parse method with this one, add support for getting
+        // submodule sources.
         Map<ModuleIdentifier, String> identifiersToSources = new HashMap<>();
-        for(Module module: modules) {
+        for (Module module : modules) {
             ModuleImpl moduleImpl = (ModuleImpl) module;
             identifiersToSources.put(module, moduleImpl.getSource());
         }
         return new SchemaContextImpl(modules, identifiersToSources);
     }
 
-    private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
+    private Map<ByteSource, Module> parseYangModelSources(final Collection<ByteSource> sources) throws IOException,
+    YangSyntaxErrorException {
         if (sources == null || sources.isEmpty()) {
             return Collections.emptyMap();
         }
@@ -320,7 +323,7 @@ public final class YangParserImpl implements YangContextParser {
         Map<ByteSource, ModuleBuilder> sourceToBuilder = resolveSources(sources);
         // sort and check for duplicates
         List<ModuleBuilder> sorted = ModuleDependencySort.sort(sourceToBuilder.values());
-        ParserUtils.setSourceToBuilder(sourceToBuilder);
+        BuilderUtils.setSourceToBuilder(sourceToBuilder);
         Map<String, TreeMap<Date, ModuleBuilder>> modules = orderModules(sorted);
         Map<ModuleBuilder, Module> builderToModule = build(modules);
         Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
@@ -344,13 +347,15 @@ public final class YangParserImpl implements YangContextParser {
      *         parsed from stream
      * @throws YangSyntaxErrorException
      */
-    private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams) throws IOException, YangSyntaxErrorException {
+    private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams) throws IOException,
+    YangSyntaxErrorException {
         Map<ByteSource, ModuleBuilder> builders = parseSourcesToBuilders(streams);
         Map<ByteSource, ModuleBuilder> result = resolveSubmodules(builders);
         return result;
     }
 
-    private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
+    private Map<ByteSource, ModuleBuilder> parseSourcesToBuilders(final Collection<ByteSource> sources)
+            throws IOException, YangSyntaxErrorException {
         final ParseTreeWalker walker = new ParseTreeWalker();
         final Map<ByteSource, ParseTree> sourceToTree = parseYangSources(sources);
         final Map<ByteSource, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
@@ -378,7 +383,7 @@ public final class YangParserImpl implements YangContextParser {
             sourceToBuilder.put(source, moduleBuilder);
         }
 
-        ParserUtils.setSourceToBuilder(sourceToBuilder);
+        BuilderUtils.setSourceToBuilder(sourceToBuilder);
         return sourceToBuilder;
     }
 
@@ -442,7 +447,7 @@ public final class YangParserImpl implements YangContextParser {
         module.getAugmentBuilders().addAll(submodule.getAugmentBuilders());
         module.getAllAugments().addAll(submodule.getAllAugments());
         module.getChildNodeBuilders().addAll(submodule.getChildNodeBuilders());
-        module.getChildNodes().addAll(submodule.getChildNodes());
+        module.getChildNodes().putAll(submodule.getChildNodes());
         module.getGroupings().addAll(submodule.getGroupings());
         module.getGroupingBuilders().addAll(submodule.getGroupingBuilders());
         module.getTypeDefinitions().addAll(submodule.getTypeDefinitions());
@@ -468,7 +473,8 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
-            final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException, YangSyntaxErrorException {
+            final Collection<ByteSource> yangFileStreams, final SchemaContext context) throws IOException,
+            YangSyntaxErrorException {
         Map<ByteSource, ModuleBuilder> parsedBuilders = resolveSources(yangFileStreams);
         ModuleBuilder[] builders = new ModuleBuilder[parsedBuilders.size()];
         parsedBuilders.values().toArray(builders);
@@ -522,7 +528,8 @@ public final class YangParserImpl implements YangContextParser {
      * @param filtered
      *            collection to fill up
      */
-    private void filterImports(final ModuleBuilder main, final Collection<ModuleBuilder> other, final Collection<ModuleBuilder> filtered) {
+    private void filterImports(final ModuleBuilder main, final Collection<ModuleBuilder> other,
+            final Collection<ModuleBuilder> filtered) {
         Set<ModuleImport> imports = main.getModuleImports();
 
         // if this is submodule, add parent to filtered and pick its imports
@@ -559,7 +566,8 @@ public final class YangParserImpl implements YangContextParser {
         }
     }
 
-    private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException, YangSyntaxErrorException {
+    private Map<ByteSource, ParseTree> parseYangSources(final Collection<ByteSource> sources) throws IOException,
+    YangSyntaxErrorException {
         final Map<ByteSource, ParseTree> trees = new HashMap<>();
         for (ByteSource source : sources) {
             trees.put(source, parseYangSource(source));
@@ -568,7 +576,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     private YangContext parseYangSource(final ByteSource source) throws IOException, YangSyntaxErrorException {
-       try (InputStream stream = source.openStream()) {
+        try (InputStream stream = source.openStream()) {
             final ANTLRInputStream input = new ANTLRInputStream(stream);
             final YangLexer lexer = new YangLexer(input);
             final CommonTokenStream tokens = new CommonTokenStream(lexer);
@@ -582,7 +590,7 @@ public final class YangParserImpl implements YangContextParser {
             errorListener.validate();
 
             return result;
-       }
+        }
     }
 
     public static YangContext parseStreamWithoutErrorListeners(final InputStream yangStream) {
@@ -815,9 +823,8 @@ public final class YangParserImpl implements YangContextParser {
      */
     private void setCorrectAugmentTargetPath(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
             final AugmentationSchemaBuilder augment, final SchemaContext context) {
-        ModuleBuilder module = ParserUtils.getParentModule(augment);
+        ModuleBuilder module = BuilderUtils.getParentModule(augment);
         SchemaPath oldSchemaPath = augment.getTargetPath();
-        List<QName> oldPath = oldSchemaPath.getPath();
         List<QName> newPath = new ArrayList<>();
 
         Builder parent = augment.getParent();
@@ -830,7 +837,7 @@ public final class YangParserImpl implements YangContextParser {
             String prefix;
             QName baseQName = usesParent.getQName();
             if (baseQName == null) {
-                ModuleBuilder m = ParserUtils.getParentModule(usesParent);
+                ModuleBuilder m = BuilderUtils.getParentModule(usesParent);
                 ns = m.getNamespace();
                 revision = m.getRevision();
                 prefix = m.getPrefix();
@@ -840,19 +847,21 @@ public final class YangParserImpl implements YangContextParser {
                 prefix = baseQName.getPrefix();
             }
 
-            for (QName qn : oldSchemaPath.getPath()) {
-                newPath.add(new QName(ns, revision, prefix, qn.getLocalName()));
+            final QNameModule qm = QNameModule.create(ns, revision);
+            for (QName qn : oldSchemaPath.getPathFromRoot()) {
+                newPath.add(QName.create(qm, prefix, qn.getLocalName()));
             }
         } else {
+            Iterable<QName> oldPath = oldSchemaPath.getPathFromRoot();
             for (QName qn : oldPath) {
                 URI ns = module.getNamespace();
                 Date rev = module.getRevision();
                 String localPrefix = qn.getPrefix();
                 if (localPrefix != null && !("".equals(localPrefix))) {
-                    ModuleBuilder currentModule = ParserUtils.findModuleFromBuilders(modules, module, localPrefix,
+                    ModuleBuilder currentModule = BuilderUtils.findModuleFromBuilders(modules, module, localPrefix,
                             augment.getLine());
                     if (currentModule == null) {
-                        Module m = ParserUtils.findModuleFromContext(context, module, localPrefix, augment.getLine());
+                        Module m = BuilderUtils.findModuleFromContext(context, module, localPrefix, augment.getLine());
                         if (m == null) {
                             throw new YangParseException(module.getName(), augment.getLine(), "Module with prefix "
                                     + localPrefix + " not found.");
@@ -892,7 +901,7 @@ public final class YangParserImpl implements YangContextParser {
             }
         }
         if (node instanceof ChoiceBuilder) {
-            for (ChoiceCaseBuilder child : ((ChoiceBuilder)node).getCases()) {
+            for (ChoiceCaseBuilder child : ((ChoiceBuilder) node).getCases()) {
                 correctPathForAugmentNodes(child, node.getPath());
             }
         }
@@ -908,8 +917,8 @@ public final class YangParserImpl implements YangContextParser {
      */
     private void checkAugmentMandatoryNodes(final Collection<AugmentationSchemaBuilder> augments) {
         for (AugmentationSchemaBuilder augment : augments) {
-            String augmentPrefix = augment.getTargetPath().getPath().get(0).getPrefix();
-            ModuleBuilder module = ParserUtils.getParentModule(augment);
+            String augmentPrefix = augment.getTargetPath().getPathFromRoot().iterator().next().getPrefix();
+            ModuleBuilder module = BuilderUtils.getParentModule(augment);
             String modulePrefix = module.getPrefix();
 
             if (augmentPrefix == null || augmentPrefix.isEmpty() || augmentPrefix.equals(modulePrefix)) {
@@ -988,22 +997,39 @@ public final class YangParserImpl implements YangContextParser {
 
         UsesNodeBuilder usesNode = (UsesNodeBuilder) augment.getParent();
         DataNodeContainerBuilder parentNode = usesNode.getParent();
-        SchemaNodeBuilder targetNode;
-        if (parentNode instanceof ModuleBuilder) {
-            targetNode = findSchemaNodeInModule(augment.getTargetPath().getPath(), (ModuleBuilder) parentNode);
+        Optional<SchemaNodeBuilder> potentialTargetNode;
+        SchemaPath resolvedTargetPath = augment.getTargetNodeSchemaPath();
+        if (parentNode instanceof ModuleBuilder && resolvedTargetPath.isAbsolute()) {
+            // Uses is directly used in module body, we lookup
+            // We lookup in data namespace to find correct augmentation target
+            potentialTargetNode = findSchemaNodeInModule(resolvedTargetPath, (ModuleBuilder) parentNode);
         } else {
-            targetNode = findSchemaNode(augment.getTargetPath().getPath(), (SchemaNodeBuilder) parentNode);
-        }
-
-        if (targetNode instanceof AugmentationTargetBuilder) {
-            fillAugmentTarget(augment, targetNode);
-            ((AugmentationTargetBuilder) targetNode).addAugmentation(augment);
-            augment.setResolved(true);
-            return true;
+            // Uses is used in local context (be it data namespace or grouping namespace,
+            // since all nodes via uses are imported to localName, it is safe to
+            // to proceed only with local names.
+            //
+            // Conflicting elements in other namespaces are still not present
+            // since resolveUsesAugment occurs before augmenting from external modules.
+            potentialTargetNode = Optional.<SchemaNodeBuilder> fromNullable(findSchemaNode(augment.getTargetPath()
+                    .getPath(), (SchemaNodeBuilder) parentNode));
+        }
+
+        if (potentialTargetNode.isPresent()) {
+            SchemaNodeBuilder targetNode = potentialTargetNode.get();
+            if (targetNode instanceof AugmentationTargetBuilder) {
+                fillAugmentTarget(augment, targetNode);
+                ((AugmentationTargetBuilder) targetNode).addAugmentation(augment);
+                augment.setResolved(true);
+                return true;
+            } else {
+                throw new YangParseException(module.getName(), augment.getLine(), String.format(
+                        "Failed to resolve augment in uses. Invalid augment target: %s", potentialTargetNode));
+            }
         } else {
-            throw new YangParseException(module.getName(), augment.getLine(),
-                    "Failed to resolve augment in uses. Invalid augment target: " + targetNode);
+            throw new YangParseException(module.getName(), augment.getLine(), String.format(
+                    "Failed to resolve augment in uses. Invalid augment target path: %s", augment.getTargetPath()));
         }
+
     }
 
     /**
@@ -1025,8 +1051,8 @@ public final class YangParserImpl implements YangContextParser {
             return true;
         }
 
-        List<QName> targetPath = augment.getTargetPath().getPath();
-        ModuleBuilder targetModule = findTargetModule(targetPath.get(0), module, modules, context, augment.getLine());
+        QName targetPath = augment.getTargetPath().getPathFromRoot().iterator().next();
+        ModuleBuilder targetModule = findTargetModule(targetPath, module, modules, context, augment.getLine());
         if (targetModule == null) {
             throw new YangParseException(module.getModuleName(), augment.getLine(), "Failed to resolve augment "
                     + augment);
@@ -1119,9 +1145,11 @@ public final class YangParserImpl implements YangContextParser {
                     final String baseIdentityName = identity.getBaseIdentityName();
                     final int line = identity.getLine();
                     if (baseIdentityName != null) {
-                        IdentitySchemaNodeBuilder baseIdentity = findBaseIdentity(modules, module, baseIdentityName, line);
+                        IdentitySchemaNodeBuilder baseIdentity = findBaseIdentity(modules, module, baseIdentityName,
+                                line);
                         if (baseIdentity == null) {
-                            throw new YangParseException(module.getName(), identity.getLine(), "Failed to find base identity");
+                            throw new YangParseException(module.getName(), identity.getLine(),
+                                    "Failed to find base identity");
                         } else {
                             identity.setBaseIdentity(baseIdentity);
                         }
@@ -1166,10 +1194,10 @@ public final class YangParserImpl implements YangContextParser {
                             String name = splittedBase[1];
                             ModuleBuilder dependentModule = findTargetModule(prefix, module, modules, context, line);
                             if (dependentModule != null) {
-                                result = ParserUtils.findIdentity(dependentModule.getAddedIdentities(), name);
+                                result = BuilderUtils.findIdentity(dependentModule.getAddedIdentities(), name);
                             }
                         } else {
-                            result = ParserUtils.findIdentity(module.getAddedIdentities(), baseIdentityName);
+                            result = BuilderUtils.findIdentity(module.getAddedIdentities(), baseIdentityName);
                         }
                         identity.setBaseIdentity(result);
                     }
@@ -1196,7 +1224,7 @@ public final class YangParserImpl implements YangContextParser {
             }
         }
         for (UsesNodeBuilder usesNode : allUses) {
-            ModuleBuilder module = ParserUtils.getParentModule(usesNode);
+            ModuleBuilder module = BuilderUtils.getParentModule(usesNode);
             final GroupingBuilder targetGroupingBuilder = GroupingUtils.getTargetGroupingFromModules(usesNode, modules,
                     module);
             if (targetGroupingBuilder == null) {
@@ -1222,7 +1250,8 @@ public final class YangParserImpl implements YangContextParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUsesForGroupings(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUsesForGroupings(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         final Set<GroupingBuilder> allGroupings = new HashSet<>();
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
             for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
@@ -1248,7 +1277,8 @@ public final class YangParserImpl implements YangContextParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUsesForNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUsesForNodes(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules.entrySet()) {
             for (Map.Entry<Date, ModuleBuilder> inner : entry.getValue().entrySet()) {
                 ModuleBuilder module = inner.getValue();
@@ -1272,11 +1302,11 @@ public final class YangParserImpl implements YangContextParser {
      * @param context
      *            SchemaContext containing already resolved modules
      */
-    private void resolveUses(final UsesNodeBuilder usesNode,
-            final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context) {
+    private void resolveUses(final UsesNodeBuilder usesNode, final Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            final SchemaContext context) {
         if (!usesNode.isResolved()) {
             DataNodeContainerBuilder parent = usesNode.getParent();
-            ModuleBuilder module = ParserUtils.getParentModule(parent);
+            ModuleBuilder module = BuilderUtils.getParentModule(parent);
             GroupingBuilder target = GroupingUtils.getTargetGroupingFromModules(usesNode, modules, module);
             if (target == null) {
                 resolveUsesWithContext(usesNode);
@@ -1299,8 +1329,7 @@ public final class YangParserImpl implements YangContextParser {
     }
 
     /**
-     * Copy target grouping child nodes to current location with
-     * new namespace.
+     * Copy target grouping child nodes to current location with new namespace.
      *
      * @param usesNode
      *            uses node to resolve
@@ -1312,7 +1341,7 @@ public final class YangParserImpl implements YangContextParser {
     private void resolveUsesWithContext(final UsesNodeBuilder usesNode) {
         final int line = usesNode.getLine();
         DataNodeContainerBuilder parent = usesNode.getParent();
-        ModuleBuilder module = ParserUtils.getParentModule(parent);
+        ModuleBuilder module = BuilderUtils.getParentModule(parent);
         SchemaPath parentPath;
         URI ns = null;
         Date rev = null;
@@ -1322,41 +1351,40 @@ public final class YangParserImpl implements YangContextParser {
             rev = module.getRevision();
             pref = module.getPrefix();
             if (parent instanceof AugmentationSchemaBuilder) {
-                parentPath = ((AugmentationSchemaBuilder)parent).getTargetNodeSchemaPath();
+                parentPath = ((AugmentationSchemaBuilder) parent).getTargetNodeSchemaPath();
             } else {
-                parentPath = ((ModuleBuilder)parent).getPath();
+                parentPath = ((ModuleBuilder) parent).getPath();
             }
         } else {
             ns = ((DataSchemaNodeBuilder) parent).getQName().getNamespace();
             rev = ((DataSchemaNodeBuilder) parent).getQName().getRevision();
             pref = ((DataSchemaNodeBuilder) parent).getQName().getPrefix();
-            parentPath = ((DataSchemaNodeBuilder)parent).getPath();
+            parentPath = ((DataSchemaNodeBuilder) parent).getPath();
         }
 
         GroupingDefinition gd = usesNode.getGroupingDefinition();
 
-        Set<DataSchemaNodeBuilder> childNodes = wrapChildNodes(module.getModuleName(), line,
-                gd.getChildNodes(), parentPath, ns, rev, pref);
+        Set<DataSchemaNodeBuilder> childNodes = wrapChildNodes(module.getModuleName(), line, gd.getChildNodes(),
+                parentPath, ns, rev, pref);
         parent.getChildNodeBuilders().addAll(childNodes);
         for (DataSchemaNodeBuilder childNode : childNodes) {
             setNodeAddedByUses(childNode);
         }
 
-        Set<TypeDefinitionBuilder> typedefs = wrapTypedefs(module.getModuleName(), line, gd, parentPath, ns,
-                rev, pref);
+        Set<TypeDefinitionBuilder> typedefs = wrapTypedefs(module.getModuleName(), line, gd, parentPath, ns, rev, pref);
         parent.getTypeDefinitionBuilders().addAll(typedefs);
         for (TypeDefinitionBuilder typedef : typedefs) {
             setNodeAddedByUses(typedef);
         }
 
-        Set<GroupingBuilder> groupings = wrapGroupings(module.getModuleName(), line, usesNode
-                .getGroupingDefinition().getGroupings(), parentPath, ns, rev, pref);
+        Set<GroupingBuilder> groupings = wrapGroupings(module.getModuleName(), line, usesNode.getGroupingDefinition()
+                .getGroupings(), parentPath, ns, rev, pref);
         parent.getGroupingBuilders().addAll(groupings);
         for (GroupingBuilder gb : groupings) {
             setNodeAddedByUses(gb);
         }
 
-        List<UnknownSchemaNodeBuilder> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
+        List<UnknownSchemaNodeBuilderImpl> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
                 gd.getUnknownSchemaNodes(), parentPath, ns, rev, pref);
         parent.getUnknownNodes().addAll(unknownNodes);
         for (UnknownSchemaNodeBuilder un : unknownNodes) {
@@ -1468,8 +1496,8 @@ public final class YangParserImpl implements YangContextParser {
         for (DeviationBuilder dev : module.getDeviationBuilders()) {
             int line = dev.getLine();
             SchemaPath targetPath = dev.getTargetPath();
-            List<QName> path = targetPath.getPath();
-            QName q0 = path.get(0);
+            Iterable<QName> path = targetPath.getPathFromRoot();
+            QName q0 = path.iterator().next();
             String prefix = q0.getPrefix();
             if (prefix == null) {
                 prefix = module.getPrefix();
@@ -1515,8 +1543,8 @@ public final class YangParserImpl implements YangContextParser {
         for (DeviationBuilder dev : module.getDeviationBuilders()) {
             int line = dev.getLine();
             SchemaPath targetPath = dev.getTargetPath();
-            List<QName> path = targetPath.getPath();
-            QName q0 = path.get(0);
+            Iterable<QName> path = targetPath.getPathFromRoot();
+            QName q0 = path.iterator().next();
             String prefix = q0.getPrefix();
             if (prefix == null) {
                 prefix = module.getPrefix();
@@ -1562,7 +1590,7 @@ public final class YangParserImpl implements YangContextParser {
      *            current module
      */
     private void processDeviation(final DeviationBuilder dev, final ModuleBuilder dependentModuleBuilder,
-            final List<QName> path, final ModuleBuilder module) {
+            final Iterable<QName> path, final ModuleBuilder module) {
         final int line = dev.getLine();
         Builder currentParent = dependentModuleBuilder;