Rework inlined union generation
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / yang / types / AbstractTypeProvider.java
index 6cb6ff926e493cd5c10fd7895f4bf46817f33228..1e990f5206d360383f2ad5f8ca1588a9e2774381 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.mdsal.binding.yang.types;
 
+import static java.util.Objects.requireNonNull;
 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;
@@ -31,7 +32,6 @@ 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 +39,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,7 +53,7 @@ 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.model.api.DataNodeContainer;
@@ -77,6 +78,7 @@ 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;
@@ -91,7 +93,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.
@@ -113,19 +114,22 @@ 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
+     * @param renames
      * @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();
     }
 
@@ -241,7 +245,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     }
 
     private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
-        final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getPackageName(), gto.getName());
+        final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
         final GeneratedTransferObject parent = gto.getSuperType();
         if (parent != null) {
             gtob.setExtendsType(parent);
@@ -392,13 +396,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));
     }
 
     /**
@@ -561,7 +561,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
                     returnType = resolveTypeFromDataSchemaNode(dataNode);
                 }
             } else {
-                returnType = Types.typeForClass(Object.class);
+                returnType = Types.objectType();
             }
         }
         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
@@ -644,12 +644,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());
@@ -691,9 +688,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,11 +697,19 @@ 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(String packageName, String name);
+    public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
 
-    public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(String packageName, String name);
+    public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
+
+    /**
+     * 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);
 
@@ -721,7 +724,14 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *             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>.
@@ -765,10 +775,8 @@ 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<>();
-            }
+            Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
+                module.getName(), key -> new HashMap<>());
             dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
         }
@@ -794,8 +802,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *            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)
+     *            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 +810,76 @@ 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);
+            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 (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;
     }
@@ -888,17 +898,16 @@ public abstract class AbstractTypeProvider implements TypeProvider {
     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";
 
         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);
         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,26 +922,18 @@ 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;
     }
 
@@ -941,13 +942,10 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      * <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 typeName new type identifier
      * @param typedef
      *            type definition which should be of type
      *            <code>UnionTypeDefinition</code>
-     * @param typeDefName
-     *            string with name for generated TO
      * @return generated TO builder which represents <code>typedef</code>
      * @throws NullPointerException
      *             <ul>
@@ -956,9 +954,8 @@ 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!");
+    public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
+            final UnionTypeDefinition typedef, final SchemaNode parentNode) {
         Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
         Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
 
@@ -966,19 +963,12 @@ public abstract class AbstractTypeProvider implements TypeProvider {
         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());
+        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 +982,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,16 +1000,12 @@ 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.
+     * 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
@@ -1033,14 +1019,16 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *         <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);
 
@@ -1078,7 +1066,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);
             }
@@ -1182,19 +1170,18 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      */
     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;
     }
 
     /**
@@ -1204,12 +1191,9 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      * 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 typeName new type identifier
      * @param typeDef
      *            type definition from which is the generated TO builder created
-     * @param typeDefName
-     *            string with the name for generated TO builder
      * @return generated TO builder which represents <code>typeDef</code>
      * @throws IllegalArgumentException
      *             <ul>
@@ -1217,38 +1201,28 @@ 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);
+        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;
     }
 
     /**
@@ -1302,10 +1276,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 +1285,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 +1304,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);
@@ -1349,7 +1324,7 @@ public abstract class AbstractTypeProvider implements TypeProvider {
      *            transfer object which needs to be 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);
@@ -1376,11 +1351,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);
         }
 
@@ -1430,22 +1402,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) {
@@ -1605,11 +1577,11 @@ 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) {
         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 ");
@@ -1684,7 +1656,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 {