-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
PureFunctionIdentifier.java
1109 lines (971 loc) · 35.7 KB
/
PureFunctionIdentifier.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 2009 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 java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import com.google.javascript.jscomp.CodingConvention.Cache;
import com.google.javascript.jscomp.DefinitionsRemover.Definition;
import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal;
import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback;
import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
import com.google.javascript.rhino.JSDocInfo;
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 java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Compiler pass that computes function purity. A function is pure if it has no outside visible side
* effects, and the result of the computation does not depend on external factors that are beyond
* the control of the application; repeated calls to the function should return the same value as
* long as global state hasn't changed.
*
* <p>Date.now is an example of a function that has no side effects but is not pure.
*
* @author johnlenz@google.com (John Lenz)
* <p>We will prevail, in peace and freedom from fear, and in true health, through the purity
* and essence of our natural... fluids. - General Turgidson
*/
class PureFunctionIdentifier implements CompilerPass {
private final AbstractCompiler compiler;
private final DefinitionProvider definitionProvider;
// Function node -> function side effects map
private final Map<Node, FunctionInformation> functionSideEffectMap;
// List of all function call sites; used to iterate in markPureFunctionCalls.
private final List<Node> allFunctionCalls;
// Externs and ast tree root, for use in getDebugReport. These two
// fields are null until process is called.
private Node externs;
private Node root;
public PureFunctionIdentifier(AbstractCompiler compiler,
DefinitionProvider definitionProvider) {
this.compiler = compiler;
this.definitionProvider = definitionProvider;
this.functionSideEffectMap = new HashMap<>();
this.allFunctionCalls = new ArrayList<>();
this.externs = null;
this.root = null;
}
@Override
public void process(Node externsAst, Node srcAst) {
Preconditions.checkState(
externs == null && root == null,
"It is illegal to call PureFunctionIdentifier.process twice the same instance. Please "
+ " use a new PureFunctionIdentifier instance each time.");
externs = externsAst;
root = srcAst;
NodeTraversal.traverseEs6(compiler, externs, new FunctionAnalyzer(true));
NodeTraversal.traverseEs6(compiler, root, new FunctionAnalyzer(false));
propagateSideEffects();
markPureFunctionCalls();
}
/**
* Compute debug report that includes:
* - List of all pure functions.
* - Reasons we think the remaining functions have side effects.
*/
String getDebugReport() {
Preconditions.checkNotNull(externs);
Preconditions.checkNotNull(root);
StringBuilder sb = new StringBuilder();
FunctionNames functionNames = new FunctionNames(compiler);
functionNames.process(null, externs);
functionNames.process(null, root);
sb.append("Pure functions:\n");
for (Map.Entry<Node, FunctionInformation> entry :
functionSideEffectMap.entrySet()) {
Node function = entry.getKey();
FunctionInformation functionInfo = entry.getValue();
boolean isPure =
functionInfo.mayBePure() && !functionInfo.mayHaveSideEffects();
if (isPure) {
sb.append(" ").append(functionNames.getFunctionName(function)).append("\n");
}
}
sb.append("\n");
for (Map.Entry<Node, FunctionInformation> entry :
functionSideEffectMap.entrySet()) {
Node function = entry.getKey();
FunctionInformation functionInfo = entry.getValue();
Set<String> depFunctionNames = new HashSet<>();
for (Node callSite : functionInfo.getCallsInFunctionBody()) {
Collection<Definition> defs =
getCallableDefinitions(definitionProvider,
callSite.getFirstChild());
if (defs == null) {
depFunctionNames.add("<null def list>");
continue;
}
for (Definition def : defs) {
depFunctionNames.add(
functionNames.getFunctionName(def.getRValue()));
}
}
sb.append(functionNames.getFunctionName(function))
.append(" ")
.append(functionInfo)
.append(" Calls: ")
.append(depFunctionNames)
.append("\n");
}
return sb.toString();
}
/**
* Query the DefinitionProvider for the list of definitions that
* correspond to a given qualified name subtree. Return null if
* DefinitionProvider does not contain an entry for a given name,
* one or more of the values returned by getDeclarations is not
* callable, or the "name" node is not a GETPROP or NAME.
*
* @param definitionProvider The name reference graph
* @param name Query node
* @return non-empty definition list or null
*/
private static Collection<Definition> getCallableDefinitions(
DefinitionProvider definitionProvider, Node name) {
if (name.isGetProp() || name.isName()) {
List<Definition> result = new ArrayList<>();
Collection<Definition> decls =
definitionProvider.getDefinitionsReferencedAt(name);
if (decls == null) {
return null;
}
for (Definition current : decls) {
Node rValue = current.getRValue();
if ((rValue != null) && rValue.isFunction()) {
result.add(current);
} else {
return null;
}
}
return result;
} else if (name.isOr() || name.isHook()) {
Node firstVal;
if (name.isHook()) {
firstVal = name.getSecondChild();
} else {
firstVal = name.getFirstChild();
}
Collection<Definition> defs1 = getCallableDefinitions(definitionProvider,
firstVal);
Collection<Definition> defs2 = getCallableDefinitions(definitionProvider,
firstVal.getNext());
if (defs1 != null && defs2 != null) {
defs1.addAll(defs2);
return defs1;
} else {
return null;
}
} else if (NodeUtil.isFunctionExpression(name)) {
// The anonymous function reference is also the definition.
// TODO(user) Change DefinitionUseSiteFinder so it is possible to query for
// function expressions by function node.
// isExtern is false in the call to the constructor for the
// FunctionExpressionDefinition below because we know that
// getCallableDefinitions() will only be called on the first
// child of a call and thus the function expression
// definition will never be an extern.
return ImmutableList.of(
(Definition)
new DefinitionsRemover.FunctionExpressionDefinition(name, false));
} else {
return null;
}
}
/**
* Propagate side effect information by building a graph based on
* call site information stored in FunctionInformation and the
* DefinitionProvider and then running GraphReachability to
* determine the set of functions that have side effects.
*/
private void propagateSideEffects() {
// Nodes are function declarations; Edges are function call sites.
LinkedDirectedGraph<FunctionInformation, Node> sideEffectGraph =
LinkedDirectedGraph.createWithoutAnnotations();
// create graph nodes
for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
functionInfo.graphNode = sideEffectGraph.createNode(functionInfo);
}
// add connections to called functions and side effect root.
for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
if (!functionInfo.mayHaveSideEffects()) {
continue;
}
for (Node callSite : functionInfo.getCallsInFunctionBody()) {
Node callee = callSite.getFirstChild();
Cache cacheCall = compiler.getCodingConvention().describeCachingCall(callSite);
Collection<Definition> defs = cacheCall != null
? getGoogCacheCallableDefinitions(definitionProvider, cacheCall)
: getCallableDefinitions(definitionProvider, callee);
if (defs == null) {
// Definition set is not complete or eligible. Possible
// causes include:
// * "callee" is not of type NAME or GETPROP.
// * One or more definitions are not functions.
// * One or more definitions are complex.
// (e.i. return value of a call that returns a function).
functionInfo.setTaintsUnknown();
break;
}
for (Definition def : defs) {
Node defValue = def.getRValue();
FunctionInformation dep = functionSideEffectMap.get(defValue);
Preconditions.checkNotNull(dep);
sideEffectGraph.connect(dep.graphNode, callSite, functionInfo.graphNode);
}
}
}
// Propagate side effect information to a fixed point.
FixedPointGraphTraversal.newTraversal(new SideEffectPropagationCallback())
.computeFixedPoint(sideEffectGraph);
// Mark remaining functions "pure".
for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
if (functionInfo.mayBePure()) {
functionInfo.setIsPure();
}
}
}
/**
* Set no side effect property at pure-function call sites.
*/
private void markPureFunctionCalls() {
for (Node callNode : allFunctionCalls) {
Node name = callNode.getFirstChild();
Cache cacheCall = compiler.getCodingConvention().describeCachingCall(callNode);
Collection<Definition> defs = cacheCall != null
? getGoogCacheCallableDefinitions(definitionProvider, cacheCall)
: getCallableDefinitions(definitionProvider, name);
// Default to side effects, non-local results
Node.SideEffectFlags flags = new Node.SideEffectFlags();
if (defs == null) {
flags.setMutatesGlobalState();
flags.setThrows();
flags.setReturnsTainted();
} else {
flags.clearAllFlags();
for (Definition def : defs) {
FunctionInformation functionInfo =
functionSideEffectMap.get(def.getRValue());
Preconditions.checkNotNull(functionInfo);
if (functionInfo.mutatesGlobalState()) {
flags.setMutatesGlobalState();
}
if (functionInfo.mutatesArguments()) {
flags.setMutatesArguments();
}
if (functionInfo.functionThrows()) {
flags.setThrows();
}
if (!callNode.isNew()) {
if (functionInfo.taintsThis()) {
// A FunctionInfo for "f" maps to both "f()" and "f.call()" nodes.
if (isCallOrApply(callNode)) {
flags.setMutatesArguments();
} else {
flags.setMutatesThis();
}
}
}
if (functionInfo.taintsReturn()) {
flags.setReturnsTainted();
}
if (flags.areAllFlagsSet()) {
break;
}
}
}
// Handle special cases (Math, RegExp)
if (callNode.isCall()) {
Preconditions.checkState(compiler != null);
if (!NodeUtil.functionCallHasSideEffects(callNode, compiler)) {
flags.clearSideEffectFlags();
}
} else if (callNode.isNew()) {
// Handle known cases now (Object, Date, RegExp, etc)
if (!NodeUtil.constructorCallHasSideEffects(callNode)) {
flags.clearSideEffectFlags();
}
}
callNode.setSideEffectFlags(flags.valueOf());
}
}
private Collection<Definition> getGoogCacheCallableDefinitions(
DefinitionProvider definitionProvider, Cache cacheCall) {
Preconditions.checkNotNull(cacheCall);
Preconditions.checkNotNull(definitionProvider);
List<Definition> defs = new ArrayList<>();
Collection<Definition> valueFnDefs =
getCallableDefinitions(definitionProvider, cacheCall.valueFn);
if (valueFnDefs != null) {
defs.addAll(valueFnDefs);
}
if (cacheCall.keyFn != null) {
Collection<Definition> keyFnDefs =
getCallableDefinitions(definitionProvider, cacheCall.keyFn);
if (keyFnDefs != null) {
defs.addAll(keyFnDefs);
}
}
return defs;
}
/**
* Gather list of functions, functions with @nosideeffects annotations, call sites, and functions
* that may mutate variables not defined in the local scope.
*/
private class FunctionAnalyzer implements ScopedCallback {
private final boolean inExterns;
FunctionAnalyzer(boolean inExterns) {
this.inExterns = inExterns;
}
@Override
public boolean shouldTraverse(NodeTraversal traversal, Node node, Node parent) {
// Functions need to be processed as part of pre-traversal so that an entry for the function
// exists in the FunctionInformation map when processing assignments and calls within the
// body.
if (node.isFunction()) {
visitFunction(node, parent);
}
return true;
}
@Override
public void visit(NodeTraversal traversal, Node node, Node parent) {
if (inExterns) {
return;
}
if (!NodeUtil.nodeTypeMayHaveSideEffects(node, compiler) && !node.isReturn()) {
return;
}
if (NodeUtil.isCallOrNew(node)) {
allFunctionCalls.add(node);
}
Node enclosingFunction = traversal.getEnclosingFunction();
if (enclosingFunction == null) {
return;
}
FunctionInformation sideEffectInfo = functionSideEffectMap.get(enclosingFunction);
Preconditions.checkNotNull(sideEffectInfo);
if (NodeUtil.isAssignmentOp(node) || node.isInc() || node.isDelProp() || node.isDec()) {
visitAssignmentOrUnaryOperator(sideEffectInfo, traversal.getScope(), node);
} else if (NodeUtil.isCallOrNew(node)) {
visitCall(sideEffectInfo, node);
} else if (node.isName()) {
// Variable definition are not side effects. Check that the name appears in the context of a
// variable declaration.
Preconditions.checkArgument(NodeUtil.isNameDeclaration(parent));
Node value = node.getFirstChild();
// Assignment to local, if the value isn't a safe local value,
// new object creation or literal or known primitive result
// value, add it to the local blacklist.
if (value != null && !NodeUtil.evaluatesToLocalValue(value)) {
Scope scope = traversal.getScope();
Var var = scope.getVar(node.getString());
sideEffectInfo.blacklistLocal(var);
}
} else if (node.isThrow()) {
sideEffectInfo.setFunctionThrows();
} else if (node.isReturn()) {
if (node.hasChildren() && !NodeUtil.evaluatesToLocalValue(node.getFirstChild())) {
sideEffectInfo.setTaintsReturn();
}
} else {
throw new IllegalArgumentException("Unhandled side effect node type " + node.getType());
}
}
@Override
public void enterScope(NodeTraversal t) {
// Nothing to do.
}
@Override
public void exitScope(NodeTraversal t) {
if (!t.getScope().isFunctionBlockScope() && !t.getScope().isFunctionScope()) {
return;
}
Node function = NodeUtil.getEnclosingFunction(t.getScopeRoot());
if (function == null) {
return;
}
// Handle deferred local variable modifications:
FunctionInformation sideEffectInfo = functionSideEffectMap.get(function);
Preconditions.checkNotNull(sideEffectInfo, "%s has no side effect info.", function);
if (sideEffectInfo.mutatesGlobalState()){
sideEffectInfo.resetLocalVars();
return;
}
for (Var v : t.getScope().getVarIterable()) {
boolean param = v.getParentNode().isParamList();
if (param &&
!sideEffectInfo.blacklisted().contains(v) &&
sideEffectInfo.taintedLocals().contains(v)) {
sideEffectInfo.setTaintsArguments();
continue;
}
boolean localVar = false;
// Parameters and catch values come can from other scopes.
if (v.getParentNode().isVar()) {
// TODO(johnlenz): create a useful parameter list
// sideEffectInfo.addKnownLocal(v.getName());
localVar = true;
}
// Take care of locals that might have been tainted.
if (!localVar || sideEffectInfo.blacklisted().contains(v)) {
if (sideEffectInfo.taintedLocals().contains(v)) {
// If the function has global side-effects
// don't bother with the local side-effects.
sideEffectInfo.setTaintsUnknown();
sideEffectInfo.resetLocalVars();
break;
}
}
}
if (t.getScopeRoot().isFunction()) {
sideEffectInfo.resetLocalVars();
}
}
private boolean varDeclaredInDifferentFunction(Var v, Scope scope) {
if (v == null) {
return true;
} else if (v.scope != scope) {
Node declarationRoot = NodeUtil.getEnclosingFunction(v.scope.rootNode);
Node scopeRoot = NodeUtil.getEnclosingFunction(scope.rootNode);
return declarationRoot != scopeRoot;
} else {
return false;
}
}
/**
* Record information about the side effects caused by an assignment or mutating unary operator.
*
* <p>If the operation modifies this or taints global state, mark the enclosing function as
* having those side effects.
*
* @param op operation being performed.
*/
private void visitAssignmentOrUnaryOperator(
FunctionInformation sideEffectInfo, Scope scope, Node op) {
Node lhs = op.getFirstChild();
if (lhs.isName()) {
Var var = scope.getVar(lhs.getString());
if (varDeclaredInDifferentFunction(var, scope)) {
sideEffectInfo.setTaintsGlobalState();
} else {
// Assignment to local, if the value isn't a safe local value,
// a literal or new object creation, add it to the local blacklist.
// parameter values depend on the caller.
// Note: other ops result in the name or prop being assigned a local
// value (x++ results in a number, for instance)
Preconditions.checkState(
NodeUtil.isAssignmentOp(op)
|| isIncDec(op) || op.isDelProp());
Node rhs = op.getLastChild();
if (rhs != null
&& op.isAssign()
&& !NodeUtil.evaluatesToLocalValue(rhs)) {
sideEffectInfo.blacklistLocal(var);
}
}
} else if (NodeUtil.isGet(lhs)) {
if (lhs.getFirstChild().isThis()) {
sideEffectInfo.setTaintsThis();
} else {
Var var = null;
Node objectNode = lhs.getFirstChild();
if (objectNode.isName()) {
var = scope.getVar(objectNode.getString());
}
if (varDeclaredInDifferentFunction(var, scope)) {
sideEffectInfo.setTaintsUnknown();
} else {
// Maybe a local object modification. We won't know for sure until
// we exit the scope and can validate the value of the local.
//
sideEffectInfo.addTaintedLocalObject(var);
}
}
} else {
// TODO(johnlenz): track down what is inserting NULL on the LHS
// of an assign.
// The only valid LHS expressions are NAME, GETELEM, or GETPROP.
// throw new IllegalStateException(
// "Unexpected LHS expression:" + lhs.toStringTree()
// + ", parent: " + op.toStringTree() );
sideEffectInfo.setTaintsUnknown();
}
}
/**
* Record information about a call site.
*/
private void visitCall(FunctionInformation sideEffectInfo, Node node) {
// Handle special cases (Math, RegExp)
if (node.isCall() && !NodeUtil.functionCallHasSideEffects(node, compiler)) {
return;
}
// Handle known cases now (Object, Date, RegExp, etc)
if (node.isNew() && !NodeUtil.constructorCallHasSideEffects(node)) {
return;
}
sideEffectInfo.appendCall(node);
}
/** Record function and check for @nosideeffects annotations. */
private void visitFunction(Node node, Node parent) {
Preconditions.checkArgument(node.isFunction());
Preconditions.checkState(!functionSideEffectMap.containsKey(node));
FunctionInformation sideEffectInfo = new FunctionInformation(inExterns);
functionSideEffectMap.put(node, sideEffectInfo);
JSDocInfo info = getJSDocInfoForFunction(node, parent);
if (inExterns) {
// Handle externs.
JSType jstype = node.getJSType();
FunctionType functionType = JSType.toMaybeFunctionType(jstype);
if (functionType != null) {
JSType jstypeReturn = functionType.getReturnType();
if (!isLocalValueType(jstypeReturn)) {
sideEffectInfo.setTaintsReturn();
}
}
if (info == null) {
// We don't know anything about this function so we assume it has side effects.
sideEffectInfo.setTaintsGlobalState();
} else {
if (info.modifiesThis()) {
sideEffectInfo.setTaintsThis();
} else if (info.hasSideEffectsArgumentsAnnotation()) {
sideEffectInfo.setTaintsArguments();
} else if (!info.getThrownTypes().isEmpty()) {
sideEffectInfo.setFunctionThrows();
} else if (info.isNoSideEffects()) {
sideEffectInfo.setIsPure();
} else {
sideEffectInfo.setTaintsGlobalState();
}
}
}
}
/**
* @return Whether the jstype is something known to be a local value.
*/
private boolean isLocalValueType(JSType jstype) {
Preconditions.checkNotNull(jstype);
JSType subtype = jstype.getGreatestSubtype(
(JSType) compiler.getTypeIRegistry().getNativeType(JSTypeNative.OBJECT_TYPE));
// If the type includes anything related to a object type, don't assume
// anything about the locality of the value.
return subtype.isNoType();
}
/** Get the doc info associated with the function. */
private JSDocInfo getJSDocInfoForFunction(Node node, Node parent) {
JSDocInfo info = node.getJSDocInfo();
if (info != null) {
return info;
} else if (parent.isName()) {
Node grandparent = parent.getParent();
return grandparent.hasOneChild() ? grandparent.getJSDocInfo() : null;
} else if (parent.isAssign()) {
return parent.getJSDocInfo();
} else {
return null;
}
}
}
private static boolean isIncDec(Node n) {
Token type = n.getType();
return (type == Token.INC || type == Token.DEC);
}
/**
* @return Whether the node is known to be a value that is not a reference
* outside the local scope.
*/
@SuppressWarnings("unused")
private static boolean isKnownLocalValue(final Node value) {
Predicate<Node> taintingPredicate =
new Predicate<Node>() {
@Override
public boolean apply(Node value) {
switch (value.getType()) {
case ASSIGN:
// The assignment might cause an alias, look at the LHS.
return false;
case THIS:
// TODO(johnlenz): maybe redirect this to be a tainting list for 'this'.
return false;
case NAME:
// TODO(johnlenz): add to local tainting list, if the NAME
// is known to be a local.
return false;
case GETELEM:
case GETPROP:
// There is no information about the locality of object properties.
return false;
case CALL:
// TODO(johnlenz): add to local tainting list, if the call result
// is not known to be a local result.
return false;
default:
break;
}
return false;
}
};
return NodeUtil.evaluatesToLocalValue(value, taintingPredicate);
}
/**
* Callback that propagates side effect information across call sites.
*/
private static class SideEffectPropagationCallback
implements EdgeCallback<FunctionInformation, Node> {
@Override
public boolean traverseEdge(FunctionInformation callee,
Node callSite,
FunctionInformation caller) {
Preconditions.checkArgument(callSite.isCall() ||
callSite.isNew());
boolean changed = false;
if (!caller.mutatesGlobalState() && callee.mutatesGlobalState()) {
caller.setTaintsGlobalState();
changed = true;
}
if (!caller.functionThrows() && callee.functionThrows()) {
caller.setFunctionThrows();
changed = true;
}
if (!caller.mutatesGlobalState() && callee.mutatesArguments() &&
!NodeUtil.allArgsUnescapedLocal(callSite)) {
// TODO(nicksantos): We should track locals in the caller
// and using that to be more precise. See testMutatesArguments3.
caller.setTaintsGlobalState();
changed = true;
}
if (callee.mutatesThis()) {
// Side effects only propagate via regular calls.
// Calling a constructor that modifies "this" has no side effects.
if (!callSite.isNew()) {
// Notice that we're using "mutatesThis" from the callee
// FunctionInfo. If the call site is actually a .call or .apply, then
// the "this" is going to be one of its arguments.
boolean isCallOrApply = isCallOrApply(callSite);
Node objectNode = isCallOrApply ?
callSite.getSecondChild() :
callSite.getFirstFirstChild();
if (objectNode != null && objectNode.isName()
&& !isCallOrApply) {
// Exclude ".call" and ".apply" as the value may still be
// null or undefined. We don't need to worry about this with a
// direct method call because null and undefined don't have any
// properties.
// TODO(nicksantos): Turn this back on when locals-tracking
// is fixed. See testLocalizedSideEffects11.
//if (!caller.knownLocals.contains(name)) {
if (!caller.mutatesGlobalState()) {
caller.setTaintsGlobalState();
changed = true;
}
//}
} else if (objectNode != null && objectNode.isThis()) {
if (!caller.mutatesThis()) {
caller.setTaintsThis();
changed = true;
}
} else if (objectNode != null
&& NodeUtil.evaluatesToLocalValue(objectNode)
&& !isCallOrApply) {
// Modifying 'this' on a known local object doesn't change any
// significant state.
// TODO(johnlenz): We can improve this by including literal values
// that we know for sure are not null.
} else if (!caller.mutatesGlobalState()) {
caller.setTaintsGlobalState();
changed = true;
}
}
}
return changed;
}
}
private static boolean isCallOrApply(Node callSite) {
return NodeUtil.isFunctionObjectCall(callSite) ||
NodeUtil.isFunctionObjectApply(callSite);
}
/**
* Keeps track of a function's known side effects by type and the
* list of calls that appear in a function's body.
*/
private static class FunctionInformation {
private DiGraphNode graphNode;
private List<Node> callsInFunctionBody = null;
private Set<Var> blacklisted = null;
private Set<Var> taintedLocals = null;
private int bitmask = 0;
private static final int EXTERN_MASK = 1 << 0;
private static final int PURE_FUNCTION_MASK = 1 << 1;
private static final int FUNCTION_THROWS_MASK = 1 << 2;
private static final int TAINTS_GLOBAL_STATE_MASK = 1 << 3;
private static final int TAINTS_THIS_MASK = 1 << 4;
private static final int TAINTS_ARGUMENTS_MASK = 1 << 5;
private static final int TAINTS_UNKNOWN_MASK = 1 << 6;
private static final int TAINTS_RETURN_MASK = 1 << 7;
private void setMask(int mask, boolean value) {
if (value) {
bitmask |= mask;
} else {
bitmask &= ~mask;
}
}
private boolean getMask(int mask) {
return (bitmask & mask) != 0;
}
private boolean extern() {
return getMask(EXTERN_MASK);
}
private boolean pureFunction() {
return getMask(PURE_FUNCTION_MASK);
}
private boolean taintsGlobalState() {
return getMask(TAINTS_GLOBAL_STATE_MASK);
}
private boolean taintsThis() {
return getMask(TAINTS_THIS_MASK);
}
private boolean taintsUnknown() {
return getMask(TAINTS_UNKNOWN_MASK);
}
private boolean taintsReturn() {
return getMask(TAINTS_RETURN_MASK);
}
/**
* Returns true if function has an explicit "throw".
*/
boolean functionThrows() {
return getMask(FUNCTION_THROWS_MASK);
}
FunctionInformation(boolean extern) {
this.setMask(EXTERN_MASK, extern);
checkInvariant();
}
public Set<Var> taintedLocals() {
if (taintedLocals == null) {
return Collections.emptySet();
}
return taintedLocals;
}
/**
* @param var
*/
void addTaintedLocalObject(Var var) {
if (taintedLocals == null) {
taintedLocals = new HashSet<>();
}
taintedLocals.add(var);
}
void resetLocalVars() {
blacklisted = Collections.emptySet();
taintedLocals = Collections.emptySet();
}
public Set<Var> blacklisted() {
if (blacklisted == null) {
return Collections.emptySet();
}
return blacklisted;
}
/**
* @param var
*/
public void blacklistLocal(Var var) {
if (blacklisted == null) {
blacklisted = new HashSet<>();
}
blacklisted.add(var);
}
/**
* @return false if function known to have side effects.
*/
boolean mayBePure() {
return !getMask(
FUNCTION_THROWS_MASK
| TAINTS_GLOBAL_STATE_MASK
| TAINTS_THIS_MASK
| TAINTS_ARGUMENTS_MASK
| TAINTS_UNKNOWN_MASK);
}
/**
* @return false if function known to be pure.
*/
boolean mayHaveSideEffects() {
return !pureFunction();
}
/**
* Mark the function as being pure.
*/
void setIsPure() {
this.setMask(PURE_FUNCTION_MASK, true);
checkInvariant();
}
/**
* Marks the function as having "modifies globals" side effects.
*/
void setTaintsGlobalState() {
setMask(TAINTS_GLOBAL_STATE_MASK, true);
checkInvariant();
}
/**
* Marks the function as having "modifies this" side effects.
*/
void setTaintsThis() {
setMask(TAINTS_THIS_MASK, true);
checkInvariant();
}
/**
* Marks the function as having "modifies arguments" side effects.
*/
void setTaintsArguments() {
setMask(TAINTS_ARGUMENTS_MASK, true);
checkInvariant();
}
/**
* Marks the function as having "throw" side effects.
*/
void setFunctionThrows() {
setMask(FUNCTION_THROWS_MASK, true);
checkInvariant();
}
/**
* Marks the function as having "complex" side effects that are
* not otherwise explicitly tracked.
*/
void setTaintsUnknown() {
setMask(TAINTS_UNKNOWN_MASK, true);
checkInvariant();
}
/**
* Marks the function as having non-local return result.
*/
void setTaintsReturn() {
setMask(TAINTS_RETURN_MASK, true);
checkInvariant();
}
/**
* Returns true if function mutates global state.
*/
boolean mutatesGlobalState() {
return getMask(TAINTS_GLOBAL_STATE_MASK | TAINTS_UNKNOWN_MASK);
}
/**