"use strict";

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };

var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };

Object.defineProperty(exports, "__esModule", {
    value: true
});
/*
  Copyright (C) 2015 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.
*/

var Syntax = require("estraverse").Syntax;

var Map = _interopRequire(require("es6-map"));

var Reference = _interopRequire(require("./reference"));

var Variable = _interopRequire(require("./variable"));

var Definition = _interopRequire(require("./definition"));

var assert = _interopRequire(require("assert"));

function isStrictScope(scope, block, isMethodDefinition, useDirective) {
    var body, i, iz, stmt, expr;

    // When upper scope is exists and strict, inner scope is also strict.
    if (scope.upper && scope.upper.isStrict) {
        return true;
    }

    // ArrowFunctionExpression's scope is always strict scope.
    if (block.type === Syntax.ArrowFunctionExpression) {
        return true;
    }

    if (isMethodDefinition) {
        return true;
    }

    if (scope.type === "class" || scope.type === "module") {
        return true;
    }

    if (scope.type === "block" || scope.type === "switch") {
        return false;
    }

    if (scope.type === "function") {
        if (block.type === "Program") {
            body = block;
        } else {
            body = block.body;
        }
    } else if (scope.type === "global") {
        body = block;
    } else {
        return false;
    }

    // Search 'use strict' directive.
    if (useDirective) {
        for (i = 0, iz = body.body.length; i < iz; ++i) {
            stmt = body.body[i];
            if (stmt.type !== "DirectiveStatement") {
                break;
            }
            if (stmt.raw === "\"use strict\"" || stmt.raw === "'use strict'") {
                return true;
            }
        }
    } else {
        for (i = 0, iz = body.body.length; i < iz; ++i) {
            stmt = body.body[i];
            if (stmt.type !== Syntax.ExpressionStatement) {
                break;
            }
            expr = stmt.expression;
            if (expr.type !== Syntax.Literal || typeof expr.value !== "string") {
                break;
            }
            if (expr.raw != null) {
                if (expr.raw === "\"use strict\"" || expr.raw === "'use strict'") {
                    return true;
                }
            } else {
                if (expr.value === "use strict") {
                    return true;
                }
            }
        }
    }
    return false;
}

function registerScope(scopeManager, scope) {
    var scopes;

    scopeManager.scopes.push(scope);

    scopes = scopeManager.__nodeToScope.get(scope.block);
    if (scopes) {
        scopes.push(scope);
    } else {
        scopeManager.__nodeToScope.set(scope.block, [scope]);
    }
}

function shouldBeStatically(def) {
    return def.type === Variable.ClassName || def.type === Variable.Variable && def.parent.kind !== "var";
}

/**
 * @class Scope
 */

var Scope = (function () {
    function Scope(scopeManager, type, upperScope, block, isMethodDefinition) {
        _classCallCheck(this, Scope);

        /**
         * One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
         * @member {String} Scope#type
         */
        this.type = type;
        /**
        * The scoped {@link Variable}s of this scope, as <code>{ Variable.name
        * : Variable }</code>.
        * @member {Map} Scope#set
        */
        this.set = new Map();
        /**
         * The tainted variables of this scope, as <code>{ Variable.name :
         * boolean }</code>.
         * @member {Map} Scope#taints */
        this.taints = new Map();
        /**
         * Generally, through the lexical scoping of JS you can always know
         * which variable an identifier in the source code refers to. There are
         * a few exceptions to this rule. With 'global' and 'with' scopes you
         * can only decide at runtime which variable a reference refers to.
         * Moreover, if 'eval()' is used in a scope, it might introduce new
         * bindings in this or its prarent scopes.
         * All those scopes are considered 'dynamic'.
         * @member {boolean} Scope#dynamic
         */
        this.dynamic = this.type === "global" || this.type === "with";
        /**
         * A reference to the scope-defining syntax node.
         * @member {esprima.Node} Scope#block
         */
        this.block = block;
        /**
        * The {@link Reference|references} that are not resolved with this scope.
        * @member {Reference[]} Scope#through
        */
        this.through = [];
        /**
        * The scoped {@link Variable}s of this scope. In the case of a
        * 'function' scope this includes the automatic argument <em>arguments</em> as
        * its first element, as well as all further formal arguments.
        * @member {Variable[]} Scope#variables
        */
        this.variables = [];
        /**
        * Any variable {@link Reference|reference} found in this scope. This
        * includes occurrences of local variables as well as variables from
        * parent scopes (including the global scope). For local variables
        * this also includes defining occurrences (like in a 'var' statement).
        * In a 'function' scope this does not include the occurrences of the
        * formal parameter in the parameter list.
        * @member {Reference[]} Scope#references
        */
        this.references = [];

        /**
        * For 'global' and 'function' scopes, this is a self-reference. For
        * other scope types this is the <em>variableScope</em> value of the
        * parent scope.
        * @member {Scope} Scope#variableScope
        */
        this.variableScope = this.type === "global" || this.type === "function" || this.type === "module" ? this : upperScope.variableScope;
        /**
        * Whether this scope is created by a FunctionExpression.
        * @member {boolean} Scope#functionExpressionScope
        */
        this.functionExpressionScope = false;
        /**
        * Whether this is a scope that contains an 'eval()' invocation.
        * @member {boolean} Scope#directCallToEvalScope
        */
        this.directCallToEvalScope = false;
        /**
        * @member {boolean} Scope#thisFound
        */
        this.thisFound = false;

        this.__left = [];

        /**
        * Reference to the parent {@link Scope|scope}.
        * @member {Scope} Scope#upper
        */
        this.upper = upperScope;
        /**
        * Whether 'use strict' is in effect in this scope.
        * @member {boolean} Scope#isStrict
        */
        this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());

        /**
        * List of nested {@link Scope}s.
        * @member {Scope[]} Scope#childScopes
        */
        this.childScopes = [];
        if (this.upper) {
            this.upper.childScopes.push(this);
        }

        registerScope(scopeManager, this);
    }

    _createClass(Scope, {
        __shouldStaticallyClose: {
            value: function __shouldStaticallyClose(scopeManager) {
                return !this.dynamic || scopeManager.__isOptimistic();
            }
        },
        __shouldStaticallyCloseForGlobal: {
            value: function __shouldStaticallyCloseForGlobal(ref) {
                // On global scope, let/const/class declarations should be resolved statically.
                var name = ref.identifier.name;
                if (!this.set.has(name)) {
                    return false;
                }

                var variable = this.set.get(name);
                var defs = variable.defs;
                return defs.length > 0 && defs.every(shouldBeStatically);
            }
        },
        __staticCloseRef: {
            value: function __staticCloseRef(ref) {
                if (!this.__resolve(ref)) {
                    this.__delegateToUpperScope(ref);
                }
            }
        },
        __dynamicCloseRef: {
            value: function __dynamicCloseRef(ref) {
                // notify all names are through to global
                var current = this;
                do {
                    current.through.push(ref);
                    current = current.upper;
                } while (current);
            }
        },
        __globalCloseRef: {
            value: function __globalCloseRef(ref) {
                // let/const/class declarations should be resolved statically.
                // others should be resolved dynamically.
                if (this.__shouldStaticallyCloseForGlobal(ref)) {
                    this.__staticCloseRef(ref);
                } else {
                    this.__dynamicCloseRef(ref);
                }
            }
        },
        __close: {
            value: function __close(scopeManager) {
                var closeRef;
                if (this.__shouldStaticallyClose(scopeManager)) {
                    closeRef = this.__staticCloseRef;
                } else if (this.type !== "global") {
                    closeRef = this.__dynamicCloseRef;
                } else {
                    closeRef = this.__globalCloseRef;
                }

                // Try Resolving all references in this scope.
                for (var i = 0, iz = this.__left.length; i < iz; ++i) {
                    var ref = this.__left[i];
                    closeRef.call(this, ref);
                }
                this.__left = null;

                return this.upper;
            }
        },
        __resolve: {
            value: function __resolve(ref) {
                var variable, name;
                name = ref.identifier.name;
                if (this.set.has(name)) {
                    variable = this.set.get(name);
                    variable.references.push(ref);
                    variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
                    if (ref.tainted) {
                        variable.tainted = true;
                        this.taints.set(variable.name, true);
                    }
                    ref.resolved = variable;
                    return true;
                }
                return false;
            }
        },
        __delegateToUpperScope: {
            value: function __delegateToUpperScope(ref) {
                if (this.upper) {
                    this.upper.__left.push(ref);
                }
                this.through.push(ref);
            }
        },
        __defineGeneric: {
            value: function __defineGeneric(name, set, variables, node, def) {
                var variable;

                variable = set.get(name);
                if (!variable) {
                    variable = new Variable(name, this);
                    set.set(name, variable);
                    variables.push(variable);
                }

                if (def) {
                    variable.defs.push(def);
                }
                if (node) {
                    variable.identifiers.push(node);
                }
            }
        },
        __define: {
            value: function __define(node, def) {
                if (node && node.type === Syntax.Identifier) {
                    this.__defineGeneric(node.name, this.set, this.variables, node, def);
                }
            }
        },
        __referencing: {
            value: function __referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
                // because Array element may be null
                if (!node || node.type !== Syntax.Identifier) {
                    return;
                }

                // Specially handle like `this`.
                if (node.name === "super") {
                    return;
                }

                var ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
                this.references.push(ref);
                this.__left.push(ref);
            }
        },
        __detectEval: {
            value: function __detectEval() {
                var current;
                current = this;
                this.directCallToEvalScope = true;
                do {
                    current.dynamic = true;
                    current = current.upper;
                } while (current);
            }
        },
        __detectThis: {
            value: function __detectThis() {
                this.thisFound = true;
            }
        },
        __isClosed: {
            value: function __isClosed() {
                return this.__left === null;
            }
        },
        resolve: {

            /**
             * returns resolved {Reference}
             * @method Scope#resolve
             * @param {Esprima.Identifier} ident - identifier to be resolved.
             * @return {Reference}
             */

            value: function resolve(ident) {
                var ref, i, iz;
                assert(this.__isClosed(), "Scope should be closed.");
                assert(ident.type === Syntax.Identifier, "Target should be identifier.");
                for (i = 0, iz = this.references.length; i < iz; ++i) {
                    ref = this.references[i];
                    if (ref.identifier === ident) {
                        return ref;
                    }
                }
                return null;
            }
        },
        isStatic: {

            /**
             * returns this scope is static
             * @method Scope#isStatic
             * @return {boolean}
             */

            value: function isStatic() {
                return !this.dynamic;
            }
        },
        isArgumentsMaterialized: {

            /**
             * returns this scope has materialized arguments
             * @method Scope#isArgumentsMaterialized
             * @return {boolean}
             */

            value: function isArgumentsMaterialized() {
                return true;
            }
        },
        isThisMaterialized: {

            /**
             * returns this scope has materialized `this` reference
             * @method Scope#isThisMaterialized
             * @return {boolean}
             */

            value: function isThisMaterialized() {
                return true;
            }
        },
        isUsedName: {
            value: function isUsedName(name) {
                if (this.set.has(name)) {
                    return true;
                }
                for (var i = 0, iz = this.through.length; i < iz; ++i) {
                    if (this.through[i].identifier.name === name) {
                        return true;
                    }
                }
                return false;
            }
        }
    });

    return Scope;
})();

exports["default"] = Scope;

var GlobalScope = exports.GlobalScope = (function (_Scope) {
    function GlobalScope(scopeManager, block) {
        _classCallCheck(this, GlobalScope);

        _get(Object.getPrototypeOf(GlobalScope.prototype), "constructor", this).call(this, scopeManager, "global", null, block, false);
        this.implicit = {
            set: new Map(),
            variables: [],
            /**
            * List of {@link Reference}s that are left to be resolved (i.e. which
            * need to be linked to the variable they refer to).
            * @member {Reference[]} Scope#implicit#left
            */
            left: []
        };
    }

    _inherits(GlobalScope, _Scope);

    _createClass(GlobalScope, {
        __close: {
            value: function __close(scopeManager) {
                var implicit = [];
                for (var i = 0, iz = this.__left.length; i < iz; ++i) {
                    var ref = this.__left[i];
                    if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
                        implicit.push(ref.__maybeImplicitGlobal);
                    }
                }

                // create an implicit global variable from assignment expression
                for (var i = 0, iz = implicit.length; i < iz; ++i) {
                    var info = implicit[i];
                    this.__defineImplicit(info.pattern, new Definition(Variable.ImplicitGlobalVariable, info.pattern, info.node, null, null, null));
                }

                this.implicit.left = this.__left;

                return _get(Object.getPrototypeOf(GlobalScope.prototype), "__close", this).call(this, scopeManager);
            }
        },
        __defineImplicit: {
            value: function __defineImplicit(node, def) {
                if (node && node.type === Syntax.Identifier) {
                    this.__defineGeneric(node.name, this.implicit.set, this.implicit.variables, node, def);
                }
            }
        }
    });

    return GlobalScope;
})(Scope);

var ModuleScope = exports.ModuleScope = (function (_Scope2) {
    function ModuleScope(scopeManager, upperScope, block) {
        _classCallCheck(this, ModuleScope);

        _get(Object.getPrototypeOf(ModuleScope.prototype), "constructor", this).call(this, scopeManager, "module", upperScope, block, false);
    }

    _inherits(ModuleScope, _Scope2);

    return ModuleScope;
})(Scope);

var FunctionExpressionNameScope = exports.FunctionExpressionNameScope = (function (_Scope3) {
    function FunctionExpressionNameScope(scopeManager, upperScope, block) {
        _classCallCheck(this, FunctionExpressionNameScope);

        _get(Object.getPrototypeOf(FunctionExpressionNameScope.prototype), "constructor", this).call(this, scopeManager, "function-expression-name", upperScope, block, false);
        this.__define(block.id, new Definition(Variable.FunctionName, block.id, block, null, null, null));
        this.functionExpressionScope = true;
    }

    _inherits(FunctionExpressionNameScope, _Scope3);

    return FunctionExpressionNameScope;
})(Scope);

var CatchScope = exports.CatchScope = (function (_Scope4) {
    function CatchScope(scopeManager, upperScope, block) {
        _classCallCheck(this, CatchScope);

        _get(Object.getPrototypeOf(CatchScope.prototype), "constructor", this).call(this, scopeManager, "catch", upperScope, block, false);
    }

    _inherits(CatchScope, _Scope4);

    return CatchScope;
})(Scope);

var WithScope = exports.WithScope = (function (_Scope5) {
    function WithScope(scopeManager, upperScope, block) {
        _classCallCheck(this, WithScope);

        _get(Object.getPrototypeOf(WithScope.prototype), "constructor", this).call(this, scopeManager, "with", upperScope, block, false);
    }

    _inherits(WithScope, _Scope5);

    _createClass(WithScope, {
        __close: {
            value: function __close(scopeManager) {
                if (this.__shouldStaticallyClose(scopeManager)) {
                    return _get(Object.getPrototypeOf(WithScope.prototype), "__close", this).call(this, scopeManager);
                }

                for (var i = 0, iz = this.__left.length; i < iz; ++i) {
                    var ref = this.__left[i];
                    ref.tainted = true;
                    this.__delegateToUpperScope(ref);
                }
                this.__left = null;

                return this.upper;
            }
        }
    });

    return WithScope;
})(Scope);

var TDZScope = exports.TDZScope = (function (_Scope6) {
    function TDZScope(scopeManager, upperScope, block) {
        _classCallCheck(this, TDZScope);

        _get(Object.getPrototypeOf(TDZScope.prototype), "constructor", this).call(this, scopeManager, "TDZ", upperScope, block, false);
    }

    _inherits(TDZScope, _Scope6);

    return TDZScope;
})(Scope);

var BlockScope = exports.BlockScope = (function (_Scope7) {
    function BlockScope(scopeManager, upperScope, block) {
        _classCallCheck(this, BlockScope);

        _get(Object.getPrototypeOf(BlockScope.prototype), "constructor", this).call(this, scopeManager, "block", upperScope, block, false);
    }

    _inherits(BlockScope, _Scope7);

    return BlockScope;
})(Scope);

var SwitchScope = exports.SwitchScope = (function (_Scope8) {
    function SwitchScope(scopeManager, upperScope, block) {
        _classCallCheck(this, SwitchScope);

        _get(Object.getPrototypeOf(SwitchScope.prototype), "constructor", this).call(this, scopeManager, "switch", upperScope, block, false);
    }

    _inherits(SwitchScope, _Scope8);

    return SwitchScope;
})(Scope);

var FunctionScope = exports.FunctionScope = (function (_Scope9) {
    function FunctionScope(scopeManager, upperScope, block, isMethodDefinition) {
        _classCallCheck(this, FunctionScope);

        _get(Object.getPrototypeOf(FunctionScope.prototype), "constructor", this).call(this, scopeManager, "function", upperScope, block, isMethodDefinition);

        // section 9.2.13, FunctionDeclarationInstantiation.
        // NOTE Arrow functions never have an arguments objects.
        if (this.block.type !== Syntax.ArrowFunctionExpression) {
            this.__defineArguments();
        }
    }

    _inherits(FunctionScope, _Scope9);

    _createClass(FunctionScope, {
        isArgumentsMaterialized: {
            value: function isArgumentsMaterialized() {
                // TODO(Constellation)
                // We can more aggressive on this condition like this.
                //
                // function t() {
                //     // arguments of t is always hidden.
                //     function arguments() {
                //     }
                // }
                if (this.block.type === Syntax.ArrowFunctionExpression) {
                    return false;
                }

                if (!this.isStatic()) {
                    return true;
                }

                var variable = this.set.get("arguments");
                assert(variable, "Always have arguments variable.");
                return variable.tainted || variable.references.length !== 0;
            }
        },
        isThisMaterialized: {
            value: function isThisMaterialized() {
                if (!this.isStatic()) {
                    return true;
                }
                return this.thisFound;
            }
        },
        __defineArguments: {
            value: function __defineArguments() {
                this.__defineGeneric("arguments", this.set, this.variables, null, null);
                this.taints.set("arguments", true);
            }
        }
    });

    return FunctionScope;
})(Scope);

var ForScope = exports.ForScope = (function (_Scope10) {
    function ForScope(scopeManager, upperScope, block) {
        _classCallCheck(this, ForScope);

        _get(Object.getPrototypeOf(ForScope.prototype), "constructor", this).call(this, scopeManager, "for", upperScope, block, false);
    }

    _inherits(ForScope, _Scope10);

    return ForScope;
})(Scope);

var ClassScope = exports.ClassScope = (function (_Scope11) {
    function ClassScope(scopeManager, upperScope, block) {
        _classCallCheck(this, ClassScope);

        _get(Object.getPrototypeOf(ClassScope.prototype), "constructor", this).call(this, scopeManager, "class", upperScope, block, false);
    }

    _inherits(ClassScope, _Scope11);

    return ClassScope;
})(Scope);

/* vim: set sw=4 ts=4 et tw=80 : */
//# sourceMappingURL=data:application/json;base64,[encoded data, 44584 characters]