/*
  Copyright (C) 2012-2013 Yusuke Suzuki <utatane.tea@gmail.com>

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*jslint bitwise:true */
/*global module:true, require:true*/
(function () {
    'use strict';

    var Name,
        Syntax,
        common,
        status,
        modified;

    Name = 'dead-code-elimination';

    common = require('../common');
    Syntax = common.Syntax;

    function JumpTarget(node, status, type) {
        this.node = node;
        this.type = type;
        this.labels = status.labels || [];
        status.labels = null;
    }

    JumpTarget.NAMED_ONLY = 0;  // (00)2
    JumpTarget.ITERATION = 2;   // (10)2
    JumpTarget.SWITCH = 3;      // (11)2

    JumpTarget.prototype.isIteration = function isIteration() {
        return this.type === JumpTarget.ITERATION;
    };

    JumpTarget.prototype.isAnonymous = function isAnonymous() {
        return this.type & 2;
    };

    JumpTarget.prototype.contains = function contains(label) {
        return this.labels.indexOf(label) !== -1;
    };

    function Jumps() {
        this.targets = [];
    }

    Jumps.prototype.lookupContinuableTarget = function lookupContinuableTarget(label) {
        var i, target;
        for (i = this.targets.length - 1; i >= 0; --i) {
            target = this.targets[i];
            if (target.isIteration() && (!label || target.contains(label.name))) {
                return target.node;
            }
        }
        common.unreachable();
    };

    Jumps.prototype.lookupBreakableTarget = function lookupBreakableTarget(label) {
        var i, target;
        for (i = this.targets.length - 1; i >= 0; --i) {
            target = this.targets[i];
            if (label) {
                if (target.contains(label.name)) {
                    return target.node;
                }
            } else {
                if (target.isAnonymous()) {
                    return target.node;
                }
            }
        }
        common.unreachable();
    };

    Jumps.prototype.push = function push(target) {
        this.targets.push(target);
    };

    Jumps.prototype.pop = function pop() {
        this.targets.pop();
    };

    // Status implementation
    //
    // This is based on Constellation/iv lv5 railgun compiler continuation_status.h

    function Status(upper) {
        this.current = [];
        this.upper = upper;
        this.jumps = new Jumps();
        this.labels = null;
        this.next();
    }

    Status.NEXT = {};

    Status.prototype.insert = function insert(stmt) {
        this.current.push(stmt);
    };

    Status.prototype.erase = function erase(stmt) {
        var index = this.current.indexOf(stmt);
        if (index === -1) {
            return false;
        }
        this.current.splice(index, 1);
        return true;
    };

    Status.prototype.kill = function kill() {
        return this.erase(Status.NEXT);
    };

    Status.prototype.has = function has(stmt) {
        return this.current.indexOf(stmt) !== -1;
    };

    Status.prototype.jumpTo = function jumpTo(stmt) {
        this.kill();
        this.insert(stmt);
    };

    Status.prototype.resolveJump = function resolveJump(stmt) {
        var index = this.current.indexOf(stmt);
        if (index !== -1) {
            this.current.splice(index, 1);
            this.insert(Status.NEXT);
        }
    };

    Status.prototype.clear = function clear() {
        this.current.length = 0;
    };

    Status.prototype.next = function next() {
        this.insert(Status.NEXT);
    };

    Status.prototype.isDead = function isDead() {
        return !this.has(Status.NEXT);
    };

    Status.prototype.revive = function revive() {
        if (this.isDead()) {
            this.next();
            return true;
        }
        return false;
    };

    Status.prototype.register = function register(node) {
        if (!this.labels) {
            this.labels = [];
        }
        this.labels.push(node.label.name);
    };

    Status.prototype.unregister = function unregister() {
        this.labels = null;
    };

    Status.isRequired = function isRequired(node) {
        var type = node.type;
        common.assert(node, 'should be node');
        return type === Syntax.Program || type === Syntax.FunctionExpression || type === Syntax.FunctionDeclaration;
    };

    function Context(node) {
        node.__$context = this;
        this.node = node;
    }

    Context.prototype.detach = function detach() {
        delete this.node.__$context;
    };

    Context.lookup = function lookup(node) {
        return node.__$context;
    };

    function getForwardLastNode(node) {
        while (true) {
            switch (node.type) {
            case Syntax.IfStatement:
                if (node.alternate) {
                    return null;
                }
                node = node.consequent;
                continue;

            case Syntax.WithStatement:
            case Syntax.LabeledStatement:
                node = node.body;
                continue;

            case Syntax.BlockStatement:
                if (node.body.length) {
                    node = common.Array.last(node.body);
                    continue;
                }
                break;
            }
            return node;
        }
    }

    function visitLoopBody(loop, body) {
        var jump, last;
        last = getForwardLastNode(body);
        if (last) {
            if (last.type === Syntax.ContinueStatement) {
                jump = status.jumps.lookupContinuableTarget(last.label);
                if (jump === loop) {
                    // this continue is dead code
                    modified = true;
                    common.convertToEmptyStatement(last);
                }
            }
        }
        return visit(body);
    }

    function visit(target) {
        var live = false;

        if (!target) {
            return !status.isDead();
        }

        function eliminate(node, array) {
            var i, iz, stmt, ret, info, result;
            result = [];
            for (i = 0, iz = array.length; i < iz; ++i) {
                stmt = array[i];
                if (stmt.type === Syntax.IfStatement) {
                    info = new Context(stmt);
                    ret = visit(stmt);
                    info.detach();
                } else {
                    ret = visit(stmt);
                }
                if (ret) {
                    live |= 1;
                    result.push(stmt);

                    // we transform
                    //     if (cond) {
                    //         #1
                    //         return;
                    //     } else
                    //         #2;
                    //     #3
                    //  to
                    //     if (cond) {
                    //         #1
                    //         return;
                    //     }
                    //     #2
                    //     #3
                    //
                    // and
                    //
                    //     if (cond)
                    //         #1;
                    //     else {
                    //         #2
                    //         return;
                    //     }
                    //     #3
                    //  to
                    //     if (!cond) {
                    //         #2
                    //         return;
                    //     }
                    //     #1
                    //     #3
                    if (stmt.type === Syntax.IfStatement && stmt.alternate) {
                        if ((!info.consequent || !info.alternate) && info.consequent !== info.alternate) {
                            modified = true;
                            if (info.consequent) {
                                stmt.test = common.moveLocation(stmt.test, {
                                    type: Syntax.UnaryExpression,
                                    operator: '!',
                                    argument: stmt.test
                                });
                                result.push(stmt.consequent);
                                stmt.consequent = stmt.alternate;
                                stmt.alternate = null;
                            } else {  // info.alternate
                                result.push(stmt.alternate);
                                stmt.alternate = null;
                            }
                        }
                    }
                } else {
                    // deleted
                    modified = true;
                }
            }
            return result;
        }

        common.traverse(target, {
            enter: function enter(node) {
                var i, iz, stmt, consequent, alternate, ctx, hasDefaultClause;
                if (Status.isRequired(node)) {
                    status = new Status(status);
                }

                live |= !status.isDead();

                switch (node.type) {
                case Syntax.Program:
                    node.body = eliminate(node, node.body);
                    return common.VisitorOption.Skip;

                case Syntax.BlockStatement:
                    status.jumps.push(new JumpTarget(node, status, JumpTarget.NAMED_ONLY));
                    node.body = eliminate(node, node.body);
                    status.jumps.pop();

                    status.resolveJump(node);
                    return common.VisitorOption.Skip;

                case Syntax.BreakStatement:
                    // like
                    //   label: break label;
                    // we treat as like empty statement
                    if (node.label && status.labels && status.labels.indexOf(node.label)) {
                        // change this statement to empty statement
                        modified = true;
                        common.convertToEmptyStatement(node);
                    } else {
                        status.jumpTo(status.jumps.lookupBreakableTarget(node.label));
                    }
                    return common.VisitorOption.Skip;

                case Syntax.CatchClause:
                    live |= visit(node.body);
                    return common.VisitorOption.Skip;

                case Syntax.ContinueStatement:
                    status.jumpTo(status.jumps.lookupContinuableTarget(node.label));
                    return common.VisitorOption.Skip;

                case Syntax.DoWhileStatement:
                    status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
                    live |= visitLoopBody(node, node.body);
                    status.jumps.pop();

                    live |= visit(node.test);
                    status.resolveJump(node);
                    status.revive();
                    return common.VisitorOption.Skip;

                case Syntax.DebuggerStatement:
                    return common.VisitorOption.Skip;

                case Syntax.EmptyStatement:
                    return common.VisitorOption.Skip;

                case Syntax.ExpressionStatement:
                    break;

                case Syntax.ForStatement:
                    live |= visit(node.init);
                    live |= visit(node.test);

                    status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
                    live |= visitLoopBody(node, node.body);
                    status.jumps.pop();

                    live |= visit(node.update);
                    status.resolveJump(node);
                    status.revive();
                    return common.VisitorOption.Skip;

                case Syntax.ForInStatement:
                    live |= visit(node.left);
                    live |= visit(node.right);

                    status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
                    live |= visitLoopBody(node, node.body);
                    status.jumps.pop();

                    status.resolveJump(node);
                    status.revive();
                    return common.VisitorOption.Skip;

                case Syntax.IfStatement:
                    live |= visit(node.test);
                    live |= visit(node.consequent);
                    if (!node.alternate) {
                        status.revive();
                        return common.VisitorOption.Skip;
                    }

                    consequent = !status.isDead();
                    if (!status.revive()) {
                        status.insert(node);
                    }

                    live |= visit(node.alternate);
                    alternate = !status.isDead();
                    if (status.erase(node)) {
                        status.revive();
                    }
                    if ((ctx = Context.lookup(node))) {
                        ctx.consequent = consequent;
                        ctx.alternate = alternate;
                    }
                    return common.VisitorOption.Skip;

                case Syntax.LabeledStatement:
                    status.register(node);
                    break;

                case Syntax.ReturnStatement:
                    live |= visit(node.argument);
                    status.kill();
                    return common.VisitorOption.Skip;

                case Syntax.SwitchStatement:
                    visit(node.discriminant);

                    status.jumps.push(new JumpTarget(node, status, JumpTarget.SWITCH));
                    for (i = 0, iz = node.cases.length; i < iz; ++i) {
                        stmt = node.cases[i];
                        live |= visit(stmt);
                        if (!stmt.test) {
                            hasDefaultClause = true;
                        }
                        if (status.isDead() && (i + 1) < iz) {
                            status.next();
                        }
                    }
                    status.jumps.pop();

                    status.resolveJump(node);
                    if (status.isDead() && !hasDefaultClause) {
                        status.next();
                    }
                    return common.VisitorOption.Skip;

                case Syntax.SwitchCase:
                    if (node.test) {
                        live |= visit(node.test);
                    }
                    node.consequent = eliminate(node, node.consequent);
                    return common.VisitorOption.Skip;

                case Syntax.ThrowStatement:
                    live |= visit(node.argument);
                    status.kill();
                    return common.VisitorOption.Skip;

                case Syntax.TryStatement:
                    live |= visit(node.block);

                    if (node.handlers && node.handlers.length) {
                        if (!status.revive()) {
                            status.insert(node);
                        }
                        node.handlers = eliminate(node, node.handlers);
                        if (status.erase(node)) {
                            status.revive();
                        }
                    }

                    if (node.finalizer) {
                        if (!status.revive()) {
                            status.insert(node);
                        }
                        live |= visit(node.finalizer);
                        if (!status.erase(node)) {
                            status.kill();
                        }
                    }
                    return common.VisitorOption.Skip;

                case Syntax.WhileStatement:
                    live |= visit(node.test);

                    status.jumps.push(new JumpTarget(node, status, JumpTarget.ITERATION));
                    live |= visitLoopBody(node, node.body);
                    status.jumps.pop();

                    status.resolveJump(node);
                    status.revive();
                    return common.VisitorOption.Skip;

                case Syntax.WithStatement:
                    break;

                case Syntax.VariableDeclaration:
                case Syntax.FunctionDeclaration:
                    live = true;
                    break;
                }
            },

            leave: function leave(node) {
                if (Status.isRequired(node)) {
                    status = status.upper;
                    return;
                }

                if (node.type === Syntax.LabeledStatement) {
                    status.unregister();
                }
            }
        });

        return live;
    }

    // This is iv / lv5 / railgun bytecode compiler dead code elimination algorithm
    function deadCodeElimination(tree, options) {
        var result;

        result = (options.get('destructive', { pathName: Name })) ? tree : common.deepCopy(tree);

        status = null;
        modified = false;

        visit(result);

        common.assert(status === null, 'status should be null');

        return {
            result: result,
            modified: modified
        };
    }

    deadCodeElimination.passName = Name;
    module.exports = deadCodeElimination;
}());
/* vim: set sw=4 ts=4 et tw=80 : */
