Binding generator v2 - uses statement - support choice
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / impl / AuxiliaryGenUtils.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 static com.google.common.base.Preconditions.checkArgument;
12 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
13 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.replacePackageTopNamespace;
14 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.BOOLEAN;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Splitter;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.Iterables;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.regex.Pattern;
26 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForModule;
27 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNode;
28 import org.opendaylight.mdsal.binding.javav2.generator.impl.txt.yangTemplateForNodes;
29 import org.opendaylight.mdsal.binding.javav2.generator.impl.util.YangTextTemplate;
30 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
31 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
32 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
35 import org.opendaylight.mdsal.binding.javav2.generator.util.YangSnippetCleaner;
36 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
37 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
38 import org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeProviderImpl;
39 import org.opendaylight.mdsal.binding.javav2.model.api.Constant;
40 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
41 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
42 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
43 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
44 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
45 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
46 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
47 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
48 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
51 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
57 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Status;
62 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
68
69 /**
70  * Auxiliary util class for {@link GenHelperUtil} class
71  */
72 @Beta
73 final class AuxiliaryGenUtils {
74
75     private static final Splitter BSDOT_SPLITTER = Splitter.on(".");
76     private static final char NEW_LINE = '\n';
77     private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
78
79     /**
80      * Constant with the concrete name of identifier.
81      */
82     private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
83
84     /**
85      * Constant with the concrete name of namespace.
86      */
87     private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
88
89     private AuxiliaryGenUtils() {
90         throw new UnsupportedOperationException("Util class");
91     }
92
93     static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
94         if (status == Status.DEPRECATED) {
95             builder.addAnnotation("", "Deprecated");
96         }
97     }
98
99     public static boolean hasBuilderClass(final SchemaNode schemaNode, final BindingNamespaceType namespaceType) {
100         return (namespaceType.equals(BindingNamespaceType.Data)
101                 && (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
102                 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition
103                 || schemaNode instanceof ChoiceCaseNode));
104     }
105
106     static Constant qNameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
107                                   final QName name) {
108         return toBuilder.addConstant(Types.typeForClass(QName.class), constantName, name);
109     }
110
111     /**
112      * Created a method signature builder as part of
113      * <code>interfaceBuilder</code>.
114      *
115      * The method signature builder is created for the getter method of
116      * <code>schemaNodeName</code>. Also <code>comment</code> and
117      * <code>returnType</code> information are added to the builder.
118      *
119      * @param interfaceBuilder
120      *            generated type builder for which the getter method should be
121      *            created
122      * @param schemaNodeName
123      *            string with schema node name. The name will be the part of the
124      *            getter method name.
125      * @param comment
126      *            string with comment for the getter method
127      * @param returnType
128      *            type which represents the return type of the getter method
129      * @param status
130      *            status from yang file, for deprecated annotation
131      * @return method signature builder which represents the getter method of
132      *         <code>interfaceBuilder</code>
133      */
134     static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
135                                                   final String schemaNodeName, final String comment, final Type returnType, final Status status) {
136
137         final MethodSignatureBuilder getMethod = interfaceBuilder
138                 .addMethod(getterMethodName(schemaNodeName, returnType));
139         if (status == Status.DEPRECATED) {
140             getMethod.addAnnotation("", "Deprecated");
141         }
142         getMethod.setComment(encodeAngleBrackets(comment));
143         getMethod.setReturnType(returnType);
144         return getMethod;
145     }
146
147     /**
148      * Creates the name of the getter method name from <code>localName</code>.
149      *
150      * @param localName
151      *            string with the name of the getter method
152      * @param returnType
153      *            return type
154      * @return string with the name of the getter method for
155      *         <code>methodName</code> in JAVA method format
156      */
157     private static String getterMethodName(final String localName, final Type returnType) {
158         final StringBuilder method = new StringBuilder();
159         if (BOOLEAN.equals(returnType)) {
160             method.append("is");
161         } else {
162             method.append("get");
163         }
164         // underscore used as separator for distinction of method parts in convertIdentifier()
165         method.append('_').append(localName);
166         return JavaIdentifierNormalizer.normalizeSpecificIdentifier(method.toString(), JavaIdentifier.METHOD);
167     }
168
169     static String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName,
170                                     final SchemaContext schemaContext, final boolean verboseClassComments,
171                                     final BindingNamespaceType namespaceType) {
172         final StringBuilder sb = new StringBuilder();
173         final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
174         final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
175
176         if (!Strings.isNullOrEmpty(formattedDescription)) {
177             sb.append(formattedDescription);
178             sb.append(NEW_LINE);
179         }
180
181         final Module module = SchemaContextUtil.findParentModule(schemaContext, schemaNode);
182         if (verboseClassComments) {
183             sb.append("<p>");
184             sb.append("This class represents the following YANG schema fragment defined in module <b>");
185             sb.append(module.getName());
186             sb.append("</b>");
187             sb.append(NEW_LINE);
188             sb.append("<pre>");
189             sb.append(NEW_LINE);
190             String formedYang = YangSnippetCleaner.clean(yangTemplateForNode.render(schemaNode, module).body());
191             sb.append(encodeAngleBrackets(formedYang));
192             sb.append("</pre>");
193             sb.append(NEW_LINE);
194             sb.append("The schema path to identify an instance is");
195             sb.append(NEW_LINE);
196             sb.append("<i>");
197             sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
198             sb.append("</i>");
199             sb.append(NEW_LINE);
200
201             if (hasBuilderClass(schemaNode, namespaceType) && !(schemaNode instanceof OperationDefinition)) {
202                 final StringBuilder linkToBuilderClass = new StringBuilder();
203                 final String basePackageName = BindingMapping.getRootPackageName(module);
204
205                 linkToBuilderClass
206                         .append(replacePackageTopNamespace(basePackageName, fullyQualifiedName,
207                                 namespaceType, BindingNamespaceType.Builder))
208                         .append("Builder");
209                 sb.append(NEW_LINE);
210                 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
211                 sb.append(NEW_LINE);
212                 sb.append("@see ");
213                 sb.append(linkToBuilderClass);
214                 sb.append(NEW_LINE);
215                 if (schemaNode instanceof ListSchemaNode) {
216                     final StringBuilder linkToKeyClass = new StringBuilder();
217
218                     final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
219                     final String className = namespace[namespace.length - 1];
220
221                     linkToKeyClass.append(BindingGeneratorUtil.packageNameForSubGeneratedType(basePackageName, schemaNode,
222                             BindingNamespaceType.Key))
223                             .append('.')
224                             .append(className)
225                             .append("Key");
226
227                     final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
228                     if (keyDef != null && !keyDef.isEmpty()) {
229                         sb.append("@see ");
230                         sb.append(linkToKeyClass);
231                     }
232                     sb.append(NEW_LINE);
233                 }
234             }
235         }
236
237         return replaceAllIllegalChars(sb);
238     }
239
240     static String createDescription(final Module module, final boolean verboseClassComments) {
241         final StringBuilder sb = new StringBuilder();
242         final String moduleDescription = encodeAngleBrackets(module.getDescription());
243         final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
244
245         if (!Strings.isNullOrEmpty(formattedDescription)) {
246             sb.append(formattedDescription);
247             sb.append(NEW_LINE);
248         }
249
250         if (verboseClassComments) {
251             sb.append("<p>");
252             sb.append("This class represents the following YANG schema fragment defined in module <b>");
253             sb.append(module.getName());
254             sb.append("</b>");
255             sb.append(NEW_LINE);
256             sb.append("<pre>");
257             sb.append(NEW_LINE);
258             String formedYang = YangSnippetCleaner.clean(yangTemplateForModule.render(module).body());
259             sb.append(encodeAngleBrackets(formedYang));
260             sb.append("</pre>");
261         }
262
263         return replaceAllIllegalChars(sb);
264     }
265
266     static String createDescription(final Set<? extends SchemaNode> schemaNodes, final Module module, final
267             boolean verboseClassComments) {
268         final StringBuilder sb = new StringBuilder();
269
270         if (!isNullOrEmpty(schemaNodes)) {
271             final SchemaNode node = schemaNodes.iterator().next();
272
273             if (node instanceof RpcDefinition) {
274                 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + module.getName() + "</b>");
275             } else if (node instanceof NotificationDefinition) {
276                 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + module.getName() + "</b>");
277             }
278         }
279         sb.append(NEW_LINE);
280
281         if (verboseClassComments) {
282             sb.append("<pre>");
283             sb.append(NEW_LINE);
284             sb.append(encodeAngleBrackets(yangTemplateForNodes.render(schemaNodes, module).body()));
285             sb.append("</pre>");
286             sb.append(NEW_LINE);
287         }
288
289         return replaceAllIllegalChars(sb);
290     }
291
292     private static boolean isNullOrEmpty(final Collection<?> list) {
293         return list == null || list.isEmpty();
294     }
295
296     /**
297      * Returns first unique name for the augment generated type builder. The
298      * generated type builder name for augment consists from name of augmented
299      * node and serial number of its augmentation.
300      *
301      * @param builders
302      *            map of builders which were created in the package to which the
303      *            augmentation belongs
304      * @param genTypeName
305      *            string with name of augmented node
306      * @return string with unique name for augmentation builder
307      */
308     static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
309         int index = 1;
310         if (builders != null) {
311             while (builders.containsKey(genTypeName + index)) {
312                 index = index + 1;
313             }
314         }
315         return genTypeName + index;
316     }
317
318     /**
319      * @param unknownSchemaNodes unknown schema nodes
320      * @return nodeParameter of UnknownSchemaNode
321      */
322     static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
323         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
324             final QName nodeType = unknownSchemaNode.getNodeType();
325             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
326                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
327                 return unknownSchemaNode.getNodeParameter();
328             }
329         }
330         return null;
331     }
332
333     /**
334      * Adds enumeration builder created from <code>enumTypeDef</code> to
335      * <code>typeBuilder</code>.
336      *
337      * Each <code>enumTypeDef</code> item is added to builder with its name and
338      * value.
339      *
340      * @param enumTypeDef
341      *            EnumTypeDefinition contains enum data
342      * @param enumName
343      *            string contains name which will be assigned to enumeration
344      *            builder
345      * @param typeBuilder
346      *            GeneratedTypeBuilder to which will be enum builder assigned
347      * @param module
348      *            Module in which type should be generated
349      * @return enumeration builder which contains data from
350      *         <code>enumTypeDef</code>
351      */
352     static EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
353         final Map<Module, ModuleContext> genCtx, final GeneratedTypeBuilder typeBuilder, final Module module) {
354         if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
355             final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName.getLocalName());
356             final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
357             enumBuilder.setDescription(enumTypedefDescription);
358             enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
359             final ModuleContext ctx = genCtx.get(module);
360             ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
361             return enumBuilder;
362         }
363         return null;
364     }
365
366
367     /**
368      * Builds generated TO builders for <code>typeDef</code> of type
369      * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
370      * also added to <code>typeBuilder</code> as enclosing transfer object.
371      *
372      * If more then one generated TO builder is created for enclosing then all
373      * of the generated TO builders are added to <code>typeBuilder</code> as
374      * enclosing transfer objects.
375      *
376      * @param typeDef
377      *            type definition which can be of type <code>UnionType</code> or
378      *            <code>BitsTypeDefinition</code>
379      * @param typeBuilder
380      *            generated type builder to which is added generated TO created
381      *            from <code>typeDef</code>
382      * @param leaf
383      *            string with name for generated TO builder
384      * @param parentModule
385      *            parent module
386      * @return generated TO builder for <code>typeDef</code>
387      */
388     static GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef, final GeneratedTypeBuilder
389             typeBuilder, final DataSchemaNode leaf, final Module parentModule, final TypeProvider typeProvider,
390             final SchemaContext schemaContext) {
391         final String classNameFromLeaf = leaf.getQName().getLocalName();
392         GeneratedTOBuilder genTOBuilder = null;
393         final String packageName = typeBuilder.getFullyQualifiedName();
394         if (typeDef instanceof UnionTypeDefinition) {
395             genTOBuilder = ((TypeProviderImpl) typeProvider)
396                     .provideGeneratedTOBuilderForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
397                             classNameFromLeaf, leaf, schemaContext,
398                             ((TypeProviderImpl) typeProvider).getGenTypeDefsContextMap());
399         } else if (typeDef instanceof BitsTypeDefinition) {
400             genTOBuilder = (((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
401                     packageName, typeDef, classNameFromLeaf, parentModule.getName());
402         }
403         if (genTOBuilder != null) {
404             typeBuilder.addEnclosingTransferObject(genTOBuilder);
405             return genTOBuilder;
406         }
407         return null;
408
409     }
410
411     @SuppressWarnings({ "unchecked", "rawtypes" })
412     static Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
413             final GeneratedTypeBuilder typeBuilder, final Module parentModule, final TypeProvider typeProvider) {
414         final GeneratedTOBuilderImpl returnType = (GeneratedTOBuilderImpl) genTOBuilder;
415         final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
416
417         returnType.setDescription(typedefDescription);
418         returnType.setReference(typeDef.getReference());
419         returnType.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
420         returnType.setModuleName(parentModule.getName());
421
422         genTOBuilder.setTypedef(true);
423         genTOBuilder.setIsUnion(true);
424         TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
425
426         return returnType.toInstance();
427     }
428
429     static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
430         return leaf.getPath().equals(type.getPath()) || leaf.getPath().equals(type.getPath().getParent());
431
432     }
433
434     /**
435      * Generates for the <code>list</code> which contains any list keys special
436      * generated TO builder.
437      *
438      * @param packageName
439      *            string with package name to which the list belongs
440      * @param list
441      *            schema node of list
442      * @return generated TO builder which represents the keys of the
443      *         <code>list</code> or empty TO builder if <code>list</code> is null or list of
444      *         key definitions is null or empty.
445      */
446     static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
447         GeneratedTOBuilder genTOBuilder = null;
448         if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
449             // underscore used as separator for distinction of class name parts
450             final String genTOName =
451                     new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
452                             .toString();
453             genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
454         }
455         return genTOBuilder;
456     }
457
458     static GeneratedTypeBuilder resolveListKeyTypeBuilder(final String packageName, final ListSchemaNode list) {
459         GeneratedTypeBuilder genTypeBuilder = null;
460         if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
461             // underscore used as separator for distinction of class name parts
462             final String genTOName =
463                     new StringBuilder(list.getQName().getLocalName()).append('_').append(BindingNamespaceType.Key)
464                             .toString();
465             genTypeBuilder = new GeneratedTypeBuilderImpl(packageName, genTOName);
466         }
467         return genTypeBuilder;
468     }
469
470     /**
471      * Converts <code>leaf</code> schema node to property of generated TO
472      * builder.
473      *
474      * @param toBuilder
475      *            generated TO builder to which is <code>leaf</code> added as
476      *            property
477      * @param leaf
478      *            leaf schema node which is added to <code>toBuilder</code> as
479      *            property
480      * @param returnType
481      *            property type
482      * @param isReadOnly
483      *            boolean value which says if leaf property is|isn't read only
484      * @return boolean value
485      *         <ul>
486      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
487      *         name equals null or if leaf is added by <i>uses</i>.</li>
488      *         <li>true - other cases</li>
489      *         </ul>
490      */
491     static boolean resolveLeafSchemaNodeAsProperty(final String nodeName, final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
492         final Type returnType, final boolean isReadOnly) {
493
494         if (returnType == null) {
495             return false;
496         }
497         final String leafName = leaf.getQName().getLocalName();
498         final String leafGetterName;
499
500         StringBuilder sb = new StringBuilder(nodeName)
501                 .append('_')
502                 .append(leafName);
503         leafGetterName = sb.toString();
504
505         final String leafDesc = encodeAngleBrackets(leaf.getDescription());
506         final GeneratedPropertyBuilder propBuilder =
507                 toBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(leafGetterName, JavaIdentifier.METHOD));
508         propBuilder.setReadOnly(isReadOnly);
509         propBuilder.setReturnType(returnType);
510         propBuilder.setComment(leafDesc);
511         toBuilder.addEqualsIdentity(propBuilder);
512         toBuilder.addHashIdentity(propBuilder);
513         toBuilder.addToStringProperty(propBuilder);
514         return true;
515     }
516
517     static void checkModuleAndModuleName(final Module module) {
518         checkArgument(module != null, "Module reference cannot be NULL.");
519         checkArgument(module.getName() != null, "Module name cannot be NULL.");
520     }
521
522     @VisibleForTesting
523     public static String replaceAllIllegalChars(final StringBuilder stringBuilder){
524         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
525         return ret.isEmpty() ? "" : ret;
526     }
527 }