Bug 1411 #3 BindingGeneratorImpl decomposition - Leafs
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / impl / AugmentToGenType.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  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
9 package org.opendaylight.mdsal.binding.javav2.generator.impl;
10
11 import com.google.common.annotations.Beta;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import java.util.ArrayList;
15 import java.util.Collections;
16 import java.util.Comparator;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
22 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
23 import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl;
24 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
25 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
26 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
40 import org.opendaylight.yangtools.yang.model.api.UsesNode;
41 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
42
43 @Beta
44 final class AugmentToGenType {
45
46     /**
47      * Comparator based on augment target path.
48      */
49     private static final Comparator<AugmentationSchema> AUGMENT_COMP = (o1, o2) -> {
50         final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
51         final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
52
53         while (thisIt.hasNext()) {
54             if (!otherIt.hasNext()) {
55                 return 1;
56             }
57
58             final int comp = thisIt.next().compareTo(otherIt.next());
59             if (comp != 0) {
60                 return comp;
61             }
62         }
63
64         return otherIt.hasNext() ? -1 : 0;
65     };
66
67     private AugmentToGenType() {
68         throw new UnsupportedOperationException("Utility class");
69     }
70
71     /**
72      * Converts all <b>augmentation</b> of the module to the list
73      * <code>Type</code> objects.
74      *
75      * @param module
76      *            module from which is obtained list of all augmentation objects
77      *            to iterate over them
78      * @param schemaContext
79      * @param genCtx
80      * @param genTypeBuilders
81      *
82      * @throws IllegalArgumentException
83      *             <ul>
84      *             <li>if the module is null</li>
85      *             <li>if the name of module is null</li>
86      *             </ul>
87      * @throws IllegalStateException
88      *             if set of augmentations from module is null
89      */
90     static Map<Module, ModuleContext> generate(final Module module, final SchemaContext schemaContext,
91             final TypeProvider typeProvider, final Map<Module, ModuleContext> genCtx,
92             Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final boolean verboseClassComments) {
93
94         Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
95         Preconditions.checkArgument(module.getName() != null, "Module name cannot be NULL.");
96         Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
97
98         final String basePackageName = BindingMapping.getRootPackageName(module);
99         final List<AugmentationSchema> augmentations = resolveAugmentations(module);
100         Map<Module, ModuleContext> resultCtx = genCtx;
101         for (final AugmentationSchema augment : augmentations) {
102             resultCtx = augmentationToGenTypes(basePackageName, augment, module, schemaContext, verboseClassComments,
103                     resultCtx, genTypeBuilders, typeProvider);
104         }
105         return resultCtx;
106     }
107
108     /**
109      * Returns list of <code>AugmentationSchema</code> objects. The objects are
110      * sorted according to the length of their target path from the shortest to
111      * the longest.
112      *
113      * @param module
114      *            module from which is obtained list of all augmentation objects
115      * @return list of sorted <code>AugmentationSchema</code> objects obtained
116      *         from <code>module</code>
117      * @throws IllegalArgumentException
118      *             if module is null
119      * @throws IllegalStateException
120      *             if set of module augmentations is null
121      */
122     private static List<AugmentationSchema> resolveAugmentations(final Module module) {
123         Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
124         Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
125
126         final Set<AugmentationSchema> augmentations = module.getAugmentations();
127         final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
128         Collections.sort(sortedAugmentations, AUGMENT_COMP);
129
130         return sortedAugmentations;
131     }
132
133     /**
134      * Converts <code>augSchema</code> to list of <code>Type</code> which
135      * contains generated type for augmentation. In addition there are also
136      * generated types for all containers, list and choices which are child of
137      * <code>augSchema</code> node or a generated types for cases are added if
138      * augmented node is choice.
139      *
140      * @param augmentPackageName
141      *            string with the name of the package to which the augmentation
142      *            belongs
143      * @param augSchema
144      *            AugmentationSchema which is contains data about augmentation
145      *            (target path, childs...)
146      * @param module
147      *            current module
148      * @param schemaContext
149      * @param genCtx
150      * @param genTypeBuilders
151      * @throws IllegalArgumentException
152      *             <ul>
153      *             <li>if <code>augmentPackageName</code> equals null</li>
154      *             <li>if <code>augSchema</code> equals null</li>
155      *             </ul>
156      * @throws IllegalStateException
157      *             if augment target path is null
158      * @return
159      */
160     private static Map<Module, ModuleContext> augmentationToGenTypes(final String augmentPackageName, final AugmentationSchema augSchema,
161             final Module module, final SchemaContext schemaContext, final boolean verboseClassComments,
162             Map<Module, ModuleContext> genCtx, Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders,
163             final TypeProvider typeProvider) {
164
165         Map<Module, ModuleContext> generatedCtx;
166         Preconditions.checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
167         Preconditions.checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
168         Preconditions.checkState(augSchema.getTargetPath() != null,
169                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
170
171         generatedCtx = GenHelperUtil.processUsesAugments(schemaContext, augSchema, module, genCtx, genTypeBuilders,
172                 verboseClassComments, typeProvider);
173         final SchemaPath targetPath = augSchema.getTargetPath();
174         SchemaNode targetSchemaNode;
175
176         targetSchemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, targetPath);
177         if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
178             if (targetSchemaNode instanceof DerivableSchemaNode) {
179                 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
180             }
181             if (targetSchemaNode == null) {
182                 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
183                         + " in module " + module.getName());
184             }
185         }
186         if (targetSchemaNode == null) {
187             throw new IllegalArgumentException("augment target not found: " + targetPath);
188         }
189
190         GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
191                 generatedCtx);
192         if (targetTypeBuilder == null) {
193             targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), generatedCtx);
194         }
195         if (targetTypeBuilder == null) {
196             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
197         }
198
199         if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
200             final String packageName = augmentPackageName;
201             final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
202                     targetTypeBuilder.getName());
203             generatedCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType,
204                     augSchema, genTypeBuilders, generatedCtx);
205             return generatedCtx;
206
207         } else {
208             generatedCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, augmentPackageName,
209                     targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(),
210                     null, generatedCtx, verboseClassComments, genTypeBuilders, typeProvider);
211             return generatedCtx;
212         }
213     }
214
215     public static Map<Module, ModuleContext> usesAugmentationToGenTypes(final SchemaContext schemaContext, final String
216                         augmentPackageName, final AugmentationSchema augSchema, final Module module, final UsesNode usesNode, final DataNodeContainer
217                         usesNodeParent, Map<Module, ModuleContext> genCtx,
218                         Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders,
219                         final boolean verboseClassComments, final TypeProvider typeProvider) {
220
221         Map<Module, ModuleContext> generatedCtx;
222         Preconditions.checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
223         Preconditions.checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
224         Preconditions.checkState(augSchema.getTargetPath() != null,
225                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
226
227         generatedCtx = GenHelperUtil.processUsesAugments(schemaContext, augSchema, module, genCtx, genTypeBuilders,
228                 verboseClassComments, typeProvider);
229         final SchemaPath targetPath = augSchema.getTargetPath();
230         final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(schemaContext, targetPath, usesNode);
231         if (targetSchemaNode == null) {
232             throw new IllegalArgumentException("augment target not found: " + targetPath);
233         }
234
235         GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
236                 generatedCtx);
237         if (targetTypeBuilder == null) {
238             targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), generatedCtx);
239         }
240         if (targetTypeBuilder == null) {
241             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
242         }
243
244         if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
245             String packageName = augmentPackageName;
246             if (usesNodeParent instanceof SchemaNode) {
247                 packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(augmentPackageName,
248                         ((SchemaNode) usesNodeParent).getPath());
249             }
250             generatedCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName,
251                     targetTypeBuilder.toInstance(), augSchema, genTypeBuilders, generatedCtx);
252             return generatedCtx;
253         } else {
254             generatedCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, augmentPackageName,
255                     targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(),
256                     usesNodeParent, generatedCtx, verboseClassComments, genTypeBuilders, typeProvider);
257             return generatedCtx;
258         }
259     }
260
261     /**
262      * Convenient method to find node added by uses statement.
263      * @param schemaContext
264      * @param targetPath
265      *            node path
266      * @param parentUsesNode
267      *            parent of uses node
268      * @return node from its original location in grouping
269      */
270     private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaContext schemaContext, final SchemaPath targetPath,
271                                           final UsesNode parentUsesNode) {
272         final SchemaNode targetGrouping = SchemaContextUtil.findNodeInSchemaContext(schemaContext, parentUsesNode
273                 .getGroupingPath()
274                 .getPathFromRoot());
275         if (!(targetGrouping instanceof GroupingDefinition)) {
276             throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
277         }
278
279         final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
280         SchemaNode result = grouping;
281         for (final QName node : targetPath.getPathFromRoot()) {
282             if (result instanceof DataNodeContainer) {
283                 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
284                 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
285             } else if (result instanceof ChoiceSchemaNode) {
286                 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
287             }
288         }
289         if (result == null) {
290             return null;
291         }
292
293         if (result instanceof DerivableSchemaNode) {
294             DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
295             Optional<? extends SchemaNode> originalNode = castedResult
296                     .getOriginal();
297             if (castedResult.isAddedByUses() && originalNode.isPresent()) {
298                 result = originalNode.get();
299             }
300         }
301
302         if (result instanceof DataSchemaNode) {
303             DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
304             if (resultDataSchemaNode.isAddedByUses()) {
305                 // The original node is required, but we have only the copy of
306                 // the original node.
307                 // Maybe this indicates a bug in Yang parser.
308                 throw new IllegalStateException(
309                         "Failed to generate code for augment in "
310                                 + parentUsesNode);
311             } else {
312                 return resultDataSchemaNode;
313             }
314         } else {
315             throw new IllegalStateException(
316                     "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
317                             + parentUsesNode);
318         }
319     }
320
321     /**
322      * Generates list of generated types for all the cases of a choice which are
323      * added to the choice through the augment.
324      *
325      * @param schemaContext
326      * @param module
327      *            current module
328      * @param basePackageName
329      *            string contains name of package to which augment belongs. If
330      *            an augmented choice is from an other package (pcg1) than an
331      *            augmenting choice (pcg2) then case's of the augmenting choice
332      *            will belong to pcg2.
333      * @param targetType
334      *            Type which represents target choice
335      * @param targetNode
336      *            node which represents target choice
337      * @param augmentedNodes
338      *            set of choice case nodes for which is checked if are/aren't
339      *            added to choice through augmentation
340      * @return list of generated types which represents augmented cases of
341      *         choice <code>refChoiceType</code>
342      * @throws IllegalArgumentException
343      *             <ul>
344      *             <li>if <code>basePackageName</code> is null</li>
345      *             <li>if <code>targetType</code> is null</li>
346      *             <li>if <code>augmentedNodes</code> is null</li>
347      *             </ul>
348      */
349     private static Map<Module, ModuleContext> generateTypesFromAugmentedChoiceCases(final SchemaContext schemaContext, final Module module,
350                           final String basePackageName, final Type targetType, final ChoiceSchemaNode targetNode,
351                           final Iterable<DataSchemaNode> augmentedNodes, final DataNodeContainer usesNodeParent,
352                           Map<Module, ModuleContext> genCtx, final boolean verboseClassComments,
353                           Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final TypeProvider typeProvider) {
354         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
355         Preconditions.checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
356         Preconditions.checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
357
358         for (final DataSchemaNode caseNode : augmentedNodes) {
359             if (caseNode != null) {
360                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
361                         caseNode.getPath(), null);
362                 final GeneratedTypeBuilder caseTypeBuilder = GenHelperUtil.addDefaultInterfaceDefinition(packageName,
363                         caseNode, module, genCtx, schemaContext, verboseClassComments, genTypeBuilders);
364                 caseTypeBuilder.addImplementsType(targetType);
365
366                 SchemaNode parent;
367                 final SchemaPath nodeSp = targetNode.getPath();
368                 parent = SchemaContextUtil.findDataSchemaNode(schemaContext, nodeSp.getParent());
369
370                 GeneratedTypeBuilder childOfType = null;
371                 if (parent instanceof Module) {
372                     childOfType = genCtx.get(parent).getModuleNode();
373                 } else if (parent instanceof ChoiceCaseNode) {
374                     childOfType = GenHelperUtil.findCaseByPath(parent.getPath(), genCtx);
375                 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
376                     childOfType = GenHelperUtil.findChildNodeByPath(parent.getPath(), genCtx);
377                 } else if (parent instanceof GroupingDefinition) {
378                     childOfType = GenHelperUtil.findGroupingByPath(parent.getPath(), genCtx);
379                 }
380
381                 if (childOfType == null) {
382                     throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
383                 }
384
385                 ChoiceCaseNode node = null;
386                 final String caseLocalName = caseNode.getQName().getLocalName();
387                 if (caseNode instanceof ChoiceCaseNode) {
388                     node = (ChoiceCaseNode) caseNode;
389                 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
390                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
391                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
392                         if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
393                                 ().getLocalName())) {
394                             node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
395                             break;
396                         }
397                     }
398                 } else {
399                     node = targetNode.getCaseNodeByName(caseLocalName);
400                 }
401                 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
402                 if (childNodes != null) {
403                     GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType,
404                             childNodes, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider);
405                 }
406                 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
407                 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
408             }
409         }
410         return genCtx;
411     }
412 }