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