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