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.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;
45 final class AugmentToGenType {
48 * Comparator based on augment target path.
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();
54 while (thisIt.hasNext()) {
55 if (!otherIt.hasNext()) {
59 final int comp = thisIt.next().compareTo(otherIt.next());
65 return otherIt.hasNext() ? -1 : 0;
68 private AugmentToGenType() {
69 throw new UnsupportedOperationException("Utility class");
73 * Converts all <b>augmentation</b> of the module to the list
74 * <code>Type</code> objects.
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
85 * @throws IllegalArgumentException
87 * <li>if the module is null</li>
88 * <li>if the name of module is null</li>
90 * @throws IllegalStateException
91 * if set of augmentations from module is null
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) {
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.");
101 final String basePackageName = BindingMapping.getRootPackageName(module);
102 final List<AugmentationSchema> augmentations = resolveAugmentations(module);
103 Map<Module, ModuleContext> resultCtx = genCtx;
105 //let's group augments by target path
106 Map<SchemaPath, List<AugmentationSchema>> augmentationsGrouped =
107 augmentations.stream().collect(Collectors.groupingBy(AugmentationSchema::getTargetPath));
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);
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
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
129 * @throws IllegalStateException
130 * if set of module augmentations is null
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.");
136 final Set<AugmentationSchema> augmentations = module.getAugmentations();
137 final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
138 Collections.sort(sortedAugmentations, AUGMENT_COMP);
140 return sortedAugmentations;
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.
150 * @param augmentPackageName
151 * string with the name of the package to which the augmentation
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
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) {
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).");
178 //TODO: implement uses-augment scenario
180 SchemaNode targetSchemaNode;
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();
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());
193 if (targetSchemaNode == null) {
194 throw new IllegalArgumentException("augment target not found: " + targetPath);
197 //TODO: loose this assignment afterwards
198 Map<Module, ModuleContext> generatedCtx = genCtx;
200 GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
202 if (targetTypeBuilder == null) {
203 targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), generatedCtx);
205 if (targetTypeBuilder == null) {
206 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
209 if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
210 generatedCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, augmentPackageName,
211 targetTypeBuilder.toInstance(), schemaPathAugmentListEntry.getValue(), genTypeBuilders, generatedCtx,
212 schemaContext, verboseClassComments, typeProvider);
214 //TODO: implement augmented choice cases scenario
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) {
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).");
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);
236 GeneratedTypeBuilder targetTypeBuilder = GenHelperUtil.findChildNodeByPath(targetSchemaNode.getPath(),
238 if (targetTypeBuilder == null) {
239 targetTypeBuilder = GenHelperUtil.findCaseByPath(targetSchemaNode.getPath(), genCtx);
241 if (targetTypeBuilder == null) {
242 throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
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);
255 genCtx = GenHelperUtil.addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName,
256 targetTypeBuilder.toInstance(), augSchema, genTypeBuilders, genCtx, schemaContext,
257 verboseClassComments, typeProvider);
260 genCtx = generateTypesFromAugmentedChoiceCases(schemaContext, module, augmentPackageName,
261 targetTypeBuilder.toInstance(), (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(),
262 usesNodeParent, genCtx, verboseClassComments, genTypeBuilders, typeProvider);
268 * Convenient method to find node added by uses statement.
269 * @param schemaContext
272 * @param parentUsesNode
273 * parent of uses node
274 * @return node from its original location in grouping
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);
284 for (GroupingDefinition group : module.getGroupings()) {
285 if (group.getQName().equals(current)) {
286 targetGrouping = group;
292 if (targetGrouping == null) {
293 throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
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());
306 if (result == null) {
310 if (result instanceof DerivableSchemaNode) {
311 DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
312 Optional<? extends SchemaNode> originalNode = castedResult
314 if (castedResult.isAddedByUses() && originalNode.isPresent()) {
315 result = originalNode.get();
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 "
329 return resultDataSchemaNode;
332 throw new IllegalStateException(
333 "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
339 * Generates list of generated types for all the cases of a choice which are
340 * added to the choice through the augment.
342 * @param schemaContext
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.
351 * Type which represents target choice
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
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>
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.");
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);
384 final SchemaPath nodeSp = targetNode.getPath();
385 parent = SchemaContextUtil.findDataSchemaNode(schemaContext, nodeSp.getParent());
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);
398 if (childOfType == null) {
399 throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
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);
416 node = targetNode.getCaseNodeByName(caseLocalName);
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);
423 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
424 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);