aboutsummaryrefslogtreecommitdiff
path: root/src/jdk/nashorn/internal/codegen/Lower.java
blob: 5f0026893c9fb948594f4c7bf64a6daf1ec46488 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package jdk.nashorn.internal.codegen;

import static jdk.nashorn.internal.codegen.CompilerConstants.ARGUMENTS;
import static jdk.nashorn.internal.codegen.CompilerConstants.CALLEE;
import static jdk.nashorn.internal.codegen.CompilerConstants.EVAL;
import static jdk.nashorn.internal.codegen.CompilerConstants.SCOPE;
import static jdk.nashorn.internal.codegen.CompilerConstants.SCRIPT_RETURN;
import static jdk.nashorn.internal.codegen.CompilerConstants.THIS;
import static jdk.nashorn.internal.codegen.CompilerConstants.VARARGS;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;
import jdk.nashorn.internal.ir.AccessNode;
import jdk.nashorn.internal.ir.BaseNode;
import jdk.nashorn.internal.ir.BinaryNode;
import jdk.nashorn.internal.ir.Block;
import jdk.nashorn.internal.ir.BreakNode;
import jdk.nashorn.internal.ir.CallNode;
import jdk.nashorn.internal.ir.CaseNode;
import jdk.nashorn.internal.ir.CatchNode;
import jdk.nashorn.internal.ir.ContinueNode;
import jdk.nashorn.internal.ir.DoWhileNode;
import jdk.nashorn.internal.ir.EmptyNode;
import jdk.nashorn.internal.ir.ExecuteNode;
import jdk.nashorn.internal.ir.ForNode;
import jdk.nashorn.internal.ir.FunctionNode;
import jdk.nashorn.internal.ir.IdentNode;
import jdk.nashorn.internal.ir.IfNode;
import jdk.nashorn.internal.ir.IndexNode;
import jdk.nashorn.internal.ir.LabelNode;
import jdk.nashorn.internal.ir.LabeledNode;
import jdk.nashorn.internal.ir.LineNumberNode;
import jdk.nashorn.internal.ir.LiteralNode;
import jdk.nashorn.internal.ir.Node;
import jdk.nashorn.internal.ir.ReturnNode;
import jdk.nashorn.internal.ir.SwitchNode;
import jdk.nashorn.internal.ir.Symbol;
import jdk.nashorn.internal.ir.ThrowNode;
import jdk.nashorn.internal.ir.TryNode;
import jdk.nashorn.internal.ir.UnaryNode;
import jdk.nashorn.internal.ir.VarNode;
import jdk.nashorn.internal.ir.WhileNode;
import jdk.nashorn.internal.ir.WithNode;
import jdk.nashorn.internal.ir.visitor.NodeOperatorVisitor;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.parser.TokenType;
import jdk.nashorn.internal.runtime.DebugLogger;
import jdk.nashorn.internal.runtime.ScriptRuntime;
import jdk.nashorn.internal.runtime.Source;

/**
 * Lower to more primitive operations. After lowering, an AST still has no symbols
 * and types, but several nodes have been turned into more low level constructs
 * and control flow termination criteria have been computed.
 *
 * We do things like code copying/inlining of finallies here, as it is much
 * harder and context dependent to do any code copying after symbols have been
 * finalized.
 */

final class Lower extends NodeOperatorVisitor {

    /**
     * Nesting level stack. Currently just used for loops to avoid the problem
     * with terminal bodies that end with throw/return but still do continues to
     * outer loops or same loop.
     */
    private final Deque<Node> nesting;

    private static final DebugLogger LOG = new DebugLogger("lower");

    private Node lastStatement;

    private List<Node> statements;

    /**
     * Constructor.
     *
     * @param compiler the compiler
     */
    Lower() {
        this.nesting    = new ArrayDeque<>();
        this.statements = new ArrayList<>();
    }

    @Override
    public Node enter(final Block block) {
        final Node       savedLastStatement = lastStatement;
        final List<Node> savedStatements    = statements;

        try {
            this.statements = new ArrayList<>();
            for (final Node statement : block.getStatements()) {
                statement.accept(this);
                /*
                 * This is slightly unsound, for example if we have a loop with
                 * a guarded statement like if (x) continue in the body and the
                 * body ends with TERMINAL, e.g. return; we removed the continue
                 * before we had the loop stack, as all we cared about was a
                 * return last in the loop.
                 *
                 * @see NASHORN-285
                 */
                if (lastStatement != null && lastStatement.isTerminal()) {
                    copyTerminal(block, lastStatement);
                    break;
                }
            }
            block.setStatements(statements);

        } finally {
            this.statements = savedStatements;
            this.lastStatement = savedLastStatement;
        }

        return null;
    }

    @Override
    public Node enter(final BreakNode breakNode) {
        return enterBreakOrContinue(breakNode);
    }

    @Override
    public Node enter(final CallNode callNode) {
        final Node function = markerFunction(callNode.getFunction());
        callNode.setFunction(function);
        checkEval(callNode); //check if this is an eval call and store the information
        return callNode;
    }

    @Override
    public Node leave(final CaseNode caseNode) {
        caseNode.copyTerminalFlags(caseNode.getBody());
        return caseNode;
    }

    @Override
    public Node leave(final CatchNode catchNode) {
        catchNode.copyTerminalFlags(catchNode.getBody());
        addStatement(catchNode);
        return catchNode;
    }

    @Override
    public Node enter(final ContinueNode continueNode) {
        return enterBreakOrContinue(continueNode);
    }

    @Override
    public Node enter(final DoWhileNode doWhileNode) {
        return enter((WhileNode)doWhileNode);
    }

    @Override
    public Node leave(final DoWhileNode doWhileNode) {
        return leave((WhileNode)doWhileNode);
    }

    @Override
    public Node enter(final EmptyNode emptyNode) {
        return null;
    }

    @Override
    public Node leave(final ExecuteNode executeNode) {
        final Node expr = executeNode.getExpression();

        if (getCurrentFunctionNode().isScript()) {
            if (!(expr instanceof Block)) {
                if (!isInternalExpression(expr) && !isEvalResultAssignment(expr)) {
                    executeNode.setExpression(new BinaryNode(executeNode.getSource(), Token.recast(executeNode.getToken(), TokenType.ASSIGN),
                            getCurrentFunctionNode().getResultNode(),
                            expr));
                }
            }
        }

        copyTerminal(executeNode, executeNode.getExpression());
        addStatement(executeNode);

        return executeNode;
    }

    @Override
    public Node enter(final ForNode forNode) {
        nest(forNode);
        return forNode;
    }

    @Override
    public Node leave(final ForNode forNode) {
        final Node  test = forNode.getTest();
        final Block body = forNode.getBody();

        if (!forNode.isForIn() && test == null) {
            setHasGoto(forNode);
        }

        final boolean escapes = controlFlowEscapes(body);
        if (escapes) {
            setTerminal(body, false);
        }

        // pop the loop from the loop context
        unnest(forNode);

        if (!forNode.isForIn() && conservativeAlwaysTrue(test)) {
            forNode.setTest(null);
            setTerminal(forNode, !escapes);
        }

        addStatement(forNode);

        return forNode;
    }

    @Override
    public Node enter(final FunctionNode functionNode) {
        LOG.info("START FunctionNode: " + functionNode.getName());

        if (functionNode.isLazy()) {
            LOG.info("LAZY: " + functionNode.getName());
            return null;
        }

        initFunctionNode(functionNode);

        Node initialEvalResult = LiteralNode.newInstance(functionNode, ScriptRuntime.UNDEFINED);

        nest(functionNode);

        /*
         * As we are evaluating a nested structure, we need to store the
         * statement list for the surrounding block and restore it when the
         * function is done
         */
        final List<Node> savedStatements = statements;
        final Node savedLastStatement = lastStatement;

        statements    = new ArrayList<>();
        lastStatement = null;

        // for initial eval result is the last declared function
        for (final FunctionNode nestedFunction : functionNode.getFunctions()) {
            final IdentNode ident = nestedFunction.getIdent();
            if (ident != null && nestedFunction.isStatement()) {
                initialEvalResult = new IdentNode(ident);
            }
        }

        if (functionNode.needsSelfSymbol()) {
            //function needs to start with var funcIdent = __callee_;
            statements.add(functionNode.getSelfSymbolInit().accept(this));
        }

        try {
            // Every nested function needs a definition in the outer function with its name. Add these.
            for (final FunctionNode nestedFunction : functionNode.getFunctions()) {
                final VarNode varNode = nestedFunction.getFunctionVarNode();
                if (varNode != null) {
                    final LineNumberNode lineNumberNode = nestedFunction.getFunctionVarLineNumberNode();
                    if (lineNumberNode != null) {
                        lineNumberNode.accept(this);
                    }
                    varNode.accept(this);
                    varNode.setIsFunctionVarNode();
                }
            }

            if (functionNode.isScript()) {
                new ExecuteNode(functionNode.getSource(), functionNode.getFirstToken(), functionNode.getFinish(), initialEvalResult).accept(this);
            }

            //do the statements - this fills the block with code
            for (final Node statement : functionNode.getStatements()) {
                statement.accept(this);
                //If there are unused terminated endpoints in the function, we need
                // to add a "return undefined" in those places for correct semantics
                LOG.info("Checking lastStatement="+lastStatement+" for terminal flags");
                if (lastStatement != null && lastStatement.hasTerminalFlags()) {
                    copyTerminal(functionNode, lastStatement);
                    break;
                }
            }

            functionNode.setStatements(statements);

            if (!functionNode.isTerminal()) {
                guaranteeReturn(functionNode);
            }

            //lower all nested functions
            for (final FunctionNode nestedFunction : functionNode.getFunctions()) {
                nestedFunction.accept(this);
            }

        } finally {
            statements    = savedStatements;
            lastStatement = savedLastStatement;
        }

        LOG.info("END FunctionNode: " + functionNode.getName());
        unnest(functionNode);

        return null;
    }

    @Override
    public Node enter(final IfNode ifNode) {
        return nest(ifNode);
    }

    @Override
    public Node leave(final IfNode ifNode) {
        final Node pass = ifNode.getPass();
        final Node fail = ifNode.getFail();

        if (pass.isTerminal() && fail != null && fail.isTerminal()) {
            setTerminal(ifNode,  true);
        }

        addStatement(ifNode);
        unnest(ifNode);

        return ifNode;
    }

    @Override
    public Node enter(LabelNode labelNode) {
        final Block body = labelNode.getBody();
        body.accept(this);
        copyTerminal(labelNode, body);
        addStatement(labelNode);
        return null;
    }

    @Override
    public Node enter(final LineNumberNode lineNumberNode) {
        addStatement(lineNumberNode, false); // don't put it in lastStatement cache
        return null;
    }

    @Override
    public Node enter(final ReturnNode returnNode) {
        final TryNode tryNode = returnNode.getTryChain();
        final Node    expr    = returnNode.getExpression();

        if (tryNode != null) {
            //we are inside a try block - we don't necessarily have a result node yet. attr will do that.
            if (expr != null) {
                final Source source = getCurrentFunctionNode().getSource();

                //we need to evaluate the result of the return in case it is complex while
                //still in the try block, store it in a result value and return it afterwards
                final long token        = returnNode.getToken();
                final Node resultNode   = new IdentNode(getCurrentFunctionNode().getResultNode());
                final Node assignResult = new BinaryNode(source, Token.recast(token, TokenType.ASSIGN), resultNode, expr);

                //add return_in_try = expr; to try block
                new ExecuteNode(source, token, Token.descPosition(token), assignResult).accept(this);

                //splice in the finally code, inlining it here
                if (copyFinally(tryNode, null)) {
                    return null;
                }

                //make sure that the return node now returns 'return_in_try'
                returnNode.setExpression(resultNode);
            } else if (copyFinally(tryNode, null)) {
                return null;
            }
        } else if (expr != null) {
            returnNode.setExpression(expr.accept(this));
        }

        addStatement(returnNode);

        return null;
    }

    @Override
    public Node leave(final ReturnNode returnNode) {
        addStatement(returnNode); //ReturnNodes are always terminal, marked as such in constructor
        return returnNode;
    }

    @Override
    public Node enter(final SwitchNode switchNode) {
        nest(switchNode);
        return switchNode;
    }

    @Override
    public Node leave(final SwitchNode switchNode) {
        unnest(switchNode);

        final List<CaseNode> cases       = switchNode.getCases();
        final CaseNode       defaultCase = switchNode.getDefaultCase();

        boolean allTerminal = !cases.isEmpty();
        for (final CaseNode caseNode : switchNode.getCases()) {
            allTerminal &= caseNode.isTerminal();
        }

        if (allTerminal && defaultCase != null && defaultCase.isTerminal()) {
            setTerminal(switchNode, true);
        }

        addStatement(switchNode);

        return switchNode;
    }

    @Override
    public Node leave(final ThrowNode throwNode) {
        addStatement(throwNode); //ThrowNodes are always terminal, marked as such in constructor
        return throwNode;
    }

    @Override
    public Node enter(final TryNode tryNode) {
        final Block  finallyBody = tryNode.getFinallyBody();
        final long   token       = tryNode.getToken();
        final int    finish      = tryNode.getFinish();

        nest(tryNode);

        if (finallyBody == null) {
            //do nothing if no finally exists
            return tryNode;
        }

        /*
         * We have a finally clause.
         *
         * Transform to do finally tail duplication as follows:
         *
         * <pre>
         *  try {
         *    try_body
         *  } catch e1 {
         *    catchbody_1
         *  }
         *  ...
         *  } catch en {
         *    catchbody_n
         *  } finally {
         *    finally_body
         *  }
         *
         *  (where e1 ... en are optional)
         *
         *  turns into
         *
         *  try {
         *    try {
         *      try_body
         *    } catch e1 {
         *      catchbody1
         *      //nothing inlined explicitly here, return, break other
         *      //terminals may inline the finally body
         *      ...
         *    } catch en {
         *      catchbody2
         *      //nothing inlined explicitly here, return, break other
         *      //terminals may inline the finally body
         *    }
         *  } catch all ex {
         *      finally_body_inlined
         *      rethrow ex
         *  }
         *  finally_body_inlined
         * </pre>
         *
         * If tries are catches are terminal, visitors for return, break &
         * continue will handle the tail duplications. Throw needs to be
         * treated specially with the catchall as described in the above
         * ASCII art.
         *
         * If the try isn't terminal we do the finally_body_inlined at the
         * end. If the try is terminated with continue/break/return the
         * existing visitor logic will inline the finally before that
         * operation. if the try is terminated with a throw, the catches e1
         * ... en will have a chance to process the exception. If the
         * appropriate catch e1..en is non terminal we fall through to the
         * last finally_body_inlined. if the catch e1...en IS terminal with
         * continue/break/return existing visitor logic will fix it. If they
         * are terminal with another throw it goes to the catchall and the
         * finally_body_inlined marked (*) will fix it before rethrowing
         * whatever problem there was for identical semantic.
         */
        final Source source = getCurrentFunctionNode().getSource();

        // if try node does not contain a catch we can skip creation of a new
        // try node and just append our synthetic catch to the existing try node.
        if (!tryNode.getCatchBlocks().isEmpty()) {
            // insert an intermediate try-catch* node, where we move the body and all catch blocks.
            // the original try node become a try-finally container for the new try-catch* node.
            // because we don't clone (to avoid deep copy), we have to fix the block chain in the end.
            final TryNode innerTryNode;
            innerTryNode = new TryNode(source, token, finish, tryNode.getNext());
            innerTryNode.setBody(tryNode.getBody());
            innerTryNode.setCatchBlocks(tryNode.getCatchBlocks());

            // set outer tryNode's body to innerTryNode
            final Block outerBody;
            outerBody = new Block(source, token, finish, tryNode.getBody().getParent(), getCurrentFunctionNode());
            outerBody.setStatements(new ArrayList<Node>(Arrays.asList(innerTryNode)));
            tryNode.setBody(outerBody);
            tryNode.setCatchBlocks(null);

            // now before we go on, we have to fix the block parents
            // (we repair the block tree after the insertion so that all references are intact)
            innerTryNode.getBody().setParent(tryNode.getBody());
            for (final Block block : innerTryNode.getCatchBlocks()) {
                block.setParent(tryNode.getBody());
            }
        }

        // create a catch-all that inlines finally and rethrows

        final Block catchBlock      = new Block(source, token, finish, getCurrentBlock(), getCurrentFunctionNode());
        //this catch block should get define symbol

        final Block catchBody       = new Block(source, token, finish, catchBlock, getCurrentFunctionNode());
        final Node  catchAllFinally = finallyBody.clone();

        catchBody.addStatement(new ExecuteNode(source, finallyBody.getToken(), finallyBody.getFinish(), catchAllFinally));
        setTerminal(catchBody, true);

        final CatchNode catchAllNode;
        final IdentNode exception;

        exception    = new IdentNode(source, token, finish, getCurrentFunctionNode().uniqueName("catch_all"));
        catchAllNode = new CatchNode(source, token, finish, new IdentNode(exception), null, catchBody);
        catchAllNode.setIsSyntheticRethrow();

        catchBlock.addStatement(catchAllNode);

        // replace all catches of outer tryNode with the catch-all
        tryNode.setCatchBlocks(new ArrayList<>(Arrays.asList(catchBlock)));

        /*
         * We leave the finally block for the original try in place for now
         * so that children visitations will work. It is removed and placed
         * afterwards in the else case below, after all children are visited
         */

        return tryNode;
    }

    @Override
    public Node leave(final TryNode tryNode) {
        final Block finallyBody   = tryNode.getFinallyBody();

        boolean allTerminal = tryNode.getBody().isTerminal() && (finallyBody == null || finallyBody.isTerminal());

        for (final Block catchBlock : tryNode.getCatchBlocks()) {
            allTerminal &= catchBlock.isTerminal();
        }

        tryNode.setIsTerminal(allTerminal);

        addStatement(tryNode);
        unnest(tryNode);

        // if finally body is present, place it after the tryNode
        if (finallyBody != null) {
            tryNode.setFinallyBody(null);
            addStatement(finallyBody);
        }

        return tryNode;
    }

    @Override
    public Node leave(final VarNode varNode) {
        addStatement(varNode);
        return varNode;
    }

    @Override
    public Node enter(final WhileNode whileNode) {
        return nest(whileNode);
    }

    @Override
    public Node leave(final WhileNode whileNode) {
        final Node test = whileNode.getTest();

        if (test == null) {
            setHasGoto(whileNode);
        }

        final Block   body    = whileNode.getBody();
        final boolean escapes = controlFlowEscapes(body);
        if (escapes) {
            setTerminal(body, false);
        }

        Node node = whileNode;

        if (body.isTerminal()) {
            if (whileNode instanceof DoWhileNode) {
                setTerminal(whileNode, true);
            } else if (conservativeAlwaysTrue(test)) {
                node = new ForNode(whileNode.getSource(), whileNode.getToken(), whileNode.getFinish());
                ((ForNode)node).setBody(body);
                ((ForNode)node).accept(this);
                setTerminal(node, !escapes);
            }
        }

        // pop the loop from the loop context
        unnest(whileNode);
        addStatement(node);

        return node;
    }

    @Override
    public Node leave(final WithNode withNode) {
        if (withNode.getBody().isTerminal()) {
            setTerminal(withNode,  true);
        }
        addStatement(withNode);

        return withNode;
    }

    @Override
    public Node leaveDELETE(final UnaryNode unaryNode) {
        final Node rhs = unaryNode.rhs();
        if (rhs instanceof IdentNode || rhs instanceof BaseNode) {
            return unaryNode;
        }
        addStatement(new ExecuteNode(rhs));
        return LiteralNode.newInstance(unaryNode, true);
    }

    /**
     * Given a function node that is a callee in a CallNode, replace it with
     * the appropriate marker function. This is used by {@link CodeGenerator}
     * for fast scope calls
     *
     * @param function function called by a CallNode
     * @return transformed node to marker function or identity if not ident/access/indexnode
     */
    private static Node markerFunction(final Node function) {
        if (function instanceof IdentNode) {
            return new IdentNode((IdentNode)function) {
                @Override
                public boolean isFunction() {
                    return true;
                }
            };
        } else if (function instanceof AccessNode) {
            return new AccessNode((AccessNode)function) {
                @Override
                public boolean isFunction() {
                    return true;
                }
            };
        } else if (function instanceof IndexNode) {
            return new IndexNode((IndexNode)function) {
                @Override
                public boolean isFunction() {
                    return true;
                }
            };
        }

        return function;
    }

    /**
     * Calculate a synthetic eval location for a node for the stacktrace, for example src#17<eval>
     * @param node a node
     * @return eval location
     */
    private static String evalLocation(final IdentNode node) {
        //final StringBuilder sb = new StringBuilder(node.getSource().getName());
        return new StringBuilder().
            append(node.getSource().getName()).
            append('#').
            append(node.getSource().getLine(node.position())).
            append("<eval>").
            toString();
    }

    /**
     * Check whether a call node may be a call to eval. In that case we
     * clone the args in order to create the following construct in
     * {@link CodeGenerator}
     *
     * <pre>
     * if (calledFuntion == buildInEval) {
     *    eval(cloned arg);
     * } else {
     *    cloned arg;
     * }
     * </pre>
     *
     * @param callNode call node to check if it's an eval
     */
    private void checkEval(final CallNode callNode) {
        if (callNode.getFunction() instanceof IdentNode) {

            final List<Node> args   = callNode.getArgs();
            final IdentNode  callee = (IdentNode)callNode.getFunction();

            // 'eval' call with at least one argument
            if (args.size() >= 1 && EVAL.tag().equals(callee.getName())) {
                final CallNode.EvalArgs evalArgs =
                    new CallNode.EvalArgs(
                        args.get(0).clone().accept(this), //clone as we use this for the "is eval case". original evaluated separately for "is not eval case"
                        getCurrentFunctionNode().getThisNode(),
                        evalLocation(callee),
                        getCurrentFunctionNode().isStrictMode());
                callNode.setEvalArgs(evalArgs);
            }
        }
    }

    private static boolean conservativeAlwaysTrue(final Node node) {
        return node == null || ((node instanceof LiteralNode) && Boolean.TRUE.equals(((LiteralNode<?>)node).getValue()));
    }

    /**
     * Helper that given a loop body makes sure that it is not terminal if it
     * has a continue that leads to the loop header or to outer loops' loop
     * headers. This means that, even if the body ends with a terminal
     * statement, we cannot tag it as terminal
     *
     * @param loopBody the loop body to check
     * @return true if control flow may escape the loop
     */
    private boolean controlFlowEscapes(final Node loopBody) {
        final List<Node> escapes = new ArrayList<>();

        loopBody.accept(new NodeVisitor() {
            @Override
            public Node leave(final BreakNode node) {
                escapes.add(node);
                return node;
            }

            @Override
            public Node leave(final ContinueNode node) {
                // all inner loops have been popped.
                if (nesting.contains(node.getTargetNode())) {
                    escapes.add(node);
                }
                return node;
            }
        });

        return !escapes.isEmpty();
    }

    private void guaranteeReturn(final FunctionNode functionNode) {
        Node resultNode;

        if (functionNode.isScript()) {
            resultNode = functionNode.getResultNode(); // the eval result, symbol assigned in Attr
        } else {
            if (lastStatement != null && lastStatement.isTerminal() || lastStatement instanceof ReturnNode) {
                return; //already in place or not needed, as it should be for a non-undefined returning function
            }
            resultNode = LiteralNode.newInstance(functionNode, ScriptRuntime.UNDEFINED);
        }

        //create a return statement
        final Node returnNode = new ReturnNode(functionNode.getSource(), functionNode.getLastToken(), functionNode.getFinish(), resultNode, null);
        returnNode.accept(this);
    }


    private Node nest(final Node node) {
        LOG.info("Nesting: " + node);
        LOG.indent();
        nesting.push(node);
        return node;
    }

    private void unnest(final Node node) {
        LOG.unindent();
        assert nesting.getFirst() == node : "inconsistent nesting order : " + nesting.getFirst() + " != " + node;
        LOG.info("Unnesting: " + nesting);
        nesting.pop();
    }

    private static void setTerminal(final Node node, final boolean isTerminal) {
        LOG.info("terminal = " + isTerminal + " for " + node);
        node.setIsTerminal(isTerminal);
    }

    private static void setHasGoto(final Node node) { //, final boolean hasGoto) {
        LOG.info("hasGoto = true for " + node);
        node.setHasGoto();
    }

    private static void copyTerminal(final Node node, final Node sourceNode) {
        LOG.info("copy terminal flags " + sourceNode + " -> " + node);
        node.copyTerminalFlags(sourceNode);
    }

    private void addStatement(final Node statement, final boolean storeInLastStatement) {
        LOG.info("add statement = " + statement + " (lastStatement = " + lastStatement + ")");
        statements.add(statement);
        if (storeInLastStatement) {
            lastStatement = statement;
        }
    }

    private void addStatement(final Node statement) {
        addStatement(statement, true);
    }

    /**
     * Determine if Try block is inside target block.
     *
     * @param tryNode Try node to test.
     * @param target  Target block.
     *
     * @return true if try block is inside the target, false otherwise.
     */
    private boolean isNestedTry(final TryNode tryNode, final Block target) {
        for (Block current = getCurrentBlock(); current != target; current = current.getParent()) {
            if (tryNode.getBody() == current) {
                return true;
            }

            for (final Block catchBlock : tryNode.getCatchBlocks()) {
                if (catchBlock == current) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Clones the body of the try finallys up to the target block.
     *
     * @param node       first try node in the chain.
     * @param targetNode target block of the break/continue statement or null for return
     *
     * @return true if terminates.
     */
    private boolean copyFinally(final TryNode node, final Node targetNode) {
        Block target = null;

        if (targetNode instanceof Block) {
            target = (Block)targetNode;
        }

        for (TryNode tryNode = node; tryNode != null; tryNode = tryNode.getNext()) {
            if (target != null && !isNestedTry(tryNode, target)) {
                return false;
            }

            Block finallyBody = tryNode.getFinallyBody();
            if (finallyBody == null) {
                continue;
            }

            finallyBody = (Block)finallyBody.clone();
            final boolean hasTerminalFlags = finallyBody.hasTerminalFlags();

            new ExecuteNode(finallyBody.getSource(), finallyBody.getToken(), finallyBody.getFinish(), finallyBody).accept(this);

            if (hasTerminalFlags) {
                getCurrentBlock().copyTerminalFlags(finallyBody);
                return true;
            }
        }

        return false;
    }

    private Node enterBreakOrContinue(final LabeledNode labeledNode) {
        final TryNode tryNode = labeledNode.getTryChain();
        if (tryNode != null && copyFinally(tryNode, labeledNode.getTargetNode())) {
            return null;
        }
        addStatement(labeledNode);
        return null;
    }


    /**
     * An internal expression has a symbol that is tagged internal. Check if
     * this is such a node
     *
     * @param expression expression to check for internal symbol
     * @return true if internal, false otherwise
     */
    private static boolean isInternalExpression(final Node expression) {
        final Symbol symbol = expression.getSymbol();
        return symbol != null && symbol.isInternal();
    }

    /**
     * Is this an assignment to the special variable that hosts scripting eval
     * results?
     *
     * @param expression expression to check whether it is $evalresult = X
     * @return true if an assignment to eval result, false otherwise
     */
    private boolean isEvalResultAssignment(final Node expression) {
        Node e = expression;
        if (e.tokenType() == TokenType.DISCARD) {
            e = ((UnaryNode)expression).rhs();
        }
        final Node resultNode = getCurrentFunctionNode().getResultNode();
        return e instanceof BinaryNode && ((BinaryNode)e).lhs().equals(resultNode);
    }

    /**
     * Prepare special function nodes.
     * TODO : only create those that are needed.
     * TODO : make sure slot numbering is not hardcoded in {@link CompilerConstants} - now creation order is significant
     */
    private static void initFunctionNode(final FunctionNode functionNode) {
        final Source source = functionNode.getSource();
        final long token    = functionNode.getToken();
        final int  finish   = functionNode.getFinish();

        functionNode.setThisNode(new IdentNode(source, token, finish, THIS.tag()));
        functionNode.setScopeNode(new IdentNode(source, token, finish, SCOPE.tag()));
        functionNode.setResultNode(new IdentNode(source, token, finish, SCRIPT_RETURN.tag()));
        functionNode.setCalleeNode(new IdentNode(source, token, finish, CALLEE.tag()));
        if (functionNode.isVarArg()) {
            functionNode.setVarArgsNode(new IdentNode(source, token, finish, VARARGS.tag()));
            if (functionNode.needsArguments()) {
                functionNode.setArgumentsNode(new IdentNode(source, token, finish, ARGUMENTS.tag()));
            }
        }
    }

}