-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ConformanceRules.java
1851 lines (1676 loc) · 65.4 KB
/
ConformanceRules.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2014 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ascii;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import com.google.javascript.jscomp.CheckConformance.InvalidRequirementSpec;
import com.google.javascript.jscomp.CheckConformance.Rule;
import com.google.javascript.jscomp.CodingConvention.AssertionFunctionSpec;
import com.google.javascript.jscomp.Requirement.Severity;
import com.google.javascript.jscomp.Requirement.Type;
import com.google.javascript.jscomp.parsing.JsDocInfoParser;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.Nullable;
/**
* Standard conformance rules. See
* third_party/java_src/jscomp/java/com/google/javascript/jscomp/conformance.proto
*/
@GwtIncompatible("java.lang.reflect, java.util.regex")
public final class ConformanceRules {
private ConformanceRules() {}
/**
* Classes extending AbstractRule must return ConformanceResult
* from their checkConformance implementation. For simple rules, the
* constants CONFORMANCE, POSSIBLE_VIOLATION, VIOLATION are sufficient.
* However, for some rules additional clarification specific to the
* violation instance is helpful, for that, an instance of this class
* can be created to associate a note with the violation.
*/
public static class ConformanceResult {
ConformanceResult(ConformanceLevel level) {
this(level, "");
}
ConformanceResult(ConformanceLevel level, String note) {
this.level = level;
this.note = note;
}
public final ConformanceLevel level;
public final String note;
// For CONFORMANCE rules that don't generate notes:
public static final ConformanceResult CONFORMANCE = new ConformanceResult(
ConformanceLevel.CONFORMANCE);
public static final ConformanceResult POSSIBLE_VIOLATION = new ConformanceResult(
ConformanceLevel.POSSIBLE_VIOLATION);
private static final ConformanceResult POSSIBLE_VIOLATION_DUE_TO_LOOSE_TYPES =
new ConformanceResult(
ConformanceLevel.POSSIBLE_VIOLATION,
"The type information available for this expression is too loose "
+ "to ensure conformance.");
public static final ConformanceResult VIOLATION = new ConformanceResult(
ConformanceLevel.VIOLATION);
}
/** Possible check check results */
public static enum ConformanceLevel {
// Nothing interesting detected.
CONFORMANCE,
// In the optionally typed world of the Closure Compiler type system
// it is possible that detect patterns that match with looser types
// that the target pattern.
POSSIBLE_VIOLATION,
// Definitely a violation.
VIOLATION,
}
/**
* A conformance rule implementation to support things common to all rules such as whitelisting
* and reporting.
*/
public abstract static class AbstractRule implements Rule {
final AbstractCompiler compiler;
final String message;
final Severity severity;
final ImmutableList<String> whitelist;
final ImmutableList<String> onlyApplyTo;
@Nullable final Pattern whitelistRegexp;
@Nullable final Pattern onlyApplyToRegexp;
final boolean reportLooseTypeViolations;
final TypeMatchingStrategy typeMatchingStrategy;
final Requirement requirement;
public AbstractRule(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
if (!requirement.hasErrorMessage()) {
throw new InvalidRequirementSpec("missing message");
}
this.compiler = compiler;
message = requirement.getErrorMessage();
if (requirement.getSeverity() == Severity.UNSPECIFIED) {
severity = Severity.WARNING;
} else {
severity = requirement.getSeverity();
}
whitelist = ImmutableList.copyOf(requirement.getWhitelistList());
whitelistRegexp = buildPattern(
requirement.getWhitelistRegexpList());
onlyApplyTo = ImmutableList.copyOf(requirement.getOnlyApplyToList());
onlyApplyToRegexp = buildPattern(
requirement.getOnlyApplyToRegexpList());
reportLooseTypeViolations = requirement.getReportLooseTypeViolations();
typeMatchingStrategy = getTypeMatchingStrategy(requirement);
this.requirement = requirement;
}
private static TypeMatchingStrategy getTypeMatchingStrategy(Requirement requirement) {
switch (requirement.getTypeMatchingStrategy()) {
case LOOSE:
return TypeMatchingStrategy.LOOSE;
case STRICT_NULLABILITY:
return TypeMatchingStrategy.STRICT_NULLABILITY;
case SUBTYPES:
return TypeMatchingStrategy.SUBTYPES;
case EXACT:
return TypeMatchingStrategy.EXACT;
default:
throw new IllegalStateException("Unknown TypeMatchingStrategy");
}
}
@Nullable
private static Pattern buildPattern(List<String> reqPatterns)
throws InvalidRequirementSpec {
if (reqPatterns == null || reqPatterns.isEmpty()) {
return null;
}
// validate the patterns
for (String reqPattern : reqPatterns) {
try {
Pattern.compile(reqPattern);
} catch (PatternSyntaxException e) {
throw new InvalidRequirementSpec("invalid regex pattern");
}
}
Pattern pattern = null;
try {
String jointRegExp = "(" + Joiner.on("|").join(reqPatterns) + ")";
pattern = Pattern.compile(jointRegExp);
} catch (PatternSyntaxException e) {
throw new RuntimeException("bad joined regexp", e);
}
return pattern;
}
/**
* @return Whether the code represented by the Node conforms to the
* rule.
*/
protected abstract ConformanceResult checkConformance(
NodeTraversal t, Node n);
/**
* @return Whether the specified Node should be checked for conformance, according to this
* rule's whitelist configuration.
*/
protected final boolean isWhitelistedByRequirement(Node n) {
String srcfile = NodeUtil.getSourceName(n);
if (srcfile == null) {
return true;
} else if (!onlyApplyTo.isEmpty() || onlyApplyToRegexp != null) {
return pathIsInListOrRegexp(srcfile, onlyApplyTo, onlyApplyToRegexp)
&& !pathIsInListOrRegexp(srcfile, whitelist, whitelistRegexp);
} else {
return !pathIsInListOrRegexp(srcfile, whitelist, whitelistRegexp);
}
}
private static boolean pathIsInListOrRegexp(
String srcfile, ImmutableList<String> list, @Nullable Pattern regexp) {
for (int i = 0; i < list.size(); i++) {
String entry = list.get(i);
if (!entry.isEmpty() && srcfile.startsWith(entry)) {
return true;
}
}
return regexp != null && regexp.matcher(srcfile).find();
}
@Override
public final void check(NodeTraversal t, Node n) {
ConformanceResult result = checkConformance(t, n);
if (result.level != ConformanceLevel.CONFORMANCE) {
report(n, result);
}
}
/**
* Report a conformance warning for the given node.
*
* @param n The node representing the violating code.
* @param result The result representing the confidence of the violation.
*/
protected void report(Node n, ConformanceResult result) {
DiagnosticType msg;
if (severity == Severity.ERROR) {
// Always report findings that are errors, even if the types are too loose to be certain.
// TODO(bangert): If this causes problems, add another severity category that only
// errors when certain.
msg = CheckConformance.CONFORMANCE_ERROR;
} else {
if (result.level == ConformanceLevel.VIOLATION) {
msg = CheckConformance.CONFORMANCE_VIOLATION;
} else {
msg = CheckConformance.CONFORMANCE_POSSIBLE_VIOLATION;
}
}
String separator = (result.note.isEmpty())
? ""
: "\n";
JSError err = JSError.make(n, msg, message, separator, result.note);
// Note that shouldReportConformanceViolation has to be called first; this allows
// logging violations that would otherwise be whitelisted.
if (compiler.getErrorManager().shouldReportConformanceViolation(requirement, err)
&& isWhitelistedByRequirement(n)) {
compiler.report(err);
}
}
}
abstract static class AbstractTypeRestrictionRule extends AbstractRule {
private final JSType nativeObjectType;
private final JSType whitelistedTypes;
private final ImmutableList<Node> assertionsFunctionNames;
public AbstractTypeRestrictionRule(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
nativeObjectType = compiler.getTypeRegistry().getNativeType(JSTypeNative.OBJECT_TYPE);
List<String> whitelistedTypeNames = requirement.getValueList();
whitelistedTypes = union(whitelistedTypeNames);
ImmutableList.Builder<Node> builder = ImmutableList.builder();
for (AssertionFunctionSpec fn : compiler.getCodingConvention().getAssertionFunctions()) {
builder.add(NodeUtil.newQName(compiler, fn.getFunctionName()));
}
assertionsFunctionNames = builder.build();
}
protected boolean isWhitelistedType(Node n) {
if (whitelistedTypes != null && n.getJSType() != null) {
JSType targetType = n.getJSType().restrictByNotNullOrUndefined();
if (targetType.isSubtypeOf(whitelistedTypes)) {
return true;
}
}
return false;
}
protected boolean isKnown(Node n) {
return !isUnknown(n)
&& !isBottom(n)
&& !isTypeVariable(n); // TODO(johnlenz): Remove this restriction
}
protected boolean isNativeObjectType(Node n) {
JSType type = n.getJSType().restrictByNotNullOrUndefined();
return type.isEquivalentTo(nativeObjectType);
}
protected boolean isTop(Node n) {
JSType type = n.getJSType();
return type != null && type.isAllType();
}
protected boolean isUnknown(Node n) {
JSType type = n.getJSType();
return (type == null || type.isUnknownType());
}
protected boolean isSomeUnknownType(Node n) {
JSType type = n.getJSType();
return (type == null || type.isSomeUnknownType());
}
protected boolean isTypeVariable(Node n) {
JSType type = n.getJSType().restrictByNotNullOrUndefined();
return type.isTypeVariable();
}
private boolean isBottom(Node n) {
JSType type = n.getJSType().restrictByNotNullOrUndefined();
return type.isEmptyType();
}
protected JSType union(List<String> typeNames) {
JSTypeRegistry registry = compiler.getTypeRegistry();
List<JSType> types = new ArrayList<>();
for (String typeName : typeNames) {
JSType type = registry.getGlobalType(typeName);
if (type != null) {
types.add(type);
}
}
if (types.isEmpty()) {
return null;
} else {
return registry.createUnionType(types);
}
}
protected boolean isAssertionCall(Node n) {
if (n.isCall() && n.getFirstChild().isQualifiedName()) {
Node target = n.getFirstChild();
for (int i = 0; i < assertionsFunctionNames.size(); i++) {
if (target.matchesQualifiedName(assertionsFunctionNames.get(i))) {
return true;
}
}
}
return false;
}
protected boolean isTypeImmediatelyTightened(Node n) {
return isAssertionCall(n.getParent())
|| n.getParent().isTypeOf()
|| /* casted node */ n.getJSTypeBeforeCast() != null;
}
protected boolean isUsed(Node n) {
if (n.getParent().isName() || NodeUtil.isLhsByDestructuring(n)) {
return false;
}
// Consider lvalues in assignment operations to be used iff the actual assignment
// operation's result is used. e.g. for `a.b.c`:
// USED: `alert(x = a.b.c);`
// UNUSED: `x = a.b.c;`
if (NodeUtil.isAssignmentOp(n.getParent())) {
return NodeUtil.isExpressionResultUsed(n.getParent());
}
return NodeUtil.isExpressionResultUsed(n);
}
}
/**
* Check that variables annotated as @const have an inferred type, if there is
* no type given explicitly.
*/
static class InferredConstCheck extends AbstractRule {
public InferredConstCheck(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
JSDocInfo jsDoc = n.getJSDocInfo();
if (jsDoc != null && jsDoc.hasConstAnnotation() && jsDoc.getType() == null) {
if (n.isAssign()) {
n = n.getFirstChild();
}
JSType type = n.getJSType();
if (type != null && type.isUnknownType()
&& !NodeUtil.isNamespaceDecl(n)) {
return ConformanceResult.VIOLATION;
}
}
return ConformanceResult.CONFORMANCE;
}
}
/**
* Banned dependency rule
*/
static class BannedDependency extends AbstractRule {
private final List<String> paths;
BannedDependency(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
paths = requirement.getValueList();
if (paths.isEmpty()) {
throw new InvalidRequirementSpec("missing value");
}
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
if (n.isScript()) {
String srcFile = n.getSourceFileName();
for (int i = 0; i < paths.size(); i++) {
String path = paths.get(i);
if (srcFile.startsWith(path)) {
return ConformanceResult.VIOLATION;
}
}
}
return ConformanceResult.CONFORMANCE;
}
}
/**
* Banned name rule
*/
static class BannedName extends AbstractRule {
private final Requirement.Type requirementType;
private final ImmutableList<Node> names;
BannedName(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
if (requirement.getValueCount() == 0) {
throw new InvalidRequirementSpec("missing value");
}
requirementType = requirement.getType();
ImmutableList.Builder<Node> builder = ImmutableList.builder();
for (String name : requirement.getValueList()) {
builder.add(NodeUtil.newQName(compiler, name));
}
names = builder.build();
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
if (isCandidateNode(n)) {
if (requirementType == Type.BANNED_NAME_CALL) {
if (!ConformanceUtil.isCallTarget(n)) {
return ConformanceResult.CONFORMANCE;
}
}
for (int i = 0; i < names.size(); i++) {
Node nameNode = names.get(i);
if (n.matchesQualifiedName(nameNode) && isRootOfQualifiedNameGlobal(t, n)) {
if (NodeUtil.isInSyntheticScript(n)) {
return ConformanceResult.CONFORMANCE;
} else {
return ConformanceResult.VIOLATION;
}
}
}
}
return ConformanceResult.CONFORMANCE;
}
private boolean isCandidateNode(Node n) {
switch(n.getToken()) {
case GETPROP:
return n.getFirstChild().isQualifiedName();
case NAME:
return !n.getString().isEmpty();
default:
return false;
}
}
private static boolean isRootOfQualifiedNameGlobal(NodeTraversal t, Node n) {
String rootName = NodeUtil.getRootOfQualifiedName(n).getQualifiedName();
Var v = t.getScope().getVar(rootName);
return v != null && v.isGlobal();
}
}
/**
* Banned property rule
*/
static class BannedProperty extends AbstractRule {
private static class Property {
final String type;
final String property;
Property(String type, String property) {
this.type = type;
this.property = property;
}
}
private final ImmutableList<Property> props;
private final Requirement.Type requirementType;
BannedProperty(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
if (requirement.getValueCount() == 0) {
throw new InvalidRequirementSpec("missing value");
}
checkArgument(
requirement.getType() == Type.BANNED_PROPERTY
|| requirement.getType() == Type.BANNED_PROPERTY_READ
|| requirement.getType() == Type.BANNED_PROPERTY_WRITE
|| requirement.getType() == Type.BANNED_PROPERTY_NON_CONSTANT_WRITE
|| requirement.getType() == Type.BANNED_PROPERTY_CALL);
requirementType = requirement.getType();
ImmutableList.Builder<Property> builder = ImmutableList.builder();
List<String> values = requirement.getValueList();
for (String value : values) {
String type = getClassFromDeclarationName(value);
String property = getPropertyFromDeclarationName(value);
if (type == null || property == null) {
throw new InvalidRequirementSpec("bad prop value");
}
builder.add(new Property(type, property));
}
props = builder.build();
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
if (NodeUtil.isGet(n) && n.getLastChild().isString()) {
// TODO(dimvar): Instead of the for-loop, we could make props be a multi-map from
// the property name to Property, and then here just pull the relevant Property instances.
// Won't make much difference to performance, since props usually only has a few elements,
// but it will make the code clearer.
for (int i = 0; i < props.size(); i++) {
Property prop = props.get(i);
ConformanceResult result = checkConformance(t, n, prop);
if (result.level != ConformanceLevel.CONFORMANCE) {
return result;
}
}
}
return ConformanceResult.CONFORMANCE;
}
private ConformanceResult checkConformance(NodeTraversal t, Node propAccess, Property prop) {
if (isCandidatePropUse(propAccess, prop)) {
JSTypeRegistry registry = t.getCompiler().getTypeRegistry();
JSType typeWithBannedProp = registry.getGlobalType(prop.type);
Node receiver = propAccess.getFirstChild();
if (typeWithBannedProp != null && receiver.getJSType() != null) {
JSType foundType = receiver.getJSType().restrictByNotNullOrUndefined();
ObjectType foundObj = foundType.toMaybeObjectType();
if (foundObj != null) {
if (foundObj.isFunctionPrototypeType()) {
FunctionType ownerFun = foundObj.getOwnerFunction();
if (ownerFun.isConstructor()) {
foundType = ownerFun.getInstanceType();
}
} else if (foundObj.isGenericObjectType()) {
foundType = foundObj.getRawType();
}
}
if (foundType.isSomeUnknownType()
|| foundType.isTypeVariable()
|| foundType.isEmptyType()
|| foundType.isAllType()
|| foundType.isEquivalentTo(registry.getNativeType(JSTypeNative.OBJECT_TYPE))) {
if (reportLooseTypeViolations) {
return ConformanceResult.POSSIBLE_VIOLATION_DUE_TO_LOOSE_TYPES;
}
} else if (foundType.isSubtypeOf(typeWithBannedProp)) {
return ConformanceResult.VIOLATION;
} else if (typeWithBannedProp.isSubtypeWithoutStructuralTyping(foundType)) {
if (matchesPrototype(typeWithBannedProp, foundType)) {
return ConformanceResult.VIOLATION;
} else if (reportLooseTypeViolations) {
// Access of a banned property through a super class may be a violation
return ConformanceResult.POSSIBLE_VIOLATION_DUE_TO_LOOSE_TYPES;
}
}
}
}
return ConformanceResult.CONFORMANCE;
}
private boolean matchesPrototype(JSType type, JSType maybePrototype) {
ObjectType methodClassObjectType = type.toMaybeObjectType();
if (methodClassObjectType != null) {
if (methodClassObjectType.getPrototypeObject().isEquivalentTo(maybePrototype)) {
return true;
}
}
return false;
}
/**
* Determines if {@code n} is a potentially banned use of {@code prop}.
*
* Specifically this is the case if {@code n} is a use of a property with
* the name specified by {@code prop}. Furthermore, if the conformance
* requirement under consideration only bans assignment to the property,
* {@code n} is only a candidate if it is an l-value.
*/
private boolean isCandidatePropUse(Node propAccess, Property prop) {
Preconditions.checkState(propAccess.isGetProp() || propAccess.isGetElem(),
"Expected property-access node but found %s", propAccess);
if (propAccess.getLastChild().getString().equals(prop.property)) {
if (requirementType == Type.BANNED_PROPERTY_WRITE) {
return NodeUtil.isLValue(propAccess);
} else if (requirementType == Type.BANNED_PROPERTY_NON_CONSTANT_WRITE) {
if (!NodeUtil.isLValue(propAccess)) {
return false;
}
if (NodeUtil.isLhsOfAssign(propAccess)
&& (NodeUtil.isLiteralValue(propAccess.getNext(), false /* includeFunctions */)
|| NodeUtil.isSomeCompileTimeConstStringValue(propAccess.getNext()))) {
return false;
}
return true;
} else if (requirementType == Type.BANNED_PROPERTY_READ) {
return !NodeUtil.isLValue(propAccess) && NodeUtil.isExpressionResultUsed(propAccess);
} else if (requirementType == Type.BANNED_PROPERTY_CALL) {
return ConformanceUtil.isCallTarget(propAccess);
} else {
return true;
}
}
return false;
}
/**
* From a provide name extract the method name.
*/
private static String getPropertyFromDeclarationName(String specName) {
String[] parts = specName.split("\\.prototype\\.");
checkState(parts.length == 1 || parts.length == 2);
if (parts.length == 2) {
return parts[1];
}
return null;
}
/**
* From a provide name extract the class name.
*/
private static String getClassFromDeclarationName(String specName) {
String[] parts = specName.split("\\.prototype\\.");
checkState(parts.length == 1 || parts.length == 2);
if (parts.length == 2) {
return parts[0];
}
return null;
}
}
private static class ConformanceUtil {
static boolean isCallTarget(Node n) {
Node parent = n.getParent();
return (parent.isCall() || parent.isNew())
&& parent.getFirstChild() == n;
}
static JSType evaluateTypeString(
AbstractCompiler compiler, String expression)
throws InvalidRequirementSpec {
Node typeNodes = JsDocInfoParser.parseTypeString(expression);
if (typeNodes == null) {
throw new InvalidRequirementSpec("bad type expression");
}
JSTypeExpression typeExpr = new JSTypeExpression(
typeNodes, "conformance");
return compiler.getTypeRegistry().evaluateTypeExpressionInGlobalScope(typeExpr);
}
/**
* Validate the parameters and the 'this' type, of a new or call.
* @see TypeCheck#visitParameterList
*/
static boolean validateCall(
AbstractCompiler compiler,
Node callOrNew,
FunctionType functionType,
boolean isCallInvocation) {
checkState(callOrNew.isCall() || callOrNew.isNew());
return validateParameterList(compiler, callOrNew, functionType, isCallInvocation)
&& validateThis(callOrNew, functionType, isCallInvocation);
}
private static boolean validateThis(
Node callOrNew,
FunctionType functionType,
boolean isCallInvocation) {
if (callOrNew.isNew()) {
return true;
}
JSType thisType = functionType.getTypeOfThis();
if (thisType == null || thisType.isUnknownType()) {
return true;
}
Node thisNode = isCallInvocation
? callOrNew.getSecondChild()
: callOrNew.getFirstFirstChild();
JSType thisNodeType =
thisNode.getJSType().restrictByNotNullOrUndefined();
return thisNodeType.isSubtypeOf(thisType);
}
private static boolean validateParameterList(
AbstractCompiler compiler,
Node callOrNew,
FunctionType functionType,
boolean isCallInvocation) {
Iterator<Node> arguments = callOrNew.children().iterator();
arguments.next(); // skip the function name
if (isCallInvocation && arguments.hasNext()) {
arguments.next();
}
// Get all the annotated types of the argument nodes
ImmutableList.Builder<JSType> argumentTypes = ImmutableList.builder();
while (arguments.hasNext()) {
JSType argType = arguments.next().getJSType();
if (argType == null) {
argType = compiler.getTypeRegistry().getNativeType(JSTypeNative.UNKNOWN_TYPE);
}
argumentTypes.add(argType);
}
return functionType.acceptsArguments(argumentTypes.build());
}
}
/**
* Restricted name call rule
*/
static class RestrictedNameCall extends AbstractRule {
private static class Restriction {
final Node name;
final FunctionType restrictedCallType;
Restriction(Node name, FunctionType restrictedCallType) {
this.name = name;
this.restrictedCallType = restrictedCallType;
}
}
private final ImmutableList<Restriction> restrictions;
RestrictedNameCall(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
if (requirement.getValueCount() == 0) {
throw new InvalidRequirementSpec("missing value");
}
ImmutableList.Builder <Restriction> builder = ImmutableList.builder();
for (String value : requirement.getValueList()) {
Node name = NodeUtil.newQName(compiler, getNameFromValue(value));
String restrictedDecl = getTypeFromValue(value);
if (name == null || restrictedDecl == null) {
throw new InvalidRequirementSpec("bad prop value");
}
FunctionType restrictedCallType = ConformanceUtil.evaluateTypeString(
compiler, restrictedDecl).toMaybeFunctionType();
if (restrictedCallType == null) {
throw new InvalidRequirementSpec("invalid conformance type");
}
builder.add(new Restriction(name, restrictedCallType));
}
restrictions = builder.build();
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
if (ConformanceUtil.isCallTarget(n) && n.isQualifiedName()) {
// TODO(johnlenz): restrict to global names
for (int i = 0; i < restrictions.size(); i++) {
Restriction r = restrictions.get(i);
if (n.matchesQualifiedName(r.name)) {
if (!ConformanceUtil.validateCall(
compiler, n.getParent(), r.restrictedCallType, false)) {
return ConformanceResult.VIOLATION;
}
} else if (n.isGetProp() && n.getLastChild().getString().equals("call")
&& n.getFirstChild().matchesQualifiedName(r.name)) {
if (!ConformanceUtil.validateCall(
compiler, n.getParent(), r.restrictedCallType, true)) {
return ConformanceResult.VIOLATION;
}
}
}
}
return ConformanceResult.CONFORMANCE;
}
private static String getNameFromValue(String specName) {
int index = specName.indexOf(':');
if (index < 1) {
return null;
}
return specName.substring(0, index);
}
private static String getTypeFromValue(String specName) {
int index = specName.indexOf(':');
if (index < 1) {
return null;
}
return specName.substring(index + 1);
}
}
/**
* Banned property call rule
*/
static class RestrictedMethodCall extends AbstractRule {
private static class Restriction {
final String type;
final String property;
final FunctionType restrictedCallType;
Restriction(
String type, String property, FunctionType restrictedCallType) {
this.type = type;
this.property = property;
this.restrictedCallType = restrictedCallType;
}
}
private final ImmutableList<Restriction> restrictions;
RestrictedMethodCall(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);
if (requirement.getValueCount() == 0) {
throw new InvalidRequirementSpec("missing value");
}
ImmutableList.Builder <Restriction> builder = ImmutableList.builder();
for (String value : requirement.getValueList()) {
String type = getClassFromDeclarationName(value);
String property = getPropertyFromDeclarationName(value);
String restrictedDecl = getTypeFromValue(value);
if (type == null || property == null || restrictedDecl == null) {
throw new InvalidRequirementSpec("bad prop value");
}
FunctionType restrictedCallType = ConformanceUtil.evaluateTypeString(
compiler, restrictedDecl).toMaybeFunctionType();
if (restrictedCallType == null) {
throw new InvalidRequirementSpec("invalid conformance type");
}
builder.add(new Restriction(type, property, restrictedCallType));
}
restrictions = builder.build();
}
@Override
protected ConformanceResult checkConformance(NodeTraversal t, Node n) {
if (NodeUtil.isGet(n)
&& ConformanceUtil.isCallTarget(n)
&& n.getLastChild().isString()) {
for (int i = 0; i < restrictions.size(); i++) {
Restriction r = restrictions.get(i);
ConformanceResult result = ConformanceResult.CONFORMANCE;
if (matchesProp(n, r)) {
result = checkConformance(t, n, r, false);
} else if (n.getLastChild().getString().equals("call")
&& matchesProp(n.getFirstChild(), r)) {
// handle .call invocation
result = checkConformance(t, n, r, true);
}
// TODO(johnlenz): should "apply" always be a possible violation?
if (result.level != ConformanceLevel.CONFORMANCE) {
return result;
}
}
}
return ConformanceResult.CONFORMANCE;
}
private ConformanceResult checkConformance(
NodeTraversal t, Node n, Restriction r, boolean isCallInvocation) {
JSTypeRegistry registry = t.getCompiler().getTypeRegistry();
JSType methodClassType = registry.getGlobalType(r.type);
Node lhs = isCallInvocation ? n.getFirstFirstChild() : n.getFirstChild();
if (methodClassType != null && lhs.getJSType() != null) {
JSType targetType = lhs.getJSType().restrictByNotNullOrUndefined();
if (targetType.isUnknownType()
|| targetType.isUnresolved()
|| targetType.isAllType()
|| targetType.isEquivalentTo(registry.getNativeType(JSTypeNative.OBJECT_TYPE))) {
if (reportLooseTypeViolations
&& !ConformanceUtil.validateCall(
compiler, n.getParent(), r.restrictedCallType, isCallInvocation)) {
return ConformanceResult.POSSIBLE_VIOLATION_DUE_TO_LOOSE_TYPES;
}
} else if (targetType.isSubtypeOf(methodClassType)) {
if (!ConformanceUtil.validateCall(
compiler, n.getParent(), r.restrictedCallType, isCallInvocation)) {
return ConformanceResult.VIOLATION;
}
}
}
return ConformanceResult.CONFORMANCE;
}
private boolean matchesProp(Node n, Restriction r) {
return n.isGetProp() && n.getLastChild().getString().equals(r.property);
}
/**
* From a provide name extract the method name.
*/
private static String getPropertyFromDeclarationName(String specName)
throws InvalidRequirementSpec {
String[] parts = removeTypeDecl(specName).split("\\.prototype\\.");
checkState(parts.length == 1 || parts.length == 2);
if (parts.length == 2) {
return parts[1];
}
return null;
}
/**
* From a provide name extract the class name.
*/
private static String getClassFromDeclarationName(String specName)
throws InvalidRequirementSpec {
String tmp = removeTypeDecl(specName);
String[] parts = tmp.split("\\.prototype\\.");
checkState(parts.length == 1 || parts.length == 2);
if (parts.length == 2) {
return parts[0];
}
return null;
}
private static String removeTypeDecl(String specName)
throws InvalidRequirementSpec {
int index = specName.indexOf(':');
if (index < 1) {
throw new InvalidRequirementSpec("value should be in the form NAME:TYPE");
}
return specName.substring(0, index);
}
private static String getTypeFromValue(String specName) {
int index = specName.indexOf(':');
if (index < 1) {
return null;
}
return specName.substring(index + 1);
}
}
/**
* Banned Code Pattern rule
*/
static class BannedCodePattern extends AbstractRule {
private final ImmutableList<TemplateAstMatcher> restrictions;
BannedCodePattern(AbstractCompiler compiler, Requirement requirement)
throws InvalidRequirementSpec {
super(compiler, requirement);