ast-utils.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124
  1. /**
  2. * @fileoverview Common utils for AST.
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const esutils = require("esutils");
  10. const espree = require("espree");
  11. const escapeRegExp = require("escape-string-regexp");
  12. const {
  13. breakableTypePattern,
  14. createGlobalLinebreakMatcher,
  15. lineBreakPattern,
  16. shebangPattern
  17. } = require("../../shared/ast-utils");
  18. //------------------------------------------------------------------------------
  19. // Helpers
  20. //------------------------------------------------------------------------------
  21. const anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
  22. const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
  23. const arrayOrTypedArrayPattern = /Array$/u;
  24. const arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/u;
  25. const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
  26. const thisTagPattern = /^[\s*]*@this/mu;
  27. const COMMENTS_IGNORE_PATTERN = /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
  28. const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u;
  29. const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
  30. // A set of node types that can contain a list of statements
  31. const STATEMENT_LIST_PARENTS = new Set(["Program", "BlockStatement", "StaticBlock", "SwitchCase"]);
  32. const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u;
  33. // Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string
  34. const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN = /^(?:[^\\]|\\.)*\\(?:[1-9]|0[0-9])/su;
  35. const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]);
  36. /**
  37. * Checks reference if is non initializer and writable.
  38. * @param {Reference} reference A reference to check.
  39. * @param {int} index The index of the reference in the references.
  40. * @param {Reference[]} references The array that the reference belongs to.
  41. * @returns {boolean} Success/Failure
  42. * @private
  43. */
  44. function isModifyingReference(reference, index, references) {
  45. const identifier = reference.identifier;
  46. /*
  47. * Destructuring assignments can have multiple default value, so
  48. * possibly there are multiple writeable references for the same
  49. * identifier.
  50. */
  51. const modifyingDifferentIdentifier = index === 0 ||
  52. references[index - 1].identifier !== identifier;
  53. return (identifier &&
  54. reference.init === false &&
  55. reference.isWrite() &&
  56. modifyingDifferentIdentifier
  57. );
  58. }
  59. /**
  60. * Checks whether the given string starts with uppercase or not.
  61. * @param {string} s The string to check.
  62. * @returns {boolean} `true` if the string starts with uppercase.
  63. */
  64. function startsWithUpperCase(s) {
  65. return s[0] !== s[0].toLocaleLowerCase();
  66. }
  67. /**
  68. * Checks whether or not a node is a constructor.
  69. * @param {ASTNode} node A function node to check.
  70. * @returns {boolean} Whether or not a node is a constructor.
  71. */
  72. function isES5Constructor(node) {
  73. return (node.id && startsWithUpperCase(node.id.name));
  74. }
  75. /**
  76. * Finds a function node from ancestors of a node.
  77. * @param {ASTNode} node A start node to find.
  78. * @returns {Node|null} A found function node.
  79. */
  80. function getUpperFunction(node) {
  81. for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
  82. if (anyFunctionPattern.test(currentNode.type)) {
  83. return currentNode;
  84. }
  85. }
  86. return null;
  87. }
  88. /**
  89. * Checks whether a given node is a function node or not.
  90. * The following types are function nodes:
  91. *
  92. * - ArrowFunctionExpression
  93. * - FunctionDeclaration
  94. * - FunctionExpression
  95. * @param {ASTNode|null} node A node to check.
  96. * @returns {boolean} `true` if the node is a function node.
  97. */
  98. function isFunction(node) {
  99. return Boolean(node && anyFunctionPattern.test(node.type));
  100. }
  101. /**
  102. * Checks whether a given node is a loop node or not.
  103. * The following types are loop nodes:
  104. *
  105. * - DoWhileStatement
  106. * - ForInStatement
  107. * - ForOfStatement
  108. * - ForStatement
  109. * - WhileStatement
  110. * @param {ASTNode|null} node A node to check.
  111. * @returns {boolean} `true` if the node is a loop node.
  112. */
  113. function isLoop(node) {
  114. return Boolean(node && anyLoopPattern.test(node.type));
  115. }
  116. /**
  117. * Checks whether the given node is in a loop or not.
  118. * @param {ASTNode} node The node to check.
  119. * @returns {boolean} `true` if the node is in a loop.
  120. */
  121. function isInLoop(node) {
  122. for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) {
  123. if (isLoop(currentNode)) {
  124. return true;
  125. }
  126. }
  127. return false;
  128. }
  129. /**
  130. * Determines whether the given node is a `null` literal.
  131. * @param {ASTNode} node The node to check
  132. * @returns {boolean} `true` if the node is a `null` literal
  133. */
  134. function isNullLiteral(node) {
  135. /*
  136. * Checking `node.value === null` does not guarantee that a literal is a null literal.
  137. * When parsing values that cannot be represented in the current environment (e.g. unicode
  138. * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
  139. * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
  140. * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
  141. */
  142. return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
  143. }
  144. /**
  145. * Checks whether or not a node is `null` or `undefined`.
  146. * @param {ASTNode} node A node to check.
  147. * @returns {boolean} Whether or not the node is a `null` or `undefined`.
  148. * @public
  149. */
  150. function isNullOrUndefined(node) {
  151. return (
  152. isNullLiteral(node) ||
  153. (node.type === "Identifier" && node.name === "undefined") ||
  154. (node.type === "UnaryExpression" && node.operator === "void")
  155. );
  156. }
  157. /**
  158. * Checks whether or not a node is callee.
  159. * @param {ASTNode} node A node to check.
  160. * @returns {boolean} Whether or not the node is callee.
  161. */
  162. function isCallee(node) {
  163. return node.parent.type === "CallExpression" && node.parent.callee === node;
  164. }
  165. /**
  166. * Returns the result of the string conversion applied to the evaluated value of the given expression node,
  167. * if it can be determined statically.
  168. *
  169. * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
  170. * In all other cases, this function returns `null`.
  171. * @param {ASTNode} node Expression node.
  172. * @returns {string|null} String value if it can be determined. Otherwise, `null`.
  173. */
  174. function getStaticStringValue(node) {
  175. switch (node.type) {
  176. case "Literal":
  177. if (node.value === null) {
  178. if (isNullLiteral(node)) {
  179. return String(node.value); // "null"
  180. }
  181. if (node.regex) {
  182. return `/${node.regex.pattern}/${node.regex.flags}`;
  183. }
  184. if (node.bigint) {
  185. return node.bigint;
  186. }
  187. // Otherwise, this is an unknown literal. The function will return null.
  188. } else {
  189. return String(node.value);
  190. }
  191. break;
  192. case "TemplateLiteral":
  193. if (node.expressions.length === 0 && node.quasis.length === 1) {
  194. return node.quasis[0].value.cooked;
  195. }
  196. break;
  197. // no default
  198. }
  199. return null;
  200. }
  201. /**
  202. * Gets the property name of a given node.
  203. * The node can be a MemberExpression, a Property, or a MethodDefinition.
  204. *
  205. * If the name is dynamic, this returns `null`.
  206. *
  207. * For examples:
  208. *
  209. * a.b // => "b"
  210. * a["b"] // => "b"
  211. * a['b'] // => "b"
  212. * a[`b`] // => "b"
  213. * a[100] // => "100"
  214. * a[b] // => null
  215. * a["a" + "b"] // => null
  216. * a[tag`b`] // => null
  217. * a[`${b}`] // => null
  218. *
  219. * let a = {b: 1} // => "b"
  220. * let a = {["b"]: 1} // => "b"
  221. * let a = {['b']: 1} // => "b"
  222. * let a = {[`b`]: 1} // => "b"
  223. * let a = {[100]: 1} // => "100"
  224. * let a = {[b]: 1} // => null
  225. * let a = {["a" + "b"]: 1} // => null
  226. * let a = {[tag`b`]: 1} // => null
  227. * let a = {[`${b}`]: 1} // => null
  228. * @param {ASTNode} node The node to get.
  229. * @returns {string|null} The property name if static. Otherwise, null.
  230. */
  231. function getStaticPropertyName(node) {
  232. let prop;
  233. switch (node && node.type) {
  234. case "ChainExpression":
  235. return getStaticPropertyName(node.expression);
  236. case "Property":
  237. case "PropertyDefinition":
  238. case "MethodDefinition":
  239. prop = node.key;
  240. break;
  241. case "MemberExpression":
  242. prop = node.property;
  243. break;
  244. // no default
  245. }
  246. if (prop) {
  247. if (prop.type === "Identifier" && !node.computed) {
  248. return prop.name;
  249. }
  250. return getStaticStringValue(prop);
  251. }
  252. return null;
  253. }
  254. /**
  255. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  256. * @param {ASTNode} node The node to address.
  257. * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
  258. */
  259. function skipChainExpression(node) {
  260. return node && node.type === "ChainExpression" ? node.expression : node;
  261. }
  262. /**
  263. * Check if the `actual` is an expected value.
  264. * @param {string} actual The string value to check.
  265. * @param {string | RegExp} expected The expected string value or pattern.
  266. * @returns {boolean} `true` if the `actual` is an expected value.
  267. */
  268. function checkText(actual, expected) {
  269. return typeof expected === "string"
  270. ? actual === expected
  271. : expected.test(actual);
  272. }
  273. /**
  274. * Check if a given node is an Identifier node with a given name.
  275. * @param {ASTNode} node The node to check.
  276. * @param {string | RegExp} name The expected name or the expected pattern of the object name.
  277. * @returns {boolean} `true` if the node is an Identifier node with the name.
  278. */
  279. function isSpecificId(node, name) {
  280. return node.type === "Identifier" && checkText(node.name, name);
  281. }
  282. /**
  283. * Check if a given node is member access with a given object name and property name pair.
  284. * This is regardless of optional or not.
  285. * @param {ASTNode} node The node to check.
  286. * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object.
  287. * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property.
  288. * @returns {boolean} `true` if the node is member access with the object name and property name pair.
  289. * The node is a `MemberExpression` or `ChainExpression`.
  290. */
  291. function isSpecificMemberAccess(node, objectName, propertyName) {
  292. const checkNode = skipChainExpression(node);
  293. if (checkNode.type !== "MemberExpression") {
  294. return false;
  295. }
  296. if (objectName && !isSpecificId(checkNode.object, objectName)) {
  297. return false;
  298. }
  299. if (propertyName) {
  300. const actualPropertyName = getStaticPropertyName(checkNode);
  301. if (typeof actualPropertyName !== "string" || !checkText(actualPropertyName, propertyName)) {
  302. return false;
  303. }
  304. }
  305. return true;
  306. }
  307. /**
  308. * Check if two literal nodes are the same value.
  309. * @param {ASTNode} left The Literal node to compare.
  310. * @param {ASTNode} right The other Literal node to compare.
  311. * @returns {boolean} `true` if the two literal nodes are the same value.
  312. */
  313. function equalLiteralValue(left, right) {
  314. // RegExp literal.
  315. if (left.regex || right.regex) {
  316. return Boolean(
  317. left.regex &&
  318. right.regex &&
  319. left.regex.pattern === right.regex.pattern &&
  320. left.regex.flags === right.regex.flags
  321. );
  322. }
  323. // BigInt literal.
  324. if (left.bigint || right.bigint) {
  325. return left.bigint === right.bigint;
  326. }
  327. return left.value === right.value;
  328. }
  329. /**
  330. * Check if two expressions reference the same value. For example:
  331. * a = a
  332. * a.b = a.b
  333. * a[0] = a[0]
  334. * a['b'] = a['b']
  335. * @param {ASTNode} left The left side of the comparison.
  336. * @param {ASTNode} right The right side of the comparison.
  337. * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility.
  338. * @returns {boolean} `true` if both sides match and reference the same value.
  339. */
  340. function isSameReference(left, right, disableStaticComputedKey = false) {
  341. if (left.type !== right.type) {
  342. // Handle `a.b` and `a?.b` are samely.
  343. if (left.type === "ChainExpression") {
  344. return isSameReference(left.expression, right, disableStaticComputedKey);
  345. }
  346. if (right.type === "ChainExpression") {
  347. return isSameReference(left, right.expression, disableStaticComputedKey);
  348. }
  349. return false;
  350. }
  351. switch (left.type) {
  352. case "Super":
  353. case "ThisExpression":
  354. return true;
  355. case "Identifier":
  356. case "PrivateIdentifier":
  357. return left.name === right.name;
  358. case "Literal":
  359. return equalLiteralValue(left, right);
  360. case "ChainExpression":
  361. return isSameReference(left.expression, right.expression, disableStaticComputedKey);
  362. case "MemberExpression": {
  363. if (!disableStaticComputedKey) {
  364. const nameA = getStaticPropertyName(left);
  365. // x.y = x["y"]
  366. if (nameA !== null) {
  367. return (
  368. isSameReference(left.object, right.object, disableStaticComputedKey) &&
  369. nameA === getStaticPropertyName(right)
  370. );
  371. }
  372. }
  373. /*
  374. * x[0] = x[0]
  375. * x[y] = x[y]
  376. * x.y = x.y
  377. */
  378. return (
  379. left.computed === right.computed &&
  380. isSameReference(left.object, right.object, disableStaticComputedKey) &&
  381. isSameReference(left.property, right.property, disableStaticComputedKey)
  382. );
  383. }
  384. default:
  385. return false;
  386. }
  387. }
  388. /**
  389. * Checks whether or not a node is `Reflect.apply`.
  390. * @param {ASTNode} node A node to check.
  391. * @returns {boolean} Whether or not the node is a `Reflect.apply`.
  392. */
  393. function isReflectApply(node) {
  394. return isSpecificMemberAccess(node, "Reflect", "apply");
  395. }
  396. /**
  397. * Checks whether or not a node is `Array.from`.
  398. * @param {ASTNode} node A node to check.
  399. * @returns {boolean} Whether or not the node is a `Array.from`.
  400. */
  401. function isArrayFromMethod(node) {
  402. return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from");
  403. }
  404. /**
  405. * Checks whether or not a node is a method which has `thisArg`.
  406. * @param {ASTNode} node A node to check.
  407. * @returns {boolean} Whether or not the node is a method which has `thisArg`.
  408. */
  409. function isMethodWhichHasThisArg(node) {
  410. return isSpecificMemberAccess(node, null, arrayMethodPattern);
  411. }
  412. /**
  413. * Creates the negate function of the given function.
  414. * @param {Function} f The function to negate.
  415. * @returns {Function} Negated function.
  416. */
  417. function negate(f) {
  418. return token => !f(token);
  419. }
  420. /**
  421. * Checks whether or not a node has a `@this` tag in its comments.
  422. * @param {ASTNode} node A node to check.
  423. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  424. * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
  425. */
  426. function hasJSDocThisTag(node, sourceCode) {
  427. const jsdocComment = sourceCode.getJSDocComment(node);
  428. if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
  429. return true;
  430. }
  431. // Checks `@this` in its leading comments for callbacks,
  432. // because callbacks don't have its JSDoc comment.
  433. // e.g.
  434. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
  435. return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value));
  436. }
  437. /**
  438. * Determines if a node is surrounded by parentheses.
  439. * @param {SourceCode} sourceCode The ESLint source code object
  440. * @param {ASTNode} node The node to be checked.
  441. * @returns {boolean} True if the node is parenthesised.
  442. * @private
  443. */
  444. function isParenthesised(sourceCode, node) {
  445. const previousToken = sourceCode.getTokenBefore(node),
  446. nextToken = sourceCode.getTokenAfter(node);
  447. return Boolean(previousToken && nextToken) &&
  448. previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
  449. nextToken.value === ")" && nextToken.range[0] >= node.range[1];
  450. }
  451. /**
  452. * Checks if the given token is a `=` token or not.
  453. * @param {Token} token The token to check.
  454. * @returns {boolean} `true` if the token is a `=` token.
  455. */
  456. function isEqToken(token) {
  457. return token.value === "=" && token.type === "Punctuator";
  458. }
  459. /**
  460. * Checks if the given token is an arrow token or not.
  461. * @param {Token} token The token to check.
  462. * @returns {boolean} `true` if the token is an arrow token.
  463. */
  464. function isArrowToken(token) {
  465. return token.value === "=>" && token.type === "Punctuator";
  466. }
  467. /**
  468. * Checks if the given token is a comma token or not.
  469. * @param {Token} token The token to check.
  470. * @returns {boolean} `true` if the token is a comma token.
  471. */
  472. function isCommaToken(token) {
  473. return token.value === "," && token.type === "Punctuator";
  474. }
  475. /**
  476. * Checks if the given token is a dot token or not.
  477. * @param {Token} token The token to check.
  478. * @returns {boolean} `true` if the token is a dot token.
  479. */
  480. function isDotToken(token) {
  481. return token.value === "." && token.type === "Punctuator";
  482. }
  483. /**
  484. * Checks if the given token is a `?.` token or not.
  485. * @param {Token} token The token to check.
  486. * @returns {boolean} `true` if the token is a `?.` token.
  487. */
  488. function isQuestionDotToken(token) {
  489. return token.value === "?." && token.type === "Punctuator";
  490. }
  491. /**
  492. * Checks if the given token is a semicolon token or not.
  493. * @param {Token} token The token to check.
  494. * @returns {boolean} `true` if the token is a semicolon token.
  495. */
  496. function isSemicolonToken(token) {
  497. return token.value === ";" && token.type === "Punctuator";
  498. }
  499. /**
  500. * Checks if the given token is a colon token or not.
  501. * @param {Token} token The token to check.
  502. * @returns {boolean} `true` if the token is a colon token.
  503. */
  504. function isColonToken(token) {
  505. return token.value === ":" && token.type === "Punctuator";
  506. }
  507. /**
  508. * Checks if the given token is an opening parenthesis token or not.
  509. * @param {Token} token The token to check.
  510. * @returns {boolean} `true` if the token is an opening parenthesis token.
  511. */
  512. function isOpeningParenToken(token) {
  513. return token.value === "(" && token.type === "Punctuator";
  514. }
  515. /**
  516. * Checks if the given token is a closing parenthesis token or not.
  517. * @param {Token} token The token to check.
  518. * @returns {boolean} `true` if the token is a closing parenthesis token.
  519. */
  520. function isClosingParenToken(token) {
  521. return token.value === ")" && token.type === "Punctuator";
  522. }
  523. /**
  524. * Checks if the given token is an opening square bracket token or not.
  525. * @param {Token} token The token to check.
  526. * @returns {boolean} `true` if the token is an opening square bracket token.
  527. */
  528. function isOpeningBracketToken(token) {
  529. return token.value === "[" && token.type === "Punctuator";
  530. }
  531. /**
  532. * Checks if the given token is a closing square bracket token or not.
  533. * @param {Token} token The token to check.
  534. * @returns {boolean} `true` if the token is a closing square bracket token.
  535. */
  536. function isClosingBracketToken(token) {
  537. return token.value === "]" && token.type === "Punctuator";
  538. }
  539. /**
  540. * Checks if the given token is an opening brace token or not.
  541. * @param {Token} token The token to check.
  542. * @returns {boolean} `true` if the token is an opening brace token.
  543. */
  544. function isOpeningBraceToken(token) {
  545. return token.value === "{" && token.type === "Punctuator";
  546. }
  547. /**
  548. * Checks if the given token is a closing brace token or not.
  549. * @param {Token} token The token to check.
  550. * @returns {boolean} `true` if the token is a closing brace token.
  551. */
  552. function isClosingBraceToken(token) {
  553. return token.value === "}" && token.type === "Punctuator";
  554. }
  555. /**
  556. * Checks if the given token is a comment token or not.
  557. * @param {Token} token The token to check.
  558. * @returns {boolean} `true` if the token is a comment token.
  559. */
  560. function isCommentToken(token) {
  561. return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
  562. }
  563. /**
  564. * Checks if the given token is a keyword token or not.
  565. * @param {Token} token The token to check.
  566. * @returns {boolean} `true` if the token is a keyword token.
  567. */
  568. function isKeywordToken(token) {
  569. return token.type === "Keyword";
  570. }
  571. /**
  572. * Gets the `(` token of the given function node.
  573. * @param {ASTNode} node The function node to get.
  574. * @param {SourceCode} sourceCode The source code object to get tokens.
  575. * @returns {Token} `(` token.
  576. */
  577. function getOpeningParenOfParams(node, sourceCode) {
  578. // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param.
  579. if (node.type === "ArrowFunctionExpression" && node.params.length === 1) {
  580. const argToken = sourceCode.getFirstToken(node.params[0]);
  581. const maybeParenToken = sourceCode.getTokenBefore(argToken);
  582. return isOpeningParenToken(maybeParenToken) ? maybeParenToken : argToken;
  583. }
  584. // Otherwise, returns paren.
  585. return node.id
  586. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  587. : sourceCode.getFirstToken(node, isOpeningParenToken);
  588. }
  589. /**
  590. * Checks whether or not the tokens of two given nodes are same.
  591. * @param {ASTNode} left A node 1 to compare.
  592. * @param {ASTNode} right A node 2 to compare.
  593. * @param {SourceCode} sourceCode The ESLint source code object.
  594. * @returns {boolean} the source code for the given node.
  595. */
  596. function equalTokens(left, right, sourceCode) {
  597. const tokensL = sourceCode.getTokens(left);
  598. const tokensR = sourceCode.getTokens(right);
  599. if (tokensL.length !== tokensR.length) {
  600. return false;
  601. }
  602. for (let i = 0; i < tokensL.length; ++i) {
  603. if (tokensL[i].type !== tokensR[i].type ||
  604. tokensL[i].value !== tokensR[i].value
  605. ) {
  606. return false;
  607. }
  608. }
  609. return true;
  610. }
  611. /**
  612. * Check if the given node is a true logical expression or not.
  613. *
  614. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  615. * coalesce (`??`) are known as `ShortCircuitExpression`.
  616. * But ESTree represents those by `LogicalExpression` node.
  617. *
  618. * This function rejects coalesce expressions of `LogicalExpression` node.
  619. * @param {ASTNode} node The node to check.
  620. * @returns {boolean} `true` if the node is `&&` or `||`.
  621. * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression
  622. */
  623. function isLogicalExpression(node) {
  624. return (
  625. node.type === "LogicalExpression" &&
  626. (node.operator === "&&" || node.operator === "||")
  627. );
  628. }
  629. /**
  630. * Check if the given node is a nullish coalescing expression or not.
  631. *
  632. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  633. * coalesce (`??`) are known as `ShortCircuitExpression`.
  634. * But ESTree represents those by `LogicalExpression` node.
  635. *
  636. * This function finds only coalesce expressions of `LogicalExpression` node.
  637. * @param {ASTNode} node The node to check.
  638. * @returns {boolean} `true` if the node is `??`.
  639. */
  640. function isCoalesceExpression(node) {
  641. return node.type === "LogicalExpression" && node.operator === "??";
  642. }
  643. /**
  644. * Check if given two nodes are the pair of a logical expression and a coalesce expression.
  645. * @param {ASTNode} left A node to check.
  646. * @param {ASTNode} right Another node to check.
  647. * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression.
  648. */
  649. function isMixedLogicalAndCoalesceExpressions(left, right) {
  650. return (
  651. (isLogicalExpression(left) && isCoalesceExpression(right)) ||
  652. (isCoalesceExpression(left) && isLogicalExpression(right))
  653. );
  654. }
  655. /**
  656. * Checks if the given operator is a logical assignment operator.
  657. * @param {string} operator The operator to check.
  658. * @returns {boolean} `true` if the operator is a logical assignment operator.
  659. */
  660. function isLogicalAssignmentOperator(operator) {
  661. return LOGICAL_ASSIGNMENT_OPERATORS.has(operator);
  662. }
  663. /**
  664. * Get the colon token of the given SwitchCase node.
  665. * @param {ASTNode} node The SwitchCase node to get.
  666. * @param {SourceCode} sourceCode The source code object to get tokens.
  667. * @returns {Token} The colon token of the node.
  668. */
  669. function getSwitchCaseColonToken(node, sourceCode) {
  670. if (node.test) {
  671. return sourceCode.getTokenAfter(node.test, isColonToken);
  672. }
  673. return sourceCode.getFirstToken(node, 1);
  674. }
  675. /**
  676. * Gets ESM module export name represented by the given node.
  677. * @param {ASTNode} node `Identifier` or string `Literal` node in a position
  678. * that represents a module export name:
  679. * - `ImportSpecifier#imported`
  680. * - `ExportSpecifier#local` (if it is a re-export from another module)
  681. * - `ExportSpecifier#exported`
  682. * - `ExportAllDeclaration#exported`
  683. * @returns {string} The module export name.
  684. */
  685. function getModuleExportName(node) {
  686. if (node.type === "Identifier") {
  687. return node.name;
  688. }
  689. // string literal
  690. return node.value;
  691. }
  692. /**
  693. * Returns literal's value converted to the Boolean type
  694. * @param {ASTNode} node any `Literal` node
  695. * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy,
  696. * `null` when it cannot be determined.
  697. */
  698. function getBooleanValue(node) {
  699. if (node.value === null) {
  700. /*
  701. * it might be a null literal or bigint/regex literal in unsupported environments .
  702. * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral
  703. * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral
  704. */
  705. if (node.raw === "null") {
  706. return false;
  707. }
  708. // regex is always truthy
  709. if (typeof node.regex === "object") {
  710. return true;
  711. }
  712. return null;
  713. }
  714. return !!node.value;
  715. }
  716. /**
  717. * Checks if a branch node of LogicalExpression short circuits the whole condition
  718. * @param {ASTNode} node The branch of main condition which needs to be checked
  719. * @param {string} operator The operator of the main LogicalExpression.
  720. * @returns {boolean} true when condition short circuits whole condition
  721. */
  722. function isLogicalIdentity(node, operator) {
  723. switch (node.type) {
  724. case "Literal":
  725. return (operator === "||" && getBooleanValue(node) === true) ||
  726. (operator === "&&" && getBooleanValue(node) === false);
  727. case "UnaryExpression":
  728. return (operator === "&&" && node.operator === "void");
  729. case "LogicalExpression":
  730. /*
  731. * handles `a && false || b`
  732. * `false` is an identity element of `&&` but not `||`
  733. */
  734. return operator === node.operator &&
  735. (
  736. isLogicalIdentity(node.left, operator) ||
  737. isLogicalIdentity(node.right, operator)
  738. );
  739. case "AssignmentExpression":
  740. return ["||=", "&&="].includes(node.operator) &&
  741. operator === node.operator.slice(0, -1) &&
  742. isLogicalIdentity(node.right, operator);
  743. // no default
  744. }
  745. return false;
  746. }
  747. /**
  748. * Checks if an identifier is a reference to a global variable.
  749. * @param {Scope} scope The scope in which the identifier is referenced.
  750. * @param {ASTNode} node An identifier node to check.
  751. * @returns {boolean} `true` if the identifier is a reference to a global variable.
  752. */
  753. function isReferenceToGlobalVariable(scope, node) {
  754. const reference = scope.references.find(ref => ref.identifier === node);
  755. return Boolean(
  756. reference &&
  757. reference.resolved &&
  758. reference.resolved.scope.type === "global" &&
  759. reference.resolved.defs.length === 0
  760. );
  761. }
  762. /**
  763. * Checks if a node has a constant truthiness value.
  764. * @param {Scope} scope Scope in which the node appears.
  765. * @param {ASTNode} node The AST node to check.
  766. * @param {boolean} inBooleanPosition `true` if checking the test of a
  767. * condition. `false` in all other cases. When `false`, checks if -- for
  768. * both string and number -- if coerced to that type, the value will
  769. * be constant.
  770. * @returns {boolean} true when node's truthiness is constant
  771. * @private
  772. */
  773. function isConstant(scope, node, inBooleanPosition) {
  774. // node.elements can return null values in the case of sparse arrays ex. [,]
  775. if (!node) {
  776. return true;
  777. }
  778. switch (node.type) {
  779. case "Literal":
  780. case "ArrowFunctionExpression":
  781. case "FunctionExpression":
  782. return true;
  783. case "ClassExpression":
  784. case "ObjectExpression":
  785. /**
  786. * In theory objects like:
  787. *
  788. * `{toString: () => a}`
  789. * `{valueOf: () => a}`
  790. *
  791. * Or a classes like:
  792. *
  793. * `class { static toString() { return a } }`
  794. * `class { static valueOf() { return a } }`
  795. *
  796. * Are not constant verifiably when `inBooleanPosition` is
  797. * false, but it's an edge case we've opted not to handle.
  798. */
  799. return true;
  800. case "TemplateLiteral":
  801. return (inBooleanPosition && node.quasis.some(quasi => quasi.value.cooked.length)) ||
  802. node.expressions.every(exp => isConstant(scope, exp, false));
  803. case "ArrayExpression": {
  804. if (!inBooleanPosition) {
  805. return node.elements.every(element => isConstant(scope, element, false));
  806. }
  807. return true;
  808. }
  809. case "UnaryExpression":
  810. if (
  811. node.operator === "void" ||
  812. node.operator === "typeof" && inBooleanPosition
  813. ) {
  814. return true;
  815. }
  816. if (node.operator === "!") {
  817. return isConstant(scope, node.argument, true);
  818. }
  819. return isConstant(scope, node.argument, false);
  820. case "BinaryExpression":
  821. return isConstant(scope, node.left, false) &&
  822. isConstant(scope, node.right, false) &&
  823. node.operator !== "in";
  824. case "LogicalExpression": {
  825. const isLeftConstant = isConstant(scope, node.left, inBooleanPosition);
  826. const isRightConstant = isConstant(scope, node.right, inBooleanPosition);
  827. const isLeftShortCircuit = (isLeftConstant && isLogicalIdentity(node.left, node.operator));
  828. const isRightShortCircuit = (inBooleanPosition && isRightConstant && isLogicalIdentity(node.right, node.operator));
  829. return (isLeftConstant && isRightConstant) ||
  830. isLeftShortCircuit ||
  831. isRightShortCircuit;
  832. }
  833. case "NewExpression":
  834. return inBooleanPosition;
  835. case "AssignmentExpression":
  836. if (node.operator === "=") {
  837. return isConstant(scope, node.right, inBooleanPosition);
  838. }
  839. if (["||=", "&&="].includes(node.operator) && inBooleanPosition) {
  840. return isLogicalIdentity(node.right, node.operator.slice(0, -1));
  841. }
  842. return false;
  843. case "SequenceExpression":
  844. return isConstant(scope, node.expressions[node.expressions.length - 1], inBooleanPosition);
  845. case "SpreadElement":
  846. return isConstant(scope, node.argument, inBooleanPosition);
  847. case "CallExpression":
  848. if (node.callee.type === "Identifier" && node.callee.name === "Boolean") {
  849. if (node.arguments.length === 0 || isConstant(scope, node.arguments[0], true)) {
  850. return isReferenceToGlobalVariable(scope, node.callee);
  851. }
  852. }
  853. return false;
  854. case "Identifier":
  855. return node.name === "undefined" && isReferenceToGlobalVariable(scope, node);
  856. // no default
  857. }
  858. return false;
  859. }
  860. //------------------------------------------------------------------------------
  861. // Public Interface
  862. //------------------------------------------------------------------------------
  863. module.exports = {
  864. COMMENTS_IGNORE_PATTERN,
  865. LINEBREAKS,
  866. LINEBREAK_MATCHER: lineBreakPattern,
  867. SHEBANG_MATCHER: shebangPattern,
  868. STATEMENT_LIST_PARENTS,
  869. /**
  870. * Determines whether two adjacent tokens are on the same line.
  871. * @param {Object} left The left token object.
  872. * @param {Object} right The right token object.
  873. * @returns {boolean} Whether or not the tokens are on the same line.
  874. * @public
  875. */
  876. isTokenOnSameLine(left, right) {
  877. return left.loc.end.line === right.loc.start.line;
  878. },
  879. isNullOrUndefined,
  880. isCallee,
  881. isES5Constructor,
  882. getUpperFunction,
  883. isFunction,
  884. isLoop,
  885. isInLoop,
  886. isArrayFromMethod,
  887. isParenthesised,
  888. createGlobalLinebreakMatcher,
  889. equalTokens,
  890. isArrowToken,
  891. isClosingBraceToken,
  892. isClosingBracketToken,
  893. isClosingParenToken,
  894. isColonToken,
  895. isCommaToken,
  896. isCommentToken,
  897. isDotToken,
  898. isQuestionDotToken,
  899. isKeywordToken,
  900. isNotClosingBraceToken: negate(isClosingBraceToken),
  901. isNotClosingBracketToken: negate(isClosingBracketToken),
  902. isNotClosingParenToken: negate(isClosingParenToken),
  903. isNotColonToken: negate(isColonToken),
  904. isNotCommaToken: negate(isCommaToken),
  905. isNotDotToken: negate(isDotToken),
  906. isNotQuestionDotToken: negate(isQuestionDotToken),
  907. isNotOpeningBraceToken: negate(isOpeningBraceToken),
  908. isNotOpeningBracketToken: negate(isOpeningBracketToken),
  909. isNotOpeningParenToken: negate(isOpeningParenToken),
  910. isNotSemicolonToken: negate(isSemicolonToken),
  911. isOpeningBraceToken,
  912. isOpeningBracketToken,
  913. isOpeningParenToken,
  914. isSemicolonToken,
  915. isEqToken,
  916. /**
  917. * Checks whether or not a given node is a string literal.
  918. * @param {ASTNode} node A node to check.
  919. * @returns {boolean} `true` if the node is a string literal.
  920. */
  921. isStringLiteral(node) {
  922. return (
  923. (node.type === "Literal" && typeof node.value === "string") ||
  924. node.type === "TemplateLiteral"
  925. );
  926. },
  927. /**
  928. * Checks whether a given node is a breakable statement or not.
  929. * The node is breakable if the node is one of the following type:
  930. *
  931. * - DoWhileStatement
  932. * - ForInStatement
  933. * - ForOfStatement
  934. * - ForStatement
  935. * - SwitchStatement
  936. * - WhileStatement
  937. * @param {ASTNode} node A node to check.
  938. * @returns {boolean} `true` if the node is breakable.
  939. */
  940. isBreakableStatement(node) {
  941. return breakableTypePattern.test(node.type);
  942. },
  943. /**
  944. * Gets references which are non initializer and writable.
  945. * @param {Reference[]} references An array of references.
  946. * @returns {Reference[]} An array of only references which are non initializer and writable.
  947. * @public
  948. */
  949. getModifyingReferences(references) {
  950. return references.filter(isModifyingReference);
  951. },
  952. /**
  953. * Validate that a string passed in is surrounded by the specified character
  954. * @param {string} val The text to check.
  955. * @param {string} character The character to see if it's surrounded by.
  956. * @returns {boolean} True if the text is surrounded by the character, false if not.
  957. * @private
  958. */
  959. isSurroundedBy(val, character) {
  960. return val[0] === character && val[val.length - 1] === character;
  961. },
  962. /**
  963. * Returns whether the provided node is an ESLint directive comment or not
  964. * @param {Line|Block} node The comment token to be checked
  965. * @returns {boolean} `true` if the node is an ESLint directive comment
  966. */
  967. isDirectiveComment(node) {
  968. const comment = node.value.trim();
  969. return (
  970. node.type === "Line" && comment.startsWith("eslint-") ||
  971. node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment)
  972. );
  973. },
  974. /**
  975. * Gets the trailing statement of a given node.
  976. *
  977. * if (code)
  978. * consequent;
  979. *
  980. * When taking this `IfStatement`, returns `consequent;` statement.
  981. * @param {ASTNode} A node to get.
  982. * @returns {ASTNode|null} The trailing statement's node.
  983. */
  984. getTrailingStatement: esutils.ast.trailingStatement,
  985. /**
  986. * Finds the variable by a given name in a given scope and its upper scopes.
  987. * @param {eslint-scope.Scope} initScope A scope to start find.
  988. * @param {string} name A variable name to find.
  989. * @returns {eslint-scope.Variable|null} A found variable or `null`.
  990. */
  991. getVariableByName(initScope, name) {
  992. let scope = initScope;
  993. while (scope) {
  994. const variable = scope.set.get(name);
  995. if (variable) {
  996. return variable;
  997. }
  998. scope = scope.upper;
  999. }
  1000. return null;
  1001. },
  1002. /**
  1003. * Checks whether or not a given function node is the default `this` binding.
  1004. *
  1005. * First, this checks the node:
  1006. *
  1007. * - The given node is not in `PropertyDefinition#value` position.
  1008. * - The given node is not `StaticBlock`.
  1009. * - The function name does not start with uppercase. It's a convention to capitalize the names
  1010. * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
  1011. * - The function does not have a JSDoc comment that has a @this tag.
  1012. *
  1013. * Next, this checks the location of the node.
  1014. * If the location is below, this judges `this` is valid.
  1015. *
  1016. * - The location is not on an object literal.
  1017. * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
  1018. * functions only, as the name of the variable is considered to be the name of the function in this case.
  1019. * This check is not performed if `capIsConstructor` is set to `false`.
  1020. * - The location is not on an ES2015 class.
  1021. * - Its `bind`/`call`/`apply` method is not called directly.
  1022. * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
  1023. * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock`
  1024. * or any expression that is `PropertyDefinition#value` node.
  1025. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  1026. * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
  1027. * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
  1028. * @returns {boolean} The function node is the default `this` binding.
  1029. */
  1030. isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
  1031. /*
  1032. * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers.
  1033. * Therefore, A expression node at `PropertyDefinition#value` is a function.
  1034. * In this case, `this` is always not default binding.
  1035. */
  1036. if (node.parent.type === "PropertyDefinition" && node.parent.value === node) {
  1037. return false;
  1038. }
  1039. // Class static blocks are implicit functions. In this case, `this` is always not default binding.
  1040. if (node.type === "StaticBlock") {
  1041. return false;
  1042. }
  1043. if (
  1044. (capIsConstructor && isES5Constructor(node)) ||
  1045. hasJSDocThisTag(node, sourceCode)
  1046. ) {
  1047. return false;
  1048. }
  1049. const isAnonymous = node.id === null;
  1050. let currentNode = node;
  1051. while (currentNode) {
  1052. const parent = currentNode.parent;
  1053. switch (parent.type) {
  1054. /*
  1055. * Looks up the destination.
  1056. * e.g., obj.foo = nativeFoo || function foo() { ... };
  1057. */
  1058. case "LogicalExpression":
  1059. case "ConditionalExpression":
  1060. case "ChainExpression":
  1061. currentNode = parent;
  1062. break;
  1063. /*
  1064. * If the upper function is IIFE, checks the destination of the return value.
  1065. * e.g.
  1066. * obj.foo = (function() {
  1067. * // setup...
  1068. * return function foo() { ... };
  1069. * })();
  1070. * obj.foo = (() =>
  1071. * function foo() { ... }
  1072. * )();
  1073. */
  1074. case "ReturnStatement": {
  1075. const func = getUpperFunction(parent);
  1076. if (func === null || !isCallee(func)) {
  1077. return true;
  1078. }
  1079. currentNode = func.parent;
  1080. break;
  1081. }
  1082. case "ArrowFunctionExpression":
  1083. if (currentNode !== parent.body || !isCallee(parent)) {
  1084. return true;
  1085. }
  1086. currentNode = parent.parent;
  1087. break;
  1088. /*
  1089. * e.g.
  1090. * var obj = { foo() { ... } };
  1091. * var obj = { foo: function() { ... } };
  1092. * class A { constructor() { ... } }
  1093. * class A { foo() { ... } }
  1094. * class A { get foo() { ... } }
  1095. * class A { set foo() { ... } }
  1096. * class A { static foo() { ... } }
  1097. * class A { foo = function() { ... } }
  1098. */
  1099. case "Property":
  1100. case "PropertyDefinition":
  1101. case "MethodDefinition":
  1102. return parent.value !== currentNode;
  1103. /*
  1104. * e.g.
  1105. * obj.foo = function foo() { ... };
  1106. * Foo = function() { ... };
  1107. * [obj.foo = function foo() { ... }] = a;
  1108. * [Foo = function() { ... }] = a;
  1109. */
  1110. case "AssignmentExpression":
  1111. case "AssignmentPattern":
  1112. if (parent.left.type === "MemberExpression") {
  1113. return false;
  1114. }
  1115. if (
  1116. capIsConstructor &&
  1117. isAnonymous &&
  1118. parent.left.type === "Identifier" &&
  1119. startsWithUpperCase(parent.left.name)
  1120. ) {
  1121. return false;
  1122. }
  1123. return true;
  1124. /*
  1125. * e.g.
  1126. * var Foo = function() { ... };
  1127. */
  1128. case "VariableDeclarator":
  1129. return !(
  1130. capIsConstructor &&
  1131. isAnonymous &&
  1132. parent.init === currentNode &&
  1133. parent.id.type === "Identifier" &&
  1134. startsWithUpperCase(parent.id.name)
  1135. );
  1136. /*
  1137. * e.g.
  1138. * var foo = function foo() { ... }.bind(obj);
  1139. * (function foo() { ... }).call(obj);
  1140. * (function foo() { ... }).apply(obj, []);
  1141. */
  1142. case "MemberExpression":
  1143. if (
  1144. parent.object === currentNode &&
  1145. isSpecificMemberAccess(parent, null, bindOrCallOrApplyPattern)
  1146. ) {
  1147. const maybeCalleeNode = parent.parent.type === "ChainExpression"
  1148. ? parent.parent
  1149. : parent;
  1150. return !(
  1151. isCallee(maybeCalleeNode) &&
  1152. maybeCalleeNode.parent.arguments.length >= 1 &&
  1153. !isNullOrUndefined(maybeCalleeNode.parent.arguments[0])
  1154. );
  1155. }
  1156. return true;
  1157. /*
  1158. * e.g.
  1159. * Reflect.apply(function() {}, obj, []);
  1160. * Array.from([], function() {}, obj);
  1161. * list.forEach(function() {}, obj);
  1162. */
  1163. case "CallExpression":
  1164. if (isReflectApply(parent.callee)) {
  1165. return (
  1166. parent.arguments.length !== 3 ||
  1167. parent.arguments[0] !== currentNode ||
  1168. isNullOrUndefined(parent.arguments[1])
  1169. );
  1170. }
  1171. if (isArrayFromMethod(parent.callee)) {
  1172. return (
  1173. parent.arguments.length !== 3 ||
  1174. parent.arguments[1] !== currentNode ||
  1175. isNullOrUndefined(parent.arguments[2])
  1176. );
  1177. }
  1178. if (isMethodWhichHasThisArg(parent.callee)) {
  1179. return (
  1180. parent.arguments.length !== 2 ||
  1181. parent.arguments[0] !== currentNode ||
  1182. isNullOrUndefined(parent.arguments[1])
  1183. );
  1184. }
  1185. return true;
  1186. // Otherwise `this` is default.
  1187. default:
  1188. return true;
  1189. }
  1190. }
  1191. /* c8 ignore next */
  1192. return true;
  1193. },
  1194. /**
  1195. * Get the precedence level based on the node type
  1196. * @param {ASTNode} node node to evaluate
  1197. * @returns {int} precedence level
  1198. * @private
  1199. */
  1200. getPrecedence(node) {
  1201. switch (node.type) {
  1202. case "SequenceExpression":
  1203. return 0;
  1204. case "AssignmentExpression":
  1205. case "ArrowFunctionExpression":
  1206. case "YieldExpression":
  1207. return 1;
  1208. case "ConditionalExpression":
  1209. return 3;
  1210. case "LogicalExpression":
  1211. switch (node.operator) {
  1212. case "||":
  1213. case "??":
  1214. return 4;
  1215. case "&&":
  1216. return 5;
  1217. // no default
  1218. }
  1219. /* falls through */
  1220. case "BinaryExpression":
  1221. switch (node.operator) {
  1222. case "|":
  1223. return 6;
  1224. case "^":
  1225. return 7;
  1226. case "&":
  1227. return 8;
  1228. case "==":
  1229. case "!=":
  1230. case "===":
  1231. case "!==":
  1232. return 9;
  1233. case "<":
  1234. case "<=":
  1235. case ">":
  1236. case ">=":
  1237. case "in":
  1238. case "instanceof":
  1239. return 10;
  1240. case "<<":
  1241. case ">>":
  1242. case ">>>":
  1243. return 11;
  1244. case "+":
  1245. case "-":
  1246. return 12;
  1247. case "*":
  1248. case "/":
  1249. case "%":
  1250. return 13;
  1251. case "**":
  1252. return 15;
  1253. // no default
  1254. }
  1255. /* falls through */
  1256. case "UnaryExpression":
  1257. case "AwaitExpression":
  1258. return 16;
  1259. case "UpdateExpression":
  1260. return 17;
  1261. case "CallExpression":
  1262. case "ChainExpression":
  1263. case "ImportExpression":
  1264. return 18;
  1265. case "NewExpression":
  1266. return 19;
  1267. default:
  1268. return 20;
  1269. }
  1270. },
  1271. /**
  1272. * Checks whether the given node is an empty block node or not.
  1273. * @param {ASTNode|null} node The node to check.
  1274. * @returns {boolean} `true` if the node is an empty block.
  1275. */
  1276. isEmptyBlock(node) {
  1277. return Boolean(node && node.type === "BlockStatement" && node.body.length === 0);
  1278. },
  1279. /**
  1280. * Checks whether the given node is an empty function node or not.
  1281. * @param {ASTNode|null} node The node to check.
  1282. * @returns {boolean} `true` if the node is an empty function.
  1283. */
  1284. isEmptyFunction(node) {
  1285. return isFunction(node) && module.exports.isEmptyBlock(node.body);
  1286. },
  1287. /**
  1288. * Get directives from directive prologue of a Program or Function node.
  1289. * @param {ASTNode} node The node to check.
  1290. * @returns {ASTNode[]} The directives found in the directive prologue.
  1291. */
  1292. getDirectivePrologue(node) {
  1293. const directives = [];
  1294. // Directive prologues only occur at the top of files or functions.
  1295. if (
  1296. node.type === "Program" ||
  1297. node.type === "FunctionDeclaration" ||
  1298. node.type === "FunctionExpression" ||
  1299. /*
  1300. * Do not check arrow functions with implicit return.
  1301. * `() => "use strict";` returns the string `"use strict"`.
  1302. */
  1303. (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement")
  1304. ) {
  1305. const statements = node.type === "Program" ? node.body : node.body.body;
  1306. for (const statement of statements) {
  1307. if (
  1308. statement.type === "ExpressionStatement" &&
  1309. statement.expression.type === "Literal"
  1310. ) {
  1311. directives.push(statement);
  1312. } else {
  1313. break;
  1314. }
  1315. }
  1316. }
  1317. return directives;
  1318. },
  1319. /**
  1320. * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
  1321. * after the node will be parsed as a decimal point, rather than a property-access dot.
  1322. * @param {ASTNode} node The node to check.
  1323. * @returns {boolean} `true` if this node is a decimal integer.
  1324. * @example
  1325. *
  1326. * 0 // true
  1327. * 5 // true
  1328. * 50 // true
  1329. * 5_000 // true
  1330. * 1_234_56 // true
  1331. * 08 // true
  1332. * 0192 // true
  1333. * 5. // false
  1334. * .5 // false
  1335. * 5.0 // false
  1336. * 5.00_00 // false
  1337. * 05 // false
  1338. * 0x5 // false
  1339. * 0b101 // false
  1340. * 0b11_01 // false
  1341. * 0o5 // false
  1342. * 5e0 // false
  1343. * 5e1_000 // false
  1344. * 5n // false
  1345. * 1_000n // false
  1346. * "5" // false
  1347. *
  1348. */
  1349. isDecimalInteger(node) {
  1350. return node.type === "Literal" && typeof node.value === "number" &&
  1351. DECIMAL_INTEGER_PATTERN.test(node.raw);
  1352. },
  1353. /**
  1354. * Determines whether this token is a decimal integer numeric token.
  1355. * This is similar to isDecimalInteger(), but for tokens.
  1356. * @param {Token} token The token to check.
  1357. * @returns {boolean} `true` if this token is a decimal integer.
  1358. */
  1359. isDecimalIntegerNumericToken(token) {
  1360. return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value);
  1361. },
  1362. /**
  1363. * Gets the name and kind of the given function node.
  1364. *
  1365. * - `function foo() {}` .................... `function 'foo'`
  1366. * - `(function foo() {})` .................. `function 'foo'`
  1367. * - `(function() {})` ...................... `function`
  1368. * - `function* foo() {}` ................... `generator function 'foo'`
  1369. * - `(function* foo() {})` ................. `generator function 'foo'`
  1370. * - `(function*() {})` ..................... `generator function`
  1371. * - `() => {}` ............................. `arrow function`
  1372. * - `async () => {}` ....................... `async arrow function`
  1373. * - `({ foo: function foo() {} })` ......... `method 'foo'`
  1374. * - `({ foo: function() {} })` ............. `method 'foo'`
  1375. * - `({ ['foo']: function() {} })` ......... `method 'foo'`
  1376. * - `({ [foo]: function() {} })` ........... `method`
  1377. * - `({ foo() {} })` ....................... `method 'foo'`
  1378. * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
  1379. * - `({ foo: function*() {} })` ............ `generator method 'foo'`
  1380. * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
  1381. * - `({ [foo]: function*() {} })` .......... `generator method`
  1382. * - `({ *foo() {} })` ...................... `generator method 'foo'`
  1383. * - `({ foo: async function foo() {} })` ... `async method 'foo'`
  1384. * - `({ foo: async function() {} })` ....... `async method 'foo'`
  1385. * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
  1386. * - `({ [foo]: async function() {} })` ..... `async method`
  1387. * - `({ async foo() {} })` ................. `async method 'foo'`
  1388. * - `({ get foo() {} })` ................... `getter 'foo'`
  1389. * - `({ set foo(a) {} })` .................. `setter 'foo'`
  1390. * - `class A { constructor() {} }` ......... `constructor`
  1391. * - `class A { foo() {} }` ................. `method 'foo'`
  1392. * - `class A { *foo() {} }` ................ `generator method 'foo'`
  1393. * - `class A { async foo() {} }` ........... `async method 'foo'`
  1394. * - `class A { ['foo']() {} }` ............. `method 'foo'`
  1395. * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
  1396. * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
  1397. * - `class A { [foo]() {} }` ............... `method`
  1398. * - `class A { *[foo]() {} }` .............. `generator method`
  1399. * - `class A { async [foo]() {} }` ......... `async method`
  1400. * - `class A { get foo() {} }` ............. `getter 'foo'`
  1401. * - `class A { set foo(a) {} }` ............ `setter 'foo'`
  1402. * - `class A { static foo() {} }` .......... `static method 'foo'`
  1403. * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
  1404. * - `class A { static async foo() {} }` .... `static async method 'foo'`
  1405. * - `class A { static get foo() {} }` ...... `static getter 'foo'`
  1406. * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
  1407. * - `class A { foo = () => {}; }` .......... `method 'foo'`
  1408. * - `class A { foo = function() {}; }` ..... `method 'foo'`
  1409. * - `class A { foo = function bar() {}; }` . `method 'foo'`
  1410. * - `class A { static foo = () => {}; }` ... `static method 'foo'`
  1411. * - `class A { '#foo' = () => {}; }` ....... `method '#foo'`
  1412. * - `class A { #foo = () => {}; }` ......... `private method #foo`
  1413. * - `class A { static #foo = () => {}; }` .. `static private method #foo`
  1414. * - `class A { '#foo'() {} }` .............. `method '#foo'`
  1415. * - `class A { #foo() {} }` ................ `private method #foo`
  1416. * - `class A { static #foo() {} }` ......... `static private method #foo`
  1417. * @param {ASTNode} node The function node to get.
  1418. * @returns {string} The name and kind of the function node.
  1419. */
  1420. getFunctionNameWithKind(node) {
  1421. const parent = node.parent;
  1422. const tokens = [];
  1423. if (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1424. // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features
  1425. if (parent.static) {
  1426. tokens.push("static");
  1427. }
  1428. if (!parent.computed && parent.key.type === "PrivateIdentifier") {
  1429. tokens.push("private");
  1430. }
  1431. }
  1432. if (node.async) {
  1433. tokens.push("async");
  1434. }
  1435. if (node.generator) {
  1436. tokens.push("generator");
  1437. }
  1438. if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1439. if (parent.kind === "constructor") {
  1440. return "constructor";
  1441. }
  1442. if (parent.kind === "get") {
  1443. tokens.push("getter");
  1444. } else if (parent.kind === "set") {
  1445. tokens.push("setter");
  1446. } else {
  1447. tokens.push("method");
  1448. }
  1449. } else if (parent.type === "PropertyDefinition") {
  1450. tokens.push("method");
  1451. } else {
  1452. if (node.type === "ArrowFunctionExpression") {
  1453. tokens.push("arrow");
  1454. }
  1455. tokens.push("function");
  1456. }
  1457. if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1458. if (!parent.computed && parent.key.type === "PrivateIdentifier") {
  1459. tokens.push(`#${parent.key.name}`);
  1460. } else {
  1461. const name = getStaticPropertyName(parent);
  1462. if (name !== null) {
  1463. tokens.push(`'${name}'`);
  1464. } else if (node.id) {
  1465. tokens.push(`'${node.id.name}'`);
  1466. }
  1467. }
  1468. } else if (node.id) {
  1469. tokens.push(`'${node.id.name}'`);
  1470. }
  1471. return tokens.join(" ");
  1472. },
  1473. /**
  1474. * Gets the location of the given function node for reporting.
  1475. *
  1476. * - `function foo() {}`
  1477. * ^^^^^^^^^^^^
  1478. * - `(function foo() {})`
  1479. * ^^^^^^^^^^^^
  1480. * - `(function() {})`
  1481. * ^^^^^^^^
  1482. * - `function* foo() {}`
  1483. * ^^^^^^^^^^^^^
  1484. * - `(function* foo() {})`
  1485. * ^^^^^^^^^^^^^
  1486. * - `(function*() {})`
  1487. * ^^^^^^^^^
  1488. * - `() => {}`
  1489. * ^^
  1490. * - `async () => {}`
  1491. * ^^
  1492. * - `({ foo: function foo() {} })`
  1493. * ^^^^^^^^^^^^^^^^^
  1494. * - `({ foo: function() {} })`
  1495. * ^^^^^^^^^^^^^
  1496. * - `({ ['foo']: function() {} })`
  1497. * ^^^^^^^^^^^^^^^^^
  1498. * - `({ [foo]: function() {} })`
  1499. * ^^^^^^^^^^^^^^^
  1500. * - `({ foo() {} })`
  1501. * ^^^
  1502. * - `({ foo: function* foo() {} })`
  1503. * ^^^^^^^^^^^^^^^^^^
  1504. * - `({ foo: function*() {} })`
  1505. * ^^^^^^^^^^^^^^
  1506. * - `({ ['foo']: function*() {} })`
  1507. * ^^^^^^^^^^^^^^^^^^
  1508. * - `({ [foo]: function*() {} })`
  1509. * ^^^^^^^^^^^^^^^^
  1510. * - `({ *foo() {} })`
  1511. * ^^^^
  1512. * - `({ foo: async function foo() {} })`
  1513. * ^^^^^^^^^^^^^^^^^^^^^^^
  1514. * - `({ foo: async function() {} })`
  1515. * ^^^^^^^^^^^^^^^^^^^
  1516. * - `({ ['foo']: async function() {} })`
  1517. * ^^^^^^^^^^^^^^^^^^^^^^^
  1518. * - `({ [foo]: async function() {} })`
  1519. * ^^^^^^^^^^^^^^^^^^^^^
  1520. * - `({ async foo() {} })`
  1521. * ^^^^^^^^^
  1522. * - `({ get foo() {} })`
  1523. * ^^^^^^^
  1524. * - `({ set foo(a) {} })`
  1525. * ^^^^^^^
  1526. * - `class A { constructor() {} }`
  1527. * ^^^^^^^^^^^
  1528. * - `class A { foo() {} }`
  1529. * ^^^
  1530. * - `class A { *foo() {} }`
  1531. * ^^^^
  1532. * - `class A { async foo() {} }`
  1533. * ^^^^^^^^^
  1534. * - `class A { ['foo']() {} }`
  1535. * ^^^^^^^
  1536. * - `class A { *['foo']() {} }`
  1537. * ^^^^^^^^
  1538. * - `class A { async ['foo']() {} }`
  1539. * ^^^^^^^^^^^^^
  1540. * - `class A { [foo]() {} }`
  1541. * ^^^^^
  1542. * - `class A { *[foo]() {} }`
  1543. * ^^^^^^
  1544. * - `class A { async [foo]() {} }`
  1545. * ^^^^^^^^^^^
  1546. * - `class A { get foo() {} }`
  1547. * ^^^^^^^
  1548. * - `class A { set foo(a) {} }`
  1549. * ^^^^^^^
  1550. * - `class A { static foo() {} }`
  1551. * ^^^^^^^^^^
  1552. * - `class A { static *foo() {} }`
  1553. * ^^^^^^^^^^^
  1554. * - `class A { static async foo() {} }`
  1555. * ^^^^^^^^^^^^^^^^
  1556. * - `class A { static get foo() {} }`
  1557. * ^^^^^^^^^^^^^^
  1558. * - `class A { static set foo(a) {} }`
  1559. * ^^^^^^^^^^^^^^
  1560. * - `class A { foo = function() {} }`
  1561. * ^^^^^^^^^^^^^^
  1562. * - `class A { static foo = function() {} }`
  1563. * ^^^^^^^^^^^^^^^^^^^^^
  1564. * - `class A { foo = (a, b) => {} }`
  1565. * ^^^^^^
  1566. * @param {ASTNode} node The function node to get.
  1567. * @param {SourceCode} sourceCode The source code object to get tokens.
  1568. * @returns {string} The location of the function node for reporting.
  1569. */
  1570. getFunctionHeadLoc(node, sourceCode) {
  1571. const parent = node.parent;
  1572. let start = null;
  1573. let end = null;
  1574. if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1575. start = parent.loc.start;
  1576. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1577. } else if (node.type === "ArrowFunctionExpression") {
  1578. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  1579. start = arrowToken.loc.start;
  1580. end = arrowToken.loc.end;
  1581. } else {
  1582. start = node.loc.start;
  1583. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1584. }
  1585. return {
  1586. start: Object.assign({}, start),
  1587. end: Object.assign({}, end)
  1588. };
  1589. },
  1590. /**
  1591. * Gets next location when the result is not out of bound, otherwise returns null.
  1592. *
  1593. * Assumptions:
  1594. *
  1595. * - The given location represents a valid location in the given source code.
  1596. * - Columns are 0-based.
  1597. * - Lines are 1-based.
  1598. * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
  1599. * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
  1600. * The start (column 0) of that extra line is considered to be a valid location.
  1601. *
  1602. * Examples of successive locations (line, column):
  1603. *
  1604. * code: foo
  1605. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
  1606. *
  1607. * code: foo<LF>
  1608. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1609. *
  1610. * code: foo<CR><LF>
  1611. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1612. *
  1613. * code: a<LF>b
  1614. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
  1615. *
  1616. * code: a<LF>b<LF>
  1617. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1618. *
  1619. * code: a<CR><LF>b<CR><LF>
  1620. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1621. *
  1622. * code: a<LF><LF>
  1623. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
  1624. *
  1625. * code: <LF>
  1626. * locations: (1, 0) -> (2, 0) -> null
  1627. *
  1628. * code:
  1629. * locations: (1, 0) -> null
  1630. * @param {SourceCode} sourceCode The sourceCode
  1631. * @param {{line: number, column: number}} location The location
  1632. * @returns {{line: number, column: number} | null} Next location
  1633. */
  1634. getNextLocation(sourceCode, { line, column }) {
  1635. if (column < sourceCode.lines[line - 1].length) {
  1636. return {
  1637. line,
  1638. column: column + 1
  1639. };
  1640. }
  1641. if (line < sourceCode.lines.length) {
  1642. return {
  1643. line: line + 1,
  1644. column: 0
  1645. };
  1646. }
  1647. return null;
  1648. },
  1649. /**
  1650. * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
  1651. * surrounding the node.
  1652. * @param {SourceCode} sourceCode The source code object
  1653. * @param {ASTNode} node An expression node
  1654. * @returns {string} The text representing the node, with all surrounding parentheses included
  1655. */
  1656. getParenthesisedText(sourceCode, node) {
  1657. let leftToken = sourceCode.getFirstToken(node);
  1658. let rightToken = sourceCode.getLastToken(node);
  1659. while (
  1660. sourceCode.getTokenBefore(leftToken) &&
  1661. sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
  1662. sourceCode.getTokenBefore(leftToken).value === "(" &&
  1663. sourceCode.getTokenAfter(rightToken) &&
  1664. sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
  1665. sourceCode.getTokenAfter(rightToken).value === ")"
  1666. ) {
  1667. leftToken = sourceCode.getTokenBefore(leftToken);
  1668. rightToken = sourceCode.getTokenAfter(rightToken);
  1669. }
  1670. return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]);
  1671. },
  1672. /**
  1673. * Determine if a node has a possibility to be an Error object
  1674. * @param {ASTNode} node ASTNode to check
  1675. * @returns {boolean} True if there is a chance it contains an Error obj
  1676. */
  1677. couldBeError(node) {
  1678. switch (node.type) {
  1679. case "Identifier":
  1680. case "CallExpression":
  1681. case "NewExpression":
  1682. case "MemberExpression":
  1683. case "TaggedTemplateExpression":
  1684. case "YieldExpression":
  1685. case "AwaitExpression":
  1686. case "ChainExpression":
  1687. return true; // possibly an error object.
  1688. case "AssignmentExpression":
  1689. if (["=", "&&="].includes(node.operator)) {
  1690. return module.exports.couldBeError(node.right);
  1691. }
  1692. if (["||=", "??="].includes(node.operator)) {
  1693. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1694. }
  1695. /**
  1696. * All other assignment operators are mathematical assignment operators (arithmetic or bitwise).
  1697. * An assignment expression with a mathematical operator can either evaluate to a primitive value,
  1698. * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object.
  1699. */
  1700. return false;
  1701. case "SequenceExpression": {
  1702. const exprs = node.expressions;
  1703. return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]);
  1704. }
  1705. case "LogicalExpression":
  1706. /*
  1707. * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it
  1708. * doesn't short-circuit, it takes the value from the right side, so the right side must always be
  1709. * a plausible error. A future improvement could verify that the left side could be truthy by
  1710. * excluding falsy literals.
  1711. */
  1712. if (node.operator === "&&") {
  1713. return module.exports.couldBeError(node.right);
  1714. }
  1715. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1716. case "ConditionalExpression":
  1717. return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate);
  1718. default:
  1719. return false;
  1720. }
  1721. },
  1722. /**
  1723. * Check if a given node is a numeric literal or not.
  1724. * @param {ASTNode} node The node to check.
  1725. * @returns {boolean} `true` if the node is a number or bigint literal.
  1726. */
  1727. isNumericLiteral(node) {
  1728. return (
  1729. node.type === "Literal" &&
  1730. (typeof node.value === "number" || Boolean(node.bigint))
  1731. );
  1732. },
  1733. /**
  1734. * Determines whether two tokens can safely be placed next to each other without merging into a single token
  1735. * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
  1736. * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
  1737. * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
  1738. * next to each other, behavior is undefined (although it should return `true` in most cases).
  1739. */
  1740. canTokensBeAdjacent(leftValue, rightValue) {
  1741. const espreeOptions = {
  1742. ecmaVersion: espree.latestEcmaVersion,
  1743. comment: true,
  1744. range: true
  1745. };
  1746. let leftToken;
  1747. if (typeof leftValue === "string") {
  1748. let tokens;
  1749. try {
  1750. tokens = espree.tokenize(leftValue, espreeOptions);
  1751. } catch {
  1752. return false;
  1753. }
  1754. const comments = tokens.comments;
  1755. leftToken = tokens[tokens.length - 1];
  1756. if (comments.length) {
  1757. const lastComment = comments[comments.length - 1];
  1758. if (!leftToken || lastComment.range[0] > leftToken.range[0]) {
  1759. leftToken = lastComment;
  1760. }
  1761. }
  1762. } else {
  1763. leftToken = leftValue;
  1764. }
  1765. /*
  1766. * If a hashbang comment was passed as a token object from SourceCode,
  1767. * its type will be "Shebang" because of the way ESLint itself handles hashbangs.
  1768. * If a hashbang comment was passed in a string and then tokenized in this function,
  1769. * its type will be "Hashbang" because of the way Espree tokenizes hashbangs.
  1770. */
  1771. if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") {
  1772. return false;
  1773. }
  1774. let rightToken;
  1775. if (typeof rightValue === "string") {
  1776. let tokens;
  1777. try {
  1778. tokens = espree.tokenize(rightValue, espreeOptions);
  1779. } catch {
  1780. return false;
  1781. }
  1782. const comments = tokens.comments;
  1783. rightToken = tokens[0];
  1784. if (comments.length) {
  1785. const firstComment = comments[0];
  1786. if (!rightToken || firstComment.range[0] < rightToken.range[0]) {
  1787. rightToken = firstComment;
  1788. }
  1789. }
  1790. } else {
  1791. rightToken = rightValue;
  1792. }
  1793. if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") {
  1794. if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") {
  1795. const PLUS_TOKENS = new Set(["+", "++"]);
  1796. const MINUS_TOKENS = new Set(["-", "--"]);
  1797. return !(
  1798. PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) ||
  1799. MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value)
  1800. );
  1801. }
  1802. if (leftToken.type === "Punctuator" && leftToken.value === "/") {
  1803. return !["Block", "Line", "RegularExpression"].includes(rightToken.type);
  1804. }
  1805. return true;
  1806. }
  1807. if (
  1808. leftToken.type === "String" || rightToken.type === "String" ||
  1809. leftToken.type === "Template" || rightToken.type === "Template"
  1810. ) {
  1811. return true;
  1812. }
  1813. if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) {
  1814. return true;
  1815. }
  1816. if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") {
  1817. return true;
  1818. }
  1819. if (rightToken.type === "PrivateIdentifier") {
  1820. return true;
  1821. }
  1822. return false;
  1823. },
  1824. /**
  1825. * Get the `loc` object of a given name in a `/*globals` directive comment.
  1826. * @param {SourceCode} sourceCode The source code to convert index to loc.
  1827. * @param {Comment} comment The `/*globals` directive comment which include the name.
  1828. * @param {string} name The name to find.
  1829. * @returns {SourceLocation} The `loc` object.
  1830. */
  1831. getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
  1832. const namePattern = new RegExp(`[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`, "gu");
  1833. // To ignore the first text "global".
  1834. namePattern.lastIndex = comment.value.indexOf("global") + 6;
  1835. // Search a given variable name.
  1836. const match = namePattern.exec(comment.value);
  1837. // Convert the index to loc.
  1838. const start = sourceCode.getLocFromIndex(
  1839. comment.range[0] +
  1840. "/*".length +
  1841. (match ? match.index + 1 : 0)
  1842. );
  1843. const end = {
  1844. line: start.line,
  1845. column: start.column + (match ? name.length : 1)
  1846. };
  1847. return { start, end };
  1848. },
  1849. /**
  1850. * Determines whether the given raw string contains an octal escape sequence
  1851. * or a non-octal decimal escape sequence ("\8", "\9").
  1852. *
  1853. * "\1", "\2" ... "\7", "\8", "\9"
  1854. * "\00", "\01" ... "\07", "\08", "\09"
  1855. *
  1856. * "\0", when not followed by a digit, is not an octal escape sequence.
  1857. * @param {string} rawString A string in its raw representation.
  1858. * @returns {boolean} `true` if the string contains at least one octal escape sequence
  1859. * or at least one non-octal decimal escape sequence.
  1860. */
  1861. hasOctalOrNonOctalDecimalEscapeSequence(rawString) {
  1862. return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString);
  1863. },
  1864. isReferenceToGlobalVariable,
  1865. isLogicalExpression,
  1866. isCoalesceExpression,
  1867. isMixedLogicalAndCoalesceExpressions,
  1868. isNullLiteral,
  1869. getStaticStringValue,
  1870. getStaticPropertyName,
  1871. skipChainExpression,
  1872. isSpecificId,
  1873. isSpecificMemberAccess,
  1874. equalLiteralValue,
  1875. isSameReference,
  1876. isLogicalAssignmentOperator,
  1877. getSwitchCaseColonToken,
  1878. getModuleExportName,
  1879. isConstant
  1880. };