Remove parent type references
[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 = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
669
670         addEnumDescription(enumBuilder, enumTypeDef);
671         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
672         return enumBuilder.toInstance();
673     }
674
675     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
676
677     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
678
679     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
680
681     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
682
683     /**
684      * Converts the pattern constraints to the list of the strings which represents these constraints.
685      *
686      * @param patternConstraints list of pattern constraints
687      * @return list of strings which represents the constraint patterns
688      */
689     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
690
691     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
692
693     /**
694      * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
695      * constraints.
696      *
697      * @param typedef extended type in which are the pattern constraints sought
698      * @return list of strings which represents the constraint patterns
699      * @throws IllegalArgumentException if <code>typedef</code> equals null
700      *
701      */
702     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
703         if (!(typedef instanceof StringTypeDefinition)) {
704             return ImmutableMap.of();
705         }
706
707         // TODO: run diff against base ?
708         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
709     }
710
711     /**
712      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
713      *
714      * @param dataNode contains information about YANG type
715      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
716      */
717     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final boolean inGrouping) {
718         Type returnType = null;
719         if (dataNode != null) {
720             if (dataNode instanceof LeafSchemaNode) {
721                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
722                 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
723                 returnType = javaTypeForSchemaDefinitionType(type, leaf, inGrouping);
724             } else if (dataNode instanceof LeafListSchemaNode) {
725                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
726                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList, inGrouping);
727             }
728         }
729         return returnType;
730     }
731
732     /**
733      * Passes through all modules and through all its type definitions and convert it to generated types.
734      *
735      * <p>
736      * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
737      * of a module are at the beginning sorted so that type definition with less amount of references to other type
738      * definition are processed first.<br>
739      * For each module is created mapping record in the map
740      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
741      * which map current module name to the map which maps type names to returned types (generated types).
742      */
743     private void resolveTypeDefsFromContext() {
744         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
745
746         for (Module module : modulesSortedByDependency) {
747             Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
748                 module.getName(), key -> new HashMap<>());
749             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
750             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
751         }
752
753         for (Module module : modulesSortedByDependency) {
754             if (module != null) {
755                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
756                 if (basePackageName != null) {
757                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
758                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
759                         typedefToGeneratedType(basePackageName, module, typedef);
760                     }
761                 }
762             }
763         }
764     }
765
766     /**
767      * Create Type for specified type definition.
768      *
769      * @param basePackageName string with name of package to which the module belongs
770      * @param module string with the name of the module for to which the <code>typedef</code> belongs
771      * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
772      *                (usually generated TO)
773      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
774      *         <code>null</code> value if <code>basePackageName</code> or
775      *         <code>modulName</code> or <code>typedef</code> or Q name of
776      *         <code>typedef</code> equals <code>null</code>
777      */
778     private Type typedefToGeneratedType(final String basePackageName, final Module module,
779             final TypeDefinition<?> typedef) {
780         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
781
782         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
783         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
784             return null;
785         }
786
787         final String typedefName = typedef.getQName().getLocalName();
788
789         final GeneratedType returnType;
790         if (baseTypedef.getBaseType() != null) {
791             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
792                 module.getName());
793         } else if (baseTypedef instanceof UnionTypeDefinition) {
794             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
795                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
796                 (UnionTypeDefinition) baseTypedef, typedef);
797             genTOBuilder.setTypedef(true);
798             genTOBuilder.setIsUnion(true);
799             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
800             makeSerializable(genTOBuilder);
801             returnType = genTOBuilder.build();
802
803             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
804             // so we are placing the builder alongside the union.
805             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
806                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
807             unionBuilder.setIsUnionBuilder(true);
808             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
809             method.setReturnType(returnType);
810             method.addParameter(Types.STRING, "defaultValue");
811             method.setAccessModifier(AccessModifier.PUBLIC);
812             method.setStatic(true);
813             additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
814         } else if (baseTypedef instanceof EnumTypeDefinition) {
815             // enums are automatically Serializable
816             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
817             // TODO units for typedef enum
818             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
819         } else if (baseTypedef instanceof BitsTypeDefinition) {
820             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
821                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
822                 (BitsTypeDefinition) baseTypedef, module.getName());
823             genTOBuilder.setTypedef(true);
824             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
825             makeSerializable(genTOBuilder);
826             returnType = genTOBuilder.build();
827         } else {
828             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
829             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
830         }
831         if (returnType != null) {
832             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
833                     genTypeDefsContextMap.get(module.getName());
834             final Optional<Revision> moduleRevision = module.getRevision();
835             Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
836             if (typeMap != null) {
837                 if (typeMap.isEmpty()) {
838                     typeMap = new HashMap<>(4);
839                     modulesByDate.put(moduleRevision, typeMap);
840                 }
841                 typeMap.put(typedefName, returnType);
842             }
843             return returnType;
844         }
845         return null;
846     }
847
848     /**
849      * Wraps base YANG type to generated TO.
850      *
851      * @param basePackageName string with name of package to which the module belongs
852      * @param typedef type definition which is converted to the TO
853      * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
854      * @return generated transfer object which represent<code>javaType</code>
855      */
856     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
857             final Type javaType, final String moduleName) {
858         requireNonNull(javaType, "javaType cannot be null");
859
860         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
861         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
862         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
863         genPropBuilder.setReturnType(javaType);
864
865         genTOBuilder.addEqualsIdentity(genPropBuilder);
866         genTOBuilder.addHashIdentity(genPropBuilder);
867         genTOBuilder.addToStringProperty(genPropBuilder);
868         genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
869         if (typedef.getStatus() == Status.DEPRECATED) {
870             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
871         }
872         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
873             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
874         }
875         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
876         genTOBuilder.setTypedef(true);
877         makeSerializable(genTOBuilder);
878         return genTOBuilder.build();
879     }
880
881     /**
882      * Converts output list of generated TO builders to one TO builder (first
883      * from list) which contains the remaining builders as its enclosing TO.
884      *
885      * @param typeName new type identifier
886      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
887      * @return generated TO builder with the list of enclosed generated TO builders
888      */
889     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
890             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
891         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
892             parentNode);
893         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
894
895         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
896         builders.forEach(resultTOBuilder::addEnclosingTransferObject);
897         return resultTOBuilder;
898     }
899
900     /**
901      * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
902      * <code>typedef</code> is added to generated TO builder as property.
903      *
904      * @param typeName new type identifier
905      * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
906      * @return generated TO builder which represents <code>typedef</code>
907      * @throws NullPointerException
908      *             <ul>
909      *             <li>if <code>basePackageName</code> is null</li>
910      *             <li>if <code>typedef</code> is null</li>
911      *             <li>if Qname of <code>typedef</code> is null</li>
912      *             </ul>
913      */
914     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
915             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
916         requireNonNull(typedef, "Type Definition cannot be NULL!");
917         requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
918
919         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
920         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
921         final Module module = findParentModule(schemaContext, parentNode);
922
923         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
924         unionGenTOBuilder.setIsUnion(true);
925         unionGenTOBuilder.setSchemaPath(typedef.getPath());
926         unionGenTOBuilder.setModuleName(module.getName());
927         unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
928         addCodegenInformation(unionGenTOBuilder, typedef);
929         generatedTOBuilders.add(unionGenTOBuilder);
930
931         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
932         // also negation information and hence guarantees uniqueness.
933         final Map<String, String> expressions = new HashMap<>();
934         for (TypeDefinition<?> unionType : unionTypes) {
935             final String unionTypeName = unionType.getQName().getLocalName();
936
937             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
938             // do not follow type encapsulation -- we use the general case for that.
939             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
940                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
941             } else if (unionType instanceof UnionTypeDefinition) {
942                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
943                     (UnionTypeDefinition) unionType, parentNode));
944             } else if (unionType instanceof EnumTypeDefinition) {
945                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
946                         unionTypeName, unionGenTOBuilder);
947                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
948             } else {
949                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
950                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
951             }
952         }
953         addStringRegExAsConstant(unionGenTOBuilder, expressions);
954
955         storeGenTO(typedef, unionGenTOBuilder, parentNode);
956
957         return generatedTOBuilders;
958     }
959
960     /**
961      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
962      *
963      * <p>
964      * In this case the new generated TO is created for union subtype (recursive call of method
965      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
966      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
967      * created property which type is equal to new generated TO.
968      *
969      * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
970      * @param basePackageName string with the name of the module package
971      * @param unionSubtype type definition which represents union subtype
972      * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
973      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
974      */
975     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
976             final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
977         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
978             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
979         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
980             newTOBuilderName, unionSubtype, parentNode);
981
982         final GeneratedPropertyBuilder propertyBuilder;
983         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
984             newTOBuilderName.simpleName()));
985         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
986         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
987         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
988
989         return subUnionGenTOBUilders;
990     }
991
992     /**
993      * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
994      * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
995      * the base type is used for the property creation.
996      *
997      * @param parentUnionGenTOBuilder generated TO builder in which new property is created
998      * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
999      * @param expressions list of strings with the regular expressions
1000      * @param parentNode parent Schema Node for Extended Subtype
1001      */
1002     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1003             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1004         final String unionTypeName = unionSubtype.getQName().getLocalName();
1005         final Type genTO = findGenTO(unionTypeName, unionSubtype);
1006         if (genTO != null) {
1007             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1008             return;
1009         }
1010
1011         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1012         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1013             final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
1014                 BindingGeneratorUtil.getRestrictions(unionSubtype));
1015             if (javaType != null) {
1016                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1017             }
1018         } else if (baseType instanceof LeafrefTypeDefinition) {
1019             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1020             boolean typeExist = false;
1021             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1022                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1023                 if (origType != null && javaType != null && javaType == origType) {
1024                     typeExist = true;
1025                     break;
1026                 }
1027             }
1028             if (!typeExist && javaType != null) {
1029                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1030                     javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1031             }
1032         }
1033         if (baseType instanceof StringTypeDefinition) {
1034             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1035         }
1036     }
1037
1038     /**
1039      * Searches for generated TO for <code>searchedTypeDef</code> type  definition
1040      * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1041      *
1042      * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1043      * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1044      */
1045     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1046         final Module typeModule = findParentModule(schemaContext, parentNode);
1047         if (typeModule != null && typeModule.getName() != null) {
1048             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
1049                 typeModule.getName());
1050             final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
1051             if (genTOs != null) {
1052                 return genTOs.get(searchedTypeName);
1053             }
1054         }
1055         return null;
1056     }
1057
1058     /**
1059      * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1060      * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1061      *
1062      * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1063      * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1064      */
1065     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1066             final SchemaNode parentNode) {
1067         if (!(newTypeDef instanceof UnionTypeDefinition)) {
1068             final Module parentModule = findParentModule(schemaContext, parentNode);
1069             if (parentModule != null && parentModule.getName() != null) {
1070                 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
1071                     parentModule.getName());
1072                 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
1073                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1074             }
1075         }
1076     }
1077
1078     /**
1079      * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1080      * to <code>unonGenTransObject</code>.
1081      *
1082      * @param unionGenTransObject generated TO to which should be property added
1083      * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1084      * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1085      */
1086     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1087             final String propertyName) {
1088         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1089             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1090                     .addProperty(BindingMapping.getPropertyName(propertyName));
1091             propBuilder.setReturnType(type);
1092
1093             unionGenTransObject.addEqualsIdentity(propBuilder);
1094             unionGenTransObject.addHashIdentity(propBuilder);
1095             unionGenTransObject.addToStringProperty(propBuilder);
1096         }
1097     }
1098
1099     /**
1100      * Converts <code>typedef</code> to the generated TO builder.
1101      *
1102      * @param basePackageName string with name of package to which the module belongs
1103      * @param typedef type definition from which is the generated TO builder created
1104      * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1105      */
1106     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1107             final TypeDefinition<?> typedef, final String moduleName) {
1108         JavaTypeName name = renames.get(typedef);
1109         if (name == null) {
1110             name = JavaTypeName.create(
1111                 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1112                 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1113         }
1114
1115         final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1116         newType.setSchemaPath(typedef.getPath());
1117         newType.setModuleName(moduleName);
1118         addCodegenInformation(newType, typedef);
1119         return newType;
1120     }
1121
1122     /**
1123      * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1124      * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1125      * properties.
1126      *
1127      * @param typeName new type identifier
1128      * @param typeDef type definition from which is the generated TO builder created
1129      * @return generated TO builder which represents <code>typeDef</code>
1130      * @throws IllegalArgumentException
1131      *             <ul>
1132      *             <li>if <code>typeDef</code> equals null</li>
1133      *             <li>if <code>basePackageName</code> equals null</li>
1134      *             </ul>
1135      */
1136     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1137             final BitsTypeDefinition typeDef, final String moduleName) {
1138         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1139         genTOBuilder.setSchemaPath(typeDef.getPath());
1140         genTOBuilder.setModuleName(moduleName);
1141         genTOBuilder.setBaseType(typeDef);
1142         genTOBuilder.addImplementsType(TYPE_OBJECT);
1143         addCodegenInformation(genTOBuilder, typeDef);
1144
1145         for (Bit bit : typeDef.getBits()) {
1146             final String name = bit.getName();
1147             GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
1148                 BindingMapping.getPropertyName(name));
1149             genPropertyBuilder.setReadOnly(true);
1150             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1151
1152             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1153             genTOBuilder.addHashIdentity(genPropertyBuilder);
1154             genTOBuilder.addToStringProperty(genPropertyBuilder);
1155         }
1156
1157         return genTOBuilder;
1158     }
1159
1160     /**
1161      * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1162      * the <code>regularExpressions</code>.
1163      *
1164      * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1165      * @param expressions list of string which represent regular expressions
1166      */
1167     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1168             final Map<String, String> expressions) {
1169         if (!expressions.isEmpty()) {
1170             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1171                 ImmutableMap.copyOf(expressions));
1172         }
1173     }
1174
1175     /**
1176      * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1177      * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1178      *
1179      * <p>
1180      * It is assumed that <code>innerExtendedType</code> is already present in
1181      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1182      * for the returning generated TO.
1183      *
1184      * @param typedef Type Definition
1185      * @param innerExtendedType extended type which is part of some other extended type
1186      * @param basePackageName string with the package name of the module
1187      * @param moduleName Module Name
1188      * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1189      * @throws IllegalArgumentException
1190      *             <ul>
1191      *             <li>if <code>extendedType</code> equals null</li>
1192      *             <li>if <code>basePackageName</code> equals null</li>
1193      *             <li>if <code>typedefName</code> equals null</li>
1194      *             </ul>
1195      */
1196     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1197             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1198         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1199         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1200
1201         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1202             BindingMapping.getClassName(typedef.getQName())));
1203         genTOBuilder.setSchemaPath(typedef.getPath());
1204         genTOBuilder.setModuleName(moduleName);
1205         genTOBuilder.setTypedef(true);
1206         addCodegenInformation(genTOBuilder, typedef);
1207
1208         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1209         genTOBuilder.setRestrictions(r);
1210         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1211
1212         if (typedef.getStatus() == Status.DEPRECATED) {
1213             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
1214         }
1215
1216         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1217             genTOBuilder.setIsUnion(true);
1218         }
1219
1220         Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
1221         Map<String, GeneratedType> typeMap = null;
1222         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1223         if (parentModule != null) {
1224             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1225             typeMap = modulesByDate.get(parentModule.getRevision());
1226         }
1227
1228         if (typeMap != null) {
1229             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1230             final GeneratedType type = typeMap.get(innerTypeDef);
1231             if (type instanceof GeneratedTransferObject) {
1232                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1233             }
1234         }
1235         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1236         makeSerializable(genTOBuilder);
1237
1238         return genTOBuilder.build();
1239     }
1240
1241     /**
1242      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1243      * property.
1244      *
1245      * @param gto transfer object which needs to be made serializable
1246      */
1247     private static void makeSerializable(final GeneratedTOBuilder gto) {
1248         gto.addImplementsType(Types.serializableType());
1249         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1250         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1251         gto.setSUID(prop);
1252     }
1253
1254     /**
1255      * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1256      * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1257      * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1258      * type definitions are in the list behind all type definitions on which depends.
1259      *
1260      * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1261      * @return list of type definitions sorted according their each other dependencies (type definitions which are
1262      *              dependent on other type definitions are in list behind them).
1263      */
1264     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1265             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1266         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1267
1268         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1269         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1270             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1271             List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1272                 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1273             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1274         }
1275
1276         // SortedMap guarantees order corresponding to keys in ascending order
1277         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1278             sortedTypeDefinition.addAll(v);
1279         }
1280
1281         return sortedTypeDefinition;
1282     }
1283
1284     /**
1285      * Returns how many immersion is necessary to get from the type definition to the base type.
1286      *
1287      * @param typeDefinition type definition for which is depth sought.
1288      * @return number of immersions which are necessary to get from the type definition to the base type
1289      */
1290     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1291         // FIXME: rewrite this in a non-recursive manner
1292         if (typeDefinition == null) {
1293             return 1;
1294         }
1295         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1296         if (baseType == null) {
1297             return 1;
1298         }
1299
1300         int depth = 1;
1301         if (baseType.getBaseType() != null) {
1302             depth = depth + getTypeDefinitionDepth(baseType);
1303         } else if (baseType instanceof UnionTypeDefinition) {
1304             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1305             int maxChildDepth = 0;
1306             int childDepth = 1;
1307             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1308                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1309                 if (childDepth > maxChildDepth) {
1310                     maxChildDepth = childDepth;
1311                 }
1312             }
1313             return maxChildDepth;
1314         }
1315         return depth;
1316     }
1317
1318     /**
1319      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1320      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1321      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1322      *
1323      * @param name string with name of augmented node
1324      * @return string with the number suffix incremented by one (or 1 is added)
1325      */
1326     private static String provideAvailableNameForGenTOBuilder(final String name) {
1327         final int dollar = name.indexOf('$');
1328         if (dollar == -1) {
1329             return name + "$1";
1330         }
1331
1332         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1333         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1334         return name.substring(0, dollar + 1) + newSuffix;
1335     }
1336
1337     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1338         if (!Strings.isNullOrEmpty(units)) {
1339             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1340             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1341             prop.setReturnType(Types.STRING);
1342             to.addToStringProperty(prop);
1343         }
1344     }
1345
1346     private Module getParentModule(final SchemaNode node) {
1347         final QName qname = node.getPath().getPathFromRoot().iterator().next();
1348         return schemaContext.findModule(qname.getModule()).orElse(null);
1349     }
1350 }