15e3f4b7442d1e4be1cd57d4f02d1ed89987f616
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / AbstractTypeGenerator.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o.  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.generator.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
30 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
31 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
32 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
33 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
34 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
35 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
36 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
37 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
38 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
39 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
40 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
41 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
42 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
43 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
44 import static org.opendaylight.mdsal.binding.model.util.Types.mapTypeFor;
45 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveBooleanType;
46 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveIntType;
47 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
48 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
49 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
50 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
51 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
52
53 import com.google.common.base.Splitter;
54 import com.google.common.collect.Iterables;
55 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
56 import java.util.AbstractMap.SimpleImmutableEntry;
57 import java.util.ArrayList;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.Comparator;
61 import java.util.HashMap;
62 import java.util.HashSet;
63 import java.util.Iterator;
64 import java.util.List;
65 import java.util.Map;
66 import java.util.Optional;
67 import org.eclipse.jdt.annotation.NonNull;
68 import org.eclipse.jdt.annotation.Nullable;
69 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
70 import org.opendaylight.mdsal.binding.model.api.Constant;
71 import org.opendaylight.mdsal.binding.model.api.DefaultType;
72 import org.opendaylight.mdsal.binding.model.api.Enumeration;
73 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
74 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
75 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
76 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
77 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
78 import org.opendaylight.mdsal.binding.model.api.Restrictions;
79 import org.opendaylight.mdsal.binding.model.api.Type;
80 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
81 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
82 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
83 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
84 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
85 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
86 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
87 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
88 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
89 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
90 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
91 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
92 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
93 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
94 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
95 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
96 import org.opendaylight.yangtools.yang.common.QName;
97 import org.opendaylight.yangtools.yang.common.QNameModule;
98 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
99 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
100 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
103 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
104 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
105 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
106 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
107 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
108 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
109 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
110 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
111 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
112 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
113 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
114 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
115 import org.opendaylight.yangtools.yang.model.api.InputSchemaNode;
116 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
117 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
118 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
119 import org.opendaylight.yangtools.yang.model.api.Module;
120 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
121 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
122 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
123 import org.opendaylight.yangtools.yang.model.api.OutputSchemaNode;
124 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
125 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
126 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
127 import org.opendaylight.yangtools.yang.model.api.Status;
128 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
129 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
130 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
131 import org.opendaylight.yangtools.yang.model.api.UsesNode;
132 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
133 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
134 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
135 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
136 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
137 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
138 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
139 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
140 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
141 import org.slf4j.Logger;
142 import org.slf4j.LoggerFactory;
143
144 abstract class AbstractTypeGenerator {
145     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeGenerator.class);
146     private static final Splitter COLON_SPLITTER = Splitter.on(':');
147     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
148     private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
149     private static final JavaTypeName CHECK_RETURN_VALUE_ANNOTATION =
150             // Do not refer to annotation class, as it may not be available at runtime
151             JavaTypeName.create("edu.umd.cs.findbugs.annotations", "CheckReturnValue");
152     private static final Type LIST_STRING_TYPE = listTypeFor(BaseYangTypes.STRING_TYPE);
153
154     /**
155      * Comparator based on augment target path.
156      */
157     private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
158         final Iterator<QName> thisIt = o1.getTargetPath().getNodeIdentifiers().iterator();
159         final Iterator<QName> otherIt = o2.getTargetPath().getNodeIdentifiers().iterator();
160
161         while (thisIt.hasNext()) {
162             if (!otherIt.hasNext()) {
163                 return 1;
164             }
165
166             final int comp = thisIt.next().compareTo(otherIt.next());
167             if (comp != 0) {
168                 return comp;
169             }
170         }
171
172         return otherIt.hasNext() ? -1 : 0;
173     };
174
175     /**
176      * Constant with the concrete name of identifier.
177      */
178     private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
179
180     /**
181      * Constant with the concrete name of namespace.
182      */
183     private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
184
185     private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
186
187     /**
188      * Outer key represents the package name. Outer value represents map of all builders in the same package. Inner key
189      * represents the schema node name (in JAVA class/interface name format). Inner value represents instance of builder
190      * for schema node specified in key part.
191      */
192     private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
193
194     /**
195      * Provide methods for converting YANG types to JAVA types.
196      */
197     private final AbstractTypeProvider typeProvider;
198
199     /**
200      * Holds reference to schema context to resolve data of augmented element when creating augmentation builder.
201      */
202     private final @NonNull EffectiveModelContext schemaContext;
203
204     /**
205      * Holds renamed elements.
206      */
207     private final Map<SchemaNode, JavaTypeName> renames;
208
209     AbstractTypeGenerator(final EffectiveModelContext context, final AbstractTypeProvider typeProvider,
210             final Map<SchemaNode, JavaTypeName> renames) {
211         this.schemaContext = requireNonNull(context);
212         this.typeProvider = requireNonNull(typeProvider);
213         this.renames = requireNonNull(renames);
214
215         final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
216         final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
217         for (final Module contextModule : contextModules) {
218             contexts.add(moduleToGenTypes(contextModule));
219         }
220
221         contexts.forEach(this::allAugmentsToGenTypes);
222     }
223
224     final @NonNull EffectiveModelContext schemaContext() {
225         return schemaContext;
226     }
227
228     final Collection<ModuleContext> moduleContexts() {
229         return genCtx.values();
230     }
231
232     final ModuleContext moduleContext(final QNameModule module) {
233         return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
234     }
235
236     final AbstractTypeProvider typeProvider() {
237         return typeProvider;
238     }
239
240     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
241
242     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
243
244     abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
245             Collection<? extends SchemaNode> nodes);
246
247     abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
248
249     abstract void addRpcMethodComment(TypeMemberBuilder<?> genType, RpcDefinition node);
250
251     private ModuleContext moduleToGenTypes(final Module module) {
252         final ModuleContext context = new ModuleContext(module);
253         genCtx.put(module.getQNameModule(), context);
254         allTypeDefinitionsToGenTypes(context);
255         groupingsToGenTypes(context, module.getGroupings());
256         allIdentitiesToGenTypes(context);
257
258         if (!module.getChildNodes().isEmpty()) {
259             final GeneratedTypeBuilder moduleType = moduleToDataType(context);
260             context.addModuleNode(moduleType);
261             resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes(), false);
262         }
263
264         // Resolve RPCs and notifications only after we have created instantiated tree
265         rpcMethodsToGenType(context);
266         notificationsToGenType(context);
267         return context;
268     }
269
270     /**
271      * Converts all extended type definitions of module to the list of
272      * <code>Type</code> objects.
273      *
274      * @param module
275      *            module from which is obtained set of type definitions
276      * @throws IllegalArgumentException
277      *             <ul>
278      *             <li>if module is null</li>
279      *             <li>if name of module is null</li>
280      *             </ul>
281      * @throws IllegalStateException
282      *             if set of type definitions from module is null
283      */
284     private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
285         final Module module = context.module();
286         checkArgument(module.getName() != null, "Module name cannot be NULL.");
287
288         for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
289             if (typedef != null) {
290                 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,  typedef);
291                 if (type != null) {
292                     context.addTypedefType(typedef, type);
293                     context.addTypeToSchema(type,typedef);
294                 }
295             }
296         }
297     }
298
299     private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type baseInterface,
300             final DataSchemaNode node, final boolean inGrouping) {
301         if (node.isAugmenting() || node.isAddedByUses()) {
302             return null;
303         }
304         final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
305         addConcreteInterfaceMethods(genType);
306         annotateDeprecatedIfNecessary(node, genType);
307
308         final Module module = context.module();
309         genType.setModuleName(module.getName());
310         addCodegenInformation(genType, module, node);
311         genType.setSchemaPath(node.getPath());
312         if (node instanceof DataNodeContainer) {
313             context.addChildNodeType(node, genType);
314             groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
315             processUsesAugments((DataNodeContainer) node, context, inGrouping);
316         }
317         return genType;
318     }
319
320     private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
321             final Type baseInterface, final ContainerSchemaNode node, final boolean inGrouping) {
322         final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
323         if (genType != null) {
324             constructGetter(parent, genType, node);
325             resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
326             actionsToGenType(context, genType, node, null, inGrouping);
327             notificationsToGenType(context, genType, node, null, inGrouping);
328         }
329     }
330
331     private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
332             final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
333         final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
334         if (genType != null) {
335             final List<String> listKeys = listKeys(node);
336             final GeneratedTOBuilder keyTypeBuilder;
337             if (!listKeys.isEmpty()) {
338                 keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
339                     packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
340                     BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
341                         .addImplementsType(identifier(genType));
342                 genType.addImplementsType(identifiable(keyTypeBuilder));
343             } else {
344                 keyTypeBuilder = null;
345             }
346
347             // Decide whether to generate a List or a Map
348             final ParameterizedType listType;
349             if (keyTypeBuilder != null && !node.isUserOrdered()) {
350                 listType = mapTypeFor(keyTypeBuilder, genType);
351             } else {
352                 listType = listTypeFor(genType);
353             }
354
355             constructGetter(parent, listType, node).setMechanics(ValueMechanics.NULLIFY_EMPTY);
356             constructNonnull(parent, listType, node);
357
358             actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
359             notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
360
361             for (final DataSchemaNode schemaNode : node.getChildNodes()) {
362                 if (!schemaNode.isAugmenting()) {
363                     addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
364                 }
365             }
366
367             // serialVersionUID
368             if (keyTypeBuilder != null) {
369                 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
370                 prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
371                 keyTypeBuilder.setSUID(prop);
372             }
373
374             typeBuildersToGenTypes(context, genType, keyTypeBuilder);
375         }
376     }
377
378     private void processUsesAugments(final DataNodeContainer node, final ModuleContext context,
379             final boolean inGrouping) {
380         for (final UsesNode usesNode : node.getUses()) {
381             for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
382                 usesAugmentationToGenTypes(context, augment, usesNode, node, inGrouping);
383                 processUsesAugments(augment, context, inGrouping);
384             }
385         }
386     }
387
388     /**
389      * Converts all <b>augmentation</b> of the module to the list
390      * <code>Type</code> objects.
391      *
392      * @param module
393      *            module from which is obtained list of all augmentation objects
394      *            to iterate over them
395      * @throws IllegalArgumentException
396      *             <ul>
397      *             <li>if the module is null</li>
398      *             <li>if the name of module is null</li>
399      *             </ul>
400      * @throws IllegalStateException
401      *             if set of augmentations from module is null
402      */
403     private void allAugmentsToGenTypes(final ModuleContext context) {
404         final Module module = context.module();
405         checkArgument(module != null, "Module reference cannot be NULL.");
406         checkArgument(module.getName() != null, "Module name cannot be NULL.");
407         checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
408
409         for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
410             augmentationToGenTypes(context, augment);
411         }
412     }
413
414     /**
415      * Returns list of <code>AugmentationSchema</code> objects. The objects are
416      * sorted according to the length of their target path from the shortest to
417      * the longest.
418      *
419      * @param module
420      *            module from which is obtained list of all augmentation objects
421      * @return list of sorted <code>AugmentationSchema</code> objects obtained
422      *         from <code>module</code>
423      * @throws IllegalArgumentException
424      *             if module is null
425      * @throws IllegalStateException
426      *             if set of module augmentations is null
427      */
428     private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
429         checkArgument(module != null, "Module reference cannot be NULL.");
430         checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
431
432         final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(module.getAugmentations());
433         sortedAugmentations.sort(AUGMENT_COMP);
434
435         return sortedAugmentations;
436     }
437
438     /**
439      * Create GeneratedTypeBuilder object from module argument.
440      *
441      * @param module
442      *            Module object from which builder will be created
443      * @return <code>GeneratedTypeBuilder</code> which is internal
444      *         representation of the module
445      * @throws IllegalArgumentException
446      *             if module is null
447      */
448     private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
449         final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
450         final Module module = context.module();
451         addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
452         moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
453         // if we have more than 2 top level uses statements we need to define getImplementedInterface() on the
454         // top level DataRoot object
455         if (module.getUses().size() > 1) {
456             narrowImplementedInterface(moduleDataTypeBuilder);
457         }
458
459         addCodegenInformation(moduleDataTypeBuilder, module);
460         return moduleDataTypeBuilder;
461     }
462
463     private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
464             final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
465         for (final ActionDefinition action : parentSchema.getActions()) {
466             if (action.isAugmenting()) {
467                 continue;
468             }
469
470             final GeneratedType input;
471             final GeneratedType output;
472             if (action.isAddedByUses()) {
473                 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
474                 // Original definition may live in a different module, make sure we account for that
475                 final ModuleContext origContext = moduleContext(
476                     orig.getPath().getPathFromRoot().iterator().next().getModule());
477                 input = context.addAliasType(origContext, orig.getInput(), action.getInput());
478                 output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
479             } else {
480                 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
481                 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
482             }
483
484             if (!(parentSchema instanceof GroupingDefinition)) {
485                 // Parent is a non-grouping, hence we need to establish an Action instance, which can be completely
486                 // identified by an InstanceIdentifier. We do not generate Actions for groupings as they are inexact,
487                 // and do not capture an actual instantiation.
488                 final QName qname = action.getQName();
489                 final GeneratedTypeBuilder builder = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
490                     packageNameForGeneratedType(context.modulePackageName(), action.getPath()),
491                     BindingMapping.getClassName(qname)));
492                 qnameConstant(builder, context.moduleInfoType(), qname.getLocalName());
493
494                 annotateDeprecatedIfNecessary(action, builder);
495                 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
496                         : action(parent, input, output));
497
498                 addCodegenInformation(builder, context.module(), action);
499                 context.addChildNodeType(action, builder);
500             }
501         }
502     }
503
504     private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
505         final QName qname = action.getQName();
506         for (UsesNode uses : parent.getUses()) {
507             final GroupingDefinition grp = uses.getSourceGrouping();
508             // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
509             // namespace
510             final Optional<ActionDefinition> found = grp.findAction(qname.bindTo(grp.getQName().getModule()));
511             if (found.isPresent()) {
512                 final ActionDefinition result = found.get();
513                 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
514             }
515         }
516
517         return Optional.empty();
518     }
519
520     private GeneratedType actionContainer(final ModuleContext context, final Type baseInterface,
521             final ContainerLike schema, final boolean inGrouping) {
522         final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, schema, inGrouping);
523         resolveDataSchemaNodes(context, genType, genType, schema.getChildNodes(), inGrouping);
524         return genType.build();
525     }
526
527     /**
528      * Converts all <b>RPCs</b> input and output substatements of the module
529      * to the list of <code>Type</code> objects. In addition are to containers
530      * and lists which belong to input or output also part of returning list.
531      *
532      * @param module
533      *            module from which is obtained set of all rpc objects to
534      *            iterate over them
535      * @throws IllegalArgumentException
536      *             <ul>
537      *             <li>if the module is null</li>
538      *             <li>if the name of module is null</li>
539      *             </ul>
540      * @throws IllegalStateException
541      *             if set of rpcs from module is null
542      */
543     private void rpcMethodsToGenType(final ModuleContext context) {
544         final Module module = context.module();
545         checkArgument(module.getName() != null, "Module name cannot be NULL.");
546         final Collection<? extends RpcDefinition> rpcDefinitions = module.getRpcs();
547         checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
548         if (rpcDefinitions.isEmpty()) {
549             return;
550         }
551
552         final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
553         interfaceBuilder.addImplementsType(RPC_SERVICE);
554
555         addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
556
557         for (final RpcDefinition rpc : rpcDefinitions) {
558             if (rpc != null) {
559                 final String rpcName = BindingMapping.getClassName(rpc.getQName());
560                 final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
561                 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
562
563                 // Do not refer to annotation class, as it may not be available at runtime
564                 method.addAnnotation(CHECK_RETURN_VALUE_ANNOTATION);
565                 addRpcMethodComment(method, rpc);
566                 method.addParameter(
567                     createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput()), RPC_INPUT), "input");
568                 method.setReturnType(listenableFutureTypeFor(
569                     rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput()), RPC_OUTPUT))));
570             }
571         }
572
573         context.addTopLevelNodeType(interfaceBuilder);
574     }
575
576     private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
577             final ContainerLike schema, final Type type) {
578         processUsesAugments(schema, context, false);
579         final GeneratedTypeBuilder outType = addRawInterfaceDefinition(context,
580             JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
581             schema);
582         addImplementedInterfaceFromUses(schema, outType);
583         outType.addImplementsType(type);
584         outType.addImplementsType(augmentable(outType));
585         addConcreteInterfaceMethods(outType);
586         annotateDeprecatedIfNecessary(rpc, outType);
587         resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
588         context.addChildNodeType(schema, outType);
589         return outType.build();
590     }
591
592     /**
593      * Converts all <b>notifications</b> of the module to the list of
594      * <code>Type</code> objects. In addition are to this list added containers
595      * and lists which are part of this notification.
596      *
597      * @param module
598      *            module from which is obtained set of all notification objects
599      *            to iterate over them
600      * @throws IllegalArgumentException
601      *             <ul>
602      *             <li>if the module equals null</li>
603      *             <li>if the name of module equals null</li>
604      *             </ul>
605      * @throws IllegalStateException
606      *             if set of notifications from module is null
607      */
608     private void notificationsToGenType(final ModuleContext context) {
609         final Module module = context.module();
610         checkArgument(module.getName() != null, "Module name cannot be NULL.");
611         final Collection<? extends NotificationDefinition> notifications = module.getNotifications();
612         if (notifications.isEmpty()) {
613             return;
614         }
615
616         final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
617         listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
618
619         for (final NotificationDefinition notification : notifications) {
620             if (notification != null) {
621                 processUsesAugments(notification, context, false);
622
623                 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
624                     context.modulePackageName(), notification, DATA_OBJECT, context);
625                 addConcreteInterfaceMethods(notificationInterface);
626                 annotateDeprecatedIfNecessary(notification, notificationInterface);
627                 notificationInterface.addImplementsType(NOTIFICATION);
628                 context.addChildNodeType(notification, notificationInterface);
629
630                 // Notification object
631                 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
632                     notification.getChildNodes(), false);
633
634                 final MethodSignatureBuilder notificationMethod =
635                     listenerInterface.addMethod("on" + notificationInterface.getName())
636                     .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
637                     .setReturnType(primitiveVoidType());
638
639                 annotateDeprecatedIfNecessary(notification, notificationMethod);
640                 if (notification.getStatus().equals(Status.OBSOLETE)) {
641                     notificationMethod.setDefault(true);
642                 }
643                 addComment(notificationMethod, notification);
644             }
645         }
646
647         addCodegenInformation(listenerInterface, module, "notifications", notifications);
648         context.addTopLevelNodeType(listenerInterface);
649     }
650
651     private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
652             final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
653             final boolean inGrouping) {
654         final Collection<? extends NotificationDefinition> notifications = parentSchema.getNotifications();
655         if (notifications.isEmpty()) {
656             return;
657         }
658
659         for (NotificationDefinition notif : notifications) {
660             if (notif.isAugmenting()) {
661                 continue;
662             }
663             if (parentSchema instanceof GroupingDefinition) {
664                 // Notifications cannot be really established, as they lack instantiation context, which would be
665                 // completely described by an InstanceIdentifier -- hence we cannot create a binding class
666                 continue;
667             }
668
669             processUsesAugments(notif, context, false);
670
671             final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
672                 packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
673             addConcreteInterfaceMethods(notifInterface);
674             annotateDeprecatedIfNecessary(notif, notifInterface);
675
676             notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
677                     : instanceNotification(notifInterface, parent));
678             context.addChildNodeType(notif, notifInterface);
679
680             // Notification object
681             resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
682         }
683     }
684
685     /**
686      * Converts all <b>identities</b> of the module to the list of
687      * <code>Type</code> objects.
688      *
689      * @param module
690      *            module from which is obtained set of all identity objects to
691      *            iterate over them
692      * @param schemaContext
693      *            schema context only used as input parameter for method
694      *            {@link BindingGeneratorImpl#identityToGenType}
695      *
696      */
697     private void allIdentitiesToGenTypes(final ModuleContext context) {
698         final Collection<? extends IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
699
700         if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
701             for (final IdentitySchemaNode identity : schemaIdentities) {
702                 identityToGenType(context, identity);
703             }
704         }
705     }
706
707     /**
708      * Converts the <b>identity</b> object to GeneratedType. Firstly it is
709      * created transport object builder. If identity contains base identity then
710      * reference to base identity is added to superior identity as its extend.
711      * If identity doesn't contain base identity then only reference to abstract
712      * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
713      * BaseIdentity} is added
714      *
715      * @param module
716      *            current module
717      * @param basePackageName
718      *            string contains the module package name
719      * @param identity
720      *            IdentitySchemaNode which contains data about identity
721      */
722     private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
723         if (identity == null) {
724             return;
725         }
726
727         JavaTypeName name = renames.get(identity);
728         if (name == null) {
729             name = JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
730                 BindingMapping.getClassName(identity.getQName()));
731         }
732
733         final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(name);
734         final Collection<? extends IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
735         if (!baseIdentities.isEmpty()) {
736             for (IdentitySchemaNode baseIdentity : baseIdentities) {
737                 JavaTypeName base = renames.get(baseIdentity);
738                 if (base == null) {
739                     final QName qname = baseIdentity.getQName();
740                     base = JavaTypeName.create(BindingMapping.getRootPackageName(qname.getModule()),
741                         BindingMapping.getClassName(qname));
742                 }
743
744                 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(base).build();
745                 newType.addImplementsType(gto);
746             }
747         } else {
748             newType.addImplementsType(BASE_IDENTITY);
749         }
750
751         final Module module = context.module();
752         addCodegenInformation(newType, module, identity);
753         newType.setModuleName(module.getName());
754         newType.setSchemaPath(identity.getPath());
755
756         qnameConstant(newType, context.moduleInfoType(), identity.getQName().getLocalName());
757
758         context.addIdentityType(identity, newType);
759     }
760
761     private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
762             final JavaTypeName yangModuleInfo, final String localName) {
763         return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
764             new SimpleImmutableEntry<>(yangModuleInfo, localName));
765     }
766
767     /**
768      * Converts all <b>groupings</b> of the module to the list of
769      * <code>Type</code> objects. Firstly are groupings sorted according mutual
770      * dependencies. At least dependent (independent) groupings are in the list
771      * saved at first positions. For every grouping the record is added to map
772      * {@link ModuleContext#groupings allGroupings}
773      *
774      * @param module
775      *            current module
776      * @param groupings
777      *            collection of groupings from which types will be generated
778      *
779      */
780     private void groupingsToGenTypes(final ModuleContext context,
781             final Collection<? extends GroupingDefinition> groupings) {
782         for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
783             // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
784             // node of grouping is resolved to the method.
785             final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
786             narrowImplementedInterface(genType);
787             annotateDeprecatedIfNecessary(grouping, genType);
788             context.addGroupingType(grouping, genType);
789             resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
790             groupingsToGenTypes(context, grouping.getGroupings());
791             processUsesAugments(grouping, context, true);
792             actionsToGenType(context, genType, grouping, null, true);
793             notificationsToGenType(context, genType, grouping, null, true);
794         }
795     }
796
797     /**
798      * Adds enumeration builder created from <code>enumTypeDef</code> to <code>typeBuilder</code>. Each
799      * <code>enumTypeDef</code> item is added to builder with its name and value.
800      *
801      * @param enumTypeDef EnumTypeDefinition contains enum data
802      * @param enumName string contains name which will be assigned to enumeration builder
803      * @param typeBuilder GeneratedTypeBuilder to which will be enum builder assigned
804      * @param module Module in which type should be generated
805      * @return enumeration builder which contains data from <code>enumTypeDef</code>
806      */
807     private Enumeration resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
808             final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
809         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
810         typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
811         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
812         final Enumeration ret = enumBuilder.toInstance(typeBuilder);
813         context.addTypeToSchema(ret, enumTypeDef);
814         context.addInnerTypedefType(enumTypeDef.getPath(), ret);
815         return ret;
816     }
817
818     /**
819      * Generates type builder for <code>module</code>.
820      *
821      * @param module Module which is source of package name for generated type builder
822      * @param postfix string which is added to the module class name representation as suffix
823      * @return instance of GeneratedTypeBuilder which represents <code>module</code>.
824      * @throws IllegalArgumentException if <code>module</code> is null
825      */
826     private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
827         final Module module = context.module();
828         final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
829         final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
830             JavaTypeName.create(context.modulePackageName(), moduleName));
831
832         moduleBuilder.setModuleName(moduleName);
833         addCodegenInformation(moduleBuilder, module);
834         return moduleBuilder;
835     }
836
837     /**
838      * Converts <code>augSchema</code> to list of <code>Type</code> which contains generated type for augmentation.
839      * In addition there are also generated types for all containers, list and choices which are child of
840      * <code>augSchema</code> node or a generated types for cases are added if augmented node is choice.
841      *
842      * @param augmentPackageName string with the name of the package to which the augmentation belongs
843      * @param augSchema AugmentationSchema which is contains data about augmentation (target path, childs...)
844      * @param module current module
845      * @throws IllegalArgumentException
846      *             <ul>
847      *             <li>if <code>augmentPackageName</code> equals null</li>
848      *             <li>if <code>augSchema</code> equals null</li>
849      *             </ul>
850      * @throws IllegalStateException
851      *             if augment target path is null
852      */
853     private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
854         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
855         checkState(augSchema.getTargetPath() != null,
856                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
857
858         processUsesAugments(augSchema, context, false);
859         final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
860         SchemaNode targetSchemaNode = null;
861
862         // FIXME: can we use findDataSchemaNode() instead?
863         targetSchemaNode = findDataSchemaNode(schemaContext, targetPath.getNodeIdentifiers());
864         if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
865             if (targetSchemaNode instanceof DerivableSchemaNode) {
866                 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
867             }
868             if (targetSchemaNode == null) {
869                 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
870                         + " in module " + context.module().getName());
871             }
872         }
873         if (targetSchemaNode == null) {
874             throw new IllegalArgumentException("augment target not found: " + targetPath);
875         }
876
877         if (targetSchemaNode instanceof ChoiceSchemaNode) {
878             final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
879             checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
880             generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
881                 augSchema.getChildNodes(), null, false);
882             return;
883         }
884
885         final JavaTypeName targetName;
886         if (targetSchemaNode instanceof CaseSchemaNode) {
887             final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
888             checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
889             targetName = builder.getIdentifier();
890         } else {
891             final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
892             if (builder == null) {
893                 targetName = findAliasByPath(targetSchemaNode.getPath());
894                 checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
895             } else {
896                 targetName = builder.getIdentifier();
897             }
898         }
899
900         addRawAugmentGenTypeDefinition(context, DefaultType.of(targetName), augSchema, false);
901     }
902
903     private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
904             final UsesNode usesNode, final DataNodeContainer usesNodeParent, final boolean inGrouping) {
905         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
906         checkState(augSchema.getTargetPath() != null,
907                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
908
909         processUsesAugments(augSchema, context, inGrouping);
910         final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
911         final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
912         if (targetSchemaNode == null) {
913             throw new IllegalArgumentException("augment target not found: " + targetPath);
914         }
915
916         GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
917         if (targetTypeBuilder == null) {
918             targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
919         }
920         if (targetTypeBuilder == null) {
921             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
922         }
923
924         if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
925             if (usesNodeParent instanceof SchemaNode) {
926                 addRawAugmentGenTypeDefinition(context,
927                     packageNameForAugmentedGeneratedType(context.modulePackageName(),
928                         ((SchemaNode) usesNodeParent).getPath()),
929                     targetTypeBuilder.build(), augSchema, inGrouping);
930             } else {
931                 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema, inGrouping);
932             }
933         } else {
934             generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
935                 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent, inGrouping);
936         }
937     }
938
939     /**
940      * Convenient method to find node added by uses statement.
941      *
942      * @param targetPath node path
943      * @param parentUsesNode parent of uses node
944      * @return node from its original location in grouping
945      */
946     private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaNodeIdentifier targetPath,
947             final UsesNode parentUsesNode) {
948         SchemaNode result = parentUsesNode.getSourceGrouping();
949         for (final QName node : targetPath.getNodeIdentifiers()) {
950             // FIXME: this dispatch is rather ugly, we probably want to refactor it a bit
951             if (result instanceof DataNodeContainer) {
952                 final QName resultNode = node.bindTo(result.getQName().getModule());
953
954                 SchemaNode found = ((DataNodeContainer) result).getDataChildByName(resultNode);
955                 if (found == null) {
956                     if (result instanceof ActionNodeContainer) {
957                         found = ((ActionNodeContainer) result).findAction(resultNode).orElse(null);
958                     }
959                     if (found == null && result instanceof NotificationNodeContainer) {
960                         found = ((NotificationNodeContainer) result).findNotification(resultNode).orElse(null);
961                     }
962                 }
963                 result = found;
964             } else if (result instanceof ChoiceSchemaNode) {
965                 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
966             } else if (result instanceof ActionDefinition) {
967                 final ActionDefinition action = (ActionDefinition) result;
968                 final QName resultNode = node.bindTo(result.getQName().getModule());
969
970                 final InputSchemaNode input = action.getInput();
971                 final OutputSchemaNode output = action.getOutput();
972                 if (resultNode.equals(input.getQName())) {
973                     result = input;
974                 } else if (resultNode.equals(output.getQName())) {
975                     result = output;
976                 } else {
977                     result = null;
978                 }
979             } else if (result != null) {
980                 throw new IllegalStateException("Cannot handle " + result);
981             }
982         }
983         if (result == null) {
984             return null;
985         }
986
987         if (result instanceof DerivableSchemaNode) {
988             DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
989             Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
990             if (castedResult.isAddedByUses() && originalNode.isPresent()) {
991                 result = originalNode.get();
992             }
993         }
994
995         if (result instanceof DataSchemaNode) {
996             DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
997             if (resultDataSchemaNode.isAddedByUses()) {
998                 // The original node is required, but we have only the copy of
999                 // the original node.
1000                 // Maybe this indicates a bug in Yang parser.
1001                 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
1002             }
1003
1004             return resultDataSchemaNode;
1005         }
1006
1007         throw new IllegalStateException(
1008             "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
1009                     + parentUsesNode);
1010     }
1011
1012     /**
1013      * Returns a generated type builder for an augmentation. The name of the type builder is equal to the name
1014      * of augmented node with serial number as suffix.
1015      *
1016      * @param context current module
1017      * @param augmentPackageName string with contains the package name to which the augment belongs
1018      * @param basePackageName string with the package name to which the augmented node belongs
1019      * @param targetTypeRef target type
1020      * @param augSchema augmentation schema which contains data about the child nodes and uses of augment
1021      * @return generated type builder for augment
1022      */
1023     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
1024             final String augmentPackageName, final Type targetTypeRef,
1025             final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1026         Map<String, GeneratedTypeBuilder> augmentBuilders =
1027             genTypeBuilders.computeIfAbsent(augmentPackageName, k -> new HashMap<>());
1028         final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
1029
1030         String augTypeName;
1031         if (augIdentifier != null) {
1032             augTypeName = BindingMapping.getClassName(augIdentifier);
1033         } else {
1034             augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
1035         }
1036
1037         final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
1038             JavaTypeName.create(augmentPackageName, augTypeName));
1039
1040         augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
1041         addConcreteInterfaceMethods(augTypeBuilder);
1042
1043         annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
1044         addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
1045
1046         augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
1047         actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1048         notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
1049
1050         augmentBuilders.put(augTypeName, augTypeBuilder);
1051
1052         if (!augSchema.getChildNodes().isEmpty()) {
1053             context.addTypeToAugmentation(augTypeBuilder, augSchema);
1054         }
1055
1056         context.addAugmentType(augTypeBuilder);
1057         return augTypeBuilder;
1058     }
1059
1060     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
1061             final AugmentationSchemaNode augSchema, final boolean inGrouping) {
1062         return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema,
1063             inGrouping);
1064     }
1065
1066     private static String getAugmentIdentifier(final Collection<? extends UnknownSchemaNode> unknownSchemaNodes) {
1067         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1068             final QName nodeType = unknownSchemaNode.getNodeType();
1069             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1070                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1071                 return unknownSchemaNode.getNodeParameter();
1072             }
1073         }
1074         return null;
1075     }
1076
1077     /**
1078      * Returns first unique name for the augment generated type builder. The generated type builder name for augment
1079      * consists from name of augmented node and serial number of its augmentation.
1080      *
1081      * @param builders map of builders which were created in the package to which the augmentation belongs
1082      * @param genTypeName string with name of augmented node
1083      * @return string with unique name for augmentation builder
1084      */
1085     private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1086         int index = 1;
1087         if (builders != null) {
1088             while (builders.containsKey(genTypeName + index)) {
1089                 index = index + 1;
1090             }
1091         }
1092         return genTypeName + index;
1093     }
1094
1095     /**
1096      * Adds the methods to <code>typeBuilder</code> which represent subnodes of node for which <code>typeBuilder</code>
1097      * was created. The subnodes aren't mapped to the methods if they are part of grouping or augment (in this case are
1098      * already part of them).
1099      *
1100      * @param module current module
1101      * @param parent generated type builder which represents any node. The subnodes of this node are added
1102      *               to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1103      *               container, choice.
1104      * @param childOf parent type
1105      * @param schemaNodes set of data schema nodes which are the children of the node for which
1106      *                    <code>typeBuilder</code> was created
1107      * @return generated type builder which is the same builder as input parameter. The getter methods (representing
1108      *         child nodes) could be added to it.
1109      */
1110     private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1111             final @Nullable Type childOf, final Iterable<? extends DataSchemaNode> schemaNodes,
1112             final boolean inGrouping) {
1113         if (schemaNodes != null && parent != null) {
1114             final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1115             for (final DataSchemaNode schemaNode : schemaNodes) {
1116                 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1117                     addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface, inGrouping);
1118                 }
1119             }
1120         }
1121         return parent;
1122     }
1123
1124     /**
1125      * Adds the methods to <code>typeBuilder</code> what represents subnodes of node for which <code>typeBuilder</code>
1126      * was created.
1127      *
1128      * @param module current module
1129      * @param typeBuilder generated type builder which represents any node. The subnodes of this node are added
1130      *                    to the <code>typeBuilder</code> as methods. The subnode can be of type leaf, leaf-list, list,
1131      *                    container, choice.
1132      * @param childOf parent type
1133      * @param schemaNodes set of data schema nodes which are the children of the node for which <code>typeBuilder</code>
1134      *                    was created
1135      * @return generated type builder which is the same object as the input parameter <code>typeBuilder</code>.
1136      *         The getter method could be added to it.
1137      */
1138     private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1139             final GeneratedTypeBuilder typeBuilder, final Iterable<? extends DataSchemaNode> schemaNodes,
1140             final boolean inGrouping) {
1141         if (schemaNodes != null && typeBuilder != null) {
1142             final Type baseInterface = childOf(typeBuilder);
1143             for (final DataSchemaNode schemaNode : schemaNodes) {
1144                 if (!schemaNode.isAugmenting()) {
1145                     addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface, inGrouping);
1146                 }
1147             }
1148         }
1149         return typeBuilder;
1150     }
1151
1152     /**
1153      * Adds to <code>typeBuilder</code> a method which is derived from <code>schemaNode</code>.
1154      *
1155      * @param node data schema node which is added to <code>typeBuilder</code> as a method
1156      * @param typeBuilder generated type builder to which is <code>schemaNode</code> added as a method.
1157      * @param childOf parent type
1158      * @param module current module
1159      */
1160     private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1161             final GeneratedTypeBuilder typeBuilder, final Type baseInterface, final boolean inGrouping) {
1162         if (node != null && typeBuilder != null) {
1163             if (node instanceof LeafSchemaNode) {
1164                 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context, inGrouping);
1165             } else if (node instanceof LeafListSchemaNode) {
1166                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context, inGrouping);
1167             } else if (node instanceof ContainerSchemaNode) {
1168                 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node, inGrouping);
1169             } else if (node instanceof ListSchemaNode) {
1170                 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node, inGrouping);
1171             } else if (node instanceof ChoiceSchemaNode) {
1172                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node, inGrouping);
1173             } else if (node instanceof AnyxmlSchemaNode || node instanceof AnydataSchemaNode) {
1174                 opaqueToGeneratedType(context, typeBuilder, node);
1175             } else {
1176                 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1177                         typeBuilder.getFullyQualifiedName());
1178             }
1179         }
1180     }
1181
1182     /**
1183      * Converts <code>choiceNode</code> to the list of generated types for choice and its cases. The package names
1184      * for choice and for its cases are created as concatenation of the module package (<code>basePackageName</code>)
1185      * and names of all parents node.
1186      *
1187      * @param context current module
1188      * @param basePackageName string with the module package name
1189      * @param parent parent type
1190      * @param choiceNode choice node which is mapped to generated type. Also child nodes - cases are mapped to generated
1191      *                   types.
1192      * @throws IllegalArgumentException
1193      *             <ul>
1194      *             <li>if <code>basePackageName</code> is null</li>
1195      *             <li>if <code>choiceNode</code> is null</li>
1196      *             </ul>
1197      */
1198     private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1199             final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1200         if (!choiceNode.isAddedByUses()) {
1201             final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(context,
1202                 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1203                 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1204             choiceTypeBuilder.addImplementsType(choiceIn(parent));
1205             annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
1206             context.addChildNodeType(choiceNode, choiceTypeBuilder);
1207
1208             final GeneratedType choiceType = choiceTypeBuilder.build();
1209             generateTypesFromChoiceCases(context, choiceType, choiceNode, inGrouping);
1210
1211             constructGetter(parent, choiceType, choiceNode);
1212         }
1213     }
1214
1215     private void opaqueToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1216             final DataSchemaNode anyNode) {
1217         if (!anyNode.isAddedByUses()) {
1218             final GeneratedTypeBuilder anyxmlTypeBuilder = addRawInterfaceDefinition(context,
1219                 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), anyNode.getPath()),
1220                 BindingMapping.getClassName(anyNode.getQName())), anyNode);
1221             anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
1222             defaultImplementedInterace(anyxmlTypeBuilder);
1223             annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
1224             context.addChildNodeType(anyNode, anyxmlTypeBuilder);
1225
1226             constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
1227         }
1228     }
1229
1230     /**
1231      * Converts <code>caseNodes</code> set to list of corresponding generated types. For every <i>case</i> which is not
1232      * added through augment or <i>uses</i> is created generated type builder. The package names for the builder is
1233      * created as concatenation of the module package and names of all parents nodes of the concrete <i>case</i>. There
1234      * is also relation "<i>implements type</i>" between every case builder and <i>choice</i> type
1235      *
1236      * @param context current module context
1237      * @param refChoiceType type which represents superior <i>case</i>
1238      * @param choiceNode choice case node which is mapped to generated type
1239      * @throws IllegalArgumentException
1240      *             <ul>
1241      *             <li>if <code>refChoiceType</code> equals null</li>
1242      *             <li>if <code>caseNodes</code> equals null</li>
1243      *             </ul>
1244      */
1245     private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1246             final ChoiceSchemaNode choiceNode, final boolean inGrouping) {
1247         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1248         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1249
1250         for (final CaseSchemaNode caseNode : choiceNode.getCases()) {
1251             if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1252                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1253                 caseTypeBuilder.addImplementsType(refChoiceType);
1254                 addConcreteInterfaceMethods(caseTypeBuilder);
1255                 annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
1256                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1257                 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1258                 final Iterable<? extends DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1259                 if (caseChildNodes != null) {
1260                     final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1261
1262                     if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1263                         SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1264
1265                         if (parent instanceof AugmentationSchemaNode) {
1266                             final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1267                             final SchemaNodeIdentifier targetPath = augSchema.getTargetPath();
1268                             // FIXME: can we use findDataSchemaNode?
1269                             SchemaNode targetSchemaNode = findNodeInSchemaContext(schemaContext,
1270                                 targetPath.getNodeIdentifiers());
1271                             if (targetSchemaNode instanceof DataSchemaNode
1272                                     && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1273                                 if (targetSchemaNode instanceof DerivableSchemaNode) {
1274                                     targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1275                                             .orElse(null);
1276                                 }
1277                                 if (targetSchemaNode == null) {
1278                                     throw new IllegalStateException(
1279                                             "Failed to find target node from grouping for augmentation " + augSchema
1280                                                     + " in module " + context.module().getName());
1281                                 }
1282                             }
1283                             parent = targetSchemaNode;
1284                         }
1285
1286                         checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1287                         Type childOfType = findChildNodeByPath(parent.getPath());
1288                         if (childOfType == null) {
1289                             childOfType = findGroupingByPath(parent.getPath());
1290                         }
1291                         resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes, inGrouping);
1292                     } else {
1293                         resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes,
1294                             inGrouping);
1295                     }
1296                 }
1297             }
1298             processUsesAugments(caseNode, context, inGrouping);
1299         }
1300     }
1301
1302     /**
1303      * Generates list of generated types for all the cases of a choice which are added to the choice through
1304      * the augment.
1305      *
1306      * @param module current module
1307      * @param basePackageName string contains name of package to which augment belongs. If an augmented choice is
1308      *                        from an other package (pcg1) than an augmenting choice (pcg2) then case's
1309      *                        of the augmenting choice will belong to pcg2.
1310      * @param targetType Type which represents target choice
1311      * @param targetNode node which represents target choice
1312      * @param augmentedNodes set of choice case nodes for which is checked if are/are not added to choice through
1313      *                       augmentation
1314      * @throws IllegalArgumentException
1315      *             <ul>
1316      *             <li>if <code>basePackageName</code> is null</li>
1317      *             <li>if <code>targetType</code> is null</li>
1318      *             <li>if <code>augmentedNodes</code> is null</li>
1319      *             </ul>
1320      */
1321     // FIXME: nullness rules need to untangled in this method
1322     @SuppressFBWarnings("NP_NULL_ON_SOME_PATH")
1323     private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1324             final Type targetType, final ChoiceSchemaNode targetNode,
1325             final Iterable<? extends DataSchemaNode> augmentedNodes,
1326             final DataNodeContainer usesNodeParent, final boolean inGrouping) {
1327         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1328         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1329
1330         for (final DataSchemaNode caseNode : augmentedNodes) {
1331             if (caseNode != null) {
1332                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1333                 caseTypeBuilder.addImplementsType(targetType);
1334                 addConcreteInterfaceMethods(caseTypeBuilder);
1335
1336                 CaseSchemaNode node = null;
1337                 final String caseLocalName = caseNode.getQName().getLocalName();
1338                 if (caseNode instanceof CaseSchemaNode) {
1339                     node = (CaseSchemaNode) caseNode;
1340                 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1341                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
1342                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1343                         if (dataSchemaNode instanceof ChoiceSchemaNode
1344                                 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1345                             node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1346                             break;
1347                         }
1348                     }
1349                 } else {
1350                     node = findNamedCase(targetNode, caseLocalName);
1351                 }
1352                 final Iterable<? extends DataSchemaNode> childNodes = node.getChildNodes();
1353                 if (childNodes != null) {
1354                     resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes,
1355                         inGrouping);
1356                 }
1357                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1358                 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1359             }
1360         }
1361     }
1362
1363     private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1364         final SchemaPath nodePath = targetNode.getPath();
1365         final SchemaPath parentSp = nodePath.getParent();
1366         if (parentSp.getParent() == null) {
1367             return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1368         }
1369
1370         final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1371         GeneratedTypeBuilder childOfType = null;
1372         if (parent instanceof CaseSchemaNode) {
1373             childOfType = findCaseByPath(parent.getPath());
1374         } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1375             childOfType = findChildNodeByPath(parent.getPath());
1376         } else if (parent instanceof GroupingDefinition) {
1377             childOfType = findGroupingByPath(parent.getPath());
1378         }
1379
1380         if (childOfType == null) {
1381             throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1382         }
1383
1384         return childOfType;
1385     }
1386
1387     private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1388         final List<? extends CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1389         return cases.isEmpty() ? null : cases.get(0);
1390     }
1391
1392     private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1393         // New parser with encapsulated type
1394         if (leaf.getPath().equals(type.getPath())) {
1395             return true;
1396         }
1397
1398         // Embedded type definition with new parser. Also takes care of the old parser with bits
1399         if (leaf.getPath().equals(type.getPath().getParent())) {
1400             return true;
1401         }
1402
1403         return false;
1404     }
1405
1406     private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1407             final List<PatternConstraint> patternConstraints) {
1408         if (!patternConstraints.isEmpty()) {
1409             final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1410                 .append(BindingMapping.getPropertyName(leafName));
1411             typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1412                 typeProvider.resolveRegExpressions(patternConstraints));
1413         }
1414     }
1415
1416     /**
1417      * Converts <code>leaf</code> to the getter method which is added to <code>typeBuilder</code>.
1418      *
1419      * @param typeBuilder generated type builder to which is added getter method as <code>leaf</code> mapping
1420      * @param leaf leaf schema node which is mapped as getter method which is added to <code>typeBuilder</code>
1421      * @param module Module in which type was defined
1422      * @return boolean value
1423      *         <ul>
1424      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1425      *         null</li>
1426      *         <li>true - in other cases</li>
1427      *         </ul>
1428      */
1429     private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1430             final ModuleContext context, final boolean inGrouping) {
1431         if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1432             return null;
1433         }
1434
1435         final Module parentModule = findParentModule(schemaContext, leaf);
1436         Type returnType = null;
1437
1438         final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1439         if (isInnerType(leaf, typeDef)) {
1440             if (typeDef instanceof EnumTypeDefinition) {
1441                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1442                 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(), typeBuilder, context);
1443                 typeProvider.putReferencedType(leaf.getPath(), returnType);
1444             } else if (typeDef instanceof UnionTypeDefinition) {
1445                 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1446                 returnType = addTOToTypeBuilder(unionDef, typeBuilder, leaf, parentModule);
1447                 // Store the inner type within the union so that we can find the reference for it
1448                 context.addInnerTypedefType(typeDef.getPath(), returnType);
1449             } else if (typeDef instanceof BitsTypeDefinition) {
1450                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1451                     parentModule);
1452                 if (genTOBuilder != null) {
1453                     returnType = genTOBuilder.build();
1454                 }
1455             } else {
1456                 // It is constrained version of already declared type (inner declared type exists, only for special
1457                 // cases (Enum, Union, Bits), which were already checked.
1458                 // In order to get proper class we need to look up closest derived type and apply restrictions from leaf
1459                 // type
1460                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1461                 final TypeDefinition<?> baseOrDeclaredType = getBaseOrDeclaredType(typeDef);
1462                 // we need to try to lookup an already generated type in case the leafref is targetting a generated type
1463                 if (baseOrDeclaredType instanceof LeafrefTypeDefinition) {
1464                     final SchemaNode leafrefTarget =
1465                             typeProvider.getTargetForLeafref((LeafrefTypeDefinition) baseOrDeclaredType, leaf);
1466                     if (leafrefTarget instanceof TypedDataSchemaNode) {
1467                         returnType = context.getInnerType(((TypedDataSchemaNode) leafrefTarget).getType().getPath());
1468                     }
1469                 }
1470                 if (returnType == null) {
1471                     returnType = typeProvider.javaTypeForSchemaDefinitionType(baseOrDeclaredType, leaf,
1472                             restrictions, inGrouping);
1473                 }
1474
1475                 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1476             }
1477         } else {
1478             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1479             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions, inGrouping);
1480             addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1481         }
1482
1483         if (returnType == null) {
1484             return null;
1485         }
1486
1487         if (typeDef instanceof EnumTypeDefinition) {
1488             typeProvider.putReferencedType(leaf.getPath(), returnType);
1489         }
1490
1491         final MethodSignatureBuilder getter = constructGetter(typeBuilder,  returnType, leaf);
1492         processContextRefExtension(leaf, getter, parentModule);
1493         return returnType;
1494     }
1495
1496     private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1497         // Returns DerivedType in case of new parser.
1498         final TypeDefinition<?> baseType = typeDef.getBaseType();
1499         return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1500     }
1501
1502     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1503             final Module module) {
1504         for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1505             final QName nodeType = node.getNodeType();
1506             if ("context-reference".equals(nodeType.getLocalName())) {
1507                 final String nodeParam = node.getNodeParameter();
1508                 IdentitySchemaNode identity = null;
1509                 String basePackageName = null;
1510                 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1511                 final Iterator<String> iterator = splittedElement.iterator();
1512                 final int length = Iterables.size(splittedElement);
1513                 if (length == 1) {
1514                     identity = findIdentityByName(module.getIdentities(), iterator.next());
1515                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1516                 } else if (length == 2) {
1517                     final String prefix = iterator.next();
1518                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1519                     if (dependentModule == null) {
1520                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1521                                 + prefix);
1522                     }
1523                     identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1524                     basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1525                 } else {
1526                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1527                             + nodeParam);
1528                 }
1529                 if (identity == null) {
1530                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1531                             + nodeParam);
1532                 }
1533
1534                 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1535                 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1536                 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1537                 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1538             }
1539         }
1540     }
1541
1542     private static IdentitySchemaNode findIdentityByName(final Collection<? extends IdentitySchemaNode> identities,
1543             final String name) {
1544         for (final IdentitySchemaNode id : identities) {
1545             if (id.getQName().getLocalName().equals(name)) {
1546                 return id;
1547             }
1548         }
1549         return null;
1550     }
1551
1552     private Module findModuleFromImports(final Collection<? extends ModuleImport> imports, final String prefix) {
1553         for (final ModuleImport imp : imports) {
1554             if (imp.getPrefix().equals(prefix)) {
1555                 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1556             }
1557         }
1558         return null;
1559     }
1560
1561     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1562             final boolean isReadOnly) {
1563         if (leaf != null && toBuilder != null) {
1564             Type returnType;
1565             final TypeDefinition<?> typeDef = CompatUtils.compatType(leaf);
1566             if (typeDef instanceof UnionTypeDefinition) {
1567                 // GeneratedType for this type definition should have be already created
1568                 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1569                 returnType = mc.getTypedefs().get(typeDef.getPath());
1570                 if (returnType == null) {
1571                     // This may still be an inner type, try to find it
1572                     returnType = mc.getInnerType(typeDef.getPath());
1573                 }
1574             } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1575                 // Annonymous enumeration (already generated, since it is inherited via uses).
1576                 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1577                 QName qname = originalLeaf.getQName();
1578                 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1579             } else {
1580                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1581             }
1582             return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1583         }
1584         return false;
1585     }
1586
1587     /**
1588      * Converts <code>leaf</code> schema node to property of generated TO builder.
1589      *
1590      * @param toBuilder generated TO builder to which is <code>leaf</code> added as property
1591      * @param leaf leaf schema node which is added to <code>toBuilder</code> as property
1592      * @param returnType property type
1593      * @param isReadOnly boolean value which says if leaf property is|isn't read only
1594      * @return boolean value
1595      *         <ul>
1596      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1597      *         name equals null or if leaf is added by <i>uses</i>.</li>
1598      *         <li>true - other cases</li>
1599      *         </ul>
1600      */
1601     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1602             final Type returnType, final boolean isReadOnly) {
1603         if (returnType == null) {
1604             return false;
1605         }
1606         final String leafName = leaf.getQName().getLocalName();
1607         final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1608         propBuilder.setReadOnly(isReadOnly);
1609         propBuilder.setReturnType(returnType);
1610         addComment(propBuilder, leaf);
1611
1612         toBuilder.addEqualsIdentity(propBuilder);
1613         toBuilder.addHashIdentity(propBuilder);
1614         toBuilder.addToStringProperty(propBuilder);
1615         return true;
1616     }
1617
1618     /**
1619      * Converts <code>node</code> leaf list schema node to getter method of <code>typeBuilder</code>.
1620      *
1621      * @param typeBuilder generated type builder to which is <code>node</code> added as getter method
1622      * @param node leaf list schema node which is added to <code>typeBuilder</code> as getter method
1623      * @param module module
1624      * @return boolean value
1625      *         <ul>
1626      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
1627      *         nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1628      *         <li>false - other cases</li>
1629      *         </ul>
1630      */
1631     private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1632             final ModuleContext context, final boolean inGrouping) {
1633         if (node == null || typeBuilder == null || node.isAddedByUses()) {
1634             return false;
1635         }
1636
1637         final QName nodeName = node.getQName();
1638
1639         final TypeDefinition<?> typeDef = node.getType();
1640         final Module parentModule = findParentModule(schemaContext, node);
1641
1642         Type returnType = null;
1643         if (typeDef.getBaseType() == null) {
1644             if (typeDef instanceof EnumTypeDefinition) {
1645                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1646                 returnType = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName, typeBuilder, context);
1647                 typeProvider.putReferencedType(node.getPath(), returnType);
1648             } else if (typeDef instanceof UnionTypeDefinition) {
1649                 final UnionTypeDefinition unionDef = (UnionTypeDefinition)typeDef;
1650                 returnType = addTOToTypeBuilder(unionDef, typeBuilder, node, parentModule);
1651             } else if (typeDef instanceof BitsTypeDefinition) {
1652                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1653                     node, parentModule);
1654                 returnType = genTOBuilder.build();
1655             } else {
1656                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1657                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1658                 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1659             }
1660         } else {
1661             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1662             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions, inGrouping);
1663             addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1664         }
1665
1666         constructGetter(typeBuilder, listTypeFor(returnType), node);
1667         return true;
1668     }
1669
1670     private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final UnionTypeDefinition typeDef,
1671             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1672         final GeneratedTOBuilder returnTypeBuilder = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1673         returnTypeBuilder.setIsUnion(true);
1674         addCodegenInformation(returnTypeBuilder, parentModule, typeDef);
1675         returnTypeBuilder.setSchemaPath(typeDef.getPath());
1676         returnTypeBuilder.setModuleName(parentModule.getName());
1677         final GeneratedTransferObject returnType = returnTypeBuilder.build();
1678
1679         genTOBuilder.setTypedef(true);
1680         genTOBuilder.setIsUnion(true);
1681         AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1682
1683         createUnionBuilder(genTOBuilder, typeBuilder, returnType, parentModule);
1684         return returnType;
1685     }
1686
1687     private void createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder,
1688             final GeneratedTransferObject returnType, final Module parentModule) {
1689         // Append enclosing path hierarchy without dots
1690         final StringBuilder sb = new StringBuilder();
1691         genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1692         final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1693             JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1694         unionBuilder.setIsUnionBuilder(true);
1695
1696         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1697         method.setReturnType(returnType);
1698         method.addParameter(STRING, "defaultValue");
1699         method.setAccessModifier(AccessModifier.PUBLIC);
1700         method.setStatic(true);
1701
1702         final GeneratedTransferObject unionBuilderType = unionBuilder.build();
1703         typeProvider.getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilderType);
1704     }
1705
1706     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1707             final SchemaNode schemaNode) {
1708         return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1709     }
1710
1711     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1712             final SchemaNode schemaNode, final Type baseInterface) {
1713         final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1714         return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1715     }
1716
1717     /**
1718      * Instantiates generated type builder with <code>packageName</code> and <code>schemaNode</code>. The new builder
1719      * always implements {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1720      * If <code>schemaNode</code> is instance of GroupingDefinition it also implements
1721      * {@link org.opendaylight.yangtools.yang.binding.Augmentable Augmentable}.<br>
1722      * If <code>schemaNode</code> is instance of
1723      * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer DataNodeContainer} it can also implement nodes
1724      * which are specified in <i>uses</i>.
1725      *
1726      * @param packageName string with the name of the package to which <code>schemaNode</code> belongs.
1727      * @param schemaNode schema node for which is created generated type builder
1728      * @param parent parent type (can be null)
1729      * @return generated type builder <code>schemaNode</code>
1730      */
1731     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1732             final Type baseInterface, final ModuleContext context) {
1733         JavaTypeName name = renames.get(schemaNode);
1734         if (name == null) {
1735             name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1736         }
1737
1738         final GeneratedTypeBuilder it = addRawInterfaceDefinition(context, name, schemaNode);
1739         it.addImplementsType(baseInterface);
1740         if (!(schemaNode instanceof GroupingDefinition)) {
1741             it.addImplementsType(augmentable(it));
1742         }
1743         if (schemaNode instanceof DataNodeContainer) {
1744             final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1745             groupingsToGenTypes(context, containerSchema.getGroupings());
1746             addImplementedInterfaceFromUses(containerSchema, it);
1747         }
1748
1749         return it;
1750     }
1751
1752     /**
1753      * Returns reference to generated type builder for specified <code>schemaNode</code> with <code>packageName</code>.
1754      * Firstly the generated type builder is searched in {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}.
1755      * If it is not found it is created and added to <code>genTypeBuilders</code>.
1756      *
1757      * @param packageName string with the package name to which returning generated type builder belongs
1758      * @param schemaNode schema node which provide data about the schema node name
1759      * @param prefix return type name prefix
1760      * @return generated type builder for <code>schemaNode</code>
1761      * @throws IllegalArgumentException
1762      *             <ul>
1763      *             <li>if <code>schemaNode</code> is null</li>
1764      *             <li>if <code>packageName</code> is null</li>
1765      *             <li>if QName of schema node is null</li>
1766      *             <li>if schemaNode name is null</li>
1767      *             </ul>
1768      */
1769     private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final JavaTypeName identifier,
1770             final SchemaNode schemaNode) {
1771         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1772         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1773         final String schemaNodeName = schemaNode.getQName().getLocalName();
1774         checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1775
1776         // FIXME: Validation of name conflict
1777         final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1778         qnameConstant(newType, context.moduleInfoType(), schemaNode.getQName().getLocalName());
1779
1780         final Module module = context.module();
1781         addCodegenInformation(newType, module, schemaNode);
1782         newType.setSchemaPath(schemaNode.getPath());
1783         newType.setModuleName(module.getName());
1784
1785         final String packageName = identifier.packageName();
1786         final String simpleName = identifier.simpleName();
1787         if (!genTypeBuilders.containsKey(packageName)) {
1788             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1789             builders.put(simpleName, newType);
1790             genTypeBuilders.put(packageName, builders);
1791         } else {
1792             final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1793             if (!builders.containsKey(simpleName)) {
1794                 builders.put(simpleName, newType);
1795             }
1796         }
1797         return newType;
1798     }
1799
1800     /**
1801      * Created a method signature builder as part of <code>interfaceBuilder</code>. The method signature builder is
1802      * created for the getter method of <code>schemaNodeName</code>. Also <code>comment</code>
1803      * and <code>returnType</code> information are added to the builder.
1804      *
1805      * @param interfaceBuilder generated type builder for which the getter method should be created
1806      * @param returnType type which represents the return type of the getter method
1807      * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1808      * @param comment string with comment for the getter method
1809      * @param status status from yang file, for deprecated annotation
1810      * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1811      */
1812     private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1813             final SchemaNode node) {
1814         final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1815             BindingMapping.getGetterMethodName(node.getQName().getLocalName()));
1816         getMethod.setReturnType(returnType);
1817
1818         annotateDeprecatedIfNecessary(node, getMethod);
1819         addComment(getMethod, node);
1820
1821         if (BOOLEAN.equals(returnType)) {
1822             // Construct a default 'isFoo()' method for compatibility
1823             interfaceBuilder.addMethod(BindingMapping.getGetterMethodName(node.getQName().getLocalName(), true))
1824                 .setAccessModifier(AccessModifier.PUBLIC)
1825                 .setDefault(true)
1826                 .setReturnType(BOOLEAN);
1827         }
1828
1829         return getMethod;
1830     }
1831
1832     private static void constructNonnull(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1833             final ListSchemaNode node) {
1834         final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1835             BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
1836         getMethod.setReturnType(returnType).setDefault(true);
1837         annotateDeprecatedIfNecessary(node, getMethod);
1838     }
1839
1840     /**
1841      * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method or to <code>genTOBuilder</code>
1842      * as a property.
1843      *
1844      * @param basePackageName string contains the module package name
1845      * @param schemaNode data schema node which should be added as getter method to <code>typeBuilder</code>
1846      *                   or as a property to <code>genTOBuilder</code> if is part of the list key
1847      * @param typeBuilder generated type builder for the list schema node
1848      * @param genTOBuilder generated TO builder for the list keys
1849      * @param listKeys list of string which contains names of the list keys
1850      * @param module current module
1851      * @throws IllegalArgumentException
1852      *             <ul>
1853      *             <li>if <code>schemaNode</code> equals null</li>
1854      *             <li>if <code>typeBuilder</code> equals null</li>
1855      *             </ul>
1856      */
1857     private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1858             final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1859             final List<String> listKeys, final boolean inGrouping) {
1860         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1861         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1862
1863         if (schemaNode instanceof LeafSchemaNode) {
1864             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1865             final String leafName = leaf.getQName().getLocalName();
1866             Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context, inGrouping);
1867             if (listKeys.contains(leafName)) {
1868                 if (type == null) {
1869                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1870                 } else {
1871                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1872                 }
1873             }
1874         } else if (!schemaNode.isAddedByUses()) {
1875             if (schemaNode instanceof LeafListSchemaNode) {
1876                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context, inGrouping);
1877             } else if (schemaNode instanceof ContainerSchemaNode) {
1878                 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1879                     (ContainerSchemaNode) schemaNode, inGrouping);
1880             } else if (schemaNode instanceof ChoiceSchemaNode) {
1881                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
1882             } else if (schemaNode instanceof ListSchemaNode) {
1883                 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
1884             } else if (schemaNode instanceof AnyxmlSchemaNode || schemaNode instanceof AnydataSchemaNode) {
1885                 opaqueToGeneratedType(context, typeBuilder, schemaNode);
1886             }
1887         }
1888     }
1889
1890     private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1891             final GeneratedTOBuilder genTOBuilder) {
1892         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1893
1894         if (genTOBuilder != null) {
1895             final GeneratedTransferObject genTO = genTOBuilder.build();
1896             // Add Identifiable.getKey() for items
1897             typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1898                 .addAnnotation(OVERRIDE_ANNOTATION);
1899             context.addGeneratedTOBuilder(genTOBuilder);
1900         }
1901     }
1902
1903     /**
1904      * Selects the names of the list keys from <code>list</code> and returns them as the list of the strings.
1905      *
1906      * @param list of string with names of the list keys
1907      * @return list of string which represents names of the list keys. If the <code>list</code> contains no keys then
1908      *         an empty list is returned.
1909      */
1910     private static List<String> listKeys(final ListSchemaNode list) {
1911         final List<QName> keyDefinition = list.getKeyDefinition();
1912         switch (keyDefinition.size()) {
1913             case 0:
1914                 return Collections.emptyList();
1915             case 1:
1916                 return Collections.singletonList(keyDefinition.get(0).getLocalName());
1917             default:
1918                 final List<String> listKeys = new ArrayList<>(keyDefinition.size());
1919                 for (final QName keyDef : keyDefinition) {
1920                     listKeys.add(keyDef.getLocalName());
1921                 }
1922                 return listKeys;
1923         }
1924     }
1925
1926     /**
1927      * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}. If more then one generated TO builder
1928      * is created for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as
1929      * enclosing transfer objects.
1930      *
1931      * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1932      * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1933      * @param leaf string with name for generated TO builder
1934      * @param parentModule parent module
1935      * @return generated TO builder for <code>typeDef</code>
1936      */
1937     private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1938             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1939         final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1940             allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
1941
1942         checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1943         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1944         final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1945         types.forEach(resultTOBuilder::addEnclosingTransferObject);
1946         genTOBuilders.forEach(typeBuilder::addEnclosingTransferObject);
1947
1948         for (GeneratedTOBuilder builder : types) {
1949             if (builder.isUnion()) {
1950                 final GeneratedTransferObject type = builder.build();
1951                 createUnionBuilder(builder, typeBuilder, type, parentModule);
1952             }
1953         }
1954
1955         return createReturnTypeForUnion(resultTOBuilder, typeDef, typeBuilder, parentModule);
1956     }
1957
1958     /**
1959      * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are also added
1960      * to <code>typeBuilder</code> as enclosing transfer object. If more then one generated TO builder is created
1961      * for enclosing then all of the generated TO builders are added to <code>typeBuilder</code> as enclosing transfer
1962      * objects.
1963      *
1964      * @param typeDef type definition which can be of type <code>UnionType</code> or <code>BitsTypeDefinition</code>
1965      * @param typeBuilder generated type builder to which is added generated TO created from <code>typeDef</code>
1966      * @param leaf string with name for generated TO builder
1967      * @param parentModule parent module
1968      * @return generated TO builder for <code>typeDef</code>
1969      */
1970     private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1971             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1972         final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1973             allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
1974         typeBuilder.addEnclosingTransferObject(genTOBuilder);
1975         return genTOBuilder;
1976     }
1977
1978     /**
1979      * Adds the implemented types to type builder. The method passes through the list of <i>uses</i> in
1980      * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding generated type
1981      * from {@link ModuleContext#groupings allGroupings} which is added as <i>implements type</i>
1982      * to <code>builder</code>
1983      *
1984      * @param dataNodeContainer element which contains the list of used YANG groupings
1985      * @param builder builder to which are added implemented types according to <code>dataNodeContainer</code>
1986      * @return generated type builder with all implemented types
1987      */
1988     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1989             final GeneratedTypeBuilder builder) {
1990         for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1991             final GeneratedTypeBuilder genType = findGrouping(usesNode.getSourceGrouping());
1992             if (genType == null) {
1993                 throw new IllegalStateException("Grouping " + usesNode.getSourceGrouping().getQName()
1994                     + " is not resolved for " + builder.getFullyQualifiedName());
1995             }
1996
1997             builder.addImplementsType(genType.build());
1998         }
1999         return builder;
2000     }
2001
2002     private JavaTypeName findAliasByPath(final SchemaPath path) {
2003         for (final ModuleContext ctx : genCtx.values()) {
2004             final JavaTypeName result = ctx.getAlias(path);
2005             if (result != null) {
2006                 return result;
2007             }
2008         }
2009         return null;
2010     }
2011
2012     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2013         for (final ModuleContext ctx : genCtx.values()) {
2014             final GeneratedTypeBuilder result = ctx.getChildNode(path);
2015             if (result != null) {
2016                 return result;
2017             }
2018         }
2019         return null;
2020     }
2021
2022     private GeneratedTypeBuilder findGrouping(final GroupingDefinition grouping) {
2023         for (final ModuleContext ctx : genCtx.values()) {
2024             final GeneratedTypeBuilder result = ctx.getGrouping(grouping.getPath());
2025             if (result != null) {
2026                 return result;
2027             }
2028         }
2029         return null;
2030     }
2031
2032     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2033         for (final ModuleContext ctx : genCtx.values()) {
2034             final GeneratedTypeBuilder result = ctx.getGrouping(path);
2035             if (result != null) {
2036                 return result;
2037             }
2038         }
2039         return null;
2040     }
2041
2042     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2043         for (final ModuleContext ctx : genCtx.values()) {
2044             final GeneratedTypeBuilder result = ctx.getCase(path);
2045             if (result != null) {
2046                 return result;
2047             }
2048         }
2049         return null;
2050     }
2051
2052     private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
2053         // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
2054         return parent.createEnclosed(BindingMapping.getClassName(child), "$");
2055     }
2056
2057     private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
2058         switch (node.getStatus()) {
2059             case DEPRECATED:
2060                 // FIXME: we really want to use a pre-made annotation
2061                 builder.addAnnotation(DEPRECATED_ANNOTATION);
2062                 break;
2063             case OBSOLETE:
2064                 builder.addAnnotation(DEPRECATED_ANNOTATION).addParameter("forRemoval", "true");
2065                 break;
2066             case CURRENT:
2067                 // No-op
2068                 break;
2069             default:
2070                 throw new IllegalStateException("Unhandled status in " + node);
2071         }
2072     }
2073
2074     private static void addConcreteInterfaceMethods(final GeneratedTypeBuilder typeBuilder) {
2075         defaultImplementedInterace(typeBuilder);
2076
2077         typeBuilder.addMethod(BindingMapping.BINDING_HASHCODE_NAME)
2078             .setAccessModifier(AccessModifier.PUBLIC)
2079             .setStatic(true)
2080             .setReturnType(primitiveIntType());
2081         typeBuilder.addMethod(BindingMapping.BINDING_EQUALS_NAME)
2082             .setAccessModifier(AccessModifier.PUBLIC)
2083             .setStatic(true)
2084             .setReturnType(primitiveBooleanType());
2085         typeBuilder.addMethod(BindingMapping.BINDING_TO_STRING_NAME)
2086             .setAccessModifier(AccessModifier.PUBLIC)
2087             .setStatic(true)
2088             .setReturnType(STRING);
2089     }
2090
2091     private static void narrowImplementedInterface(final GeneratedTypeBuilder typeBuilder) {
2092         defineImplementedInterfaceMethod(typeBuilder, wildcardTypeFor(typeBuilder.getIdentifier()));
2093     }
2094
2095     private static void defaultImplementedInterace(final GeneratedTypeBuilder typeBuilder) {
2096         defineImplementedInterfaceMethod(typeBuilder, DefaultType.of(typeBuilder)).setDefault(true);
2097     }
2098
2099     private static MethodSignatureBuilder defineImplementedInterfaceMethod(final GeneratedTypeBuilder typeBuilder,
2100             final Type classType) {
2101         final MethodSignatureBuilder ret = typeBuilder
2102                 .addMethod(BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME)
2103                 .setAccessModifier(AccessModifier.PUBLIC)
2104                 .setReturnType(classType(classType));
2105         ret.addAnnotation(OVERRIDE_ANNOTATION);
2106         return ret;
2107     }
2108 }