Cleanup AbstractTypeProvider.isLeafRefSelfReference()
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / yang / types / AbstractTypeProvider.java
index 6cb6ff926e493cd5c10fd7895f4bf46817f33228..4f422cb04e817e90be95aef9fed4b0461eec98b8 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.mdsal.binding.yang.types;
 
+import static java.util.Objects.requireNonNull;
+import static org.opendaylight.mdsal.binding.model.util.BindingTypes.TYPE_OBJECT;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
@@ -15,23 +17,20 @@ import com.google.common.annotations.Beta;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
-import com.google.common.io.BaseEncoding;
-import java.io.Serializable;
 import java.math.BigDecimal;
-import java.math.BigInteger;
 import java.util.ArrayList;
+import java.util.Base64;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.TreeMap;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
@@ -39,6 +38,7 @@ import org.opendaylight.mdsal.binding.model.api.ConcreteType;
 import org.opendaylight.mdsal.binding.model.api.Enumeration;
 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
 import org.opendaylight.mdsal.binding.model.api.Restrictions;
 import org.opendaylight.mdsal.binding.model.api.Type;
 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
@@ -52,16 +52,20 @@ import org.opendaylight.mdsal.binding.model.util.TypeConstants;
 import org.opendaylight.mdsal.binding.model.util.Types;
 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.Revision;
+import org.opendaylight.yangtools.yang.common.Uint16;
+import org.opendaylight.yangtools.yang.common.Uint32;
+import org.opendaylight.yangtools.yang.common.Uint64;
+import org.opendaylight.yangtools.yang.common.Uint8;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
+import org.opendaylight.yangtools.yang.model.api.PathExpression;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
@@ -77,10 +81,11 @@ import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
-import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
+import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
@@ -91,7 +96,6 @@ import org.slf4j.LoggerFactory;
 public abstract class AbstractTypeProvider implements TypeProvider {
     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
     private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
-    private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
 
     // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
     // the case, as unions are emitted to their correct schema path.
@@ -103,9 +107,6 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      */
     private final SchemaContext schemaContext;
 
-    /**
-     * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
-     */
     private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
 
     /**
@@ -113,29 +114,27 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      */
     private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
     private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
+    private final Map<SchemaNode, JavaTypeName> renames;
 
     /**
      * Creates new instance of class <code>TypeProviderImpl</code>.
      *
-     * @param schemaContext
-     *            contains the schema data red from YANG files
-     * @throws IllegalArgumentException
-     *             if <code>schemaContext</code> equal null.
+     * @param schemaContext contains the schema data red from YANG files
+     * @param renames renaming table
+     * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
      */
-    AbstractTypeProvider(final SchemaContext schemaContext) {
+    AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
-
         this.schemaContext = schemaContext;
+        this.renames = requireNonNull(renames);
         resolveTypeDefsFromContext();
     }
 
     /**
-     * Puts <code>refType</code> to map with key <code>refTypePath</code>
+     * Puts <code>refType</code> to map with key <code>refTypePath</code>.
      *
-     * @param refTypePath
-     *            schema path used as the map key
-     * @param refType
-     *            type which represents the map value
+     * @param refTypePath schema path used as the map key
+     * @param refType type which represents the map value
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>refTypePath</code> equal null</li>
@@ -154,32 +153,16 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         return additionalTypes;
     }
 
-    /**
-     *
-     * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
-     *
-     * @param type
-     *            string with YANG name of type
-     * @return JAVA <code>Type</code> for YANG type <code>type</code>
-     * @see TypeProvider#javaTypeForYangType(String)
-     */
-    @Override
-    @Deprecated
-    public Type javaTypeForYangType(final String type) {
-        return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
-    }
-
     @Override
-    public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
-        return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
+    public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
+            final boolean lenientRelativeLeafrefs) {
+        return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
     }
 
     /**
-     * Converts schema definition type <code>typeDefinition</code> to JAVA
-     * <code>Type</code>
+     * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
      *
-     * @param typeDefinition
-     *            type definition which is converted to JAVA type
+     * @param typeDefinition type definition which is converted to JAVA type
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>typeDefinition</code> equal null</li>
@@ -189,7 +172,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      */
     @Override
     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
-            final Restrictions r) {
+            final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
         Preconditions.checkArgument(typeDefinition.getQName() != null,
                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
@@ -203,20 +186,20 @@ public abstract class AbstractTypeProvider implements TypeProvider {
             // a base type which holds these constraints.
             if (typeDefinition instanceof DecimalTypeDefinition) {
                 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
-                    parentNode, r);
+                    parentNode, restrictions, lenientRelativeLeafrefs);
                 if (ret != null) {
                     return ret;
                 }
             }
 
             // Deal with leafrefs/identityrefs
-            Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
+            Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
             if (ret != null) {
                 return ret;
             }
 
             // FIXME: it looks as though we could be using the same codepath as above...
-            ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
+            ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
             if (ret == null) {
                 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
             }
@@ -224,8 +207,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
             return ret;
         }
 
-        Type returnType = javaTypeForExtendedType(typeDefinition);
-        if (r != null && returnType instanceof GeneratedTransferObject) {
+        Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
+        if (restrictions != null && returnType instanceof GeneratedTransferObject) {
             final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
             final Module module = findParentModule(schemaContext, parentNode);
             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
@@ -234,19 +217,20 @@ public abstract class AbstractTypeProvider implements TypeProvider {
             final String genTOName = BindingMapping.getClassName(typedefName);
             final String name = packageName + "." + genTOName;
             if (!returnType.getFullyQualifiedName().equals(name)) {
-                returnType = shadedTOWithRestrictions(gto, r);
+                returnType = shadedTOWithRestrictions(gto, restrictions);
             }
         }
         return returnType;
     }
 
-    private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
-        final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getPackageName(), gto.getName());
+    private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
+            final Restrictions restrictions) {
+        final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
         final GeneratedTransferObject parent = gto.getSuperType();
         if (parent != null) {
             gtob.setExtendsType(parent);
         }
-        gtob.setRestrictions(r);
+        gtob.setRestrictions(restrictions);
         for (GeneratedProperty gp : gto.getProperties()) {
             final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
             gpb.setValue(gp.getValue());
@@ -260,63 +244,58 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
-        final SchemaNode leafRefValueNode;
-        final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
-        final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
-            GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
-
-        ///// skip leafrefs in augments - they're checked once augments are resolved
-        final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
-        boolean isAugmenting = false;
+        /*
+         * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
+         * are resolved.
+         */
         DataNodeContainer current = null;
         DataSchemaNode dataChildByName;
-
-        while (iterator.hasNext() && !isAugmenting) {
-            final QName next = iterator.next();
+        for (QName next : parentNode.getPath().getPathFromRoot()) {
             if (current == null) {
                 dataChildByName = schemaContext.getDataChildByName(next);
             } else {
                 dataChildByName = current.getDataChildByName(next);
             }
-            if (dataChildByName != null) {
-                isAugmenting = dataChildByName.isAugmenting();
-            } else {
+            if (dataChildByName == null) {
+                return false;
+            }
+            if (dataChildByName.isAugmenting()) {
                 return false;
             }
             if (dataChildByName instanceof DataNodeContainer) {
                 current = (DataNodeContainer) dataChildByName;
             }
         }
-        if (isAugmenting) {
-            return false;
-        }
-        /////
 
+        // Then try to look up the expression.
+        final PathExpression leafRefXPath = leafref.getPathStatement();
+        final PathExpression leafRefStrippedXPath = new PathExpressionImpl(
+            GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), leafRefXPath.isAbsolute());
         final Module parentModule = getParentModule(parentNode);
+        final SchemaNode leafRefValueNode;
         if (!leafRefStrippedXPath.isAbsolute()) {
             leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
                     parentNode, leafRefStrippedXPath);
         } else {
             leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
         }
-        return leafRefValueNode != null ? leafRefValueNode.equals(parentNode) : false;
+        return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
     }
 
     /**
-     * Returns JAVA <code>Type</code> for instances of the type
-     * <code>LeafrefTypeDefinition</code> or
+     * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
      * <code>IdentityrefTypeDefinition</code>.
      *
-     * @param typeDefinition
-     *            type definition which is converted to JAVA <code>Type</code>
+     * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
      */
-    private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
+    private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
+            final boolean inGrouping) {
         if (typeDefinition instanceof LeafrefTypeDefinition) {
             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
             Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
                 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
-            return provideTypeForLeafref(leafref, parentNode);
+            return provideTypeForLeafref(leafref, parentNode, inGrouping);
         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
             return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
         }
@@ -325,17 +304,15 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Returns JAVA <code>Type</code> for instances of the type
-     * <code>ExtendedType</code>.
+     * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
      *
-     * @param typeDefinition
-     *            type definition which is converted to JAVA <code>Type</code>
+     * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
      */
-    private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
+    private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
         final String typedefName = typeDefinition.getQName().getLocalName();
         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
-        Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
+        Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
         if (returnType == null) {
             if (baseTypeDef instanceof EnumTypeDefinition) {
                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
@@ -352,7 +329,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                     }
                     if (returnType == null) {
                         returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
-                                baseTypeDef, typeDefinition, r);
+                                baseTypeDef, typeDefinition, r, lenient);
                     }
                 }
             }
@@ -361,19 +338,15 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Seeks for identity reference <code>idref</code> the JAVA
-     * <code>type</code>.<br />
-     * <br />
+     * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
      *
+     * <p>
      * <i>Example:<br />
      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
      *
-     * @param idref
-     *            identityref type definition for which JAVA <code>Type</code>
-     *            is sought
-     * @return JAVA <code>Type</code> of the identity which is referenced through
-     *         <code>idref</code>
+     * @param idref identityref type definition for which JAVA <code>Type</code> is sought
+     * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
      */
     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
         final Collection<IdentitySchemaNode> identities = idref.getIdentities();
@@ -392,13 +365,9 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
 
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
-        final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
-            identity.getPath());
-        final String genTypeName = BindingMapping.getClassName(identity.getQName());
-
-        final Type baseType = Types.typeForClass(Class.class);
-        final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
-        return Types.parameterizedTypeFor(baseType, paramType);
+        final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
+            basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
+        return Types.classType(Types.wildcardTypeFor(identifier));
     }
 
     /**
@@ -416,11 +385,11 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *             <li>if name of <code>typeDefinition</code></li>
      *             </ul>
      */
-    public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
+    public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
+            final SchemaNode parentNode) {
         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
         if (typeDefinition.getQName() == null) {
-            throw new IllegalArgumentException(
-                    "Type Definition cannot have non specified QName (QName cannot be NULL!)");
+            throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
         }
         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
                 "Type Definitions Local Name cannot be NULL!");
@@ -513,69 +482,93 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
+     * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
+     * to find referenced node and its <code>Type</code> is returned.
      *
-     * The path of <code>leafrefType</code> is followed to find referenced node
-     * and its <code>Type</code> is returned.
-     *
-     * @param leafrefType
-     *            leafref type definition for which is the type sought
-     * @return JAVA <code>Type</code> of data schema node which is referenced in
-     *         <code>leafrefType</code>
+     * @param leafrefType leafref type definition for which is the type sought
+     * @param parentNode parent node of the leaf being resolved
+     * @param inGrouping true if we are resolving the type within a grouping.
+     * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>leafrefType</code> equal null</li>
      *             <li>if path statement of <code>leafrefType</code> equal null</li>
      *             </ul>
-     *
      */
-    public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
-        Type returnType = null;
+    public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
+            final boolean inGrouping) {
         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
 
-        Preconditions.checkArgument(leafrefType.getPathStatement() != null,
-                "The Path Statement for Leafref Type Definition cannot be NULL!");
+        final PathExpression xpath = leafrefType.getPathStatement();
+        Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
 
-        final RevisionAwareXPath xpath = leafrefType.getPathStatement();
-        final String strXPath = xpath.toString();
+        final String strXPath = xpath.getOriginalString();
+        if (strXPath.indexOf('[') != -1) {
+            // XXX: why are we special-casing this?
+            return Types.objectType();
+        }
 
-        if (strXPath != null) {
-            if (strXPath.indexOf('[') == -1) {
-                final Module module = findParentModule(schemaContext, parentNode);
-                Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
+        final Module module = findParentModule(schemaContext, parentNode);
+        Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
 
-                final SchemaNode dataNode;
-                if (xpath.isAbsolute()) {
-                    dataNode = findDataSchemaNode(schemaContext, module, xpath);
-                } else {
-                    dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
-                }
-                Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
-                        strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
-
-                if (leafContainsEnumDefinition(dataNode)) {
-                    returnType = referencedTypes.get(dataNode.getPath());
-                } else if (leafListContainsEnumDefinition(dataNode)) {
-                    returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
-                } else {
-                    returnType = resolveTypeFromDataSchemaNode(dataNode);
-                }
-            } else {
-                returnType = Types.typeForClass(Object.class);
+        final SchemaNode dataNode;
+        if (xpath.isAbsolute()) {
+            dataNode = findDataSchemaNode(schemaContext, module, xpath);
+        } else {
+            dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
+            if (dataNode == null && inGrouping) {
+                // Relative path within a grouping may end up being unresolvable because it may refer outside
+                // the grouping, in which case it is polymorphic based on instantiation, for example:
+                //
+                // grouping foo {
+                //     leaf foo {
+                //         type leafref {
+                //             path "../../bar";
+                //         }
+                //     }
+                // }
+                //
+                // container one {
+                //     leaf bar {
+                //         type string;
+                //     }
+                //     uses foo;
+                // }
+                //
+                // container two {
+                //     leaf bar {
+                //         type uint16;
+                //     }
+                //     uses foo;
+                // }
+                LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
+                    parentNode);
+                return Types.objectType();
             }
         }
+        Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
+                strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
+
+        // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
+        Type returnType = null;
+        if (leafContainsEnumDefinition(dataNode)) {
+            returnType = referencedTypes.get(dataNode.getPath());
+        } else if (leafListContainsEnumDefinition(dataNode)) {
+            returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
+        }
+        if (returnType == null) {
+            returnType = resolveTypeFromDataSchemaNode(dataNode);
+        }
         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
         return returnType;
     }
 
     /**
-     * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
-     * so then checks if it is of type <code>EnumTypeDefinition</code>.
+     * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
+     * <code>EnumTypeDefinition</code>.
      *
-     * @param dataNode
-     *            data schema node for which is checked if it is leaf and if it
-     *            is of enum type
+     * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
      * @return boolean value
      *         <ul>
      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
@@ -585,20 +578,16 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
         if (dataNode instanceof LeafSchemaNode) {
             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
-            if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
-                return true;
-            }
+            return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
         }
         return false;
     }
 
     /**
-     * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
-     * it so then checks if it is of type <code>EnumTypeDefinition</code>.
+     * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
+     * <code>EnumTypeDefinition</code>.
      *
-     * @param dataNode
-     *            data schema node for which is checked if it is leaflist and if
-     *            it is of enum type
+     * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
      * @return boolean value
      *         <ul>
      *         <li>true - if <code>dataNode</code> is leaflist of type
@@ -609,24 +598,17 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
         if (dataNode instanceof LeafListSchemaNode) {
             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
-            if (leafList.getType() instanceof EnumTypeDefinition) {
-                return true;
-            }
+            return leafList.getType() instanceof EnumTypeDefinition;
         }
         return false;
     }
 
     /**
-     * Converts <code>enumTypeDef</code> to
-     * {@link Enumeration
-     * enumeration}.
+     * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
      *
-     * @param enumTypeDef
-     *            enumeration type definition which is converted to enumeration
-     * @param enumName
-     *            string with name which is used as the enumeration name
-     * @return enumeration type which is built with data (name, enum values)
-     *         from <code>enumTypeDef</code>
+     * @param enumTypeDef enumeration type definition which is converted to enumeration
+     * @param enumName string with name which is used as the enumeration name
+     * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>enumTypeDef</code> equals null</li>
@@ -644,12 +626,9 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
 
-        final String enumerationName = BindingMapping.getClassName(enumName);
-
         final Module module = findParentModule(schemaContext, parentNode);
-        final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
-
-        final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(basePackageName, enumerationName);
+        final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
+            BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
         addEnumDescription(enumBuilder, enumTypeDef);
         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
         enumBuilder.setModuleName(module.getName());
@@ -659,18 +638,12 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
-     * taken from <code>enumTypeDef</code>.
+     * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
      *
-     * @param enumTypeDef
-     *            enumeration type definition is source of enumeration data for
-     *            <code>typeBuilder</code>
-     * @param enumName
-     *            string with the name of enumeration
-     * @param typeBuilder
-     *            generated type builder to which is enumeration added
-     * @return enumeration type which contains enumeration data form
-     *         <code>enumTypeDef</code>
+     * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
+     * @param enumName string with the name of enumeration
+     * @param typeBuilder generated type builder to which is enumeration added
+     * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>enumTypeDef</code> equals null</li>
@@ -691,9 +664,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
 
-        final String enumerationName = BindingMapping.getClassName(enumName);
-
-        final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
+        final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
 
         addEnumDescription(enumBuilder, enumTypeDef);
         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
@@ -702,32 +673,44 @@ public abstract class AbstractTypeProvider implements TypeProvider {
 
     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
 
-    public abstract AbstractEnumerationBuilder newEnumerationBuilder(String packageName, String name);
+    public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
+
+    public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
 
-    public abstract GeneratedTOBuilder newGeneratedTOBuilder(String packageName, String name);
+    public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
 
-    public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(String packageName, String name);
+    /**
+     * Converts the pattern constraints to the list of the strings which represents these constraints.
+     *
+     * @param patternConstraints list of pattern constraints
+     * @return list of strings which represents the constraint patterns
+     */
+    public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
 
     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
 
     /**
-     * Converts the pattern constraints from <code>typedef</code> to the list of
-     * the strings which represents these constraints.
+     * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
+     * constraints.
      *
-     * @param typedef
-     *            extended type in which are the pattern constraints sought
+     * @param typedef extended type in which are the pattern constraints sought
      * @return list of strings which represents the constraint patterns
-     * @throws IllegalArgumentException
-     *             if <code>typedef</code> equals null
+     * @throws IllegalArgumentException if <code>typedef</code> equals null
      *
      */
-    abstract Map<String, String> resolveRegExpressionsFromTypedef(TypeDefinition<?> typedef);
+    private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
+        if (!(typedef instanceof StringTypeDefinition)) {
+            return ImmutableMap.of();
+        }
+
+        // TODO: run diff against base ?
+        return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
+    }
 
     /**
      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
      *
-     * @param dataNode
-     *            contains information about YANG type
+     * @param dataNode contains information about YANG type
      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
      */
     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
@@ -735,7 +718,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         if (dataNode != null) {
             if (dataNode instanceof LeafSchemaNode) {
                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
-                final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
+                final TypeDefinition<?> type = CompatUtils.compatType(leaf);
                 returnType = javaTypeForSchemaDefinitionType(type, leaf);
             } else if (dataNode instanceof LeafListSchemaNode) {
                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
@@ -746,18 +729,15 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Passes through all modules and through all its type definitions and
-     * convert it to generated types.
+     * Passes through all modules and through all its type definitions and convert it to generated types.
      *
-     * The modules are firstly sorted by mutual dependencies. The modules are
-     * sequentially passed. All type definitions of a module are at the
-     * beginning sorted so that type definition with less amount of references
-     * to other type definition are processed first.<br />
+     * <p>
+     * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
+     * of a module are at the beginning sorted so that type definition with less amount of references to other type
+     * definition are processed first.<br>
      * For each module is created mapping record in the map
      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
-     * which map current module name to the map which maps type names to
-     * returned types (generated types).
-     *
+     * which map current module name to the map which maps type names to returned types (generated types).
      */
     private void resolveTypeDefsFromContext() {
         final Set<Module> modules = schemaContext.getModules();
@@ -765,11 +745,9 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
 
         for (Module module : modulesSortedByDependency) {
-            Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
-            if (dateTypeMap == null) {
-                dateTypeMap = new HashMap<>();
-            }
-            dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
+            Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
+                module.getName(), key -> new HashMap<>());
+            dateTypeMap.put(module.getRevision(), Collections.emptyMap());
             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
         }
 
@@ -787,15 +765,12 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
+     * Create Type for specified type definition.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param module
-     *            string with the name of the module for to which the
-     *            <code>typedef</code> belongs
-     * @param typedef
-     *            type definition of the node for which should be creted JAVA
-     *            <code>Type</code> (usually generated TO)
+     * @param basePackageName string with name of package to which the module belongs
+     * @param module string with the name of the module for to which the <code>typedef</code> belongs
+     * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
+     *                (usually generated TO)
      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
      *         <code>null</code> value if <code>basePackageName</code> or
      *         <code>modulName</code> or <code>typedef</code> or Q name of
@@ -803,73 +778,70 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      */
     private Type typedefToGeneratedType(final String basePackageName, final Module module,
             final TypeDefinition<?> typedef) {
-        final String moduleName = module.getName();
-        final Optional<Revision> moduleRevision = module.getRevision();
-        if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
-            final String typedefName = typedef.getQName().getLocalName();
-            final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
-            // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
-            if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
-                    && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
-                Type returnType = null;
-                if (innerTypeDefinition.getBaseType() != null) {
-                    returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
-                        module.getName());
-                } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
-                    final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
-                            (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
-                    genTOBuilder.setTypedef(true);
-                    genTOBuilder.setIsUnion(true);
-                    addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
-                    makeSerializable(genTOBuilder);
-                    returnType = genTOBuilder.build();
-                    // union builder
-                    final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(genTOBuilder.getPackageName(),
-                            genTOBuilder.getName() + "Builder");
-                    unionBuilder.setIsUnionBuilder(true);
-                    final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
-                    method.setReturnType(returnType);
-                    method.addParameter(Types.STRING, "defaultValue");
-                    method.setAccessModifier(AccessModifier.PUBLIC);
-                    method.setStatic(true);
-                    Set<Type> types = additionalTypes.get(module);
-                    if (types == null) {
-                        types = Sets.<Type> newHashSet(unionBuilder.build());
-                        additionalTypes.put(module, types);
-                    } else {
-                        types.add(unionBuilder.build());
-                    }
-                } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
-                    // enums are automatically Serializable
-                    final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
-                    // TODO units for typedef enum
-                    returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
-                } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
-                    final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
-                    final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
-                            basePackageName, bitsTypeDefinition, typedefName, module.getName());
-                    genTOBuilder.setTypedef(true);
-                    addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
-                    makeSerializable(genTOBuilder);
-                    returnType = genTOBuilder.build();
-                } else {
-                    final Type javaType = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
-                    returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
-                }
-                if (returnType != null) {
-                    final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
-                            genTypeDefsContextMap.get(moduleName);
-                    Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
-                    if (typeMap != null) {
-                        if (typeMap.isEmpty()) {
-                            typeMap = new HashMap<>(4);
-                            modulesByDate.put(moduleRevision, typeMap);
-                        }
-                        typeMap.put(typedefName, returnType);
-                    }
-                    return returnType;
+        final TypeDefinition<?> baseTypedef = typedef.getBaseType();
+
+        // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
+        if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
+            return null;
+        }
+
+        final String typedefName = typedef.getQName().getLocalName();
+
+        final Type returnType;
+        if (baseTypedef.getBaseType() != null) {
+            returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
+                module.getName());
+        } else if (baseTypedef instanceof UnionTypeDefinition) {
+            final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
+                JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
+                (UnionTypeDefinition) baseTypedef, typedef);
+            genTOBuilder.setTypedef(true);
+            genTOBuilder.setIsUnion(true);
+            addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
+            makeSerializable(genTOBuilder);
+            returnType = genTOBuilder.build();
+
+            // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
+            // so we are placing the builder alongside the union.
+            final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
+                JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
+            unionBuilder.setIsUnionBuilder(true);
+            final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
+            method.setReturnType(returnType);
+            method.addParameter(Types.STRING, "defaultValue");
+            method.setAccessModifier(AccessModifier.PUBLIC);
+            method.setStatic(true);
+            additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
+        } else if (baseTypedef instanceof EnumTypeDefinition) {
+            // enums are automatically Serializable
+            final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
+            // TODO units for typedef enum
+            returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
+        } else if (baseTypedef instanceof BitsTypeDefinition) {
+            final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
+                JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
+                (BitsTypeDefinition) baseTypedef, module.getName());
+            genTOBuilder.setTypedef(true);
+            addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
+            makeSerializable(genTOBuilder);
+            returnType = genTOBuilder.build();
+        } else {
+            final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
+            returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
+        }
+        if (returnType != null) {
+            final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
+                    genTypeDefsContextMap.get(module.getName());
+            final Optional<Revision> moduleRevision = module.getRevision();
+            Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
+            if (typeMap != null) {
+                if (typeMap.isEmpty()) {
+                    typeMap = new HashMap<>(4);
+                    modulesByDate.put(moduleRevision, typeMap);
                 }
+                typeMap.put(typedefName, returnType);
             }
+            return returnType;
         }
         return null;
     }
@@ -877,28 +849,25 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     /**
      * Wraps base YANG type to generated TO.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition which is converted to the TO
-     * @param javaType
-     *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
+     * @param basePackageName string with name of package to which the module belongs
+     * @param typedef type definition which is converted to the TO
+     * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
      * @return generated transfer object which represent<code>javaType</code>
      */
     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
             final Type javaType, final String moduleName) {
-        Preconditions.checkNotNull(javaType, "javaType cannot be null");
-        final String propertyName = "value";
+        requireNonNull(javaType, "javaType cannot be null");
 
         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
-        final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
+        final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
         genPropBuilder.setReturnType(javaType);
         genTOBuilder.addEqualsIdentity(genPropBuilder);
         genTOBuilder.addHashIdentity(genPropBuilder);
         genTOBuilder.addToStringProperty(genPropBuilder);
+        genTOBuilder.addImplementsType(TYPE_OBJECT);
         if (typedef.getStatus() == Status.DEPRECATED) {
-            genTOBuilder.addAnnotation("", "Deprecated");
+            genTOBuilder.addAnnotation("java.lang", "Deprecated");
         }
         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
@@ -913,41 +882,27 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      * Converts output list of generated TO builders to one TO builder (first
      * from list) which contains the remaining builders as its enclosing TO.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition which should be of type
-     *            <code>UnionTypeDefinition</code>
-     * @param typeDefName
-     *            string with name for generated TO
-     * @return generated TO builder with the list of enclosed generated TO
-     *         builders
+     * @param typeName new type identifier
+     * @param typedef type definition which should be of type {@link UnionTypeDefinition}
+     * @return generated TO builder with the list of enclosed generated TO builders
      */
-    public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
-            final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
-        final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
-                typedef, typeDefName, parentNode);
+    public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
+            final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
+        final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
+            parentNode);
         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
 
         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
         builders.forEach(resultTOBuilder::addEnclosingTransferObject);
-
-        resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
         return resultTOBuilder;
     }
 
     /**
-     * Converts <code>typedef</code> to generated TO with
-     * <code>typeDefName</code>. Every union type from <code>typedef</code> is
-     * added to generated TO builder as property.
+     * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
+     * <code>typedef</code> is added to generated TO builder as property.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition which should be of type
-     *            <code>UnionTypeDefinition</code>
-     * @param typeDefName
-     *            string with name for generated TO
+     * @param typeName new type identifier
+     * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
      * @return generated TO builder which represents <code>typedef</code>
      * @throws NullPointerException
      *             <ul>
@@ -956,29 +911,22 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *             <li>if Qname of <code>typedef</code> is null</li>
      *             </ul>
      */
-    public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
-            final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
-        Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
-        Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
-        Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
+    public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
+            final UnionTypeDefinition typedef, final SchemaNode parentNode) {
+        requireNonNull(typedef, "Type Definition cannot be NULL!");
+        requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
 
         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
         final Module module = findParentModule(schemaContext, parentNode);
 
-        final GeneratedTOBuilder unionGenTOBuilder;
-        if (typeDefName != null && !typeDefName.isEmpty()) {
-            final String typeName = BindingMapping.getClassName(typeDefName);
-            unionGenTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
-            unionGenTOBuilder.setSchemaPath(typedef.getPath());
-            unionGenTOBuilder.setModuleName(module.getName());
-            addCodegenInformation(unionGenTOBuilder, typedef);
-        } else {
-            unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
-        }
-
-        generatedTOBuilders.add(unionGenTOBuilder);
+        final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
         unionGenTOBuilder.setIsUnion(true);
+        unionGenTOBuilder.setSchemaPath(typedef.getPath());
+        unionGenTOBuilder.setModuleName(module.getName());
+        unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
+        addCodegenInformation(unionGenTOBuilder, typedef);
+        generatedTOBuilders.add(unionGenTOBuilder);
 
         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
         // also negation information and hence guarantees uniqueness.
@@ -992,7 +940,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
             } else if (unionType instanceof UnionTypeDefinition) {
                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
-                    (UnionTypeDefinition) unionType, basePackageName, parentNode));
+                    (UnionTypeDefinition) unionType, parentNode));
             } else if (unionType instanceof EnumTypeDefinition) {
                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
                         unionTypeName, unionGenTOBuilder);
@@ -1010,37 +958,31 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Wraps code which handle case when union subtype is also of the type
-     * <code>UnionType</code>.
+     * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
      *
-     * In this case the new generated TO is created for union subtype (recursive
-     * call of method
-     * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
-     * String, SchemaNode)}
-     * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
-     * <code>parentUnionGenTOBuilder</code> is created property which type is
-     * equal to new generated TO.
+     * <p>
+     * In this case the new generated TO is created for union subtype (recursive call of method
+     * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
+     * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
+     * created property which type is equal to new generated TO.
      *
-     * @param parentUnionGenTOBuilder
-     *            generated TO builder to which is the property with the child
-     *            union subtype added
-     * @param basePackageName
-     *            string with the name of the module package
-     * @param unionSubtype
-     *            type definition which represents union subtype
-     * @return list of generated TO builders. The number of the builders can be
-     *         bigger one due to recursive call of
+     * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
+     * @param basePackageName string with the name of the module package
+     * @param unionSubtype type definition which represents union subtype
+     * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
      */
     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
-            final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
-        final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
+            final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
+        final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
+            provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
-                basePackageName, unionSubtype, newTOBuilderName, parentNode);
+            newTOBuilderName, unionSubtype, parentNode);
 
         final GeneratedPropertyBuilder propertyBuilder;
-        propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
-        propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
+        propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
+            newTOBuilderName.simpleName()));
+        propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
 
@@ -1048,23 +990,14 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Wraps code which handle case when union subtype is of the type
-     * <code>ExtendedType</code>.
-     *
-     * If TO for this type already exists it is used for the creation of the
-     * property in <code>parentUnionGenTOBuilder</code>. In other case the base
-     * type is used for the property creation.
-     *
-     * @param parentUnionGenTOBuilder
-     *            generated TO builder in which new property is created
-     * @param unionSubtype
-     *            type definition of the <code>ExtendedType</code> type which
-     *            represents union subtype
-     * @param expressions
-     *            list of strings with the regular expressions
-     * @param parentNode
-     *            parent Schema Node for Extended Subtype
+     * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
+     * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
+     * the base type is used for the property creation.
      *
+     * @param parentUnionGenTOBuilder generated TO builder in which new property is created
+     * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
+     * @param expressions list of strings with the regular expressions
+     * @param parentNode parent Schema Node for Extended Subtype
      */
     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
@@ -1078,7 +1011,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
             final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
-                parentNode);
+                parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
             if (javaType != null) {
                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
             }
@@ -1103,18 +1036,17 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Searches for generated TO for <code>searchedTypeDef</code> type
-     * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
+     * Searches for generated TO for <code>searchedTypeDef</code> type  definition
+     * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
      *
-     * @param searchedTypeName
-     *            string with name of <code>searchedTypeDef</code>
-     * @return generated TO for <code>searchedTypeDef</code> or
-     *         <code>null</code> it it doesn't exist
+     * @param searchedTypeName string with name of <code>searchedTypeDef</code>
+     * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
      */
     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
         final Module typeModule = findParentModule(schemaContext, parentNode);
         if (typeModule != null && typeModule.getName() != null) {
-            final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
+            final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
+                typeModule.getName());
             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
             if (genTOs != null) {
                 return genTOs.get(searchedTypeName);
@@ -1124,21 +1056,19 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Stores generated TO created from <code>genTOBuilder</code> for
-     * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
-     * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
+     * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
+     * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
      *
-     * @param newTypeDef
-     *            type definition for which is <code>genTOBuilder</code> created
-     * @param genTOBuilder
-     *            generated TO builder which is converted to generated TO and
-     *            stored
+     * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
+     * @param genTOBuilder generated TO builder which is converted to generated TO and stored
      */
-    private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
+    private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
+            final SchemaNode parentNode) {
         if (!(newTypeDef instanceof UnionTypeDefinition)) {
             final Module parentModule = findParentModule(schemaContext, parentNode);
             if (parentModule != null && parentModule.getName() != null) {
-                final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
+                final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
+                    parentModule.getName());
                 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
             }
@@ -1146,19 +1076,15 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Adds a new property with the name <code>propertyName</code> and with type
-     * <code>type</code> to <code>unonGenTransObject</code>.
+     * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
+     * to <code>unonGenTransObject</code>.
      *
-     * @param unionGenTransObject
-     *            generated TO to which should be property added
-     * @param type
-     *            JAVA <code>type</code> of the property which should be added
-     *            to <code>unionGentransObject</code>
-     * @param propertyName
-     *            string with name of property which should be added to
-     *            <code>unionGentransObject</code>
+     * @param unionGenTransObject generated TO to which should be property added
+     * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
+     * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
      */
-    private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
+    private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
+            final String propertyName) {
         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
                     .addProperty(BindingMapping.getPropertyName(propertyName));
@@ -1173,43 +1099,33 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     /**
      * Converts <code>typedef</code> to the generated TO builder.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition from which is the generated TO builder created
-     * @return generated TO builder which contains data from
-     *         <code>typedef</code> and <code>basePackageName</code>
+     * @param basePackageName string with name of package to which the module belongs
+     * @param typedef type definition from which is the generated TO builder created
+     * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
      */
     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
             final TypeDefinition<?> typedef, final String moduleName) {
-
-        final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
-        final String typeDefTOName = typedef.getQName().getLocalName();
-
-        if (packageName != null && typeDefTOName != null) {
-            final String genTOName = BindingMapping.getClassName(typeDefTOName);
-            final GeneratedTOBuilder newType = newGeneratedTOBuilder(packageName, genTOName);
-            newType.setSchemaPath(typedef.getPath());
-            newType.setModuleName(moduleName);
-            addCodegenInformation(newType, typedef);
-            return newType;
+        JavaTypeName name = renames.get(typedef);
+        if (name == null) {
+            name = JavaTypeName.create(
+                BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
+                BindingMapping.getClassName(typedef.getQName().getLocalName()));
         }
-        return null;
+
+        final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
+        newType.setSchemaPath(typedef.getPath());
+        newType.setModuleName(moduleName);
+        addCodegenInformation(newType, typedef);
+        return newType;
     }
 
     /**
-     * Converts <code>typeDef</code> which should be of the type
-     * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
-     *
-     * All the bits of the typeDef are added to returning generated TO as
+     * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
+     * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
      * properties.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typeDef
-     *            type definition from which is the generated TO builder created
-     * @param typeDefName
-     *            string with the name for generated TO builder
+     * @param typeName new type identifier
+     * @param typeDef type definition from which is the generated TO builder created
      * @return generated TO builder which represents <code>typeDef</code>
      * @throws IllegalArgumentException
      *             <ul>
@@ -1217,50 +1133,37 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *             <li>if <code>basePackageName</code> equals null</li>
      *             </ul>
      */
-    public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
-            final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
-
-        Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
-        Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
-
-        if (typeDef instanceof BitsTypeDefinition) {
-            final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
-
-            final String typeName = BindingMapping.getClassName(typeDefName);
-            final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
-            genTOBuilder.setSchemaPath(typeDef.getPath());
-            genTOBuilder.setModuleName(moduleName);
-            genTOBuilder.setBaseType(typeDef);
-            addCodegenInformation(genTOBuilder, typeDef);
-
-            final List<Bit> bitList = bitsTypeDefinition.getBits();
-            GeneratedPropertyBuilder genPropertyBuilder;
-            for (Bit bit : bitList) {
-                final String name = bit.getName();
-                genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
-                genPropertyBuilder.setReadOnly(true);
-                genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
-
-                genTOBuilder.addEqualsIdentity(genPropertyBuilder);
-                genTOBuilder.addHashIdentity(genPropertyBuilder);
-                genTOBuilder.addToStringProperty(genPropertyBuilder);
-            }
-
-            return genTOBuilder;
+    public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
+            final BitsTypeDefinition typeDef, final String moduleName) {
+        final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
+        genTOBuilder.setSchemaPath(typeDef.getPath());
+        genTOBuilder.setModuleName(moduleName);
+        genTOBuilder.setBaseType(typeDef);
+        genTOBuilder.addImplementsType(TYPE_OBJECT);
+        addCodegenInformation(genTOBuilder, typeDef);
+
+        final List<Bit> bitList = typeDef.getBits();
+        GeneratedPropertyBuilder genPropertyBuilder;
+        for (Bit bit : bitList) {
+            final String name = bit.getName();
+            genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
+            genPropertyBuilder.setReadOnly(true);
+            genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+
+            genTOBuilder.addEqualsIdentity(genPropertyBuilder);
+            genTOBuilder.addHashIdentity(genPropertyBuilder);
+            genTOBuilder.addToStringProperty(genPropertyBuilder);
         }
-        return null;
+
+        return genTOBuilder;
     }
 
     /**
+     * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
+     * the <code>regularExpressions</code>.
      *
-     * Adds to the <code>genTOBuilder</code> the constant which contains regular
-     * expressions from the <code>regularExpressions</code>
-     *
-     * @param genTOBuilder
-     *            generated TO builder to which are
-     *            <code>regular expressions</code> added
-     * @param expressions
-     *            list of string which represent regular expressions
+     * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
+     * @param expressions list of string which represent regular expressions
      */
     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
             final Map<String, String> expressions) {
@@ -1271,25 +1174,19 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Creates generated TO with data about inner extended type
-     * <code>innerExtendedType</code>, about the package name
-     * <code>typedefName</code> and about the generated TO name
-     * <code>typedefName</code>.
+     * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
+     * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
      *
-     * It is supposed that <code>innerExtendedType</code> is already present in
-     * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
-     * be possible set it as extended type for the returning generated TO.
+     * <p>
+     * It is assumed that <code>innerExtendedType</code> is already present in
+     * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
+     * for the returning generated TO.
      *
-     * @param typedef
-     *            Type Definition
-     * @param innerExtendedType
-     *            extended type which is part of some other extended type
-     * @param basePackageName
-     *            string with the package name of the module
-     * @param moduleName
-     *            Module Name
-     * @return generated TO which extends generated TO for
-     *         <code>innerExtendedType</code>
+     * @param typedef Type Definition
+     * @param innerExtendedType extended type which is part of some other extended type
+     * @param basePackageName string with the package name of the module
+     * @param moduleName Module Name
+     * @return generated TO which extends generated TO for <code>innerExtendedType</code>
      * @throws IllegalArgumentException
      *             <ul>
      *             <li>if <code>extendedType</code> equals null</li>
@@ -1302,10 +1199,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
 
-        final String typedefName = typedef.getQName().getLocalName();
-        final String classTypedefName = BindingMapping.getClassName(typedefName);
-        final String innerTypeDef = innerExtendedType.getQName().getLocalName();
-        final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, classTypedefName);
+        final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
+            BindingMapping.getClassName(typedef.getQName())));
         genTOBuilder.setSchemaPath(typedef.getPath());
         genTOBuilder.setModuleName(moduleName);
         genTOBuilder.setTypedef(true);
@@ -1313,8 +1208,10 @@ public abstract class AbstractTypeProvider implements TypeProvider {
 
         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
         genTOBuilder.setRestrictions(r);
+        addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
+
         if (typedef.getStatus() == Status.DEPRECATED) {
-            genTOBuilder.addAnnotation("", "Deprecated");
+            genTOBuilder.addAnnotation("java.lang", "Deprecated");
         }
 
         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
@@ -1330,6 +1227,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         }
 
         if (typeMap != null) {
+            final String innerTypeDef = innerExtendedType.getQName().getLocalName();
             final Type type = typeMap.get(innerTypeDef);
             if (type instanceof GeneratedTransferObject) {
                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
@@ -1342,32 +1240,27 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Add {@link Serializable} to implemented interfaces of this TO. Also
-     * compute and add serialVersionUID property.
+     * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
+     * property.
      *
-     * @param gto
-     *            transfer object which needs to be serializable
+     * @param gto transfer object which needs to be made serializable
      */
     private static void makeSerializable(final GeneratedTOBuilder gto) {
-        gto.addImplementsType(Types.typeForClass(Serializable.class));
+        gto.addImplementsType(Types.serializableType());
         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
         gto.setSUID(prop);
     }
 
     /**
-     * Finds out for each type definition how many immersion (depth) is
-     * necessary to get to the base type. Every type definition is inserted to
-     * the map which key is depth and value is list of type definitions with
-     * equal depth. In next step are lists from this map concatenated to one
-     * list in ascending order according to their depth. All type definitions
-     * are in the list behind all type definitions on which depends.
+     * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
+     * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
+     * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
+     * type definitions are in the list behind all type definitions on which depends.
      *
-     * @param unsortedTypeDefinitions
-     *            list of type definitions which should be sorted by depth
-     * @return list of type definitions sorted according their each other
-     *         dependencies (type definitions which are depend on other type
-     *         definitions are in list behind them).
+     * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
+     * @return list of type definitions sorted according their each other dependencies (type definitions which are
+     *              dependent on other type definitions are in list behind them).
      */
     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
@@ -1376,11 +1269,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
-            List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
-            if (typeDefinitionsConcreteDepth == null) {
-                typeDefinitionsConcreteDepth = new ArrayList<>();
-                typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
-            }
+            List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
+                typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
         }
 
@@ -1393,13 +1283,10 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Returns how many immersion is necessary to get from the type definition
-     * to the base type.
+     * Returns how many immersion is necessary to get from the type definition to the base type.
      *
-     * @param typeDefinition
-     *            type definition for which is depth sought.
-     * @return number of immersions which are necessary to get from the type
-     *         definition to the base type
+     * @param typeDefinition type definition for which is depth sought.
+     * @return number of immersions which are necessary to get from the type definition to the base type
      */
     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
         // FIXME: rewrite this in a non-recursive manner
@@ -1430,22 +1317,22 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     /**
-     * Returns string which contains the same value as <code>name</code> but
-     * integer suffix is incremented by one. If <code>name</code> contains no
-     * number suffix then number 1 is added.
+     * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
+     * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
+     * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
      *
-     * @param name
-     *            string with name of augmented node
+     * @param name string with name of augmented node
      * @return string with the number suffix incremented by one (or 1 is added)
      */
     private static String provideAvailableNameForGenTOBuilder(final String name) {
-        final Matcher mtch = NUMBERS_PATTERN.matcher(name);
-        if (mtch.find()) {
-            final int newSuffix = Integer.parseInt(name.substring(mtch.start())) + 1;
-            return name.substring(0, mtch.start()) + newSuffix;
+        final int dollar = name.indexOf('$');
+        if (dollar == -1) {
+            return name + "$1";
         }
 
-        return name + 1;
+        final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
+        Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
+        return name.substring(0, dollar + 1) + newSuffix;
     }
 
     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
@@ -1463,12 +1350,12 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
-        final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
+        final TypeDefinition<?> type = CompatUtils.compatType(node);
         final QName typeQName = type.getQName();
         final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
-        Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
-        Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
-                node);
+        requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
+        requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
+            + node);
 
         final StringBuilder sb = new StringBuilder();
         String result = null;
@@ -1486,7 +1373,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
-                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
+                    type.getPath());
                 parentName = BindingMapping.getClassName(parent.getName());
                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             }
@@ -1506,12 +1394,14 @@ public abstract class AbstractTypeProvider implements TypeProvider {
             if (type.getBaseType() != null) {
                 final Module m = getParentModule(type);
                 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
-                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
+                    type.getPath());
                 className = packageName + "." + BindingMapping.getClassName(typeQName);
             } else {
                 final Module parentModule = getParentModule(node);
                 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
-                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
+                    node.getPath());
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
             result = className + "." + newDefVal;
@@ -1532,25 +1422,13 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         } else if (base instanceof StringTypeDefinition) {
             result = "\"" + defaultValue + "\"";
         } else if (BaseTypes.isUint8(base)) {
-            result = typeToValueOfDef(Short.class, defaultValue);
+            result = typeToValueOfDef(Uint8.class, defaultValue);
         } else if (BaseTypes.isUint16(base)) {
-            result = typeToValueOfDef(Integer.class, defaultValue);
+            result = typeToValueOfDef(Uint16.class, defaultValue);
         } else if (BaseTypes.isUint32(base)) {
-            result = typeToValueOfDef(Long.class, defaultValue);
+            result = typeToValueOfDef(Uint32.class, defaultValue);
         } else if (BaseTypes.isUint64(base)) {
-            switch (defaultValue) {
-                case "0":
-                    result = "java.math.BigInteger.ZERO";
-                    break;
-                case "1":
-                    result = "java.math.BigInteger.ONE";
-                    break;
-                case "10":
-                    result = "java.math.BigInteger.TEN";
-                    break;
-                default:
-                    result = typeToDef(BigInteger.class, defaultValue);
-            }
+            result = typeToValueOfDef(Uint64.class, defaultValue);
         } else if (base instanceof UnionTypeDefinition) {
             result = unionToDef(node);
         } else {
@@ -1562,7 +1440,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
             final Module m = getParentModule(type);
             final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
-            final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+            final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
+                type.getPath());
             final String className = packageName + "." + BindingMapping.getClassName(typeQName);
             sb.insert(0, "new " + className + "(");
             sb.insert(sb.length(), ')');
@@ -1592,8 +1471,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
 
     private static String binaryToDef(final String defaultValue) {
         final StringBuilder sb = new StringBuilder();
-        final BaseEncoding en = BaseEncoding.base64();
-        final byte[] encoded = en.decode(defaultValue);
+        final byte[] encoded = Base64.getDecoder().decode(defaultValue);
         sb.append("new byte[] {");
         for (int i = 0; i < encoded.length; i++) {
             sb.append(encoded[i]);
@@ -1605,11 +1483,12 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         return sb.toString();
     }
 
-    private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
+    private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
 
-    private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
+    private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
+            final boolean isExt) {
         final List<Bit> bits = new ArrayList<>(type.getBits());
-        Collections.sort(bits, BIT_NAME_COMPARATOR);
+        bits.sort(BIT_NAME_COMPARATOR);
         final StringBuilder sb = new StringBuilder();
         if (!isExt) {
             sb.append("new ");
@@ -1637,13 +1516,14 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         return schemaContext.findModule(qname.getModule()).orElse(null);
     }
 
-    private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
+    private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
+            final String defaultValue) {
         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
                 "The Path Statement for Leafref Type Definition cannot be NULL!");
 
-        final RevisionAwareXPath xpath = leafrefType.getPathStatement();
-        final String strXPath = xpath.toString();
+        final PathExpression xpath = leafrefType.getPathStatement();
+        final String strXPath = xpath.getOriginalString();
 
         if (strXPath != null) {
             if (strXPath.indexOf('[') == -1) {
@@ -1667,7 +1547,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     private String unionToDef(final LeafSchemaNode node) {
-        final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
+        final TypeDefinition<?> type = CompatUtils.compatType(node);
         String parentName;
         String className;
 
@@ -1684,7 +1564,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 }
                 if (module == null) {
                     final List<Module> modulesList = new ArrayList<>(modules);
-                    Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
+                    modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
                     module = modulesList.get(0);
                 }
             } else {
@@ -1702,7 +1582,8 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
-                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
+                    UNION_PATH);
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
         }