Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2011 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.CharMatcher;
20 import com.google.common.base.Preconditions;
21 import com.google.common.collect.Lists;
22 import com.google.common.collect.Maps;
23 import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
24 import com.google.javascript.rhino.IR;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.SortedMap;
32
33 /**
34 * Process goog.tweak primitives. Checks that:
35 * <ul>
36 * <li>parameters to goog.tweak.register* are literals of the correct type.
37 * <li>the parameter to goog.tweak.get* is a string literal.
38 * <li>parameters to goog.tweak.overrideDefaultValue are literals of the correct
39 * type.
40 * <li>tweak IDs passed to goog.tweak.get* and goog.tweak.overrideDefaultValue
41 * correspond to registered tweaks.
42 * <li>all calls to goog.tweak.register* and goog.tweak.overrideDefaultValue are
43 * within the top-level context.
44 * <li>each tweak is registered only once.
45 * <li>calls to goog.tweak.overrideDefaultValue occur before the call to the
46 * corresponding goog.tweak.register* function.
47 * </ul>
48 * @author [email protected] (Andrew Grieve)
49 */
50 class ProcessTweaks implements CompilerPass {
51
52 private final AbstractCompiler compiler;
53 private final boolean stripTweaks;
54 private final SortedMap<String, Node> compilerDefaultValueOverrides;
55
56 private static final CharMatcher ID_MATCHER = CharMatcher.inRange('a', 'z').
57 or(CharMatcher.inRange('A', 'Z')).or(CharMatcher.anyOf("0123456789_."));
58
59 // Warnings and Errors.
60 static final DiagnosticType UNKNOWN_TWEAK_WARNING =
61 DiagnosticType.warning(
62 "JSC_UNKNOWN_TWEAK_WARNING",
63 "no tweak registered with ID {0}");
64
65 static final DiagnosticType TWEAK_MULTIPLY_REGISTERED_ERROR =
66 DiagnosticType.error(
67 "JSC_TWEAK_MULTIPLY_REGISTERED_ERROR",
68 "Tweak {0} has already been registered.");
69
70 static final DiagnosticType NON_LITERAL_TWEAK_ID_ERROR =
71 DiagnosticType.error(
72 "JSC_NON_LITERAL_TWEAK_ID_ERROR",
73 "tweak ID must be a string literal");
74
75 static final DiagnosticType INVALID_TWEAK_DEFAULT_VALUE_WARNING =
76 DiagnosticType.warning(
77 "JSC_INVALID_TWEAK_DEFAULT_VALUE_WARNING",
78 "tweak {0} registered with {1} must have a default value that is a " +
79 "literal of type {2}");
80
81 static final DiagnosticType NON_GLOBAL_TWEAK_INIT_ERROR =
82 DiagnosticType.error(
83 "JSC_NON_GLOBAL_TWEAK_INIT_ERROR",
84 "tweak declaration {0} must occur in the global scope");
85
86 static final DiagnosticType TWEAK_OVERRIDE_AFTER_REGISTERED_ERROR =
87 DiagnosticType.error(
88 "JSC_TWEAK_OVERRIDE_AFTER_REGISTERED_ERROR",
89 "Cannot override the default value of tweak {0} after it has been " +
90 "registered");
91
92 static final DiagnosticType TWEAK_WRONG_GETTER_TYPE_WARNING =
93 DiagnosticType.warning(
94 "JSC_TWEAK_WRONG_GETTER_TYPE_WARNING",
95 "tweak getter function {0} used for tweak registered using {1}");
96
97 static final DiagnosticType INVALID_TWEAK_ID_ERROR =
98 DiagnosticType.error(
99 "JSC_INVALID_TWEAK_ID_ERROR",
100 "tweak ID contains illegal characters. Only letters, numbers, _ " +
101 "and . are allowed");
102
103 /**
104 * An enum of goog.tweak functions.
105 */
106 private static enum TweakFunction {
107 REGISTER_BOOLEAN("goog.tweak.registerBoolean", "boolean", Token.TRUE,
108 Token.FALSE),
109 REGISTER_NUMBER("goog.tweak.registerNumber", "number", Token.NUMBER),
110 REGISTER_STRING("goog.tweak.registerString", "string", Token.STRING),
111 OVERRIDE_DEFAULT_VALUE("goog.tweak.overrideDefaultValue"),
112 GET_COMPILER_OVERRIDES("goog.tweak.getCompilerOverrides_"),
113 GET_BOOLEAN("goog.tweak.getBoolean", REGISTER_BOOLEAN),
114 GET_NUMBER("goog.tweak.getNumber", REGISTER_NUMBER),
115 GET_STRING("goog.tweak.getString", REGISTER_STRING);
116
117 final String name;
118 final String expectedTypeName;
119 final int validNodeTypeA;
120 final int validNodeTypeB;
121 final TweakFunction registerFunction;
122
123 TweakFunction(String name) {
124 this(name, null, Token.ERROR, Token.ERROR, null);
125 }
126
127 TweakFunction(String name, String expectedTypeName,
128 int validNodeTypeA) {
129 this(name, expectedTypeName, validNodeTypeA, Token.ERROR, null);
130 }
131
132 TweakFunction(String name, String expectedTypeName,
133 int validNodeTypeA, int validNodeTypeB) {
134 this(name, expectedTypeName, validNodeTypeA, validNodeTypeB, null);
135 }
136
137 TweakFunction(String name, TweakFunction registerFunction) {
138 this(name, null, Token.ERROR, Token.ERROR, registerFunction);
139 }
140
141 TweakFunction(String name, String expectedTypeName,
142 int validNodeTypeA, int validNodeTypeB,
143 TweakFunction registerFunction) {
144 this.name = name;
145 this.expectedTypeName = expectedTypeName;
146 this.validNodeTypeA = validNodeTypeA;
147 this.validNodeTypeB = validNodeTypeB;
148 this.registerFunction = registerFunction;
149 }
150
151 boolean isValidNodeType(int type) {
152 return type == validNodeTypeA || type == validNodeTypeB;
153 }
154
155 boolean isCorrectRegisterFunction(TweakFunction registerFunction) {
156 Preconditions.checkNotNull(registerFunction);
157 return this.registerFunction == registerFunction;
158 }
159
160 boolean isGetterFunction() {
161 return registerFunction != null;
162 }
163
164 String getName() {
165 return name;
166 }
167
168 String getExpectedTypeName() {
169 return expectedTypeName;
170 }
171
172 Node createDefaultValueNode() {
173 switch (this) {
174 case REGISTER_BOOLEAN:
175 return IR.falseNode();
176 case REGISTER_NUMBER:
177 return IR.number(0);
178 case REGISTER_STRING:
179 return IR.string("");
180 default:
181 throw new IllegalStateException();
182 }
183 }
184 }
185
186 // A map of function name -> TweakFunction.
187 private static final Map<String, TweakFunction> TWEAK_FUNCTIONS_MAP;
188 static {
189 TWEAK_FUNCTIONS_MAP = Maps.newHashMap();
190 for (TweakFunction func : TweakFunction.values()) {
191 TWEAK_FUNCTIONS_MAP.put(func.getName(), func);
192 }
193 }
194
195 ProcessTweaks(AbstractCompiler compiler, boolean stripTweaks,
196 Map<String, Node> compilerDefaultValueOverrides) {
197 this.compiler = compiler;
198 this.stripTweaks = stripTweaks;
199 // Having the map sorted is required for the unit tests to be deterministic.
200 this.compilerDefaultValueOverrides = Maps.newTreeMap();
201 this.compilerDefaultValueOverrides.putAll(compilerDefaultValueOverrides);
202 }
203
204 @Override
205 public void process(Node externs, Node root) {
206 CollectTweaksResult result = collectTweaks(root);
207 applyCompilerDefaultValueOverrides(result.tweakInfos);
208
209 boolean changed = false;
210
211 if (stripTweaks) {
212 changed = stripAllCalls(result.tweakInfos);
213 } else if (!compilerDefaultValueOverrides.isEmpty()) {
214 changed = replaceGetCompilerOverridesCalls(result.getOverridesCalls);
215 }
216 if (changed) {
217 compiler.reportCodeChange();
218 }
219 }
220
221 /**
222 * Passes the compiler default value overrides to the JS by replacing calls
223 * to goog.tweak.getCompilerOverrids_ with a map of tweak ID->default value;
224 */
225 private boolean replaceGetCompilerOverridesCalls(
226 List<TweakFunctionCall> calls) {
227 for (TweakFunctionCall call : calls) {
228 Node callNode = call.callNode;
229 Node objNode = createCompilerDefaultValueOverridesVarNode(callNode);
230 callNode.getParent().replaceChild(callNode, objNode);
231 }
232 return !calls.isEmpty();
233 }
234
235 /**
236 * Removes all CALL nodes in the given TweakInfos, replacing calls to getter
237 * functions with the tweak's default value.
238 */
239 private boolean stripAllCalls(Map<String, TweakInfo> tweakInfos) {
240 for (TweakInfo tweakInfo : tweakInfos.values()) {
241 boolean isRegistered = tweakInfo.isRegistered();
242 for (TweakFunctionCall functionCall : tweakInfo.functionCalls) {
243 Node callNode = functionCall.callNode;
244 Node parent = callNode.getParent();
245 if (functionCall.tweakFunc.isGetterFunction()) {
246 Node newValue;
247 if (isRegistered) {
248 newValue = tweakInfo.getDefaultValueNode().cloneNode();
249 } else {
250 // When we find a getter of an unregistered tweak, there has
251 // already been a warning about it, so now just use a default
252 // value when stripping.
253 TweakFunction registerFunction =
254 functionCall.tweakFunc.registerFunction;
255 newValue = registerFunction.createDefaultValueNode();
256 }
257 parent.replaceChild(callNode, newValue);
258 } else {
259 Node voidZeroNode = IR.voidNode(IR.number(0).srcref(callNode))
260 .srcref(callNode);
261 parent.replaceChild(callNode, voidZeroNode);
262 }
263 }
264 }
265 return !tweakInfos.isEmpty();
266 }
267
268 /**
269 * Creates a JS object that holds a map of tweakId -> default value override.
270 */
271 private Node createCompilerDefaultValueOverridesVarNode(
272 Node sourceInformationNode) {
273 Node objNode = IR.objectlit().srcref(sourceInformationNode);
274 for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) {
275 Node objKeyNode = IR.stringKey(entry.getKey())
276 .copyInformationFrom(sourceInformationNode);
277 Node objValueNode = entry.getValue().cloneNode()
278 .copyInformationFrom(sourceInformationNode);
279 objKeyNode.addChildToBack(objValueNode);
280 objNode.addChildToBack(objKeyNode);
281 }
282 return objNode;
283 }
284
285 /** Sets the default values of tweaks based on compiler options. */
286 private void applyCompilerDefaultValueOverrides(
287 Map<String, TweakInfo> tweakInfos) {
288 for (Entry<String, Node> entry : compilerDefaultValueOverrides.entrySet()) {
289 String tweakId = entry.getKey();
290 TweakInfo tweakInfo = tweakInfos.get(tweakId);
291 if (tweakInfo == null) {
292 compiler.report(JSError.make(UNKNOWN_TWEAK_WARNING, tweakId));
293 } else {
294 TweakFunction registerFunc = tweakInfo.registerCall.tweakFunc;
295 Node value = entry.getValue();
296 if (!registerFunc.isValidNodeType(value.getType())) {
297 compiler.report(JSError.make(INVALID_TWEAK_DEFAULT_VALUE_WARNING,
298 tweakId, registerFunc.getName(),
299 registerFunc.getExpectedTypeName()));
300 } else {
301 tweakInfo.defaultValueNode = value;
302 }
303 }
304 }
305 }
306
307 /**
308 * Finds all calls to goog.tweak functions and emits warnings/errors if any
309 * of the calls have issues.
310 * @return A map of {@link TweakInfo} structures, keyed by tweak ID.
311 */
312 private CollectTweaksResult collectTweaks(Node root) {
313 CollectTweaks pass = new CollectTweaks();
314 NodeTraversal.traverse(compiler, root, pass);
315
316 Map<String, TweakInfo> tweakInfos = pass.allTweaks;
317 for (TweakInfo tweakInfo: tweakInfos.values()) {
318 tweakInfo.emitAllWarnings();
319 }
320 return new CollectTweaksResult(tweakInfos, pass.getOverridesCalls);
321 }
322
323 private final static class CollectTweaksResult {
324 final Map<String, TweakInfo> tweakInfos;
325 final List<TweakFunctionCall> getOverridesCalls;
326
327 CollectTweaksResult(Map<String, TweakInfo> tweakInfos,
328 List<TweakFunctionCall> getOverridesCalls) {
329 this.tweakInfos = tweakInfos;
330 this.getOverridesCalls = getOverridesCalls;
331 }
332 }
333
334 /**
335 * Processes all calls to goog.tweak functions.
336 */
337 private final class CollectTweaks extends AbstractPostOrderCallback {
338 final Map<String, TweakInfo> allTweaks = Maps.newHashMap();
339 final List<TweakFunctionCall> getOverridesCalls = Lists.newArrayList();
340
341 @SuppressWarnings("incomplete-switch")
342 @Override
343 public void visit(NodeTraversal t, Node n, Node parent) {
344 if (!n.isCall()) {
345 return;
346 }
347
348 String callName = n.getFirstChild().getQualifiedName();
349 TweakFunction tweakFunc = TWEAK_FUNCTIONS_MAP.get(callName);
350 if (tweakFunc == null) {
351 return;
352 }
353
354 if (tweakFunc == TweakFunction.GET_COMPILER_OVERRIDES) {
355 getOverridesCalls.add(
356 new TweakFunctionCall(t.getSourceName(), tweakFunc, n));
357 return;
358 }
359
360 // Ensure the first parameter (the tweak ID) is a string literal.
361 Node tweakIdNode = n.getFirstChild().getNext();
362 if (!tweakIdNode.isString()) {
363 compiler.report(t.makeError(tweakIdNode, NON_LITERAL_TWEAK_ID_ERROR));
364 return;
365 }
366 String tweakId = tweakIdNode.getString();
367
368 // Make sure there is a TweakInfo structure for it.
369 TweakInfo tweakInfo = allTweaks.get(tweakId);
370 if (tweakInfo == null) {
371 tweakInfo = new TweakInfo(tweakId);
372 allTweaks.put(tweakId, tweakInfo);
373 }
374
375 switch (tweakFunc) {
376 case REGISTER_BOOLEAN:
377 case REGISTER_NUMBER:
378 case REGISTER_STRING:
379 // Ensure the ID contains only valid characters.
380 if (!ID_MATCHER.matchesAllOf(tweakId)) {
381 compiler.report(t.makeError(tweakIdNode, INVALID_TWEAK_ID_ERROR));
382 }
383
384 // Ensure tweaks are registered in the global scope.
385 if (!t.inGlobalScope()) {
386 compiler.report(
387 t.makeError(n, NON_GLOBAL_TWEAK_INIT_ERROR, tweakId));
388 break;
389 }
390
391 // Ensure tweaks are registered only once.
392 if (tweakInfo.isRegistered()) {
393 compiler.report(
394 t.makeError(n, TWEAK_MULTIPLY_REGISTERED_ERROR, tweakId));
395 break;
396 }
397
398 Node tweakDefaultValueNode = tweakIdNode.getNext().getNext();
399 tweakInfo.addRegisterCall(t.getSourceName(), tweakFunc, n,
400 tweakDefaultValueNode);
401 break;
402 case OVERRIDE_DEFAULT_VALUE:
403 // Ensure tweaks overrides occur in the global scope.
404 if (!t.inGlobalScope()) {
405 compiler.report(
406 t.makeError(n, NON_GLOBAL_TWEAK_INIT_ERROR, tweakId));
407 break;
408 }
409 // Ensure tweak overrides occur before the tweak is registered.
410 if (tweakInfo.isRegistered()) {
411 compiler.report(
412 t.makeError(n, TWEAK_OVERRIDE_AFTER_REGISTERED_ERROR, tweakId));
413 break;
414 }
415
416 tweakDefaultValueNode = tweakIdNode.getNext();
417 tweakInfo.addOverrideDefaultValueCall(t.getSourceName(), tweakFunc, n,
418 tweakDefaultValueNode);
419 break;
420 case GET_BOOLEAN:
421 case GET_NUMBER:
422 case GET_STRING:
423 tweakInfo.addGetterCall(t.getSourceName(), tweakFunc, n);
424 }
425 }
426 }
427
428 /**
429 * Holds information about a call to a goog.tweak function.
430 */
431 private static final class TweakFunctionCall {
432 final String sourceName;
433 final TweakFunction tweakFunc;
434 final Node callNode;
435 final Node valueNode;
436
437 TweakFunctionCall(String sourceName, TweakFunction tweakFunc,
438 Node callNode) {
439 this(sourceName, tweakFunc, callNode, null);
440 }
441
442 TweakFunctionCall(String sourceName, TweakFunction tweakFunc, Node callNode,
443 Node valueNode) {
444 this.sourceName = sourceName;
445 this.callNode = callNode;
446 this.tweakFunc = tweakFunc;
447 this.valueNode = valueNode;
448 }
449
450 Node getIdNode() {
451 return callNode.getFirstChild().getNext();
452 }
453 }
454
455 /**
456 * Stores information about a single tweak.
457 */
458 private final class TweakInfo {
459 final String tweakId;
460 final List<TweakFunctionCall> functionCalls;
461 TweakFunctionCall registerCall;
462 Node defaultValueNode;
463
464 TweakInfo(String tweakId) {
465 this.tweakId = tweakId;
466 functionCalls = Lists.newArrayList();
467 }
468
469 /**
470 * If this tweak is registered, then looks for type warnings in default
471 * value parameters and getter functions. If it is not registered, emits an
472 * error for each function call.
473 */
474 void emitAllWarnings() {
475 if (isRegistered()) {
476 emitAllTypeWarnings();
477 } else {
478 emitUnknownTweakErrors();
479 }
480 }
481
482 /**
483 * Emits a warning for each default value parameter that has the wrong type
484 * and for each getter function that was used for the wrong type of tweak.
485 */
486 void emitAllTypeWarnings() {
487 for (TweakFunctionCall call : functionCalls) {
488 Node valueNode = call.valueNode;
489 TweakFunction tweakFunc = call.tweakFunc;
490 TweakFunction registerFunc = registerCall.tweakFunc;
491 if (valueNode != null) {
492 // For register* and overrideDefaultValue calls, ensure the default
493 // value is a literal of the correct type.
494 if (!registerFunc.isValidNodeType(valueNode.getType())) {
495 compiler.report(JSError.make(call.sourceName,
496 valueNode, INVALID_TWEAK_DEFAULT_VALUE_WARNING,
497 tweakId, registerFunc.getName(),
498 registerFunc.getExpectedTypeName()));
499 }
500 } else if (tweakFunc.isGetterFunction()) {
501 // For getter calls, ensure the correct getter was used.
502 if (!tweakFunc.isCorrectRegisterFunction(registerFunc)) {
503 compiler.report(JSError.make(call.sourceName,
504 call.callNode, TWEAK_WRONG_GETTER_TYPE_WARNING,
505 tweakFunc.getName(), registerFunc.getName()));
506 }
507 }
508 }
509 }
510
511 /**
512 * Emits an error for each function call that was found.
513 */
514 void emitUnknownTweakErrors() {
515 for (TweakFunctionCall call : functionCalls) {
516 compiler.report(JSError.make(call.sourceName,
517 call.getIdNode(), UNKNOWN_TWEAK_WARNING, tweakId));
518 }
519 }
520
521 void addRegisterCall(String sourceName, TweakFunction tweakFunc,
522 Node callNode, Node defaultValueNode) {
523 registerCall = new TweakFunctionCall(sourceName, tweakFunc, callNode,
524 defaultValueNode);
525 functionCalls.add(registerCall);
526 }
527
528 void addOverrideDefaultValueCall(String sourceName,
529 TweakFunction tweakFunc, Node callNode, Node defaultValueNode) {
530 functionCalls.add(new TweakFunctionCall(sourceName, tweakFunc, callNode,
531 defaultValueNode));
532 this.defaultValueNode = defaultValueNode;
533 }
534
535 void addGetterCall(String sourceName, TweakFunction tweakFunc,
536 Node callNode) {
537 functionCalls.add(new TweakFunctionCall(sourceName, tweakFunc, callNode));
538 }
539
540 boolean isRegistered() {
541 return registerCall != null;
542 }
543
544 Node getDefaultValueNode() {
545 Preconditions.checkState(isRegistered());
546 // Use calls to goog.tweak.overrideDefaultValue() first.
547 if (defaultValueNode != null) {
548 return defaultValueNode;
549 }
550 // Use the value passed to the register function next.
551 if (registerCall.valueNode != null) {
552 return registerCall.valueNode;
553 }
554 // Otherwise, use the default value for the tweak's type.
555 return registerCall.tweakFunc.createDefaultValueNode();
556 }
557 }
558 }