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