ast-utils.js 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476
  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 cannot be continued by a punctuator when ending with a string Literal that is a direct child.
  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. * Checks if a node is used as an import attribute key, either in a static or dynamic import.
  984. * @param {ASTNode} node The node to check.
  985. * @returns {boolean} Whether the node is used as an import attribute key.
  986. */
  987. function isImportAttributeKey(node) {
  988. const { parent } = node;
  989. // static import/re-export
  990. if (parent.type === "ImportAttribute" && parent.key === node) {
  991. return true;
  992. }
  993. // dynamic import
  994. if (
  995. parent.type === "Property" &&
  996. !parent.computed &&
  997. (parent.key === node || parent.value === node && parent.shorthand && !parent.method) &&
  998. parent.parent.type === "ObjectExpression"
  999. ) {
  1000. const objectExpression = parent.parent;
  1001. const objectExpressionParent = objectExpression.parent;
  1002. if (
  1003. objectExpressionParent.type === "ImportExpression" &&
  1004. objectExpressionParent.options === objectExpression
  1005. ) {
  1006. return true;
  1007. }
  1008. // nested key
  1009. if (
  1010. objectExpressionParent.type === "Property" &&
  1011. objectExpressionParent.value === objectExpression
  1012. ) {
  1013. return isImportAttributeKey(objectExpressionParent.key);
  1014. }
  1015. }
  1016. return false;
  1017. }
  1018. //------------------------------------------------------------------------------
  1019. // Public Interface
  1020. //------------------------------------------------------------------------------
  1021. module.exports = {
  1022. COMMENTS_IGNORE_PATTERN,
  1023. LINEBREAKS,
  1024. LINEBREAK_MATCHER: lineBreakPattern,
  1025. SHEBANG_MATCHER: shebangPattern,
  1026. STATEMENT_LIST_PARENTS,
  1027. ECMASCRIPT_GLOBALS,
  1028. /**
  1029. * Determines whether two adjacent tokens are on the same line.
  1030. * @param {Object} left The left token object.
  1031. * @param {Object} right The right token object.
  1032. * @returns {boolean} Whether or not the tokens are on the same line.
  1033. * @public
  1034. */
  1035. isTokenOnSameLine(left, right) {
  1036. return left.loc.end.line === right.loc.start.line;
  1037. },
  1038. isNullOrUndefined,
  1039. isCallee,
  1040. isES5Constructor,
  1041. getUpperFunction,
  1042. isFunction,
  1043. isLoop,
  1044. isInLoop,
  1045. isArrayFromMethod,
  1046. isParenthesised,
  1047. createGlobalLinebreakMatcher,
  1048. equalTokens,
  1049. isArrowToken,
  1050. isClosingBraceToken,
  1051. isClosingBracketToken,
  1052. isClosingParenToken,
  1053. isColonToken,
  1054. isCommaToken,
  1055. isCommentToken,
  1056. isDotToken,
  1057. isQuestionDotToken,
  1058. isKeywordToken,
  1059. isNotClosingBraceToken: negate(isClosingBraceToken),
  1060. isNotClosingBracketToken: negate(isClosingBracketToken),
  1061. isNotClosingParenToken: negate(isClosingParenToken),
  1062. isNotColonToken: negate(isColonToken),
  1063. isNotCommaToken: negate(isCommaToken),
  1064. isNotDotToken: negate(isDotToken),
  1065. isNotQuestionDotToken: negate(isQuestionDotToken),
  1066. isNotOpeningBraceToken: negate(isOpeningBraceToken),
  1067. isNotOpeningBracketToken: negate(isOpeningBracketToken),
  1068. isNotOpeningParenToken: negate(isOpeningParenToken),
  1069. isNotSemicolonToken: negate(isSemicolonToken),
  1070. isOpeningBraceToken,
  1071. isOpeningBracketToken,
  1072. isOpeningParenToken,
  1073. isSemicolonToken,
  1074. isEqToken,
  1075. /**
  1076. * Checks whether or not a given node is a string literal.
  1077. * @param {ASTNode} node A node to check.
  1078. * @returns {boolean} `true` if the node is a string literal.
  1079. */
  1080. isStringLiteral(node) {
  1081. return (
  1082. (node.type === "Literal" && typeof node.value === "string") ||
  1083. node.type === "TemplateLiteral"
  1084. );
  1085. },
  1086. /**
  1087. * Checks whether a given node is a breakable statement or not.
  1088. * The node is breakable if the node is one of the following type:
  1089. *
  1090. * - DoWhileStatement
  1091. * - ForInStatement
  1092. * - ForOfStatement
  1093. * - ForStatement
  1094. * - SwitchStatement
  1095. * - WhileStatement
  1096. * @param {ASTNode} node A node to check.
  1097. * @returns {boolean} `true` if the node is breakable.
  1098. */
  1099. isBreakableStatement(node) {
  1100. return breakableTypePattern.test(node.type);
  1101. },
  1102. /**
  1103. * Gets references which are non initializer and writable.
  1104. * @param {Reference[]} references An array of references.
  1105. * @returns {Reference[]} An array of only references which are non initializer and writable.
  1106. * @public
  1107. */
  1108. getModifyingReferences(references) {
  1109. return references.filter(isModifyingReference);
  1110. },
  1111. /**
  1112. * Validate that a string passed in is surrounded by the specified character
  1113. * @param {string} val The text to check.
  1114. * @param {string} character The character to see if it's surrounded by.
  1115. * @returns {boolean} True if the text is surrounded by the character, false if not.
  1116. * @private
  1117. */
  1118. isSurroundedBy(val, character) {
  1119. return val[0] === character && val.at(-1) === character;
  1120. },
  1121. /**
  1122. * Returns whether the provided node is an ESLint directive comment or not
  1123. * @param {Line|Block} node The comment token to be checked
  1124. * @returns {boolean} `true` if the node is an ESLint directive comment
  1125. */
  1126. isDirectiveComment(node) {
  1127. const comment = node.value.trim();
  1128. return (
  1129. node.type === "Line" && comment.startsWith("eslint-") ||
  1130. node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment)
  1131. );
  1132. },
  1133. /**
  1134. * Gets the trailing statement of a given node.
  1135. *
  1136. * if (code)
  1137. * consequent;
  1138. *
  1139. * When taking this `IfStatement`, returns `consequent;` statement.
  1140. * @param {ASTNode} A node to get.
  1141. * @returns {ASTNode|null} The trailing statement's node.
  1142. */
  1143. getTrailingStatement: esutils.ast.trailingStatement,
  1144. /**
  1145. * Finds the variable by a given name in a given scope and its upper scopes.
  1146. * @param {eslint-scope.Scope} initScope A scope to start find.
  1147. * @param {string} name A variable name to find.
  1148. * @returns {eslint-scope.Variable|null} A found variable or `null`.
  1149. */
  1150. getVariableByName(initScope, name) {
  1151. let scope = initScope;
  1152. while (scope) {
  1153. const variable = scope.set.get(name);
  1154. if (variable) {
  1155. return variable;
  1156. }
  1157. scope = scope.upper;
  1158. }
  1159. return null;
  1160. },
  1161. /**
  1162. * Checks whether or not a given function node is the default `this` binding.
  1163. *
  1164. * First, this checks the node:
  1165. *
  1166. * - The given node is not in `PropertyDefinition#value` position.
  1167. * - The given node is not `StaticBlock`.
  1168. * - The function name does not start with uppercase. It's a convention to capitalize the names
  1169. * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
  1170. * - The function does not have a JSDoc comment that has a @this tag.
  1171. *
  1172. * Next, this checks the location of the node.
  1173. * If the location is below, this judges `this` is valid.
  1174. *
  1175. * - The location is not on an object literal.
  1176. * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
  1177. * functions only, as the name of the variable is considered to be the name of the function in this case.
  1178. * This check is not performed if `capIsConstructor` is set to `false`.
  1179. * - The location is not on an ES2015 class.
  1180. * - Its `bind`/`call`/`apply` method is not called directly.
  1181. * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
  1182. * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock`
  1183. * or any expression that is `PropertyDefinition#value` node.
  1184. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  1185. * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
  1186. * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
  1187. * @returns {boolean} The function node is the default `this` binding.
  1188. */
  1189. isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
  1190. /*
  1191. * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers.
  1192. * Therefore, A expression node at `PropertyDefinition#value` is a function.
  1193. * In this case, `this` is always not default binding.
  1194. */
  1195. if (node.parent.type === "PropertyDefinition" && node.parent.value === node) {
  1196. return false;
  1197. }
  1198. // Class static blocks are implicit functions. In this case, `this` is always not default binding.
  1199. if (node.type === "StaticBlock") {
  1200. return false;
  1201. }
  1202. if (
  1203. (capIsConstructor && isES5Constructor(node)) ||
  1204. hasJSDocThisTag(node, sourceCode)
  1205. ) {
  1206. return false;
  1207. }
  1208. const isAnonymous = node.id === null;
  1209. let currentNode = node;
  1210. while (currentNode) {
  1211. const parent = currentNode.parent;
  1212. switch (parent.type) {
  1213. /*
  1214. * Looks up the destination.
  1215. * e.g., obj.foo = nativeFoo || function foo() { ... };
  1216. */
  1217. case "LogicalExpression":
  1218. case "ConditionalExpression":
  1219. case "ChainExpression":
  1220. currentNode = parent;
  1221. break;
  1222. /*
  1223. * If the upper function is IIFE, checks the destination of the return value.
  1224. * e.g.
  1225. * obj.foo = (function() {
  1226. * // setup...
  1227. * return function foo() { ... };
  1228. * })();
  1229. * obj.foo = (() =>
  1230. * function foo() { ... }
  1231. * )();
  1232. */
  1233. case "ReturnStatement": {
  1234. const func = getUpperFunction(parent);
  1235. if (func === null || !isCallee(func)) {
  1236. return true;
  1237. }
  1238. currentNode = func.parent;
  1239. break;
  1240. }
  1241. case "ArrowFunctionExpression":
  1242. if (currentNode !== parent.body || !isCallee(parent)) {
  1243. return true;
  1244. }
  1245. currentNode = parent.parent;
  1246. break;
  1247. /*
  1248. * e.g.
  1249. * var obj = { foo() { ... } };
  1250. * var obj = { foo: function() { ... } };
  1251. * class A { constructor() { ... } }
  1252. * class A { foo() { ... } }
  1253. * class A { get foo() { ... } }
  1254. * class A { set foo() { ... } }
  1255. * class A { static foo() { ... } }
  1256. * class A { foo = function() { ... } }
  1257. */
  1258. case "Property":
  1259. case "PropertyDefinition":
  1260. case "MethodDefinition":
  1261. return parent.value !== currentNode;
  1262. /*
  1263. * e.g.
  1264. * obj.foo = function foo() { ... };
  1265. * Foo = function() { ... };
  1266. * [obj.foo = function foo() { ... }] = a;
  1267. * [Foo = function() { ... }] = a;
  1268. */
  1269. case "AssignmentExpression":
  1270. case "AssignmentPattern":
  1271. if (parent.left.type === "MemberExpression") {
  1272. return false;
  1273. }
  1274. if (
  1275. capIsConstructor &&
  1276. isAnonymous &&
  1277. parent.left.type === "Identifier" &&
  1278. startsWithUpperCase(parent.left.name)
  1279. ) {
  1280. return false;
  1281. }
  1282. return true;
  1283. /*
  1284. * e.g.
  1285. * var Foo = function() { ... };
  1286. */
  1287. case "VariableDeclarator":
  1288. return !(
  1289. capIsConstructor &&
  1290. isAnonymous &&
  1291. parent.init === currentNode &&
  1292. parent.id.type === "Identifier" &&
  1293. startsWithUpperCase(parent.id.name)
  1294. );
  1295. /*
  1296. * e.g.
  1297. * var foo = function foo() { ... }.bind(obj);
  1298. * (function foo() { ... }).call(obj);
  1299. * (function foo() { ... }).apply(obj, []);
  1300. */
  1301. case "MemberExpression":
  1302. if (
  1303. parent.object === currentNode &&
  1304. isSpecificMemberAccess(parent, null, bindOrCallOrApplyPattern)
  1305. ) {
  1306. const maybeCalleeNode = parent.parent.type === "ChainExpression"
  1307. ? parent.parent
  1308. : parent;
  1309. return !(
  1310. isCallee(maybeCalleeNode) &&
  1311. maybeCalleeNode.parent.arguments.length >= 1 &&
  1312. !isNullOrUndefined(maybeCalleeNode.parent.arguments[0])
  1313. );
  1314. }
  1315. return true;
  1316. /*
  1317. * e.g.
  1318. * Reflect.apply(function() {}, obj, []);
  1319. * Array.from([], function() {}, obj);
  1320. * list.forEach(function() {}, obj);
  1321. */
  1322. case "CallExpression":
  1323. if (isReflectApply(parent.callee)) {
  1324. return (
  1325. parent.arguments.length !== 3 ||
  1326. parent.arguments[0] !== currentNode ||
  1327. isNullOrUndefined(parent.arguments[1])
  1328. );
  1329. }
  1330. if (isArrayFromMethod(parent.callee)) {
  1331. return (
  1332. parent.arguments.length !== 3 ||
  1333. parent.arguments[1] !== currentNode ||
  1334. isNullOrUndefined(parent.arguments[2])
  1335. );
  1336. }
  1337. if (isMethodWhichHasThisArg(parent.callee)) {
  1338. return (
  1339. parent.arguments.length !== 2 ||
  1340. parent.arguments[0] !== currentNode ||
  1341. isNullOrUndefined(parent.arguments[1])
  1342. );
  1343. }
  1344. return true;
  1345. // Otherwise `this` is default.
  1346. default:
  1347. return true;
  1348. }
  1349. }
  1350. /* c8 ignore next */
  1351. return true;
  1352. },
  1353. /**
  1354. * Get the precedence level based on the node type
  1355. * @param {ASTNode} node node to evaluate
  1356. * @returns {int} precedence level
  1357. * @private
  1358. */
  1359. getPrecedence(node) {
  1360. switch (node.type) {
  1361. case "SequenceExpression":
  1362. return 0;
  1363. case "AssignmentExpression":
  1364. case "ArrowFunctionExpression":
  1365. case "YieldExpression":
  1366. return 1;
  1367. case "ConditionalExpression":
  1368. return 3;
  1369. case "LogicalExpression":
  1370. switch (node.operator) {
  1371. case "||":
  1372. case "??":
  1373. return 4;
  1374. case "&&":
  1375. return 5;
  1376. // no default
  1377. }
  1378. /* falls through */
  1379. case "BinaryExpression":
  1380. switch (node.operator) {
  1381. case "|":
  1382. return 6;
  1383. case "^":
  1384. return 7;
  1385. case "&":
  1386. return 8;
  1387. case "==":
  1388. case "!=":
  1389. case "===":
  1390. case "!==":
  1391. return 9;
  1392. case "<":
  1393. case "<=":
  1394. case ">":
  1395. case ">=":
  1396. case "in":
  1397. case "instanceof":
  1398. return 10;
  1399. case "<<":
  1400. case ">>":
  1401. case ">>>":
  1402. return 11;
  1403. case "+":
  1404. case "-":
  1405. return 12;
  1406. case "*":
  1407. case "/":
  1408. case "%":
  1409. return 13;
  1410. case "**":
  1411. return 15;
  1412. // no default
  1413. }
  1414. /* falls through */
  1415. case "UnaryExpression":
  1416. case "AwaitExpression":
  1417. return 16;
  1418. case "UpdateExpression":
  1419. return 17;
  1420. case "CallExpression":
  1421. case "ChainExpression":
  1422. case "ImportExpression":
  1423. return 18;
  1424. case "NewExpression":
  1425. return 19;
  1426. default:
  1427. if (node.type in eslintVisitorKeys) {
  1428. return 20;
  1429. }
  1430. /*
  1431. * if the node is not a standard node that we know about, then assume it has the lowest precedence
  1432. * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of
  1433. * unwrapping them and potentially changing the meaning of the code or introducing a syntax error.
  1434. */
  1435. return -1;
  1436. }
  1437. },
  1438. /**
  1439. * Checks whether the given node is an empty block node or not.
  1440. * @param {ASTNode|null} node The node to check.
  1441. * @returns {boolean} `true` if the node is an empty block.
  1442. */
  1443. isEmptyBlock(node) {
  1444. return Boolean(node && node.type === "BlockStatement" && node.body.length === 0);
  1445. },
  1446. /**
  1447. * Checks whether the given node is an empty function node or not.
  1448. * @param {ASTNode|null} node The node to check.
  1449. * @returns {boolean} `true` if the node is an empty function.
  1450. */
  1451. isEmptyFunction(node) {
  1452. return isFunction(node) && module.exports.isEmptyBlock(node.body);
  1453. },
  1454. /**
  1455. * Get directives from directive prologue of a Program or Function node.
  1456. * @param {ASTNode} node The node to check.
  1457. * @returns {ASTNode[]} The directives found in the directive prologue.
  1458. */
  1459. getDirectivePrologue(node) {
  1460. const directives = [];
  1461. // Directive prologues only occur at the top of files or functions.
  1462. if (
  1463. node.type === "Program" ||
  1464. node.type === "FunctionDeclaration" ||
  1465. node.type === "FunctionExpression" ||
  1466. /*
  1467. * Do not check arrow functions with implicit return.
  1468. * `() => "use strict";` returns the string `"use strict"`.
  1469. */
  1470. (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement")
  1471. ) {
  1472. const statements = node.type === "Program" ? node.body : node.body.body;
  1473. for (const statement of statements) {
  1474. if (
  1475. statement.type === "ExpressionStatement" &&
  1476. statement.expression.type === "Literal"
  1477. ) {
  1478. directives.push(statement);
  1479. } else {
  1480. break;
  1481. }
  1482. }
  1483. }
  1484. return directives;
  1485. },
  1486. /**
  1487. * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
  1488. * after the node will be parsed as a decimal point, rather than a property-access dot.
  1489. * @param {ASTNode} node The node to check.
  1490. * @returns {boolean} `true` if this node is a decimal integer.
  1491. * @example
  1492. *
  1493. * 0 // true
  1494. * 5 // true
  1495. * 50 // true
  1496. * 5_000 // true
  1497. * 1_234_56 // true
  1498. * 08 // true
  1499. * 0192 // true
  1500. * 5. // false
  1501. * .5 // false
  1502. * 5.0 // false
  1503. * 5.00_00 // false
  1504. * 05 // false
  1505. * 0x5 // false
  1506. * 0b101 // false
  1507. * 0b11_01 // false
  1508. * 0o5 // false
  1509. * 5e0 // false
  1510. * 5e1_000 // false
  1511. * 5n // false
  1512. * 1_000n // false
  1513. * "5" // false
  1514. *
  1515. */
  1516. isDecimalInteger(node) {
  1517. return node.type === "Literal" && typeof node.value === "number" &&
  1518. DECIMAL_INTEGER_PATTERN.test(node.raw);
  1519. },
  1520. /**
  1521. * Determines whether this token is a decimal integer numeric token.
  1522. * This is similar to isDecimalInteger(), but for tokens.
  1523. * @param {Token} token The token to check.
  1524. * @returns {boolean} `true` if this token is a decimal integer.
  1525. */
  1526. isDecimalIntegerNumericToken(token) {
  1527. return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value);
  1528. },
  1529. /**
  1530. * Gets the name and kind of the given function node.
  1531. *
  1532. * - `function foo() {}` .................... `function 'foo'`
  1533. * - `(function foo() {})` .................. `function 'foo'`
  1534. * - `(function() {})` ...................... `function`
  1535. * - `function* foo() {}` ................... `generator function 'foo'`
  1536. * - `(function* foo() {})` ................. `generator function 'foo'`
  1537. * - `(function*() {})` ..................... `generator function`
  1538. * - `() => {}` ............................. `arrow function`
  1539. * - `async () => {}` ....................... `async arrow function`
  1540. * - `({ foo: function foo() {} })` ......... `method 'foo'`
  1541. * - `({ foo: function() {} })` ............. `method 'foo'`
  1542. * - `({ ['foo']: function() {} })` ......... `method 'foo'`
  1543. * - `({ [foo]: function() {} })` ........... `method`
  1544. * - `({ foo() {} })` ....................... `method 'foo'`
  1545. * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
  1546. * - `({ foo: function*() {} })` ............ `generator method 'foo'`
  1547. * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
  1548. * - `({ [foo]: function*() {} })` .......... `generator method`
  1549. * - `({ *foo() {} })` ...................... `generator method 'foo'`
  1550. * - `({ foo: async function foo() {} })` ... `async method 'foo'`
  1551. * - `({ foo: async function() {} })` ....... `async method 'foo'`
  1552. * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
  1553. * - `({ [foo]: async function() {} })` ..... `async method`
  1554. * - `({ async foo() {} })` ................. `async method 'foo'`
  1555. * - `({ get foo() {} })` ................... `getter 'foo'`
  1556. * - `({ set foo(a) {} })` .................. `setter 'foo'`
  1557. * - `class A { constructor() {} }` ......... `constructor`
  1558. * - `class A { foo() {} }` ................. `method 'foo'`
  1559. * - `class A { *foo() {} }` ................ `generator method 'foo'`
  1560. * - `class A { async foo() {} }` ........... `async method 'foo'`
  1561. * - `class A { ['foo']() {} }` ............. `method 'foo'`
  1562. * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
  1563. * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
  1564. * - `class A { [foo]() {} }` ............... `method`
  1565. * - `class A { *[foo]() {} }` .............. `generator method`
  1566. * - `class A { async [foo]() {} }` ......... `async method`
  1567. * - `class A { get foo() {} }` ............. `getter 'foo'`
  1568. * - `class A { set foo(a) {} }` ............ `setter 'foo'`
  1569. * - `class A { static foo() {} }` .......... `static method 'foo'`
  1570. * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
  1571. * - `class A { static async foo() {} }` .... `static async method 'foo'`
  1572. * - `class A { static get foo() {} }` ...... `static getter 'foo'`
  1573. * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
  1574. * - `class A { foo = () => {}; }` .......... `method 'foo'`
  1575. * - `class A { foo = function() {}; }` ..... `method 'foo'`
  1576. * - `class A { foo = function bar() {}; }` . `method 'foo'`
  1577. * - `class A { static foo = () => {}; }` ... `static method 'foo'`
  1578. * - `class A { '#foo' = () => {}; }` ....... `method '#foo'`
  1579. * - `class A { #foo = () => {}; }` ......... `private method #foo`
  1580. * - `class A { static #foo = () => {}; }` .. `static private method #foo`
  1581. * - `class A { '#foo'() {} }` .............. `method '#foo'`
  1582. * - `class A { #foo() {} }` ................ `private method #foo`
  1583. * - `class A { static #foo() {} }` ......... `static private method #foo`
  1584. * @param {ASTNode} node The function node to get.
  1585. * @returns {string} The name and kind of the function node.
  1586. */
  1587. getFunctionNameWithKind(node) {
  1588. const parent = node.parent;
  1589. const tokens = [];
  1590. if (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1591. // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features
  1592. if (parent.static) {
  1593. tokens.push("static");
  1594. }
  1595. if (!parent.computed && parent.key.type === "PrivateIdentifier") {
  1596. tokens.push("private");
  1597. }
  1598. }
  1599. if (node.async) {
  1600. tokens.push("async");
  1601. }
  1602. if (node.generator) {
  1603. tokens.push("generator");
  1604. }
  1605. if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1606. if (parent.kind === "constructor") {
  1607. return "constructor";
  1608. }
  1609. if (parent.kind === "get") {
  1610. tokens.push("getter");
  1611. } else if (parent.kind === "set") {
  1612. tokens.push("setter");
  1613. } else {
  1614. tokens.push("method");
  1615. }
  1616. } else if (parent.type === "PropertyDefinition") {
  1617. tokens.push("method");
  1618. } else {
  1619. if (node.type === "ArrowFunctionExpression") {
  1620. tokens.push("arrow");
  1621. }
  1622. tokens.push("function");
  1623. }
  1624. if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1625. if (!parent.computed && parent.key.type === "PrivateIdentifier") {
  1626. tokens.push(`#${parent.key.name}`);
  1627. } else {
  1628. const name = getStaticPropertyName(parent);
  1629. if (name !== null) {
  1630. tokens.push(`'${name}'`);
  1631. } else if (node.id) {
  1632. tokens.push(`'${node.id.name}'`);
  1633. }
  1634. }
  1635. } else if (node.id) {
  1636. tokens.push(`'${node.id.name}'`);
  1637. }
  1638. return tokens.join(" ");
  1639. },
  1640. /**
  1641. * Gets the location of the given function node for reporting.
  1642. *
  1643. * - `function foo() {}`
  1644. * ^^^^^^^^^^^^
  1645. * - `(function foo() {})`
  1646. * ^^^^^^^^^^^^
  1647. * - `(function() {})`
  1648. * ^^^^^^^^
  1649. * - `function* foo() {}`
  1650. * ^^^^^^^^^^^^^
  1651. * - `(function* foo() {})`
  1652. * ^^^^^^^^^^^^^
  1653. * - `(function*() {})`
  1654. * ^^^^^^^^^
  1655. * - `() => {}`
  1656. * ^^
  1657. * - `async () => {}`
  1658. * ^^
  1659. * - `({ foo: function foo() {} })`
  1660. * ^^^^^^^^^^^^^^^^^
  1661. * - `({ foo: function() {} })`
  1662. * ^^^^^^^^^^^^^
  1663. * - `({ ['foo']: function() {} })`
  1664. * ^^^^^^^^^^^^^^^^^
  1665. * - `({ [foo]: function() {} })`
  1666. * ^^^^^^^^^^^^^^^
  1667. * - `({ foo() {} })`
  1668. * ^^^
  1669. * - `({ foo: function* foo() {} })`
  1670. * ^^^^^^^^^^^^^^^^^^
  1671. * - `({ foo: function*() {} })`
  1672. * ^^^^^^^^^^^^^^
  1673. * - `({ ['foo']: function*() {} })`
  1674. * ^^^^^^^^^^^^^^^^^^
  1675. * - `({ [foo]: function*() {} })`
  1676. * ^^^^^^^^^^^^^^^^
  1677. * - `({ *foo() {} })`
  1678. * ^^^^
  1679. * - `({ foo: async function foo() {} })`
  1680. * ^^^^^^^^^^^^^^^^^^^^^^^
  1681. * - `({ foo: async function() {} })`
  1682. * ^^^^^^^^^^^^^^^^^^^
  1683. * - `({ ['foo']: async function() {} })`
  1684. * ^^^^^^^^^^^^^^^^^^^^^^^
  1685. * - `({ [foo]: async function() {} })`
  1686. * ^^^^^^^^^^^^^^^^^^^^^
  1687. * - `({ async foo() {} })`
  1688. * ^^^^^^^^^
  1689. * - `({ get foo() {} })`
  1690. * ^^^^^^^
  1691. * - `({ set foo(a) {} })`
  1692. * ^^^^^^^
  1693. * - `class A { constructor() {} }`
  1694. * ^^^^^^^^^^^
  1695. * - `class A { foo() {} }`
  1696. * ^^^
  1697. * - `class A { *foo() {} }`
  1698. * ^^^^
  1699. * - `class A { async foo() {} }`
  1700. * ^^^^^^^^^
  1701. * - `class A { ['foo']() {} }`
  1702. * ^^^^^^^
  1703. * - `class A { *['foo']() {} }`
  1704. * ^^^^^^^^
  1705. * - `class A { async ['foo']() {} }`
  1706. * ^^^^^^^^^^^^^
  1707. * - `class A { [foo]() {} }`
  1708. * ^^^^^
  1709. * - `class A { *[foo]() {} }`
  1710. * ^^^^^^
  1711. * - `class A { async [foo]() {} }`
  1712. * ^^^^^^^^^^^
  1713. * - `class A { get foo() {} }`
  1714. * ^^^^^^^
  1715. * - `class A { set foo(a) {} }`
  1716. * ^^^^^^^
  1717. * - `class A { static foo() {} }`
  1718. * ^^^^^^^^^^
  1719. * - `class A { static *foo() {} }`
  1720. * ^^^^^^^^^^^
  1721. * - `class A { static async foo() {} }`
  1722. * ^^^^^^^^^^^^^^^^
  1723. * - `class A { static get foo() {} }`
  1724. * ^^^^^^^^^^^^^^
  1725. * - `class A { static set foo(a) {} }`
  1726. * ^^^^^^^^^^^^^^
  1727. * - `class A { foo = function() {} }`
  1728. * ^^^^^^^^^^^^^^
  1729. * - `class A { static foo = function() {} }`
  1730. * ^^^^^^^^^^^^^^^^^^^^^
  1731. * - `class A { foo = (a, b) => {} }`
  1732. * ^^^^^^
  1733. * @param {ASTNode} node The function node to get.
  1734. * @param {SourceCode} sourceCode The source code object to get tokens.
  1735. * @returns {string} The location of the function node for reporting.
  1736. */
  1737. getFunctionHeadLoc(node, sourceCode) {
  1738. const parent = node.parent;
  1739. let start;
  1740. let end;
  1741. if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
  1742. start = parent.loc.start;
  1743. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1744. } else if (node.type === "ArrowFunctionExpression") {
  1745. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  1746. start = arrowToken.loc.start;
  1747. end = arrowToken.loc.end;
  1748. } else {
  1749. start = node.loc.start;
  1750. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1751. }
  1752. return {
  1753. start: Object.assign({}, start),
  1754. end: Object.assign({}, end)
  1755. };
  1756. },
  1757. /**
  1758. * Gets next location when the result is not out of bound, otherwise returns null.
  1759. *
  1760. * Assumptions:
  1761. *
  1762. * - The given location represents a valid location in the given source code.
  1763. * - Columns are 0-based.
  1764. * - Lines are 1-based.
  1765. * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
  1766. * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
  1767. * The start (column 0) of that extra line is considered to be a valid location.
  1768. *
  1769. * Examples of successive locations (line, column):
  1770. *
  1771. * code: foo
  1772. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
  1773. *
  1774. * code: foo<LF>
  1775. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1776. *
  1777. * code: foo<CR><LF>
  1778. * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
  1779. *
  1780. * code: a<LF>b
  1781. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
  1782. *
  1783. * code: a<LF>b<LF>
  1784. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1785. *
  1786. * code: a<CR><LF>b<CR><LF>
  1787. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
  1788. *
  1789. * code: a<LF><LF>
  1790. * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
  1791. *
  1792. * code: <LF>
  1793. * locations: (1, 0) -> (2, 0) -> null
  1794. *
  1795. * code:
  1796. * locations: (1, 0) -> null
  1797. * @param {SourceCode} sourceCode The sourceCode
  1798. * @param {{line: number, column: number}} location The location
  1799. * @returns {{line: number, column: number} | null} Next location
  1800. */
  1801. getNextLocation(sourceCode, { line, column }) {
  1802. if (column < sourceCode.lines[line - 1].length) {
  1803. return {
  1804. line,
  1805. column: column + 1
  1806. };
  1807. }
  1808. if (line < sourceCode.lines.length) {
  1809. return {
  1810. line: line + 1,
  1811. column: 0
  1812. };
  1813. }
  1814. return null;
  1815. },
  1816. /**
  1817. * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
  1818. * surrounding the node.
  1819. * @param {SourceCode} sourceCode The source code object
  1820. * @param {ASTNode} node An expression node
  1821. * @returns {string} The text representing the node, with all surrounding parentheses included
  1822. */
  1823. getParenthesisedText(sourceCode, node) {
  1824. let leftToken = sourceCode.getFirstToken(node);
  1825. let rightToken = sourceCode.getLastToken(node);
  1826. while (
  1827. sourceCode.getTokenBefore(leftToken) &&
  1828. sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
  1829. sourceCode.getTokenBefore(leftToken).value === "(" &&
  1830. sourceCode.getTokenAfter(rightToken) &&
  1831. sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
  1832. sourceCode.getTokenAfter(rightToken).value === ")"
  1833. ) {
  1834. leftToken = sourceCode.getTokenBefore(leftToken);
  1835. rightToken = sourceCode.getTokenAfter(rightToken);
  1836. }
  1837. return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]);
  1838. },
  1839. /**
  1840. * Determine if a node has a possibility to be an Error object
  1841. * @param {ASTNode} node ASTNode to check
  1842. * @returns {boolean} True if there is a chance it contains an Error obj
  1843. */
  1844. couldBeError(node) {
  1845. switch (node.type) {
  1846. case "Identifier":
  1847. case "CallExpression":
  1848. case "NewExpression":
  1849. case "MemberExpression":
  1850. case "TaggedTemplateExpression":
  1851. case "YieldExpression":
  1852. case "AwaitExpression":
  1853. case "ChainExpression":
  1854. return true; // possibly an error object.
  1855. case "AssignmentExpression":
  1856. if (["=", "&&="].includes(node.operator)) {
  1857. return module.exports.couldBeError(node.right);
  1858. }
  1859. if (["||=", "??="].includes(node.operator)) {
  1860. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1861. }
  1862. /**
  1863. * All other assignment operators are mathematical assignment operators (arithmetic or bitwise).
  1864. * An assignment expression with a mathematical operator can either evaluate to a primitive value,
  1865. * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object.
  1866. */
  1867. return false;
  1868. case "SequenceExpression": {
  1869. const exprs = node.expressions;
  1870. return exprs.length !== 0 && module.exports.couldBeError(exprs.at(-1));
  1871. }
  1872. case "LogicalExpression":
  1873. /*
  1874. * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it
  1875. * doesn't short-circuit, it takes the value from the right side, so the right side must always be
  1876. * a plausible error. A future improvement could verify that the left side could be truthy by
  1877. * excluding falsy literals.
  1878. */
  1879. if (node.operator === "&&") {
  1880. return module.exports.couldBeError(node.right);
  1881. }
  1882. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1883. case "ConditionalExpression":
  1884. return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate);
  1885. default:
  1886. return false;
  1887. }
  1888. },
  1889. /**
  1890. * Check if a given node is a numeric literal or not.
  1891. * @param {ASTNode} node The node to check.
  1892. * @returns {boolean} `true` if the node is a number or bigint literal.
  1893. */
  1894. isNumericLiteral(node) {
  1895. return (
  1896. node.type === "Literal" &&
  1897. (typeof node.value === "number" || Boolean(node.bigint))
  1898. );
  1899. },
  1900. /**
  1901. * Determines whether two tokens can safely be placed next to each other without merging into a single token
  1902. * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
  1903. * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
  1904. * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
  1905. * next to each other, behavior is undefined (although it should return `true` in most cases).
  1906. */
  1907. canTokensBeAdjacent(leftValue, rightValue) {
  1908. const espreeOptions = {
  1909. ecmaVersion: espree.latestEcmaVersion,
  1910. comment: true,
  1911. range: true
  1912. };
  1913. let leftToken;
  1914. if (typeof leftValue === "string") {
  1915. let tokens;
  1916. try {
  1917. tokens = espree.tokenize(leftValue, espreeOptions);
  1918. } catch {
  1919. return false;
  1920. }
  1921. const comments = tokens.comments;
  1922. leftToken = tokens.at(-1);
  1923. if (comments.length) {
  1924. const lastComment = comments.at(-1);
  1925. if (!leftToken || lastComment.range[0] > leftToken.range[0]) {
  1926. leftToken = lastComment;
  1927. }
  1928. }
  1929. } else {
  1930. leftToken = leftValue;
  1931. }
  1932. /*
  1933. * If a hashbang comment was passed as a token object from SourceCode,
  1934. * its type will be "Shebang" because of the way ESLint itself handles hashbangs.
  1935. * If a hashbang comment was passed in a string and then tokenized in this function,
  1936. * its type will be "Hashbang" because of the way Espree tokenizes hashbangs.
  1937. */
  1938. if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") {
  1939. return false;
  1940. }
  1941. let rightToken;
  1942. if (typeof rightValue === "string") {
  1943. let tokens;
  1944. try {
  1945. tokens = espree.tokenize(rightValue, espreeOptions);
  1946. } catch {
  1947. return false;
  1948. }
  1949. const comments = tokens.comments;
  1950. rightToken = tokens[0];
  1951. if (comments.length) {
  1952. const firstComment = comments[0];
  1953. if (!rightToken || firstComment.range[0] < rightToken.range[0]) {
  1954. rightToken = firstComment;
  1955. }
  1956. }
  1957. } else {
  1958. rightToken = rightValue;
  1959. }
  1960. if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") {
  1961. if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") {
  1962. const PLUS_TOKENS = new Set(["+", "++"]);
  1963. const MINUS_TOKENS = new Set(["-", "--"]);
  1964. return !(
  1965. PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) ||
  1966. MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value)
  1967. );
  1968. }
  1969. if (leftToken.type === "Punctuator" && leftToken.value === "/") {
  1970. return !["Block", "Line", "RegularExpression"].includes(rightToken.type);
  1971. }
  1972. return true;
  1973. }
  1974. if (
  1975. leftToken.type === "String" || rightToken.type === "String" ||
  1976. leftToken.type === "Template" || rightToken.type === "Template"
  1977. ) {
  1978. return true;
  1979. }
  1980. if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) {
  1981. return true;
  1982. }
  1983. if (leftToken.type === "Block" || rightToken.type === "Block" || rightToken.type === "Line") {
  1984. return true;
  1985. }
  1986. if (rightToken.type === "PrivateIdentifier") {
  1987. return true;
  1988. }
  1989. return false;
  1990. },
  1991. /**
  1992. * Get the `loc` object of a given name in a `/*globals` directive comment.
  1993. * @param {SourceCode} sourceCode The source code to convert index to loc.
  1994. * @param {Comment} comment The `/*globals` directive comment which include the name.
  1995. * @param {string} name The name to find.
  1996. * @returns {SourceLocation} The `loc` object.
  1997. */
  1998. getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
  1999. const namePattern = new RegExp(`[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`, "gu");
  2000. // To ignore the first text "global".
  2001. namePattern.lastIndex = comment.value.indexOf("global") + 6;
  2002. // Search a given variable name.
  2003. const match = namePattern.exec(comment.value);
  2004. // Convert the index to loc.
  2005. const start = sourceCode.getLocFromIndex(
  2006. comment.range[0] +
  2007. "/*".length +
  2008. (match ? match.index + 1 : 0)
  2009. );
  2010. const end = {
  2011. line: start.line,
  2012. column: start.column + (match ? name.length : 1)
  2013. };
  2014. return { start, end };
  2015. },
  2016. /**
  2017. * Determines whether the given raw string contains an octal escape sequence
  2018. * or a non-octal decimal escape sequence ("\8", "\9").
  2019. *
  2020. * "\1", "\2" ... "\7", "\8", "\9"
  2021. * "\00", "\01" ... "\07", "\08", "\09"
  2022. *
  2023. * "\0", when not followed by a digit, is not an octal escape sequence.
  2024. * @param {string} rawString A string in its raw representation.
  2025. * @returns {boolean} `true` if the string contains at least one octal escape sequence
  2026. * or at least one non-octal decimal escape sequence.
  2027. */
  2028. hasOctalOrNonOctalDecimalEscapeSequence(rawString) {
  2029. return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString);
  2030. },
  2031. /**
  2032. * Determines whether the given node is a template literal without expressions.
  2033. * @param {ASTNode} node Node to check.
  2034. * @returns {boolean} True if the node is a template literal without expressions.
  2035. */
  2036. isStaticTemplateLiteral(node) {
  2037. return node.type === "TemplateLiteral" && node.expressions.length === 0;
  2038. },
  2039. /**
  2040. * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
  2041. * The braces, which make the given block body, are necessary in either of the following situations:
  2042. *
  2043. * 1. The statement is a lexical declaration.
  2044. * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
  2045. *
  2046. * if (a) {
  2047. * if (b)
  2048. * foo();
  2049. * }
  2050. * else
  2051. * bar();
  2052. *
  2053. * if (a)
  2054. * while (b)
  2055. * while (c) {
  2056. * while (d)
  2057. * if (e)
  2058. * while(f)
  2059. * foo();
  2060. * }
  2061. * else
  2062. * bar();
  2063. * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
  2064. * @param {SourceCode} sourceCode The source code
  2065. * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
  2066. * would change the semantics of the code or produce a syntax error.
  2067. */
  2068. areBracesNecessary(node, sourceCode) {
  2069. /**
  2070. * Determines if the given node is a lexical declaration (let, const, function, or class)
  2071. * @param {ASTNode} nodeToCheck The node to check
  2072. * @returns {boolean} True if the node is a lexical declaration
  2073. * @private
  2074. */
  2075. function isLexicalDeclaration(nodeToCheck) {
  2076. if (nodeToCheck.type === "VariableDeclaration") {
  2077. return nodeToCheck.kind === "const" || nodeToCheck.kind === "let";
  2078. }
  2079. return nodeToCheck.type === "FunctionDeclaration" || nodeToCheck.type === "ClassDeclaration";
  2080. }
  2081. /**
  2082. * Checks if the given token is an `else` token or not.
  2083. * @param {Token} token The token to check.
  2084. * @returns {boolean} `true` if the token is an `else` token.
  2085. */
  2086. function isElseKeywordToken(token) {
  2087. return token.value === "else" && token.type === "Keyword";
  2088. }
  2089. /**
  2090. * Determines whether the given node has an `else` keyword token as the first token after.
  2091. * @param {ASTNode} nodeToCheck The node to check.
  2092. * @returns {boolean} `true` if the node is followed by an `else` keyword token.
  2093. */
  2094. function isFollowedByElseKeyword(nodeToCheck) {
  2095. const nextToken = sourceCode.getTokenAfter(nodeToCheck);
  2096. return Boolean(nextToken) && isElseKeywordToken(nextToken);
  2097. }
  2098. /**
  2099. * Determines whether the code represented by the given node contains an `if` statement
  2100. * that would become associated with an `else` keyword directly appended to that code.
  2101. *
  2102. * Examples where it returns `true`:
  2103. *
  2104. * if (a)
  2105. * foo();
  2106. *
  2107. * if (a) {
  2108. * foo();
  2109. * }
  2110. *
  2111. * if (a)
  2112. * foo();
  2113. * else if (b)
  2114. * bar();
  2115. *
  2116. * while (a)
  2117. * if (b)
  2118. * if(c)
  2119. * foo();
  2120. * else
  2121. * bar();
  2122. *
  2123. * Examples where it returns `false`:
  2124. *
  2125. * if (a)
  2126. * foo();
  2127. * else
  2128. * bar();
  2129. *
  2130. * while (a) {
  2131. * if (b)
  2132. * if(c)
  2133. * foo();
  2134. * else
  2135. * bar();
  2136. * }
  2137. *
  2138. * while (a)
  2139. * if (b) {
  2140. * if(c)
  2141. * foo();
  2142. * }
  2143. * else
  2144. * bar();
  2145. * @param {ASTNode} nodeToCheck Node representing the code to check.
  2146. * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
  2147. */
  2148. function hasUnsafeIf(nodeToCheck) {
  2149. switch (nodeToCheck.type) {
  2150. case "IfStatement":
  2151. if (!nodeToCheck.alternate) {
  2152. return true;
  2153. }
  2154. return hasUnsafeIf(nodeToCheck.alternate);
  2155. case "ForStatement":
  2156. case "ForInStatement":
  2157. case "ForOfStatement":
  2158. case "LabeledStatement":
  2159. case "WithStatement":
  2160. case "WhileStatement":
  2161. return hasUnsafeIf(nodeToCheck.body);
  2162. default:
  2163. return false;
  2164. }
  2165. }
  2166. const statement = node.body[0];
  2167. return isLexicalDeclaration(statement) ||
  2168. hasUnsafeIf(statement) && isFollowedByElseKeyword(node);
  2169. },
  2170. isReferenceToGlobalVariable,
  2171. isLogicalExpression,
  2172. isCoalesceExpression,
  2173. isMixedLogicalAndCoalesceExpressions,
  2174. isNullLiteral,
  2175. getStaticStringValue,
  2176. getStaticPropertyName,
  2177. skipChainExpression,
  2178. isSpecificId,
  2179. isSpecificMemberAccess,
  2180. equalLiteralValue,
  2181. isSameReference,
  2182. isLogicalAssignmentOperator,
  2183. getSwitchCaseColonToken,
  2184. getModuleExportName,
  2185. isConstant,
  2186. isTopLevelExpressionStatement,
  2187. isDirective,
  2188. isStartOfExpressionStatement,
  2189. needsPrecedingSemicolon,
  2190. isImportAttributeKey
  2191. };