forked from opprop/checker-framework-inference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInferenceUtil.java
More file actions
332 lines (281 loc) · 11.9 KB
/
InferenceUtil.java
File metadata and controls
332 lines (281 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package checkers.inference.util;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedWildcardType;
import org.checkerframework.javacutil.AnnotationMirrorSet;
import org.checkerframework.javacutil.BugInCF;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.lang.model.element.AnnotationMirror;
public class InferenceUtil {
/**
* Clear all primary annotations on atm
*
* @return the set of cleared annotations
*/
public static AnnotationMirrorSet clearAnnos(final AnnotatedTypeMirror atm) {
final AnnotationMirrorSet oldAnnos = new AnnotationMirrorSet();
oldAnnos.addAll(atm.getAnnotations());
atm.clearAnnotations();
return oldAnnos;
}
/**
* TODO: This method is similar to the code in https://github.com/eisop/checker-framework
* /blob/6f12277290642f8fb89a5c614b31fe419eb0a7b1/framework/src/main/java/
* org/checkerframework/framework/type/DefaultInferredTypesApplier.java#L134, it should be
* cleaned up when the code of this link is improved.
*/
public static void removePrimaryTypeVariableAnnotation(
AnnotatedTypeVariable atv, AnnotationMirror potentialVarAnno) {
AnnotationMirror ub = atv.getUpperBound().getAnnotationInHierarchy(potentialVarAnno);
AnnotationMirror lb = atv.getLowerBound().getAnnotationInHierarchy(potentialVarAnno);
atv.removeAnnotation(potentialVarAnno);
if (ub != null) {
atv.getUpperBound().addAnnotation(ub);
}
if (lb != null) {
atv.getLowerBound().addAnnotation(lb);
}
}
/**
* If the given condition isn't true throw an illegal argument exception with the given message
*/
public static void testArgument(boolean condition, final String message) {
if (!condition) {
throw new IllegalArgumentException(message);
}
}
/** Is the given classTree a declaration of an anonymous class */
public static boolean isAnonymousClass(ClassTree classTree) {
return (classTree.getSimpleName() == null)
|| (classTree.getSimpleName().toString().equals(""));
}
/** Is this newClassTree a declaration of an anonymous class */
public static boolean isAnonymousClass(NewClassTree newClassTree) {
if (newClassTree.getClassBody() == null) {
return false;
}
return isAnonymousClass(newClassTree.getClassBody());
}
/**
* Converts the collection to a string using its natural ordering. Objects are converted using
* their toString method and then delimited by a comma (,)
*
* @param toPrint The collection to joined together as a string.
* @return toPrint in string form
*/
public static String join(Collection<?> toPrint) {
return join(toPrint, ", ");
}
/**
* Converts the collection to a string using its natural ordering. Objects are converted using
* their toString method and then delimited by separator
*
* @param toPrint The collection to joined together as a string.
* @return all elements of toPrint converted to strings and separated by separator
*/
public static String join(Collection<?> toPrint, final String separator) {
if (toPrint == null) {
return null;
}
if (toPrint.isEmpty()) {
return "";
}
Iterator<?> iterator = toPrint.iterator();
StringBuilder sb = new StringBuilder();
sb.append(iterator.next());
while (iterator.hasNext()) {
sb.append(separator);
sb.append(iterator.next().toString());
}
return sb.toString();
}
/**
* For the given map, create a string from all entries in the map's natural order, separated by
* ", "
*
* @see checkers.inference.util.InferenceUtil#join(java.util.Map, String)
* @param toPrint The Map we wish to create a string from
* @return A string containing the entries of toPrint separated by separator
*/
public static String join(Map<?, ?> toPrint) {
return join(toPrint, ", ");
}
/**
* For the given map, create a string from all entries in the map's natural order arranged as
* follows: Key1 -> Value1<separator>Key2 -> Value2<separator>...KeyN -> ValueN e.g for a Map( 1
* -> "One", 2 -> "Two", 3 -> "Three" ) and a separator of "_sep_" the output would be "1 ->
* One_sep_2 -> Two_sep_3 -> Three
*
* @param toPrint The Map we wish to create a string from
* @return A string containing the entries of toPrint separated by separator
*/
public static String join(Map<?, ?> toPrint, final String separator) {
if (toPrint == null) {
return null;
}
if (toPrint.isEmpty()) {
return "";
}
final Iterator<? extends Map.Entry<?, ?>> iterator = toPrint.entrySet().iterator();
final StringBuilder sb = new StringBuilder();
final Map.Entry<?, ?> first = iterator.next();
sb.append(first.getKey() + " -> " + first.getValue());
for (Map.Entry<?, ?> entry : toPrint.entrySet()) {
sb.append(separator);
sb.append(entry.getKey() + " -> " + entry.getValue());
}
return sb.toString();
}
private static List<String> detachedVarSymbols =
Arrays.asList("index#num", "iter#num", "assertionsEnabled#num", "array#num");
public static boolean isDetachedVariable(Tree targetTree) {
String name;
if (targetTree instanceof VariableTree) {
name = ((VariableTree) targetTree).getName().toString();
} else if (targetTree instanceof IdentifierTree) {
name = ((IdentifierTree) targetTree).getName().toString();
} else {
return false;
}
for (String str : detachedVarSymbols) {
if (name.startsWith(str)) {
return true;
}
}
return false;
}
public static AnnotatedTypeMirror findUpperBoundType(final AnnotatedTypeVariable typeVariable) {
return findUpperBoundType(typeVariable, false);
}
public static AnnotatedTypeMirror findUpperBoundType(
final AnnotatedTypeVariable typeVariable, final boolean allowUnannotatedTypes) {
AnnotatedTypeMirror upperBoundType = typeVariable.getUpperBound();
while (upperBoundType.getAnnotations().isEmpty()) {
switch (upperBoundType.getKind()) {
case TYPEVAR:
upperBoundType = ((AnnotatedTypeVariable) upperBoundType).getUpperBound();
break;
case WILDCARD:
upperBoundType = ((AnnotatedWildcardType) upperBoundType).getExtendsBound();
break;
case INTERSECTION:
// TODO: We need clear semantics for INTERSECTIONS, using first
// alternative for now
upperBoundType = upperBoundType.directSupertypes().get(0);
break;
default:
if (!allowUnannotatedTypes) {
throw new BugInCF(
"Couldn't find upperBoundType, annotations are empty!:\n"
+ "typeVariable="
+ typeVariable
+ "\n"
+ "currentUpperBoundType="
+ upperBoundType);
} else {
return upperBoundType;
}
}
}
return upperBoundType;
}
public static AnnotatedTypeMirror findLowerBoundType(final AnnotatedTypeVariable typeVariable) {
return findLowerBoundType(typeVariable, false);
}
public static AnnotatedTypeMirror findLowerBoundType(
final AnnotatedTypeVariable typeVariable, final boolean allowUnannotatedTypes) {
AnnotatedTypeMirror lowerBoundType = typeVariable.getLowerBound();
while (lowerBoundType.getAnnotations().isEmpty()) {
switch (lowerBoundType.getKind()) {
case TYPEVAR:
lowerBoundType = ((AnnotatedTypeVariable) lowerBoundType).getLowerBound();
break;
case WILDCARD:
lowerBoundType = ((AnnotatedWildcardType) lowerBoundType).getSuperBound();
break;
case INTERSECTION:
// TODO: We need clear semantics for INTERSECTIONS, using first alternative for
// now
lowerBoundType = lowerBoundType.directSupertypes().get(0);
break;
default:
if (!allowUnannotatedTypes) {
throw new BugInCF(
"Couldn't find lowerBoundType, annotations are empty!:\n"
+ "typeVariable="
+ typeVariable
+ "\n"
+ "currentLowerBoundType="
+ lowerBoundType);
} else {
return lowerBoundType;
}
}
}
return lowerBoundType;
}
/** Set the root logging level and handler level. */
public static void setLoggingLevel(Level level) {
Logger root = Logger.getLogger("");
root.setLevel(level);
// Handler for console (reuse it if it already exists)
Handler consoleHandler = null;
// see if there is already a console handler
for (Handler handler : root.getHandlers()) {
if (handler instanceof ConsoleHandler) {
// found the console handler
consoleHandler = handler;
break;
}
}
if (consoleHandler == null) {
// there was no console handler found, create a new one
consoleHandler = new ConsoleHandler();
root.addHandler(consoleHandler);
}
// set the console handler to fine:
consoleHandler.setLevel(level);
}
public static void flushAllLoggers(boolean flushSystemOut) {
LogManager logMan = LogManager.getLogManager();
Enumeration<String> logNames = LogManager.getLogManager().getLoggerNames();
while (logNames.hasMoreElements()) {
for (Handler handler : logMan.getLogger(logNames.nextElement()).getHandlers()) {
handler.flush();
}
}
if (flushSystemOut) {
System.out.flush();
}
}
public static <KEY, VALUE> LinkedHashMap<KEY, VALUE> makeOrderedMap(
Set<KEY> keys, Collection<VALUE> values) {
if (keys.size() != values.size()) {
throw new RuntimeException("Keys.size != values.size" + keys + "\n -> \n" + values);
}
final LinkedHashMap<KEY, VALUE> result = new LinkedHashMap<>();
Iterator<KEY> keyIter = keys.iterator();
Iterator<VALUE> valueIter = values.iterator();
while (keyIter.hasNext()) {
result.put(keyIter.next(), valueIter.next());
}
return result;
}
}