Debian Codegraph @

src/com/google/javascript/jscomp/RenameLabels.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
17 package com.google.javascript.jscomp;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Supplier;
21 import com.google.common.collect.Lists;
22 import com.google.javascript.jscomp.NodeTraversal.ScopedCallback;
23 import com.google.javascript.rhino.Node;
24 import com.google.javascript.rhino.Token;
25
26 import java.util.ArrayList;
27 import java.util.Deque;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Map;
31
32
33 /**
34 * RenameLabels renames all the labels so that they have short names, to reduce
35 * code size and also to obfuscate the code.
36 *
37 * Label names have a unique namespace, so variable or function names clashes
38 * are not a concern, but keywords clashes are.
39 *
40 * Additionally, labels names are only within the statements include in the
41 * label and do not cross function boundaries. This means that it is possible to
42 * create one label name that is used for labels at any given depth of label
43 * nesting. Typically, the name "a" will be used for all top-level labels, "b"
44 * for the next nested label, and so on. For example:
45 *
46 * <code>
47 * function bar() {
48 * a: {
49 * b: {
50 * foo();
51 * }
52 * }
53 *
54 * a: {
55 * b: break a;
56 * }
57 * }
58 * </code>
59 *
60 * The general processes is as follows: process() is the entry point for the
61 * CompilerPass, and from there a standard "ScopedCallback" traversal is done,
62 * where "shouldTraverse" is called when descending the tree, and the "visit" is
63 * called in a depth first manner. The name for the label is selected during the
64 * decent in "shouldTraverse", and the references to the label name are renamed
65 * as they are encountered during the "visit". This means that if the label is
66 * unreferenced, it is known when the label node is visited, and, if so, can be
67 * safely removed.
68 *
69 * @author [email protected] (John Lenz)
70 */
71 final class RenameLabels implements CompilerPass {
72 private final AbstractCompiler compiler;
73 private final Supplier<String> nameSupplier;
74 private final boolean removeUnused;
75
76 RenameLabels(AbstractCompiler compiler) {
77 this(compiler, new DefaultNameSupplier(), true);
78 }
79
80 RenameLabels(
81 AbstractCompiler compiler,
82 Supplier<String> supplier,
83 boolean removeUnused) {
84 this.compiler = compiler;
85 this.nameSupplier = supplier;
86 this.removeUnused = removeUnused;
87 }
88
89 static class DefaultNameSupplier implements Supplier<String> {
90 // NameGenerator is used to create safe label names.
91 final NameGenerator nameGenerator =
92 new NameGenerator(new HashSet<String>(), "", null);
93
94 @Override
95 public String get() {
96 return nameGenerator.generateNextName();
97 }
98 }
99
100 /**
101 * Iterate through the nodes, renaming all the labels.
102 */
103 class ProcessLabels implements ScopedCallback {
104
105 ProcessLabels() {
106 // Create a entry for global scope.
107 namespaceStack.push(new LabelNamespace());
108 }
109
110 // A stack of labels namespaces. Labels in an outer scope aren't part of an
111 // inner scope, so a new namespace is created each time a scope is entered.
112 final Deque<LabelNamespace> namespaceStack = Lists.newLinkedList();
113
114 // The list of generated names. Typically, the first name will be "a",
115 // the second "b", etc.
116 final ArrayList<String> names = new ArrayList<String>();
117
118
119 @Override
120 public void enterScope(NodeTraversal nodeTraversal) {
121 // Start a new namespace for label names.
122 namespaceStack.push(new LabelNamespace());
123 }
124
125 @Override
126 public void exitScope(NodeTraversal nodeTraversal) {
127 namespaceStack.pop();
128 }
129
130 /**
131 * shouldTraverse is call when descending into the Node tree, so it is used
132 * here to build the context for label renames.
133 *
134 * {@inheritDoc}
135 */
136 @Override
137 public boolean shouldTraverse(NodeTraversal nodeTraversal, Node node,
138 Node parent) {
139 if (node.isLabel()) {
140 // Determine the new name for this label.
141 LabelNamespace current = namespaceStack.peek();
142 int currentDepth = current.renameMap.size() + 1;
143 String name = node.getFirstChild().getString();
144
145 // Store the context for this label name.
146 LabelInfo li = new LabelInfo(currentDepth);
147 Preconditions.checkState(!current.renameMap.containsKey(name));
148 current.renameMap.put(name, li);
149
150 // Create a new name, if needed, for this depth.
151 if (names.size() < currentDepth) {
152 names.add(nameSupplier.get());
153 }
154
155 String newName = getNameForId(currentDepth);
156 compiler.addToDebugLog("label renamed: " + name + " => " + newName);
157 }
158
159 return true;
160 }
161
162 /**
163 * Delegate the actual processing of the node to visitLabel and
164 * visitBreakOrContinue.
165 *
166 * {@inheritDoc}
167 */
168 @Override
169 public void visit(NodeTraversal nodeTraversal, Node node, Node parent) {
170 switch (node.getType()) {
171 case Token.LABEL:
172 visitLabel(node, parent);
173 break;
174
175 case Token.BREAK:
176 case Token.CONTINUE:
177 visitBreakOrContinue(node);
178 break;
179 }
180 }
181
182 /**
183 * Rename label references in breaks and continues.
184 * @param node The break or continue node.
185 */
186 private void visitBreakOrContinue(Node node) {
187 Node nameNode = node.getFirstChild();
188 if (nameNode != null) {
189 // This is a named break or continue;
190 String name = nameNode.getString();
191 Preconditions.checkState(name.length() != 0);
192 LabelInfo li = getLabelInfo(name);
193 if (li != null) {
194 String newName = getNameForId(li.id);
195 // Mark the label as referenced so it isn't removed.
196 li.referenced = true;
197 if (!name.equals(newName)) {
198 // Give it the short name.
199 nameNode.setString(newName);
200 compiler.reportCodeChange();
201 }
202 }
203 }
204 }
205
206 /**
207 * Rename or remove labels.
208 * @param node The label node.
209 * @param parent The parent of the label node.
210 */
211 private void visitLabel(Node node, Node parent) {
212 Node nameNode = node.getFirstChild();
213 Preconditions.checkState(nameNode != null);
214 String name = nameNode.getString();
215 LabelInfo li = getLabelInfo(name);
216 // This is a label...
217 if (li.referenced || !removeUnused) {
218 String newName = getNameForId(li.id);
219 if (!name.equals(newName)) {
220 // ... and it is used, give it the short name.
221 nameNode.setString(newName);
222 compiler.reportCodeChange();
223 }
224 } else {
225 // ... and it is not referenced, just remove it.
226 Node newChild = node.getLastChild();
227 node.removeChild(newChild);
228 parent.replaceChild(node, newChild);
229 if (newChild.isBlock()) {
230 NodeUtil.tryMergeBlock(newChild);
231 }
232 compiler.reportCodeChange();
233 }
234
235 // Remove the label from the current stack of labels.
236 namespaceStack.peek().renameMap.remove(name);
237 }
238
239 /**
240 * @param id The id, which is the depth of the label in the current context,
241 * for which to get a short name.
242 * @return The short name of the identified label.
243 */
244 String getNameForId(int id) {
245 return names.get(id - 1);
246 }
247
248 /**
249 * @param name The name to retrieve information about.
250 * @return The structure representing the name in the current context.
251 */
252 LabelInfo getLabelInfo(String name) {
253 return namespaceStack.peek().renameMap.get(name);
254 }
255 }
256
257 @Override
258 public void process(Node externs, Node root) {
259 // Do variable reference counting.
260 NodeTraversal.traverse(compiler, root, new ProcessLabels());
261 }
262
263
264 private static class LabelInfo {
265 boolean referenced = false;
266 final int id;
267
268 LabelInfo(int id) {
269 this.id = id;
270 }
271 }
272
273
274 private static class LabelNamespace {
275 final Map<String, LabelInfo> renameMap = new HashMap<String, LabelInfo>();
276 }
277
278 }