-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
CheckAccessControls.java
1346 lines (1172 loc) · 46.1 KB
/
CheckAccessControls.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 2008 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.auto.value.AutoValue;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfo.Visibility;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.StaticSourceFile;
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.util.Deque;
import java.util.LinkedList;
import java.util.function.Supplier;
import javax.annotation.Nullable;
/**
* A compiler pass that checks that the programmer has obeyed all the access
* control restrictions indicated by JSDoc annotations, like
* {@code @private} and {@code @deprecated}.
*
* Because access control restrictions are attached to type information, this pass must run
* after TypeInference, and InferJSDocInfo.
*
* @author nicksantos@google.com (Nick Santos)
*/
class CheckAccessControls extends AbstractPostOrderCallback
implements ScopedCallback, HotSwapCompilerPass {
static final DiagnosticType DEPRECATED_NAME = DiagnosticType.disabled(
"JSC_DEPRECATED_VAR",
"Variable {0} has been deprecated.");
static final DiagnosticType DEPRECATED_NAME_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_VAR_REASON",
"Variable {0} has been deprecated: {1}");
static final DiagnosticType DEPRECATED_PROP = DiagnosticType.disabled(
"JSC_DEPRECATED_PROP",
"Property {0} of type {1} has been deprecated.");
static final DiagnosticType DEPRECATED_PROP_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_PROP_REASON",
"Property {0} of type {1} has been deprecated: {2}");
static final DiagnosticType DEPRECATED_CLASS = DiagnosticType.disabled(
"JSC_DEPRECATED_CLASS",
"Class {0} has been deprecated.");
static final DiagnosticType DEPRECATED_CLASS_REASON = DiagnosticType.disabled(
"JSC_DEPRECATED_CLASS_REASON",
"Class {0} has been deprecated: {1}");
static final DiagnosticType BAD_PACKAGE_PROPERTY_ACCESS =
DiagnosticType.error(
"JSC_BAD_PACKAGE_PROPERTY_ACCESS",
"Access to package-private property {0} of {1} not allowed here.");
static final DiagnosticType BAD_PRIVATE_GLOBAL_ACCESS =
DiagnosticType.error(
"JSC_BAD_PRIVATE_GLOBAL_ACCESS",
"Access to private variable {0} not allowed outside file {1}.");
static final DiagnosticType BAD_PRIVATE_PROPERTY_ACCESS =
DiagnosticType.warning(
"JSC_BAD_PRIVATE_PROPERTY_ACCESS",
"Access to private property {0} of {1} not allowed here.");
static final DiagnosticType BAD_PROTECTED_PROPERTY_ACCESS =
DiagnosticType.warning(
"JSC_BAD_PROTECTED_PROPERTY_ACCESS",
"Access to protected property {0} of {1} not allowed here.");
static final DiagnosticType
BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY =
DiagnosticType.error(
"JSC_BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY",
"Overridden property {0} in file with fileoverview visibility {1}"
+ " must explicitly redeclare superclass visibility");
static final DiagnosticType PRIVATE_OVERRIDE =
DiagnosticType.warning(
"JSC_PRIVATE_OVERRIDE",
"Overriding private property of {0}.");
static final DiagnosticType EXTEND_FINAL_CLASS =
DiagnosticType.error(
"JSC_EXTEND_FINAL_CLASS",
"{0} is not allowed to extend final class {1}.");
static final DiagnosticType VISIBILITY_MISMATCH =
DiagnosticType.warning(
"JSC_VISIBILITY_MISMATCH",
"Overriding {0} property of {1} with {2} property.");
static final DiagnosticType CONST_PROPERTY_REASSIGNED_VALUE =
DiagnosticType.warning(
"JSC_CONSTANT_PROPERTY_REASSIGNED_VALUE",
"constant property {0} assigned a value more than once");
static final DiagnosticType CONST_PROPERTY_DELETED =
DiagnosticType.warning(
"JSC_CONSTANT_PROPERTY_DELETED",
"constant property {0} cannot be deleted");
static final DiagnosticType CONVENTION_MISMATCH =
DiagnosticType.warning(
"JSC_CONVENTION_MISMATCH",
"Declared access conflicts with access convention.");
private final AbstractCompiler compiler;
private final JSTypeRegistry typeRegistry;
private final boolean enforceCodingConventions;
// State about the current traversal.
private int deprecationDepth = 0;
// NOTE: LinkedList is almost always the wrong choice, but in this case we have at most a small
// handful of elements, it provides the smoothest API (push, pop, and a peek that doesn't throw
// on empty), and (unlike ArrayDeque) is null-permissive. No other option meets all these needs.
private final Deque<JSType> currentClassStack = new LinkedList<JSType>();
private ImmutableMap<StaticSourceFile, Visibility> defaultVisibilityForFiles;
private final Multimap<JSType, String> initializedConstantProperties;
CheckAccessControls(
AbstractCompiler compiler, boolean enforceCodingConventions) {
this.compiler = compiler;
this.typeRegistry = compiler.getTypeRegistry();
this.initializedConstantProperties = HashMultimap.create();
this.enforceCodingConventions = enforceCodingConventions;
}
@Override
public void process(Node externs, Node root) {
CollectFileOverviewVisibility collectPass =
new CollectFileOverviewVisibility(compiler);
collectPass.process(externs, root);
defaultVisibilityForFiles = collectPass.getFileOverviewVisibilityMap();
NodeTraversal.traverse(compiler, externs, this);
NodeTraversal.traverse(compiler, root, this);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
CollectFileOverviewVisibility collectPass =
new CollectFileOverviewVisibility(compiler);
collectPass.hotSwapScript(scriptRoot, originalRoot);
defaultVisibilityForFiles = collectPass.getFileOverviewVisibilityMap();
NodeTraversal.traverse(compiler, scriptRoot, this);
}
@Override
public void enterScope(NodeTraversal t) {
Node n = t.getScopeRoot();
if (isDeprecationScopeRoot(n)) {
deprecationDepth++;
}
if (isFunctionOrClass(n)) {
currentClassStack.push(bestInstanceTypeForMethodOrCtor(n, n.getParent()));
}
}
@Override
public void exitScope(NodeTraversal t) {
Node n = t.getScopeRoot();
if (isDeprecationScopeRoot(n)) {
deprecationDepth--;
}
if (n.isFunction()) {
currentClassStack.pop();
} else if (n.isClass()) {
currentClassStack.pop();
}
}
/**
* Returns the instance object type that best represents a method or constructor definition, or
* {@code null} if there is no representative type.
*
* <ul>
* <li>Prototype methods => The instance type having that prototype
* <li>Instance methods => The type the method is attached to
* <li>Constructors => The type that constructor instantiates
* <li>Object literal members => {@code null}
* </ul>
*
* TODO(nickreid): Remove the {@code parent} parameter.
*/
@Nullable
private JSType bestInstanceTypeForMethodOrCtor(Node n, Node parent) {
checkState(isFunctionOrClass(n), n);
if (parent.isAssign()) {
Node lValue = parent.getFirstChild();
if (NodeUtil.isGet(lValue)) {
// We have an assignment of the form `a.b = ...`.
JSType lValueType = lValue.getJSType();
if (lValueType != null && (lValueType.isConstructor() || lValueType.isInterface())) {
// Case `a.B = ...`
return normalizeClassType(lValueType);
} else if (NodeUtil.isPrototypeProperty(lValue)) {
// Case `a.B.prototype = ...`
return normalizeClassType(NodeUtil.getPrototypeClassName(lValue).getJSType());
} else {
// Case `a.b = ...`
return normalizeClassType(lValue.getFirstChild().getJSType());
}
} else {
// We have an assignment of the form "a = ...", so pull the
// type off the "a".
return normalizeClassType(lValue.getJSType());
}
} else if (NodeUtil.isFunctionDeclaration(n)
|| NodeUtil.isClassDeclaration(n)
|| parent.isName()) {
return normalizeClassType(n.getJSType());
} else if (parent.isStringKey()
|| parent.isGetterDef()
|| parent.isSetterDef()
|| parent.isMemberFunctionDef()
|| parent.isComputedProp()) {
Node objectLitParent = parent.getGrandparent();
if (!objectLitParent.isAssign()) {
return null;
}
Node className = NodeUtil.getPrototypeClassName(objectLitParent.getFirstChild());
if (className != null) {
return normalizeClassType(className.getJSType());
}
}
return null;
}
/**
* Normalize the type of a constructor, its instance, and its prototype
* all down to the same type (the instance type).
*/
private static JSType normalizeClassType(JSType type) {
if (type == null || type.isUnknownType()) {
return type;
} else if (type.isConstructor() || type.isInterface()) {
return type.toMaybeFunctionType().getInstanceType();
} else if (type.isFunctionPrototypeType()) {
return normalizePrototypeObject(type.toMaybeObjectType());
}
return type;
}
private static ObjectType normalizePrototypeObject(ObjectType type) {
FunctionType owner = type.getOwnerFunction();
if (owner.hasInstanceType()) {
return owner.getInstanceType();
}
return type;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case NAME:
checkNameDeprecation(t, n, parent);
checkNameVisibility(t, n, parent);
break;
case STRING_KEY:
case GETTER_DEF:
case SETTER_DEF:
case MEMBER_FUNCTION_DEF:
if (!parent.isObjectLit()) {
// TODO(b/80580110): Eventually object literals should be covered by `PropertyReference`s.
// However, doing so initially would have caused too many errors in existing code and
// delayed support for class syntax.
break;
}
checkKeyVisibilityConvention(t, n, parent);
break;
case NEW:
checkConstructorDeprecation(t, n);
break;
case FUNCTION:
case CLASS:
checkFinalClassOverrides(t, n, parent);
break;
default:
break;
}
@Nullable PropertyReference propRef = createPropertyReference(n);
if (propRef != null) {
checkPropertyDeprecation(t, propRef);
checkPropertyVisibility(t, propRef);
checkConstantProperty(t, propRef);
}
}
/** Checks the given NEW node to ensure that access restrictions are obeyed. */
private void checkConstructorDeprecation(NodeTraversal t, Node n) {
if (!shouldEmitDeprecationWarning(t, n)) {
return;
}
JSType type = n.getJSType();
if (type != null) {
String deprecationInfo = getTypeDeprecationInfo(type);
if (deprecationInfo != null) {
if (!deprecationInfo.isEmpty()) {
compiler.report(
t.makeError(n, DEPRECATED_CLASS_REASON,
type.toString(), deprecationInfo));
} else {
compiler.report(
t.makeError(n, DEPRECATED_CLASS, type.toString()));
}
}
}
}
/**
* Checks the given NAME node to ensure that access restrictions are obeyed.
*/
private void checkNameDeprecation(NodeTraversal t, Node n, Node parent) {
if (!shouldEmitDeprecationWarning(t, n)) {
return;
}
// Don't bother checking definitions or constructors.
if (parent.isFunction() || NodeUtil.isNameDeclaration(parent) || parent.isNew()) {
return;
}
Var var = t.getScope().getVar(n.getString());
JSDocInfo docInfo = var == null ? null : var.getJSDocInfo();
if (docInfo != null && docInfo.isDeprecated()) {
if (docInfo.getDeprecationReason() != null) {
compiler.report(
t.makeError(n, DEPRECATED_NAME_REASON, n.getString(),
docInfo.getDeprecationReason()));
} else {
compiler.report(
t.makeError(n, DEPRECATED_NAME, n.getString()));
}
}
}
/** Checks the given GETPROP node to ensure that access restrictions are obeyed. */
private void checkPropertyDeprecation(NodeTraversal t, PropertyReference propRef) {
if (!shouldEmitDeprecationWarning(t, propRef)) {
return;
}
// Don't bother checking constructors.
if (propRef.getSourceNode().getParent().isNew()) {
return;
}
ObjectType objectType = castToObject(dereference(propRef.getReceiverType()));
String propertyName = propRef.getName();
if (objectType != null) {
String deprecationInfo
= getPropertyDeprecationInfo(objectType, propertyName);
if (deprecationInfo != null) {
if (!deprecationInfo.isEmpty()) {
compiler.report(
t.makeError(
propRef.getSourceNode(),
DEPRECATED_PROP_REASON,
propertyName,
propRef.getReadableTypeNameOrDefault(),
deprecationInfo));
} else {
compiler.report(
t.makeError(
propRef.getSourceNode(),
DEPRECATED_PROP,
propertyName,
propRef.getReadableTypeNameOrDefault()));
}
}
}
}
private boolean isPrivateByConvention(String name) {
return enforceCodingConventions
&& compiler.getCodingConvention().isPrivate(name);
}
/**
* Determines whether the given OBJECTLIT property visibility violates the coding convention.
*
* @param t The current traversal.
* @param key The objectlit key node (STRING_KEY, GETTER_DEF, SETTER_DEF, MEMBER_FUNCTION_DEF).
*/
private void checkKeyVisibilityConvention(NodeTraversal t, Node key, Node parent) {
JSDocInfo info = key.getJSDocInfo();
if (info == null) {
return;
}
if (!isPrivateByConvention(key.getString())) {
return;
}
Node assign = parent.getParent();
if (assign == null || !assign.isAssign()) {
return;
}
Node left = assign.getFirstChild();
if (!left.isGetProp()
|| !left.getLastChild().getString().equals("prototype")) {
return;
}
Visibility declaredVisibility = info.getVisibility();
// Visibility is declared to be something other than private.
if (declaredVisibility != Visibility.INHERITED
&& declaredVisibility != Visibility.PRIVATE) {
compiler.report(t.makeError(key, CONVENTION_MISMATCH));
}
}
/**
* Reports an error if the given name is not visible in the current context.
* @param t The current traversal.
* @param name The name node.
*/
private void checkNameVisibility(NodeTraversal t, Node name, Node parent) {
Var var = t.getScope().getVar(name.getString());
if (var == null) {
return;
}
Visibility v = checkPrivateNameConvention(
AccessControlUtils.getEffectiveNameVisibility(
name, var, defaultVisibilityForFiles), name);
switch (v) {
case PACKAGE:
if (!isPackageAccessAllowed(var, name)) {
compiler.report(
t.makeError(name, BAD_PACKAGE_PROPERTY_ACCESS,
name.getString(), var.getSourceFile().getName()));
}
break;
case PRIVATE:
if (!isPrivateAccessAllowed(var, name, parent)) {
compiler.report(
t.makeError(name, BAD_PRIVATE_GLOBAL_ACCESS,
name.getString(), var.getSourceFile().getName()));
}
break;
default:
// Nothing to do for PUBLIC and PROTECTED
// (which is irrelevant for names).
break;
}
}
/**
* Returns the effective visibility of the given name, reporting an error
* if there is a contradiction in the various sources of visibility
* (example: a variable with a trailing underscore that is declared
* {@code @public}).
*/
private Visibility checkPrivateNameConvention(Visibility v, Node name) {
if (isPrivateByConvention(name.getString())) {
if (v != Visibility.PRIVATE && v != Visibility.INHERITED) {
compiler.report(JSError.make(name, CONVENTION_MISMATCH));
}
return Visibility.PRIVATE;
}
return v;
}
private static boolean isPrivateAccessAllowed(Var var, Node name, Node parent) {
StaticSourceFile varSrc = var.getSourceFile();
StaticSourceFile refSrc = name.getStaticSourceFile();
JSDocInfo docInfo = var.getJSDocInfo();
if (varSrc != null
&& refSrc != null
&& !varSrc.getName().equals(refSrc.getName())) {
return docInfo != null && docInfo.isConstructor()
&& isValidPrivateConstructorAccess(parent);
} else {
return true;
}
}
private boolean isPackageAccessAllowed(Var var, Node name) {
StaticSourceFile varSrc = var.getSourceFile();
StaticSourceFile refSrc = name.getStaticSourceFile();
CodingConvention codingConvention = compiler.getCodingConvention();
if (varSrc != null && refSrc != null) {
String srcPackage = codingConvention.getPackageName(varSrc);
String refPackage = codingConvention.getPackageName(refSrc);
return srcPackage != null
&& refPackage != null
&& srcPackage.equals(refPackage);
} else {
// If the source file of either var or name is unavailable, conservatively
// assume they belong to different packages.
// TODO(brndn): by contrast, isPrivateAccessAllowed does allow
// private access when a source file is unknown. I didn't change it
// in order not to break existing code.
return false;
}
}
private void checkOverriddenPropertyVisibilityMismatch(
Visibility overriding,
Visibility overridden,
@Nullable Visibility fileOverview,
NodeTraversal t,
PropertyReference propRef) {
if (overriding == Visibility.INHERITED
&& overriding != overridden
&& fileOverview != null
&& fileOverview != Visibility.INHERITED) {
compiler.report(
t.makeError(
propRef.getSourceNode(),
BAD_PROPERTY_OVERRIDE_IN_FILE_WITH_FILEOVERVIEW_VISIBILITY,
propRef.getName(),
fileOverview.name()));
}
}
@Nullable
private static Visibility getOverridingPropertyVisibility(PropertyReference propRef) {
JSDocInfo overridingInfo = propRef.getJSDocInfo();
return overridingInfo == null || !overridingInfo.isOverride()
? null
: overridingInfo.getVisibility();
}
/** Checks if a constructor is trying to override a final class. */
private void checkFinalClassOverrides(NodeTraversal t, Node ctor, Node parent) {
checkArgument(isFunctionOrClass(ctor), ctor);
JSType type = ctor.getJSType().toMaybeFunctionType();
if (type != null && type.isConstructor()) {
JSType finalParentClass =
getSuperClassInstanceIfFinal(bestInstanceTypeForMethodOrCtor(ctor, parent));
if (finalParentClass != null) {
compiler.report(
t.makeError(
ctor,
EXTEND_FINAL_CLASS,
type.getDisplayName(),
finalParentClass.getDisplayName()));
}
}
}
/** Determines whether the given constant property got reassigned */
private void checkConstantProperty(NodeTraversal t, PropertyReference propRef) {
if (!propRef.isMutation()) {
return;
}
ObjectType objectType = castToObject(dereference(propRef.getReceiverType()));
String propertyName = propRef.getName();
boolean isConstant = isPropertyDeclaredConstant(objectType, propertyName);
// Check whether constant properties are reassigned
if (isConstant) {
JSDocInfo info = propRef.getJSDocInfo();
if (info != null && info.getSuppressions().contains("const")) {
return;
}
if (propRef.isDeletion()) {
compiler.report(t.makeError(propRef.getSourceNode(), CONST_PROPERTY_DELETED, propertyName));
return;
}
// Can't check for constant properties on generic function types.
// TODO(johnlenz): I'm not 100% certain this is necessary, or if
// the type is being inspected incorrectly.
if (objectType == null
|| (objectType.isFunctionType()
&& !objectType.toMaybeFunctionType().isConstructor())) {
return;
}
ObjectType oType = objectType;
while (oType != null) {
if (initializedConstantProperties.containsEntry(oType, propertyName)
|| initializedConstantProperties.containsEntry(
getCanonicalInstance(oType), propertyName)) {
compiler.report(
t.makeError(propRef.getSourceNode(), CONST_PROPERTY_REASSIGNED_VALUE, propertyName));
break;
}
oType = oType.getPrototypeObject();
}
initializedConstantProperties.put(objectType, propertyName);
// Add the prototype when we're looking at an instance object
if (objectType.isInstanceType()) {
ObjectType prototype = objectType.getPrototypeObject();
if (prototype != null && prototype.hasProperty(propertyName)) {
initializedConstantProperties.put(prototype, propertyName);
}
}
}
}
/**
* Return an object with the same nominal type as obj,
* but without any possible extra properties that exist on obj.
*/
static ObjectType getCanonicalInstance(ObjectType obj) {
FunctionType ctor = obj.getConstructor();
return ctor == null ? obj : ctor.getInstanceType();
}
/** Dereference a type, autoboxing it and filtering out null. */
@Nullable
private static ObjectType dereference(JSType type) {
return type == null ? null : type.dereference();
}
private JSType typeOrUnknown(JSType type) {
return (type == null) ? typeRegistry.getNativeType(JSTypeNative.UNKNOWN_TYPE) : type;
}
private ObjectType typeOrUnknown(ObjectType type) {
return (ObjectType) typeOrUnknown((JSType) type);
}
private ObjectType boxedOrUnknown(@Nullable JSType type) {
return typeOrUnknown(dereference(type));
}
/** Reports an error if the given property is not visible in the current context. */
private void checkPropertyVisibility(NodeTraversal t, PropertyReference propRef) {
JSDocInfo jsdoc = propRef.getJSDocInfo();
if (jsdoc != null && jsdoc.getSuppressions().contains("visibility")) {
return;
}
JSType rawReferenceType = typeOrUnknown(propRef.getReceiverType()).autobox();
ObjectType referenceType = castToObject(rawReferenceType);
String propertyName = propRef.getName();
boolean isPrivateByConvention = isPrivateByConvention(propertyName);
if (isPrivateByConvention && propertyIsDeclaredButNotPrivate(propRef)) {
compiler.report(t.makeError(propRef.getSourceNode(), CONVENTION_MISMATCH));
return;
}
StaticSourceFile definingSource =
AccessControlUtils.getDefiningSource(propRef.getSourceNode(), referenceType, propertyName);
boolean isClassType = false;
// Is this a normal property access, or are we trying to override
// an existing property?
boolean isOverride = propRef.isDocumentedDeclaration() || propRef.isOverride();
ObjectType objectType = AccessControlUtils.getObjectType(
referenceType, isOverride, propertyName);
Visibility fileOverviewVisibility =
defaultVisibilityForFiles.get(definingSource);
Visibility visibility =
getEffectivePropertyVisibility(
propRef,
referenceType,
defaultVisibilityForFiles,
enforceCodingConventions ? compiler.getCodingConvention() : null);
if (isOverride) {
Visibility overriding = getOverridingPropertyVisibility(propRef);
if (overriding != null) {
checkOverriddenPropertyVisibilityMismatch(
overriding, visibility, fileOverviewVisibility, t, propRef);
}
}
JSType reportType = rawReferenceType;
if (objectType != null) {
Node node = objectType.getOwnPropertyDefSite(propertyName);
if (node == null) {
// Assume the property is public.
return;
}
reportType = objectType;
definingSource = node.getStaticSourceFile();
isClassType = objectType.getOwnPropertyJSDocInfo(propertyName).isConstructor();
} else if (!isPrivateByConvention && fileOverviewVisibility == null) {
// We can only check visibility references if we know what file
// it was defined in.
// Otherwise just assume the property is public.
return;
}
StaticSourceFile referenceSource = propRef.getSourceNode().getStaticSourceFile();
if (isOverride) {
boolean sameInput = referenceSource != null
&& referenceSource.getName().equals(definingSource.getName());
checkOverriddenPropertyVisibility(
t, propRef, visibility, fileOverviewVisibility, reportType, sameInput);
} else {
checkNonOverriddenPropertyVisibility(
t, propRef, visibility, isClassType, reportType, referenceSource, definingSource);
}
}
private static boolean propertyIsDeclaredButNotPrivate(PropertyReference propRef) {
if (!propRef.isDocumentedDeclaration() && !propRef.isOverride()) {
return false;
}
Visibility declaredVisibility = propRef.getJSDocInfo().getVisibility();
if (declaredVisibility == Visibility.PRIVATE || declaredVisibility == Visibility.INHERITED) {
return false;
}
return true;
}
private void checkOverriddenPropertyVisibility(
NodeTraversal t,
PropertyReference propRef,
Visibility visibility,
Visibility fileOverviewVisibility,
JSType objectType,
boolean sameInput) {
Visibility overridingVisibility =
propRef.isOverride() ? propRef.getJSDocInfo().getVisibility() : Visibility.INHERITED;
// Check that:
// (a) the property *can* be overridden,
// (b) the visibility of the override is the same as the
// visibility of the original property,
// (c) the visibility is explicitly redeclared if the override is in
// a file with default visibility in the @fileoverview block.
if (visibility == Visibility.PRIVATE && !sameInput) {
compiler.report(
t.makeError(propRef.getSourceNode(), PRIVATE_OVERRIDE, objectType.toString()));
} else if (overridingVisibility != Visibility.INHERITED
&& overridingVisibility != visibility
&& fileOverviewVisibility == null) {
compiler.report(
t.makeError(
propRef.getSourceNode(),
VISIBILITY_MISMATCH,
visibility.name(),
objectType.toString(),
overridingVisibility.name()));
}
}
private void checkNonOverriddenPropertyVisibility(
NodeTraversal t,
PropertyReference propRef,
Visibility visibility,
boolean isClassType,
JSType objectType,
StaticSourceFile referenceSource,
StaticSourceFile definingSource) {
// private access is always allowed in the same file.
if (referenceSource != null
&& definingSource != null
&& referenceSource.getName().equals(definingSource.getName())) {
return;
}
JSType ownerType = normalizeClassType(objectType);
switch (visibility) {
case PACKAGE:
checkPackagePropertyVisibility(t, propRef, referenceSource, definingSource);
break;
case PRIVATE:
checkPrivatePropertyVisibility(t, propRef, isClassType, ownerType);
break;
case PROTECTED:
checkProtectedPropertyVisibility(t, propRef, ownerType);
break;
default:
break;
}
}
private void checkPackagePropertyVisibility(
NodeTraversal t,
PropertyReference propRef,
StaticSourceFile referenceSource,
StaticSourceFile definingSource) {
CodingConvention codingConvention = compiler.getCodingConvention();
String refPackage = codingConvention.getPackageName(referenceSource);
String defPackage = codingConvention.getPackageName(definingSource);
if (refPackage == null
|| defPackage == null
|| !refPackage.equals(defPackage)) {
compiler.report(
t.makeError(
propRef.getSourceNode(),
BAD_PACKAGE_PROPERTY_ACCESS,
propRef.getName(),
propRef.getReadableTypeNameOrDefault()));
}
}
private void checkPrivatePropertyVisibility(
NodeTraversal t, PropertyReference propRef, boolean isClassType, JSType ownerType) {
if (isClassType && isValidPrivateConstructorAccess(propRef.getParentNode())) {
return;
}
// private access is not allowed outside the file from a different
// enclosing class.
// TODO(tbreisacher): Should we also include the filename where ownerType is defined?
String readableTypeName =
ownerType.equals(propRef.getReceiverType())
? propRef.getReadableTypeNameOrDefault()
: ownerType.toString();
compiler.report(
t.makeError(
propRef.getSourceNode(),
BAD_PRIVATE_PROPERTY_ACCESS,
propRef.getName(),
readableTypeName));
}
private void checkProtectedPropertyVisibility(
NodeTraversal t, PropertyReference propRef, JSType ownerType) {
// There are 3 types of legal accesses of a protected property:
// 1) Accesses in the same file
// 2) Overriding the property in a subclass
// 3) Accessing the property from inside a subclass
// The first two have already been checked for.
for (JSType scopeType : currentClassStack) {
if (scopeType == null) {
continue;
} else if (scopeType.isSubtypeOf(ownerType)) {
return;
}
}
compiler.report(
t.makeError(
propRef.getSourceNode(),
BAD_PROTECTED_PROPERTY_ACCESS,
propRef.getName(),
propRef.getReadableTypeNameOrDefault()));
}
/**
* Whether the given access of a private constructor is legal.
*
* For example,
* new PrivateCtor_(); // not legal
* PrivateCtor_.newInstance(); // legal
* x instanceof PrivateCtor_ // legal
*
* This is a weird special case, because our visibility system is inherited
* from Java, and JavaScript has no distinction between classes and
* constructors like Java does.
*
* We may want to revisit this if we decide to make the restrictions tighter.
*/
private static boolean isValidPrivateConstructorAccess(Node parent) {
return !parent.isNew();
}
/**
* Determines whether a deprecation warning should be emitted.
*
* @param t The current traversal.
* @param n The node which we are checking.
* @param parent The parent of the node which we are checking.
*/
private boolean shouldEmitDeprecationWarning(NodeTraversal t, Node n) {
// In the global scope, there are only two kinds of accesses that should
// be flagged for warnings:
// 1) Calls of deprecated functions and methods.
// 2) Instantiations of deprecated classes.
// For now, we just let everything else by.
if (t.inGlobalScope()) {
if (!NodeUtil.isInvocationTarget(n) && !n.isNew()) {
return false;
}
}
return !canAccessDeprecatedTypes(t);
}
/** Determines whether a deprecation warning should be emitted. */
private boolean shouldEmitDeprecationWarning(NodeTraversal t, PropertyReference propRef) {
// In the global scope, there are only two kinds of accesses that should
// be flagged for warnings:
// 1) Calls of deprecated functions and methods.
// 2) Instantiations of deprecated classes.
// For now, we just let everything else by.
if (t.inGlobalScope()) {
if (!NodeUtil.isInvocationTarget(propRef.getSourceNode())) {
return false;
}
}
// We can always assign to a deprecated property, to keep it up to date.
if (propRef.isMutation()) {
return false;
}
// Don't warn if the node is just declaring the property, not reading it.
JSDocInfo jsdoc = propRef.getJSDocInfo();
if (propRef.isDeclaration() && (jsdoc != null) && jsdoc.isDeprecated()) {
return false;
}
return !canAccessDeprecatedTypes(t);
}
/**
* Returns whether it's currently OK to access deprecated names and
* properties.
*
* There are 3 exceptions when we're allowed to use a deprecated
* type or property:
* 1) When we're in a deprecated function.
* 2) When we're in a deprecated class.
* 3) When we're in a static method of a deprecated class.
*/
private boolean canAccessDeprecatedTypes(NodeTraversal t) {
Node scopeRoot = t.getClosestHoistScopeRoot();
if (NodeUtil.isFunctionBlock(scopeRoot)) {
scopeRoot = scopeRoot.getParent();
}
Node scopeRootParent = scopeRoot.getParent();
return
// Case #1
(deprecationDepth > 0)
// Case #2
|| (getTypeDeprecationInfo(getTypeOfThis(scopeRoot)) != null)
// Case #3
|| (scopeRootParent != null
&& scopeRootParent.isAssign()
&& getTypeDeprecationInfo(bestInstanceTypeForMethodOrCtor(scopeRoot, scopeRootParent))
!= null);
}
/**
* Returns whether this node roots a subtree under which references to deprecated constructs are
* allowed.
*/
private static boolean isDeprecationScopeRoot(Node n) {
if (!isFunctionOrClass(n)) {
return false;
}
return getDeprecationReason(NodeUtil.getBestJSDocInfo(n)) != null;
}