Debian Codegraph @

rhino/src/org/mozilla/javascript/IRFactory.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.ArrayComprehension;
10 import org.mozilla.javascript.ast.ArrayComprehensionLoop;
11 import org.mozilla.javascript.ast.ArrayLiteral;
12 import org.mozilla.javascript.ast.Assignment;
13 import org.mozilla.javascript.ast.AstNode;
14 import org.mozilla.javascript.ast.AstRoot;
15 import org.mozilla.javascript.ast.Block;
16 import org.mozilla.javascript.ast.BreakStatement;
17 import org.mozilla.javascript.ast.CatchClause;
18 import org.mozilla.javascript.ast.ConditionalExpression;
19 import org.mozilla.javascript.ast.ContinueStatement;
20 import org.mozilla.javascript.ast.DestructuringForm;
21 import org.mozilla.javascript.ast.DoLoop;
22 import org.mozilla.javascript.ast.ElementGet;
23 import org.mozilla.javascript.ast.EmptyExpression;
24 import org.mozilla.javascript.ast.ExpressionStatement;
25 import org.mozilla.javascript.ast.ForInLoop;
26 import org.mozilla.javascript.ast.ForLoop;
27 import org.mozilla.javascript.ast.FunctionCall;
28 import org.mozilla.javascript.ast.FunctionNode;
29 import org.mozilla.javascript.ast.GeneratorExpression;
30 import org.mozilla.javascript.ast.GeneratorExpressionLoop;
31 import org.mozilla.javascript.ast.IfStatement;
32 import org.mozilla.javascript.ast.InfixExpression;
33 import org.mozilla.javascript.ast.Jump;
34 import org.mozilla.javascript.ast.Label;
35 import org.mozilla.javascript.ast.LabeledStatement;
36 import org.mozilla.javascript.ast.LetNode;
37 import org.mozilla.javascript.ast.Loop;
38 import org.mozilla.javascript.ast.Name;
39 import org.mozilla.javascript.ast.NewExpression;
40 import org.mozilla.javascript.ast.NumberLiteral;
41 import org.mozilla.javascript.ast.ObjectLiteral;
42 import org.mozilla.javascript.ast.ObjectProperty;
43 import org.mozilla.javascript.ast.ParenthesizedExpression;
44 import org.mozilla.javascript.ast.PropertyGet;
45 import org.mozilla.javascript.ast.RegExpLiteral;
46 import org.mozilla.javascript.ast.ReturnStatement;
47 import org.mozilla.javascript.ast.Scope;
48 import org.mozilla.javascript.ast.ScriptNode;
49 import org.mozilla.javascript.ast.StringLiteral;
50 import org.mozilla.javascript.ast.SwitchCase;
51 import org.mozilla.javascript.ast.SwitchStatement;
52 import org.mozilla.javascript.ast.Symbol;
53 import org.mozilla.javascript.ast.ThrowStatement;
54 import org.mozilla.javascript.ast.TryStatement;
55 import org.mozilla.javascript.ast.UnaryExpression;
56 import org.mozilla.javascript.ast.VariableDeclaration;
57 import org.mozilla.javascript.ast.VariableInitializer;
58 import org.mozilla.javascript.ast.WhileLoop;
59 import org.mozilla.javascript.ast.WithStatement;
60 import org.mozilla.javascript.ast.XmlDotQuery;
61 import org.mozilla.javascript.ast.XmlElemRef;
62 import org.mozilla.javascript.ast.XmlExpression;
63 import org.mozilla.javascript.ast.XmlFragment;
64 import org.mozilla.javascript.ast.XmlLiteral;
65 import org.mozilla.javascript.ast.XmlMemberGet;
66 import org.mozilla.javascript.ast.XmlPropRef;
67 import org.mozilla.javascript.ast.XmlRef;
68 import org.mozilla.javascript.ast.XmlString;
69 import org.mozilla.javascript.ast.Yield;
70
71 import java.util.List;
72 import java.util.ArrayList;
73
74 /**
75 * This class rewrites the parse tree into an IR suitable for codegen.
76 *
77 * @see Node
78 * @author Mike McCabe
79 * @author Norris Boyd
80 */
81 public final class IRFactory extends Parser
82 {
83 private static final int LOOP_DO_WHILE = 0;
84 private static final int LOOP_WHILE = 1;
85 private static final int LOOP_FOR = 2;
86
87 private static final int ALWAYS_TRUE_BOOLEAN = 1;
88 private static final int ALWAYS_FALSE_BOOLEAN = -1;
89
90 private Decompiler decompiler = new Decompiler();
91
92 public IRFactory() {
93 super();
94 }
95
96 public IRFactory(CompilerEnvirons env) {
97 this(env, env.getErrorReporter());
98 }
99
100 public IRFactory(CompilerEnvirons env, ErrorReporter errorReporter) {
101 super(env, errorReporter);
102 }
103
104 /**
105 * Transforms the tree into a lower-level IR suitable for codegen.
106 * Optionally generates the encoded source.
107 */
108 public ScriptNode transformTree(AstRoot root) {
109 currentScriptOrFn = root;
110 this.inUseStrictDirective = root.isInStrictMode();
111 int sourceStartOffset = decompiler.getCurrentOffset();
112
113 if (Token.printTrees) {
114 System.out.println("IRFactory.transformTree");
115 System.out.println(root.debugPrint());
116 }
117 ScriptNode script = (ScriptNode)transform(root);
118
119 int sourceEndOffset = decompiler.getCurrentOffset();
120 script.setEncodedSourceBounds(sourceStartOffset,
121 sourceEndOffset);
122
123 if (compilerEnv.isGeneratingSource()) {
124 script.setEncodedSource(decompiler.getEncodedSource());
125 }
126
127 decompiler = null;
128 return script;
129 }
130
131 // Might want to convert this to polymorphism - move transform*
132 // functions into the AstNode subclasses. OTOH that would make
133 // IR transformation part of the public AST API - desirable?
134 // Another possibility: create AstTransformer interface and adapter.
135 public Node transform(AstNode node) {
136 switch (node.getType()) {
137 case Token.ARRAYCOMP:
138 return transformArrayComp((ArrayComprehension)node);
139 case Token.ARRAYLIT:
140 return transformArrayLiteral((ArrayLiteral)node);
141 case Token.BLOCK:
142 return transformBlock(node);
143 case Token.BREAK:
144 return transformBreak((BreakStatement)node);
145 case Token.CALL:
146 return transformFunctionCall((FunctionCall)node);
147 case Token.CONTINUE:
148 return transformContinue((ContinueStatement)node);
149 case Token.DO:
150 return transformDoLoop((DoLoop)node);
151 case Token.EMPTY:
152 return node;
153 case Token.FOR:
154 if (node instanceof ForInLoop) {
155 return transformForInLoop((ForInLoop)node);
156 } else {
157 return transformForLoop((ForLoop)node);
158 }
159 case Token.FUNCTION:
160 return transformFunction((FunctionNode)node);
161 case Token.GENEXPR:
162 return transformGenExpr((GeneratorExpression)node);
163 case Token.GETELEM:
164 return transformElementGet((ElementGet)node);
165 case Token.GETPROP:
166 return transformPropertyGet((PropertyGet)node);
167 case Token.HOOK:
168 return transformCondExpr((ConditionalExpression)node);
169 case Token.IF:
170 return transformIf((IfStatement)node);
171
172 case Token.TRUE:
173 case Token.FALSE:
174 case Token.THIS:
175 case Token.NULL:
176 case Token.DEBUGGER:
177 return transformLiteral(node);
178
179 case Token.NAME:
180 return transformName((Name)node);
181 case Token.NUMBER:
182 return transformNumber((NumberLiteral)node);
183 case Token.NEW:
184 return transformNewExpr((NewExpression)node);
185 case Token.OBJECTLIT:
186 return transformObjectLiteral((ObjectLiteral)node);
187 case Token.REGEXP:
188 return transformRegExp((RegExpLiteral)node);
189 case Token.RETURN:
190 return transformReturn((ReturnStatement)node);
191 case Token.SCRIPT:
192 return transformScript((ScriptNode)node);
193 case Token.STRING:
194 return transformString((StringLiteral)node);
195 case Token.SWITCH:
196 return transformSwitch((SwitchStatement)node);
197 case Token.THROW:
198 return transformThrow((ThrowStatement)node);
199 case Token.TRY:
200 return transformTry((TryStatement)node);
201 case Token.WHILE:
202 return transformWhileLoop((WhileLoop)node);
203 case Token.WITH:
204 return transformWith((WithStatement)node);
205 case Token.YIELD:
206 return transformYield((Yield)node);
207 default:
208 if (node instanceof ExpressionStatement) {
209 return transformExprStmt((ExpressionStatement)node);
210 }
211 if (node instanceof Assignment) {
212 return transformAssignment((Assignment)node);
213 }
214 if (node instanceof UnaryExpression) {
215 return transformUnary((UnaryExpression)node);
216 }
217 if (node instanceof XmlMemberGet) {
218 return transformXmlMemberGet((XmlMemberGet)node);
219 }
220 if (node instanceof InfixExpression) {
221 return transformInfix((InfixExpression)node);
222 }
223 if (node instanceof VariableDeclaration) {
224 return transformVariables((VariableDeclaration)node);
225 }
226 if (node instanceof ParenthesizedExpression) {
227 return transformParenExpr((ParenthesizedExpression)node);
228 }
229 if (node instanceof LabeledStatement) {
230 return transformLabeledStatement((LabeledStatement)node);
231 }
232 if (node instanceof LetNode) {
233 return transformLetNode((LetNode)node);
234 }
235 if (node instanceof XmlRef) {
236 return transformXmlRef((XmlRef)node);
237 }
238 if (node instanceof XmlLiteral) {
239 return transformXmlLiteral((XmlLiteral)node);
240 }
241 throw new IllegalArgumentException("Can't transform: " + node);
242 }
243 }
244
245 private Node transformArrayComp(ArrayComprehension node) {
246 // An array comprehension expression such as
247 //
248 // [expr for (x in foo) for each ([y, z] in bar) if (cond)]
249 //
250 // is rewritten approximately as
251 //
252 // new Scope(ARRAYCOMP) {
253 // new Node(BLOCK) {
254 // let tmp1 = new Array;
255 // for (let x in foo) {
256 // for each (let tmp2 in bar) {
257 // if (cond) {
258 // tmp1.push([y, z] = tmp2, expr);
259 // }
260 // }
261 // }
262 // }
263 // createName(tmp1)
264 // }
265
266 int lineno = node.getLineno();
267 Scope scopeNode = createScopeNode(Token.ARRAYCOMP, lineno);
268 String arrayName = currentScriptOrFn.getNextTempName();
269 pushScope(scopeNode);
270 try {
271 defineSymbol(Token.LET, arrayName, false);
272 Node block = new Node(Token.BLOCK, lineno);
273 Node newArray = createCallOrNew(Token.NEW, createName("Array"));
274 Node init = new Node(Token.EXPR_VOID,
275 createAssignment(Token.ASSIGN,
276 createName(arrayName),
277 newArray),
278 lineno);
279 block.addChildToBack(init);
280 block.addChildToBack(arrayCompTransformHelper(node, arrayName));
281 scopeNode.addChildToBack(block);
282 scopeNode.addChildToBack(createName(arrayName));
283 return scopeNode;
284 } finally {
285 popScope();
286 }
287 }
288
289 private Node arrayCompTransformHelper(ArrayComprehension node,
290 String arrayName) {
291 decompiler.addToken(Token.LB);
292 int lineno = node.getLineno();
293 Node expr = transform(node.getResult());
294
295 List<ArrayComprehensionLoop> loops = node.getLoops();
296 int numLoops = loops.size();
297
298 // Walk through loops, collecting and defining their iterator symbols.
299 Node[] iterators = new Node[numLoops];
300 Node[] iteratedObjs = new Node[numLoops];
301
302 for (int i = 0; i < numLoops; i++) {
303 ArrayComprehensionLoop acl = loops.get(i);
304 decompiler.addName(" ");
305 decompiler.addToken(Token.FOR);
306 if (acl.isForEach()) {
307 decompiler.addName("each ");
308 }
309 decompiler.addToken(Token.LP);
310
311 AstNode iter = acl.getIterator();
312 String name = null;
313 if (iter.getType() == Token.NAME) {
314 name = iter.getString();
315 decompiler.addName(name);
316 } else {
317 // destructuring assignment
318 decompile(iter);
319 name = currentScriptOrFn.getNextTempName();
320 defineSymbol(Token.LP, name, false);
321 expr = createBinary(Token.COMMA,
322 createAssignment(Token.ASSIGN,
323 iter,
324 createName(name)),
325 expr);
326 }
327 Node init = createName(name);
328 // Define as a let since we want the scope of the variable to
329 // be restricted to the array comprehension
330 defineSymbol(Token.LET, name, false);
331 iterators[i] = init;
332
333 if (acl.isForOf()) {
334 decompiler.addName("of ");
335 } else {
336 decompiler.addToken(Token.IN);
337 }
338 iteratedObjs[i] = transform(acl.getIteratedObject());
339 decompiler.addToken(Token.RP);
340 }
341
342 // generate code for tmpArray.push(body)
343 Node call = createCallOrNew(Token.CALL,
344 createPropertyGet(createName(arrayName),
345 null,
346 "push", 0));
347
348 Node body = new Node(Token.EXPR_VOID, call, lineno);
349
350 if (node.getFilter() != null) {
351 decompiler.addName(" ");
352 decompiler.addToken(Token.IF);
353 decompiler.addToken(Token.LP);
354 body = createIf(transform(node.getFilter()), body, null, lineno);
355 decompiler.addToken(Token.RP);
356 }
357
358 // Now walk loops in reverse to build up the body statement.
359 int pushed = 0;
360 try {
361 for (int i = numLoops-1; i >= 0; i--) {
362 ArrayComprehensionLoop acl = loops.get(i);
363 Scope loop = createLoopNode(null, // no label
364 acl.getLineno());
365 pushScope(loop);
366 pushed++;
367 body = createForIn(Token.LET,
368 loop,
369 iterators[i],
370 iteratedObjs[i],
371 body,
372 acl.isForEach(),
373 acl.isForOf());
374 }
375 } finally {
376 for (int i = 0; i < pushed; i++) {
377 popScope();
378 }
379 }
380
381 decompiler.addToken(Token.RB);
382
383 // Now that we've accumulated any destructuring forms,
384 // add expr to the call node; it's pushed on each iteration.
385 call.addChildToBack(expr);
386 return body;
387 }
388
389 private Node transformArrayLiteral(ArrayLiteral node) {
390 if (node.isDestructuring()) {
391 return node;
392 }
393 decompiler.addToken(Token.LB);
394 List<AstNode> elems = node.getElements();
395 Node array = new Node(Token.ARRAYLIT);
396 List<Integer> skipIndexes = null;
397 for (int i = 0; i < elems.size(); ++i) {
398 AstNode elem = elems.get(i);
399 if (elem.getType() != Token.EMPTY) {
400 array.addChildToBack(transform(elem));
401 } else {
402 if (skipIndexes == null) {
403 skipIndexes = new ArrayList<Integer>();
404 }
405 skipIndexes.add(i);
406 }
407 if (i < elems.size() - 1)
408 decompiler.addToken(Token.COMMA);
409 }
410 decompiler.addToken(Token.RB);
411 array.putIntProp(Node.DESTRUCTURING_ARRAY_LENGTH,
412 node.getDestructuringLength());
413 if (skipIndexes != null) {
414 int[] skips = new int[skipIndexes.size()];
415 for (int i = 0; i < skipIndexes.size(); i++)
416 skips[i] = skipIndexes.get(i);
417 array.putProp(Node.SKIP_INDEXES_PROP, skips);
418 }
419 return array;
420 }
421
422 private Node transformAssignment(Assignment node) {
423 AstNode left = removeParens(node.getLeft());
424 Node target = null;
425 if (isDestructuring(left)) {
426 decompile(left);
427 target = left;
428 } else {
429 target = transform(left);
430 }
431 decompiler.addToken(node.getType());
432 return createAssignment(node.getType(),
433 target,
434 transform(node.getRight()));
435 }
436
437 private Node transformBlock(AstNode node) {
438 if (node instanceof Scope) {
439 pushScope((Scope)node);
440 }
441 try {
442 List<Node> kids = new ArrayList<Node>();
443 for (Node kid : node) {
444 kids.add(transform((AstNode)kid));
445 }
446 node.removeChildren();
447 for (Node kid : kids) {
448 node.addChildToBack(kid);
449 }
450 return node;
451 } finally {
452 if (node instanceof Scope) {
453 popScope();
454 }
455 }
456 }
457
458 private Node transformBreak(BreakStatement node) {
459 decompiler.addToken(Token.BREAK);
460 if (node.getBreakLabel() != null) {
461 decompiler.addName(node.getBreakLabel().getIdentifier());
462 }
463 decompiler.addEOL(Token.SEMI);
464 return node;
465 }
466
467 private Node transformCondExpr(ConditionalExpression node) {
468 Node test = transform(node.getTestExpression());
469 decompiler.addToken(Token.HOOK);
470 Node ifTrue = transform(node.getTrueExpression());
471 decompiler.addToken(Token.COLON);
472 Node ifFalse = transform(node.getFalseExpression());
473 return createCondExpr(test, ifTrue, ifFalse);
474 }
475
476 private Node transformContinue(ContinueStatement node) {
477 decompiler.addToken(Token.CONTINUE);
478 if (node.getLabel() != null) {
479 decompiler.addName(node.getLabel().getIdentifier());
480 }
481 decompiler.addEOL(Token.SEMI);
482 return node;
483 }
484
485 private Node transformDoLoop(DoLoop loop) {
486 loop.setType(Token.LOOP);
487 pushScope(loop);
488 try {
489 decompiler.addToken(Token.DO);
490 decompiler.addEOL(Token.LC);
491 Node body = transform(loop.getBody());
492 decompiler.addToken(Token.RC);
493 decompiler.addToken(Token.WHILE);
494 decompiler.addToken(Token.LP);
495 Node cond = transform(loop.getCondition());
496 decompiler.addToken(Token.RP);
497 decompiler.addEOL(Token.SEMI);
498 return createLoop(loop, LOOP_DO_WHILE,
499 body, cond, null, null);
500 } finally {
501 popScope();
502 }
503 }
504
505 private Node transformElementGet(ElementGet node) {
506 // OPT: could optimize to createPropertyGet
507 // iff elem is string that can not be number
508 Node target = transform(node.getTarget());
509 decompiler.addToken(Token.LB);
510 Node element = transform(node.getElement());
511 decompiler.addToken(Token.RB);
512 return new Node(Token.GETELEM, target, element);
513 }
514
515 private Node transformExprStmt(ExpressionStatement node) {
516 Node expr = transform(node.getExpression());
517 decompiler.addEOL(Token.SEMI);
518 return new Node(node.getType(), expr, node.getLineno());
519 }
520
521 private Node transformForInLoop(ForInLoop loop) {
522 decompiler.addToken(Token.FOR);
523 if (loop.isForEach())
524 decompiler.addName("each ");
525 decompiler.addToken(Token.LP);
526
527 loop.setType(Token.LOOP);
528 pushScope(loop);
529 try {
530 int declType = -1;
531 AstNode iter = loop.getIterator();
532 if (iter instanceof VariableDeclaration) {
533 declType = ((VariableDeclaration)iter).getType();
534 }
535 Node lhs = transform(iter);
536 if (loop.isForOf()) {
537 decompiler.addName("of ");
538 } else {
539 decompiler.addToken(Token.IN);
540 }
541 Node obj = transform(loop.getIteratedObject());
542 decompiler.addToken(Token.RP);
543 decompiler.addEOL(Token.LC);
544 Node body = transform(loop.getBody());
545 decompiler.addEOL(Token.RC);
546 return createForIn(declType, loop, lhs, obj, body,
547 loop.isForEach(), loop.isForOf());
548 } finally {
549 popScope();
550 }
551 }
552
553 private Node transformForLoop(ForLoop loop) {
554 decompiler.addToken(Token.FOR);
555 decompiler.addToken(Token.LP);
556 loop.setType(Token.LOOP);
557 // XXX: Can't use pushScope/popScope here since 'createFor' may split
558 // the scope
559 Scope savedScope = currentScope;
560 currentScope = loop;
561 try {
562 Node init = transform(loop.getInitializer());
563 decompiler.addToken(Token.SEMI);
564 Node test = transform(loop.getCondition());
565 decompiler.addToken(Token.SEMI);
566 Node incr = transform(loop.getIncrement());
567 decompiler.addToken(Token.RP);
568 decompiler.addEOL(Token.LC);
569 Node body = transform(loop.getBody());
570 decompiler.addEOL(Token.RC);
571 return createFor(loop, init, test, incr, body);
572 } finally {
573 currentScope = savedScope;
574 }
575 }
576
577 private Node transformFunction(FunctionNode fn) {
578 int functionType = fn.getFunctionType();
579 int start = decompiler.markFunctionStart(functionType);
580 Node mexpr = decompileFunctionHeader(fn);
581 int index = currentScriptOrFn.addFunction(fn);
582
583 PerFunctionVariables savedVars = new PerFunctionVariables(fn);
584 try {
585 // If we start needing to record much more codegen metadata during
586 // function parsing, we should lump it all into a helper class.
587 Node destructuring = (Node)fn.getProp(Node.DESTRUCTURING_PARAMS);
588 fn.removeProp(Node.DESTRUCTURING_PARAMS);
589
590 int lineno = fn.getBody().getLineno();
591 ++nestingOfFunction; // only for body, not params
592 Node body = transform(fn.getBody());
593
594 if (!fn.isExpressionClosure()) {
595 decompiler.addToken(Token.RC);
596 }
597 fn.setEncodedSourceBounds(start, decompiler.markFunctionEnd(start));
598
599 if (functionType != FunctionNode.FUNCTION_EXPRESSION && !fn.isExpressionClosure()) {
600 // Add EOL only if function is not part of expression
601 // since it gets SEMI + EOL from Statement in that case
602 decompiler.addToken(Token.EOL);
603 }
604
605 if (destructuring != null) {
606 body.addChildToFront(new Node(Token.EXPR_VOID,
607 destructuring, lineno));
608 }
609
610 int syntheticType = fn.getFunctionType();
611 Node pn = initFunction(fn, index, body, syntheticType);
612 if (mexpr != null) {
613 pn = createAssignment(Token.ASSIGN, mexpr, pn);
614 if (syntheticType != FunctionNode.FUNCTION_EXPRESSION) {
615 pn = createExprStatementNoReturn(pn, fn.getLineno());
616 }
617 }
618 return pn;
619
620 } finally {
621 --nestingOfFunction;
622 savedVars.restore();
623 }
624 }
625
626 private Node transformFunctionCall(FunctionCall node) {
627 Node call = createCallOrNew(Token.CALL, transform(node.getTarget()));
628 call.setLineno(node.getLineno());
629 decompiler.addToken(Token.LP);
630 List<AstNode> args = node.getArguments();
631 for (int i = 0; i < args.size(); i++) {
632 AstNode arg = args.get(i);
633 call.addChildToBack(transform(arg));
634 if (i < args.size() - 1) {
635 decompiler.addToken(Token.COMMA);
636 }
637 }
638 decompiler.addToken(Token.RP);
639 return call;
640 }
641
642 private Node transformGenExpr(GeneratorExpression node) {
643 Node pn;
644
645 FunctionNode fn = new FunctionNode();
646 fn.setSourceName(currentScriptOrFn.getNextTempName());
647 fn.setIsGenerator();
648 fn.setFunctionType(FunctionNode.FUNCTION_EXPRESSION);
649 fn.setRequiresActivation();
650
651 int functionType = fn.getFunctionType();
652 int start = decompiler.markFunctionStart(functionType);
653 Node mexpr = decompileFunctionHeader(fn);
654 int index = currentScriptOrFn.addFunction(fn);
655
656 PerFunctionVariables savedVars = new PerFunctionVariables(fn);
657 try {
658 // If we start needing to record much more codegen metadata during
659 // function parsing, we should lump it all into a helper class.
660 Node destructuring = (Node)fn.getProp(Node.DESTRUCTURING_PARAMS);
661 fn.removeProp(Node.DESTRUCTURING_PARAMS);
662
663 int lineno = node.lineno;
664 ++nestingOfFunction; // only for body, not params
665 Node body = genExprTransformHelper(node);
666
667 if (!fn.isExpressionClosure()) {
668 decompiler.addToken(Token.RC);
669 }
670 fn.setEncodedSourceBounds(start, decompiler.markFunctionEnd(start));
671
672 if (functionType != FunctionNode.FUNCTION_EXPRESSION && !fn.isExpressionClosure()) {
673 // Add EOL only if function is not part of expression
674 // since it gets SEMI + EOL from Statement in that case
675 decompiler.addToken(Token.EOL);
676 }
677
678 if (destructuring != null) {
679 body.addChildToFront(new Node(Token.EXPR_VOID,
680 destructuring, lineno));
681 }
682
683 int syntheticType = fn.getFunctionType();
684 pn = initFunction(fn, index, body, syntheticType);
685 if (mexpr != null) {
686 pn = createAssignment(Token.ASSIGN, mexpr, pn);
687 if (syntheticType != FunctionNode.FUNCTION_EXPRESSION) {
688 pn = createExprStatementNoReturn(pn, fn.getLineno());
689 }
690 }
691 } finally {
692 --nestingOfFunction;
693 savedVars.restore();
694 }
695
696 Node call = createCallOrNew(Token.CALL, pn);
697 call.setLineno(node.getLineno());
698 decompiler.addToken(Token.LP);
699 decompiler.addToken(Token.RP);
700 return call;
701 }
702
703 private Node genExprTransformHelper(GeneratorExpression node) {
704 decompiler.addToken(Token.LP);
705 int lineno = node.getLineno();
706 Node expr = transform(node.getResult());
707
708 List<GeneratorExpressionLoop> loops = node.getLoops();
709 int numLoops = loops.size();
710
711 // Walk through loops, collecting and defining their iterator symbols.
712 Node[] iterators = new Node[numLoops];
713 Node[] iteratedObjs = new Node[numLoops];
714
715 for (int i = 0; i < numLoops; i++) {
716 GeneratorExpressionLoop acl = loops.get(i);
717 decompiler.addName(" ");
718 decompiler.addToken(Token.FOR);
719 decompiler.addToken(Token.LP);
720
721 AstNode iter = acl.getIterator();
722 String name = null;
723 if (iter.getType() == Token.NAME) {
724 name = iter.getString();
725 decompiler.addName(name);
726 } else {
727 // destructuring assignment
728 decompile(iter);
729 name = currentScriptOrFn.getNextTempName();
730 defineSymbol(Token.LP, name, false);
731 expr = createBinary(Token.COMMA,
732 createAssignment(Token.ASSIGN,
733 iter,
734 createName(name)),
735 expr);
736 }
737 Node init = createName(name);
738 // Define as a let since we want the scope of the variable to
739 // be restricted to the array comprehension
740 defineSymbol(Token.LET, name, false);
741 iterators[i] = init;
742
743 if (acl.isForOf()) {
744 decompiler.addName("of ");
745 } else {
746 decompiler.addToken(Token.IN);
747 }
748 iteratedObjs[i] = transform(acl.getIteratedObject());
749 decompiler.addToken(Token.RP);
750 }
751
752 // generate code for tmpArray.push(body)
753 Node yield = new Node(Token.YIELD, expr, node.getLineno());
754
755 Node body = new Node(Token.EXPR_VOID, yield, lineno);
756
757 if (node.getFilter() != null) {
758 decompiler.addName(" ");
759 decompiler.addToken(Token.IF);
760 decompiler.addToken(Token.LP);
761 body = createIf(transform(node.getFilter()), body, null, lineno);
762 decompiler.addToken(Token.RP);
763 }
764
765 // Now walk loops in reverse to build up the body statement.
766 int pushed = 0;
767 try {
768 for (int i = numLoops-1; i >= 0; i--) {
769 GeneratorExpressionLoop acl = loops.get(i);
770 Scope loop = createLoopNode(null, // no label
771 acl.getLineno());
772 pushScope(loop);
773 pushed++;
774 body = createForIn(Token.LET,
775 loop,
776 iterators[i],
777 iteratedObjs[i],
778 body,
779 acl.isForEach(),
780 acl.isForOf());
781 }
782 } finally {
783 for (int i = 0; i < pushed; i++) {
784 popScope();
785 }
786 }
787
788 decompiler.addToken(Token.RP);
789
790 return body;
791 }
792
793 private Node transformIf(IfStatement n) {
794 decompiler.addToken(Token.IF);
795 decompiler.addToken(Token.LP);
796 Node cond = transform(n.getCondition());
797 decompiler.addToken(Token.RP);
798 decompiler.addEOL(Token.LC);
799 Node ifTrue = transform(n.getThenPart());
800 Node ifFalse = null;
801 if (n.getElsePart() != null) {
802 decompiler.addToken(Token.RC);
803 decompiler.addToken(Token.ELSE);
804 decompiler.addEOL(Token.LC);
805 ifFalse = transform(n.getElsePart());
806 }
807 decompiler.addEOL(Token.RC);
808 return createIf(cond, ifTrue, ifFalse, n.getLineno());
809 }
810
811 private Node transformInfix(InfixExpression node) {
812 Node left = transform(node.getLeft());
813 decompiler.addToken(node.getType());
814 Node right = transform(node.getRight());
815 if (node instanceof XmlDotQuery) {
816 decompiler.addToken(Token.RP);
817 }
818 return createBinary(node.getType(), left, right);
819 }
820
821 private Node transformLabeledStatement(LabeledStatement ls) {
822 Label label = ls.getFirstLabel();
823 List<Label> labels = ls.getLabels();
824 decompiler.addName(label.getName());
825 if (labels.size() > 1) {
826 // more than one label
827 for (Label lb : labels.subList(1, labels.size())) {
828 decompiler.addEOL(Token.COLON);
829 decompiler.addName(lb.getName());
830 }
831 }
832 if (ls.getStatement().getType() == Token.BLOCK) {
833 // reuse OBJECTLIT for ':' workaround, cf. transformObjectLiteral()
834 decompiler.addToken(Token.OBJECTLIT);
835 decompiler.addEOL(Token.LC);
836 } else {
837 decompiler.addEOL(Token.COLON);
838 }
839 Node statement = transform(ls.getStatement());
840 if (ls.getStatement().getType() == Token.BLOCK) {
841 decompiler.addEOL(Token.RC);
842 }
843
844 // Make a target and put it _after_ the statement node. Add in the
845 // LABEL node, so breaks get the right target.
846 Node breakTarget = Node.newTarget();
847 Node block = new Node(Token.BLOCK, label, statement, breakTarget);
848 label.target = breakTarget;
849
850 return block;
851 }
852
853 private Node transformLetNode(LetNode node) {
854 pushScope(node);
855 try {
856 decompiler.addToken(Token.LET);
857 decompiler.addToken(Token.LP);
858 Node vars = transformVariableInitializers(node.getVariables());
859 decompiler.addToken(Token.RP);
860 node.addChildToBack(vars);
861 boolean letExpr = node.getType() == Token.LETEXPR;
862 if (node.getBody() != null) {
863 if (letExpr) {
864 decompiler.addName(" ");
865 } else {
866 decompiler.addEOL(Token.LC);
867 }
868 node.addChildToBack(transform(node.getBody()));
869 if (!letExpr) {
870 decompiler.addEOL(Token.RC);
871 }
872 }
873 return node;
874 } finally {
875 popScope();
876 }
877 }
878
879 private Node transformLiteral(AstNode node) {
880 decompiler.addToken(node.getType());
881 return node;
882 }
883
884 private Node transformName(Name node) {
885 decompiler.addName(node.getIdentifier());
886 return node;
887 }
888
889 private Node transformNewExpr(NewExpression node) {
890 decompiler.addToken(Token.NEW);
891 Node nx = createCallOrNew(Token.NEW, transform(node.getTarget()));
892 nx.setLineno(node.getLineno());
893 List<AstNode> args = node.getArguments();
894 decompiler.addToken(Token.LP);
895 for (int i = 0; i < args.size(); i++) {
896 AstNode arg = args.get(i);
897 nx.addChildToBack(transform(arg));
898 if (i < args.size() - 1) {
899 decompiler.addToken(Token.COMMA);
900 }
901 }
902 decompiler.addToken(Token.RP);
903 if (node.getInitializer() != null) {
904 nx.addChildToBack(transformObjectLiteral(node.getInitializer()));
905 }
906 return nx;
907 }
908
909 private Node transformNumber(NumberLiteral node) {
910 decompiler.addNumber(node.getNumber());
911 return node;
912 }
913
914 private Node transformObjectLiteral(ObjectLiteral node) {
915 if (node.isDestructuring()) {
916 return node;
917 }
918 // createObjectLiteral rewrites its argument as object
919 // creation plus object property entries, so later compiler
920 // stages don't need to know about object literals.
921 decompiler.addToken(Token.LC);
922 List<ObjectProperty> elems = node.getElements();
923 Node object = new Node(Token.OBJECTLIT);
924 Object[] properties;
925 if (elems.isEmpty()) {
926 properties = ScriptRuntime.emptyArgs;
927 } else {
928 int size = elems.size(), i = 0;
929 properties = new Object[size];
930 for (ObjectProperty prop : elems) {
931 if (prop.isGetterMethod()) {
932 decompiler.addToken(Token.GET);
933 } else if (prop.isSetterMethod()) {
934 decompiler.addToken(Token.SET);
935 } else if (prop.isNormalMethod()) {
936 decompiler.addToken(Token.METHOD);
937 }
938
939 properties[i++] = getPropKey(prop.getLeft());
940
941 // OBJECTLIT is used as ':' in object literal for
942 // decompilation to solve spacing ambiguity.
943 if (!(prop.isMethod())) {
944 decompiler.addToken(Token.OBJECTLIT);
945 }
946
947 Node right = transform(prop.getRight());
948 if (prop.isGetterMethod()) {
949 right = createUnary(Token.GET, right);
950 } else if (prop.isSetterMethod()) {
951 right = createUnary(Token.SET, right);
952 } else if (prop.isNormalMethod()) {
953 right = createUnary(Token.METHOD, right);
954 }
955 object.addChildToBack(right);
956
957 if (i < size) {
958 decompiler.addToken(Token.COMMA);
959 }
960 }
961 }
962 decompiler.addToken(Token.RC);
963 object.putProp(Node.OBJECT_IDS_PROP, properties);
964 return object;
965 }
966
967 private Object getPropKey(Node id) {
968 Object key;
969 if (id instanceof Name) {
970 String s = ((Name)id).getIdentifier();
971 decompiler.addName(s);
972 key = ScriptRuntime.getIndexObject(s);
973 } else if (id instanceof StringLiteral) {
974 String s = ((StringLiteral)id).getValue();
975 decompiler.addString(s);
976 key = ScriptRuntime.getIndexObject(s);
977 } else if (id instanceof NumberLiteral) {
978 double n = ((NumberLiteral)id).getNumber();
979 decompiler.addNumber(n);
980 key = ScriptRuntime.getIndexObject(n);
981 } else {
982 throw Kit.codeBug();
983 }
984 return key;
985 }
986
987 private Node transformParenExpr(ParenthesizedExpression node) {
988 AstNode expr = node.getExpression();
989 decompiler.addToken(Token.LP);
990 int count = 1;
991 while (expr instanceof ParenthesizedExpression) {
992 decompiler.addToken(Token.LP);
993 count++;
994 expr = ((ParenthesizedExpression)expr).getExpression();
995 }
996 Node result = transform(expr);
997 for (int i = 0; i < count; i++) {
998 decompiler.addToken(Token.RP);
999 }
1000 result.putProp(Node.PARENTHESIZED_PROP, Boolean.TRUE);
1001 return result;
1002 }
1003
1004 private Node transformPropertyGet(PropertyGet node) {
1005 Node target = transform(node.getTarget());
1006 String name = node.getProperty().getIdentifier();
1007 decompiler.addToken(Token.DOT);
1008 decompiler.addName(name);
1009 return createPropertyGet(target, null, name, 0);
1010 }
1011
1012 private Node transformRegExp(RegExpLiteral node) {
1013 decompiler.addRegexp(node.getValue(), node.getFlags());
1014 currentScriptOrFn.addRegExp(node);
1015 return node;
1016 }
1017
1018 private Node transformReturn(ReturnStatement node) {
1019 boolean expClosure = Boolean.TRUE.equals(node.getProp(Node.EXPRESSION_CLOSURE_PROP));
1020 boolean isArrow = Boolean.TRUE.equals(node.getProp(Node.ARROW_FUNCTION_PROP));
1021 if (expClosure) {
1022 if (!isArrow) {
1023 decompiler.addName(" ");
1024 }
1025 } else {
1026 decompiler.addToken(Token.RETURN);
1027 }
1028 AstNode rv = node.getReturnValue();
1029 Node value = rv == null ? null : transform(rv);
1030 if (!expClosure) decompiler.addEOL(Token.SEMI);
1031 return rv == null
1032 ? new Node(Token.RETURN, node.getLineno())
1033 : new Node(Token.RETURN, value, node.getLineno());
1034 }
1035
1036 private Node transformScript(ScriptNode node) {
1037 decompiler.addToken(Token.SCRIPT);
1038 if (currentScope != null) Kit.codeBug();
1039 currentScope = node;
1040 Node body = new Node(Token.BLOCK);
1041 for (Node kid : node) {
1042 body.addChildToBack(transform((AstNode)kid));
1043 }
1044 node.removeChildren();
1045 Node children = body.getFirstChild();
1046 if (children != null) {
1047 node.addChildrenToBack(children);
1048 }
1049 return node;
1050 }
1051
1052 private Node transformString(StringLiteral node) {
1053 decompiler.addString(node.getValue());
1054 return Node.newString(node.getValue());
1055 }
1056
1057 private Node transformSwitch(SwitchStatement node) {
1058 // The switch will be rewritten from:
1059 //
1060 // switch (expr) {
1061 // case test1: statements1;
1062 // ...
1063 // default: statementsDefault;
1064 // ...
1065 // case testN: statementsN;
1066 // }
1067 //
1068 // to:
1069 //
1070 // {
1071 // switch (expr) {
1072 // case test1: goto label1;
1073 // ...
1074 // case testN: goto labelN;
1075 // }
1076 // goto labelDefault;
1077 // label1:
1078 // statements1;
1079 // ...
1080 // labelDefault:
1081 // statementsDefault;
1082 // ...
1083 // labelN:
1084 // statementsN;
1085 // breakLabel:
1086 // }
1087 //
1088 // where inside switch each "break;" without label will be replaced
1089 // by "goto breakLabel".
1090 //
1091 // If the original switch does not have the default label, then
1092 // after the switch he transformed code would contain this goto:
1093 // goto breakLabel;
1094 // instead of:
1095 // goto labelDefault;
1096
1097 decompiler.addToken(Token.SWITCH);
1098 decompiler.addToken(Token.LP);
1099 Node switchExpr = transform(node.getExpression());
1100 decompiler.addToken(Token.RP);
1101 node.addChildToBack(switchExpr);
1102
1103 Node block = new Node(Token.BLOCK, node, node.getLineno());
1104 decompiler.addEOL(Token.LC);
1105
1106 for (SwitchCase sc : node.getCases()) {
1107 AstNode expr = sc.getExpression();
1108 Node caseExpr = null;
1109
1110 if (expr != null) {
1111 decompiler.addToken(Token.CASE);
1112 caseExpr = transform(expr);
1113 } else {
1114 decompiler.addToken(Token.DEFAULT);
1115 }
1116 decompiler.addEOL(Token.COLON);
1117
1118 List<AstNode> stmts = sc.getStatements();
1119 Node body = new Block();
1120 if (stmts != null) {
1121 for (AstNode kid : stmts) {
1122 body.addChildToBack(transform(kid));
1123 }
1124 }
1125 addSwitchCase(block, caseExpr, body);
1126 }
1127 decompiler.addEOL(Token.RC);
1128 closeSwitch(block);
1129 return block;
1130 }
1131
1132 private Node transformThrow(ThrowStatement node) {
1133 decompiler.addToken(Token.THROW);
1134 Node value = transform(node.getExpression());
1135 decompiler.addEOL(Token.SEMI);
1136 return new Node(Token.THROW, value, node.getLineno());
1137 }
1138
1139 private Node transformTry(TryStatement node) {
1140 decompiler.addToken(Token.TRY);
1141 decompiler.addEOL(Token.LC);
1142 Node tryBlock = transform(node.getTryBlock());
1143 decompiler.addEOL(Token.RC);
1144
1145 Node catchBlocks = new Block();
1146 for (CatchClause cc : node.getCatchClauses()) {
1147 decompiler.addToken(Token.CATCH);
1148 decompiler.addToken(Token.LP);
1149
1150 String varName = cc.getVarName().getIdentifier();
1151 decompiler.addName(varName);
1152
1153 Node catchCond = null;
1154 AstNode ccc = cc.getCatchCondition();
1155 if (ccc != null) {
1156 decompiler.addName(" ");
1157 decompiler.addToken(Token.IF);
1158 catchCond = transform(ccc);
1159 } else {
1160 catchCond = new EmptyExpression();
1161 }
1162 decompiler.addToken(Token.RP);
1163 decompiler.addEOL(Token.LC);
1164
1165 Node body = transform(cc.getBody());
1166 decompiler.addEOL(Token.RC);
1167
1168 catchBlocks.addChildToBack(createCatch(varName, catchCond,
1169 body, cc.getLineno()));
1170 }
1171 Node finallyBlock = null;
1172 if (node.getFinallyBlock() != null) {
1173 decompiler.addToken(Token.FINALLY);
1174 decompiler.addEOL(Token.LC);
1175 finallyBlock = transform(node.getFinallyBlock());
1176 decompiler.addEOL(Token.RC);
1177 }
1178 return createTryCatchFinally(tryBlock, catchBlocks,
1179 finallyBlock, node.getLineno());
1180 }
1181
1182 private Node transformUnary(UnaryExpression node) {
1183 int type = node.getType();
1184 if (type == Token.DEFAULTNAMESPACE) {
1185 return transformDefaultXmlNamepace(node);
1186 }
1187 if (node.isPrefix()) {
1188 decompiler.addToken(type);
1189 }
1190 Node child = transform(node.getOperand());
1191 if (node.isPostfix()) {
1192 decompiler.addToken(type);
1193 }
1194 if (type == Token.INC || type == Token.DEC) {
1195 return createIncDec(type, node.isPostfix(), child);
1196 }
1197 return createUnary(type, child);
1198 }
1199
1200 private Node transformVariables(VariableDeclaration node) {
1201 decompiler.addToken(node.getType());
1202 transformVariableInitializers(node);
1203
1204 // Might be most robust to have parser record whether it was
1205 // a variable declaration statement, possibly as a node property.
1206 AstNode parent = node.getParent();
1207 if (!(parent instanceof Loop)
1208 && !(parent instanceof LetNode)) {
1209 decompiler.addEOL(Token.SEMI);
1210 }
1211 return node;
1212 }
1213
1214 private Node transformVariableInitializers(VariableDeclaration node) {
1215 List<VariableInitializer> vars = node.getVariables();
1216 int size = vars.size(), i = 0;
1217 for (VariableInitializer var : vars) {
1218 AstNode target = var.getTarget();
1219 AstNode init = var.getInitializer();
1220
1221 Node left = null;
1222 if (var.isDestructuring()) {
1223 decompile(target); // decompile but don't transform
1224 left = target;
1225 } else {
1226 left = transform(target);
1227 }
1228
1229 Node right = null;
1230 if (init != null) {
1231 decompiler.addToken(Token.ASSIGN);
1232 right = transform(init);
1233 }
1234
1235 if (var.isDestructuring()) {
1236 if (right == null) { // TODO: should this ever happen?
1237 node.addChildToBack(left);
1238 } else {
1239 Node d = createDestructuringAssignment(node.getType(),
1240 left, right);
1241 node.addChildToBack(d);
1242 }
1243 } else {
1244 if (right != null) {
1245 left.addChildToBack(right);
1246 }
1247 node.addChildToBack(left);
1248 }
1249 if (i++ < size-1) {
1250 decompiler.addToken(Token.COMMA);
1251 }
1252 }
1253 return node;
1254 }
1255
1256 private Node transformWhileLoop(WhileLoop loop) {
1257 decompiler.addToken(Token.WHILE);
1258 loop.setType(Token.LOOP);
1259 pushScope(loop);
1260 try {
1261 decompiler.addToken(Token.LP);
1262 Node cond = transform(loop.getCondition());
1263 decompiler.addToken(Token.RP);
1264 decompiler.addEOL(Token.LC);
1265 Node body = transform(loop.getBody());
1266 decompiler.addEOL(Token.RC);
1267 return createLoop(loop, LOOP_WHILE, body, cond, null, null);
1268 } finally {
1269 popScope();
1270 }
1271 }
1272
1273 private Node transformWith(WithStatement node) {
1274 decompiler.addToken(Token.WITH);
1275 decompiler.addToken(Token.LP);
1276 Node expr = transform(node.getExpression());
1277 decompiler.addToken(Token.RP);
1278 decompiler.addEOL(Token.LC);
1279 Node stmt = transform(node.getStatement());
1280 decompiler.addEOL(Token.RC);
1281 return createWith(expr, stmt, node.getLineno());
1282 }
1283
1284 private Node transformYield(Yield node) {
1285 decompiler.addToken(Token.YIELD);
1286 Node kid = node.getValue() == null ? null : transform(node.getValue());
1287 if (kid != null)
1288 return new Node(Token.YIELD, kid, node.getLineno());
1289 else
1290 return new Node(Token.YIELD, node.getLineno());
1291 }
1292
1293 private Node transformXmlLiteral(XmlLiteral node) {
1294 // a literal like <foo>{bar}</foo> is rewritten as
1295 // new XML("<foo>" + bar + "</foo>");
1296
1297 Node pnXML = new Node(Token.NEW, node.getLineno());
1298 List<XmlFragment> frags = node.getFragments();
1299
1300 XmlString first = (XmlString)frags.get(0);
1301 boolean anon = first.getXml().trim().startsWith("<>");
1302 pnXML.addChildToBack(createName(anon ? "XMLList" : "XML"));
1303
1304 Node pn = null;
1305 for (XmlFragment frag : frags) {
1306 if (frag instanceof XmlString) {
1307 String xml = ((XmlString)frag).getXml();
1308 decompiler.addName(xml);
1309 if (pn == null) {
1310 pn = createString(xml);
1311 } else {
1312 pn = createBinary(Token.ADD, pn, createString(xml));
1313 }
1314 } else {
1315 XmlExpression xexpr = (XmlExpression)frag;
1316 boolean isXmlAttr = xexpr.isXmlAttribute();
1317 Node expr;
1318 decompiler.addToken(Token.LC);
1319 if (xexpr.getExpression() instanceof EmptyExpression) {
1320 expr = createString("");
1321 } else {
1322 expr = transform(xexpr.getExpression());
1323 }
1324 decompiler.addToken(Token.RC);
1325 if (isXmlAttr) {
1326 // Need to put the result in double quotes
1327 expr = createUnary(Token.ESCXMLATTR, expr);
1328 Node prepend = createBinary(Token.ADD,
1329 createString("\""),
1330 expr);
1331 expr = createBinary(Token.ADD,
1332 prepend,
1333 createString("\""));
1334 } else {
1335 expr = createUnary(Token.ESCXMLTEXT, expr);
1336 }
1337 pn = createBinary(Token.ADD, pn, expr);
1338 }
1339 }
1340
1341 pnXML.addChildToBack(pn);
1342 return pnXML;
1343 }
1344
1345 private Node transformXmlMemberGet(XmlMemberGet node) {
1346 XmlRef ref = node.getMemberRef();
1347 Node pn = transform(node.getLeft());
1348 int flags = ref.isAttributeAccess() ? Node.ATTRIBUTE_FLAG : 0;
1349 if (node.getType() == Token.DOTDOT) {
1350 flags |= Node.DESCENDANTS_FLAG;
1351 decompiler.addToken(Token.DOTDOT);
1352 } else {
1353 decompiler.addToken(Token.DOT);
1354 }
1355 return transformXmlRef(pn, ref, flags);
1356 }
1357
1358 // We get here if we weren't a child of a . or .. infix node
1359 private Node transformXmlRef(XmlRef node) {
1360 int memberTypeFlags = node.isAttributeAccess()
1361 ? Node.ATTRIBUTE_FLAG : 0;
1362 return transformXmlRef(null, node, memberTypeFlags);
1363 }
1364
1365 private Node transformXmlRef(Node pn, XmlRef node, int memberTypeFlags) {
1366 if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0)
1367 decompiler.addToken(Token.XMLATTR);
1368 Name namespace = node.getNamespace();
1369 String ns = namespace != null ? namespace.getIdentifier() : null;
1370 if (ns != null) {
1371 decompiler.addName(ns);
1372 decompiler.addToken(Token.COLONCOLON);
1373 }
1374 if (node instanceof XmlPropRef) {
1375 String name = ((XmlPropRef)node).getPropName().getIdentifier();
1376 decompiler.addName(name);
1377 return createPropertyGet(pn, ns, name, memberTypeFlags);
1378 } else {
1379 decompiler.addToken(Token.LB);
1380 Node expr = transform(((XmlElemRef)node).getExpression());
1381 decompiler.addToken(Token.RB);
1382 return createElementGet(pn, ns, expr, memberTypeFlags);
1383 }
1384 }
1385
1386 private Node transformDefaultXmlNamepace(UnaryExpression node) {
1387 decompiler.addToken(Token.DEFAULT);
1388 decompiler.addName(" xml");
1389 decompiler.addName(" namespace");
1390 decompiler.addToken(Token.ASSIGN);
1391 Node child = transform(node.getOperand());
1392 return createUnary(Token.DEFAULTNAMESPACE, child);
1393 }
1394
1395 /**
1396 * If caseExpression argument is null it indicates a default label.
1397 */
1398 private void addSwitchCase(Node switchBlock, Node caseExpression,
1399 Node statements)
1400 {
1401 if (switchBlock.getType() != Token.BLOCK) throw Kit.codeBug();
1402 Jump switchNode = (Jump)switchBlock.getFirstChild();
1403 if (switchNode.getType() != Token.SWITCH) throw Kit.codeBug();
1404
1405 Node gotoTarget = Node.newTarget();
1406 if (caseExpression != null) {
1407 Jump caseNode = new Jump(Token.CASE, caseExpression);
1408 caseNode.target = gotoTarget;
1409 switchNode.addChildToBack(caseNode);
1410 } else {
1411 switchNode.setDefault(gotoTarget);
1412 }
1413 switchBlock.addChildToBack(gotoTarget);
1414 switchBlock.addChildToBack(statements);
1415 }
1416
1417 private void closeSwitch(Node switchBlock)
1418 {
1419 if (switchBlock.getType() != Token.BLOCK) throw Kit.codeBug();
1420 Jump switchNode = (Jump)switchBlock.getFirstChild();
1421 if (switchNode.getType() != Token.SWITCH) throw Kit.codeBug();
1422
1423 Node switchBreakTarget = Node.newTarget();
1424 // switchNode.target is only used by NodeTransformer
1425 // to detect switch end
1426 switchNode.target = switchBreakTarget;
1427
1428 Node defaultTarget = switchNode.getDefault();
1429 if (defaultTarget == null) {
1430 defaultTarget = switchBreakTarget;
1431 }
1432
1433 switchBlock.addChildAfter(makeJump(Token.GOTO, defaultTarget),
1434 switchNode);
1435 switchBlock.addChildToBack(switchBreakTarget);
1436 }
1437
1438 private Node createExprStatementNoReturn(Node expr, int lineno) {
1439 return new Node(Token.EXPR_VOID, expr, lineno);
1440 }
1441
1442 private Node createString(String string) {
1443 return Node.newString(string);
1444 }
1445
1446 /**
1447 * Catch clause of try/catch/finally
1448 * @param varName the name of the variable to bind to the exception
1449 * @param catchCond the condition under which to catch the exception.
1450 * May be null if no condition is given.
1451 * @param stmts the statements in the catch clause
1452 * @param lineno the starting line number of the catch clause
1453 */
1454 private Node createCatch(String varName, Node catchCond, Node stmts,
1455 int lineno) {
1456 if (catchCond == null) {
1457 catchCond = new Node(Token.EMPTY);
1458 }
1459 return new Node(Token.CATCH, createName(varName),
1460 catchCond, stmts, lineno);
1461 }
1462
1463 private Node initFunction(FunctionNode fnNode, int functionIndex,
1464 Node statements, int functionType) {
1465 fnNode.setFunctionType(functionType);
1466 fnNode.addChildToBack(statements);
1467
1468 int functionCount = fnNode.getFunctionCount();
1469 if (functionCount != 0) {
1470 // Functions containing other functions require activation objects
1471 fnNode.setRequiresActivation();
1472 }
1473
1474 if (functionType == FunctionNode.FUNCTION_EXPRESSION) {
1475 Name name = fnNode.getFunctionName();
1476 if (name != null && name.length() != 0
1477 && fnNode.getSymbol(name.getIdentifier()) == null) {
1478 // A function expression needs to have its name as a
1479 // variable (if it isn't already allocated as a variable).
1480 // See ECMA Ch. 13. We add code to the beginning of the
1481 // function to initialize a local variable of the
1482 // function's name to the function value, but only if the
1483 // function doesn't already define a formal parameter, var,
1484 // or nested function with the same name.
1485 fnNode.putSymbol(new Symbol(Token.FUNCTION, name.getIdentifier()));
1486 Node setFn = new Node(Token.EXPR_VOID,
1487 new Node(Token.SETNAME,
1488 Node.newString(Token.BINDNAME,
1489 name.getIdentifier()),
1490 new Node(Token.THISFN)));
1491 statements.addChildrenToFront(setFn);
1492 }
1493 }
1494
1495 // Add return to end if needed.
1496 Node lastStmt = statements.getLastChild();
1497 if (lastStmt == null || lastStmt.getType() != Token.RETURN) {
1498 statements.addChildToBack(new Node(Token.RETURN));
1499 }
1500
1501 Node result = Node.newString(Token.FUNCTION, fnNode.getName());
1502 result.putIntProp(Node.FUNCTION_PROP, functionIndex);
1503 return result;
1504 }
1505
1506 /**
1507 * Create loop node. The code generator will later call
1508 * createWhile|createDoWhile|createFor|createForIn
1509 * to finish loop generation.
1510 */
1511 private Scope createLoopNode(Node loopLabel, int lineno) {
1512 Scope result = createScopeNode(Token.LOOP, lineno);
1513 if (loopLabel != null) {
1514 ((Jump)loopLabel).setLoop(result);
1515 }
1516 return result;
1517 }
1518
1519 private Node createFor(Scope loop, Node init,
1520 Node test, Node incr, Node body) {
1521 if (init.getType() == Token.LET) {
1522 // rewrite "for (let i=s; i < N; i++)..." as
1523 // "let (i=s) { for (; i < N; i++)..." so that "s" is evaluated
1524 // outside the scope of the for.
1525 Scope let = Scope.splitScope(loop);
1526 let.setType(Token.LET);
1527 let.addChildrenToBack(init);
1528 let.addChildToBack(createLoop(loop, LOOP_FOR, body, test,
1529 new Node(Token.EMPTY), incr));
1530 return let;
1531 }
1532 return createLoop(loop, LOOP_FOR, body, test, init, incr);
1533 }
1534
1535 private Node createLoop(Jump loop, int loopType, Node body,
1536 Node cond, Node init, Node incr)
1537 {
1538 Node bodyTarget = Node.newTarget();
1539 Node condTarget = Node.newTarget();
1540 if (loopType == LOOP_FOR && cond.getType() == Token.EMPTY) {
1541 cond = new Node(Token.TRUE);
1542 }
1543 Jump IFEQ = new Jump(Token.IFEQ, cond);
1544 IFEQ.target = bodyTarget;
1545 Node breakTarget = Node.newTarget();
1546
1547 loop.addChildToBack(bodyTarget);
1548 loop.addChildrenToBack(body);
1549 if (loopType == LOOP_WHILE || loopType == LOOP_FOR) {
1550 // propagate lineno to condition
1551 loop.addChildrenToBack(new Node(Token.EMPTY, loop.getLineno()));
1552 }
1553 loop.addChildToBack(condTarget);
1554 loop.addChildToBack(IFEQ);
1555 loop.addChildToBack(breakTarget);
1556
1557 loop.target = breakTarget;
1558 Node continueTarget = condTarget;
1559
1560 if (loopType == LOOP_WHILE || loopType == LOOP_FOR) {
1561 // Just add a GOTO to the condition in the do..while
1562 loop.addChildToFront(makeJump(Token.GOTO, condTarget));
1563
1564 if (loopType == LOOP_FOR) {
1565 int initType = init.getType();
1566 if (initType != Token.EMPTY) {
1567 if (initType != Token.VAR && initType != Token.LET) {
1568 init = new Node(Token.EXPR_VOID, init);
1569 }
1570 loop.addChildToFront(init);
1571 }
1572 Node incrTarget = Node.newTarget();
1573 loop.addChildAfter(incrTarget, body);
1574 if (incr.getType() != Token.EMPTY) {
1575 incr = new Node(Token.EXPR_VOID, incr);
1576 loop.addChildAfter(incr, incrTarget);
1577 }
1578 continueTarget = incrTarget;
1579 }
1580 }
1581
1582 loop.setContinue(continueTarget);
1583 return loop;
1584 }
1585
1586 /**
1587 * Generate IR for a for..in loop.
1588 */
1589 private Node createForIn(int declType, Node loop, Node lhs,
1590 Node obj, Node body, boolean isForEach, boolean isForOf)
1591 {
1592 int destructuring = -1;
1593 int destructuringLen = 0;
1594 Node lvalue;
1595 int type = lhs.getType();
1596 if (type == Token.VAR || type == Token.LET) {
1597 Node kid = lhs.getLastChild();
1598 int kidType = kid.getType();
1599 if (kidType == Token.ARRAYLIT || kidType == Token.OBJECTLIT)
1600 {
1601 type = destructuring = kidType;
1602 lvalue = kid;
1603 destructuringLen = 0;
1604 if (kid instanceof ArrayLiteral)
1605 destructuringLen = ((ArrayLiteral) kid).getDestructuringLength();
1606 } else if (kidType == Token.NAME) {
1607 lvalue = Node.newString(Token.NAME, kid.getString());
1608 } else {
1609 reportError("msg.bad.for.in.lhs");
1610 return null;
1611 }
1612 } else if (type == Token.ARRAYLIT || type == Token.OBJECTLIT) {
1613 destructuring = type;
1614 lvalue = lhs;
1615 destructuringLen = 0;
1616 if (lhs instanceof ArrayLiteral)
1617 destructuringLen = ((ArrayLiteral) lhs).getDestructuringLength();
1618 } else {
1619 lvalue = makeReference(lhs);
1620 if (lvalue == null) {
1621 reportError("msg.bad.for.in.lhs");
1622 return null;
1623 }
1624 }
1625
1626 Node localBlock = new Node(Token.LOCAL_BLOCK);
1627 int initType = isForEach ? Token.ENUM_INIT_VALUES
1628 : isForOf ? Token.ENUM_INIT_VALUES_IN_ORDER
1629 : (destructuring != -1
1630 ? Token.ENUM_INIT_ARRAY
1631 : Token.ENUM_INIT_KEYS);
1632 Node init = new Node(initType, obj);
1633 init.putProp(Node.LOCAL_BLOCK_PROP, localBlock);
1634 Node cond = new Node(Token.ENUM_NEXT);
1635 cond.putProp(Node.LOCAL_BLOCK_PROP, localBlock);
1636 Node id = new Node(Token.ENUM_ID);
1637 id.putProp(Node.LOCAL_BLOCK_PROP, localBlock);
1638
1639 Node newBody = new Node(Token.BLOCK);
1640 Node assign;
1641 if (destructuring != -1) {
1642 assign = createDestructuringAssignment(declType, lvalue, id);
1643 if (!isForEach && !isForOf &&
1644 (destructuring == Token.OBJECTLIT ||
1645 destructuringLen != 2))
1646 {
1647 // destructuring assignment is only allowed in for..each or
1648 // with an array type of length 2 (to hold key and value)
1649 reportError("msg.bad.for.in.destruct");
1650 }
1651 } else {
1652 assign = simpleAssignment(lvalue, id);
1653 }
1654 newBody.addChildToBack(new Node(Token.EXPR_VOID, assign));
1655 newBody.addChildToBack(body);
1656
1657 loop = createLoop((Jump)loop, LOOP_WHILE, newBody, cond, null, null);
1658 loop.addChildToFront(init);
1659 if (type == Token.VAR || type == Token.LET)
1660 loop.addChildToFront(lhs);
1661 localBlock.addChildToBack(loop);
1662
1663 return localBlock;
1664 }
1665
1666 /**
1667 * Try/Catch/Finally
1668 *
1669 * The IRFactory tries to express as much as possible in the tree;
1670 * the responsibilities remaining for Codegen are to add the Java
1671 * handlers: (Either (but not both) of TARGET and FINALLY might not
1672 * be defined)
1673 *
1674 * - a catch handler for javascript exceptions that unwraps the
1675 * exception onto the stack and GOTOes to the catch target
1676 *
1677 * - a finally handler
1678 *
1679 * ... and a goto to GOTO around these handlers.
1680 */
1681 private Node createTryCatchFinally(Node tryBlock, Node catchBlocks,
1682 Node finallyBlock, int lineno)
1683 {
1684 boolean hasFinally = (finallyBlock != null)
1685 && (finallyBlock.getType() != Token.BLOCK
1686 || finallyBlock.hasChildren());
1687
1688 // short circuit
1689 if (tryBlock.getType() == Token.BLOCK && !tryBlock.hasChildren()
1690 && !hasFinally)
1691 {
1692 return tryBlock;
1693 }
1694
1695 boolean hasCatch = catchBlocks.hasChildren();
1696
1697 // short circuit
1698 if (!hasFinally && !hasCatch) {
1699 // bc finally might be an empty block...
1700 return tryBlock;
1701 }
1702
1703 Node handlerBlock = new Node(Token.LOCAL_BLOCK);
1704 Jump pn = new Jump(Token.TRY, tryBlock, lineno);
1705 pn.putProp(Node.LOCAL_BLOCK_PROP, handlerBlock);
1706
1707 if (hasCatch) {
1708 // jump around catch code
1709 Node endCatch = Node.newTarget();
1710 pn.addChildToBack(makeJump(Token.GOTO, endCatch));
1711
1712 // make a TARGET for the catch that the tcf node knows about
1713 Node catchTarget = Node.newTarget();
1714 pn.target = catchTarget;
1715 // mark it
1716 pn.addChildToBack(catchTarget);
1717
1718 //
1719 // Given
1720 //
1721 // try {
1722 // tryBlock;
1723 // } catch (e if condition1) {
1724 // something1;
1725 // ...
1726 //
1727 // } catch (e if conditionN) {
1728 // somethingN;
1729 // } catch (e) {
1730 // somethingDefault;
1731 // }
1732 //
1733 // rewrite as
1734 //
1735 // try {
1736 // tryBlock;
1737 // goto after_catch:
1738 // } catch (x) {
1739 // with (newCatchScope(e, x)) {
1740 // if (condition1) {
1741 // something1;
1742 // goto after_catch;
1743 // }
1744 // }
1745 // ...
1746 // with (newCatchScope(e, x)) {
1747 // if (conditionN) {
1748 // somethingN;
1749 // goto after_catch;
1750 // }
1751 // }
1752 // with (newCatchScope(e, x)) {
1753 // somethingDefault;
1754 // goto after_catch;
1755 // }
1756 // }
1757 // after_catch:
1758 //
1759 // If there is no default catch, then the last with block
1760 // arround "somethingDefault;" is replaced by "rethrow;"
1761
1762 // It is assumed that catch handler generation will store
1763 // exeception object in handlerBlock register
1764
1765 // Block with local for exception scope objects
1766 Node catchScopeBlock = new Node(Token.LOCAL_BLOCK);
1767
1768 // expects catchblocks children to be (cond block) pairs.
1769 Node cb = catchBlocks.getFirstChild();
1770 boolean hasDefault = false;
1771 int scopeIndex = 0;
1772 while (cb != null) {
1773 int catchLineNo = cb.getLineno();
1774
1775 Node name = cb.getFirstChild();
1776 Node cond = name.getNext();
1777 Node catchStatement = cond.getNext();
1778 cb.removeChild(name);
1779 cb.removeChild(cond);
1780 cb.removeChild(catchStatement);
1781
1782 // Add goto to the catch statement to jump out of catch
1783 // but prefix it with LEAVEWITH since try..catch produces
1784 // "with"code in order to limit the scope of the exception
1785 // object.
1786 catchStatement.addChildToBack(new Node(Token.LEAVEWITH));
1787 catchStatement.addChildToBack(makeJump(Token.GOTO, endCatch));
1788
1789 // Create condition "if" when present
1790 Node condStmt;
1791 if (cond.getType() == Token.EMPTY) {
1792 condStmt = catchStatement;
1793 hasDefault = true;
1794 } else {
1795 condStmt = createIf(cond, catchStatement, null,
1796 catchLineNo);
1797 }
1798
1799 // Generate code to create the scope object and store
1800 // it in catchScopeBlock register
1801 Node catchScope = new Node(Token.CATCH_SCOPE, name,
1802 createUseLocal(handlerBlock));
1803 catchScope.putProp(Node.LOCAL_BLOCK_PROP, catchScopeBlock);
1804 catchScope.putIntProp(Node.CATCH_SCOPE_PROP, scopeIndex);
1805 catchScopeBlock.addChildToBack(catchScope);
1806
1807 // Add with statement based on catch scope object
1808 catchScopeBlock.addChildToBack(
1809 createWith(createUseLocal(catchScopeBlock), condStmt,
1810 catchLineNo));
1811
1812 // move to next cb
1813 cb = cb.getNext();
1814 ++scopeIndex;
1815 }
1816 pn.addChildToBack(catchScopeBlock);
1817 if (!hasDefault) {
1818 // Generate code to rethrow if no catch clause was executed
1819 Node rethrow = new Node(Token.RETHROW);
1820 rethrow.putProp(Node.LOCAL_BLOCK_PROP, handlerBlock);
1821 pn.addChildToBack(rethrow);
1822 }
1823
1824 pn.addChildToBack(endCatch);
1825 }
1826
1827 if (hasFinally) {
1828 Node finallyTarget = Node.newTarget();
1829 pn.setFinally(finallyTarget);
1830
1831 // add jsr finally to the try block
1832 pn.addChildToBack(makeJump(Token.JSR, finallyTarget));
1833
1834 // jump around finally code
1835 Node finallyEnd = Node.newTarget();
1836 pn.addChildToBack(makeJump(Token.GOTO, finallyEnd));
1837
1838 pn.addChildToBack(finallyTarget);
1839 Node fBlock = new Node(Token.FINALLY, finallyBlock);
1840 fBlock.putProp(Node.LOCAL_BLOCK_PROP, handlerBlock);
1841 pn.addChildToBack(fBlock);
1842
1843 pn.addChildToBack(finallyEnd);
1844 }
1845 handlerBlock.addChildToBack(pn);
1846 return handlerBlock;
1847 }
1848
1849 private Node createWith(Node obj, Node body, int lineno) {
1850 setRequiresActivation();
1851 Node result = new Node(Token.BLOCK, lineno);
1852 result.addChildToBack(new Node(Token.ENTERWITH, obj));
1853 Node bodyNode = new Node(Token.WITH, body, lineno);
1854 result.addChildrenToBack(bodyNode);
1855 result.addChildToBack(new Node(Token.LEAVEWITH));
1856 return result;
1857 }
1858
1859 private Node createIf(Node cond, Node ifTrue, Node ifFalse, int lineno)
1860 {
1861 int condStatus = isAlwaysDefinedBoolean(cond);
1862 if (condStatus == ALWAYS_TRUE_BOOLEAN) {
1863 return ifTrue;
1864 } else if (condStatus == ALWAYS_FALSE_BOOLEAN) {
1865 if (ifFalse != null) {
1866 return ifFalse;
1867 }
1868 // Replace if (false) xxx by empty block
1869 return new Node(Token.BLOCK, lineno);
1870 }
1871
1872 Node result = new Node(Token.BLOCK, lineno);
1873 Node ifNotTarget = Node.newTarget();
1874 Jump IFNE = new Jump(Token.IFNE, cond);
1875 IFNE.target = ifNotTarget;
1876
1877 result.addChildToBack(IFNE);
1878 result.addChildrenToBack(ifTrue);
1879
1880 if (ifFalse != null) {
1881 Node endTarget = Node.newTarget();
1882 result.addChildToBack(makeJump(Token.GOTO, endTarget));
1883 result.addChildToBack(ifNotTarget);
1884 result.addChildrenToBack(ifFalse);
1885 result.addChildToBack(endTarget);
1886 } else {
1887 result.addChildToBack(ifNotTarget);
1888 }
1889
1890 return result;
1891 }
1892
1893 private Node createCondExpr(Node cond, Node ifTrue, Node ifFalse) {
1894 int condStatus = isAlwaysDefinedBoolean(cond);
1895 if (condStatus == ALWAYS_TRUE_BOOLEAN) {
1896 return ifTrue;
1897 } else if (condStatus == ALWAYS_FALSE_BOOLEAN) {
1898 return ifFalse;
1899 }
1900 return new Node(Token.HOOK, cond, ifTrue, ifFalse);
1901 }
1902
1903 private Node createUnary(int nodeType, Node child)
1904 {
1905 int childType = child.getType();
1906 switch (nodeType) {
1907 case Token.DELPROP: {
1908 Node n;
1909 if (childType == Token.NAME) {
1910 // Transform Delete(Name "a")
1911 // to Delete(Bind("a"), String("a"))
1912 child.setType(Token.BINDNAME);
1913 Node left = child;
1914 Node right = Node.newString(child.getString());
1915 n = new Node(nodeType, left, right);
1916 } else if (childType == Token.GETPROP ||
1917 childType == Token.GETELEM)
1918 {
1919 Node left = child.getFirstChild();
1920 Node right = child.getLastChild();
1921 child.removeChild(left);
1922 child.removeChild(right);
1923 n = new Node(nodeType, left, right);
1924 } else if (childType == Token.GET_REF) {
1925 Node ref = child.getFirstChild();
1926 child.removeChild(ref);
1927 n = new Node(Token.DEL_REF, ref);
1928 } else {
1929 // Always evaluate delete operand, see ES5 11.4.1 & bug #726121
1930 n = new Node(nodeType, new Node(Token.TRUE), child);
1931 }
1932 return n;
1933 }
1934 case Token.TYPEOF:
1935 if (childType == Token.NAME) {
1936 child.setType(Token.TYPEOFNAME);
1937 return child;
1938 }
1939 break;
1940 case Token.BITNOT:
1941 if (childType == Token.NUMBER) {
1942 int value = ScriptRuntime.toInt32(child.getDouble());
1943 child.setDouble(~value);
1944 return child;
1945 }
1946 break;
1947 case Token.NEG:
1948 if (childType == Token.NUMBER) {
1949 child.setDouble(-child.getDouble());
1950 return child;
1951 }
1952 break;
1953 case Token.NOT: {
1954 int status = isAlwaysDefinedBoolean(child);
1955 if (status != 0) {
1956 int type;
1957 if (status == ALWAYS_TRUE_BOOLEAN) {
1958 type = Token.FALSE;
1959 } else {
1960 type = Token.TRUE;
1961 }
1962 if (childType == Token.TRUE || childType == Token.FALSE) {
1963 child.setType(type);
1964 return child;
1965 }
1966 return new Node(type);
1967 }
1968 break;
1969 }
1970 }
1971 return new Node(nodeType, child);
1972 }
1973
1974 private Node createCallOrNew(int nodeType, Node child) {
1975 int type = Node.NON_SPECIALCALL;
1976 if (child.getType() == Token.NAME) {
1977 String name = child.getString();
1978 if (name.equals("eval")) {
1979 type = Node.SPECIALCALL_EVAL;
1980 } else if (name.equals("With")) {
1981 type = Node.SPECIALCALL_WITH;
1982 }
1983 } else if (child.getType() == Token.GETPROP) {
1984 String name = child.getLastChild().getString();
1985 if (name.equals("eval")) {
1986 type = Node.SPECIALCALL_EVAL;
1987 }
1988 }
1989 Node node = new Node(nodeType, child);
1990 if (type != Node.NON_SPECIALCALL) {
1991 // Calls to these functions require activation objects.
1992 setRequiresActivation();
1993 node.putIntProp(Node.SPECIALCALL_PROP, type);
1994 }
1995 return node;
1996 }
1997
1998 private Node createIncDec(int nodeType, boolean post, Node child)
1999 {
2000 child = makeReference(child);
2001 int childType = child.getType();
2002
2003 switch (childType) {
2004 case Token.NAME:
2005 case Token.GETPROP:
2006 case Token.GETELEM:
2007 case Token.GET_REF: {
2008 Node n = new Node(nodeType, child);
2009 int incrDecrMask = 0;
2010 if (nodeType == Token.DEC) {
2011 incrDecrMask |= Node.DECR_FLAG;
2012 }
2013 if (post) {
2014 incrDecrMask |= Node.POST_FLAG;
2015 }
2016 n.putIntProp(Node.INCRDECR_PROP, incrDecrMask);
2017 return n;
2018 }
2019 }
2020 throw Kit.codeBug();
2021 }
2022
2023 private Node createPropertyGet(Node target, String namespace, String name,
2024 int memberTypeFlags)
2025 {
2026 if (namespace == null && memberTypeFlags == 0) {
2027 if (target == null) {
2028 return createName(name);
2029 }
2030 checkActivationName(name, Token.GETPROP);
2031 if (ScriptRuntime.isSpecialProperty(name)) {
2032 Node ref = new Node(Token.REF_SPECIAL, target);
2033 ref.putProp(Node.NAME_PROP, name);
2034 return new Node(Token.GET_REF, ref);
2035 }
2036 return new Node(Token.GETPROP, target, Node.newString(name));
2037 }
2038 Node elem = Node.newString(name);
2039 memberTypeFlags |= Node.PROPERTY_FLAG;
2040 return createMemberRefGet(target, namespace, elem, memberTypeFlags);
2041 }
2042
2043 /**
2044 * @param target the node before the LB
2045 * @param namespace optional namespace
2046 * @param elem the node in the brackets
2047 * @param memberTypeFlags E4X flags
2048 */
2049 private Node createElementGet(Node target, String namespace, Node elem,
2050 int memberTypeFlags)
2051 {
2052 // OPT: could optimize to createPropertyGet
2053 // iff elem is string that can not be number
2054 if (namespace == null && memberTypeFlags == 0) {
2055 // stand-alone [aaa] as primary expression is array literal
2056 // declaration and should not come here!
2057 if (target == null) throw Kit.codeBug();
2058 return new Node(Token.GETELEM, target, elem);
2059 }
2060 return createMemberRefGet(target, namespace, elem, memberTypeFlags);
2061 }
2062
2063 private Node createMemberRefGet(Node target, String namespace, Node elem,
2064 int memberTypeFlags)
2065 {
2066 Node nsNode = null;
2067 if (namespace != null) {
2068 // See 11.1.2 in ECMA 357
2069 if (namespace.equals("*")) {
2070 nsNode = new Node(Token.NULL);
2071 } else {
2072 nsNode = createName(namespace);
2073 }
2074 }
2075 Node ref;
2076 if (target == null) {
2077 if (namespace == null) {
2078 ref = new Node(Token.REF_NAME, elem);
2079 } else {
2080 ref = new Node(Token.REF_NS_NAME, nsNode, elem);
2081 }
2082 } else {
2083 if (namespace == null) {
2084 ref = new Node(Token.REF_MEMBER, target, elem);
2085 } else {
2086 ref = new Node(Token.REF_NS_MEMBER, target, nsNode, elem);
2087 }
2088 }
2089 if (memberTypeFlags != 0) {
2090 ref.putIntProp(Node.MEMBER_TYPE_PROP, memberTypeFlags);
2091 }
2092 return new Node(Token.GET_REF, ref);
2093 }
2094
2095 private Node createBinary(int nodeType, Node left, Node right) {
2096 switch (nodeType) {
2097
2098 case Token.ADD:
2099 // numerical addition and string concatenation
2100 if (left.type == Token.STRING) {
2101 String s2;
2102 if (right.type == Token.STRING) {
2103 s2 = right.getString();
2104 } else if (right.type == Token.NUMBER) {
2105 s2 = ScriptRuntime.numberToString(right.getDouble(), 10);
2106 } else {
2107 break;
2108 }
2109 String s1 = left.getString();
2110 left.setString(s1.concat(s2));
2111 return left;
2112 } else if (left.type == Token.NUMBER) {
2113 if (right.type == Token.NUMBER) {
2114 left.setDouble(left.getDouble() + right.getDouble());
2115 return left;
2116 } else if (right.type == Token.STRING) {
2117 String s1, s2;
2118 s1 = ScriptRuntime.numberToString(left.getDouble(), 10);
2119 s2 = right.getString();
2120 right.setString(s1.concat(s2));
2121 return right;
2122 }
2123 }
2124 // can't do anything if we don't know both types - since
2125 // 0 + object is supposed to call toString on the object and do
2126 // string concantenation rather than addition
2127 break;
2128
2129 case Token.SUB:
2130 // numerical subtraction
2131 if (left.type == Token.NUMBER) {
2132 double ld = left.getDouble();
2133 if (right.type == Token.NUMBER) {
2134 //both numbers
2135 left.setDouble(ld - right.getDouble());
2136 return left;
2137 } else if (ld == 0.0) {
2138 // first 0: 0-x -> -x
2139 return new Node(Token.NEG, right);
2140 }
2141 } else if (right.type == Token.NUMBER) {
2142 if (right.getDouble() == 0.0) {
2143 //second 0: x - 0 -> +x
2144 // can not make simply x because x - 0 must be number
2145 return new Node(Token.POS, left);
2146 }
2147 }
2148 break;
2149
2150 case Token.MUL:
2151 // numerical multiplication
2152 if (left.type == Token.NUMBER) {
2153 double ld = left.getDouble();
2154 if (right.type == Token.NUMBER) {
2155 //both numbers
2156 left.setDouble(ld * right.getDouble());
2157 return left;
2158 } else if (ld == 1.0) {
2159 // first 1: 1 * x -> +x
2160 return new Node(Token.POS, right);
2161 }
2162 } else if (right.type == Token.NUMBER) {
2163 if (right.getDouble() == 1.0) {
2164 //second 1: x * 1 -> +x
2165 // can not make simply x because x - 0 must be number
2166 return new Node(Token.POS, left);
2167 }
2168 }
2169 // can't do x*0: Infinity * 0 gives NaN, not 0
2170 break;
2171
2172 case Token.DIV:
2173 // number division
2174 if (right.type == Token.NUMBER) {
2175 double rd = right.getDouble();
2176 if (left.type == Token.NUMBER) {
2177 // both constants -- just divide, trust Java to handle x/0
2178 left.setDouble(left.getDouble() / rd);
2179 return left;
2180 } else if (rd == 1.0) {
2181 // second 1: x/1 -> +x
2182 // not simply x to force number convertion
2183 return new Node(Token.POS, left);
2184 }
2185 }
2186 break;
2187
2188 case Token.AND: {
2189 // Since x && y gives x, not false, when Boolean(x) is false,
2190 // and y, not Boolean(y), when Boolean(x) is true, x && y
2191 // can only be simplified if x is defined. See bug 309957.
2192
2193 int leftStatus = isAlwaysDefinedBoolean(left);
2194 if (leftStatus == ALWAYS_FALSE_BOOLEAN) {
2195 // if the first one is false, just return it
2196 return left;
2197 } else if (leftStatus == ALWAYS_TRUE_BOOLEAN) {
2198 // if first is true, set to second
2199 return right;
2200 }
2201 break;
2202 }
2203
2204 case Token.OR: {
2205 // Since x || y gives x, not true, when Boolean(x) is true,
2206 // and y, not Boolean(y), when Boolean(x) is false, x || y
2207 // can only be simplified if x is defined. See bug 309957.
2208
2209 int leftStatus = isAlwaysDefinedBoolean(left);
2210 if (leftStatus == ALWAYS_TRUE_BOOLEAN) {
2211 // if the first one is true, just return it
2212 return left;
2213 } else if (leftStatus == ALWAYS_FALSE_BOOLEAN) {
2214 // if first is false, set to second
2215 return right;
2216 }
2217 break;
2218 }
2219 }
2220
2221 return new Node(nodeType, left, right);
2222 }
2223
2224 private Node createAssignment(int assignType, Node left, Node right)
2225 {
2226 Node ref = makeReference(left);
2227 if (ref == null) {
2228 if (left.getType() == Token.ARRAYLIT ||
2229 left.getType() == Token.OBJECTLIT)
2230 {
2231 if (assignType != Token.ASSIGN) {
2232 reportError("msg.bad.destruct.op");
2233 return right;
2234 }
2235 return createDestructuringAssignment(-1, left, right);
2236 }
2237 reportError("msg.bad.assign.left");
2238 return right;
2239 }
2240 left = ref;
2241
2242 int assignOp;
2243 switch (assignType) {
2244 case Token.ASSIGN:
2245 return simpleAssignment(left, right);
2246 case Token.ASSIGN_BITOR: assignOp = Token.BITOR; break;
2247 case Token.ASSIGN_BITXOR: assignOp = Token.BITXOR; break;
2248 case Token.ASSIGN_BITAND: assignOp = Token.BITAND; break;
2249 case Token.ASSIGN_LSH: assignOp = Token.LSH; break;
2250 case Token.ASSIGN_RSH: assignOp = Token.RSH; break;
2251 case Token.ASSIGN_URSH: assignOp = Token.URSH; break;
2252 case Token.ASSIGN_ADD: assignOp = Token.ADD; break;
2253 case Token.ASSIGN_SUB: assignOp = Token.SUB; break;
2254 case Token.ASSIGN_MUL: assignOp = Token.MUL; break;
2255 case Token.ASSIGN_DIV: assignOp = Token.DIV; break;
2256 case Token.ASSIGN_MOD: assignOp = Token.MOD; break;
2257 default: throw Kit.codeBug();
2258 }
2259
2260 int nodeType = left.getType();
2261 switch (nodeType) {
2262 case Token.NAME: {
2263 Node op = new Node(assignOp, left, right);
2264 Node lvalueLeft = Node.newString(Token.BINDNAME, left.getString());
2265 return new Node(Token.SETNAME, lvalueLeft, op);
2266 }
2267 case Token.GETPROP:
2268 case Token.GETELEM: {
2269 Node obj = left.getFirstChild();
2270 Node id = left.getLastChild();
2271
2272 int type = nodeType == Token.GETPROP
2273 ? Token.SETPROP_OP
2274 : Token.SETELEM_OP;
2275
2276 Node opLeft = new Node(Token.USE_STACK);
2277 Node op = new Node(assignOp, opLeft, right);
2278 return new Node(type, obj, id, op);
2279 }
2280 case Token.GET_REF: {
2281 ref = left.getFirstChild();
2282 checkMutableReference(ref);
2283 Node opLeft = new Node(Token.USE_STACK);
2284 Node op = new Node(assignOp, opLeft, right);
2285 return new Node(Token.SET_REF_OP, ref, op);
2286 }
2287 }
2288
2289 throw Kit.codeBug();
2290 }
2291
2292 private Node createUseLocal(Node localBlock) {
2293 if (Token.LOCAL_BLOCK != localBlock.getType()) throw Kit.codeBug();
2294 Node result = new Node(Token.LOCAL_LOAD);
2295 result.putProp(Node.LOCAL_BLOCK_PROP, localBlock);
2296 return result;
2297 }
2298
2299 private Jump makeJump(int type, Node target) {
2300 Jump n = new Jump(type);
2301 n.target = target;
2302 return n;
2303 }
2304
2305 private Node makeReference(Node node) {
2306 int type = node.getType();
2307 switch (type) {
2308 case Token.NAME:
2309 case Token.GETPROP:
2310 case Token.GETELEM:
2311 case Token.GET_REF:
2312 return node;
2313 case Token.CALL:
2314 node.setType(Token.REF_CALL);
2315 return new Node(Token.GET_REF, node);
2316 }
2317 // Signal caller to report error
2318 return null;
2319 }
2320
2321 // Check if Node always mean true or false in boolean context
2322 private static int isAlwaysDefinedBoolean(Node node) {
2323 switch (node.getType()) {
2324 case Token.FALSE:
2325 case Token.NULL:
2326 return ALWAYS_FALSE_BOOLEAN;
2327 case Token.TRUE:
2328 return ALWAYS_TRUE_BOOLEAN;
2329 case Token.NUMBER: {
2330 double num = node.getDouble();
2331 if (num == num && num != 0.0) {
2332 return ALWAYS_TRUE_BOOLEAN;
2333 } else {
2334 return ALWAYS_FALSE_BOOLEAN;
2335 }
2336 }
2337 }
2338 return 0;
2339 }
2340
2341 // Check if node is the target of a destructuring bind.
2342 boolean isDestructuring(Node n) {
2343 return n instanceof DestructuringForm
2344 && ((DestructuringForm)n).isDestructuring();
2345 }
2346
2347 Node decompileFunctionHeader(FunctionNode fn) {
2348 Node mexpr = null;
2349 if (fn.getFunctionName() != null) {
2350 decompiler.addName(fn.getName());
2351 } else if (fn.getMemberExprNode() != null) {
2352 mexpr = transform(fn.getMemberExprNode());
2353 }
2354 boolean isArrow = fn.getFunctionType() == FunctionNode.ARROW_FUNCTION;
2355 boolean noParen = isArrow && fn.getLp() == -1;
2356 if (!noParen) {
2357 decompiler.addToken(Token.LP);
2358 }
2359 List<AstNode> params = fn.getParams();
2360 for (int i = 0; i < params.size(); i++) {
2361 decompile(params.get(i));
2362 if (i < params.size() - 1) {
2363 decompiler.addToken(Token.COMMA);
2364 }
2365 }
2366 if (!noParen) {
2367 decompiler.addToken(Token.RP);
2368 }
2369 if (isArrow) {
2370 decompiler.addToken(Token.ARROW);
2371 }
2372 if (!fn.isExpressionClosure()) {
2373 decompiler.addEOL(Token.LC);
2374 }
2375 return mexpr;
2376 }
2377
2378 void decompile(AstNode node) {
2379 switch (node.getType()) {
2380 case Token.ARRAYLIT:
2381 decompileArrayLiteral((ArrayLiteral)node);
2382 break;
2383 case Token.OBJECTLIT:
2384 decompileObjectLiteral((ObjectLiteral)node);
2385 break;
2386 case Token.STRING:
2387 decompiler.addString(((StringLiteral)node).getValue());
2388 break;
2389 case Token.NAME:
2390 decompiler.addName(((Name)node).getIdentifier());
2391 break;
2392 case Token.NUMBER:
2393 decompiler.addNumber(((NumberLiteral)node).getNumber());
2394 break;
2395 case Token.GETPROP:
2396 decompilePropertyGet((PropertyGet)node);
2397 break;
2398 case Token.EMPTY:
2399 break;
2400 case Token.GETELEM:
2401 decompileElementGet((ElementGet) node);
2402 break;
2403 case Token.THIS:
2404 decompiler.addToken(node.getType());
2405 break;
2406 default:
2407 Kit.codeBug("unexpected token: "
2408 + Token.typeToName(node.getType()));
2409 }
2410 }
2411
2412 // used for destructuring forms, since we don't transform() them
2413 void decompileArrayLiteral(ArrayLiteral node) {
2414 decompiler.addToken(Token.LB);
2415 List<AstNode> elems = node.getElements();
2416 int size = elems.size();
2417 for (int i = 0; i < size; i++) {
2418 AstNode elem = elems.get(i);
2419 decompile(elem);
2420 if (i < size - 1) {
2421 decompiler.addToken(Token.COMMA);
2422 }
2423 }
2424 decompiler.addToken(Token.RB);
2425 }
2426
2427 // only used for destructuring forms
2428 void decompileObjectLiteral(ObjectLiteral node) {
2429 decompiler.addToken(Token.LC);
2430 List<ObjectProperty> props = node.getElements();
2431 int size = props.size();
2432 for (int i = 0; i < size; i++) {
2433 ObjectProperty prop = props.get(i);
2434 boolean destructuringShorthand =
2435 Boolean.TRUE.equals(prop.getProp(Node.DESTRUCTURING_SHORTHAND));
2436 decompile(prop.getLeft());
2437 if (!destructuringShorthand) {
2438 decompiler.addToken(Token.COLON);
2439 decompile(prop.getRight());
2440 }
2441 if (i < size - 1) {
2442 decompiler.addToken(Token.COMMA);
2443 }
2444 }
2445 decompiler.addToken(Token.RC);
2446 }
2447
2448 // only used for destructuring forms
2449 void decompilePropertyGet(PropertyGet node) {
2450 decompile(node.getTarget());
2451 decompiler.addToken(Token.DOT);
2452 decompile(node.getProperty());
2453 }
2454
2455 // only used for destructuring forms
2456 void decompileElementGet(ElementGet node) {
2457 decompile(node.getTarget());
2458 decompiler.addToken(Token.LB);
2459 decompile(node.getElement());
2460 decompiler.addToken(Token.RB);
2461 }
2462 }