Debian Codegraph @

src/com/google/javascript/jscomp/JsMessageVisitor.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 static com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
20
21 import com.google.common.base.CaseFormat;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
24 import com.google.javascript.jscomp.JsMessage.Builder;
25 import com.google.javascript.jscomp.Scope.Var;
26 import com.google.javascript.rhino.JSDocInfo;
27 import com.google.javascript.rhino.Node;
28 import com.google.javascript.rhino.Token;
29
30 import java.util.*;
31 import java.util.regex.*;
32
33 import javax.annotation.Nullable;
34
35 /**
36 * Traverses across parsed tree and finds I18N messages. Then it passes it to
37 * {@link JsMessageVisitor#processJsMessage(JsMessage, JsMessageDefinition)}.
38 *
39 * @author [email protected] (Anatol Pomazau)
40 */
41 abstract class JsMessageVisitor extends AbstractPostOrderCallback
42 implements CompilerPass {
43
44 private static final String MSG_FUNCTION_NAME = "goog.getMsg";
45 private static final String MSG_FALLBACK_FUNCTION_NAME =
46 "goog.getMsgWithFallback";
47
48 static final DiagnosticType MESSAGE_HAS_NO_DESCRIPTION =
49 DiagnosticType.warning("JSC_MSG_HAS_NO_DESCRIPTION",
50 "Message {0} has no description. Add @desc JsDoc tag.");
51
52 static final DiagnosticType MESSAGE_HAS_NO_TEXT =
53 DiagnosticType.warning("JSC_MSG_HAS_NO_TEXT",
54 "Message value of {0} is just an empty string. "
55 + "Empty messages are forbidden." );
56
57 static final DiagnosticType MESSAGE_TREE_MALFORMED =
58 DiagnosticType.error("JSC_MSG_TREE_MALFORMED",
59 "Message parse tree malformed. {0}");
60
61 static final DiagnosticType MESSAGE_HAS_NO_VALUE =
62 DiagnosticType.error("JSC_MSG_HAS_NO_VALUE",
63 "message node {0} has no value");
64
65 static final DiagnosticType MESSAGE_DUPLICATE_KEY =
66 DiagnosticType.error("JSC_MSG_KEY_DUPLICATED",
67 "duplicate message variable name found for {0}, " +
68 "initial definition {1}:{2}");
69
70 static final DiagnosticType MESSAGE_NODE_IS_ORPHANED =
71 DiagnosticType.warning("JSC_MSG_ORPHANED_NODE", MSG_FUNCTION_NAME +
72 "() function could be used only with MSG_* property or variable");
73
74 static final DiagnosticType MESSAGE_NOT_INITIALIZED_USING_NEW_SYNTAX =
75 DiagnosticType.error("JSC_MSG_NOT_INITIALIZED_USING_NEW_SYNTAX",
76 "message not initialized using " + MSG_FUNCTION_NAME);
77
78 static final DiagnosticType BAD_FALLBACK_SYNTAX =
79 DiagnosticType.error("JSC_MSG_BAD_FALLBACK_SYNTAX",
80 String.format(
81 "Bad syntax. " +
82 "Expected syntax: goog.getMsgWithFallback(MSG_1, MSG_2)",
83 MSG_FALLBACK_FUNCTION_NAME));
84
85 static final DiagnosticType FALLBACK_ARG_ERROR =
86 DiagnosticType.error("JSC_MSG_FALLBACK_ARG_ERROR",
87 "Could not find message entry for fallback argument {0}");
88
89 private static final String PH_JS_PREFIX = "{$";
90 private static final String PH_JS_SUFFIX = "}";
91
92 static final String MSG_PREFIX = "MSG_";
93
94 /**
95 * Pattern for unnamed messages.
96 * <p>
97 * All JS messages in JS code should have unique name but messages in
98 * generated code (i.e. from soy template) could have duplicated message names.
99 * Later we replace the message names with ids constructed as a hash of the
100 * message content.
101 * <p>
102 * <link href="http://code.google.com/p/closure-templates/">
103 * Soy</link> generates messages with names MSG_UNNAMED_<NUMBER> . This
104 * pattern recognizes such messages.
105 */
106 private static final Pattern MSG_UNNAMED_PATTERN =
107 Pattern.compile("MSG_UNNAMED_\\d+");
108
109 private static final Pattern CAMELCASE_PATTERN =
110 Pattern.compile("[a-z][a-zA-Z\\d]*[_\\d]*");
111
112 static final String HIDDEN_DESC_PREFIX = "@hidden";
113
114 // For old-style JS messages
115 private static final String DESC_SUFFIX = "_HELP";
116
117 private final boolean needToCheckDuplications;
118 private final JsMessage.Style style;
119 private final JsMessage.IdGenerator idGenerator;
120 final AbstractCompiler compiler;
121
122 /**
123 * The names encountered associated with their defining node and source. We
124 * use it for tracking duplicated message ids in the source code.
125 */
126 private final Map<String, MessageLocation> messageNames =
127 Maps.newHashMap();
128
129 private final Map<Var, JsMessage> unnamedMessages =
130 Maps.newHashMap();
131
132 /**
133 * List of found goog.getMsg call nodes.
134 *
135 * When we visit goog.getMsg() node we add a pair node:sourcename and later
136 * when we visit its parent we remove this pair. All nodes that are left at
137 * the end of traversing are orphaned nodes. It means have no corresponding
138 * var or property node.
139 */
140 private final Map<Node, String> googMsgNodes = Maps.newHashMap();
141
142 private final CheckLevel checkLevel;
143
144 /**
145 * Creates JS message visitor.
146 *
147 * @param compiler the compiler instance
148 * @param needToCheckDuplications whether to check duplicated messages in
149 * traversed
150 * @param style style that should be used during parsing
151 * @param idGenerator generator that used for creating unique ID for the
152 * message
153 */
154 JsMessageVisitor(AbstractCompiler compiler,
155 boolean needToCheckDuplications,
156 JsMessage.Style style, JsMessage.IdGenerator idGenerator) {
157
158 this.compiler = compiler;
159 this.needToCheckDuplications = needToCheckDuplications;
160 this.style = style;
161 this.idGenerator = idGenerator;
162
163 checkLevel = (style == JsMessage.Style.CLOSURE)
164 ? CheckLevel.ERROR : CheckLevel.WARNING;
165
166 // TODO(anatol): add flag that decides whether to process UNNAMED messages.
167 // Some projects would not want such functionality (unnamed) as they don't
168 // use SOY templates.
169 }
170
171 @Override
172 public void process(Node externs, Node root) {
173 NodeTraversal.traverse(compiler, root, this);
174
175 for (Map.Entry<Node, String> msgNode : googMsgNodes.entrySet()) {
176 compiler.report(JSError.make(msgNode.getValue(), msgNode.getKey(),
177 checkLevel, MESSAGE_NODE_IS_ORPHANED));
178 }
179 }
180
181 @Override
182 public void visit(NodeTraversal traversal, Node node, Node parent) {
183 String messageKey;
184 boolean isVar;
185 Node msgNode, msgNodeParent;
186
187 switch (node.getType()) {
188 case Token.NAME:
189 // var MSG_HELLO = 'Message'
190 if ((parent != null) && (parent.isVar())) {
191 messageKey = node.getString();
192 isVar = true;
193 } else {
194 return;
195 }
196
197 msgNode = node.getFirstChild();
198 msgNodeParent = node;
199 break;
200 case Token.ASSIGN:
201 // somenamespace.someclass.MSG_HELLO = 'Message'
202 isVar = false;
203
204 Node getProp = node.getFirstChild();
205 if (!getProp.isGetProp()) {
206 return;
207 }
208
209 Node propNode = getProp.getLastChild();
210
211 messageKey = propNode.getString();
212 msgNode = node.getLastChild();
213 msgNodeParent = node;
214 break;
215 case Token.CALL:
216 // goog.getMsg()
217 String fnName = node.getFirstChild().getQualifiedName();
218 if (MSG_FUNCTION_NAME.equals(fnName)) {
219 googMsgNodes.put(node, traversal.getSourceName());
220 } else if (MSG_FALLBACK_FUNCTION_NAME.equals(fnName)) {
221 visitFallbackFunctionCall(traversal, node);
222 }
223 return;
224 default:
225 return;
226 }
227
228 // Is this a message name?
229 boolean isNewStyleMessage =
230 msgNode != null && msgNode.isCall();
231 if (!isMessageName(messageKey, isNewStyleMessage)) {
232 return;
233 }
234
235 if (msgNode == null) {
236 compiler.report(
237 traversal.makeError(node, MESSAGE_HAS_NO_VALUE, messageKey));
238 return;
239 }
240
241 // Just report a warning if a qualified messageKey that looks like a message
242 // (e.g. "a.b.MSG_X") doesn't use goog.getMsg().
243 if (isNewStyleMessage) {
244 googMsgNodes.remove(msgNode);
245 } else if (style != JsMessage.Style.LEGACY) {
246 compiler.report(traversal.makeError(node, checkLevel,
247 MESSAGE_NOT_INITIALIZED_USING_NEW_SYNTAX));
248 }
249
250 boolean isUnnamedMsg = isUnnamedMessageName(messageKey);
251
252 Builder builder = new Builder(
253 isUnnamedMsg ? null : messageKey);
254 builder.setSourceName(traversal.getSourceName());
255
256 try {
257 if (isVar) {
258 extractMessageFromVariable(builder, node, parent, parent.getParent());
259 } else {
260 extractMessageFromProperty(builder, node.getFirstChild(), node);
261 }
262 } catch (MalformedException ex) {
263 compiler.report(traversal.makeError(ex.getNode(),
264 MESSAGE_TREE_MALFORMED, ex.getMessage()));
265 return;
266 }
267
268 JsMessage extractedMessage = builder.build(idGenerator);
269
270 // If asked to check named internal messages.
271 if (needToCheckDuplications
272 && !isUnnamedMsg
273 && !extractedMessage.isExternal()) {
274 checkIfMessageDuplicated(messageKey, msgNode);
275 }
276 trackMessage(traversal, extractedMessage,
277 messageKey, msgNode, isUnnamedMsg);
278
279 if (extractedMessage.isEmpty()) {
280 // value of the message is an empty string. Translators do not like it.
281 compiler.report(traversal.makeError(node, MESSAGE_HAS_NO_TEXT,
282 messageKey));
283 }
284
285 // New-style messages must have descriptions. We don't emit a warning
286 // for legacy-style messages, because there are thousands of
287 // them in legacy code that are not worth the effort to fix, since they've
288 // already been translated anyway.
289 String desc = extractedMessage.getDesc();
290 if (isNewStyleMessage
291 && (desc == null || desc.trim().isEmpty())
292 && !extractedMessage.isExternal()) {
293 compiler.report(traversal.makeError(node, MESSAGE_HAS_NO_DESCRIPTION,
294 messageKey));
295 }
296
297 JsMessageDefinition msgDefinition = new JsMessageDefinition(
298 node, msgNode, msgNodeParent);
299 processJsMessage(extractedMessage, msgDefinition);
300 }
301
302 /**
303 * Track a message for later retrieval.
304 *
305 * This is used for tracking duplicates, and for figuring out message
306 * fallback. Not all message types are trackable, because that would
307 * require a more sophisticated analysis. e.g.,
308 * function f(s) { s.MSG_UNNAMED_X = 'Some untrackable message'; }
309 */
310 private void trackMessage(
311 NodeTraversal t, JsMessage message, String msgName,
312 Node msgNode, boolean isUnnamedMessage) {
313 if (!isUnnamedMessage) {
314 MessageLocation location = new MessageLocation(message, msgNode);
315 messageNames.put(msgName, location);
316 } else if (msgNode.isName()) {
317 Var var = t.getScope().getVar(msgName);
318 if (var != null) {
319 unnamedMessages.put(var, message);
320 }
321 }
322 }
323
324 /** Get a previously tracked message. */
325 private JsMessage getTrackedMessage(NodeTraversal t, String msgName) {
326 boolean isUnnamedMessage = isUnnamedMessageName(msgName);
327 if (!isUnnamedMessage) {
328 MessageLocation location = messageNames.get(msgName);
329 return location == null ? null : location.message;
330 } else {
331 Var var = t.getScope().getVar(msgName);
332 if (var != null) {
333 return unnamedMessages.get(var);
334 }
335 }
336 return null;
337 }
338
339 /**
340 * Checks if message already processed. If so - it generates 'message
341 * duplicated' compiler error.
342 *
343 * @param msgName the name of the message
344 * @param msgNode the node that represents JS message
345 */
346 private void checkIfMessageDuplicated(String msgName, Node msgNode) {
347 if (messageNames.containsKey(msgName)) {
348 MessageLocation location = messageNames.get(msgName);
349 compiler.report(JSError.make(msgNode, MESSAGE_DUPLICATE_KEY,
350 msgName, location.messageNode.getSourceFileName(),
351 Integer.toString(location.messageNode.getLineno())));
352 }
353 }
354
355 /**
356 * Creates a {@link JsMessage} for a JS message defined using a JS variable
357 * declaration (e.g <code>var MSG_X = ...;</code>).
358 *
359 * @param builder the message builder
360 * @param nameNode a NAME node for a JS message variable
361 * @param parentNode a VAR node, parent of {@code nameNode}
362 * @param grandParentNode the grandparent of {@code nameNode}. This node is
363 * only used to get meta data about the message that might be
364 * surrounding it (e.g. a message description). This argument may be
365 * null if the meta data is not needed.
366 * @throws MalformedException if {@code varNode} does not
367 * correspond to a valid JS message VAR node
368 */
369 private void extractMessageFromVariable(
370 Builder builder, Node nameNode, Node parentNode,
371 @Nullable Node grandParentNode) throws MalformedException {
372
373 // Determine the message's value
374 Node valueNode = nameNode.getFirstChild();
375 switch (valueNode.getType()) {
376 case Token.STRING:
377 case Token.ADD:
378 maybeInitMetaDataFromJsDocOrHelpVar(builder, parentNode,
379 grandParentNode);
380 builder.appendStringPart(extractStringFromStringExprNode(valueNode));
381 break;
382 case Token.FUNCTION:
383 maybeInitMetaDataFromJsDocOrHelpVar(builder, parentNode,
384 grandParentNode);
385 extractFromFunctionNode(builder, valueNode);
386 break;
387 case Token.CALL:
388 maybeInitMetaDataFromJsDoc(builder, parentNode);
389 extractFromCallNode(builder, valueNode);
390 break;
391 default:
392 throw new MalformedException("Cannot parse value of message "
393 + builder.getKey(), valueNode);
394 }
395 }
396
397 /**
398 * Creates a {@link JsMessage} for a JS message defined using an assignment to
399 * a qualified name (e.g <code>a.b.MSG_X = goog.getMsg(...);</code>).
400 *
401 * @param builder the message builder
402 * @param getPropNode a GETPROP node in a JS message assignment
403 * @param assignNode an ASSIGN node, parent of {@code getPropNode}.
404 * @throws MalformedException if {@code getPropNode} does not
405 * correspond to a valid JS message node
406 */
407 private void extractMessageFromProperty(
408 Builder builder, Node getPropNode, Node assignNode)
409 throws MalformedException {
410 Node callNode = getPropNode.getNext();
411 maybeInitMetaDataFromJsDoc(builder, assignNode);
412 extractFromCallNode(builder, callNode);
413 }
414
415 /**
416 * Initializes the meta data in a JsMessage by examining the nodes just before
417 * and after a message VAR node.
418 *
419 * @param builder the message builder whose meta data will be initialized
420 * @param varNode the message VAR node
421 * @param parentOfVarNode {@code varNode}'s parent node
422 */
423 private void maybeInitMetaDataFromJsDocOrHelpVar(
424 Builder builder, Node varNode, @Nullable Node parentOfVarNode)
425 throws MalformedException {
426
427 // First check description in @desc
428 if (maybeInitMetaDataFromJsDoc(builder, varNode)) {
429 return;
430 }
431
432 // Check the preceding node for meta data
433 if ((parentOfVarNode != null) &&
434 maybeInitMetaDataFromHelpVar(builder,
435 parentOfVarNode.getChildBefore(varNode))) {
436 return;
437 }
438
439 // Check the subsequent node for meta data
440 maybeInitMetaDataFromHelpVar(builder, varNode.getNext());
441 }
442
443 /**
444 * Initializes the meta data in a JsMessage by examining a node just before or
445 * after a message VAR node.
446 *
447 * @param builder the message builder whose meta data will be initialized
448 * @param sibling a node adjacent to the message VAR node
449 * @return true iff message has corresponding description variable
450 */
451 private boolean maybeInitMetaDataFromHelpVar(Builder builder,
452 @Nullable Node sibling) throws MalformedException {
453 if ((sibling != null) && (sibling.isVar())) {
454 Node nameNode = sibling.getFirstChild();
455 String name = nameNode.getString();
456 if (name.equals(builder.getKey() + DESC_SUFFIX)) {
457 Node valueNode = nameNode.getFirstChild();
458 String desc = extractStringFromStringExprNode(valueNode);
459 if (desc.startsWith(HIDDEN_DESC_PREFIX)) {
460 builder.setDesc(desc.substring(HIDDEN_DESC_PREFIX.length()).trim());
461 builder.setIsHidden(true);
462 } else {
463 builder.setDesc(desc);
464 }
465 return true;
466 }
467 }
468 return false;
469 }
470
471 /**
472 * Initializes the meta data in a message builder given a node that may
473 * contain JsDoc properties.
474 *
475 * @param builder the message builder whose meta data will be initialized
476 * @param node the node with the message's JSDoc properties
477 * @return true if message has JsDoc with valid description in @desc
478 * annotation
479 */
480 private boolean maybeInitMetaDataFromJsDoc(Builder builder, Node node) {
481 boolean messageHasDesc = false;
482 JSDocInfo info = node.getJSDocInfo();
483 if (info != null) {
484 String desc = info.getDescription();
485 if (desc != null) {
486 builder.setDesc(desc);
487 messageHasDesc = true;
488 }
489 if (info.isHidden()) {
490 builder.setIsHidden(true);
491 }
492 if (info.getMeaning() != null) {
493 builder.setMeaning(info.getMeaning());
494 }
495 }
496
497 return messageHasDesc;
498 }
499
500 /**
501 * Returns the string value associated with a node representing a JS string or
502 * several JS strings added together (e.g. {@code 'str'} or {@code 's' + 't' +
503 * 'r'}).
504 *
505 * @param node the node from where we extract the string
506 * @return String representation of the node
507 * @throws MalformedException if the parsed message is invalid
508 */
509 private static String extractStringFromStringExprNode(Node node)
510 throws MalformedException {
511 switch (node.getType()) {
512 case Token.STRING:
513 return node.getString();
514 case Token.ADD:
515 StringBuilder sb = new StringBuilder();
516 for (Node child : node.children()) {
517 sb.append(extractStringFromStringExprNode(child));
518 }
519 return sb.toString();
520 default:
521 throw new MalformedException("STRING or ADD node expected; found: " +
522 getReadableTokenName(node), node);
523 }
524 }
525
526 /**
527 * Initializes a message builder from a FUNCTION node.
528 * <p>
529 * <pre>
530 * The tree should look something like:
531 *
532 * function
533 * |-- name
534 * |-- lp
535 * | |-- name <arg1>
536 * | -- name <arg2>
537 * -- block
538 * |
539 * --return
540 * |
541 * --add
542 * |-- string foo
543 * -- name <arg1>
544 * </pre>
545 *
546 * @param builder the message builder
547 * @param node the function node that contains a message
548 * @throws MalformedException if the parsed message is invalid
549 */
550 private void extractFromFunctionNode(Builder builder, Node node)
551 throws MalformedException {
552 Set<String> phNames = Sets.newHashSet();
553
554 for (Node fnChild : node.children()) {
555 switch (fnChild.getType()) {
556 case Token.NAME:
557 // This is okay. The function has a name, but it is empty.
558 break;
559 case Token.PARAM_LIST:
560 // Parse the placeholder names from the function argument list.
561 for (Node argumentNode : fnChild.children()) {
562 if (argumentNode.isName()) {
563 String phName = argumentNode.getString();
564 if (phNames.contains(phName)) {
565 throw new MalformedException("Duplicate placeholder name: "
566 + phName, argumentNode);
567 } else {
568 phNames.add(phName);
569 }
570 }
571 }
572 break;
573 case Token.BLOCK:
574 // Build the message's value by examining the return statement
575 Node returnNode = fnChild.getFirstChild();
576 if (!returnNode.isReturn()) {
577 throw new MalformedException("RETURN node expected; found: "
578 + getReadableTokenName(returnNode), returnNode);
579 }
580 for (Node child : returnNode.children()) {
581 extractFromReturnDescendant(builder, child);
582 }
583
584 // Check that all placeholders from the message text have appropriate
585 // object literal keys
586 for (String phName : builder.getPlaceholders()) {
587 if(!phNames.contains(phName)) {
588 throw new MalformedException(
589 "Unrecognized message placeholder referenced: " + phName,
590 returnNode);
591 }
592 }
593 break;
594 default:
595 throw new MalformedException(
596 "NAME, LP, or BLOCK node expected; found: "
597 + getReadableTokenName(node), fnChild);
598 }
599 }
600 }
601
602 /**
603 * Appends value parts to the message builder by traversing the descendants
604 * of the given RETURN node.
605 *
606 * @param builder the message builder
607 * @param node the node from where we extract a message
608 * @throws MalformedException if the parsed message is invalid
609 */
610 private void extractFromReturnDescendant(Builder builder, Node node)
611 throws MalformedException {
612
613 switch (node.getType()) {
614 case Token.STRING:
615 builder.appendStringPart(node.getString());
616 break;
617 case Token.NAME:
618 builder.appendPlaceholderReference(node.getString());
619 break;
620 case Token.ADD:
621 for (Node child : node.children()) {
622 extractFromReturnDescendant(builder, child);
623 }
624 break;
625 default:
626 throw new MalformedException(
627 "STRING, NAME, or ADD node expected; found: "
628 + getReadableTokenName(node), node);
629 }
630 }
631
632 /**
633 * Initializes a message builder from a CALL node.
634 * <p>
635 * The tree should look something like:
636 *
637 * <pre>
638 * call
639 * |-- getprop
640 * | |-- name 'goog'
641 * | +-- string 'getMsg'
642 * |
643 * |-- string 'Hi {$userName}! Welcome to {$product}.'
644 * +-- objlit
645 * |-- string 'userName'
646 * |-- name 'someUserName'
647 * |-- string 'product'
648 * +-- call
649 * +-- name 'getProductName'
650 * </pre>
651 *
652 * @param builder the message builder
653 * @param node the call node from where we extract the message
654 * @throws MalformedException if the parsed message is invalid
655 */
656 private void extractFromCallNode(Builder builder,
657 Node node) throws MalformedException {
658 // Check the function being called
659 if (!node.isCall()) {
660 throw new MalformedException(
661 "Message must be initialized using " + MSG_FUNCTION_NAME +
662 " function.", node);
663 }
664
665 Node fnNameNode = node.getFirstChild();
666 if (!MSG_FUNCTION_NAME.equals(fnNameNode.getQualifiedName())) {
667 throw new MalformedException(
668 "Message initialized using unrecognized function. " +
669 "Please use " + MSG_FUNCTION_NAME + "() instead.", fnNameNode);
670 }
671
672 // Get the message string
673 Node stringLiteralNode = fnNameNode.getNext();
674 if (stringLiteralNode == null) {
675 throw new MalformedException("Message string literal expected",
676 stringLiteralNode);
677 }
678 // Parse the message string and append parts to the builder
679 parseMessageTextNode(builder, stringLiteralNode);
680
681 Node objLitNode = stringLiteralNode.getNext();
682 Set<String> phNames = Sets.newHashSet();
683 if (objLitNode != null) {
684 // Register the placeholder names
685 if (!objLitNode.isObjectLit()) {
686 throw new MalformedException("OBJLIT node expected", objLitNode);
687 }
688 for (Node aNode = objLitNode.getFirstChild(); aNode != null;
689 aNode = aNode.getNext()) {
690 if (!aNode.isStringKey()) {
691 throw new MalformedException("STRING_KEY node expected as OBJLIT key",
692 aNode);
693 }
694 String phName = aNode.getString();
695 if (!isLowerCamelCaseWithNumericSuffixes(phName)) {
696 throw new MalformedException(
697 "Placeholder name not in lowerCamelCase: " + phName, aNode);
698 }
699
700 if (phNames.contains(phName)) {
701 throw new MalformedException("Duplicate placeholder name: "
702 + phName, aNode);
703 }
704
705 phNames.add(phName);
706 }
707 }
708
709 // Check that all placeholders from the message text have appropriate objlit
710 // values
711 Set<String> usedPlaceholders = builder.getPlaceholders();
712 for (String phName : usedPlaceholders) {
713 if(!phNames.contains(phName)) {
714 throw new MalformedException(
715 "Unrecognized message placeholder referenced: " + phName,
716 objLitNode);
717 }
718 }
719
720 // Check that objLiteral have only names that are present in the
721 // message text
722 for (String phName : phNames) {
723 if(!usedPlaceholders.contains(phName)) {
724 throw new MalformedException(
725 "Unused message placeholder: " + phName,
726 objLitNode);
727 }
728 }
729 }
730
731 /**
732 * Appends the message parts in a JS message value extracted from the given
733 * text node.
734 *
735 * @param builder the JS message builder to append parts to
736 * @param node the node with string literal that contains the message text
737 * @throws MalformedException if {@code value} contains a reference to
738 * an unregistered placeholder
739 */
740 private void parseMessageTextNode(Builder builder, Node node)
741 throws MalformedException {
742 String value = extractStringFromStringExprNode(node);
743
744 while(true) {
745 int phBegin = value.indexOf(PH_JS_PREFIX);
746 if (phBegin < 0) {
747 // Just a string literal
748 builder.appendStringPart(value);
749 return;
750 } else {
751 if (phBegin > 0) {
752 // A string literal followed by a placeholder
753 builder.appendStringPart(value.substring(0, phBegin));
754 }
755
756 // A placeholder. Find where it ends
757 int phEnd = value.indexOf(PH_JS_SUFFIX, phBegin);
758 if (phEnd < 0) {
759 throw new MalformedException(
760 "Placeholder incorrectly formatted in: " + builder.getKey(),
761 node);
762 }
763
764 String phName = value.substring(phBegin + PH_JS_PREFIX.length(),
765 phEnd);
766 builder.appendPlaceholderReference(phName);
767 int nextPos = phEnd + PH_JS_SUFFIX.length();
768 if (nextPos < value.length()) {
769 // Iterate on the rest of the message value
770 value = value.substring(nextPos);
771 } else {
772 // The message is parsed
773 return;
774 }
775 }
776 }
777 }
778
779 /** Visit a call to goog.getMsgWithFallback. */
780 private void visitFallbackFunctionCall(NodeTraversal t, Node call) {
781 // Check to make sure the function call looks like:
782 // goog.getMsgWithFallback(MSG_1, MSG_2);
783 if (call.getChildCount() != 3 ||
784 !call.getChildAtIndex(1).isName() ||
785 !call.getChildAtIndex(2).isName()) {
786 compiler.report(t.makeError(call, BAD_FALLBACK_SYNTAX));
787 return;
788 }
789
790 Node firstArg = call.getChildAtIndex(1);
791 JsMessage firstMessage = getTrackedMessage(t, firstArg.getString());
792 if (firstMessage == null) {
793 compiler.report(
794 t.makeError(firstArg, FALLBACK_ARG_ERROR, firstArg.getString()));
795 return;
796 }
797
798 Node secondArg = firstArg.getNext();
799 JsMessage secondMessage = getTrackedMessage(
800 t, call.getChildAtIndex(2).getString());
801 if (secondMessage == null) {
802 compiler.report(
803 t.makeError(secondArg, FALLBACK_ARG_ERROR, secondArg.getString()));
804 return;
805 }
806
807 processMessageFallback(call, firstMessage, secondMessage);
808 }
809
810
811 /**
812 * Processes found JS message. Several examples of "standard" processing
813 * routines are:
814 * <ol>
815 * <li>extract all JS messages
816 * <li>replace JS messages with localized versions for some specific language
817 * <li>check that messages have correct syntax and present in localization
818 * bundle
819 * </ol>
820 *
821 * @param message the found message
822 * @param definition the definition of the object and usually contains all
823 * additional message information like message node/parent's node
824 */
825 abstract void processJsMessage(JsMessage message,
826 JsMessageDefinition definition);
827
828 /**
829 * Processes the goog.getMsgWithFallback primitive.
830 * goog.getMsgWithFallback(MSG_1, MSG_2);
831 *
832 * By default, does nothing.
833 */
834 void processMessageFallback(Node callNode, JsMessage message1,
835 JsMessage message2) {}
836
837 /**
838 * Returns whether the given JS identifier is a valid JS message name.
839 */
840 boolean isMessageName(String identifier, boolean isNewStyleMessage) {
841 return identifier.startsWith(MSG_PREFIX) &&
842 (style == JsMessage.Style.CLOSURE || isNewStyleMessage ||
843 !identifier.endsWith(DESC_SUFFIX));
844 }
845
846 /**
847 * Returns whether the given message name is in the unnamed namespace.
848 */
849 private static boolean isUnnamedMessageName(String identifier) {
850 return MSG_UNNAMED_PATTERN.matcher(identifier).matches();
851 }
852
853 /**
854 * Returns whether a string is nonempty, begins with a lowercase letter, and
855 * contains only digits and underscores after the first underscore.
856 */
857 static boolean isLowerCamelCaseWithNumericSuffixes(String input) {
858 return CAMELCASE_PATTERN.matcher(input).matches();
859 }
860
861 /**
862 * Returns human-readable name of the given node's type.
863 */
864 private static String getReadableTokenName(Node node) {
865 return Token.name(node.getType());
866 }
867
868 /**
869 * Converts the given string from upper-underscore case to lower-camel case,
870 * preserving numeric suffixes. For example: "NAME" -> "name" "A4_LETTER" ->
871 * "a4Letter" "START_SPAN_1_23" -> "startSpan_1_23".
872 */
873 static String toLowerCamelCaseWithNumericSuffixes(String input) {
874 // Determine where the numeric suffixes begin
875 int suffixStart = input.length();
876 while (suffixStart > 0) {
877 char ch = '\0';
878 int numberStart = suffixStart;
879 while (numberStart > 0) {
880 ch = input.charAt(numberStart - 1);
881 if (Character.isDigit(ch)) {
882 numberStart--;
883 } else {
884 break;
885 }
886 }
887 if ((numberStart > 0) && (numberStart < suffixStart) && (ch == '_')) {
888 suffixStart = numberStart - 1;
889 } else {
890 break;
891 }
892 }
893
894 if (suffixStart == input.length()) {
895 return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, input);
896 } else {
897 return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,
898 input.substring(0, suffixStart)) +
899 input.substring(suffixStart);
900 }
901 }
902
903 /**
904 * Checks a node's type.
905 *
906 * @throws MalformedException if the node is null or the wrong type
907 */
908 protected void checkNode(@Nullable Node node, int type) throws MalformedException {
909 if (node == null) {
910 throw new MalformedException(
911 "Expected node type " + type + "; found: null", node);
912 }
913 if (node.getType() != type) {
914 throw new MalformedException(
915 "Expected node type " + type + "; found: " + node.getType(), node);
916 }
917 }
918
919 static class MalformedException extends Exception {
920 private static final long serialVersionUID = 1L;
921
922 private final Node node;
923
924 MalformedException(String message, Node node) {
925 super(message);
926 this.node = node;
927 }
928
929 Node getNode() {
930 return node;
931 }
932 }
933
934 private static class MessageLocation {
935 private final JsMessage message;
936 private final Node messageNode;
937
938 private MessageLocation(JsMessage message, Node messageNode) {
939 this.message = message;
940 this.messageNode = messageNode;
941 }
942 }
943 }