ast-utils.js 79 KB

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