Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2006 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.collect.Lists;
20 import com.google.javascript.jscomp.CheckLevel;
21 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
22 import com.google.javascript.rhino.IR;
23 import com.google.javascript.rhino.JSDocInfoBuilder;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26
27 import java.util.List;
28
29 /**
30 * Checks for non side effecting statements such as
31 * <pre>
32 * var s = "this string is "
33 * "continued on the next line but you forgot the +";
34 * x == foo(); // should that be '='?
35 * foo();; // probably just a stray-semicolon. Doesn't hurt to check though
36 * </p>
37 * and generates warnings.
38 *
39 */
40 final class CheckSideEffects extends AbstractPostOrderCallback
41 implements HotSwapCompilerPass {
42
43 static final DiagnosticType USELESS_CODE_ERROR = DiagnosticType.warning(
44 "JSC_USELESS_CODE",
45 "Suspicious code. {0}");
46
47 static final String PROTECTOR_FN = "JSCOMPILER_PRESERVE";
48
49 private final CheckLevel level;
50
51 private final List<Node> problemNodes = Lists.newArrayList();
52
53 private final AbstractCompiler compiler;
54
55 private final boolean protectSideEffectFreeCode;
56
57 CheckSideEffects(AbstractCompiler compiler, CheckLevel level,
58 boolean protectSideEffectFreeCode) {
59 this.compiler = compiler;
60 this.level = level;
61 this.protectSideEffectFreeCode = protectSideEffectFreeCode;
62 }
63
64 @Override
65 public void process(Node externs, Node root) {
66 NodeTraversal.traverse(compiler, root, this);
67
68 // Code with hidden side-effect code is common, for example
69 // accessing "el.offsetWidth" forces a reflow in browsers, to allow this
70 // will still allowing local dead code removal in general,
71 // protect the "side-effect free" code in the source.
72 //
73 if (protectSideEffectFreeCode) {
74 protectSideEffects();
75 }
76 }
77
78 @Override
79 public void hotSwapScript(Node scriptRoot, Node originalRoot) {
80 NodeTraversal.traverse(compiler, scriptRoot, this);
81 }
82
83 @Override
84 public void visit(NodeTraversal t, Node n, Node parent) {
85 // VOID nodes appear when there are extra semicolons at the BLOCK level.
86 // I've been unable to think of any cases where this indicates a bug,
87 // and apparently some people like keeping these semicolons around,
88 // so we'll allow it.
89 if (n.isEmpty() ||
90 n.isComma()) {
91 return;
92 }
93
94 if (parent == null) {
95 return;
96 }
97
98 // Do not try to remove a block or an expr result. We already handle
99 // these cases when we visit the child, and the peephole passes will
100 // fix up the tree in more clever ways when these are removed.
101 if (n.isExprResult() || n.isBlock()) {
102 return;
103 }
104
105 // This no-op statement was there so that JSDoc information could
106 // be attached to the name. This check should not complain about it.
107 if (n.isQualifiedName() && n.getJSDocInfo() != null) {
108 return;
109 }
110
111 boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);
112 boolean isSimpleOp = NodeUtil.isSimpleOperator(n);
113 if (!isResultUsed &&
114 (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {
115 String msg = "This code lacks side-effects. Is there a bug?";
116 if (n.isString()) {
117 msg = "Is there a missing '+' on the previous line?";
118 } else if (isSimpleOp) {
119 msg = "The result of the '" + Token.name(n.getType()).toLowerCase() +
120 "' operator is not being used.";
121 }
122
123 t.getCompiler().report(
124 t.makeError(n, level, USELESS_CODE_ERROR, msg));
125 // TODO(johnlenz): determine if it is necessary to
126 // try to protect side-effect free statements as well.
127 if (!NodeUtil.isStatement(n)) {
128 problemNodes.add(n);
129 }
130 }
131 }
132
133 /**
134 * Protect side-effect free nodes by making them parameters
135 * to a extern function call. This call will be removed
136 * after all the optimizations passes have run.
137 */
138 private void protectSideEffects() {
139 if (!problemNodes.isEmpty()) {
140 addExtern();
141 for (Node n : problemNodes) {
142 Node name = IR.name(PROTECTOR_FN).srcref(n);
143 name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
144 Node replacement = IR.call(name).srcref(n);
145 replacement.putBooleanProp(Node.FREE_CALL, true);
146 n.getParent().replaceChild(n, replacement);
147 replacement.addChildToBack(n);
148 }
149 compiler.reportCodeChange();
150 }
151 }
152
153 private void addExtern() {
154 Node name = IR.name(PROTECTOR_FN);
155 name.putBooleanProp(Node.IS_CONSTANT_NAME, true);
156 Node var = IR.var(name);
157 // Add "@noalias" so we can strip the method when AliasExternals is enabled.
158 JSDocInfoBuilder builder = new JSDocInfoBuilder(false);
159 builder.recordNoAlias();
160 var.setJSDocInfo(builder.build(var));
161 CompilerInput input = compiler.getSynthesizedExternsInput();
162 input.getAstRoot(compiler).addChildrenToBack(var);
163 compiler.reportCodeChange();
164 }
165
166 /**
167 * Remove side-effect sync functions.
168 */
169 static class StripProtection extends AbstractPostOrderCallback implements CompilerPass {
170
171 private final AbstractCompiler compiler;
172
173 StripProtection(AbstractCompiler compiler) {
174 this.compiler = compiler;
175 }
176
177 @Override
178 public void process(Node externs, Node root) {
179 NodeTraversal.traverse(compiler, root, this);
180 }
181
182 @Override
183 public void visit(NodeTraversal t, Node n, Node parent) {
184 if (n.isCall()) {
185 Node target = n.getFirstChild();
186 // TODO(johnlenz): add this to the coding convention
187 // so we can remove goog.reflect.sinkValue as well.
188 if (target.isName() && target.getString().equals(PROTECTOR_FN)) {
189 Node expr = n.getLastChild();
190 n.detachChildren();
191 parent.replaceChild(n, expr);
192 }
193 }
194 }
195 }
196 }