index.mjs 63 KB

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