Update ParserListenerUtils to use SchemaPath
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / impl / YangParserImpl.java
index de41975645703cedfb74ec4e9b0442ef469c1621..cea011edcbd4652a155d15b8185ad1d457e637a8 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,34 +7,40 @@
 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.base.Splitter;
+import com.google.common.collect.HashBiMap;
+import com.google.common.io.ByteSource;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -43,6 +48,8 @@ import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
 
+import javax.annotation.concurrent.Immutable;
+
 import org.antlr.v4.runtime.ANTLRInputStream;
 import org.antlr.v4.runtime.CommonTokenStream;
 import org.antlr.v4.runtime.tree.ParseTree;
@@ -51,6 +58,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,43 +76,43 @@ 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;
-
-
+@Immutable
 public final class YangParserImpl implements YangContextParser {
     private static final Logger LOG = LoggerFactory.getLogger(YangParserImpl.class);
-
     private static final String FAIL_DEVIATION_TARGET = "Failed to find deviation target.";
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
+    private static final YangParserImpl INSTANCE = new YangParserImpl();
+
+    public static YangParserImpl getInstance() {
+        return INSTANCE;
+    }
 
     @Override
     @Deprecated
@@ -117,7 +125,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 +135,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 +144,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,21 +190,21 @@ 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);
-        SchemaContext result = parseSources(sources, context);
-        return result;
+        Collection<ByteSource> sources = BuilderUtils.filesToByteSources(yangFiles);
+        return parseSources(sources, context);
     }
 
     @Override
     @Deprecated
     public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams) {
-        Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
         try {
+            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 +212,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()])));
@@ -213,8 +223,8 @@ public final class YangParserImpl implements YangContextParser {
     @Override
     @Deprecated
     public Set<Module> parseYangModelsFromStreams(final List<InputStream> yangModelStreams, final SchemaContext context) {
-        Collection<ByteSource> sources = ParserUtils.streamsToByteSources(yangModelStreams);
         try {
+            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 +232,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 +314,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 +333,6 @@ 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);
         Map<String, TreeMap<Date, ModuleBuilder>> modules = orderModules(sorted);
         Map<ModuleBuilder, Module> builderToModule = build(modules);
         Map<ModuleBuilder, ByteSource> builderToSource = HashBiMap.create(sourceToBuilder).inverse();
@@ -344,13 +356,15 @@ public final class YangParserImpl implements YangContextParser {
      *         parsed from stream
      * @throws YangSyntaxErrorException
      */
-    private Map<ByteSource, ModuleBuilder> resolveSources(final Collection<ByteSource> streams) throws IOException, YangSyntaxErrorException {
+    // TODO: remove ByteSource result after removing YangModelParser
+    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;
+        return resolveSubmodules(builders);
     }
 
-    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<>();
@@ -361,23 +375,19 @@ public final class YangParserImpl implements YangContextParser {
         YangParserListenerImpl yangModelParser;
         for (Map.Entry<ByteSource, ParseTree> entry : sourceToTree.entrySet()) {
             ByteSource source = entry.getKey();
-            String path = null;
-            InputStream stream = source.openStream();
-            if (stream instanceof NamedInputStream) {
-                path = stream.toString();
-            }
-            try {
-                stream.close();
-            } catch (IOException e) {
-                LOG.warn("Failed to close stream {}", stream);
+            String path = null; // TODO refactor to Optional
+            //TODO refactor so that path can be retrieved without opening stream: NamedInputStream -> NamedByteSource ?
+            try(InputStream stream = source.openStream()) {
+                if (stream instanceof NamedInputStream) {
+                    path = stream.toString();
+                }
             }
-
             yangModelParser = new YangParserListenerImpl(path);
             walker.walk(yangModelParser, entry.getValue());
             ModuleBuilder moduleBuilder = yangModelParser.getModuleBuilder();
+            moduleBuilder.setSource(source);
             sourceToBuilder.put(source, moduleBuilder);
         }
-
         return sourceToBuilder;
     }
 
@@ -441,7 +451,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());
@@ -467,7 +477,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);
@@ -521,7 +532,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
@@ -558,7 +570,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));
@@ -567,7 +580,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);
@@ -581,9 +594,14 @@ public final class YangParserImpl implements YangContextParser {
             errorListener.validate();
 
             return result;
-       }
+        }
     }
 
+    /**
+     * Mini parser: This parsing context does not validate full YANG module, only
+     * parses header up to the revisions and imports.
+     * @see org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo
+     */
     public static YangContext parseStreamWithoutErrorListeners(final InputStream yangStream) {
         YangContext result = null;
         try {
@@ -814,9 +832,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();
@@ -824,46 +841,41 @@ public final class YangParserImpl implements YangContextParser {
             DataNodeContainerBuilder usesParent = ((UsesNodeBuilder) parent).getParent();
             newPath.addAll(usesParent.getPath().getPath());
 
-            URI ns;
-            Date revision;
-            String prefix;
-            QName baseQName = usesParent.getQName();
+            final QName baseQName = usesParent.getQName();
+            final QNameModule qnm;
+            final String prefix;
             if (baseQName == null) {
-                ModuleBuilder m = ParserUtils.getParentModule(usesParent);
-                ns = m.getNamespace();
-                revision = m.getRevision();
+                ModuleBuilder m = BuilderUtils.getParentModule(usesParent);
+                qnm = m.getQNameModule();
                 prefix = m.getPrefix();
             } else {
-                ns = baseQName.getNamespace();
-                revision = baseQName.getRevision();
+                qnm = baseQName.getModule();
                 prefix = baseQName.getPrefix();
             }
 
-            for (QName qn : oldSchemaPath.getPath()) {
-                newPath.add(new QName(ns, revision, prefix, qn.getLocalName()));
+            for (QName qn : oldSchemaPath.getPathFromRoot()) {
+                newPath.add(QName.create(qnm, prefix, qn.getLocalName()));
             }
         } else {
+            Iterable<QName> oldPath = oldSchemaPath.getPathFromRoot();
             for (QName qn : oldPath) {
-                URI ns = module.getNamespace();
-                Date rev = module.getRevision();
+                QNameModule qnm = module.getQNameModule();
                 String localPrefix = qn.getPrefix();
-                if (localPrefix != null && !("".equals(localPrefix))) {
-                    ModuleBuilder currentModule = ParserUtils.findModuleFromBuilders(modules, module, localPrefix,
+                if (localPrefix != null && !localPrefix.isEmpty()) {
+                    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.");
                         }
-                        ns = m.getNamespace();
-                        rev = m.getRevision();
+                        qnm = m.getQNameModule();
                     } else {
-                        ns = currentModule.getNamespace();
-                        rev = currentModule.getRevision();
+                        qnm = currentModule.getQNameModule();
                     }
                 }
-                newPath.add(new QName(ns, rev, localPrefix, qn.getLocalName()));
+                newPath.add(new QName(qnm.getNamespace(), qnm.getRevision(), localPrefix, qn.getLocalName()));
             }
         }
         augment.setTargetNodeSchemaPath(SchemaPath.create(newPath, true));
@@ -891,7 +903,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());
             }
         }
@@ -907,8 +919,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)) {
@@ -987,22 +999,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()));
         }
+
     }
 
     /**
@@ -1024,8 +1053,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);
@@ -1052,10 +1081,10 @@ public final class YangParserImpl implements YangContextParser {
      */
     private ModuleBuilder findTargetModule(final QName qname, final ModuleBuilder module,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context, final int line) {
-        ModuleBuilder targetModule = null;
+        ModuleBuilder targetModule;
 
         String prefix = qname.getPrefix();
-        if (prefix == null || prefix.equals("")) {
+        if (prefix == null || prefix.isEmpty()) {
             targetModule = module;
         } else {
             targetModule = findModuleFromBuilders(modules, module, qname.getPrefix(), line);
@@ -1079,7 +1108,7 @@ public final class YangParserImpl implements YangContextParser {
 
     private ModuleBuilder findTargetModule(final String prefix, final ModuleBuilder module,
             final Map<String, TreeMap<Date, ModuleBuilder>> modules, final SchemaContext context, final int line) {
-        ModuleBuilder targetModule = null;
+        ModuleBuilder targetModule;
 
         if (prefix == null || prefix.equals("")) {
             targetModule = module;
@@ -1118,9 +1147,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);
                         }
@@ -1155,20 +1186,21 @@ public final class YangParserImpl implements YangContextParser {
                     if (baseIdentityName != null) {
 
                         IdentitySchemaNodeBuilder result = null;
-                        if (baseIdentityName.contains(":")) {
-                            String[] splittedBase = baseIdentityName.split(":");
-                            if (splittedBase.length > 2) {
+                        if (baseIdentityName.indexOf(':') != -1) {
+                            final Iterator<String> split = COLON_SPLITTER.split(baseIdentityName).iterator();
+                            final String prefix = split.next();
+                            final String name = split.next();
+                            if (split.hasNext()) {
                                 throw new YangParseException(module.getName(), line,
                                         "Failed to parse identityref base: " + baseIdentityName);
                             }
-                            String prefix = splittedBase[0];
-                            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);
                     }
@@ -1195,7 +1227,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) {
@@ -1221,7 +1253,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()) {
@@ -1247,7 +1280,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();
@@ -1271,11 +1305,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);
@@ -1298,8 +1332,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
@@ -1311,52 +1344,46 @@ 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;
-        String pref = null;
+
+        final QName parentQName;
         if (parent instanceof AugmentationSchemaBuilder || parent instanceof ModuleBuilder) {
-            ns = module.getNamespace();
-            rev = module.getRevision();
-            pref = module.getPrefix();
+            parentQName = QName.create(module.getQNameModule(), module.getPrefix(), "dummy");
             if (parent instanceof AugmentationSchemaBuilder) {
-                parentPath = ((AugmentationSchemaBuilder)parent).getTargetNodeSchemaPath();
+                parentPath = ((AugmentationSchemaBuilder) parent).getTargetNodeSchemaPath();
             } else {
-                parentPath = ((ModuleBuilder)parent).getPath();
+                parentPath = parent.getPath();
             }
         } else {
-            ns = ((DataSchemaNodeBuilder) parent).getQName().getNamespace();
-            rev = ((DataSchemaNodeBuilder) parent).getQName().getRevision();
-            pref = ((DataSchemaNodeBuilder) parent).getQName().getPrefix();
-            parentPath = ((DataSchemaNodeBuilder)parent).getPath();
+            parentQName = parent.getQName();
+            parentPath = 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, parentQName);
         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, parentQName);
         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, parentQName);
         parent.getGroupingBuilders().addAll(groupings);
         for (GroupingBuilder gb : groupings) {
             setNodeAddedByUses(gb);
         }
 
-        List<UnknownSchemaNodeBuilder> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
-                gd.getUnknownSchemaNodes(), parentPath, ns, rev, pref);
+        List<UnknownSchemaNodeBuilderImpl> unknownNodes = wrapUnknownNodes(module.getModuleName(), line,
+                gd.getUnknownSchemaNodes(), parentPath, parentQName);
         parent.getUnknownNodes().addAll(unknownNodes);
         for (UnknownSchemaNodeBuilder un : unknownNodes) {
             un.setAddedByUses(true);
@@ -1467,8 +1494,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();
@@ -1514,8 +1541,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();
@@ -1561,7 +1588,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;