2 * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.mdsal.binding.javav2.generator.impl;
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;
20 import java.util.Map.Entry;
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;
46 final class AugmentToGenType {
49 * Comparator based on augment target path.
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();
55 while (thisIt.hasNext()) {
56 if (!otherIt.hasNext()) {
60 final int comp = thisIt.next().compareTo(otherIt.next());
66 return otherIt.hasNext() ? -1 : 0;
70 * Comparator based on augment target path.
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();
76 while (thisIt.hasNext()) {
77 if (!otherIt.hasNext()) {
81 final int comp = thisIt.next().compareTo(otherIt.next());
87 return otherIt.hasNext() ? -1 : 0;
90 private AugmentToGenType() {
91 throw new UnsupportedOperationException("Utility class");
95 * Converts all <b>augmentation</b> of the module to the list
96 * <code>Type</code> objects.
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
107 * @throws IllegalArgumentException
109 * <li>if the module is null</li>
110 * <li>if the name of module is null</li>
112 * @throws IllegalStateException
113 * if set of augmentations from module is null
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) {
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.");
123 final String basePackageName = BindingMapping.getRootPackageName(module);
124 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
125 Map<Module, ModuleContext> resultCtx = genCtx;
127 //let's group augments by target path
128 Map<SchemaPath, List<AugmentationSchema>> augmentationsGrouped =
129 augmentations.stream().collect(Collectors.groupingBy(AugmentationSchema::getTargetPath));
131 List<Map.Entry<SchemaPath, List<AugmentationSchema>>> sortedAugmentationsGrouped =
132 new ArrayList<>(augmentationsGrouped.entrySet());
133 Collections.sort(sortedAugmentationsGrouped, AUGMENTS_COMP);
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);
140 for (AugmentationSchema augSchema : schemaPathAugmentListEntry.getValue()) {
141 GenHelperUtil.processUsesImplements(augSchema, module, schemaContext, genCtx, BindingNamespaceType.Data);
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
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
160 * @throws IllegalStateException
161 * if set of module augmentations is null
163 private static List<AugmentationSchema> resolveAugmentations(final Module module) {
164 Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
165 Preconditions.checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
167 final Set<AugmentationSchema> augmentations = module.getAugmentations();
168 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
169 Collections.sort(sortedAugmentations, AUGMENT_COMP);
171 return sortedAugmentations;
175 * Converts <code>augSchema</code> to list of <code>Type</code> which
176 * contains generated type for augmentation. In addition there are also
177 * generated types for all containers, list and choices which are child of
178 * <code>augSchema</code> node or a generated types for cases are added if
179 * augmented node is choice.
181 * @param basePackageName
182 * string with the name of the package to which the augmentation
184 * @param schemaPathAugmentListEntry
185 * list of AugmentationSchema nodes grouped by target path
186 * @param module current module
187 * @param schemaContext actual schema context
188 * @param verboseClassComments verbosity switch
189 * @param genCtx generated input context
190 * @param genTypeBuilders auxiliary type builders map
191 * @param typeProvider actual type provider instance
192 * @throws IllegalArgumentException
193 * if <code>augmentPackageName</code> equals null
194 * @throws IllegalStateException
195 * if augment target path is null
196 * @return generated context
198 private static Map<Module, ModuleContext> augmentationToGenTypes(final String basePackageName,
199 final Entry<SchemaPath, List<AugmentationSchema>> schemaPathAugmentListEntry, final Module module,
200 final SchemaContext schemaContext, final boolean verboseClassComments,
201 Map<Module, ModuleContext> genCtx, Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders,
202 final TypeProvider typeProvider) {
203 Preconditions.checkArgument(basePackageName != null, "Package Name cannot be NULL.");
204 Preconditions.checkArgument(schemaPathAugmentListEntry != null, "Augmentation List Entry cannot be NULL.");
205 final SchemaPath targetPath = schemaPathAugmentListEntry.getKey();
206 Preconditions.checkState(targetPath != null,
207 "Augmentation List Entry does not contain Target Path (Target Path is NULL).");
209 final List<AugmentationSchema> augmentationSchemaList = schemaPathAugmentListEntry.getValue();
210 Preconditions.checkState(augmentationSchemaList.size() > 0,
211 "Augmentation List cannot be empty.");
213 SchemaNode targetSchemaNode = SchemaContextUtil.findDataSchemaNode(schemaContext, targetPath);
214 if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
215 if (targetSchemaNode instanceof DerivableSchemaNode) {
216 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
218 if (targetSchemaNode == null) {
219 throw new IllegalStateException("Failed to find target node from grouping in augmentation " +
220 schemaPathAugmentListEntry.getValue().get(0)
221 + " in module " + module.getName());
224 if (targetSchemaNode == null) {
225 throw new IllegalArgumentException("augment target not found: " + targetPath);
228 GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
230 if (targetTypeBuilder == null) {
231 targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), genCtx);
233 if (targetTypeBuilder == null) {
234 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
237 final String augmentNamespacePackageName =
238 BindingGeneratorUtil.packageNameForAugmentedGeneratedType(basePackageName, targetPath);
240 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
241 genCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, augmentNamespacePackageName,
242 targetTypeBuilder.toInstance(), schemaPathAugmentListEntry.getValue(), genTypeBuilders, genCtx,
243 schemaContext, verboseClassComments, typeProvider, BindingNamespaceType.Data);
245 genCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, basePackageName,
246 targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode,
247 schemaPathAugmentListEntry.getValue(),
248 null, genCtx, verboseClassComments, genTypeBuilders, typeProvider,
249 BindingNamespaceType.Data);
254 static Map<Module, ModuleContext> usesAugmentationToGenTypes(final SchemaContext schemaContext,
255 final String augmentPackageName, final List<AugmentationSchema> schemaPathAugmentListEntry, final Module module,
256 final UsesNode usesNode, final DataNodeContainer usesNodeParent, Map<Module, ModuleContext> genCtx,
257 Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final boolean verboseClassComments,
258 final TypeProvider typeProvider, final BindingNamespaceType namespaceType) {
260 Preconditions.checkArgument(augmentPackageName != null, "Package Name cannot be NULL.");
261 Preconditions.checkArgument(schemaPathAugmentListEntry != null,
262 "Augmentation Schema List Entry cannot be NULL.");
263 Preconditions.checkState(schemaPathAugmentListEntry.size() > 0,
264 "Augmentation Schema List cannot be empty");
266 final SchemaPath targetPath = schemaPathAugmentListEntry.get(0).getTargetPath();
267 Preconditions.checkState(targetPath != null,
268 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
270 final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(schemaContext, targetPath, usesNode);
271 if (targetSchemaNode == null) {
272 throw new IllegalArgumentException("augment target not found: " + targetPath);
275 GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
277 if (targetTypeBuilder == null) {
278 targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), genCtx);
280 if (targetTypeBuilder == null) {
281 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
284 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
285 String packageName = augmentPackageName;
286 if (usesNodeParent instanceof SchemaNode) {
287 packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(augmentPackageName,
288 ((SchemaNode) usesNodeParent).getPath());
289 } else if (usesNodeParent instanceof AugmentationSchema) {
290 Type parentTypeBuilder = genCtx.get(module).getTargetToAugmentation()
291 .get(((AugmentationSchema) usesNodeParent).getTargetPath());
292 packageName = BindingGeneratorUtil.packageNameForAugmentedGeneratedType(parentTypeBuilder.getPackageName(),
293 (AugmentationSchema)usesNodeParent);
295 genCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, packageName,
296 targetTypeBuilder.toInstance(), schemaPathAugmentListEntry, genTypeBuilders, genCtx,
297 schemaContext, verboseClassComments, typeProvider, namespaceType);
300 genCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, augmentPackageName,
301 targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode,
302 schemaPathAugmentListEntry,
303 usesNodeParent, genCtx, verboseClassComments, genTypeBuilders, typeProvider, namespaceType);
309 * Convenient method to find node added by uses statement.
310 * @param schemaContext
313 * @param parentUsesNode
314 * parent of uses node
315 * @return node from its original location in grouping
317 private static DataSchemaNode findOriginalTargetFromGrouping(final SchemaContext schemaContext, final SchemaPath targetPath,
318 final UsesNode parentUsesNode) {
319 SchemaNode targetGrouping = null;
320 QName current = parentUsesNode.getGroupingPath().getPathFromRoot().iterator().next();
321 Module module = schemaContext.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
322 if (module == null) {
323 throw new IllegalArgumentException("Fialed to find module for grouping in: " + parentUsesNode);
325 for (GroupingDefinition group : module.getGroupings()) {
326 if (group.getQName().equals(current)) {
327 targetGrouping = group;
333 if (targetGrouping == null) {
334 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
337 SchemaNode result = targetGrouping;
338 for (final QName node : targetPath.getPathFromRoot()) {
339 if (result instanceof DataNodeContainer) {
340 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
341 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
342 } else if (result instanceof ChoiceSchemaNode) {
343 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
346 if (result == null) {
350 if (result instanceof DerivableSchemaNode) {
351 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
352 Optional<? extends SchemaNode> originalNode = castedResult
354 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
355 result = originalNode.get();
359 if (result instanceof DataSchemaNode) {
360 DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
361 if (resultDataSchemaNode.isAddedByUses()) {
362 // The original node is required, but we have only the copy of
363 // the original node.
364 // Maybe this indicates a bug in Yang parser.
365 throw new IllegalStateException(
366 "Failed to generate code for augment in "
369 return resultDataSchemaNode;
372 throw new IllegalStateException(
373 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
379 * Generates list of generated types for all the cases of a choice which are
380 * added to the choice through the augment.
382 * @param schemaContext
385 * @param basePackageName
386 * string contains name of package to which augment belongs. If
387 * an augmented choice is from an other package (pcg1) than an
388 * augmenting choice (pcg2) then case's of the augmenting choice
389 * will belong to pcg2.
391 * Type which represents target choice
393 * node which represents target choice
394 * @param schemaPathAugmentListEntry
395 * list of AugmentationSchema nodes grouped by target path
396 * @return list of generated types which represents augmented cases of
397 * choice <code>refChoiceType</code>
398 * @throws IllegalArgumentException
400 * <li>if <code>basePackageName</code> is null</li>
401 * <li>if <code>targetType</code> is null</li>
402 * <li>if <code>augmentedNodes</code> is null</li>
405 private static Map<Module, ModuleContext> generateTypesFromAugmentedChoiceCases(
406 final SchemaContext schemaContext, final Module module,
407 final String basePackageName, final Type targetType, final ChoiceSchemaNode targetNode,
408 final List<AugmentationSchema> schemaPathAugmentListEntry,
409 final DataNodeContainer usesNodeParent,
410 Map<Module, ModuleContext> genCtx, final boolean verboseClassComments,
411 Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, final TypeProvider typeProvider,
412 final BindingNamespaceType namespaceType) {
413 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
414 Preconditions.checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
415 Preconditions.checkArgument(schemaPathAugmentListEntry != null, "Set of Choice Case Nodes cannot be NULL.");
418 for (final AugmentationSchema augmentationSchema : schemaPathAugmentListEntry) {
419 for (final DataSchemaNode caseNode : augmentationSchema.getChildNodes()) {
420 if (caseNode != null) {
421 final GeneratedTypeBuilder caseTypeBuilder = GenHelperUtil.addDefaultInterfaceDefinition(basePackageName,
422 caseNode, module, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider,
424 caseTypeBuilder.addImplementsType(targetType);
427 final SchemaPath nodeSp = targetNode.getPath();
428 parent = SchemaContextUtil.findDataSchemaNode(schemaContext, nodeSp.getParent());
430 GeneratedTypeBuilder childOfType = null;
431 if (parent instanceof Module) {
432 childOfType = genCtx.get(parent).getModuleNode();
433 } else if (parent instanceof ChoiceCaseNode) {
434 childOfType = GenHelperUtil.findCaseByPath(parent.getPath(), genCtx);
435 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
436 childOfType = GenHelperUtil.findChildNodeByPath(parent.getPath(), genCtx);
437 } else if (parent instanceof GroupingDefinition) {
438 childOfType = GenHelperUtil.findGroupingByPath(parent.getPath(), genCtx);
441 if (childOfType == null) {
442 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
445 ChoiceCaseNode node = null;
446 final String caseLocalName = caseNode.getQName().getLocalName();
447 if (caseNode instanceof ChoiceCaseNode) {
448 node = (ChoiceCaseNode) caseNode;
449 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
450 final String targetNodeLocalName = targetNode.getQName().getLocalName();
451 for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
452 if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
453 ().getLocalName())) {
454 node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
459 node = targetNode.getCaseNodeByName(caseLocalName);
461 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
462 if (childNodes != null) {
463 GenHelperUtil.resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType,
464 childNodes, genCtx, schemaContext, verboseClassComments, genTypeBuilders, typeProvider,
467 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
468 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);