ast-utils.js 60 KB

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