5431 lines
244 KiB
JavaScript
5431 lines
244 KiB
JavaScript
|
/**
|
||
|
* @author Toru Nagashima <https://github.com/mysticatea>
|
||
|
* See LICENSE file in root directory for full license.
|
||
|
*/
|
||
|
'use strict';
|
||
|
|
||
|
Object.defineProperty(exports, '__esModule', { value: true });
|
||
|
|
||
|
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
||
|
|
||
|
var path = require('path');
|
||
|
var path__default = _interopDefault(path);
|
||
|
var Evk = _interopDefault(require('eslint-visitor-keys'));
|
||
|
var sortedLastIndex = _interopDefault(require('lodash/sortedLastIndex'));
|
||
|
var assert = _interopDefault(require('assert'));
|
||
|
var last = _interopDefault(require('lodash/last'));
|
||
|
var findLastIndex = _interopDefault(require('lodash/findLastIndex'));
|
||
|
var debugFactory = _interopDefault(require('debug'));
|
||
|
var first = _interopDefault(require('lodash/first'));
|
||
|
var sortedIndexBy = _interopDefault(require('lodash/sortedIndexBy'));
|
||
|
var escope = _interopDefault(require('eslint-scope'));
|
||
|
var Module = _interopDefault(require('module'));
|
||
|
var semver = require('semver');
|
||
|
var dependencyEspree = require('espree');
|
||
|
var sortedLastIndexBy = _interopDefault(require('lodash/sortedLastIndexBy'));
|
||
|
var EventEmitter = _interopDefault(require('events'));
|
||
|
var esquery = _interopDefault(require('esquery'));
|
||
|
var union = _interopDefault(require('lodash/union'));
|
||
|
var intersection = _interopDefault(require('lodash/intersection'));
|
||
|
var memoize = _interopDefault(require('lodash/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");
|
||
|
}
|
||
|
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 (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.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(this.ltOffsets, index) + 1;
|
||
|
const column = index - (line === 1 ? 0 : this.ltOffsets[line - 2]);
|
||
|
return { line, column };
|
||
|
}
|
||
|
}
|
||
|
|
||
|
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(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(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("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 isSFCFile(parserOptions) {
|
||
|
if (parserOptions.filePath === "<input>") {
|
||
|
return true;
|
||
|
}
|
||
|
return path.extname(parserOptions.filePath || "unknown.vue") === ".vue";
|
||
|
}
|
||
|
function getScriptParser(parser, getParserLang) {
|
||
|
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") {
|
||
|
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.createRequire ||
|
||
|
Module.createRequireFromPath ||
|
||
|
((modname) => {
|
||
|
const mod = new Module(modname);
|
||
|
mod.filename = modname;
|
||
|
mod.paths = Module._nodeModulePaths(path__default.dirname(modname));
|
||
|
mod._compile("module.exports = require;", modname);
|
||
|
return mod.exports;
|
||
|
});
|
||
|
|
||
|
function isLinterPath(p) {
|
||
|
return (p.includes(`eslint${path__default.sep}lib${path__default.sep}linter${path__default.sep}linter.js`) ||
|
||
|
p.includes(`eslint${path__default.sep}lib${path__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.version)) {
|
||
|
escopeCache = escope;
|
||
|
}
|
||
|
}
|
||
|
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.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;
|
||
|
}
|
||
|
}
|
||
|
return espreeCache;
|
||
|
}
|
||
|
function getNewestEspree() {
|
||
|
let newest = dependencyEspree;
|
||
|
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();
|
||
|
return (_a = getDefault === null || getDefault === void 0 ? void 0 : getDefault(defVer)) !== null && _a !== void 0 ? _a : defVer;
|
||
|
}
|
||
|
return normalizeEcmaVersion(parserOptions.ecmaVersion);
|
||
|
}
|
||
|
function getDefaultEcmaVersion() {
|
||
|
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,
|
||
|
};
|
||
|
Object.defineProperty(ret, "variable", { enumerable: false });
|
||
|
return ret;
|
||
|
}
|
||
|
function transformVariable(variable) {
|
||
|
const ret = {
|
||
|
id: variable.defs[0].name,
|
||
|
kind: variable.scope.type === "for" ? "v-for" : "scope",
|
||
|
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 analyze(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.globalScope;
|
||
|
}
|
||
|
function analyzeExternalReferences(ast, parserOptions) {
|
||
|
const scope = analyze(ast, parserOptions);
|
||
|
return scope.through.filter(isUnique).map(transformReference);
|
||
|
}
|
||
|
function analyzeVariablesAndExternalReferences(ast, parserOptions) {
|
||
|
const scope = analyze(ast, parserOptions);
|
||
|
return {
|
||
|
variables: getForScope(scope)
|
||
|
.variables.filter(hasDefinition)
|
||
|
.map(transformVariable),
|
||
|
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$1);
|
||
|
return Object.assign(Object.assign({}, parserOptions), { ecmaVersion: espreeEcmaVersion });
|
||
|
}
|
||
|
function getDefaultEcmaVersion$1(def) {
|
||
|
if (semver.lte("8.0.0", getEspreeFromUser().version)) {
|
||
|
return getEspreeFromUser().latestEcmaVersion;
|
||
|
}
|
||
|
return Math.max(def, DEFAULT_ECMA_VERSION);
|
||
|
}
|
||
|
|
||
|
const ALIAS_ITERATOR = /^([\s\S]*?(?:\s|\)))(\bin\b|\bof\b)([\s\S]*)$/u;
|
||
|
const PARENS = /^(\s*\()([\s\S]*?)(\)\s*)$/u;
|
||
|
const DUMMY_PARENT = {};
|
||
|
const IS_FUNCTION_EXPRESSION = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\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(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) {
|
||
|
try {
|
||
|
const result = parseScript(code, parserOptions);
|
||
|
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 ast = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions).ast;
|
||
|
const tokens = ast.tokens || [];
|
||
|
const comments = ast.comments || [];
|
||
|
const references = analyzeExternalReferences(ast, 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 { ast } = parseScriptFragment(`0${argsCode}`, locationCalculator
|
||
|
.getSubCalculatorAfter(paren)
|
||
|
.getSubCalculatorShift(-1), parserOptions);
|
||
|
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(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(ast, parserOptions));
|
||
|
}
|
||
|
const firstToken = tokens[0];
|
||
|
const lastToken = last(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(code, parserOptions) {
|
||
|
const parser = typeof parserOptions.parser === "string"
|
||
|
? loadParser(parserOptions.parser)
|
||
|
: getEspreeFromEcmaVersion(parserOptions.ecmaVersion);
|
||
|
const result = typeof parser.parseForESLint === "function"
|
||
|
? parser.parseForESLint(code, parserOptions)
|
||
|
: parser.parse(code, parserOptions);
|
||
|
if (result.ast != null) {
|
||
|
return result;
|
||
|
}
|
||
|
return { ast: result };
|
||
|
}
|
||
|
function parseScriptElement(node, globalLocationCalculator, originalParserOptions) {
|
||
|
const parserOptions = isScriptSetupElement(node)
|
||
|
? getScriptSetupParserOptions(originalParserOptions)
|
||
|
: Object.assign(Object.assign({}, originalParserOptions), { ecmaVersion: originalParserOptions.ecmaVersion || DEFAULT_ECMA_VERSION });
|
||
|
const text = node.children[0];
|
||
|
const { code, offset } = text != null && text.type === "VText"
|
||
|
? { code: text.value, offset: text.range[0] }
|
||
|
: { code: "", offset: node.startTag.range[1] };
|
||
|
const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(offset);
|
||
|
const result = parseScriptFragment(code, locationCalculator, parserOptions);
|
||
|
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(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 ast = parseScriptFragment(`for(let ${processed.aliasesWithBrackets}${processed.delimiter}${processed.iterator});`, locationCalculator.getSubCalculatorShift(processed.hasParens ? -8 : -9), parserOptions).ast;
|
||
|
const tokens = ast.tokens || [];
|
||
|
const comments = ast.comments || [];
|
||
|
const scope = analyzeVariablesAndExternalReferences(ast, 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,
|
||
|
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(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(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,
|
||
|
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 ast = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions).ast;
|
||
|
const tokens = ast.tokens || [];
|
||
|
const comments = ast.comments || [];
|
||
|
const variables = analyzeExternalReferences(ast, 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 ast = parseScriptFragment(`0(${code})`, locationCalculator.getSubCalculatorShift(-2), parserOptions).ast;
|
||
|
const tokens = ast.tokens || [];
|
||
|
const comments = ast.comments || [];
|
||
|
const references = analyzeExternalReferences(ast, 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 ast = parseScriptFragment(`void function($event){${code}}`, locationCalculator.getSubCalculatorShift(-22), parserOptions).ast;
|
||
|
const references = analyzeExternalReferences(ast, parserOptions);
|
||
|
const outermostStatement = ast.body[0];
|
||
|
const functionDecl = outermostStatement.expression.argument;
|
||
|
const block = functionDecl.body;
|
||
|
const body = block.body;
|
||
|
const firstStatement = first(body);
|
||
|
const lastStatement = last(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,
|
||
|
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 ast = parseScriptFragment(`void function(${code}) {}`, locationCalculator.getSubCalculatorShift(-14), parserOptions).ast;
|
||
|
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(ast, parserOptions);
|
||
|
const references = scope.references;
|
||
|
const variables = scope.variables;
|
||
|
const firstParam = first(params);
|
||
|
const lastParam = last(params);
|
||
|
const expression = {
|
||
|
type: "VSlotScopeExpression",
|
||
|
range: [firstParam.range[0], lastParam.range[1]],
|
||
|
loc: { start: firstParam.loc.start, end: lastParam.loc.end },
|
||
|
parent: DUMMY_PARENT,
|
||
|
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 replaceTokens(document, node, newTokens) {
|
||
|
if (document == null) {
|
||
|
return;
|
||
|
}
|
||
|
const index = sortedIndexBy(document.tokens, node, byRange0);
|
||
|
const count = sortedLastIndexBy(document.tokens, node, byRange1) - index;
|
||
|
document.tokens.splice(index, count, ...newTokens);
|
||
|
}
|
||
|
function replaceAndSplitTokens(document, node, newTokens) {
|
||
|
if (document == null) {
|
||
|
return;
|
||
|
}
|
||
|
const index = sortedIndexBy(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(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(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(document.errors, error, byIndex);
|
||
|
document.errors.splice(index, 0, error);
|
||
|
}
|
||
|
function byIndex(x) {
|
||
|
return x.index;
|
||
|
}
|
||
|
|
||
|
const shorthandSign = /^[.:@#]/u;
|
||
|
const shorthandNameMap = { ":": "bind", ".": "bind", "@": "on", "#": "slot" };
|
||
|
const invalidDynamicArgumentNextChar = /^[\s\r\n=/>]$/u;
|
||
|
function getTagName(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, globalLocationCalculator, node, tagName, directiveKey) {
|
||
|
const firstChar = code[node.range[0]];
|
||
|
const quoted = firstChar === '"' || firstChar === "'";
|
||
|
const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(node.range[0] + (quoted ? 1 : 0));
|
||
|
const directiveName = directiveKey.name.name;
|
||
|
let result;
|
||
|
if (quoted && node.value === "") {
|
||
|
result = {
|
||
|
expression: null,
|
||
|
tokens: [],
|
||
|
comments: [],
|
||
|
variables: [],
|
||
|
references: [],
|
||
|
};
|
||
|
}
|
||
|
else if (directiveName === "for") {
|
||
|
result = parseVForExpression(node.value, locationCalculator, parserOptions);
|
||
|
}
|
||
|
else if (directiveName === "on" && directiveKey.argument != null) {
|
||
|
result = parseVOnExpression(node.value, locationCalculator, parserOptions);
|
||
|
}
|
||
|
else if (directiveName === "slot" ||
|
||
|
directiveName === "slot-scope" ||
|
||
|
(tagName === "template" && directiveName === "scope")) {
|
||
|
result = parseSlotScopeExpression(node.value, locationCalculator, parserOptions);
|
||
|
}
|
||
|
else if (directiveName === "bind") {
|
||
|
result = parseExpression(node.value, locationCalculator, parserOptions, { allowFilters: true });
|
||
|
}
|
||
|
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 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, 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) {
|
||
|
return;
|
||
|
}
|
||
|
try {
|
||
|
const ret = parseAttributeValue(code, parserOptions, locationCalculator, node.value, getTagName(node.parent.parent, isSFCFile(parserOptions)), 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 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 = 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) {
|
||
|
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(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(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(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(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(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$2 = Object.freeze({});
|
||
|
function getTagName$1(startTagOrElement, isSFC) {
|
||
|
return isSFC ? startTagOrElement.rawName : startTagOrElement.name;
|
||
|
}
|
||
|
function isMathMLIntegrationPoint(element, isSFC) {
|
||
|
if (element.namespace === NS.MathML) {
|
||
|
const name = getTagName$1(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$1(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$1(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(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(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 parserOptions = Object.assign(Object.assign({}, this.baseParserOptions), { parser: getScriptParser(this.baseParserOptions.parser, function* () {
|
||
|
yield "<template>";
|
||
|
yield getParserLangFromSFC(doc);
|
||
|
}) });
|
||
|
for (const proc of this.postProcessesForScript) {
|
||
|
proc(parserOptions);
|
||
|
}
|
||
|
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(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$1(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) {
|
||
|
const tagName = this.getTagName(node.parent.parent);
|
||
|
const attrName = this.getTagName(node.key);
|
||
|
if ((this.expressionEnabled ||
|
||
|
(attrName === "v-pre" && !this.isInVPreElement)) &&
|
||
|
(DIRECTIVE_NAME.test(attrName) ||
|
||
|
attrName === "slot-scope" ||
|
||
|
(tagName === "template" && attrName === "scope"))) {
|
||
|
this.postProcessesForScript.push((parserOptions) => {
|
||
|
convertToDirective(this.text, parserOptions, 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");
|
||
|
}
|
||
|
}
|
||
|
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$2,
|
||
|
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(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");
|
||
|
const lang = (_a = langAttr === null || langAttr === void 0 ? void 0 : langAttr.value) === null || _a === void 0 ? void 0 : _a.value;
|
||
|
if (elementName === "template") {
|
||
|
if (lang && lang !== "html") {
|
||
|
this.tokenizer.state = "RAWTEXT";
|
||
|
}
|
||
|
this.expressionEnabled = true;
|
||
|
}
|
||
|
else if (this.isSFC) {
|
||
|
if (!lang || lang !== "html") {
|
||
|
this.tokenizer.state = "RAWTEXT";
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
if (HTML_RCDATA_TAGS.has(elementName)) {
|
||
|
this.tokenizer.state = "RCDATA";
|
||
|
}
|
||
|
if (HTML_RAWTEXT_TAGS.has(elementName)) {
|
||
|
this.tokenizer.state = "RAWTEXT";
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
if (HTML_RCDATA_TAGS.has(elementName)) {
|
||
|
this.tokenizer.state = "RCDATA";
|
||
|
}
|
||
|
if (HTML_RAWTEXT_TAGS.has(elementName)) {
|
||
|
this.tokenizer.state = "RAWTEXT";
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
EndTag(token) {
|
||
|
debug("[html] EndTag %j", token);
|
||
|
const i = findLastIndex(this.elementStack, (el) => el.name.toLowerCase() === token.name);
|
||
|
if (i === -1) {
|
||
|
this.reportParseError(token, "x-invalid-end-tag");
|
||
|
return;
|
||
|
}
|
||
|
const element = this.elementStack[i];
|
||
|
element.endTag = {
|
||
|
type: "VEndTag",
|
||
|
range: token.range,
|
||
|
loc: token.loc,
|
||
|
parent: element,
|
||
|
};
|
||
|
this.popElementStackUntil(i);
|
||
|
}
|
||
|
Text(token) {
|
||
|
debug("[html] Text %j", token);
|
||
|
const parent = this.currentNode;
|
||
|
parent.children.push({
|
||
|
type: "VText",
|
||
|
range: token.range,
|
||
|
loc: token.loc,
|
||
|
parent,
|
||
|
value: token.value,
|
||
|
});
|
||
|
}
|
||
|
Mustache(token) {
|
||
|
debug("[html] Mustache %j", token);
|
||
|
const parent = this.currentNode;
|
||
|
const container = {
|
||
|
type: "VExpressionContainer",
|
||
|
range: token.range,
|
||
|
loc: token.loc,
|
||
|
parent,
|
||
|
expression: null,
|
||
|
references: [],
|
||
|
};
|
||
|
parent.children.push(container);
|
||
|
this.postProcessesForScript.push((parserOptions) => {
|
||
|
processMustache(parserOptions, this.locationCalculator, container, token);
|
||
|
resolveReferences(container);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
const alternativeCR = new Map([[128, 8364], [130, 8218], [131, 402], [132, 8222], [133, 8230], [134, 8224], [135, 8225], [136, 710], [137, 8240], [138, 352], [139, 8249], [140, 338], [142, 381], [145, 8216], [146, 8217], [147, 8220], [148, 8221], [149, 8226], [150, 8211], [151, 8212], [152, 732], [153, 8482], [154, 353], [155, 8250], [156, 339], [158, 382], [159, 376]]);
|
||
|
|
||
|
const entitySets = [{ "length": 32, "entities": { "CounterClockwiseContourIntegral;": [8755] } }, { "length": 25, "entities": { "ClockwiseContourIntegral;": [8754], "DoubleLongLeftRightArrow;": [10234] } }, { "length": 24, "entities": { "NotNestedGreaterGreater;": [10914, 824] } }, { "length": 23, "entities": { "DiacriticalDoubleAcute;": [733], "NotSquareSupersetEqual;": [8931] } }, { "length": 22, "entities": { "CloseCurlyDoubleQuote;": [8221], "DoubleContourIntegral;": [8751], "FilledVerySmallSquare;": [9642], "NegativeVeryThinSpace;": [8203], "NotPrecedesSlantEqual;": [8928], "NotRightTriangleEqual;": [8941], "NotSucceedsSlantEqual;": [8929] } }, { "length": 21, "entities": { "CapitalDifferentialD;": [8517], "DoubleLeftRightArrow;": [8660], "DoubleLongRightArrow;": [10233], "EmptyVerySmallSquare;": [9643], "NestedGreaterGreater;": [8811], "NotDoubleVerticalBar;": [8742], "NotGreaterSlantEqual;": [10878, 824], "NotLeftTriangleEqual;": [8940], "NotSquareSubsetEqual;": [8930], "OpenCurlyDoubleQuote;": [8220], "ReverseUpEquilibrium;": [10607] } }, { "length": 20, "entities": { "DoubleLongLeftArrow;": [10232], "DownLeftRightVector;": [10576], "LeftArrowRightArrow;": [8646], "NegativeMediumSpace;": [8203], "NotGreaterFullEqual;": [8807, 824], "NotRightTriangleBar;": [10704, 824], "RightArrowLeftArrow;": [8644], "SquareSupersetEqual;": [8850], "leftrightsquigarrow;": [8621] } }, { "length": 19, "entities": { "DownRightTeeVector;": [10591], "DownRightVectorBar;": [10583], "LongLeftRightArrow;": [10231], "Longleftrightarrow;": [10234], "NegativeThickSpace;": [8203], "NotLeftTriangleBar;": [10703, 824], "PrecedesSlantEqual;": [8828], "ReverseEquilibrium;": [8651], "RightDoubleBracket;": [10215], "RightDownTeeVector;": [10589], "RightDownVectorBar;": [10581], "RightTriangleEqual;": [8885], "SquareIntersection;": [8851], "SucceedsSlantEqual;": [8829], "blacktriangleright;": [9656], "longleftrightarrow;": [10231] } }, { "length": 18, "entities": { "DoubleUpDownArrow;": [8661], "DoubleVerticalBar;": [8741], "DownLeftTeeVector;": [10590], "DownLeftVectorBar;": [10582], "FilledSmallSquare;": [9724], "GreaterSlantEqual;": [10878], "LeftDoubleBracket;": [10214], "LeftDownTeeVector;": [10593], "LeftDownVectorBar;": [10585], "LeftTriangleEqual;": [8884], "NegativeThinSpace;": [8203], "NotGreaterGreater;": [8811, 824], "NotLessSlantEqual;": [10877, 824], "NotNestedLessLess;": [10913, 824], "NotReverseElement;": [8716], "NotSquareSuperset;": [8848, 824], "NotTildeFullEqual;": [8775], "RightAngleBracket;": [10217], "RightUpDownVector;": [10575], "SquareSubsetEqual;": [8849], "VerticalSeparator;": [10072], "blacktriangledown;": [9662], "blacktriangleleft;": [9666], "leftrightharpoons;": [8651], "rightleftharpoons;": [8652], "twoheadrightarrow;": [8608] } }, { "length": 17, "entities": { "DiacriticalAcute;": [180], "DiacriticalGrave;": [96], "DiacriticalTilde;": [732], "DoubleRightArrow;": [8658], "DownArrowUpArrow;": [8693], "EmptySmallSquare;": [9723], "GreaterEqualLess;": [8923], "GreaterFullEqual;": [8807], "LeftAngleBracket;": [10216], "LeftUpDownVector;": [10577], "LessEqualGreater;": [8922], "NonBreakingSpace;": [160], "NotPrecedesEqual;": [10927, 824], "NotRightTriangle;": [8939], "NotSucceedsEqual;": [10928, 824], "NotSucceedsTilde;": [8831, 824], "NotSupersetEqual;": [8841], "RightTriangleBar;": [10704], "RightUpTeeVector;": [10588], "RightUpVectorBar;": [10580], "UnderParenthesis;": [9181], "UpArrowDownArrow;": [8645], "circlearrowright;": [8635], "downharpoonright;": [8642], "ntrianglerighteq;": [8941], "rightharpoondown;": [8641], "rightrightarrows;": [8649], "twoheadleftarrow;": [8606], "vartriangleright;": [8883] } }, { "length": 16, "entities": { "CloseCurlyQuote;": [8217], "ContourIntegral;": [8750], "DoubleDownArrow;": [8659], "DoubleLeftArrow;": [8656], "DownRightVector;": [8641], "LeftRightVector;": [10574], "LeftTriangleBar;": [10703], "LeftUpTeeVector;": [10592], "LeftUpVectorBar;": [10584], "LowerRightArrow;": [8600], "NotGreaterEqual;": [8817], "NotGreaterTilde;": [8821], "NotHumpDownHump;": [8782, 824], "NotLeftTrian
|
||
|
|
||
|
const EOF = -1;
|
||
|
const NULL = 0x00;
|
||
|
const TABULATION = 0x09;
|
||
|
const CARRIAGE_RETURN = 0x0D;
|
||
|
const LINE_FEED = 0x0A;
|
||
|
const FORM_FEED = 0x0C;
|
||
|
const SPACE = 0x20;
|
||
|
const EXCLAMATION_MARK = 0x21;
|
||
|
const QUOTATION_MARK = 0x22;
|
||
|
const NUMBER_SIGN = 0x23;
|
||
|
const AMPERSAND = 0x26;
|
||
|
const APOSTROPHE = 0x27;
|
||
|
const HYPHEN_MINUS = 0x2D;
|
||
|
const SOLIDUS = 0x2F;
|
||
|
const DIGIT_0 = 0x30;
|
||
|
const DIGIT_9 = 0x39;
|
||
|
const SEMICOLON = 0x3B;
|
||
|
const LESS_THAN_SIGN = 0x3C;
|
||
|
const EQUALS_SIGN = 0x3D;
|
||
|
const GREATER_THAN_SIGN = 0x3E;
|
||
|
const QUESTION_MARK = 0x3F;
|
||
|
const LATIN_CAPITAL_A = 0x41;
|
||
|
const LATIN_CAPITAL_D = 0x44;
|
||
|
const LATIN_CAPITAL_F = 0x46;
|
||
|
const LATIN_CAPITAL_X = 0x58;
|
||
|
const LATIN_CAPITAL_Z = 0x5A;
|
||
|
const LEFT_SQUARE_BRACKET = 0x5B;
|
||
|
const RIGHT_SQUARE_BRACKET = 0x5D;
|
||
|
const GRAVE_ACCENT = 0x60;
|
||
|
const LATIN_SMALL_A = 0x61;
|
||
|
const LATIN_SMALL_F = 0x66;
|
||
|
const LATIN_SMALL_X = 0x78;
|
||
|
const LATIN_SMALL_Z = 0x7A;
|
||
|
const LEFT_CURLY_BRACKET = 0x7B;
|
||
|
const RIGHT_CURLY_BRACKET = 0x7D;
|
||
|
const NULL_REPLACEMENT = 0xFFFD;
|
||
|
function isWhitespace(cp) {
|
||
|
return cp === TABULATION || cp === LINE_FEED || cp === FORM_FEED || cp === CARRIAGE_RETURN || cp === SPACE;
|
||
|
}
|
||
|
function isUpperLetter(cp) {
|
||
|
return cp >= LATIN_CAPITAL_A && cp <= LATIN_CAPITAL_Z;
|
||
|
}
|
||
|
function isLowerLetter(cp) {
|
||
|
return cp >= LATIN_SMALL_A && cp <= LATIN_SMALL_Z;
|
||
|
}
|
||
|
function isLetter(cp) {
|
||
|
return isLowerLetter(cp) || isUpperLetter(cp);
|
||
|
}
|
||
|
function isDigit(cp) {
|
||
|
return cp >= DIGIT_0 && cp <= DIGIT_9;
|
||
|
}
|
||
|
function isUpperHexDigit(cp) {
|
||
|
return cp >= LATIN_CAPITAL_A && cp <= LATIN_CAPITAL_F;
|
||
|
}
|
||
|
function isLowerHexDigit(cp) {
|
||
|
return cp >= LATIN_SMALL_A && cp <= LATIN_SMALL_F;
|
||
|
}
|
||
|
function isHexDigit(cp) {
|
||
|
return isDigit(cp) || isUpperHexDigit(cp) || isLowerHexDigit(cp);
|
||
|
}
|
||
|
function isControl(cp) {
|
||
|
return (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F);
|
||
|
}
|
||
|
function isSurrogate(cp) {
|
||
|
return cp >= 0xD800 && cp <= 0xDFFF;
|
||
|
}
|
||
|
function isSurrogatePair(cp) {
|
||
|
return cp >= 0xDC00 && cp <= 0xDFFF;
|
||
|
}
|
||
|
function isNonCharacter(cp) {
|
||
|
return ((cp >= 0xFDD0 && cp <= 0xFDEF) ||
|
||
|
((cp & 0xFFFE) === 0xFFFE && cp <= 0x10FFFF));
|
||
|
}
|
||
|
function toLowerCodePoint(cp) {
|
||
|
return cp + 0x0020;
|
||
|
}
|
||
|
|
||
|
class Tokenizer {
|
||
|
constructor(text, parserOptions) {
|
||
|
this.vExpressionScriptState = null;
|
||
|
debug("[html] the source code length: %d", text.length);
|
||
|
this.text = text;
|
||
|
this.gaps = [];
|
||
|
this.lineTerminators = [];
|
||
|
this.parserOptions = parserOptions || {};
|
||
|
this.lastCodePoint = NULL;
|
||
|
this.offset = -1;
|
||
|
this.column = -1;
|
||
|
this.line = 1;
|
||
|
this.state = "DATA";
|
||
|
this.returnState = "DATA";
|
||
|
this.reconsuming = false;
|
||
|
this.buffer = [];
|
||
|
this.crStartOffset = -1;
|
||
|
this.crCode = 0;
|
||
|
this.errors = [];
|
||
|
this.committedToken = null;
|
||
|
this.provisionalToken = null;
|
||
|
this.currentToken = null;
|
||
|
this.lastTagOpenToken = null;
|
||
|
this.tokenStartOffset = -1;
|
||
|
this.tokenStartColumn = -1;
|
||
|
this.tokenStartLine = 1;
|
||
|
this.namespace = NS.HTML;
|
||
|
this.expressionEnabled = false;
|
||
|
}
|
||
|
nextToken() {
|
||
|
let cp = this.lastCodePoint;
|
||
|
while (this.committedToken == null &&
|
||
|
(cp !== EOF || this.reconsuming)) {
|
||
|
if (this.provisionalToken != null && !this.isProvisionalState()) {
|
||
|
this.commitProvisionalToken();
|
||
|
if (this.committedToken != null) {
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
if (this.reconsuming) {
|
||
|
this.reconsuming = false;
|
||
|
cp = this.lastCodePoint;
|
||
|
}
|
||
|
else {
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
debug("[html] parse", cp, this.state);
|
||
|
this.state = this[this.state](cp);
|
||
|
}
|
||
|
{
|
||
|
const token = this.consumeCommittedToken();
|
||
|
if (token != null) {
|
||
|
return token;
|
||
|
}
|
||
|
}
|
||
|
assert(cp === EOF);
|
||
|
if (this.currentToken != null) {
|
||
|
this.endToken();
|
||
|
const token = this.consumeCommittedToken();
|
||
|
if (token != null) {
|
||
|
return token;
|
||
|
}
|
||
|
}
|
||
|
return this.currentToken;
|
||
|
}
|
||
|
consumeCommittedToken() {
|
||
|
const token = this.committedToken;
|
||
|
this.committedToken = null;
|
||
|
return token;
|
||
|
}
|
||
|
consumeNextCodePoint() {
|
||
|
if (this.offset >= this.text.length) {
|
||
|
this.lastCodePoint = EOF;
|
||
|
return EOF;
|
||
|
}
|
||
|
this.offset += this.lastCodePoint >= 0x10000 ? 2 : 1;
|
||
|
if (this.offset >= this.text.length) {
|
||
|
this.advanceLocation();
|
||
|
this.lastCodePoint = EOF;
|
||
|
return EOF;
|
||
|
}
|
||
|
const cp = this.text.codePointAt(this.offset);
|
||
|
if (isSurrogate(this.text.charCodeAt(this.offset)) &&
|
||
|
!isSurrogatePair(this.text.charCodeAt(this.offset + 1))) {
|
||
|
this.reportParseError("surrogate-in-input-stream");
|
||
|
}
|
||
|
if (isNonCharacter(cp)) {
|
||
|
this.reportParseError("noncharacter-in-input-stream");
|
||
|
}
|
||
|
if (isControl(cp) && !isWhitespace(cp) && cp !== NULL) {
|
||
|
this.reportParseError("control-character-in-input-stream");
|
||
|
}
|
||
|
if (this.lastCodePoint === CARRIAGE_RETURN && cp === LINE_FEED) {
|
||
|
this.lastCodePoint = LINE_FEED;
|
||
|
this.gaps.push(this.offset);
|
||
|
return this.consumeNextCodePoint();
|
||
|
}
|
||
|
this.advanceLocation();
|
||
|
this.lastCodePoint = cp;
|
||
|
if (cp === CARRIAGE_RETURN) {
|
||
|
return LINE_FEED;
|
||
|
}
|
||
|
return cp;
|
||
|
}
|
||
|
advanceLocation() {
|
||
|
if (this.lastCodePoint === LINE_FEED) {
|
||
|
this.lineTerminators.push(this.offset);
|
||
|
this.line += 1;
|
||
|
this.column = 0;
|
||
|
}
|
||
|
else {
|
||
|
this.column += this.lastCodePoint >= 0x10000 ? 2 : 1;
|
||
|
}
|
||
|
}
|
||
|
reconsumeAs(state) {
|
||
|
this.reconsuming = true;
|
||
|
return state;
|
||
|
}
|
||
|
reportParseError(code) {
|
||
|
const error = ParseError.fromCode(code, this.offset, this.line, this.column);
|
||
|
this.errors.push(error);
|
||
|
debug("[html] syntax error:", error.message);
|
||
|
}
|
||
|
setStartTokenMark() {
|
||
|
this.tokenStartOffset = this.offset;
|
||
|
this.tokenStartLine = this.line;
|
||
|
this.tokenStartColumn = this.column;
|
||
|
}
|
||
|
clearStartTokenMark() {
|
||
|
this.tokenStartOffset = -1;
|
||
|
}
|
||
|
startToken(type) {
|
||
|
if (this.tokenStartOffset === -1) {
|
||
|
this.setStartTokenMark();
|
||
|
}
|
||
|
const offset = this.tokenStartOffset;
|
||
|
const line = this.tokenStartLine;
|
||
|
const column = this.tokenStartColumn;
|
||
|
if (this.currentToken != null) {
|
||
|
this.endToken();
|
||
|
}
|
||
|
this.tokenStartOffset = -1;
|
||
|
const token = (this.currentToken = {
|
||
|
type,
|
||
|
range: [offset, -1],
|
||
|
loc: {
|
||
|
start: { line, column },
|
||
|
end: { line: -1, column: -1 },
|
||
|
},
|
||
|
value: "",
|
||
|
});
|
||
|
debug("[html] start token: %d %s", offset, token.type);
|
||
|
return this.currentToken;
|
||
|
}
|
||
|
endToken() {
|
||
|
if (this.currentToken == null) {
|
||
|
throw new Error("Invalid state");
|
||
|
}
|
||
|
if (this.tokenStartOffset === -1) {
|
||
|
this.setStartTokenMark();
|
||
|
}
|
||
|
const token = this.currentToken;
|
||
|
const offset = this.tokenStartOffset;
|
||
|
const line = this.tokenStartLine;
|
||
|
const column = this.tokenStartColumn;
|
||
|
const provisional = this.isProvisionalState();
|
||
|
this.currentToken = null;
|
||
|
this.tokenStartOffset = -1;
|
||
|
token.range[1] = offset;
|
||
|
token.loc.end.line = line;
|
||
|
token.loc.end.column = column;
|
||
|
if (token.range[0] === offset && !provisional) {
|
||
|
debug("[html] abandon token: %j %s %j", token.range, token.type, token.value);
|
||
|
return null;
|
||
|
}
|
||
|
if (provisional) {
|
||
|
if (this.provisionalToken != null) {
|
||
|
this.commitProvisionalToken();
|
||
|
}
|
||
|
this.provisionalToken = token;
|
||
|
debug("[html] provisional-commit token: %j %s %j", token.range, token.type, token.value);
|
||
|
}
|
||
|
else {
|
||
|
this.commitToken(token);
|
||
|
}
|
||
|
return token;
|
||
|
}
|
||
|
commitToken(token) {
|
||
|
assert(this.committedToken == null, "Invalid state: the commited token existed already.");
|
||
|
debug("[html] commit token: %j %j %s %j", token.range, token.loc, token.type, token.value);
|
||
|
this.committedToken = token;
|
||
|
if (token.type === "HTMLTagOpen") {
|
||
|
this.lastTagOpenToken = token;
|
||
|
}
|
||
|
}
|
||
|
isProvisionalState() {
|
||
|
return (this.state.startsWith("RCDATA_") ||
|
||
|
this.state.startsWith("RAWTEXT_"));
|
||
|
}
|
||
|
commitProvisionalToken() {
|
||
|
assert(this.provisionalToken != null, "Invalid state: the provisional token was not found.");
|
||
|
const token = this.provisionalToken;
|
||
|
this.provisionalToken = null;
|
||
|
if (token.range[0] < token.range[1]) {
|
||
|
this.commitToken(token);
|
||
|
}
|
||
|
}
|
||
|
rollbackProvisionalToken() {
|
||
|
assert(this.currentToken != null);
|
||
|
assert(this.provisionalToken != null);
|
||
|
const token = this.currentToken;
|
||
|
debug("[html] rollback token: %d %s", token.range[0], token.type);
|
||
|
this.currentToken = this.provisionalToken;
|
||
|
this.provisionalToken = null;
|
||
|
}
|
||
|
appendTokenValue(cp, expected) {
|
||
|
const token = this.currentToken;
|
||
|
if (token == null || (expected != null && token.type !== expected)) {
|
||
|
const msg1 = expected ? `"${expected}" type` : "any token";
|
||
|
const msg2 = token ? `"${token.type}" type` : "no token";
|
||
|
throw new Error(`Tokenizer: Invalid state. Expected ${msg1}, but got ${msg2}.`);
|
||
|
}
|
||
|
token.value += String.fromCodePoint(cp);
|
||
|
}
|
||
|
isAppropriateEndTagOpen() {
|
||
|
return (this.currentToken != null &&
|
||
|
this.lastTagOpenToken != null &&
|
||
|
this.currentToken.type === "HTMLEndTagOpen" &&
|
||
|
this.currentToken.value === this.lastTagOpenToken.value);
|
||
|
}
|
||
|
DATA(cp) {
|
||
|
this.clearStartTokenMark();
|
||
|
while (true) {
|
||
|
const type = isWhitespace(cp) ? "HTMLWhitespace" : "HTMLText";
|
||
|
if (this.currentToken != null && this.currentToken.type !== type) {
|
||
|
this.endToken();
|
||
|
return this.reconsumeAs(this.state);
|
||
|
}
|
||
|
if (this.currentToken == null) {
|
||
|
this.startToken(type);
|
||
|
}
|
||
|
if (cp === AMPERSAND) {
|
||
|
this.returnState = "DATA";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === LESS_THAN_SIGN) {
|
||
|
this.setStartTokenMark();
|
||
|
return "TAG_OPEN";
|
||
|
}
|
||
|
if (cp === LEFT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "DATA";
|
||
|
return "V_EXPRESSION_START";
|
||
|
}
|
||
|
if (cp === RIGHT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "DATA";
|
||
|
return "V_EXPRESSION_END";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
}
|
||
|
this.appendTokenValue(cp, type);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
RCDATA(cp) {
|
||
|
this.clearStartTokenMark();
|
||
|
while (true) {
|
||
|
const type = isWhitespace(cp) ? "HTMLWhitespace" : "HTMLRCDataText";
|
||
|
if (this.currentToken != null && this.currentToken.type !== type) {
|
||
|
this.endToken();
|
||
|
return this.reconsumeAs(this.state);
|
||
|
}
|
||
|
if (this.currentToken == null) {
|
||
|
this.startToken(type);
|
||
|
}
|
||
|
if (cp === AMPERSAND) {
|
||
|
this.returnState = "RCDATA";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === LESS_THAN_SIGN) {
|
||
|
this.setStartTokenMark();
|
||
|
return "RCDATA_LESS_THAN_SIGN";
|
||
|
}
|
||
|
if (cp === LEFT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "RCDATA";
|
||
|
return "V_EXPRESSION_START";
|
||
|
}
|
||
|
if (cp === RIGHT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "RCDATA";
|
||
|
return "V_EXPRESSION_END";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
this.appendTokenValue(cp, type);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
RAWTEXT(cp) {
|
||
|
this.clearStartTokenMark();
|
||
|
while (true) {
|
||
|
const type = isWhitespace(cp) ? "HTMLWhitespace" : "HTMLRawText";
|
||
|
if (this.currentToken != null && this.currentToken.type !== type) {
|
||
|
this.endToken();
|
||
|
return this.reconsumeAs(this.state);
|
||
|
}
|
||
|
if (this.currentToken == null) {
|
||
|
this.startToken(type);
|
||
|
}
|
||
|
if (cp === LESS_THAN_SIGN) {
|
||
|
this.setStartTokenMark();
|
||
|
return "RAWTEXT_LESS_THAN_SIGN";
|
||
|
}
|
||
|
if (cp === LEFT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "RAWTEXT";
|
||
|
return "V_EXPRESSION_START";
|
||
|
}
|
||
|
if (cp === RIGHT_CURLY_BRACKET && this.expressionEnabled) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "RAWTEXT";
|
||
|
return "V_EXPRESSION_END";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
this.appendTokenValue(cp, type);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
TAG_OPEN(cp) {
|
||
|
if (cp === EXCLAMATION_MARK) {
|
||
|
return "MARKUP_DECLARATION_OPEN";
|
||
|
}
|
||
|
if (cp === SOLIDUS) {
|
||
|
return "END_TAG_OPEN";
|
||
|
}
|
||
|
if (isLetter(cp)) {
|
||
|
this.startToken("HTMLTagOpen");
|
||
|
return this.reconsumeAs("TAG_NAME");
|
||
|
}
|
||
|
if (cp === QUESTION_MARK) {
|
||
|
this.reportParseError("unexpected-question-mark-instead-of-tag-name");
|
||
|
this.startToken("HTMLBogusComment");
|
||
|
return this.reconsumeAs("BOGUS_COMMENT");
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.clearStartTokenMark();
|
||
|
this.reportParseError("eof-before-tag-name");
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLText");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.reportParseError("invalid-first-character-of-tag-name");
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLText");
|
||
|
return this.reconsumeAs("DATA");
|
||
|
}
|
||
|
END_TAG_OPEN(cp) {
|
||
|
if (isLetter(cp)) {
|
||
|
this.startToken("HTMLEndTagOpen");
|
||
|
return this.reconsumeAs("TAG_NAME");
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.endToken();
|
||
|
this.reportParseError("missing-end-tag-name");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.clearStartTokenMark();
|
||
|
this.reportParseError("eof-before-tag-name");
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLText");
|
||
|
this.appendTokenValue(SOLIDUS, "HTMLText");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.reportParseError("invalid-first-character-of-tag-name");
|
||
|
this.startToken("HTMLBogusComment");
|
||
|
return this.reconsumeAs("BOGUS_COMMENT");
|
||
|
}
|
||
|
TAG_NAME(cp) {
|
||
|
while (true) {
|
||
|
if (isWhitespace(cp)) {
|
||
|
this.endToken();
|
||
|
return "BEFORE_ATTRIBUTE_NAME";
|
||
|
}
|
||
|
if (cp === SOLIDUS) {
|
||
|
this.endToken();
|
||
|
this.setStartTokenMark();
|
||
|
return "SELF_CLOSING_START_TAG";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
this.appendTokenValue(isUpperLetter(cp) ? toLowerCodePoint(cp) : cp, null);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
RCDATA_LESS_THAN_SIGN(cp) {
|
||
|
if (cp === SOLIDUS) {
|
||
|
this.buffer = [];
|
||
|
return "RCDATA_END_TAG_OPEN";
|
||
|
}
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRCDataText");
|
||
|
return this.reconsumeAs("RCDATA");
|
||
|
}
|
||
|
RCDATA_END_TAG_OPEN(cp) {
|
||
|
if (isLetter(cp)) {
|
||
|
this.startToken("HTMLEndTagOpen");
|
||
|
return this.reconsumeAs("RCDATA_END_TAG_NAME");
|
||
|
}
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRCDataText");
|
||
|
this.appendTokenValue(SOLIDUS, "HTMLRCDataText");
|
||
|
return this.reconsumeAs("RCDATA");
|
||
|
}
|
||
|
RCDATA_END_TAG_NAME(cp) {
|
||
|
while (true) {
|
||
|
if (isWhitespace(cp) && this.isAppropriateEndTagOpen()) {
|
||
|
this.endToken();
|
||
|
return "BEFORE_ATTRIBUTE_NAME";
|
||
|
}
|
||
|
if (cp === SOLIDUS && this.isAppropriateEndTagOpen()) {
|
||
|
this.endToken();
|
||
|
this.setStartTokenMark();
|
||
|
return "SELF_CLOSING_START_TAG";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN && this.isAppropriateEndTagOpen()) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (!isLetter(cp)) {
|
||
|
this.rollbackProvisionalToken();
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRCDataText");
|
||
|
this.appendTokenValue(SOLIDUS, "HTMLRCDataText");
|
||
|
for (const cp1 of this.buffer) {
|
||
|
this.appendTokenValue(cp1, "HTMLRCDataText");
|
||
|
}
|
||
|
return this.reconsumeAs("RCDATA");
|
||
|
}
|
||
|
this.appendTokenValue(isUpperLetter(cp) ? toLowerCodePoint(cp) : cp, "HTMLEndTagOpen");
|
||
|
this.buffer.push(cp);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
RAWTEXT_LESS_THAN_SIGN(cp) {
|
||
|
if (cp === SOLIDUS) {
|
||
|
this.buffer = [];
|
||
|
return "RAWTEXT_END_TAG_OPEN";
|
||
|
}
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRawText");
|
||
|
return this.reconsumeAs("RAWTEXT");
|
||
|
}
|
||
|
RAWTEXT_END_TAG_OPEN(cp) {
|
||
|
if (isLetter(cp)) {
|
||
|
this.startToken("HTMLEndTagOpen");
|
||
|
return this.reconsumeAs("RAWTEXT_END_TAG_NAME");
|
||
|
}
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRawText");
|
||
|
this.appendTokenValue(SOLIDUS, "HTMLRawText");
|
||
|
return this.reconsumeAs("RAWTEXT");
|
||
|
}
|
||
|
RAWTEXT_END_TAG_NAME(cp) {
|
||
|
while (true) {
|
||
|
if (cp === SOLIDUS && this.isAppropriateEndTagOpen()) {
|
||
|
this.endToken();
|
||
|
this.setStartTokenMark();
|
||
|
return "SELF_CLOSING_START_TAG";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN && this.isAppropriateEndTagOpen()) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (isWhitespace(cp) && this.isAppropriateEndTagOpen()) {
|
||
|
this.endToken();
|
||
|
return "BEFORE_ATTRIBUTE_NAME";
|
||
|
}
|
||
|
if (!isLetter(cp) && !maybeValidCustomBlock.call(this, cp)) {
|
||
|
this.rollbackProvisionalToken();
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLRawText");
|
||
|
this.appendTokenValue(SOLIDUS, "HTMLRawText");
|
||
|
for (const cp1 of this.buffer) {
|
||
|
this.appendTokenValue(cp1, "HTMLRawText");
|
||
|
}
|
||
|
return this.reconsumeAs("RAWTEXT");
|
||
|
}
|
||
|
this.appendTokenValue(isUpperLetter(cp) ? toLowerCodePoint(cp) : cp, "HTMLEndTagOpen");
|
||
|
this.buffer.push(cp);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
function maybeValidCustomBlock(nextCp) {
|
||
|
return (this.currentToken &&
|
||
|
this.lastTagOpenToken &&
|
||
|
this.lastTagOpenToken.value.startsWith(this.currentToken.value + String.fromCodePoint(nextCp)));
|
||
|
}
|
||
|
}
|
||
|
BEFORE_ATTRIBUTE_NAME(cp) {
|
||
|
while (isWhitespace(cp)) {
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
if (cp === SOLIDUS || cp === GREATER_THAN_SIGN || cp === EOF) {
|
||
|
return this.reconsumeAs("AFTER_ATTRIBUTE_NAME");
|
||
|
}
|
||
|
if (cp === EQUALS_SIGN) {
|
||
|
this.reportParseError("unexpected-equals-sign-before-attribute-name");
|
||
|
this.startToken("HTMLIdentifier");
|
||
|
this.appendTokenValue(cp, "HTMLIdentifier");
|
||
|
return "ATTRIBUTE_NAME";
|
||
|
}
|
||
|
this.startToken("HTMLIdentifier");
|
||
|
return this.reconsumeAs("ATTRIBUTE_NAME");
|
||
|
}
|
||
|
ATTRIBUTE_NAME(cp) {
|
||
|
while (true) {
|
||
|
if (isWhitespace(cp) ||
|
||
|
cp === SOLIDUS ||
|
||
|
cp === GREATER_THAN_SIGN ||
|
||
|
cp === EOF) {
|
||
|
this.endToken();
|
||
|
return this.reconsumeAs("AFTER_ATTRIBUTE_NAME");
|
||
|
}
|
||
|
if (cp === EQUALS_SIGN) {
|
||
|
this.startToken("HTMLAssociation");
|
||
|
return "BEFORE_ATTRIBUTE_VALUE";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
if (cp === QUOTATION_MARK ||
|
||
|
cp === APOSTROPHE ||
|
||
|
cp === LESS_THAN_SIGN) {
|
||
|
this.reportParseError("unexpected-character-in-attribute-name");
|
||
|
}
|
||
|
this.appendTokenValue(isUpperLetter(cp) ? toLowerCodePoint(cp) : cp, "HTMLIdentifier");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
AFTER_ATTRIBUTE_NAME(cp) {
|
||
|
while (isWhitespace(cp)) {
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
if (cp === SOLIDUS) {
|
||
|
this.setStartTokenMark();
|
||
|
return "SELF_CLOSING_START_TAG";
|
||
|
}
|
||
|
if (cp === EQUALS_SIGN) {
|
||
|
this.startToken("HTMLAssociation");
|
||
|
return "BEFORE_ATTRIBUTE_VALUE";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.startToken("HTMLIdentifier");
|
||
|
return this.reconsumeAs("ATTRIBUTE_NAME");
|
||
|
}
|
||
|
BEFORE_ATTRIBUTE_VALUE(cp) {
|
||
|
this.endToken();
|
||
|
while (isWhitespace(cp)) {
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.reportParseError("missing-attribute-value");
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.startToken("HTMLLiteral");
|
||
|
if (cp === QUOTATION_MARK) {
|
||
|
return "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
|
||
|
}
|
||
|
if (cp === APOSTROPHE) {
|
||
|
return "ATTRIBUTE_VALUE_SINGLE_QUOTED";
|
||
|
}
|
||
|
return this.reconsumeAs("ATTRIBUTE_VALUE_UNQUOTED");
|
||
|
}
|
||
|
ATTRIBUTE_VALUE_DOUBLE_QUOTED(cp) {
|
||
|
while (true) {
|
||
|
if (cp === QUOTATION_MARK) {
|
||
|
return "AFTER_ATTRIBUTE_VALUE_QUOTED";
|
||
|
}
|
||
|
if (cp === AMPERSAND) {
|
||
|
this.returnState = "ATTRIBUTE_VALUE_DOUBLE_QUOTED";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLLiteral");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
ATTRIBUTE_VALUE_SINGLE_QUOTED(cp) {
|
||
|
while (true) {
|
||
|
if (cp === APOSTROPHE) {
|
||
|
return "AFTER_ATTRIBUTE_VALUE_QUOTED";
|
||
|
}
|
||
|
if (cp === AMPERSAND) {
|
||
|
this.returnState = "ATTRIBUTE_VALUE_SINGLE_QUOTED";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLLiteral");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
ATTRIBUTE_VALUE_UNQUOTED(cp) {
|
||
|
while (true) {
|
||
|
if (isWhitespace(cp)) {
|
||
|
this.endToken();
|
||
|
return "BEFORE_ATTRIBUTE_NAME";
|
||
|
}
|
||
|
if (cp === AMPERSAND) {
|
||
|
this.returnState = "ATTRIBUTE_VALUE_UNQUOTED";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
if (cp === QUOTATION_MARK ||
|
||
|
cp === APOSTROPHE ||
|
||
|
cp === LESS_THAN_SIGN ||
|
||
|
cp === EQUALS_SIGN ||
|
||
|
cp === GRAVE_ACCENT) {
|
||
|
this.reportParseError("unexpected-character-in-unquoted-attribute-value");
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLLiteral");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
AFTER_ATTRIBUTE_VALUE_QUOTED(cp) {
|
||
|
this.endToken();
|
||
|
if (isWhitespace(cp)) {
|
||
|
return "BEFORE_ATTRIBUTE_NAME";
|
||
|
}
|
||
|
if (cp === SOLIDUS) {
|
||
|
this.setStartTokenMark();
|
||
|
return "SELF_CLOSING_START_TAG";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.startToken("HTMLTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.reportParseError("missing-whitespace-between-attributes");
|
||
|
return this.reconsumeAs("BEFORE_ATTRIBUTE_NAME");
|
||
|
}
|
||
|
SELF_CLOSING_START_TAG(cp) {
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.startToken("HTMLSelfClosingTagClose");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-tag");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.reportParseError("unexpected-solidus-in-tag");
|
||
|
this.clearStartTokenMark();
|
||
|
return this.reconsumeAs("BEFORE_ATTRIBUTE_NAME");
|
||
|
}
|
||
|
BOGUS_COMMENT(cp) {
|
||
|
while (true) {
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
this.appendTokenValue(cp, null);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
MARKUP_DECLARATION_OPEN(cp) {
|
||
|
if (cp === HYPHEN_MINUS && this.text[this.offset + 1] === "-") {
|
||
|
this.offset += 1;
|
||
|
this.column += 1;
|
||
|
this.startToken("HTMLComment");
|
||
|
return "COMMENT_START";
|
||
|
}
|
||
|
if (cp === LATIN_CAPITAL_D &&
|
||
|
this.text.slice(this.offset + 1, this.offset + 7) === "OCTYPE") {
|
||
|
this.startToken("HTMLBogusComment");
|
||
|
this.appendTokenValue(cp, "HTMLBogusComment");
|
||
|
return "BOGUS_COMMENT";
|
||
|
}
|
||
|
if (cp === LEFT_SQUARE_BRACKET &&
|
||
|
this.text.slice(this.offset + 1, this.offset + 7) === "CDATA[") {
|
||
|
this.offset += 6;
|
||
|
this.column += 6;
|
||
|
if (this.namespace === NS.HTML) {
|
||
|
this.reportParseError("cdata-in-html-content");
|
||
|
this.startToken("HTMLBogusComment").value = "[CDATA[";
|
||
|
return "BOGUS_COMMENT";
|
||
|
}
|
||
|
this.startToken("HTMLCDataText");
|
||
|
return "CDATA_SECTION";
|
||
|
}
|
||
|
this.reportParseError("incorrectly-opened-comment");
|
||
|
this.startToken("HTMLBogusComment");
|
||
|
return this.reconsumeAs("BOGUS_COMMENT");
|
||
|
}
|
||
|
COMMENT_START(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_START_DASH";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.reportParseError("abrupt-closing-of-empty-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
COMMENT_START_DASH(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_END";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.reportParseError("abrupt-closing-of-empty-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
COMMENT(cp) {
|
||
|
while (true) {
|
||
|
if (cp === LESS_THAN_SIGN) {
|
||
|
this.appendTokenValue(LESS_THAN_SIGN, "HTMLComment");
|
||
|
return "COMMENT_LESS_THAN_SIGN";
|
||
|
}
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_END_DASH";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
cp = NULL_REPLACEMENT;
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLComment");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
COMMENT_LESS_THAN_SIGN(cp) {
|
||
|
while (true) {
|
||
|
if (cp === EXCLAMATION_MARK) {
|
||
|
this.appendTokenValue(cp, "HTMLComment");
|
||
|
return "COMMENT_LESS_THAN_SIGN_BANG";
|
||
|
}
|
||
|
if (cp !== LESS_THAN_SIGN) {
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLComment");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
COMMENT_LESS_THAN_SIGN_BANG(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_LESS_THAN_SIGN_BANG_DASH";
|
||
|
}
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
COMMENT_LESS_THAN_SIGN_BANG_DASH(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH";
|
||
|
}
|
||
|
return this.reconsumeAs("COMMENT_END_DASH");
|
||
|
}
|
||
|
COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH(cp) {
|
||
|
if (cp !== GREATER_THAN_SIGN && cp !== EOF) {
|
||
|
this.reportParseError("nested-comment");
|
||
|
}
|
||
|
return this.reconsumeAs("COMMENT_END");
|
||
|
}
|
||
|
COMMENT_END_DASH(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
return "COMMENT_END";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
COMMENT_END(cp) {
|
||
|
while (true) {
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EXCLAMATION_MARK) {
|
||
|
return "COMMENT_END_BANG";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
if (cp !== HYPHEN_MINUS) {
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
COMMENT_END_BANG(cp) {
|
||
|
if (cp === HYPHEN_MINUS) {
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
this.appendTokenValue(EXCLAMATION_MARK, "HTMLComment");
|
||
|
return "COMMENT_END_DASH";
|
||
|
}
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
this.reportParseError("incorrectly-closed-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-comment");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(HYPHEN_MINUS, "HTMLComment");
|
||
|
this.appendTokenValue(EXCLAMATION_MARK, "HTMLComment");
|
||
|
return this.reconsumeAs("COMMENT");
|
||
|
}
|
||
|
CDATA_SECTION(cp) {
|
||
|
while (true) {
|
||
|
if (cp === RIGHT_SQUARE_BRACKET) {
|
||
|
return "CDATA_SECTION_BRACKET";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("eof-in-cdata");
|
||
|
return "DATA";
|
||
|
}
|
||
|
this.appendTokenValue(cp, "HTMLCDataText");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
CDATA_SECTION_BRACKET(cp) {
|
||
|
if (cp === RIGHT_SQUARE_BRACKET) {
|
||
|
return "CDATA_SECTION_END";
|
||
|
}
|
||
|
this.appendTokenValue(RIGHT_SQUARE_BRACKET, "HTMLCDataText");
|
||
|
return this.reconsumeAs("CDATA_SECTION");
|
||
|
}
|
||
|
CDATA_SECTION_END(cp) {
|
||
|
while (true) {
|
||
|
if (cp === GREATER_THAN_SIGN) {
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp !== RIGHT_SQUARE_BRACKET) {
|
||
|
this.appendTokenValue(RIGHT_SQUARE_BRACKET, "HTMLCDataText");
|
||
|
this.appendTokenValue(RIGHT_SQUARE_BRACKET, "HTMLCDataText");
|
||
|
return this.reconsumeAs("CDATA_SECTION");
|
||
|
}
|
||
|
this.appendTokenValue(RIGHT_SQUARE_BRACKET, "HTMLCDataText");
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
CHARACTER_REFERENCE(cp) {
|
||
|
this.crStartOffset = this.offset - 1;
|
||
|
this.buffer = [AMPERSAND];
|
||
|
if (isWhitespace(cp) || cp === LESS_THAN_SIGN || cp === EOF) {
|
||
|
return this.reconsumeAs("CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
if (cp === NUMBER_SIGN) {
|
||
|
this.buffer.push(cp);
|
||
|
return "NUMERIC_CHARACTER_REFERENCE";
|
||
|
}
|
||
|
return this.reconsumeAs("NAMED_CHARACTER_REFERENCE");
|
||
|
}
|
||
|
NAMED_CHARACTER_REFERENCE(cp) {
|
||
|
for (const entitySet of entitySets) {
|
||
|
const length = entitySet.length;
|
||
|
const entities = entitySet.entities;
|
||
|
const text = this.text.slice(this.offset, this.offset + length);
|
||
|
const codepoints = entities[text];
|
||
|
if (codepoints == null) {
|
||
|
continue;
|
||
|
}
|
||
|
const semi = text.endsWith(";");
|
||
|
const next = this.text.codePointAt(this.offset + 1);
|
||
|
this.offset += length - 1;
|
||
|
this.column += length - 1;
|
||
|
if (this.returnState.startsWith("ATTR") &&
|
||
|
!semi &&
|
||
|
next != null &&
|
||
|
(next === EQUALS_SIGN || isLetter(next) || isDigit(next))) {
|
||
|
for (const cp1 of text) {
|
||
|
this.buffer.push(cp1.codePointAt(0));
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
if (!semi) {
|
||
|
this.reportParseError("missing-semicolon-after-character-reference");
|
||
|
}
|
||
|
this.buffer = codepoints;
|
||
|
}
|
||
|
return "CHARACTER_REFERENCE_END";
|
||
|
}
|
||
|
for (const cp0 of this.buffer) {
|
||
|
this.appendTokenValue(cp0, null);
|
||
|
}
|
||
|
this.appendTokenValue(cp, null);
|
||
|
return "AMBIGUOUS_AMPERSAND";
|
||
|
}
|
||
|
AMBIGUOUS_AMPERSAND(cp) {
|
||
|
while (isDigit(cp) || isLetter(cp)) {
|
||
|
this.appendTokenValue(cp, null);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
if (cp === SEMICOLON) {
|
||
|
this.reportParseError("unknown-named-character-reference");
|
||
|
}
|
||
|
return this.reconsumeAs(this.returnState);
|
||
|
}
|
||
|
NUMERIC_CHARACTER_REFERENCE(cp) {
|
||
|
this.crCode = 0;
|
||
|
if (cp === LATIN_SMALL_X || cp === LATIN_CAPITAL_X) {
|
||
|
this.buffer.push(cp);
|
||
|
return "HEXADEMICAL_CHARACTER_REFERENCE_START";
|
||
|
}
|
||
|
return this.reconsumeAs("DECIMAL_CHARACTER_REFERENCE_START");
|
||
|
}
|
||
|
HEXADEMICAL_CHARACTER_REFERENCE_START(cp) {
|
||
|
if (isHexDigit(cp)) {
|
||
|
return this.reconsumeAs("HEXADEMICAL_CHARACTER_REFERENCE");
|
||
|
}
|
||
|
this.reportParseError("absence-of-digits-in-numeric-character-reference");
|
||
|
return this.reconsumeAs("CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
DECIMAL_CHARACTER_REFERENCE_START(cp) {
|
||
|
if (isDigit(cp)) {
|
||
|
return this.reconsumeAs("DECIMAL_CHARACTER_REFERENCE");
|
||
|
}
|
||
|
this.reportParseError("absence-of-digits-in-numeric-character-reference");
|
||
|
return this.reconsumeAs("CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
HEXADEMICAL_CHARACTER_REFERENCE(cp) {
|
||
|
while (true) {
|
||
|
if (isDigit(cp)) {
|
||
|
this.crCode = 16 * this.crCode + (cp - 0x30);
|
||
|
}
|
||
|
else if (isUpperHexDigit(cp)) {
|
||
|
this.crCode = 16 * this.crCode + (cp - 0x37);
|
||
|
}
|
||
|
else if (isLowerHexDigit(cp)) {
|
||
|
this.crCode = 16 * this.crCode + (cp - 0x57);
|
||
|
}
|
||
|
else {
|
||
|
if (cp === SEMICOLON) {
|
||
|
return "NUMERIC_CHARACTER_REFERENCE_END";
|
||
|
}
|
||
|
this.reportParseError("missing-semicolon-after-character-reference");
|
||
|
return this.reconsumeAs("NUMERIC_CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
DECIMAL_CHARACTER_REFERENCE(cp) {
|
||
|
while (true) {
|
||
|
if (isDigit(cp)) {
|
||
|
this.crCode = 10 * this.crCode + (cp - 0x30);
|
||
|
}
|
||
|
else {
|
||
|
if (cp === SEMICOLON) {
|
||
|
return "NUMERIC_CHARACTER_REFERENCE_END";
|
||
|
}
|
||
|
this.reportParseError("missing-semicolon-after-character-reference");
|
||
|
return this.reconsumeAs("NUMERIC_CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
NUMERIC_CHARACTER_REFERENCE_END(_cp) {
|
||
|
let code = this.crCode;
|
||
|
if (code === 0) {
|
||
|
this.reportParseError("null-character-reference");
|
||
|
code = NULL_REPLACEMENT;
|
||
|
}
|
||
|
else if (code > 0x10ffff) {
|
||
|
this.reportParseError("character-reference-outside-unicode-range");
|
||
|
code = NULL_REPLACEMENT;
|
||
|
}
|
||
|
else if (isSurrogate(code)) {
|
||
|
this.reportParseError("surrogate-character-reference");
|
||
|
code = NULL_REPLACEMENT;
|
||
|
}
|
||
|
else if (isNonCharacter(code)) {
|
||
|
this.reportParseError("noncharacter-character-reference");
|
||
|
}
|
||
|
else if (code === 0x0d || (isControl(code) && !isWhitespace(code))) {
|
||
|
this.reportParseError("control-character-reference");
|
||
|
code = alternativeCR.get(code) || code;
|
||
|
}
|
||
|
this.buffer = [code];
|
||
|
return this.reconsumeAs("CHARACTER_REFERENCE_END");
|
||
|
}
|
||
|
CHARACTER_REFERENCE_END(_cp) {
|
||
|
assert(this.currentToken != null);
|
||
|
const token = this.currentToken;
|
||
|
const len0 = token.value.length;
|
||
|
for (const cp1 of this.buffer) {
|
||
|
this.appendTokenValue(cp1, null);
|
||
|
}
|
||
|
const newLength = token.value.length - len0;
|
||
|
for (let i = this.crStartOffset + newLength; i < this.offset; ++i) {
|
||
|
this.gaps.push(i);
|
||
|
}
|
||
|
return this.reconsumeAs(this.returnState);
|
||
|
}
|
||
|
V_EXPRESSION_START(cp) {
|
||
|
var _a;
|
||
|
if (cp === LEFT_CURLY_BRACKET) {
|
||
|
this.startToken("VExpressionStart");
|
||
|
this.appendTokenValue(LEFT_CURLY_BRACKET, null);
|
||
|
this.appendTokenValue(LEFT_CURLY_BRACKET, null);
|
||
|
if (!((_a = this.parserOptions.vueFeatures) === null || _a === void 0 ? void 0 : _a.interpolationAsNonHTML)) {
|
||
|
return this.returnState;
|
||
|
}
|
||
|
const closeIndex = this.text.indexOf("}}", this.offset + 1);
|
||
|
if (closeIndex === -1) {
|
||
|
this.reportParseError("x-missing-interpolation-end");
|
||
|
return this.returnState;
|
||
|
}
|
||
|
this.vExpressionScriptState = {
|
||
|
state: this.returnState,
|
||
|
};
|
||
|
return "V_EXPRESSION_DATA";
|
||
|
}
|
||
|
this.appendTokenValue(LEFT_CURLY_BRACKET, null);
|
||
|
return this.reconsumeAs(this.returnState);
|
||
|
}
|
||
|
V_EXPRESSION_DATA(cp) {
|
||
|
this.clearStartTokenMark();
|
||
|
const state = this.vExpressionScriptState.state;
|
||
|
while (true) {
|
||
|
const type = isWhitespace(cp)
|
||
|
? "HTMLWhitespace"
|
||
|
: state === "RCDATA"
|
||
|
? "HTMLRawText"
|
||
|
: state === "RAWTEXT"
|
||
|
? "HTMLRCDataText"
|
||
|
: "HTMLText";
|
||
|
if (this.currentToken != null && this.currentToken.type !== type) {
|
||
|
this.endToken();
|
||
|
return this.reconsumeAs(this.state);
|
||
|
}
|
||
|
if (this.currentToken == null) {
|
||
|
this.startToken(type);
|
||
|
}
|
||
|
if (cp === AMPERSAND && state !== "RAWTEXT") {
|
||
|
this.returnState = "V_EXPRESSION_DATA";
|
||
|
return "CHARACTER_REFERENCE";
|
||
|
}
|
||
|
if (cp === RIGHT_CURLY_BRACKET) {
|
||
|
this.setStartTokenMark();
|
||
|
this.returnState = "V_EXPRESSION_DATA";
|
||
|
return "V_EXPRESSION_END";
|
||
|
}
|
||
|
if (cp === EOF) {
|
||
|
this.reportParseError("x-missing-interpolation-end");
|
||
|
return "DATA";
|
||
|
}
|
||
|
if (cp === NULL) {
|
||
|
this.reportParseError("unexpected-null-character");
|
||
|
}
|
||
|
this.appendTokenValue(cp, type);
|
||
|
cp = this.consumeNextCodePoint();
|
||
|
}
|
||
|
}
|
||
|
V_EXPRESSION_END(cp) {
|
||
|
if (cp === RIGHT_CURLY_BRACKET) {
|
||
|
this.startToken("VExpressionEnd");
|
||
|
this.appendTokenValue(RIGHT_CURLY_BRACKET, null);
|
||
|
this.appendTokenValue(RIGHT_CURLY_BRACKET, null);
|
||
|
return this.vExpressionScriptState
|
||
|
? this.vExpressionScriptState.state
|
||
|
: this.returnState;
|
||
|
}
|
||
|
this.appendTokenValue(RIGHT_CURLY_BRACKET, null);
|
||
|
return this.reconsumeAs(this.returnState);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function getPossibleTypes(parsedSelector) {
|
||
|
switch (parsedSelector.type) {
|
||
|
case "identifier":
|
||
|
return [parsedSelector.value];
|
||
|
case "matches": {
|
||
|
const typesForComponents = parsedSelector.selectors.map(getPossibleTypes);
|
||
|
if (typesForComponents.every(Boolean)) {
|
||
|
return union(...typesForComponents);
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
case "compound": {
|
||
|
const typesForComponents = parsedSelector.selectors.map(getPossibleTypes).filter(Boolean);
|
||
|
if (!typesForComponents.length) {
|
||
|
return null;
|
||
|
}
|
||
|
return intersection(...typesForComponents);
|
||
|
}
|
||
|
case "child":
|
||
|
case "descendant":
|
||
|
case "sibling":
|
||
|
case "adjacent":
|
||
|
return getPossibleTypes(parsedSelector.right);
|
||
|
default:
|
||
|
return null;
|
||
|
}
|
||
|
}
|
||
|
function countClassAttributes(parsedSelector) {
|
||
|
switch (parsedSelector.type) {
|
||
|
case "child":
|
||
|
case "descendant":
|
||
|
case "sibling":
|
||
|
case "adjacent":
|
||
|
return countClassAttributes(parsedSelector.left) + countClassAttributes(parsedSelector.right);
|
||
|
case "compound":
|
||
|
case "not":
|
||
|
case "matches":
|
||
|
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countClassAttributes(childSelector), 0);
|
||
|
case "attribute":
|
||
|
case "field":
|
||
|
case "nth-child":
|
||
|
case "nth-last-child":
|
||
|
return 1;
|
||
|
default:
|
||
|
return 0;
|
||
|
}
|
||
|
}
|
||
|
function countIdentifiers(parsedSelector) {
|
||
|
switch (parsedSelector.type) {
|
||
|
case "child":
|
||
|
case "descendant":
|
||
|
case "sibling":
|
||
|
case "adjacent":
|
||
|
return countIdentifiers(parsedSelector.left) + countIdentifiers(parsedSelector.right);
|
||
|
case "compound":
|
||
|
case "not":
|
||
|
case "matches":
|
||
|
return parsedSelector.selectors.reduce((sum, childSelector) => sum + countIdentifiers(childSelector), 0);
|
||
|
case "identifier":
|
||
|
return 1;
|
||
|
default:
|
||
|
return 0;
|
||
|
}
|
||
|
}
|
||
|
function compareSpecificity(selectorA, selectorB) {
|
||
|
return selectorA.attributeCount - selectorB.attributeCount ||
|
||
|
selectorA.identifierCount - selectorB.identifierCount ||
|
||
|
(selectorA.rawSelector <= selectorB.rawSelector ? -1 : 1);
|
||
|
}
|
||
|
function tryParseSelector(rawSelector) {
|
||
|
try {
|
||
|
return esquery.parse(rawSelector.replace(/:exit$/, ""));
|
||
|
}
|
||
|
catch (err) {
|
||
|
if (typeof err.offset === "number") {
|
||
|
throw new Error(`Syntax error in selector "${rawSelector}" at position ${err.offset}: ${err.message}`);
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
const parseSelector = memoize(rawSelector => {
|
||
|
const parsedSelector = tryParseSelector(rawSelector);
|
||
|
return {
|
||
|
rawSelector,
|
||
|
isExit: rawSelector.endsWith(":exit"),
|
||
|
parsedSelector,
|
||
|
listenerTypes: getPossibleTypes(parsedSelector),
|
||
|
attributeCount: countClassAttributes(parsedSelector),
|
||
|
identifierCount: countIdentifiers(parsedSelector),
|
||
|
};
|
||
|
});
|
||
|
class NodeEventGenerator {
|
||
|
constructor(emitter, esqueryOptions) {
|
||
|
this.emitter = emitter;
|
||
|
this.esqueryOptions = esqueryOptions;
|
||
|
this.currentAncestry = [];
|
||
|
this.enterSelectorsByNodeType = new Map();
|
||
|
this.exitSelectorsByNodeType = new Map();
|
||
|
this.anyTypeEnterSelectors = [];
|
||
|
this.anyTypeExitSelectors = [];
|
||
|
const eventNames = typeof emitter.eventNames === "function"
|
||
|
? emitter.eventNames()
|
||
|
: Object.keys(emitter._events);
|
||
|
for (const rawSelector of eventNames) {
|
||
|
if (typeof rawSelector === "symbol") {
|
||
|
continue;
|
||
|
}
|
||
|
const selector = parseSelector(rawSelector);
|
||
|
if (selector.listenerTypes) {
|
||
|
for (const nodeType of selector.listenerTypes) {
|
||
|
const typeMap = selector.isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType;
|
||
|
let selectors = typeMap.get(nodeType);
|
||
|
if (selectors == null) {
|
||
|
typeMap.set(nodeType, (selectors = []));
|
||
|
}
|
||
|
selectors.push(selector);
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
(selector.isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors).push(selector);
|
||
|
}
|
||
|
}
|
||
|
this.anyTypeEnterSelectors.sort(compareSpecificity);
|
||
|
this.anyTypeExitSelectors.sort(compareSpecificity);
|
||
|
for (const selectorList of this.enterSelectorsByNodeType.values()) {
|
||
|
selectorList.sort(compareSpecificity);
|
||
|
}
|
||
|
for (const selectorList of this.exitSelectorsByNodeType.values()) {
|
||
|
selectorList.sort(compareSpecificity);
|
||
|
}
|
||
|
}
|
||
|
applySelector(node, selector) {
|
||
|
if (esquery.matches(node, selector.parsedSelector, this.currentAncestry, this.esqueryOptions)) {
|
||
|
this.emitter.emit(selector.rawSelector, node);
|
||
|
}
|
||
|
}
|
||
|
applySelectors(node, isExit) {
|
||
|
const selectorsByNodeType = (isExit ? this.exitSelectorsByNodeType : this.enterSelectorsByNodeType).get(node.type) || [];
|
||
|
const anyTypeSelectors = isExit ? this.anyTypeExitSelectors : this.anyTypeEnterSelectors;
|
||
|
let selectorsByTypeIndex = 0;
|
||
|
let anyTypeSelectorsIndex = 0;
|
||
|
while (selectorsByTypeIndex < selectorsByNodeType.length || anyTypeSelectorsIndex < anyTypeSelectors.length) {
|
||
|
if (selectorsByTypeIndex >= selectorsByNodeType.length ||
|
||
|
(anyTypeSelectorsIndex < anyTypeSelectors.length && compareSpecificity(anyTypeSelectors[anyTypeSelectorsIndex], selectorsByNodeType[selectorsByTypeIndex]) < 0)) {
|
||
|
this.applySelector(node, anyTypeSelectors[anyTypeSelectorsIndex++]);
|
||
|
}
|
||
|
else {
|
||
|
this.applySelector(node, selectorsByNodeType[selectorsByTypeIndex++]);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
enterNode(node) {
|
||
|
if (node.parent) {
|
||
|
this.currentAncestry.unshift(node.parent);
|
||
|
}
|
||
|
this.applySelectors(node, false);
|
||
|
}
|
||
|
leaveNode(node) {
|
||
|
this.applySelectors(node, true);
|
||
|
this.currentAncestry.shift();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function getStartLocation(token) {
|
||
|
return token.range[0];
|
||
|
}
|
||
|
function search(tokens, location) {
|
||
|
return sortedIndexBy(tokens, { range: [location] }, getStartLocation);
|
||
|
}
|
||
|
function getFirstIndex(tokens, indexMap, startLoc) {
|
||
|
if (startLoc in indexMap) {
|
||
|
return indexMap[startLoc];
|
||
|
}
|
||
|
if ((startLoc - 1) in indexMap) {
|
||
|
const index = indexMap[startLoc - 1];
|
||
|
const token = (index >= 0 && index < tokens.length) ? tokens[index] : null;
|
||
|
if (token && token.range[0] >= startLoc) {
|
||
|
return index;
|
||
|
}
|
||
|
return index + 1;
|
||
|
}
|
||
|
return 0;
|
||
|
}
|
||
|
function getLastIndex(tokens, indexMap, endLoc) {
|
||
|
if (endLoc in indexMap) {
|
||
|
return indexMap[endLoc] - 1;
|
||
|
}
|
||
|
if ((endLoc - 1) in indexMap) {
|
||
|
const index = indexMap[endLoc - 1];
|
||
|
const token = (index >= 0 && index < tokens.length) ? tokens[index] : null;
|
||
|
if (token && token.range[1] > endLoc) {
|
||
|
return index - 1;
|
||
|
}
|
||
|
return index;
|
||
|
}
|
||
|
return tokens.length - 1;
|
||
|
}
|
||
|
|
||
|
class Cursor {
|
||
|
constructor() {
|
||
|
this.current = null;
|
||
|
}
|
||
|
getOneToken() {
|
||
|
return this.moveNext() ? this.current : null;
|
||
|
}
|
||
|
getAllTokens() {
|
||
|
const tokens = [];
|
||
|
while (this.moveNext()) {
|
||
|
tokens.push(this.current);
|
||
|
}
|
||
|
return tokens;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class BackwardTokenCommentCursor extends Cursor {
|
||
|
constructor(tokens, comments, indexMap, startLoc, endLoc) {
|
||
|
super();
|
||
|
this.tokens = tokens;
|
||
|
this.comments = comments;
|
||
|
this.tokenIndex = getLastIndex(tokens, indexMap, endLoc);
|
||
|
this.commentIndex = search(comments, endLoc) - 1;
|
||
|
this.border = startLoc;
|
||
|
}
|
||
|
moveNext() {
|
||
|
const token = (this.tokenIndex >= 0) ? this.tokens[this.tokenIndex] : null;
|
||
|
const comment = (this.commentIndex >= 0) ? this.comments[this.commentIndex] : null;
|
||
|
if (token && (!comment || token.range[1] > comment.range[1])) {
|
||
|
this.current = token;
|
||
|
this.tokenIndex -= 1;
|
||
|
}
|
||
|
else if (comment) {
|
||
|
this.current = comment;
|
||
|
this.commentIndex -= 1;
|
||
|
}
|
||
|
else {
|
||
|
this.current = null;
|
||
|
}
|
||
|
return this.current != null && (this.border === -1 || this.current.range[0] >= this.border);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class BackwardTokenCursor extends Cursor {
|
||
|
constructor(tokens, _comments, indexMap, startLoc, endLoc) {
|
||
|
super();
|
||
|
this.tokens = tokens;
|
||
|
this.index = getLastIndex(tokens, indexMap, endLoc);
|
||
|
this.indexEnd = getFirstIndex(tokens, indexMap, startLoc);
|
||
|
}
|
||
|
moveNext() {
|
||
|
if (this.index >= this.indexEnd) {
|
||
|
this.current = this.tokens[this.index];
|
||
|
this.index -= 1;
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
getOneToken() {
|
||
|
return (this.index >= this.indexEnd) ? this.tokens[this.index] : null;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class DecorativeCursor extends Cursor {
|
||
|
constructor(cursor) {
|
||
|
super();
|
||
|
this.cursor = cursor;
|
||
|
}
|
||
|
moveNext() {
|
||
|
const retv = this.cursor.moveNext();
|
||
|
this.current = this.cursor.current;
|
||
|
return retv;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class FilterCursor extends DecorativeCursor {
|
||
|
constructor(cursor, predicate) {
|
||
|
super(cursor);
|
||
|
this.predicate = predicate;
|
||
|
}
|
||
|
moveNext() {
|
||
|
const predicate = this.predicate;
|
||
|
while (super.moveNext()) {
|
||
|
if (predicate(this.current)) {
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class ForwardTokenCommentCursor extends Cursor {
|
||
|
constructor(tokens, comments, indexMap, startLoc, endLoc) {
|
||
|
super();
|
||
|
this.tokens = tokens;
|
||
|
this.comments = comments;
|
||
|
this.tokenIndex = getFirstIndex(tokens, indexMap, startLoc);
|
||
|
this.commentIndex = search(comments, startLoc);
|
||
|
this.border = endLoc;
|
||
|
}
|
||
|
moveNext() {
|
||
|
const token = (this.tokenIndex < this.tokens.length) ? this.tokens[this.tokenIndex] : null;
|
||
|
const comment = (this.commentIndex < this.comments.length) ? this.comments[this.commentIndex] : null;
|
||
|
if (token && (!comment || token.range[0] < comment.range[0])) {
|
||
|
this.current = token;
|
||
|
this.tokenIndex += 1;
|
||
|
}
|
||
|
else if (comment) {
|
||
|
this.current = comment;
|
||
|
this.commentIndex += 1;
|
||
|
}
|
||
|
else {
|
||
|
this.current = null;
|
||
|
}
|
||
|
return this.current != null && (this.border === -1 || this.current.range[1] <= this.border);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class ForwardTokenCursor extends Cursor {
|
||
|
constructor(tokens, _comments, indexMap, startLoc, endLoc) {
|
||
|
super();
|
||
|
this.tokens = tokens;
|
||
|
this.index = getFirstIndex(tokens, indexMap, startLoc);
|
||
|
this.indexEnd = getLastIndex(tokens, indexMap, endLoc);
|
||
|
}
|
||
|
moveNext() {
|
||
|
if (this.index <= this.indexEnd) {
|
||
|
this.current = this.tokens[this.index];
|
||
|
this.index += 1;
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
getOneToken() {
|
||
|
return (this.index <= this.indexEnd) ? this.tokens[this.index] : null;
|
||
|
}
|
||
|
getAllTokens() {
|
||
|
return this.tokens.slice(this.index, this.indexEnd + 1);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class LimitCursor extends DecorativeCursor {
|
||
|
constructor(cursor, count) {
|
||
|
super(cursor);
|
||
|
this.count = count;
|
||
|
}
|
||
|
moveNext() {
|
||
|
if (this.count > 0) {
|
||
|
this.count -= 1;
|
||
|
return super.moveNext();
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class SkipCursor extends DecorativeCursor {
|
||
|
constructor(cursor, count) {
|
||
|
super(cursor);
|
||
|
this.count = count;
|
||
|
}
|
||
|
moveNext() {
|
||
|
while (this.count > 0) {
|
||
|
this.count -= 1;
|
||
|
if (!super.moveNext()) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
return super.moveNext();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class CursorFactory {
|
||
|
constructor(TokenCursor, TokenCommentCursor) {
|
||
|
this.TokenCursor = TokenCursor;
|
||
|
this.TokenCommentCursor = TokenCommentCursor;
|
||
|
}
|
||
|
createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments) {
|
||
|
const TokenCursor = includeComments ? this.TokenCommentCursor : this.TokenCursor;
|
||
|
return new TokenCursor(tokens, comments, indexMap, startLoc, endLoc);
|
||
|
}
|
||
|
createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, count) {
|
||
|
let cursor = this.createBaseCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments);
|
||
|
if (filter) {
|
||
|
cursor = new FilterCursor(cursor, filter);
|
||
|
}
|
||
|
if (skip >= 1) {
|
||
|
cursor = new SkipCursor(cursor, skip);
|
||
|
}
|
||
|
if (count >= 0) {
|
||
|
cursor = new LimitCursor(cursor, count);
|
||
|
}
|
||
|
return cursor;
|
||
|
}
|
||
|
}
|
||
|
const forward = new CursorFactory(ForwardTokenCursor, ForwardTokenCommentCursor);
|
||
|
const backward = new CursorFactory(BackwardTokenCursor, BackwardTokenCommentCursor);
|
||
|
|
||
|
class PaddedTokenCursor extends ForwardTokenCursor {
|
||
|
constructor(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) {
|
||
|
super(tokens, comments, indexMap, startLoc, endLoc);
|
||
|
this.index = Math.max(0, this.index - beforeCount);
|
||
|
this.indexEnd = Math.min(tokens.length - 1, this.indexEnd + afterCount);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function isCommentToken(token) {
|
||
|
return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
|
||
|
}
|
||
|
function createIndexMap(tokens, comments) {
|
||
|
const map = Object.create(null);
|
||
|
let tokenIndex = 0;
|
||
|
let commentIndex = 0;
|
||
|
let nextStart = 0;
|
||
|
let range = null;
|
||
|
while (tokenIndex < tokens.length || commentIndex < comments.length) {
|
||
|
nextStart = (commentIndex < comments.length) ? comments[commentIndex].range[0] : Number.MAX_SAFE_INTEGER;
|
||
|
while (tokenIndex < tokens.length && (range = tokens[tokenIndex].range)[0] < nextStart) {
|
||
|
map[range[0]] = tokenIndex;
|
||
|
map[range[1] - 1] = tokenIndex;
|
||
|
tokenIndex += 1;
|
||
|
}
|
||
|
nextStart = (tokenIndex < tokens.length) ? tokens[tokenIndex].range[0] : Number.MAX_SAFE_INTEGER;
|
||
|
while (commentIndex < comments.length && (range = comments[commentIndex].range)[0] < nextStart) {
|
||
|
map[range[0]] = tokenIndex;
|
||
|
map[range[1] - 1] = tokenIndex;
|
||
|
commentIndex += 1;
|
||
|
}
|
||
|
}
|
||
|
return map;
|
||
|
}
|
||
|
function createCursorWithSkip(factory, tokens, comments, indexMap, startLoc, endLoc, opts) {
|
||
|
let includeComments = false;
|
||
|
let skip = 0;
|
||
|
let filter = null;
|
||
|
if (typeof opts === "number") {
|
||
|
skip = opts | 0;
|
||
|
}
|
||
|
else if (typeof opts === "function") {
|
||
|
filter = opts;
|
||
|
}
|
||
|
else if (opts) {
|
||
|
includeComments = Boolean(opts.includeComments);
|
||
|
skip = opts.skip || 0;
|
||
|
filter = opts.filter || null;
|
||
|
}
|
||
|
assert(skip >= 0, "options.skip should be zero or a positive integer.");
|
||
|
assert(!filter || typeof filter === "function", "options.filter should be a function.");
|
||
|
return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, skip, -1);
|
||
|
}
|
||
|
function createCursorWithCount(factory, tokens, comments, indexMap, startLoc, endLoc, opts) {
|
||
|
let includeComments = false;
|
||
|
let count = 0;
|
||
|
let countExists = false;
|
||
|
let filter = null;
|
||
|
if (typeof opts === "number") {
|
||
|
count = opts | 0;
|
||
|
countExists = true;
|
||
|
}
|
||
|
else if (typeof opts === "function") {
|
||
|
filter = opts;
|
||
|
}
|
||
|
else if (opts) {
|
||
|
includeComments = Boolean(opts.includeComments);
|
||
|
count = opts.count || 0;
|
||
|
countExists = typeof opts.count === "number";
|
||
|
filter = opts.filter || null;
|
||
|
}
|
||
|
assert(count >= 0, "options.count should be zero or a positive integer.");
|
||
|
assert(!filter || typeof filter === "function", "options.filter should be a function.");
|
||
|
return factory.createCursor(tokens, comments, indexMap, startLoc, endLoc, includeComments, filter, 0, countExists ? count : -1);
|
||
|
}
|
||
|
function createCursorWithPadding(tokens, comments, indexMap, startLoc, endLoc, beforeCount, afterCount) {
|
||
|
if (typeof beforeCount === "undefined" && typeof afterCount === "undefined") {
|
||
|
return new ForwardTokenCursor(tokens, comments, indexMap, startLoc, endLoc);
|
||
|
}
|
||
|
if (typeof beforeCount === "number" || typeof beforeCount === "undefined") {
|
||
|
return new PaddedTokenCursor(tokens, comments, indexMap, startLoc, endLoc, beforeCount || 0, afterCount || 0);
|
||
|
}
|
||
|
return createCursorWithCount(forward, tokens, comments, indexMap, startLoc, endLoc, beforeCount);
|
||
|
}
|
||
|
function getAdjacentCommentTokensFromCursor(cursor) {
|
||
|
const tokens = [];
|
||
|
let currentToken = cursor.getOneToken();
|
||
|
while (currentToken && isCommentToken(currentToken)) {
|
||
|
tokens.push(currentToken);
|
||
|
currentToken = cursor.getOneToken();
|
||
|
}
|
||
|
return tokens;
|
||
|
}
|
||
|
class TokenStore {
|
||
|
constructor(tokens, comments) {
|
||
|
this._tokens = tokens;
|
||
|
this._comments = comments;
|
||
|
this._indexMap = createIndexMap(tokens, comments);
|
||
|
}
|
||
|
getTokenByRangeStart(offset, options) {
|
||
|
const includeComments = Boolean(options && options.includeComments);
|
||
|
const token = forward.createBaseCursor(this._tokens, this._comments, this._indexMap, offset, -1, includeComments).getOneToken();
|
||
|
if (token && token.range[0] === offset) {
|
||
|
return token;
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
getFirstToken(node, options) {
|
||
|
return createCursorWithSkip(forward, this._tokens, this._comments, this._indexMap, node.range[0], node.range[1], options).getOneToken();
|
||
|
}
|
||
|
getLastToken(node, options) {
|
||
|
return createCursorWithSkip(backward, this._tokens, this._comments, this._indexMap, node.range[0], node.range[1], options).getOneToken();
|
||
|
}
|
||
|
getTokenBefore(node, options) {
|
||
|
return createCursorWithSkip(backward, this._tokens, this._comments, this._indexMap, -1, node.range[0], options).getOneToken();
|
||
|
}
|
||
|
getTokenAfter(node, options) {
|
||
|
return createCursorWithSkip(forward, this._tokens, this._comments, this._indexMap, node.range[1], -1, options).getOneToken();
|
||
|
}
|
||
|
getFirstTokenBetween(left, right, options) {
|
||
|
return createCursorWithSkip(forward, this._tokens, this._comments, this._indexMap, left.range[1], right.range[0], options).getOneToken();
|
||
|
}
|
||
|
getLastTokenBetween(left, right, options) {
|
||
|
return createCursorWithSkip(backward, this._tokens, this._comments, this._indexMap, left.range[1], right.range[0], options).getOneToken();
|
||
|
}
|
||
|
getTokenOrCommentBefore(node, skip) {
|
||
|
return this.getTokenBefore(node, { includeComments: true, skip });
|
||
|
}
|
||
|
getTokenOrCommentAfter(node, skip) {
|
||
|
return this.getTokenAfter(node, { includeComments: true, skip });
|
||
|
}
|
||
|
getFirstTokens(node, options) {
|
||
|
return createCursorWithCount(forward, this._tokens, this._comments, this._indexMap, node.range[0], node.range[1], options).getAllTokens();
|
||
|
}
|
||
|
getLastTokens(node, options) {
|
||
|
return createCursorWithCount(backward, this._tokens, this._comments, this._indexMap, node.range[0], node.range[1], options).getAllTokens().reverse();
|
||
|
}
|
||
|
getTokensBefore(node, options) {
|
||
|
return createCursorWithCount(backward, this._tokens, this._comments, this._indexMap, -1, node.range[0], options).getAllTokens().reverse();
|
||
|
}
|
||
|
getTokensAfter(node, options) {
|
||
|
return createCursorWithCount(forward, this._tokens, this._comments, this._indexMap, node.range[1], -1, options).getAllTokens();
|
||
|
}
|
||
|
getFirstTokensBetween(left, right, options) {
|
||
|
return createCursorWithCount(forward, this._tokens, this._comments, this._indexMap, left.range[1], right.range[0], options).getAllTokens();
|
||
|
}
|
||
|
getLastTokensBetween(left, right, options) {
|
||
|
return createCursorWithCount(backward, this._tokens, this._comments, this._indexMap, left.range[1], right.range[0], options).getAllTokens().reverse();
|
||
|
}
|
||
|
getTokens(node, beforeCount, afterCount) {
|
||
|
return createCursorWithPadding(this._tokens, this._comments, this._indexMap, node.range[0], node.range[1], beforeCount, afterCount).getAllTokens();
|
||
|
}
|
||
|
getTokensBetween(left, right, padding) {
|
||
|
return createCursorWithPadding(this._tokens, this._comments, this._indexMap, left.range[1], right.range[0], padding, typeof padding === "number" ? padding : undefined).getAllTokens();
|
||
|
}
|
||
|
commentsExistBetween(left, right) {
|
||
|
const index = search(this._comments, left.range[1]);
|
||
|
return (index < this._comments.length &&
|
||
|
this._comments[index].range[1] <= right.range[0]);
|
||
|
}
|
||
|
getCommentsBefore(nodeOrToken) {
|
||
|
const cursor = createCursorWithCount(backward, this._tokens, this._comments, this._indexMap, -1, nodeOrToken.range[0], { includeComments: true });
|
||
|
return getAdjacentCommentTokensFromCursor(cursor).reverse();
|
||
|
}
|
||
|
getCommentsAfter(nodeOrToken) {
|
||
|
const cursor = createCursorWithCount(forward, this._tokens, this._comments, this._indexMap, nodeOrToken.range[1], -1, { includeComments: true });
|
||
|
return getAdjacentCommentTokensFromCursor(cursor);
|
||
|
}
|
||
|
getCommentsInside(node) {
|
||
|
return this.getTokens(node, {
|
||
|
includeComments: true,
|
||
|
filter: isCommentToken,
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function isVElement(node) {
|
||
|
return node.type === "VElement";
|
||
|
}
|
||
|
function getCustomBlocks(document) {
|
||
|
return document
|
||
|
? document.children
|
||
|
.filter(isVElement)
|
||
|
.filter((block) => block.name !== "script" &&
|
||
|
block.name !== "template" &&
|
||
|
block.name !== "style")
|
||
|
: [];
|
||
|
}
|
||
|
function parseCustomBlockElement(node, parser, globalLocationCalculator, parserOptions) {
|
||
|
const text = node.children[0];
|
||
|
const { code, range, loc } = text != null && text.type === "VText"
|
||
|
? {
|
||
|
code: text.value,
|
||
|
range: text.range,
|
||
|
loc: text.loc,
|
||
|
}
|
||
|
: {
|
||
|
code: "",
|
||
|
range: [
|
||
|
node.startTag.range[1],
|
||
|
node.endTag.range[0],
|
||
|
],
|
||
|
loc: {
|
||
|
start: node.startTag.loc.end,
|
||
|
end: node.endTag.loc.start,
|
||
|
},
|
||
|
};
|
||
|
const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(range[0]);
|
||
|
try {
|
||
|
return parseCustomBlockFragment(code, parser, locationCalculator, parserOptions);
|
||
|
}
|
||
|
catch (e) {
|
||
|
return {
|
||
|
error: e,
|
||
|
ast: {
|
||
|
type: "Program",
|
||
|
sourceType: "module",
|
||
|
loc: {
|
||
|
start: Object.assign({}, loc.start),
|
||
|
end: Object.assign({}, loc.end),
|
||
|
},
|
||
|
range: [...range],
|
||
|
body: [],
|
||
|
tokens: [],
|
||
|
comments: [],
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
function parseCustomBlockFragment(code, parser, locationCalculator, parserOptions) {
|
||
|
try {
|
||
|
const result = parseBlock(code, parser, Object.assign({ ecmaVersion: DEFAULT_ECMA_VERSION, loc: true, range: true, raw: true, tokens: true, comment: true, eslintVisitorKeys: true, eslintScopeManager: true }, parserOptions));
|
||
|
fixLocations(result, locationCalculator);
|
||
|
return result;
|
||
|
}
|
||
|
catch (err) {
|
||
|
const perr = ParseError.normalize(err);
|
||
|
if (perr) {
|
||
|
fixErrorLocation(perr, locationCalculator);
|
||
|
throw perr;
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
function parseBlock(code, parser, parserOptions) {
|
||
|
const result = typeof parser.parseForESLint === "function"
|
||
|
? parser.parseForESLint(code, parserOptions)
|
||
|
: parser.parse(code, parserOptions);
|
||
|
if (result.ast != null) {
|
||
|
return result;
|
||
|
}
|
||
|
return { ast: result };
|
||
|
}
|
||
|
function createCustomBlockSharedContext({ text, customBlock, parsedResult, globalLocationCalculator, parserOptions, }) {
|
||
|
let sourceCode;
|
||
|
let scopeManager;
|
||
|
let currentNode;
|
||
|
return {
|
||
|
serCurrentNode(node) {
|
||
|
currentNode = node;
|
||
|
},
|
||
|
context: {
|
||
|
getAncestors: () => getAncestors(currentNode),
|
||
|
getDeclaredVariables: (...args) => getScopeManager().getDeclaredVariables(...args),
|
||
|
getScope: () => getScope(getScopeManager(), currentNode),
|
||
|
markVariableAsUsed: (name) => markVariableAsUsed(getScopeManager(), currentNode, parserOptions, name),
|
||
|
parserServices: Object.assign(Object.assign({ customBlock, parseCustomBlockElement(parser, options) {
|
||
|
return parseCustomBlockElement(customBlock, parser, globalLocationCalculator, Object.assign(Object.assign({}, parserOptions), options));
|
||
|
} }, (parsedResult.services || {})), (parsedResult.error
|
||
|
? { parseError: parsedResult.error }
|
||
|
: {})),
|
||
|
getSourceCode,
|
||
|
},
|
||
|
};
|
||
|
function getSourceCode() {
|
||
|
return (sourceCode ||
|
||
|
(sourceCode = new (require("eslint").SourceCode)({
|
||
|
text,
|
||
|
ast: parsedResult.ast,
|
||
|
parserServices: parsedResult.services,
|
||
|
scopeManager: getScopeManager(),
|
||
|
visitorKeys: parsedResult.visitorKeys,
|
||
|
})));
|
||
|
}
|
||
|
function getScopeManager() {
|
||
|
if (parsedResult.scopeManager || scopeManager) {
|
||
|
return parsedResult.scopeManager || scopeManager;
|
||
|
}
|
||
|
const ecmaVersion = getEcmaVersionIfUseEspree(parserOptions) || 2022;
|
||
|
const ecmaFeatures = parserOptions.ecmaFeatures || {};
|
||
|
const sourceType = parserOptions.sourceType || "script";
|
||
|
scopeManager = getEslintScope().analyze(parsedResult.ast, {
|
||
|
ignoreEval: true,
|
||
|
nodejsScope: false,
|
||
|
impliedStrict: ecmaFeatures.impliedStrict,
|
||
|
ecmaVersion,
|
||
|
sourceType,
|
||
|
fallback: getFallbackKeys,
|
||
|
});
|
||
|
return scopeManager;
|
||
|
}
|
||
|
}
|
||
|
function getAncestors(node) {
|
||
|
const ancestorsStartingAtParent = [];
|
||
|
for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
|
||
|
ancestorsStartingAtParent.push(ancestor);
|
||
|
}
|
||
|
return ancestorsStartingAtParent.reverse();
|
||
|
}
|
||
|
function getScope(scopeManager, currentNode) {
|
||
|
const inner = currentNode.type !== "Program";
|
||
|
for (let node = currentNode; node; node = node.parent || null) {
|
||
|
const scope = scopeManager.acquire(node, inner);
|
||
|
if (scope) {
|
||
|
if (scope.type === "function-expression-name") {
|
||
|
return scope.childScopes[0];
|
||
|
}
|
||
|
return scope;
|
||
|
}
|
||
|
}
|
||
|
return scopeManager.scopes[0];
|
||
|
}
|
||
|
function markVariableAsUsed(scopeManager, currentNode, parserOptions, name) {
|
||
|
const hasGlobalReturn = parserOptions.ecmaFeatures && parserOptions.ecmaFeatures.globalReturn;
|
||
|
const specialScope = hasGlobalReturn || parserOptions.sourceType === "module";
|
||
|
const currentScope = getScope(scopeManager, currentNode);
|
||
|
const initialScope = currentScope.type === "global" && specialScope
|
||
|
? currentScope.childScopes[0]
|
||
|
: currentScope;
|
||
|
for (let scope = initialScope; scope; scope = scope.upper) {
|
||
|
const variable = scope.variables.find((scopeVar) => scopeVar.name === name);
|
||
|
if (variable) {
|
||
|
variable.eslintUsed = true;
|
||
|
return true;
|
||
|
}
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
function define(sourceText, rootAST, document, globalLocationCalculator, { parserOptions }) {
|
||
|
const templateBodyEmitters = new Map();
|
||
|
const stores = new WeakMap();
|
||
|
const documentEmitters = new Map();
|
||
|
const customBlocksEmitters = new Map();
|
||
|
const isSFC = isSFCFile(parserOptions);
|
||
|
return {
|
||
|
defineTemplateBodyVisitor(templateBodyVisitor, scriptVisitor, options) {
|
||
|
var _a;
|
||
|
if (scriptVisitor == null) {
|
||
|
scriptVisitor = {};
|
||
|
}
|
||
|
if (rootAST.templateBody == null) {
|
||
|
return scriptVisitor;
|
||
|
}
|
||
|
const templateBodyTriggerSelector = (_a = options === null || options === void 0 ? void 0 : options.templateBodyTriggerSelector) !== null && _a !== void 0 ? _a : "Program:exit";
|
||
|
let emitter = templateBodyEmitters.get(templateBodyTriggerSelector);
|
||
|
if (emitter == null) {
|
||
|
emitter = new EventEmitter();
|
||
|
emitter.setMaxListeners(0);
|
||
|
templateBodyEmitters.set(templateBodyTriggerSelector, emitter);
|
||
|
const programExitHandler = scriptVisitor[templateBodyTriggerSelector];
|
||
|
scriptVisitor[templateBodyTriggerSelector] = (node) => {
|
||
|
try {
|
||
|
if (typeof programExitHandler === "function") {
|
||
|
programExitHandler(node);
|
||
|
}
|
||
|
const generator = new NodeEventGenerator(emitter, {
|
||
|
visitorKeys: KEYS,
|
||
|
fallback: getFallbackKeys,
|
||
|
});
|
||
|
traverseNodes(rootAST.templateBody, generator);
|
||
|
}
|
||
|
finally {
|
||
|
scriptVisitor[templateBodyTriggerSelector] =
|
||
|
programExitHandler;
|
||
|
templateBodyEmitters.delete(templateBodyTriggerSelector);
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
for (const selector of Object.keys(templateBodyVisitor)) {
|
||
|
emitter.on(selector, templateBodyVisitor[selector]);
|
||
|
}
|
||
|
return scriptVisitor;
|
||
|
},
|
||
|
defineDocumentVisitor(documentVisitor, options) {
|
||
|
var _a;
|
||
|
const scriptVisitor = {};
|
||
|
if (!document) {
|
||
|
return scriptVisitor;
|
||
|
}
|
||
|
const documentTriggerSelector = (_a = options === null || options === void 0 ? void 0 : options.triggerSelector) !== null && _a !== void 0 ? _a : "Program:exit";
|
||
|
let emitter = documentEmitters.get(documentTriggerSelector);
|
||
|
if (emitter == null) {
|
||
|
emitter = new EventEmitter();
|
||
|
emitter.setMaxListeners(0);
|
||
|
documentEmitters.set(documentTriggerSelector, emitter);
|
||
|
const programExitHandler = scriptVisitor[documentTriggerSelector];
|
||
|
scriptVisitor[documentTriggerSelector] = (node) => {
|
||
|
try {
|
||
|
if (typeof programExitHandler === "function") {
|
||
|
programExitHandler(node);
|
||
|
}
|
||
|
const generator = new NodeEventGenerator(emitter, {
|
||
|
visitorKeys: KEYS,
|
||
|
fallback: getFallbackKeys,
|
||
|
});
|
||
|
traverseNodes(document, generator);
|
||
|
}
|
||
|
finally {
|
||
|
scriptVisitor[documentTriggerSelector] =
|
||
|
programExitHandler;
|
||
|
documentEmitters.delete(documentTriggerSelector);
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
for (const selector of Object.keys(documentVisitor)) {
|
||
|
emitter.on(selector, documentVisitor[selector]);
|
||
|
}
|
||
|
return scriptVisitor;
|
||
|
},
|
||
|
defineCustomBlocksVisitor(context, parser, rule, scriptVisitor) {
|
||
|
var _a;
|
||
|
if (scriptVisitor == null) {
|
||
|
scriptVisitor = {};
|
||
|
}
|
||
|
if (!isSFC) {
|
||
|
return scriptVisitor;
|
||
|
}
|
||
|
parserOptions = Object.assign({}, parserOptions);
|
||
|
const customBlocks = getCustomBlocks(document).filter((block) => block.endTag &&
|
||
|
!block.startTag.attributes.some((attr) => !attr.directive && attr.key.name === "src"));
|
||
|
if (!customBlocks.length || globalLocationCalculator == null) {
|
||
|
return {};
|
||
|
}
|
||
|
const key = (_a = parser.parseForESLint) !== null && _a !== void 0 ? _a : parser.parse;
|
||
|
let factories = customBlocksEmitters.get(key);
|
||
|
if (factories == null) {
|
||
|
factories = [];
|
||
|
customBlocksEmitters.set(key, factories);
|
||
|
const visitorFactories = factories;
|
||
|
const programExitHandler = scriptVisitor["Program:exit"];
|
||
|
scriptVisitor["Program:exit"] = (node) => {
|
||
|
try {
|
||
|
if (typeof programExitHandler === "function") {
|
||
|
programExitHandler(node);
|
||
|
}
|
||
|
for (const customBlock of customBlocks) {
|
||
|
const lang = getLang(customBlock);
|
||
|
const activeVisitorFactories = visitorFactories.filter((f) => f.test(lang, customBlock));
|
||
|
if (!activeVisitorFactories.length) {
|
||
|
continue;
|
||
|
}
|
||
|
const parsedResult = parseCustomBlockElement(customBlock, parser, globalLocationCalculator, parserOptions);
|
||
|
const { serCurrentNode, context: customBlockContext, } = createCustomBlockSharedContext({
|
||
|
text: sourceText,
|
||
|
customBlock,
|
||
|
parsedResult,
|
||
|
globalLocationCalculator,
|
||
|
parserOptions,
|
||
|
});
|
||
|
const emitter = new EventEmitter();
|
||
|
emitter.setMaxListeners(0);
|
||
|
for (const factory of activeVisitorFactories) {
|
||
|
const ctx = Object.assign({}, customBlockContext);
|
||
|
ctx.__proto__ = factory.context;
|
||
|
const visitor = factory.create(ctx);
|
||
|
for (const selector of Object.keys(visitor || {})) {
|
||
|
emitter.on(selector, visitor[selector]);
|
||
|
}
|
||
|
}
|
||
|
const generator = new NodeEventGenerator(emitter, {
|
||
|
visitorKeys: parsedResult.visitorKeys,
|
||
|
fallback: getFallbackKeys,
|
||
|
});
|
||
|
traverseNodes(parsedResult.ast, {
|
||
|
visitorKeys: parsedResult.visitorKeys,
|
||
|
enterNode(n) {
|
||
|
serCurrentNode(n);
|
||
|
generator.enterNode(n);
|
||
|
},
|
||
|
leaveNode(n) {
|
||
|
serCurrentNode(n);
|
||
|
generator.leaveNode(n);
|
||
|
},
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
finally {
|
||
|
scriptVisitor["Program:exit"] = programExitHandler;
|
||
|
customBlocksEmitters.delete(key);
|
||
|
}
|
||
|
};
|
||
|
}
|
||
|
const target = rule.target;
|
||
|
const test = typeof target === "function"
|
||
|
? target
|
||
|
: Array.isArray(target)
|
||
|
? (lang) => Boolean(lang && target.includes(lang))
|
||
|
: (lang) => target === lang;
|
||
|
factories.push({
|
||
|
context,
|
||
|
test,
|
||
|
create: rule.create,
|
||
|
});
|
||
|
return scriptVisitor;
|
||
|
},
|
||
|
getTemplateBodyTokenStore() {
|
||
|
const key = document || stores;
|
||
|
let store = stores.get(key);
|
||
|
if (!store) {
|
||
|
store =
|
||
|
document != null
|
||
|
? new TokenStore(document.tokens, document.comments)
|
||
|
: new TokenStore([], []);
|
||
|
stores.set(key, store);
|
||
|
}
|
||
|
return store;
|
||
|
},
|
||
|
getDocumentFragment() {
|
||
|
return document;
|
||
|
},
|
||
|
};
|
||
|
}
|
||
|
|
||
|
class CodeBlocks {
|
||
|
constructor() {
|
||
|
this.remapBlocks = [];
|
||
|
this.splitPunctuators = [];
|
||
|
this.code = "";
|
||
|
}
|
||
|
get length() {
|
||
|
return this.code.length;
|
||
|
}
|
||
|
append(codeLet, originalOffset) {
|
||
|
const rangeStart = this.code.length;
|
||
|
this.code += codeLet.trimRight();
|
||
|
this.remapBlocks.push({
|
||
|
range: [rangeStart, this.code.length],
|
||
|
offset: originalOffset - rangeStart,
|
||
|
});
|
||
|
}
|
||
|
appendSplitPunctuators(punctuator) {
|
||
|
this.splitPunctuators.push(this.code.length, this.code.length + 1);
|
||
|
this.code += `\n${punctuator}\n`;
|
||
|
}
|
||
|
appendCodeBlocks(codeBlocks) {
|
||
|
const start = this.code.length;
|
||
|
this.code += codeBlocks.code;
|
||
|
this.remapBlocks.push(...codeBlocks.remapBlocks.map((b) => ({
|
||
|
range: [b.range[0] + start, b.range[1] + start],
|
||
|
offset: b.offset - start,
|
||
|
})));
|
||
|
this.splitPunctuators.push(...codeBlocks.splitPunctuators.map((s) => s + start));
|
||
|
}
|
||
|
}
|
||
|
class RestoreASTCallbacks {
|
||
|
constructor() {
|
||
|
this.callbacks = [];
|
||
|
}
|
||
|
addCallback(originalOffsetStart, range, callback) {
|
||
|
this.callbacks.push({
|
||
|
range: [
|
||
|
originalOffsetStart + range[0],
|
||
|
originalOffsetStart + range[1],
|
||
|
],
|
||
|
callback,
|
||
|
});
|
||
|
}
|
||
|
restore(program, scriptSetupStatements, linesAndColumns) {
|
||
|
if (this.callbacks.length === 0) {
|
||
|
return;
|
||
|
}
|
||
|
const callbacks = new Set(this.callbacks);
|
||
|
for (const statement of scriptSetupStatements) {
|
||
|
for (const cb of callbacks) {
|
||
|
if (cb.range[0] <= statement.range[0] &&
|
||
|
statement.range[1] <= cb.range[1]) {
|
||
|
const restored = cb.callback(statement);
|
||
|
if (restored) {
|
||
|
const removeIndex = program.body.indexOf(statement);
|
||
|
if (removeIndex >= 0) {
|
||
|
program.body.splice(removeIndex, 1);
|
||
|
program.body.push(restored.statement);
|
||
|
program.tokens.push(...restored.tokens);
|
||
|
restored.statement.parent = program;
|
||
|
callbacks.delete(cb);
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if (callbacks.size) {
|
||
|
const [cb] = callbacks;
|
||
|
const loc = linesAndColumns.getLocFromIndex(cb.range[0]);
|
||
|
throw new ParseError("Could not parse <script setup>. Failed to restore ExportNamedDeclaration.", undefined, cb.range[0], loc.line, loc.column);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
function parseScript$1(code, parserOptions, locationCalculator) {
|
||
|
try {
|
||
|
return parseScript(code, parserOptions);
|
||
|
}
|
||
|
catch (err) {
|
||
|
const perr = ParseError.normalize(err);
|
||
|
if (perr) {
|
||
|
fixErrorLocation(perr, locationCalculator);
|
||
|
throw perr;
|
||
|
}
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
function parseScriptSetupElements(scriptSetupElement, scriptElement, code, linesAndColumns, originalParserOptions) {
|
||
|
const parserOptions = getScriptSetupParserOptions(originalParserOptions);
|
||
|
const scriptSetupModuleCodeBlocks = getScriptSetupModuleCodeBlocks(scriptSetupElement, scriptElement, code, linesAndColumns, parserOptions);
|
||
|
if (!scriptSetupModuleCodeBlocks) {
|
||
|
return parseScriptFragment("", simpleOffsetLocationCalculator(scriptSetupElement.startTag.range[1], linesAndColumns), parserOptions);
|
||
|
}
|
||
|
const locationCalculator = {
|
||
|
getFixOffset(offset, kind) {
|
||
|
const test = kind === "start"
|
||
|
? (block) => offset < block.range[1]
|
||
|
: (block) => offset <= block.range[1];
|
||
|
for (const block of scriptSetupModuleCodeBlocks.codeBlocks
|
||
|
.remapBlocks) {
|
||
|
if (test(block)) {
|
||
|
return block.offset;
|
||
|
}
|
||
|
}
|
||
|
return offset;
|
||
|
},
|
||
|
getLocFromIndex: linesAndColumns.getLocFromIndex.bind(linesAndColumns),
|
||
|
};
|
||
|
const result = parseScript$1(scriptSetupModuleCodeBlocks.codeBlocks.code, parserOptions, locationCalculator);
|
||
|
const scriptSetupStatements = remapAST(result, scriptSetupModuleCodeBlocks);
|
||
|
remapLocationAndTokens(result, scriptSetupModuleCodeBlocks, locationCalculator);
|
||
|
if (scriptSetupModuleCodeBlocks.restoreASTCallbacks) {
|
||
|
scriptSetupModuleCodeBlocks.restoreASTCallbacks.restore(result.ast, scriptSetupStatements, linesAndColumns);
|
||
|
}
|
||
|
if (result.ast.tokens != null) {
|
||
|
for (const node of [scriptSetupElement, scriptElement]) {
|
||
|
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>",
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
result.ast.tokens.sort((a, b) => a.range[0] - b.range[0]);
|
||
|
}
|
||
|
result.ast.body.sort((a, b) => a.range[0] - b.range[0]);
|
||
|
const programEndOffset = result.ast.body.reduce((end, node) => Math.max(end, node.range[1]), 0);
|
||
|
result.ast.range[1] = programEndOffset;
|
||
|
result.ast.loc.end = locationCalculator.getLocFromIndex(programEndOffset);
|
||
|
if (result.ast.end != null) {
|
||
|
result.ast.end = [scriptSetupElement, scriptElement].reduce((end, node) => {
|
||
|
var _a, _b;
|
||
|
const textNode = node.children[0];
|
||
|
return Math.max(end, textNode != null && textNode.type === "VText"
|
||
|
? textNode.range[1]
|
||
|
: (_b = (_a = node.endTag) === null || _a === void 0 ? void 0 : _a.range[1]) !== null && _b !== void 0 ? _b : node.range[1]);
|
||
|
}, 0);
|
||
|
}
|
||
|
return result;
|
||
|
}
|
||
|
function getScriptSetupModuleCodeBlocks(scriptSetupElement, scriptElement, sfcCode, linesAndColumns, parserOptions) {
|
||
|
const scriptSetupCodeBlocks = getScriptSetupCodeBlocks(scriptSetupElement, sfcCode, linesAndColumns, parserOptions);
|
||
|
const textNode = scriptElement.children[0];
|
||
|
if (textNode == null || textNode.type !== "VText") {
|
||
|
return scriptSetupCodeBlocks;
|
||
|
}
|
||
|
const [scriptStartOffset, scriptEndOffset] = textNode.range;
|
||
|
const codeBlocks = new CodeBlocks();
|
||
|
codeBlocks.append(sfcCode.slice(scriptStartOffset, scriptEndOffset), scriptStartOffset);
|
||
|
if (scriptSetupCodeBlocks == null) {
|
||
|
return { codeBlocks };
|
||
|
}
|
||
|
codeBlocks.appendSplitPunctuators(";");
|
||
|
const scriptSetupOffset = codeBlocks.length;
|
||
|
codeBlocks.appendCodeBlocks(scriptSetupCodeBlocks.codeBlocks);
|
||
|
return {
|
||
|
codeBlocks,
|
||
|
scriptSetupBlockRange: [
|
||
|
scriptSetupCodeBlocks.scriptSetupBlockRange[0] + scriptSetupOffset,
|
||
|
scriptSetupCodeBlocks.scriptSetupBlockRange[1] + scriptSetupOffset,
|
||
|
],
|
||
|
restoreASTCallbacks: scriptSetupCodeBlocks.restoreASTCallbacks,
|
||
|
};
|
||
|
}
|
||
|
function getScriptSetupCodeBlocks(node, sfcCode, linesAndColumns, parserOptions) {
|
||
|
const textNode = node.children[0];
|
||
|
if (textNode == null || textNode.type !== "VText") {
|
||
|
return null;
|
||
|
}
|
||
|
const [scriptSetupStartOffset, scriptSetupEndOffset] = textNode.range;
|
||
|
const scriptCode = sfcCode.slice(scriptSetupStartOffset, scriptSetupEndOffset);
|
||
|
const offsetLocationCalculator = simpleOffsetLocationCalculator(scriptSetupStartOffset, linesAndColumns);
|
||
|
const result = parseScript$1(scriptCode, parserOptions, offsetLocationCalculator);
|
||
|
const { ast } = result;
|
||
|
const importCodeBlocks = new CodeBlocks();
|
||
|
const statementCodeBlocks = new CodeBlocks();
|
||
|
const exportDefaultCodeBlocks = new CodeBlocks();
|
||
|
const restoreASTCallbacks = new RestoreASTCallbacks();
|
||
|
let astOffset = 0;
|
||
|
function processAppend(codeBlocks, start, end) {
|
||
|
if (start < end) {
|
||
|
codeBlocks.append(scriptCode.slice(start, end), scriptSetupStartOffset + start);
|
||
|
astOffset = end;
|
||
|
}
|
||
|
}
|
||
|
function processStatementCodeBlock(start) {
|
||
|
if (astOffset < start) {
|
||
|
processAppend(statementCodeBlocks, astOffset, start);
|
||
|
statementCodeBlocks.appendSplitPunctuators(";");
|
||
|
}
|
||
|
}
|
||
|
function processModuleCodeBlock(codeBlocks, start, end) {
|
||
|
processAppend(codeBlocks, start, end);
|
||
|
codeBlocks.appendSplitPunctuators(";");
|
||
|
}
|
||
|
for (const body of ast.body) {
|
||
|
if (body.type === "ImportDeclaration" ||
|
||
|
body.type === "ExportAllDeclaration" ||
|
||
|
(body.type === "ExportNamedDeclaration" && body.source != null)) {
|
||
|
const [start, end] = getNodeFullRange(body);
|
||
|
processStatementCodeBlock(start);
|
||
|
processModuleCodeBlock(importCodeBlocks, start, end);
|
||
|
}
|
||
|
else if (body.type === "ExportDefaultDeclaration") {
|
||
|
const [start, end] = getNodeFullRange(body);
|
||
|
processStatementCodeBlock(start);
|
||
|
processModuleCodeBlock(exportDefaultCodeBlocks, start, end);
|
||
|
}
|
||
|
else if (body.type === "ExportNamedDeclaration") {
|
||
|
const [start, end] = getNodeFullRange(body);
|
||
|
processStatementCodeBlock(start);
|
||
|
const tokens = ast.tokens;
|
||
|
const exportTokenIndex = tokens.findIndex((t) => t.range[0] === body.range[0]);
|
||
|
const exportToken = tokens[exportTokenIndex];
|
||
|
if (exportToken && exportToken.value === "export") {
|
||
|
processAppend(statementCodeBlocks, astOffset, exportToken.range[0]);
|
||
|
if (body.declaration) {
|
||
|
processModuleCodeBlock(statementCodeBlocks, exportToken.range[1], end);
|
||
|
restoreASTCallbacks.addCallback(scriptSetupStartOffset, [start, end], (statement) => {
|
||
|
if (statement.type !== body.declaration.type) {
|
||
|
return null;
|
||
|
}
|
||
|
fixNodeLocations(body, result.visitorKeys, offsetLocationCalculator);
|
||
|
fixLocation(exportToken, offsetLocationCalculator);
|
||
|
body.declaration = statement;
|
||
|
statement.parent = body;
|
||
|
return {
|
||
|
statement: body,
|
||
|
tokens: [exportToken],
|
||
|
};
|
||
|
});
|
||
|
}
|
||
|
else {
|
||
|
statementCodeBlocks.appendSplitPunctuators("(");
|
||
|
const restoreTokens = [exportToken];
|
||
|
let startOffset = exportToken.range[1];
|
||
|
for (const spec of body.specifiers) {
|
||
|
if (spec.local.range[0] < spec.exported.range[0]) {
|
||
|
const localTokenIndex = tokens.findIndex((t) => t.range[0] === spec.local.range[0], exportTokenIndex);
|
||
|
checkToken(tokens[localTokenIndex], spec.local.name);
|
||
|
const asToken = tokens[localTokenIndex + 1];
|
||
|
checkToken(asToken, "as");
|
||
|
restoreTokens.push(asToken);
|
||
|
const exportedToken = tokens[localTokenIndex + 2];
|
||
|
checkToken(exportedToken, spec.exported.name);
|
||
|
restoreTokens.push(exportedToken);
|
||
|
processAppend(statementCodeBlocks, startOffset, asToken.range[0]);
|
||
|
processAppend(statementCodeBlocks, asToken.range[1], exportedToken.range[0]);
|
||
|
startOffset = exportedToken.range[1];
|
||
|
}
|
||
|
}
|
||
|
processAppend(statementCodeBlocks, startOffset, end);
|
||
|
statementCodeBlocks.appendSplitPunctuators(")");
|
||
|
statementCodeBlocks.appendSplitPunctuators(";");
|
||
|
restoreASTCallbacks.addCallback(scriptSetupStartOffset, [start, end], (statement) => {
|
||
|
if (statement.type !== "ExpressionStatement" ||
|
||
|
statement.expression.type !== "ObjectExpression") {
|
||
|
return null;
|
||
|
}
|
||
|
const locals = [];
|
||
|
for (const prop of statement.expression
|
||
|
.properties) {
|
||
|
if (prop.type !== "Property" ||
|
||
|
prop.value.type !== "Identifier") {
|
||
|
return null;
|
||
|
}
|
||
|
locals.push(prop.value);
|
||
|
}
|
||
|
if (body.specifiers.length !== locals.length) {
|
||
|
return null;
|
||
|
}
|
||
|
const map = new Map();
|
||
|
for (let index = 0; index < body.specifiers.length; index++) {
|
||
|
const spec = body.specifiers[index];
|
||
|
const local = locals[index];
|
||
|
if (spec.local.name !== local.name) {
|
||
|
return null;
|
||
|
}
|
||
|
map.set(spec, local);
|
||
|
}
|
||
|
fixNodeLocations(body, result.visitorKeys, offsetLocationCalculator);
|
||
|
for (const token of restoreTokens) {
|
||
|
fixLocation(token, offsetLocationCalculator);
|
||
|
}
|
||
|
for (const [spec, local] of map) {
|
||
|
spec.local = local;
|
||
|
local.parent = spec;
|
||
|
}
|
||
|
return {
|
||
|
statement: body,
|
||
|
tokens: restoreTokens,
|
||
|
};
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
processModuleCodeBlock(statementCodeBlocks, start, end);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
processStatementCodeBlock(scriptSetupEndOffset);
|
||
|
const codeBlocks = new CodeBlocks();
|
||
|
codeBlocks.appendCodeBlocks(importCodeBlocks);
|
||
|
const scriptSetupBlockRangeStart = codeBlocks.length;
|
||
|
codeBlocks.appendSplitPunctuators("{");
|
||
|
codeBlocks.appendCodeBlocks(statementCodeBlocks);
|
||
|
codeBlocks.appendSplitPunctuators("}");
|
||
|
const scriptSetupBlockRangeEnd = codeBlocks.length;
|
||
|
codeBlocks.appendCodeBlocks(exportDefaultCodeBlocks);
|
||
|
return {
|
||
|
codeBlocks,
|
||
|
scriptSetupBlockRange: [
|
||
|
scriptSetupBlockRangeStart,
|
||
|
scriptSetupBlockRangeEnd,
|
||
|
],
|
||
|
restoreASTCallbacks,
|
||
|
};
|
||
|
function getNodeFullRange(n) {
|
||
|
let start = n.range[0];
|
||
|
let end = n.range[1];
|
||
|
traverseNodes(n, {
|
||
|
visitorKeys: result.visitorKeys,
|
||
|
enterNode(c) {
|
||
|
start = Math.min(start, c.range[0]);
|
||
|
end = Math.max(end, c.range[1]);
|
||
|
},
|
||
|
leaveNode() {
|
||
|
},
|
||
|
});
|
||
|
return [start, end];
|
||
|
}
|
||
|
function checkToken(token, value) {
|
||
|
if (token.value === value) {
|
||
|
return;
|
||
|
}
|
||
|
const perr = new ParseError(`Could not parse <script setup>. Expected "${value}", but it was "${token.value}".`, undefined, token.range[0], token.loc.start.line, token.loc.start.column);
|
||
|
fixErrorLocation(perr, offsetLocationCalculator);
|
||
|
throw perr;
|
||
|
}
|
||
|
}
|
||
|
function remapAST(result, { scriptSetupBlockRange, codeBlocks }) {
|
||
|
if (!scriptSetupBlockRange) {
|
||
|
return [];
|
||
|
}
|
||
|
let scriptSetupBlock = null;
|
||
|
const scriptSetupStatements = [];
|
||
|
for (let index = result.ast.body.length - 1; index >= 0; index--) {
|
||
|
const body = result.ast.body[index];
|
||
|
if (body.type === "BlockStatement") {
|
||
|
if (scriptSetupBlockRange[0] <= body.range[0] &&
|
||
|
body.range[1] <= scriptSetupBlockRange[1]) {
|
||
|
if (scriptSetupBlock) {
|
||
|
throw new Error(`Unexpected state error: An unexpected block statement was found. ${JSON.stringify(body.loc)}`);
|
||
|
}
|
||
|
scriptSetupBlock = body;
|
||
|
scriptSetupStatements.push(...body.body.filter((b) => !isSplitPunctuatorsEmptyStatement(b)));
|
||
|
result.ast.body.splice(index, 1, ...scriptSetupStatements);
|
||
|
}
|
||
|
}
|
||
|
else if (body.type === "EmptyStatement") {
|
||
|
if (isSplitPunctuatorsEmptyStatement(body)) {
|
||
|
result.ast.body.splice(index, 1);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if (result.scopeManager && scriptSetupBlock) {
|
||
|
const blockScope = result.scopeManager.acquire(scriptSetupBlock, true);
|
||
|
remapScope(result.scopeManager, blockScope);
|
||
|
}
|
||
|
return scriptSetupStatements;
|
||
|
function isSplitPunctuatorsEmptyStatement(body) {
|
||
|
return (body.type === "EmptyStatement" &&
|
||
|
codeBlocks.splitPunctuators.includes(body.range[1] - 1));
|
||
|
}
|
||
|
function remapScope(scopeManager, blockScope) {
|
||
|
const moduleScope = blockScope.upper;
|
||
|
for (const reference of blockScope.references) {
|
||
|
reference.from = moduleScope;
|
||
|
moduleScope.references.push(reference);
|
||
|
}
|
||
|
for (const variable of blockScope.variables) {
|
||
|
variable.scope = moduleScope;
|
||
|
const alreadyVariable = moduleScope.variables.find((v) => v.name === variable.name);
|
||
|
if (alreadyVariable) {
|
||
|
alreadyVariable.defs.push(...variable.defs);
|
||
|
alreadyVariable.identifiers.push(...variable.identifiers);
|
||
|
alreadyVariable.references.push(...variable.references);
|
||
|
for (const reference of variable.references) {
|
||
|
reference.resolved = alreadyVariable;
|
||
|
}
|
||
|
}
|
||
|
else {
|
||
|
moduleScope.variables.push(variable);
|
||
|
moduleScope.set.set(variable.name, variable);
|
||
|
}
|
||
|
}
|
||
|
const upper = blockScope.upper;
|
||
|
if (upper) {
|
||
|
const index = upper.childScopes.indexOf(blockScope);
|
||
|
if (index >= 0) {
|
||
|
upper.childScopes.splice(index, 1);
|
||
|
}
|
||
|
}
|
||
|
const index = scopeManager.scopes.indexOf(blockScope);
|
||
|
if (index >= 0) {
|
||
|
scopeManager.scopes.splice(index, 1);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
function remapLocationAndTokens(result, { codeBlocks }, locationCalculator) {
|
||
|
const tokens = result.ast.tokens || [];
|
||
|
const endMap = new Map();
|
||
|
const buffer = [];
|
||
|
for (let index = tokens.length - 1; index >= 0; index--) {
|
||
|
const token = tokens[index];
|
||
|
if (token.range[0] + 1 === token.range[1] &&
|
||
|
codeBlocks.splitPunctuators.includes(token.range[0])) {
|
||
|
tokens.splice(index, 1);
|
||
|
buffer.push(token.range[1]);
|
||
|
continue;
|
||
|
}
|
||
|
else {
|
||
|
for (const end of buffer) {
|
||
|
endMap.set(end, token.range[1]);
|
||
|
}
|
||
|
buffer.length = 0;
|
||
|
}
|
||
|
}
|
||
|
traverseNodes(result.ast, {
|
||
|
visitorKeys: result.visitorKeys,
|
||
|
enterNode(node) {
|
||
|
const rangeEnd = endMap.get(node.range[1]);
|
||
|
if (rangeEnd != null) {
|
||
|
node.range[1] = rangeEnd;
|
||
|
}
|
||
|
if (node.end) {
|
||
|
const end = endMap.get(node.end);
|
||
|
if (end != null) {
|
||
|
node.end = rangeEnd;
|
||
|
}
|
||
|
}
|
||
|
},
|
||
|
leaveNode() {
|
||
|
},
|
||
|
});
|
||
|
fixLocations(result, locationCalculator);
|
||
|
}
|
||
|
function simpleOffsetLocationCalculator(offset, linesAndColumns) {
|
||
|
return {
|
||
|
getFixOffset() {
|
||
|
return offset;
|
||
|
},
|
||
|
getLocFromIndex: linesAndColumns.getLocFromIndex.bind(linesAndColumns),
|
||
|
};
|
||
|
}
|
||
|
|
||
|
function parseStyleElements(elements, globalLocationCalculator, originalParserOptions) {
|
||
|
const parserOptions = Object.assign(Object.assign({}, originalParserOptions), { ecmaVersion: originalParserOptions.ecmaVersion || DEFAULT_ECMA_VERSION });
|
||
|
for (const style of elements) {
|
||
|
style.style = true;
|
||
|
parseStyleElement(style, globalLocationCalculator, parserOptions, {
|
||
|
inlineComment: (getLang(style) || "css") !== "css",
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
function parseStyleElement(style, globalLocationCalculator, parserOptions, cssOptions) {
|
||
|
if (style.children.length !== 1) {
|
||
|
return;
|
||
|
}
|
||
|
const textNode = style.children[0];
|
||
|
if (textNode.type !== "VText") {
|
||
|
return;
|
||
|
}
|
||
|
const code = textNode.value;
|
||
|
if (!/v-bind(?:\(|\/)/u.test(code)) {
|
||
|
return;
|
||
|
}
|
||
|
const locationCalculator = globalLocationCalculator.getSubCalculatorAfter(textNode.range[0]);
|
||
|
const document = getOwnerDocument(style);
|
||
|
parseStyle(document, style, code, locationCalculator, parserOptions, cssOptions);
|
||
|
}
|
||
|
function parseStyle(document, style, code, locationCalculator, parserOptions, cssOptions) {
|
||
|
let textStart = 0;
|
||
|
for (const { range, expr, exprOffset, quote, openingParenOffset, comments, } of iterateVBind(code, cssOptions)) {
|
||
|
insertComments(document, comments.map((c) => createSimpleToken(c.type, locationCalculator.getOffsetWithGap(c.range[0]), locationCalculator.getOffsetWithGap(c.range[1]), c.value, locationCalculator)));
|
||
|
const container = {
|
||
|
type: "VExpressionContainer",
|
||
|
range: [
|
||
|
locationCalculator.getOffsetWithGap(range[0]),
|
||
|
locationCalculator.getOffsetWithGap(range[1]),
|
||
|
],
|
||
|
loc: {
|
||
|
start: locationCalculator.getLocation(range[0]),
|
||
|
end: locationCalculator.getLocation(range[1]),
|
||
|
},
|
||
|
parent: style,
|
||
|
expression: null,
|
||
|
references: [],
|
||
|
};
|
||
|
const openingParenStart = locationCalculator.getOffsetWithGap(openingParenOffset);
|
||
|
const beforeTokens = [
|
||
|
createSimpleToken("HTMLRawText", container.range[0], container.range[0] + 6, "v-bind", locationCalculator),
|
||
|
createSimpleToken("Punctuator", openingParenStart, openingParenStart + 1, "(", locationCalculator),
|
||
|
];
|
||
|
const afterTokens = [
|
||
|
createSimpleToken("Punctuator", container.range[1] - 1, container.range[1], ")", locationCalculator),
|
||
|
];
|
||
|
if (quote) {
|
||
|
const openStart = locationCalculator.getOffsetWithGap(exprOffset - 1);
|
||
|
beforeTokens.push(createSimpleToken("Punctuator", openStart, openStart + 1, quote, locationCalculator));
|
||
|
const closeStart = locationCalculator.getOffsetWithGap(exprOffset + expr.length);
|
||
|
afterTokens.unshift(createSimpleToken("Punctuator", closeStart, closeStart + 1, quote, locationCalculator));
|
||
|
}
|
||
|
const beforeLast = beforeTokens[beforeTokens.length - 1];
|
||
|
replaceAndSplitTokens(document, {
|
||
|
range: [container.range[0], beforeLast.range[1]],
|
||
|
loc: { start: container.loc.start, end: beforeLast.loc.end },
|
||
|
}, beforeTokens);
|
||
|
const afterFirst = afterTokens[0];
|
||
|
replaceAndSplitTokens(document, {
|
||
|
range: [afterFirst.range[0], container.range[1]],
|
||
|
loc: { start: afterFirst.loc.start, end: container.loc.end },
|
||
|
}, afterTokens);
|
||
|
const lastChild = style.children[style.children.length - 1];
|
||
|
style.children.push(container);
|
||
|
if (lastChild.type === "VText") {
|
||
|
const newTextNode = {
|
||
|
type: "VText",
|
||
|
range: [container.range[1], lastChild.range[1]],
|
||
|
loc: {
|
||
|
start: Object.assign({}, container.loc.end),
|
||
|
end: Object.assign({}, lastChild.loc.end),
|
||
|
},
|
||
|
parent: style,
|
||
|
value: code.slice(range[1]),
|
||
|
};
|
||
|
style.children.push(newTextNode);
|
||
|
lastChild.range[1] = container.range[0];
|
||
|
lastChild.loc.end = Object.assign({}, container.loc.start);
|
||
|
lastChild.value = code.slice(textStart, range[0]);
|
||
|
textStart = range[1];
|
||
|
}
|
||
|
try {
|
||
|
const ret = parseExpression(expr, locationCalculator.getSubCalculatorShift(exprOffset), parserOptions, { allowEmpty: false, allowFilters: false });
|
||
|
if (ret.expression) {
|
||
|
ret.expression.parent = container;
|
||
|
container.expression = ret.expression;
|
||
|
container.references = ret.references;
|
||
|
}
|
||
|
replaceAndSplitTokens(document, {
|
||
|
range: [beforeLast.range[1], afterFirst.range[0]],
|
||
|
loc: {
|
||
|
start: beforeLast.loc.end,
|
||
|
end: afterFirst.loc.start,
|
||
|
},
|
||
|
}, ret.tokens);
|
||
|
insertComments(document, ret.comments);
|
||
|
for (const variable of ret.variables) {
|
||
|
style.variables.push(variable);
|
||
|
}
|
||
|
resolveReferences(container);
|
||
|
}
|
||
|
catch (err) {
|
||
|
debug("[style] Parse error: %s", err);
|
||
|
if (ParseError.isParseError(err)) {
|
||
|
insertError(document, err);
|
||
|
}
|
||
|
else {
|
||
|
throw err;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
function isQuote(c) {
|
||
|
return c === '"' || c === "'";
|
||
|
}
|
||
|
function isCommentStart(c) {
|
||
|
return c === "/*" || c === "//";
|
||
|
}
|
||
|
const COMMENT = {
|
||
|
"/*": {
|
||
|
type: "Block",
|
||
|
closing: "*/",
|
||
|
},
|
||
|
"//": {
|
||
|
type: "Line",
|
||
|
closing: "\n",
|
||
|
},
|
||
|
};
|
||
|
function* iterateVBind(code, cssOptions) {
|
||
|
const re = cssOptions.inlineComment
|
||
|
? /"|'|\/[*/]|\bv-bind/gu
|
||
|
: /"|'|\/\*|\bv-bind/gu;
|
||
|
let match;
|
||
|
while ((match = re.exec(code))) {
|
||
|
const startToken = match[0];
|
||
|
if (isQuote(startToken)) {
|
||
|
re.lastIndex = skipString(code, startToken, re.lastIndex);
|
||
|
}
|
||
|
else if (isCommentStart(startToken)) {
|
||
|
re.lastIndex = skipComment(code, COMMENT[startToken].closing, re.lastIndex);
|
||
|
}
|
||
|
else {
|
||
|
const openingParen = findVBindOpeningParen(code, re.lastIndex, cssOptions);
|
||
|
if (!openingParen) {
|
||
|
continue;
|
||
|
}
|
||
|
const start = match.index;
|
||
|
const arg = parseVBindArg(code, openingParen.openingParenOffset + 1, cssOptions);
|
||
|
if (!arg) {
|
||
|
continue;
|
||
|
}
|
||
|
yield {
|
||
|
range: [start, arg.end],
|
||
|
expr: arg.expr,
|
||
|
exprOffset: arg.exprOffset,
|
||
|
quote: arg.quote,
|
||
|
openingParenOffset: openingParen.openingParenOffset,
|
||
|
comments: [...openingParen.comments, ...arg.comments],
|
||
|
};
|
||
|
re.lastIndex = arg.end;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
function findVBindOpeningParen(code, nextIndex, cssOptions) {
|
||
|
const re = cssOptions.inlineComment ? /\/[*/]|[\s\S]/gu : /\/\*|[\s\S]/gu;
|
||
|
re.lastIndex = nextIndex;
|
||
|
let match;
|
||
|
const comments = [];
|
||
|
while ((match = re.exec(code))) {
|
||
|
const token = match[0];
|
||
|
if (token === "(") {
|
||
|
return {
|
||
|
openingParenOffset: match.index,
|
||
|
comments,
|
||
|
};
|
||
|
}
|
||
|
else if (isCommentStart(token)) {
|
||
|
const comment = COMMENT[token];
|
||
|
const start = match.index;
|
||
|
const end = (re.lastIndex = skipComment(code, comment.closing, re.lastIndex));
|
||
|
comments.push({
|
||
|
type: comment.type,
|
||
|
range: [start, end],
|
||
|
value: code.slice(start + token.length, end - comment.closing.length),
|
||
|
});
|
||
|
continue;
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
function parseVBindArg(code, nextIndex, cssOptions) {
|
||
|
const re = cssOptions.inlineComment ? /"|'|\/[*/]|\)/gu : /"|'|\/\*|\)/gu;
|
||
|
const startTokenIndex = (re.lastIndex = skipSpaces(code, nextIndex));
|
||
|
let match;
|
||
|
const stringRanges = [];
|
||
|
const comments = [];
|
||
|
while ((match = re.exec(code))) {
|
||
|
const token = match[0];
|
||
|
if (isQuote(token)) {
|
||
|
const start = match.index;
|
||
|
const end = (re.lastIndex = skipString(code, token, re.lastIndex));
|
||
|
stringRanges.push([start, end]);
|
||
|
}
|
||
|
else if (isCommentStart(token)) {
|
||
|
const comment = COMMENT[token];
|
||
|
const start = match.index;
|
||
|
const end = (re.lastIndex = skipComment(code, comment.closing, re.lastIndex));
|
||
|
comments.push({
|
||
|
type: comment.type,
|
||
|
range: [start, end],
|
||
|
value: code.slice(start + token.length, end - comment.closing.length),
|
||
|
});
|
||
|
}
|
||
|
else {
|
||
|
if (stringRanges.length === 1) {
|
||
|
const range = stringRanges[0];
|
||
|
const exprRange = [range[0] + 1, range[1] - 1];
|
||
|
return {
|
||
|
expr: code.slice(...exprRange),
|
||
|
exprOffset: exprRange[0],
|
||
|
quote: code[range[0]],
|
||
|
end: re.lastIndex,
|
||
|
comments,
|
||
|
};
|
||
|
}
|
||
|
return {
|
||
|
expr: code.slice(startTokenIndex, match.index).trim(),
|
||
|
exprOffset: startTokenIndex,
|
||
|
quote: null,
|
||
|
end: re.lastIndex,
|
||
|
comments: [],
|
||
|
};
|
||
|
}
|
||
|
}
|
||
|
return null;
|
||
|
}
|
||
|
function skipString(code, quote, nextIndex) {
|
||
|
for (let index = nextIndex; index < code.length; index++) {
|
||
|
const c = code[index];
|
||
|
if (c === "\\") {
|
||
|
index++;
|
||
|
continue;
|
||
|
}
|
||
|
if (c === quote) {
|
||
|
return index + 1;
|
||
|
}
|
||
|
}
|
||
|
return code.length;
|
||
|
}
|
||
|
function skipComment(code, closing, nextIndex) {
|
||
|
const index = code.indexOf(closing, nextIndex);
|
||
|
if (index >= nextIndex) {
|
||
|
return index + closing.length;
|
||
|
}
|
||
|
return code.length;
|
||
|
}
|
||
|
function skipSpaces(code, nextIndex) {
|
||
|
for (let index = nextIndex; index < code.length; index++) {
|
||
|
const c = code[index];
|
||
|
if (c.trim()) {
|
||
|
return index;
|
||
|
}
|
||
|
}
|
||
|
return code.length;
|
||
|
}
|
||
|
|
||
|
const STARTS_WITH_LT = /^\s*</u;
|
||
|
function isVueFile(code, options) {
|
||
|
const filePath = options.filePath || "unknown.js";
|
||
|
return path.extname(filePath) === ".vue" || STARTS_WITH_LT.test(code);
|
||
|
}
|
||
|
function parseForESLint(code, parserOptions) {
|
||
|
var _a, _b;
|
||
|
const options = Object.assign({
|
||
|
comment: true,
|
||
|
loc: true,
|
||
|
range: true,
|
||
|
tokens: true,
|
||
|
}, parserOptions || {});
|
||
|
let result;
|
||
|
let document;
|
||
|
let locationCalculator;
|
||
|
if (!isVueFile(code, options)) {
|
||
|
result = parseScript(code, Object.assign(Object.assign({}, options), { ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION, parser: getScriptParser(options.parser, () => {
|
||
|
const ext = (path.extname(options.filePath || "unknown.js")
|
||
|
.toLowerCase() || "")
|
||
|
.slice(1);
|
||
|
if (/^[jt]sx$/u.test(ext)) {
|
||
|
return [ext, ext.slice(0, -1)];
|
||
|
}
|
||
|
return ext;
|
||
|
}) }));
|
||
|
document = null;
|
||
|
locationCalculator = null;
|
||
|
}
|
||
|
else {
|
||
|
const optionsForTemplate = Object.assign(Object.assign({}, options), { ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION });
|
||
|
const skipParsingScript = options.parser === false;
|
||
|
const tokenizer = new Tokenizer(code, optionsForTemplate);
|
||
|
const rootAST = new Parser(tokenizer, optionsForTemplate).parse();
|
||
|
locationCalculator = new LocationCalculatorForHtml(tokenizer.gaps, tokenizer.lineTerminators);
|
||
|
const scripts = rootAST.children.filter(isScriptElement);
|
||
|
const template = rootAST.children.find(isTemplateElement);
|
||
|
const templateLang = getLang(template) || "html";
|
||
|
const concreteInfo = {
|
||
|
tokens: rootAST.tokens,
|
||
|
comments: rootAST.comments,
|
||
|
errors: rootAST.errors,
|
||
|
};
|
||
|
const templateBody = template != null && templateLang === "html"
|
||
|
? Object.assign(template, concreteInfo)
|
||
|
: undefined;
|
||
|
const scriptParser = getScriptParser(options.parser, () => getParserLangFromSFC(rootAST));
|
||
|
let scriptSetup;
|
||
|
if (skipParsingScript || !scripts.length) {
|
||
|
result = parseScript("", Object.assign(Object.assign({}, options), { ecmaVersion: options.ecmaVersion || DEFAULT_ECMA_VERSION, parser: scriptParser }));
|
||
|
}
|
||
|
else if (scripts.length === 2 &&
|
||
|
(scriptSetup = scripts.find(isScriptSetupElement))) {
|
||
|
result = parseScriptSetupElements(scriptSetup, scripts.find((e) => e !== scriptSetup), code, new LinesAndColumns(tokenizer.lineTerminators), Object.assign(Object.assign({}, options), { parser: scriptParser }));
|
||
|
}
|
||
|
else {
|
||
|
result = parseScriptElement(scripts[0], locationCalculator, Object.assign(Object.assign({}, options), { parser: scriptParser }));
|
||
|
}
|
||
|
if ((_b = (_a = options.vueFeatures) === null || _a === void 0 ? void 0 : _a.styleCSSVariableInjection) !== null && _b !== void 0 ? _b : true) {
|
||
|
const styles = rootAST.children.filter(isStyleElement);
|
||
|
parseStyleElements(styles, locationCalculator, Object.assign(Object.assign({}, options), { parser: getScriptParser(options.parser, function* () {
|
||
|
yield "<template>";
|
||
|
yield getParserLangFromSFC(rootAST);
|
||
|
}) }));
|
||
|
}
|
||
|
result.ast.templateBody = templateBody;
|
||
|
document = rootAST;
|
||
|
}
|
||
|
result.services = Object.assign(result.services || {}, define(code, result.ast, document, locationCalculator, {
|
||
|
parserOptions: options,
|
||
|
}));
|
||
|
return result;
|
||
|
}
|
||
|
function parse(code, options) {
|
||
|
return parseForESLint(code, options).ast;
|
||
|
}
|
||
|
|
||
|
exports.AST = index;
|
||
|
exports.parse = parse;
|
||
|
exports.parseForESLint = parseForESLint;
|
||
|
//# sourceMappingURL=index.js.map
|