/**
 * @author Toru Nagashima <https://github.com/mysticatea>
 * See LICENSE file in root directory for full license.
 */
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var path = require('path');
var Evk = require('eslint-visitor-keys');
var sortedLastIndex = require('lodash/sortedLastIndex');
var assert = require('assert');
var last = require('lodash/last');
var findLastIndex = require('lodash/findLastIndex');
var debugFactory = require('debug');
var first = require('lodash/first');
var sortedIndexBy = require('lodash/sortedIndexBy');
var escope = require('eslint-scope');
var Module = require('module');
var semver = require('semver');
var dependencyEspree = require('espree');
var sortedLastIndexBy = require('lodash/sortedLastIndexBy');
var EventEmitter = require('events');
var esquery = require('esquery');
var union = require('lodash/union');
var intersection = require('lodash/intersection');
var memoize = require('lodash/memoize');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var path__namespace = /*#__PURE__*/_interopNamespace(path);
var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
var Evk__namespace = /*#__PURE__*/_interopNamespace(Evk);
var sortedLastIndex__default = /*#__PURE__*/_interopDefaultLegacy(sortedLastIndex);
var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
var last__default = /*#__PURE__*/_interopDefaultLegacy(last);
var findLastIndex__default = /*#__PURE__*/_interopDefaultLegacy(findLastIndex);
var debugFactory__default = /*#__PURE__*/_interopDefaultLegacy(debugFactory);
var first__default = /*#__PURE__*/_interopDefaultLegacy(first);
var sortedIndexBy__default = /*#__PURE__*/_interopDefaultLegacy(sortedIndexBy);
var escope__namespace = /*#__PURE__*/_interopNamespace(escope);
var Module__default = /*#__PURE__*/_interopDefaultLegacy(Module);
var dependencyEspree__namespace = /*#__PURE__*/_interopNamespace(dependencyEspree);
var sortedLastIndexBy__default = /*#__PURE__*/_interopDefaultLegacy(sortedLastIndexBy);
var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
var esquery__default = /*#__PURE__*/_interopDefaultLegacy(esquery);
var union__default = /*#__PURE__*/_interopDefaultLegacy(union);
var intersection__default = /*#__PURE__*/_interopDefaultLegacy(intersection);
var memoize__default = /*#__PURE__*/_interopDefaultLegacy(memoize);

function isAcornStyleParseError(x) {
    return (typeof x.message === "string" &&
        typeof x.pos === "number" &&
        typeof x.loc === "object" &&
        x.loc !== null &&
        typeof x.loc.line === "number" &&
        typeof x.loc.column === "number");
}
function isTSError(x) {
    return (!(x instanceof ParseError) &&
        typeof x.message === "string" &&
        typeof x.index === "number" &&
        typeof x.lineNumber === "number" &&
        typeof x.column === "number" &&
        x.name === "TSError");
}
class ParseError extends SyntaxError {
    constructor(message, code, offset, line, column) {
        super(message);
        this.code = code;
        this.index = offset;
        this.lineNumber = line;
        this.column = column;
    }
    static fromCode(code, offset, line, column) {
        return new ParseError(code, code, offset, line, column);
    }
    static normalize(x) {
        if (isTSError(x)) {
            return new ParseError(x.message, undefined, x.index, x.lineNumber, x.column);
        }
        if (ParseError.isParseError(x)) {
            return x;
        }
        if (isAcornStyleParseError(x)) {
            return new ParseError(x.message, undefined, x.pos, x.loc.line, x.loc.column);
        }
        return null;
    }
    static isParseError(x) {
        return (x instanceof ParseError ||
            (typeof x.message === "string" &&
                typeof x.index === "number" &&
                typeof x.lineNumber === "number" &&
                typeof x.column === "number"));
    }
}

const NS = Object.freeze({
    HTML: "http://www.w3.org/1999/xhtml",
    MathML: "http://www.w3.org/1998/Math/MathML",
    SVG: "http://www.w3.org/2000/svg",
    XLink: "http://www.w3.org/1999/xlink",
    XML: "http://www.w3.org/XML/1998/namespace",
    XMLNS: "http://www.w3.org/2000/xmlns/",
});

const KEYS = Evk__namespace.unionWith({
    VAttribute: ["key", "value"],
    VDirectiveKey: ["name", "argument", "modifiers"],
    VDocumentFragment: ["children"],
    VElement: ["startTag", "children", "endTag"],
    VEndTag: [],
    VExpressionContainer: ["expression"],
    VFilter: ["callee", "arguments"],
    VFilterSequenceExpression: ["expression", "filters"],
    VForExpression: ["left", "right"],
    VIdentifier: [],
    VLiteral: [],
    VOnExpression: ["body"],
    VSlotScopeExpression: ["params"],
    VStartTag: ["attributes"],
    VText: [],
});
function fallbackKeysFilter(key) {
    let value = null;
    return (key !== "comments" &&
        key !== "leadingComments" &&
        key !== "loc" &&
        key !== "parent" &&
        key !== "range" &&
        key !== "tokens" &&
        key !== "trailingComments" &&
        (value = this[key]) !== null &&
        typeof value === "object" &&
        (typeof value.type === "string" || Array.isArray(value)));
}
function getFallbackKeys(node) {
    return Object.keys(node).filter(fallbackKeysFilter, node);
}
function isNode(x) {
    return x !== null && typeof x === "object" && typeof x.type === "string";
}
function traverse(node, parent, visitor) {
    let i = 0;
    let j = 0;
    visitor.enterNode(node, parent);
    const keys = (visitor.visitorKeys || KEYS)[node.type] || getFallbackKeys(node);
    for (i = 0; i < keys.length; ++i) {
        const child = node[keys[i]];
        if (Array.isArray(child)) {
            for (j = 0; j < child.length; ++j) {
                if (isNode(child[j])) {
                    traverse(child[j], node, visitor);
                }
            }
        }
        else if (isNode(child)) {
            traverse(child, node, visitor);
        }
    }
    visitor.leaveNode(node, parent);
}
function traverseNodes(node, visitor) {
    traverse(node, null, visitor);
}

var index = /*#__PURE__*/Object.freeze({
    __proto__: null,
    ParseError: ParseError,
    NS: NS,
    KEYS: KEYS,
    traverseNodes: traverseNodes,
    getFallbackKeys: getFallbackKeys
});

class LinesAndColumns {
    constructor(ltOffsets) {
        this.ltOffsets = ltOffsets;
    }
    getLocFromIndex(index) {
        const line = sortedLastIndex__default["default"](this.ltOffsets, index) + 1;
        const column = index - (line === 1 ? 0 : this.ltOffsets[line - 2]);
        return { line, column };
    }
    createOffsetLocationCalculator(offset) {
        return {
            getFixOffset() {
                return offset;
            },
            getLocFromIndex: this.getLocFromIndex.bind(this),
        };
    }
}

class LocationCalculatorForHtml extends LinesAndColumns {
    constructor(gapOffsets, ltOffsets, baseOffset, shiftOffset = 0) {
        super(ltOffsets);
        this.gapOffsets = gapOffsets;
        this.ltOffsets = ltOffsets;
        this.baseOffset = baseOffset || 0;
        this.baseIndexOfGap =
            this.baseOffset === 0
                ? 0
                : sortedLastIndex__default["default"](gapOffsets, this.baseOffset);
        this.shiftOffset = shiftOffset;
    }
    getSubCalculatorAfter(offset) {
        return new LocationCalculatorForHtml(this.gapOffsets, this.ltOffsets, this.baseOffset + offset, this.shiftOffset);
    }
    getSubCalculatorShift(offset) {
        return new LocationCalculatorForHtml(this.gapOffsets, this.ltOffsets, this.baseOffset, this.shiftOffset + offset);
    }
    _getGap(index) {
        const offsets = this.gapOffsets;
        let g0 = sortedLastIndex__default["default"](offsets, index + this.baseOffset);
        let pos = index + this.baseOffset + g0 - this.baseIndexOfGap;
        while (g0 < offsets.length && offsets[g0] <= pos) {
            g0 += 1;
            pos += 1;
        }
        return g0 - this.baseIndexOfGap;
    }
    getLocation(index) {
        return this.getLocFromIndex(this.getOffsetWithGap(index));
    }
    getOffsetWithGap(index) {
        return index + this.getFixOffset(index);
    }
    getFixOffset(offset) {
        const shiftOffset = this.shiftOffset;
        const gap = this._getGap(offset + shiftOffset);
        return this.baseOffset + gap + shiftOffset;
    }
}

const debug = debugFactory__default["default"]("vue-eslint-parser");

function isScriptElement(node) {
    return node.type === "VElement" && node.name === "script";
}
function isScriptSetupElement(script) {
    return (isScriptElement(script) &&
        script.startTag.attributes.some((attr) => !attr.directive && attr.key.name === "setup"));
}
function isTemplateElement(node) {
    return node.type === "VElement" && node.name === "template";
}
function isStyleElement(node) {
    return node.type === "VElement" && node.name === "style";
}
function getOwnerDocument(leafNode) {
    let node = leafNode;
    while (node != null && node.type !== "VDocumentFragment") {
        node = node.parent;
    }
    return node;
}
function isLang(attribute) {
    return attribute.directive === false && attribute.key.name === "lang";
}
function getLang(element) {
    const langAttr = element && element.startTag.attributes.find(isLang);
    const lang = langAttr && langAttr.value && langAttr.value.value;
    return lang || null;
}
function isTSLang(element) {
    const lang = getLang(element);
    return lang === "ts" || lang === "tsx";
}
function findGenericDirective(element) {
    return (element.startTag.attributes.find((attr) => {
        var _a, _b;
        return attr.directive &&
            ((_b = (_a = attr.value) === null || _a === void 0 ? void 0 : _a.expression) === null || _b === void 0 ? void 0 : _b.type) === "VGenericExpression";
    }) || null);
}

function isParserObject(value) {
    return isEnhancedParserObject(value) || isBasicParserObject(value);
}
function isEnhancedParserObject(value) {
    return Boolean(value && typeof value.parseForESLint === "function");
}
function isBasicParserObject(value) {
    return Boolean(value && typeof value.parse === "function");
}

function isSFCFile(parserOptions) {
    if (parserOptions.filePath === "<input>") {
        return true;
    }
    return path__namespace.extname(parserOptions.filePath || "unknown.vue") === ".vue";
}
function getScriptParser(parser, getParserLang) {
    if (isParserObject(parser)) {
        return parser;
    }
    if (parser && typeof parser === "object") {
        const parserLang = getParserLang();
        const parserLangs = parserLang == null
            ? []
            : typeof parserLang === "string"
                ? [parserLang]
                : parserLang;
        for (const lang of parserLangs) {
            const parserForLang = lang && parser[lang];
            if (typeof parserForLang === "string" ||
                isParserObject(parserForLang)) {
                return parserForLang;
            }
        }
        return parser.js;
    }
    return typeof parser === "string" ? parser : undefined;
}
function getParserLangFromSFC(doc) {
    if (doc) {
        const scripts = doc.children.filter(isScriptElement);
        const script = (scripts.length === 2 && scripts.find(isScriptSetupElement)) ||
            scripts[0];
        if (script) {
            return getLang(script);
        }
    }
    return null;
}

const createRequire = Module__default["default"].createRequire ||
    Module__default["default"].createRequireFromPath ||
    ((modname) => {
        const mod = new Module__default["default"](modname);
        mod.filename = modname;
        mod.paths = Module__default["default"]._nodeModulePaths(path__default["default"].dirname(modname));
        mod._compile("module.exports = require;", modname);
        return mod.exports;
    });

function isLinterPath(p) {
    return (p.includes(`eslint${path__default["default"].sep}lib${path__default["default"].sep}linter${path__default["default"].sep}linter.js`) ||
        p.includes(`eslint${path__default["default"].sep}lib${path__default["default"].sep}linter.js`));
}
function getLinterRequire() {
    const linterPath = Object.keys(require.cache).find(isLinterPath);
    if (linterPath) {
        try {
            return createRequire(linterPath);
        }
        catch (_a) {
        }
    }
    return null;
}

let escopeCache = null;
function getEslintScope() {
    var _a;
    if (!escopeCache) {
        escopeCache = (_a = getLinterRequire()) === null || _a === void 0 ? void 0 : _a("eslint-scope");
        if (!escopeCache ||
            escopeCache.version == null ||
            semver.lte(escopeCache.version, escope__namespace.version)) {
            escopeCache = escope__namespace;
        }
    }
    return escopeCache;
}

let espreeCache = null;
function getEspreeFromEcmaVersion(ecmaVersion) {
    const linterEspree = getEspreeFromLinter();
    if (ecmaVersion == null) {
        return linterEspree;
    }
    if (ecmaVersion === "latest") {
        return getNewestEspree();
    }
    if (normalizeEcmaVersion(ecmaVersion) <= getLatestEcmaVersion(linterEspree)) {
        return linterEspree;
    }
    const userEspree = getEspreeFromUser();
    if (normalizeEcmaVersion(ecmaVersion) <= getLatestEcmaVersion(userEspree)) {
        return userEspree;
    }
    return linterEspree;
}
function getEspreeFromUser() {
    try {
        const cwd = process.cwd();
        const relativeTo = path__default["default"].join(cwd, "__placeholder__.js");
        return createRequire(relativeTo)("espree");
    }
    catch (_a) {
        return getEspreeFromLinter();
    }
}
function getEspreeFromLinter() {
    var _a;
    if (!espreeCache) {
        espreeCache = (_a = getLinterRequire()) === null || _a === void 0 ? void 0 : _a("espree");
        if (!espreeCache) {
            espreeCache = dependencyEspree__namespace;
        }
    }
    return espreeCache;
}
function getNewestEspree() {
    let newest = dependencyEspree__namespace;
    const linterEspree = getEspreeFromLinter();
    if (linterEspree.version != null &&
        semver.lte(newest.version, linterEspree.version)) {
        newest = linterEspree;
    }
    const userEspree = getEspreeFromUser();
    if (userEspree.version != null && semver.lte(newest.version, userEspree.version)) {
        newest = userEspree;
    }
    return newest;
}
function getEcmaVersionIfUseEspree(parserOptions, getDefault) {
    var _a;
    if (parserOptions.parser != null && parserOptions.parser !== "espree") {
        return undefined;
    }
    if (parserOptions.ecmaVersion === "latest") {
        return normalizeEcmaVersion(getLatestEcmaVersion(getNewestEspree()));
    }
    if (parserOptions.ecmaVersion == null) {
        const defVer = getDefaultEcmaVersion$1();
        return (_a = getDefault === null || getDefault === void 0 ? void 0 : getDefault(defVer)) !== null && _a !== void 0 ? _a : defVer;
    }
    return normalizeEcmaVersion(parserOptions.ecmaVersion);
}
function getDefaultEcmaVersion$1() {
    if (semver.lt(getEspreeFromLinter().version, "9.0.0")) {
        return 5;
    }
    return normalizeEcmaVersion(getLatestEcmaVersion(getNewestEspree()));
}
function normalizeEcmaVersion(version) {
    if (version > 5 && version < 2015) {
        return version + 2009;
    }
    return version;
}
function getLatestEcmaVersion(espree) {
    if (espree.latestEcmaVersion == null) {
        for (const { v, latest } of [
            { v: "6.1.0", latest: 2020 },
            { v: "4.0.0", latest: 2019 },
        ]) {
            if (semver.lte(v, espree.version)) {
                return latest;
            }
        }
        return 2018;
    }
    return normalizeEcmaVersion(espree.latestEcmaVersion);
}

function isUnique(reference, index, references) {
    return (index === 0 || reference.identifier !== references[index - 1].identifier);
}
function hasDefinition(variable) {
    return variable.defs.length >= 1;
}
function transformReference(reference) {
    const ret = {
        id: reference.identifier,
        mode: reference.isReadOnly()
            ? "r"
            : reference.isWriteOnly()
                ? "w"
                : "rw",
        variable: null,
        isValueReference: reference.isValueReference,
        isTypeReference: reference.isTypeReference,
    };
    Object.defineProperty(ret, "variable", { enumerable: false });
    return ret;
}
function transformVariable(variable, kind) {
    const ret = {
        id: variable.defs[0].name,
        kind,
        references: [],
    };
    Object.defineProperty(ret, "references", { enumerable: false });
    return ret;
}
function getForScope(scope) {
    const child = scope.childScopes[0];
    return child.block === scope.block ? child.childScopes[0] : child;
}
function analyzeScope(ast, parserOptions) {
    const ecmaVersion = getEcmaVersionIfUseEspree(parserOptions) || 2022;
    const ecmaFeatures = parserOptions.ecmaFeatures || {};
    const sourceType = parserOptions.sourceType || "script";
    const result = getEslintScope().analyze(ast, {
        ignoreEval: true,
        nodejsScope: false,
        impliedStrict: ecmaFeatures.impliedStrict,
        ecmaVersion,
        sourceType,
        fallback: getFallbackKeys,
    });
    return result;
}
function analyze(parserResult, parserOptions) {
    const scopeManager = parserResult.scopeManager ||
        analyzeScope(parserResult.ast, parserOptions);
    return scopeManager.globalScope;
}
function analyzeExternalReferences(parserResult, parserOptions) {
    const scope = analyze(parserResult, parserOptions);
    return scope.through.filter(isUnique).map(transformReference);
}
function analyzeVariablesAndExternalReferences(parserResult, kind, parserOptions) {
    const scope = analyze(parserResult, parserOptions);
    return {
        variables: getForScope(scope)
            .variables.filter(hasDefinition)
            .map((v) => transformVariable(v, kind)),
        references: scope.through.filter(isUnique).map(transformReference),
    };
}

function fixLocations(result, locationCalculator) {
    fixNodeLocations(result.ast, result.visitorKeys, locationCalculator);
    for (const token of result.ast.tokens || []) {
        fixLocation(token, locationCalculator);
    }
    for (const comment of result.ast.comments || []) {
        fixLocation(comment, locationCalculator);
    }
}
function fixNodeLocations(rootNode, visitorKeys, locationCalculator) {
    const traversed = new Map();
    traverseNodes(rootNode, {
        visitorKeys,
        enterNode(node, parent) {
            if (!traversed.has(node)) {
                traversed.set(node, node);
                node.parent = parent;
                if (traversed.has(node.range)) {
                    if (!traversed.has(node.loc)) {
                        node.loc.start = locationCalculator.getLocFromIndex(node.range[0]);
                        node.loc.end = locationCalculator.getLocFromIndex(node.range[1]);
                        traversed.set(node.loc, node);
                    }
                    else if (node.start != null || node.end != null) {
                        const traversedNode = traversed.get(node.range);
                        if (traversedNode.type === node.type) {
                            node.start = traversedNode.start;
                            node.end = traversedNode.end;
                        }
                    }
                }
                else {
                    fixLocation(node, locationCalculator);
                    traversed.set(node.range, node);
                    traversed.set(node.loc, node);
                }
            }
        },
        leaveNode() {
        },
    });
}
function fixLocation(node, locationCalculator) {
    const range = node.range;
    const loc = node.loc;
    const d0 = locationCalculator.getFixOffset(range[0], "start");
    const d1 = locationCalculator.getFixOffset(range[1], "end");
    if (d0 !== 0) {
        range[0] += d0;
        if (node.start != null) {
            node.start += d0;
        }
        loc.start = locationCalculator.getLocFromIndex(range[0]);
    }
    if (d1 !== 0) {
        range[1] += d1;
        if (node.end != null) {
            node.end += d0;
        }
        loc.end = locationCalculator.getLocFromIndex(range[1]);
    }
    return node;
}
function fixErrorLocation(error, locationCalculator) {
    const diff = locationCalculator.getFixOffset(error.index, "start");
    error.index += diff;
    const loc = locationCalculator.getLocFromIndex(error.index);
    error.lineNumber = loc.line;
    error.column = loc.column;
}

const DEFAULT_ECMA_VERSION = 2017;
function getScriptSetupParserOptions(parserOptions) {
    const espreeEcmaVersion = getEcmaVersionIfUseEspree(parserOptions, getDefaultEcmaVersion);
    return Object.assign(Object.assign({}, parserOptions), { ecmaVersion: espreeEcmaVersion });
}
function getDefaultEcmaVersion(def) {
    if (semver.lte("8.0.0", getEspreeFromUser().version)) {
        return getEspreeFromUser().latestEcmaVersion;
    }
    return Math.max(def, DEFAULT_ECMA_VERSION);
}

function extractGeneric(element) {
    const genericAttr = findGenericDirective(element);
    if (!genericAttr) {
        return null;
    }
    const genericNode = genericAttr.value.expression;
    const defineTypes = genericNode.params.map((t, i) => ({
        node: t,
        define: `type ${t.name.name} = ${getConstraint(t, genericNode.rawParams[i])}`,
    }));
    return {
        node: genericNode,
        defineTypes,
        postprocess({ result, getTypeBlock, isRemoveTarget, getTypeDefScope }) {
            var _a;
            const node = (_a = getTypeBlock === null || getTypeBlock === void 0 ? void 0 : getTypeBlock(result.ast)) !== null && _a !== void 0 ? _a : result.ast;
            removeTypeDeclarations(node, isRemoveTarget);
            if (result.ast.tokens) {
                removeTypeDeclarationTokens(result.ast.tokens, isRemoveTarget);
            }
            if (result.ast.comments) {
                removeTypeDeclarationTokens(result.ast.comments, isRemoveTarget);
            }
            if (result.scopeManager) {
                const typeDefScope = getTypeDefScope(result.scopeManager);
                restoreScope(result.scopeManager, typeDefScope, isRemoveTarget);
            }
        },
    };
    function removeTypeDeclarations(node, isRemoveTarget) {
        for (let index = node.body.length - 1; index >= 0; index--) {
            if (isRemoveTarget(node.body[index])) {
                node.body.splice(index, 1);
            }
        }
    }
    function removeTypeDeclarationTokens(tokens, isRemoveTarget) {
        for (let index = tokens.length - 1; index >= 0; index--) {
            if (isRemoveTarget(tokens[index])) {
                tokens.splice(index, 1);
            }
        }
    }
    function restoreScope(scopeManager, typeDefScope, isRemoveTarget) {
        for (const variable of [...typeDefScope.variables]) {
            let def = variable.defs.find((d) => isRemoveTarget(d.name));
            while (def) {
                removeVariableDef(variable, def, typeDefScope);
                def = variable.defs.find((d) => isRemoveTarget(d.name));
            }
        }
        for (const reference of [...typeDefScope.references]) {
            if (isRemoveTarget(reference.identifier)) {
                removeReference(reference, typeDefScope);
            }
        }
        for (const scope of [...scopeManager.scopes]) {
            if (isRemoveTarget(scope.block)) {
                removeScope(scopeManager, scope);
            }
        }
    }
}
function getConstraint(node, rawParam) {
    if (!node.constraint) {
        return "unknown";
    }
    let index = rawParam.indexOf(node.name.name) + node.name.name.length;
    let startIndex = null;
    while (index < rawParam.length) {
        if (startIndex == null) {
            if (rawParam.startsWith("extends", index)) {
                startIndex = index = index + 7;
                continue;
            }
        }
        else if (rawParam[index] === "=") {
            if (rawParam[index + 1] === ">") {
                index += 2;
                continue;
            }
            return rawParam.slice(startIndex, index);
        }
        if (rawParam.startsWith("//", index)) {
            const lfIndex = rawParam.indexOf("\n", index);
            if (lfIndex >= 0) {
                index = lfIndex + 1;
                continue;
            }
            return "unknown";
        }
        if (rawParam.startsWith("/*", index)) {
            const endIndex = rawParam.indexOf("*/", index);
            if (endIndex >= 0) {
                index = endIndex + 2;
                continue;
            }
            return "unknown";
        }
        index++;
    }
    if (startIndex == null) {
        return "unknown";
    }
    return rawParam.slice(startIndex);
}
function removeVariableDef(variable, def, scope) {
    const defIndex = variable.defs.indexOf(def);
    if (defIndex < 0) {
        return;
    }
    variable.defs.splice(defIndex, 1);
    if (variable.defs.length === 0) {
        referencesToThrough(variable.references, scope);
        variable.references.forEach((r) => {
            if (r.init) {
                r.init = false;
            }
            r.resolved = null;
        });
        scope.variables.splice(scope.variables.indexOf(variable), 1);
        const name = variable.name;
        if (variable === scope.set.get(name)) {
            scope.set.delete(name);
        }
    }
    else {
        const idIndex = variable.identifiers.indexOf(def.name);
        if (idIndex >= 0) {
            variable.identifiers.splice(idIndex, 1);
        }
    }
}
function referencesToThrough(references, baseScope) {
    let scope = baseScope;
    while (scope) {
        addAllReferences(scope.through, references);
        scope = scope.upper;
    }
}
function addAllReferences(list, elements) {
    list.push(...elements);
    list.sort((a, b) => a.identifier.range[0] - b.identifier.range[0]);
}
function removeReference(reference, baseScope) {
    if (reference.resolved) {
        if (reference.resolved.defs.some((d) => d.name === reference.identifier)) {
            const varIndex = baseScope.variables.indexOf(reference.resolved);
            if (varIndex >= 0) {
                baseScope.variables.splice(varIndex, 1);
            }
            const name = reference.identifier.name;
            if (reference.resolved === baseScope.set.get(name)) {
                baseScope.set.delete(name);
            }
        }
        else {
            const refIndex = reference.resolved.references.indexOf(reference);
            if (refIndex >= 0) {
                reference.resolved.references.splice(refIndex, 1);
            }
        }
    }
    let scope = baseScope;
    while (scope) {
        const refIndex = scope.references.indexOf(reference);
        if (refIndex >= 0) {
            scope.references.splice(refIndex, 1);
        }
        const throughIndex = scope.through.indexOf(reference);
        if (throughIndex >= 0) {
            scope.through.splice(throughIndex, 1);
        }
        scope = scope.upper;
    }
}
function removeScope(scopeManager, scope) {
    for (const childScope of scope.childScopes) {
        removeScope(scopeManager, childScope);
    }
    while (scope.references[0]) {
        removeReference(scope.references[0], scope);
    }
    const upper = scope.upper;
    if (upper) {
        const index = upper.childScopes.indexOf(scope);
        if (index >= 0) {
            upper.childScopes.splice(index, 1);
        }
    }
    const index = scopeManager.scopes.indexOf(scope);
    if (index >= 0) {
        scopeManager.scopes.splice(index, 1);
    }
}

const ALIAS_ITERATOR = /^([\s\S]*?(?:\s|\)))(\bin\b|\bof\b)([\s\S]*)$/u;
const PARENS = /^(\s*\()([\s\S]*?)(\)\s*)$/u;
const DUMMY_PARENT$2 = {};
const IS_FUNCTION_EXPRESSION = /^\s*([\w$_]+|(async\s*)?\([^)]*?\))\s*(:[^=]+)?=>|^\s*(async\s+)?function(?:\s+[\w$]+)?\s*\(/u;
const IS_SIMPLE_PATH = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?'\]|\["[^"]*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/u;
function processVForAliasAndIterator(code) {
    const match = ALIAS_ITERATOR.exec(code);
    if (match != null) {
        const aliases = match[1];
        const parenMatch = PARENS.exec(aliases);
        return {
            aliases,
            hasParens: Boolean(parenMatch),
            aliasesWithBrackets: parenMatch
                ? `${parenMatch[1].slice(0, -1)}[${parenMatch[2]}]${parenMatch[3].slice(1)}`
                : `[${aliases.slice(0, -1)}]`,
            delimiter: match[2] || "",
            iterator: match[3],
        };
    }
    return {
        aliases: "",
        hasParens: false,
        aliasesWithBrackets: "",
        delimiter: "",
        iterator: code,
    };
}
function getCommaTokenBeforeNode(tokens, node) {
    let tokenIndex = sortedIndexBy__default["default"](tokens, { range: node.range }, (t) => t.range[0]);
    while (tokenIndex >= 0) {
        const token = tokens[tokenIndex];
        if (token.type === "Punctuator" && token.value === ",") {
            return token;
        }
        tokenIndex -= 1;
    }
    return null;
}
function throwEmptyError(locationCalculator, expected) {
    const loc = locationCalculator.getLocation(0);
    const err = new ParseError(`Expected to be ${expected}, but got empty.`, undefined, 0, loc.line, loc.column);
    fixErrorLocation(err, locationCalculator);
    throw err;
}
function throwUnexpectedTokenError(name, token) {
    const err = new ParseError(`Unexpected token '${name}'.`, undefined, token.range[0], token.loc.start.line, token.loc.start.column);
    throw err;
}
function throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator) {
    if (ParseError.isParseError(err)) {
        const endOffset = locationCalculator.getOffsetWithGap(code.length);
        if (err.index >= endOffset) {
            err.message = "Unexpected end of expression.";
        }
    }
    throw err;
}
function parseScriptFragment(code, locationCalculator, parserOptions) {
    return parseScriptFragmentWithOption(code, locationCalculator, parserOptions);
}
function parseScriptFragmentWithOption(code, locationCalculator, parserOptions, processOptions) {
    var _a;
    try {
        const result = parseScript$1(code, parserOptions);
        (_a = processOptions === null || processOptions === void 0 ? void 0 : processOptions.preFixLocationProcess) === null || _a === void 0 ? void 0 : _a.call(processOptions, result);
        fixLocations(result, locationCalculator);
        return result;
    }
    catch (err) {
        const perr = ParseError.normalize(err);
        if (perr) {
            fixErrorLocation(perr, locationCalculator);
            throw perr;
        }
        throw err;
    }
}
const validDivisionCharRE = /[\w).+\-_$\]]/u;
function splitFilters(exp) {
    const result = [];
    let inSingle = false;
    let inDouble = false;
    let inTemplateString = false;
    let inRegex = false;
    let curly = 0;
    let square = 0;
    let paren = 0;
    let lastFilterIndex = 0;
    let c = 0;
    let prev = 0;
    for (let i = 0; i < exp.length; i++) {
        prev = c;
        c = exp.charCodeAt(i);
        if (inSingle) {
            if (c === 0x27 && prev !== 0x5c) {
                inSingle = false;
            }
        }
        else if (inDouble) {
            if (c === 0x22 && prev !== 0x5c) {
                inDouble = false;
            }
        }
        else if (inTemplateString) {
            if (c === 0x60 && prev !== 0x5c) {
                inTemplateString = false;
            }
        }
        else if (inRegex) {
            if (c === 0x2f && prev !== 0x5c) {
                inRegex = false;
            }
        }
        else if (c === 0x7c &&
            exp.charCodeAt(i + 1) !== 0x7c &&
            exp.charCodeAt(i - 1) !== 0x7c &&
            !curly &&
            !square &&
            !paren) {
            result.push(exp.slice(lastFilterIndex, i));
            lastFilterIndex = i + 1;
        }
        else {
            switch (c) {
                case 0x22:
                    inDouble = true;
                    break;
                case 0x27:
                    inSingle = true;
                    break;
                case 0x60:
                    inTemplateString = true;
                    break;
                case 0x28:
                    paren++;
                    break;
                case 0x29:
                    paren--;
                    break;
                case 0x5b:
                    square++;
                    break;
                case 0x5d:
                    square--;
                    break;
                case 0x7b:
                    curly++;
                    break;
                case 0x7d:
                    curly--;
                    break;
            }
            if (c === 0x2f) {
                let j = i - 1;
                let p;
                for (; j >= 0; j--) {
                    p = exp.charAt(j);
                    if (p !== " ") {
                        break;
                    }
                }
                if (!p || !validDivisionCharRE.test(p)) {
                    inRegex = true;
                }
            }
        }
    }
    result.push(exp.slice(lastFilterIndex));
    return result;
}
function parseExpressionBody(code, locationCalculator, parserOptions, allowEmpty = false) {
    debug('[script] parse expression: "0(%s)"', code);
    try {
        const result = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions);
        const { ast } = result;
        const tokens = ast.tokens || [];
        const comments = ast.comments || [];
        const references = analyzeExternalReferences(result, parserOptions);
        const statement = ast.body[0];
        const callExpression = statement.expression;
        const expression = callExpression.arguments[0];
        if (!allowEmpty && !expression) {
            return throwEmptyError(locationCalculator, "an expression");
        }
        if (expression && expression.type === "SpreadElement") {
            return throwUnexpectedTokenError("...", expression);
        }
        if (callExpression.arguments[1]) {
            const node = callExpression.arguments[1];
            return throwUnexpectedTokenError(",", getCommaTokenBeforeNode(tokens, node) || node);
        }
        tokens.shift();
        tokens.shift();
        tokens.pop();
        return { expression, tokens, comments, references, variables: [] };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function parseFilter(code, locationCalculator, parserOptions) {
    debug('[script] parse filter: "%s"', code);
    try {
        const expression = {
            type: "VFilter",
            parent: null,
            range: [0, 0],
            loc: {},
            callee: null,
            arguments: [],
        };
        const tokens = [];
        const comments = [];
        const references = [];
        const paren = code.indexOf("(");
        const calleeCode = paren === -1 ? code : code.slice(0, paren);
        const argsCode = paren === -1 ? null : code.slice(paren);
        if (calleeCode.trim()) {
            const spaces = /^\s*/u.exec(calleeCode)[0];
            const subCalculator = locationCalculator.getSubCalculatorShift(spaces.length);
            const { ast } = parseScriptFragment(`"${calleeCode.trim()}"`, subCalculator, parserOptions);
            const statement = ast.body[0];
            const callee = statement.expression;
            if (callee.type !== "Literal") {
                const { loc, range } = ast.tokens[0];
                return throwUnexpectedTokenError('"', {
                    range: [range[1] - 1, range[1]],
                    loc: {
                        start: {
                            line: loc.end.line,
                            column: loc.end.column - 1,
                        },
                        end: loc.end,
                    },
                });
            }
            expression.callee = {
                type: "Identifier",
                parent: expression,
                range: [
                    callee.range[0],
                    subCalculator.getOffsetWithGap(calleeCode.trim().length),
                ],
                loc: {
                    start: callee.loc.start,
                    end: subCalculator.getLocation(calleeCode.trim().length),
                },
                name: String(callee.value),
            };
            tokens.push({
                type: "Identifier",
                value: calleeCode.trim(),
                range: expression.callee.range,
                loc: expression.callee.loc,
            });
        }
        else {
            return throwEmptyError(locationCalculator, "a filter name");
        }
        if (argsCode != null) {
            const result = parseScriptFragment(`0${argsCode}`, locationCalculator
                .getSubCalculatorAfter(paren)
                .getSubCalculatorShift(-1), parserOptions);
            const { ast } = result;
            const statement = ast.body[0];
            const callExpression = statement.expression;
            ast.tokens.shift();
            if (callExpression.type !== "CallExpression" ||
                callExpression.callee.type !== "Literal") {
                let nestCount = 1;
                for (const token of ast.tokens.slice(1)) {
                    if (nestCount === 0) {
                        return throwUnexpectedTokenError(token.value, token);
                    }
                    if (token.type === "Punctuator" && token.value === "(") {
                        nestCount += 1;
                    }
                    if (token.type === "Punctuator" && token.value === ")") {
                        nestCount -= 1;
                    }
                }
                const token = last__default["default"](ast.tokens);
                return throwUnexpectedTokenError(token.value, token);
            }
            for (const argument of callExpression.arguments) {
                argument.parent = expression;
                expression.arguments.push(argument);
            }
            tokens.push(...ast.tokens);
            comments.push(...ast.comments);
            references.push(...analyzeExternalReferences(result, parserOptions));
        }
        const firstToken = tokens[0];
        const lastToken = last__default["default"](tokens);
        expression.range = [firstToken.range[0], lastToken.range[1]];
        expression.loc = { start: firstToken.loc.start, end: lastToken.loc.end };
        return { expression, tokens, comments, references, variables: [] };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function loadParser(parser) {
    if (parser !== "espree") {
        return require(parser);
    }
    return getEspreeFromUser();
}
function parseScript$1(code, parserOptions) {
    const parser = typeof parserOptions.parser === "string"
        ? loadParser(parserOptions.parser)
        : isParserObject(parserOptions.parser)
            ? parserOptions.parser
            : getEspreeFromEcmaVersion(parserOptions.ecmaVersion);
    const result = isEnhancedParserObject(parser)
        ? parser.parseForESLint(code, parserOptions)
        : parser.parse(code, parserOptions);
    if (result.ast != null) {
        return result;
    }
    return { ast: result };
}
function parseScriptElement(node, sfcCode, linesAndColumns, originalParserOptions) {
    var _a, _b;
    const parserOptions = isScriptSetupElement(node)
        ? getScriptSetupParserOptions(originalParserOptions)
        : Object.assign(Object.assign({}, originalParserOptions), { ecmaVersion: originalParserOptions.ecmaVersion || DEFAULT_ECMA_VERSION });
    let generic = null;
    let code;
    let offset;
    const textNode = node.children[0];
    if (textNode != null && textNode.type === "VText") {
        const [scriptStartOffset, scriptEndOffset] = textNode.range;
        code = sfcCode.slice(scriptStartOffset, scriptEndOffset);
        offset = scriptStartOffset;
        generic = extractGeneric(node);
        if (generic) {
            const defineTypesCode = `${generic.defineTypes
                .map((e) => e.define)
                .join(";")};\n`;
            code = defineTypesCode + code;
            offset -= defineTypesCode.length;
        }
    }
    else {
        code = "";
        offset = node.startTag.range[1];
    }
    const locationCalculator = linesAndColumns.createOffsetLocationCalculator(offset);
    const result = parseScriptFragment(code, locationCalculator, parserOptions);
    if (generic) {
        generic.postprocess({
            result,
            isRemoveTarget(nodeOrToken) {
                return nodeOrToken.range[1] <= textNode.range[0];
            },
            getTypeDefScope(scopeManager) {
                var _a;
                return ((_a = scopeManager.globalScope.childScopes.find((s) => s.type === "module")) !== null && _a !== void 0 ? _a : scopeManager.globalScope);
            },
        });
        const startToken = [
            result.ast.body[0],
            (_a = result.ast.tokens) === null || _a === void 0 ? void 0 : _a[0],
            (_b = result.ast.comments) === null || _b === void 0 ? void 0 : _b[0],
        ]
            .filter((e) => Boolean(e))
            .sort((a, b) => a.range[0] - b.range[0])
            .find((t) => Boolean(t));
        if (startToken && result.ast.range[0] !== startToken.range[0]) {
            result.ast.range[0] = startToken.range[0];
            if (result.ast.start != null) {
                result.ast.start = startToken.start;
            }
            result.ast.loc.start = Object.assign({}, startToken.loc.start);
        }
    }
    if (result.ast.tokens != null) {
        const startTag = node.startTag;
        const endTag = node.endTag;
        result.ast.tokens.unshift({
            type: "Punctuator",
            range: startTag.range,
            loc: startTag.loc,
            value: "<script>",
        });
        if (endTag != null) {
            result.ast.tokens.push({
                type: "Punctuator",
                range: endTag.range,
                loc: endTag.loc,
                value: "</script>",
            });
        }
    }
    return result;
}
function parseExpression(code, locationCalculator, parserOptions, { allowEmpty = false, allowFilters = false } = {}) {
    var _a, _b;
    debug('[script] parse expression: "%s"', code);
    const [mainCode, ...filterCodes] = allowFilters && ((_b = (_a = parserOptions.vueFeatures) === null || _a === void 0 ? void 0 : _a.filter) !== null && _b !== void 0 ? _b : true)
        ? splitFilters(code)
        : [code];
    if (filterCodes.length === 0) {
        return parseExpressionBody(code, locationCalculator, parserOptions, allowEmpty);
    }
    const retB = parseExpressionBody(mainCode, locationCalculator, parserOptions);
    if (!retB.expression) {
        return retB;
    }
    const ret = retB;
    ret.expression = {
        type: "VFilterSequenceExpression",
        parent: null,
        expression: retB.expression,
        filters: [],
        range: retB.expression.range.slice(0),
        loc: Object.assign({}, retB.expression.loc),
    };
    ret.expression.expression.parent = ret.expression;
    let prevLoc = mainCode.length;
    for (const filterCode of filterCodes) {
        ret.tokens.push(fixLocation({
            type: "Punctuator",
            value: "|",
            range: [prevLoc, prevLoc + 1],
            loc: {},
        }, locationCalculator));
        const retF = parseFilter(filterCode, locationCalculator.getSubCalculatorShift(prevLoc + 1), parserOptions);
        if (retF) {
            if (retF.expression) {
                ret.expression.filters.push(retF.expression);
                retF.expression.parent = ret.expression;
            }
            ret.tokens.push(...retF.tokens);
            ret.comments.push(...retF.comments);
            ret.references.push(...retF.references);
        }
        prevLoc += 1 + filterCode.length;
    }
    const lastToken = last__default["default"](ret.tokens);
    ret.expression.range[1] = lastToken.range[1];
    ret.expression.loc.end = lastToken.loc.end;
    return ret;
}
function parseVForExpression(code, locationCalculator, parserOptions) {
    if (code.trim() === "") {
        throwEmptyError(locationCalculator, "'<alias> in <expression>'");
    }
    if (isEcmaVersion5(parserOptions)) {
        return parseVForExpressionForEcmaVersion5(code, locationCalculator, parserOptions);
    }
    const processed = processVForAliasAndIterator(code);
    if (!processed.aliases.trim()) {
        return throwEmptyError(locationCalculator, "an alias");
    }
    try {
        debug('[script] parse v-for expression: "for(%s%s%s);"', processed.aliasesWithBrackets, processed.delimiter, processed.iterator);
        const result = parseScriptFragment(`for(let ${processed.aliasesWithBrackets}${processed.delimiter}${processed.iterator});`, locationCalculator.getSubCalculatorShift(processed.hasParens ? -8 : -9), parserOptions);
        const { ast } = result;
        const tokens = ast.tokens || [];
        const comments = ast.comments || [];
        const scope = analyzeVariablesAndExternalReferences(result, "v-for", parserOptions);
        const references = scope.references;
        const variables = scope.variables;
        const statement = ast.body[0];
        const varDecl = statement.left;
        const id = varDecl.declarations[0].id;
        const left = id.elements;
        const right = statement.right;
        if (!processed.hasParens && !left.length) {
            return throwEmptyError(locationCalculator, "an alias");
        }
        tokens.shift();
        tokens.shift();
        tokens.shift();
        tokens.pop();
        tokens.pop();
        const closeOffset = statement.left.range[1] - 1;
        const closeIndex = tokens.findIndex((t) => t.range[0] === closeOffset);
        if (processed.hasParens) {
            const open = tokens[0];
            if (open != null) {
                open.value = "(";
            }
            const close = tokens[closeIndex];
            if (close != null) {
                close.value = ")";
            }
        }
        else {
            tokens.splice(closeIndex, 1);
            tokens.shift();
        }
        const firstToken = tokens[0] || statement.left;
        const lastToken = tokens[tokens.length - 1] || statement.right;
        const expression = {
            type: "VForExpression",
            range: [firstToken.range[0], lastToken.range[1]],
            loc: { start: firstToken.loc.start, end: lastToken.loc.end },
            parent: DUMMY_PARENT$2,
            left,
            right,
        };
        for (const l of left) {
            if (l != null) {
                l.parent = expression;
            }
        }
        right.parent = expression;
        return { expression, tokens, comments, references, variables };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function isEcmaVersion5(parserOptions) {
    const ecmaVersion = getEcmaVersionIfUseEspree(parserOptions);
    return ecmaVersion != null && ecmaVersion <= 5;
}
function parseVForExpressionForEcmaVersion5(code, locationCalculator, parserOptions) {
    const processed = processVForAliasAndIterator(code);
    if (!processed.aliases.trim()) {
        return throwEmptyError(locationCalculator, "an alias");
    }
    try {
        const tokens = [];
        const comments = [];
        const parsedAliases = parseVForAliasesForEcmaVersion5(processed.aliasesWithBrackets, locationCalculator.getSubCalculatorShift(processed.hasParens ? 0 : -1), parserOptions);
        if (processed.hasParens) {
            const open = parsedAliases.tokens[0];
            if (open != null) {
                open.value = "(";
            }
            const close = last__default["default"](parsedAliases.tokens);
            if (close != null) {
                close.value = ")";
            }
        }
        else {
            parsedAliases.tokens.shift();
            parsedAliases.tokens.pop();
        }
        tokens.push(...parsedAliases.tokens);
        comments.push(...parsedAliases.comments);
        const { left, variables } = parsedAliases;
        if (!processed.hasParens && !left.length) {
            return throwEmptyError(locationCalculator, "an alias");
        }
        const delimiterStart = processed.aliases.length;
        const delimiterEnd = delimiterStart + processed.delimiter.length;
        tokens.push(fixLocation({
            type: processed.delimiter === "in" ? "Keyword" : "Identifier",
            value: processed.delimiter,
            start: delimiterStart,
            end: delimiterEnd,
            loc: {},
            range: [delimiterStart, delimiterEnd],
        }, locationCalculator));
        const parsedIterator = parseVForIteratorForEcmaVersion5(processed.iterator, locationCalculator.getSubCalculatorShift(delimiterEnd), parserOptions);
        tokens.push(...parsedIterator.tokens);
        comments.push(...parsedIterator.comments);
        const { right, references } = parsedIterator;
        const firstToken = tokens[0];
        const lastToken = last__default["default"](tokens) || firstToken;
        const expression = {
            type: "VForExpression",
            range: [firstToken.range[0], lastToken.range[1]],
            loc: { start: firstToken.loc.start, end: lastToken.loc.end },
            parent: DUMMY_PARENT$2,
            left,
            right,
        };
        for (const l of left) {
            if (l != null) {
                l.parent = expression;
            }
        }
        right.parent = expression;
        return { expression, tokens, comments, references, variables };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function parseVForAliasesForEcmaVersion5(code, locationCalculator, parserOptions) {
    const result = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions);
    const { ast } = result;
    const tokens = ast.tokens || [];
    const comments = ast.comments || [];
    const variables = analyzeExternalReferences(result, parserOptions).map(transformVariable);
    const statement = ast.body[0];
    const callExpression = statement.expression;
    const expression = callExpression.arguments[0];
    const left = expression.elements.filter((e) => {
        if (e == null || e.type === "Identifier") {
            return true;
        }
        const errorToken = tokens.find((t) => e.range[0] <= t.range[0] && t.range[1] <= e.range[1]);
        return throwUnexpectedTokenError(errorToken.value, errorToken);
    });
    tokens.shift();
    tokens.shift();
    tokens.pop();
    return { left, tokens, comments, variables };
    function transformVariable(reference) {
        const ret = {
            id: reference.id,
            kind: "v-for",
            references: [],
        };
        Object.defineProperty(ret, "references", { enumerable: false });
        return ret;
    }
}
function parseVForIteratorForEcmaVersion5(code, locationCalculator, parserOptions) {
    const result = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions);
    const { ast } = result;
    const tokens = ast.tokens || [];
    const comments = ast.comments || [];
    const references = analyzeExternalReferences(result, parserOptions);
    const statement = ast.body[0];
    const callExpression = statement.expression;
    const expression = callExpression.arguments[0];
    if (!expression) {
        return throwEmptyError(locationCalculator, "an expression");
    }
    if (expression && expression.type === "SpreadElement") {
        return throwUnexpectedTokenError("...", expression);
    }
    const right = expression;
    tokens.shift();
    tokens.shift();
    tokens.pop();
    return { right, tokens, comments, references };
}
function parseVOnExpression(code, locationCalculator, parserOptions) {
    if (IS_FUNCTION_EXPRESSION.test(code) || IS_SIMPLE_PATH.test(code)) {
        return parseExpressionBody(code, locationCalculator, parserOptions);
    }
    return parseVOnExpressionBody(code, locationCalculator, parserOptions);
}
function parseVOnExpressionBody(code, locationCalculator, parserOptions) {
    debug('[script] parse v-on expression: "void function($event){%s}"', code);
    if (code.trim() === "") {
        throwEmptyError(locationCalculator, "statements");
    }
    try {
        const result = parseScriptFragment(`void function($event){${code}}`, locationCalculator.getSubCalculatorShift(-22), parserOptions);
        const { ast } = result;
        const references = analyzeExternalReferences(result, parserOptions);
        const outermostStatement = ast.body[0];
        const functionDecl = outermostStatement.expression.argument;
        const block = functionDecl.body;
        const body = block.body;
        const firstStatement = first__default["default"](body);
        const lastStatement = last__default["default"](body);
        const expression = {
            type: "VOnExpression",
            range: [
                firstStatement != null
                    ? firstStatement.range[0]
                    : block.range[0] + 1,
                lastStatement != null
                    ? lastStatement.range[1]
                    : block.range[1] - 1,
            ],
            loc: {
                start: firstStatement != null
                    ? firstStatement.loc.start
                    : locationCalculator.getLocation(1),
                end: lastStatement != null
                    ? lastStatement.loc.end
                    : locationCalculator.getLocation(code.length + 1),
            },
            parent: DUMMY_PARENT$2,
            body,
        };
        const tokens = ast.tokens || [];
        const comments = ast.comments || [];
        for (const b of body) {
            b.parent = expression;
        }
        tokens.splice(0, 6);
        tokens.pop();
        return { expression, tokens, comments, references, variables: [] };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function parseSlotScopeExpression(code, locationCalculator, parserOptions) {
    debug('[script] parse slot-scope expression: "void function(%s) {}"', code);
    if (code.trim() === "") {
        throwEmptyError(locationCalculator, "an identifier or an array/object pattern");
    }
    try {
        const result = parseScriptFragment(`void function(${code}) {}`, locationCalculator.getSubCalculatorShift(-14), parserOptions);
        const { ast } = result;
        const statement = ast.body[0];
        const rawExpression = statement.expression;
        const functionDecl = rawExpression.argument;
        const params = functionDecl.params;
        if (params.length === 0) {
            return {
                expression: null,
                tokens: [],
                comments: [],
                references: [],
                variables: [],
            };
        }
        const tokens = ast.tokens || [];
        const comments = ast.comments || [];
        const scope = analyzeVariablesAndExternalReferences(result, "scope", parserOptions);
        const references = scope.references;
        const variables = scope.variables;
        const firstParam = first__default["default"](params);
        const lastParam = last__default["default"](params);
        const expression = {
            type: "VSlotScopeExpression",
            range: [firstParam.range[0], lastParam.range[1]],
            loc: { start: firstParam.loc.start, end: lastParam.loc.end },
            parent: DUMMY_PARENT$2,
            params: functionDecl.params,
        };
        for (const param of params) {
            param.parent = expression;
        }
        tokens.shift();
        tokens.shift();
        tokens.shift();
        tokens.pop();
        tokens.pop();
        tokens.pop();
        return { expression, tokens, comments, references, variables };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}
function parseGenericExpression(code, locationCalculator, parserOptions) {
    debug('[script] parse generic definition: "void function<%s>() {}"', code);
    if (code.trim() === "") {
        throwEmptyError(locationCalculator, "a type parameter");
    }
    function getParams(result) {
        const { ast } = result;
        const statement = ast.body[0];
        const rawExpression = statement.expression;
        const classDecl = rawExpression.argument;
        const typeParameters = classDecl
            .typeParameters;
        return typeParameters === null || typeParameters === void 0 ? void 0 : typeParameters.params;
    }
    try {
        const rawParams = [];
        const scriptLet = `void function<${code}>(){}`;
        const result = parseScriptFragmentWithOption(scriptLet, locationCalculator.getSubCalculatorShift(-14), Object.assign(Object.assign({}, parserOptions), { project: undefined }), {
            preFixLocationProcess(preResult) {
                const params = getParams(preResult);
                if (params) {
                    for (const param of params) {
                        rawParams.push(scriptLet.slice(param.range[0], param.range[1]));
                    }
                }
            },
        });
        const { ast } = result;
        const params = getParams(result);
        if (!params || params.length === 0) {
            return {
                expression: null,
                tokens: [],
                comments: [],
                references: [],
                variables: [],
            };
        }
        const tokens = ast.tokens || [];
        const comments = ast.comments || [];
        const scope = analyzeVariablesAndExternalReferences(result, "generic", parserOptions);
        const references = scope.references;
        const variables = scope.variables;
        const firstParam = first__default["default"](params);
        const lastParam = last__default["default"](params);
        const expression = {
            type: "VGenericExpression",
            range: [firstParam.range[0], lastParam.range[1]],
            loc: { start: firstParam.loc.start, end: lastParam.loc.end },
            parent: DUMMY_PARENT$2,
            params,
            rawParams,
        };
        for (const param of params) {
            ;
            param.parent = expression;
        }
        tokens.shift();
        tokens.shift();
        tokens.shift();
        tokens.pop();
        tokens.pop();
        tokens.pop();
        tokens.pop();
        tokens.pop();
        return { expression, tokens, comments, references, variables };
    }
    catch (err) {
        return throwErrorAsAdjustingOutsideOfCode(err, code, locationCalculator);
    }
}

function replaceTokens(document, node, newTokens) {
    if (document == null) {
        return;
    }
    const index = sortedIndexBy__default["default"](document.tokens, node, byRange0);
    const count = sortedLastIndexBy__default["default"](document.tokens, node, byRange1) - index;
    document.tokens.splice(index, count, ...newTokens);
}
function replaceAndSplitTokens(document, node, newTokens) {
    if (document == null) {
        return;
    }
    const index = sortedIndexBy__default["default"](document.tokens, node, byRange0);
    if (document.tokens.length === index ||
        node.range[0] < document.tokens[index].range[0]) {
        const beforeToken = document.tokens[index - 1];
        const value = beforeToken.value;
        const splitOffset = node.range[0] - beforeToken.range[0];
        const afterToken = {
            type: beforeToken.type,
            range: [node.range[0], beforeToken.range[1]],
            loc: {
                start: Object.assign({}, node.loc.start),
                end: Object.assign({}, beforeToken.loc.end),
            },
            value: value.slice(splitOffset),
        };
        beforeToken.range[1] = node.range[0];
        beforeToken.loc.end = Object.assign({}, node.loc.start);
        beforeToken.value = value.slice(0, splitOffset);
        document.tokens.splice(index, 0, afterToken);
    }
    let lastIndex = sortedLastIndexBy__default["default"](document.tokens, node, byRange1);
    if (lastIndex === 0 ||
        node.range[1] < document.tokens[lastIndex].range[1]) {
        const beforeToken = document.tokens[lastIndex];
        const value = beforeToken.value;
        const splitOffset = beforeToken.range[1] -
            beforeToken.range[0] -
            (beforeToken.range[1] - node.range[1]);
        const afterToken = {
            type: beforeToken.type,
            range: [node.range[1], beforeToken.range[1]],
            loc: {
                start: Object.assign({}, node.loc.end),
                end: Object.assign({}, beforeToken.loc.end),
            },
            value: value.slice(splitOffset),
        };
        beforeToken.range[1] = node.range[1];
        beforeToken.loc.end = Object.assign({}, node.loc.end);
        beforeToken.value = value.slice(0, splitOffset);
        document.tokens.splice(lastIndex + 1, 0, afterToken);
        lastIndex++;
    }
    const count = lastIndex - index;
    document.tokens.splice(index, count, ...newTokens);
}
function insertComments(document, newComments) {
    if (document == null || newComments.length === 0) {
        return;
    }
    const index = sortedIndexBy__default["default"](document.comments, newComments[0], byRange0);
    document.comments.splice(index, 0, ...newComments);
}
function createSimpleToken(type, start, end, value, linesAndColumns) {
    return {
        type,
        range: [start, end],
        loc: {
            start: linesAndColumns.getLocFromIndex(start),
            end: linesAndColumns.getLocFromIndex(end),
        },
        value,
    };
}
function byRange0(x) {
    return x.range[0];
}
function byRange1(x) {
    return x.range[1];
}

function insertError(document, error) {
    if (document == null) {
        return;
    }
    const index = sortedIndexBy__default["default"](document.errors, error, byIndex);
    document.errors.splice(index, 0, error);
}
function byIndex(x) {
    return x.index;
}

function camelize(str) {
    return str.replace(/-(\w)/gu, (_, c) => (c ? c.toUpperCase() : ""));
}

const shorthandSign = /^[.:@#]/u;
const shorthandNameMap = { ":": "bind", ".": "bind", "@": "on", "#": "slot" };
const invalidDynamicArgumentNextChar = /^[\s\r\n=/>]$/u;
function getTagName$1(startTagOrElement, isSFC) {
    return isSFC ? startTagOrElement.rawName : startTagOrElement.name;
}
function parseDirectiveKeyStatically(node, document) {
    const { name: text, rawName: rawText, range: [offset], loc: { start: { column, line }, }, } = node;
    const directiveKey = {
        type: "VDirectiveKey",
        range: node.range,
        loc: node.loc,
        parent: node.parent,
        name: null,
        argument: null,
        modifiers: [],
    };
    let i = 0;
    function createIdentifier(start, end, name) {
        return {
            type: "VIdentifier",
            parent: directiveKey,
            range: [offset + start, offset + end],
            loc: {
                start: { column: column + start, line },
                end: { column: column + end, line },
            },
            name: name || text.slice(start, end),
            rawName: rawText.slice(start, end),
        };
    }
    if (shorthandSign.test(text)) {
        const sign = text[0];
        directiveKey.name = createIdentifier(0, 1, shorthandNameMap[sign]);
        i = 1;
    }
    else {
        const colon = text.indexOf(":");
        if (colon !== -1) {
            directiveKey.name = createIdentifier(0, colon);
            i = colon + 1;
        }
    }
    if (directiveKey.name != null && text[i] === "[") {
        const len = text.slice(i).lastIndexOf("]");
        if (len !== -1) {
            directiveKey.argument = createIdentifier(i, i + len + 1);
            i = i + len + 1 + (text[i + len + 1] === "." ? 1 : 0);
        }
    }
    const modifiers = text
        .slice(i)
        .split(".")
        .map((modifierName) => {
        const modifier = createIdentifier(i, i + modifierName.length);
        if (modifierName === "" && i < text.length) {
            insertError(document, new ParseError(`Unexpected token '${text[i]}'`, undefined, offset + i, line, column + i));
        }
        i += modifierName.length + 1;
        return modifier;
    });
    if (directiveKey.name == null) {
        directiveKey.name = modifiers.shift();
    }
    else if (directiveKey.argument == null && modifiers[0].name !== "") {
        directiveKey.argument = modifiers.shift() || null;
    }
    directiveKey.modifiers = modifiers.filter(isNotEmptyModifier);
    if (directiveKey.name.name === "v-") {
        insertError(document, new ParseError(`Unexpected token '${text[directiveKey.name.range[1] - offset]}'`, undefined, directiveKey.name.range[1], directiveKey.name.loc.end.line, directiveKey.name.loc.end.column));
    }
    if (directiveKey.name.rawName === "." &&
        !directiveKey.modifiers.some(isPropModifier)) {
        const pos = (directiveKey.argument || directiveKey.name).range[1] - offset;
        const propModifier = createIdentifier(pos, pos, "prop");
        directiveKey.modifiers.unshift(propModifier);
    }
    return directiveKey;
}
function isPropModifier(node) {
    return node.name === "prop";
}
function isNotEmptyModifier(node) {
    return node.name !== "";
}
function parseDirectiveKeyTokens(node) {
    const { name, argument, modifiers } = node;
    const shorthand = name.range[1] - name.range[0] === 1;
    const tokens = [];
    if (shorthand) {
        tokens.push({
            type: "Punctuator",
            range: name.range,
            loc: name.loc,
            value: name.rawName,
        });
    }
    else {
        tokens.push({
            type: "HTMLIdentifier",
            range: name.range,
            loc: name.loc,
            value: name.rawName,
        });
        if (argument) {
            tokens.push({
                type: "Punctuator",
                range: [name.range[1], argument.range[0]],
                loc: { start: name.loc.end, end: argument.loc.start },
                value: ":",
            });
        }
    }
    if (argument) {
        tokens.push({
            type: "HTMLIdentifier",
            range: argument.range,
            loc: argument.loc,
            value: argument.rawName,
        });
    }
    let lastNode = argument || name;
    for (const modifier of modifiers) {
        if (modifier.rawName === "") {
            continue;
        }
        tokens.push({
            type: "Punctuator",
            range: [lastNode.range[1], modifier.range[0]],
            loc: { start: lastNode.loc.end, end: modifier.loc.start },
            value: ".",
        }, {
            type: "HTMLIdentifier",
            range: modifier.range,
            loc: modifier.loc,
            value: modifier.rawName,
        });
        lastNode = modifier;
    }
    return tokens;
}
function convertDynamicArgument(node, document, parserOptions, locationCalculator) {
    const { argument } = node;
    if (!(argument != null &&
        argument.type === "VIdentifier" &&
        argument.name.startsWith("[") &&
        argument.name.endsWith("]"))) {
        return;
    }
    const { rawName, range, loc } = argument;
    try {
        const { comments, expression, references, tokens } = parseExpression(rawName.slice(1, -1), locationCalculator.getSubCalculatorAfter(range[0] + 1), parserOptions);
        node.argument = {
            type: "VExpressionContainer",
            range,
            loc,
            parent: node,
            expression,
            references,
        };
        if (expression != null) {
            expression.parent = node.argument;
        }
        tokens.unshift(createSimpleToken("Punctuator", range[0], range[0] + 1, "[", locationCalculator));
        tokens.push(createSimpleToken("Punctuator", range[1] - 1, range[1], "]", locationCalculator));
        replaceTokens(document, node.argument, tokens);
        insertComments(document, comments);
    }
    catch (error) {
        debug("[template] Parse error: %s", error);
        if (ParseError.isParseError(error)) {
            node.argument = {
                type: "VExpressionContainer",
                range,
                loc,
                parent: node,
                expression: null,
                references: [],
            };
            insertError(document, error);
        }
        else {
            throw error;
        }
    }
}
function createDirectiveKey(node, document, parserOptions, locationCalculator) {
    const directiveKey = parseDirectiveKeyStatically(node, document);
    const tokens = parseDirectiveKeyTokens(directiveKey);
    replaceTokens(document, directiveKey, tokens);
    if (directiveKey.name.name.startsWith("v-")) {
        directiveKey.name.name = directiveKey.name.name.slice(2);
    }
    if (directiveKey.name.rawName.startsWith("v-")) {
        directiveKey.name.rawName = directiveKey.name.rawName.slice(2);
    }
    convertDynamicArgument(directiveKey, document, parserOptions, locationCalculator);
    return directiveKey;
}
function parseAttributeValue(code, parserOptions, scriptParserOptions, globalLocationCalculator, node, element, directiveKey) {
    const firstChar = code[node.range[0]];
    const quoted = firstChar === '"' || firstChar === "'";
    const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(node.range[0] + (quoted ? 1 : 0));
    const directiveKind = getStandardDirectiveKind(parserOptions, element, directiveKey);
    let result;
    if (quoted && node.value === "") {
        result = {
            expression: null,
            tokens: [],
            comments: [],
            variables: [],
            references: [],
        };
    }
    else if (directiveKind === "for") {
        result = parseVForExpression(node.value, locationCalculator, parserOptions);
    }
    else if (directiveKind === "on" && directiveKey.argument != null) {
        result = parseVOnExpression(node.value, locationCalculator, parserOptions);
    }
    else if (directiveKind === "slot") {
        result = parseSlotScopeExpression(node.value, locationCalculator, parserOptions);
    }
    else if (directiveKind === "bind") {
        result = parseExpression(node.value, locationCalculator, parserOptions, { allowFilters: true });
    }
    else if (directiveKind === "generic") {
        result = parseGenericExpression(node.value, locationCalculator, scriptParserOptions);
    }
    else {
        result = parseExpression(node.value, locationCalculator, parserOptions);
    }
    if (quoted) {
        result.tokens.unshift(createSimpleToken("Punctuator", node.range[0], node.range[0] + 1, firstChar, globalLocationCalculator));
        result.tokens.push(createSimpleToken("Punctuator", node.range[1] - 1, node.range[1], firstChar, globalLocationCalculator));
    }
    return result;
}
function getStandardDirectiveKind(parserOptions, element, directiveKey) {
    const directiveName = directiveKey.name.name;
    if (directiveName === "for") {
        return "for";
    }
    else if (directiveName === "on") {
        return "on";
    }
    else if (directiveName === "slot" ||
        directiveName === "slot-scope" ||
        (directiveName === "scope" &&
            getTagName$1(element, isSFCFile(parserOptions)) === "template")) {
        return "slot";
    }
    else if (directiveName === "bind") {
        return "bind";
    }
    else if (directiveName === "generic" &&
        element.parent.type === "VDocumentFragment" &&
        getTagName$1(element, isSFCFile(parserOptions)) === "script" &&
        isScriptSetupElement(element) &&
        isTSLang(element)) {
        return "generic";
    }
    return null;
}
function resolveReference(referene, element) {
    let node = element;
    while (node != null && node.type === "VElement") {
        for (const variable of node.variables) {
            if (variable.id.name === referene.id.name) {
                referene.variable = variable;
                variable.references.push(referene);
                return;
            }
        }
        node = node.parent;
    }
}
function convertToDirective(code, parserOptions, scriptParserOptions, locationCalculator, node) {
    debug('[template] convert to directive: %s="%s" %j', node.key.name, node.value && node.value.value, node.range);
    const document = getOwnerDocument(node);
    const directive = node;
    directive.directive = true;
    directive.key = createDirectiveKey(node.key, document, parserOptions, locationCalculator);
    const { argument } = directive.key;
    if (argument &&
        argument.type === "VIdentifier" &&
        argument.name.startsWith("[")) {
        const nextChar = code[argument.range[1]];
        if (nextChar == null || invalidDynamicArgumentNextChar.test(nextChar)) {
            const char = nextChar == null ? "EOF" : JSON.stringify(nextChar).slice(1, -1);
            insertError(document, new ParseError(`Dynamic argument cannot contain the '${char}' character.`, undefined, argument.range[1], argument.loc.end.line, argument.loc.end.column));
        }
    }
    if (node.value == null) {
        if (directive.key.name.name === "bind") {
            convertForVBindSameNameShorthandValue(directive, parserOptions, locationCalculator);
        }
        return;
    }
    try {
        const ret = parseAttributeValue(code, parserOptions, scriptParserOptions, locationCalculator, node.value, node.parent.parent, directive.key);
        directive.value = {
            type: "VExpressionContainer",
            range: node.value.range,
            loc: node.value.loc,
            parent: directive,
            expression: ret.expression,
            references: ret.references,
        };
        if (ret.expression != null) {
            ret.expression.parent = directive.value;
        }
        for (const variable of ret.variables) {
            node.parent.parent.variables.push(variable);
        }
        replaceTokens(document, node.value, ret.tokens);
        insertComments(document, ret.comments);
    }
    catch (err) {
        debug("[template] Parse error: %s", err);
        if (ParseError.isParseError(err)) {
            directive.value = {
                type: "VExpressionContainer",
                range: node.value.range,
                loc: node.value.loc,
                parent: directive,
                expression: null,
                references: [],
            };
            insertError(document, err);
        }
        else {
            throw err;
        }
    }
}
function convertForVBindSameNameShorthandValue(directive, parserOptions, locationCalculator) {
    if (directive.key.name.name !== "bind" ||
        directive.key.argument == null ||
        directive.key.argument.type !== "VIdentifier") {
        return;
    }
    const vId = directive.key.argument;
    const camelName = camelize(vId.rawName);
    let result = null;
    try {
        result = parseScriptFragment(camelName, locationCalculator.getSubCalculatorAfter(vId.range[0]), parserOptions);
    }
    catch (err) {
        debug("[template] Parse error: %s", err);
    }
    if (result == null ||
        result.ast.body.length !== 1 ||
        result.ast.body[0].type !== "ExpressionStatement" ||
        result.ast.body[0].expression.type !== "Identifier") {
        return;
    }
    const id = result.ast.body[0].expression;
    id.range[1] = vId.range[1];
    id.loc.end = Object.assign({}, vId.loc.end);
    if (id.end != null) {
        id.end = vId.end;
    }
    directive.value = {
        type: "VExpressionContainer",
        range: [...vId.range],
        loc: {
            start: Object.assign({}, vId.loc.start),
            end: Object.assign({}, vId.loc.end),
        },
        parent: directive,
        expression: id,
        references: [
            {
                id,
                mode: "r",
                variable: null,
            },
        ],
    };
    id.parent = directive.value;
}
function processMustache(parserOptions, globalLocationCalculator, node, mustache) {
    const range = [
        mustache.startToken.range[1],
        mustache.endToken.range[0],
    ];
    debug("[template] convert mustache {{%s}} %j", mustache.value, range);
    const document = getOwnerDocument(node);
    try {
        const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(range[0]);
        const ret = parseExpression(mustache.value, locationCalculator, parserOptions, { allowEmpty: true, allowFilters: true });
        node.expression = ret.expression || null;
        node.references = ret.references;
        if (ret.expression != null) {
            ret.expression.parent = node;
        }
        replaceTokens(document, { range }, ret.tokens);
        insertComments(document, ret.comments);
    }
    catch (err) {
        debug("[template] Parse error: %s", err);
        if (ParseError.isParseError(err)) {
            insertError(document, err);
        }
        else {
            throw err;
        }
    }
}
function resolveReferences(container) {
    let element = container.parent;
    while (element != null && element.type !== "VElement") {
        element = element.parent;
    }
    if (element != null) {
        for (const reference of container.references) {
            resolveReference(reference, element);
        }
    }
}

const SVG_ATTRIBUTE_NAME_MAP = new Map([
    ["attributename", "attributeName"],
    ["attributetype", "attributeType"],
    ["basefrequency", "baseFrequency"],
    ["baseprofile", "baseProfile"],
    ["calcmode", "calcMode"],
    ["clippathunits", "clipPathUnits"],
    ["diffuseconstant", "diffuseConstant"],
    ["edgemode", "edgeMode"],
    ["filterunits", "filterUnits"],
    ["glyphref", "glyphRef"],
    ["gradienttransform", "gradientTransform"],
    ["gradientunits", "gradientUnits"],
    ["kernelmatrix", "kernelMatrix"],
    ["kernelunitlength", "kernelUnitLength"],
    ["keypoints", "keyPoints"],
    ["keysplines", "keySplines"],
    ["keytimes", "keyTimes"],
    ["lengthadjust", "lengthAdjust"],
    ["limitingconeangle", "limitingConeAngle"],
    ["markerheight", "markerHeight"],
    ["markerunits", "markerUnits"],
    ["markerwidth", "markerWidth"],
    ["maskcontentunits", "maskContentUnits"],
    ["maskunits", "maskUnits"],
    ["numoctaves", "numOctaves"],
    ["pathlength", "pathLength"],
    ["patterncontentunits", "patternContentUnits"],
    ["patterntransform", "patternTransform"],
    ["patternunits", "patternUnits"],
    ["pointsatx", "pointsAtX"],
    ["pointsaty", "pointsAtY"],
    ["pointsatz", "pointsAtZ"],
    ["preservealpha", "preserveAlpha"],
    ["preserveaspectratio", "preserveAspectRatio"],
    ["primitiveunits", "primitiveUnits"],
    ["refx", "refX"],
    ["refy", "refY"],
    ["repeatcount", "repeatCount"],
    ["repeatdur", "repeatDur"],
    ["requiredextensions", "requiredExtensions"],
    ["requiredfeatures", "requiredFeatures"],
    ["specularconstant", "specularConstant"],
    ["specularexponent", "specularExponent"],
    ["spreadmethod", "spreadMethod"],
    ["startoffset", "startOffset"],
    ["stddeviation", "stdDeviation"],
    ["stitchtiles", "stitchTiles"],
    ["surfacescale", "surfaceScale"],
    ["systemlanguage", "systemLanguage"],
    ["tablevalues", "tableValues"],
    ["targetx", "targetX"],
    ["targety", "targetY"],
    ["textlength", "textLength"],
    ["viewbox", "viewBox"],
    ["viewtarget", "viewTarget"],
    ["xchannelselector", "xChannelSelector"],
    ["ychannelselector", "yChannelSelector"],
    ["zoomandpan", "zoomAndPan"],
]);
const MATHML_ATTRIBUTE_NAME_MAP = new Map([
    ["definitionurl", "definitionUrl"]
]);

const HTML_VOID_ELEMENT_TAGS = new Set([
    "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
    "param", "source", "track", "wbr",
]);
const HTML_CAN_BE_LEFT_OPEN_TAGS = new Set([
    "colgroup", "li", "options", "p", "td", "tfoot", "th", "thead",
    "tr", "source",
]);
const HTML_NON_FHRASING_TAGS = new Set([
    "address", "article", "aside", "base", "blockquote", "body", "caption",
    "col", "colgroup", "dd", "details", "dialog", "div", "dl", "dt", "fieldset",
    "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5",
    "h6", "head", "header", "hgroup", "hr", "html", "legend", "li", "menuitem",
    "meta", "optgroup", "option", "param", "rp", "rt", "source", "style",
    "summary", "tbody", "td", "tfoot", "th", "thead", "title", "tr", "track",
]);
const HTML_RCDATA_TAGS = new Set([
    "title", "textarea",
]);
const HTML_RAWTEXT_TAGS = new Set([
    "style", "xmp", "iframe", "noembed", "noframes", "noscript", "script",
]);
const SVG_TAGS$1 = new Set([
    "a", "altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor",
    "animateMotion", "animateTransform", "animation", "audio", "canvas",
    "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "discard",
    "ellipse", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite",
    "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap",
    "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB",
    "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode",
    "feMorphology", "feOffset", "fePointLight", "feSpecularLighting",
    "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face",
    "font-face-format", "font-face-name", "font-face-src", "font-face-uri",
    "foreignObject", "g", "glyph", "glyphRef", "handler", "hatch", "hatchpath",
    "hkern", "iframe", "image", "line", "linearGradient", "listener", "marker",
    "mask", "mesh", "meshgradient", "meshpatch", "meshrow", "metadata",
    "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline",
    "prefetch", "radialGradient", "rect", "script", "set", "solidColor",
    "solidcolor", "stop", "style", "svg", "switch", "symbol", "tbreak", "text",
    "textArea", "textPath", "title", "tref", "tspan", "unknown", "use", "video",
    "view", "vkern",
]);
const SVG_ELEMENT_NAME_MAP = new Map();
for (const name of SVG_TAGS$1) {
    if (/[A-Z]/.test(name)) {
        SVG_ELEMENT_NAME_MAP.set(name.toLowerCase(), name);
    }
}

const DUMMY_PARENT$1 = Object.freeze({});
function concat(text, token) {
    return text + token.value;
}
class IntermediateTokenizer {
    constructor(tokenizer) {
        this.tokenizer = tokenizer;
        this.currentToken = null;
        this.attribute = null;
        this.attributeNames = new Set();
        this.expressionStartToken = null;
        this.expressionTokens = [];
        this.tokens = [];
        this.comments = [];
    }
    get text() {
        return this.tokenizer.text;
    }
    get errors() {
        return this.tokenizer.errors;
    }
    get state() {
        return this.tokenizer.state;
    }
    set state(value) {
        this.tokenizer.state = value;
    }
    get namespace() {
        return this.tokenizer.namespace;
    }
    set namespace(value) {
        this.tokenizer.namespace = value;
    }
    get expressionEnabled() {
        return this.tokenizer.expressionEnabled;
    }
    set expressionEnabled(value) {
        this.tokenizer.expressionEnabled = value;
    }
    nextToken() {
        let token = null;
        let result = null;
        while (result == null && (token = this.tokenizer.nextToken()) != null) {
            result = this[token.type](token);
        }
        if (result == null && token == null && this.currentToken != null) {
            result = this.commit();
        }
        return result;
    }
    commit() {
        assert__default["default"](this.currentToken != null || this.expressionStartToken != null);
        let token = this.currentToken;
        this.currentToken = null;
        this.attribute = null;
        if (this.expressionStartToken != null) {
            const start = this.expressionStartToken;
            const end = last__default["default"](this.expressionTokens) || start;
            const value = this.expressionTokens.reduce(concat, start.value);
            this.expressionStartToken = null;
            this.expressionTokens = [];
            if (token == null) {
                token = {
                    type: "Text",
                    range: [start.range[0], end.range[1]],
                    loc: { start: start.loc.start, end: end.loc.end },
                    value,
                };
            }
            else if (token.type === "Text") {
                token.range[1] = end.range[1];
                token.loc.end = end.loc.end;
                token.value += value;
            }
            else {
                throw new Error("unreachable");
            }
        }
        return token;
    }
    reportParseError(token, code) {
        const error = ParseError.fromCode(code, token.range[0], token.loc.start.line, token.loc.start.column);
        this.errors.push(error);
        debug("[html] syntax error:", error.message);
    }
    processComment(token) {
        this.comments.push(token);
        if (this.currentToken != null && this.currentToken.type === "Text") {
            return this.commit();
        }
        return null;
    }
    processText(token) {
        this.tokens.push(token);
        let result = null;
        if (this.expressionStartToken != null) {
            const lastToken = last__default["default"](this.expressionTokens) || this.expressionStartToken;
            if (lastToken.range[1] === token.range[0]) {
                this.expressionTokens.push(token);
                return null;
            }
            result = this.commit();
        }
        else if (this.currentToken != null) {
            if (this.currentToken.type === "Text" &&
                this.currentToken.range[1] === token.range[0]) {
                this.currentToken.value += token.value;
                this.currentToken.range[1] = token.range[1];
                this.currentToken.loc.end = token.loc.end;
                return null;
            }
            result = this.commit();
        }
        assert__default["default"](this.currentToken == null);
        this.currentToken = {
            type: "Text",
            range: [token.range[0], token.range[1]],
            loc: { start: token.loc.start, end: token.loc.end },
            value: token.value,
        };
        return result;
    }
    HTMLAssociation(token) {
        this.tokens.push(token);
        if (this.attribute != null) {
            this.attribute.range[1] = token.range[1];
            this.attribute.loc.end = token.loc.end;
            if (this.currentToken == null ||
                this.currentToken.type !== "StartTag") {
                throw new Error("unreachable");
            }
            this.currentToken.range[1] = token.range[1];
            this.currentToken.loc.end = token.loc.end;
        }
        return null;
    }
    HTMLBogusComment(token) {
        return this.processComment(token);
    }
    HTMLCDataText(token) {
        return this.processText(token);
    }
    HTMLComment(token) {
        return this.processComment(token);
    }
    HTMLEndTagOpen(token) {
        this.tokens.push(token);
        let result = null;
        if (this.currentToken != null || this.expressionStartToken != null) {
            result = this.commit();
        }
        this.currentToken = {
            type: "EndTag",
            range: [token.range[0], token.range[1]],
            loc: { start: token.loc.start, end: token.loc.end },
            name: token.value,
        };
        return result;
    }
    HTMLIdentifier(token) {
        this.tokens.push(token);
        if (this.currentToken == null ||
            this.currentToken.type === "Text" ||
            this.currentToken.type === "Mustache") {
            throw new Error("unreachable");
        }
        if (this.currentToken.type === "EndTag") {
            this.reportParseError(token, "end-tag-with-attributes");
            return null;
        }
        if (this.attributeNames.has(token.value)) {
            this.reportParseError(token, "duplicate-attribute");
        }
        this.attributeNames.add(token.value);
        this.attribute = {
            type: "VAttribute",
            range: [token.range[0], token.range[1]],
            loc: { start: token.loc.start, end: token.loc.end },
            parent: DUMMY_PARENT$1,
            directive: false,
            key: {
                type: "VIdentifier",
                range: [token.range[0], token.range[1]],
                loc: { start: token.loc.start, end: token.loc.end },
                parent: DUMMY_PARENT$1,
                name: token.value,
                rawName: this.text.slice(token.range[0], token.range[1]),
            },
            value: null,
        };
        this.attribute.key.parent = this.attribute;
        this.currentToken.range[1] = token.range[1];
        this.currentToken.loc.end = token.loc.end;
        this.currentToken.attributes.push(this.attribute);
        return null;
    }
    HTMLLiteral(token) {
        this.tokens.push(token);
        if (this.attribute != null) {
            this.attribute.range[1] = token.range[1];
            this.attribute.loc.end = token.loc.end;
            this.attribute.value = {
                type: "VLiteral",
                range: [token.range[0], token.range[1]],
                loc: { start: token.loc.start, end: token.loc.end },
                parent: this.attribute,
                value: token.value,
            };
            if (this.currentToken == null ||
                this.currentToken.type !== "StartTag") {
                throw new Error("unreachable");
            }
            this.currentToken.range[1] = token.range[1];
            this.currentToken.loc.end = token.loc.end;
        }
        return null;
    }
    HTMLRCDataText(token) {
        return this.processText(token);
    }
    HTMLRawText(token) {
        return this.processText(token);
    }
    HTMLSelfClosingTagClose(token) {
        this.tokens.push(token);
        if (this.currentToken == null || this.currentToken.type === "Text") {
            throw new Error("unreachable");
        }
        if (this.currentToken.type === "StartTag") {
            this.currentToken.selfClosing = true;
        }
        else {
            this.reportParseError(token, "end-tag-with-trailing-solidus");
        }
        this.currentToken.range[1] = token.range[1];
        this.currentToken.loc.end = token.loc.end;
        return this.commit();
    }
    HTMLTagClose(token) {
        this.tokens.push(token);
        if (this.currentToken == null || this.currentToken.type === "Text") {
            throw new Error("unreachable");
        }
        this.currentToken.range[1] = token.range[1];
        this.currentToken.loc.end = token.loc.end;
        return this.commit();
    }
    HTMLTagOpen(token) {
        this.tokens.push(token);
        let result = null;
        if (this.currentToken != null || this.expressionStartToken != null) {
            result = this.commit();
        }
        this.currentToken = {
            type: "StartTag",
            range: [token.range[0], token.range[1]],
            loc: { start: token.loc.start, end: token.loc.end },
            name: token.value,
            rawName: this.text.slice(token.range[0] + 1, token.range[1]),
            selfClosing: false,
            attributes: [],
        };
        this.attribute = null;
        this.attributeNames.clear();
        return result;
    }
    HTMLText(token) {
        return this.processText(token);
    }
    HTMLWhitespace(token) {
        return this.processText(token);
    }
    VExpressionStart(token) {
        if (this.expressionStartToken != null) {
            return this.processText(token);
        }
        const separated = this.currentToken != null &&
            this.currentToken.range[1] !== token.range[0];
        const result = separated ? this.commit() : null;
        this.tokens.push(token);
        this.expressionStartToken = token;
        return result;
    }
    VExpressionEnd(token) {
        if (this.expressionStartToken == null) {
            return this.processText(token);
        }
        const start = this.expressionStartToken;
        const end = last__default["default"](this.expressionTokens) || start;
        if (token.range[0] === start.range[1]) {
            this.tokens.pop();
            this.expressionStartToken = null;
            const result = this.processText(start);
            this.processText(token);
            return result;
        }
        if (end.range[1] !== token.range[0]) {
            const result = this.commit();
            this.processText(token);
            return result;
        }
        const value = this.expressionTokens.reduce(concat, "");
        this.tokens.push(token);
        this.expressionStartToken = null;
        this.expressionTokens = [];
        const result = this.currentToken != null ? this.commit() : null;
        this.currentToken = {
            type: "Mustache",
            range: [start.range[0], token.range[1]],
            loc: { start: start.loc.start, end: token.loc.end },
            value,
            startToken: start,
            endToken: token,
        };
        return result || this.commit();
    }
}

const DIRECTIVE_NAME = /^(?:v-|[.:@#]).*[^.:@#]$/u;
const DT_DD = /^d[dt]$/u;
const DUMMY_PARENT = Object.freeze({});
function getTagName(startTagOrElement, isSFC) {
    return isSFC ? startTagOrElement.rawName : startTagOrElement.name;
}
function isMathMLIntegrationPoint(element, isSFC) {
    if (element.namespace === NS.MathML) {
        const name = getTagName(element, isSFC);
        return (name === "mi" ||
            name === "mo" ||
            name === "mn" ||
            name === "ms" ||
            name === "mtext");
    }
    return false;
}
function isHTMLIntegrationPoint(element, isSFC) {
    if (element.namespace === NS.MathML) {
        return (getTagName(element, isSFC) === "annotation-xml" &&
            element.startTag.attributes.some((a) => a.directive === false &&
                a.key.name === "encoding" &&
                a.value != null &&
                (a.value.value === "text/html" ||
                    a.value.value === "application/xhtml+xml")));
    }
    if (element.namespace === NS.SVG) {
        const name = getTagName(element, isSFC);
        return name === "foreignObject" || name === "desc" || name === "title";
    }
    return false;
}
function adjustElementName(name, namespace) {
    if (namespace === NS.SVG) {
        return SVG_ELEMENT_NAME_MAP.get(name) || name;
    }
    return name;
}
function adjustAttributeName(name, namespace) {
    if (namespace === NS.SVG) {
        return SVG_ATTRIBUTE_NAME_MAP.get(name) || name;
    }
    if (namespace === NS.MathML) {
        return MATHML_ATTRIBUTE_NAME_MAP.get(name) || name;
    }
    return name;
}
function propagateEndLocation(node) {
    const lastChild = (node.type === "VElement" ? node.endTag : null) || last__default["default"](node.children);
    if (lastChild != null) {
        node.range[1] = lastChild.range[1];
        node.loc.end = lastChild.loc.end;
    }
}
class Parser {
    constructor(tokenizer, parserOptions) {
        this.postProcessesForScript = [];
        this.tokenizer = new IntermediateTokenizer(tokenizer);
        this.locationCalculator = new LocationCalculatorForHtml(tokenizer.gaps, tokenizer.lineTerminators);
        this.baseParserOptions = parserOptions;
        this.isSFC = isSFCFile(parserOptions);
        this.document = {
            type: "VDocumentFragment",
            range: [0, 0],
            loc: {
                start: { line: 1, column: 0 },
                end: { line: 1, column: 0 },
            },
            parent: null,
            children: [],
            tokens: this.tokens,
            comments: this.comments,
            errors: this.errors,
        };
        this.elementStack = [];
        this.vPreElement = null;
        this.postProcessesForScript = [];
    }
    get text() {
        return this.tokenizer.text;
    }
    get tokens() {
        return this.tokenizer.tokens;
    }
    get comments() {
        return this.tokenizer.comments;
    }
    get errors() {
        return this.tokenizer.errors;
    }
    get namespace() {
        return this.tokenizer.namespace;
    }
    set namespace(value) {
        this.tokenizer.namespace = value;
    }
    get expressionEnabled() {
        return this.tokenizer.expressionEnabled;
    }
    set expressionEnabled(value) {
        this.tokenizer.expressionEnabled = value;
    }
    get currentNode() {
        return last__default["default"](this.elementStack) || this.document;
    }
    get isInVPreElement() {
        return this.vPreElement != null;
    }
    parse() {
        let token = null;
        while ((token = this.tokenizer.nextToken()) != null) {
            this[token.type](token);
        }
        this.popElementStackUntil(0);
        propagateEndLocation(this.document);
        const doc = this.document;
        const htmlParserOptions = Object.assign(Object.assign({}, this.baseParserOptions), { parser: getScriptParser(this.baseParserOptions.parser, function* () {
                yield "<template>";
                yield getParserLangFromSFC(doc);
            }) });
        const scriptParserOptions = Object.assign(Object.assign({}, this.baseParserOptions), { parser: getScriptParser(this.baseParserOptions.parser, () => getParserLangFromSFC(doc)) });
        for (const proc of this.postProcessesForScript) {
            proc(htmlParserOptions, scriptParserOptions);
        }
        this.postProcessesForScript = [];
        return doc;
    }
    reportParseError(token, code) {
        const error = ParseError.fromCode(code, token.range[0], token.loc.start.line, token.loc.start.column);
        this.errors.push(error);
        debug("[html] syntax error:", error.message);
    }
    popElementStack() {
        assert__default["default"](this.elementStack.length >= 1);
        const element = this.elementStack.pop();
        propagateEndLocation(element);
        const current = this.currentNode;
        this.namespace =
            current.type === "VElement" ? current.namespace : NS.HTML;
        if (this.vPreElement === element) {
            this.vPreElement = null;
            this.expressionEnabled = true;
        }
        if (this.elementStack.length === 0) {
            this.expressionEnabled = false;
        }
    }
    popElementStackUntil(index) {
        while (this.elementStack.length > index) {
            this.popElementStack();
        }
    }
    getTagName(startTagOrElement) {
        return getTagName(startTagOrElement, this.isSFC);
    }
    detectNamespace(token) {
        const name = this.getTagName(token);
        let ns = this.namespace;
        if (ns === NS.MathML || ns === NS.SVG) {
            const element = this.currentNode;
            if (element.type === "VElement") {
                if (element.namespace === NS.MathML &&
                    this.getTagName(element) === "annotation-xml" &&
                    name === "svg") {
                    return NS.SVG;
                }
                if (isHTMLIntegrationPoint(element, this.isSFC) ||
                    (isMathMLIntegrationPoint(element, this.isSFC) &&
                        name !== "mglyph" &&
                        name !== "malignmark")) {
                    ns = NS.HTML;
                }
            }
        }
        if (ns === NS.HTML) {
            if (name === "svg") {
                return NS.SVG;
            }
            if (name === "math") {
                return NS.MathML;
            }
        }
        if (name === "template") {
            const xmlns = token.attributes.find((a) => a.key.name === "xmlns");
            const value = xmlns && xmlns.value && xmlns.value.value;
            if (value === NS.HTML || value === NS.MathML || value === NS.SVG) {
                return value;
            }
        }
        return ns;
    }
    closeCurrentElementIfNecessary(token) {
        const element = this.currentNode;
        if (element.type !== "VElement") {
            return;
        }
        const name = this.getTagName(token);
        const elementName = this.getTagName(element);
        if (elementName === "p" && HTML_NON_FHRASING_TAGS.has(name)) {
            this.popElementStack();
        }
        if (elementName === name && HTML_CAN_BE_LEFT_OPEN_TAGS.has(name)) {
            this.popElementStack();
        }
        if (DT_DD.test(elementName) && DT_DD.test(name)) {
            this.popElementStack();
        }
    }
    processAttribute(node, namespace) {
        if (this.needConvertToDirective(node)) {
            this.postProcessesForScript.push((parserOptions, scriptParserOptions) => {
                convertToDirective(this.text, parserOptions, scriptParserOptions, this.locationCalculator, node);
            });
            return;
        }
        node.key.name = adjustAttributeName(node.key.name, namespace);
        const key = this.getTagName(node.key);
        const value = node.value && node.value.value;
        if (key === "xmlns" && value !== namespace) {
            this.reportParseError(node, "x-invalid-namespace");
        }
        else if (key === "xmlns:xlink" && value !== NS.XLink) {
            this.reportParseError(node, "x-invalid-namespace");
        }
    }
    needConvertToDirective(node) {
        const element = node.parent.parent;
        const tagName = this.getTagName(element);
        const attrName = this.getTagName(node.key);
        if (attrName === "generic" &&
            element.parent.type === "VDocumentFragment" &&
            isScriptSetupElement(element) &&
            isTSLang(element)) {
            return true;
        }
        const expressionEnabled = this.expressionEnabled ||
            (attrName === "v-pre" && !this.isInVPreElement);
        if (!expressionEnabled) {
            return false;
        }
        return (DIRECTIVE_NAME.test(attrName) ||
            attrName === "slot-scope" ||
            (tagName === "template" && attrName === "scope"));
    }
    processTemplateText(token, templateTokenizerOption) {
        const TemplateTokenizer = typeof templateTokenizerOption === "function"
            ? templateTokenizerOption
            :
                require(templateTokenizerOption);
        const templateTokenizer = new TemplateTokenizer(token.value, this.text, {
            startingLine: token.loc.start.line,
            startingColumn: token.loc.start.column,
        });
        const rootTokenizer = this.tokenizer;
        this.tokenizer = templateTokenizer;
        let templateToken = null;
        while ((templateToken = templateTokenizer.nextToken()) != null) {
            this[templateToken.type](templateToken);
        }
        this.tokenizer = rootTokenizer;
        const index = sortedIndexBy__default["default"](this.tokenizer.tokens, token, (x) => x.range[0]);
        const count = sortedLastIndexBy__default["default"](this.tokenizer.tokens, token, (x) => x.range[1]) -
            index;
        this.tokenizer.tokens.splice(index, count, ...templateTokenizer.tokens);
        this.tokenizer.comments.push(...templateTokenizer.comments);
        this.tokenizer.errors.push(...templateTokenizer.errors);
    }
    StartTag(token) {
        var _a;
        debug("[html] StartTag %j", token);
        this.closeCurrentElementIfNecessary(token);
        const parent = this.currentNode;
        const namespace = this.detectNamespace(token);
        const element = {
            type: "VElement",
            range: [token.range[0], token.range[1]],
            loc: { start: token.loc.start, end: token.loc.end },
            parent,
            name: adjustElementName(token.name, namespace),
            rawName: token.rawName,
            namespace,
            startTag: {
                type: "VStartTag",
                range: token.range,
                loc: token.loc,
                parent: DUMMY_PARENT,
                selfClosing: token.selfClosing,
                attributes: token.attributes,
            },
            children: [],
            endTag: null,
            variables: [],
        };
        const hasVPre = !this.isInVPreElement &&
            token.attributes.some((a) => this.getTagName(a.key) === "v-pre");
        if (hasVPre) {
            this.expressionEnabled = false;
        }
        parent.children.push(element);
        element.startTag.parent = element;
        for (const attribute of token.attributes) {
            attribute.parent = element.startTag;
            this.processAttribute(attribute, namespace);
        }
        this.postProcessesForScript.push(() => {
            for (const attribute of element.startTag.attributes) {
                if (attribute.directive) {
                    if (attribute.key.argument != null &&
                        attribute.key.argument.type === "VExpressionContainer") {
                        resolveReferences(attribute.key.argument);
                    }
                    if (attribute.value != null) {
                        resolveReferences(attribute.value);
                    }
                }
            }
        });
        const isVoid = namespace === NS.HTML &&
            HTML_VOID_ELEMENT_TAGS.has(this.getTagName(element));
        if (token.selfClosing && !isVoid && namespace === NS.HTML) {
            this.reportParseError(token, "non-void-html-element-start-tag-with-trailing-solidus");
        }
        if (token.selfClosing || isVoid) {
            this.expressionEnabled = !this.isInVPreElement;
            return;
        }
        this.elementStack.push(element);
        if (hasVPre) {
            assert__default["default"](this.vPreElement === null);
            this.vPreElement = element;
        }
        this.namespace = namespace;
        if (namespace === NS.HTML) {
            const elementName = this.getTagName(element);
            if (element.parent.type === "VDocumentFragment") {
                const langAttr = element.startTag.attributes.find((a) => !a.directive && a.key.name === "lang"