index.mjs 60 KB

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