Refactor mdsal-binding-generator artifacts
[mdsal.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / yang / types / AbstractTypeProvider.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.yang.types;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.binding.model.ri.BindingTypes.TYPE_OBJECT;
12
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.Iterables;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.TreeMap;
29 import org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil;
30 import org.opendaylight.mdsal.binding.generator.impl.reactor.SerialVersionHelper;
31 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
32 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
33 import org.opendaylight.mdsal.binding.model.api.Enumeration;
34 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
35 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
36 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
37 import org.opendaylight.mdsal.binding.model.api.Restrictions;
38 import org.opendaylight.mdsal.binding.model.api.Type;
39 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
40 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
41 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
42 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
43 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
45 import org.opendaylight.mdsal.binding.model.ri.BaseYangTypes;
46 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
47 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
48 import org.opendaylight.mdsal.binding.model.ri.Types;
49 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.AbstractEnumerationBuilder;
50 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
51 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.Revision;
54 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.opendaylight.yangtools.yang.model.api.Status;
60 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
63 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
67 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
70
71 // FIXME: remove this class
72 @Deprecated(forRemoval = true)
73 abstract class AbstractTypeProvider implements TypeProvider {
74     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
75     private static final CharMatcher DASH_COLON_MATCHER = CharMatcher.anyOf("-:");
76
77     /**
78      * Contains the schema data red from YANG files.
79      */
80     private final SchemaContext schemaContext;
81
82     private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
83         new HashMap<>();
84
85     /**
86      * The map which maps schema paths to JAVA <code>Type</code>.
87      */
88     private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
89     private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
90
91     /**
92      * Creates new instance of class <code>TypeProviderImpl</code>.
93      *
94      * @param schemaContext contains the schema data red from YANG files
95      * @param renames renaming table
96      * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
97      */
98     AbstractTypeProvider(final EffectiveModelContext schemaContext) {
99         this.schemaContext = requireNonNull(schemaContext);
100
101         resolveTypeDefsFromContext();
102     }
103
104     /**
105      * Puts <code>refType</code> to map with key <code>refTypePath</code>.
106      *
107      * @param refTypePath schema path used as the map key
108      * @param refType type which represents the map value
109      * @throws IllegalArgumentException
110      *             <ul>
111      *             <li>if <code>refTypePath</code> equal null</li>
112      *             <li>if <code>refType</code> equal null</li>
113      *             </ul>
114      *
115      */
116     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
117         Preconditions.checkArgument(refTypePath != null,
118                 "Path reference of Enumeration Type Definition cannot be NULL!");
119         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
120         referencedTypes.put(refTypePath, refType);
121     }
122
123     public Map<Module, Set<GeneratedType>> getAdditionalTypes() {
124         return additionalTypes;
125     }
126
127     @Override
128     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
129             final boolean lenientRelativeLeafrefs) {
130         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
131     }
132
133     /**
134      * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
135      *
136      * @param typeDefinition type definition which is converted to JAVA type
137      * @throws IllegalArgumentException
138      *             <ul>
139      *             <li>if <code>typeDefinition</code> equal null</li>
140      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
141      *             <li>if name of <code>typeDefinition</code> equal null</li>
142      *             </ul>
143      */
144     @Override
145     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
146             final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
147         throw new UnsupportedOperationException();
148     }
149
150     /**
151      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
152      *
153      * @param typeDefinition
154      *            type definition which should be converted to JAVA
155      *            <code>Type</code>
156      * @return JAVA <code>Type</code> which represents
157      *         <code>typeDefinition</code>
158      * @throws IllegalArgumentException
159      *             <ul>
160      *             <li>if <code>typeDefinition</code> equal null</li>
161      *             <li>if Q name of <code>typeDefinition</code></li>
162      *             <li>if name of <code>typeDefinition</code></li>
163      *             </ul>
164      */
165     public GeneratedType generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
166             final SchemaNode parentNode) {
167         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
168         if (typeDefinition.getQName() == null) {
169             throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
170         }
171         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
172                 "Type Definitions Local Name cannot be NULL!");
173
174         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
175         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
176             /*
177              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
178              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
179              * this:
180              *
181              *     identity iden;
182              *
183              *     container foo {
184              *         leaf foo {
185              *             type identityref {
186              *                 base iden;
187              *             }
188              *         }
189              *     }
190              *
191              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
192              * dicey when we throw in:
193              *
194              *     typedef bar-ref {
195              *         type identityref {
196              *             base iden;
197              *         }
198              *     }
199              *
200              *     container bar {
201              *         leaf bar {
202              *             type bar-ref;
203              *         }
204              *     }
205              *
206              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
207              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
208              * is formed.
209              *
210              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
211              * an encapsulation for identityref typedefs.
212              *
213              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
214              * option, as it would look as though it is the product of a different construct:
215              *
216              *     identity bar-ref {
217              *         base iden;
218              *     }
219              *
220              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
221              * sub-identities of iden.
222              *
223              * The story behind leafrefs is probably similar, but that needs to be ascertained.
224              */
225             return null;
226         }
227
228         final Module module = findParentModule(schemaContext, parentNode);
229         if (module != null) {
230             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
231                 module.getName());
232             final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
233             if (genTOs != null) {
234                 return genTOs.get(typeDefinition.getQName().getLocalName());
235             }
236         }
237         return null;
238     }
239
240     /**
241      * Gets base type definition for <code>extendTypeDef</code>. The method is
242      * recursively called until non <code>ExtendedType</code> type is found.
243      *
244      * @param extendTypeDef
245      *            type definition for which is the base type definition sought
246      * @return type definition which is base type for <code>extendTypeDef</code>
247      * @throws IllegalArgumentException
248      *             if <code>extendTypeDef</code> equal null
249      */
250     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
251         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
252
253         TypeDefinition<?> ret = extendTypeDef;
254         while (ret.getBaseType() != null) {
255             ret = ret.getBaseType();
256         }
257
258         return ret;
259     }
260
261     /**
262      * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
263      *
264      * @param enumTypeDef enumeration type definition which is converted to enumeration
265      * @param enumName string with name which is used as the enumeration name
266      * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
267      * @throws IllegalArgumentException
268      *             <ul>
269      *             <li>if <code>enumTypeDef</code> equals null</li>
270      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
271      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
272      *             <li>if name of <code>enumTypeDef</code> equal null</li>
273      *             </ul>
274      */
275     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
276             final SchemaNode parentNode) {
277         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
278         Preconditions.checkArgument(enumTypeDef.getValues() != null,
279                 "EnumTypeDefinition MUST contain at least ONE value definition!");
280         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
281         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
282                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
283
284         final Module module = findParentModule(schemaContext, parentNode);
285         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
286             BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
287         addEnumDescription(enumBuilder, enumTypeDef);
288         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
289         enumBuilder.setModuleName(module.getName());
290         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
291         return enumBuilder.toInstance();
292     }
293
294     /**
295      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
296      *
297      * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
298      * @param enumName string with the name of enumeration
299      * @param typeBuilder generated type builder to which is enumeration added
300      * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
301      * @throws IllegalArgumentException
302      *             <ul>
303      *             <li>if <code>enumTypeDef</code> equals null</li>
304      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
305      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
306      *             <li>if name of <code>enumTypeDef</code> equal null</li>
307      *             <li>if name of <code>typeBuilder</code> equal null</li>
308      *             </ul>
309      *
310      */
311     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
312             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
313         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
314         Preconditions.checkArgument(enumTypeDef.getValues() != null,
315                 "EnumTypeDefinition MUST contain at least ONE value definition!");
316         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
317         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
318                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
319         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
320
321         final EnumBuilder enumBuilder = newEnumerationBuilder(
322             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
323         addEnumDescription(enumBuilder, enumTypeDef);
324         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
325         final Enumeration ret = enumBuilder.toInstance();
326         typeBuilder.addEnumeration(ret);
327
328         return ret;
329     }
330
331     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
332
333     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
334
335     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
336
337     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
338
339     /**
340      * Converts the pattern constraints to the list of the strings which represents these constraints.
341      *
342      * @param patternConstraints list of pattern constraints
343      * @return list of strings which represents the constraint patterns
344      */
345     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
346
347     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
348
349     /**
350      * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
351      * constraints.
352      *
353      * @param typedef extended type in which are the pattern constraints sought
354      * @return list of strings which represents the constraint patterns
355      * @throws IllegalArgumentException if <code>typedef</code> equals null
356      *
357      */
358     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
359         if (!(typedef instanceof StringTypeDefinition)) {
360             return ImmutableMap.of();
361         }
362
363         // TODO: run diff against base ?
364         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
365     }
366
367     /**
368      * Passes through all modules and through all its type definitions and convert it to generated types.
369      *
370      * <p>
371      * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
372      * of a module are at the beginning sorted so that type definition with less amount of references to other type
373      * definition are processed first.<br>
374      * For each module is created mapping record in the map
375      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
376      * which map current module name to the map which maps type names to returned types (generated types).
377      */
378     private void resolveTypeDefsFromContext() {
379         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
380
381         for (Module module : modulesSortedByDependency) {
382             Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
383                 module.getName(), key -> new HashMap<>());
384             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
385             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
386         }
387
388         for (Module module : modulesSortedByDependency) {
389             if (module != null) {
390                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
391                 if (basePackageName != null) {
392                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
393                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
394                         typedefToGeneratedType(basePackageName, module, typedef);
395                     }
396                 }
397             }
398         }
399     }
400
401     /**
402      * Create Type for specified type definition.
403      *
404      * @param basePackageName string with name of package to which the module belongs
405      * @param module string with the name of the module for to which the <code>typedef</code> belongs
406      * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
407      *                (usually generated TO)
408      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
409      *         <code>null</code> value if <code>basePackageName</code> or
410      *         <code>modulName</code> or <code>typedef</code> or Q name of
411      *         <code>typedef</code> equals <code>null</code>
412      */
413     private Type typedefToGeneratedType(final String basePackageName, final Module module,
414             final TypeDefinition<?> typedef) {
415         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
416
417         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
418         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
419             return null;
420         }
421
422         final String typedefName = typedef.getQName().getLocalName();
423
424         final GeneratedType returnType;
425         if (baseTypedef.getBaseType() != null) {
426             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
427                 module.getName());
428         } else if (baseTypedef instanceof UnionTypeDefinition) {
429             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
430                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
431                 (UnionTypeDefinition) baseTypedef, typedef);
432             genTOBuilder.setTypedef(true);
433             genTOBuilder.setIsUnion(true);
434             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
435             makeSerializable(genTOBuilder);
436             returnType = genTOBuilder.build();
437
438             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
439             // so we are placing the builder alongside the union.
440             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
441                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
442             unionBuilder.setIsUnionBuilder(true);
443             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
444             method.setReturnType(returnType);
445             method.addParameter(Types.STRING, "defaultValue");
446             method.setAccessModifier(AccessModifier.PUBLIC);
447             method.setStatic(true);
448             additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
449         } else if (baseTypedef instanceof EnumTypeDefinition) {
450             // enums are automatically Serializable
451             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
452             // TODO units for typedef enum
453             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
454         } else if (baseTypedef instanceof BitsTypeDefinition) {
455             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
456                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
457                 (BitsTypeDefinition) baseTypedef, module.getName());
458             genTOBuilder.setTypedef(true);
459             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
460             makeSerializable(genTOBuilder);
461             returnType = genTOBuilder.build();
462         } else {
463             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
464             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
465         }
466         if (returnType != null) {
467             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
468                     genTypeDefsContextMap.get(module.getName());
469             final Optional<Revision> moduleRevision = module.getRevision();
470             Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
471             if (typeMap != null) {
472                 if (typeMap.isEmpty()) {
473                     typeMap = new HashMap<>(4);
474                     modulesByDate.put(moduleRevision, typeMap);
475                 }
476                 typeMap.put(typedefName, returnType);
477             }
478             return returnType;
479         }
480         return null;
481     }
482
483     /**
484      * Wraps base YANG type to generated TO.
485      *
486      * @param basePackageName string with name of package to which the module belongs
487      * @param typedef type definition which is converted to the TO
488      * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
489      * @return generated transfer object which represent<code>javaType</code>
490      */
491     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
492             final Type javaType, final String moduleName) {
493         requireNonNull(javaType, "javaType cannot be null");
494
495         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
496         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
497         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
498         genPropBuilder.setReturnType(javaType);
499
500         genTOBuilder.addEqualsIdentity(genPropBuilder);
501         genTOBuilder.addHashIdentity(genPropBuilder);
502         genTOBuilder.addToStringProperty(genPropBuilder);
503         genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
504         if (typedef.getStatus() == Status.DEPRECATED) {
505             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
506         }
507         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
508             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
509         }
510         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
511         genTOBuilder.setTypedef(true);
512         makeSerializable(genTOBuilder);
513         return genTOBuilder.build();
514     }
515
516     /**
517      * Converts output list of generated TO builders to one TO builder (first
518      * from list) which contains the remaining builders as its enclosing TO.
519      *
520      * @param typeName new type identifier
521      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
522      * @return generated TO builder with the list of enclosed generated TO builders
523      */
524     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
525             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
526         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
527             parentNode);
528         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
529
530         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
531         builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
532         return resultTOBuilder;
533     }
534
535     /**
536      * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
537      * <code>typedef</code> is added to generated TO builder as property.
538      *
539      * @param typeName new type identifier
540      * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
541      * @return generated TO builder which represents <code>typedef</code>
542      * @throws NullPointerException
543      *             <ul>
544      *             <li>if <code>basePackageName</code> is null</li>
545      *             <li>if <code>typedef</code> is null</li>
546      *             <li>if Qname of <code>typedef</code> is null</li>
547      *             </ul>
548      */
549     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
550             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
551         requireNonNull(typedef, "Type Definition cannot be NULL!");
552         requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
553
554         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
555         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
556         final Module module = findParentModule(schemaContext, parentNode);
557
558         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
559         unionGenTOBuilder.setIsUnion(true);
560         unionGenTOBuilder.setSchemaPath(typedef.getPath());
561         unionGenTOBuilder.setModuleName(module.getName());
562         unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
563         addCodegenInformation(unionGenTOBuilder, typedef);
564         generatedTOBuilders.add(unionGenTOBuilder);
565
566         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
567         // also negation information and hence guarantees uniqueness.
568         final Map<String, String> expressions = new HashMap<>();
569         for (TypeDefinition<?> unionType : unionTypes) {
570             final String unionTypeName = unionType.getQName().getLocalName();
571
572             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
573             // do not follow type encapsulation -- we use the general case for that.
574             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
575                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
576             } else if (unionType instanceof UnionTypeDefinition) {
577                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
578                     (UnionTypeDefinition) unionType, parentNode));
579             } else if (unionType instanceof EnumTypeDefinition) {
580                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
581                         unionTypeName, unionGenTOBuilder);
582                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
583             } else {
584                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
585                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
586             }
587         }
588         addStringRegExAsConstant(unionGenTOBuilder, expressions);
589
590         storeGenTO(typedef, unionGenTOBuilder, parentNode);
591
592         return generatedTOBuilders;
593     }
594
595     /**
596      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
597      *
598      * <p>
599      * In this case the new generated TO is created for union subtype (recursive call of method
600      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
601      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
602      * created property which type is equal to new generated TO.
603      *
604      * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
605      * @param basePackageName string with the name of the module package
606      * @param unionSubtype type definition which represents union subtype
607      * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
608      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
609      */
610     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
611             final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
612         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
613             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
614         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
615             newTOBuilderName, unionSubtype, parentNode);
616
617         final GeneratedPropertyBuilder propertyBuilder;
618         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
619             newTOBuilderName.simpleName()));
620         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
621         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
622         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
623
624         return subUnionGenTOBUilders;
625     }
626
627     /**
628      * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
629      * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
630      * the base type is used for the property creation.
631      *
632      * @param parentUnionGenTOBuilder generated TO builder in which new property is created
633      * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
634      * @param expressions list of strings with the regular expressions
635      * @param parentNode parent Schema Node for Extended Subtype
636      */
637     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
638             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
639         final String unionTypeName = unionSubtype.getQName().getLocalName();
640         final Type genTO = findGenTO(unionTypeName, unionSubtype);
641         if (genTO != null) {
642             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
643             return;
644         }
645
646         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
647         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
648             final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
649                 BindingGeneratorUtil.getRestrictions(unionSubtype));
650             if (javaType != null) {
651                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
652             }
653         } else if (baseType instanceof LeafrefTypeDefinition) {
654             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
655             boolean typeExist = false;
656             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
657                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
658                 if (origType != null && javaType != null && javaType == origType) {
659                     typeExist = true;
660                     break;
661                 }
662             }
663             if (!typeExist && javaType != null) {
664                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
665                     BindingMapping.getUnionLeafrefMemberName(parentUnionGenTOBuilder.getName(), javaType.getName()));
666             }
667         }
668         if (baseType instanceof StringTypeDefinition) {
669             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
670         }
671     }
672
673     /**
674      * Searches for generated TO for <code>searchedTypeDef</code> type  definition
675      * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
676      *
677      * @param searchedTypeName string with name of <code>searchedTypeDef</code>
678      * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
679      */
680     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
681         final Module typeModule = findParentModule(schemaContext, parentNode);
682         if (typeModule != null && typeModule.getName() != null) {
683             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
684                 typeModule.getName());
685             final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
686             if (genTOs != null) {
687                 return genTOs.get(searchedTypeName);
688             }
689         }
690         return null;
691     }
692
693     /**
694      * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
695      * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
696      *
697      * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
698      * @param genTOBuilder generated TO builder which is converted to generated TO and stored
699      */
700     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
701             final SchemaNode parentNode) {
702         if (!(newTypeDef instanceof UnionTypeDefinition)) {
703             final Module parentModule = findParentModule(schemaContext, parentNode);
704             if (parentModule != null && parentModule.getName() != null) {
705                 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
706                     parentModule.getName());
707                 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
708                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
709             }
710         }
711     }
712
713     /**
714      * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
715      * to <code>unonGenTransObject</code>.
716      *
717      * @param unionGenTransObject generated TO to which should be property added
718      * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
719      * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
720      */
721     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
722             final String propertyName) {
723         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
724             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
725                     .addProperty(BindingMapping.getPropertyName(propertyName));
726             propBuilder.setReturnType(type);
727
728             unionGenTransObject.addEqualsIdentity(propBuilder);
729             unionGenTransObject.addHashIdentity(propBuilder);
730             unionGenTransObject.addToStringProperty(propBuilder);
731         }
732     }
733
734     /**
735      * Converts <code>typedef</code> to the generated TO builder.
736      *
737      * @param basePackageName string with name of package to which the module belongs
738      * @param typedef type definition from which is the generated TO builder created
739      * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
740      */
741     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
742             final TypeDefinition<?> typedef, final String moduleName) {
743         final JavaTypeName name = JavaTypeName.create(
744                 packageNameForGeneratedType(basePackageName, typedef.getPath()),
745                 BindingMapping.getClassName(typedef.getQName().getLocalName()));
746
747         final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
748         newType.setSchemaPath(typedef.getPath());
749         newType.setModuleName(moduleName);
750         addCodegenInformation(newType, typedef);
751         return newType;
752     }
753
754     /**
755      * Creates package name from specified <code>basePackageName</code> (package name for module)
756      * and <code>schemaPath</code>. Resulting package name is concatenation of <code>basePackageName</code>
757      * and all local names of YANG nodes which are parents of some node for which <code>schemaPath</code> is specified.
758      *
759      * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
760      *                        return an invalid string.
761      * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
762      * @return string with valid JAVA package name
763      * @throws NullPointerException if any of the arguments are null
764      */
765     private static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath) {
766         final int size = Iterables.size(schemaPath.getPathTowardsRoot()) - 1;
767         if (size <= 0) {
768             return basePackageName;
769         }
770
771         return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
772     }
773
774     private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int size) {
775         final StringBuilder builder = new StringBuilder(base);
776         final Iterator<QName> iterator = path.iterator();
777         for (int i = 0; i < size; ++i) {
778             builder.append('.');
779             final String nodeLocalName = iterator.next().getLocalName();
780             // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
781             builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
782         }
783         return BindingMapping.normalizePackageName(builder.toString());
784     }
785
786
787     /**
788      * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
789      * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
790      * properties.
791      *
792      * @param typeName new type identifier
793      * @param typeDef type definition from which is the generated TO builder created
794      * @return generated TO builder which represents <code>typeDef</code>
795      * @throws IllegalArgumentException
796      *             <ul>
797      *             <li>if <code>typeDef</code> equals null</li>
798      *             <li>if <code>basePackageName</code> equals null</li>
799      *             </ul>
800      */
801     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
802             final BitsTypeDefinition typeDef, final String moduleName) {
803         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
804         genTOBuilder.setSchemaPath(typeDef.getPath());
805         genTOBuilder.setModuleName(moduleName);
806         genTOBuilder.setBaseType(typeDef);
807         genTOBuilder.addImplementsType(TYPE_OBJECT);
808         addCodegenInformation(genTOBuilder, typeDef);
809
810         for (Bit bit : typeDef.getBits()) {
811             final String name = bit.getName();
812             GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
813                 BindingMapping.getPropertyName(name));
814             genPropertyBuilder.setReadOnly(true);
815             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
816
817             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
818             genTOBuilder.addHashIdentity(genPropertyBuilder);
819             genTOBuilder.addToStringProperty(genPropertyBuilder);
820         }
821
822         return genTOBuilder;
823     }
824
825     /**
826      * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
827      * the <code>regularExpressions</code>.
828      *
829      * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
830      * @param expressions list of string which represent regular expressions
831      */
832     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
833             final Map<String, String> expressions) {
834         if (!expressions.isEmpty()) {
835             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
836                 ImmutableMap.copyOf(expressions));
837         }
838     }
839
840     /**
841      * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
842      * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
843      *
844      * <p>
845      * It is assumed that <code>innerExtendedType</code> is already present in
846      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
847      * for the returning generated TO.
848      *
849      * @param typedef Type Definition
850      * @param innerExtendedType extended type which is part of some other extended type
851      * @param basePackageName string with the package name of the module
852      * @param moduleName Module Name
853      * @return generated TO which extends generated TO for <code>innerExtendedType</code>
854      * @throws IllegalArgumentException
855      *             <ul>
856      *             <li>if <code>extendedType</code> equals null</li>
857      *             <li>if <code>basePackageName</code> equals null</li>
858      *             <li>if <code>typedefName</code> equals null</li>
859      *             </ul>
860      */
861     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
862             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
863         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
864         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
865
866         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
867             BindingMapping.getClassName(typedef.getQName())));
868         genTOBuilder.setSchemaPath(typedef.getPath());
869         genTOBuilder.setModuleName(moduleName);
870         genTOBuilder.setTypedef(true);
871         addCodegenInformation(genTOBuilder, typedef);
872
873         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
874         genTOBuilder.setRestrictions(r);
875         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
876
877         if (typedef.getStatus() == Status.DEPRECATED) {
878             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
879         }
880
881         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
882             genTOBuilder.setIsUnion(true);
883         }
884
885         Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
886         Map<String, GeneratedType> typeMap = null;
887         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
888         if (parentModule != null) {
889             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
890             typeMap = modulesByDate.get(parentModule.getRevision());
891         }
892
893         if (typeMap != null) {
894             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
895             final GeneratedType type = typeMap.get(innerTypeDef);
896             if (type instanceof GeneratedTransferObject) {
897                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
898             }
899         }
900         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
901         makeSerializable(genTOBuilder);
902
903         return genTOBuilder.build();
904     }
905
906     /**
907      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
908      * property.
909      *
910      * @param gto transfer object which needs to be made serializable
911      */
912     private static void makeSerializable(final GeneratedTOBuilder gto) {
913         gto.addImplementsType(Types.serializableType());
914         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
915         prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
916         gto.setSUID(prop);
917     }
918
919     /**
920      * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
921      * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
922      * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
923      * type definitions are in the list behind all type definitions on which depends.
924      *
925      * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
926      * @return list of type definitions sorted according their each other dependencies (type definitions which are
927      *              dependent on other type definitions are in list behind them).
928      */
929     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
930             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
931         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
932
933         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
934         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
935             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
936             List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
937                 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
938             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
939         }
940
941         // SortedMap guarantees order corresponding to keys in ascending order
942         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
943             sortedTypeDefinition.addAll(v);
944         }
945
946         return sortedTypeDefinition;
947     }
948
949     /**
950      * Returns how many immersion is necessary to get from the type definition to the base type.
951      *
952      * @param typeDefinition type definition for which is depth sought.
953      * @return number of immersions which are necessary to get from the type definition to the base type
954      */
955     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
956         // FIXME: rewrite this in a non-recursive manner
957         if (typeDefinition == null) {
958             return 1;
959         }
960         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
961         if (baseType == null) {
962             return 1;
963         }
964
965         int depth = 1;
966         if (baseType.getBaseType() != null) {
967             depth = depth + getTypeDefinitionDepth(baseType);
968         } else if (baseType instanceof UnionTypeDefinition) {
969             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
970             int maxChildDepth = 0;
971             int childDepth = 1;
972             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
973                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
974                 if (childDepth > maxChildDepth) {
975                     maxChildDepth = childDepth;
976                 }
977             }
978             return maxChildDepth;
979         }
980         return depth;
981     }
982
983     /**
984      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
985      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
986      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
987      *
988      * @param name string with name of augmented node
989      * @return string with the number suffix incremented by one (or 1 is added)
990      */
991     private static String provideAvailableNameForGenTOBuilder(final String name) {
992         final int dollar = name.indexOf('$');
993         if (dollar == -1) {
994             return name + "$1";
995         }
996
997         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
998         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
999         return name.substring(0, dollar + 1) + newSuffix;
1000     }
1001
1002     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1003         if (!Strings.isNullOrEmpty(units)) {
1004             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1005             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1006             prop.setReturnType(Types.STRING);
1007             to.addToStringProperty(prop);
1008         }
1009     }
1010
1011     /**
1012      * Returns parent Yang Module for specified Schema Context in which Schema
1013      * Node is declared. If the Schema Node is not present in Schema Context the
1014      * operation will return <code>null</code>.
1015      *
1016      * @param context Schema Context
1017      * @param schemaNode Schema Node
1018      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
1019      *         return <code>null</code>
1020      * @throws NullPointerException if any of the arguments is null
1021      */
1022     private static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
1023         return context.findModule(schemaNode.getQName().getModule()).orElse(null);
1024     }
1025 }