Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright 2004 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.javascript.rhino.IR;
20 import com.google.javascript.rhino.Node;
21 import com.google.javascript.rhino.Token;
22
23 import java.util.Iterator;
24
25 import javax.annotation.Nullable;
26
27 /**
28 * ReplaceMessages replaces user-visible messages with alternatives.
29 * It uses Google specific JsMessageVisitor implementation.
30 *
31 */
32 class ReplaceMessages extends JsMessageVisitor {
33 private final MessageBundle bundle;
34 private final boolean strictReplacement;
35
36 static final DiagnosticType BUNDLE_DOES_NOT_HAVE_THE_MESSAGE =
37 DiagnosticType.error("JSC_BUNDLE_DOES_NOT_HAVE_THE_MESSAGE",
38 "Message with id = {0} could not be found in replacement bundle");
39
40 ReplaceMessages(AbstractCompiler compiler, MessageBundle bundle,
41 boolean checkDuplicatedMessages, JsMessage.Style style,
42 boolean strictReplacement) {
43
44 super(compiler, checkDuplicatedMessages, style, bundle.idGenerator());
45
46 this.bundle = bundle;
47 this.strictReplacement = strictReplacement;
48 }
49
50 @Override
51 void processMessageFallback(
52 Node callNode, JsMessage message1, JsMessage message2) {
53 boolean isFirstMessageTranslated =
54 (bundle.getMessage(message1.getId()) != null);
55 boolean isSecondMessageTranslated =
56 (bundle.getMessage(message2.getId()) != null);
57 Node replacementNode =
58 isSecondMessageTranslated && !isFirstMessageTranslated ?
59 callNode.getChildAtIndex(2) : callNode.getChildAtIndex(1);
60 callNode.getParent().replaceChild(callNode,
61 replacementNode.detachFromParent());
62 }
63
64 @Override
65 void processJsMessage(JsMessage message,
66 JsMessageDefinition definition) {
67
68 // Get the replacement.
69 JsMessage replacement = bundle.getMessage(message.getId());
70 if (replacement == null) {
71 if (strictReplacement) {
72 compiler.report(JSError.make(message.getSourceName(),
73 definition.getMessageNode(), BUNDLE_DOES_NOT_HAVE_THE_MESSAGE,
74 message.getId()));
75 // Fallback to the default message
76 return;
77 } else {
78 // In case if it is not a strict replacement we could leave original
79 // message.
80 replacement = message;
81 }
82 }
83
84 // Replace the message.
85 Node newValue;
86 Node msgNode = definition.getMessageNode();
87 try {
88 newValue = getNewValueNode(replacement, msgNode);
89 } catch (MalformedException e) {
90 compiler.report(JSError.make(message.getSourceName(),
91 e.getNode(), MESSAGE_TREE_MALFORMED, e.getMessage()));
92 newValue = msgNode;
93 }
94
95 if (newValue != msgNode) {
96 newValue.copyInformationFromForTree(msgNode);
97 definition.getMessageParentNode().replaceChild(msgNode, newValue);
98 compiler.reportCodeChange();
99 }
100 }
101
102 /**
103 * Constructs a node representing a message's value, or, if possible, just
104 * modifies {@code origValueNode} so that it accurately represents the
105 * message's value.
106 *
107 * @param message a message
108 * @param origValueNode the message's original value node
109 * @return a Node that can replace {@code origValueNode}
110 *
111 * @throws MalformedException if the passed node's subtree structure is
112 * not as expected
113 */
114 private Node getNewValueNode(JsMessage message, Node origValueNode)
115 throws MalformedException {
116 switch (origValueNode.getType()) {
117 case Token.FUNCTION:
118 // The message is a function. Modify the function node.
119 updateFunctionNode(message, origValueNode);
120 return origValueNode;
121 case Token.STRING:
122 // The message is a simple string. Modify the string node.
123 String newString = message.toString();
124 if (!origValueNode.getString().equals(newString)) {
125 origValueNode.setString(newString);
126 compiler.reportCodeChange();
127 }
128 return origValueNode;
129 case Token.ADD:
130 // The message is a simple string. Create a string node.
131 return IR.string(message.toString());
132 case Token.CALL:
133 // The message is a function call. Replace it with a string expression.
134 return replaceCallNode(message, origValueNode);
135 default:
136 throw new MalformedException(
137 "Expected FUNCTION, STRING, or ADD node; found: " +
138 origValueNode.getType(), origValueNode);
139 }
140 }
141
142 /**
143 * Updates the descendants of a FUNCTION node to represent a message's value.
144 * <p>
145 * The tree looks something like:
146 * <pre>
147 * function
148 * |-- name
149 * |-- lp
150 * | |-- name <arg1>
151 * | -- name <arg2>
152 * -- block
153 * |
154 * --return
155 * |
156 * --add
157 * |-- string foo
158 * -- name <arg1>
159 * </pre>
160 *
161 * @param message a message
162 * @param functionNode the message's original FUNCTION value node
163 *
164 * @throws MalformedException if the passed node's subtree structure is
165 * not as expected
166 */
167 private void updateFunctionNode(JsMessage message, Node functionNode)
168 throws MalformedException {
169 checkNode(functionNode, Token.FUNCTION);
170 Node nameNode = functionNode.getFirstChild();
171 checkNode(nameNode, Token.NAME);
172 Node argListNode = nameNode.getNext();
173 checkNode(argListNode, Token.PARAM_LIST);
174 Node oldBlockNode = argListNode.getNext();
175 checkNode(oldBlockNode, Token.BLOCK);
176
177 Iterator<CharSequence> iterator = message.parts().iterator();
178 Node valueNode = iterator.hasNext()
179 ? constructAddOrStringNode(iterator, argListNode)
180 : IR.string("");
181 Node newBlockNode = IR.block(IR.returnNode(valueNode));
182
183 // TODO(user): checkTreeEqual is overkill. I am in process of rewriting
184 // these functions.
185 if (newBlockNode.checkTreeEquals(oldBlockNode) != null) {
186 newBlockNode.copyInformationFromForTree(oldBlockNode);
187 functionNode.replaceChild(oldBlockNode, newBlockNode);
188 compiler.reportCodeChange();
189 }
190 }
191
192 /**
193 * Creates a parse tree corresponding to the remaining message parts in
194 * an iteration. The result will contain only STRING nodes, NAME nodes
195 * (corresponding to placeholder references), and/or ADD nodes used to
196 * combine the other two types.
197 *
198 * @param partsIterator an iterator over message parts
199 * @param argListNode an LP node whose children are valid placeholder names
200 * @return the root of the constructed parse tree
201 *
202 * @throws MalformedException if {@code partsIterator} contains a
203 * placeholder reference that does not correspond to a valid argument in
204 * the arg list
205 */
206 private Node constructAddOrStringNode(Iterator<CharSequence> partsIterator,
207 Node argListNode)
208 throws MalformedException {
209 CharSequence part = partsIterator.next();
210 Node partNode = null;
211 if (part instanceof JsMessage.PlaceholderReference) {
212 JsMessage.PlaceholderReference phRef =
213 (JsMessage.PlaceholderReference) part;
214
215 for (Node node : argListNode.children()) {
216 if (node.isName()) {
217 String arg = node.getString();
218
219 // We ignore the case here because the transconsole only supports
220 // uppercase placeholder names, but function arguments in JavaScript
221 // code can have mixed case.
222 if (arg.equalsIgnoreCase(phRef.getName())) {
223 partNode = IR.name(arg);
224 }
225 }
226 }
227
228 if (partNode == null) {
229 throw new MalformedException(
230 "Unrecognized message placeholder referenced: " + phRef.getName(),
231 argListNode);
232 }
233 } else {
234 // The part is just a string literal.
235 partNode = IR.string(part.toString());
236 }
237
238 if (partsIterator.hasNext()) {
239 return IR.add(partNode,
240 constructAddOrStringNode(partsIterator, argListNode));
241 } else {
242 return partNode;
243 }
244 }
245
246 /**
247 * Replaces a CALL node with an inlined message value.
248 * <p>
249 * The call tree looks something like:
250 * <pre>
251 * call
252 * |-- getprop
253 * | |-- name 'goog'
254 * | +-- string 'getMsg'
255 * |
256 * |-- string 'Hi {$userName}! Welcome to {$product}.'
257 * +-- objlit
258 * |-- string 'userName'
259 * |-- name 'someUserName'
260 * |-- string 'product'
261 * +-- call
262 * +-- name 'getProductName'
263 * <pre>
264 * <p>
265 * For that example, we'd return:
266 * <pre>
267 * add
268 * |-- string 'Hi '
269 * +-- add
270 * |-- name someUserName
271 * +-- add
272 * |-- string '! Welcome to '
273 * +-- add
274 * |-- call
275 * | +-- name 'getProductName'
276 * +-- string '.'
277 * </pre>
278 * @param message a message
279 * @param callNode the message's original CALL value node
280 * @return a STRING node, or an ADD node that does string concatenation, if
281 * the message has one or more placeholders
282 *
283 * @throws MalformedException if the passed node's subtree structure is
284 * not as expected
285 */
286 private Node replaceCallNode(JsMessage message, Node callNode)
287 throws MalformedException {
288 checkNode(callNode, Token.CALL);
289 Node getPropNode = callNode.getFirstChild();
290 checkNode(getPropNode, Token.GETPROP);
291 Node stringExprNode = getPropNode.getNext();
292 checkStringExprNode(stringExprNode);
293 Node objLitNode = stringExprNode.getNext();
294
295 // Build the replacement tree.
296 return constructStringExprNode(message.parts().iterator(), objLitNode);
297 }
298
299 /**
300 * Creates a parse tree corresponding to the remaining message parts in an
301 * iteration. The result consists of one or more STRING nodes, placeholder
302 * replacement value nodes (which can be arbitrary expressions), and ADD
303 * nodes.
304 *
305 * @param parts an iterator over message parts
306 * @param objLitNode an OBJLIT node mapping placeholder names to values
307 * @return the root of the constructed parse tree
308 *
309 * @throws MalformedException if {@code parts} contains a placeholder
310 * reference that does not correspond to a valid placeholder name
311 */
312 private Node constructStringExprNode(Iterator<CharSequence> parts,
313 Node objLitNode) throws MalformedException {
314
315 CharSequence part = parts.next();
316 Node partNode = null;
317 if (part instanceof JsMessage.PlaceholderReference) {
318 JsMessage.PlaceholderReference phRef =
319 (JsMessage.PlaceholderReference) part;
320
321 // The translated message is null
322 if (objLitNode == null) {
323 throw new MalformedException("Empty placeholder value map " +
324 "for a translated message with placeholders.", objLitNode);
325 }
326
327 for (Node key = objLitNode.getFirstChild(); key != null;
328 key = key.getNext()) {
329 if (key.getString().equals(phRef.getName())) {
330 Node valueNode = key.getFirstChild();
331 partNode = valueNode.cloneTree();
332 }
333 }
334
335 if (partNode == null) {
336 throw new MalformedException(
337 "Unrecognized message placeholder referenced: " + phRef.getName(),
338 objLitNode);
339 }
340 } else {
341 // The part is just a string literal.
342 partNode = IR.string(part.toString());
343 }
344
345 if (parts.hasNext()) {
346 return IR.add(partNode,
347 constructStringExprNode(parts, objLitNode));
348 } else {
349 return partNode;
350 }
351 }
352
353 /**
354 * Checks that a node is a valid string expression (either a string literal
355 * or a concatenation of string literals).
356 *
357 * @throws IllegalArgumentException if the node is null or the wrong type
358 */
359 private void checkStringExprNode(@Nullable Node node) {
360 if (node == null) {
361 throw new IllegalArgumentException("Expected a string; found: null");
362 }
363 switch (node.getType()) {
364 case Token.STRING:
365 break;
366 case Token.ADD:
367 Node c = node.getFirstChild();
368 checkStringExprNode(c);
369 checkStringExprNode(c.getNext());
370 break;
371 default:
372 throw new IllegalArgumentException(
373 "Expected a string; found: " + node.getType());
374 }
375 }
376 }