Debian Codegraph @

src/com/google/javascript/jscomp/parsing/IRFactory.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.parsing;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.parsing.Config.LanguageMode;
23 import com.google.javascript.rhino.IR;
24 import com.google.javascript.rhino.JSDocInfo;
25 import com.google.javascript.rhino.Node;
26 import com.google.javascript.rhino.Token;
27 import com.google.javascript.rhino.head.ErrorReporter;
28 import com.google.javascript.rhino.head.Token.CommentType;
29 import com.google.javascript.rhino.head.ast.ArrayLiteral;
30 import com.google.javascript.rhino.head.ast.Assignment;
31 import com.google.javascript.rhino.head.ast.AstNode;
32 import com.google.javascript.rhino.head.ast.AstRoot;
33 import com.google.javascript.rhino.head.ast.Block;
34 import com.google.javascript.rhino.head.ast.BreakStatement;
35 import com.google.javascript.rhino.head.ast.CatchClause;
36 import com.google.javascript.rhino.head.ast.Comment;
37 import com.google.javascript.rhino.head.ast.ConditionalExpression;
38 import com.google.javascript.rhino.head.ast.ContinueStatement;
39 import com.google.javascript.rhino.head.ast.DoLoop;
40 import com.google.javascript.rhino.head.ast.ElementGet;
41 import com.google.javascript.rhino.head.ast.EmptyExpression;
42 import com.google.javascript.rhino.head.ast.EmptyStatement;
43 import com.google.javascript.rhino.head.ast.ExpressionStatement;
44 import com.google.javascript.rhino.head.ast.ForInLoop;
45 import com.google.javascript.rhino.head.ast.ForLoop;
46 import com.google.javascript.rhino.head.ast.FunctionCall;
47 import com.google.javascript.rhino.head.ast.FunctionNode;
48 import com.google.javascript.rhino.head.ast.IfStatement;
49 import com.google.javascript.rhino.head.ast.InfixExpression;
50 import com.google.javascript.rhino.head.ast.KeywordLiteral;
51 import com.google.javascript.rhino.head.ast.Label;
52 import com.google.javascript.rhino.head.ast.LabeledStatement;
53 import com.google.javascript.rhino.head.ast.Name;
54 import com.google.javascript.rhino.head.ast.NewExpression;
55 import com.google.javascript.rhino.head.ast.NumberLiteral;
56 import com.google.javascript.rhino.head.ast.ObjectLiteral;
57 import com.google.javascript.rhino.head.ast.ObjectProperty;
58 import com.google.javascript.rhino.head.ast.ParenthesizedExpression;
59 import com.google.javascript.rhino.head.ast.PropertyGet;
60 import com.google.javascript.rhino.head.ast.RegExpLiteral;
61 import com.google.javascript.rhino.head.ast.ReturnStatement;
62 import com.google.javascript.rhino.head.ast.Scope;
63 import com.google.javascript.rhino.head.ast.StringLiteral;
64 import com.google.javascript.rhino.head.ast.SwitchCase;
65 import com.google.javascript.rhino.head.ast.SwitchStatement;
66 import com.google.javascript.rhino.head.ast.ThrowStatement;
67 import com.google.javascript.rhino.head.ast.TryStatement;
68 import com.google.javascript.rhino.head.ast.UnaryExpression;
69 import com.google.javascript.rhino.head.ast.VariableDeclaration;
70 import com.google.javascript.rhino.head.ast.VariableInitializer;
71 import com.google.javascript.rhino.head.ast.WhileLoop;
72 import com.google.javascript.rhino.head.ast.WithStatement;
73 import com.google.javascript.rhino.jstype.StaticSourceFile;
74
75 import java.util.Set;
76
77 /**
78 * IRFactory transforms the new AST to the old AST.
79 *
80 */
81 class IRFactory {
82
83 static final String GETTER_ERROR_MESSAGE =
84 "getters are not supported in older versions of JS. " +
85 "If you are targeting newer versions of JS, " +
86 "set the appropriate language_in option.";
87
88 static final String SETTER_ERROR_MESSAGE =
89 "setters are not supported in older versions of JS. " +
90 "If you are targeting newer versions of JS, " +
91 "set the appropriate language_in option.";
92
93 static final String SUSPICIOUS_COMMENT_WARNING =
94 "Non-JSDoc comment has annotations. " +
95 "Did you mean to start it with '/**'?";
96
97 static final String MISPLACED_TYPE_ANNOTATION =
98 "Type annotations are not allowed here. Are you missing parentheses?";
99
100 private final String sourceString;
101 private final StaticSourceFile sourceFile;
102 private final String sourceName;
103 private final Config config;
104 private final ErrorReporter errorReporter;
105 private final TransformDispatcher transformDispatcher;
106
107 private static final ImmutableSet<String> ALLOWED_DIRECTIVES =
108 ImmutableSet.of("use strict");
109
110 private static final ImmutableSet<String> ES5_RESERVED_KEYWORDS =
111 ImmutableSet.of(
112 // From Section 7.6.1.2
113 "class", "const", "enum", "export", "extends", "import", "super");
114 private static final ImmutableSet<String> ES5_STRICT_RESERVED_KEYWORDS =
115 ImmutableSet.of(
116 // From Section 7.6.1.2
117 "class", "const", "enum", "export", "extends", "import", "super",
118 "implements", "interface", "let", "package", "private", "protected",
119 "public", "static", "yield");
120
121 private final Set<String> reservedKeywords;
122 private final Set<Comment> parsedComments = Sets.newHashSet();
123
124 // @license text gets appended onto the fileLevelJsDocBuilder as found,
125 // and stored in JSDocInfo for placeholder node.
126 Node rootNodeJsDocHolder = new Node(Token.SCRIPT);
127 Node.FileLevelJsDocBuilder fileLevelJsDocBuilder =
128 rootNodeJsDocHolder.getJsDocBuilderForNode();
129 JSDocInfo fileOverviewInfo = null;
130
131 // Use a template node for properties set on all nodes to minimize the
132 // memory footprint associated with these.
133 private Node templateNode;
134
135 // TODO(johnlenz): Consider creating a template pool for ORIGINALNAME_PROP.
136
137 private IRFactory(String sourceString,
138 StaticSourceFile sourceFile,
139 Config config,
140 ErrorReporter errorReporter) {
141 this.sourceString = sourceString;
142 this.sourceFile = sourceFile;
143
144 // Sometimes this will be null in tests.
145 this.sourceName = sourceFile == null ? null : sourceFile.getName();
146
147 this.config = config;
148 this.errorReporter = errorReporter;
149 this.transformDispatcher = new TransformDispatcher();
150 // The template node properties are applied to all nodes in this transform.
151 this.templateNode = createTemplateNode();
152
153 switch (config.languageMode) {
154 case ECMASCRIPT3:
155 // Reserved words are handled by the Rhino parser.
156 reservedKeywords = null;
157 break;
158 case ECMASCRIPT5:
159 reservedKeywords = ES5_RESERVED_KEYWORDS;
160 break;
161 case ECMASCRIPT5_STRICT:
162 reservedKeywords = ES5_STRICT_RESERVED_KEYWORDS;
163 break;
164 default:
165 throw new IllegalStateException("unknown language mode");
166 }
167 }
168
169 // Create a template node to use as a source of common attributes, this allows
170 // the prop structure to be shared among all the node from this source file.
171 // This reduces the cost of these properties to O(nodes) to O(files).
172 private Node createTemplateNode() {
173 // The Node type choice is arbitrary.
174 Node templateNode = new Node(Token.SCRIPT);
175 templateNode.setStaticSourceFile(sourceFile);
176 return templateNode;
177 }
178
179 public static Node transformTree(AstRoot node,
180 StaticSourceFile sourceFile,
181 String sourceString,
182 Config config,
183 ErrorReporter errorReporter) {
184 IRFactory irFactory = new IRFactory(sourceString, sourceFile,
185 config, errorReporter);
186 Node irNode = irFactory.transform(node);
187
188 if (node.getComments() != null) {
189 for (Comment comment : node.getComments()) {
190 if (comment.getCommentType() == CommentType.JSDOC &&
191 !irFactory.parsedComments.contains(comment)) {
192 irFactory.handlePossibleFileOverviewJsDoc(comment, irNode);
193 } else if (comment.getCommentType() == CommentType.BLOCK_COMMENT) {
194 irFactory.handleBlockComment(comment);
195 }
196 }
197 }
198
199 irFactory.setFileOverviewJsDoc(irNode);
200
201 return irNode;
202 }
203
204 private void setFileOverviewJsDoc(Node irNode) {
205 // Only after we've seen all @fileoverview entries, attach the
206 // last one to the root node, and copy the found license strings
207 // to that node.
208 JSDocInfo rootNodeJsDoc = rootNodeJsDocHolder.getJSDocInfo();
209 if (rootNodeJsDoc != null) {
210 irNode.setJSDocInfo(rootNodeJsDoc);
211 rootNodeJsDoc.setAssociatedNode(irNode);
212 }
213
214 if (fileOverviewInfo != null) {
215 if ((irNode.getJSDocInfo() != null) &&
216 (irNode.getJSDocInfo().getLicense() != null)) {
217 fileOverviewInfo.setLicense(irNode.getJSDocInfo().getLicense());
218 }
219 irNode.setJSDocInfo(fileOverviewInfo);
220 fileOverviewInfo.setAssociatedNode(irNode);
221 }
222 }
223
224 private Node transformBlock(AstNode node) {
225 Node irNode = transform(node);
226 if (!irNode.isBlock()) {
227 if (irNode.isEmpty()) {
228 irNode.setType(Token.BLOCK);
229 irNode.setWasEmptyNode(true);
230 } else {
231 Node newBlock = newNode(Token.BLOCK, irNode);
232 newBlock.setLineno(irNode.getLineno());
233 newBlock.setCharno(irNode.getCharno());
234 maybeSetLengthFrom(newBlock, node);
235 irNode = newBlock;
236 }
237 }
238 return irNode;
239 }
240
241 /**
242 * Check to see if the given block comment looks like it should be JSDoc.
243 */
244 private void handleBlockComment(Comment comment) {
245 String value = comment.getValue();
246 if (value.indexOf("/* @") != -1 ||
247 value.indexOf("\n * @") != -1) {
248 errorReporter.warning(
249 SUSPICIOUS_COMMENT_WARNING,
250 sourceName,
251 comment.getLineno(), "", 0);
252 }
253 }
254
255 /**
256 * @return true if the jsDocParser represents a fileoverview.
257 */
258 private boolean handlePossibleFileOverviewJsDoc(
259 JsDocInfoParser jsDocParser) {
260 if (jsDocParser.getFileOverviewJSDocInfo() != fileOverviewInfo) {
261 fileOverviewInfo = jsDocParser.getFileOverviewJSDocInfo();
262 return true;
263 }
264 return false;
265 }
266
267 private void handlePossibleFileOverviewJsDoc(Comment comment, Node irNode) {
268 JsDocInfoParser jsDocParser = createJsDocInfoParser(comment, irNode);
269 parsedComments.add(comment);
270 handlePossibleFileOverviewJsDoc(jsDocParser);
271 }
272
273 private JSDocInfo handleJsDoc(AstNode node, Node irNode) {
274 Comment comment = node.getJsDocNode();
275 if (comment != null) {
276 JsDocInfoParser jsDocParser = createJsDocInfoParser(comment, irNode);
277 parsedComments.add(comment);
278 if (!handlePossibleFileOverviewJsDoc(jsDocParser)) {
279 JSDocInfo info = jsDocParser.retrieveAndResetParsedJSDocInfo();
280 if (info != null) {
281 validateTypeAnnotations(info, node);
282 }
283 return info;
284 }
285 }
286 return null;
287 }
288
289 private void validateTypeAnnotations(JSDocInfo info, AstNode node) {
290 if (info.hasType()) {
291 boolean valid = false;
292 switch (node.getType()) {
293 // Casts are valid
294 case com.google.javascript.rhino.head.Token.LP:
295 valid = node instanceof ParenthesizedExpression;
296 break;
297 // Variable declarations are valid
298 case com.google.javascript.rhino.head.Token.VAR:
299 valid = true;
300 break;
301 // Function declarations are valid
302 case com.google.javascript.rhino.head.Token.FUNCTION:
303 FunctionNode fnNode = (FunctionNode)node;
304 valid = fnNode.getFunctionType() == FunctionNode.FUNCTION_STATEMENT;
305 break;
306 // Object literal properties and catch declarations are valid.
307 case com.google.javascript.rhino.head.Token.NAME:
308 valid = node.getParent() instanceof ObjectProperty
309 || node.getParent() instanceof CatchClause
310 || node.getParent() instanceof FunctionNode;
311 break;
312 // Object literal properties are valid
313 case com.google.javascript.rhino.head.Token.GET:
314 case com.google.javascript.rhino.head.Token.SET:
315 case com.google.javascript.rhino.head.Token.NUMBER:
316 case com.google.javascript.rhino.head.Token.STRING:
317 valid = node.getParent() instanceof ObjectProperty;
318 break;
319
320 // Property assignments are valid, if at the root of an expression.
321 case com.google.javascript.rhino.head.Token.ASSIGN:
322 if (node instanceof Assignment) {
323 valid = isExprStmt(node.getParent())
324 && isPropAccess(((Assignment)node).getLeft());
325 }
326 break;
327
328 // Property definitions are valid, if at the root of an expression.
329 case com.google.javascript.rhino.head.Token.GETPROP:
330 case com.google.javascript.rhino.head.Token.GETELEM:
331 valid = isExprStmt(node.getParent());
332 break;
333 }
334 if (!valid) {
335 errorReporter.warning(MISPLACED_TYPE_ANNOTATION,
336 sourceName,
337 node.getLineno(), "", 0);
338 }
339 }
340 }
341
342 private boolean isPropAccess(AstNode node) {
343 return node.getType() == com.google.javascript.rhino.head.Token.GETPROP
344 || node.getType() == com.google.javascript.rhino.head.Token.GETELEM;
345 }
346
347 private boolean isExprStmt(AstNode node) {
348 return node.getType() == com.google.javascript.rhino.head.Token.EXPR_RESULT
349 || node.getType() == com.google.javascript.rhino.head.Token.EXPR_VOID;
350 }
351
352 private Node transform(AstNode node) {
353 Node irNode = justTransform(node);
354 JSDocInfo jsDocInfo = handleJsDoc(node, irNode);
355 if (jsDocInfo != null) {
356 irNode = maybeInjectCastNode(node, jsDocInfo, irNode);
357 irNode.setJSDocInfo(jsDocInfo);
358 }
359 setSourceInfo(irNode, node);
360 return irNode;
361 }
362
363 private Node maybeInjectCastNode(AstNode node, JSDocInfo info, Node irNode) {
364 if (node.getType() == com.google.javascript.rhino.head.Token.LP
365 && node instanceof ParenthesizedExpression
366 && info.hasType()
367 // TODO(johnlenz): for now, attach object literal type directly.
368 && !irNode.isObjectLit()) {
369 irNode = newNode(Token.CAST, irNode);
370 }
371 return irNode;
372 }
373
374 /**
375 * Parameter NAMEs are special, because they can have inline type docs
376 * attached.
377 *
378 * function f(/** string &#42;/ x) {}
379 * annotates 'x' as a string.
380 *
381 * @see http://code.google.com/p/jsdoc-toolkit/wiki/InlineDocs
382 */
383 private Node transformParameter(AstNode node) {
384 Node irNode = justTransform(node);
385 Comment comment = node.getJsDocNode();
386 if (comment != null) {
387 JSDocInfo info = parseInlineTypeDoc(comment, irNode);
388 if (info != null) {
389 irNode.setJSDocInfo(info);
390 }
391 }
392 setSourceInfo(irNode, node);
393 return irNode;
394 }
395
396 private Node transformNameAsString(Name node) {
397 Node irNode = transformDispatcher.processName(node, true);
398 JSDocInfo jsDocInfo = handleJsDoc(node, irNode);
399 if (jsDocInfo != null) {
400 irNode.setJSDocInfo(jsDocInfo);
401 }
402 setSourceInfo(irNode, node);
403 return irNode;
404 }
405
406 private Node transformNumberAsString(NumberLiteral literalNode) {
407 Node irNode = newStringNode(getStringValue(literalNode.getNumber()));
408 JSDocInfo jsDocInfo = handleJsDoc(literalNode, irNode);
409 if (jsDocInfo != null) {
410 irNode.setJSDocInfo(jsDocInfo);
411 }
412 setSourceInfo(irNode, literalNode);
413 return irNode;
414 }
415
416 private static String getStringValue(double value) {
417 long longValue = (long) value;
418
419 // Return "1" instead of "1.0"
420 if (longValue == value) {
421 return Long.toString(longValue);
422 } else {
423 return Double.toString(value);
424 }
425 }
426
427 private void setSourceInfo(Node irNode, AstNode node) {
428 if (irNode.getLineno() == -1) {
429 // If we didn't already set the line, then set it now. This avoids
430 // cases like ParenthesizedExpression where we just return a previous
431 // node, but don't want the new node to get its parent's line number.
432 int lineno = node.getLineno();
433 irNode.setLineno(lineno);
434 int charno = position2charno(node.getAbsolutePosition());
435 irNode.setCharno(charno);
436 maybeSetLengthFrom(irNode, node);
437 }
438 }
439
440 /**
441 * Creates a JsDocInfoParser and parses the JsDoc string.
442 *
443 * Used both for handling individual JSDoc comments and for handling
444 * file-level JSDoc comments (@fileoverview and @license).
445 *
446 * @param node The JsDoc Comment node to parse.
447 * @param irNode
448 * @return A JsDocInfoParser. Will contain either fileoverview JsDoc, or
449 * normal JsDoc, or no JsDoc (if the method parses to the wrong level).
450 */
451 private JsDocInfoParser createJsDocInfoParser(Comment node, Node irNode) {
452 String comment = node.getValue();
453 int lineno = node.getLineno();
454 int position = node.getAbsolutePosition();
455
456 // The JsDocInfoParser expects the comment without the initial '/**'.
457 int numOpeningChars = 3;
458 JsDocInfoParser jsdocParser =
459 new JsDocInfoParser(
460 new JsDocTokenStream(comment.substring(numOpeningChars),
461 lineno,
462 position2charno(position) + numOpeningChars),
463 node,
464 irNode,
465 config,
466 errorReporter);
467 jsdocParser.setFileLevelJsDocBuilder(fileLevelJsDocBuilder);
468 jsdocParser.setFileOverviewJSDocInfo(fileOverviewInfo);
469 jsdocParser.parse();
470 return jsdocParser;
471 }
472
473 /**
474 * Parses inline type info.
475 */
476 private JSDocInfo parseInlineTypeDoc(Comment node, Node irNode) {
477 String comment = node.getValue();
478 int lineno = node.getLineno();
479 int position = node.getAbsolutePosition();
480
481 // The JsDocInfoParser expects the comment without the initial '/**'.
482 int numOpeningChars = 3;
483 JsDocInfoParser parser =
484 new JsDocInfoParser(
485 new JsDocTokenStream(comment.substring(numOpeningChars),
486 lineno,
487 position2charno(position) + numOpeningChars),
488 node,
489 irNode,
490 config,
491 errorReporter);
492 return parser.parseInlineTypeDoc();
493 }
494
495 // Set the length on the node if we're in IDE mode.
496 private void maybeSetLengthFrom(Node node, AstNode source) {
497 if (config.isIdeMode) {
498 node.setLength(source.getLength());
499 }
500 }
501
502 private int position2charno(int position) {
503 int lineIndex = sourceString.lastIndexOf('\n', position);
504 if (lineIndex == -1) {
505 return position;
506 } else {
507 // Subtract one for initial position being 0.
508 return position - lineIndex - 1;
509 }
510 }
511
512 private Node justTransform(AstNode node) {
513 return transformDispatcher.process(node);
514 }
515
516 private class TransformDispatcher extends TypeSafeDispatcher<Node> {
517 private Node processGeneric(
518 com.google.javascript.rhino.head.Node n) {
519 Node node = newNode(transformTokenType(n.getType()));
520 for (com.google.javascript.rhino.head.Node child : n) {
521 node.addChildToBack(transform((AstNode)child));
522 }
523 return node;
524 }
525
526 /**
527 * Transforms the given node and then sets its type to Token.STRING if it
528 * was Token.NAME. If its type was already Token.STRING, then quotes it.
529 * Used for properties, as the old AST uses String tokens, while the new one
530 * uses Name tokens for unquoted strings. For example, in
531 * var o = {'a' : 1, b: 2};
532 * the string 'a' is quoted, while the name b is turned into a string, but
533 * unquoted.
534 */
535 private Node transformAsString(AstNode n) {
536 Node ret;
537 if (n instanceof Name) {
538 ret = transformNameAsString((Name)n);
539 } else if (n instanceof NumberLiteral) {
540 ret = transformNumberAsString((NumberLiteral)n);
541 ret.putBooleanProp(Node.QUOTED_PROP, true);
542 } else {
543 ret = transform(n);
544 ret.putBooleanProp(Node.QUOTED_PROP, true);
545 }
546 Preconditions.checkState(ret.isString());
547 return ret;
548 }
549
550 @Override
551 Node processArrayLiteral(ArrayLiteral literalNode) {
552 if (literalNode.isDestructuring()) {
553 reportDestructuringAssign(literalNode);
554 }
555
556 Node node = newNode(Token.ARRAYLIT);
557 for (AstNode child : literalNode.getElements()) {
558 Node c = transform(child);
559 node.addChildToBack(c);
560 }
561 return node;
562 }
563
564 @Override
565 Node processAssignment(Assignment assignmentNode) {
566 Node assign = processInfixExpression(assignmentNode);
567 Node target = assign.getFirstChild();
568 if (!validAssignmentTarget(target)) {
569 errorReporter.error(
570 "invalid assignment target",
571 sourceName,
572 target.getLineno(), "", 0);
573 }
574 return assign;
575 }
576
577 @Override
578 Node processAstRoot(AstRoot rootNode) {
579 Node node = newNode(Token.SCRIPT);
580 for (com.google.javascript.rhino.head.Node child : rootNode) {
581 node.addChildToBack(transform((AstNode)child));
582 }
583 parseDirectives(node);
584 return node;
585 }
586
587 /**
588 * Parse the directives, encode them in the AST, and remove their nodes.
589 *
590 * For information on ES5 directives, see section 14.1 of
591 * ECMA-262, Edition 5.
592 *
593 * It would be nice if Rhino would eventually take care of this for
594 * us, but right now their directive-processing is a one-off.
595 */
596 private void parseDirectives(Node node) {
597 // Remove all the directives, and encode them in the AST.
598 Set<String> directives = null;
599 while (isDirective(node.getFirstChild())) {
600 String directive = node.removeFirstChild().getFirstChild().getString();
601 if (directives == null) {
602 directives = Sets.newHashSet(directive);
603 } else {
604 directives.add(directive);
605 }
606 }
607
608 if (directives != null) {
609 node.setDirectives(directives);
610 }
611 }
612
613 private boolean isDirective(Node n) {
614 if (n == null) return false;
615
616 int nType = n.getType();
617 return nType == Token.EXPR_RESULT &&
618 n.getFirstChild().isString() &&
619 ALLOWED_DIRECTIVES.contains(n.getFirstChild().getString());
620 }
621
622 @Override
623 Node processBlock(Block blockNode) {
624 return processGeneric(blockNode);
625 }
626
627 @Override
628 Node processBreakStatement(BreakStatement statementNode) {
629 Node node = newNode(Token.BREAK);
630 if (statementNode.getBreakLabel() != null) {
631 Node labelName = transform(statementNode.getBreakLabel());
632 // Change the NAME to LABEL_NAME
633 labelName.setType(Token.LABEL_NAME);
634 node.addChildToBack(labelName);
635 }
636 return node;
637 }
638
639 @Override
640 Node processCatchClause(CatchClause clauseNode) {
641 AstNode catchVar = clauseNode.getVarName();
642 Node node = newNode(Token.CATCH, transform(catchVar));
643 if (clauseNode.getCatchCondition() != null) {
644 errorReporter.error(
645 "Catch clauses are not supported",
646 sourceName,
647 clauseNode.getCatchCondition().getLineno(), "", 0);
648 }
649 node.addChildToBack(transformBlock(clauseNode.getBody()));
650 return node;
651 }
652
653 @Override
654 Node processConditionalExpression(ConditionalExpression exprNode) {
655 return newNode(
656 Token.HOOK,
657 transform(exprNode.getTestExpression()),
658 transform(exprNode.getTrueExpression()),
659 transform(exprNode.getFalseExpression()));
660 }
661
662 @Override
663 Node processContinueStatement(ContinueStatement statementNode) {
664 Node node = newNode(Token.CONTINUE);
665 if (statementNode.getLabel() != null) {
666 Node labelName = transform(statementNode.getLabel());
667 // Change the NAME to LABEL_NAME
668 labelName.setType(Token.LABEL_NAME);
669 node.addChildToBack(labelName);
670 }
671 return node;
672 }
673
674 @Override
675 Node processDoLoop(DoLoop loopNode) {
676 return newNode(
677 Token.DO,
678 transformBlock(loopNode.getBody()),
679 transform(loopNode.getCondition()));
680 }
681
682 @Override
683 Node processElementGet(ElementGet getNode) {
684 return newNode(
685 Token.GETELEM,
686 transform(getNode.getTarget()),
687 transform(getNode.getElement()));
688 }
689
690 @Override
691 Node processEmptyExpression(EmptyExpression exprNode) {
692 Node node = newNode(Token.EMPTY);
693 return node;
694 }
695
696 @Override
697 Node processEmptyStatement(EmptyStatement exprNode) {
698 Node node = newNode(Token.EMPTY);
699 return node;
700 }
701
702 @Override
703 Node processExpressionStatement(ExpressionStatement statementNode) {
704 Node node = newNode(transformTokenType(statementNode.getType()));
705 node.addChildToBack(transform(statementNode.getExpression()));
706 return node;
707 }
708
709 @Override
710 Node processForInLoop(ForInLoop loopNode) {
711 if (loopNode.isForEach()) {
712 errorReporter.error(
713 "unsupported language extension: for each",
714 sourceName,
715 loopNode.getLineno(), "", 0);
716
717 // Return the bare minimum to put the AST in a valid state.
718 return newNode(Token.EXPR_RESULT, Node.newNumber(0));
719 }
720 return newNode(
721 Token.FOR,
722 transform(loopNode.getIterator()),
723 transform(loopNode.getIteratedObject()),
724 transformBlock(loopNode.getBody()));
725 }
726
727 @Override
728 Node processForLoop(ForLoop loopNode) {
729 Node node = newNode(
730 Token.FOR,
731 transform(loopNode.getInitializer()),
732 transform(loopNode.getCondition()),
733 transform(loopNode.getIncrement()));
734 node.addChildToBack(transformBlock(loopNode.getBody()));
735 return node;
736 }
737
738 @Override
739 Node processFunctionCall(FunctionCall callNode) {
740 Node node = newNode(transformTokenType(callNode.getType()),
741 transform(callNode.getTarget()));
742 for (AstNode child : callNode.getArguments()) {
743 node.addChildToBack(transform(child));
744 }
745
746 node.setLineno(node.getFirstChild().getLineno());
747 node.setCharno(node.getFirstChild().getCharno());
748 maybeSetLengthFrom(node, callNode);
749 return node;
750 }
751
752 @Override
753 Node processFunctionNode(FunctionNode functionNode) {
754 Name name = functionNode.getFunctionName();
755 Boolean isUnnamedFunction = false;
756 if (name == null) {
757 int functionType = functionNode.getFunctionType();
758 if (functionType != FunctionNode.FUNCTION_EXPRESSION) {
759 errorReporter.error(
760 "unnamed function statement",
761 sourceName,
762 functionNode.getLineno(), "", 0);
763
764 // Return the bare minimum to put the AST in a valid state.
765 return newNode(Token.EXPR_RESULT, Node.newNumber(0));
766 }
767 name = new Name();
768 name.setIdentifier("");
769 isUnnamedFunction = true;
770 }
771 Node node = newNode(Token.FUNCTION);
772 Node newName = transform(name);
773 if (isUnnamedFunction) {
774 // Old Rhino tagged the empty name node with the line number of the
775 // declaration.
776 newName.setLineno(functionNode.getLineno());
777 // TODO(bowdidge) Mark line number of paren correctly.
778 // Same problem as below - the left paren might not be on the
779 // same line as the function keyword.
780 int lpColumn = functionNode.getAbsolutePosition() +
781 functionNode.getLp();
782 newName.setCharno(position2charno(lpColumn));
783 maybeSetLengthFrom(newName, name);
784 }
785
786 node.addChildToBack(newName);
787 Node lp = newNode(Token.PARAM_LIST);
788 // The left paren's complicated because it's not represented by an
789 // AstNode, so there's nothing that has the actual line number that it
790 // appeared on. We know the paren has to appear on the same line as the
791 // function name (or else a semicolon will be inserted.) If there's no
792 // function name, assume the paren was on the same line as the function.
793 // TODO(bowdidge): Mark line number of paren correctly.
794 Name fnName = functionNode.getFunctionName();
795 if (fnName != null) {
796 lp.setLineno(fnName.getLineno());
797 } else {
798 lp.setLineno(functionNode.getLineno());
799 }
800 int lparenCharno = functionNode.getLp() +
801 functionNode.getAbsolutePosition();
802
803 lp.setCharno(position2charno(lparenCharno));
804 for (AstNode param : functionNode.getParams()) {
805 Node paramNode = transformParameter(param);
806 // When in ideMode Rhino can generate a param list with only a single
807 // ErrorNode. This is transformed into an EMPTY node. Drop this node in
808 // ideMode to keep the AST in a valid state.
809 if (paramNode.isName()) {
810 lp.addChildToBack(paramNode);
811 } else {
812 // We expect this in ideMode or when there is an error handling
813 // destructuring parameter assignments which aren't supported
814 // (an error has already been reported).
815 Preconditions.checkState(
816 config.isIdeMode
817 || paramNode.isObjectLit()
818 || paramNode.isArrayLit());
819 }
820 }
821 node.addChildToBack(lp);
822
823 Node bodyNode = transform(functionNode.getBody());
824 if (!bodyNode.isBlock()) {
825 // When in ideMode Rhino tries to parse some constructs the compiler
826 // doesn't support, repair it here. see Rhino's
827 // Parser#parseFunctionBodyExpr.
828 Preconditions.checkState(config.isIdeMode);
829 bodyNode = IR.block();
830 }
831 parseDirectives(bodyNode);
832 node.addChildToBack(bodyNode);
833 return node;
834 }
835
836 @Override
837 Node processIfStatement(IfStatement statementNode) {
838 Node node = newNode(Token.IF);
839 node.addChildToBack(transform(statementNode.getCondition()));
840 node.addChildToBack(transformBlock(statementNode.getThenPart()));
841 if (statementNode.getElsePart() != null) {
842 node.addChildToBack(transformBlock(statementNode.getElsePart()));
843 }
844 return node;
845 }
846
847 @Override
848 Node processInfixExpression(InfixExpression exprNode) {
849 Node n = newNode(
850 transformTokenType(exprNode.getType()),
851 transform(exprNode.getLeft()),
852 transform(exprNode.getRight()));
853 n.setLineno(exprNode.getLineno());
854 n.setCharno(position2charno(exprNode.getAbsolutePosition()));
855 maybeSetLengthFrom(n, exprNode);
856 return n;
857 }
858
859 @Override
860 Node processKeywordLiteral(KeywordLiteral literalNode) {
861 return newNode(transformTokenType(literalNode.getType()));
862 }
863
864 @Override
865 Node processLabel(Label labelNode) {
866 return newStringNode(Token.LABEL_NAME, labelNode.getName());
867 }
868
869 @Override
870 Node processLabeledStatement(LabeledStatement statementNode) {
871 Node node = newNode(Token.LABEL);
872 Node prev = null;
873 Node cur = node;
874 for (Label label : statementNode.getLabels()) {
875 if (prev != null) {
876 prev.addChildToBack(cur);
877 }
878 cur.addChildToBack(transform(label));
879
880 cur.setLineno(label.getLineno());
881 maybeSetLengthFrom(cur, label);
882
883 int clauseAbsolutePosition =
884 position2charno(label.getAbsolutePosition());
885 cur.setCharno(clauseAbsolutePosition);
886
887 prev = cur;
888 cur = newNode(Token.LABEL);
889 }
890 prev.addChildToBack(transform(statementNode.getStatement()));
891 return node;
892 }
893
894 @Override
895 Node processName(Name nameNode) {
896 return processName(nameNode, false);
897 }
898
899 Node processName(Name nameNode, boolean asString) {
900 if (asString) {
901 return newStringNode(Token.STRING, nameNode.getIdentifier());
902 } else {
903 if (isReservedKeyword(nameNode.getIdentifier())) {
904 errorReporter.error(
905 "identifier is a reserved word",
906 sourceName,
907 nameNode.getLineno(), "", 0);
908 }
909 return newStringNode(Token.NAME, nameNode.getIdentifier());
910 }
911 }
912
913 /**
914 * @return Whether the
915 */
916 private boolean isReservedKeyword(String identifier) {
917 return reservedKeywords != null && reservedKeywords.contains(identifier);
918 }
919
920 @Override
921 Node processNewExpression(NewExpression exprNode) {
922 Node node = newNode(
923 transformTokenType(exprNode.getType()),
924 transform(exprNode.getTarget()));
925 for (AstNode child : exprNode.getArguments()) {
926 node.addChildToBack(transform(child));
927 }
928 node.setLineno(exprNode.getLineno());
929 node.setCharno(position2charno(exprNode.getAbsolutePosition()));
930 maybeSetLengthFrom(node, exprNode);
931 return node;
932 }
933
934 @Override
935 Node processNumberLiteral(NumberLiteral literalNode) {
936 return newNumberNode(literalNode.getNumber());
937 }
938
939 @Override
940 Node processObjectLiteral(ObjectLiteral literalNode) {
941 if (literalNode.isDestructuring()) {
942 reportDestructuringAssign(literalNode);
943 }
944
945 Node node = newNode(Token.OBJECTLIT);
946 for (ObjectProperty el : literalNode.getElements()) {
947 if (config.languageMode == LanguageMode.ECMASCRIPT3) {
948 if (el.isGetter()) {
949 reportGetter(el);
950 continue;
951 } else if (el.isSetter()) {
952 reportSetter(el);
953 continue;
954 }
955 }
956
957 Node key = transformAsString(el.getLeft());
958 key.setType(Token.STRING_KEY);
959
960 Node value = transform(el.getRight());
961 if (el.isGetter()) {
962 key.setType(Token.GETTER_DEF);
963 Preconditions.checkState(value.isFunction());
964 if (getFnParamNode(value).hasChildren()) {
965 reportGetterParam(el.getLeft());
966 }
967 } else if (el.isSetter()) {
968 key.setType(Token.SETTER_DEF);
969 Preconditions.checkState(value.isFunction());
970 if (!getFnParamNode(value).hasOneChild()) {
971 reportSetterParam(el.getLeft());
972 }
973 }
974 key.addChildToFront(value);
975 node.addChildToBack(key);
976 }
977 return node;
978 }
979
980 /**
981 * @param fnNode The function.
982 * @return The Node containing the Function parameters.
983 */
984 Node getFnParamNode(Node fnNode) {
985 // Function NODE: [ FUNCTION -> NAME, LP -> ARG1, ARG2, ... ]
986 Preconditions.checkArgument(fnNode.isFunction());
987 return fnNode.getFirstChild().getNext();
988 }
989
990 @Override
991 Node processObjectProperty(ObjectProperty propertyNode) {
992 return processInfixExpression(propertyNode);
993 }
994
995 @Override
996 Node processParenthesizedExpression(ParenthesizedExpression exprNode) {
997 Node node = transform(exprNode.getExpression());
998 return node;
999 }
1000
1001 @Override
1002 Node processPropertyGet(PropertyGet getNode) {
1003 Node leftChild = transform(getNode.getTarget());
1004 Node newNode = newNode(
1005 Token.GETPROP, leftChild, transformAsString(getNode.getProperty()));
1006 newNode.setLineno(leftChild.getLineno());
1007 newNode.setCharno(leftChild.getCharno());
1008 maybeSetLengthFrom(newNode, getNode);
1009 return newNode;
1010 }
1011
1012 @Override
1013 Node processRegExpLiteral(RegExpLiteral literalNode) {
1014 Node literalStringNode = newStringNode(literalNode.getValue());
1015 // assume it's on the same line.
1016 literalStringNode.setLineno(literalNode.getLineno());
1017 maybeSetLengthFrom(literalStringNode, literalNode);
1018 Node node = newNode(Token.REGEXP, literalStringNode);
1019 String flags = literalNode.getFlags();
1020 if (flags != null && !flags.isEmpty()) {
1021 Node flagsNode = newStringNode(flags);
1022 // Assume the flags are on the same line as the literal node.
1023 flagsNode.setLineno(literalNode.getLineno());
1024 maybeSetLengthFrom(flagsNode, literalNode);
1025 node.addChildToBack(flagsNode);
1026 }
1027 return node;
1028 }
1029
1030 @Override
1031 Node processReturnStatement(ReturnStatement statementNode) {
1032 Node node = newNode(Token.RETURN);
1033 if (statementNode.getReturnValue() != null) {
1034 node.addChildToBack(transform(statementNode.getReturnValue()));
1035 }
1036 return node;
1037 }
1038
1039 @Override
1040 Node processScope(Scope scopeNode) {
1041 return processGeneric(scopeNode);
1042 }
1043
1044 @Override
1045 Node processStringLiteral(StringLiteral literalNode) {
1046 String value = literalNode.getValue();
1047 Node n = newStringNode(value);
1048 if (value.indexOf('\u000B') != -1) {
1049 // NOTE(nicksantos): In JavaScript, there are 3 ways to
1050 // represent a vertical tab: \v, \x0B, \u000B.
1051 // The \v notation was added later, and is not understood
1052 // on IE. So we need to preserve it as-is. This is really
1053 // obnoxious, because we do not have a good way to represent
1054 // how the original string was encoded without making the
1055 // representation of strings much more complicated.
1056 //
1057 // To handle this, we look at the original source test, and
1058 // mark the string as \v-encoded or not. If a string is
1059 // \v encoded, then all the vertical tabs in that string
1060 // will be encoded with a \v.
1061 int start = literalNode.getAbsolutePosition();
1062 int end = start + literalNode.getLength();
1063 if (start < sourceString.length() &&
1064 (sourceString.substring(
1065 start, Math.min(sourceString.length(), end))
1066 .indexOf("\\v") != -1)) {
1067 n.putBooleanProp(Node.SLASH_V, true);
1068 }
1069 }
1070 return n;
1071 }
1072
1073 @Override
1074 Node processSwitchCase(SwitchCase caseNode) {
1075 Node node;
1076 if (caseNode.isDefault()) {
1077 node = newNode(Token.DEFAULT_CASE);
1078 } else {
1079 AstNode expr = caseNode.getExpression();
1080 node = newNode(Token.CASE, transform(expr));
1081 }
1082 Node block = newNode(Token.BLOCK);
1083 block.putBooleanProp(Node.SYNTHETIC_BLOCK_PROP, true);
1084 block.setLineno(caseNode.getLineno());
1085 block.setCharno(position2charno(caseNode.getAbsolutePosition()));
1086 maybeSetLengthFrom(block, caseNode);
1087 if (caseNode.getStatements() != null) {
1088 for (AstNode child : caseNode.getStatements()) {
1089 block.addChildToBack(transform(child));
1090 }
1091 }
1092 node.addChildToBack(block);
1093 return node;
1094 }
1095
1096 @Override
1097 Node processSwitchStatement(SwitchStatement statementNode) {
1098 Node node = newNode(Token.SWITCH,
1099 transform(statementNode.getExpression()));
1100 for (AstNode child : statementNode.getCases()) {
1101 node.addChildToBack(transform(child));
1102 }
1103 return node;
1104 }
1105
1106 @Override
1107 Node processThrowStatement(ThrowStatement statementNode) {
1108 return newNode(Token.THROW,
1109 transform(statementNode.getExpression()));
1110 }
1111
1112 @Override
1113 Node processTryStatement(TryStatement statementNode) {
1114 Node node = newNode(Token.TRY,
1115 transformBlock(statementNode.getTryBlock()));
1116 Node block = newNode(Token.BLOCK);
1117 boolean lineSet = false;
1118
1119 for (CatchClause cc : statementNode.getCatchClauses()) {
1120 // Mark the enclosing block at the same line as the first catch
1121 // clause.
1122 if (lineSet == false) {
1123 block.setLineno(cc.getLineno());
1124 maybeSetLengthFrom(block, cc);
1125 lineSet = true;
1126 }
1127 block.addChildToBack(transform(cc));
1128 }
1129 node.addChildToBack(block);
1130
1131 AstNode finallyBlock = statementNode.getFinallyBlock();
1132 if (finallyBlock != null) {
1133 node.addChildToBack(transformBlock(finallyBlock));
1134 }
1135
1136 // If we didn't set the line on the catch clause, then
1137 // we've got an empty catch clause. Set its line to be the same
1138 // as the finally block (to match Old Rhino's behavior.)
1139 if ((lineSet == false) && (finallyBlock != null)) {
1140 block.setLineno(finallyBlock.getLineno());
1141 maybeSetLengthFrom(block, finallyBlock);
1142 }
1143
1144 return node;
1145 }
1146
1147 @Override
1148 Node processUnaryExpression(UnaryExpression exprNode) {
1149 int type = transformTokenType(exprNode.getType());
1150 Node operand = transform(exprNode.getOperand());
1151 if (type == Token.NEG && operand.isNumber()) {
1152 operand.setDouble(-operand.getDouble());
1153 return operand;
1154 } else {
1155 if (type == Token.DELPROP &&
1156 !(operand.isGetProp() ||
1157 operand.isGetElem() ||
1158 operand.isName())) {
1159 String msg =
1160 "Invalid delete operand. Only properties can be deleted.";
1161 errorReporter.error(
1162 msg,
1163 sourceName,
1164 operand.getLineno(), "", 0);
1165 } else if (type == Token.INC || type == Token.DEC) {
1166 if (!validAssignmentTarget(operand)) {
1167 String msg = (type == Token.INC)
1168 ? "invalid increment target"
1169 : "invalid decrement target";
1170 errorReporter.error(
1171 msg,
1172 sourceName,
1173 operand.getLineno(), "", 0);
1174 }
1175 }
1176
1177 Node node = newNode(type, operand);
1178 if (exprNode.isPostfix()) {
1179 node.putBooleanProp(Node.INCRDECR_PROP, true);
1180 }
1181 return node;
1182 }
1183 }
1184
1185 private boolean validAssignmentTarget(Node target) {
1186 switch (target.getType()) {
1187 case Token.CAST: // CAST is a bit weird, but syntactically valid.
1188 case Token.NAME:
1189 case Token.GETPROP:
1190 case Token.GETELEM:
1191 return true;
1192 }
1193 return false;
1194 }
1195
1196 @Override
1197 Node processVariableDeclaration(VariableDeclaration declarationNode) {
1198 if (!config.acceptConstKeyword && declarationNode.getType() ==
1199 com.google.javascript.rhino.head.Token.CONST) {
1200 processIllegalToken(declarationNode);
1201 }
1202
1203 Node node = newNode(Token.VAR);
1204 for (VariableInitializer child : declarationNode.getVariables()) {
1205 node.addChildToBack(transform(child));
1206 }
1207 return node;
1208 }
1209
1210 @Override
1211 Node processVariableInitializer(VariableInitializer initializerNode) {
1212 Node node = transform(initializerNode.getTarget());
1213 if (initializerNode.getInitializer() != null) {
1214 Node initalizer = transform(initializerNode.getInitializer());
1215 node.addChildToBack(initalizer);
1216 }
1217 return node;
1218 }
1219
1220 @Override
1221 Node processWhileLoop(WhileLoop loopNode) {
1222 return newNode(
1223 Token.WHILE,
1224 transform(loopNode.getCondition()),
1225 transformBlock(loopNode.getBody()));
1226 }
1227
1228 @Override
1229 Node processWithStatement(WithStatement statementNode) {
1230 return newNode(
1231 Token.WITH,
1232 transform(statementNode.getExpression()),
1233 transformBlock(statementNode.getStatement()));
1234 }
1235
1236 @Override
1237 Node processIllegalToken(AstNode node) {
1238 errorReporter.error(
1239 "Unsupported syntax: " +
1240 com.google.javascript.rhino.head.Token.typeToName(
1241 node.getType()),
1242 sourceName,
1243 node.getLineno(), "", 0);
1244 return newNode(Token.EMPTY);
1245 }
1246
1247 void reportDestructuringAssign(AstNode node) {
1248 errorReporter.error(
1249 "destructuring assignment forbidden",
1250 sourceName,
1251 node.getLineno(), "", 0);
1252 }
1253
1254 void reportGetter(AstNode node) {
1255 errorReporter.error(
1256 GETTER_ERROR_MESSAGE,
1257 sourceName,
1258 node.getLineno(), "", 0);
1259 }
1260
1261 void reportSetter(AstNode node) {
1262 errorReporter.error(
1263 SETTER_ERROR_MESSAGE,
1264 sourceName,
1265 node.getLineno(), "", 0);
1266 }
1267
1268 void reportGetterParam(AstNode node) {
1269 errorReporter.error(
1270 "getters may not have parameters",
1271 sourceName,
1272 node.getLineno(), "", 0);
1273 }
1274
1275 void reportSetterParam(AstNode node) {
1276 errorReporter.error(
1277 "setters must have exactly one parameter",
1278 sourceName,
1279 node.getLineno(), "", 0);
1280 }
1281 }
1282
1283 private static int transformTokenType(int token) {
1284 switch (token) {
1285 case com.google.javascript.rhino.head.Token.RETURN:
1286 return Token.RETURN;
1287 case com.google.javascript.rhino.head.Token.BITOR:
1288 return Token.BITOR;
1289 case com.google.javascript.rhino.head.Token.BITXOR:
1290 return Token.BITXOR;
1291 case com.google.javascript.rhino.head.Token.BITAND:
1292 return Token.BITAND;
1293 case com.google.javascript.rhino.head.Token.EQ:
1294 return Token.EQ;
1295 case com.google.javascript.rhino.head.Token.NE:
1296 return Token.NE;
1297 case com.google.javascript.rhino.head.Token.LT:
1298 return Token.LT;
1299 case com.google.javascript.rhino.head.Token.LE:
1300 return Token.LE;
1301 case com.google.javascript.rhino.head.Token.GT:
1302 return Token.GT;
1303 case com.google.javascript.rhino.head.Token.GE:
1304 return Token.GE;
1305 case com.google.javascript.rhino.head.Token.LSH:
1306 return Token.LSH;
1307 case com.google.javascript.rhino.head.Token.RSH:
1308 return Token.RSH;
1309 case com.google.javascript.rhino.head.Token.URSH:
1310 return Token.URSH;
1311 case com.google.javascript.rhino.head.Token.ADD:
1312 return Token.ADD;
1313 case com.google.javascript.rhino.head.Token.SUB:
1314 return Token.SUB;
1315 case com.google.javascript.rhino.head.Token.MUL:
1316 return Token.MUL;
1317 case com.google.javascript.rhino.head.Token.DIV:
1318 return Token.DIV;
1319 case com.google.javascript.rhino.head.Token.MOD:
1320 return Token.MOD;
1321 case com.google.javascript.rhino.head.Token.NOT:
1322 return Token.NOT;
1323 case com.google.javascript.rhino.head.Token.BITNOT:
1324 return Token.BITNOT;
1325 case com.google.javascript.rhino.head.Token.POS:
1326 return Token.POS;
1327 case com.google.javascript.rhino.head.Token.NEG:
1328 return Token.NEG;
1329 case com.google.javascript.rhino.head.Token.NEW:
1330 return Token.NEW;
1331 case com.google.javascript.rhino.head.Token.DELPROP:
1332 return Token.DELPROP;
1333 case com.google.javascript.rhino.head.Token.TYPEOF:
1334 return Token.TYPEOF;
1335 case com.google.javascript.rhino.head.Token.GETPROP:
1336 return Token.GETPROP;
1337 case com.google.javascript.rhino.head.Token.GETELEM:
1338 return Token.GETELEM;
1339 case com.google.javascript.rhino.head.Token.CALL:
1340 return Token.CALL;
1341 case com.google.javascript.rhino.head.Token.NAME:
1342 return Token.NAME;
1343 case com.google.javascript.rhino.head.Token.NUMBER:
1344 return Token.NUMBER;
1345 case com.google.javascript.rhino.head.Token.STRING:
1346 return Token.STRING;
1347 case com.google.javascript.rhino.head.Token.NULL:
1348 return Token.NULL;
1349 case com.google.javascript.rhino.head.Token.THIS:
1350 return Token.THIS;
1351 case com.google.javascript.rhino.head.Token.FALSE:
1352 return Token.FALSE;
1353 case com.google.javascript.rhino.head.Token.TRUE:
1354 return Token.TRUE;
1355 case com.google.javascript.rhino.head.Token.SHEQ:
1356 return Token.SHEQ;
1357 case com.google.javascript.rhino.head.Token.SHNE:
1358 return Token.SHNE;
1359 case com.google.javascript.rhino.head.Token.REGEXP:
1360 return Token.REGEXP;
1361 case com.google.javascript.rhino.head.Token.THROW:
1362 return Token.THROW;
1363 case com.google.javascript.rhino.head.Token.IN:
1364 return Token.IN;
1365 case com.google.javascript.rhino.head.Token.INSTANCEOF:
1366 return Token.INSTANCEOF;
1367 case com.google.javascript.rhino.head.Token.ARRAYLIT:
1368 return Token.ARRAYLIT;
1369 case com.google.javascript.rhino.head.Token.OBJECTLIT:
1370 return Token.OBJECTLIT;
1371 case com.google.javascript.rhino.head.Token.TRY:
1372 return Token.TRY;
1373 // The LP represents a parameter list
1374 case com.google.javascript.rhino.head.Token.LP:
1375 return Token.PARAM_LIST;
1376 case com.google.javascript.rhino.head.Token.COMMA:
1377 return Token.COMMA;
1378 case com.google.javascript.rhino.head.Token.ASSIGN:
1379 return Token.ASSIGN;
1380 case com.google.javascript.rhino.head.Token.ASSIGN_BITOR:
1381 return Token.ASSIGN_BITOR;
1382 case com.google.javascript.rhino.head.Token.ASSIGN_BITXOR:
1383 return Token.ASSIGN_BITXOR;
1384 case com.google.javascript.rhino.head.Token.ASSIGN_BITAND:
1385 return Token.ASSIGN_BITAND;
1386 case com.google.javascript.rhino.head.Token.ASSIGN_LSH:
1387 return Token.ASSIGN_LSH;
1388 case com.google.javascript.rhino.head.Token.ASSIGN_RSH:
1389 return Token.ASSIGN_RSH;
1390 case com.google.javascript.rhino.head.Token.ASSIGN_URSH:
1391 return Token.ASSIGN_URSH;
1392 case com.google.javascript.rhino.head.Token.ASSIGN_ADD:
1393 return Token.ASSIGN_ADD;
1394 case com.google.javascript.rhino.head.Token.ASSIGN_SUB:
1395 return Token.ASSIGN_SUB;
1396 case com.google.javascript.rhino.head.Token.ASSIGN_MUL:
1397 return Token.ASSIGN_MUL;
1398 case com.google.javascript.rhino.head.Token.ASSIGN_DIV:
1399 return Token.ASSIGN_DIV;
1400 case com.google.javascript.rhino.head.Token.ASSIGN_MOD:
1401 return Token.ASSIGN_MOD;
1402 case com.google.javascript.rhino.head.Token.HOOK:
1403 return Token.HOOK;
1404 case com.google.javascript.rhino.head.Token.OR:
1405 return Token.OR;
1406 case com.google.javascript.rhino.head.Token.AND:
1407 return Token.AND;
1408 case com.google.javascript.rhino.head.Token.INC:
1409 return Token.INC;
1410 case com.google.javascript.rhino.head.Token.DEC:
1411 return Token.DEC;
1412 case com.google.javascript.rhino.head.Token.FUNCTION:
1413 return Token.FUNCTION;
1414 case com.google.javascript.rhino.head.Token.IF:
1415 return Token.IF;
1416 case com.google.javascript.rhino.head.Token.SWITCH:
1417 return Token.SWITCH;
1418 case com.google.javascript.rhino.head.Token.CASE:
1419 return Token.CASE;
1420 case com.google.javascript.rhino.head.Token.DEFAULT:
1421 return Token.DEFAULT_CASE;
1422 case com.google.javascript.rhino.head.Token.WHILE:
1423 return Token.WHILE;
1424 case com.google.javascript.rhino.head.Token.DO:
1425 return Token.DO;
1426 case com.google.javascript.rhino.head.Token.FOR:
1427 return Token.FOR;
1428 case com.google.javascript.rhino.head.Token.BREAK:
1429 return Token.BREAK;
1430 case com.google.javascript.rhino.head.Token.CONTINUE:
1431 return Token.CONTINUE;
1432 case com.google.javascript.rhino.head.Token.VAR:
1433 return Token.VAR;
1434 case com.google.javascript.rhino.head.Token.WITH:
1435 return Token.WITH;
1436 case com.google.javascript.rhino.head.Token.CATCH:
1437 return Token.CATCH;
1438 case com.google.javascript.rhino.head.Token.VOID:
1439 return Token.VOID;
1440 case com.google.javascript.rhino.head.Token.EMPTY:
1441 return Token.EMPTY;
1442 case com.google.javascript.rhino.head.Token.BLOCK:
1443 return Token.BLOCK;
1444 case com.google.javascript.rhino.head.Token.LABEL:
1445 return Token.LABEL;
1446 case com.google.javascript.rhino.head.Token.EXPR_VOID:
1447 case com.google.javascript.rhino.head.Token.EXPR_RESULT:
1448 return Token.EXPR_RESULT;
1449 case com.google.javascript.rhino.head.Token.SCRIPT:
1450 return Token.SCRIPT;
1451 case com.google.javascript.rhino.head.Token.GET:
1452 return Token.GETTER_DEF;
1453 case com.google.javascript.rhino.head.Token.SET:
1454 return Token.SETTER_DEF;
1455 case com.google.javascript.rhino.head.Token.CONST:
1456 return Token.CONST;
1457 case com.google.javascript.rhino.head.Token.DEBUGGER:
1458 return Token.DEBUGGER;
1459 }
1460
1461 // Token without name
1462 throw new IllegalStateException(String.valueOf(token));
1463 }
1464
1465 // Simple helper to create nodes and set the initial node properties.
1466 private Node newNode(int type) {
1467 return new Node(type).clonePropsFrom(templateNode);
1468 }
1469
1470 private Node newNode(int type, Node child1) {
1471 return new Node(type, child1).clonePropsFrom(templateNode);
1472 }
1473
1474 private Node newNode(int type, Node child1, Node child2) {
1475 return new Node(type, child1, child2).clonePropsFrom(templateNode);
1476 }
1477
1478 private Node newNode(int type, Node child1, Node child2, Node child3) {
1479 return new Node(type, child1, child2, child3).clonePropsFrom(templateNode);
1480 }
1481
1482 private Node newStringNode(String value) {
1483 return IR.string(value).clonePropsFrom(templateNode);
1484 }
1485
1486 private Node newStringNode(int type, String value) {
1487 return Node.newString(type, value).clonePropsFrom(templateNode);
1488 }
1489
1490 private Node newNumberNode(Double value) {
1491 return IR.number(value).clonePropsFrom(templateNode);
1492 }
1493 }