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