Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2009 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 static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
20
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Joiner;
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 import com.google.javascript.rhino.jstype.JSType;
28
29 import java.util.Map;
30 import java.util.Set;
31
32 import javax.annotation.Nullable;
33
34 /**
35 * ReplaceCssNames replaces occurrences of goog.getCssName('foo') with
36 * a shorter version from the passed in renaming map. There are two
37 * styles of operation: for 'BY_WHOLE' we look up the whole string in the
38 * renaming map. For 'BY_PART', all the class name's components,
39 * separated by '-', are renamed individually and then recombined.
40 *
41 * Given the renaming map:
42 * {
43 * once: 'a',
44 * upon: 'b',
45 * atime: 'c',
46 * long: 'd',
47 * time: 'e',
48 * ago: 'f'
49 * }
50 *
51 * The following outputs are expected with the 'BY_PART' renaming style:
52 *
53 * goog.getCssName('once') -> 'a'
54 * goog.getCssName('once-upon-atime') -> 'a-b-c'
55 *
56 * var baseClass = goog.getCssName('long-time');
57 * el.className = goog.getCssName(baseClass, 'ago');
58 * ->
59 * var baseClass = 'd-e';
60 * el.className = baseClass + '-f';
61 *
62 * However if we have the following renaming map with the 'BY_WHOLE' renaming style:
63 * {
64 * once: 'a',
65 * upon-atime: 'b',
66 * long-time: 'c',
67 * ago: 'd'
68 * }
69 *
70 * Then we would expect:
71 *
72 * goog.getCssName('once') -> 'a'
73 *
74 * var baseClass = goog.getCssName('long-time');
75 * el.className = goog.getCssName(baseClass, 'ago');
76 * ->
77 * var baseClass = 'c';
78 * el.className = baseClass + '-d';
79 *
80 * In addition, the CSS names before replacement can optionally be gathered.
81 *
82 */
83 class ReplaceCssNames implements CompilerPass {
84
85 static final String GET_CSS_NAME_FUNCTION = "goog.getCssName";
86
87 static final DiagnosticType INVALID_NUM_ARGUMENTS_ERROR =
88 DiagnosticType.error("JSC_GETCSSNAME_NUM_ARGS",
89 "goog.getCssName called with \"{0}\" arguments, expected 1 or 2.");
90
91 static final DiagnosticType STRING_LITERAL_EXPECTED_ERROR =
92 DiagnosticType.error("JSC_GETCSSNAME_STRING_LITERAL_EXPECTED",
93 "goog.getCssName called with invalid argument, string literal " +
94 "expected. Was \"{0}\".");
95
96 static final DiagnosticType UNEXPECTED_STRING_LITERAL_ERROR =
97 DiagnosticType.error("JSC_GETCSSNAME_UNEXPECTED_STRING_LITERAL",
98 "goog.getCssName called with invalid arguments, string literal " +
99 "passed as first of two arguments. Did you mean " +
100 "goog.getCssName(\"{0}-{1}\")?");
101
102 static final DiagnosticType UNKNOWN_SYMBOL_WARNING =
103 DiagnosticType.warning("JSC_GETCSSNAME_UNKNOWN_CSS_SYMBOL",
104 "goog.getCssName called with unrecognized symbol \"{0}\" in class " +
105 "\"{1}\".");
106
107
108 private final AbstractCompiler compiler;
109
110 private final Map<String, Integer> cssNames;
111
112 private CssRenamingMap symbolMap;
113
114 private final Set<String> whitelist;
115
116 private final JSType nativeStringType;
117
118 ReplaceCssNames(AbstractCompiler compiler,
119 @Nullable Map<String, Integer> cssNames,
120 @Nullable Set<String> whitelist) {
121 this.compiler = compiler;
122 this.cssNames = cssNames;
123 this.whitelist = whitelist;
124 this.nativeStringType = compiler.getTypeRegistry()
125 .getNativeType(STRING_TYPE);
126 }
127
128 @Override
129 public void process(Node externs, Node root) {
130 // The CssRenamingMap may not have been available from the compiler when
131 // this ReplaceCssNames pass was constructed, so getCssRenamingMap() should
132 // only be called before this pass is actually run.
133 symbolMap = getCssRenamingMap();
134
135 NodeTraversal.traverse(compiler, root, new Traversal());
136 }
137
138 @VisibleForTesting
139 protected CssRenamingMap getCssRenamingMap() {
140 return compiler.getCssRenamingMap();
141 }
142
143 private class Traversal extends AbstractPostOrderCallback {
144
145 @Override
146 public void visit(NodeTraversal t, Node n, Node parent) {
147 if (n.isCall() &&
148 GET_CSS_NAME_FUNCTION.equals(n.getFirstChild().getQualifiedName())) {
149 int count = n.getChildCount();
150 Node first = n.getFirstChild().getNext();
151 switch (count) {
152 case 2:
153 // Replace the function call with the processed argument.
154 if (first.isString()) {
155 processStringNode(t, first);
156 n.removeChild(first);
157 parent.replaceChild(n, first);
158 compiler.reportCodeChange();
159 } else {
160 compiler.report(t.makeError(n, STRING_LITERAL_EXPECTED_ERROR,
161 Token.name(first.getType())));
162 }
163 break;
164
165 case 3:
166 // Replace function call with concatenation of two args. It's
167 // assumed the first arg has already been processed.
168
169 Node second = first.getNext();
170
171 if (!second.isString()) {
172 compiler.report(t.makeError(n, STRING_LITERAL_EXPECTED_ERROR,
173 Token.name(second.getType())));
174 } else if (first.isString()) {
175 compiler.report(t.makeError(
176 n, UNEXPECTED_STRING_LITERAL_ERROR,
177 first.getString(), second.getString()));
178 } else {
179 processStringNode(t, second);
180 n.removeChild(first);
181 Node replacement = IR.add(first,
182 IR.string("-" + second.getString())
183 .copyInformationFrom(second))
184 .copyInformationFrom(n);
185 replacement.setJSType(nativeStringType);
186 parent.replaceChild(n, replacement);
187 compiler.reportCodeChange();
188 }
189 break;
190
191 default:
192 compiler.report(t.makeError(
193 n, INVALID_NUM_ARGUMENTS_ERROR, String.valueOf(count)));
194 }
195 }
196 }
197
198 /**
199 * Processes a string argument to goog.getCssName(). The string will be
200 * renamed based off the symbol map. If there is no map or any part of the
201 * name can't be renamed, a warning is reported to the compiler and the node
202 * is left unchanged.
203 *
204 * If the type is unexpected then an error is reported to the compiler.
205 *
206 * @param t The node traversal.
207 * @param n The string node to process.
208 */
209 private void processStringNode(NodeTraversal t, Node n) {
210 String name = n.getString();
211 if (whitelist != null && whitelist.contains(name)) {
212 // We apply the whitelist before splitting on dashes, and not after.
213 // External substitution maps should do the same.
214 return;
215 }
216 String[] parts = name.split("-");
217 if (symbolMap != null) {
218 String replacement = null;
219 switch (symbolMap.getStyle()) {
220 case BY_WHOLE:
221 replacement = symbolMap.get(name);
222 if (replacement == null) {
223 compiler.report(
224 t.makeError(n, UNKNOWN_SYMBOL_WARNING, name, name));
225 return;
226 }
227 break;
228 case BY_PART:
229 String[] replaced = new String[parts.length];
230 for (int i = 0; i < parts.length; i++) {
231 String part = symbolMap.get(parts[i]);
232 if (part == null) {
233 // If we can't encode all parts, don't encode any of it.
234 compiler.report(
235 t.makeError(n, UNKNOWN_SYMBOL_WARNING, parts[i], name));
236 return;
237 }
238 replaced[i] = part;
239 }
240 replacement = Joiner.on("-").join(replaced);
241 break;
242 default:
243 throw new IllegalStateException(
244 "Unknown replacement style: " + symbolMap.getStyle());
245 }
246 n.setString(replacement);
247 }
248 if (cssNames != null) {
249 // We still want to collect statistics even if we've already
250 // done the full replace. The statistics are collected on a
251 // per-part basis.
252 for (int i = 0; i < parts.length; i++) {
253 Integer count = cssNames.get(parts[i]);
254 if (count == null) {
255 count = Integer.valueOf(0);
256 }
257 cssNames.put(parts[i], count.intValue() + 1);
258 }
259 }
260 }
261 }
262
263 }