Debian Codegraph @

src/com/google/javascript/jscomp/jsonml/Reader.java

raw symbols SCIP
1 /*
2 * Copyright 2010 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.jsonml;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.javascript.jscomp.AbstractCompiler;
23 import com.google.javascript.jscomp.DiagnosticType;
24 import com.google.javascript.jscomp.JSError;
25 import com.google.javascript.rhino.IR;
26 import com.google.javascript.rhino.Node;
27 import com.google.javascript.rhino.Token;
28
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33
34 /**
35 * Traverse JsonML source tree and generates AST.
36 *
37 * @author [email protected] (Daniel Hans)
38 */
39 public class Reader {
40
41 static final DiagnosticType JSONML_SYNTAX = DiagnosticType.error(
42 "JSONML_SYNTAX", "Syntax error: {0}");
43
44 /** Root element of JsonML tree which contains JavaScript source. */
45 private JsonML rootElement;
46
47 /** Name of JavaScript source file */
48 private String sourceName;
49
50 /** Error reporter */
51 private ErrorReporter errorReporter;
52
53 /** List of ES5 directives supported by JsonML */
54 private final Set<String> ALLOWED_DIRECTIVES = Sets.newHashSet("use strict");
55
56 /** Number of node in JsonML order which is currently processed */
57 private int nodeIndex;
58
59 /**
60 * Inner class which is responsible for passing reader errors
61 * to the JS compiler.
62 */
63 private class ErrorReporter {
64 private AbstractCompiler compiler;
65
66 ErrorReporter(AbstractCompiler compiler) {
67 this.compiler = compiler;
68 }
69
70 private void report(JsonML element, String...arguments)
71 throws JsonMLException {
72 report(JSONML_SYNTAX, element, arguments);
73 }
74
75 private void report(DiagnosticType type, JsonML element,
76 String... arguments) throws JsonMLException {
77 // nodeIndex is the number of the node in which the error occurred
78 // we will store it in line number
79 int lineno = nodeIndex;
80 int charno = -1;
81
82 report(JSError.make(sourceName, lineno, charno, type, arguments));
83 }
84
85 /**
86 * Reports a new parser error to the compiler and terminates the job.
87 * @param error JSError instance to be passed to the compiler
88 */
89 private void report(JSError error) throws JsonMLException {
90 report(error, true);
91 }
92
93 /**
94 * Reports a new parser error to the compiler and terminates the job
95 * if the error is fatal.
96 * @param error JSError instance to be passed to the compiler
97 * @param terminal if true, parsing is terminated by throwing exception
98 */
99 private void report(JSError error, boolean terminal)
100 throws JsonMLException {
101 compiler.report(error);
102 if (terminal) {
103 throw new JsonMLException();
104 }
105 }
106 }
107
108 // TODO(dhans): Maybe this state can be replaced with a simpler check
109 /**
110 * Stores state if EXPR_RESULT node should be inserted. The reason why
111 * we have to keep track on that is JsonML representation does not have this
112 * information.
113 */
114 private boolean insertExprResultState = true;
115
116 public void setRootElement(JsonML rootElement) {
117 this.rootElement = rootElement;
118 }
119
120 /**
121 * Generates AST for a specified JsonML source file.
122 * @return root node of the generated AST
123 * @throws JsonMLException if an error occurs
124 */
125 public Node parse(AbstractCompiler compiler) throws JsonMLException {
126 if (compiler == null) {
127 // TODO(dhans): Review error handling
128 // maybe throw an exception that compiler is required for errors.
129 return null;
130 }
131
132 errorReporter = this.new ErrorReporter(compiler);
133 Node root = IR.block();
134 nodeIndex = -1;
135
136 Preconditions.checkState(rootElement.getType() == TagType.Program);
137 transformElement(rootElement, root);
138 return root.removeFirstChild();
139 }
140
141 /**
142 * Retrieves value of an attribute, but does not throw an exception if
143 * the attribute is not present for a specified JsonML element.
144 * @param type desired type of the attribute
145 * @return value of the attribute or null if it is not specified
146 * @throws JsonMLException i.e. when the value has a wrong type
147 */
148 private <T> T getOptionalAttribute(JsonML element, TagAttr attr,
149 Class<T> type) throws JsonMLException {
150 return getAttribute(element, attr, type, true);
151 }
152
153 /**
154 * Retrieves value of an attribute and throws an exception if
155 * the attribute is not present for a specified JsonML element.
156 * @param type desired type of the attribute
157 * @return value of the attribute
158 * @throws JsonMLException i.e. when the attribute does not exist
159 */
160 private <T> T getAttribute(JsonML element, TagAttr attr, Class<T> type)
161 throws JsonMLException {
162 return getAttribute(element, attr, type, false);
163 }
164
165 private <T> T getAttribute(JsonML element, TagAttr attr, Class<T> type,
166 boolean optional) throws JsonMLException {
167 Object value = element.getAttribute(attr);
168
169 if (value == null) {
170 if (type == null || optional) {
171 return null;
172 }
173
174 throw new JsonMLException(
175 "Missing " + attr.name() + " attribute for "
176 + element.getType().name() + " element.");
177 }
178
179 // Double type is a special case, as it might be represented by all
180 // Number types or even by certain strings which contain only digit chars
181 if (type.equals(Double.class)) {
182 if (value instanceof Number) {
183 return type.cast(((Number) value).doubleValue());
184 }
185 if (value instanceof String) {
186 return type.cast(Double.valueOf((String) value));
187 }
188
189 throw new JsonMLException(
190 "Wrong type of " + attr.name() + " attribute. "
191 + "Received: " + value.getClass() + ". Expected: " + type.getName());
192 }
193
194 if (type.isInstance(value)) {
195 return type.cast(value);
196 }
197
198 throw new JsonMLException(
199 "Wrong type of " + attr.name() + "attribute. "
200 + "Received: " + value.getClass() + ". Expected: " + type.getName());
201 }
202
203 /**
204 * Retrieves an attribute whose type should be Object.
205 */
206 private Object getObjectAttribute(JsonML element, TagAttr attr)
207 throws JsonMLException {
208 return getAttribute(element, attr, Object.class);
209 }
210
211 /**
212 * Retrieves an attribute whose type should be String.
213 */
214 private String getStringAttribute(JsonML element, TagAttr attr)
215 throws JsonMLException {
216 return getAttribute(element, attr, String.class);
217 }
218
219 private void validate(JsonML element) throws JsonMLException {
220 String errorMessage = Validator.validate(element);
221 if (errorMessage != null) {
222 errorReporter.report(element, errorMessage);
223 }
224 }
225
226 /**
227 * Recursively transforms JsonML tree into AST.
228 *
229 * @param element JsonML element to transform
230 * @param parent current parent AST node, i.e. when the element is
231 * transformed
232 * to a new AST node, it should be added as a last child to the parent Node.
233 */
234 private void transformElement(JsonML element, Node parent)
235 throws JsonMLException {
236 // next element is transformed
237 nodeIndex++;
238
239 // the element has to be validated
240 validate(element);
241
242 // determine if EXPR_RESULT should be inserted
243 if (insertExprResultState && JsonMLUtil.isExpression(element)) {
244 transformExpr(element, parent);
245 return;
246 }
247
248 switch (element.getType()) {
249 case ArrayExpr:
250 transformArrayExpr(element, parent);
251 break;
252 case AssignExpr:
253 transformAssignExpr(element, parent);
254 break;
255 case BinaryExpr:
256 transformBinaryExpr(element, parent);
257 break;
258 case BlockStmt:
259 transformBlock(element, parent);
260 break;
261 case BreakStmt:
262 transformBreakStmt(element, parent);
263 break;
264 case CallExpr:
265 transformCallExpr(element, parent);
266 break;
267 case Case:
268 transformCase(element, parent);
269 break;
270 case CatchClause:
271 transformCatchClause(element, parent);
272 break;
273 case ConditionalExpr:
274 transformConditionalExpr(element, parent);
275 break;
276 case ContinueStmt:
277 transformContinueStmt(element, parent);
278 break;
279 case CountExpr:
280 transformCountExpr(element, parent);
281 break;
282 case DataProp:
283 transformDataProp(element, parent);
284 break;
285 case GetterProp:
286 transformGetterProp(element, parent);
287 break;
288 case SetterProp:
289 transformSetterProp(element, parent);
290 break;
291 case DefaultCase:
292 transformDefaultCase(element, parent);
293 break;
294 case DeleteExpr:
295 transformDeleteExpr(element, parent);
296 break;
297 case DoWhileStmt:
298 transformDoWhileStmt(element, parent);
299 break;
300 case Empty:
301 transformEmpty(element, parent);
302 break;
303 case EmptyStmt:
304 transformEmptyStmt(element, parent);
305 break;
306 case EvalExpr:
307 transformEvalExpr(element, parent);
308 break;
309 case ForInStmt:
310 transformForInStmt(element, parent);
311 break;
312 case ForStmt:
313 transformForStmt(element, parent);
314 break;
315 case FunctionDecl:
316 transformFunctionDecl(element, parent);
317 break;
318 case FunctionExpr:
319 transformFunctionExpr(element, parent);
320 break;
321 case IdExpr:
322 transformIdExpr(element, parent);
323 break;
324 case IdPatt:
325 transformIdPatt(element, parent);
326 break;
327 case IfStmt:
328 transformIfStmt(element, parent);
329 break;
330 case InitPatt:
331 transformInitPatt(element, parent);
332 break;
333 case InvokeExpr:
334 transformInvokeExpr(element, parent);
335 break;
336 case LabelledStmt:
337 transformLabelledStmt(element, parent);
338 break;
339 case LiteralExpr:
340 transformLiteralExpr(element, parent);
341 break;
342 case LogicalAndExpr:
343 transformLogicalAndExpr(element, parent);
344 break;
345 case LogicalOrExpr:
346 transformLogicalOrExpr(element, parent);
347 break;
348 case MemberExpr:
349 transformMemberExpr(element, parent);
350 break;
351 case NewExpr:
352 transformNewExpr(element, parent);
353 break;
354 case ObjectExpr:
355 transformObjectExpr(element, parent);
356 break;
357 case ParamDecl:
358 transformParamDecl(element, parent);
359 break;
360 case Program:
361 transformProgram(element, parent);
362 break;
363 case PrologueDecl:
364 transformPrologueDecl(element, parent);
365 break;
366 case RegExpExpr:
367 transformRegExpExpr(element, parent);
368 break;
369 case ReturnStmt:
370 transformReturnStmt(element, parent);
371 break;
372 case SwitchStmt:
373 transformSwitchStmt(element, parent);
374 break;
375 case ThisExpr:
376 transformThisExpr(element, parent);
377 break;
378 case ThrowStmt:
379 transformThrowStmt(element, parent);
380 break;
381 case TryStmt:
382 transformTryStmt(element, parent);
383 break;
384 case TypeofExpr:
385 transformTypeofExpr(element, parent);
386 break;
387 case UnaryExpr:
388 transformUnaryExpr(element, parent);
389 break;
390 case VarDecl:
391 transformVarDecl(element, parent);
392 break;
393 case WhileStmt:
394 transformWhileStmt(element, parent);
395 break;
396 case WithStmt:
397 transformWithStmt(element, parent);
398 break;
399 }
400 }
401
402 /*
403 * Helper functions.
404 * Usually called by functions which process particular JsonML elements.
405 */
406
407 private void transformAllChildren(JsonML element, Node parent,
408 boolean newState) throws JsonMLException {
409 transformElements(element.getChildren(), parent, newState);
410 }
411
412 private void transformAllChildren(JsonML element, Node parent)
413 throws JsonMLException {
414 transformElements(element.getChildren(), parent);
415 }
416
417 private void transformAllChildrenFromIndex(JsonML element, Node parent,
418 int fromIndex, boolean newState) throws JsonMLException {
419 transformElements(element.getChildren().subList(
420 fromIndex, element.childrenSize()), parent, newState);
421 }
422
423 private void transformElements(List<JsonML> elements, Node parent,
424 boolean newState) throws JsonMLException {
425 boolean oldState = insertExprResultState;
426 insertExprResultState = newState;
427 transformElements(elements, parent);
428 insertExprResultState = oldState;
429 }
430
431 private void transformElements(List<JsonML> elements, Node parent)
432 throws JsonMLException {
433 for (JsonML element : elements) {
434 transformElement(element, parent);
435 }
436 }
437
438 /**
439 * Responsible for inserting EXPR_RESULT nodes.
440 */
441 private boolean transformExpr(JsonML element, Node parent)
442 throws JsonMLException {
443 boolean result = false;
444 if (insertExprResultState) {
445 Node node = new Node(Token.EXPR_RESULT);
446 parent.addChildToBack(node);
447 insertExprResultState = false;
448 nodeIndex--; // the same node will be transformed again
449 transformElement(element, node);
450 insertExprResultState = true;
451 result = true;
452 }
453 return result;
454 }
455
456 /**
457 * Generic function responsible for dealing with JsonML elements describing
458 * for loop (ForStmt and ForInStmt).
459 */
460 private void transformForLoop(JsonML element, Node parent, int childno)
461 throws JsonMLException {
462 Preconditions.checkState(insertExprResultState == true);
463 insertExprResultState = false;
464
465 Node node = createNode(Token.FOR, element);
466 parent.addChildToBack(node);
467
468 JsonML child;
469 for (int i = 0; i < childno; ++i) {
470 child = element.getChild(i);
471 if (child.getType() == TagType.EmptyStmt ||
472 child.getType() == TagType.Empty) {
473 nodeIndex++;
474 node.addChildToBack(IR.empty());
475 } else {
476 transformElement(child, node);
477 }
478 }
479
480 transformPotentiallyUnwrappedBlock(element.getChild(childno), node);
481 insertExprResultState = true;
482 }
483
484 /**
485 * Generic function responsible for dealing with the following JsonML
486 * elements: BreakStmt and ContinueStmt.
487 */
488 private void transformJumpStmt(JsonML element, Node parent, int type)
489 throws JsonMLException {
490 Node node = createNode(type, element);
491 parent.addChildToBack(node);
492
493 String label = getOptionalAttribute(element, TagAttr.LABEL, String.class);
494 if (label != null) {
495 node.addChildToBack(IR.labelName(label));
496 }
497 }
498
499 /**
500 * Generic function responsible for dealing with JsonML elements describing
501 * logical two arguments expressions: LogicalAndExpr and LogicalOrExpr.
502 */
503 private void transformLogicalExpr(JsonML element, Node parent, int type)
504 throws JsonMLException {
505 transformTwoArgumentExpr(element, parent, type);
506 }
507
508 /**
509 * Generic function responsible for dealing with all kind of expressions
510 * which are passed exactly two arguments.
511 */
512 private void transformTwoArgumentExpr(JsonML element, Node parent,
513 int type) throws JsonMLException {
514 Node node = createNode(type, element);
515 parent.addChildToBack(node);
516 transformAllChildren(element, node);
517 }
518
519 /**
520 * Transforms an element which should be transformed into a BLOCK node, but
521 * may not be represented by BlockStmt. In this case, additional BLOCK node
522 * is created.
523 */
524 private void transformPotentiallyUnwrappedBlock(JsonML element, Node parent)
525 throws JsonMLException {
526
527 // in theory it should be always EmptyStmt, but due to possible
528 // compatibility issues Empty element is allowed as well
529 if (element.getType() == TagType.EmptyStmt ||
530 element.getType() == TagType.Empty) {
531 nodeIndex++;
532 // Empty elements are only replaced by BLOCK node
533 Node block = IR.block();
534 parent.addChildToBack(block);
535 block.putBooleanProp(Node.EMPTY_BLOCK, true);
536 } else if (element.getType() != TagType.BlockStmt) {
537 Node block = IR.block();
538 parent.addChildToBack(block);
539 boolean state = insertExprResultState;
540 insertExprResultState = true;
541 transformElement(element, block);
542 insertExprResultState = state;
543 } else {
544 nodeIndex++;
545 transformBlock(element, parent);
546 }
547 }
548
549 /*
550 * Main functions.
551 * Functions responsible for handling particular JsonML elements. Depending
552 * on type, transformElement function dispatches actual work to
553 * the corresponding function below.
554 */
555
556 private void transformArrayExpr(JsonML element, Node parent)
557 throws JsonMLException {
558
559 Node node = createNode(Token.ARRAYLIT, element);
560 parent.addChildToBack(node);
561
562 // iterate through all the children and look for empty elements
563 for (JsonML child : element.getChildren()) {
564 transformElement(child, node);
565 }
566 }
567
568 private void transformAssignExpr(JsonML element, Node parent)
569 throws JsonMLException {
570 String op = getStringAttribute(element, TagAttr.OP);
571 int type = Operator.getNodeTypeForAssignOp(op);
572 transformTwoArgumentExpr(element, parent, type);
573 }
574
575 private void transformBinaryExpr(JsonML element, Node parent)
576 throws JsonMLException {
577 String op = getStringAttribute(element, TagAttr.OP);
578 int type = Operator.getNodeTypeForBinaryOp(op);
579 transformTwoArgumentExpr(element, parent, type);
580 }
581
582 private void transformBlock(JsonML element, Node parent)
583 throws JsonMLException {
584 transformBlock(element, parent, 0, element.childrenSize());
585 }
586
587 private void transformBlock(JsonML element, Node parent, int start)
588 throws JsonMLException {
589 transformBlock(element, parent, start, element.childrenSize());
590 }
591
592 private void transformBlock(JsonML element, Node parent, int start, int end)
593 throws JsonMLException {
594 Node node = createNode(Token.BLOCK, element);
595 parent.addChildToBack(node);
596 transformElements(element.getChildren(start, end), node, true);
597 }
598
599 private void transformBreakStmt(JsonML element, Node parent)
600 throws JsonMLException {
601 transformJumpStmt(element, parent, Token.BREAK);
602 }
603
604 private void transformCallExpr(JsonML element, Node parent)
605 throws JsonMLException {
606
607 Node node = createNode(Token.CALL, element);
608 parent.addChildToBack(node);
609
610 transformAllChildren(element, node);
611
612 // Keep track of of the "this" context of a call. A call without an
613 // explicit "this" is a free call.
614 Node first = node.getFirstChild();
615 if (first.getType() != Token.GETPROP && first.getType() != Token.GETELEM) {
616 node.putBooleanProp(Node.FREE_CALL, true);
617 }
618 }
619
620 private void transformCase(JsonML element, Node parent)
621 throws JsonMLException {
622
623 Node node = createNode(Token.CASE, element);
624 parent.addChildToBack(node);
625
626 // the first element represents case id
627 JsonML child = element.getChild(0);
628 transformElement(child, node);
629
630 // always insert an extra BLOCK node
631 Node block = IR.block();
632 block.setIsSyntheticBlock(true);
633 node.addChildToBack(block);
634
635 transformAllChildrenFromIndex(element, block, 1, true);
636 }
637
638 private void transformCatchClause(JsonML element, Node parent)
639 throws JsonMLException {
640
641 Node node = createNode(Token.CATCH, element);
642 parent.addChildToBack(node);
643
644 JsonML child = element.getChild(0);
645 transformElement(child, node);
646
647 // the second child represents actual block
648 child = element.getChild(1);
649 transformElement(child, node);
650 }
651
652 private void transformConditionalExpr(JsonML element, Node parent)
653 throws JsonMLException {
654 Node node = createNode(Token.HOOK, element);
655 parent.addChildToBack(node);
656
657 transformAllChildren(element, node);
658 }
659
660 private void transformContinueStmt(JsonML element, Node parent)
661 throws JsonMLException {
662 transformJumpStmt(element, parent, Token.CONTINUE);
663 }
664
665 /*
666 * CountExpr are both incrementing and decrementing expressions (++x, --x)
667 */
668 private void transformCountExpr(JsonML element, Node parent)
669 throws JsonMLException {
670 String op = getStringAttribute(element, TagAttr.OP);
671
672 int type = Operator.getNodeTypeForCountOp(op);
673
674 Boolean isPrefix = getAttribute(element, TagAttr.IS_PREFIX, Boolean.class);
675 Node node = createNode(type, element);
676 node.putIntProp(Node.INCRDECR_PROP, isPrefix ? 0 : 1);
677 parent.addChildToBack(node);
678
679 transformElement(element.getChild(0), node);
680 }
681
682 /*
683 * DataProp is the name for an object property which is initialized
684 * when the object is created by object literal.
685 * For example, in {x: 1, y: 2} each property is represented by its own
686 * DataProp.
687 */
688 private void transformDataProp(JsonML element, Node parent)
689 throws JsonMLException {
690 Object name = getObjectAttribute(element, TagAttr.NAME);
691
692 Node node = null;
693 if (name instanceof Number) {
694 node = IR.stringKey(getStringValue(((Number) name).doubleValue()));
695 } else if (name instanceof String) {
696 node = IR.stringKey((String) name);
697 } else {
698 throw new IllegalStateException(
699 "The name of the property has invalid type.");
700 }
701
702 setPosition(node);
703 parent.addChildToBack(node);
704
705 transformElement(element.getChild(0), node);
706 }
707
708 private static String getStringValue(double value) {
709 long longValue = (long) value;
710
711 // Return "1" instead of "1.0"
712 if (longValue == value) {
713 return Long.toString(longValue);
714 } else {
715 return Double.toString(value);
716 }
717 }
718
719 /*
720 * GetterProp is a object literal entry for a getter.
721 * For example, {get x() {return 1}}
722 */
723 private void transformGetterProp(JsonML element, Node parent)
724 throws JsonMLException {
725 transformProp(Token.GETTER_DEF, element, parent);
726 }
727
728 /*
729 * GetterProp is a object literal entry for a getter.
730 * For example, {set x() {return 1}}
731 */
732 private void transformSetterProp(JsonML element, Node parent)
733 throws JsonMLException {
734 transformProp(Token.SETTER_DEF, element, parent);
735 }
736
737 private void transformProp(int tokenType, JsonML element, Node parent)
738 throws JsonMLException {
739 Object name = getObjectAttribute(element, TagAttr.NAME);
740
741 Node node = null;
742 if (name instanceof Number) {
743 // TODO(johnlenz): convert the number to a quoted string.
744 throw new IllegalStateException(
745 "Not yet supported.");
746 } else if (name instanceof String) {
747 node = Node.newString(tokenType, (String) name);
748 } else {
749 throw new IllegalStateException(
750 "The name of the property has invalid type.");
751 }
752
753 setPosition(node);
754 parent.addChildToBack(node);
755
756 transformElement(element.getChild(0), node);
757 }
758
759
760 private void transformDefaultCase(JsonML element, Node parent)
761 throws JsonMLException {
762 Node node = createNode(Token.DEFAULT_CASE, element);
763 parent.addChildToBack(node);
764
765 // the first child represent body
766 Node block = IR.block();
767 block.setIsSyntheticBlock(true);
768 node.addChildToBack(block);
769
770 transformAllChildren(element, block, true);
771 }
772
773 private void transformDeleteExpr(JsonML element, Node parent)
774 throws JsonMLException {
775
776 Node node = createNode(Token.DELPROP, element);
777 parent.addChildToBack(node);
778
779 transformElement(element.getChild(0), node);
780 }
781
782 private void transformDoWhileStmt(JsonML element, Node parent)
783 throws JsonMLException {
784 Preconditions.checkState(insertExprResultState == true);
785 insertExprResultState = false;
786
787 Node node = createNode(Token.DO, element);
788 parent.addChildToBack(node);
789
790 // the first child represents body
791 JsonML child = element.getChild(0);
792 transformPotentiallyUnwrappedBlock(child, node);
793
794 // the second child represents condition
795 child = element.getChild(1);
796 transformElement(child, node);
797
798 insertExprResultState = true;
799 }
800
801 private void transformEmpty(JsonML element, Node parent) {
802 switch (parent.getType()) {
803 case Token.ARRAYLIT:
804 parent.addChildToBack(IR.empty());
805 break;
806 case Token.FUNCTION:
807 parent.addChildToBack(IR.name(""));
808 break;
809 default:
810 throw new IllegalArgumentException("Unexpected Empty element.");
811 }
812 }
813
814 private void transformEmptyStmt(JsonML element, Node parent) {
815 Preconditions.checkState(
816 parent.getType() == Token.BLOCK || parent.getType() == Token.SCRIPT);
817 parent.addChildToBack(IR.empty());
818 }
819
820 private void transformEvalExpr(JsonML element, Node parent)
821 throws JsonMLException {
822
823 Node node = createNode(Token.CALL, element);
824 node.putBooleanProp(Node.FREE_CALL, true);
825 parent.addChildToBack(node);
826
827 Node child = IR.name("eval");
828 child.putBooleanProp(Node.DIRECT_EVAL, true);
829 node.addChildToBack(child);
830
831 transformAllChildren(element, node);
832 }
833
834 private void transformForInStmt(JsonML element, Node parent)
835 throws JsonMLException {
836 transformForLoop(element, parent, 2);
837 }
838
839 private void transformForStmt(JsonML element, Node parent)
840 throws JsonMLException {
841 transformForLoop(element, parent, 3);
842 }
843
844 private void transformFunction(JsonML element, Node parent,
845 boolean needsName) throws JsonMLException {
846 Node node = createNode(Token.FUNCTION, element);
847 parent.addChildToBack(node);
848
849 JsonML child = element.getChild(0);
850 String name = "";
851
852 // it be already validated at this point that a non empty name exists
853 // if it is a function declaration
854 transformElement(element.getChild(0), node);
855
856 transformElement(element.getChild(1), node);
857
858 // other children represents function body which should be
859 // wrapped inside a block node
860 transformBlock(element, node, 2);
861 }
862
863 private void transformFunctionDecl(JsonML element, Node parent)
864 throws JsonMLException {
865 transformFunction(element, parent, true);
866 }
867
868 private void transformFunctionExpr(JsonML element, Node parent)
869 throws JsonMLException {
870 transformFunction(element, parent, false);
871 }
872
873 private void transformIdExpr(JsonML element, Node parent)
874 throws JsonMLException {
875 String name = getStringAttribute(element, TagAttr.NAME);
876 Node node = IR.name(name);
877 setPosition(node);
878 parent.addChildToBack(node);
879 }
880
881 /*
882 * InitPatt represents all variable declarations value initialization.
883 * It has two children: name of the variable and the initial value.
884 */
885 private void transformInitPatt(JsonML element, Node parent)
886 throws JsonMLException {
887 JsonML child = element.getChild(0);
888 nodeIndex++;
889 Node node = IR.name(
890 getAttribute(child, TagAttr.NAME, String.class));
891 setPosition(node);
892 parent.addChildToBack(node);
893
894 child = element.getChild(1);
895 transformElement(child, node);
896 }
897
898 private void transformIdPatt(JsonML element, Node parent)
899 throws JsonMLException {
900 Node node = IR.name(
901 getStringAttribute(element, TagAttr.NAME));
902 setPosition(node);
903 parent.addChildToBack(node);
904 }
905
906 private void transformIfStmt(JsonML element, Node parent)
907 throws JsonMLException {
908 Preconditions.checkState(insertExprResultState == true);
909 insertExprResultState = false;
910
911 Node node = createNode(Token.IF, element);
912 parent.addChildToBack(node);
913
914 // the first child represents condition
915 JsonML child = element.getChild(0);
916 transformElement(child, node);
917
918 // the second child is required
919 child = element.getChild(1);
920 transformPotentiallyUnwrappedBlock(child, node);
921
922 // the third child represents else part and is not required by AST
923 child = element.getChild(2);
924 if (child.getType() != TagType.EmptyStmt &&
925 child.getType() != TagType.Empty) {
926 transformPotentiallyUnwrappedBlock(child, node);
927 } else {
928 nodeIndex++;
929 }
930 insertExprResultState = true;
931 }
932
933 private void transformInvokeExpr(JsonML element, Node parent)
934 throws JsonMLException {
935 Node node = createNode(Token.CALL, element);
936 parent.addChildToBack(node);
937
938 transformMemberExpr(element, node);
939
940 transformElements(element.getChildren(2, element.childrenSize()), node);
941 }
942
943 private void transformLabelledStmt(JsonML element, Node parent)
944 throws JsonMLException {
945 String label = getStringAttribute(element, TagAttr.LABEL);
946 Node node = createNode(Token.LABEL, element);
947 node.addChildToBack(IR.labelName(label));
948 parent.addChildToBack(node);
949
950 JsonML child = element.getChild(0);
951 if (child.getType() == TagType.EmptyStmt) {
952 nodeIndex++;
953 node.addChildToBack(IR.empty());
954 } else {
955 transformElement(element.getChild(0), node);
956 }
957 }
958
959 private void transformLiteralExpr(JsonML element, Node parent)
960 throws JsonMLException {
961
962 Node node = null;
963 Type type = Type.get(getStringAttribute(element, TagAttr.TYPE));
964 switch (type) {
965 case BOOLEAN: {
966 Boolean value = getAttribute(element, TagAttr.VALUE, Boolean.class);
967 if (value) {
968 node = IR.trueNode();
969 } else {
970 node = IR.falseNode();
971 }
972 break;
973 }
974
975 case NULL: {
976 // needed to throw an exception if value is not null
977 getAttribute(element, TagAttr.VALUE, null);
978 node = IR.nullNode();
979 break;
980 }
981
982 case NUMBER: {
983 Double value = getAttribute(element, TagAttr.VALUE, Double.class);
984 node = IR.number(value);
985 break;
986 }
987
988 case STRING: {
989 String value = getStringAttribute(element, TagAttr.VALUE);
990 node = IR.string(value);
991 break;
992 }
993
994 default:
995 throw new JsonMLException("Unrecognized type attribute.");
996 }
997
998 setPosition(node);
999 parent.addChildToBack(node);
1000 }
1001
1002 private void transformLogicalAndExpr(JsonML element, Node parent)
1003 throws JsonMLException {
1004 transformLogicalExpr(element, parent, Token.AND);
1005 }
1006
1007 private void transformLogicalOrExpr(JsonML element, Node parent)
1008 throws JsonMLException {
1009 transformLogicalExpr(element, parent, Token.OR);
1010 }
1011
1012 private void transformMemberExpr(JsonML element, Node parent)
1013 throws JsonMLException {
1014
1015 String op = getAttribute(element, TagAttr.OP, String.class);
1016 int type;
1017 if (op.equals(".")) {
1018 type = Token.GETPROP;
1019 } else if (op.equals("[]")) {
1020 type = Token.GETELEM;
1021 } else {
1022 throw new JsonMLException("Invalid OP argument: " + op);
1023 }
1024
1025 Node node = createNode(type, element);
1026 parent.addChildToBack(node);
1027
1028 transformElement(element.getChild(0), node);
1029 transformElement(element.getChild(1), node);
1030 }
1031
1032 private void transformNewExpr(JsonML element, Node parent)
1033 throws JsonMLException {
1034 Node node = createNode(Token.NEW, element);
1035 parent.addChildToBack(node);
1036 transformAllChildren(element, node);
1037 }
1038
1039 private void transformObjectExpr(JsonML element, Node parent)
1040 throws JsonMLException {
1041 Node node = createNode(Token.OBJECTLIT, element);
1042 parent.addChildToBack(node);
1043
1044 transformAllChildren(element, node);
1045 }
1046
1047 private void transformParamDecl(JsonML element, Node parent)
1048 throws JsonMLException {
1049 // formal arguments should be wrapped by LP node
1050 Node node = createNode(Token.PARAM_LIST, element);
1051 parent.addChildToBack(node);
1052
1053 transformAllChildren(element, node);
1054 }
1055
1056 private void transformProgram(JsonML element, Node parent)
1057 throws JsonMLException {
1058 Preconditions.checkNotNull(parent);
1059 insertExprResultState = true;
1060
1061 Node script = IR.script();
1062 parent.addChildToBack(script);
1063
1064 for (JsonML child : element.getChildren()) {
1065 transformElement(child, script);
1066 }
1067 }
1068
1069 private void transformPrologueDecl(JsonML element, Node parent)
1070 throws JsonMLException {
1071 String directive = getStringAttribute(element, TagAttr.DIRECTIVE);
1072
1073 if (ALLOWED_DIRECTIVES.contains(directive)) {
1074 Set<String> directives = parent.getDirectives();
1075 if (directives == null) {
1076 directives = Sets.newHashSet();
1077 }
1078 directives.add(directive);
1079 parent.setDirectives(directives);
1080 } else {
1081 // for a directive which is not supported, we create a regular node
1082 Node node = IR.exprResult(IR.string(directive));
1083 parent.addChildToBack(node);
1084 }
1085 }
1086
1087 private void transformRegExpExpr(JsonML element, Node parent)
1088 throws JsonMLException {
1089 Node node = createNode(Token.REGEXP, element);
1090 parent.addChildToBack(node);
1091
1092 String body = getStringAttribute(element, TagAttr.BODY);
1093 node.addChildToBack(IR.string(body));
1094
1095 String flags = getStringAttribute(element, TagAttr.FLAGS);
1096 if (!(flags.equals(""))) {
1097 node.addChildToBack(IR.string(flags));
1098 }
1099 }
1100
1101 private void transformReturnStmt(JsonML element, Node parent)
1102 throws JsonMLException {
1103 Preconditions.checkState(insertExprResultState == true);
1104 Node node = createNode(Token.RETURN, element);
1105 parent.addChildToBack(node);
1106
1107 if (element.hasChildren()) {
1108 insertExprResultState = false;
1109 transformElement(element.getChild(0), node);
1110 insertExprResultState = true;
1111 }
1112 }
1113
1114 private void transformSwitchStmt(JsonML element, Node parent)
1115 throws JsonMLException {
1116 Preconditions.checkState(insertExprResultState == true);
1117 insertExprResultState = false;
1118
1119 Node node = createNode(Token.SWITCH, element);
1120 parent.addChildToBack(node);
1121
1122 // make sure it has at least one child
1123 // the first child represents switch param
1124 JsonML child = element.getChild(0);
1125 transformElement(child, node);
1126
1127 // the rest of the children represent cases
1128 for (int i = 1; i < element.childrenSize(); ++i) {
1129 child = element.getChild(i);
1130 // make sure it is case or default
1131 transformElement(child, node);
1132 }
1133
1134 insertExprResultState = true;
1135 }
1136
1137 /**
1138 * @throws JsonMLException
1139 */
1140 private void transformThisExpr(JsonML element, Node parent)
1141 throws JsonMLException {
1142 parent.addChildToBack(createNode(Token.THIS, element));
1143 }
1144
1145 private void transformThrowStmt(JsonML element, Node parent)
1146 throws JsonMLException {
1147 Preconditions.checkState(insertExprResultState == true);
1148 Node node = createNode(Token.THROW, element);
1149 parent.addChildToBack(node);
1150
1151 insertExprResultState = false;
1152 transformElement(element.getChild(0), node);
1153 insertExprResultState = true;
1154 }
1155
1156 private void transformTryStmt(JsonML element, Node parent)
1157 throws JsonMLException {
1158 Preconditions.checkState(insertExprResultState == true);
1159 Node node = createNode(Token.TRY, element);
1160 parent.addChildToBack(node);
1161
1162 // the first child represents try body
1163 JsonML child = element.getChild(0);
1164 transformElement(child, node);
1165
1166 // the second child represents catch
1167 Node block = IR.block();
1168 node.addChildToBack(block);
1169 child = element.getChild(1);
1170
1171 if (child.getType() == TagType.CatchClause) {
1172 transformElement(child, block);
1173 } else {
1174 // catch clause is not present, but the element has to be counted
1175 nodeIndex++;
1176 }
1177
1178 // if the third child is present, it represents finally
1179 if (element.childrenSize() == 3) {
1180 child = element.getChild(2);
1181 transformElement(child, node);
1182 }
1183 }
1184
1185 private void transformTypeofExpr(JsonML element, Node parent)
1186 throws JsonMLException {
1187 Node node = createNode(Token.TYPEOF, element);
1188 parent.addChildToBack(node);
1189 transformElement(element.getChild(0), node);
1190 }
1191
1192 private void transformUnaryExpr(JsonML element, Node parent)
1193 throws JsonMLException {
1194 String op = getStringAttribute(element, TagAttr.OP);
1195 int type = Operator.getNodeTypeForUnaryOp(op);
1196
1197 Node node = createNode(type, element);
1198 parent.addChildToBack(node);
1199
1200 transformAllChildren(element, node);
1201 }
1202
1203 private void transformVarDecl(JsonML element, Node parent)
1204 throws JsonMLException {
1205 Node node = createNode(Token.VAR, element);
1206 parent.addChildToBack(node);
1207
1208 transformAllChildren(element, node, false);
1209 }
1210
1211 private void transformWhileStmt(JsonML element, Node parent)
1212 throws JsonMLException {
1213 Preconditions.checkState(insertExprResultState == true);
1214 insertExprResultState = false;
1215
1216 Node node = createNode(Token.WHILE, element);
1217 parent.addChildToBack(node);
1218
1219 // the first child represents loop condition
1220 JsonML child = element.getChild(0);
1221 transformElement(child, node);
1222
1223 // the second child represents loop body
1224 child = element.getChild(1);
1225 transformPotentiallyUnwrappedBlock(child, node);
1226
1227 insertExprResultState = true;
1228 }
1229
1230 private void transformWithStmt(JsonML element, Node parent)
1231 throws JsonMLException {
1232 Preconditions.checkState(insertExprResultState == true);
1233 insertExprResultState = false;
1234
1235 Node node = createNode(Token.WITH, element);
1236 parent.addChildToBack(node);
1237
1238 // the first child represents object
1239 JsonML child = element.getChild(0);
1240 transformElement(child, node);
1241
1242 // the second child represents body
1243 child = element.getChild(1);
1244 transformPotentiallyUnwrappedBlock(child, node);
1245
1246 insertExprResultState = true;
1247 }
1248
1249 /**
1250 * Creates a node which refers to a particular JsonML element.
1251 */
1252 private Node createNode(int type, JsonML element) {
1253 return new Node(type, nodeIndex, -1);
1254 }
1255
1256 /**
1257 * Sets position for a node which refers to a particular JsonML element.
1258 * The position says which number (in pre-order) has the corresponding
1259 * JsonML element in the tree.
1260 */
1261 private void setPosition(Node node) {
1262 node.setLineno(nodeIndex);
1263 }
1264
1265 /**
1266 * Internal representation for operators which are used by JsonML as
1267 * attributes for various elements.
1268 */
1269 private enum Operator {
1270 // Assign Operators
1271 ASSIGN("="),
1272 ASSIGN_BITOR("|="),
1273 ASSIGN_BITXOR("^="),
1274 ASSIGN_BITAND("&="),
1275 ASSIGN_LSH("<<="),
1276 ASSIGN_RSH(">>="),
1277 ASSIGN_URSH(">>>="),
1278 ASSIGN_ADD("+="),
1279 ASSIGN_SUB("-="),
1280 ASSIGN_MUL("*="),
1281 ASSIGN_DIV("/="),
1282 ASSIGN_MOD("%="),
1283
1284 // Binary Operators
1285 BITOR("|"),
1286 BITXOR("^"),
1287 BITAND("&"),
1288 EQ("=="),
1289 NE("!="),
1290 LT("<"),
1291 LE("<="),
1292 GT(">"),
1293 GE(">="),
1294 LSH("<<"),
1295 RSH(">>"),
1296 URSH(">>>"),
1297 ADD("+"),
1298 SUB("-"),
1299 MUL("*"),
1300 DIV("/"),
1301 MOD("%"),
1302 SHEQ("==="),
1303 SHNE("!=="),
1304 COMMA(","),
1305 INSTANCEOF("instanceof"),
1306 IN("in"),
1307
1308 // Count Operators
1309 DEC("--"),
1310 INC("++"),
1311
1312 // Unary Operators
1313 NOT("!"),
1314 BITNOT("~"),
1315 POS("+_unary"), // "+" would be a duplicate with ADD
1316 NEG("-_unary"), // "-" would be a duplicate with SUB
1317 VOID("void");
1318
1319 private final String name;
1320 private static Map<String, Operator> lookup = Maps.newHashMap();
1321
1322 // Maps string representation of operators with corresponding enums
1323 static {
1324 for (Operator op : Operator.values()) {
1325 lookup.put(op.getName(), op);
1326 }
1327 }
1328
1329 private String getName() {
1330 return this.name;
1331 }
1332
1333 private Operator(String name) {
1334 this.name = name;
1335 }
1336
1337 private static Operator get(String name) {
1338 return lookup.get(name);
1339 }
1340
1341 /**
1342 * Returns assign operator associated with a specified name.
1343 */
1344 private static int getNodeTypeForAssignOp(String name) {
1345 Operator op = get(name);
1346 if (op == null) {
1347 return Token.ERROR;
1348 }
1349
1350 int type;
1351 switch (op) {
1352 case ASSIGN:
1353 type = Token.ASSIGN;
1354 break;
1355 case ASSIGN_BITOR:
1356 type = Token.ASSIGN_BITOR;
1357 break;
1358 case ASSIGN_BITXOR:
1359 type = Token.ASSIGN_BITXOR;
1360 break;
1361 case ASSIGN_BITAND:
1362 type = Token.ASSIGN_BITAND;
1363 break;
1364 case ASSIGN_LSH:
1365 type = Token.ASSIGN_LSH;
1366 break;
1367 case ASSIGN_RSH:
1368 type = Token.ASSIGN_RSH;
1369 break;
1370 case ASSIGN_URSH:
1371 type = Token.ASSIGN_URSH;
1372 break;
1373 case ASSIGN_ADD:
1374 type = Token.ASSIGN_ADD;
1375 break;
1376 case ASSIGN_SUB:
1377 type = Token.ASSIGN_SUB;
1378 break;
1379 case ASSIGN_MUL:
1380 type = Token.ASSIGN_MUL;
1381 break;
1382 case ASSIGN_DIV:
1383 type = Token.ASSIGN_DIV;
1384 break;
1385 case ASSIGN_MOD:
1386 type = Token.ASSIGN_MOD;
1387 break;
1388 default:
1389 throw new IllegalArgumentException(""
1390 + "Invalid type of assign expression.");
1391 }
1392 return type;
1393 }
1394
1395 /**
1396 * Returns binary operator associated with a specified name.
1397 */
1398 private static int getNodeTypeForBinaryOp(String name) {
1399 Operator op = get(name);
1400
1401 int type;
1402 switch (op) {
1403 case BITOR:
1404 type = Token.BITOR;
1405 break;
1406 case BITXOR:
1407 type = Token.BITXOR;
1408 break;
1409 case BITAND:
1410 type = Token.BITAND;
1411 break;
1412 case EQ:
1413 type = Token.EQ;
1414 break;
1415 case NE:
1416 type = Token.NE;
1417 break;
1418 case LT:
1419 type = Token.LT;
1420 break;
1421 case LE:
1422 type = Token.LE;
1423 break;
1424 case GT:
1425 type = Token.GT;
1426 break;
1427 case GE:
1428 type = Token.GE;
1429 break;
1430 case LSH:
1431 type = Token.LSH;
1432 break;
1433 case RSH:
1434 type = Token.RSH;
1435 break;
1436 case URSH:
1437 type = Token.URSH;
1438 break;
1439 case ADD:
1440 type = Token.ADD;
1441 break;
1442 case SUB:
1443 type = Token.SUB;
1444 break;
1445 case MUL:
1446 type = Token.MUL;
1447 break;
1448 case DIV:
1449 type = Token.DIV;
1450 break;
1451 case MOD:
1452 type = Token.MOD;
1453 break;
1454 case SHEQ:
1455 type = Token.SHEQ;
1456 break;
1457 case SHNE:
1458 type = Token.SHNE;
1459 break;
1460 case COMMA:
1461 type = Token.COMMA;
1462 break;
1463 case INSTANCEOF:
1464 type = Token.INSTANCEOF;
1465 break;
1466 case IN:
1467 type = Token.IN;
1468 break;
1469 default:
1470 throw new IllegalArgumentException(""
1471 + "Invalid type of binary expression.");
1472 }
1473 return type;
1474 }
1475
1476 /**
1477 * Returns count operator(++, --) associated with a specified name.
1478 */
1479 private static int getNodeTypeForCountOp(String name) {
1480 Operator op = get(name);
1481 if (op == null) {
1482 return Token.ERROR;
1483 }
1484
1485 int type;
1486 switch (op) {
1487 case DEC:
1488 type = Token.DEC;
1489 break;
1490 case INC:
1491 type = Token.INC;
1492 break;
1493 default:
1494 throw new IllegalArgumentException(""
1495 + "Invalid type of count expression.");
1496 }
1497 return type;
1498 }
1499
1500 /**
1501 * Returns assign operator associated with a specified name.
1502 */
1503 private static int getNodeTypeForUnaryOp(String name) {
1504 String realName = new String(name);
1505 if (name.equals("+") || name.equals("-")) {
1506 realName += "_unary";
1507 }
1508 Operator op = get(realName);
1509
1510 int type;
1511 switch (op) {
1512 case NOT:
1513 type = Token.NOT;
1514 break;
1515 case BITNOT:
1516 type = Token.BITNOT;
1517 break;
1518 case POS:
1519 type = Token.POS;
1520 break;
1521 case NEG:
1522 type = Token.NEG;
1523 break;
1524 case VOID:
1525 type = Token.VOID;
1526 break;
1527 default:
1528 throw new IllegalArgumentException(""
1529 + "Invalid type of unary expression.");
1530 }
1531 return type;
1532 }
1533 }
1534
1535 /**
1536 * Internal representation of possible types of arguments of JsonML.
1537 */
1538 private enum Type {
1539 BOOLEAN("boolean"),
1540 NULL("null"),
1541 NUMBER("number"),
1542 STRING("string");
1543
1544 private final String name;
1545 private static Map<String, Type> lookup = new HashMap<String, Type>();
1546
1547 static {
1548 for (Type type : Type.values()) {
1549 lookup.put(type.getName(), type);
1550 }
1551 }
1552
1553 private String getName() {
1554 return this.name;
1555 }
1556
1557 private Type(String name) {
1558 this.name = name;
1559 }
1560
1561 private static Type get(String name) {
1562 return lookup.get(name);
1563 }
1564 }
1565 }