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