Merge "Fixed validation bug of YANG import statement"
[controller.git] / opendaylight / sal / yang-prototype / code-generator / yang-model-parser-impl / src / main / java / org / opendaylight / controller / yang / model / parser / impl / YangModelParserImpl.java
index fce723edff9ea6ebd32b7d814ad371d00abaa53a..946bfb429699ef1d3133b5f3ca0ad7e222b1fa08 100644 (file)
@@ -12,8 +12,9 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
+import java.net.URI;
 import java.util.ArrayList;
-import java.util.Calendar;
+import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -29,41 +30,50 @@ import org.antlr.v4.runtime.tree.ParseTreeWalker;
 import org.opendaylight.controller.antlrv4.code.gen.YangLexer;
 import org.opendaylight.controller.antlrv4.code.gen.YangParser;
 import org.opendaylight.controller.yang.common.QName;
-import org.opendaylight.controller.yang.model.api.AugmentationSchema;
 import org.opendaylight.controller.yang.model.api.DataSchemaNode;
 import org.opendaylight.controller.yang.model.api.ExtensionDefinition;
 import org.opendaylight.controller.yang.model.api.Module;
 import org.opendaylight.controller.yang.model.api.ModuleImport;
+import org.opendaylight.controller.yang.model.api.MustDefinition;
 import org.opendaylight.controller.yang.model.api.NotificationDefinition;
 import org.opendaylight.controller.yang.model.api.RpcDefinition;
 import org.opendaylight.controller.yang.model.api.SchemaContext;
 import org.opendaylight.controller.yang.model.api.SchemaPath;
 import org.opendaylight.controller.yang.model.api.TypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.BinaryTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.DecimalTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.InstanceIdentifierTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.IntegerTypeDefinition;
 import org.opendaylight.controller.yang.model.api.type.LengthConstraint;
 import org.opendaylight.controller.yang.model.api.type.PatternConstraint;
 import org.opendaylight.controller.yang.model.api.type.RangeConstraint;
 import org.opendaylight.controller.yang.model.api.type.StringTypeDefinition;
-import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
 import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
 import org.opendaylight.controller.yang.model.parser.builder.api.AugmentationSchemaBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.api.AugmentationTargetBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.api.Builder;
 import org.opendaylight.controller.yang.model.parser.builder.api.ChildNodeBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.api.DataSchemaNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.api.GroupingBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.api.TypeAwareBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.api.TypeDefinitionBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.api.UsesNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.AnyXmlBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.ChoiceBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.ContainerSchemaNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.IdentitySchemaNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.LeafListSchemaNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.LeafSchemaNodeBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.ListSchemaNodeBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.impl.ModuleBuilder;
+import org.opendaylight.controller.yang.model.parser.builder.impl.TypedefBuilder;
 import org.opendaylight.controller.yang.model.parser.builder.impl.UnionTypeBuilder;
-import org.opendaylight.controller.yang.model.util.BaseConstraints;
-import org.opendaylight.controller.yang.model.util.BinaryType;
-import org.opendaylight.controller.yang.model.util.BitsType;
-import org.opendaylight.controller.yang.model.util.StringType;
+import org.opendaylight.controller.yang.model.parser.util.ParserUtils;
+import org.opendaylight.controller.yang.model.parser.util.RefineHolder;
+import org.opendaylight.controller.yang.model.parser.util.RefineHolder.Refine;
+import org.opendaylight.controller.yang.model.parser.util.TypeConstraints;
+import org.opendaylight.controller.yang.model.parser.util.YangParseException;
+import org.opendaylight.controller.yang.model.util.ExtendedType;
 import org.opendaylight.controller.yang.model.util.UnknownType;
-import org.opendaylight.controller.yang.model.util.YangTypesConverter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -73,61 +83,98 @@ public class YangModelParserImpl implements YangModelParser {
             .getLogger(YangModelParserImpl.class);
 
     @Override
-    public Module parseYangModel(String yangFile) {
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuildersFromStreams(yangFile);
-        Set<Module> result = build(modules);
+    public Module parseYangModel(final String yangFile) {
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangFile);
+        final Set<Module> result = build(modules);
         return result.iterator().next();
     }
 
     @Override
-    public Set<Module> parseYangModels(String... yangFiles) {
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuildersFromStreams(yangFiles);
-        Set<Module> result = build(modules);
-        return result;
+    public Set<Module> parseYangModels(final String... yangFiles) {
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangFiles);
+        return build(modules);
     }
 
     @Override
     public Set<Module> parseYangModelsFromStreams(
-            InputStream... yangModelStreams) {
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuildersFromStreams(yangModelStreams);
-        Set<Module> result = build(modules);
-        return result;
+            final InputStream... yangModelStreams) {
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = resolveModuleBuilders(yangModelStreams);
+        return build(modules);
     }
 
     @Override
-    public SchemaContext resolveSchemaContext(Set<Module> modules) {
+    public SchemaContext resolveSchemaContext(final Set<Module> modules) {
         return new SchemaContextImpl(modules);
     }
 
-    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuildersFromStreams(
-            String... yangFiles) {
-        InputStream[] streams = new InputStream[yangFiles.length];
-        for(int i = 0; i < yangFiles.length; i++) {
+    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
+            final String... yangFiles) {
+        final InputStream[] streams = loadStreams(yangFiles);
+        Map<String, TreeMap<Date, ModuleBuilder>> result = Collections
+                .emptyMap();
+
+        if (streams != null) {
+            result = resolveModuleBuilders(streams);
+            closeStreams(streams);
+        }
+        return result;
+    }
+
+    private InputStream[] loadStreams(final String... yangFiles) {
+        final InputStream[] streams = new InputStream[yangFiles.length];
+        for (int i = 0; i < yangFiles.length; i++) {
             final String yangFileName = yangFiles[i];
             final File yangFile = new File(yangFileName);
-            FileInputStream inStream = null;
             try {
-                inStream = new FileInputStream(yangFile);
-            } catch(FileNotFoundException e) {
-                logger.warn("Exception while reading yang stream: " + inStream, e);
+                streams[i] = new FileInputStream(yangFile);
+            } catch (FileNotFoundException e) {
+                logger.warn("Exception while reading yang stream: "
+                        + streams[i], e);
             }
-            streams[i] = inStream;
         }
-        return resolveModuleBuildersFromStreams(streams);
+        return streams;
     }
 
-    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuildersFromStreams(
-            InputStream... yangFiles) {
-        final Map<String, TreeMap<Date, ModuleBuilder>> modules = new HashMap<String, TreeMap<Date, ModuleBuilder>>();
+    private void closeStreams(final InputStream[] streams) {
+        if (streams != null) {
+            for (int i = 0; i < streams.length; i++) {
+                try {
+                    if (streams[i] != null) {
+                        streams[i].close();
+                    }
+                } catch (IOException e) {
+                    logger.warn("Exception while closing yang stream: "
+                            + streams[i], e);
+                }
+            }
+        }
+    }
 
-        final YangModelParserListenerImpl yangModelParser = new YangModelParserListenerImpl();
+    private Map<String, TreeMap<Date, ModuleBuilder>> resolveModuleBuilders(
+            final InputStream... yangFiles) {
+        final Map<String, TreeMap<Date, ModuleBuilder>> modules = new HashMap<String, TreeMap<Date, ModuleBuilder>>();
         final ParseTreeWalker walker = new ParseTreeWalker();
-
-        List<ParseTree> trees = parseStreams(yangFiles);
-
-        ModuleBuilder[] builders = new ModuleBuilder[trees.size()];
-
+        final List<ParseTree> trees = parseStreams(yangFiles);
+        final ModuleBuilder[] builders = new ModuleBuilder[trees.size()];
+
+       // validation\r
+        // if validation fails with any file, do not continue and throw\r
+        // exception\r
+        for (int i = 0; i < trees.size(); i++) {\r
+            try {\r
+                final YangModelValidationListener yangModelParser = new YangModelValidationListener();\r
+                walker.walk(yangModelParser, trees.get(i));\r
+            } catch (IllegalStateException e) {\r
+                // wrap exception to add information about which file failed\r
+                throw new YangValidationException(\r
+                        "Yang validation failed for file" + yangFiles[i], e);\r
+            }\r
+        }\r
+
+
+        YangModelParserListenerImpl yangModelParser = null;
         for (int i = 0; i < trees.size(); i++) {
+            yangModelParser = new YangModelParserListenerImpl();
             walker.walk(yangModelParser, trees.get(i));
             builders[i] = yangModelParser.getModuleBuilder();
         }
@@ -136,30 +183,28 @@ public class YangModelParserImpl implements YangModelParser {
             final String builderName = builder.getName();
             Date builderRevision = builder.getRevision();
             if (builderRevision == null) {
-                builderRevision = createEpochTime();
+                builderRevision = new Date(0L);
             }
-
             TreeMap<Date, ModuleBuilder> builderByRevision = modules
                     .get(builderName);
             if (builderByRevision == null) {
                 builderByRevision = new TreeMap<Date, ModuleBuilder>();
             }
             builderByRevision.put(builderRevision, builder);
-
             modules.put(builderName, builderByRevision);
         }
         return modules;
     }
 
-    private List<ParseTree> parseStreams(InputStream... yangStreams) {
-        List<ParseTree> trees = new ArrayList<ParseTree>();
+    private List<ParseTree> parseStreams(final InputStream... yangStreams) {
+        final List<ParseTree> trees = new ArrayList<ParseTree>();
         for (InputStream yangStream : yangStreams) {
             trees.add(parseStream(yangStream));
         }
         return trees;
     }
 
-    private ParseTree parseStream(InputStream yangStream) {
+    private ParseTree parseStream(final InputStream yangStream) {
         ParseTree result = null;
         try {
             final ANTLRInputStream input = new ANTLRInputStream(yangStream);
@@ -173,38 +218,40 @@ public class YangModelParserImpl implements YangModelParser {
         return result;
     }
 
-    private Set<Module> build(Map<String, TreeMap<Date, ModuleBuilder>> modules) {
-        // first validate
+    private Set<Module> build(final Map<String, TreeMap<Date, ModuleBuilder>> modules) {
+        // validate
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules
                 .entrySet()) {
             for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue()
                     .entrySet()) {
-                ModuleBuilder moduleBuilder = childEntry.getValue();
-                validateBuilder(modules, moduleBuilder);
+                final ModuleBuilder moduleBuilder = childEntry.getValue();
+                validateModule(modules, moduleBuilder);
             }
         }
-        // then build
+
+        // build
         final Set<Module> result = new HashSet<Module>();
         for (Map.Entry<String, TreeMap<Date, ModuleBuilder>> entry : modules
                 .entrySet()) {
             final Map<Date, Module> modulesByRevision = new HashMap<Date, Module>();
             for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue()
                     .entrySet()) {
-                ModuleBuilder moduleBuilder = childEntry.getValue();
-                modulesByRevision.put(childEntry.getKey(),
-                        moduleBuilder.build());
-                result.add(moduleBuilder.build());
+                final ModuleBuilder moduleBuilder = childEntry.getValue();
+                final Module module = moduleBuilder.build();
+                modulesByRevision.put(childEntry.getKey(), module);
+                result.add(module);
             }
         }
-
         return result;
     }
 
-    private void validateBuilder(
+    private void validateModule(
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
             ModuleBuilder builder) {
-        resolveTypedefs(modules, builder);
+        resolveDirtyNodes(modules, builder);
         resolveAugments(modules, builder);
+        resolveIdentities(modules, builder);
+        resolveUses(modules, builder);
     }
 
     /**
@@ -216,241 +263,370 @@ public class YangModelParserImpl implements YangModelParser {
      * @param module
      *            current module
      */
-    private void resolveTypedefs(
+    private void resolveDirtyNodes(
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
             ModuleBuilder module) {
-        Map<List<String>, TypeAwareBuilder> dirtyNodes = module
+        final Map<List<String>, TypeAwareBuilder> dirtyNodes = module
                 .getDirtyNodes();
-        if (dirtyNodes.size() == 0) {
-            return;
-        } else {
+        if (!dirtyNodes.isEmpty()) {
             for (Map.Entry<List<String>, TypeAwareBuilder> entry : dirtyNodes
                     .entrySet()) {
-                TypeAwareBuilder typeToResolve = entry.getValue();
 
-                if (typeToResolve instanceof UnionTypeBuilder) {
-                    resolveUnionTypeBuilder(modules, module,
-                            (UnionTypeBuilder) typeToResolve);
+                final TypeAwareBuilder nodeToResolve = entry.getValue();
+                // different handling for union types
+                if (nodeToResolve instanceof UnionTypeBuilder) {
+                    final UnionTypeBuilder union = (UnionTypeBuilder) nodeToResolve;
+                    List<TypeDefinition<?>> unionTypes = union.getTypes();
+                    List<UnknownType> toRemove = new ArrayList<UnknownType>();
+                    for (TypeDefinition<?> td : unionTypes) {
+                        if (td instanceof UnknownType) {
+                            UnknownType unknownType = (UnknownType) td;
+                            TypeDefinitionBuilder resolvedType = resolveTypeUnion(
+                                    nodeToResolve, unknownType, modules, module);
+                            union.setType(resolvedType);
+                            toRemove.add(unknownType);
+                        }
+                    }
+                    unionTypes.removeAll(toRemove);
                 } else {
-                    UnknownType ut = (UnknownType) typeToResolve.getType();
-                    TypeDefinition<?> resolvedType = findTargetType(ut,
-                            modules, module);
-                    typeToResolve.setType(resolvedType);
+                    TypeDefinitionBuilder resolvedType = resolveType(
+                            nodeToResolve, modules, module);
+                    nodeToResolve.setType(resolvedType);
                 }
             }
         }
     }
 
-    private UnionTypeBuilder resolveUnionTypeBuilder(
+    private TypeDefinitionBuilder resolveType(TypeAwareBuilder typeToResolve,
+            Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder builder) {
+        TypeConstraints constraints = new TypeConstraints();
+
+        TypeDefinitionBuilder targetType = getTypedefBuilder(typeToResolve,
+                modules, builder);
+        TypeConstraints tConstraints = findConstraints(typeToResolve,
+                constraints, modules, builder);
+        targetType.setRanges(tConstraints.getRange());
+        targetType.setLengths(tConstraints.getLength());
+        targetType.setPatterns(tConstraints.getPatterns());
+        targetType.setFractionDigits(tConstraints.getFractionDigits());
+
+        return targetType;
+    }
+
+    private TypeDefinitionBuilder resolveTypeUnion(
+            TypeAwareBuilder typeToResolve, UnknownType unknownType,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder builder, UnionTypeBuilder unionTypeBuilderToResolve) {
+            ModuleBuilder builder) {
+        TypeConstraints constraints = new TypeConstraints();
+
+        TypeDefinitionBuilder targetType = getUnionBuilder(typeToResolve,
+                unknownType, modules, builder);
+        TypeConstraints tConstraints = findConstraints(typeToResolve,
+                constraints, modules, builder);
+        targetType.setRanges(tConstraints.getRange());
+        targetType.setLengths(tConstraints.getLength());
+        targetType.setPatterns(tConstraints.getPatterns());
+        targetType.setFractionDigits(tConstraints.getFractionDigits());
+
+        return targetType;
+    }
 
-        List<TypeDefinition<?>> resolvedTypes = new ArrayList<TypeDefinition<?>>();
-        List<TypeDefinition<?>> typesToRemove = new ArrayList<TypeDefinition<?>>();
+    private TypeDefinitionBuilder getTypedefBuilder(
+            TypeAwareBuilder nodeToResolve,
+            Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder builder) {
 
-        for (TypeDefinition<?> td : unionTypeBuilderToResolve.getTypes()) {
-            if (td instanceof UnknownType) {
-                TypeDefinition<?> resolvedType = findTargetType(
-                        (UnknownType) td, modules, builder);
-                resolvedTypes.add(resolvedType);
-                typesToRemove.add(td);
-            }
+        TypeDefinition<?> nodeToResolveBase = nodeToResolve.getType();
+        if (nodeToResolveBase != null
+                && !(nodeToResolveBase instanceof UnknownType)) {
+            return (TypeDefinitionBuilder) nodeToResolve;
         }
 
-        List<TypeDefinition<?>> unionTypeBuilderTypes = unionTypeBuilderToResolve
-                .getTypes();
-        unionTypeBuilderTypes.addAll(resolvedTypes);
-        unionTypeBuilderTypes.removeAll(typesToRemove);
+        UnknownType unknownType = (UnknownType) nodeToResolve.getType();
 
-        return unionTypeBuilderToResolve;
+        QName unknownTypeQName = unknownType.getQName();
+        String unknownTypeName = unknownTypeQName.getLocalName();
+        String unknownTypePrefix = unknownTypeQName.getPrefix();
+
+        // search for module which contains referenced typedef
+        ModuleBuilder dependentModule = findDependentModule(modules, builder,
+                unknownTypePrefix);
+        TypeDefinitionBuilder lookedUpBuilder = findTypedefBuilderByName(
+                dependentModule, unknownTypeName);
+
+        TypeDefinitionBuilder lookedUpBuilderCopy = copyTypedefBuilder(
+                lookedUpBuilder, nodeToResolve instanceof TypeDefinitionBuilder);
+        TypeDefinitionBuilder resolvedCopy = resolveCopiedBuilder(
+                lookedUpBuilderCopy, modules, dependentModule);
+        return resolvedCopy;
     }
 
-    private TypeDefinition<?> findTargetType(UnknownType ut,
+    private TypeDefinitionBuilder getUnionBuilder(
+            TypeAwareBuilder nodeToResolve, UnknownType unknownType,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder builder) {
+            ModuleBuilder module) {
 
-        Map<TypeDefinitionBuilder, TypeConstraints> foundedTypeDefinitionBuilder = findTypeDefinitionBuilderWithConstraints(
-                modules, ut, builder);
-        TypeDefinitionBuilder targetType = foundedTypeDefinitionBuilder
-                .entrySet().iterator().next().getKey();
-        TypeConstraints constraints = foundedTypeDefinitionBuilder.entrySet()
-                .iterator().next().getValue();
-
-        TypeDefinition<?> targetTypeBaseType = targetType.getBaseType();
-        String targetTypeBaseTypeName = targetTypeBaseType.getQName()
-                .getLocalName();
-
-        // RANGE
-        List<RangeConstraint> ranges = ut.getRangeStatements();
-        resolveRanges(ranges, targetType, modules, builder);
-
-        // LENGTH
-        List<LengthConstraint> lengths = ut.getLengthStatements();
-        resolveLengths(lengths, targetType, modules, builder);
-
-        // PATTERN
-        List<PatternConstraint> patterns = ut.getPatterns();
-
-        // Fraction Digits
-        Integer fractionDigits = ut.getFractionDigits();
-
-        // MERGE CONSTRAINTS (enumeration and leafref omitted
-        // because
-        // they have no restrictions)
-        if (targetTypeBaseType instanceof DecimalTypeDefinition) {
-            List<RangeConstraint> fullRanges = new ArrayList<RangeConstraint>();
-            fullRanges.addAll(constraints.getRanges());
-            fullRanges.addAll(ranges);
-            Integer fd = fractionDigits == null ? constraints
-                    .getFractionDigits() : fractionDigits;
-            targetTypeBaseType = YangTypesConverter
-                    .javaTypeForBaseYangDecimal64Type(fullRanges, fd);
-        } else if (targetTypeBaseType instanceof IntegerTypeDefinition) {
-            List<RangeConstraint> fullRanges = new ArrayList<RangeConstraint>();
-            fullRanges.addAll(constraints.getRanges());
-            fullRanges.addAll(ranges);
-            if (targetTypeBaseTypeName.startsWith("int")) {
-                targetTypeBaseType = YangTypesConverter
-                        .javaTypeForBaseYangSignedIntegerType(
-                                targetTypeBaseTypeName, fullRanges);
-            } else {
-                targetTypeBaseType = YangTypesConverter
-                        .javaTypeForBaseYangUnsignedIntegerType(
-                                targetTypeBaseTypeName, fullRanges);
+        TypeDefinition<?> baseTypeToResolve = nodeToResolve.getType();
+        if (baseTypeToResolve != null
+                && !(baseTypeToResolve instanceof UnknownType)) {
+            return (TypeDefinitionBuilder) nodeToResolve;
+        }
+
+        QName unknownTypeQName = unknownType.getQName();
+        String unknownTypeName = unknownTypeQName.getLocalName();
+        String unknownTypePrefix = unknownTypeQName.getPrefix();
+
+        // search for module which contains referenced typedef
+        ModuleBuilder dependentModule = findDependentModule(modules, module,
+                unknownTypePrefix);
+        TypeDefinitionBuilder lookedUpBuilder = findTypedefBuilderByName(
+                dependentModule, unknownTypeName);
+
+        TypeDefinitionBuilder lookedUpBuilderCopy = copyTypedefBuilder(
+                lookedUpBuilder, nodeToResolve instanceof TypeDefinitionBuilder);
+        TypeDefinitionBuilder resolvedCopy = resolveCopiedBuilder(
+                lookedUpBuilderCopy, modules, dependentModule);
+        return resolvedCopy;
+    }
+
+    private TypeDefinitionBuilder copyTypedefBuilder(TypeDefinitionBuilder old,
+            boolean seekByTypedefBuilder) {
+        if (old instanceof UnionTypeBuilder) {
+            UnionTypeBuilder oldUnion = (UnionTypeBuilder) old;
+            UnionTypeBuilder newUnion = new UnionTypeBuilder();
+            for (TypeDefinition<?> td : oldUnion.getTypes()) {
+                newUnion.setType(td);
             }
-        } else if (targetTypeBaseType instanceof StringTypeDefinition) {
-            List<LengthConstraint> fullLengths = new ArrayList<LengthConstraint>();
-            fullLengths.addAll(constraints.getLengths());
-            fullLengths.addAll(lengths);
-            List<PatternConstraint> fullPatterns = new ArrayList<PatternConstraint>();
-            fullPatterns.addAll(constraints.getPatterns());
-            fullPatterns.addAll(patterns);
-            targetTypeBaseType = new StringType(fullLengths, fullPatterns);
-        } else if (targetTypeBaseType instanceof BitsTypeDefinition) {
-            BitsTypeDefinition bitsType = (BitsTypeDefinition) targetTypeBaseType;
-            List<Bit> bits = bitsType.getBits();
-            targetTypeBaseType = new BitsType(bits);
-        } else if (targetTypeBaseType instanceof BinaryTypeDefinition) {
-            targetTypeBaseType = new BinaryType(null, lengths, null);
-        } else if (targetTypeBaseTypeName.equals("instance-identifier")) {
-            // TODO: instance-identifier
-            /*
-             * boolean requireInstance = isRequireInstance(typeBody); type = new
-             * InstanceIdentifier(null, requireInstance);
-             */
-        }
-
-        return targetTypeBaseType;
-    }
-
-    private TypeDefinitionBuilder findTypeDefinitionBuilder(
-            Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            UnknownType unknownType, ModuleBuilder builder) {
-        Map<TypeDefinitionBuilder, TypeConstraints> result = findTypeDefinitionBuilderWithConstraints(
-                modules, unknownType, builder);
-        return result.entrySet().iterator().next().getKey();
+            for (TypeDefinitionBuilder tdb : oldUnion.getTypedefs()) {
+                newUnion.setType(copyTypedefBuilder(tdb, true));
+            }
+            return newUnion;
+        }
+
+        QName oldName = old.getQName();
+        QName newName = new QName(oldName.getNamespace(),
+                oldName.getRevision(), oldName.getPrefix(),
+                oldName.getLocalName());
+        TypeDefinitionBuilder tdb = new TypedefBuilder(newName);
+
+        tdb.setRanges(old.getRanges());
+        tdb.setLengths(old.getLengths());
+        tdb.setPatterns(old.getPatterns());
+        tdb.setFractionDigits(old.getFractionDigits());
+
+        TypeDefinition<?> oldType = old.getType();
+        if (oldType == null) {
+            tdb.setType(old.getTypedef());
+        } else {
+            tdb.setType(oldType);
+        }
+
+        if (!seekByTypedefBuilder) {
+            tdb.setDescription(old.getDescription());
+            tdb.setReference(old.getReference());
+            tdb.setStatus(old.getStatus());
+            tdb.setDefaultValue(old.getDefaultValue());
+            tdb.setUnits(old.getUnits());
+        }
+        return tdb;
     }
 
-    private Map<TypeDefinitionBuilder, TypeConstraints> findTypeDefinitionBuilderWithConstraints(
+    private TypeDefinitionBuilder resolveCopiedBuilder(
+            TypeDefinitionBuilder copy,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            UnknownType unknownType, ModuleBuilder builder) {
-        return findTypeDefinitionBuilderWithConstraints(new TypeConstraints(),
-                modules, unknownType, builder);
+            ModuleBuilder builder) {
+
+        if (copy instanceof UnionTypeBuilder) {
+            UnionTypeBuilder union = (UnionTypeBuilder) copy;
+            List<TypeDefinition<?>> unionTypes = union.getTypes();
+            List<UnknownType> toRemove = new ArrayList<UnknownType>();
+            for (TypeDefinition<?> td : unionTypes) {
+                if (td instanceof UnknownType) {
+                    UnknownType unknownType = (UnknownType) td;
+                    TypeDefinitionBuilder resolvedType = resolveTypeUnion(
+                            union, unknownType, modules, builder);
+                    union.setType(resolvedType);
+                    toRemove.add(unknownType);
+                }
+            }
+            unionTypes.removeAll(toRemove);
+
+            return union;
+        }
+
+        TypeDefinition<?> base = copy.getType();
+        TypeDefinitionBuilder baseTdb = copy.getTypedef();
+        if (base != null && !(base instanceof UnknownType)) {
+            return copy;
+        } else if (base instanceof UnknownType) {
+            UnknownType unknownType = (UnknownType) base;
+            QName unknownTypeQName = unknownType.getQName();
+            String unknownTypePrefix = unknownTypeQName.getPrefix();
+            ModuleBuilder dependentModule = findDependentModule(modules,
+                    builder, unknownTypePrefix);
+            TypeDefinitionBuilder unknownTypeBuilder = getTypedefBuilder(copy,
+                    modules, dependentModule);
+            copy.setType(unknownTypeBuilder);
+            return copy;
+        } else if (base == null && baseTdb != null) {
+            // make a copy of baseTypeDef and call again
+            TypeDefinitionBuilder baseTdbCopy = copyTypedefBuilder(baseTdb,
+                    true);
+            TypeDefinitionBuilder baseTdbCopyResolved = resolveCopiedBuilder(
+                    baseTdbCopy, modules, builder);
+            copy.setType(baseTdbCopyResolved);
+            return copy;
+        } else {
+            throw new IllegalStateException(
+                    "TypeDefinitionBuilder in unexpected state");
+        }
     }
 
-    /**
-     * Traverse through all referenced types chain until base YANG type is
-     * founded.
-     *
-     * @param constraints current type constraints
-     * @param modules all available modules
-     * @param unknownType unknown type
-     * @param builder current module
-     * @return map, where key is type referenced and value is its constraints
-     */
-    private Map<TypeDefinitionBuilder, TypeConstraints> findTypeDefinitionBuilderWithConstraints(
-            TypeConstraints constraints,
+    private TypeDefinitionBuilder findTypedefBuilder(QName unknownTypeQName,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            UnknownType unknownType, ModuleBuilder builder) {
-        Map<TypeDefinitionBuilder, TypeConstraints> result = new HashMap<TypeDefinitionBuilder, TypeConstraints>();
+            ModuleBuilder builder) {
 
-        // TypeDefinition<?> unknownType = typeBuilder.getType();
-        QName unknownTypeQName = unknownType.getQName();
         String unknownTypeName = unknownTypeQName.getLocalName();
         String unknownTypePrefix = unknownTypeQName.getPrefix();
 
         // search for module which contains referenced typedef
-        ModuleBuilder dependentModuleBuilder;
-        if (unknownTypePrefix.equals(builder.getPrefix())) {
-            dependentModuleBuilder = builder;
-        } else {
-            ModuleImport dependentModuleImport = getModuleImport(builder,
-                    unknownTypePrefix);
-            String dependentModuleName = dependentModuleImport.getModuleName();
-            Date dependentModuleRevision = dependentModuleImport.getRevision();
-            TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules
-                    .get(dependentModuleName);
-            if (dependentModuleRevision == null) {
-                dependentModuleBuilder = moduleBuildersByRevision.lastEntry()
-                        .getValue();
-            } else {
-                dependentModuleBuilder = moduleBuildersByRevision
-                        .get(dependentModuleRevision);
-            }
-        }
+        ModuleBuilder dependentModule = findDependentModule(modules, builder,
+                unknownTypePrefix);
 
-        // pull all typedef statements from dependent module...
-        final Set<TypeDefinitionBuilder> typedefs = dependentModuleBuilder
-                .getModuleTypedefs();
-        // and search for referenced typedef
-        TypeDefinitionBuilder lookedUpBuilder = null;
-        for (TypeDefinitionBuilder tdb : typedefs) {
-            QName qname = tdb.getQName();
-            if (qname.getLocalName().equals(unknownTypeName)) {
-                lookedUpBuilder = tdb;
-                break;
-            }
+        TypeDefinitionBuilder lookedUpBuilder = findTypedefBuilderByName(
+                dependentModule, unknownTypeName);
+
+        TypeDefinitionBuilder copied = copyTypedefBuilder(lookedUpBuilder, true);
+        return copied;
+    }
+
+    private TypeConstraints findConstraints(TypeAwareBuilder nodeToResolve,
+            TypeConstraints constraints,
+            Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder builder) {
+
+        // union type cannot be restricted
+        if (nodeToResolve instanceof UnionTypeBuilder) {
+            return constraints;
         }
 
         // if referenced type is UnknownType again, search recursively with
         // current constraints
-        TypeDefinition<?> referencedType = lookedUpBuilder.getBaseType();
-        if (referencedType instanceof UnknownType) {
-            UnknownType unknown = (UnknownType) lookedUpBuilder.getBaseType();
-
-            final List<RangeConstraint> ranges = unknown.getRangeStatements();
+        TypeDefinition<?> referencedType = nodeToResolve.getType();
+        List<RangeConstraint> ranges = Collections.emptyList();
+        List<LengthConstraint> lengths = Collections.emptyList();
+        List<PatternConstraint> patterns = Collections.emptyList();
+        Integer fractionDigits = null;
+        if (referencedType == null) {
+            TypeDefinitionBuilder tdb = (TypeDefinitionBuilder) nodeToResolve;
+            ranges = tdb.getRanges();
+            constraints.addRanges(ranges);
+            lengths = tdb.getLengths();
+            constraints.addLengths(lengths);
+            patterns = tdb.getPatterns();
+            constraints.addPatterns(patterns);
+            fractionDigits = tdb.getFractionDigits();
+            constraints.setFractionDigits(fractionDigits);
+            return constraints;
+        } else if (referencedType instanceof ExtendedType) {
+            ExtendedType ext = (ExtendedType) referencedType;
+            ranges = ext.getRanges();
+            constraints.addRanges(ranges);
+            lengths = ext.getLengths();
+            constraints.addLengths(lengths);
+            patterns = ext.getPatterns();
+            constraints.addPatterns(patterns);
+            fractionDigits = ext.getFractionDigits();
+            constraints.setFractionDigits(fractionDigits);
+            return findConstraints(
+                    findTypedefBuilder(ext.getQName(), modules, builder),
+                    constraints, modules, builder);
+        } else if (referencedType instanceof UnknownType) {
+            UnknownType unknown = (UnknownType) referencedType;
+
+            ranges = unknown.getRangeStatements();
             constraints.addRanges(ranges);
-            final List<LengthConstraint> lengths = unknown
-                    .getLengthStatements();
+            lengths = unknown.getLengthStatements();
             constraints.addLengths(lengths);
-            final List<PatternConstraint> patterns = unknown.getPatterns();
+            patterns = unknown.getPatterns();
             constraints.addPatterns(patterns);
-            return findTypeDefinitionBuilderWithConstraints(constraints,
-                    modules, unknown, dependentModuleBuilder);
+            fractionDigits = unknown.getFractionDigits();
+            constraints.setFractionDigits(fractionDigits);
+
+            String unknownTypePrefix = unknown.getQName().getPrefix();
+            if (unknownTypePrefix == null || "".equals(unknownTypePrefix)) {
+                unknownTypePrefix = builder.getPrefix();
+            }
+            ModuleBuilder dependentModule = findDependentModule(modules,
+                    builder, unknown.getQName().getPrefix());
+            TypeDefinitionBuilder unknownTypeBuilder = findTypedefBuilder(
+                    unknown.getQName(), modules, builder);
+            return findConstraints(unknownTypeBuilder, constraints, modules,
+                    dependentModule);
         } else {
-            // pull restriction from this base type and add them to
-            // 'constraints'
-            if (referencedType instanceof DecimalTypeDefinition) {
-                constraints.addRanges(((DecimalTypeDefinition) referencedType)
-                        .getRangeStatements());
-                constraints
-                        .setFractionDigits(((DecimalTypeDefinition) referencedType)
-                                .getFractionDigits());
-            } else if (referencedType instanceof IntegerTypeDefinition) {
-                constraints.addRanges(((IntegerTypeDefinition) referencedType)
-                        .getRangeStatements());
-            } else if (referencedType instanceof StringTypeDefinition) {
-                constraints.addPatterns(((StringTypeDefinition) referencedType)
-                        .getPatterns());
-            } else if (referencedType instanceof BinaryTypeDefinition) {
-                constraints.addLengths(((BinaryTypeDefinition) referencedType)
-                        .getLengthConstraints());
-            } else if (referencedType instanceof InstanceIdentifierTypeDefinition) {
-                // TODO: instance-identifier
+            // HANDLE BASE YANG TYPE
+            mergeConstraints(referencedType, constraints);
+            return constraints;
+        }
+
+    }
+
+    /**
+     * Go through all typedef statements from given module and search for one
+     * with given name
+     *
+     * @param typedefs
+     *            typedef statements to search
+     * @param name
+     *            name of searched typedef
+     * @return typedef with name equals to given name
+     */
+    private TypeDefinitionBuilder findTypedefBuilderByName(
+            ModuleBuilder dependentModule, String name) {
+        TypeDefinitionBuilder result = null;
+        final Set<TypeDefinitionBuilder> typedefs = dependentModule
+                .getModuleTypedefs();
+        for (TypeDefinitionBuilder td : typedefs) {
+            if (td.getQName().getLocalName().equals(name)) {
+                result = td;
+                break;
             }
+        }
+        if (result == null) {
+            throw new YangParseException("Target module '"
+                    + dependentModule.getName()
+                    + "' does not contain typedef '" + name + "'.");
+        }
+        return result;
+    }
 
-            result.put(lookedUpBuilder, constraints);
-            return result;
+    /**
+     * Pull restriction from referenced type and add them to given constraints
+     *
+     * @param referencedType
+     * @param constraints
+     */
+    private void mergeConstraints(TypeDefinition<?> referencedType,
+            TypeConstraints constraints) {
+
+        if (referencedType instanceof DecimalTypeDefinition) {
+            constraints.addRanges(((DecimalTypeDefinition) referencedType)
+                    .getRangeStatements());
+            constraints
+                    .setFractionDigits(((DecimalTypeDefinition) referencedType)
+                            .getFractionDigits());
+        } else if (referencedType instanceof IntegerTypeDefinition) {
+            constraints.addRanges(((IntegerTypeDefinition) referencedType)
+                    .getRangeStatements());
+        } else if (referencedType instanceof StringTypeDefinition) {
+            constraints.addPatterns(((StringTypeDefinition) referencedType)
+                    .getPatterns());
+            constraints.addLengths(((StringTypeDefinition) referencedType)
+                    .getLengthStatements());
+        } else if (referencedType instanceof BinaryTypeDefinition) {
+            constraints.addLengths(((BinaryTypeDefinition) referencedType)
+                    .getLengthConstraints());
         }
     }
 
@@ -463,47 +639,67 @@ public class YangModelParserImpl implements YangModelParser {
      * @param module
      *            current module
      */
-    private void resolveAugments(
+    public void resolveAugments(
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
             ModuleBuilder module) {
         Set<AugmentationSchemaBuilder> augmentBuilders = module
                 .getAddedAugments();
 
-        Set<AugmentationSchema> augments = new HashSet<AugmentationSchema>();
         for (AugmentationSchemaBuilder augmentBuilder : augmentBuilders) {
             SchemaPath augmentTargetSchemaPath = augmentBuilder.getTargetPath();
-            String prefix = null;
-            List<String> augmentTargetPath = new ArrayList<String>();
-            for (QName pathPart : augmentTargetSchemaPath.getPath()) {
-                prefix = pathPart.getPrefix();
-                augmentTargetPath.add(pathPart.getLocalName());
-            }
-            ModuleImport dependentModuleImport = getModuleImport(module,
-                    prefix);
-            String dependentModuleName = dependentModuleImport.getModuleName();
-            augmentTargetPath.add(0, dependentModuleName);
+            List<QName> path = augmentTargetSchemaPath.getPath();
 
-            Date dependentModuleRevision = dependentModuleImport.getRevision();
+            String prefix = path.get(path.size() - 1).getPrefix();
+            List<String> augmentTargetPath = new ArrayList<String>();
 
-            TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules
-                    .get(dependentModuleName);
-            ModuleBuilder dependentModule;
-            if (dependentModuleRevision == null) {
-                dependentModule = moduleBuildersByRevision.lastEntry()
-                        .getValue();
-            } else {
-                dependentModule = moduleBuildersByRevision
-                        .get(dependentModuleRevision);
+            for (QName pathPart : path) {
+                if (pathPart.getPrefix().equals(prefix)) {
+                    augmentTargetPath.add(pathPart.getLocalName());
+                }
+            }
+            if (prefix == null) {
+                prefix = module.getPrefix();
             }
 
+            ModuleBuilder dependentModule = findDependentModule(modules,
+                    module, prefix);
+            augmentTargetPath.add(0, dependentModule.getName());
+
             AugmentationTargetBuilder augmentTarget = (AugmentationTargetBuilder) dependentModule
                     .getNode(augmentTargetPath);
-            AugmentationSchema result = augmentBuilder.build();
-            augmentTarget.addAugmentation(result);
-            fillAugmentTarget(augmentBuilder, (ChildNodeBuilder) augmentTarget);
-            augments.add(result);
+
+            // augment target could be another augment, so if target is not
+            // found, get augments in target module and search for target node
+            if (augmentTarget == null) {
+                for (AugmentationSchemaBuilder builder : dependentModule
+                        .getAddedAugments()) {
+                    for (DataSchemaNodeBuilder dataBuilder : builder
+                            .getChildNodes()) {
+                        SchemaPath dataBuilderPath = dataBuilder.getPath();
+                        List<QName> qnamePath = dataBuilderPath.getPath();
+                        List<String> dataBuilderStringPath = new ArrayList<String>();
+
+                        // start from 1: augment name omitted
+                        for (int i = 1; i < qnamePath.size(); i++) {
+                            dataBuilderStringPath.add(qnamePath.get(i)
+                                    .getLocalName());
+                        }
+                        // module name omitted
+                        augmentTargetPath.remove(0);
+                        if (augmentTargetPath.equals(dataBuilderStringPath)) {
+                            augmentTarget = (AugmentationTargetBuilder) dataBuilder;
+                            augmentTarget.addAugmentation(augmentBuilder);
+                            fillAugmentTarget(augmentBuilder,
+                                    (ChildNodeBuilder) augmentTarget);
+                        }
+                    }
+                }
+            } else {
+                augmentTarget.addAugmentation(augmentBuilder);
+                fillAugmentTarget(augmentBuilder,
+                        (ChildNodeBuilder) augmentTarget);
+            }
         }
-        module.setAugmentations(augments);
     }
 
     /**
@@ -521,136 +717,312 @@ public class YangModelParserImpl implements YangModelParser {
     }
 
     /**
-     * Get module import referenced by given prefix.
+     * Go through identity statements defined in current module and resolve
+     * their 'base' statement if present.
      *
-     * @param builder
-     *            module to search
-     * @param prefix
-     *            prefix associated with import
-     * @return ModuleImport based on given prefix
+     * @param modules
+     *            all modules
+     * @param module
+     *            module being resolved
      */
-    private ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
-        ModuleImport moduleImport = null;
-        for (ModuleImport mi : builder.getModuleImports()) {
-            if (mi.getPrefix().equals(prefix)) {
-                moduleImport = mi;
-                break;
+    private void resolveIdentities(
+            Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder module) {
+        Set<IdentitySchemaNodeBuilder> identities = module.getAddedIdentities();
+        for (IdentitySchemaNodeBuilder identity : identities) {
+            String baseIdentityName = identity.getBaseIdentityName();
+            if (baseIdentityName != null) {
+                String baseIdentityPrefix = null;
+                String baseIdentityLocalName = null;
+                if (baseIdentityName.contains(":")) {
+                    String[] splitted = baseIdentityName.split(":");
+                    baseIdentityPrefix = splitted[0];
+                    baseIdentityLocalName = splitted[1];
+                } else {
+                    baseIdentityPrefix = module.getPrefix();
+                    baseIdentityLocalName = baseIdentityName;
+                }
+                ModuleBuilder dependentModule = findDependentModule(modules,
+                        module, baseIdentityPrefix);
+
+                Set<IdentitySchemaNodeBuilder> dependentModuleIdentities = dependentModule
+                        .getAddedIdentities();
+                for (IdentitySchemaNodeBuilder idBuilder : dependentModuleIdentities) {
+                    if (idBuilder.getQName().getLocalName()
+                            .equals(baseIdentityLocalName)) {
+                        identity.setBaseIdentity(idBuilder);
+                    }
+                }
             }
         }
-        return moduleImport;
     }
 
     /**
-     * Helper method for resolving special 'min' or 'max' values in range
-     * constraint
+     * Go through uses statements defined in current module and resolve their
+     * refine statements.
      *
-     * @param ranges ranges to resolve
-     * @param targetType target type
-     * @param modules all available modules
-     * @param builder current module
+     * @param modules
+     *            all modules
+     * @param module
+     *            module being resolved
      */
-    private void resolveRanges(List<RangeConstraint> ranges,
-            TypeDefinitionBuilder targetType,
-            Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder builder) {
-        if (ranges != null && ranges.size() > 0) {
-            Long min = (Long) ranges.get(0).getMin();
-            Long max = (Long) ranges.get(ranges.size() - 1).getMax();
-            // if range contains one of the special values 'min' or 'max'
-            if (min.equals(Long.MIN_VALUE) || max.equals(Long.MAX_VALUE)) {
-                Long[] values = parseRangeConstraint(targetType, modules,
-                        builder);
-                if (min.equals(Long.MIN_VALUE)) {
-                    min = values[0];
-                    RangeConstraint oldFirst = ranges.get(0);
-                    RangeConstraint newFirst = BaseConstraints.rangeConstraint(
-                            min, oldFirst.getMax(), oldFirst.getDescription(),
-                            oldFirst.getReference());
-                    ranges.set(0, newFirst);
-                }
-                if (max.equals(Long.MAX_VALUE)) {
-                    max = values[1];
-                    RangeConstraint oldLast = ranges.get(ranges.size() - 1);
-                    RangeConstraint newLast = BaseConstraints.rangeConstraint(
-                            oldLast.getMin(), max, oldLast.getDescription(),
-                            oldLast.getReference());
-                    ranges.set(ranges.size() - 1, newLast);
+    private void resolveUses(Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder module) {
+        Map<List<String>, UsesNodeBuilder> moduleUses = module
+                .getAddedUsesNodes();
+        for (Map.Entry<List<String>, UsesNodeBuilder> entry : moduleUses
+                .entrySet()) {
+            List<String> key = entry.getKey();
+            UsesNodeBuilder usesNode = entry.getValue();
+
+            String groupingName = key.get(key.size() - 1);
+
+            List<RefineHolder> refines = usesNode.getRefines();
+            for (RefineHolder refine : refines) {
+                Refine refineType = refine.getType();
+
+                // refine statements
+                String defaultStr = refine.getDefaultStr();
+                Boolean mandatory = refine.isMandatory();
+                MustDefinition must = refine.getMust();
+                Boolean presence = refine.isPresence();
+                Integer min = refine.getMinElements();
+                Integer max = refine.getMaxElements();
+
+                switch (refineType) {
+                case LEAF:
+                    LeafSchemaNodeBuilder leaf = (LeafSchemaNodeBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (defaultStr != null && !("".equals(defaultStr))) {
+                        leaf.setDefaultStr(defaultStr);
+                    }
+                    if (mandatory != null) {
+                        leaf.getConstraints().setMandatory(mandatory);
+                    }
+                    if (must != null) {
+                        leaf.getConstraints().addMustDefinition(must);
+                    }
+                    usesNode.addRefineNode(leaf);
+                    break;
+                case CONTAINER:
+                    ContainerSchemaNodeBuilder container = (ContainerSchemaNodeBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (presence != null) {
+                        container.setPresence(presence);
+                    }
+                    if (must != null) {
+                        container.getConstraints().addMustDefinition(must);
+                    }
+                    usesNode.addRefineNode(container);
+                    break;
+                case LIST:
+                    ListSchemaNodeBuilder list = (ListSchemaNodeBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (must != null) {
+                        list.getConstraints().addMustDefinition(must);
+                    }
+                    if (min != null) {
+                        list.getConstraints().setMinElements(min);
+                    }
+                    if (max != null) {
+                        list.getConstraints().setMaxElements(max);
+                    }
+                    break;
+                case LEAF_LIST:
+                    LeafListSchemaNodeBuilder leafList = (LeafListSchemaNodeBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (must != null) {
+                        leafList.getConstraints().addMustDefinition(must);
+                    }
+                    if (min != null) {
+                        leafList.getConstraints().setMinElements(min);
+                    }
+                    if (max != null) {
+                        leafList.getConstraints().setMaxElements(max);
+                    }
+                    break;
+                case CHOICE:
+                    ChoiceBuilder choice = (ChoiceBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (defaultStr != null) {
+                        choice.setDefaultCase(defaultStr);
+                    }
+                    if (mandatory != null) {
+                        choice.getConstraints().setMandatory(mandatory);
+                    }
+                    break;
+                case ANYXML:
+                    AnyXmlBuilder anyXml = (AnyXmlBuilder) getRefineTargetBuilder(
+                            groupingName, refine, modules, module);
+                    if (mandatory != null) {
+                        anyXml.getConstraints().setMandatory(mandatory);
+                    }
+                    if (must != null) {
+                        anyXml.getConstraints().addMustDefinition(must);
+                    }
                 }
             }
         }
+
     }
 
     /**
-     * Helper method for resolving special 'min' or 'max' values in length
-     * constraint
+     * Find original builder of refine node and return copy of this builder.
      *
-     * @param lengths lengths to resolve
-     * @param targetType target type
-     * @param modules all available modules
-     * @param builder current module
+     * @param groupingPath
+     *            path to grouping which contains node to refine
+     * @param refine
+     *            refine object containing informations about refine
+     * @param modules
+     *            all loaded modules
+     * @param module
+     *            current module
+     * @return copy of Builder object of node to be refined if it is present in
+     *         grouping, null otherwise
      */
-    private void resolveLengths(List<LengthConstraint> lengths,
-            TypeDefinitionBuilder targetType,
+    private Builder getRefineTargetBuilder(String groupingPath,
+            RefineHolder refine,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder builder) {
-        if (lengths != null && lengths.size() > 0) {
-            Long min = lengths.get(0).getMin();
-            Long max = lengths.get(lengths.size() - 1).getMax();
-            // if length contains one of the special values 'min' or 'max'
-            if (min.equals(Long.MIN_VALUE) || max.equals(Long.MAX_VALUE)) {
-                Long[] values = parseRangeConstraint(targetType, modules,
-                        builder);
-                if (min.equals(Long.MIN_VALUE)) {
-                    min = values[0];
-                    LengthConstraint oldFirst = lengths.get(0);
-                    LengthConstraint newFirst = BaseConstraints
-                            .lengthConstraint(min, oldFirst.getMax(),
-                                    oldFirst.getDescription(),
-                                    oldFirst.getReference());
-                    lengths.set(0, newFirst);
-                }
-                if (max.equals(Long.MAX_VALUE)) {
-                    max = values[1];
-                    LengthConstraint oldLast = lengths.get(lengths.size() - 1);
-                    LengthConstraint newLast = BaseConstraints
-                            .lengthConstraint(oldLast.getMin(), max,
-                                    oldLast.getDescription(),
-                                    oldLast.getReference());
-                    lengths.set(lengths.size() - 1, newLast);
-                }
-            }
+            ModuleBuilder module) {
+        Builder result = null;
+        Builder lookedUpBuilder = findRefineTargetBuilder(groupingPath,
+                refine.getName(), modules, module);
+        if (lookedUpBuilder instanceof LeafSchemaNodeBuilder) {
+            result = ParserUtils
+                    .copyLeafBuilder((LeafSchemaNodeBuilder) lookedUpBuilder);
+        } else if (lookedUpBuilder instanceof ContainerSchemaNodeBuilder) {
+            result = ParserUtils
+                    .copyContainerBuilder((ContainerSchemaNodeBuilder) lookedUpBuilder);
+        } else if (lookedUpBuilder instanceof ListSchemaNodeBuilder) {
+            result = ParserUtils
+                    .copyListBuilder((ListSchemaNodeBuilder) lookedUpBuilder);
+        } else if (lookedUpBuilder instanceof LeafListSchemaNodeBuilder) {
+            result = ParserUtils
+                    .copyLeafListBuilder((LeafListSchemaNodeBuilder) lookedUpBuilder);
+        } else if (lookedUpBuilder instanceof ChoiceBuilder) {
+            result = ParserUtils
+                    .copyChoiceBuilder((ChoiceBuilder) lookedUpBuilder);
+        } else if (lookedUpBuilder instanceof AnyXmlBuilder) {
+            result = ParserUtils
+                    .copyAnyXmlBuilder((AnyXmlBuilder) lookedUpBuilder);
+        } else {
+            throw new YangParseException("Target '" + refine.getName()
+                    + "' can not be refined");
         }
+        return result;
     }
 
-    private Long[] parseRangeConstraint(TypeDefinitionBuilder targetType,
+    /**
+     * Find builder of refine node.
+     *
+     * @param groupingPath
+     *            path to grouping which contains node to refine
+     * @param refineNodeName
+     *            name of node to be refined
+     * @param modules
+     *            all loaded modules
+     * @param module
+     *            current module
+     * @return Builder object of refine node if it is present in grouping, null
+     *         otherwise
+     */
+    private Builder findRefineTargetBuilder(String groupingPath,
+            String refineNodeName,
             Map<String, TreeMap<Date, ModuleBuilder>> modules,
-            ModuleBuilder builder) {
-        TypeDefinition<?> targetBaseType = targetType.getBaseType();
-
-        if (targetBaseType instanceof IntegerTypeDefinition) {
-            IntegerTypeDefinition itd = (IntegerTypeDefinition) targetBaseType;
-            List<RangeConstraint> ranges = itd.getRangeStatements();
-            Long min = (Long) ranges.get(0).getMin();
-            Long max = (Long) ranges.get(ranges.size() - 1).getMax();
-            return new Long[] { min, max };
-        } else if (targetBaseType instanceof DecimalTypeDefinition) {
-            DecimalTypeDefinition dtd = (DecimalTypeDefinition) targetBaseType;
-            List<RangeConstraint> ranges = dtd.getRangeStatements();
-            Long min = (Long) ranges.get(0).getMin();
-            Long max = (Long) ranges.get(ranges.size() - 1).getMax();
-            return new Long[] { min, max };
+            ModuleBuilder module) {
+        SchemaPath path = ParserUtils.parseUsesPath(groupingPath);
+        List<String> builderPath = new ArrayList<String>();
+        String prefix = null;
+        for (QName qname : path.getPath()) {
+            builderPath.add(qname.getLocalName());
+            prefix = qname.getPrefix();
+        }
+        if (prefix == null) {
+            prefix = module.getPrefix();
+        }
+
+        ModuleBuilder dependentModule = findDependentModule(modules, module,
+                prefix);
+        builderPath.add(0, "grouping");
+        builderPath.add(0, dependentModule.getName());
+        GroupingBuilder builder = (GroupingBuilder) dependentModule
+                .getNode(builderPath);
+
+        return builder.getChildNode(refineNodeName);
+    }
+
+    /**
+     * Find dependent module based on given prefix
+     *
+     * @param modules
+     *            all available modules
+     * @param module
+     *            current module
+     * @param prefix
+     *            target module prefix
+     * @return
+     */
+    private ModuleBuilder findDependentModule(
+            Map<String, TreeMap<Date, ModuleBuilder>> modules,
+            ModuleBuilder module, String prefix) {
+        ModuleBuilder dependentModule = null;
+        Date dependentModuleRevision = null;
+
+        if (prefix.equals(module.getPrefix())) {
+            dependentModule = module;
         } else {
-            return parseRangeConstraint(
-                    findTypeDefinitionBuilder(modules,
-                            (UnknownType) targetBaseType, builder), modules,
-                    builder);
+            ModuleImport dependentModuleImport = getModuleImport(module, prefix);
+            if (dependentModuleImport == null) {
+                throw new YangParseException("No import found with prefix '"
+                        + prefix + "' in module " + module.getName() + "'.");
+            }
+            String dependentModuleName = dependentModuleImport.getModuleName();
+            dependentModuleRevision = dependentModuleImport.getRevision();
+
+            TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules
+                    .get(dependentModuleName);
+            if (moduleBuildersByRevision == null) {
+                throw new YangParseException(
+                        "Failed to find dependent module '"
+                                + dependentModuleName + "' needed by module '"
+                                + module.getName() + "'.");
+            }
+            if (dependentModuleRevision == null) {
+                dependentModule = moduleBuildersByRevision.lastEntry()
+                        .getValue();
+            } else {
+                dependentModule = moduleBuildersByRevision
+                        .get(dependentModuleRevision);
+            }
         }
+
+        if (dependentModule == null) {
+            throw new YangParseException(
+                    "Failed to find dependent module with prefix '" + prefix
+                            + "' and revision '" + dependentModuleRevision
+                            + "'.");
+        }
+        return dependentModule;
     }
 
-    private Date createEpochTime() {
-        Calendar c = Calendar.getInstance();
-        c.setTimeInMillis(0);
-        return c.getTime();
+    /**
+     * Get module import referenced by given prefix.
+     *
+     * @param builder
+     *            module to search
+     * @param prefix
+     *            prefix associated with import
+     * @return ModuleImport based on given prefix
+     */
+    private ModuleImport getModuleImport(ModuleBuilder builder, String prefix) {
+        ModuleImport moduleImport = null;
+        for (ModuleImport mi : builder.getModuleImports()) {
+            if (mi.getPrefix().equals(prefix)) {
+                moduleImport = mi;
+                break;
+            }
+        }
+        return moduleImport;
     }
 
     private static class SchemaContextImpl implements SchemaContext {
@@ -700,46 +1072,30 @@ public class YangModelParserImpl implements YangModelParser {
             }
             return extensions;
         }
-    }
-
-    private static class TypeConstraints {
-        private final List<RangeConstraint> ranges = new ArrayList<RangeConstraint>();
-        private final List<LengthConstraint> lengths = new ArrayList<LengthConstraint>();
-        private final List<PatternConstraint> patterns = new ArrayList<PatternConstraint>();
-        private Integer fractionDigits;
-
-        public List<RangeConstraint> getRanges() {
-            return ranges;
-        }
 
-        public void addRanges(List<RangeConstraint> ranges) {
-            this.ranges.addAll(0, ranges);
-        }
-
-        public List<LengthConstraint> getLengths() {
-            return lengths;
-        }
-
-        public void addLengths(List<LengthConstraint> lengths) {
-            this.lengths.addAll(0, lengths);
-        }
-
-        public List<PatternConstraint> getPatterns() {
-            return patterns;
-        }
-
-        public void addPatterns(List<PatternConstraint> patterns) {
-            this.patterns.addAll(0, patterns);
-        }
-
-        public Integer getFractionDigits() {
-            return fractionDigits;
+        @Override
+        public Module findModuleByName(final String name, final Date revision) {
+            if ((name != null) && (revision != null)) {
+                for (final Module module : modules) {
+                    if (module.getName().equals(name)
+                            && module.getRevision().equals(revision)) {
+                        return module;
+                    }
+                }
+            }
+            return null;
         }
 
-        public void setFractionDigits(Integer fractionDigits) {
-            if (fractionDigits != null) {
-                this.fractionDigits = fractionDigits;
+        @Override
+        public Module findModuleByNamespace(URI namespace) {
+            if (namespace != null) {
+                for (final Module module : modules) {
+                    if (module.getNamespace().equals(namespace)) {
+                        return module;
+                    }
+                }
             }
+            return null;
         }
     }