index.js 61 KB

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