/*
  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, escope, evaluator, modified;

    Name = 'remove-side-effect-free-expressions';
    escope = require('escope');
    common = require('../common');
    evaluator = require('../evaluator');
    Syntax = common.Syntax;

    function reduce(node, scope, parent, isResultNeeded) {
        var i, iz, expr, result, prev;

        common.assert(node.expressions.length > 1, 'expressions should be more than one');

        result = [];
        for (i = 0, iz = node.expressions.length; i < iz; ++i) {
            prev = expr;
            expr = node.expressions[i];
            if (((i + 1) !== iz) || !isResultNeeded) {
                if (!evaluator.hasSideEffect(expr, scope)) {
                    continue;
                }
            }
            result.push(expr);
        }

        if (!isResultNeeded && result.length === 0) {
            modified = true;
            return expr;
        }

        common.assert(result.length > 0, 'result should be more than zero');

        // not changed
        do {
            if (iz === result.length) {
                return node;
            }

            if (result.length === 1) {
                if (!common.SpecialNode.canExtractSequence(result[0], parent, scope)) {
                    result.unshift(prev);
                    continue;
                }
                modified = true;
                return result[0];
            }
            modified = true;
            node.expressions = result;
            return node;
        } while (true);
    }

    function removeSideEffectFreeExpressions(tree, options) {
        var result, scope, manager, preserveCompletionValue;

        function isResultNeeded(parent, scope) {
            if (parent.type === Syntax.ExpressionStatement && (!preserveCompletionValue || scope.type !== 'global')) {
                return false;
            }
            return true;
        }

        result = options.get('destructive', { pathName: Name }) ? tree : common.deepCopy(tree);
        preserveCompletionValue = options.get('preserveCompletionValue', { pathName: Name });
        modified = false;
        scope = null;
        manager = escope.analyze(result, { directive: true });
        manager.attach();

        result = common.replace(result, {
            enter: function enter(node, parent) {
                var res, unary, trans;

                res = node;
                scope = manager.acquire(node) || scope;
                if (res.type === Syntax.SequenceExpression) {
                    res = reduce(res, scope, parent, isResultNeeded(parent, scope));
                }

                if (res.type === Syntax.SequenceExpression) {
                    common.assert(res.expressions.length > 1, 'sequences\' length should be more than 1');
                    unary = common.Array.last(res.expressions);
                    if (unary.type === Syntax.UnaryExpression && unary.operator === 'void' && !evaluator.hasSideEffect(unary.argument, scope)) {
                        // (x, void sideEffectFree) => (void x)
                        modified = true;
                        res.expressions.pop();
                        trans = common.moveLocation(unary, {
                            type: Syntax.UnaryExpression,
                            operator: 'void',
                            argument: common.Array.last(res.expressions)
                        });
                        if (res.expressions.length === 1) {
                            res = trans;
                        } else {
                            res.expressions[res.expressions.length - 1] = trans;
                        }
                    }
                }

                // Because eval code should return last evaluated value in
                // ExpressionStatement, we should not remove.
                if (!isResultNeeded(res, scope)) {
                    if (!evaluator.hasSideEffect(res.expression, scope)) {
                        modified = true;
                        res = common.moveLocation(res, {
                            type: Syntax.EmptyStatement
                        });
                    }
                }
                return res;
            },
            leave: function leave(node) {
                scope = manager.release(node) || scope;
            }
        });

        manager.detach();

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

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