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