Debian Codegraph @

src/com/google/javascript/jscomp/PureFunctionIdentifier.java

raw symbols SCIP
1 /*
2 * Copyright 2009 The Closure Compiler Authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Charsets;
20 import com.google.common.base.Preconditions;
21 import com.google.common.base.Predicate;
22 import com.google.common.collect.Lists;
23 import com.google.common.collect.Maps;
24 import com.google.common.collect.Sets;
25 import com.google.common.io.Files;
26 import com.google.javascript.jscomp.DefinitionsRemover.Definition;
27 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
28 import com.google.javascript.jscomp.Scope.Var;
29 import com.google.javascript.jscomp.graph.DiGraph;
30 import com.google.javascript.jscomp.graph.FixedPointGraphTraversal;
31 import com.google.javascript.jscomp.graph.FixedPointGraphTraversal.EdgeCallback;
32 import com.google.javascript.jscomp.graph.LinkedDirectedGraph;
33 import com.google.javascript.rhino.JSDocInfo;
34 import com.google.javascript.rhino.Node;
35 import com.google.javascript.rhino.Token;
36 import com.google.javascript.rhino.jstype.FunctionType;
37 import com.google.javascript.rhino.jstype.JSType;
38 import com.google.javascript.rhino.jstype.JSTypeNative;
39
40 import java.io.File;
41 import java.io.IOException;
42 import java.util.Collection;
43 import java.util.Collections;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48
49 /**
50 * Compiler pass that computes function purity. A function is pure if
51 * it has no outside visible side effects, and the result of the
52 * computation does not depend on external factors that are beyond the
53 * control of the application; repeated calls to the function should
54 * return the same value as long as global state hasn't changed.
55 *
56 * Date.now is an example of a function that has no side effects but
57 * is not pure.
58 *
59 *
60 * We will prevail, in peace and freedom from fear, and in true
61 * health, through the purity and essence of our natural... fluids.
62 * - General Turgidson
63 */
64 class PureFunctionIdentifier implements CompilerPass {
65 static final DiagnosticType INVALID_NO_SIDE_EFFECT_ANNOTATION =
66 DiagnosticType.error(
67 "JSC_INVALID_NO_SIDE_EFFECT_ANNOTATION",
68 "@nosideeffects may only appear in externs files.");
69
70 static final DiagnosticType INVALID_MODIFIES_ANNOTATION =
71 DiagnosticType.error(
72 "JSC_INVALID_MODIFIES_ANNOTATION",
73 "@modifies may only appear in externs files.");
74
75 private final AbstractCompiler compiler;
76 private final DefinitionProvider definitionProvider;
77
78 // Function node -> function side effects map
79 private final Map<Node, FunctionInformation> functionSideEffectMap;
80
81 // List of all function call sites; used to iterate in markPureFunctionCalls.
82 private final List<Node> allFunctionCalls;
83
84 // Externs and ast tree root, for use in getDebugReport. These two
85 // fields are null until process is called.
86 private Node externs;
87 private Node root;
88
89 public PureFunctionIdentifier(AbstractCompiler compiler,
90 DefinitionProvider definitionProvider) {
91 this.compiler = compiler;
92 this.definitionProvider = definitionProvider;
93 this.functionSideEffectMap = Maps.newHashMap();
94 this.allFunctionCalls = Lists.newArrayList();
95 this.externs = null;
96 this.root = null;
97 }
98
99 @Override
100 public void process(Node externsAst, Node srcAst) {
101 if (externs != null || root != null) {
102 throw new IllegalStateException(
103 "It is illegal to call PureFunctionIdentifier.process " +
104 "twice the same instance. Please use a new " +
105 "PureFunctionIdentifier instance each time.");
106 }
107
108 externs = externsAst;
109 root = srcAst;
110
111 NodeTraversal.traverse(compiler, externs, new FunctionAnalyzer(true));
112 NodeTraversal.traverse(compiler, root, new FunctionAnalyzer(false));
113
114 propagateSideEffects();
115
116 markPureFunctionCalls();
117 }
118
119 /**
120 * Compute debug report that includes:
121 * - List of all pure functions.
122 * - Reasons we think the remaining functions have side effects.
123 */
124 String getDebugReport() {
125 Preconditions.checkNotNull(externs);
126 Preconditions.checkNotNull(root);
127
128 StringBuilder sb = new StringBuilder();
129
130 FunctionNames functionNames = new FunctionNames(compiler);
131 functionNames.process(null, externs);
132 functionNames.process(null, root);
133
134 sb.append("Pure functions:\n");
135 for (Map.Entry<Node, FunctionInformation> entry :
136 functionSideEffectMap.entrySet()) {
137 Node function = entry.getKey();
138 FunctionInformation functionInfo = entry.getValue();
139
140 boolean isPure =
141 functionInfo.mayBePure() && !functionInfo.mayHaveSideEffects();
142 if (isPure) {
143 sb.append(" " + functionNames.getFunctionName(function) + "\n");
144 }
145 }
146 sb.append("\n");
147
148 for (Map.Entry<Node, FunctionInformation> entry :
149 functionSideEffectMap.entrySet()) {
150 Node function = entry.getKey();
151 FunctionInformation functionInfo = entry.getValue();
152
153 Set<String> depFunctionNames = Sets.newHashSet();
154 for (Node callSite : functionInfo.getCallsInFunctionBody()) {
155 Collection<Definition> defs =
156 getCallableDefinitions(definitionProvider,
157 callSite.getFirstChild());
158
159 if (defs == null) {
160 depFunctionNames.add("<null def list>");
161 continue;
162 }
163
164 for (Definition def : defs) {
165 depFunctionNames.add(
166 functionNames.getFunctionName(def.getRValue()));
167 }
168 }
169
170 sb.append(functionNames.getFunctionName(function) + " " +
171 functionInfo.toString() +
172 " Calls: " + depFunctionNames + "\n");
173 }
174
175 return sb.toString();
176 }
177
178 /**
179 * Query the DefinitionProvider for the list of definitions that
180 * correspond to a given qualified name subtree. Return null if
181 * DefinitionProvider does not contain an entry for a given name,
182 * one or more of the values returned by getDeclarations is not
183 * callable, or the "name" node is not a GETPROP or NAME.
184 *
185 * @param definitionProvider The name reference graph
186 * @param name Query node
187 * @return non-empty definition list or null
188 */
189 private static Collection<Definition> getCallableDefinitions(
190 DefinitionProvider definitionProvider, Node name) {
191 if (name.isGetProp() || name.isName()) {
192 List<Definition> result = Lists.newArrayList();
193
194 Collection<Definition> decls =
195 definitionProvider.getDefinitionsReferencedAt(name);
196 if (decls == null) {
197 return null;
198 }
199
200 for (Definition current : decls) {
201 Node rValue = current.getRValue();
202 if ((rValue != null) && rValue.isFunction()) {
203 result.add(current);
204 } else {
205 return null;
206 }
207 }
208
209 return result;
210 } else if (name.isOr() || name.isHook()) {
211 Node firstVal;
212 if (name.isHook()) {
213 firstVal = name.getFirstChild().getNext();
214 } else {
215 firstVal = name.getFirstChild();
216 }
217
218 Collection<Definition> defs1 = getCallableDefinitions(definitionProvider,
219 firstVal);
220 Collection<Definition> defs2 = getCallableDefinitions(definitionProvider,
221 firstVal.getNext());
222 if (defs1 != null && defs2 != null) {
223 defs1.addAll(defs2);
224 return defs1;
225 } else {
226 return null;
227 }
228 } else if (NodeUtil.isFunctionExpression(name)) {
229 // The anonymous function reference is also the definition.
230 // TODO(user) Change SimpleDefinitionFinder so it is possible to query for
231 // function expressions by function node.
232
233 // isExtern is false in the call to the constructor for the
234 // FunctionExpressionDefinition below because we know that
235 // getCallableDefinitions() will only be called on the first
236 // child of a call and thus the function expression
237 // definition will never be an extern.
238 return Lists.newArrayList(
239 (Definition)
240 new DefinitionsRemover.FunctionExpressionDefinition(name, false));
241 } else {
242 return null;
243 }
244 }
245
246 /**
247 * Propagate side effect information by building a graph based on
248 * call site information stored in FunctionInformation and the
249 * DefinitionProvider and then running GraphReachability to
250 * determine the set of functions that have side effects.
251 */
252 private void propagateSideEffects() {
253 // Nodes are function declarations; Edges are function call sites.
254 DiGraph<FunctionInformation, Node> sideEffectGraph =
255 LinkedDirectedGraph.createWithoutAnnotations();
256
257 // create graph nodes
258 for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
259 sideEffectGraph.createNode(functionInfo);
260 }
261
262 // add connections to called functions and side effect root.
263 for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
264 if (!functionInfo.mayHaveSideEffects()) {
265 continue;
266 }
267
268 for (Node callSite : functionInfo.getCallsInFunctionBody()) {
269 Node callee = callSite.getFirstChild();
270 Collection<Definition> defs =
271 getCallableDefinitions(definitionProvider, callee);
272 if (defs == null) {
273 // Definition set is not complete or eligible. Possible
274 // causes include:
275 // * "callee" is not of type NAME or GETPROP.
276 // * One or more definitions are not functions.
277 // * One or more definitions are complex.
278 // (e.i. return value of a call that returns a function).
279 functionInfo.setTaintsUnknown();
280 break;
281 }
282
283 for (Definition def : defs) {
284 Node defValue = def.getRValue();
285 FunctionInformation dep = functionSideEffectMap.get(defValue);
286 Preconditions.checkNotNull(dep);
287 sideEffectGraph.connect(dep, callSite, functionInfo);
288 }
289 }
290 }
291
292 // Propagate side effect information to a fixed point.
293 FixedPointGraphTraversal.newTraversal(new SideEffectPropagationCallback())
294 .computeFixedPoint(sideEffectGraph);
295
296 // Mark remaining functions "pure".
297 for (FunctionInformation functionInfo : functionSideEffectMap.values()) {
298 if (functionInfo.mayBePure()) {
299 functionInfo.setIsPure();
300 }
301 }
302 }
303
304 /**
305 * Set no side effect property at pure-function call sites.
306 */
307 private void markPureFunctionCalls() {
308 for (Node callNode : allFunctionCalls) {
309 Node name = callNode.getFirstChild();
310 Collection<Definition> defs =
311 getCallableDefinitions(definitionProvider, name);
312 // Default to side effects, non-local results
313 Node.SideEffectFlags flags = new Node.SideEffectFlags();
314 if (defs == null) {
315 flags.setMutatesGlobalState();
316 flags.setThrows();
317 flags.setReturnsTainted();
318 } else {
319 flags.clearAllFlags();
320 for (Definition def : defs) {
321 FunctionInformation functionInfo =
322 functionSideEffectMap.get(def.getRValue());
323 Preconditions.checkNotNull(functionInfo);
324 // TODO(johnlenz): set the arguments separately from the
325 // global state flag.
326 if (functionInfo.mutatesGlobalState()) {
327 flags.setMutatesGlobalState();
328 }
329
330 if (functionInfo.functionThrows) {
331 flags.setThrows();
332 }
333
334 if (!callNode.isNew()) {
335 if (functionInfo.taintsThis) {
336 flags.setMutatesThis();
337 }
338 }
339
340 if (functionInfo.taintsReturn) {
341 flags.setReturnsTainted();
342 }
343
344 if (flags.areAllFlagsSet()) {
345 break;
346 }
347 }
348 }
349
350 // Handle special cases (Math, RegExp)
351 if (callNode.isCall()) {
352 Preconditions.checkState(compiler != null);
353 if (!NodeUtil.functionCallHasSideEffects(callNode, compiler)) {
354 flags.clearSideEffectFlags();
355 }
356 } else if (callNode.isNew()) {
357 // Handle known cases now (Object, Date, RegExp, etc)
358 if (!NodeUtil.constructorCallHasSideEffects(callNode)) {
359 flags.clearSideEffectFlags();
360 }
361 }
362
363 callNode.setSideEffectFlags(flags.valueOf());
364 }
365 }
366
367 /**
368 * Gather list of functions, functions with @nosideeffects
369 * annotations, call sites, and functions that may mutate variables
370 * not defined in the local scope.
371 */
372 private class FunctionAnalyzer implements ScopedCallback {
373 private final boolean inExterns;
374
375 FunctionAnalyzer(boolean inExterns) {
376 this.inExterns = inExterns;
377 }
378
379 @Override
380 public boolean shouldTraverse(NodeTraversal traversal,
381 Node node,
382 Node parent) {
383
384 // Functions need to be processed as part of pre-traversal so an
385 // entry for the enclosing function exists in the
386 // FunctionInformation map when processing assignments and calls
387 // inside visit.
388 if (node.isFunction()) {
389 Node gramp = parent.getParent();
390 visitFunction(traversal, node, parent, gramp);
391 }
392
393 return true;
394 }
395
396 @Override
397 public void visit(NodeTraversal traversal, Node node, Node parent) {
398
399 if (inExterns) {
400 return;
401 }
402
403 if (!NodeUtil.nodeTypeMayHaveSideEffects(node)
404 && !node.isReturn()) {
405 return;
406 }
407
408 if (node.isCall() || node.isNew()) {
409 allFunctionCalls.add(node);
410 }
411
412 Node enclosingFunction = traversal.getEnclosingFunction();
413 if (enclosingFunction != null) {
414 FunctionInformation sideEffectInfo =
415 functionSideEffectMap.get(enclosingFunction);
416 Preconditions.checkNotNull(sideEffectInfo);
417
418 if (NodeUtil.isAssignmentOp(node)) {
419 visitAssignmentOrUnaryOperator(
420 sideEffectInfo, traversal.getScope(),
421 node, node.getFirstChild(), node.getLastChild());
422 } else {
423 switch(node.getType()) {
424 case Token.CALL:
425 case Token.NEW:
426 visitCall(sideEffectInfo, node);
427 break;
428 case Token.DELPROP:
429 case Token.DEC:
430 case Token.INC:
431 visitAssignmentOrUnaryOperator(
432 sideEffectInfo, traversal.getScope(),
433 node, node.getFirstChild(), null);
434 break;
435 case Token.NAME:
436 // Variable definition are not side effects.
437 // Just check that the name appears in the context of a
438 // variable declaration.
439 Preconditions.checkArgument(
440 NodeUtil.isVarDeclaration(node));
441 Node value = node.getFirstChild();
442 // Assignment to local, if the value isn't a safe local value,
443 // new object creation or literal or known primitive result
444 // value, add it to the local blacklist.
445 if (value != null && !NodeUtil.evaluatesToLocalValue(value)) {
446 Scope scope = traversal.getScope();
447 Var var = scope.getVar(node.getString());
448 sideEffectInfo.blacklistLocal(var);
449 }
450 break;
451 case Token.THROW:
452 visitThrow(sideEffectInfo);
453 break;
454 case Token.RETURN:
455 if (node.hasChildren()
456 && !NodeUtil.evaluatesToLocalValue(node.getFirstChild())) {
457 sideEffectInfo.setTaintsReturn();
458 }
459 break;
460 default:
461 throw new IllegalArgumentException(
462 "Unhandled side effect node type " +
463 Token.name(node.getType()));
464 }
465 }
466 }
467 }
468
469 @Override
470 public void enterScope(NodeTraversal t) {
471 // Nothing to do.
472 }
473
474 @Override
475 public void exitScope(NodeTraversal t) {
476 if (t.inGlobalScope()) {
477 return;
478 }
479
480 // Handle deferred local variable modifications:
481 //
482 FunctionInformation sideEffectInfo =
483 functionSideEffectMap.get(t.getScopeRoot());
484 if (sideEffectInfo.mutatesGlobalState()){
485 sideEffectInfo.resetLocalVars();
486 return;
487 }
488
489 for (Iterator<Var> i = t.getScope().getVars(); i.hasNext();) {
490 Var v = i.next();
491 boolean localVar = false;
492 // Parameters and catch values come can from other scopes.
493 if (v.getParentNode().isVar()) {
494 // TODO(johnlenz): create a useful parameter list
495 sideEffectInfo.knownLocals.add(v.getName());
496 localVar = true;
497 }
498
499 // Take care of locals that might have been tainted.
500 if (!localVar || sideEffectInfo.blacklisted.contains(v)) {
501 if (sideEffectInfo.taintedLocals.contains(v)) {
502 // If the function has global side-effects
503 // don't bother with the local side-effects.
504 sideEffectInfo.setTaintsUnknown();
505 sideEffectInfo.resetLocalVars();
506 break;
507 }
508 }
509 }
510
511 sideEffectInfo.taintedLocals = null;
512 sideEffectInfo.blacklisted = null;
513 }
514
515
516 /**
517 * Record information about the side effects caused by an
518 * assignment or mutating unary operator.
519 *
520 * If the operation modifies this or taints global state, mark the
521 * enclosing function as having those side effects.
522 * @param op operation being performed.
523 * @param lhs The store location (name or get) being operated on.
524 * @param rhs The right have value, if any.
525 */
526 private void visitAssignmentOrUnaryOperator(
527 FunctionInformation sideEffectInfo,
528 Scope scope, Node op, Node lhs, Node rhs) {
529 if (lhs.isName()) {
530 Var var = scope.getVar(lhs.getString());
531 if (var == null || var.scope != scope) {
532 sideEffectInfo.setTaintsGlobalState();
533 } else {
534 // Assignment to local, if the value isn't a safe local value,
535 // a literal or new object creation, add it to the local blacklist.
536 // parameter values depend on the caller.
537
538 // Note: other ops result in the name or prop being assigned a local
539 // value (x++ results in a number, for instance)
540 Preconditions.checkState(
541 NodeUtil.isAssignmentOp(op)
542 || isIncDec(op) || op.isDelProp());
543 if (rhs != null
544 && op.isAssign()
545 && !NodeUtil.evaluatesToLocalValue(rhs)) {
546 sideEffectInfo.blacklistLocal(var);
547 }
548 }
549 } else if (NodeUtil.isGet(lhs)) {
550 if (lhs.getFirstChild().isThis()) {
551 sideEffectInfo.setTaintsThis();
552 } else {
553 Var var = null;
554 Node objectNode = lhs.getFirstChild();
555 if (objectNode.isName()) {
556 var = scope.getVar(objectNode.getString());
557 }
558 if (var == null || var.scope != scope) {
559 sideEffectInfo.setTaintsUnknown();
560 } else {
561 // Maybe a local object modification. We won't know for sure until
562 // we exit the scope and can validate the value of the local.
563 //
564 sideEffectInfo.addTaintedLocalObject(var);
565 }
566 }
567 } else {
568 // TODO(johnlenz): track down what is inserting NULL on the LHS
569 // of an assign.
570
571 // The only valid LHS expressions are NAME, GETELEM, or GETPROP.
572 // throw new IllegalStateException(
573 // "Unexpected LHS expression:" + lhs.toStringTree()
574 // + ", parent: " + op.toStringTree() );
575 sideEffectInfo.setTaintsUnknown();
576 }
577 }
578
579 /**
580 * Record information about a call site.
581 */
582 private void visitCall(FunctionInformation sideEffectInfo, Node node) {
583 // Handle special cases (Math, RegExp)
584 if (node.isCall()
585 && !NodeUtil.functionCallHasSideEffects(node, compiler)) {
586 return;
587 }
588
589 // Handle known cases now (Object, Date, RegExp, etc)
590 if (node.isNew()
591 && !NodeUtil.constructorCallHasSideEffects(node)) {
592 return;
593 }
594
595 sideEffectInfo.appendCall(node);
596 }
597
598 /**
599 * Record function and check for @nosideeffects annotations.
600 */
601 private void visitFunction(NodeTraversal traversal,
602 Node node,
603 Node parent,
604 Node gramp) {
605 Preconditions.checkArgument(!functionSideEffectMap.containsKey(node));
606
607 FunctionInformation sideEffectInfo = new FunctionInformation(inExterns);
608 functionSideEffectMap.put(node, sideEffectInfo);
609
610 if (inExterns) {
611 JSType jstype = node.getJSType();
612 boolean knownLocalResult = false;
613 FunctionType functionType = JSType.toMaybeFunctionType(jstype);
614 if (functionType != null) {
615 JSType jstypeReturn = functionType.getReturnType();
616 if (isLocalValueType(jstypeReturn)) {
617 knownLocalResult = true;
618 }
619 }
620 if (!knownLocalResult) {
621 sideEffectInfo.setTaintsReturn();
622 }
623 }
624
625 JSDocInfo info = getJSDocInfoForFunction(node, parent, gramp);
626 if (info != null) {
627 boolean hasSpecificSideEffects = false;
628 if (hasSideEffectsThisAnnotation(info)) {
629 if (inExterns) {
630 hasSpecificSideEffects = true;
631 sideEffectInfo.setTaintsThis();
632 } else {
633 traversal.report(node, INVALID_MODIFIES_ANNOTATION);
634 }
635 }
636
637 if (hasSideEffectsArgumentsAnnotation(info)) {
638 if (inExterns) {
639 hasSpecificSideEffects = true;
640 sideEffectInfo.setTaintsArguments();
641 } else {
642 traversal.report(node, INVALID_MODIFIES_ANNOTATION);
643 }
644 }
645
646 if (inExterns && !info.getThrownTypes().isEmpty()) {
647 hasSpecificSideEffects = true;
648 sideEffectInfo.setFunctionThrows();
649 }
650
651 if (!hasSpecificSideEffects) {
652 if (hasNoSideEffectsAnnotation(info)) {
653 if (inExterns) {
654 sideEffectInfo.setIsPure();
655 } else {
656 traversal.report(node, INVALID_NO_SIDE_EFFECT_ANNOTATION);
657 }
658 } else if (inExterns) {
659 sideEffectInfo.setTaintsGlobalState();
660 }
661 }
662 } else {
663 if (inExterns) {
664 sideEffectInfo.setTaintsGlobalState();
665 }
666 }
667 }
668
669 /**
670 * @return Whether the jstype is something known to be a local value.
671 */
672 private boolean isLocalValueType(JSType jstype) {
673 Preconditions.checkNotNull(jstype);
674 JSType subtype = jstype.getGreatestSubtype(
675 compiler.getTypeRegistry().getNativeType(JSTypeNative.OBJECT_TYPE));
676 // If the type includes anything related to a object type, don't assume
677 // anything about the locality of the value.
678 return subtype.isNoType();
679 }
680
681 /**
682 * Record that the enclosing function throws.
683 */
684 private void visitThrow(FunctionInformation sideEffectInfo) {
685 sideEffectInfo.setFunctionThrows();
686 }
687
688 /**
689 * Get the doc info associated with the function.
690 */
691 private JSDocInfo getJSDocInfoForFunction(
692 Node node, Node parent, Node gramp) {
693 JSDocInfo info = node.getJSDocInfo();
694 if (info != null) {
695 return info;
696 } else if (parent.isName()) {
697 return gramp.hasOneChild() ? gramp.getJSDocInfo() : null;
698 } else if (parent.isAssign()) {
699 return parent.getJSDocInfo();
700 } else {
701 return null;
702 }
703 }
704
705 /**
706 * Get the value of the @nosideeffects annotation stored in the
707 * doc info.
708 */
709 private boolean hasNoSideEffectsAnnotation(JSDocInfo docInfo) {
710 Preconditions.checkNotNull(docInfo);
711 return docInfo.isNoSideEffects();
712 }
713
714 /**
715 * Get the value of the @modifies{this} annotation stored in the
716 * doc info.
717 */
718 private boolean hasSideEffectsThisAnnotation(JSDocInfo docInfo) {
719 Preconditions.checkNotNull(docInfo);
720 return (docInfo.getModifies().contains("this"));
721 }
722
723 /**
724 * @returns Whether the @modifies annotation includes "arguments"
725 * or any named parameters.
726 */
727 private boolean hasSideEffectsArgumentsAnnotation(JSDocInfo docInfo) {
728 Preconditions.checkNotNull(docInfo);
729 Set<String> modifies = docInfo.getModifies();
730 // TODO(johnlenz): if we start tracking parameters individually
731 // this should simply be a check for "arguments".
732 return (modifies.size() > 1
733 || (modifies.size() == 1 && !modifies.contains("this")));
734 }
735 }
736
737 private static boolean isIncDec(Node n) {
738 int type = n.getType();
739 return (type == Token.INC || type == Token.DEC);
740 }
741
742 /**
743 * @return Whether the node is known to be a value that is not a reference
744 * outside the local scope.
745 */
746 @SuppressWarnings("unused")
747 private static boolean isKnownLocalValue(final Node value) {
748 Predicate<Node> taintingPredicate = new Predicate<Node>() {
749 @Override
750 public boolean apply(Node value) {
751 switch (value.getType()) {
752 case Token.ASSIGN:
753 // The assignment might cause an alias, look at the LHS.
754 return false;
755 case Token.THIS:
756 // TODO(johnlenz): maybe redirect this to be a tainting list for 'this'.
757 return false;
758 case Token.NAME:
759 // TODO(johnlenz): add to local tainting list, if the NAME
760 // is known to be a local.
761 return false;
762 case Token.GETELEM:
763 case Token.GETPROP:
764 // There is no information about the locality of object properties.
765 return false;
766 case Token.CALL:
767 // TODO(johnlenz): add to local tainting list, if the call result
768 // is not known to be a local result.
769 return false;
770 }
771 return false;
772 }
773 };
774
775 return NodeUtil.evaluatesToLocalValue(value, taintingPredicate);
776 }
777
778 /**
779 * Callback that propagates side effect information across call sites.
780 */
781 private static class SideEffectPropagationCallback
782 implements EdgeCallback<FunctionInformation, Node> {
783 @Override
784 public boolean traverseEdge(FunctionInformation callee,
785 Node callSite,
786 FunctionInformation caller) {
787 Preconditions.checkArgument(callSite.isCall() ||
788 callSite.isNew());
789
790 boolean changed = false;
791 if (!caller.mutatesGlobalState() && callee.mutatesGlobalState()) {
792 caller.setTaintsGlobalState();
793 changed = true;
794 }
795
796 if (!caller.functionThrows() && callee.functionThrows()) {
797 caller.setFunctionThrows();
798 changed = true;
799 }
800
801 if (callee.mutatesThis()) {
802 // Side effects only propagate via regular calls.
803 // Calling a constructor that modifies "this" has no side effects.
804 if (!callSite.isNew()) {
805 Node objectNode = getCallThisObject(callSite);
806 if (objectNode != null && objectNode.isName()
807 && !isCallOrApply(callSite)) {
808 // Exclude ".call" and ".apply" as the value may still be
809 // null or undefined. We don't need to worry about this with a
810 // direct method call because null and undefined don't have any
811 // properties.
812
813 // TODO(nicksantos): Turn this back on when locals-tracking
814 // is fixed. See testLocalizedSideEffects11.
815 //if (!caller.knownLocals.contains(name)) {
816 if (!caller.mutatesGlobalState()) {
817 caller.setTaintsGlobalState();
818 changed = true;
819 }
820 //}
821 } else if (objectNode != null && objectNode.isThis()) {
822 if (!caller.mutatesThis()) {
823 caller.setTaintsThis();
824 changed = true;
825 }
826 } else if (objectNode != null
827 && NodeUtil.evaluatesToLocalValue(objectNode)
828 && !isCallOrApply(callSite)) {
829 // Modifying 'this' on a known local object doesn't change any
830 // significant state.
831 // TODO(johnlenz): We can improve this by including literal values
832 // that we know for sure are not null.
833 } else if (!caller.mutatesGlobalState()) {
834 caller.setTaintsGlobalState();
835 changed = true;
836 }
837 }
838 }
839
840 return changed;
841 }
842 }
843
844 /**
845 * Analyze a call site and extract the node that will be act as
846 * "this" inside the call, which is either the object part of the
847 * qualified function name, the first argument to the call in the
848 * case of ".call" and ".apply" or null if object is not specified
849 * in either of those ways.
850 *
851 * @return node that will act as "this" for the call.
852 */
853 private static Node getCallThisObject(Node callSite) {
854 Node callTarget = callSite.getFirstChild();
855 if (!NodeUtil.isGet(callTarget)) {
856
857 // "this" is not specified explicitly; call modifies global "this".
858 return null;
859 }
860
861 String propString = callTarget.getLastChild().getString();
862 if (propString.equals("call") || propString.equals("apply")) {
863 return callTarget.getNext();
864 } else {
865 return callTarget.getFirstChild();
866 }
867 }
868
869 private static boolean isCallOrApply(Node callSite) {
870 Node callTarget = callSite.getFirstChild();
871 if (NodeUtil.isGet(callTarget)) {
872 String propString = callTarget.getLastChild().getString();
873 if (propString.equals("call") || propString.equals("apply")) {
874 return true;
875 }
876 }
877 return false;
878 }
879
880 /**
881 * Keeps track of a function's known side effects by type and the
882 * list of calls that appear in a function's body.
883 */
884 private static class FunctionInformation {
885 private final boolean extern;
886 private final List<Node> callsInFunctionBody = Lists.newArrayList();
887 private Set<Var> blacklisted = Sets.newHashSet();
888 private Set<Var> taintedLocals = Sets.newHashSet();
889 private Set<String> knownLocals = Sets.newHashSet();
890 private boolean pureFunction = false;
891 private boolean functionThrows = false;
892 private boolean taintsGlobalState = false;
893 private boolean taintsThis = false;
894 private boolean taintsArguments = false;
895 private boolean taintsUnknown = false;
896 private boolean taintsReturn = false;
897
898 FunctionInformation(boolean extern) {
899 this.extern = extern;
900 checkInvariant();
901 }
902
903 /**
904 * @param var
905 */
906 void addTaintedLocalObject(Var var) {
907 taintedLocals.add(var);
908 }
909
910 void resetLocalVars() {
911 blacklisted = null;
912 taintedLocals = null;
913 knownLocals = Collections.emptySet();
914 }
915
916 /**
917 * @param var
918 */
919 public void blacklistLocal(Var var) {
920 blacklisted.add(var);
921 }
922
923 /**
924 * @returns false if function known to have side effects.
925 */
926 boolean mayBePure() {
927 return !(functionThrows ||
928 taintsGlobalState ||
929 taintsThis ||
930 taintsArguments ||
931 taintsUnknown);
932 }
933
934 /**
935 * @returns false if function known to be pure.
936 */
937 boolean mayHaveSideEffects() {
938 return !pureFunction;
939 }
940
941 /**
942 * Mark the function as being pure.
943 */
944 void setIsPure() {
945 pureFunction = true;
946 checkInvariant();
947 }
948
949 /**
950 * Marks the function as having "modifies globals" side effects.
951 */
952 void setTaintsGlobalState() {
953 taintsGlobalState = true;
954 checkInvariant();
955 }
956
957 /**
958 * Marks the function as having "modifies this" side effects.
959 */
960 void setTaintsThis() {
961 taintsThis = true;
962 checkInvariant();
963 }
964
965 /**
966 * Marks the function as having "modifies arguments" side effects.
967 */
968 void setTaintsArguments() {
969 taintsArguments = true;
970 checkInvariant();
971 }
972
973 /**
974 * Marks the function as having "throw" side effects.
975 */
976 void setFunctionThrows() {
977 functionThrows = true;
978 checkInvariant();
979 }
980
981 /**
982 * Marks the function as having "complex" side effects that are
983 * not otherwise explicitly tracked.
984 */
985 void setTaintsUnknown() {
986 taintsUnknown = true;
987 checkInvariant();
988 }
989
990 /**
991 * Marks the function as having non-local return result.
992 */
993 void setTaintsReturn() {
994 taintsReturn = true;
995 checkInvariant();
996 }
997
998
999 /**
1000 * Returns true if function mutates global state.
1001 */
1002 boolean mutatesGlobalState() {
1003 // TODO(johnlenz): track arguments separately.
1004 return taintsGlobalState || taintsArguments || taintsUnknown;
1005 }
1006
1007 /**
1008 * Returns true if function mutates "this".
1009 */
1010 boolean mutatesThis() {
1011 return taintsThis;
1012 }
1013
1014 /**
1015 * Returns true if function has an explicit "throw".
1016 */
1017 boolean functionThrows() {
1018 return functionThrows;
1019 }
1020
1021 /**
1022 * Verify internal consistency. Should be called at the end of
1023 * every method that mutates internal state.
1024 */
1025 private void checkInvariant() {
1026 boolean invariant = mayBePure() || mayHaveSideEffects();
1027 if (!invariant) {
1028 throw new IllegalStateException("Invariant failed. " + toString());
1029 }
1030 }
1031
1032 /**
1033 * Add a CALL or NEW node to the list of calls this function makes.
1034 */
1035 void appendCall(Node callNode) {
1036 callsInFunctionBody.add(callNode);
1037 }
1038
1039 /**
1040 * Gets the list of CALL and NEW nodes.
1041 */
1042 List<Node> getCallsInFunctionBody() {
1043 return callsInFunctionBody;
1044 }
1045
1046 @Override
1047 public String toString() {
1048 List<String> status = Lists.newArrayList();
1049 if (extern) {
1050 status.add("extern");
1051 }
1052
1053 if (pureFunction) {
1054 status.add("pure");
1055 }
1056
1057 if (taintsThis) {
1058 status.add("this");
1059 }
1060
1061 if (taintsGlobalState) {
1062 status.add("global");
1063 }
1064
1065 if (functionThrows) {
1066 status.add("throw");
1067 }
1068
1069 if (taintsUnknown) {
1070 status.add("complex");
1071 }
1072
1073 return "Side effects: " + status.toString();
1074 }
1075 }
1076
1077 /**
1078 * A compiler pass that constructs a reference graph and drives
1079 * the PureFunctionIdentifier across it.
1080 */
1081 static class Driver implements CompilerPass {
1082 private final AbstractCompiler compiler;
1083 private final String reportPath;
1084 private final boolean useNameReferenceGraph;
1085
1086 Driver(AbstractCompiler compiler, String reportPath,
1087 boolean useNameReferenceGraph) {
1088 this.compiler = compiler;
1089 this.reportPath = reportPath;
1090 this.useNameReferenceGraph = useNameReferenceGraph;
1091 }
1092
1093 @Override
1094 public void process(Node externs, Node root) {
1095 DefinitionProvider definitionProvider = null;
1096 if (useNameReferenceGraph) {
1097 NameReferenceGraphConstruction graphBuilder =
1098 new NameReferenceGraphConstruction(compiler);
1099 graphBuilder.process(externs, root);
1100 definitionProvider = graphBuilder.getNameReferenceGraph();
1101 } else {
1102 SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler);
1103 defFinder.process(externs, root);
1104 definitionProvider = defFinder;
1105 }
1106
1107 PureFunctionIdentifier pureFunctionIdentifier =
1108 new PureFunctionIdentifier(compiler, definitionProvider);
1109 pureFunctionIdentifier.process(externs, root);
1110
1111 if (reportPath != null) {
1112 try {
1113 Files.write(pureFunctionIdentifier.getDebugReport(),
1114 new File(reportPath),
1115 Charsets.UTF_8);
1116 } catch (IOException e) {
1117 throw new RuntimeException(e);
1118 }
1119 }
1120 }
1121 }
1122 }