forked from uber/NullAway
/
LibraryModelsHandler.java
636 lines (574 loc) · 26.9 KB
/
LibraryModelsHandler.java
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
* Copyright (c) 2017 Uber Technologies, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.uber.nullaway.handlers;
import static com.uber.nullaway.LibraryModels.MethodRef.methodRef;
import static com.uber.nullaway.Nullness.NONNULL;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.Sets;
import com.google.errorprone.VisitorState;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Types;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;
import com.uber.nullaway.LibraryModels;
import com.uber.nullaway.LibraryModels.MethodRef;
import com.uber.nullaway.NullAway;
import com.uber.nullaway.dataflow.AccessPath;
import com.uber.nullaway.dataflow.AccessPathNullnessPropagation;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.checkerframework.dataflow.cfg.node.MethodInvocationNode;
import org.checkerframework.dataflow.cfg.node.Node;
/**
* This Handler deals with any methods from unannotated packages for which we need a nullability
* model.
*
* <p>It loads the required LibraryModels and inserts their nullability information at the right
* points through the flow of our analysis.
*/
public class LibraryModelsHandler extends BaseNoOpHandler {
private final LibraryModels libraryModels;
@Nullable private OptimizedLibraryModels optLibraryModels;
public LibraryModelsHandler() {
super();
libraryModels = loadLibraryModels();
}
@Override
public ImmutableSet<Integer> onUnannotatedInvocationGetNonNullPositions(
NullAway analysis,
VisitorState state,
Symbol.MethodSymbol methodSymbol,
List<? extends ExpressionTree> actualParams,
ImmutableSet<Integer> nonNullPositions) {
return Sets.union(
nonNullPositions, getOptLibraryModels(state.context).nonNullParameters(methodSymbol))
.immutableCopy();
}
@Override
public ImmutableSet<Integer> onUnannotatedInvocationGetExplicitlyNullablePositions(
Context context,
Symbol.MethodSymbol methodSymbol,
ImmutableSet<Integer> explicitlyNullablePositions) {
return Sets.union(
explicitlyNullablePositions,
getOptLibraryModels(context).explicitlyNullableParameters(methodSymbol))
.immutableCopy();
}
@Override
public boolean onOverrideMayBeNullExpr(
NullAway analysis, ExpressionTree expr, VisitorState state, boolean exprMayBeNull) {
if (expr.getKind() == Tree.Kind.METHOD_INVOCATION
&& getOptLibraryModels(state.context)
.hasNullableReturn(
(Symbol.MethodSymbol) ASTHelpers.getSymbol(expr), state.getTypes())) {
return analysis.nullnessFromDataflow(state, expr) || exprMayBeNull;
}
if (expr.getKind() == Tree.Kind.METHOD_INVOCATION
&& getOptLibraryModels(state.context)
.hasNonNullReturn((Symbol.MethodSymbol) ASTHelpers.getSymbol(expr), state.getTypes())) {
return false;
}
return exprMayBeNull;
}
@Override
public NullnessHint onDataflowVisitMethodInvocation(
MethodInvocationNode node,
Types types,
Context context,
AccessPathNullnessPropagation.SubNodeValues inputs,
AccessPathNullnessPropagation.Updates thenUpdates,
AccessPathNullnessPropagation.Updates elseUpdates,
AccessPathNullnessPropagation.Updates bothUpdates) {
Symbol.MethodSymbol callee = ASTHelpers.getSymbol(node.getTree());
Preconditions.checkNotNull(callee);
setUnconditionalArgumentNullness(bothUpdates, node.getArguments(), callee, context);
setConditionalArgumentNullness(thenUpdates, elseUpdates, node.getArguments(), callee, context);
if (getOptLibraryModels(context).hasNonNullReturn(callee, types)) {
return NullnessHint.FORCE_NONNULL;
} else if (getOptLibraryModels(context).hasNullableReturn(callee, types)) {
return NullnessHint.HINT_NULLABLE;
} else {
return NullnessHint.UNKNOWN;
}
}
private void setConditionalArgumentNullness(
AccessPathNullnessPropagation.Updates thenUpdates,
AccessPathNullnessPropagation.Updates elseUpdates,
List<Node> arguments,
Symbol.MethodSymbol callee,
Context context) {
Set<Integer> nullImpliesTrueParameters =
getOptLibraryModels(context).nullImpliesTrueParameters(callee);
for (AccessPath accessPath : accessPathsAtIndexes(nullImpliesTrueParameters, arguments)) {
elseUpdates.set(accessPath, NONNULL);
}
}
private static Iterable<AccessPath> accessPathsAtIndexes(
Set<Integer> indexes, List<Node> arguments) {
List<AccessPath> result = new ArrayList<>();
for (Integer i : indexes) {
Preconditions.checkArgument(i >= 0 && i < arguments.size(), "Invalid argument index: " + i);
if (i >= 0 && i < arguments.size()) {
Node argument = arguments.get(i);
AccessPath ap = AccessPath.getAccessPathForNodeNoMapGet(argument);
if (ap != null) {
result.add(ap);
}
}
}
return result;
}
private OptimizedLibraryModels getOptLibraryModels(Context context) {
if (optLibraryModels == null) {
optLibraryModels = new OptimizedLibraryModels(libraryModels, context);
}
return optLibraryModels;
}
private void setUnconditionalArgumentNullness(
AccessPathNullnessPropagation.Updates bothUpdates,
List<Node> arguments,
Symbol.MethodSymbol callee,
Context context) {
Set<Integer> requiredNonNullParameters =
getOptLibraryModels(context).failIfNullParameters(callee);
for (AccessPath accessPath : accessPathsAtIndexes(requiredNonNullParameters, arguments)) {
bothUpdates.set(accessPath, NONNULL);
}
}
private static LibraryModels loadLibraryModels() {
Iterable<LibraryModels> externalLibraryModels =
ServiceLoader.load(LibraryModels.class, LibraryModels.class.getClassLoader());
ImmutableSet.Builder<LibraryModels> libModelsBuilder = new ImmutableSet.Builder<>();
libModelsBuilder.add(new DefaultLibraryModels()).addAll(externalLibraryModels);
return new CombinedLibraryModels(libModelsBuilder.build());
}
private static class DefaultLibraryModels implements LibraryModels {
private static final ImmutableSetMultimap<MethodRef, Integer> FAIL_IF_NULL_PARAMETERS =
new ImmutableSetMultimap.Builder<MethodRef, Integer>()
.put(methodRef("com.google.common.base.Preconditions", "<T>checkNotNull(T)"), 0)
.put(methodRef("java.util.Objects", "<T>requireNonNull(T)"), 0)
.put(methodRef("java.util.Objects", "<T>requireNonNull(T,java.lang.String)"), 0)
.put(methodRef("org.junit.Assert", "assertNotNull(java.lang.Object)"), 0)
.put(
methodRef("org.junit.Assert", "assertNotNull(java.lang.String,java.lang.Object)"),
1)
.put(
methodRef("org.junit.jupiter.api.Assertions", "assertNotNull(java.lang.Object)"), 0)
.put(
methodRef(
"org.junit.jupiter.api.Assertions",
"assertNotNull(java.lang.Object,java.lang.String)"),
0)
.put(
methodRef(
"org.junit.jupiter.api.Assertions",
"assertNotNull(java.lang.Object,java.util.function.Supplier<java.lang.String>)"),
0)
.build();
private static final ImmutableSetMultimap<MethodRef, Integer> EXPLICITLY_NULLABLE_PARAMETERS =
new ImmutableSetMultimap.Builder<MethodRef, Integer>()
.put(
methodRef(
"android.view.GestureDetector.OnGestureListener",
"onScroll(android.view.MotionEvent,android.view.MotionEvent,float,float)"),
0)
.build();
private static final ImmutableSetMultimap<MethodRef, Integer> NON_NULL_PARAMETERS =
new ImmutableSetMultimap.Builder<MethodRef, Integer>()
.put(
methodRef(
"com.android.sdklib.build.ApkBuilder",
"ApkBuilder(java.io.File,java.io.File,java.io.File,java.lang.String,java.io.PrintStream)"),
0)
.put(
methodRef(
"com.android.sdklib.build.ApkBuilder",
"ApkBuilder(java.io.File,java.io.File,java.io.File,java.lang.String,java.io.PrintStream)"),
1)
.put(methodRef("com.google.common.collect.ImmutableList.Builder", "add(E)"), 0)
.put(
methodRef(
"com.google.common.collect.ImmutableList.Builder",
"addAll(java.lang.Iterable<? extends E>)"),
0)
.put(methodRef("com.google.common.collect.ImmutableSet.Builder", "add(E)"), 0)
.put(
methodRef(
"com.google.common.collect.ImmutableSet.Builder",
"addAll(java.lang.Iterable<? extends E>)"),
0)
.put(methodRef("com.google.common.collect.ImmutableSortedSet.Builder", "add(E)"), 0)
.put(
methodRef(
"com.google.common.collect.ImmutableSortedSet.Builder",
"addAll(java.lang.Iterable<? extends E>)"),
0)
.put(
methodRef(
"com.google.common.collect.Iterables",
"<T>getFirst(java.lang.Iterable<? extends T>,T)"),
0)
.put(
methodRef(
"com.google.common.util.concurrent.SettableFuture",
"setException(java.lang.Throwable)"),
0)
.put(methodRef("java.io.File", "File(java.lang.String)"), 0)
.put(methodRef("java.lang.Class", "getResource(java.lang.String)"), 0)
.put(methodRef("java.lang.Class", "isAssignableFrom(java.lang.Class<?>)"), 0)
.put(methodRef("java.lang.System", "getProperty(java.lang.String)"), 0)
.put(
methodRef(
"java.net.URLClassLoader", "newInstance(java.net.URL[],java.lang.ClassLoader)"),
0)
.put(
methodRef(
"javax.lang.model.element.Element", "<A>getAnnotation(java.lang.Class<A>)"),
0)
.put(
methodRef(
"javax.lang.model.util.Elements", "getPackageElement(java.lang.CharSequence)"),
0)
.put(
methodRef(
"javax.lang.model.util.Elements", "getTypeElement(java.lang.CharSequence)"),
0)
.put(
methodRef(
"javax.lang.model.util.Elements",
"getDocComment(javax.lang.model.element.Element)"),
0)
.put(methodRef("java.util.Optional", "<T>of(T)"), 0)
.put(methodRef("java.util.Deque", "addFirst(E)"), 0)
.put(methodRef("java.util.Deque", "addLast(E)"), 0)
.put(methodRef("java.util.Deque", "offerFirst(E)"), 0)
.put(methodRef("java.util.Deque", "offerLast(E)"), 0)
.put(methodRef("java.util.Deque", "add(E)"), 0)
.put(methodRef("java.util.Deque", "offer(E)"), 0)
.put(methodRef("java.util.Deque", "push(E)"), 0)
.put(methodRef("java.util.Collection", "<T>toArray(T[])"), 0)
.put(methodRef("java.util.ArrayDeque", "addFirst(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "addLast(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "offerFirst(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "offerLast(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "add(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "offer(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "push(E)"), 0)
.put(methodRef("java.util.ArrayDeque", "<T>toArray(T[])"), 0)
.build();
private static final ImmutableSetMultimap<MethodRef, Integer> NULL_IMPLIES_TRUE_PARAMETERS =
new ImmutableSetMultimap.Builder<MethodRef, Integer>()
.put(methodRef("com.google.common.base.Strings", "isNullOrEmpty(java.lang.String)"), 0)
.put(methodRef("java.util.Objects", "isNull(java.lang.Object)"), 0)
.put(methodRef("android.text.TextUtils", "isEmpty(java.lang.CharSequence)"), 0)
.put(methodRef("org.apache.commons.lang.StringUtils", "isEmpty(java.lang.String)"), 0)
.put(
methodRef(
"org.apache.commons.lang3.StringUtils", "isEmpty(java.lang.CharSequence)"),
0)
.build();
private static final ImmutableSet<MethodRef> NULLABLE_RETURNS =
new ImmutableSet.Builder<MethodRef>()
.add(methodRef("java.lang.ref.Reference", "get()"))
.add(methodRef("java.lang.ref.PhantomReference", "get()"))
.add(methodRef("java.lang.ref.SoftReference", "get()"))
.add(methodRef("java.lang.ref.WeakReference", "get()"))
.add(methodRef("java.util.concurrent.atomic.AtomicReference", "get()"))
.add(methodRef("java.util.Map", "get(java.lang.Object)"))
.add(methodRef("javax.lang.model.element.Element", "getEnclosingElement()"))
.add(methodRef("javax.lang.model.element.ExecutableElement", "getDefaultValue()"))
.add(methodRef("javax.lang.model.element.PackageElement", "getEnclosingElement()"))
.add(methodRef("javax.lang.model.element.VariableElement", "getConstantValue()"))
.add(methodRef("javax.lang.model.type.WildcardType", "getSuperBound()"))
.add(methodRef("android.app.ActivityManager", "getRunningAppProcesses()"))
.add(methodRef("android.view.View", "getHandler()"))
.add(methodRef("java.lang.Throwable", "getMessage()"))
.add(methodRef("android.webkit.WebView", "getUrl()"))
.build();
private static final ImmutableSet<MethodRef> NONNULL_RETURNS =
new ImmutableSet.Builder<MethodRef>()
.add(methodRef("com.google.gson", "<T>fromJson(String,Class)"))
.add(methodRef("android.app.Activity", "<T>findViewById(int)"))
.add(methodRef("android.view.View", "<T>findViewById(int)"))
.add(methodRef("android.view.View", "getResources()"))
.add(methodRef("android.view.ViewGroup", "getChildAt(int)"))
.add(
methodRef(
"android.content.res.Resources",
"getDrawable(int,android.content.res.Resources.Theme)"))
.add(methodRef("android.support.v4.app.Fragment", "getActivity()"))
.add(methodRef("androidx.fragment.app.Fragment", "getActivity()"))
.add(methodRef("android.support.v4.app.Fragment", "getArguments()"))
.add(methodRef("androidx.fragment.app.Fragment", "getArguments()"))
.add(methodRef("android.support.v4.app.Fragment", "getContext()"))
.add(methodRef("androidx.fragment.app.Fragment", "getContext()"))
.add(
methodRef(
"android.support.v4.app.Fragment",
"onCreateView(android.view.LayoutInflater,android.view.ViewGroup,android.os.Bundle)"))
.add(
methodRef(
"androidx.fragment.app.Fragment",
"onCreateView(android.view.LayoutInflater,android.view.ViewGroup,android.os.Bundle)"))
.add(
methodRef(
"android.support.v4.content.ContextCompat",
"getDrawable(android.content.Context,int)"))
.add(
methodRef(
"androidx.core.content.ContextCompat",
"getDrawable(android.content.Context,int)"))
.add(methodRef("android.support.v7.app.AppCompatDialog", "<T>findViewById(int)"))
.add(methodRef("androidx.appcompat.app.AppCompatDialog", "<T>findViewById(int)"))
.add(
methodRef(
"android.support.v7.content.res.AppCompatResources",
"getDrawable(android.content.Context,int)"))
.add(
methodRef(
"androidx.appcompat.content.res.AppCompatResources",
"getDrawable(android.content.Context,int)"))
.add(methodRef("android.support.design.widget.TextInputLayout", "getEditText()"))
.build();
@Override
public ImmutableSetMultimap<MethodRef, Integer> failIfNullParameters() {
return FAIL_IF_NULL_PARAMETERS;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> explicitlyNullableParameters() {
return EXPLICITLY_NULLABLE_PARAMETERS;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> nonNullParameters() {
return NON_NULL_PARAMETERS;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> nullImpliesTrueParameters() {
return NULL_IMPLIES_TRUE_PARAMETERS;
}
@Override
public ImmutableSet<MethodRef> nullableReturns() {
return NULLABLE_RETURNS;
}
@Override
public ImmutableSet<MethodRef> nonNullReturns() {
return NONNULL_RETURNS;
}
}
private static class CombinedLibraryModels implements LibraryModels {
private final ImmutableSetMultimap<MethodRef, Integer> failIfNullParameters;
private final ImmutableSetMultimap<MethodRef, Integer> explicitlyNullableParameters;
private final ImmutableSetMultimap<MethodRef, Integer> nonNullParameters;
private final ImmutableSetMultimap<MethodRef, Integer> nullImpliesTrueParameters;
private final ImmutableSet<MethodRef> nullableReturns;
private final ImmutableSet<MethodRef> nonNullReturns;
public CombinedLibraryModels(Iterable<LibraryModels> models) {
ImmutableSetMultimap.Builder<MethodRef, Integer> failIfNullParametersBuilder =
new ImmutableSetMultimap.Builder<>();
ImmutableSetMultimap.Builder<MethodRef, Integer> explicitlyNullableParametersBuilder =
new ImmutableSetMultimap.Builder<>();
ImmutableSetMultimap.Builder<MethodRef, Integer> nonNullParametersBuilder =
new ImmutableSetMultimap.Builder<>();
ImmutableSetMultimap.Builder<MethodRef, Integer> nullImpliesTrueParametersBuilder =
new ImmutableSetMultimap.Builder<>();
ImmutableSet.Builder<MethodRef> nullableReturnsBuilder = new ImmutableSet.Builder<>();
ImmutableSet.Builder<MethodRef> nonNullReturnsBuilder = new ImmutableSet.Builder<>();
for (LibraryModels libraryModels : models) {
for (Map.Entry<MethodRef, Integer> entry : libraryModels.failIfNullParameters().entries()) {
failIfNullParametersBuilder.put(entry);
}
for (Map.Entry<MethodRef, Integer> entry :
libraryModels.explicitlyNullableParameters().entries()) {
explicitlyNullableParametersBuilder.put(entry);
}
for (Map.Entry<MethodRef, Integer> entry : libraryModels.nonNullParameters().entries()) {
nonNullParametersBuilder.put(entry);
}
for (Map.Entry<MethodRef, Integer> entry :
libraryModels.nullImpliesTrueParameters().entries()) {
nullImpliesTrueParametersBuilder.put(entry);
}
for (MethodRef name : libraryModels.nullableReturns()) {
nullableReturnsBuilder.add(name);
}
for (MethodRef name : libraryModels.nonNullReturns()) {
nonNullReturnsBuilder.add(name);
}
}
failIfNullParameters = failIfNullParametersBuilder.build();
explicitlyNullableParameters = explicitlyNullableParametersBuilder.build();
nonNullParameters = nonNullParametersBuilder.build();
nullImpliesTrueParameters = nullImpliesTrueParametersBuilder.build();
nullableReturns = nullableReturnsBuilder.build();
nonNullReturns = nonNullReturnsBuilder.build();
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> failIfNullParameters() {
return failIfNullParameters;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> explicitlyNullableParameters() {
return explicitlyNullableParameters;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> nonNullParameters() {
return nonNullParameters;
}
@Override
public ImmutableSetMultimap<MethodRef, Integer> nullImpliesTrueParameters() {
return nullImpliesTrueParameters;
}
@Override
public ImmutableSet<MethodRef> nullableReturns() {
return nullableReturns;
}
@Override
public ImmutableSet<MethodRef> nonNullReturns() {
return nonNullReturns;
}
}
/**
* A view of library models optimized to make lookup of {@link
* com.sun.tools.javac.code.Symbol.MethodSymbol}s fast
*/
private static class OptimizedLibraryModels {
/**
* Mapping from {@link MethodRef} to some state, where lookups first check for a matching method
* name as an optimization. The {@link Name} data structure is used to avoid unnecessary String
* conversions when looking up {@link com.sun.tools.javac.code.Symbol.MethodSymbol}s.
*
* @param <T>
*/
private static class NameIndexedMap<T> {
private final Map<Name, Map<MethodRef, T>> state;
NameIndexedMap(Map<Name, Map<MethodRef, T>> state) {
this.state = state;
}
@Nullable
public T get(Symbol.MethodSymbol symbol) {
Map<MethodRef, T> methodRefTMap = state.get(symbol.name);
if (methodRefTMap == null) {
return null;
}
MethodRef ref = MethodRef.fromSymbol(symbol);
return methodRefTMap.get(ref);
}
public boolean nameNotPresent(Symbol.MethodSymbol symbol) {
return state.get(symbol.name) == null;
}
}
private final NameIndexedMap<ImmutableSet<Integer>> failIfNullParams;
private final NameIndexedMap<ImmutableSet<Integer>> explicitlyNullableParams;
private final NameIndexedMap<ImmutableSet<Integer>> nonNullParams;
private final NameIndexedMap<ImmutableSet<Integer>> nullImpliesTrueParams;
private final NameIndexedMap<Boolean> nullableRet;
private final NameIndexedMap<Boolean> nonNullRet;
public OptimizedLibraryModels(LibraryModels models, Context context) {
Names names = Names.instance(context);
failIfNullParams = makeOptimizedIntSetLookup(names, models.failIfNullParameters());
explicitlyNullableParams =
makeOptimizedIntSetLookup(names, models.explicitlyNullableParameters());
nonNullParams = makeOptimizedIntSetLookup(names, models.nonNullParameters());
nullImpliesTrueParams = makeOptimizedIntSetLookup(names, models.nullImpliesTrueParameters());
nullableRet = makeOptimizedBoolLookup(names, models.nullableReturns());
nonNullRet = makeOptimizedBoolLookup(names, models.nonNullReturns());
}
public boolean hasNonNullReturn(Symbol.MethodSymbol symbol, Types types) {
return lookupHandlingOverrides(symbol, types, nonNullRet) != null;
}
public boolean hasNullableReturn(Symbol.MethodSymbol symbol, Types types) {
return lookupHandlingOverrides(symbol, types, nullableRet) != null;
}
ImmutableSet<Integer> failIfNullParameters(Symbol.MethodSymbol symbol) {
return lookupImmutableSet(symbol, failIfNullParams);
}
ImmutableSet<Integer> explicitlyNullableParameters(Symbol.MethodSymbol symbol) {
return lookupImmutableSet(symbol, explicitlyNullableParams);
}
ImmutableSet<Integer> nonNullParameters(Symbol.MethodSymbol symbol) {
return lookupImmutableSet(symbol, nonNullParams);
}
ImmutableSet<Integer> nullImpliesTrueParameters(Symbol.MethodSymbol symbol) {
return lookupImmutableSet(symbol, nullImpliesTrueParams);
}
private ImmutableSet<Integer> lookupImmutableSet(
Symbol.MethodSymbol symbol, NameIndexedMap<ImmutableSet<Integer>> lookup) {
ImmutableSet<Integer> result = lookup.get(symbol);
return (result == null) ? ImmutableSet.of() : result;
}
private NameIndexedMap<ImmutableSet<Integer>> makeOptimizedIntSetLookup(
Names names, ImmutableSetMultimap<MethodRef, Integer> ref2Ints) {
return makeOptimizedLookup(names, ref2Ints.keySet(), ref2Ints::get);
}
private NameIndexedMap<Boolean> makeOptimizedBoolLookup(
Names names, ImmutableSet<MethodRef> refs) {
return makeOptimizedLookup(names, refs, (ref) -> true);
}
private <T> NameIndexedMap<T> makeOptimizedLookup(
Names names, Set<MethodRef> refs, Function<MethodRef, T> getValForRef) {
Map<Name, Map<MethodRef, T>> nameMapping = new LinkedHashMap<>();
for (MethodRef ref : refs) {
Name methodName = names.fromString(ref.methodName);
Map<MethodRef, T> mapForName = nameMapping.get(methodName);
if (mapForName == null) {
mapForName = new LinkedHashMap<>();
nameMapping.put(methodName, mapForName);
}
mapForName.put(ref, getValForRef.apply(ref));
}
return new NameIndexedMap<>(nameMapping);
}
/**
* checks if symbol is present in the NameIndexedMap or if it overrides some method in the
* NameIndexedMap
*/
@Nullable
private static Symbol.MethodSymbol lookupHandlingOverrides(
Symbol.MethodSymbol symbol, Types types, NameIndexedMap<Boolean> optLookup) {
if (optLookup.nameNotPresent(symbol)) {
// no model matching the method name, so we don't need to check for overridden methods
return null;
}
if (optLookup.get(symbol) != null) {
return symbol;
}
for (Symbol.MethodSymbol superSymbol : ASTHelpers.findSuperMethods(symbol, types)) {
if (optLookup.get(superSymbol) != null) {
return superSymbol;
}
}
return null;
}
}
}