2 * Copyright (c) 2016 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.binding2.generator.impl;
11 import com.google.common.annotations.Beta;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Iterables;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.regex.Pattern;
21 import org.opendaylight.mdsal.binding2.generator.impl.util.YangTextTemplate;
22 import org.opendaylight.mdsal.binding2.generator.util.BindingGeneratorUtil;
23 import org.opendaylight.mdsal.binding2.generator.util.BindingTypes;
24 import org.opendaylight.mdsal.binding2.generator.util.Types;
25 import org.opendaylight.mdsal.binding2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
26 import org.opendaylight.mdsal.binding2.model.api.Constant;
27 import org.opendaylight.mdsal.binding2.model.api.GeneratedType;
28 import org.opendaylight.mdsal.binding2.model.api.Type;
29 import org.opendaylight.mdsal.binding2.model.api.type.builder.GeneratedTypeBuilder;
30 import org.opendaylight.mdsal.binding2.model.api.type.builder.GeneratedTypeBuilderBase;
31 import org.opendaylight.mdsal.binding2.txt.yangTemplateForModule;
32 import org.opendaylight.mdsal.binding2.txt.yangTemplateForNode;
33 import org.opendaylight.mdsal.binding2.util.BindingMapping;
34 import org.opendaylight.yangtools.yang.common.QName;
35 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
47 import org.opendaylight.yangtools.yang.model.api.Status;
48 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.UsesNode;
50 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
53 * Helper util class used for generation of types in binding spec v2.
56 final class GenHelperUtil {
58 private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
59 private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
60 private static final char NEW_LINE = '\n';
63 * Constant with the concrete name of identifier.
65 private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
68 * Constant with the concrete name of namespace.
70 private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
72 private GenHelperUtil() {
73 throw new UnsupportedOperationException("Util class");
77 * Create GeneratedTypeBuilder object from module argument.
80 * Module object from which builder will be created
82 * @param verboseClassComments
84 * @return <code>GeneratedTypeBuilder</code> which is internal
85 * representation of the module
86 * @throws IllegalArgumentException
89 static GeneratedTypeBuilder moduleToDataType(final Module module, Map<Module, ModuleContext> genCtx, final boolean verboseClassComments) {
90 Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
92 final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(module, "Data", verboseClassComments);
93 addImplementedInterfaceFromUses(module, moduleDataTypeBuilder, genCtx);
94 moduleDataTypeBuilder.addImplementsType(BindingTypes.TREE_ROOT);
95 moduleDataTypeBuilder.addComment(module.getDescription());
96 moduleDataTypeBuilder.setDescription(createDescription(module, verboseClassComments));
97 moduleDataTypeBuilder.setReference(module.getReference());
98 return moduleDataTypeBuilder;
102 * Generates type builder for <code>module</code>.
105 * Module which is source of package name for generated type
108 * string which is added to the module class name representation
110 * @param verboseClassComments
111 * @return instance of GeneratedTypeBuilder which represents
112 * <code>module</code>.
113 * @throws IllegalArgumentException
114 * if <code>module</code> is null
116 static GeneratedTypeBuilder moduleTypeBuilder(final Module module, final String postfix, final boolean verboseClassComments) {
117 Preconditions.checkArgument(module != null, "Module reference cannot be NULL.");
118 final String packageName = BindingMapping.getRootPackageName(module);
119 final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
121 final GeneratedTypeBuilderImpl moduleBuilder = new GeneratedTypeBuilderImpl(packageName, moduleName);
122 moduleBuilder.setDescription(createDescription(module, verboseClassComments));
123 moduleBuilder.setReference(module.getReference());
124 moduleBuilder.setModuleName(moduleName);
126 return moduleBuilder;
130 * Adds the implemented types to type builder.
132 * The method passes through the list of <i>uses</i> in
133 * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
134 * generated type from all groupings
135 * allGroupings} which is added as <i>implements type</i> to
136 * <code>builder</code>
138 * @param dataNodeContainer
139 * element which contains the list of used YANG groupings
141 * builder to which are added implemented types according to
142 * <code>dataNodeContainer</code>
144 * @return generated type builder with all implemented types
146 private static GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
147 final GeneratedTypeBuilder builder, Map<Module, ModuleContext> genCtx) {
148 for (final UsesNode usesNode : dataNodeContainer.getUses()) {
149 if (usesNode.getGroupingPath() != null) {
150 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath(), genCtx).toInstance();
151 if (genType == null) {
152 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
153 + builder.getName());
156 builder.addImplementsType(genType);
162 static GeneratedTypeBuilder findGroupingByPath(final SchemaPath path, Map<Module, ModuleContext> genCtx) {
163 for (final ModuleContext ctx : genCtx.values()) {
164 final GeneratedTypeBuilder result = ctx.getGrouping(path);
165 if (result != null) {
172 private static String createDescription(final Module module, final boolean verboseClassComments) {
173 final StringBuilder sb = new StringBuilder();
174 final String moduleDescription = BindingGeneratorUtil.encodeAngleBrackets(module.getDescription());
175 final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
177 if (!Strings.isNullOrEmpty(formattedDescription)) {
178 sb.append(formattedDescription);
182 if (verboseClassComments) {
184 sb.append("This class represents the following YANG schema fragment defined in module <b>");
185 sb.append(module.getName());
190 sb.append(BindingGeneratorUtil.encodeAngleBrackets(yangTemplateForModule.render(module).body()));
194 return replaceAllIllegalChars(sb);
198 public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
199 final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
200 return ret.isEmpty() ? "" : ret;
204 * Adds the methods to <code>typeBuilder</code> which represent subnodes of
205 * node for which <code>typeBuilder</code> was created.
207 * The subnodes aren't mapped to the methods if they are part of grouping or
208 * augment (in this case are already part of them).
212 * @param basePackageName
213 * string contains the module package name
215 * generated type builder which represents any node. The subnodes
216 * of this node are added to the <code>typeBuilder</code> as
217 * methods. The subnode can be of type leaf, leaf-list, list,
222 * set of data schema nodes which are the children of the node
223 * for which <code>typeBuilder</code> was created
224 * @return generated type builder which is the same builder as input
225 * parameter. The getter methods (representing child nodes) could be
228 static GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
229 final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
230 if (schemaNodes != null && parent != null) {
231 for (final DataSchemaNode schemaNode : schemaNodes) {
232 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
233 //TODO: design decomposition and implement it
234 //addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
241 static Map<Module, ModuleContext> processUsesAugments(final SchemaContext schemaContext, final
242 DataNodeContainer node, final Module module, Map<Module, ModuleContext> genCtx, Map<String,
243 Map<String, GeneratedTypeBuilder>> genTypeBuilders, final boolean verboseClassComments) {
244 final String basePackageName = BindingMapping.getRootPackageName(module);
245 for (final UsesNode usesNode : node.getUses()) {
246 for (final AugmentationSchema augment : usesNode.getAugmentations()) {
247 genCtx = AugmentToGenType.usesAugmentationToGenTypes(schemaContext, basePackageName, augment, module,
249 node, genCtx, genTypeBuilders, verboseClassComments);
250 genCtx = processUsesAugments(schemaContext, augment, module, genCtx, genTypeBuilders, verboseClassComments);
256 static GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path, Map<Module, ModuleContext> genCtx) {
257 for (final ModuleContext ctx : genCtx.values()) {
258 final GeneratedTypeBuilder result = ctx.getChildNode(path);
259 if (result != null) {
266 static GeneratedTypeBuilder findCaseByPath(final SchemaPath path, Map<Module, ModuleContext> genCtx) {
267 for (final ModuleContext ctx : genCtx.values()) {
268 final GeneratedTypeBuilder result = ctx.getCase(path);
269 if (result != null) {
277 * Returns a generated type builder for an augmentation.
279 * The name of the type builder is equal to the name of augmented node with
280 * serial number as suffix.
284 * @param augmentPackageName
285 * string with contains the package name to which the augment
287 * @param basePackageName
288 * string with the package name to which the augmented node
290 * @param targetTypeRef
293 * augmentation schema which contains data about the child nodes
294 * and uses of augment
295 * @return generated type builder for augment in genCtx
297 static Map<Module, ModuleContext> addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
298 final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema,
299 Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders, Map<Module, ModuleContext> genCtx) {
301 Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
302 if (augmentBuilders == null) {
303 augmentBuilders = new HashMap<>();
304 genTypeBuilders.put(augmentPackageName, augmentBuilders);
306 final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
309 if (augIdentifier != null) {
310 augTypeName = BindingMapping.getClassName(augIdentifier);
312 augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
315 GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
317 augTypeBuilder.addImplementsType(BindingTypes.TREE_NODE);
318 augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
319 annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
320 augTypeBuilder = addImplementedInterfaceFromUses(augSchema, augTypeBuilder, genCtx);
322 augTypeBuilder = augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema
324 augmentBuilders.put(augTypeName, augTypeBuilder);
326 if(!augSchema.getChildNodes().isEmpty()) {
327 genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
330 genCtx.get(module).addAugmentType(augTypeBuilder);
335 * Adds the methods to <code>typeBuilder</code> what represents subnodes of
336 * node for which <code>typeBuilder</code> was created.
340 * @param basePackageName
341 * string contains the module package name
343 * generated type builder which represents any node. The subnodes
344 * of this node are added to the <code>typeBuilder</code> as
345 * methods. The subnode can be of type leaf, leaf-list, list,
350 * set of data schema nodes which are the children of the node
351 * for which <code>typeBuilder</code> was created
352 * @return generated type builder which is the same object as the input
353 * parameter <code>typeBuilder</code>. The getter method could be
356 private static GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
357 final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
358 final Iterable<DataSchemaNode> schemaNodes) {
359 if ((schemaNodes != null) && (typeBuilder != null)) {
360 for (final DataSchemaNode schemaNode : schemaNodes) {
361 if (!schemaNode.isAugmenting()) {
362 //TODO: design decomposition and implement it
363 //addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
371 * @param unknownSchemaNodes
372 * @return nodeParameter of UnknownSchemaNode
374 private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
375 for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
376 final QName nodeType = unknownSchemaNode.getNodeType();
377 if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
378 && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
379 return unknownSchemaNode.getNodeParameter();
386 * Returns first unique name for the augment generated type builder. The
387 * generated type builder name for augment consists from name of augmented
388 * node and serial number of its augmentation.
391 * map of builders which were created in the package to which the
392 * augmentation belongs
394 * string with name of augmented node
395 * @return string with unique name for augmentation builder
397 private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
399 if (builders != null) {
400 while (builders.containsKey(genTypeName + index)) {
404 return genTypeName + index;
407 static GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode
408 schemaNode, final Module module, Map<Module, ModuleContext> genCtx, final SchemaContext schemaContext,
409 final boolean verboseClassComments, Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders) {
410 return addDefaultInterfaceDefinition(packageName, schemaNode, null, module, genCtx, schemaContext,
411 verboseClassComments, genTypeBuilders);
415 * Instantiates generated type builder with <code>packageName</code> and
416 * <code>schemaNode</code>.
418 * The new builder always implements
419 * {@link org.opendaylight.mdsal.binding2.spec.TreeNode TreeNode}.<br>
420 * If <code>schemaNode</code> is instance of GroupingDefinition it also
421 * implements {@link org.opendaylight.mdsal.binding2.spec.Augmentable
423 * If <code>schemaNode</code> is instance of
424 * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
425 * DataNodeContainer} it can also implement nodes which are specified in
429 * string with the name of the package to which
430 * <code>schemaNode</code> belongs.
432 * schema node for which is created generated type builder
434 * parent type (can be null)
435 * @param schemaContext
436 * @return generated type builder <code>schemaNode</code>
438 private static GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode
439 schemaNode, final Type parent, final Module module, Map<Module, ModuleContext> genCtx,
440 final SchemaContext schemaContext, final boolean verboseClassComments, Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders) {
441 GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, schemaContext, "",
442 verboseClassComments, genTypeBuilders);
443 if (parent == null) {
444 it.addImplementsType(BindingTypes.TREE_NODE);
446 it.addImplementsType(BindingTypes.treeChildNode(parent));
448 if (!(schemaNode instanceof GroupingDefinition)) {
449 it.addImplementsType(BindingTypes.augmentable(it));
452 if (schemaNode instanceof DataNodeContainer) {
453 //TODO: design decomposition and implement it
454 //groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
455 it = addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it, genCtx);
462 * Returns reference to generated type builder for specified
463 * <code>schemaNode</code> with <code>packageName</code>.
465 * Firstly the generated type builder is searched in
466 * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
467 * found it is created and added to <code>genTypeBuilders</code>.
470 * string with the package name to which returning generated type
473 * schema node which provide data about the schema node name
474 * @param schemaContext
476 * return type name prefix
477 * @return generated type builder for <code>schemaNode</code>
478 * @throws IllegalArgumentException
480 * <li>if <code>schemaNode</code> is null</li>
481 * <li>if <code>packageName</code> is null</li>
482 * <li>if QName of schema node is null</li>
483 * <li>if schemaNode name is null</li>
487 private static GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
488 final SchemaContext schemaContext, final String prefix, final boolean verboseClassComments,
489 Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders) {
490 Preconditions.checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
491 Preconditions.checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
492 Preconditions.checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
493 final String schemaNodeName = schemaNode.getQName().getLocalName();
494 Preconditions.checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
497 if (prefix == null) {
498 genTypeName = BindingMapping.getClassName(schemaNodeName);
500 genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
503 final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
504 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
505 qNameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
506 newType.addComment(schemaNode.getDescription());
507 newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName(), schemaContext, verboseClassComments));
508 newType.setReference(schemaNode.getReference());
509 newType.setSchemaPath((List<QName>) schemaNode.getPath().getPathFromRoot());
510 newType.setModuleName(module.getName());
512 //FIXME: update genTypeBuilders for callers
513 if (!genTypeBuilders.containsKey(packageName)) {
514 final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
515 builders.put(genTypeName, newType);
516 genTypeBuilders.put(packageName, builders);
518 final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
519 if (!builders.containsKey(genTypeName)) {
520 builders.put(genTypeName, newType);
527 private static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
529 return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
532 private static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
533 final SchemaContext schemaContext, final boolean verboseClassComments) {
534 final StringBuilder sb = new StringBuilder();
535 final String nodeDescription = BindingGeneratorUtil.encodeAngleBrackets(schemaNode.getDescription());
536 final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
538 if (!Strings.isNullOrEmpty(formattedDescription)) {
539 sb.append(formattedDescription);
543 if (verboseClassComments) {
544 final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
545 final StringBuilder linkToBuilderClass = new StringBuilder();
546 final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
547 final String className = namespace[namespace.length - 1];
549 if (hasBuilderClass(schemaNode)) {
550 linkToBuilderClass.append(className);
551 linkToBuilderClass.append("Builder");
555 sb.append("This class represents the following YANG schema fragment defined in module <b>");
556 sb.append(module.getName());
561 sb.append(BindingGeneratorUtil.encodeAngleBrackets(yangTemplateForNode.render(schemaNode).body()));
564 sb.append("The schema path to identify an instance is");
567 sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
571 if (hasBuilderClass(schemaNode)) {
573 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
576 sb.append(linkToBuilderClass);
578 if (schemaNode instanceof ListSchemaNode) {
579 final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
580 if (keyDef != null && !keyDef.isEmpty()) {
582 sb.append(className);
590 return replaceAllIllegalChars(sb);
593 private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
594 if (status == Status.DEPRECATED) {
595 builder.addAnnotation("", "Deprecated");
599 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
600 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
601 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {