Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ast-utils.js 61KB

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