Specialize JavaFileTemplate.importedName(Type)
[mdsal.git] / binding / mdsal-binding-java-api-generator / src / main / java / org / opendaylight / mdsal / binding / java / api / generator / AbstractJavaGeneratedType.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 java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableMap.Builder;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Iterables;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Map;
19 import java.util.Set;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.mdsal.binding.model.api.Enumeration;
23 import org.opendaylight.mdsal.binding.model.api.Enumeration.Pair;
24 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
25 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
26 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
27 import org.opendaylight.mdsal.binding.model.api.Type;
28 import org.opendaylight.mdsal.binding.model.api.WildcardType;
29
30 /**
31  * Abstract class representing a generated type, either top-level or nested. It takes care of tracking references
32  * to other Java types and resolving them as best as possible. This class is NOT thread-safe.
33  *
34  * @author Robert Varga
35  */
36 @NonNullByDefault
37 abstract class AbstractJavaGeneratedType {
38     private final Map<JavaTypeName, @Nullable String> nameCache = new HashMap<>();
39     private final ImmutableMap<String, NestedJavaGeneratedType> enclosedTypes;
40     private final ImmutableSet<String> conflictingNames;
41
42     private final JavaTypeName name;
43
44     AbstractJavaGeneratedType(final GeneratedType genType) {
45         name = genType.getIdentifier();
46         final Builder<String, NestedJavaGeneratedType> b = ImmutableMap.builder();
47         for (GeneratedType type : Iterables.concat(genType.getEnclosedTypes(), genType.getEnumerations())) {
48             b.put(type.getIdentifier().simpleName(), new NestedJavaGeneratedType(this, type));
49         }
50         enclosedTypes = b.build();
51
52         final Set<String> cb = new HashSet<>();
53         if (genType instanceof Enumeration) {
54             ((Enumeration) genType).getValues().stream().map(Pair::getMappedName).forEach(cb::add);
55         }
56         // TODO: perhaps we can do something smarter to actually access the types
57         collectAccessibleTypes(cb, genType);
58
59         conflictingNames = ImmutableSet.copyOf(cb);
60     }
61
62     private void collectAccessibleTypes(final Set<String> set, final GeneratedType type) {
63         for (Type impl : type.getImplements()) {
64             if (impl instanceof GeneratedType) {
65                 final GeneratedType genType = (GeneratedType) impl;
66                 for (GeneratedType inner : Iterables.concat(genType.getEnclosedTypes(), genType.getEnumerations())) {
67                     set.add(inner.getIdentifier().simpleName());
68                 }
69                 collectAccessibleTypes(set, genType);
70             }
71         }
72     }
73
74     final JavaTypeName getName() {
75         return name;
76     }
77
78     final String getSimpleName() {
79         return name.simpleName();
80     }
81
82     final String getReferenceString(final Type type) {
83         final String ref = getReferenceString(type.getIdentifier());
84         return type instanceof ParameterizedType ? getReferenceString(new StringBuilder(ref), type,
85             ((ParameterizedType) type).getActualTypeArguments())
86                 : ref;
87     }
88
89     final String getReferenceString(final Type type, final String... annotations) {
90         // Package-private method, all callers who would be passing an empty array are bound to the more special
91         // case above, hence we know annotations.length >= 1
92         final String ref = getReferenceString(type.getIdentifier());
93         return type instanceof ParameterizedType ? getReferenceString(annotate(ref, annotations), type,
94             ((ParameterizedType) type).getActualTypeArguments())
95                 : annotate(ref, annotations).toString();
96     }
97
98     private String getReferenceString(final StringBuilder sb, final Type type, final Type[] arguments) {
99         if (arguments.length == 0) {
100             return sb.append("<?>").toString();
101         }
102
103         sb.append('<');
104         for (int i = 0; i < arguments.length; i++) {
105             final Type arg = arguments[i];
106             if (arg instanceof WildcardType) {
107                 sb.append("? extends ");
108             }
109             sb.append(getReferenceString(arg));
110             if (i != arguments.length - 1) {
111                 sb.append(", ");
112             }
113         }
114         return sb.append('>').toString();
115     }
116
117     final String getReferenceString(final JavaTypeName type) {
118         if (type.packageName().isEmpty()) {
119             // This is a packageless primitive type, refer to it directly
120             return type.simpleName();
121         }
122
123         // Self-reference, return simple name
124         if (name.equals(type)) {
125             return name.simpleName();
126         }
127
128         // Fast path: we have already resolved how to refer to this type
129         final String existing = nameCache.get(type);
130         if (existing != null) {
131             return existing;
132         }
133
134         // Fork based on whether the class is in this compilation unit, package or neither
135         final String result;
136         if (name.topLevelClass().equals(type.topLevelClass())) {
137             result = localTypeName(type);
138         } else if (name.packageName().equals(type.packageName())) {
139             result = packageTypeName(type);
140         } else {
141             result = foreignTypeName(type);
142         }
143
144         nameCache.put(type, result);
145         return result;
146     }
147
148     final NestedJavaGeneratedType getEnclosedType(final JavaTypeName type) {
149         return requireNonNull(enclosedTypes.get(type.simpleName()));
150     }
151
152     final boolean checkAndImportType(final JavaTypeName type) {
153         // We can import the type only if it does not conflict with us or our immediately-enclosed types
154         final String simpleName = type.simpleName();
155         return !simpleName.equals(getSimpleName()) && !enclosedTypes.containsKey(simpleName)
156                 && !conflictingNames.contains(simpleName) && importCheckedType(type);
157     }
158
159     abstract boolean importCheckedType(JavaTypeName type);
160
161     abstract String localTypeName(JavaTypeName type);
162
163     private String foreignTypeName(final JavaTypeName type) {
164         return checkAndImportType(type) ? type.simpleName() : type.toString();
165     }
166
167     private String packageTypeName(final JavaTypeName type) {
168         // Try to anchor the top-level type and use a local reference
169         return checkAndImportType(type.topLevelClass()) ? type.localName() : type.toString();
170     }
171
172     private static StringBuilder annotate(final String ref, final String... annotations) {
173         final StringBuilder sb = new StringBuilder();
174         final int dot = ref.lastIndexOf('.');
175         if (dot != -1) {
176             sb.append(ref, 0, dot + 1);
177         }
178         for (String annotation : annotations) {
179             sb.append('@').append(annotation).append(' ');
180         }
181
182         return sb.append(ref, dot + 1, ref.length());
183     }
184 }