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