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