index.mjs 55 KB

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