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