ast-utils.js 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733
  1. /**
  2. * @fileoverview Common utils for AST.
  3. * @author Gyandeep Singh
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const { KEYS: eslintVisitorKeys } = require("eslint-visitor-keys");
  10. const esutils = require("esutils");
  11. const espree = require("espree");
  12. const escapeRegExp = require("escape-string-regexp");
  13. const {
  14. breakableTypePattern,
  15. createGlobalLinebreakMatcher,
  16. lineBreakPattern,
  17. shebangPattern,
  18. } = require("../../shared/ast-utils");
  19. const globals = require("../../../conf/globals");
  20. const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version");
  21. //------------------------------------------------------------------------------
  22. // Helpers
  23. //------------------------------------------------------------------------------
  24. const anyFunctionPattern =
  25. /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
  26. const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
  27. const arrayMethodWithThisArgPattern =
  28. /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u;
  29. const arrayOrTypedArrayPattern = /Array$/u;
  30. const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
  31. const thisTagPattern = /^[\s*]*@this/mu;
  32. const COMMENTS_IGNORE_PATTERN =
  33. /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
  34. const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u;
  35. const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
  36. // A set of node types that can contain a list of statements
  37. const STATEMENT_LIST_PARENTS = new Set([
  38. "Program",
  39. "BlockStatement",
  40. "StaticBlock",
  41. "SwitchCase",
  42. ]);
  43. const LEXICAL_DECLARATION_KINDS = new Set([
  44. "let",
  45. "const",
  46. "using",
  47. "await using",
  48. ]);
  49. const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u;
  50. // Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string
  51. const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN =
  52. /^(?:[^\\]|\\.)*\\(?:[1-9]|0\d)/su;
  53. const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]);
  54. /**
  55. * All builtin global variables defined in the latest ECMAScript specification.
  56. * @type {Record<string,boolean>} Key is the name of the variable. Value is `true` if the variable is considered writable, `false` otherwise.
  57. */
  58. const ECMASCRIPT_GLOBALS = globals[`es${LATEST_ECMA_VERSION}`];
  59. /**
  60. * Checks reference if is non initializer and writable.
  61. * @param {Reference} reference A reference to check.
  62. * @param {number} index The index of the reference in the references.
  63. * @param {Reference[]} references The array that the reference belongs to.
  64. * @returns {boolean} Success/Failure
  65. * @private
  66. */
  67. function isModifyingReference(reference, index, references) {
  68. const identifier = reference.identifier;
  69. /*
  70. * Destructuring assignments can have multiple default value, so
  71. * possibly there are multiple writeable references for the same
  72. * identifier.
  73. */
  74. const modifyingDifferentIdentifier =
  75. index === 0 || references[index - 1].identifier !== identifier;
  76. return (
  77. identifier &&
  78. reference.init === false &&
  79. reference.isWrite() &&
  80. modifyingDifferentIdentifier
  81. );
  82. }
  83. /**
  84. * Checks whether the given string starts with uppercase or not.
  85. * @param {string} s The string to check.
  86. * @returns {boolean} `true` if the string starts with uppercase.
  87. */
  88. function startsWithUpperCase(s) {
  89. return s[0] !== s[0].toLocaleLowerCase();
  90. }
  91. /**
  92. * Checks whether or not a node is a constructor.
  93. * @param {ASTNode} node A function node to check.
  94. * @returns {boolean} Whether or not a node is a constructor.
  95. */
  96. function isES5Constructor(node) {
  97. return node.id && startsWithUpperCase(node.id.name);
  98. }
  99. /**
  100. * Finds a function node from ancestors of a node.
  101. * @param {ASTNode} node A start node to find.
  102. * @returns {Node|null} A found function node.
  103. */
  104. function getUpperFunction(node) {
  105. for (
  106. let currentNode = node;
  107. currentNode;
  108. currentNode = currentNode.parent
  109. ) {
  110. if (anyFunctionPattern.test(currentNode.type)) {
  111. return currentNode;
  112. }
  113. }
  114. return null;
  115. }
  116. /**
  117. * Checks whether a given node is a function node or not.
  118. * The following types are function nodes:
  119. *
  120. * - ArrowFunctionExpression
  121. * - FunctionDeclaration
  122. * - FunctionExpression
  123. * @param {ASTNode|null} node A node to check.
  124. * @returns {boolean} `true` if the node is a function node.
  125. */
  126. function isFunction(node) {
  127. return Boolean(node && anyFunctionPattern.test(node.type));
  128. }
  129. /**
  130. * Checks whether a given node is a loop node or not.
  131. * The following types are loop nodes:
  132. *
  133. * - DoWhileStatement
  134. * - ForInStatement
  135. * - ForOfStatement
  136. * - ForStatement
  137. * - WhileStatement
  138. * @param {ASTNode|null} node A node to check.
  139. * @returns {boolean} `true` if the node is a loop node.
  140. */
  141. function isLoop(node) {
  142. return Boolean(node && anyLoopPattern.test(node.type));
  143. }
  144. /**
  145. * Checks whether the given node is in a loop or not.
  146. * @param {ASTNode} node The node to check.
  147. * @returns {boolean} `true` if the node is in a loop.
  148. */
  149. function isInLoop(node) {
  150. for (
  151. let currentNode = node;
  152. currentNode && !isFunction(currentNode);
  153. currentNode = currentNode.parent
  154. ) {
  155. if (isLoop(currentNode)) {
  156. return true;
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * Determines whether the given node is a `null` literal.
  163. * @param {ASTNode} node The node to check
  164. * @returns {boolean} `true` if the node is a `null` literal
  165. */
  166. function isNullLiteral(node) {
  167. /*
  168. * Checking `node.value === null` does not guarantee that a literal is a null literal.
  169. * When parsing values that cannot be represented in the current environment (e.g. unicode
  170. * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
  171. * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
  172. * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
  173. */
  174. return (
  175. node.type === "Literal" &&
  176. node.value === null &&
  177. !node.regex &&
  178. !node.bigint
  179. );
  180. }
  181. /**
  182. * Checks whether or not a node is `null` or `undefined`.
  183. * @param {ASTNode} node A node to check.
  184. * @returns {boolean} Whether or not the node is a `null` or `undefined`.
  185. * @public
  186. */
  187. function isNullOrUndefined(node) {
  188. return (
  189. isNullLiteral(node) ||
  190. (node.type === "Identifier" && node.name === "undefined") ||
  191. (node.type === "UnaryExpression" && node.operator === "void")
  192. );
  193. }
  194. /**
  195. * Checks whether or not a node is callee.
  196. * @param {ASTNode} node A node to check.
  197. * @returns {boolean} Whether or not the node is callee.
  198. */
  199. function isCallee(node) {
  200. return node.parent.type === "CallExpression" && node.parent.callee === node;
  201. }
  202. /**
  203. * Returns the result of the string conversion applied to the evaluated value of the given expression node,
  204. * if it can be determined statically.
  205. *
  206. * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
  207. * In all other cases, this function returns `null`.
  208. * @param {ASTNode} node Expression node.
  209. * @returns {string|null} String value if it can be determined. Otherwise, `null`.
  210. */
  211. function getStaticStringValue(node) {
  212. switch (node.type) {
  213. case "Literal":
  214. if (node.value === null) {
  215. if (isNullLiteral(node)) {
  216. return String(node.value); // "null"
  217. }
  218. if (node.regex) {
  219. return `/${node.regex.pattern}/${node.regex.flags}`;
  220. }
  221. if (node.bigint) {
  222. return node.bigint;
  223. }
  224. // Otherwise, this is an unknown literal. The function will return null.
  225. } else {
  226. return String(node.value);
  227. }
  228. break;
  229. case "TemplateLiteral":
  230. if (node.expressions.length === 0 && node.quasis.length === 1) {
  231. return node.quasis[0].value.cooked;
  232. }
  233. break;
  234. // no default
  235. }
  236. return null;
  237. }
  238. /**
  239. * Gets the property name of a given node.
  240. * The node can be a MemberExpression, a Property, or a MethodDefinition.
  241. *
  242. * If the name is dynamic, this returns `null`.
  243. *
  244. * For examples:
  245. *
  246. * a.b // => "b"
  247. * a["b"] // => "b"
  248. * a['b'] // => "b"
  249. * a[`b`] // => "b"
  250. * a[100] // => "100"
  251. * a[b] // => null
  252. * a["a" + "b"] // => null
  253. * a[tag`b`] // => null
  254. * a[`${b}`] // => null
  255. *
  256. * let a = {b: 1} // => "b"
  257. * let a = {["b"]: 1} // => "b"
  258. * let a = {['b']: 1} // => "b"
  259. * let a = {[`b`]: 1} // => "b"
  260. * let a = {[100]: 1} // => "100"
  261. * let a = {[b]: 1} // => null
  262. * let a = {["a" + "b"]: 1} // => null
  263. * let a = {[tag`b`]: 1} // => null
  264. * let a = {[`${b}`]: 1} // => null
  265. * @param {ASTNode} node The node to get.
  266. * @returns {string|null} The property name if static. Otherwise, null.
  267. */
  268. function getStaticPropertyName(node) {
  269. let prop;
  270. switch (node && node.type) {
  271. case "ChainExpression":
  272. return getStaticPropertyName(node.expression);
  273. case "Property":
  274. case "PropertyDefinition":
  275. case "MethodDefinition":
  276. case "TSPropertySignature":
  277. case "TSMethodSignature":
  278. prop = node.key;
  279. break;
  280. case "MemberExpression":
  281. prop = node.property;
  282. break;
  283. // no default
  284. }
  285. if (prop) {
  286. if (prop.type === "Identifier" && !node.computed) {
  287. return prop.name;
  288. }
  289. return getStaticStringValue(prop);
  290. }
  291. return null;
  292. }
  293. /**
  294. * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
  295. * @param {ASTNode} node The node to address.
  296. * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
  297. */
  298. function skipChainExpression(node) {
  299. return node && node.type === "ChainExpression" ? node.expression : node;
  300. }
  301. /**
  302. * Check if the `actual` is an expected value.
  303. * @param {string} actual The string value to check.
  304. * @param {string | RegExp} expected The expected string value or pattern.
  305. * @returns {boolean} `true` if the `actual` is an expected value.
  306. */
  307. function checkText(actual, expected) {
  308. return typeof expected === "string"
  309. ? actual === expected
  310. : expected.test(actual);
  311. }
  312. /**
  313. * Check if a given node is an Identifier node with a given name.
  314. * @param {ASTNode} node The node to check.
  315. * @param {string | RegExp} name The expected name or the expected pattern of the object name.
  316. * @returns {boolean} `true` if the node is an Identifier node with the name.
  317. */
  318. function isSpecificId(node, name) {
  319. return node.type === "Identifier" && checkText(node.name, name);
  320. }
  321. /**
  322. * Check if a given node is member access with a given object name and property name pair.
  323. * This is regardless of optional or not.
  324. * @param {ASTNode} node The node to check.
  325. * @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.
  326. * @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.
  327. * @returns {boolean} `true` if the node is member access with the object name and property name pair.
  328. * The node is a `MemberExpression` or `ChainExpression`.
  329. */
  330. function isSpecificMemberAccess(node, objectName, propertyName) {
  331. const checkNode = skipChainExpression(node);
  332. if (checkNode.type !== "MemberExpression") {
  333. return false;
  334. }
  335. if (objectName && !isSpecificId(checkNode.object, objectName)) {
  336. return false;
  337. }
  338. if (propertyName) {
  339. const actualPropertyName = getStaticPropertyName(checkNode);
  340. if (
  341. typeof actualPropertyName !== "string" ||
  342. !checkText(actualPropertyName, propertyName)
  343. ) {
  344. return false;
  345. }
  346. }
  347. return true;
  348. }
  349. /**
  350. * Check if two literal nodes are the same value.
  351. * @param {ASTNode} left The Literal node to compare.
  352. * @param {ASTNode} right The other Literal node to compare.
  353. * @returns {boolean} `true` if the two literal nodes are the same value.
  354. */
  355. function equalLiteralValue(left, right) {
  356. // RegExp literal.
  357. if (left.regex || right.regex) {
  358. return Boolean(
  359. left.regex &&
  360. right.regex &&
  361. left.regex.pattern === right.regex.pattern &&
  362. left.regex.flags === right.regex.flags,
  363. );
  364. }
  365. // BigInt literal.
  366. if (left.bigint || right.bigint) {
  367. return left.bigint === right.bigint;
  368. }
  369. return left.value === right.value;
  370. }
  371. /**
  372. * Check if two expressions reference the same value. For example:
  373. * a = a
  374. * a.b = a.b
  375. * a[0] = a[0]
  376. * a['b'] = a['b']
  377. * @param {ASTNode} left The left side of the comparison.
  378. * @param {ASTNode} right The right side of the comparison.
  379. * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility.
  380. * @returns {boolean} `true` if both sides match and reference the same value.
  381. */
  382. function isSameReference(left, right, disableStaticComputedKey = false) {
  383. if (left.type !== right.type) {
  384. // Handle `a.b` and `a?.b` are samely.
  385. if (left.type === "ChainExpression") {
  386. return isSameReference(
  387. left.expression,
  388. right,
  389. disableStaticComputedKey,
  390. );
  391. }
  392. if (right.type === "ChainExpression") {
  393. return isSameReference(
  394. left,
  395. right.expression,
  396. disableStaticComputedKey,
  397. );
  398. }
  399. return false;
  400. }
  401. switch (left.type) {
  402. case "Super":
  403. case "ThisExpression":
  404. return true;
  405. case "Identifier":
  406. case "PrivateIdentifier":
  407. return left.name === right.name;
  408. case "Literal":
  409. return equalLiteralValue(left, right);
  410. case "ChainExpression":
  411. return isSameReference(
  412. left.expression,
  413. right.expression,
  414. disableStaticComputedKey,
  415. );
  416. case "MemberExpression": {
  417. if (!disableStaticComputedKey) {
  418. const nameA = getStaticPropertyName(left);
  419. // x.y = x["y"]
  420. if (nameA !== null) {
  421. return (
  422. isSameReference(
  423. left.object,
  424. right.object,
  425. disableStaticComputedKey,
  426. ) && nameA === getStaticPropertyName(right)
  427. );
  428. }
  429. }
  430. /*
  431. * x[0] = x[0]
  432. * x[y] = x[y]
  433. * x.y = x.y
  434. */
  435. return (
  436. left.computed === right.computed &&
  437. isSameReference(
  438. left.object,
  439. right.object,
  440. disableStaticComputedKey,
  441. ) &&
  442. isSameReference(
  443. left.property,
  444. right.property,
  445. disableStaticComputedKey,
  446. )
  447. );
  448. }
  449. default:
  450. return false;
  451. }
  452. }
  453. /**
  454. * Checks whether or not a node is `Reflect.apply`.
  455. * @param {ASTNode} node A node to check.
  456. * @returns {boolean} Whether or not the node is a `Reflect.apply`.
  457. */
  458. function isReflectApply(node) {
  459. return isSpecificMemberAccess(node, "Reflect", "apply");
  460. }
  461. /**
  462. * Checks whether or not a node is `Array.from`.
  463. * @param {ASTNode} node A node to check.
  464. * @returns {boolean} Whether or not the node is a `Array.from`.
  465. */
  466. function isArrayFromMethod(node) {
  467. return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from");
  468. }
  469. /**
  470. * Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument.
  471. * @param {ASTNode} node A node to check.
  472. * @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument.
  473. */
  474. function isMethodWhichHasThisArg(node) {
  475. return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern);
  476. }
  477. /**
  478. * Creates the negate function of the given function.
  479. * @param {Function} f The function to negate.
  480. * @returns {Function} Negated function.
  481. */
  482. function negate(f) {
  483. return token => !f(token);
  484. }
  485. /**
  486. * Checks whether or not a node has a `@this` tag in its comments.
  487. * @param {ASTNode} node A node to check.
  488. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  489. * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
  490. */
  491. function hasJSDocThisTag(node, sourceCode) {
  492. const jsdocComment = sourceCode.getJSDocComment(node);
  493. if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
  494. return true;
  495. }
  496. // Checks `@this` in its leading comments for callbacks,
  497. // because callbacks don't have its JSDoc comment.
  498. // e.g.
  499. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
  500. return sourceCode
  501. .getCommentsBefore(node)
  502. .some(comment => thisTagPattern.test(comment.value));
  503. }
  504. /**
  505. * Determines if a node is surrounded by parentheses.
  506. * @param {SourceCode} sourceCode The ESLint source code object
  507. * @param {ASTNode} node The node to be checked.
  508. * @returns {boolean} True if the node is parenthesised.
  509. * @private
  510. */
  511. function isParenthesised(sourceCode, node) {
  512. const previousToken = sourceCode.getTokenBefore(node),
  513. nextToken = sourceCode.getTokenAfter(node);
  514. return (
  515. Boolean(previousToken && nextToken) &&
  516. previousToken.value === "(" &&
  517. previousToken.range[1] <= node.range[0] &&
  518. nextToken.value === ")" &&
  519. nextToken.range[0] >= node.range[1]
  520. );
  521. }
  522. /**
  523. * Checks if the given token is a `=` token or not.
  524. * @param {Token} token The token to check.
  525. * @returns {boolean} `true` if the token is a `=` token.
  526. */
  527. function isEqToken(token) {
  528. return token.value === "=" && token.type === "Punctuator";
  529. }
  530. /**
  531. * Checks if the given token is an arrow token or not.
  532. * @param {Token} token The token to check.
  533. * @returns {boolean} `true` if the token is an arrow token.
  534. */
  535. function isArrowToken(token) {
  536. return token.value === "=>" && token.type === "Punctuator";
  537. }
  538. /**
  539. * Checks if the given token is a comma token or not.
  540. * @param {Token} token The token to check.
  541. * @returns {boolean} `true` if the token is a comma token.
  542. */
  543. function isCommaToken(token) {
  544. return token.value === "," && token.type === "Punctuator";
  545. }
  546. /**
  547. * Checks if the given token is a dot token or not.
  548. * @param {Token} token The token to check.
  549. * @returns {boolean} `true` if the token is a dot token.
  550. */
  551. function isDotToken(token) {
  552. return token.value === "." && token.type === "Punctuator";
  553. }
  554. /**
  555. * Checks if the given token is a `?.` token or not.
  556. * @param {Token} token The token to check.
  557. * @returns {boolean} `true` if the token is a `?.` token.
  558. */
  559. function isQuestionDotToken(token) {
  560. return token.value === "?." && token.type === "Punctuator";
  561. }
  562. /**
  563. * Checks if the given token is a semicolon token or not.
  564. * @param {Token} token The token to check.
  565. * @returns {boolean} `true` if the token is a semicolon token.
  566. */
  567. function isSemicolonToken(token) {
  568. return token.value === ";" && token.type === "Punctuator";
  569. }
  570. /**
  571. * Checks if the given token is a colon token or not.
  572. * @param {Token} token The token to check.
  573. * @returns {boolean} `true` if the token is a colon token.
  574. */
  575. function isColonToken(token) {
  576. return token.value === ":" && token.type === "Punctuator";
  577. }
  578. /**
  579. * Checks if the given token is an opening parenthesis token or not.
  580. * @param {Token} token The token to check.
  581. * @returns {boolean} `true` if the token is an opening parenthesis token.
  582. */
  583. function isOpeningParenToken(token) {
  584. return token.value === "(" && token.type === "Punctuator";
  585. }
  586. /**
  587. * Checks if the given token is a closing parenthesis token or not.
  588. * @param {Token} token The token to check.
  589. * @returns {boolean} `true` if the token is a closing parenthesis token.
  590. */
  591. function isClosingParenToken(token) {
  592. return token.value === ")" && token.type === "Punctuator";
  593. }
  594. /**
  595. * Checks if the given token is an opening square bracket token or not.
  596. * @param {Token} token The token to check.
  597. * @returns {boolean} `true` if the token is an opening square bracket token.
  598. */
  599. function isOpeningBracketToken(token) {
  600. return token.value === "[" && token.type === "Punctuator";
  601. }
  602. /**
  603. * Checks if the given token is a closing square bracket token or not.
  604. * @param {Token} token The token to check.
  605. * @returns {boolean} `true` if the token is a closing square bracket token.
  606. */
  607. function isClosingBracketToken(token) {
  608. return token.value === "]" && token.type === "Punctuator";
  609. }
  610. /**
  611. * Checks if the given token is an opening brace token or not.
  612. * @param {Token} token The token to check.
  613. * @returns {boolean} `true` if the token is an opening brace token.
  614. */
  615. function isOpeningBraceToken(token) {
  616. return token.value === "{" && token.type === "Punctuator";
  617. }
  618. /**
  619. * Checks if the given token is a closing brace token or not.
  620. * @param {Token} token The token to check.
  621. * @returns {boolean} `true` if the token is a closing brace token.
  622. */
  623. function isClosingBraceToken(token) {
  624. return token.value === "}" && token.type === "Punctuator";
  625. }
  626. /**
  627. * Checks if the given token is a comment token or not.
  628. * @param {Token} token The token to check.
  629. * @returns {boolean} `true` if the token is a comment token.
  630. */
  631. function isCommentToken(token) {
  632. return (
  633. token.type === "Line" ||
  634. token.type === "Block" ||
  635. token.type === "Shebang"
  636. );
  637. }
  638. /**
  639. * Checks if the given token is a keyword token or not.
  640. * @param {Token} token The token to check.
  641. * @returns {boolean} `true` if the token is a keyword token.
  642. */
  643. function isKeywordToken(token) {
  644. return token.type === "Keyword";
  645. }
  646. /**
  647. * Gets the `(` token of the given function node.
  648. * @param {ASTNode} node The function node to get.
  649. * @param {SourceCode} sourceCode The source code object to get tokens.
  650. * @returns {Token} `(` token.
  651. */
  652. function getOpeningParenOfParams(node, sourceCode) {
  653. // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param.
  654. if (node.type === "ArrowFunctionExpression" && node.params.length === 1) {
  655. const argToken = sourceCode.getFirstToken(node.params[0]);
  656. const maybeParenToken = sourceCode.getTokenBefore(argToken);
  657. return isOpeningParenToken(maybeParenToken)
  658. ? maybeParenToken
  659. : argToken;
  660. }
  661. // Otherwise, returns paren.
  662. return node.id
  663. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  664. : sourceCode.getFirstToken(node, isOpeningParenToken);
  665. }
  666. /**
  667. * Checks whether or not the tokens of two given nodes are same.
  668. * @param {ASTNode} left A node 1 to compare.
  669. * @param {ASTNode} right A node 2 to compare.
  670. * @param {SourceCode} sourceCode The ESLint source code object.
  671. * @returns {boolean} the source code for the given node.
  672. */
  673. function equalTokens(left, right, sourceCode) {
  674. const tokensL = sourceCode.getTokens(left);
  675. const tokensR = sourceCode.getTokens(right);
  676. if (tokensL.length !== tokensR.length) {
  677. return false;
  678. }
  679. for (let i = 0; i < tokensL.length; ++i) {
  680. if (
  681. tokensL[i].type !== tokensR[i].type ||
  682. tokensL[i].value !== tokensR[i].value
  683. ) {
  684. return false;
  685. }
  686. }
  687. return true;
  688. }
  689. /**
  690. * Check if the given node is a true logical expression or not.
  691. *
  692. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  693. * coalesce (`??`) are known as `ShortCircuitExpression`.
  694. * But ESTree represents those by `LogicalExpression` node.
  695. *
  696. * This function rejects coalesce expressions of `LogicalExpression` node.
  697. * @param {ASTNode} node The node to check.
  698. * @returns {boolean} `true` if the node is `&&` or `||`.
  699. * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression
  700. */
  701. function isLogicalExpression(node) {
  702. return (
  703. node.type === "LogicalExpression" &&
  704. (node.operator === "&&" || node.operator === "||")
  705. );
  706. }
  707. /**
  708. * Check if the given node is a nullish coalescing expression or not.
  709. *
  710. * The three binary expressions logical-or (`||`), logical-and (`&&`), and
  711. * coalesce (`??`) are known as `ShortCircuitExpression`.
  712. * But ESTree represents those by `LogicalExpression` node.
  713. *
  714. * This function finds only coalesce expressions of `LogicalExpression` node.
  715. * @param {ASTNode} node The node to check.
  716. * @returns {boolean} `true` if the node is `??`.
  717. */
  718. function isCoalesceExpression(node) {
  719. return node.type === "LogicalExpression" && node.operator === "??";
  720. }
  721. /**
  722. * Check if given two nodes are the pair of a logical expression and a coalesce expression.
  723. * @param {ASTNode} left A node to check.
  724. * @param {ASTNode} right Another node to check.
  725. * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression.
  726. */
  727. function isMixedLogicalAndCoalesceExpressions(left, right) {
  728. return (
  729. (isLogicalExpression(left) && isCoalesceExpression(right)) ||
  730. (isCoalesceExpression(left) && isLogicalExpression(right))
  731. );
  732. }
  733. /**
  734. * Checks if the given operator is a logical assignment operator.
  735. * @param {string} operator The operator to check.
  736. * @returns {boolean} `true` if the operator is a logical assignment operator.
  737. */
  738. function isLogicalAssignmentOperator(operator) {
  739. return LOGICAL_ASSIGNMENT_OPERATORS.has(operator);
  740. }
  741. /**
  742. * Get the colon token of the given SwitchCase node.
  743. * @param {ASTNode} node The SwitchCase node to get.
  744. * @param {SourceCode} sourceCode The source code object to get tokens.
  745. * @returns {Token} The colon token of the node.
  746. */
  747. function getSwitchCaseColonToken(node, sourceCode) {
  748. if (node.test) {
  749. return sourceCode.getTokenAfter(node.test, isColonToken);
  750. }
  751. return sourceCode.getFirstToken(node, 1);
  752. }
  753. /**
  754. * Gets ESM module export name represented by the given node.
  755. * @param {ASTNode} node `Identifier` or string `Literal` node in a position
  756. * that represents a module export name:
  757. * - `ImportSpecifier#imported`
  758. * - `ExportSpecifier#local` (if it is a re-export from another module)
  759. * - `ExportSpecifier#exported`
  760. * - `ExportAllDeclaration#exported`
  761. * @returns {string} The module export name.
  762. */
  763. function getModuleExportName(node) {
  764. if (node.type === "Identifier") {
  765. return node.name;
  766. }
  767. // string literal
  768. return node.value;
  769. }
  770. /**
  771. * Returns literal's value converted to the Boolean type
  772. * @param {ASTNode} node any `Literal` node
  773. * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy,
  774. * `null` when it cannot be determined.
  775. */
  776. function getBooleanValue(node) {
  777. if (node.value === null) {
  778. /*
  779. * it might be a null literal or bigint/regex literal in unsupported environments .
  780. * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral
  781. * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral
  782. */
  783. if (node.raw === "null") {
  784. return false;
  785. }
  786. // regex is always truthy
  787. if (typeof node.regex === "object") {
  788. return true;
  789. }
  790. return null;
  791. }
  792. return !!node.value;
  793. }
  794. /**
  795. * Checks if a branch node of LogicalExpression short circuits the whole condition
  796. * @param {ASTNode} node The branch of main condition which needs to be checked
  797. * @param {string} operator The operator of the main LogicalExpression.
  798. * @returns {boolean} true when condition short circuits whole condition
  799. */
  800. function isLogicalIdentity(node, operator) {
  801. switch (node.type) {
  802. case "Literal":
  803. return (
  804. (operator === "||" && getBooleanValue(node) === true) ||
  805. (operator === "&&" && getBooleanValue(node) === false)
  806. );
  807. case "UnaryExpression":
  808. return operator === "&&" && node.operator === "void";
  809. case "LogicalExpression":
  810. /*
  811. * handles `a && false || b`
  812. * `false` is an identity element of `&&` but not `||`
  813. */
  814. return (
  815. operator === node.operator &&
  816. (isLogicalIdentity(node.left, operator) ||
  817. isLogicalIdentity(node.right, operator))
  818. );
  819. case "AssignmentExpression":
  820. return (
  821. ["||=", "&&="].includes(node.operator) &&
  822. operator === node.operator.slice(0, -1) &&
  823. isLogicalIdentity(node.right, operator)
  824. );
  825. // no default
  826. }
  827. return false;
  828. }
  829. /**
  830. * Checks if an identifier is a reference to a global variable.
  831. * @param {Scope} scope The scope in which the identifier is referenced.
  832. * @param {ASTNode} node An identifier node to check.
  833. * @returns {boolean} `true` if the identifier is a reference to a global variable.
  834. */
  835. function isReferenceToGlobalVariable(scope, node) {
  836. const reference = scope.references.find(ref => ref.identifier === node);
  837. return Boolean(
  838. reference &&
  839. reference.resolved &&
  840. reference.resolved.scope.type === "global" &&
  841. reference.resolved.defs.length === 0,
  842. );
  843. }
  844. /**
  845. * Checks if a node has a constant truthiness value.
  846. * @param {Scope} scope Scope in which the node appears.
  847. * @param {ASTNode} node The AST node to check.
  848. * @param {boolean} inBooleanPosition `true` if checking the test of a
  849. * condition. `false` in all other cases. When `false`, checks if -- for
  850. * both string and number -- if coerced to that type, the value will
  851. * be constant.
  852. * @returns {boolean} true when node's truthiness is constant
  853. * @private
  854. */
  855. function isConstant(scope, node, inBooleanPosition) {
  856. // node.elements can return null values in the case of sparse arrays ex. [,]
  857. if (!node) {
  858. return true;
  859. }
  860. switch (node.type) {
  861. case "Literal":
  862. case "ArrowFunctionExpression":
  863. case "FunctionExpression":
  864. return true;
  865. case "ClassExpression":
  866. case "ObjectExpression":
  867. /**
  868. * In theory objects like:
  869. *
  870. * `{toString: () => a}`
  871. * `{valueOf: () => a}`
  872. *
  873. * Or a classes like:
  874. *
  875. * `class { static toString() { return a } }`
  876. * `class { static valueOf() { return a } }`
  877. *
  878. * Are not constant verifiably when `inBooleanPosition` is
  879. * false, but it's an edge case we've opted not to handle.
  880. */
  881. return true;
  882. case "TemplateLiteral":
  883. return (
  884. (inBooleanPosition &&
  885. node.quasis.some(quasi => quasi.value.cooked.length)) ||
  886. node.expressions.every(exp => isConstant(scope, exp, false))
  887. );
  888. case "ArrayExpression": {
  889. if (!inBooleanPosition) {
  890. return node.elements.every(element =>
  891. isConstant(scope, element, false),
  892. );
  893. }
  894. return true;
  895. }
  896. case "UnaryExpression":
  897. if (
  898. node.operator === "void" ||
  899. (node.operator === "typeof" && inBooleanPosition)
  900. ) {
  901. return true;
  902. }
  903. if (node.operator === "!") {
  904. return isConstant(scope, node.argument, true);
  905. }
  906. return isConstant(scope, node.argument, false);
  907. case "BinaryExpression":
  908. return (
  909. isConstant(scope, node.left, false) &&
  910. isConstant(scope, node.right, false) &&
  911. node.operator !== "in"
  912. );
  913. case "LogicalExpression": {
  914. const isLeftConstant = isConstant(
  915. scope,
  916. node.left,
  917. inBooleanPosition,
  918. );
  919. const isRightConstant = isConstant(
  920. scope,
  921. node.right,
  922. inBooleanPosition,
  923. );
  924. const isLeftShortCircuit =
  925. isLeftConstant && isLogicalIdentity(node.left, node.operator);
  926. const isRightShortCircuit =
  927. inBooleanPosition &&
  928. isRightConstant &&
  929. isLogicalIdentity(node.right, node.operator);
  930. return (
  931. (isLeftConstant && isRightConstant) ||
  932. isLeftShortCircuit ||
  933. isRightShortCircuit
  934. );
  935. }
  936. case "NewExpression":
  937. return inBooleanPosition;
  938. case "AssignmentExpression":
  939. if (node.operator === "=") {
  940. return isConstant(scope, node.right, inBooleanPosition);
  941. }
  942. if (["||=", "&&="].includes(node.operator) && inBooleanPosition) {
  943. return isLogicalIdentity(
  944. node.right,
  945. node.operator.slice(0, -1),
  946. );
  947. }
  948. return false;
  949. case "SequenceExpression":
  950. return isConstant(
  951. scope,
  952. node.expressions.at(-1),
  953. inBooleanPosition,
  954. );
  955. case "SpreadElement":
  956. return isConstant(scope, node.argument, inBooleanPosition);
  957. case "CallExpression":
  958. if (
  959. node.callee.type === "Identifier" &&
  960. node.callee.name === "Boolean"
  961. ) {
  962. if (
  963. node.arguments.length === 0 ||
  964. isConstant(scope, node.arguments[0], true)
  965. ) {
  966. return isReferenceToGlobalVariable(scope, node.callee);
  967. }
  968. }
  969. return false;
  970. case "Identifier":
  971. return (
  972. node.name === "undefined" &&
  973. isReferenceToGlobalVariable(scope, node)
  974. );
  975. // no default
  976. }
  977. return false;
  978. }
  979. /**
  980. * Checks whether a node is an ExpressionStatement at the top level of a file, function body, or TypeScript module block.
  981. * A top-level ExpressionStatement node is a directive if it contains a single unparenthesized
  982. * string literal and if it occurs either as the first sibling or immediately after another
  983. * directive.
  984. * @param {ASTNode} node The node to check.
  985. * @returns {boolean} Whether or not the node is an ExpressionStatement at the top level of a
  986. * file, function body, or TypeScript module block.
  987. */
  988. function isTopLevelExpressionStatement(node) {
  989. if (node.type !== "ExpressionStatement") {
  990. return false;
  991. }
  992. const parent = node.parent;
  993. return (
  994. parent.type === "Program" ||
  995. parent.type === "TSModuleBlock" ||
  996. (parent.type === "BlockStatement" && isFunction(parent.parent))
  997. );
  998. }
  999. /**
  1000. * Check whether the given node is a part of a directive prologue or not.
  1001. * @param {ASTNode} node The node to check.
  1002. * @returns {boolean} `true` if the node is a part of directive prologue.
  1003. */
  1004. function isDirective(node) {
  1005. return (
  1006. node.type === "ExpressionStatement" &&
  1007. typeof node.directive === "string"
  1008. );
  1009. }
  1010. /**
  1011. * Tests if a node appears at the beginning of an ancestor ExpressionStatement node.
  1012. * @param {ASTNode} node The node to check.
  1013. * @returns {boolean} Whether the node appears at the beginning of an ancestor ExpressionStatement node.
  1014. */
  1015. function isStartOfExpressionStatement(node) {
  1016. const start = node.range[0];
  1017. let ancestor = node;
  1018. while ((ancestor = ancestor.parent) && ancestor.range[0] === start) {
  1019. if (ancestor.type === "ExpressionStatement") {
  1020. return true;
  1021. }
  1022. }
  1023. return false;
  1024. }
  1025. /**
  1026. * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon.
  1027. * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at
  1028. * the start of the body of an `ArrowFunctionExpression`.
  1029. * @type {(sourceCode: SourceCode, node: ASTNode) => boolean}
  1030. * @param {SourceCode} sourceCode The source code object.
  1031. * @param {ASTNode} node A node at the position where an opening parenthesis or bracket will be inserted.
  1032. * @returns {boolean} Whether a semicolon is required before the opening parenthesis or bracket.
  1033. */
  1034. let needsPrecedingSemicolon;
  1035. {
  1036. const BREAK_OR_CONTINUE = new Set(["BreakStatement", "ContinueStatement"]);
  1037. // Declaration types that cannot be continued by a punctuator when ending with a string Literal that is a direct child.
  1038. const DECLARATIONS = new Set([
  1039. "ExportAllDeclaration",
  1040. "ExportNamedDeclaration",
  1041. "ImportDeclaration",
  1042. ]);
  1043. const IDENTIFIER_OR_KEYWORD = new Set(["Identifier", "Keyword"]);
  1044. // Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types.
  1045. const NODE_TYPES_BY_KEYWORD = {
  1046. __proto__: null,
  1047. break: "BreakStatement",
  1048. continue: "ContinueStatement",
  1049. debugger: "DebuggerStatement",
  1050. do: "DoWhileStatement",
  1051. else: "IfStatement",
  1052. return: "ReturnStatement",
  1053. yield: "YieldExpression",
  1054. };
  1055. /*
  1056. * Before an opening parenthesis, postfix `++` and `--` always trigger ASI;
  1057. * the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement.
  1058. */
  1059. const PUNCTUATORS = new Set([":", ";", "{", "=>", "++", "--"]);
  1060. /*
  1061. * Statements that can contain an `ExpressionStatement` after a closing parenthesis.
  1062. * DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis.
  1063. */
  1064. const STATEMENTS = new Set([
  1065. "DoWhileStatement",
  1066. "ForInStatement",
  1067. "ForOfStatement",
  1068. "ForStatement",
  1069. "IfStatement",
  1070. "WhileStatement",
  1071. "WithStatement",
  1072. ]);
  1073. const TS_TYPE_NODE_TYPES = new Set([
  1074. "TSAsExpression",
  1075. "TSSatisfiesExpression",
  1076. "TSTypeAliasDeclaration",
  1077. "TSTypeAnnotation",
  1078. ]);
  1079. /**
  1080. * Determines whether a specified node is inside a TypeScript type context.
  1081. * @param {ASTNode} node The node to check.
  1082. * @returns {boolean} Whether the node is inside a TypeScript type context.
  1083. */
  1084. function isInType(node) {
  1085. for (let currNode = node; ; ) {
  1086. const { parent } = currNode;
  1087. if (!parent) {
  1088. break;
  1089. }
  1090. if (
  1091. TS_TYPE_NODE_TYPES.has(parent.type) &&
  1092. currNode === parent.typeAnnotation
  1093. ) {
  1094. return true;
  1095. }
  1096. currNode = parent;
  1097. }
  1098. return false;
  1099. }
  1100. needsPrecedingSemicolon = function (sourceCode, node) {
  1101. const prevToken = sourceCode.getTokenBefore(node);
  1102. if (
  1103. !prevToken ||
  1104. (prevToken.type === "Punctuator" &&
  1105. PUNCTUATORS.has(prevToken.value))
  1106. ) {
  1107. return false;
  1108. }
  1109. const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
  1110. if (
  1111. prevNode.type === "TSDeclareFunction" ||
  1112. prevNode.parent.type === "TSImportEqualsDeclaration" ||
  1113. prevNode.parent.parent?.type === "TSImportEqualsDeclaration" ||
  1114. TS_TYPE_NODE_TYPES.has(prevNode.type) ||
  1115. isInType(prevNode)
  1116. ) {
  1117. return false;
  1118. }
  1119. if (isClosingParenToken(prevToken)) {
  1120. return !STATEMENTS.has(prevNode.type);
  1121. }
  1122. if (isClosingBraceToken(prevToken)) {
  1123. return (
  1124. (prevNode.type === "BlockStatement" &&
  1125. prevNode.parent.type === "FunctionExpression" &&
  1126. prevNode.parent.parent.type !== "MethodDefinition") ||
  1127. (prevNode.type === "ClassBody" &&
  1128. prevNode.parent.type === "ClassExpression") ||
  1129. prevNode.type === "ObjectExpression"
  1130. );
  1131. }
  1132. if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) {
  1133. if (
  1134. prevNode.parent.type === "VariableDeclarator" &&
  1135. !prevNode.parent.init
  1136. ) {
  1137. return false;
  1138. }
  1139. if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) {
  1140. return false;
  1141. }
  1142. const keyword = prevToken.value;
  1143. const nodeType = NODE_TYPES_BY_KEYWORD[keyword];
  1144. return prevNode.type !== nodeType;
  1145. }
  1146. if (prevToken.type === "String") {
  1147. return !DECLARATIONS.has(prevNode.parent.type);
  1148. }
  1149. return true;
  1150. };
  1151. }
  1152. /**
  1153. * Checks if a node is used as an import attribute key, either in a static or dynamic import.
  1154. * @param {ASTNode} node The node to check.
  1155. * @returns {boolean} Whether the node is used as an import attribute key.
  1156. */
  1157. function isImportAttributeKey(node) {
  1158. const { parent } = node;
  1159. // static import/re-export
  1160. if (parent.type === "ImportAttribute" && parent.key === node) {
  1161. return true;
  1162. }
  1163. // dynamic import
  1164. if (
  1165. parent.type === "Property" &&
  1166. !parent.computed &&
  1167. (parent.key === node ||
  1168. (parent.value === node && parent.shorthand && !parent.method)) &&
  1169. parent.parent.type === "ObjectExpression"
  1170. ) {
  1171. const objectExpression = parent.parent;
  1172. const objectExpressionParent = objectExpression.parent;
  1173. if (
  1174. objectExpressionParent.type === "ImportExpression" &&
  1175. objectExpressionParent.options === objectExpression
  1176. ) {
  1177. return true;
  1178. }
  1179. // nested key
  1180. if (
  1181. objectExpressionParent.type === "Property" &&
  1182. objectExpressionParent.value === objectExpression
  1183. ) {
  1184. return isImportAttributeKey(objectExpressionParent.key);
  1185. }
  1186. }
  1187. return false;
  1188. }
  1189. //------------------------------------------------------------------------------
  1190. // Public Interface
  1191. //------------------------------------------------------------------------------
  1192. module.exports = {
  1193. COMMENTS_IGNORE_PATTERN,
  1194. LINEBREAKS,
  1195. LINEBREAK_MATCHER: lineBreakPattern,
  1196. SHEBANG_MATCHER: shebangPattern,
  1197. STATEMENT_LIST_PARENTS,
  1198. ECMASCRIPT_GLOBALS,
  1199. /**
  1200. * Determines whether two adjacent tokens are on the same line.
  1201. * @param {Object} left The left token object.
  1202. * @param {Object} right The right token object.
  1203. * @returns {boolean} Whether or not the tokens are on the same line.
  1204. * @public
  1205. */
  1206. isTokenOnSameLine(left, right) {
  1207. return left.loc.end.line === right.loc.start.line;
  1208. },
  1209. isNullOrUndefined,
  1210. isCallee,
  1211. isES5Constructor,
  1212. getUpperFunction,
  1213. isFunction,
  1214. isLoop,
  1215. isInLoop,
  1216. isArrayFromMethod,
  1217. isParenthesised,
  1218. createGlobalLinebreakMatcher,
  1219. equalTokens,
  1220. isArrowToken,
  1221. isClosingBraceToken,
  1222. isClosingBracketToken,
  1223. isClosingParenToken,
  1224. isColonToken,
  1225. isCommaToken,
  1226. isCommentToken,
  1227. isDotToken,
  1228. isQuestionDotToken,
  1229. isKeywordToken,
  1230. isNotClosingBraceToken: negate(isClosingBraceToken),
  1231. isNotClosingBracketToken: negate(isClosingBracketToken),
  1232. isNotClosingParenToken: negate(isClosingParenToken),
  1233. isNotColonToken: negate(isColonToken),
  1234. isNotCommaToken: negate(isCommaToken),
  1235. isNotDotToken: negate(isDotToken),
  1236. isNotQuestionDotToken: negate(isQuestionDotToken),
  1237. isNotOpeningBraceToken: negate(isOpeningBraceToken),
  1238. isNotOpeningBracketToken: negate(isOpeningBracketToken),
  1239. isNotOpeningParenToken: negate(isOpeningParenToken),
  1240. isNotSemicolonToken: negate(isSemicolonToken),
  1241. isOpeningBraceToken,
  1242. isOpeningBracketToken,
  1243. isOpeningParenToken,
  1244. isSemicolonToken,
  1245. isEqToken,
  1246. /**
  1247. * Checks whether or not a given node is a string literal.
  1248. * @param {ASTNode} node A node to check.
  1249. * @returns {boolean} `true` if the node is a string literal.
  1250. */
  1251. isStringLiteral(node) {
  1252. return (
  1253. (node.type === "Literal" && typeof node.value === "string") ||
  1254. node.type === "TemplateLiteral"
  1255. );
  1256. },
  1257. /**
  1258. * Checks whether a given node is a breakable statement or not.
  1259. * The node is breakable if the node is one of the following type:
  1260. *
  1261. * - DoWhileStatement
  1262. * - ForInStatement
  1263. * - ForOfStatement
  1264. * - ForStatement
  1265. * - SwitchStatement
  1266. * - WhileStatement
  1267. * @param {ASTNode} node A node to check.
  1268. * @returns {boolean} `true` if the node is breakable.
  1269. */
  1270. isBreakableStatement(node) {
  1271. return breakableTypePattern.test(node.type);
  1272. },
  1273. /**
  1274. * Gets references which are non initializer and writable.
  1275. * @param {Reference[]} references An array of references.
  1276. * @returns {Reference[]} An array of only references which are non initializer and writable.
  1277. * @public
  1278. */
  1279. getModifyingReferences(references) {
  1280. return references.filter(isModifyingReference);
  1281. },
  1282. /**
  1283. * Validate that a string passed in is surrounded by the specified character
  1284. * @param {string} val The text to check.
  1285. * @param {string} character The character to see if it's surrounded by.
  1286. * @returns {boolean} True if the text is surrounded by the character, false if not.
  1287. * @private
  1288. */
  1289. isSurroundedBy(val, character) {
  1290. return val[0] === character && val.at(-1) === character;
  1291. },
  1292. /**
  1293. * Returns whether the provided node is an ESLint directive comment or not
  1294. * @param {Line|Block} node The comment token to be checked
  1295. * @returns {boolean} `true` if the node is an ESLint directive comment
  1296. */
  1297. isDirectiveComment(node) {
  1298. const comment = node.value.trim();
  1299. return (
  1300. (node.type === "Line" && comment.startsWith("eslint-")) ||
  1301. (node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment))
  1302. );
  1303. },
  1304. /**
  1305. * Gets the trailing statement of a given node.
  1306. *
  1307. * if (code)
  1308. * consequent;
  1309. *
  1310. * When taking this `IfStatement`, returns `consequent;` statement.
  1311. * @param {ASTNode} A node to get.
  1312. * @returns {ASTNode|null} The trailing statement's node.
  1313. */
  1314. getTrailingStatement: esutils.ast.trailingStatement,
  1315. /**
  1316. * Finds the variable by a given name in a given scope and its upper scopes.
  1317. * @param {eslint-scope.Scope} initScope A scope to start find.
  1318. * @param {string} name A variable name to find.
  1319. * @returns {eslint-scope.Variable|null} A found variable or `null`.
  1320. */
  1321. getVariableByName(initScope, name) {
  1322. let scope = initScope;
  1323. while (scope) {
  1324. const variable = scope.set.get(name);
  1325. if (variable) {
  1326. return variable;
  1327. }
  1328. scope = scope.upper;
  1329. }
  1330. return null;
  1331. },
  1332. /**
  1333. * Checks whether or not a given function node is the default `this` binding.
  1334. *
  1335. * First, this checks the node:
  1336. *
  1337. * - The given node is not in `PropertyDefinition#value` position.
  1338. * - The given node is not `StaticBlock`.
  1339. * - The function name does not start with uppercase. It's a convention to capitalize the names
  1340. * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
  1341. * - The function does not have a JSDoc comment that has a @this tag.
  1342. *
  1343. * Next, this checks the location of the node.
  1344. * If the location is below, this judges `this` is valid.
  1345. *
  1346. * - The location is not on an object literal.
  1347. * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
  1348. * functions only, as the name of the variable is considered to be the name of the function in this case.
  1349. * This check is not performed if `capIsConstructor` is set to `false`.
  1350. * - The location is not on an ES2015 class.
  1351. * - Its `bind`/`call`/`apply` method is not called directly.
  1352. * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
  1353. * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock`
  1354. * or any expression that is `PropertyDefinition#value` node.
  1355. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  1356. * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
  1357. * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
  1358. * @returns {boolean} The function node is the default `this` binding.
  1359. */
  1360. isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
  1361. /*
  1362. * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers.
  1363. * Therefore, A expression node at `PropertyDefinition#value` is a function.
  1364. * In this case, `this` is always not default binding.
  1365. */
  1366. if (
  1367. node.parent.type === "PropertyDefinition" &&
  1368. node.parent.value === node
  1369. ) {
  1370. return false;
  1371. }
  1372. // Class static blocks are implicit functions. In this case, `this` is always not default binding.
  1373. if (node.type === "StaticBlock") {
  1374. return false;
  1375. }
  1376. // Check if the function has a parameter named `this`.
  1377. if (
  1378. (node.type === "FunctionDeclaration" ||
  1379. node.type === "FunctionExpression") &&
  1380. node.params.some(
  1381. param => param.type === "Identifier" && param.name === "this",
  1382. )
  1383. ) {
  1384. return false;
  1385. }
  1386. if (
  1387. (capIsConstructor && isES5Constructor(node)) ||
  1388. hasJSDocThisTag(node, sourceCode)
  1389. ) {
  1390. return false;
  1391. }
  1392. const isAnonymous = node.id === null;
  1393. let currentNode = node;
  1394. while (currentNode) {
  1395. const parent = currentNode.parent;
  1396. switch (parent.type) {
  1397. /*
  1398. * Looks up the destination.
  1399. * e.g., obj.foo = nativeFoo || function foo() { ... };
  1400. */
  1401. case "LogicalExpression":
  1402. case "ConditionalExpression":
  1403. case "ChainExpression":
  1404. currentNode = parent;
  1405. break;
  1406. /*
  1407. * If the upper function is IIFE, checks the destination of the return value.
  1408. * e.g.
  1409. * obj.foo = (function() {
  1410. * // setup...
  1411. * return function foo() { ... };
  1412. * })();
  1413. * obj.foo = (() =>
  1414. * function foo() { ... }
  1415. * )();
  1416. */
  1417. case "ReturnStatement": {
  1418. const func = getUpperFunction(parent);
  1419. if (func === null || !isCallee(func)) {
  1420. return true;
  1421. }
  1422. currentNode = func.parent;
  1423. break;
  1424. }
  1425. case "ArrowFunctionExpression":
  1426. if (currentNode !== parent.body || !isCallee(parent)) {
  1427. return true;
  1428. }
  1429. currentNode = parent.parent;
  1430. break;
  1431. /*
  1432. * e.g.
  1433. * var obj = { foo() { ... } };
  1434. * var obj = { foo: function() { ... } };
  1435. * class A { constructor() { ... } }
  1436. * class A { foo() { ... } }
  1437. * class A { get foo() { ... } }
  1438. * class A { set foo() { ... } }
  1439. * class A { static foo() { ... } }
  1440. * class A { foo = function() { ... } }
  1441. */
  1442. case "Property":
  1443. case "PropertyDefinition":
  1444. case "MethodDefinition":
  1445. return parent.value !== currentNode;
  1446. /*
  1447. * e.g.
  1448. * obj.foo = function foo() { ... };
  1449. * Foo = function() { ... };
  1450. * [obj.foo = function foo() { ... }] = a;
  1451. * [Foo = function() { ... }] = a;
  1452. */
  1453. case "AssignmentExpression":
  1454. case "AssignmentPattern":
  1455. if (parent.left.type === "MemberExpression") {
  1456. return false;
  1457. }
  1458. if (
  1459. capIsConstructor &&
  1460. isAnonymous &&
  1461. parent.left.type === "Identifier" &&
  1462. startsWithUpperCase(parent.left.name)
  1463. ) {
  1464. return false;
  1465. }
  1466. return true;
  1467. /*
  1468. * e.g.
  1469. * var Foo = function() { ... };
  1470. */
  1471. case "VariableDeclarator":
  1472. return !(
  1473. capIsConstructor &&
  1474. isAnonymous &&
  1475. parent.init === currentNode &&
  1476. parent.id.type === "Identifier" &&
  1477. startsWithUpperCase(parent.id.name)
  1478. );
  1479. /*
  1480. * e.g.
  1481. * var foo = function foo() { ... }.bind(obj);
  1482. * (function foo() { ... }).call(obj);
  1483. * (function foo() { ... }).apply(obj, []);
  1484. */
  1485. case "MemberExpression":
  1486. if (
  1487. parent.object === currentNode &&
  1488. isSpecificMemberAccess(
  1489. parent,
  1490. null,
  1491. bindOrCallOrApplyPattern,
  1492. )
  1493. ) {
  1494. const maybeCalleeNode =
  1495. parent.parent.type === "ChainExpression"
  1496. ? parent.parent
  1497. : parent;
  1498. return !(
  1499. isCallee(maybeCalleeNode) &&
  1500. maybeCalleeNode.parent.arguments.length >= 1 &&
  1501. !isNullOrUndefined(
  1502. maybeCalleeNode.parent.arguments[0],
  1503. )
  1504. );
  1505. }
  1506. return true;
  1507. /*
  1508. * e.g.
  1509. * Reflect.apply(function() {}, obj, []);
  1510. * Array.from([], function() {}, obj);
  1511. * list.forEach(function() {}, obj);
  1512. */
  1513. case "CallExpression":
  1514. if (isReflectApply(parent.callee)) {
  1515. return (
  1516. parent.arguments.length !== 3 ||
  1517. parent.arguments[0] !== currentNode ||
  1518. isNullOrUndefined(parent.arguments[1])
  1519. );
  1520. }
  1521. if (isArrayFromMethod(parent.callee)) {
  1522. return (
  1523. parent.arguments.length !== 3 ||
  1524. parent.arguments[1] !== currentNode ||
  1525. isNullOrUndefined(parent.arguments[2])
  1526. );
  1527. }
  1528. if (isMethodWhichHasThisArg(parent.callee)) {
  1529. return (
  1530. parent.arguments.length !== 2 ||
  1531. parent.arguments[0] !== currentNode ||
  1532. isNullOrUndefined(parent.arguments[1])
  1533. );
  1534. }
  1535. return true;
  1536. // Otherwise `this` is default.
  1537. default:
  1538. return true;
  1539. }
  1540. }
  1541. /* c8 ignore next */
  1542. return true;
  1543. },
  1544. /**
  1545. * Get the precedence level based on the node type
  1546. * @param {ASTNode} node node to evaluate
  1547. * @returns {number} precedence level
  1548. * @private
  1549. */
  1550. getPrecedence(node) {
  1551. switch (node.type) {
  1552. case "SequenceExpression":
  1553. return 0;
  1554. case "AssignmentExpression":
  1555. case "ArrowFunctionExpression":
  1556. case "YieldExpression":
  1557. return 1;
  1558. case "ConditionalExpression":
  1559. return 3;
  1560. case "LogicalExpression":
  1561. switch (node.operator) {
  1562. case "||":
  1563. case "??":
  1564. return 4;
  1565. case "&&":
  1566. return 5;
  1567. // no default
  1568. }
  1569. /* falls through */
  1570. case "BinaryExpression":
  1571. switch (node.operator) {
  1572. case "|":
  1573. return 6;
  1574. case "^":
  1575. return 7;
  1576. case "&":
  1577. return 8;
  1578. case "==":
  1579. case "!=":
  1580. case "===":
  1581. case "!==":
  1582. return 9;
  1583. case "<":
  1584. case "<=":
  1585. case ">":
  1586. case ">=":
  1587. case "in":
  1588. case "instanceof":
  1589. return 10;
  1590. case "<<":
  1591. case ">>":
  1592. case ">>>":
  1593. return 11;
  1594. case "+":
  1595. case "-":
  1596. return 12;
  1597. case "*":
  1598. case "/":
  1599. case "%":
  1600. return 13;
  1601. case "**":
  1602. return 15;
  1603. // no default
  1604. }
  1605. /* falls through */
  1606. case "UnaryExpression":
  1607. case "AwaitExpression":
  1608. return 16;
  1609. case "UpdateExpression":
  1610. return 17;
  1611. case "CallExpression":
  1612. case "ChainExpression":
  1613. case "ImportExpression":
  1614. return 18;
  1615. case "NewExpression":
  1616. return 19;
  1617. default:
  1618. if (node.type in eslintVisitorKeys) {
  1619. return 20;
  1620. }
  1621. /*
  1622. * if the node is not a standard node that we know about, then assume it has the lowest precedence
  1623. * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of
  1624. * unwrapping them and potentially changing the meaning of the code or introducing a syntax error.
  1625. */
  1626. return -1;
  1627. }
  1628. },
  1629. /**
  1630. * Checks whether the given node is an empty block node or not.
  1631. * @param {ASTNode|null} node The node to check.
  1632. * @returns {boolean} `true` if the node is an empty block.
  1633. */
  1634. isEmptyBlock(node) {
  1635. return Boolean(
  1636. node && node.type === "BlockStatement" && node.body.length === 0,
  1637. );
  1638. },
  1639. /**
  1640. * Checks whether the given node is an empty function node or not.
  1641. * @param {ASTNode|null} node The node to check.
  1642. * @returns {boolean} `true` if the node is an empty function.
  1643. */
  1644. isEmptyFunction(node) {
  1645. return isFunction(node) && module.exports.isEmptyBlock(node.body);
  1646. },
  1647. /**
  1648. * Get directives from directive prologue of a Program or Function node.
  1649. * @param {ASTNode} node The node to check.
  1650. * @returns {ASTNode[]} The directives found in the directive prologue.
  1651. */
  1652. getDirectivePrologue(node) {
  1653. const directives = [];
  1654. // Directive prologues only occur at the top of files or functions.
  1655. if (
  1656. node.type === "Program" ||
  1657. node.type === "FunctionDeclaration" ||
  1658. node.type === "FunctionExpression" ||
  1659. /*
  1660. * Do not check arrow functions with implicit return.
  1661. * `() => "use strict";` returns the string `"use strict"`.
  1662. */
  1663. (node.type === "ArrowFunctionExpression" &&
  1664. node.body.type === "BlockStatement")
  1665. ) {
  1666. const statements =
  1667. node.type === "Program" ? node.body : node.body.body;
  1668. for (const statement of statements) {
  1669. if (
  1670. statement.type === "ExpressionStatement" &&
  1671. statement.expression.type === "Literal"
  1672. ) {
  1673. directives.push(statement);
  1674. } else {
  1675. break;
  1676. }
  1677. }
  1678. }
  1679. return directives;
  1680. },
  1681. /**
  1682. * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
  1683. * after the node will be parsed as a decimal point, rather than a property-access dot.
  1684. * @param {ASTNode} node The node to check.
  1685. * @returns {boolean} `true` if this node is a decimal integer.
  1686. * @example
  1687. *
  1688. * 0 // true
  1689. * 5 // true
  1690. * 50 // true
  1691. * 5_000 // true
  1692. * 1_234_56 // true
  1693. * 08 // true
  1694. * 0192 // true
  1695. * 5. // false
  1696. * .5 // false
  1697. * 5.0 // false
  1698. * 5.00_00 // false
  1699. * 05 // false
  1700. * 0x5 // false
  1701. * 0b101 // false
  1702. * 0b11_01 // false
  1703. * 0o5 // false
  1704. * 5e0 // false
  1705. * 5e1_000 // false
  1706. * 5n // false
  1707. * 1_000n // false
  1708. * "5" // false
  1709. *
  1710. */
  1711. isDecimalInteger(node) {
  1712. return (
  1713. node.type === "Literal" &&
  1714. typeof node.value === "number" &&
  1715. DECIMAL_INTEGER_PATTERN.test(node.raw)
  1716. );
  1717. },
  1718. /**
  1719. * Determines whether this token is a decimal integer numeric token.
  1720. * This is similar to isDecimalInteger(), but for tokens.
  1721. * @param {Token} token The token to check.
  1722. * @returns {boolean} `true` if this token is a decimal integer.
  1723. */
  1724. isDecimalIntegerNumericToken(token) {
  1725. return (
  1726. token.type === "Numeric" &&
  1727. DECIMAL_INTEGER_PATTERN.test(token.value)
  1728. );
  1729. },
  1730. /**
  1731. * Gets the name and kind of the given function node.
  1732. *
  1733. * - `function foo() {}` .................... `function 'foo'`
  1734. * - `(function foo() {})` .................. `function 'foo'`
  1735. * - `(function() {})` ...................... `function`
  1736. * - `function* foo() {}` ................... `generator function 'foo'`
  1737. * - `(function* foo() {})` ................. `generator function 'foo'`
  1738. * - `(function*() {})` ..................... `generator function`
  1739. * - `() => {}` ............................. `arrow function`
  1740. * - `async () => {}` ....................... `async arrow function`
  1741. * - `({ foo: function foo() {} })` ......... `method 'foo'`
  1742. * - `({ foo: function() {} })` ............. `method 'foo'`
  1743. * - `({ ['foo']: function() {} })` ......... `method 'foo'`
  1744. * - `({ [foo]: function() {} })` ........... `method`
  1745. * - `({ foo() {} })` ....................... `method 'foo'`
  1746. * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
  1747. * - `({ foo: function*() {} })` ............ `generator method 'foo'`
  1748. * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
  1749. * - `({ [foo]: function*() {} })` .......... `generator method`
  1750. * - `({ *foo() {} })` ...................... `generator method 'foo'`
  1751. * - `({ foo: async function foo() {} })` ... `async method 'foo'`
  1752. * - `({ foo: async function() {} })` ....... `async method 'foo'`
  1753. * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
  1754. * - `({ [foo]: async function() {} })` ..... `async method`
  1755. * - `({ async foo() {} })` ................. `async method 'foo'`
  1756. * - `({ get foo() {} })` ................... `getter 'foo'`
  1757. * - `({ set foo(a) {} })` .................. `setter 'foo'`
  1758. * - `class A { constructor() {} }` ......... `constructor`
  1759. * - `class A { foo() {} }` ................. `method 'foo'`
  1760. * - `class A { *foo() {} }` ................ `generator method 'foo'`
  1761. * - `class A { async foo() {} }` ........... `async method 'foo'`
  1762. * - `class A { ['foo']() {} }` ............. `method 'foo'`
  1763. * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
  1764. * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
  1765. * - `class A { [foo]() {} }` ............... `method`
  1766. * - `class A { *[foo]() {} }` .............. `generator method`
  1767. * - `class A { async [foo]() {} }` ......... `async method`
  1768. * - `class A { get foo() {} }` ............. `getter 'foo'`
  1769. * - `class A { set foo(a) {} }` ............ `setter 'foo'`
  1770. * - `class A { static foo() {} }` .......... `static method 'foo'`
  1771. * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
  1772. * - `class A { static async foo() {} }` .... `static async method 'foo'`
  1773. * - `class A { static get foo() {} }` ...... `static getter 'foo'`
  1774. * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
  1775. * - `class A { foo = () => {}; }` .......... `method 'foo'`
  1776. * - `class A { foo = function() {}; }` ..... `method 'foo'`
  1777. * - `class A { foo = function bar() {}; }` . `method 'foo'`
  1778. * - `class A { static foo = () => {}; }` ... `static method 'foo'`
  1779. * - `class A { '#foo' = () => {}; }` ....... `method '#foo'`
  1780. * - `class A { #foo = () => {}; }` ......... `private method #foo`
  1781. * - `class A { static #foo = () => {}; }` .. `static private method #foo`
  1782. * - `class A { '#foo'() {} }` .............. `method '#foo'`
  1783. * - `class A { #foo() {} }` ................ `private method #foo`
  1784. * - `class A { static #foo() {} }` ......... `static private method #foo`
  1785. * @param {ASTNode} node The function node to get.
  1786. * @returns {string} The name and kind of the function node.
  1787. */
  1788. getFunctionNameWithKind(node) {
  1789. const parent = node.parent;
  1790. const tokens = [];
  1791. if (
  1792. parent.type === "MethodDefinition" ||
  1793. parent.type === "PropertyDefinition" ||
  1794. node.type === "TSPropertySignature" ||
  1795. node.type === "TSMethodSignature"
  1796. ) {
  1797. // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features
  1798. if (parent.static) {
  1799. tokens.push("static");
  1800. }
  1801. if (!parent.computed && parent.key?.type === "PrivateIdentifier") {
  1802. tokens.push("private");
  1803. }
  1804. }
  1805. if (node.async) {
  1806. tokens.push("async");
  1807. }
  1808. if (node.generator) {
  1809. tokens.push("generator");
  1810. }
  1811. if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1812. if (parent.kind === "constructor") {
  1813. return "constructor";
  1814. }
  1815. if (parent.kind === "get") {
  1816. tokens.push("getter");
  1817. } else if (parent.kind === "set") {
  1818. tokens.push("setter");
  1819. } else {
  1820. tokens.push("method");
  1821. }
  1822. } else if (node.type === "TSMethodSignature") {
  1823. if (node.kind === "get") {
  1824. tokens.push("getter");
  1825. } else if (node.kind === "set") {
  1826. tokens.push("setter");
  1827. } else {
  1828. tokens.push("method");
  1829. }
  1830. } else if (parent.type === "PropertyDefinition") {
  1831. tokens.push("method");
  1832. } else {
  1833. if (node.type === "ArrowFunctionExpression") {
  1834. tokens.push("arrow");
  1835. }
  1836. tokens.push("function");
  1837. }
  1838. if (
  1839. parent.type === "Property" ||
  1840. parent.type === "MethodDefinition" ||
  1841. parent.type === "PropertyDefinition"
  1842. ) {
  1843. if (!parent.computed && parent.key.type === "PrivateIdentifier") {
  1844. tokens.push(`#${parent.key.name}`);
  1845. } else {
  1846. const name = getStaticPropertyName(parent);
  1847. if (name !== null) {
  1848. tokens.push(`'${name}'`);
  1849. } else if (node.id) {
  1850. tokens.push(`'${node.id.name}'`);
  1851. }
  1852. }
  1853. } else if (node.type === "TSMethodSignature") {
  1854. tokens.push(`'${getStaticPropertyName(node)}'`);
  1855. } else if (node.id) {
  1856. tokens.push(`'${node.id.name}'`);
  1857. }
  1858. return tokens.join(" ");
  1859. },
  1860. /**
  1861. * Gets the location of the given function node for reporting.
  1862. *
  1863. * - `function foo() {}`
  1864. * ^^^^^^^^^^^^
  1865. * - `(function foo() {})`
  1866. * ^^^^^^^^^^^^
  1867. * - `(function() {})`
  1868. * ^^^^^^^^
  1869. * - `function* foo() {}`
  1870. * ^^^^^^^^^^^^^
  1871. * - `(function* foo() {})`
  1872. * ^^^^^^^^^^^^^
  1873. * - `(function*() {})`
  1874. * ^^^^^^^^^
  1875. * - `() => {}`
  1876. * ^^
  1877. * - `async () => {}`
  1878. * ^^
  1879. * - `({ foo: function foo() {} })`
  1880. * ^^^^^^^^^^^^^^^^^
  1881. * - `({ foo: function() {} })`
  1882. * ^^^^^^^^^^^^^
  1883. * - `({ ['foo']: function() {} })`
  1884. * ^^^^^^^^^^^^^^^^^
  1885. * - `({ [foo]: function() {} })`
  1886. * ^^^^^^^^^^^^^^^
  1887. * - `({ foo() {} })`
  1888. * ^^^
  1889. * - `({ foo: function* foo() {} })`
  1890. * ^^^^^^^^^^^^^^^^^^
  1891. * - `({ foo: function*() {} })`
  1892. * ^^^^^^^^^^^^^^
  1893. * - `({ ['foo']: function*() {} })`
  1894. * ^^^^^^^^^^^^^^^^^^
  1895. * - `({ [foo]: function*() {} })`
  1896. * ^^^^^^^^^^^^^^^^
  1897. * - `({ *foo() {} })`
  1898. * ^^^^
  1899. * - `({ foo: async function foo() {} })`
  1900. * ^^^^^^^^^^^^^^^^^^^^^^^
  1901. * - `({ foo: async function() {} })`
  1902. * ^^^^^^^^^^^^^^^^^^^
  1903. * - `({ ['foo']: async function() {} })`
  1904. * ^^^^^^^^^^^^^^^^^^^^^^^
  1905. * - `({ [foo]: async function() {} })`
  1906. * ^^^^^^^^^^^^^^^^^^^^^
  1907. * - `({ async foo() {} })`
  1908. * ^^^^^^^^^
  1909. * - `({ get foo() {} })`
  1910. * ^^^^^^^
  1911. * - `({ set foo(a) {} })`
  1912. * ^^^^^^^
  1913. * - `class A { constructor() {} }`
  1914. * ^^^^^^^^^^^
  1915. * - `class A { foo() {} }`
  1916. * ^^^
  1917. * - `class A { *foo() {} }`
  1918. * ^^^^
  1919. * - `class A { async foo() {} }`
  1920. * ^^^^^^^^^
  1921. * - `class A { ['foo']() {} }`
  1922. * ^^^^^^^
  1923. * - `class A { *['foo']() {} }`
  1924. * ^^^^^^^^
  1925. * - `class A { async ['foo']() {} }`
  1926. * ^^^^^^^^^^^^^
  1927. * - `class A { [foo]() {} }`
  1928. * ^^^^^
  1929. * - `class A { *[foo]() {} }`
  1930. * ^^^^^^
  1931. * - `class A { async [foo]() {} }`
  1932. * ^^^^^^^^^^^
  1933. * - `class A { get foo() {} }`
  1934. * ^^^^^^^
  1935. * - `class A { set foo(a) {} }`
  1936. * ^^^^^^^
  1937. * - `class A { static foo() {} }`
  1938. * ^^^^^^^^^^
  1939. * - `class A { static *foo() {} }`
  1940. * ^^^^^^^^^^^
  1941. * - `class A { static async foo() {} }`
  1942. * ^^^^^^^^^^^^^^^^
  1943. * - `class A { static get foo() {} }`
  1944. * ^^^^^^^^^^^^^^
  1945. * - `class A { static set foo(a) {} }`
  1946. * ^^^^^^^^^^^^^^
  1947. * - `class A { foo = function() {} }`
  1948. * ^^^^^^^^^^^^^^
  1949. * - `class A { static foo = function() {} }`
  1950. * ^^^^^^^^^^^^^^^^^^^^^
  1951. * - `class A { foo = (a, b) => {} }`
  1952. * ^^^^^^
  1953. * @param {ASTNode} node The function node to get.
  1954. * @param {SourceCode} sourceCode The source code object to get tokens.
  1955. * @returns {string} The location of the function node for reporting.
  1956. */
  1957. getFunctionHeadLoc(node, sourceCode) {
  1958. const parent = node.parent;
  1959. let start;
  1960. let end;
  1961. if (
  1962. parent.type === "Property" ||
  1963. parent.type === "MethodDefinition" ||
  1964. parent.type === "PropertyDefinition" ||
  1965. parent.type === "TSPropertySignature" ||
  1966. parent.type === "TSMethodSignature"
  1967. ) {
  1968. start = parent.loc.start;
  1969. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1970. } else if (node.type === "ArrowFunctionExpression") {
  1971. const arrowToken = sourceCode.getTokenBefore(
  1972. node.body,
  1973. isArrowToken,
  1974. );
  1975. start = arrowToken.loc.start;
  1976. end = arrowToken.loc.end;
  1977. } else {
  1978. start = node.loc.start;
  1979. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1980. }
  1981. return {
  1982. start: Object.assign({}, start),
  1983. end: Object.assign({}, end),
  1984. };
  1985. },
  1986. /**
  1987. * Gets next location when the result is not out of bound, otherwise returns null.
  1988. *
  1989. * Assumptions:
  1990. *
  1991. * - The given location represents a valid location in the given source code.
  1992. * - Columns are 0-based.
  1993. * - Lines are 1-based.
  1994. * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
  1995. * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
  1996. * The start (column 0) of that extra line is considered to be a valid location.
  1997. *
  1998. * Examples of successive locations (line, column):
  1999. *
  2000. * code: foo
  2001. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
  2002. *
  2003. * code: foo<LF>
  2004. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  2005. *
  2006. * code: foo<CR><LF>
  2007. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  2008. *
  2009. * code: a<LF>b
  2010. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
  2011. *
  2012. * code: a<LF>b<LF>
  2013. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  2014. *
  2015. * code: a<CR><LF>b<CR><LF>
  2016. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  2017. *
  2018. * code: a<LF><LF>
  2019. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
  2020. *
  2021. * code: <LF>
  2022. * locations: (1, 0) -> (2, 0) -> null
  2023. *
  2024. * code:
  2025. * locations: (1, 0) -> null
  2026. * @param {SourceCode} sourceCode The sourceCode
  2027. * @param {{line: number, column: number}} location The location
  2028. * @returns {{line: number, column: number} | null} Next location
  2029. */
  2030. getNextLocation(sourceCode, { line, column }) {
  2031. if (column < sourceCode.lines[line - 1].length) {
  2032. return {
  2033. line,
  2034. column: column + 1,
  2035. };
  2036. }
  2037. if (line < sourceCode.lines.length) {
  2038. return {
  2039. line: line + 1,
  2040. column: 0,
  2041. };
  2042. }
  2043. return null;
  2044. },
  2045. /**
  2046. * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
  2047. * surrounding the node.
  2048. * @param {SourceCode} sourceCode The source code object
  2049. * @param {ASTNode} node An expression node
  2050. * @returns {string} The text representing the node, with all surrounding parentheses included
  2051. */
  2052. getParenthesisedText(sourceCode, node) {
  2053. let leftToken = sourceCode.getFirstToken(node);
  2054. let rightToken = sourceCode.getLastToken(node);
  2055. while (
  2056. sourceCode.getTokenBefore(leftToken) &&
  2057. sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
  2058. sourceCode.getTokenBefore(leftToken).value === "(" &&
  2059. sourceCode.getTokenAfter(rightToken) &&
  2060. sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
  2061. sourceCode.getTokenAfter(rightToken).value === ")"
  2062. ) {
  2063. leftToken = sourceCode.getTokenBefore(leftToken);
  2064. rightToken = sourceCode.getTokenAfter(rightToken);
  2065. }
  2066. return sourceCode
  2067. .getText()
  2068. .slice(leftToken.range[0], rightToken.range[1]);
  2069. },
  2070. /**
  2071. * Determine if a node has a possibility to be an Error object
  2072. * @param {ASTNode} node ASTNode to check
  2073. * @returns {boolean} True if there is a chance it contains an Error obj
  2074. */
  2075. couldBeError(node) {
  2076. switch (node.type) {
  2077. case "Identifier":
  2078. case "CallExpression":
  2079. case "NewExpression":
  2080. case "MemberExpression":
  2081. case "TaggedTemplateExpression":
  2082. case "YieldExpression":
  2083. case "AwaitExpression":
  2084. case "ChainExpression":
  2085. return true; // possibly an error object.
  2086. case "AssignmentExpression":
  2087. if (["=", "&&="].includes(node.operator)) {
  2088. return module.exports.couldBeError(node.right);
  2089. }
  2090. if (["||=", "??="].includes(node.operator)) {
  2091. return (
  2092. module.exports.couldBeError(node.left) ||
  2093. module.exports.couldBeError(node.right)
  2094. );
  2095. }
  2096. /**
  2097. * All other assignment operators are mathematical assignment operators (arithmetic or bitwise).
  2098. * An assignment expression with a mathematical operator can either evaluate to a primitive value,
  2099. * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object.
  2100. */
  2101. return false;
  2102. case "SequenceExpression": {
  2103. const exprs = node.expressions;
  2104. return (
  2105. exprs.length !== 0 &&
  2106. module.exports.couldBeError(exprs.at(-1))
  2107. );
  2108. }
  2109. case "LogicalExpression":
  2110. /*
  2111. * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it
  2112. * doesn't short-circuit, it takes the value from the right side, so the right side must always be
  2113. * a plausible error. A future improvement could verify that the left side could be truthy by
  2114. * excluding falsy literals.
  2115. */
  2116. if (node.operator === "&&") {
  2117. return module.exports.couldBeError(node.right);
  2118. }
  2119. return (
  2120. module.exports.couldBeError(node.left) ||
  2121. module.exports.couldBeError(node.right)
  2122. );
  2123. case "ConditionalExpression":
  2124. return (
  2125. module.exports.couldBeError(node.consequent) ||
  2126. module.exports.couldBeError(node.alternate)
  2127. );
  2128. default:
  2129. return false;
  2130. }
  2131. },
  2132. /**
  2133. * Check if a given node is a numeric literal or not.
  2134. * @param {ASTNode} node The node to check.
  2135. * @returns {boolean} `true` if the node is a number or bigint literal.
  2136. */
  2137. isNumericLiteral(node) {
  2138. return (
  2139. node.type === "Literal" &&
  2140. (typeof node.value === "number" || Boolean(node.bigint))
  2141. );
  2142. },
  2143. /**
  2144. * Determines whether two tokens can safely be placed next to each other without merging into a single token
  2145. * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
  2146. * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
  2147. * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
  2148. * next to each other, behavior is undefined (although it should return `true` in most cases).
  2149. */
  2150. canTokensBeAdjacent(leftValue, rightValue) {
  2151. const espreeOptions = {
  2152. ecmaVersion: espree.latestEcmaVersion,
  2153. comment: true,
  2154. range: true,
  2155. };
  2156. let leftToken;
  2157. if (typeof leftValue === "string") {
  2158. let tokens;
  2159. try {
  2160. tokens = espree.tokenize(leftValue, espreeOptions);
  2161. } catch {
  2162. return false;
  2163. }
  2164. const comments = tokens.comments;
  2165. leftToken = tokens.at(-1);
  2166. if (comments.length) {
  2167. const lastComment = comments.at(-1);
  2168. if (!leftToken || lastComment.range[0] > leftToken.range[0]) {
  2169. leftToken = lastComment;
  2170. }
  2171. }
  2172. } else {
  2173. leftToken = leftValue;
  2174. }
  2175. /*
  2176. * If a hashbang comment was passed as a token object from SourceCode,
  2177. * its type will be "Shebang" because of the way ESLint itself handles hashbangs.
  2178. * If a hashbang comment was passed in a string and then tokenized in this function,
  2179. * its type will be "Hashbang" because of the way Espree tokenizes hashbangs.
  2180. */
  2181. if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") {
  2182. return false;
  2183. }
  2184. let rightToken;
  2185. if (typeof rightValue === "string") {
  2186. let tokens;
  2187. try {
  2188. tokens = espree.tokenize(rightValue, espreeOptions);
  2189. } catch {
  2190. return false;
  2191. }
  2192. const comments = tokens.comments;
  2193. rightToken = tokens[0];
  2194. if (comments.length) {
  2195. const firstComment = comments[0];
  2196. if (
  2197. !rightToken ||
  2198. firstComment.range[0] < rightToken.range[0]
  2199. ) {
  2200. rightToken = firstComment;
  2201. }
  2202. }
  2203. } else {
  2204. rightToken = rightValue;
  2205. }
  2206. if (
  2207. leftToken.type === "Punctuator" ||
  2208. rightToken.type === "Punctuator"
  2209. ) {
  2210. if (
  2211. leftToken.type === "Punctuator" &&
  2212. rightToken.type === "Punctuator"
  2213. ) {
  2214. const PLUS_TOKENS = new Set(["+", "++"]);
  2215. const MINUS_TOKENS = new Set(["-", "--"]);
  2216. return !(
  2217. (PLUS_TOKENS.has(leftToken.value) &&
  2218. PLUS_TOKENS.has(rightToken.value)) ||
  2219. (MINUS_TOKENS.has(leftToken.value) &&
  2220. MINUS_TOKENS.has(rightToken.value))
  2221. );
  2222. }
  2223. if (leftToken.type === "Punctuator" && leftToken.value === "/") {
  2224. return !["Block", "Line", "RegularExpression"].includes(
  2225. rightToken.type,
  2226. );
  2227. }
  2228. return true;
  2229. }
  2230. if (
  2231. leftToken.type === "String" ||
  2232. rightToken.type === "String" ||
  2233. leftToken.type === "Template" ||
  2234. rightToken.type === "Template"
  2235. ) {
  2236. return true;
  2237. }
  2238. if (
  2239. leftToken.type !== "Numeric" &&
  2240. rightToken.type === "Numeric" &&
  2241. rightToken.value.startsWith(".")
  2242. ) {
  2243. return true;
  2244. }
  2245. if (
  2246. leftToken.type === "Block" ||
  2247. rightToken.type === "Block" ||
  2248. rightToken.type === "Line"
  2249. ) {
  2250. return true;
  2251. }
  2252. if (rightToken.type === "PrivateIdentifier") {
  2253. return true;
  2254. }
  2255. return false;
  2256. },
  2257. /**
  2258. * Get the `loc` object of a given name in a `/*globals` directive comment.
  2259. * @param {SourceCode} sourceCode The source code to convert index to loc.
  2260. * @param {Comment} comment The `/*globals` directive comment which include the name.
  2261. * @param {string} name The name to find.
  2262. * @returns {SourceLocation} The `loc` object.
  2263. */
  2264. getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
  2265. const namePattern = new RegExp(
  2266. `[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`,
  2267. "gu",
  2268. );
  2269. // To ignore the first text "global".
  2270. namePattern.lastIndex = comment.value.indexOf("global") + 6;
  2271. // Search a given variable name.
  2272. const match = namePattern.exec(comment.value);
  2273. // Convert the index to loc.
  2274. const start = sourceCode.getLocFromIndex(
  2275. comment.range[0] + "/*".length + (match ? match.index + 1 : 0),
  2276. );
  2277. const end = {
  2278. line: start.line,
  2279. column: start.column + (match ? name.length : 1),
  2280. };
  2281. return { start, end };
  2282. },
  2283. /**
  2284. * Determines whether the given raw string contains an octal escape sequence
  2285. * or a non-octal decimal escape sequence ("\8", "\9").
  2286. *
  2287. * "\1", "\2" ... "\7", "\8", "\9"
  2288. * "\00", "\01" ... "\07", "\08", "\09"
  2289. *
  2290. * "\0", when not followed by a digit, is not an octal escape sequence.
  2291. * @param {string} rawString A string in its raw representation.
  2292. * @returns {boolean} `true` if the string contains at least one octal escape sequence
  2293. * or at least one non-octal decimal escape sequence.
  2294. */
  2295. hasOctalOrNonOctalDecimalEscapeSequence(rawString) {
  2296. return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString);
  2297. },
  2298. /**
  2299. * Determines whether the given node is a template literal without expressions.
  2300. * @param {ASTNode} node Node to check.
  2301. * @returns {boolean} True if the node is a template literal without expressions.
  2302. */
  2303. isStaticTemplateLiteral(node) {
  2304. return node.type === "TemplateLiteral" && node.expressions.length === 0;
  2305. },
  2306. /**
  2307. * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
  2308. * The braces, which make the given block body, are necessary in either of the following situations:
  2309. *
  2310. * 1. The statement is a lexical declaration.
  2311. * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
  2312. *
  2313. * if (a) {
  2314. * if (b)
  2315. * foo();
  2316. * }
  2317. * else
  2318. * bar();
  2319. *
  2320. * if (a)
  2321. * while (b)
  2322. * while (c) {
  2323. * while (d)
  2324. * if (e)
  2325. * while(f)
  2326. * foo();
  2327. * }
  2328. * else
  2329. * bar();
  2330. * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
  2331. * @param {SourceCode} sourceCode The source code
  2332. * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
  2333. * would change the semantics of the code or produce a syntax error.
  2334. */
  2335. areBracesNecessary(node, sourceCode) {
  2336. /**
  2337. * Determines if the given node is a lexical declaration (let, const, using, await using, function, or class)
  2338. * @param {ASTNode} nodeToCheck The node to check
  2339. * @returns {boolean} True if the node is a lexical declaration
  2340. * @private
  2341. */
  2342. function isLexicalDeclaration(nodeToCheck) {
  2343. if (nodeToCheck.type === "VariableDeclaration") {
  2344. return LEXICAL_DECLARATION_KINDS.has(nodeToCheck.kind);
  2345. }
  2346. return (
  2347. nodeToCheck.type === "FunctionDeclaration" ||
  2348. nodeToCheck.type === "ClassDeclaration"
  2349. );
  2350. }
  2351. /**
  2352. * Checks if the given token is an `else` token or not.
  2353. * @param {Token} token The token to check.
  2354. * @returns {boolean} `true` if the token is an `else` token.
  2355. */
  2356. function isElseKeywordToken(token) {
  2357. return token.value === "else" && token.type === "Keyword";
  2358. }
  2359. /**
  2360. * Determines whether the given node has an `else` keyword token as the first token after.
  2361. * @param {ASTNode} nodeToCheck The node to check.
  2362. * @returns {boolean} `true` if the node is followed by an `else` keyword token.
  2363. */
  2364. function isFollowedByElseKeyword(nodeToCheck) {
  2365. const nextToken = sourceCode.getTokenAfter(nodeToCheck);
  2366. return Boolean(nextToken) && isElseKeywordToken(nextToken);
  2367. }
  2368. /**
  2369. * Determines whether the code represented by the given node contains an `if` statement
  2370. * that would become associated with an `else` keyword directly appended to that code.
  2371. *
  2372. * Examples where it returns `true`:
  2373. *
  2374. * if (a)
  2375. * foo();
  2376. *
  2377. * if (a) {
  2378. * foo();
  2379. * }
  2380. *
  2381. * if (a)
  2382. * foo();
  2383. * else if (b)
  2384. * bar();
  2385. *
  2386. * while (a)
  2387. * if (b)
  2388. * if(c)
  2389. * foo();
  2390. * else
  2391. * bar();
  2392. *
  2393. * Examples where it returns `false`:
  2394. *
  2395. * if (a)
  2396. * foo();
  2397. * else
  2398. * bar();
  2399. *
  2400. * while (a) {
  2401. * if (b)
  2402. * if(c)
  2403. * foo();
  2404. * else
  2405. * bar();
  2406. * }
  2407. *
  2408. * while (a)
  2409. * if (b) {
  2410. * if(c)
  2411. * foo();
  2412. * }
  2413. * else
  2414. * bar();
  2415. * @param {ASTNode} nodeToCheck Node representing the code to check.
  2416. * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
  2417. */
  2418. function hasUnsafeIf(nodeToCheck) {
  2419. switch (nodeToCheck.type) {
  2420. case "IfStatement":
  2421. if (!nodeToCheck.alternate) {
  2422. return true;
  2423. }
  2424. return hasUnsafeIf(nodeToCheck.alternate);
  2425. case "ForStatement":
  2426. case "ForInStatement":
  2427. case "ForOfStatement":
  2428. case "LabeledStatement":
  2429. case "WithStatement":
  2430. case "WhileStatement":
  2431. return hasUnsafeIf(nodeToCheck.body);
  2432. default:
  2433. return false;
  2434. }
  2435. }
  2436. const statement = node.body[0];
  2437. return (
  2438. isLexicalDeclaration(statement) ||
  2439. (hasUnsafeIf(statement) && isFollowedByElseKeyword(node))
  2440. );
  2441. },
  2442. isReferenceToGlobalVariable,
  2443. isLogicalExpression,
  2444. isCoalesceExpression,
  2445. isMixedLogicalAndCoalesceExpressions,
  2446. isNullLiteral,
  2447. getStaticStringValue,
  2448. getStaticPropertyName,
  2449. skipChainExpression,
  2450. isSpecificId,
  2451. isSpecificMemberAccess,
  2452. equalLiteralValue,
  2453. isSameReference,
  2454. isLogicalAssignmentOperator,
  2455. getSwitchCaseColonToken,
  2456. getModuleExportName,
  2457. isConstant,
  2458. isTopLevelExpressionStatement,
  2459. isDirective,
  2460. isStartOfExpressionStatement,
  2461. needsPrecedingSemicolon,
  2462. isImportAttributeKey,
  2463. getOpeningParenOfParams,
  2464. };