Import exception references
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / JavaFileTemplate.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o. 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 package org.opendaylight.mdsal.binding.java.api.generator;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.encodeAngleBrackets;
14 import static org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil.replaceAllIllegalChars;
15
16 import com.google.common.base.CharMatcher;
17 import com.google.common.base.MoreObjects;
18 import com.google.common.collect.ImmutableSortedSet;
19 import java.lang.reflect.Method;
20 import java.util.AbstractMap;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.HashMap;
26 import java.util.LinkedHashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.NoSuchElementException;
30 import java.util.Objects;
31 import java.util.Optional;
32 import java.util.Set;
33 import java.util.regex.Pattern;
34 import java.util.stream.Collectors;
35 import javax.annotation.processing.Generated;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.xtext.xbase.lib.StringExtensions;
38 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
39 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
43 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
44 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
45 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
46 import org.opendaylight.mdsal.binding.model.api.Restrictions;
47 import org.opendaylight.mdsal.binding.model.api.Type;
48 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple;
49 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single;
50 import org.opendaylight.mdsal.binding.model.ri.Types;
51 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
52 import org.opendaylight.yangtools.yang.binding.Augmentable;
53 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
54 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
56 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
58 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
61 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
62 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
63 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
64 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter;
65
66 /**
67  * Base Java file template. Contains a non-null type and imports which the generated code refers to.
68  */
69 class JavaFileTemplate {
70     /**
71      * {@code java.lang.Class} as a JavaTypeName.
72      */
73     static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
74     /**
75      * {@code java.lang.Deprecated} as a JavaTypeName.
76      */
77     static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
78     /**
79      * {@code java.lang.IllegalArgumentException} as a JavaTypeName.
80      */
81     static final @NonNull JavaTypeName IAE = JavaTypeName.create(IllegalArgumentException.class);
82     /**
83      * {@code java.lang.NullPointerException} as a JavaTypeName.
84      */
85     static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
86     /**
87      * {@code java.lang.NoSuchElementException} as a JavaTypeName.
88      */
89     static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
90     /**
91      * {@code java.lang.Override} as a JavaTypeName.
92      */
93     static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
94     /**
95      * {@code java.lang.void} as a JavaTypeName.
96      */
97     static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
98     /**
99      * {@code java.lang.SuppressWarnings} as a JavaTypeName.
100      */
101     static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
102
103     /**
104      * {@code java.util.Arrays} as a JavaTypeName.
105      */
106     static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
107     /**
108      * {@code java.util.HashMap} as a JavaTypeName.
109      */
110     static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
111     /**
112      * {@code java.util.List} as a JavaTypeName.
113      */
114     static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
115     /**
116      * {@code java.util.Map} as a JavaTypeName.
117      */
118     static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
119     /**
120      * {@code java.util.Objects} as a JavaTypeName.
121      */
122     static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
123     /**
124      * {@code java.util.regex.Pattern} as a JavaTypeName.
125      */
126     static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
127
128     /**
129      * {@code javax.annotation.processing.Generated} as a JavaTypeName.
130      */
131     static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
132
133     /**
134      * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
135      */
136     static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
137     /**
138      * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
139      */
140     static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
141
142     /**
143      * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
144      */
145     static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
146
147     /**
148      * {@code com.google.common.base.MoreObjects} as a JavaTypeName.
149      */
150     static final @NonNull JavaTypeName MOREOBJECTS = JavaTypeName.create(MoreObjects.class);
151
152     private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
153     private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
154     private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
155     private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
156         .addIgnoredStatement(YangStmtMapping.CONTACT)
157         .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
158         .addIgnoredStatement(YangStmtMapping.REFERENCE)
159         .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
160         .build();
161     private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
162     private static final Type AUGMENTATION_RET_TYPE;
163
164     static {
165         final Method m;
166         try {
167             m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
168         } catch (NoSuchMethodException e) {
169             throw new ExceptionInInitializerError(e);
170         }
171
172         AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
173     }
174
175     private final AbstractJavaGeneratedType javaType;
176     private final GeneratedType type;
177
178     JavaFileTemplate(final @NonNull GeneratedType type) {
179         this(new TopLevelJavaGeneratedType(type), type);
180     }
181
182     JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
183         this.javaType = requireNonNull(javaType);
184         this.type = requireNonNull(type);
185     }
186
187     final AbstractJavaGeneratedType javaType() {
188         return javaType;
189     }
190
191     final GeneratedType type() {
192         return type;
193     }
194
195     final String generateImportBlock() {
196         verify(javaType instanceof TopLevelJavaGeneratedType);
197         return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
198                 .collect(Collectors.joining());
199     }
200
201     final @NonNull String importedJavadocName(final @NonNull Type intype) {
202         return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
203     }
204
205     final @NonNull String importedName(final @NonNull Type intype) {
206         return javaType.getReferenceString(intype);
207     }
208
209     final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
210         return javaType.getReferenceString(intype, annotation);
211     }
212
213     final @NonNull String importedName(final Class<?> cls) {
214         return importedName(Types.typeForClass(cls));
215     }
216
217     final @NonNull String importedName(final @NonNull JavaTypeName intype) {
218         return javaType.getReferenceString(intype);
219     }
220
221     final @NonNull String importedNonNull(final @NonNull Type intype) {
222         return importedName(intype, importedName(NONNULL));
223     }
224
225     final @NonNull String importedNullable(final @NonNull Type intype) {
226         return importedName(intype, importedName(NULLABLE));
227     }
228
229     final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
230         return fullyQualifiedName(intype, importedName(NONNULL));
231     }
232
233     final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
234         return javaType.getFullyQualifiedReference(intype, annotation);
235     }
236
237     // Exposed for BuilderTemplate
238     boolean isLocalInnerClass(final JavaTypeName name) {
239         final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
240         return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
241     }
242
243     final CharSequence generateInnerClass(final GeneratedType innerClass) {
244         if (!(innerClass instanceof GeneratedTransferObject)) {
245             return "";
246         }
247
248         final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
249         final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
250         return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
251                 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
252     }
253
254     /**
255      * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
256      * {@link Arrays} if the property is an array, {@link Objects} otherwise.
257      *
258      * @param property Generated property
259      * @return Imported class name
260      */
261     final String importedUtilClass(final GeneratedProperty property) {
262         return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
263     }
264
265     final String generatedAnnotation() {
266         return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
267     }
268
269     /**
270      * Run type analysis, which results in identification of the augmentable type, as well as all methods available
271      * to the type, expressed as properties.
272      */
273     static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
274         final Set<MethodSignature> methods = new LinkedHashSet<>();
275         final Type augmentType = createMethods(type, methods);
276         final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
277                 .build();
278
279         return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
280     }
281
282     static final Restrictions restrictionsForSetter(final Type actualType) {
283         return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
284     }
285
286     static final Restrictions getRestrictions(final Type type) {
287         if (type instanceof ConcreteType) {
288             return ((ConcreteType) type).getRestrictions();
289         }
290         if (type instanceof GeneratedTransferObject) {
291             return ((GeneratedTransferObject) type).getRestrictions();
292         }
293         return null;
294     }
295
296     /**
297      * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
298      *
299      * @param property Generated property
300      * @return The string used to clone the property, or an empty string
301      */
302     static final String cloneCall(final GeneratedProperty property) {
303         return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
304     }
305
306     /**
307      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
308      * and all the methods of the implemented interfaces.
309      *
310      * @returns set of method signature instances
311      */
312     private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
313         methods.addAll(type.getMethodDefinitions());
314         return collectImplementedMethods(type, methods, type.getImplements());
315     }
316
317     /**
318      * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
319      * and recursively their implemented interfaces.
320      *
321      * @param methods set of method signatures
322      * @param implementedIfcs list of implemented interfaces
323      */
324     private static ParameterizedType collectImplementedMethods(final GeneratedType type,
325             final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
326         if (implementedIfcs == null || implementedIfcs.isEmpty()) {
327             return null;
328         }
329
330         ParameterizedType augmentType = null;
331         for (Type implementedIfc : implementedIfcs) {
332             if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
333                 final GeneratedType ifc = (GeneratedType) implementedIfc;
334                 addImplMethods(methods, ifc);
335
336                 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
337                 if (t != null && augmentType == null) {
338                     augmentType = t;
339                 }
340             } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
341                 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
342             }
343         }
344
345         return augmentType;
346     }
347
348     private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
349         for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
350             if (hasOverrideAnnotation(implMethod)) {
351                 methods.add(implMethod);
352             } else {
353                 final String implMethodName = implMethod.getName();
354                 if (BindingMapping.isGetterMethodName(implMethodName)
355                         && getterByName(methods, implMethodName).isEmpty()) {
356
357                     methods.add(implMethod);
358                 }
359             }
360         }
361     }
362
363     protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
364             final String implMethodName) {
365         for (MethodSignature method : methods) {
366             final String methodName = method.getName();
367             if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
368                 return Optional.of(method);
369             }
370         }
371         return Optional.empty();
372     }
373
374     protected static String propertyNameFromGetter(final MethodSignature getter) {
375         return propertyNameFromGetter(getter.getName());
376     }
377
378     protected static String propertyNameFromGetter(final String getterName) {
379         final String prefix;
380         if (BindingMapping.isGetterMethodName(getterName)) {
381             prefix = BindingMapping.GETTER_PREFIX;
382         } else if (BindingMapping.isNonnullMethodName(getterName)) {
383             prefix = BindingMapping.NONNULL_PREFIX;
384         } else if (BindingMapping.isRequireMethodName(getterName)) {
385             prefix = BindingMapping.REQUIRE_PREFIX;
386         } else {
387             throw new IllegalArgumentException(getterName + " is not a getter");
388         }
389         return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
390     }
391
392     /**
393      * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
394      *
395      * @param method Method to examine
396      * @return True if there is an override annotation
397      */
398     static boolean hasOverrideAnnotation(final MethodSignature method) {
399         for (final AnnotationType annotation : method.getAnnotations()) {
400             if (OVERRIDE.equals(annotation.getIdentifier())) {
401                 return true;
402             }
403         }
404         return false;
405     }
406
407     static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
408         type.getYangSourceDefinition().ifPresent(def -> {
409             sb.append('\n');
410
411             if (def instanceof Single) {
412                 final DocumentedNode node = ((Single) def).getNode();
413
414                 sb.append("<p>\n")
415                     .append("This class represents the following YANG schema fragment defined in module <b>")
416                     .append(def.getModule().argument().getLocalName()).append("</b>\n")
417                     .append("<pre>\n");
418                 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
419                 sb.append("</pre>");
420
421                 if (node instanceof SchemaNode) {
422                     final SchemaNode schema = (SchemaNode) node;
423 //                    sb.append("The schema path to identify an instance is\n");
424 //                    appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
425 //                    sb.append("</i>\n");
426
427                     if (hasBuilderClass(schema)) {
428                         final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
429
430                         sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
431                         .append("}.\n")
432                         .append("@see ").append(builderName).append('\n');
433                         if (node instanceof ListSchemaNode) {
434                             final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
435                             if (!keyDef.isEmpty()) {
436                                 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
437                             }
438                             sb.append('\n');
439                         }
440                     }
441                 }
442             } else if (def instanceof Multiple) {
443                 sb.append("<pre>\n");
444                 for (SchemaNode node : ((Multiple) def).getNodes()) {
445                     appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
446                 }
447                 sb.append("</pre>\n");
448             }
449         });
450     }
451
452     static String encodeJavadocSymbols(final String description) {
453         // FIXME: Use String.isBlank()?
454         return description == null || description.isEmpty() ? description
455             : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&amp;")).replaceAll("&#42;&#47;");
456     }
457
458     private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
459         final DeclaredStatement<?> stmt) {
460         for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
461             sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
462         }
463     }
464
465 //    private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
466 //            final List<QName> path) {
467 //        if (!path.isEmpty()) {
468 //            // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
469 //            sb.append(module.argument().getLocalName());
470 //            XMLNamespace currentNamespace = path.get(0).getNamespace();
471 //
472 //            for (QName pathElement : path) {
473 //                final XMLNamespace elementNamespace = pathElement.getNamespace();
474 //                if (!elementNamespace.equals(currentNamespace)) {
475 //                    sb.append(pathElement);
476 //                    currentNamespace = elementNamespace;
477 //                } else {
478 //                    sb.append(pathElement.getLocalName());
479 //                }
480 //            }
481 //        }
482 //    }
483
484     private static boolean hasBuilderClass(final SchemaNode schemaNode) {
485         return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
486                 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
487     }
488
489     private static boolean isSameProperty(final String getterName1, final String getterName2) {
490         return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
491     }
492
493     /**
494      * Creates set of generated property instances from getter <code>methods</code>.
495      *
496      * @param methods set of method signature instances which should be transformed to list of properties
497      * @return set of generated property instances which represents the getter <code>methods</code>
498      */
499     private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
500         if (methods == null || methods.isEmpty()) {
501             return Collections.emptySet();
502         }
503         final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
504         for (MethodSignature m : methods) {
505             final BuilderGeneratedProperty createdField = propertyFromGetter(m);
506             if (createdField != null) {
507                 result.add(createdField);
508             }
509         }
510         return result;
511     }
512
513     /**
514      * Creates generated property instance from the getter <code>method</code> name and return type.
515      *
516      * @param method method signature from which is the method name and return type obtained
517      * @return generated property instance for the getter <code>method</code>
518      * @throws IllegalArgumentException <ul>
519      *                                    <li>if the {@code method} equals {@code null}</li>
520      *                                    <li>if the name of the {@code method} equals {@code null}</li>
521      *                                    <li>if the name of the {@code method} is empty</li>
522      *                                    <li>if the return type of the {@code method} equals {@code null}</li>
523      *                                  </ul>
524      */
525     private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
526         checkArgument(method != null);
527         checkArgument(method.getReturnType() != null);
528         checkArgument(method.getName() != null);
529         checkArgument(!method.getName().isEmpty());
530         if (method.isDefault()) {
531             return null;
532         }
533         if (!BindingMapping.isGetterMethodName(method.getName())) {
534             return null;
535         }
536
537         final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
538         return new BuilderGeneratedProperty(fieldName, method);
539     }
540 }