Cleanup GeneratedTypeBuilder/enclosing mechanics
[mdsal.git] / binding / mdsal-binding-generator-impl / 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.util.BindingTypes.TYPE_OBJECT;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataTreeSchemaNode;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.ImmutableMap;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.TreeMap;
31 import java.util.regex.Pattern;
32 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
33 import org.opendaylight.mdsal.binding.generator.util.BaseYangTypesProvider;
34 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
35 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
36 import org.opendaylight.mdsal.binding.model.api.Enumeration;
37 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
38 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
40 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
41 import org.opendaylight.mdsal.binding.model.api.Restrictions;
42 import org.opendaylight.mdsal.binding.model.api.Type;
43 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
49 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
50 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
51 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
52 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
53 import org.opendaylight.mdsal.binding.model.util.Types;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
55 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
56 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.Module;
65 import org.opendaylight.yangtools.yang.model.api.PathExpression;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.api.Status;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
73 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
78 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
81 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
82 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85
86 @Beta
87 public abstract class AbstractTypeProvider implements TypeProvider {
88     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
89     private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
90     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
91
92     /**
93      * Contains the schema data red from YANG files.
94      */
95     private final SchemaContext schemaContext;
96
97     private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
98         new HashMap<>();
99
100     /**
101      * The map which maps schema paths to JAVA <code>Type</code>.
102      */
103     private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
104     private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
105     private final Map<SchemaNode, JavaTypeName> renames;
106
107     /**
108      * Creates new instance of class <code>TypeProviderImpl</code>.
109      *
110      * @param schemaContext contains the schema data red from YANG files
111      * @param renames renaming table
112      * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
113      */
114     AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
115         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
116         this.schemaContext = schemaContext;
117         this.renames = requireNonNull(renames);
118         resolveTypeDefsFromContext();
119     }
120
121     /**
122      * Puts <code>refType</code> to map with key <code>refTypePath</code>.
123      *
124      * @param refTypePath schema path used as the map key
125      * @param refType type which represents the map value
126      * @throws IllegalArgumentException
127      *             <ul>
128      *             <li>if <code>refTypePath</code> equal null</li>
129      *             <li>if <code>refType</code> equal null</li>
130      *             </ul>
131      *
132      */
133     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
134         Preconditions.checkArgument(refTypePath != null,
135                 "Path reference of Enumeration Type Definition cannot be NULL!");
136         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
137         referencedTypes.put(refTypePath, refType);
138     }
139
140     public Map<Module, Set<GeneratedType>> getAdditionalTypes() {
141         return additionalTypes;
142     }
143
144     @Override
145     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
146             final boolean lenientRelativeLeafrefs) {
147         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
148     }
149
150     /**
151      * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
152      *
153      * @param typeDefinition type definition which is converted to JAVA type
154      * @throws IllegalArgumentException
155      *             <ul>
156      *             <li>if <code>typeDefinition</code> equal null</li>
157      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
158      *             <li>if name of <code>typeDefinition</code> equal null</li>
159      *             </ul>
160      */
161     @Override
162     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
163             final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
164         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
165         Preconditions.checkArgument(typeDefinition.getQName() != null,
166                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
167         final String typedefName = typeDefinition.getQName().getLocalName();
168         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
169
170         // Deal with base types
171         if (typeDefinition.getBaseType() == null) {
172             // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
173             // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
174             // a base type which holds these constraints.
175             if (typeDefinition instanceof DecimalTypeDefinition) {
176                 final Type ret = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(typeDefinition,
177                     parentNode, restrictions, lenientRelativeLeafrefs);
178                 if (ret != null) {
179                     return ret;
180                 }
181             }
182
183             // Deal with leafrefs/identityrefs
184             Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
185             if (ret != null) {
186                 return ret;
187             }
188
189             // FIXME: it looks as though we could be using the same codepath as above...
190             ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
191             if (ret == null) {
192                 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
193             }
194
195             return ret;
196         }
197
198         Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
199         if (restrictions != null && returnType instanceof GeneratedTransferObject) {
200             final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
201             final Module module = findParentModule(schemaContext, parentNode);
202             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
203             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
204                 typeDefinition.getPath());
205             final String genTOName = BindingMapping.getClassName(typedefName);
206             final String name = packageName + "." + genTOName;
207             if (!returnType.getFullyQualifiedName().equals(name)) {
208                 returnType = shadedTOWithRestrictions(gto, restrictions);
209             }
210         }
211         return returnType;
212     }
213
214     public SchemaNode getTargetForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
215         final PathExpression xpath = leafrefType.getPathStatement();
216         Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
217
218         final Module module = findParentModule(schemaContext, parentNode);
219         Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
220
221         return xpath.isAbsolute() ? findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath)
222                 : findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
223     }
224
225     private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
226             final Restrictions restrictions) {
227         final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
228         final GeneratedTransferObject parent = gto.getSuperType();
229         if (parent != null) {
230             gtob.setExtendsType(parent);
231         }
232         gtob.setRestrictions(restrictions);
233         for (GeneratedProperty gp : gto.getProperties()) {
234             final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
235             gpb.setValue(gp.getValue());
236             gpb.setReadOnly(gp.isReadOnly());
237             gpb.setAccessModifier(gp.getAccessModifier());
238             gpb.setReturnType(gp.getReturnType());
239             gpb.setFinal(gp.isFinal());
240             gpb.setStatic(gp.isStatic());
241         }
242         return gtob.build();
243     }
244
245     private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
246         /*
247          * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
248          * are resolved.
249          */
250         DataNodeContainer current = null;
251         DataSchemaNode dataChildByName;
252         for (QName next : parentNode.getPath().getPathFromRoot()) {
253             if (current == null) {
254                 dataChildByName = schemaContext.dataChildByName(next);
255             } else {
256                 dataChildByName = current.dataChildByName(next);
257             }
258             if (dataChildByName == null) {
259                 return false;
260             }
261             if (dataChildByName.isAugmenting()) {
262                 return false;
263             }
264             if (dataChildByName instanceof DataNodeContainer) {
265                 current = (DataNodeContainer) dataChildByName;
266             }
267         }
268
269         // Then try to look up the expression.
270         final PathExpression leafRefXPath = leafref.getPathStatement();
271         final Module parentModule = getParentModule(parentNode);
272         final SchemaNode leafRefValueNode;
273         if (leafRefXPath.isAbsolute()) {
274             leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
275                 leafRefXPath);
276         } else {
277             leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
278                 parentNode, new PathExpressionImpl(
279                     GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
280         }
281
282         return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
283     }
284
285     /**
286      * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
287      * <code>IdentityrefTypeDefinition</code>.
288      *
289      * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
290      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
291      */
292     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
293             final boolean inGrouping) {
294         if (typeDefinition instanceof LeafrefTypeDefinition) {
295             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
296             Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
297                 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
298             return provideTypeForLeafref(leafref, parentNode, inGrouping);
299         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
300             return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
301         }
302
303         return null;
304     }
305
306     /**
307      * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
308      *
309      * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
310      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
311      */
312     private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
313         final String typedefName = typeDefinition.getQName().getLocalName();
314         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
315         Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
316         if (returnType == null) {
317             if (baseTypeDef instanceof EnumTypeDefinition) {
318                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
319                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
320             } else {
321                 final Module module = findParentModule(schemaContext, typeDefinition);
322                 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
323                 if (module != null) {
324                     final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
325                         module.getName());
326                     final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
327                     if (genTOs != null) {
328                         returnType = genTOs.get(typedefName);
329                     }
330                     if (returnType == null) {
331                         returnType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseTypeDef,
332                             typeDefinition, r, lenient);
333                     }
334                 }
335             }
336         }
337         return returnType;
338     }
339
340     /**
341      * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
342      *
343      * <p>
344      * <i>Example:<br />
345      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
346      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
347      *
348      * @param idref identityref type definition for which JAVA <code>Type</code> is sought
349      * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
350      */
351     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
352         final Collection<? extends IdentitySchemaNode> identities = idref.getIdentities();
353         if (identities.size() > 1) {
354             LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
355         }
356
357         final QName baseIdQName = identities.iterator().next().getQName();
358         final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
359         IdentitySchemaNode identity = null;
360         for (IdentitySchemaNode id : module.getIdentities()) {
361             if (id.getQName().equals(baseIdQName)) {
362                 identity = id;
363             }
364         }
365         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exist");
366
367         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
368         final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
369             basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
370         return Types.classType(Types.wildcardTypeFor(identifier));
371     }
372
373     /**
374      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
375      *
376      * @param typeDefinition
377      *            type definition which should be converted to JAVA
378      *            <code>Type</code>
379      * @return JAVA <code>Type</code> which represents
380      *         <code>typeDefinition</code>
381      * @throws IllegalArgumentException
382      *             <ul>
383      *             <li>if <code>typeDefinition</code> equal null</li>
384      *             <li>if Q name of <code>typeDefinition</code></li>
385      *             <li>if name of <code>typeDefinition</code></li>
386      *             </ul>
387      */
388     public GeneratedType generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
389             final SchemaNode parentNode) {
390         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
391         if (typeDefinition.getQName() == null) {
392             throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
393         }
394         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
395                 "Type Definitions Local Name cannot be NULL!");
396
397         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
398         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
399             /*
400              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
401              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
402              * this:
403              *
404              *     identity iden;
405              *
406              *     container foo {
407              *         leaf foo {
408              *             type identityref {
409              *                 base iden;
410              *             }
411              *         }
412              *     }
413              *
414              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
415              * dicey when we throw in:
416              *
417              *     typedef bar-ref {
418              *         type identityref {
419              *             base iden;
420              *         }
421              *     }
422              *
423              *     container bar {
424              *         leaf bar {
425              *             type bar-ref;
426              *         }
427              *     }
428              *
429              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
430              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
431              * is formed.
432              *
433              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
434              * an encapsulation for identityref typedefs.
435              *
436              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
437              * option, as it would look as though it is the product of a different construct:
438              *
439              *     identity bar-ref {
440              *         base iden;
441              *     }
442              *
443              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
444              * sub-identities of iden.
445              *
446              * The story behind leafrefs is probably similar, but that needs to be ascertained.
447              */
448             return null;
449         }
450
451         final Module module = findParentModule(schemaContext, parentNode);
452         if (module != null) {
453             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
454                 module.getName());
455             final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
456             if (genTOs != null) {
457                 return genTOs.get(typeDefinition.getQName().getLocalName());
458             }
459         }
460         return null;
461     }
462
463     /**
464      * Gets base type definition for <code>extendTypeDef</code>. The method is
465      * recursively called until non <code>ExtendedType</code> type is found.
466      *
467      * @param extendTypeDef
468      *            type definition for which is the base type definition sought
469      * @return type definition which is base type for <code>extendTypeDef</code>
470      * @throws IllegalArgumentException
471      *             if <code>extendTypeDef</code> equal null
472      */
473     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
474         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
475
476         TypeDefinition<?> ret = extendTypeDef;
477         while (ret.getBaseType() != null) {
478             ret = ret.getBaseType();
479         }
480
481         return ret;
482     }
483
484     /**
485      * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
486      * to find referenced node and its <code>Type</code> is returned.
487      *
488      * @param leafrefType leafref type definition for which is the type sought
489      * @param parentNode parent node of the leaf being resolved
490      * @param inGrouping true if we are resolving the type within a grouping.
491      * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
492      * @throws IllegalArgumentException
493      *             <ul>
494      *             <li>if <code>leafrefType</code> equal null</li>
495      *             <li>if path statement of <code>leafrefType</code> equal null</li>
496      *             </ul>
497      */
498     @VisibleForTesting
499     Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
500             final boolean inGrouping) {
501         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
502
503         final PathExpression xpath = leafrefType.getPathStatement();
504         Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
505
506         final String strXPath = xpath.getOriginalString();
507         if (strXPath.indexOf('[') != -1) {
508             // XXX: why are we special-casing this?
509             return Types.objectType();
510         }
511
512         final Module module = findParentModule(schemaContext, parentNode);
513         Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
514
515         final SchemaNode dataNode;
516         if (xpath.isAbsolute()) {
517             dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
518         } else {
519             dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
520             if (dataNode == null && inGrouping) {
521                 // Relative path within a grouping may end up being unresolvable because it may refer outside
522                 // the grouping, in which case it is polymorphic based on instantiation, for example:
523                 //
524                 // grouping foo {
525                 //     leaf foo {
526                 //         type leafref {
527                 //             path "../../bar";
528                 //         }
529                 //     }
530                 // }
531                 //
532                 // container one {
533                 //     leaf bar {
534                 //         type string;
535                 //     }
536                 //     uses foo;
537                 // }
538                 //
539                 // container two {
540                 //     leaf bar {
541                 //         type uint16;
542                 //     }
543                 //     uses foo;
544                 // }
545                 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
546                     parentNode);
547                 return Types.objectType();
548             }
549         }
550         Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
551                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
552
553         // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
554         Type returnType = null;
555         if (leafContainsEnumDefinition(dataNode)) {
556             returnType = referencedTypes.get(dataNode.getPath());
557         } else if (leafListContainsEnumDefinition(dataNode)) {
558             returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
559         }
560         if (returnType == null) {
561             returnType = resolveTypeFromDataSchemaNode(dataNode, inGrouping);
562         }
563         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
564                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
565         return returnType;
566     }
567
568     /**
569      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
570      * <code>EnumTypeDefinition</code>.
571      *
572      * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
573      * @return boolean value
574      *         <ul>
575      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
576      *         <li>false - other cases</li>
577      *         </ul>
578      */
579     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
580         if (dataNode instanceof LeafSchemaNode) {
581             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
582             return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
583         }
584         return false;
585     }
586
587     /**
588      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
589      * <code>EnumTypeDefinition</code>.
590      *
591      * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
592      * @return boolean value
593      *         <ul>
594      *         <li>true - if <code>dataNode</code> is leaflist of type
595      *         enumeration</li>
596      *         <li>false - other cases</li>
597      *         </ul>
598      */
599     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
600         if (dataNode instanceof LeafListSchemaNode) {
601             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
602             return leafList.getType() instanceof EnumTypeDefinition;
603         }
604         return false;
605     }
606
607     /**
608      * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
609      *
610      * @param enumTypeDef enumeration type definition which is converted to enumeration
611      * @param enumName string with name which is used as the enumeration name
612      * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
613      * @throws IllegalArgumentException
614      *             <ul>
615      *             <li>if <code>enumTypeDef</code> equals null</li>
616      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
617      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
618      *             <li>if name of <code>enumTypeDef</code> equal null</li>
619      *             </ul>
620      */
621     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
622             final SchemaNode parentNode) {
623         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
624         Preconditions.checkArgument(enumTypeDef.getValues() != null,
625                 "EnumTypeDefinition MUST contain at least ONE value definition!");
626         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
627         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
628                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
629
630         final Module module = findParentModule(schemaContext, parentNode);
631         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
632             BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
633         addEnumDescription(enumBuilder, enumTypeDef);
634         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
635         enumBuilder.setModuleName(module.getName());
636         enumBuilder.setSchemaPath(enumTypeDef.getPath());
637         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
638         return enumBuilder.toInstance();
639     }
640
641     /**
642      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
643      *
644      * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
645      * @param enumName string with the name of enumeration
646      * @param typeBuilder generated type builder to which is enumeration added
647      * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
648      * @throws IllegalArgumentException
649      *             <ul>
650      *             <li>if <code>enumTypeDef</code> equals null</li>
651      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
652      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
653      *             <li>if name of <code>enumTypeDef</code> equal null</li>
654      *             <li>if name of <code>typeBuilder</code> equal null</li>
655      *             </ul>
656      *
657      */
658     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
659             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
660         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
661         Preconditions.checkArgument(enumTypeDef.getValues() != null,
662                 "EnumTypeDefinition MUST contain at least ONE value definition!");
663         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
664         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
665                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
666         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
667
668         final EnumBuilder enumBuilder = newEnumerationBuilder(
669             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
670         addEnumDescription(enumBuilder, enumTypeDef);
671         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
672         final Enumeration ret = enumBuilder.toInstance();
673         typeBuilder.addEnumeration(ret);
674
675         return ret;
676     }
677
678     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
679
680     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
681
682     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
683
684     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
685
686     /**
687      * Converts the pattern constraints to the list of the strings which represents these constraints.
688      *
689      * @param patternConstraints list of pattern constraints
690      * @return list of strings which represents the constraint patterns
691      */
692     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
693
694     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
695
696     /**
697      * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
698      * constraints.
699      *
700      * @param typedef extended type in which are the pattern constraints sought
701      * @return list of strings which represents the constraint patterns
702      * @throws IllegalArgumentException if <code>typedef</code> equals null
703      *
704      */
705     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
706         if (!(typedef instanceof StringTypeDefinition)) {
707             return ImmutableMap.of();
708         }
709
710         // TODO: run diff against base ?
711         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
712     }
713
714     /**
715      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
716      *
717      * @param dataNode contains information about YANG type
718      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
719      */
720     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final boolean inGrouping) {
721         Type returnType = null;
722         if (dataNode != null) {
723             if (dataNode instanceof LeafSchemaNode) {
724                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
725                 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
726                 returnType = javaTypeForSchemaDefinitionType(type, leaf, inGrouping);
727             } else if (dataNode instanceof LeafListSchemaNode) {
728                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
729                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList, inGrouping);
730             }
731         }
732         return returnType;
733     }
734
735     /**
736      * Passes through all modules and through all its type definitions and convert it to generated types.
737      *
738      * <p>
739      * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
740      * of a module are at the beginning sorted so that type definition with less amount of references to other type
741      * definition are processed first.<br>
742      * For each module is created mapping record in the map
743      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
744      * which map current module name to the map which maps type names to returned types (generated types).
745      */
746     private void resolveTypeDefsFromContext() {
747         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
748
749         for (Module module : modulesSortedByDependency) {
750             Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
751                 module.getName(), key -> new HashMap<>());
752             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
753             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
754         }
755
756         for (Module module : modulesSortedByDependency) {
757             if (module != null) {
758                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
759                 if (basePackageName != null) {
760                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
761                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
762                         typedefToGeneratedType(basePackageName, module, typedef);
763                     }
764                 }
765             }
766         }
767     }
768
769     /**
770      * Create Type for specified type definition.
771      *
772      * @param basePackageName string with name of package to which the module belongs
773      * @param module string with the name of the module for to which the <code>typedef</code> belongs
774      * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
775      *                (usually generated TO)
776      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
777      *         <code>null</code> value if <code>basePackageName</code> or
778      *         <code>modulName</code> or <code>typedef</code> or Q name of
779      *         <code>typedef</code> equals <code>null</code>
780      */
781     private Type typedefToGeneratedType(final String basePackageName, final Module module,
782             final TypeDefinition<?> typedef) {
783         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
784
785         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
786         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
787             return null;
788         }
789
790         final String typedefName = typedef.getQName().getLocalName();
791
792         final GeneratedType returnType;
793         if (baseTypedef.getBaseType() != null) {
794             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
795                 module.getName());
796         } else if (baseTypedef instanceof UnionTypeDefinition) {
797             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
798                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
799                 (UnionTypeDefinition) baseTypedef, typedef);
800             genTOBuilder.setTypedef(true);
801             genTOBuilder.setIsUnion(true);
802             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
803             makeSerializable(genTOBuilder);
804             returnType = genTOBuilder.build();
805
806             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
807             // so we are placing the builder alongside the union.
808             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
809                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
810             unionBuilder.setIsUnionBuilder(true);
811             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
812             method.setReturnType(returnType);
813             method.addParameter(Types.STRING, "defaultValue");
814             method.setAccessModifier(AccessModifier.PUBLIC);
815             method.setStatic(true);
816             additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
817         } else if (baseTypedef instanceof EnumTypeDefinition) {
818             // enums are automatically Serializable
819             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
820             // TODO units for typedef enum
821             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
822         } else if (baseTypedef instanceof BitsTypeDefinition) {
823             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
824                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
825                 (BitsTypeDefinition) baseTypedef, module.getName());
826             genTOBuilder.setTypedef(true);
827             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
828             makeSerializable(genTOBuilder);
829             returnType = genTOBuilder.build();
830         } else {
831             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
832             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
833         }
834         if (returnType != null) {
835             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
836                     genTypeDefsContextMap.get(module.getName());
837             final Optional<Revision> moduleRevision = module.getRevision();
838             Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
839             if (typeMap != null) {
840                 if (typeMap.isEmpty()) {
841                     typeMap = new HashMap<>(4);
842                     modulesByDate.put(moduleRevision, typeMap);
843                 }
844                 typeMap.put(typedefName, returnType);
845             }
846             return returnType;
847         }
848         return null;
849     }
850
851     /**
852      * Wraps base YANG type to generated TO.
853      *
854      * @param basePackageName string with name of package to which the module belongs
855      * @param typedef type definition which is converted to the TO
856      * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
857      * @return generated transfer object which represent<code>javaType</code>
858      */
859     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
860             final Type javaType, final String moduleName) {
861         requireNonNull(javaType, "javaType cannot be null");
862
863         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
864         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
865         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
866         genPropBuilder.setReturnType(javaType);
867
868         genTOBuilder.addEqualsIdentity(genPropBuilder);
869         genTOBuilder.addHashIdentity(genPropBuilder);
870         genTOBuilder.addToStringProperty(genPropBuilder);
871         genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
872         if (typedef.getStatus() == Status.DEPRECATED) {
873             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
874         }
875         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
876             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
877         }
878         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
879         genTOBuilder.setTypedef(true);
880         makeSerializable(genTOBuilder);
881         return genTOBuilder.build();
882     }
883
884     /**
885      * Converts output list of generated TO builders to one TO builder (first
886      * from list) which contains the remaining builders as its enclosing TO.
887      *
888      * @param typeName new type identifier
889      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
890      * @return generated TO builder with the list of enclosed generated TO builders
891      */
892     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
893             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
894         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
895             parentNode);
896         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
897
898         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
899         builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
900         return resultTOBuilder;
901     }
902
903     /**
904      * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
905      * <code>typedef</code> is added to generated TO builder as property.
906      *
907      * @param typeName new type identifier
908      * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
909      * @return generated TO builder which represents <code>typedef</code>
910      * @throws NullPointerException
911      *             <ul>
912      *             <li>if <code>basePackageName</code> is null</li>
913      *             <li>if <code>typedef</code> is null</li>
914      *             <li>if Qname of <code>typedef</code> is null</li>
915      *             </ul>
916      */
917     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
918             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
919         requireNonNull(typedef, "Type Definition cannot be NULL!");
920         requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
921
922         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
923         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
924         final Module module = findParentModule(schemaContext, parentNode);
925
926         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
927         unionGenTOBuilder.setIsUnion(true);
928         unionGenTOBuilder.setSchemaPath(typedef.getPath());
929         unionGenTOBuilder.setModuleName(module.getName());
930         unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
931         addCodegenInformation(unionGenTOBuilder, typedef);
932         generatedTOBuilders.add(unionGenTOBuilder);
933
934         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
935         // also negation information and hence guarantees uniqueness.
936         final Map<String, String> expressions = new HashMap<>();
937         for (TypeDefinition<?> unionType : unionTypes) {
938             final String unionTypeName = unionType.getQName().getLocalName();
939
940             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
941             // do not follow type encapsulation -- we use the general case for that.
942             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
943                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
944             } else if (unionType instanceof UnionTypeDefinition) {
945                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
946                     (UnionTypeDefinition) unionType, parentNode));
947             } else if (unionType instanceof EnumTypeDefinition) {
948                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
949                         unionTypeName, unionGenTOBuilder);
950                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
951             } else {
952                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
953                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
954             }
955         }
956         addStringRegExAsConstant(unionGenTOBuilder, expressions);
957
958         storeGenTO(typedef, unionGenTOBuilder, parentNode);
959
960         return generatedTOBuilders;
961     }
962
963     /**
964      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
965      *
966      * <p>
967      * In this case the new generated TO is created for union subtype (recursive call of method
968      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
969      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
970      * created property which type is equal to new generated TO.
971      *
972      * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
973      * @param basePackageName string with the name of the module package
974      * @param unionSubtype type definition which represents union subtype
975      * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
976      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
977      */
978     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
979             final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
980         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
981             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
982         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
983             newTOBuilderName, unionSubtype, parentNode);
984
985         final GeneratedPropertyBuilder propertyBuilder;
986         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
987             newTOBuilderName.simpleName()));
988         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
989         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
990         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
991
992         return subUnionGenTOBUilders;
993     }
994
995     /**
996      * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
997      * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
998      * the base type is used for the property creation.
999      *
1000      * @param parentUnionGenTOBuilder generated TO builder in which new property is created
1001      * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
1002      * @param expressions list of strings with the regular expressions
1003      * @param parentNode parent Schema Node for Extended Subtype
1004      */
1005     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1006             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1007         final String unionTypeName = unionSubtype.getQName().getLocalName();
1008         final Type genTO = findGenTO(unionTypeName, unionSubtype);
1009         if (genTO != null) {
1010             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1011             return;
1012         }
1013
1014         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1015         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1016             final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
1017                 BindingGeneratorUtil.getRestrictions(unionSubtype));
1018             if (javaType != null) {
1019                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1020             }
1021         } else if (baseType instanceof LeafrefTypeDefinition) {
1022             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1023             boolean typeExist = false;
1024             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1025                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1026                 if (origType != null && javaType != null && javaType == origType) {
1027                     typeExist = true;
1028                     break;
1029                 }
1030             }
1031             if (!typeExist && javaType != null) {
1032                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1033                     javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1034             }
1035         }
1036         if (baseType instanceof StringTypeDefinition) {
1037             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1038         }
1039     }
1040
1041     /**
1042      * Searches for generated TO for <code>searchedTypeDef</code> type  definition
1043      * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1044      *
1045      * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1046      * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1047      */
1048     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1049         final Module typeModule = findParentModule(schemaContext, parentNode);
1050         if (typeModule != null && typeModule.getName() != null) {
1051             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
1052                 typeModule.getName());
1053             final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
1054             if (genTOs != null) {
1055                 return genTOs.get(searchedTypeName);
1056             }
1057         }
1058         return null;
1059     }
1060
1061     /**
1062      * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1063      * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1064      *
1065      * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1066      * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1067      */
1068     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1069             final SchemaNode parentNode) {
1070         if (!(newTypeDef instanceof UnionTypeDefinition)) {
1071             final Module parentModule = findParentModule(schemaContext, parentNode);
1072             if (parentModule != null && parentModule.getName() != null) {
1073                 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
1074                     parentModule.getName());
1075                 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
1076                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1077             }
1078         }
1079     }
1080
1081     /**
1082      * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1083      * to <code>unonGenTransObject</code>.
1084      *
1085      * @param unionGenTransObject generated TO to which should be property added
1086      * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1087      * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1088      */
1089     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1090             final String propertyName) {
1091         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1092             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1093                     .addProperty(BindingMapping.getPropertyName(propertyName));
1094             propBuilder.setReturnType(type);
1095
1096             unionGenTransObject.addEqualsIdentity(propBuilder);
1097             unionGenTransObject.addHashIdentity(propBuilder);
1098             unionGenTransObject.addToStringProperty(propBuilder);
1099         }
1100     }
1101
1102     /**
1103      * Converts <code>typedef</code> to the generated TO builder.
1104      *
1105      * @param basePackageName string with name of package to which the module belongs
1106      * @param typedef type definition from which is the generated TO builder created
1107      * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1108      */
1109     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1110             final TypeDefinition<?> typedef, final String moduleName) {
1111         JavaTypeName name = renames.get(typedef);
1112         if (name == null) {
1113             name = JavaTypeName.create(
1114                 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1115                 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1116         }
1117
1118         final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1119         newType.setSchemaPath(typedef.getPath());
1120         newType.setModuleName(moduleName);
1121         addCodegenInformation(newType, typedef);
1122         return newType;
1123     }
1124
1125     /**
1126      * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1127      * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1128      * properties.
1129      *
1130      * @param typeName new type identifier
1131      * @param typeDef type definition from which is the generated TO builder created
1132      * @return generated TO builder which represents <code>typeDef</code>
1133      * @throws IllegalArgumentException
1134      *             <ul>
1135      *             <li>if <code>typeDef</code> equals null</li>
1136      *             <li>if <code>basePackageName</code> equals null</li>
1137      *             </ul>
1138      */
1139     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1140             final BitsTypeDefinition typeDef, final String moduleName) {
1141         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1142         genTOBuilder.setSchemaPath(typeDef.getPath());
1143         genTOBuilder.setModuleName(moduleName);
1144         genTOBuilder.setBaseType(typeDef);
1145         genTOBuilder.addImplementsType(TYPE_OBJECT);
1146         addCodegenInformation(genTOBuilder, typeDef);
1147
1148         for (Bit bit : typeDef.getBits()) {
1149             final String name = bit.getName();
1150             GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
1151                 BindingMapping.getPropertyName(name));
1152             genPropertyBuilder.setReadOnly(true);
1153             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1154
1155             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1156             genTOBuilder.addHashIdentity(genPropertyBuilder);
1157             genTOBuilder.addToStringProperty(genPropertyBuilder);
1158         }
1159
1160         return genTOBuilder;
1161     }
1162
1163     /**
1164      * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1165      * the <code>regularExpressions</code>.
1166      *
1167      * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1168      * @param expressions list of string which represent regular expressions
1169      */
1170     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1171             final Map<String, String> expressions) {
1172         if (!expressions.isEmpty()) {
1173             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1174                 ImmutableMap.copyOf(expressions));
1175         }
1176     }
1177
1178     /**
1179      * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1180      * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1181      *
1182      * <p>
1183      * It is assumed that <code>innerExtendedType</code> is already present in
1184      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1185      * for the returning generated TO.
1186      *
1187      * @param typedef Type Definition
1188      * @param innerExtendedType extended type which is part of some other extended type
1189      * @param basePackageName string with the package name of the module
1190      * @param moduleName Module Name
1191      * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1192      * @throws IllegalArgumentException
1193      *             <ul>
1194      *             <li>if <code>extendedType</code> equals null</li>
1195      *             <li>if <code>basePackageName</code> equals null</li>
1196      *             <li>if <code>typedefName</code> equals null</li>
1197      *             </ul>
1198      */
1199     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1200             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1201         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1202         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1203
1204         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1205             BindingMapping.getClassName(typedef.getQName())));
1206         genTOBuilder.setSchemaPath(typedef.getPath());
1207         genTOBuilder.setModuleName(moduleName);
1208         genTOBuilder.setTypedef(true);
1209         addCodegenInformation(genTOBuilder, typedef);
1210
1211         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1212         genTOBuilder.setRestrictions(r);
1213         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1214
1215         if (typedef.getStatus() == Status.DEPRECATED) {
1216             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
1217         }
1218
1219         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1220             genTOBuilder.setIsUnion(true);
1221         }
1222
1223         Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
1224         Map<String, GeneratedType> typeMap = null;
1225         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1226         if (parentModule != null) {
1227             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1228             typeMap = modulesByDate.get(parentModule.getRevision());
1229         }
1230
1231         if (typeMap != null) {
1232             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1233             final GeneratedType type = typeMap.get(innerTypeDef);
1234             if (type instanceof GeneratedTransferObject) {
1235                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1236             }
1237         }
1238         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1239         makeSerializable(genTOBuilder);
1240
1241         return genTOBuilder.build();
1242     }
1243
1244     /**
1245      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1246      * property.
1247      *
1248      * @param gto transfer object which needs to be made serializable
1249      */
1250     private static void makeSerializable(final GeneratedTOBuilder gto) {
1251         gto.addImplementsType(Types.serializableType());
1252         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1253         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1254         gto.setSUID(prop);
1255     }
1256
1257     /**
1258      * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1259      * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1260      * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1261      * type definitions are in the list behind all type definitions on which depends.
1262      *
1263      * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1264      * @return list of type definitions sorted according their each other dependencies (type definitions which are
1265      *              dependent on other type definitions are in list behind them).
1266      */
1267     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1268             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1269         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1270
1271         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1272         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1273             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1274             List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1275                 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1276             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1277         }
1278
1279         // SortedMap guarantees order corresponding to keys in ascending order
1280         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1281             sortedTypeDefinition.addAll(v);
1282         }
1283
1284         return sortedTypeDefinition;
1285     }
1286
1287     /**
1288      * Returns how many immersion is necessary to get from the type definition to the base type.
1289      *
1290      * @param typeDefinition type definition for which is depth sought.
1291      * @return number of immersions which are necessary to get from the type definition to the base type
1292      */
1293     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1294         // FIXME: rewrite this in a non-recursive manner
1295         if (typeDefinition == null) {
1296             return 1;
1297         }
1298         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1299         if (baseType == null) {
1300             return 1;
1301         }
1302
1303         int depth = 1;
1304         if (baseType.getBaseType() != null) {
1305             depth = depth + getTypeDefinitionDepth(baseType);
1306         } else if (baseType instanceof UnionTypeDefinition) {
1307             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1308             int maxChildDepth = 0;
1309             int childDepth = 1;
1310             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1311                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1312                 if (childDepth > maxChildDepth) {
1313                     maxChildDepth = childDepth;
1314                 }
1315             }
1316             return maxChildDepth;
1317         }
1318         return depth;
1319     }
1320
1321     /**
1322      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1323      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1324      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1325      *
1326      * @param name string with name of augmented node
1327      * @return string with the number suffix incremented by one (or 1 is added)
1328      */
1329     private static String provideAvailableNameForGenTOBuilder(final String name) {
1330         final int dollar = name.indexOf('$');
1331         if (dollar == -1) {
1332             return name + "$1";
1333         }
1334
1335         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1336         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1337         return name.substring(0, dollar + 1) + newSuffix;
1338     }
1339
1340     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1341         if (!Strings.isNullOrEmpty(units)) {
1342             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1343             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1344             prop.setReturnType(Types.STRING);
1345             to.addToStringProperty(prop);
1346         }
1347     }
1348
1349     private Module getParentModule(final SchemaNode node) {
1350         final QName qname = node.getPath().getPathFromRoot().iterator().next();
1351         return schemaContext.findModule(qname.getModule()).orElse(null);
1352     }
1353 }