index.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var eslintVisitorKeys = require('eslint-visitor-keys');
  4. /**
  5. * Get the innermost scope which contains a given location.
  6. * @param {Scope} initialScope The initial scope to search.
  7. * @param {Node} node The location to search.
  8. * @returns {Scope} The innermost scope.
  9. */
  10. function getInnermostScope(initialScope, node) {
  11. const location = node.range[0];
  12. let scope = initialScope;
  13. let found = false;
  14. do {
  15. found = false;
  16. for (const childScope of scope.childScopes) {
  17. const range = childScope.block.range;
  18. if (range[0] <= location && location < range[1]) {
  19. scope = childScope;
  20. found = true;
  21. break
  22. }
  23. }
  24. } while (found)
  25. return scope
  26. }
  27. /**
  28. * Find the variable of a given name.
  29. * @param {Scope} initialScope The scope to start finding.
  30. * @param {string|Node} nameOrNode The variable name to find. If this is a Node object then it should be an Identifier node.
  31. * @returns {Variable|null} The found variable or null.
  32. */
  33. function findVariable(initialScope, nameOrNode) {
  34. let name = "";
  35. let scope = initialScope;
  36. if (typeof nameOrNode === "string") {
  37. name = nameOrNode;
  38. } else {
  39. name = nameOrNode.name;
  40. scope = getInnermostScope(scope, nameOrNode);
  41. }
  42. while (scope != null) {
  43. const variable = scope.set.get(name);
  44. if (variable != null) {
  45. return variable
  46. }
  47. scope = scope.upper;
  48. }
  49. return null
  50. }
  51. /**
  52. * Creates the negate function of the given function.
  53. * @param {function(Token):boolean} f - The function to negate.
  54. * @returns {function(Token):boolean} Negated function.
  55. */
  56. function negate(f) {
  57. return (token) => !f(token)
  58. }
  59. /**
  60. * Checks if the given token is a PunctuatorToken with the given value
  61. * @param {Token} token - The token to check.
  62. * @param {string} value - The value to check.
  63. * @returns {boolean} `true` if the token is a PunctuatorToken with the given value.
  64. */
  65. function isPunctuatorTokenWithValue(token, value) {
  66. return token.type === "Punctuator" && token.value === value
  67. }
  68. /**
  69. * Checks if the given token is an arrow token or not.
  70. * @param {Token} token - The token to check.
  71. * @returns {boolean} `true` if the token is an arrow token.
  72. */
  73. function isArrowToken(token) {
  74. return isPunctuatorTokenWithValue(token, "=>")
  75. }
  76. /**
  77. * Checks if the given token is a comma token or not.
  78. * @param {Token} token - The token to check.
  79. * @returns {boolean} `true` if the token is a comma token.
  80. */
  81. function isCommaToken(token) {
  82. return isPunctuatorTokenWithValue(token, ",")
  83. }
  84. /**
  85. * Checks if the given token is a semicolon token or not.
  86. * @param {Token} token - The token to check.
  87. * @returns {boolean} `true` if the token is a semicolon token.
  88. */
  89. function isSemicolonToken(token) {
  90. return isPunctuatorTokenWithValue(token, ";")
  91. }
  92. /**
  93. * Checks if the given token is a colon token or not.
  94. * @param {Token} token - The token to check.
  95. * @returns {boolean} `true` if the token is a colon token.
  96. */
  97. function isColonToken(token) {
  98. return isPunctuatorTokenWithValue(token, ":")
  99. }
  100. /**
  101. * Checks if the given token is an opening parenthesis token or not.
  102. * @param {Token} token - The token to check.
  103. * @returns {boolean} `true` if the token is an opening parenthesis token.
  104. */
  105. function isOpeningParenToken(token) {
  106. return isPunctuatorTokenWithValue(token, "(")
  107. }
  108. /**
  109. * Checks if the given token is a closing parenthesis token or not.
  110. * @param {Token} token - The token to check.
  111. * @returns {boolean} `true` if the token is a closing parenthesis token.
  112. */
  113. function isClosingParenToken(token) {
  114. return isPunctuatorTokenWithValue(token, ")")
  115. }
  116. /**
  117. * Checks if the given token is an opening square bracket token or not.
  118. * @param {Token} token - The token to check.
  119. * @returns {boolean} `true` if the token is an opening square bracket token.
  120. */
  121. function isOpeningBracketToken(token) {
  122. return isPunctuatorTokenWithValue(token, "[")
  123. }
  124. /**
  125. * Checks if the given token is a closing square bracket token or not.
  126. * @param {Token} token - The token to check.
  127. * @returns {boolean} `true` if the token is a closing square bracket token.
  128. */
  129. function isClosingBracketToken(token) {
  130. return isPunctuatorTokenWithValue(token, "]")
  131. }
  132. /**
  133. * Checks if the given token is an opening brace token or not.
  134. * @param {Token} token - The token to check.
  135. * @returns {boolean} `true` if the token is an opening brace token.
  136. */
  137. function isOpeningBraceToken(token) {
  138. return isPunctuatorTokenWithValue(token, "{")
  139. }
  140. /**
  141. * Checks if the given token is a closing brace token or not.
  142. * @param {Token} token - The token to check.
  143. * @returns {boolean} `true` if the token is a closing brace token.
  144. */
  145. function isClosingBraceToken(token) {
  146. return isPunctuatorTokenWithValue(token, "}")
  147. }
  148. /**
  149. * Checks if the given token is a comment token or not.
  150. * @param {Token} token - The token to check.
  151. * @returns {boolean} `true` if the token is a comment token.
  152. */
  153. function isCommentToken(token) {
  154. return ["Block", "Line", "Shebang"].includes(token.type)
  155. }
  156. const isNotArrowToken = negate(isArrowToken);
  157. const isNotCommaToken = negate(isCommaToken);
  158. const isNotSemicolonToken = negate(isSemicolonToken);
  159. const isNotColonToken = negate(isColonToken);
  160. const isNotOpeningParenToken = negate(isOpeningParenToken);
  161. const isNotClosingParenToken = negate(isClosingParenToken);
  162. const isNotOpeningBracketToken = negate(isOpeningBracketToken);
  163. const isNotClosingBracketToken = negate(isClosingBracketToken);
  164. const isNotOpeningBraceToken = negate(isOpeningBraceToken);
  165. const isNotClosingBraceToken = negate(isClosingBraceToken);
  166. const isNotCommentToken = negate(isCommentToken);
  167. /**
  168. * Get the `(` token of the given function node.
  169. * @param {Node} node - The function node to get.
  170. * @param {SourceCode} sourceCode - The source code object to get tokens.
  171. * @returns {Token} `(` token.
  172. */
  173. function getOpeningParenOfParams(node, sourceCode) {
  174. return node.id
  175. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  176. : sourceCode.getFirstToken(node, isOpeningParenToken)
  177. }
  178. /**
  179. * Get the location of the given function node for reporting.
  180. * @param {Node} node - The function node to get.
  181. * @param {SourceCode} sourceCode - The source code object to get tokens.
  182. * @returns {string} The location of the function node for reporting.
  183. */
  184. function getFunctionHeadLocation(node, sourceCode) {
  185. const parent = node.parent;
  186. let start = null;
  187. let end = null;
  188. if (node.type === "ArrowFunctionExpression") {
  189. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  190. start = arrowToken.loc.start;
  191. end = arrowToken.loc.end;
  192. } else if (
  193. parent.type === "Property" ||
  194. parent.type === "MethodDefinition" ||
  195. parent.type === "PropertyDefinition"
  196. ) {
  197. start = parent.loc.start;
  198. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  199. } else {
  200. start = node.loc.start;
  201. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  202. }
  203. return {
  204. start: { ...start },
  205. end: { ...end },
  206. }
  207. }
  208. /* globals globalThis, global, self, window */
  209. const globalObject =
  210. typeof globalThis !== "undefined"
  211. ? globalThis
  212. : typeof self !== "undefined"
  213. ? self
  214. : typeof window !== "undefined"
  215. ? window
  216. : typeof global !== "undefined"
  217. ? global
  218. : {};
  219. const builtinNames = Object.freeze(
  220. new Set([
  221. "Array",
  222. "ArrayBuffer",
  223. "BigInt",
  224. "BigInt64Array",
  225. "BigUint64Array",
  226. "Boolean",
  227. "DataView",
  228. "Date",
  229. "decodeURI",
  230. "decodeURIComponent",
  231. "encodeURI",
  232. "encodeURIComponent",
  233. "escape",
  234. "Float32Array",
  235. "Float64Array",
  236. "Function",
  237. "Infinity",
  238. "Int16Array",
  239. "Int32Array",
  240. "Int8Array",
  241. "isFinite",
  242. "isNaN",
  243. "isPrototypeOf",
  244. "JSON",
  245. "Map",
  246. "Math",
  247. "NaN",
  248. "Number",
  249. "Object",
  250. "parseFloat",
  251. "parseInt",
  252. "Promise",
  253. "Proxy",
  254. "Reflect",
  255. "RegExp",
  256. "Set",
  257. "String",
  258. "Symbol",
  259. "Uint16Array",
  260. "Uint32Array",
  261. "Uint8Array",
  262. "Uint8ClampedArray",
  263. "undefined",
  264. "unescape",
  265. "WeakMap",
  266. "WeakSet",
  267. ]),
  268. );
  269. const callAllowed = new Set(
  270. [
  271. Array.isArray,
  272. Array.of,
  273. Array.prototype.at,
  274. Array.prototype.concat,
  275. Array.prototype.entries,
  276. Array.prototype.every,
  277. Array.prototype.filter,
  278. Array.prototype.find,
  279. Array.prototype.findIndex,
  280. Array.prototype.flat,
  281. Array.prototype.includes,
  282. Array.prototype.indexOf,
  283. Array.prototype.join,
  284. Array.prototype.keys,
  285. Array.prototype.lastIndexOf,
  286. Array.prototype.slice,
  287. Array.prototype.some,
  288. Array.prototype.toString,
  289. Array.prototype.values,
  290. typeof BigInt === "function" ? BigInt : undefined,
  291. Boolean,
  292. Date,
  293. Date.parse,
  294. decodeURI,
  295. decodeURIComponent,
  296. encodeURI,
  297. encodeURIComponent,
  298. escape,
  299. isFinite,
  300. isNaN,
  301. isPrototypeOf,
  302. Map,
  303. Map.prototype.entries,
  304. Map.prototype.get,
  305. Map.prototype.has,
  306. Map.prototype.keys,
  307. Map.prototype.values,
  308. ...Object.getOwnPropertyNames(Math)
  309. .filter((k) => k !== "random")
  310. .map((k) => Math[k])
  311. .filter((f) => typeof f === "function"),
  312. Number,
  313. Number.isFinite,
  314. Number.isNaN,
  315. Number.parseFloat,
  316. Number.parseInt,
  317. Number.prototype.toExponential,
  318. Number.prototype.toFixed,
  319. Number.prototype.toPrecision,
  320. Number.prototype.toString,
  321. Object,
  322. Object.entries,
  323. Object.is,
  324. Object.isExtensible,
  325. Object.isFrozen,
  326. Object.isSealed,
  327. Object.keys,
  328. Object.values,
  329. parseFloat,
  330. parseInt,
  331. RegExp,
  332. Set,
  333. Set.prototype.entries,
  334. Set.prototype.has,
  335. Set.prototype.keys,
  336. Set.prototype.values,
  337. String,
  338. String.fromCharCode,
  339. String.fromCodePoint,
  340. String.raw,
  341. String.prototype.at,
  342. String.prototype.charAt,
  343. String.prototype.charCodeAt,
  344. String.prototype.codePointAt,
  345. String.prototype.concat,
  346. String.prototype.endsWith,
  347. String.prototype.includes,
  348. String.prototype.indexOf,
  349. String.prototype.lastIndexOf,
  350. String.prototype.normalize,
  351. String.prototype.padEnd,
  352. String.prototype.padStart,
  353. String.prototype.slice,
  354. String.prototype.startsWith,
  355. String.prototype.substr,
  356. String.prototype.substring,
  357. String.prototype.toLowerCase,
  358. String.prototype.toString,
  359. String.prototype.toUpperCase,
  360. String.prototype.trim,
  361. String.prototype.trimEnd,
  362. String.prototype.trimLeft,
  363. String.prototype.trimRight,
  364. String.prototype.trimStart,
  365. Symbol.for,
  366. Symbol.keyFor,
  367. unescape,
  368. ].filter((f) => typeof f === "function"),
  369. );
  370. const callPassThrough = new Set([
  371. Object.freeze,
  372. Object.preventExtensions,
  373. Object.seal,
  374. ]);
  375. /** @type {ReadonlyArray<readonly [Function, ReadonlySet<string>]>} */
  376. const getterAllowed = [
  377. [Map, new Set(["size"])],
  378. [
  379. RegExp,
  380. new Set([
  381. "dotAll",
  382. "flags",
  383. "global",
  384. "hasIndices",
  385. "ignoreCase",
  386. "multiline",
  387. "source",
  388. "sticky",
  389. "unicode",
  390. ]),
  391. ],
  392. [Set, new Set(["size"])],
  393. ];
  394. /**
  395. * Get the property descriptor.
  396. * @param {object} object The object to get.
  397. * @param {string|number|symbol} name The property name to get.
  398. */
  399. function getPropertyDescriptor(object, name) {
  400. let x = object;
  401. while ((typeof x === "object" || typeof x === "function") && x !== null) {
  402. const d = Object.getOwnPropertyDescriptor(x, name);
  403. if (d) {
  404. return d
  405. }
  406. x = Object.getPrototypeOf(x);
  407. }
  408. return null
  409. }
  410. /**
  411. * Check if a property is getter or not.
  412. * @param {object} object The object to check.
  413. * @param {string|number|symbol} name The property name to check.
  414. */
  415. function isGetter(object, name) {
  416. const d = getPropertyDescriptor(object, name);
  417. return d != null && d.get != null
  418. }
  419. /**
  420. * Get the element values of a given node list.
  421. * @param {Node[]} nodeList The node list to get values.
  422. * @param {Scope|undefined} initialScope The initial scope to find variables.
  423. * @returns {any[]|null} The value list if all nodes are constant. Otherwise, null.
  424. */
  425. function getElementValues(nodeList, initialScope) {
  426. const valueList = [];
  427. for (let i = 0; i < nodeList.length; ++i) {
  428. const elementNode = nodeList[i];
  429. if (elementNode == null) {
  430. valueList.length = i + 1;
  431. } else if (elementNode.type === "SpreadElement") {
  432. const argument = getStaticValueR(elementNode.argument, initialScope);
  433. if (argument == null) {
  434. return null
  435. }
  436. valueList.push(...argument.value);
  437. } else {
  438. const element = getStaticValueR(elementNode, initialScope);
  439. if (element == null) {
  440. return null
  441. }
  442. valueList.push(element.value);
  443. }
  444. }
  445. return valueList
  446. }
  447. /**
  448. * Returns whether the given variable is never written to after initialization.
  449. * @param {import("eslint").Scope.Variable} variable
  450. * @returns {boolean}
  451. */
  452. function isEffectivelyConst(variable) {
  453. const refs = variable.references;
  454. const inits = refs.filter((r) => r.init).length;
  455. const reads = refs.filter((r) => r.isReadOnly()).length;
  456. if (inits === 1 && reads + inits === refs.length) {
  457. // there is only one init and all other references only read
  458. return true
  459. }
  460. return false
  461. }
  462. const operations = Object.freeze({
  463. ArrayExpression(node, initialScope) {
  464. const elements = getElementValues(node.elements, initialScope);
  465. return elements != null ? { value: elements } : null
  466. },
  467. AssignmentExpression(node, initialScope) {
  468. if (node.operator === "=") {
  469. return getStaticValueR(node.right, initialScope)
  470. }
  471. return null
  472. },
  473. //eslint-disable-next-line complexity
  474. BinaryExpression(node, initialScope) {
  475. if (node.operator === "in" || node.operator === "instanceof") {
  476. // Not supported.
  477. return null
  478. }
  479. const left = getStaticValueR(node.left, initialScope);
  480. const right = getStaticValueR(node.right, initialScope);
  481. if (left != null && right != null) {
  482. switch (node.operator) {
  483. case "==":
  484. return { value: left.value == right.value } //eslint-disable-line eqeqeq
  485. case "!=":
  486. return { value: left.value != right.value } //eslint-disable-line eqeqeq
  487. case "===":
  488. return { value: left.value === right.value }
  489. case "!==":
  490. return { value: left.value !== right.value }
  491. case "<":
  492. return { value: left.value < right.value }
  493. case "<=":
  494. return { value: left.value <= right.value }
  495. case ">":
  496. return { value: left.value > right.value }
  497. case ">=":
  498. return { value: left.value >= right.value }
  499. case "<<":
  500. return { value: left.value << right.value }
  501. case ">>":
  502. return { value: left.value >> right.value }
  503. case ">>>":
  504. return { value: left.value >>> right.value }
  505. case "+":
  506. return { value: left.value + right.value }
  507. case "-":
  508. return { value: left.value - right.value }
  509. case "*":
  510. return { value: left.value * right.value }
  511. case "/":
  512. return { value: left.value / right.value }
  513. case "%":
  514. return { value: left.value % right.value }
  515. case "**":
  516. return { value: left.value ** right.value }
  517. case "|":
  518. return { value: left.value | right.value }
  519. case "^":
  520. return { value: left.value ^ right.value }
  521. case "&":
  522. return { value: left.value & right.value }
  523. // no default
  524. }
  525. }
  526. return null
  527. },
  528. CallExpression(node, initialScope) {
  529. const calleeNode = node.callee;
  530. const args = getElementValues(node.arguments, initialScope);
  531. if (args != null) {
  532. if (calleeNode.type === "MemberExpression") {
  533. if (calleeNode.property.type === "PrivateIdentifier") {
  534. return null
  535. }
  536. const object = getStaticValueR(calleeNode.object, initialScope);
  537. if (object != null) {
  538. if (
  539. object.value == null &&
  540. (object.optional || node.optional)
  541. ) {
  542. return { value: undefined, optional: true }
  543. }
  544. const property = getStaticPropertyNameValue(
  545. calleeNode,
  546. initialScope,
  547. );
  548. if (property != null) {
  549. const receiver = object.value;
  550. const methodName = property.value;
  551. if (callAllowed.has(receiver[methodName])) {
  552. return { value: receiver[methodName](...args) }
  553. }
  554. if (callPassThrough.has(receiver[methodName])) {
  555. return { value: args[0] }
  556. }
  557. }
  558. }
  559. } else {
  560. const callee = getStaticValueR(calleeNode, initialScope);
  561. if (callee != null) {
  562. if (callee.value == null && node.optional) {
  563. return { value: undefined, optional: true }
  564. }
  565. const func = callee.value;
  566. if (callAllowed.has(func)) {
  567. return { value: func(...args) }
  568. }
  569. if (callPassThrough.has(func)) {
  570. return { value: args[0] }
  571. }
  572. }
  573. }
  574. }
  575. return null
  576. },
  577. ConditionalExpression(node, initialScope) {
  578. const test = getStaticValueR(node.test, initialScope);
  579. if (test != null) {
  580. return test.value
  581. ? getStaticValueR(node.consequent, initialScope)
  582. : getStaticValueR(node.alternate, initialScope)
  583. }
  584. return null
  585. },
  586. ExpressionStatement(node, initialScope) {
  587. return getStaticValueR(node.expression, initialScope)
  588. },
  589. Identifier(node, initialScope) {
  590. if (initialScope != null) {
  591. const variable = findVariable(initialScope, node);
  592. // Built-in globals.
  593. if (
  594. variable != null &&
  595. variable.defs.length === 0 &&
  596. builtinNames.has(variable.name) &&
  597. variable.name in globalObject
  598. ) {
  599. return { value: globalObject[variable.name] }
  600. }
  601. // Constants.
  602. if (variable != null && variable.defs.length === 1) {
  603. const def = variable.defs[0];
  604. if (
  605. def.parent &&
  606. def.type === "Variable" &&
  607. (def.parent.kind === "const" ||
  608. isEffectivelyConst(variable)) &&
  609. // TODO(mysticatea): don't support destructuring here.
  610. def.node.id.type === "Identifier"
  611. ) {
  612. return getStaticValueR(def.node.init, initialScope)
  613. }
  614. }
  615. }
  616. return null
  617. },
  618. Literal(node) {
  619. //istanbul ignore if : this is implementation-specific behavior.
  620. if ((node.regex != null || node.bigint != null) && node.value == null) {
  621. // It was a RegExp/BigInt literal, but Node.js didn't support it.
  622. return null
  623. }
  624. return { value: node.value }
  625. },
  626. LogicalExpression(node, initialScope) {
  627. const left = getStaticValueR(node.left, initialScope);
  628. if (left != null) {
  629. if (
  630. (node.operator === "||" && Boolean(left.value) === true) ||
  631. (node.operator === "&&" && Boolean(left.value) === false) ||
  632. (node.operator === "??" && left.value != null)
  633. ) {
  634. return left
  635. }
  636. const right = getStaticValueR(node.right, initialScope);
  637. if (right != null) {
  638. return right
  639. }
  640. }
  641. return null
  642. },
  643. MemberExpression(node, initialScope) {
  644. if (node.property.type === "PrivateIdentifier") {
  645. return null
  646. }
  647. const object = getStaticValueR(node.object, initialScope);
  648. if (object != null) {
  649. if (object.value == null && (object.optional || node.optional)) {
  650. return { value: undefined, optional: true }
  651. }
  652. const property = getStaticPropertyNameValue(node, initialScope);
  653. if (property != null) {
  654. if (!isGetter(object.value, property.value)) {
  655. return { value: object.value[property.value] }
  656. }
  657. for (const [classFn, allowed] of getterAllowed) {
  658. if (
  659. object.value instanceof classFn &&
  660. allowed.has(property.value)
  661. ) {
  662. return { value: object.value[property.value] }
  663. }
  664. }
  665. }
  666. }
  667. return null
  668. },
  669. ChainExpression(node, initialScope) {
  670. const expression = getStaticValueR(node.expression, initialScope);
  671. if (expression != null) {
  672. return { value: expression.value }
  673. }
  674. return null
  675. },
  676. NewExpression(node, initialScope) {
  677. const callee = getStaticValueR(node.callee, initialScope);
  678. const args = getElementValues(node.arguments, initialScope);
  679. if (callee != null && args != null) {
  680. const Func = callee.value;
  681. if (callAllowed.has(Func)) {
  682. return { value: new Func(...args) }
  683. }
  684. }
  685. return null
  686. },
  687. ObjectExpression(node, initialScope) {
  688. const object = {};
  689. for (const propertyNode of node.properties) {
  690. if (propertyNode.type === "Property") {
  691. if (propertyNode.kind !== "init") {
  692. return null
  693. }
  694. const key = getStaticPropertyNameValue(
  695. propertyNode,
  696. initialScope,
  697. );
  698. const value = getStaticValueR(propertyNode.value, initialScope);
  699. if (key == null || value == null) {
  700. return null
  701. }
  702. object[key.value] = value.value;
  703. } else if (
  704. propertyNode.type === "SpreadElement" ||
  705. propertyNode.type === "ExperimentalSpreadProperty"
  706. ) {
  707. const argument = getStaticValueR(
  708. propertyNode.argument,
  709. initialScope,
  710. );
  711. if (argument == null) {
  712. return null
  713. }
  714. Object.assign(object, argument.value);
  715. } else {
  716. return null
  717. }
  718. }
  719. return { value: object }
  720. },
  721. SequenceExpression(node, initialScope) {
  722. const last = node.expressions[node.expressions.length - 1];
  723. return getStaticValueR(last, initialScope)
  724. },
  725. TaggedTemplateExpression(node, initialScope) {
  726. const tag = getStaticValueR(node.tag, initialScope);
  727. const expressions = getElementValues(
  728. node.quasi.expressions,
  729. initialScope,
  730. );
  731. if (tag != null && expressions != null) {
  732. const func = tag.value;
  733. const strings = node.quasi.quasis.map((q) => q.value.cooked);
  734. strings.raw = node.quasi.quasis.map((q) => q.value.raw);
  735. if (func === String.raw) {
  736. return { value: func(strings, ...expressions) }
  737. }
  738. }
  739. return null
  740. },
  741. TemplateLiteral(node, initialScope) {
  742. const expressions = getElementValues(node.expressions, initialScope);
  743. if (expressions != null) {
  744. let value = node.quasis[0].value.cooked;
  745. for (let i = 0; i < expressions.length; ++i) {
  746. value += expressions[i];
  747. value += node.quasis[i + 1].value.cooked;
  748. }
  749. return { value }
  750. }
  751. return null
  752. },
  753. UnaryExpression(node, initialScope) {
  754. if (node.operator === "delete") {
  755. // Not supported.
  756. return null
  757. }
  758. if (node.operator === "void") {
  759. return { value: undefined }
  760. }
  761. const arg = getStaticValueR(node.argument, initialScope);
  762. if (arg != null) {
  763. switch (node.operator) {
  764. case "-":
  765. return { value: -arg.value }
  766. case "+":
  767. return { value: +arg.value } //eslint-disable-line no-implicit-coercion
  768. case "!":
  769. return { value: !arg.value }
  770. case "~":
  771. return { value: ~arg.value }
  772. case "typeof":
  773. return { value: typeof arg.value }
  774. // no default
  775. }
  776. }
  777. return null
  778. },
  779. });
  780. /**
  781. * Get the value of a given node if it's a static value.
  782. * @param {Node} node The node to get.
  783. * @param {Scope|undefined} initialScope The scope to start finding variable.
  784. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  785. */
  786. function getStaticValueR(node, initialScope) {
  787. if (node != null && Object.hasOwnProperty.call(operations, node.type)) {
  788. return operations[node.type](node, initialScope)
  789. }
  790. return null
  791. }
  792. /**
  793. * Get the static value of property name from a MemberExpression node or a Property node.
  794. * @param {Node} node The node to get.
  795. * @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.
  796. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the property name of the node, or `null`.
  797. */
  798. function getStaticPropertyNameValue(node, initialScope) {
  799. const nameNode = node.type === "Property" ? node.key : node.property;
  800. if (node.computed) {
  801. return getStaticValueR(nameNode, initialScope)
  802. }
  803. if (nameNode.type === "Identifier") {
  804. return { value: nameNode.name }
  805. }
  806. if (nameNode.type === "Literal") {
  807. if (nameNode.bigint) {
  808. return { value: nameNode.bigint }
  809. }
  810. return { value: String(nameNode.value) }
  811. }
  812. return null
  813. }
  814. /**
  815. * Get the value of a given node if it's a static value.
  816. * @param {Node} node The node to get.
  817. * @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.
  818. * @returns {{value:any}|{value:undefined,optional?:true}|null} The static value of the node, or `null`.
  819. */
  820. function getStaticValue(node, initialScope = null) {
  821. try {
  822. return getStaticValueR(node, initialScope)
  823. } catch (_error) {
  824. return null
  825. }
  826. }
  827. /**
  828. * Get the value of a given node if it's a literal or a template literal.
  829. * @param {Node} node The node to get.
  830. * @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.
  831. * @returns {string|null} The value of the node, or `null`.
  832. */
  833. function getStringIfConstant(node, initialScope = null) {
  834. // Handle the literals that the platform doesn't support natively.
  835. if (node && node.type === "Literal" && node.value === null) {
  836. if (node.regex) {
  837. return `/${node.regex.pattern}/${node.regex.flags}`
  838. }
  839. if (node.bigint) {
  840. return node.bigint
  841. }
  842. }
  843. const evaluated = getStaticValue(node, initialScope);
  844. return evaluated && String(evaluated.value)
  845. }
  846. /**
  847. * Get the property name from a MemberExpression node or a Property node.
  848. * @param {Node} node The node to get.
  849. * @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.
  850. * @returns {string|null} The property name of the node.
  851. */
  852. function getPropertyName(node, initialScope) {
  853. switch (node.type) {
  854. case "MemberExpression":
  855. if (node.computed) {
  856. return getStringIfConstant(node.property, initialScope)
  857. }
  858. if (node.property.type === "PrivateIdentifier") {
  859. return null
  860. }
  861. return node.property.name
  862. case "Property":
  863. case "MethodDefinition":
  864. case "PropertyDefinition":
  865. if (node.computed) {
  866. return getStringIfConstant(node.key, initialScope)
  867. }
  868. if (node.key.type === "Literal") {
  869. return String(node.key.value)
  870. }
  871. if (node.key.type === "PrivateIdentifier") {
  872. return null
  873. }
  874. return node.key.name
  875. // no default
  876. }
  877. return null
  878. }
  879. /**
  880. * Get the name and kind of the given function node.
  881. * @param {ASTNode} node - The function node to get.
  882. * @param {SourceCode} [sourceCode] The source code object to get the code of computed property keys.
  883. * @returns {string} The name and kind of the function node.
  884. */
  885. // eslint-disable-next-line complexity
  886. function getFunctionNameWithKind(node, sourceCode) {
  887. const parent = node.parent;
  888. const tokens = [];
  889. const isObjectMethod = parent.type === "Property" && parent.value === node;
  890. const isClassMethod =
  891. parent.type === "MethodDefinition" && parent.value === node;
  892. const isClassFieldMethod =
  893. parent.type === "PropertyDefinition" && parent.value === node;
  894. // Modifiers.
  895. if (isClassMethod || isClassFieldMethod) {
  896. if (parent.static) {
  897. tokens.push("static");
  898. }
  899. if (parent.key.type === "PrivateIdentifier") {
  900. tokens.push("private");
  901. }
  902. }
  903. if (node.async) {
  904. tokens.push("async");
  905. }
  906. if (node.generator) {
  907. tokens.push("generator");
  908. }
  909. // Kinds.
  910. if (isObjectMethod || isClassMethod) {
  911. if (parent.kind === "constructor") {
  912. return "constructor"
  913. }
  914. if (parent.kind === "get") {
  915. tokens.push("getter");
  916. } else if (parent.kind === "set") {
  917. tokens.push("setter");
  918. } else {
  919. tokens.push("method");
  920. }
  921. } else if (isClassFieldMethod) {
  922. tokens.push("method");
  923. } else {
  924. if (node.type === "ArrowFunctionExpression") {
  925. tokens.push("arrow");
  926. }
  927. tokens.push("function");
  928. }
  929. // Names.
  930. if (isObjectMethod || isClassMethod || isClassFieldMethod) {
  931. if (parent.key.type === "PrivateIdentifier") {
  932. tokens.push(`#${parent.key.name}`);
  933. } else {
  934. const name = getPropertyName(parent);
  935. if (name) {
  936. tokens.push(`'${name}'`);
  937. } else if (sourceCode) {
  938. const keyText = sourceCode.getText(parent.key);
  939. if (!keyText.includes("\n")) {
  940. tokens.push(`[${keyText}]`);
  941. }
  942. }
  943. }
  944. } else if (node.id) {
  945. tokens.push(`'${node.id.name}'`);
  946. } else if (
  947. parent.type === "VariableDeclarator" &&
  948. parent.id &&
  949. parent.id.type === "Identifier"
  950. ) {
  951. tokens.push(`'${parent.id.name}'`);
  952. } else if (
  953. (parent.type === "AssignmentExpression" ||
  954. parent.type === "AssignmentPattern") &&
  955. parent.left &&
  956. parent.left.type === "Identifier"
  957. ) {
  958. tokens.push(`'${parent.left.name}'`);
  959. } else if (
  960. parent.type === "ExportDefaultDeclaration" &&
  961. parent.declaration === node
  962. ) {
  963. tokens.push("'default'");
  964. }
  965. return tokens.join(" ")
  966. }
  967. const typeConversionBinaryOps = Object.freeze(
  968. new Set([
  969. "==",
  970. "!=",
  971. "<",
  972. "<=",
  973. ">",
  974. ">=",
  975. "<<",
  976. ">>",
  977. ">>>",
  978. "+",
  979. "-",
  980. "*",
  981. "/",
  982. "%",
  983. "|",
  984. "^",
  985. "&",
  986. "in",
  987. ]),
  988. );
  989. const typeConversionUnaryOps = Object.freeze(new Set(["-", "+", "!", "~"]));
  990. /**
  991. * Check whether the given value is an ASTNode or not.
  992. * @param {any} x The value to check.
  993. * @returns {boolean} `true` if the value is an ASTNode.
  994. */
  995. function isNode(x) {
  996. return x !== null && typeof x === "object" && typeof x.type === "string"
  997. }
  998. const visitor = Object.freeze(
  999. Object.assign(Object.create(null), {
  1000. $visit(node, options, visitorKeys) {
  1001. const { type } = node;
  1002. if (typeof this[type] === "function") {
  1003. return this[type](node, options, visitorKeys)
  1004. }
  1005. return this.$visitChildren(node, options, visitorKeys)
  1006. },
  1007. $visitChildren(node, options, visitorKeys) {
  1008. const { type } = node;
  1009. for (const key of visitorKeys[type] || eslintVisitorKeys.getKeys(node)) {
  1010. const value = node[key];
  1011. if (Array.isArray(value)) {
  1012. for (const element of value) {
  1013. if (
  1014. isNode(element) &&
  1015. this.$visit(element, options, visitorKeys)
  1016. ) {
  1017. return true
  1018. }
  1019. }
  1020. } else if (
  1021. isNode(value) &&
  1022. this.$visit(value, options, visitorKeys)
  1023. ) {
  1024. return true
  1025. }
  1026. }
  1027. return false
  1028. },
  1029. ArrowFunctionExpression() {
  1030. return false
  1031. },
  1032. AssignmentExpression() {
  1033. return true
  1034. },
  1035. AwaitExpression() {
  1036. return true
  1037. },
  1038. BinaryExpression(node, options, visitorKeys) {
  1039. if (
  1040. options.considerImplicitTypeConversion &&
  1041. typeConversionBinaryOps.has(node.operator) &&
  1042. (node.left.type !== "Literal" || node.right.type !== "Literal")
  1043. ) {
  1044. return true
  1045. }
  1046. return this.$visitChildren(node, options, visitorKeys)
  1047. },
  1048. CallExpression() {
  1049. return true
  1050. },
  1051. FunctionExpression() {
  1052. return false
  1053. },
  1054. ImportExpression() {
  1055. return true
  1056. },
  1057. MemberExpression(node, options, visitorKeys) {
  1058. if (options.considerGetters) {
  1059. return true
  1060. }
  1061. if (
  1062. options.considerImplicitTypeConversion &&
  1063. node.computed &&
  1064. node.property.type !== "Literal"
  1065. ) {
  1066. return true
  1067. }
  1068. return this.$visitChildren(node, options, visitorKeys)
  1069. },
  1070. MethodDefinition(node, options, visitorKeys) {
  1071. if (
  1072. options.considerImplicitTypeConversion &&
  1073. node.computed &&
  1074. node.key.type !== "Literal"
  1075. ) {
  1076. return true
  1077. }
  1078. return this.$visitChildren(node, options, visitorKeys)
  1079. },
  1080. NewExpression() {
  1081. return true
  1082. },
  1083. Property(node, options, visitorKeys) {
  1084. if (
  1085. options.considerImplicitTypeConversion &&
  1086. node.computed &&
  1087. node.key.type !== "Literal"
  1088. ) {
  1089. return true
  1090. }
  1091. return this.$visitChildren(node, options, visitorKeys)
  1092. },
  1093. PropertyDefinition(node, options, visitorKeys) {
  1094. if (
  1095. options.considerImplicitTypeConversion &&
  1096. node.computed &&
  1097. node.key.type !== "Literal"
  1098. ) {
  1099. return true
  1100. }
  1101. return this.$visitChildren(node, options, visitorKeys)
  1102. },
  1103. UnaryExpression(node, options, visitorKeys) {
  1104. if (node.operator === "delete") {
  1105. return true
  1106. }
  1107. if (
  1108. options.considerImplicitTypeConversion &&
  1109. typeConversionUnaryOps.has(node.operator) &&
  1110. node.argument.type !== "Literal"
  1111. ) {
  1112. return true
  1113. }
  1114. return this.$visitChildren(node, options, visitorKeys)
  1115. },
  1116. UpdateExpression() {
  1117. return true
  1118. },
  1119. YieldExpression() {
  1120. return true
  1121. },
  1122. }),
  1123. );
  1124. /**
  1125. * Check whether a given node has any side effect or not.
  1126. * @param {Node} node The node to get.
  1127. * @param {SourceCode} sourceCode The source code object.
  1128. * @param {object} [options] The option object.
  1129. * @param {boolean} [options.considerGetters=false] If `true` then it considers member accesses as the node which has side effects.
  1130. * @param {boolean} [options.considerImplicitTypeConversion=false] If `true` then it considers implicit type conversion as the node which has side effects.
  1131. * @param {object} [options.visitorKeys=KEYS] The keys to traverse nodes. Use `context.getSourceCode().visitorKeys`.
  1132. * @returns {boolean} `true` if the node has a certain side effect.
  1133. */
  1134. function hasSideEffect(
  1135. node,
  1136. sourceCode,
  1137. { considerGetters = false, considerImplicitTypeConversion = false } = {},
  1138. ) {
  1139. return visitor.$visit(
  1140. node,
  1141. { considerGetters, considerImplicitTypeConversion },
  1142. sourceCode.visitorKeys || eslintVisitorKeys.KEYS,
  1143. )
  1144. }
  1145. /**
  1146. * Get the left parenthesis of the parent node syntax if it exists.
  1147. * E.g., `if (a) {}` then the `(`.
  1148. * @param {Node} node The AST node to check.
  1149. * @param {SourceCode} sourceCode The source code object to get tokens.
  1150. * @returns {Token|null} The left parenthesis of the parent node syntax
  1151. */
  1152. function getParentSyntaxParen(node, sourceCode) {
  1153. const parent = node.parent;
  1154. switch (parent.type) {
  1155. case "CallExpression":
  1156. case "NewExpression":
  1157. if (parent.arguments.length === 1 && parent.arguments[0] === node) {
  1158. return sourceCode.getTokenAfter(
  1159. parent.callee,
  1160. isOpeningParenToken,
  1161. )
  1162. }
  1163. return null
  1164. case "DoWhileStatement":
  1165. if (parent.test === node) {
  1166. return sourceCode.getTokenAfter(
  1167. parent.body,
  1168. isOpeningParenToken,
  1169. )
  1170. }
  1171. return null
  1172. case "IfStatement":
  1173. case "WhileStatement":
  1174. if (parent.test === node) {
  1175. return sourceCode.getFirstToken(parent, 1)
  1176. }
  1177. return null
  1178. case "ImportExpression":
  1179. if (parent.source === node) {
  1180. return sourceCode.getFirstToken(parent, 1)
  1181. }
  1182. return null
  1183. case "SwitchStatement":
  1184. if (parent.discriminant === node) {
  1185. return sourceCode.getFirstToken(parent, 1)
  1186. }
  1187. return null
  1188. case "WithStatement":
  1189. if (parent.object === node) {
  1190. return sourceCode.getFirstToken(parent, 1)
  1191. }
  1192. return null
  1193. default:
  1194. return null
  1195. }
  1196. }
  1197. /**
  1198. * Check whether a given node is parenthesized or not.
  1199. * @param {number} times The number of parantheses.
  1200. * @param {Node} node The AST node to check.
  1201. * @param {SourceCode} sourceCode The source code object to get tokens.
  1202. * @returns {boolean} `true` if the node is parenthesized the given times.
  1203. */
  1204. /**
  1205. * Check whether a given node is parenthesized or not.
  1206. * @param {Node} node The AST node to check.
  1207. * @param {SourceCode} sourceCode The source code object to get tokens.
  1208. * @returns {boolean} `true` if the node is parenthesized.
  1209. */
  1210. function isParenthesized(
  1211. timesOrNode,
  1212. nodeOrSourceCode,
  1213. optionalSourceCode,
  1214. ) {
  1215. let times, node, sourceCode, maybeLeftParen, maybeRightParen;
  1216. if (typeof timesOrNode === "number") {
  1217. times = timesOrNode | 0;
  1218. node = nodeOrSourceCode;
  1219. sourceCode = optionalSourceCode;
  1220. if (!(times >= 1)) {
  1221. throw new TypeError("'times' should be a positive integer.")
  1222. }
  1223. } else {
  1224. times = 1;
  1225. node = timesOrNode;
  1226. sourceCode = nodeOrSourceCode;
  1227. }
  1228. if (
  1229. node == null ||
  1230. // `Program` can't be parenthesized
  1231. node.parent == null ||
  1232. // `CatchClause.param` can't be parenthesized, example `try {} catch (error) {}`
  1233. (node.parent.type === "CatchClause" && node.parent.param === node)
  1234. ) {
  1235. return false
  1236. }
  1237. maybeLeftParen = maybeRightParen = node;
  1238. do {
  1239. maybeLeftParen = sourceCode.getTokenBefore(maybeLeftParen);
  1240. maybeRightParen = sourceCode.getTokenAfter(maybeRightParen);
  1241. } while (
  1242. maybeLeftParen != null &&
  1243. maybeRightParen != null &&
  1244. isOpeningParenToken(maybeLeftParen) &&
  1245. isClosingParenToken(maybeRightParen) &&
  1246. // Avoid false positive such as `if (a) {}`
  1247. maybeLeftParen !== getParentSyntaxParen(node, sourceCode) &&
  1248. --times > 0
  1249. )
  1250. return times === 0
  1251. }
  1252. /**
  1253. * @author Toru Nagashima <https://github.com/mysticatea>
  1254. * See LICENSE file in root directory for full license.
  1255. */
  1256. const placeholder = /\$(?:[$&`']|[1-9][0-9]?)/gu;
  1257. /** @type {WeakMap<PatternMatcher, {pattern:RegExp,escaped:boolean}>} */
  1258. const internal = new WeakMap();
  1259. /**
  1260. * Check whether a given character is escaped or not.
  1261. * @param {string} str The string to check.
  1262. * @param {number} index The location of the character to check.
  1263. * @returns {boolean} `true` if the character is escaped.
  1264. */
  1265. function isEscaped(str, index) {
  1266. let escaped = false;
  1267. for (let i = index - 1; i >= 0 && str.charCodeAt(i) === 0x5c; --i) {
  1268. escaped = !escaped;
  1269. }
  1270. return escaped
  1271. }
  1272. /**
  1273. * Replace a given string by a given matcher.
  1274. * @param {PatternMatcher} matcher The pattern matcher.
  1275. * @param {string} str The string to be replaced.
  1276. * @param {string} replacement The new substring to replace each matched part.
  1277. * @returns {string} The replaced string.
  1278. */
  1279. function replaceS(matcher, str, replacement) {
  1280. const chunks = [];
  1281. let index = 0;
  1282. /** @type {RegExpExecArray} */
  1283. let match = null;
  1284. /**
  1285. * @param {string} key The placeholder.
  1286. * @returns {string} The replaced string.
  1287. */
  1288. function replacer(key) {
  1289. switch (key) {
  1290. case "$$":
  1291. return "$"
  1292. case "$&":
  1293. return match[0]
  1294. case "$`":
  1295. return str.slice(0, match.index)
  1296. case "$'":
  1297. return str.slice(match.index + match[0].length)
  1298. default: {
  1299. const i = key.slice(1);
  1300. if (i in match) {
  1301. return match[i]
  1302. }
  1303. return key
  1304. }
  1305. }
  1306. }
  1307. for (match of matcher.execAll(str)) {
  1308. chunks.push(str.slice(index, match.index));
  1309. chunks.push(replacement.replace(placeholder, replacer));
  1310. index = match.index + match[0].length;
  1311. }
  1312. chunks.push(str.slice(index));
  1313. return chunks.join("")
  1314. }
  1315. /**
  1316. * Replace a given string by a given matcher.
  1317. * @param {PatternMatcher} matcher The pattern matcher.
  1318. * @param {string} str The string to be replaced.
  1319. * @param {(...strs[])=>string} replace The function to replace each matched part.
  1320. * @returns {string} The replaced string.
  1321. */
  1322. function replaceF(matcher, str, replace) {
  1323. const chunks = [];
  1324. let index = 0;
  1325. for (const match of matcher.execAll(str)) {
  1326. chunks.push(str.slice(index, match.index));
  1327. chunks.push(String(replace(...match, match.index, match.input)));
  1328. index = match.index + match[0].length;
  1329. }
  1330. chunks.push(str.slice(index));
  1331. return chunks.join("")
  1332. }
  1333. /**
  1334. * The class to find patterns as considering escape sequences.
  1335. */
  1336. class PatternMatcher {
  1337. /**
  1338. * Initialize this matcher.
  1339. * @param {RegExp} pattern The pattern to match.
  1340. * @param {{escaped:boolean}} options The options.
  1341. */
  1342. constructor(pattern, { escaped = false } = {}) {
  1343. if (!(pattern instanceof RegExp)) {
  1344. throw new TypeError("'pattern' should be a RegExp instance.")
  1345. }
  1346. if (!pattern.flags.includes("g")) {
  1347. throw new Error("'pattern' should contains 'g' flag.")
  1348. }
  1349. internal.set(this, {
  1350. pattern: new RegExp(pattern.source, pattern.flags),
  1351. escaped: Boolean(escaped),
  1352. });
  1353. }
  1354. /**
  1355. * Find the pattern in a given string.
  1356. * @param {string} str The string to find.
  1357. * @returns {IterableIterator<RegExpExecArray>} The iterator which iterate the matched information.
  1358. */
  1359. *execAll(str) {
  1360. const { pattern, escaped } = internal.get(this);
  1361. let match = null;
  1362. let lastIndex = 0;
  1363. pattern.lastIndex = 0;
  1364. while ((match = pattern.exec(str)) != null) {
  1365. if (escaped || !isEscaped(str, match.index)) {
  1366. lastIndex = pattern.lastIndex;
  1367. yield match;
  1368. pattern.lastIndex = lastIndex;
  1369. }
  1370. }
  1371. }
  1372. /**
  1373. * Check whether the pattern is found in a given string.
  1374. * @param {string} str The string to check.
  1375. * @returns {boolean} `true` if the pattern was found in the string.
  1376. */
  1377. test(str) {
  1378. const it = this.execAll(str);
  1379. const ret = it.next();
  1380. return !ret.done
  1381. }
  1382. /**
  1383. * Replace a given string.
  1384. * @param {string} str The string to be replaced.
  1385. * @param {(string|((...strs:string[])=>string))} replacer The string or function to replace. This is the same as the 2nd argument of `String.prototype.replace`.
  1386. * @returns {string} The replaced string.
  1387. */
  1388. [Symbol.replace](str, replacer) {
  1389. return typeof replacer === "function"
  1390. ? replaceF(this, String(str), replacer)
  1391. : replaceS(this, String(str), String(replacer))
  1392. }
  1393. }
  1394. const IMPORT_TYPE = /^(?:Import|Export(?:All|Default|Named))Declaration$/u;
  1395. const has = Function.call.bind(Object.hasOwnProperty);
  1396. const READ = Symbol("read");
  1397. const CALL = Symbol("call");
  1398. const CONSTRUCT = Symbol("construct");
  1399. const ESM = Symbol("esm");
  1400. const requireCall = { require: { [CALL]: true } };
  1401. /**
  1402. * Check whether a given variable is modified or not.
  1403. * @param {Variable} variable The variable to check.
  1404. * @returns {boolean} `true` if the variable is modified.
  1405. */
  1406. function isModifiedGlobal(variable) {
  1407. return (
  1408. variable == null ||
  1409. variable.defs.length !== 0 ||
  1410. variable.references.some((r) => r.isWrite())
  1411. )
  1412. }
  1413. /**
  1414. * Check if the value of a given node is passed through to the parent syntax as-is.
  1415. * For example, `a` and `b` in (`a || b` and `c ? a : b`) are passed through.
  1416. * @param {Node} node A node to check.
  1417. * @returns {boolean} `true` if the node is passed through.
  1418. */
  1419. function isPassThrough(node) {
  1420. const parent = node.parent;
  1421. switch (parent && parent.type) {
  1422. case "ConditionalExpression":
  1423. return parent.consequent === node || parent.alternate === node
  1424. case "LogicalExpression":
  1425. return true
  1426. case "SequenceExpression":
  1427. return parent.expressions[parent.expressions.length - 1] === node
  1428. case "ChainExpression":
  1429. return true
  1430. default:
  1431. return false
  1432. }
  1433. }
  1434. /**
  1435. * The reference tracker.
  1436. */
  1437. class ReferenceTracker {
  1438. /**
  1439. * Initialize this tracker.
  1440. * @param {Scope} globalScope The global scope.
  1441. * @param {object} [options] The options.
  1442. * @param {"legacy"|"strict"} [options.mode="strict"] The mode to determine the ImportDeclaration's behavior for CJS modules.
  1443. * @param {string[]} [options.globalObjectNames=["global","globalThis","self","window"]] The variable names for Global Object.
  1444. */
  1445. constructor(
  1446. globalScope,
  1447. {
  1448. mode = "strict",
  1449. globalObjectNames = ["global", "globalThis", "self", "window"],
  1450. } = {},
  1451. ) {
  1452. this.variableStack = [];
  1453. this.globalScope = globalScope;
  1454. this.mode = mode;
  1455. this.globalObjectNames = globalObjectNames.slice(0);
  1456. }
  1457. /**
  1458. * Iterate the references of global variables.
  1459. * @param {object} traceMap The trace map.
  1460. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1461. */
  1462. *iterateGlobalReferences(traceMap) {
  1463. for (const key of Object.keys(traceMap)) {
  1464. const nextTraceMap = traceMap[key];
  1465. const path = [key];
  1466. const variable = this.globalScope.set.get(key);
  1467. if (isModifiedGlobal(variable)) {
  1468. continue
  1469. }
  1470. yield* this._iterateVariableReferences(
  1471. variable,
  1472. path,
  1473. nextTraceMap,
  1474. true,
  1475. );
  1476. }
  1477. for (const key of this.globalObjectNames) {
  1478. const path = [];
  1479. const variable = this.globalScope.set.get(key);
  1480. if (isModifiedGlobal(variable)) {
  1481. continue
  1482. }
  1483. yield* this._iterateVariableReferences(
  1484. variable,
  1485. path,
  1486. traceMap,
  1487. false,
  1488. );
  1489. }
  1490. }
  1491. /**
  1492. * Iterate the references of CommonJS modules.
  1493. * @param {object} traceMap The trace map.
  1494. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1495. */
  1496. *iterateCjsReferences(traceMap) {
  1497. for (const { node } of this.iterateGlobalReferences(requireCall)) {
  1498. const key = getStringIfConstant(node.arguments[0]);
  1499. if (key == null || !has(traceMap, key)) {
  1500. continue
  1501. }
  1502. const nextTraceMap = traceMap[key];
  1503. const path = [key];
  1504. if (nextTraceMap[READ]) {
  1505. yield {
  1506. node,
  1507. path,
  1508. type: READ,
  1509. info: nextTraceMap[READ],
  1510. };
  1511. }
  1512. yield* this._iteratePropertyReferences(node, path, nextTraceMap);
  1513. }
  1514. }
  1515. /**
  1516. * Iterate the references of ES modules.
  1517. * @param {object} traceMap The trace map.
  1518. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1519. */
  1520. *iterateEsmReferences(traceMap) {
  1521. const programNode = this.globalScope.block;
  1522. for (const node of programNode.body) {
  1523. if (!IMPORT_TYPE.test(node.type) || node.source == null) {
  1524. continue
  1525. }
  1526. const moduleId = node.source.value;
  1527. if (!has(traceMap, moduleId)) {
  1528. continue
  1529. }
  1530. const nextTraceMap = traceMap[moduleId];
  1531. const path = [moduleId];
  1532. if (nextTraceMap[READ]) {
  1533. yield { node, path, type: READ, info: nextTraceMap[READ] };
  1534. }
  1535. if (node.type === "ExportAllDeclaration") {
  1536. for (const key of Object.keys(nextTraceMap)) {
  1537. const exportTraceMap = nextTraceMap[key];
  1538. if (exportTraceMap[READ]) {
  1539. yield {
  1540. node,
  1541. path: path.concat(key),
  1542. type: READ,
  1543. info: exportTraceMap[READ],
  1544. };
  1545. }
  1546. }
  1547. } else {
  1548. for (const specifier of node.specifiers) {
  1549. const esm = has(nextTraceMap, ESM);
  1550. const it = this._iterateImportReferences(
  1551. specifier,
  1552. path,
  1553. esm
  1554. ? nextTraceMap
  1555. : this.mode === "legacy"
  1556. ? { default: nextTraceMap, ...nextTraceMap }
  1557. : { default: nextTraceMap },
  1558. );
  1559. if (esm) {
  1560. yield* it;
  1561. } else {
  1562. for (const report of it) {
  1563. report.path = report.path.filter(exceptDefault);
  1564. if (
  1565. report.path.length >= 2 ||
  1566. report.type !== READ
  1567. ) {
  1568. yield report;
  1569. }
  1570. }
  1571. }
  1572. }
  1573. }
  1574. }
  1575. }
  1576. /**
  1577. * Iterate the references for a given variable.
  1578. * @param {Variable} variable The variable to iterate that references.
  1579. * @param {string[]} path The current path.
  1580. * @param {object} traceMap The trace map.
  1581. * @param {boolean} shouldReport = The flag to report those references.
  1582. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1583. */
  1584. *_iterateVariableReferences(variable, path, traceMap, shouldReport) {
  1585. if (this.variableStack.includes(variable)) {
  1586. return
  1587. }
  1588. this.variableStack.push(variable);
  1589. try {
  1590. for (const reference of variable.references) {
  1591. if (!reference.isRead()) {
  1592. continue
  1593. }
  1594. const node = reference.identifier;
  1595. if (shouldReport && traceMap[READ]) {
  1596. yield { node, path, type: READ, info: traceMap[READ] };
  1597. }
  1598. yield* this._iteratePropertyReferences(node, path, traceMap);
  1599. }
  1600. } finally {
  1601. this.variableStack.pop();
  1602. }
  1603. }
  1604. /**
  1605. * Iterate the references for a given AST node.
  1606. * @param rootNode The AST node to iterate references.
  1607. * @param {string[]} path The current path.
  1608. * @param {object} traceMap The trace map.
  1609. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1610. */
  1611. //eslint-disable-next-line complexity
  1612. *_iteratePropertyReferences(rootNode, path, traceMap) {
  1613. let node = rootNode;
  1614. while (isPassThrough(node)) {
  1615. node = node.parent;
  1616. }
  1617. const parent = node.parent;
  1618. if (parent.type === "MemberExpression") {
  1619. if (parent.object === node) {
  1620. const key = getPropertyName(parent);
  1621. if (key == null || !has(traceMap, key)) {
  1622. return
  1623. }
  1624. path = path.concat(key); //eslint-disable-line no-param-reassign
  1625. const nextTraceMap = traceMap[key];
  1626. if (nextTraceMap[READ]) {
  1627. yield {
  1628. node: parent,
  1629. path,
  1630. type: READ,
  1631. info: nextTraceMap[READ],
  1632. };
  1633. }
  1634. yield* this._iteratePropertyReferences(
  1635. parent,
  1636. path,
  1637. nextTraceMap,
  1638. );
  1639. }
  1640. return
  1641. }
  1642. if (parent.type === "CallExpression") {
  1643. if (parent.callee === node && traceMap[CALL]) {
  1644. yield { node: parent, path, type: CALL, info: traceMap[CALL] };
  1645. }
  1646. return
  1647. }
  1648. if (parent.type === "NewExpression") {
  1649. if (parent.callee === node && traceMap[CONSTRUCT]) {
  1650. yield {
  1651. node: parent,
  1652. path,
  1653. type: CONSTRUCT,
  1654. info: traceMap[CONSTRUCT],
  1655. };
  1656. }
  1657. return
  1658. }
  1659. if (parent.type === "AssignmentExpression") {
  1660. if (parent.right === node) {
  1661. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1662. yield* this._iteratePropertyReferences(parent, path, traceMap);
  1663. }
  1664. return
  1665. }
  1666. if (parent.type === "AssignmentPattern") {
  1667. if (parent.right === node) {
  1668. yield* this._iterateLhsReferences(parent.left, path, traceMap);
  1669. }
  1670. return
  1671. }
  1672. if (parent.type === "VariableDeclarator") {
  1673. if (parent.init === node) {
  1674. yield* this._iterateLhsReferences(parent.id, path, traceMap);
  1675. }
  1676. }
  1677. }
  1678. /**
  1679. * Iterate the references for a given Pattern node.
  1680. * @param {Node} patternNode The Pattern node to iterate references.
  1681. * @param {string[]} path The current path.
  1682. * @param {object} traceMap The trace map.
  1683. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1684. */
  1685. *_iterateLhsReferences(patternNode, path, traceMap) {
  1686. if (patternNode.type === "Identifier") {
  1687. const variable = findVariable(this.globalScope, patternNode);
  1688. if (variable != null) {
  1689. yield* this._iterateVariableReferences(
  1690. variable,
  1691. path,
  1692. traceMap,
  1693. false,
  1694. );
  1695. }
  1696. return
  1697. }
  1698. if (patternNode.type === "ObjectPattern") {
  1699. for (const property of patternNode.properties) {
  1700. const key = getPropertyName(property);
  1701. if (key == null || !has(traceMap, key)) {
  1702. continue
  1703. }
  1704. const nextPath = path.concat(key);
  1705. const nextTraceMap = traceMap[key];
  1706. if (nextTraceMap[READ]) {
  1707. yield {
  1708. node: property,
  1709. path: nextPath,
  1710. type: READ,
  1711. info: nextTraceMap[READ],
  1712. };
  1713. }
  1714. yield* this._iterateLhsReferences(
  1715. property.value,
  1716. nextPath,
  1717. nextTraceMap,
  1718. );
  1719. }
  1720. return
  1721. }
  1722. if (patternNode.type === "AssignmentPattern") {
  1723. yield* this._iterateLhsReferences(patternNode.left, path, traceMap);
  1724. }
  1725. }
  1726. /**
  1727. * Iterate the references for a given ModuleSpecifier node.
  1728. * @param {Node} specifierNode The ModuleSpecifier node to iterate references.
  1729. * @param {string[]} path The current path.
  1730. * @param {object} traceMap The trace map.
  1731. * @returns {IterableIterator<{node:Node,path:string[],type:symbol,info:any}>} The iterator to iterate references.
  1732. */
  1733. *_iterateImportReferences(specifierNode, path, traceMap) {
  1734. const type = specifierNode.type;
  1735. if (type === "ImportSpecifier" || type === "ImportDefaultSpecifier") {
  1736. const key =
  1737. type === "ImportDefaultSpecifier"
  1738. ? "default"
  1739. : specifierNode.imported.name;
  1740. if (!has(traceMap, key)) {
  1741. return
  1742. }
  1743. path = path.concat(key); //eslint-disable-line no-param-reassign
  1744. const nextTraceMap = traceMap[key];
  1745. if (nextTraceMap[READ]) {
  1746. yield {
  1747. node: specifierNode,
  1748. path,
  1749. type: READ,
  1750. info: nextTraceMap[READ],
  1751. };
  1752. }
  1753. yield* this._iterateVariableReferences(
  1754. findVariable(this.globalScope, specifierNode.local),
  1755. path,
  1756. nextTraceMap,
  1757. false,
  1758. );
  1759. return
  1760. }
  1761. if (type === "ImportNamespaceSpecifier") {
  1762. yield* this._iterateVariableReferences(
  1763. findVariable(this.globalScope, specifierNode.local),
  1764. path,
  1765. traceMap,
  1766. false,
  1767. );
  1768. return
  1769. }
  1770. if (type === "ExportSpecifier") {
  1771. const key = specifierNode.local.name;
  1772. if (!has(traceMap, key)) {
  1773. return
  1774. }
  1775. path = path.concat(key); //eslint-disable-line no-param-reassign
  1776. const nextTraceMap = traceMap[key];
  1777. if (nextTraceMap[READ]) {
  1778. yield {
  1779. node: specifierNode,
  1780. path,
  1781. type: READ,
  1782. info: nextTraceMap[READ],
  1783. };
  1784. }
  1785. }
  1786. }
  1787. }
  1788. ReferenceTracker.READ = READ;
  1789. ReferenceTracker.CALL = CALL;
  1790. ReferenceTracker.CONSTRUCT = CONSTRUCT;
  1791. ReferenceTracker.ESM = ESM;
  1792. /**
  1793. * This is a predicate function for Array#filter.
  1794. * @param {string} name A name part.
  1795. * @param {number} index The index of the name.
  1796. * @returns {boolean} `false` if it's default.
  1797. */
  1798. function exceptDefault(name, index) {
  1799. return !(index === 1 && name === "default")
  1800. }
  1801. var index = {
  1802. CALL,
  1803. CONSTRUCT,
  1804. ESM,
  1805. findVariable,
  1806. getFunctionHeadLocation,
  1807. getFunctionNameWithKind,
  1808. getInnermostScope,
  1809. getPropertyName,
  1810. getStaticValue,
  1811. getStringIfConstant,
  1812. hasSideEffect,
  1813. isArrowToken,
  1814. isClosingBraceToken,
  1815. isClosingBracketToken,
  1816. isClosingParenToken,
  1817. isColonToken,
  1818. isCommaToken,
  1819. isCommentToken,
  1820. isNotArrowToken,
  1821. isNotClosingBraceToken,
  1822. isNotClosingBracketToken,
  1823. isNotClosingParenToken,
  1824. isNotColonToken,
  1825. isNotCommaToken,
  1826. isNotCommentToken,
  1827. isNotOpeningBraceToken,
  1828. isNotOpeningBracketToken,
  1829. isNotOpeningParenToken,
  1830. isNotSemicolonToken,
  1831. isOpeningBraceToken,
  1832. isOpeningBracketToken,
  1833. isOpeningParenToken,
  1834. isParenthesized,
  1835. isSemicolonToken,
  1836. PatternMatcher,
  1837. READ,
  1838. ReferenceTracker,
  1839. };
  1840. exports.CALL = CALL;
  1841. exports.CONSTRUCT = CONSTRUCT;
  1842. exports.ESM = ESM;
  1843. exports.PatternMatcher = PatternMatcher;
  1844. exports.READ = READ;
  1845. exports.ReferenceTracker = ReferenceTracker;
  1846. exports["default"] = index;
  1847. exports.findVariable = findVariable;
  1848. exports.getFunctionHeadLocation = getFunctionHeadLocation;
  1849. exports.getFunctionNameWithKind = getFunctionNameWithKind;
  1850. exports.getInnermostScope = getInnermostScope;
  1851. exports.getPropertyName = getPropertyName;
  1852. exports.getStaticValue = getStaticValue;
  1853. exports.getStringIfConstant = getStringIfConstant;
  1854. exports.hasSideEffect = hasSideEffect;
  1855. exports.isArrowToken = isArrowToken;
  1856. exports.isClosingBraceToken = isClosingBraceToken;
  1857. exports.isClosingBracketToken = isClosingBracketToken;
  1858. exports.isClosingParenToken = isClosingParenToken;
  1859. exports.isColonToken = isColonToken;
  1860. exports.isCommaToken = isCommaToken;
  1861. exports.isCommentToken = isCommentToken;
  1862. exports.isNotArrowToken = isNotArrowToken;
  1863. exports.isNotClosingBraceToken = isNotClosingBraceToken;
  1864. exports.isNotClosingBracketToken = isNotClosingBracketToken;
  1865. exports.isNotClosingParenToken = isNotClosingParenToken;
  1866. exports.isNotColonToken = isNotColonToken;
  1867. exports.isNotCommaToken = isNotCommaToken;
  1868. exports.isNotCommentToken = isNotCommentToken;
  1869. exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
  1870. exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
  1871. exports.isNotOpeningParenToken = isNotOpeningParenToken;
  1872. exports.isNotSemicolonToken = isNotSemicolonToken;
  1873. exports.isOpeningBraceToken = isOpeningBraceToken;
  1874. exports.isOpeningBracketToken = isOpeningBracketToken;
  1875. exports.isOpeningParenToken = isOpeningParenToken;
  1876. exports.isParenthesized = isParenthesized;
  1877. exports.isSemicolonToken = isSemicolonToken;
  1878. //# sourceMappingURL=index.js.map