Debian Codegraph @

rhino/src/org/mozilla/javascript/Node.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript;
8
9 import org.mozilla.javascript.ast.Comment;
10 import org.mozilla.javascript.ast.FunctionNode;
11 import org.mozilla.javascript.ast.Jump;
12 import org.mozilla.javascript.ast.Name;
13 import org.mozilla.javascript.ast.NumberLiteral;
14 import org.mozilla.javascript.ast.Scope;
15 import org.mozilla.javascript.ast.ScriptNode;
16
17 import java.util.Iterator;
18 import java.util.NoSuchElementException;
19
20 /**
21 * This class implements the root of the intermediate representation.
22 *
23 * @author Norris Boyd
24 * @author Mike McCabe
25 */
26 public class Node implements Iterable<Node>
27 {
28 public static final int
29 FUNCTION_PROP = 1,
30 LOCAL_PROP = 2,
31 LOCAL_BLOCK_PROP = 3,
32 REGEXP_PROP = 4,
33 CASEARRAY_PROP = 5,
34
35 // the following properties are defined and manipulated by the
36 // optimizer -
37 // TARGETBLOCK_PROP - the block referenced by a branch node
38 // VARIABLE_PROP - the variable referenced by a BIND or NAME node
39 // ISNUMBER_PROP - this node generates code on Number children and
40 // delivers a Number result (as opposed to Objects)
41 // DIRECTCALL_PROP - this call node should emit code to test the function
42 // object against the known class and call direct if it
43 // matches.
44
45 TARGETBLOCK_PROP = 6,
46 VARIABLE_PROP = 7,
47 ISNUMBER_PROP = 8,
48 DIRECTCALL_PROP = 9,
49 SPECIALCALL_PROP = 10,
50 SKIP_INDEXES_PROP = 11, // array of skipped indexes of array literal
51 OBJECT_IDS_PROP = 12, // array of properties for object literal
52 INCRDECR_PROP = 13, // pre or post type of increment/decrement
53 CATCH_SCOPE_PROP = 14, // index of catch scope block in catch
54 LABEL_ID_PROP = 15, // label id: code generation uses it
55 MEMBER_TYPE_PROP = 16, // type of element access operation
56 NAME_PROP = 17, // property name
57 CONTROL_BLOCK_PROP = 18, // flags a control block that can drop off
58 PARENTHESIZED_PROP = 19, // expression is parenthesized
59 GENERATOR_END_PROP = 20,
60 DESTRUCTURING_ARRAY_LENGTH = 21,
61 DESTRUCTURING_NAMES = 22,
62 DESTRUCTURING_PARAMS = 23,
63 JSDOC_PROP = 24,
64 EXPRESSION_CLOSURE_PROP = 25, // JS 1.8 expression closure pseudo-return
65 DESTRUCTURING_SHORTHAND = 26, // JS 1.8 destructuring shorthand
66 ARROW_FUNCTION_PROP = 27,
67 LAST_PROP = 27;
68
69 // values of ISNUMBER_PROP to specify
70 // which of the children are Number types
71 public static final int
72 BOTH = 0,
73 LEFT = 1,
74 RIGHT = 2;
75
76 public static final int // values for SPECIALCALL_PROP
77 NON_SPECIALCALL = 0,
78 SPECIALCALL_EVAL = 1,
79 SPECIALCALL_WITH = 2;
80
81 public static final int // flags for INCRDECR_PROP
82 DECR_FLAG = 0x1,
83 POST_FLAG = 0x2;
84
85 public static final int // flags for MEMBER_TYPE_PROP
86 PROPERTY_FLAG = 0x1, // property access: element is valid name
87 ATTRIBUTE_FLAG = 0x2, // x.@y or x..@y
88 DESCENDANTS_FLAG = 0x4; // x..y or x..@i
89
90 private static class PropListItem
91 {
92 PropListItem next;
93 int type;
94 int intValue;
95 Object objectValue;
96 }
97
98 public Node(int nodeType) {
99 type = nodeType;
100 }
101
102 public Node(int nodeType, Node child) {
103 type = nodeType;
104 first = last = child;
105 child.next = null;
106 }
107
108 public Node(int nodeType, Node left, Node right) {
109 type = nodeType;
110 first = left;
111 last = right;
112 left.next = right;
113 right.next = null;
114 }
115
116 public Node(int nodeType, Node left, Node mid, Node right) {
117 type = nodeType;
118 first = left;
119 last = right;
120 left.next = mid;
121 mid.next = right;
122 right.next = null;
123 }
124
125 public Node(int nodeType, int line) {
126 type = nodeType;
127 lineno = line;
128 }
129
130 public Node(int nodeType, Node child, int line) {
131 this(nodeType, child);
132 lineno = line;
133 }
134
135 public Node(int nodeType, Node left, Node right, int line) {
136 this(nodeType, left, right);
137 lineno = line;
138 }
139
140 public Node(int nodeType, Node left, Node mid, Node right, int line) {
141 this(nodeType, left, mid, right);
142 lineno = line;
143 }
144
145 public static Node newNumber(double number) {
146 NumberLiteral n = new NumberLiteral();
147 n.setNumber(number);
148 return n;
149 }
150
151 public static Node newString(String str) {
152 return newString(Token.STRING, str);
153 }
154
155 public static Node newString(int type, String str) {
156 Name name = new Name();
157 name.setIdentifier(str);
158 name.setType(type);
159 return name;
160 }
161
162 public int getType() {
163 return type;
164 }
165
166 /**
167 * Sets the node type and returns this node.
168 */
169 public Node setType(int type) {
170 this.type = type;
171 return this;
172 }
173
174 /**
175 * Gets the JsDoc comment string attached to this node.
176 * @return the comment string or {@code null} if no JsDoc is attached to
177 * this node
178 */
179 public String getJsDoc() {
180 Comment comment = getJsDocNode();
181 if (comment != null) {
182 return comment.getValue();
183 }
184 return null;
185 }
186
187 /**
188 * Gets the JsDoc Comment object attached to this node.
189 * @return the Comment or {@code null} if no JsDoc is attached to
190 * this node
191 */
192 public Comment getJsDocNode() {
193 return (Comment) getProp(JSDOC_PROP);
194 }
195
196 /**
197 * Sets the JsDoc comment string attached to this node.
198 */
199 public void setJsDocNode(Comment jsdocNode) {
200 putProp(JSDOC_PROP, jsdocNode);
201 }
202
203 public boolean hasChildren() {
204 return first != null;
205 }
206
207 public Node getFirstChild() {
208 return first;
209 }
210
211 public Node getLastChild() {
212 return last;
213 }
214
215 public Node getNext() {
216 return next;
217 }
218
219 public Node getChildBefore(Node child) {
220 if (child == first)
221 return null;
222 Node n = first;
223 while (n.next != child) {
224 n = n.next;
225 if (n == null)
226 throw new RuntimeException("node is not a child");
227 }
228 return n;
229 }
230
231 public Node getLastSibling() {
232 Node n = this;
233 while (n.next != null) {
234 n = n.next;
235 }
236 return n;
237 }
238
239 public void addChildToFront(Node child) {
240 child.next = first;
241 first = child;
242 if (last == null) {
243 last = child;
244 }
245 }
246
247 public void addChildToBack(Node child) {
248 child.next = null;
249 if (last == null) {
250 first = last = child;
251 return;
252 }
253 last.next = child;
254 last = child;
255 }
256
257 public void addChildrenToFront(Node children) {
258 Node lastSib = children.getLastSibling();
259 lastSib.next = first;
260 first = children;
261 if (last == null) {
262 last = lastSib;
263 }
264 }
265
266 public void addChildrenToBack(Node children) {
267 if (last != null) {
268 last.next = children;
269 }
270 last = children.getLastSibling();
271 if (first == null) {
272 first = children;
273 }
274 }
275
276 /**
277 * Add 'child' before 'node'.
278 */
279 public void addChildBefore(Node newChild, Node node) {
280 if (newChild.next != null)
281 throw new RuntimeException(
282 "newChild had siblings in addChildBefore");
283 if (first == node) {
284 newChild.next = first;
285 first = newChild;
286 return;
287 }
288 Node prev = getChildBefore(node);
289 addChildAfter(newChild, prev);
290 }
291
292 /**
293 * Add 'child' after 'node'.
294 */
295 public void addChildAfter(Node newChild, Node node) {
296 if (newChild.next != null)
297 throw new RuntimeException(
298 "newChild had siblings in addChildAfter");
299 newChild.next = node.next;
300 node.next = newChild;
301 if (last == node)
302 last = newChild;
303 }
304
305 public void removeChild(Node child) {
306 Node prev = getChildBefore(child);
307 if (prev == null)
308 first = first.next;
309 else
310 prev.next = child.next;
311 if (child == last) last = prev;
312 child.next = null;
313 }
314
315 public void replaceChild(Node child, Node newChild) {
316 newChild.next = child.next;
317 if (child == first) {
318 first = newChild;
319 } else {
320 Node prev = getChildBefore(child);
321 prev.next = newChild;
322 }
323 if (child == last)
324 last = newChild;
325 child.next = null;
326 }
327
328 public void replaceChildAfter(Node prevChild, Node newChild) {
329 Node child = prevChild.next;
330 newChild.next = child.next;
331 prevChild.next = newChild;
332 if (child == last)
333 last = newChild;
334 child.next = null;
335 }
336
337 public void removeChildren() {
338 first = last = null;
339 }
340
341 private static final Node NOT_SET = new Node(Token.ERROR);
342
343 /**
344 * Iterates over the children of this Node. Supports child removal. Not
345 * thread-safe. If anyone changes the child list before the iterator
346 * finishes, the results are undefined and probably bad.
347 */
348 public class NodeIterator implements Iterator<Node> {
349 private Node cursor; // points to node to be returned next
350 private Node prev = NOT_SET;
351 private Node prev2;
352 private boolean removed = false;
353
354 public NodeIterator() {
355 cursor = Node.this.first;
356 }
357
358 public boolean hasNext() {
359 return cursor != null;
360 }
361
362 public Node next() {
363 if (cursor == null) {
364 throw new NoSuchElementException();
365 }
366 removed = false;
367 prev2 = prev;
368 prev = cursor;
369 cursor = cursor.next;
370 return prev;
371 }
372
373 public void remove() {
374 if (prev == NOT_SET) {
375 throw new IllegalStateException("next() has not been called");
376 }
377 if (removed) {
378 throw new IllegalStateException(
379 "remove() already called for current element");
380 }
381 if (prev == first) {
382 first = prev.next;
383 } else if (prev == last) {
384 prev2.next = null;
385 last = prev2;
386 } else {
387 prev2.next = cursor;
388 }
389 }
390 }
391
392 /**
393 * Returns an {@link java.util.Iterator} over the node's children.
394 */
395 public Iterator<Node> iterator() {
396 return new NodeIterator();
397 }
398
399 private static final String propToString(int propType)
400 {
401 if (Token.printTrees) {
402 // If Context.printTrees is false, the compiler
403 // can remove all these strings.
404 switch (propType) {
405 case FUNCTION_PROP: return "function";
406 case LOCAL_PROP: return "local";
407 case LOCAL_BLOCK_PROP: return "local_block";
408 case REGEXP_PROP: return "regexp";
409 case CASEARRAY_PROP: return "casearray";
410
411 case TARGETBLOCK_PROP: return "targetblock";
412 case VARIABLE_PROP: return "variable";
413 case ISNUMBER_PROP: return "isnumber";
414 case DIRECTCALL_PROP: return "directcall";
415
416 case SPECIALCALL_PROP: return "specialcall";
417 case SKIP_INDEXES_PROP: return "skip_indexes";
418 case OBJECT_IDS_PROP: return "object_ids_prop";
419 case INCRDECR_PROP: return "incrdecr_prop";
420 case CATCH_SCOPE_PROP: return "catch_scope_prop";
421 case LABEL_ID_PROP: return "label_id_prop";
422 case MEMBER_TYPE_PROP: return "member_type_prop";
423 case NAME_PROP: return "name_prop";
424 case CONTROL_BLOCK_PROP: return "control_block_prop";
425 case PARENTHESIZED_PROP: return "parenthesized_prop";
426 case GENERATOR_END_PROP: return "generator_end";
427 case DESTRUCTURING_ARRAY_LENGTH:
428 return "destructuring_array_length";
429 case DESTRUCTURING_NAMES: return "destructuring_names";
430 case DESTRUCTURING_PARAMS: return "destructuring_params";
431
432 default: Kit.codeBug();
433 }
434 }
435 return null;
436 }
437
438 private PropListItem lookupProperty(int propType)
439 {
440 PropListItem x = propListHead;
441 while (x != null && propType != x.type) {
442 x = x.next;
443 }
444 return x;
445 }
446
447 private PropListItem ensureProperty(int propType)
448 {
449 PropListItem item = lookupProperty(propType);
450 if (item == null) {
451 item = new PropListItem();
452 item.type = propType;
453 item.next = propListHead;
454 propListHead = item;
455 }
456 return item;
457 }
458
459 public void removeProp(int propType)
460 {
461 PropListItem x = propListHead;
462 if (x != null) {
463 PropListItem prev = null;
464 while (x.type != propType) {
465 prev = x;
466 x = x.next;
467 if (x == null) { return; }
468 }
469 if (prev == null) {
470 propListHead = x.next;
471 } else {
472 prev.next = x.next;
473 }
474 }
475 }
476
477 public Object getProp(int propType)
478 {
479 PropListItem item = lookupProperty(propType);
480 if (item == null) { return null; }
481 return item.objectValue;
482 }
483
484 public int getIntProp(int propType, int defaultValue)
485 {
486 PropListItem item = lookupProperty(propType);
487 if (item == null) { return defaultValue; }
488 return item.intValue;
489 }
490
491 public int getExistingIntProp(int propType)
492 {
493 PropListItem item = lookupProperty(propType);
494 if (item == null) { Kit.codeBug(); }
495 return item.intValue;
496 }
497
498 public void putProp(int propType, Object prop)
499 {
500 if (prop == null) {
501 removeProp(propType);
502 } else {
503 PropListItem item = ensureProperty(propType);
504 item.objectValue = prop;
505 }
506 }
507
508 public void putIntProp(int propType, int prop)
509 {
510 PropListItem item = ensureProperty(propType);
511 item.intValue = prop;
512 }
513
514 /**
515 * Return the line number recorded for this node.
516 * @return the line number
517 */
518 public int getLineno() {
519 return lineno;
520 }
521
522 public void setLineno(int lineno) {
523 this.lineno = lineno;
524 }
525
526 /** Can only be called when <tt>getType() == Token.NUMBER</tt> */
527 public final double getDouble() {
528 return ((NumberLiteral)this).getNumber();
529 }
530
531 public final void setDouble(double number) {
532 ((NumberLiteral)this).setNumber(number);
533 }
534
535 /** Can only be called when node has String context. */
536 public final String getString() {
537 return ((Name)this).getIdentifier();
538 }
539
540 /** Can only be called when node has String context. */
541 public final void setString(String s) {
542 if (s == null) Kit.codeBug();
543 ((Name)this).setIdentifier(s);
544 }
545
546 /** Can only be called when node has String context. */
547 public Scope getScope() {
548 return ((Name)this).getScope();
549 }
550
551 /** Can only be called when node has String context. */
552 public void setScope(Scope s) {
553 if (s == null) Kit.codeBug();
554 if (!(this instanceof Name)) {
555 throw Kit.codeBug();
556 }
557 ((Name)this).setScope(s);
558 }
559
560 public static Node newTarget()
561 {
562 return new Node(Token.TARGET);
563 }
564
565 public final int labelId()
566 {
567 if (type != Token.TARGET && type != Token.YIELD) Kit.codeBug();
568 return getIntProp(LABEL_ID_PROP, -1);
569 }
570
571 public void labelId(int labelId)
572 {
573 if (type != Token.TARGET && type != Token.YIELD) Kit.codeBug();
574 putIntProp(LABEL_ID_PROP, labelId);
575 }
576
577
578 /**
579 * Does consistent-return analysis on the function body when strict mode is
580 * enabled.
581 *
582 * function (x) { return (x+1) }
583 * is ok, but
584 * function (x) { if (x &lt; 0) return (x+1); }
585 * is not becuase the function can potentially return a value when the
586 * condition is satisfied and if not, the function does not explicitly
587 * return value.
588 *
589 * This extends to checking mismatches such as "return" and "return <value>"
590 * used in the same function. Warnings are not emitted if inconsistent
591 * returns exist in code that can be statically shown to be unreachable.
592 * Ex.
593 * <pre>function (x) { while (true) { ... if (..) { return value } ... } }
594 * </pre>
595 * emits no warning. However if the loop had a break statement, then a
596 * warning would be emitted.
597 *
598 * The consistency analysis looks at control structures such as loops, ifs,
599 * switch, try-catch-finally blocks, examines the reachable code paths and
600 * warns the user about an inconsistent set of termination possibilities.
601 *
602 * Caveat: Since the parser flattens many control structures into almost
603 * straight-line code with gotos, it makes such analysis hard. Hence this
604 * analyser is written to taken advantage of patterns of code generated by
605 * the parser (for loops, try blocks and such) and does not do a full
606 * control flow analysis of the gotos and break/continue statements.
607 * Future changes to the parser will affect this analysis.
608 */
609
610 /**
611 * These flags enumerate the possible ways a statement/function can
612 * terminate. These flags are used by endCheck() and by the Parser to
613 * detect inconsistent return usage.
614 *
615 * END_UNREACHED is reserved for code paths that are assumed to always be
616 * able to execute (example: throw, continue)
617 *
618 * END_DROPS_OFF indicates if the statement can transfer control to the
619 * next one. Statement such as return dont. A compound statement may have
620 * some branch that drops off control to the next statement.
621 *
622 * END_RETURNS indicates that the statement can return (without arguments)
623 * END_RETURNS_VALUE indicates that the statement can return a value.
624 *
625 * A compound statement such as
626 * if (condition) {
627 * return value;
628 * }
629 * Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
630 */
631 public static final int END_UNREACHED = 0;
632 public static final int END_DROPS_OFF = 1;
633 public static final int END_RETURNS = 2;
634 public static final int END_RETURNS_VALUE = 4;
635 public static final int END_YIELDS = 8;
636
637 /**
638 * Checks that every return usage in a function body is consistent with the
639 * requirements of strict-mode.
640 * @return true if the function satisfies strict mode requirement.
641 */
642 public boolean hasConsistentReturnUsage()
643 {
644 int n = endCheck();
645 return (n & END_RETURNS_VALUE) == 0 ||
646 (n & (END_DROPS_OFF|END_RETURNS|END_YIELDS)) == 0;
647 }
648
649 /**
650 * Returns in the then and else blocks must be consistent with each other.
651 * If there is no else block, then the return statement can fall through.
652 * @return logical OR of END_* flags
653 */
654 private int endCheckIf()
655 {
656 Node th, el;
657 int rv = END_UNREACHED;
658
659 th = next;
660 el = ((Jump)this).target;
661
662 rv = th.endCheck();
663
664 if (el != null)
665 rv |= el.endCheck();
666 else
667 rv |= END_DROPS_OFF;
668
669 return rv;
670 }
671
672 /**
673 * Consistency of return statements is checked between the case statements.
674 * If there is no default, then the switch can fall through. If there is a
675 * default,we check to see if all code paths in the default return or if
676 * there is a code path that can fall through.
677 * @return logical OR of END_* flags
678 */
679 private int endCheckSwitch()
680 {
681 int rv = END_UNREACHED;
682
683 // examine the cases
684 // for (n = first.next; n != null; n = n.next)
685 // {
686 // if (n.type == Token.CASE) {
687 // rv |= ((Jump)n).target.endCheck();
688 // } else
689 // break;
690 // }
691
692 // // we don't care how the cases drop into each other
693 // rv &= ~END_DROPS_OFF;
694
695 // // examine the default
696 // n = ((Jump)this).getDefault();
697 // if (n != null)
698 // rv |= n.endCheck();
699 // else
700 // rv |= END_DROPS_OFF;
701
702 // // remove the switch block
703 // rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);
704
705 return rv;
706 }
707
708 /**
709 * If the block has a finally, return consistency is checked in the
710 * finally block. If all code paths in the finally returns, then the
711 * returns in the try-catch blocks don't matter. If there is a code path
712 * that does not return or if there is no finally block, the returns
713 * of the try and catch blocks are checked for mismatch.
714 * @return logical OR of END_* flags
715 */
716 private int endCheckTry()
717 {
718 int rv = END_UNREACHED;
719
720 // a TryStatement isn't a jump - needs rewriting
721
722 // check the finally if it exists
723 // n = ((Jump)this).getFinally();
724 // if(n != null) {
725 // rv = n.next.first.endCheck();
726 // } else {
727 // rv = END_DROPS_OFF;
728 // }
729
730 // // if the finally block always returns, then none of the returns
731 // // in the try or catch blocks matter
732 // if ((rv & END_DROPS_OFF) != 0) {
733 // rv &= ~END_DROPS_OFF;
734
735 // // examine the try block
736 // rv |= first.endCheck();
737
738 // // check each catch block
739 // n = ((Jump)this).target;
740 // if (n != null)
741 // {
742 // // point to the first catch_scope
743 // for (n = n.next.first; n != null; n = n.next.next)
744 // {
745 // // check the block of user code in the catch_scope
746 // rv |= n.next.first.next.first.endCheck();
747 // }
748 // }
749 // }
750
751 return rv;
752 }
753
754 /**
755 * Return statement in the loop body must be consistent. The default
756 * assumption for any kind of a loop is that it will eventually terminate.
757 * The only exception is a loop with a constant true condition. Code that
758 * follows such a loop is examined only if one can statically determine
759 * that there is a break out of the loop.
760 * <pre>
761 * for(&lt;&gt; ; &lt;&gt;; &lt;&gt;) {}
762 * for(&lt;&gt; in &lt;&gt; ) {}
763 * while(&lt;&gt;) { }
764 * do { } while(&lt;&gt;)
765 * </pre>
766 * @return logical OR of END_* flags
767 */
768 private int endCheckLoop()
769 {
770 Node n;
771 int rv = END_UNREACHED;
772
773 // To find the loop body, we look at the second to last node of the
774 // loop node, which should be the predicate that the loop should
775 // satisfy.
776 // The target of the predicate is the loop-body for all 4 kinds of
777 // loops.
778 for (n = first; n.next != last; n = n.next) {
779 /* skip */
780 }
781 if (n.type != Token.IFEQ)
782 return END_DROPS_OFF;
783
784 // The target's next is the loop body block
785 rv = ((Jump)n).target.next.endCheck();
786
787 // check to see if the loop condition is true
788 if (n.first.type == Token.TRUE)
789 rv &= ~END_DROPS_OFF;
790
791 // look for effect of breaks
792 rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);
793
794 return rv;
795 }
796
797 /**
798 * A general block of code is examined statement by statement. If any
799 * statement (even compound ones) returns in all branches, then subsequent
800 * statements are not examined.
801 * @return logical OR of END_* flags
802 */
803 private int endCheckBlock()
804 {
805 Node n;
806 int rv = END_DROPS_OFF;
807
808 // check each statment and if the statement can continue onto the next
809 // one, then check the next statement
810 for (n=first; ((rv & END_DROPS_OFF) != 0) && n != null; n = n.next)
811 {
812 rv &= ~END_DROPS_OFF;
813 rv |= n.endCheck();
814 }
815 return rv;
816 }
817
818 /**
819 * A labelled statement implies that there maybe a break to the label. The
820 * function processes the labelled statement and then checks the
821 * CONTROL_BLOCK_PROP property to see if there is ever a break to the
822 * particular label.
823 * @return logical OR of END_* flags
824 */
825 private int endCheckLabel()
826 {
827 int rv = END_UNREACHED;
828
829 rv = next.endCheck();
830 rv |= getIntProp(CONTROL_BLOCK_PROP, END_UNREACHED);
831
832 return rv;
833 }
834
835 /**
836 * When a break is encountered annotate the statement being broken
837 * out of by setting its CONTROL_BLOCK_PROP property.
838 * @return logical OR of END_* flags
839 */
840 private int endCheckBreak()
841 {
842 Node n = ((Jump) this).getJumpStatement();
843 n.putIntProp(CONTROL_BLOCK_PROP, END_DROPS_OFF);
844 return END_UNREACHED;
845 }
846
847 /**
848 * endCheck() examines the body of a function, doing a basic reachability
849 * analysis and returns a combination of flags END_* flags that indicate
850 * how the function execution can terminate. These constitute only the
851 * pessimistic set of termination conditions. It is possible that at
852 * runtime certain code paths will never be actually taken. Hence this
853 * analysis will flag errors in cases where there may not be errors.
854 * @return logical OR of END_* flags
855 */
856 private int endCheck()
857 {
858 switch(type)
859 {
860 case Token.BREAK:
861 return endCheckBreak();
862
863 case Token.EXPR_VOID:
864 if (this.first != null)
865 return first.endCheck();
866 return END_DROPS_OFF;
867
868 case Token.YIELD:
869 return END_YIELDS;
870
871 case Token.CONTINUE:
872 case Token.THROW:
873 return END_UNREACHED;
874
875 case Token.RETURN:
876 if (this.first != null)
877 return END_RETURNS_VALUE;
878 else
879 return END_RETURNS;
880
881 case Token.TARGET:
882 if (next != null)
883 return next.endCheck();
884 else
885 return END_DROPS_OFF;
886
887 case Token.LOOP:
888 return endCheckLoop();
889
890 case Token.LOCAL_BLOCK:
891 case Token.BLOCK:
892 // there are several special kinds of blocks
893 if (first == null)
894 return END_DROPS_OFF;
895
896 switch(first.type) {
897 case Token.LABEL:
898 return first.endCheckLabel();
899
900 case Token.IFNE:
901 return first.endCheckIf();
902
903 case Token.SWITCH:
904 return first.endCheckSwitch();
905
906 case Token.TRY:
907 return first.endCheckTry();
908
909 default:
910 return endCheckBlock();
911 }
912
913 default:
914 return END_DROPS_OFF;
915 }
916 }
917
918 public boolean hasSideEffects()
919 {
920 switch (type) {
921 case Token.EXPR_VOID:
922 case Token.COMMA:
923 if (last != null)
924 return last.hasSideEffects();
925 else
926 return true;
927
928 case Token.HOOK:
929 if (first == null ||
930 first.next == null ||
931 first.next.next == null)
932 Kit.codeBug();
933 return first.next.hasSideEffects() &&
934 first.next.next.hasSideEffects();
935
936 case Token.AND:
937 case Token.OR:
938 if (first == null || last == null)
939 Kit.codeBug();
940 return first.hasSideEffects() || last.hasSideEffects();
941
942 case Token.ERROR: // Avoid cascaded error messages
943 case Token.EXPR_RESULT:
944 case Token.ASSIGN:
945 case Token.ASSIGN_ADD:
946 case Token.ASSIGN_SUB:
947 case Token.ASSIGN_MUL:
948 case Token.ASSIGN_DIV:
949 case Token.ASSIGN_MOD:
950 case Token.ASSIGN_BITOR:
951 case Token.ASSIGN_BITXOR:
952 case Token.ASSIGN_BITAND:
953 case Token.ASSIGN_LSH:
954 case Token.ASSIGN_RSH:
955 case Token.ASSIGN_URSH:
956 case Token.ENTERWITH:
957 case Token.LEAVEWITH:
958 case Token.RETURN:
959 case Token.GOTO:
960 case Token.IFEQ:
961 case Token.IFNE:
962 case Token.NEW:
963 case Token.DELPROP:
964 case Token.SETNAME:
965 case Token.SETPROP:
966 case Token.SETELEM:
967 case Token.CALL:
968 case Token.THROW:
969 case Token.RETHROW:
970 case Token.SETVAR:
971 case Token.CATCH_SCOPE:
972 case Token.RETURN_RESULT:
973 case Token.SET_REF:
974 case Token.DEL_REF:
975 case Token.REF_CALL:
976 case Token.TRY:
977 case Token.SEMI:
978 case Token.INC:
979 case Token.DEC:
980 case Token.IF:
981 case Token.ELSE:
982 case Token.SWITCH:
983 case Token.WHILE:
984 case Token.DO:
985 case Token.FOR:
986 case Token.BREAK:
987 case Token.CONTINUE:
988 case Token.VAR:
989 case Token.CONST:
990 case Token.LET:
991 case Token.LETEXPR:
992 case Token.WITH:
993 case Token.WITHEXPR:
994 case Token.CATCH:
995 case Token.FINALLY:
996 case Token.BLOCK:
997 case Token.LABEL:
998 case Token.TARGET:
999 case Token.LOOP:
1000 case Token.JSR:
1001 case Token.SETPROP_OP:
1002 case Token.SETELEM_OP:
1003 case Token.LOCAL_BLOCK:
1004 case Token.SET_REF_OP:
1005 case Token.YIELD:
1006 return true;
1007
1008 default:
1009 return false;
1010 }
1011 }
1012
1013 /**
1014 * Recursively unlabel every TARGET or YIELD node in the tree.
1015 *
1016 * This is used and should only be used for inlining finally blocks where
1017 * jsr instructions used to be. It is somewhat hackish, but implementing
1018 * a clone() operation would take much, much more effort.
1019 *
1020 * This solution works for inlining finally blocks because you should never
1021 * be writing any given block to the class file simultaneously. Therefore,
1022 * an unlabeling will never occur in the middle of a block.
1023 */
1024 public void resetTargets()
1025 {
1026 if (type == Token.FINALLY) {
1027 resetTargets_r();
1028 } else {
1029 Kit.codeBug();
1030 }
1031 }
1032
1033 private void resetTargets_r()
1034 {
1035 if (type == Token.TARGET || type == Token.YIELD) {
1036 labelId(-1);
1037 }
1038 Node child = first;
1039 while (child != null) {
1040 child.resetTargets_r();
1041 child = child.next;
1042 }
1043 }
1044
1045 @Override
1046 public String toString()
1047 {
1048 if (Token.printTrees) {
1049 StringBuilder sb = new StringBuilder();
1050 toString(new ObjToIntMap(), sb);
1051 return sb.toString();
1052 }
1053 return String.valueOf(type);
1054 }
1055
1056 private void toString(ObjToIntMap printIds, StringBuilder sb)
1057 {
1058 if (Token.printTrees) {
1059 sb.append(Token.name(type));
1060 if (this instanceof Name) {
1061 sb.append(' ');
1062 sb.append(getString());
1063 Scope scope = getScope();
1064 if (scope != null) {
1065 sb.append("[scope: ");
1066 appendPrintId(scope, printIds, sb);
1067 sb.append("]");
1068 }
1069 } else if (this instanceof Scope) {
1070 if (this instanceof ScriptNode) {
1071 ScriptNode sof = (ScriptNode)this;
1072 if (this instanceof FunctionNode) {
1073 FunctionNode fn = (FunctionNode)this;
1074 sb.append(' ');
1075 sb.append(fn.getName());
1076 }
1077 sb.append(" [source name: ");
1078 sb.append(sof.getSourceName());
1079 sb.append("] [encoded source length: ");
1080 sb.append(sof.getEncodedSourceEnd()
1081 - sof.getEncodedSourceStart());
1082 sb.append("] [base line: ");
1083 sb.append(sof.getBaseLineno());
1084 sb.append("] [end line: ");
1085 sb.append(sof.getEndLineno());
1086 sb.append(']');
1087 }
1088 if (((Scope)this).getSymbolTable() != null) {
1089 sb.append(" [scope ");
1090 appendPrintId(this, printIds, sb);
1091 sb.append(": ");
1092 Iterator<String> iter =
1093 ((Scope) this).getSymbolTable().keySet().iterator();
1094 while (iter.hasNext()) {
1095 sb.append(iter.next());
1096 sb.append(" ");
1097 }
1098 sb.append("]");
1099 }
1100 } else if (this instanceof Jump) {
1101 Jump jump = (Jump)this;
1102 if (type == Token.BREAK || type == Token.CONTINUE) {
1103 sb.append(" [label: ");
1104 appendPrintId(jump.getJumpStatement(), printIds, sb);
1105 sb.append(']');
1106 } else if (type == Token.TRY) {
1107 Node catchNode = jump.target;
1108 Node finallyTarget = jump.getFinally();
1109 if (catchNode != null) {
1110 sb.append(" [catch: ");
1111 appendPrintId(catchNode, printIds, sb);
1112 sb.append(']');
1113 }
1114 if (finallyTarget != null) {
1115 sb.append(" [finally: ");
1116 appendPrintId(finallyTarget, printIds, sb);
1117 sb.append(']');
1118 }
1119 } else if (type == Token.LABEL || type == Token.LOOP
1120 || type == Token.SWITCH)
1121 {
1122 sb.append(" [break: ");
1123 appendPrintId(jump.target, printIds, sb);
1124 sb.append(']');
1125 if (type == Token.LOOP) {
1126 sb.append(" [continue: ");
1127 appendPrintId(jump.getContinue(), printIds, sb);
1128 sb.append(']');
1129 }
1130 } else {
1131 sb.append(" [target: ");
1132 appendPrintId(jump.target, printIds, sb);
1133 sb.append(']');
1134 }
1135 } else if (type == Token.NUMBER) {
1136 sb.append(' ');
1137 sb.append(getDouble());
1138 } else if (type == Token.TARGET) {
1139 sb.append(' ');
1140 appendPrintId(this, printIds, sb);
1141 }
1142 if (lineno != -1) {
1143 sb.append(' ');
1144 sb.append(lineno);
1145 }
1146
1147 for (PropListItem x = propListHead; x != null; x = x.next) {
1148 int type = x.type;
1149 sb.append(" [");
1150 sb.append(propToString(type));
1151 sb.append(": ");
1152 String value;
1153 switch (type) {
1154 case TARGETBLOCK_PROP : // can't add this as it recurses
1155 value = "target block property";
1156 break;
1157 case LOCAL_BLOCK_PROP : // can't add this as it is dull
1158 value = "last local block";
1159 break;
1160 case ISNUMBER_PROP:
1161 switch (x.intValue) {
1162 case BOTH:
1163 value = "both";
1164 break;
1165 case RIGHT:
1166 value = "right";
1167 break;
1168 case LEFT:
1169 value = "left";
1170 break;
1171 default:
1172 throw Kit.codeBug();
1173 }
1174 break;
1175 case SPECIALCALL_PROP:
1176 switch (x.intValue) {
1177 case SPECIALCALL_EVAL:
1178 value = "eval";
1179 break;
1180 case SPECIALCALL_WITH:
1181 value = "with";
1182 break;
1183 default:
1184 // NON_SPECIALCALL should not be stored
1185 throw Kit.codeBug();
1186 }
1187 break;
1188 case OBJECT_IDS_PROP: {
1189 Object[] a = (Object[]) x.objectValue;
1190 value = "[";
1191 for (int i=0; i < a.length; i++) {
1192 value += a[i].toString();
1193 if (i+1 < a.length)
1194 value += ", ";
1195 }
1196 value += "]";
1197 break;
1198 }
1199 default :
1200 Object obj = x.objectValue;
1201 if (obj != null) {
1202 value = obj.toString();
1203 } else {
1204 value = String.valueOf(x.intValue);
1205 }
1206 break;
1207 }
1208 sb.append(value);
1209 sb.append(']');
1210 }
1211 }
1212 }
1213
1214 public String toStringTree(ScriptNode treeTop) {
1215 if (Token.printTrees) {
1216 StringBuilder sb = new StringBuilder();
1217 toStringTreeHelper(treeTop, this, null, 0, sb);
1218 return sb.toString();
1219 }
1220 return null;
1221 }
1222
1223 private static void toStringTreeHelper(ScriptNode treeTop, Node n,
1224 ObjToIntMap printIds,
1225 int level, StringBuilder sb)
1226 {
1227 if (Token.printTrees) {
1228 if (printIds == null) {
1229 printIds = new ObjToIntMap();
1230 generatePrintIds(treeTop, printIds);
1231 }
1232 for (int i = 0; i != level; ++i) {
1233 sb.append(" ");
1234 }
1235 n.toString(printIds, sb);
1236 sb.append('\n');
1237 for (Node cursor = n.getFirstChild(); cursor != null;
1238 cursor = cursor.getNext())
1239 {
1240 if (cursor.getType() == Token.FUNCTION) {
1241 int fnIndex = cursor.getExistingIntProp(Node.FUNCTION_PROP);
1242 FunctionNode fn = treeTop.getFunctionNode(fnIndex);
1243 toStringTreeHelper(fn, fn, null, level + 1, sb);
1244 } else {
1245 toStringTreeHelper(treeTop, cursor, printIds, level+1, sb);
1246 }
1247 }
1248 }
1249 }
1250
1251 private static void generatePrintIds(Node n, ObjToIntMap map)
1252 {
1253 if (Token.printTrees) {
1254 map.put(n, map.size());
1255 for (Node cursor = n.getFirstChild(); cursor != null;
1256 cursor = cursor.getNext())
1257 {
1258 generatePrintIds(cursor, map);
1259 }
1260 }
1261 }
1262
1263 private static void appendPrintId(Node n, ObjToIntMap printIds,
1264 StringBuilder sb)
1265 {
1266 if (Token.printTrees) {
1267 if (n != null) {
1268 int id = printIds.get(n, -1);
1269 sb.append('#');
1270 if (id != -1) {
1271 sb.append(id + 1);
1272 } else {
1273 sb.append("<not_available>");
1274 }
1275 }
1276 }
1277 }
1278
1279 protected int type = Token.ERROR; // type of the node, e.g. Token.NAME
1280 protected Node next; // next sibling
1281 protected Node first; // first element of a linked list of children
1282 protected Node last; // last element of a linked list of children
1283 protected int lineno = -1;
1284
1285 /**
1286 * Linked list of properties. Since vast majority of nodes would have
1287 * no more then 2 properties, linked list saves memory and provides
1288 * fast lookup. If this does not holds, propListHead can be replaced
1289 * by UintMap.
1290 */
1291 protected PropListItem propListHead;
1292 }