|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408 |
- /*! @author Toru Nagashima <https://github.com/mysticatea> */
- 'use strict';
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
- /**
- * Get the innermost scope which contains a given location.
- * @param {Scope} initialScope The initial scope to search.
- * @param {Node} node The location to search.
- * @returns {Scope} The innermost scope.
- */
- function getInnermostScope(initialScope, node) {
- const location = node.range[0];
-
- let scope = initialScope;
- let found = false;
- do {
- found = false;
- for (const childScope of scope.childScopes) {
- const range = childScope.block.range;
-
- if (range[0] <= location && location < range[1]) {
- scope = childScope;
- found = true;
- break
- }
- }
- } while (found)
-
- return scope
- }
-
- /**
- * Find the variable of a given name.
- * @param {Scope} initialScope The scope to start finding.
- * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
- * @returns {Variable|null} The found variable or null.
- */
- function findVariable(initialScope, nameOrNode) {
- let name = "";
- let scope = initialScope;
-
- if (typeof nameOrNode === "string") {
- name = nameOrNode;
- } else {
- name = nameOrNode.name;
- scope = getInnermostScope(scope, nameOrNode);
- }
-
- while (scope != null) {
- const variable = scope.set.get(name);
- if (variable != null) {
- return variable
- }
- scope = scope.upper;
- }
-
- return null
- }
-
- /**
- * Negate the result of `this` calling.
- * @param {Token} token The token to check.
- * @returns {boolean} `true` if the result of `this(token)` is `false`.
- */
- function negate0(token) {
- return !this(token) //eslint-disable-line no-invalid-this
- }
-
- /**
- * Creates the negate function of the given function.
- * @param {function(Token):boolean} f - The function to negate.
- * @returns {function(Token):boolean} Negated function.
- */
- function negate(f) {
- return negate0.bind(f)
- }
-
- /**
- * Checks if the given token is an arrow token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is an arrow token.
- */
- function isArrowToken(token) {
- return token.value === "=>" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a comma token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a comma token.
- */
- function isCommaToken(token) {
- return token.value === "," && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a semicolon token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a semicolon token.
- */
- function isSemicolonToken(token) {
- return token.value === ";" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a colon token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a colon token.
- */
- function isColonToken(token) {
- return token.value === ":" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is an opening parenthesis token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is an opening parenthesis token.
- */
- function isOpeningParenToken(token) {
- return token.value === "(" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a closing parenthesis token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a closing parenthesis token.
- */
- function isClosingParenToken(token) {
- return token.value === ")" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is an opening square bracket token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is an opening square bracket token.
- */
- function isOpeningBracketToken(token) {
- return token.value === "[" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a closing square bracket token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a closing square bracket token.
- */
- function isClosingBracketToken(token) {
- return token.value === "]" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is an opening brace token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is an opening brace token.
- */
- function isOpeningBraceToken(token) {
- return token.value === "{" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a closing brace token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a closing brace token.
- */
- function isClosingBraceToken(token) {
- return token.value === "}" && token.type === "Punctuator"
- }
-
- /**
- * Checks if the given token is a comment token or not.
- * @param {Token} token - The token to check.
- * @returns {boolean} `true` if the token is a comment token.
- */
- function isCommentToken(token) {
- return (
- token.type === "Line" ||
- token.type === "Block" ||
- token.type === "Shebang"
- )
- }
-
- const isNotArrowToken = negate(isArrowToken);
- const isNotCommaToken = negate(isCommaToken);
- const isNotSemicolonToken = negate(isSemicolonToken);
- const isNotColonToken = negate(isColonToken);
- const isNotOpeningParenToken = negate(isOpeningParenToken);
- const isNotClosingParenToken = negate(isClosingParenToken);
- const isNotOpeningBracketToken = negate(isOpeningBracketToken);
- const isNotClosingBracketToken = negate(isClosingBracketToken);
- const isNotOpeningBraceToken = negate(isOpeningBraceToken);
- const isNotClosingBraceToken = negate(isClosingBraceToken);
- const isNotCommentToken = negate(isCommentToken);
-
- /**
- * Get the `(` token of the given function node.
- * @param {Node} node - The function node to get.
- * @param {SourceCode} sourceCode - The source code object to get tokens.
- * @returns {Token} `(` token.
- */
- function getOpeningParenOfParams(node, sourceCode) {
- return node.id
- ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
- : sourceCode.getFirstToken(node, isOpeningParenToken)
- }
-
- /**
- * Get the location of the given function node for reporting.
- * @param {Node} node - The function node to get.
- * @param {SourceCode} sourceCode - The source code object to get tokens.
- * @returns {string} The location of the function node for reporting.
- */
- function getFunctionHeadLocation(node, sourceCode) {
- const parent = node.parent;
- let start = null;
- let end = null;
-
- if (node.type === "ArrowFunctionExpression") {
- const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
-
- start = arrowToken.loc.start;
- end = arrowToken.loc.end;
- } else if (
- parent.type === "Property" ||
- parent.type === "MethodDefinition"
- ) {
- start = parent.loc.start;
- end = getOpeningParenOfParams(node, sourceCode).loc.start;
- } else {
- start = node.loc.start;
- end = getOpeningParenOfParams(node, sourceCode).loc.start;
- }
-
- return {
- start: Object.assign({}, start),
- end: Object.assign({}, end),
- }
- }
-
- const builtinNames = Object.freeze(
- new Set([
- "Array",
- "ArrayBuffer",
- "Boolean",
- "DataView",
- "Date",
- "decodeURI",
- "decodeURIComponent",
- "encodeURI",
- "encodeURIComponent",
- "Error",
- "escape",
- "EvalError",
- "Float32Array",
- "Float64Array",
- "Function",
- "Infinity",
- "Int16Array",
- "Int32Array",
- "Int8Array",
- "isFinite",
- "isNaN",
- "isPrototypeOf",
- "JSON",
- "Map",
- "Math",
- "NaN",
- "Number",
- "Object",
- "parseFloat",
- "parseInt",
- "Promise",
- "Proxy",
- "RangeError",
- "ReferenceError",
- "Reflect",
- "RegExp",
- "Set",
- "String",
- "Symbol",
- "SyntaxError",
- "TypeError",
- "Uint16Array",
- "Uint32Array",
- "Uint8Array",
- "Uint8ClampedArray",
- "undefined",
- "unescape",
- "URIError",
- "WeakMap",
- "WeakSet",
- ])
- );
-
- /**
- * Get the element values of a given node list.
- * @param {Node[]} nodeList The node list to get values.
- * @param {Scope|undefined} initialScope The initial scope to find variables.
- * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
- */
- function getElementValues(nodeList, initialScope) {
- const valueList = [];
-
- for (let i = 0; i < nodeList.length; ++i) {
- const elementNode = nodeList[i];
-
- if (elementNode == null) {
- valueList.length = i + 1;
- } else if (elementNode.type === "SpreadElement") {
- const argument = getStaticValueR(elementNode.argument, initialScope);
- if (argument == null) {
- return null
- }
- valueList.push(...argument.value);
- } else {
- const element = getStaticValueR(elementNode, initialScope);
- if (element == null) {
- return null
- }
- valueList.push(element.value);
- }
- }
-
- return valueList
- }
-
- const operations = Object.freeze({
- ArrayExpression(node, initialScope) {
- const elements = getElementValues(node.elements, initialScope);
- return elements != null ? { value: elements } : null
- },
-
- AssignmentExpression(node, initialScope) {
- if (node.operator === "=") {
- return getStaticValueR(node.right, initialScope)
- }
- return null
- },
-
- //eslint-disable-next-line complexity
- BinaryExpression(node, initialScope) {
- if (node.operator === "in" || node.operator === "instanceof") {
- // Not supported.
- return null
- }
-
- const left = getStaticValueR(node.left, initialScope);
- const right = getStaticValueR(node.right, initialScope);
- if (left != null && right != null) {
- switch (node.operator) {
- case "==":
- return { value: left.value == right.value } //eslint-disable-line eqeqeq
- case "!=":
- return { value: left.value != right.value } //eslint-disable-line eqeqeq
- case "===":
- return { value: left.value === right.value }
- case "!==":
- return { value: left.value !== right.value }
- case "<":
- return { value: left.value < right.value }
- case "<=":
- return { value: left.value <= right.value }
- case ">":
- return { value: left.value > right.value }
- case ">=":
- return { value: left.value >= right.value }
- case "<<":
- return { value: left.value << right.value }
- case ">>":
- return { value: left.value >> right.value }
- case ">>>":
- return { value: left.value >>> right.value }
- case "+":
- return { value: left.value + right.value }
- case "-":
- return { value: left.value - right.value }
- case "*":
- return { value: left.value * right.value }
- case "/":
- return { value: left.value / right.value }
- case "%":
- return { value: left.value % right.value }
- case "**":
- return { value: Math.pow(left.value, right.value) }
- case "|":
- return { value: left.value | right.value }
- case "^":
- return { value: left.value ^ right.value }
- case "&":
- return { value: left.value & right.value }
-
- // no default
- }
- }
-
- return null
- },
-
- CallExpression(node, initialScope) {
- const calleeNode = node.callee;
- const args = getElementValues(node.arguments, initialScope);
-
- if (args != null) {
- if (calleeNode.type === "MemberExpression") {
- const object = getStaticValueR(calleeNode.object, initialScope);
- const property = calleeNode.computed
- ? getStaticValueR(calleeNode.property, initialScope)
- : { value: calleeNode.property.name };
-
- if (object != null && property != null) {
- const receiver = object.value;
- const methodName = property.value;
- return { value: receiver[methodName](...args) }
- }
- } else {
- const callee = getStaticValueR(calleeNode, initialScope);
- if (callee != null) {
- const func = callee.value;
- return { value: func(...args) }
- }
- }
- }
-
- return null
- },
-
- ConditionalExpression(node, initialScope) {
- const test = getStaticValueR(node.test, initialScope);
- if (test != null) {
- return test.value
- ? getStaticValueR(node.consequent, initialScope)
- : getStaticValueR(node.alternate, initialScope)
- }
- return null
- },
-
- ExpressionStatement(node, initialScope) {
- return getStaticValueR(node.expression, initialScope)
- },
-
- Identifier(node, initialScope) {
- if (initialScope != null) {
- const variable = findVariable(initialScope, node);
-
- // Built-in globals.
- if (
- variable != null &&
- variable.defs.length === 0 &&
- builtinNames.has(variable.name) &&
- variable.name in global
- ) {
- return { value: global[variable.name] }
- }
-
- // Constants.
- if (variable != null && variable.defs.length === 1) {
- const def = variable.defs[0];
- if (
- def.parent &&
- def.parent.kind === "const" &&
- // TODO(mysticatea): don't support destructuring here.
- def.node.id.type === "Identifier"
- ) {
- return getStaticValueR(def.node.init, initialScope)
- }
- }
- }
- return null
- },
-
- Literal(node) {
- //istanbul ignore if : this is implementation-specific behavior.
- if (node.regex != null && node.value == null) {
- // It was a RegExp literal, but Node.js didn't support it.
- return null
- }
- return node
- },
-
- LogicalExpression(node, initialScope) {
- const left = getStaticValueR(node.left, initialScope);
- if (left != null) {
- if (
- (node.operator === "||" && Boolean(left.value) === true) ||
- (node.operator === "&&" && Boolean(left.value) === false)
- ) {
- return left
- }
-
- const right = getStaticValueR(node.right, initialScope);
- if (right != null) {
- return right
- }
- }
-
- return null
- },
-
- MemberExpression(node, initialScope) {
- const object = getStaticValueR(node.object, initialScope);
- const property = node.computed
- ? getStaticValueR(node.property, initialScope)
- : { value: node.property.name };
-
- if (object != null && property != null) {
- return { value: object.value[property.value] }
- }
- return null
- },
-
- NewExpression(node, initialScope) {
- const callee = getStaticValueR(node.callee, initialScope);
- const args = getElementValues(node.arguments, initialScope);
-
- if (callee != null && args != null) {
- const Func = callee.value;
- return { value: new Func(...args) }
- }
-
- return null
- },
-
- ObjectExpression(node, initialScope) {
- const object = {};
-
- for (const propertyNode of node.properties) {
- if (propertyNode.type === "Property") {
- if (propertyNode.kind !== "init") {
- return null
- }
- const key = propertyNode.computed
- ? getStaticValueR(propertyNode.key, initialScope)
- : { value: propertyNode.key.name };
- const value = getStaticValueR(propertyNode.value, initialScope);
- if (key == null || value == null) {
- return null
- }
- object[key.value] = value.value;
- } else if (
- propertyNode.type === "SpreadElement" ||
- propertyNode.type === "ExperimentalSpreadProperty"
- ) {
- const argument = getStaticValueR(
- propertyNode.argument,
- initialScope
- );
- if (argument == null) {
- return null
- }
- Object.assign(object, argument.value);
- } else {
- return null
- }
- }
-
- return { value: object }
- },
-
- SequenceExpression(node, initialScope) {
- const last = node.expressions[node.expressions.length - 1];
- return getStaticValueR(last, initialScope)
- },
-
- TaggedTemplateExpression(node, initialScope) {
- const tag = getStaticValueR(node.tag, initialScope);
- const expressions = getElementValues(
- node.quasi.expressions,
- initialScope
- );
-
- if (tag != null && expressions != null) {
- const func = tag.value;
- const strings = node.quasi.quasis.map(q => q.value.cooked);
- strings.raw = node.quasi.quasis.map(q => q.value.raw);
-
- return { value: func(strings, ...expressions) }
- }
-
- return null
- },
-
- TemplateLiteral(node, initialScope) {
- const expressions = getElementValues(node.expressions, initialScope);
- if (expressions != null) {
- let value = node.quasis[0].value.cooked;
- for (let i = 0; i < expressions.length; ++i) {
- value += expressions[i];
- value += node.quasis[i + 1].value.cooked;
- }
- return { value }
- }
- return null
- },
-
- UnaryExpression(node, initialScope) {
- if (node.operator === "delete") {
- // Not supported.
- return null
- }
- if (node.operator === "void") {
- return { value: undefined }
- }
-
- const arg = getStaticValueR(node.argument, initialScope);
- if (arg != null) {
- switch (node.operator) {
- case "-":
- return { value: -arg.value }
- case "+":
- return { value: +arg.value } //eslint-disable-line no-implicit-coercion
- case "!":
- return { value: !arg.value }
- case "~":
- return { value: ~arg.value }
- case "typeof":
- return { value: typeof arg.value }
-
- // no default
- }
- }
-
- return null
- },
- });
-
- /**
- * Get the value of a given node if it's a static value.
- * @param {Node} node The node to get.
- * @param {Scope|undefined} initialScope The scope to start finding variable.
- * @returns {{value:any}|null} The static value of the node, or `null`.
- */
- function getStaticValueR(node, initialScope) {
- if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
- return operations[node.type](node, initialScope)
- }
- return null
- }
-
- /**
- * Get the value of a given node if it's a static value.
- * @param {Node} node The node to get.
- * @param {Scope} [initialScope] The scope to start finding variable. Optional. If this scope was given, this tries to resolve identifier references which are in the given node as much as possible.
- * @returns {{value:any}|null} The static value of the node, or `null`.
- */
- function getStaticValue(node, initialScope = null) {
- try {
- return getStaticValueR(node, initialScope)
- } catch (_error) {
- return null
- }
- }
-
- /**
- * Get the value of a given node if it's a literal or a template literal.
- * @param {Node} node The node to get.
- * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is an Identifier node and this scope was given, this checks the variable of the identifier, and returns the value of it if the variable is a constant.
- * @returns {string|null} The value of the node, or `null`.
- */
- function getStringIfConstant(node, initialScope = null) {
- const evaluated = getStaticValue(node, initialScope);
- return evaluated && String(evaluated.value)
- }
-
- /**
- * Get the property name from a MemberExpression node or a Property node.
- * @param {Node} node The node to get.
- * @param {Scope} [initialScope] The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
- * @returns {string|null} The property name of the node.
- */
- function getPropertyName(node, initialScope) {
- switch (node.type) {
- case "MemberExpression":
- if (node.computed) {
- return getStringIfConstant(node.property, initialScope)
- }
- return node.property.name
-
- case "Property":
- case "MethodDefinition":
- if (node.computed) {
- return getStringIfConstant(node.key, initialScope)
- }
- if (node.key.type === "Literal") {
- return String(node.key.value)
- }
- return node.key.name
-
- // no default
- }
-
- return null
- }
-
- /**
- * Get the name and kind of the given function node.
- * @param {ASTNode} node - The function node to get.
- * @returns {string} The name and kind of the function node.
- */
- function getFunctionNameWithKind(node) {
- const parent = node.parent;
- const tokens = [];
-
- if (parent.type === "MethodDefinition" && parent.static) {
- tokens.push("static");
- }
- if (node.async) {
- tokens.push("async");
- }
- if (node.generator) {
- tokens.push("generator");
- }
-
- if (node.type === "ArrowFunctionExpression") {
- tokens.push("arrow", "function");
- } else if (
- parent.type === "Property" ||
- parent.type === "MethodDefinition"
- ) {
- if (parent.kind === "constructor") {
- return "constructor"
- }
- if (parent.kind === "get") {
- tokens.push("getter");
- } else if (parent.kind === "set") {
- tokens.push("setter");
- } else {
- tokens.push("method");
- }
- } else {
- tokens.push("function");
- }
-
- if (node.id) {
- tokens.push(`'${node.id.name}'`);
- } else {
- const name = getPropertyName(parent);
-
- if (name) {
- tokens.push(`'${name}'`);
- }
- }
-
- return tokens.join(" ")
- }
-
- /**
- * @author Toru Nagashima <https://github.com/mysticatea>
- * See LICENSE file in root directory for full license.
- */
-
- const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/g;
-
- /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
- const internal = new WeakMap();
-
- /**
- * Check whether a given character is escaped or not.
- * @param {string} str The string to check.
- * @param {number} index The location of the character to check.
- * @returns {boolean} `true` if the character is escaped.
- */
- function isEscaped(str, index) {
- let escaped = false;
- for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
- escaped = !escaped;
- }
- return escaped
- }
-
- /**
- * Replace a given string by a given matcher.
- * @param {PatternMatcher} matcher The pattern matcher.
- * @param {string} str The string to be replaced.
- * @param {string} replacement The new substring to replace each matched part.
- * @returns {string} The replaced string.
- */
- function replaceS(matcher, str, replacement) {
- const chunks = [];
- let index = 0;
-
- /** @type {RegExpExecArray} */
- let match = null;
-
- /**
- * @param {string} key The placeholder.
- * @returns {string} The replaced string.
- */
- function replacer(key) {
- switch (key) {
- case "$$":
- return "$"
- case "$&":
- return match[0]
- case "$`":
- return str.slice(0, match.index)
- case "$'":
- return str.slice(match.index + match[0].length)
- default: {
- const i = key.slice(1);
- if (i in match) {
- return match[i]
- }
- return key
- }
- }
- }
-
- for (match of matcher.execAll(str)) {
- chunks.push(str.slice(index, match.index));
- chunks.push(replacement.replace(placeholder, replacer));
- index = match.index + match[0].length;
- }
- chunks.push(str.slice(index));
-
- return chunks.join("")
- }
-
- //eslint-disable-next-line valid-jsdoc
- /**
- * Replace a given string by a given matcher.
- * @param {PatternMatcher} matcher The pattern matcher.
- * @param {string} str The string to be replaced.
- * @param {(...strs[])=>string} replace The function to replace each matched part.
- * @returns {string} The replaced string.
- */
- function replaceF(matcher, str, replace) {
- const chunks = [];
- let index = 0;
-
- for (const match of matcher.execAll(str)) {
- chunks.push(str.slice(index, match.index));
- chunks.push(String(replace(...match, match.index, match.input)));
- index = match.index + match[0].length;
- }
- chunks.push(str.slice(index));
-
- return chunks.join("")
- }
-
- /**
- * The class to find patterns as considering escape sequences.
- */
- class PatternMatcher {
- /**
- * Initialize this matcher.
- * @param {RegExp} pattern The pattern to match.
- * @param {{escaped:boolean}} options The options.
- */
- constructor(pattern, { escaped = false } = {}) {
- if (!(pattern instanceof RegExp)) {
- throw new TypeError("'pattern' should be a RegExp instance.")
- }
- if (!pattern.flags.includes("g")) {
- throw new Error("'pattern' should contains 'g' flag.")
- }
-
- internal.set(this, {
- pattern: new RegExp(pattern.source, pattern.flags),
- escaped: Boolean(escaped),
- });
- }
-
- /**
- * Find the pattern in a given string.
- * @param {string} str The string to find.
- * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
- */
- *execAll(str) {
- const { pattern, escaped } = internal.get(this);
- let match = null;
- let lastIndex = 0;
-
- pattern.lastIndex = 0;
- while ((match = pattern.exec(str)) != null) {
- if (escaped || !isEscaped(str, match.index)) {
- lastIndex = pattern.lastIndex;
- yield match;
- pattern.lastIndex = lastIndex;
- }
- }
- }
-
- /**
- * Check whether the pattern is found in a given string.
- * @param {string} str The string to check.
- * @returns {boolean} `true` if the pattern was found in the string.
- */
- test(str) {
- const it = this.execAll(str);
- const ret = it.next();
- return !ret.done
- }
-
- //eslint-disable-next-line valid-jsdoc
- /**
- * Replace a given string.
- * @param {string} str The string to be replaced.
- * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
- * @returns {string} The replaced string.
- */
- [Symbol.replace](str, replacer) {
- return typeof replacer === "function"
- ? replaceF(this, String(str), replacer)
- : replaceS(this, String(str), String(replacer))
- }
- }
-
- const SENTINEL_TYPE = /^(?:.+?Statement|.+?Declaration|(?:Array|ArrowFunction|Assignment|Call|Class|Function|Member|New|Object)Expression|AssignmentPattern|Program|VariableDeclarator)$/;
- const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/;
- const has = Function.call.bind(Object.hasOwnProperty);
-
- const READ = Symbol("read");
- const CALL = Symbol("call");
- const CONSTRUCT = Symbol("construct");
- const ESM = Symbol("esm");
-
- const requireCall = { require: { [CALL]: true } };
-
- /**
- * Check whether a given variable is modified or not.
- * @param {Variable} variable The variable to check.
- * @returns {boolean} `true` if the variable is modified.
- */
- function isModifiedGlobal(variable) {
- return (
- variable == null ||
- variable.defs.length !== 0 ||
- variable.references.some(r => r.isWrite())
- )
- }
-
- /**
- * The reference tracker.
- */
- class ReferenceTracker {
- /**
- * Initialize this tracker.
- * @param {Scope} globalScope The global scope.
- * @param {object} [options] The options.
- * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
- * @param {string[]} [options.globalObjectNames=["global","self","window"]] The variable names for Global Object.
- */
- constructor(
- globalScope,
- {
- mode = "strict",
- globalObjectNames = ["global", "self", "window"],
- } = {}
- ) {
- this.variableStack = [];
- this.globalScope = globalScope;
- this.mode = mode;
- this.globalObjectNames = globalObjectNames.slice(0);
- }
-
- /**
- * Iterate the references of global variables.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *iterateGlobalReferences(traceMap) {
- for (const key of Object.keys(traceMap)) {
- const nextTraceMap = traceMap[key];
- const path = [key];
- const variable = this.globalScope.set.get(key);
-
- if (isModifiedGlobal(variable)) {
- continue
- }
-
- yield* this._iterateVariableReferences(
- variable,
- path,
- nextTraceMap,
- true
- );
- }
-
- for (const key of this.globalObjectNames) {
- const path = [];
- const variable = this.globalScope.set.get(key);
-
- if (isModifiedGlobal(variable)) {
- continue
- }
-
- yield* this._iterateVariableReferences(
- variable,
- path,
- traceMap,
- false
- );
- }
- }
-
- /**
- * Iterate the references of CommonJS modules.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *iterateCjsReferences(traceMap) {
- for (const { node } of this.iterateGlobalReferences(requireCall)) {
- const key = getStringIfConstant(node.arguments[0]);
- if (key == null || !has(traceMap, key)) {
- continue
- }
-
- const nextTraceMap = traceMap[key];
- const path = [key];
-
- if (nextTraceMap[READ]) {
- yield {
- node,
- path,
- type: READ,
- info: nextTraceMap[READ],
- };
- }
- yield* this._iteratePropertyReferences(node, path, nextTraceMap);
- }
- }
-
- /**
- * Iterate the references of ES modules.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *iterateEsmReferences(traceMap) {
- const programNode = this.globalScope.block;
-
- for (const node of programNode.body) {
- if (!IMPORT_TYPE.test(node.type) || node.source == null) {
- continue
- }
- const moduleId = node.source.value;
-
- if (!has(traceMap, moduleId)) {
- continue
- }
- const nextTraceMap = traceMap[moduleId];
- const path = [moduleId];
-
- if (nextTraceMap[READ]) {
- yield { node, path, type: READ, info: nextTraceMap[READ] };
- }
-
- if (node.type === "ExportAllDeclaration") {
- for (const key of Object.keys(nextTraceMap)) {
- const exportTraceMap = nextTraceMap[key];
- if (exportTraceMap[READ]) {
- yield {
- node,
- path: path.concat(key),
- type: READ,
- info: exportTraceMap[READ],
- };
- }
- }
- } else {
- for (const specifier of node.specifiers) {
- const esm = has(nextTraceMap, ESM);
- const it = this._iterateImportReferences(
- specifier,
- path,
- esm
- ? nextTraceMap
- : this.mode === "legacy"
- ? Object.assign(
- { default: nextTraceMap },
- nextTraceMap
- )
- : { default: nextTraceMap }
- );
-
- if (esm) {
- yield* it;
- } else {
- for (const report of it) {
- report.path = report.path.filter(exceptDefault);
- if (
- report.path.length >= 2 ||
- report.type !== READ
- ) {
- yield report;
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * Iterate the references for a given variable.
- * @param {Variable} variable The variable to iterate that references.
- * @param {string[]} path The current path.
- * @param {object} traceMap The trace map.
- * @param {boolean} shouldReport = The flag to report those references.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
- if (this.variableStack.includes(variable)) {
- return
- }
- this.variableStack.push(variable);
- try {
- for (const reference of variable.references) {
- if (!reference.isRead()) {
- continue
- }
- const node = reference.identifier;
-
- if (shouldReport && traceMap[READ]) {
- yield { node, path, type: READ, info: traceMap[READ] };
- }
- yield* this._iteratePropertyReferences(node, path, traceMap);
- }
- } finally {
- this.variableStack.pop();
- }
- }
-
- /**
- * Iterate the references for a given AST node.
- * @param rootNode The AST node to iterate references.
- * @param {string[]} path The current path.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- //eslint-disable-next-line complexity, require-jsdoc
- *_iteratePropertyReferences(rootNode, path, traceMap) {
- let node = rootNode;
- while (!SENTINEL_TYPE.test(node.parent.type)) {
- node = node.parent;
- }
-
- const parent = node.parent;
- if (parent.type === "MemberExpression") {
- if (parent.object === node) {
- const key = getPropertyName(parent);
- if (key == null || !has(traceMap, key)) {
- return
- }
-
- path = path.concat(key); //eslint-disable-line no-param-reassign
- const nextTraceMap = traceMap[key];
- if (nextTraceMap[READ]) {
- yield {
- node: parent,
- path,
- type: READ,
- info: nextTraceMap[READ],
- };
- }
- yield* this._iteratePropertyReferences(
- parent,
- path,
- nextTraceMap
- );
- }
- return
- }
- if (parent.type === "CallExpression") {
- if (parent.callee === node && traceMap[CALL]) {
- yield { node: parent, path, type: CALL, info: traceMap[CALL] };
- }
- return
- }
- if (parent.type === "NewExpression") {
- if (parent.callee === node && traceMap[CONSTRUCT]) {
- yield {
- node: parent,
- path,
- type: CONSTRUCT,
- info: traceMap[CONSTRUCT],
- };
- }
- return
- }
- if (parent.type === "AssignmentExpression") {
- if (parent.right === node) {
- yield* this._iterateLhsReferences(parent.left, path, traceMap);
- yield* this._iteratePropertyReferences(parent, path, traceMap);
- }
- return
- }
- if (parent.type === "AssignmentPattern") {
- if (parent.right === node) {
- yield* this._iterateLhsReferences(parent.left, path, traceMap);
- }
- return
- }
- if (parent.type === "VariableDeclarator") {
- if (parent.init === node) {
- yield* this._iterateLhsReferences(parent.id, path, traceMap);
- }
- }
- }
-
- /**
- * Iterate the references for a given Pattern node.
- * @param {Node} patternNode The Pattern node to iterate references.
- * @param {string[]} path The current path.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *_iterateLhsReferences(patternNode, path, traceMap) {
- if (patternNode.type === "Identifier") {
- const variable = findVariable(this.globalScope, patternNode);
- if (variable != null) {
- yield* this._iterateVariableReferences(
- variable,
- path,
- traceMap,
- false
- );
- }
- return
- }
- if (patternNode.type === "ObjectPattern") {
- for (const property of patternNode.properties) {
- const key = getPropertyName(property);
-
- if (key == null || !has(traceMap, key)) {
- continue
- }
-
- const nextPath = path.concat(key);
- const nextTraceMap = traceMap[key];
- if (nextTraceMap[READ]) {
- yield {
- node: property,
- path: nextPath,
- type: READ,
- info: nextTraceMap[READ],
- };
- }
- yield* this._iterateLhsReferences(
- property.value,
- nextPath,
- nextTraceMap
- );
- }
- return
- }
- if (patternNode.type === "AssignmentPattern") {
- yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
- }
- }
-
- /**
- * Iterate the references for a given ModuleSpecifier node.
- * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
- * @param {string[]} path The current path.
- * @param {object} traceMap The trace map.
- * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
- */
- *_iterateImportReferences(specifierNode, path, traceMap) {
- const type = specifierNode.type;
-
- if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
- const key =
- type === "ImportDefaultSpecifier"
- ? "default"
- : specifierNode.imported.name;
- if (!has(traceMap, key)) {
- return
- }
-
- path = path.concat(key); //eslint-disable-line no-param-reassign
- const nextTraceMap = traceMap[key];
- if (nextTraceMap[READ]) {
- yield {
- node: specifierNode,
- path,
- type: READ,
- info: nextTraceMap[READ],
- };
- }
- yield* this._iterateVariableReferences(
- findVariable(this.globalScope, specifierNode.local),
- path,
- nextTraceMap,
- false
- );
-
- return
- }
-
- if (type === "ImportNamespaceSpecifier") {
- yield* this._iterateVariableReferences(
- findVariable(this.globalScope, specifierNode.local),
- path,
- traceMap,
- false
- );
- return
- }
-
- if (type === "ExportSpecifier") {
- const key = specifierNode.local.name;
- if (!has(traceMap, key)) {
- return
- }
-
- path = path.concat(key); //eslint-disable-line no-param-reassign
- const nextTraceMap = traceMap[key];
- if (nextTraceMap[READ]) {
- yield {
- node: specifierNode,
- path,
- type: READ,
- info: nextTraceMap[READ],
- };
- }
- }
- }
- }
-
- ReferenceTracker.READ = READ;
- ReferenceTracker.CALL = CALL;
- ReferenceTracker.CONSTRUCT = CONSTRUCT;
- ReferenceTracker.ESM = ESM;
-
- /**
- * This is a predicate function for Array#filter.
- * @param {string} name A name part.
- * @param {number} index The index of the name.
- * @returns {boolean} `false` if it's default.
- */
- function exceptDefault(name, index) {
- return !(index === 1 && name === "default")
- }
-
- var index = {
- CALL,
- CONSTRUCT,
- ESM,
- findVariable,
- getFunctionHeadLocation,
- getFunctionNameWithKind,
- getInnermostScope,
- getPropertyName,
- getStaticValue,
- getStringIfConstant,
- isArrowToken,
- isClosingBraceToken,
- isClosingBracketToken,
- isClosingParenToken,
- isColonToken,
- isCommaToken,
- isCommentToken,
- isNotArrowToken,
- isNotClosingBraceToken,
- isNotClosingBracketToken,
- isNotClosingParenToken,
- isNotColonToken,
- isNotCommaToken,
- isNotCommentToken,
- isNotOpeningBraceToken,
- isNotOpeningBracketToken,
- isNotOpeningParenToken,
- isNotSemicolonToken,
- isOpeningBraceToken,
- isOpeningBracketToken,
- isOpeningParenToken,
- isSemicolonToken,
- PatternMatcher,
- READ,
- ReferenceTracker,
- };
-
- exports.default = index;
- exports.CALL = CALL;
- exports.CONSTRUCT = CONSTRUCT;
- exports.ESM = ESM;
- exports.findVariable = findVariable;
- exports.getFunctionHeadLocation = getFunctionHeadLocation;
- exports.getFunctionNameWithKind = getFunctionNameWithKind;
- exports.getInnermostScope = getInnermostScope;
- exports.getPropertyName = getPropertyName;
- exports.getStaticValue = getStaticValue;
- exports.getStringIfConstant = getStringIfConstant;
- exports.isArrowToken = isArrowToken;
- exports.isClosingBraceToken = isClosingBraceToken;
- exports.isClosingBracketToken = isClosingBracketToken;
- exports.isClosingParenToken = isClosingParenToken;
- exports.isColonToken = isColonToken;
- exports.isCommaToken = isCommaToken;
- exports.isCommentToken = isCommentToken;
- exports.isNotArrowToken = isNotArrowToken;
- exports.isNotClosingBraceToken = isNotClosingBraceToken;
- exports.isNotClosingBracketToken = isNotClosingBracketToken;
- exports.isNotClosingParenToken = isNotClosingParenToken;
- exports.isNotColonToken = isNotColonToken;
- exports.isNotCommaToken = isNotCommaToken;
- exports.isNotCommentToken = isNotCommentToken;
- exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
- exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
- exports.isNotOpeningParenToken = isNotOpeningParenToken;
- exports.isNotSemicolonToken = isNotSemicolonToken;
- exports.isOpeningBraceToken = isOpeningBraceToken;
- exports.isOpeningBracketToken = isOpeningBracketToken;
- exports.isOpeningParenToken = isOpeningParenToken;
- exports.isSemicolonToken = isSemicolonToken;
- exports.PatternMatcher = PatternMatcher;
- exports.READ = READ;
- exports.ReferenceTracker = ReferenceTracker;
- //# sourceMappingURL=index.js.map
|