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