index.js 61 KB

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