2 * Copyright (c) 2018 Pantheon Technologies, s.r.o. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.java.api.generator;
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;
16 import com.google.common.base.CharMatcher;
17 import com.google.common.collect.ImmutableSortedSet;
18 import java.lang.reflect.Method;
19 import java.util.AbstractMap;
20 import java.util.Arrays;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashMap;
25 import java.util.LinkedHashSet;
26 import java.util.List;
28 import java.util.NoSuchElementException;
29 import java.util.Objects;
30 import java.util.Optional;
32 import java.util.regex.Pattern;
33 import java.util.stream.Collectors;
34 import javax.annotation.processing.Generated;
35 import org.eclipse.jdt.annotation.NonNull;
36 import org.eclipse.xtext.xbase.lib.StringExtensions;
37 import org.opendaylight.mdsal.binding.model.api.AnnotationType;
38 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
42 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
43 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
44 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
45 import org.opendaylight.mdsal.binding.model.api.Restrictions;
46 import org.opendaylight.mdsal.binding.model.api.Type;
47 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Multiple;
48 import org.opendaylight.mdsal.binding.model.api.YangSourceDefinition.Single;
49 import org.opendaylight.mdsal.binding.model.ri.Types;
50 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
51 import org.opendaylight.yangtools.yang.binding.Augmentable;
52 import org.opendaylight.yangtools.yang.binding.CodeHelpers;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.XMLNamespace;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
57 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
62 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
63 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
64 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleEffectiveStatement;
65 import org.opendaylight.yangtools.yang.model.export.DeclaredStatementFormatter;
68 * Base Java file template. Contains a non-null type and imports which the generated code refers to.
70 class JavaFileTemplate {
72 * {@code java.lang.Class} as a JavaTypeName.
74 static final @NonNull JavaTypeName CLASS = JavaTypeName.create(Class.class);
76 * {@code java.lang.Deprecated} as a JavaTypeName.
78 static final @NonNull JavaTypeName DEPRECATED = JavaTypeName.create(Deprecated.class);
80 * {@code java.lang.NullPointerException} as a JavaTypeName.
82 static final @NonNull JavaTypeName NPE = JavaTypeName.create(NullPointerException.class);
84 * {@code java.lang.NoSuchElementException} as a JavaTypeName.
86 static final @NonNull JavaTypeName NSEE = JavaTypeName.create(NoSuchElementException.class);
88 * {@code java.lang.Override} as a JavaTypeName.
90 static final @NonNull JavaTypeName OVERRIDE = JavaTypeName.create(Override.class);
92 * {@code java.lang.void} as a JavaTypeName.
94 static final @NonNull JavaTypeName SUPPRESS_WARNINGS = JavaTypeName.create(SuppressWarnings.class);
96 * {@code java.lang.SuppressWarnings} as a JavaTypeName.
98 static final @NonNull JavaTypeName VOID = JavaTypeName.create(void.class);
101 * {@code java.util.Arrays} as a JavaTypeName.
103 static final @NonNull JavaTypeName JU_ARRAYS = JavaTypeName.create(Arrays.class);
105 * {@code java.util.HashMap} as a JavaTypeName.
107 static final @NonNull JavaTypeName JU_HASHMAP = JavaTypeName.create(HashMap.class);
109 * {@code java.util.List} as a JavaTypeName.
111 static final @NonNull JavaTypeName JU_LIST = JavaTypeName.create(List.class);
113 * {@code java.util.Map} as a JavaTypeName.
115 static final @NonNull JavaTypeName JU_MAP = JavaTypeName.create(Map.class);
117 * {@code java.util.Objects} as a JavaTypeName.
119 static final @NonNull JavaTypeName JU_OBJECTS = JavaTypeName.create(Objects.class);
121 * {@code java.util.regex.Pattern} as a JavaTypeName.
123 static final @NonNull JavaTypeName JUR_PATTERN = JavaTypeName.create(Pattern.class);
126 * {@code javax.annotation.processing.Generated} as a JavaTypeName.
128 static final @NonNull JavaTypeName GENERATED = JavaTypeName.create(Generated.class);
131 * {@code org.eclipse.jdt.annotation.NonNull} as a JavaTypeName.
133 static final @NonNull JavaTypeName NONNULL = JavaTypeName.create("org.eclipse.jdt.annotation", "NonNull");
135 * {@code org.eclipse.jdt.annotation.Nullable} as a JavaTypeName.
137 static final @NonNull JavaTypeName NULLABLE = JavaTypeName.create("org.eclipse.jdt.annotation", "Nullable");
140 * {@code org.opendaylight.yangtools.yang.binding.CodeHelpers} as a JavaTypeName.
142 static final @NonNull JavaTypeName CODEHELPERS = JavaTypeName.create(CodeHelpers.class);
145 private static final Comparator<MethodSignature> METHOD_COMPARATOR = new AlphabeticallyTypeMemberComparator<>();
146 private static final CharMatcher AMP_MATCHER = CharMatcher.is('&');
147 private static final Pattern TAIL_COMMENT_PATTERN = Pattern.compile("*/", Pattern.LITERAL);
148 private static final DeclaredStatementFormatter YANG_FORMATTER = DeclaredStatementFormatter.builder()
149 .addIgnoredStatement(YangStmtMapping.CONTACT)
150 .addIgnoredStatement(YangStmtMapping.DESCRIPTION)
151 .addIgnoredStatement(YangStmtMapping.REFERENCE)
152 .addIgnoredStatement(YangStmtMapping.ORGANIZATION)
154 private static final int GETTER_PREFIX_LENGTH = BindingMapping.GETTER_PREFIX.length();
155 private static final Type AUGMENTATION_RET_TYPE;
160 m = Augmentable.class.getDeclaredMethod(BindingMapping.AUGMENTABLE_AUGMENTATION_NAME, Class.class);
161 } catch (NoSuchMethodException e) {
162 throw new ExceptionInInitializerError(e);
165 AUGMENTATION_RET_TYPE = Type.of(JavaTypeName.create(m.getReturnType()));
168 private final AbstractJavaGeneratedType javaType;
169 private final GeneratedType type;
171 JavaFileTemplate(final @NonNull GeneratedType type) {
172 this(new TopLevelJavaGeneratedType(type), type);
175 JavaFileTemplate(final AbstractJavaGeneratedType javaType, final GeneratedType type) {
176 this.javaType = requireNonNull(javaType);
177 this.type = requireNonNull(type);
180 final AbstractJavaGeneratedType javaType() {
184 final GeneratedType type() {
188 final String generateImportBlock() {
189 verify(javaType instanceof TopLevelJavaGeneratedType);
190 return ((TopLevelJavaGeneratedType) javaType).imports().map(name -> "import " + name + ";\n")
191 .collect(Collectors.joining());
194 final @NonNull String importedJavadocName(final @NonNull Type intype) {
195 return importedName(intype instanceof ParameterizedType ? ((ParameterizedType) intype).getRawType() : intype);
198 final @NonNull String importedName(final @NonNull Type intype) {
199 return javaType.getReferenceString(intype);
202 final @NonNull String importedName(final @NonNull Type intype, final @NonNull String annotation) {
203 return javaType.getReferenceString(intype, annotation);
206 final @NonNull String importedName(final Class<?> cls) {
207 return importedName(Types.typeForClass(cls));
210 final @NonNull String importedName(final @NonNull JavaTypeName intype) {
211 return javaType.getReferenceString(intype);
214 final @NonNull String importedNonNull(final @NonNull Type intype) {
215 return importedName(intype, importedName(NONNULL));
218 final @NonNull String importedNullable(final @NonNull Type intype) {
219 return importedName(intype, importedName(NULLABLE));
222 final @NonNull String fullyQualifiedNonNull(final @NonNull Type intype) {
223 return fullyQualifiedName(intype, importedName(NONNULL));
226 final @NonNull String fullyQualifiedName(final @NonNull Type intype, final @NonNull String annotation) {
227 return javaType.getFullyQualifiedReference(intype, annotation);
230 // Exposed for BuilderTemplate
231 boolean isLocalInnerClass(final JavaTypeName name) {
232 final Optional<JavaTypeName> optEnc = name.immediatelyEnclosingClass();
233 return optEnc.isPresent() && type.getIdentifier().equals(optEnc.get());
236 final CharSequence generateInnerClass(final GeneratedType innerClass) {
237 if (!(innerClass instanceof GeneratedTransferObject)) {
241 final GeneratedTransferObject gto = (GeneratedTransferObject) innerClass;
242 final NestedJavaGeneratedType innerJavaType = javaType.getEnclosedType(innerClass.getIdentifier());
243 return gto.isUnionType() ? new UnionTemplate(innerJavaType, gto).generateAsInnerClass()
244 : new ClassTemplate(innerJavaType, gto).generateAsInnerClass();
248 * Return imported name of java.util class, whose hashCode/equals methods we want to invoke on the property. Returns
249 * {@link Arrays} if the property is an array, {@link Objects} otherwise.
251 * @param property Generated property
252 * @return Imported class name
254 final String importedUtilClass(final GeneratedProperty property) {
255 return importedName(property.getReturnType().getName().indexOf('[') != -1 ? JU_ARRAYS : JU_OBJECTS);
258 final String generatedAnnotation() {
259 return "@" + importedName(GENERATED) + "(\"mdsal-binding-generator\")";
263 * Run type analysis, which results in identification of the augmentable type, as well as all methods available
264 * to the type, expressed as properties.
266 static Map.Entry<Type, Set<BuilderGeneratedProperty>> analyzeTypeHierarchy(final GeneratedType type) {
267 final Set<MethodSignature> methods = new LinkedHashSet<>();
268 final Type augmentType = createMethods(type, methods);
269 final Set<MethodSignature> sortedMethods = ImmutableSortedSet.orderedBy(METHOD_COMPARATOR).addAll(methods)
272 return new AbstractMap.SimpleImmutableEntry<>(augmentType, propertiesFromMethods(sortedMethods));
275 static final Restrictions restrictionsForSetter(final Type actualType) {
276 return actualType instanceof GeneratedType ? null : getRestrictions(actualType);
279 static final Restrictions getRestrictions(final Type type) {
280 if (type instanceof ConcreteType) {
281 return ((ConcreteType) type).getRestrictions();
283 if (type instanceof GeneratedTransferObject) {
284 return ((GeneratedTransferObject) type).getRestrictions();
290 * Generate a call to {@link Object#clone()} if target field represents an array. Returns an empty string otherwise.
292 * @param property Generated property
293 * @return The string used to clone the property, or an empty string
295 static final String cloneCall(final GeneratedProperty property) {
296 return property.getReturnType().getName().endsWith("[]") ? ".clone()" : "";
300 * Returns set of method signature instances which contains all the methods of the <code>genType</code>
301 * and all the methods of the implemented interfaces.
303 * @returns set of method signature instances
305 private static ParameterizedType createMethods(final GeneratedType type, final Set<MethodSignature> methods) {
306 methods.addAll(type.getMethodDefinitions());
307 return collectImplementedMethods(type, methods, type.getImplements());
311 * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
312 * and recursively their implemented interfaces.
314 * @param methods set of method signatures
315 * @param implementedIfcs list of implemented interfaces
317 private static ParameterizedType collectImplementedMethods(final GeneratedType type,
318 final Set<MethodSignature> methods, final List<Type> implementedIfcs) {
319 if (implementedIfcs == null || implementedIfcs.isEmpty()) {
323 ParameterizedType augmentType = null;
324 for (Type implementedIfc : implementedIfcs) {
325 if (implementedIfc instanceof GeneratedType && !(implementedIfc instanceof GeneratedTransferObject)) {
326 final GeneratedType ifc = (GeneratedType) implementedIfc;
327 addImplMethods(methods, ifc);
329 final ParameterizedType t = collectImplementedMethods(type, methods, ifc.getImplements());
330 if (t != null && augmentType == null) {
333 } else if (Augmentable.class.getName().equals(implementedIfc.getFullyQualifiedName())) {
334 augmentType = Types.parameterizedTypeFor(AUGMENTATION_RET_TYPE, Type.of(type.getIdentifier()));
341 private static void addImplMethods(final Set<MethodSignature> methods, final GeneratedType implType) {
342 for (final MethodSignature implMethod : implType.getMethodDefinitions()) {
343 if (hasOverrideAnnotation(implMethod)) {
344 methods.add(implMethod);
346 final String implMethodName = implMethod.getName();
347 if (BindingMapping.isGetterMethodName(implMethodName)
348 && getterByName(methods, implMethodName).isEmpty()) {
350 methods.add(implMethod);
356 protected static Optional<MethodSignature> getterByName(final Iterable<MethodSignature> methods,
357 final String implMethodName) {
358 for (MethodSignature method : methods) {
359 final String methodName = method.getName();
360 if (BindingMapping.isGetterMethodName(methodName) && isSameProperty(method.getName(), implMethodName)) {
361 return Optional.of(method);
364 return Optional.empty();
367 protected static String propertyNameFromGetter(final MethodSignature getter) {
368 return propertyNameFromGetter(getter.getName());
371 protected static String propertyNameFromGetter(final String getterName) {
373 if (BindingMapping.isGetterMethodName(getterName)) {
374 prefix = BindingMapping.GETTER_PREFIX;
375 } else if (BindingMapping.isNonnullMethodName(getterName)) {
376 prefix = BindingMapping.NONNULL_PREFIX;
377 } else if (BindingMapping.isRequireMethodName(getterName)) {
378 prefix = BindingMapping.REQUIRE_PREFIX;
380 throw new IllegalArgumentException(getterName + " is not a getter");
382 return StringExtensions.toFirstLower(getterName.substring(prefix.length()));
386 * Check whether specified method has an attached annotation which corresponds to {@code @Override}.
388 * @param method Method to examine
389 * @return True if there is an override annotation
391 static boolean hasOverrideAnnotation(final MethodSignature method) {
392 for (final AnnotationType annotation : method.getAnnotations()) {
393 if (OVERRIDE.equals(annotation.getIdentifier())) {
400 static void appendSnippet(final StringBuilder sb, final GeneratedType type) {
401 type.getYangSourceDefinition().ifPresent(def -> {
404 if (def instanceof Single) {
405 final DocumentedNode node = ((Single) def).getNode();
408 .append("This class represents the following YANG schema fragment defined in module <b>")
409 .append(def.getModule().argument().getLocalName()).append("</b>\n")
411 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
414 if (node instanceof SchemaNode) {
415 final SchemaNode schema = (SchemaNode) node;
416 sb.append("The schema path to identify an instance is\n");
417 appendPath(sb.append("<i>"), def.getModule(), schema.getPath().getPathFromRoot());
420 if (hasBuilderClass(schema)) {
421 final String builderName = type.getName() + BindingMapping.BUILDER_SUFFIX;
423 sb.append("\n<p>To create instances of this class use {@link ").append(builderName)
425 .append("@see ").append(builderName).append('\n');
426 if (node instanceof ListSchemaNode) {
427 final var keyDef = ((ListSchemaNode) node).getKeyDefinition();
428 if (!keyDef.isEmpty()) {
429 sb.append("@see ").append(type.getName()).append(BindingMapping.KEY_SUFFIX);
435 } else if (def instanceof Multiple) {
436 sb.append("<pre>\n");
437 for (SchemaNode node : ((Multiple) def).getNodes()) {
438 appendYangSnippet(sb, def.getModule(), ((EffectiveStatement<?, ?>) node).getDeclared());
440 sb.append("</pre>\n");
445 static String encodeJavadocSymbols(final String description) {
446 // FIXME: Use String.isBlank()?
447 return description == null || description.isEmpty() ? description
448 : TAIL_COMMENT_PATTERN.matcher(AMP_MATCHER.replaceFrom(description, "&")).replaceAll("*/");
451 private static void appendYangSnippet(final StringBuilder sb, final ModuleEffectiveStatement module,
452 final DeclaredStatement<?> stmt) {
453 for (String str : YANG_FORMATTER.toYangTextSnippet(module, stmt)) {
454 sb.append(replaceAllIllegalChars(encodeAngleBrackets(encodeJavadocSymbols(str))));
458 private static void appendPath(final StringBuilder sb, final ModuleEffectiveStatement module,
459 final List<QName> path) {
460 if (!path.isEmpty()) {
461 // FIXME: this is module name, while when we switch, we end up using QName.toString() -- which is weird
462 sb.append(module.argument().getLocalName());
463 XMLNamespace currentNamespace = path.get(0).getNamespace();
465 for (QName pathElement : path) {
466 final XMLNamespace elementNamespace = pathElement.getNamespace();
467 if (!elementNamespace.equals(currentNamespace)) {
468 sb.append(pathElement);
469 currentNamespace = elementNamespace;
471 sb.append(pathElement.getLocalName());
477 private static boolean hasBuilderClass(final SchemaNode schemaNode) {
478 return schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode
479 || schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition;
482 private static boolean isSameProperty(final String getterName1, final String getterName2) {
483 return propertyNameFromGetter(getterName1).equals(propertyNameFromGetter(getterName2));
487 * Creates set of generated property instances from getter <code>methods</code>.
489 * @param methods set of method signature instances which should be transformed to list of properties
490 * @return set of generated property instances which represents the getter <code>methods</code>
492 private static Set<BuilderGeneratedProperty> propertiesFromMethods(final Collection<MethodSignature> methods) {
493 if (methods == null || methods.isEmpty()) {
494 return Collections.emptySet();
496 final Set<BuilderGeneratedProperty> result = new LinkedHashSet<>();
497 for (MethodSignature m : methods) {
498 final BuilderGeneratedProperty createdField = propertyFromGetter(m);
499 if (createdField != null) {
500 result.add(createdField);
507 * Creates generated property instance from the getter <code>method</code> name and return type.
509 * @param method method signature from which is the method name and return type obtained
510 * @return generated property instance for the getter <code>method</code>
511 * @throws IllegalArgumentException <ul>
512 * <li>if the {@code method} equals {@code null}</li>
513 * <li>if the name of the {@code method} equals {@code null}</li>
514 * <li>if the name of the {@code method} is empty</li>
515 * <li>if the return type of the {@code method} equals {@code null}</li>
518 private static BuilderGeneratedProperty propertyFromGetter(final MethodSignature method) {
519 checkArgument(method != null);
520 checkArgument(method.getReturnType() != null);
521 checkArgument(method.getName() != null);
522 checkArgument(!method.getName().isEmpty());
523 if (method.isDefault()) {
526 if (!BindingMapping.isGetterMethodName(method.getName())) {
530 final String fieldName = StringExtensions.toFirstLower(method.getName().substring(GETTER_PREFIX_LENGTH));
531 return new BuilderGeneratedProperty(fieldName, method);