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