Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2008 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 package com.google.javascript.jscomp;
17
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Lists;
20 import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode;
21 import com.google.javascript.jscomp.ControlFlowGraph.Branch;
22 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.Node;
25 import com.google.javascript.rhino.Token;
26 import com.google.protobuf.TextFormat;
27
28 import java.io.IOException;
29 import java.util.List;
30
31 /**
32 * Instruments functions for when functions first get called and defined.
33 *
34 * This pass be used to instrument code to:
35 * 1. Gather statistics from real users in the wild.
36 * 2. Incorporate utilization statistics into Selenium tests
37 * 3. Access utilization statistics from an app's debug UI
38 *
39 * By parametrizing the whole instrumentation process we expect to be
40 * able to support a wide variety of use cases and minimize the cost
41 * of developing new instrumentation schemes.
42 *
43 * TODO(user): This pass currently runs just before the variable and
44 * property renaming near the end of the optimization pass. I think
45 * Mark put it there to minimize the difference between the code
46 * generated with/without instrumentation; instrumentation makes
47 * several optimization passes do less, for example inline functions.
48 *
49 * My opinion is that we want utilization/profiling information for
50 * all function. This pass should run before most passes that modify
51 * the AST (exception being the localization pass, which makes
52 * assumptions about the structure of the AST). We should move the
53 * pass up, list inlined functions or give clients the option to
54 * instrument before or after optimization.
55 *
56 */
57 class InstrumentFunctions implements CompilerPass {
58
59 private final AbstractCompiler compiler;
60 private final FunctionNames functionNames;
61 private final String templateFilename;
62 private final String appNameStr;
63 private final String initCodeSource;
64 private final String definedFunctionName;
65 private final String reportFunctionName;
66 private final String reportFunctionExitName;
67 private final String appNameSetter;
68 private final List<String> declarationsToRemove;
69
70 /**
71 * Creates an instrument functions compiler pass.
72 *
73 * @param compiler The JSCompiler
74 * @param functionNames Assigned function identifiers.
75 * @param templateFilename Template filename; for use during error
76 * reporting only.
77 * @param appNameStr String to pass to appNameSetter.
78 * @param readable Instrumentation template protobuf text.
79 */
80 InstrumentFunctions(AbstractCompiler compiler,
81 FunctionNames functionNames,
82 String templateFilename,
83 String appNameStr,
84 Readable readable) {
85 this.compiler = compiler;
86 this.functionNames = functionNames;
87 this.templateFilename = templateFilename;
88 this.appNameStr = appNameStr;
89
90 Instrumentation.Builder builder = Instrumentation.newBuilder();
91 try {
92 TextFormat.merge(readable, builder);
93 } catch (IOException e) {
94 compiler.report(JSError.make(RhinoErrorReporter.PARSE_ERROR,
95 "Error reading instrumentation template protobuf at " +
96 templateFilename));
97 this.initCodeSource = "";
98 this.definedFunctionName = "";
99 this.reportFunctionName = "";
100 this.reportFunctionExitName = "";
101 this.appNameSetter = "";
102 this.declarationsToRemove = Lists.newArrayList();
103 return;
104 }
105
106 Instrumentation template = builder.build();
107
108 StringBuilder initCodeSourceBuilder = new StringBuilder();
109 for (String line : template.getInitList()) {
110 initCodeSourceBuilder.append(line).append("\n");
111 }
112 this.initCodeSource = initCodeSourceBuilder.toString();
113
114 this.definedFunctionName = template.getReportDefined();
115 this.reportFunctionName = template.getReportCall();
116 this.reportFunctionExitName = template.getReportExit();
117 this.appNameSetter = template.getAppNameSetter();
118
119 this.declarationsToRemove = ImmutableList.copyOf(
120 template.getDeclarationToRemoveList());
121 }
122
123 @Override
124 public void process(Node externs, Node root) {
125 Node initCode = null;
126 if (!initCodeSource.isEmpty()) {
127 Node initCodeRoot = compiler.parseSyntheticCode(
128 templateFilename + ":init", initCodeSource);
129 if (initCodeRoot != null && initCodeRoot.getFirstChild() != null) {
130 initCode = initCodeRoot.removeChildren();
131 } else {
132 return; // parse failure
133 }
134 }
135
136 NodeTraversal.traverse(compiler, root,
137 new RemoveCallback(declarationsToRemove));
138 NodeTraversal.traverse(compiler, root, new InstrumentCallback());
139
140 if (!appNameSetter.isEmpty()) {
141 Node call = IR.call(
142 IR.name(appNameSetter),
143 IR.string(appNameStr));
144 call.putBooleanProp(Node.FREE_CALL, true);
145 Node expr = IR.exprResult(call);
146
147 Node addingRoot = compiler.getNodeForCodeInsertion(null);
148 addingRoot.addChildrenToFront(expr);
149 compiler.reportCodeChange();
150 }
151
152 if (initCode != null) {
153 Node addingRoot = compiler.getNodeForCodeInsertion(null);
154 addingRoot.addChildrenToFront(initCode);
155 compiler.reportCodeChange();
156 }
157 }
158
159 /**
160 * The application must refer to these variables to output them so the
161 * application must also declare these variables for the first
162 * {@link VarCheck} pass. These declarations must be removed before the
163 * second {@link VarCheck} pass. Otherwise, the second pass would warn about
164 * duplicate declarations.
165 */
166 private static class RemoveCallback extends AbstractPostOrderCallback {
167 private final List<String> removable;
168 RemoveCallback(List<String> removable) {
169 this.removable = removable;
170 }
171
172 @Override
173 public void visit(NodeTraversal t, Node n, Node parent) {
174 if (NodeUtil.isVarDeclaration(n)) {
175 if (removable.contains(n.getString())) {
176 parent.removeChild(n);
177 if (!parent.hasChildren()) {
178 parent.getParent().removeChild(parent);
179 }
180 }
181 }
182 }
183 }
184
185 /**
186 * Traverse a function's body by instrument return sites by
187 * inserting calls to {@code reportFunctionExitName}. If the
188 * function is missing an explicit return statement in some control
189 * path, this pass inserts a call to {@code reportFunctionExitName}
190 * as the last statement in the function's body.
191 *
192 * Example:
193 * Input:
194 * function f() {
195 * if (pred) {
196 * return a;
197 * }
198 * }
199 *
200 * Template:
201 * reportFunctionExitName: "onExitFn"
202 *
203 * Output:
204 * function f() {
205 * if (pred) {
206 * return onExitFn(0, a);
207 * }
208 * onExitFn(0);
209 * }
210 *
211 **/
212 private class InstrumentReturns implements NodeTraversal.Callback {
213 private final int functionId;
214 /**
215 * @param functionId Function identifier computed by FunctionNames;
216 * used as first argument to {@code reportFunctionExitName}
217 * {@code reportFunctionExitName} must be a 2 argument function that
218 * returns it's second argument.
219 */
220 InstrumentReturns(int functionId) {
221 this.functionId = functionId;
222 }
223
224 /**
225 * @param body body of function with id == this.functionId
226 */
227 void process(Node body) {
228 NodeTraversal.traverse(compiler, body, this);
229
230 if (!allPathsReturn(body)) {
231 Node call = newReportFunctionExitNode();
232 Node expr = IR.exprResult(call);
233 body.addChildToBack(expr);
234 compiler.reportCodeChange();
235 }
236 }
237
238 @Override
239 public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
240 return !n.isFunction();
241 }
242
243 @Override
244 public void visit(NodeTraversal t, Node n, Node parent) {
245 if (!n.isReturn()) {
246 return;
247 }
248
249 Node call = newReportFunctionExitNode();
250 Node returnRhs = n.removeFirstChild();
251 if (returnRhs != null) {
252 call.addChildToBack(returnRhs);
253 }
254 n.addChildToFront(call);
255 compiler.reportCodeChange();
256 }
257
258 private Node newReportFunctionExitNode() {
259 Node call = IR.call(
260 IR.name(reportFunctionExitName),
261 IR.number(functionId));
262 call.putBooleanProp(Node.FREE_CALL, true);
263 return call;
264 }
265
266 /**
267 * @returns true if all paths from block must exit with an explicit return.
268 */
269 private boolean allPathsReturn(Node block) {
270 // Computes the control flow graph.
271 ControlFlowAnalysis cfa = new ControlFlowAnalysis(
272 compiler, false, false);
273 cfa.process(null, block);
274 ControlFlowGraph<Node> cfg = cfa.getCfg();
275
276 Node returnPathsParent = cfg.getImplicitReturn().getValue();
277 for (DiGraphNode<Node, Branch> pred :
278 cfg.getDirectedPredNodes(returnPathsParent)) {
279 Node n = pred.getValue();
280 if (!n.isReturn()) {
281 return false;
282 }
283 }
284 return true;
285 }
286 }
287
288 private class InstrumentCallback extends AbstractPostOrderCallback {
289 @Override
290 public void visit(NodeTraversal t, Node n, Node parent) {
291 if (!n.isFunction()) {
292 return;
293 }
294
295 int id = functionNames.getFunctionId(n);
296 if (id < 0) {
297 // Function node was added during compilation; don't instrument.
298 return;
299 }
300
301 if (!reportFunctionName.isEmpty()) {
302 Node body = n.getFirstChild().getNext().getNext();
303 Node call = IR.call(
304 IR.name(reportFunctionName),
305 IR.number(id));
306 call.putBooleanProp(Node.FREE_CALL, true);
307 Node expr = IR.exprResult(call);
308 body.addChildToFront(expr);
309 compiler.reportCodeChange();
310 }
311
312 if (!reportFunctionExitName.isEmpty()) {
313 Node body = n.getFirstChild().getNext().getNext();
314 (new InstrumentReturns(id)).process(body);
315 }
316
317 if (!definedFunctionName.isEmpty()) {
318 Node call = IR.call(
319 IR.name(definedFunctionName),
320 IR.number(id));
321 call.putBooleanProp(Node.FREE_CALL, true);
322 Node expr = NodeUtil.newExpr(call);
323
324 Node addingRoot = null;
325 if (NodeUtil.isFunctionDeclaration(n)) {
326 JSModule module = t.getModule();
327 addingRoot = compiler.getNodeForCodeInsertion(module);
328 addingRoot.addChildToFront(expr);
329 } else {
330 Node beforeChild = n;
331 for (Node ancestor : n.getAncestors()) {
332 int type = ancestor.getType();
333 if (type == Token.BLOCK || type == Token.SCRIPT) {
334 addingRoot = ancestor;
335 break;
336 }
337 beforeChild = ancestor;
338 }
339 addingRoot.addChildBefore(expr, beforeChild);
340 }
341 compiler.reportCodeChange();
342 }
343 }
344 }
345 }