Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2007 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.Preconditions;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.javascript.jscomp.GlobalNamespace.Name;
24 import com.google.javascript.jscomp.GlobalNamespace.Ref;
25 import com.google.javascript.jscomp.NodeTraversal.Callback;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.JSTypeExpression;
28 import com.google.javascript.rhino.Node;
29 import com.google.javascript.rhino.Token;
30 import com.google.javascript.rhino.jstype.JSType;
31 import com.google.javascript.rhino.jstype.JSTypeNative;
32
33 import java.text.MessageFormat;
34 import java.util.ArrayDeque;
35 import java.util.Deque;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Set;
39
40 /**
41 * Process variables annotated as {@code @define}. A define is
42 * a special constant that may be overridden by later files and
43 * manipulated by the compiler, much like C preprocessor {@code #define}s.
44 *
45 * @author [email protected] (Nick Santos)
46 */
47 class ProcessDefines implements CompilerPass {
48
49 /**
50 * Defines in this set will not be flagged with "unknown define" warnings.
51 * There are legacy flags that always set these defines, even when they
52 * might not be in the binary.
53 */
54 private static final Set<String> KNOWN_DEFINES =
55 Sets.newHashSet("COMPILED");
56
57 private final AbstractCompiler compiler;
58 private final Map<String, Node> dominantReplacements;
59
60 private GlobalNamespace namespace = null;
61
62 // Warnings
63 static final DiagnosticType UNKNOWN_DEFINE_WARNING = DiagnosticType.warning(
64 "JSC_UNKNOWN_DEFINE_WARNING",
65 "unknown @define variable {0}");
66
67 // Errors
68 static final DiagnosticType INVALID_DEFINE_TYPE_ERROR =
69 DiagnosticType.error(
70 "JSC_INVALID_DEFINE_TYPE_ERROR",
71 "@define tag only permits literal types");
72
73 static final DiagnosticType INVALID_DEFINE_INIT_ERROR =
74 DiagnosticType.error(
75 "JSC_INVALID_DEFINE_INIT_ERROR",
76 "illegal initialization of @define variable {0}");
77
78 static final DiagnosticType NON_GLOBAL_DEFINE_INIT_ERROR =
79 DiagnosticType.error(
80 "JSC_NON_GLOBAL_DEFINE_INIT_ERROR",
81 "@define variable {0} assignment must be global");
82
83 static final DiagnosticType DEFINE_NOT_ASSIGNABLE_ERROR =
84 DiagnosticType.error(
85 "JSC_DEFINE_NOT_ASSIGNABLE_ERROR",
86 "@define variable {0} cannot be reassigned due to code at {1}.");
87
88 private static final MessageFormat REASON_DEFINE_NOT_ASSIGNABLE =
89 new MessageFormat("line {0} of {1}");
90
91 /**
92 * Create a pass that overrides define constants.
93 *
94 * TODO(nicksantos): Write a builder to help JSCompiler induce
95 * {@code replacements} from command-line flags
96 *
97 * @param replacements A hash table of names of defines to their replacements.
98 * All replacements <b>must</b> be literals.
99 */
100 ProcessDefines(AbstractCompiler compiler, Map<String, Node> replacements) {
101 this.compiler = compiler;
102 dominantReplacements = replacements;
103 }
104
105 /**
106 * Injects a pre-computed global namespace, so that the same namespace
107 * can be re-used for multiple check passes. Returns {@code this} for
108 * easy chaining.
109 */
110 ProcessDefines injectNamespace(GlobalNamespace namespace) {
111 this.namespace = namespace;
112 return this;
113 }
114
115 @Override
116 public void process(Node externs, Node root) {
117 if (namespace == null) {
118 namespace = new GlobalNamespace(compiler, root);
119 }
120 overrideDefines(collectDefines(root, namespace));
121 }
122
123 private void overrideDefines(Map<String, DefineInfo> allDefines) {
124 boolean changed = false;
125 for (Map.Entry<String, DefineInfo> def : allDefines.entrySet()) {
126 String defineName = def.getKey();
127 DefineInfo info = def.getValue();
128 Node inputValue = dominantReplacements.get(defineName);
129 Node finalValue = inputValue != null ?
130 inputValue : info.getLastValue();
131 if (finalValue != info.initialValue) {
132 info.initialValueParent.replaceChild(
133 info.initialValue, finalValue.cloneTree());
134 compiler.addToDebugLog("Overriding @define variable " + defineName);
135 changed = changed ||
136 finalValue.getType() != info.initialValue.getType() ||
137 !finalValue.isEquivalentTo(info.initialValue);
138 }
139 }
140
141 if (changed) {
142 compiler.reportCodeChange();
143 }
144
145 Set<String> unusedReplacements = dominantReplacements.keySet();
146 unusedReplacements.removeAll(allDefines.keySet());
147 unusedReplacements.removeAll(KNOWN_DEFINES);
148 for (String unknownDefine : unusedReplacements) {
149 compiler.report(JSError.make(UNKNOWN_DEFINE_WARNING, unknownDefine));
150 }
151 }
152
153 private static String format(MessageFormat format, Object... params) {
154 return format.format(params);
155 }
156
157 /**
158 * Only defines of literal number, string, or boolean are supported.
159 */
160 private boolean isValidDefineType(JSTypeExpression expression) {
161 JSType type = expression.evaluate(null, compiler.getTypeRegistry());
162 return !type.isUnknownType() && type.isSubtype(
163 compiler.getTypeRegistry().getNativeType(
164 JSTypeNative.NUMBER_STRING_BOOLEAN));
165 }
166
167 /**
168 * Finds all defines, and creates a {@link DefineInfo} data structure for
169 * each one.
170 * @return A map of {@link DefineInfo} structures, keyed by name.
171 */
172 private Map<String, DefineInfo> collectDefines(Node root,
173 GlobalNamespace namespace) {
174 // Find all the global names with a @define annotation
175 List<Name> allDefines = Lists.newArrayList();
176 for (Name name : namespace.getNameIndex().values()) {
177 Ref decl = name.getDeclaration();
178 if (name.docInfo != null && name.docInfo.isDefine()) {
179 // Process defines should not depend on check types being enabled,
180 // so we look for the JSDoc instead of the inferred type.
181 if (isValidDefineType(name.docInfo.getType())) {
182 allDefines.add(name);
183 } else {
184 JSError error = JSError.make(
185 decl.getSourceName(),
186 decl.node, INVALID_DEFINE_TYPE_ERROR);
187 compiler.report(error);
188 }
189 } else {
190 for (Ref ref : name.getRefs()) {
191 if (ref == decl) {
192 // Declarations were handled above.
193 continue;
194 }
195
196 Node n = ref.node;
197 Node parent = ref.node.getParent();
198 JSDocInfo info = n.getJSDocInfo();
199 if (info == null &&
200 parent.isVar() && parent.hasOneChild()) {
201 info = parent.getJSDocInfo();
202 }
203
204 if (info != null && info.isDefine()) {
205 allDefines.add(name);
206 break;
207 }
208 }
209 }
210 }
211
212 CollectDefines pass = new CollectDefines(compiler, allDefines);
213 NodeTraversal.traverse(compiler, root, pass);
214 return pass.getAllDefines();
215 }
216
217 /**
218 * Finds all assignments to @defines, and figures out the last value of
219 * the @define.
220 */
221 private static final class CollectDefines implements Callback {
222
223 private final AbstractCompiler compiler;
224 private final Map<String, DefineInfo> assignableDefines;
225 private final Map<String, DefineInfo> allDefines;
226 private final Map<Node, RefInfo> allRefInfo;
227
228 // A hack that allows us to remove ASSIGN/VAR statements when
229 // we're currently visiting one of the children of the assign.
230 private Node lvalueToRemoveLater = null;
231
232 // A stack tied to the node traversal, to keep track of whether
233 // we're in a conditional block. If 1 is at the top, assignment to
234 // a define is allowed. Otherwise, it's not allowed.
235 private final Deque<Integer> assignAllowed;
236
237 CollectDefines(AbstractCompiler compiler, List<Name> listOfDefines) {
238 this.compiler = compiler;
239 this.allDefines = Maps.newHashMap();
240
241 assignableDefines = Maps.newHashMap();
242 assignAllowed = new ArrayDeque<Integer>();
243 assignAllowed.push(1);
244
245 // Create a map of references to defines keyed by node for easy lookup
246 allRefInfo = Maps.newHashMap();
247 for (Name name : listOfDefines) {
248 Ref decl = name.getDeclaration();
249 if (decl != null) {
250 allRefInfo.put(decl.node,
251 new RefInfo(decl, name));
252 }
253 for (Ref ref : name.getRefs()) {
254 if (ref == decl) {
255 // Declarations were handled above.
256 continue;
257 }
258
259 // If there's a TWIN def, only put one of the twins in.
260 if (ref.getTwin() == null || !ref.getTwin().isSet()) {
261 allRefInfo.put(ref.node, new RefInfo(ref, name));
262 }
263 }
264 }
265 }
266
267 /**
268 * Get a map of {@link DefineInfo} structures, keyed by the name of
269 * the define.
270 */
271 Map<String, DefineInfo> getAllDefines() {
272 return allDefines;
273 }
274
275 /**
276 * Keeps track of whether the traversal is in a conditional branch.
277 * We traverse all nodes of the parse tree.
278 */
279 @Override
280 public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n,
281 Node parent) {
282 updateAssignAllowedStack(n, true);
283 return true;
284 }
285
286 @Override
287 public void visit(NodeTraversal t, Node n, Node parent) {
288 RefInfo refInfo = allRefInfo.get(n);
289 if (refInfo != null) {
290 Ref ref = refInfo.ref;
291 Name name = refInfo.name;
292 String fullName = name.getFullName();
293 switch (ref.type) {
294 case SET_FROM_GLOBAL:
295 case SET_FROM_LOCAL:
296 Node valParent = getValueParent(ref);
297 Node val = valParent.getLastChild();
298 if (valParent.isAssign() && name.isSimpleName() &&
299 name.getDeclaration() == ref) {
300 // For defines, it's an error if a simple name is assigned
301 // before it's declared
302 compiler.report(
303 t.makeError(val, INVALID_DEFINE_INIT_ERROR, fullName));
304 } else if (processDefineAssignment(t, fullName, val, valParent)) {
305 // remove the assignment so that the variable is still declared,
306 // but no longer assigned to a value, e.g.,
307 // DEF_FOO = 5; // becomes "5;"
308
309 // We can't remove the ASSIGN/VAR when we're still visiting its
310 // children, so we'll have to come back later to remove it.
311 refInfo.name.removeRef(ref);
312 lvalueToRemoveLater = valParent;
313 }
314 break;
315 default:
316 if (t.inGlobalScope()) {
317 // Treat this as a reference to a define in the global scope.
318 // After this point, the define must not be reassigned,
319 // or it's an error.
320 DefineInfo info = assignableDefines.get(fullName);
321 if (info != null) {
322 setDefineInfoNotAssignable(info, t);
323 assignableDefines.remove(fullName);
324 }
325 }
326 break;
327 }
328 }
329
330 if (!t.inGlobalScope() &&
331 n.getJSDocInfo() != null && n.getJSDocInfo().isDefine()) {
332 // warn about @define annotations in local scopes
333 compiler.report(
334 t.makeError(n, NON_GLOBAL_DEFINE_INIT_ERROR, ""));
335 }
336
337 if (lvalueToRemoveLater == n) {
338 lvalueToRemoveLater = null;
339 if (n.isAssign()) {
340 Node last = n.getLastChild();
341 n.removeChild(last);
342 parent.replaceChild(n, last);
343 } else {
344 Preconditions.checkState(n.isName());
345 n.removeChild(n.getFirstChild());
346 }
347 compiler.reportCodeChange();
348 }
349
350 if (n.isCall()) {
351 if (t.inGlobalScope()) {
352 // If there's a function call in the global scope,
353 // we just say it's unsafe and freeze all the defines.
354 //
355 // NOTE(nicksantos): We could be a lot smarter here. For example,
356 // ReplaceOverriddenVars keeps a call graph of all functions and
357 // which functions/variables that they reference, and tries
358 // to statically determine which functions are "safe" and which
359 // are not. But this would be overkill, especially because
360 // the intended use of defines is with config_files, where
361 // all the defines are at the top of the bundle.
362 for (DefineInfo info : assignableDefines.values()) {
363 setDefineInfoNotAssignable(info, t);
364 }
365
366 assignableDefines.clear();
367 }
368 }
369
370 updateAssignAllowedStack(n, false);
371 }
372
373 /**
374 * Determines whether assignment to a define should be allowed
375 * in the subtree of the given node, and if not, records that fact.
376 *
377 * @param n The node whose subtree we're about to enter or exit.
378 * @param entering True if we're entering the subtree, false otherwise.
379 */
380 private void updateAssignAllowedStack(Node n, boolean entering) {
381 switch (n.getType()) {
382 case Token.CASE:
383 case Token.FOR:
384 case Token.FUNCTION:
385 case Token.HOOK:
386 case Token.IF:
387 case Token.SWITCH:
388 case Token.WHILE:
389 if (entering) {
390 assignAllowed.push(0);
391 } else {
392 assignAllowed.remove();
393 }
394 break;
395 }
396 }
397
398 /**
399 * Determines whether assignment to a define should be allowed
400 * at the current point of the traversal.
401 */
402 private boolean isAssignAllowed() {
403 return assignAllowed.element() == 1;
404 }
405
406 /**
407 * Tracks the given define.
408 *
409 * @param t The current traversal, for context.
410 * @param name The full name for this define.
411 * @param value The value assigned to the define.
412 * @param valueParent The parent node of value.
413 * @return Whether we should remove this assignment from the parse tree.
414 */
415 private boolean processDefineAssignment(NodeTraversal t,
416 String name, Node value, Node valueParent) {
417 if (value == null || !NodeUtil.isValidDefineValue(value,
418 allDefines.keySet())) {
419 compiler.report(
420 t.makeError(value, INVALID_DEFINE_INIT_ERROR, name));
421 } else if (!isAssignAllowed()) {
422 compiler.report(
423 t.makeError(valueParent, NON_GLOBAL_DEFINE_INIT_ERROR, name));
424 } else {
425 DefineInfo info = allDefines.get(name);
426 if (info == null) {
427 // First declaration of this define.
428 info = new DefineInfo(value, valueParent);
429 allDefines.put(name, info);
430 assignableDefines.put(name, info);
431 } else if (info.recordAssignment(value)) {
432 // The define was already initialized, but this is a safe
433 // re-assignment.
434 return true;
435 } else {
436 // The define was already initialized, and this is an unsafe
437 // re-assignment.
438 compiler.report(
439 t.makeError(valueParent, DEFINE_NOT_ASSIGNABLE_ERROR,
440 name, info.getReasonWhyNotAssignable()));
441 }
442 }
443
444 return false;
445 }
446
447 /**
448 * Gets the parent node of the value for any assignment to a Name.
449 * For example, in the assignment
450 * {@code var x = 3;}
451 * the parent would be the NAME node.
452 */
453 private static Node getValueParent(Ref ref) {
454 // there are two types of declarations: VARs and ASSIGNs
455 return ref.node.getParent() != null &&
456 ref.node.getParent().isVar() ?
457 ref.node : ref.node.getParent();
458 }
459
460 /**
461 * Records the fact that because of the current node in the node traversal,
462 * the define can't ever be assigned again.
463 *
464 * @param info Represents the define variable.
465 * @param t The current traversal.
466 */
467 private void setDefineInfoNotAssignable(DefineInfo info, NodeTraversal t) {
468 info.setNotAssignable(format(REASON_DEFINE_NOT_ASSIGNABLE,
469 t.getLineNumber(), t.getSourceName()));
470 }
471
472 /**
473 * A simple data structure for associating a Ref with the name
474 * that it references.
475 */
476 private static class RefInfo {
477 final Ref ref;
478 final Name name;
479
480 RefInfo(Ref ref, Name name) {
481 this.ref = ref;
482 this.name = name;
483 }
484 }
485 }
486
487 /**
488 * A simple class for storing information about a define.
489 * Gathers the initial value, the last assigned value, and whether
490 * the define can be safely assigned a new value.
491 */
492 private static final class DefineInfo {
493 public final Node initialValueParent;
494 public final Node initialValue;
495 private Node lastValue;
496 private boolean isAssignable;
497 private String reasonNotAssignable;
498
499 /**
500 * Initializes a define.
501 */
502 public DefineInfo(Node initialValue, Node initialValueParent) {
503 this.initialValueParent = initialValueParent;
504 this.initialValue = initialValue;
505 lastValue = initialValue;
506 isAssignable = true;
507 }
508
509 /**
510 * Records the fact that this define can't be assigned a value anymore.
511 *
512 * @param reason A message describing the reason why it can't be assigned.
513 */
514 public void setNotAssignable(String reason) {
515 isAssignable = false;
516 reasonNotAssignable = reason;
517 }
518
519 /**
520 * Gets the reason why a define is not assignable.
521 */
522 public String getReasonWhyNotAssignable() {
523 return reasonNotAssignable;
524 }
525
526 /**
527 * Records an assigned value.
528 *
529 * @return False if there was an error.
530 */
531 public boolean recordAssignment(Node value) {
532 lastValue = value;
533 return isAssignable;
534 }
535
536 /**
537 * Gets the last assigned value.
538 */
539 public Node getLastValue() {
540 return lastValue;
541 }
542 }
543 }