ast-utils.js 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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|[1-9]\d*)$/u;
  32. const OCTAL_ESCAPE_PATTERN = /^(?:[^\\]|\\[^0-7]|\\0(?![0-9]))*\\(?:[1-7]|0[0-9])/u;
  33. /**
  34. * Checks reference if is non initializer and writable.
  35. * @param {Reference} reference A reference to check.
  36. * @param {int} index The index of the reference in the references.
  37. * @param {Reference[]} references The array that the reference belongs to.
  38. * @returns {boolean} Success/Failure
  39. * @private
  40. */
  41. function isModifyingReference(reference, index, references) {
  42. const identifier = reference.identifier;
  43. /*
  44. * Destructuring assignments can have multiple default value, so
  45. * possibly there are multiple writeable references for the same
  46. * identifier.
  47. */
  48. const modifyingDifferentIdentifier = index === 0 ||
  49. references[index - 1].identifier !== identifier;
  50. return (identifier &&
  51. reference.init === false &&
  52. reference.isWrite() &&
  53. modifyingDifferentIdentifier
  54. );
  55. }
  56. /**
  57. * Checks whether the given string starts with uppercase or not.
  58. * @param {string} s The string to check.
  59. * @returns {boolean} `true` if the string starts with uppercase.
  60. */
  61. function startsWithUpperCase(s) {
  62. return s[0] !== s[0].toLocaleLowerCase();
  63. }
  64. /**
  65. * Checks whether or not a node is a constructor.
  66. * @param {ASTNode} node A function node to check.
  67. * @returns {boolean} Wehether or not a node is a constructor.
  68. */
  69. function isES5Constructor(node) {
  70. return (node.id && startsWithUpperCase(node.id.name));
  71. }
  72. /**
  73. * Finds a function node from ancestors of a node.
  74. * @param {ASTNode} node A start node to find.
  75. * @returns {Node|null} A found function node.
  76. */
  77. function getUpperFunction(node) {
  78. for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
  79. if (anyFunctionPattern.test(currentNode.type)) {
  80. return currentNode;
  81. }
  82. }
  83. return null;
  84. }
  85. /**
  86. * Checks whether a given node is a function node or not.
  87. * The following types are function nodes:
  88. *
  89. * - ArrowFunctionExpression
  90. * - FunctionDeclaration
  91. * - FunctionExpression
  92. * @param {ASTNode|null} node A node to check.
  93. * @returns {boolean} `true` if the node is a function node.
  94. */
  95. function isFunction(node) {
  96. return Boolean(node && anyFunctionPattern.test(node.type));
  97. }
  98. /**
  99. * Checks whether a given node is a loop node or not.
  100. * The following types are loop nodes:
  101. *
  102. * - DoWhileStatement
  103. * - ForInStatement
  104. * - ForOfStatement
  105. * - ForStatement
  106. * - WhileStatement
  107. * @param {ASTNode|null} node A node to check.
  108. * @returns {boolean} `true` if the node is a loop node.
  109. */
  110. function isLoop(node) {
  111. return Boolean(node && anyLoopPattern.test(node.type));
  112. }
  113. /**
  114. * Checks whether the given node is in a loop or not.
  115. * @param {ASTNode} node The node to check.
  116. * @returns {boolean} `true` if the node is in a loop.
  117. */
  118. function isInLoop(node) {
  119. for (let currentNode = node; currentNode && !isFunction(currentNode); currentNode = currentNode.parent) {
  120. if (isLoop(currentNode)) {
  121. return true;
  122. }
  123. }
  124. return false;
  125. }
  126. /**
  127. * Checks whether or not a node is `null` or `undefined`.
  128. * @param {ASTNode} node A node to check.
  129. * @returns {boolean} Whether or not the node is a `null` or `undefined`.
  130. * @public
  131. */
  132. function isNullOrUndefined(node) {
  133. return (
  134. module.exports.isNullLiteral(node) ||
  135. (node.type === "Identifier" && node.name === "undefined") ||
  136. (node.type === "UnaryExpression" && node.operator === "void")
  137. );
  138. }
  139. /**
  140. * Checks whether or not a node is callee.
  141. * @param {ASTNode} node A node to check.
  142. * @returns {boolean} Whether or not the node is callee.
  143. */
  144. function isCallee(node) {
  145. return node.parent.type === "CallExpression" && node.parent.callee === node;
  146. }
  147. /**
  148. * Checks whether or not a node is `Reflect.apply`.
  149. * @param {ASTNode} node A node to check.
  150. * @returns {boolean} Whether or not the node is a `Reflect.apply`.
  151. */
  152. function isReflectApply(node) {
  153. return (
  154. node.type === "MemberExpression" &&
  155. node.object.type === "Identifier" &&
  156. node.object.name === "Reflect" &&
  157. node.property.type === "Identifier" &&
  158. node.property.name === "apply" &&
  159. node.computed === false
  160. );
  161. }
  162. /**
  163. * Checks whether or not a node is `Array.from`.
  164. * @param {ASTNode} node A node to check.
  165. * @returns {boolean} Whether or not the node is a `Array.from`.
  166. */
  167. function isArrayFromMethod(node) {
  168. return (
  169. node.type === "MemberExpression" &&
  170. node.object.type === "Identifier" &&
  171. arrayOrTypedArrayPattern.test(node.object.name) &&
  172. node.property.type === "Identifier" &&
  173. node.property.name === "from" &&
  174. node.computed === false
  175. );
  176. }
  177. /**
  178. * Checks whether or not a node is a method which has `thisArg`.
  179. * @param {ASTNode} node A node to check.
  180. * @returns {boolean} Whether or not the node is a method which has `thisArg`.
  181. */
  182. function isMethodWhichHasThisArg(node) {
  183. for (
  184. let currentNode = node;
  185. currentNode.type === "MemberExpression" && !currentNode.computed;
  186. currentNode = currentNode.property
  187. ) {
  188. if (currentNode.property.type === "Identifier") {
  189. return arrayMethodPattern.test(currentNode.property.name);
  190. }
  191. }
  192. return false;
  193. }
  194. /**
  195. * Creates the negate function of the given function.
  196. * @param {Function} f The function to negate.
  197. * @returns {Function} Negated function.
  198. */
  199. function negate(f) {
  200. return token => !f(token);
  201. }
  202. /**
  203. * Checks whether or not a node has a `@this` tag in its comments.
  204. * @param {ASTNode} node A node to check.
  205. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  206. * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
  207. */
  208. function hasJSDocThisTag(node, sourceCode) {
  209. const jsdocComment = sourceCode.getJSDocComment(node);
  210. if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
  211. return true;
  212. }
  213. // Checks `@this` in its leading comments for callbacks,
  214. // because callbacks don't have its JSDoc comment.
  215. // e.g.
  216. // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
  217. return sourceCode.getCommentsBefore(node).some(comment => thisTagPattern.test(comment.value));
  218. }
  219. /**
  220. * Determines if a node is surrounded by parentheses.
  221. * @param {SourceCode} sourceCode The ESLint source code object
  222. * @param {ASTNode} node The node to be checked.
  223. * @returns {boolean} True if the node is parenthesised.
  224. * @private
  225. */
  226. function isParenthesised(sourceCode, node) {
  227. const previousToken = sourceCode.getTokenBefore(node),
  228. nextToken = sourceCode.getTokenAfter(node);
  229. return Boolean(previousToken && nextToken) &&
  230. previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
  231. nextToken.value === ")" && nextToken.range[0] >= node.range[1];
  232. }
  233. /**
  234. * Checks if the given token is an arrow token or not.
  235. * @param {Token} token The token to check.
  236. * @returns {boolean} `true` if the token is an arrow token.
  237. */
  238. function isArrowToken(token) {
  239. return token.value === "=>" && token.type === "Punctuator";
  240. }
  241. /**
  242. * Checks if the given token is a comma token or not.
  243. * @param {Token} token The token to check.
  244. * @returns {boolean} `true` if the token is a comma token.
  245. */
  246. function isCommaToken(token) {
  247. return token.value === "," && token.type === "Punctuator";
  248. }
  249. /**
  250. * Checks if the given token is a dot token or not.
  251. * @param {Token} token The token to check.
  252. * @returns {boolean} `true` if the token is a dot token.
  253. */
  254. function isDotToken(token) {
  255. return token.value === "." && token.type === "Punctuator";
  256. }
  257. /**
  258. * Checks if the given token is a semicolon token or not.
  259. * @param {Token} token The token to check.
  260. * @returns {boolean} `true` if the token is a semicolon token.
  261. */
  262. function isSemicolonToken(token) {
  263. return token.value === ";" && token.type === "Punctuator";
  264. }
  265. /**
  266. * Checks if the given token is a colon token or not.
  267. * @param {Token} token The token to check.
  268. * @returns {boolean} `true` if the token is a colon token.
  269. */
  270. function isColonToken(token) {
  271. return token.value === ":" && token.type === "Punctuator";
  272. }
  273. /**
  274. * Checks if the given token is an opening parenthesis token or not.
  275. * @param {Token} token The token to check.
  276. * @returns {boolean} `true` if the token is an opening parenthesis token.
  277. */
  278. function isOpeningParenToken(token) {
  279. return token.value === "(" && token.type === "Punctuator";
  280. }
  281. /**
  282. * Checks if the given token is a closing parenthesis token or not.
  283. * @param {Token} token The token to check.
  284. * @returns {boolean} `true` if the token is a closing parenthesis token.
  285. */
  286. function isClosingParenToken(token) {
  287. return token.value === ")" && token.type === "Punctuator";
  288. }
  289. /**
  290. * Checks if the given token is an opening square bracket token or not.
  291. * @param {Token} token The token to check.
  292. * @returns {boolean} `true` if the token is an opening square bracket token.
  293. */
  294. function isOpeningBracketToken(token) {
  295. return token.value === "[" && token.type === "Punctuator";
  296. }
  297. /**
  298. * Checks if the given token is a closing square bracket token or not.
  299. * @param {Token} token The token to check.
  300. * @returns {boolean} `true` if the token is a closing square bracket token.
  301. */
  302. function isClosingBracketToken(token) {
  303. return token.value === "]" && token.type === "Punctuator";
  304. }
  305. /**
  306. * Checks if the given token is an opening brace token or not.
  307. * @param {Token} token The token to check.
  308. * @returns {boolean} `true` if the token is an opening brace token.
  309. */
  310. function isOpeningBraceToken(token) {
  311. return token.value === "{" && token.type === "Punctuator";
  312. }
  313. /**
  314. * Checks if the given token is a closing brace token or not.
  315. * @param {Token} token The token to check.
  316. * @returns {boolean} `true` if the token is a closing brace token.
  317. */
  318. function isClosingBraceToken(token) {
  319. return token.value === "}" && token.type === "Punctuator";
  320. }
  321. /**
  322. * Checks if the given token is a comment token or not.
  323. * @param {Token} token The token to check.
  324. * @returns {boolean} `true` if the token is a comment token.
  325. */
  326. function isCommentToken(token) {
  327. return token.type === "Line" || token.type === "Block" || token.type === "Shebang";
  328. }
  329. /**
  330. * Checks if the given token is a keyword token or not.
  331. * @param {Token} token The token to check.
  332. * @returns {boolean} `true` if the token is a keyword token.
  333. */
  334. function isKeywordToken(token) {
  335. return token.type === "Keyword";
  336. }
  337. /**
  338. * Gets the `(` token of the given function node.
  339. * @param {ASTNode} node The function node to get.
  340. * @param {SourceCode} sourceCode The source code object to get tokens.
  341. * @returns {Token} `(` token.
  342. */
  343. function getOpeningParenOfParams(node, sourceCode) {
  344. return node.id
  345. ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
  346. : sourceCode.getFirstToken(node, isOpeningParenToken);
  347. }
  348. /**
  349. * Checks whether or not the tokens of two given nodes are same.
  350. * @param {ASTNode} left A node 1 to compare.
  351. * @param {ASTNode} right A node 2 to compare.
  352. * @param {SourceCode} sourceCode The ESLint source code object.
  353. * @returns {boolean} the source code for the given node.
  354. */
  355. function equalTokens(left, right, sourceCode) {
  356. const tokensL = sourceCode.getTokens(left);
  357. const tokensR = sourceCode.getTokens(right);
  358. if (tokensL.length !== tokensR.length) {
  359. return false;
  360. }
  361. for (let i = 0; i < tokensL.length; ++i) {
  362. if (tokensL[i].type !== tokensR[i].type ||
  363. tokensL[i].value !== tokensR[i].value
  364. ) {
  365. return false;
  366. }
  367. }
  368. return true;
  369. }
  370. //------------------------------------------------------------------------------
  371. // Public Interface
  372. //------------------------------------------------------------------------------
  373. module.exports = {
  374. COMMENTS_IGNORE_PATTERN,
  375. LINEBREAKS,
  376. LINEBREAK_MATCHER: lineBreakPattern,
  377. SHEBANG_MATCHER: shebangPattern,
  378. STATEMENT_LIST_PARENTS,
  379. /**
  380. * Determines whether two adjacent tokens are on the same line.
  381. * @param {Object} left The left token object.
  382. * @param {Object} right The right token object.
  383. * @returns {boolean} Whether or not the tokens are on the same line.
  384. * @public
  385. */
  386. isTokenOnSameLine(left, right) {
  387. return left.loc.end.line === right.loc.start.line;
  388. },
  389. isNullOrUndefined,
  390. isCallee,
  391. isES5Constructor,
  392. getUpperFunction,
  393. isFunction,
  394. isLoop,
  395. isInLoop,
  396. isArrayFromMethod,
  397. isParenthesised,
  398. createGlobalLinebreakMatcher,
  399. equalTokens,
  400. isArrowToken,
  401. isClosingBraceToken,
  402. isClosingBracketToken,
  403. isClosingParenToken,
  404. isColonToken,
  405. isCommaToken,
  406. isCommentToken,
  407. isDotToken,
  408. isKeywordToken,
  409. isNotClosingBraceToken: negate(isClosingBraceToken),
  410. isNotClosingBracketToken: negate(isClosingBracketToken),
  411. isNotClosingParenToken: negate(isClosingParenToken),
  412. isNotColonToken: negate(isColonToken),
  413. isNotCommaToken: negate(isCommaToken),
  414. isNotDotToken: negate(isDotToken),
  415. isNotOpeningBraceToken: negate(isOpeningBraceToken),
  416. isNotOpeningBracketToken: negate(isOpeningBracketToken),
  417. isNotOpeningParenToken: negate(isOpeningParenToken),
  418. isNotSemicolonToken: negate(isSemicolonToken),
  419. isOpeningBraceToken,
  420. isOpeningBracketToken,
  421. isOpeningParenToken,
  422. isSemicolonToken,
  423. /**
  424. * Checks whether or not a given node is a string literal.
  425. * @param {ASTNode} node A node to check.
  426. * @returns {boolean} `true` if the node is a string literal.
  427. */
  428. isStringLiteral(node) {
  429. return (
  430. (node.type === "Literal" && typeof node.value === "string") ||
  431. node.type === "TemplateLiteral"
  432. );
  433. },
  434. /**
  435. * Checks whether a given node is a breakable statement or not.
  436. * The node is breakable if the node is one of the following type:
  437. *
  438. * - DoWhileStatement
  439. * - ForInStatement
  440. * - ForOfStatement
  441. * - ForStatement
  442. * - SwitchStatement
  443. * - WhileStatement
  444. * @param {ASTNode} node A node to check.
  445. * @returns {boolean} `true` if the node is breakable.
  446. */
  447. isBreakableStatement(node) {
  448. return breakableTypePattern.test(node.type);
  449. },
  450. /**
  451. * Gets references which are non initializer and writable.
  452. * @param {Reference[]} references An array of references.
  453. * @returns {Reference[]} An array of only references which are non initializer and writable.
  454. * @public
  455. */
  456. getModifyingReferences(references) {
  457. return references.filter(isModifyingReference);
  458. },
  459. /**
  460. * Validate that a string passed in is surrounded by the specified character
  461. * @param {string} val The text to check.
  462. * @param {string} character The character to see if it's surrounded by.
  463. * @returns {boolean} True if the text is surrounded by the character, false if not.
  464. * @private
  465. */
  466. isSurroundedBy(val, character) {
  467. return val[0] === character && val[val.length - 1] === character;
  468. },
  469. /**
  470. * Returns whether the provided node is an ESLint directive comment or not
  471. * @param {Line|Block} node The comment token to be checked
  472. * @returns {boolean} `true` if the node is an ESLint directive comment
  473. */
  474. isDirectiveComment(node) {
  475. const comment = node.value.trim();
  476. return (
  477. node.type === "Line" && comment.indexOf("eslint-") === 0 ||
  478. node.type === "Block" && (
  479. comment.indexOf("global ") === 0 ||
  480. comment.indexOf("eslint ") === 0 ||
  481. comment.indexOf("eslint-") === 0
  482. )
  483. );
  484. },
  485. /**
  486. * Gets the trailing statement of a given node.
  487. *
  488. * if (code)
  489. * consequent;
  490. *
  491. * When taking this `IfStatement`, returns `consequent;` statement.
  492. * @param {ASTNode} A node to get.
  493. * @returns {ASTNode|null} The trailing statement's node.
  494. */
  495. getTrailingStatement: esutils.ast.trailingStatement,
  496. /**
  497. * Finds the variable by a given name in a given scope and its upper scopes.
  498. * @param {eslint-scope.Scope} initScope A scope to start find.
  499. * @param {string} name A variable name to find.
  500. * @returns {eslint-scope.Variable|null} A found variable or `null`.
  501. */
  502. getVariableByName(initScope, name) {
  503. let scope = initScope;
  504. while (scope) {
  505. const variable = scope.set.get(name);
  506. if (variable) {
  507. return variable;
  508. }
  509. scope = scope.upper;
  510. }
  511. return null;
  512. },
  513. /**
  514. * Checks whether or not a given function node is the default `this` binding.
  515. *
  516. * First, this checks the node:
  517. *
  518. * - The function name does not start with uppercase. It's a convention to capitalize the names
  519. * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
  520. * - The function does not have a JSDoc comment that has a @this tag.
  521. *
  522. * Next, this checks the location of the node.
  523. * If the location is below, this judges `this` is valid.
  524. *
  525. * - The location is not on an object literal.
  526. * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
  527. * functions only, as the name of the variable is considered to be the name of the function in this case.
  528. * This check is not performed if `capIsConstructor` is set to `false`.
  529. * - The location is not on an ES2015 class.
  530. * - Its `bind`/`call`/`apply` method is not called directly.
  531. * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
  532. * @param {ASTNode} node A function node to check.
  533. * @param {SourceCode} sourceCode A SourceCode instance to get comments.
  534. * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
  535. * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
  536. * @returns {boolean} The function node is the default `this` binding.
  537. */
  538. isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
  539. if (
  540. (capIsConstructor && isES5Constructor(node)) ||
  541. hasJSDocThisTag(node, sourceCode)
  542. ) {
  543. return false;
  544. }
  545. const isAnonymous = node.id === null;
  546. let currentNode = node;
  547. while (currentNode) {
  548. const parent = currentNode.parent;
  549. switch (parent.type) {
  550. /*
  551. * Looks up the destination.
  552. * e.g., obj.foo = nativeFoo || function foo() { ... };
  553. */
  554. case "LogicalExpression":
  555. case "ConditionalExpression":
  556. currentNode = parent;
  557. break;
  558. /*
  559. * If the upper function is IIFE, checks the destination of the return value.
  560. * e.g.
  561. * obj.foo = (function() {
  562. * // setup...
  563. * return function foo() { ... };
  564. * })();
  565. * obj.foo = (() =>
  566. * function foo() { ... }
  567. * )();
  568. */
  569. case "ReturnStatement": {
  570. const func = getUpperFunction(parent);
  571. if (func === null || !isCallee(func)) {
  572. return true;
  573. }
  574. currentNode = func.parent;
  575. break;
  576. }
  577. case "ArrowFunctionExpression":
  578. if (currentNode !== parent.body || !isCallee(parent)) {
  579. return true;
  580. }
  581. currentNode = parent.parent;
  582. break;
  583. /*
  584. * e.g.
  585. * var obj = { foo() { ... } };
  586. * var obj = { foo: function() { ... } };
  587. * class A { constructor() { ... } }
  588. * class A { foo() { ... } }
  589. * class A { get foo() { ... } }
  590. * class A { set foo() { ... } }
  591. * class A { static foo() { ... } }
  592. */
  593. case "Property":
  594. case "MethodDefinition":
  595. return parent.value !== currentNode;
  596. /*
  597. * e.g.
  598. * obj.foo = function foo() { ... };
  599. * Foo = function() { ... };
  600. * [obj.foo = function foo() { ... }] = a;
  601. * [Foo = function() { ... }] = a;
  602. */
  603. case "AssignmentExpression":
  604. case "AssignmentPattern":
  605. if (parent.left.type === "MemberExpression") {
  606. return false;
  607. }
  608. if (
  609. capIsConstructor &&
  610. isAnonymous &&
  611. parent.left.type === "Identifier" &&
  612. startsWithUpperCase(parent.left.name)
  613. ) {
  614. return false;
  615. }
  616. return true;
  617. /*
  618. * e.g.
  619. * var Foo = function() { ... };
  620. */
  621. case "VariableDeclarator":
  622. return !(
  623. capIsConstructor &&
  624. isAnonymous &&
  625. parent.init === currentNode &&
  626. parent.id.type === "Identifier" &&
  627. startsWithUpperCase(parent.id.name)
  628. );
  629. /*
  630. * e.g.
  631. * var foo = function foo() { ... }.bind(obj);
  632. * (function foo() { ... }).call(obj);
  633. * (function foo() { ... }).apply(obj, []);
  634. */
  635. case "MemberExpression":
  636. return (
  637. parent.object !== currentNode ||
  638. parent.property.type !== "Identifier" ||
  639. !bindOrCallOrApplyPattern.test(parent.property.name) ||
  640. !isCallee(parent) ||
  641. parent.parent.arguments.length === 0 ||
  642. isNullOrUndefined(parent.parent.arguments[0])
  643. );
  644. /*
  645. * e.g.
  646. * Reflect.apply(function() {}, obj, []);
  647. * Array.from([], function() {}, obj);
  648. * list.forEach(function() {}, obj);
  649. */
  650. case "CallExpression":
  651. if (isReflectApply(parent.callee)) {
  652. return (
  653. parent.arguments.length !== 3 ||
  654. parent.arguments[0] !== currentNode ||
  655. isNullOrUndefined(parent.arguments[1])
  656. );
  657. }
  658. if (isArrayFromMethod(parent.callee)) {
  659. return (
  660. parent.arguments.length !== 3 ||
  661. parent.arguments[1] !== currentNode ||
  662. isNullOrUndefined(parent.arguments[2])
  663. );
  664. }
  665. if (isMethodWhichHasThisArg(parent.callee)) {
  666. return (
  667. parent.arguments.length !== 2 ||
  668. parent.arguments[0] !== currentNode ||
  669. isNullOrUndefined(parent.arguments[1])
  670. );
  671. }
  672. return true;
  673. // Otherwise `this` is default.
  674. default:
  675. return true;
  676. }
  677. }
  678. /* istanbul ignore next */
  679. return true;
  680. },
  681. /**
  682. * Get the precedence level based on the node type
  683. * @param {ASTNode} node node to evaluate
  684. * @returns {int} precedence level
  685. * @private
  686. */
  687. getPrecedence(node) {
  688. switch (node.type) {
  689. case "SequenceExpression":
  690. return 0;
  691. case "AssignmentExpression":
  692. case "ArrowFunctionExpression":
  693. case "YieldExpression":
  694. return 1;
  695. case "ConditionalExpression":
  696. return 3;
  697. case "LogicalExpression":
  698. switch (node.operator) {
  699. case "||":
  700. return 4;
  701. case "&&":
  702. return 5;
  703. // no default
  704. }
  705. /* falls through */
  706. case "BinaryExpression":
  707. switch (node.operator) {
  708. case "|":
  709. return 6;
  710. case "^":
  711. return 7;
  712. case "&":
  713. return 8;
  714. case "==":
  715. case "!=":
  716. case "===":
  717. case "!==":
  718. return 9;
  719. case "<":
  720. case "<=":
  721. case ">":
  722. case ">=":
  723. case "in":
  724. case "instanceof":
  725. return 10;
  726. case "<<":
  727. case ">>":
  728. case ">>>":
  729. return 11;
  730. case "+":
  731. case "-":
  732. return 12;
  733. case "*":
  734. case "/":
  735. case "%":
  736. return 13;
  737. case "**":
  738. return 15;
  739. // no default
  740. }
  741. /* falls through */
  742. case "UnaryExpression":
  743. case "AwaitExpression":
  744. return 16;
  745. case "UpdateExpression":
  746. return 17;
  747. case "CallExpression":
  748. case "ImportExpression":
  749. return 18;
  750. case "NewExpression":
  751. return 19;
  752. default:
  753. return 20;
  754. }
  755. },
  756. /**
  757. * Checks whether the given node is an empty block node or not.
  758. * @param {ASTNode|null} node The node to check.
  759. * @returns {boolean} `true` if the node is an empty block.
  760. */
  761. isEmptyBlock(node) {
  762. return Boolean(node && node.type === "BlockStatement" && node.body.length === 0);
  763. },
  764. /**
  765. * Checks whether the given node is an empty function node or not.
  766. * @param {ASTNode|null} node The node to check.
  767. * @returns {boolean} `true` if the node is an empty function.
  768. */
  769. isEmptyFunction(node) {
  770. return isFunction(node) && module.exports.isEmptyBlock(node.body);
  771. },
  772. /**
  773. * Gets the property name of a given node.
  774. * The node can be a MemberExpression, a Property, or a MethodDefinition.
  775. *
  776. * If the name is dynamic, this returns `null`.
  777. *
  778. * For examples:
  779. *
  780. * a.b // => "b"
  781. * a["b"] // => "b"
  782. * a['b'] // => "b"
  783. * a[`b`] // => "b"
  784. * a[100] // => "100"
  785. * a[b] // => null
  786. * a["a" + "b"] // => null
  787. * a[tag`b`] // => null
  788. * a[`${b}`] // => null
  789. *
  790. * let a = {b: 1} // => "b"
  791. * let a = {["b"]: 1} // => "b"
  792. * let a = {['b']: 1} // => "b"
  793. * let a = {[`b`]: 1} // => "b"
  794. * let a = {[100]: 1} // => "100"
  795. * let a = {[b]: 1} // => null
  796. * let a = {["a" + "b"]: 1} // => null
  797. * let a = {[tag`b`]: 1} // => null
  798. * let a = {[`${b}`]: 1} // => null
  799. * @param {ASTNode} node The node to get.
  800. * @returns {string|null} The property name if static. Otherwise, null.
  801. */
  802. getStaticPropertyName(node) {
  803. let prop;
  804. switch (node && node.type) {
  805. case "Property":
  806. case "MethodDefinition":
  807. prop = node.key;
  808. break;
  809. case "MemberExpression":
  810. prop = node.property;
  811. break;
  812. // no default
  813. }
  814. switch (prop && prop.type) {
  815. case "Literal":
  816. return String(prop.value);
  817. case "TemplateLiteral":
  818. if (prop.expressions.length === 0 && prop.quasis.length === 1) {
  819. return prop.quasis[0].value.cooked;
  820. }
  821. break;
  822. case "Identifier":
  823. if (!node.computed) {
  824. return prop.name;
  825. }
  826. break;
  827. // no default
  828. }
  829. return null;
  830. },
  831. /**
  832. * Get directives from directive prologue of a Program or Function node.
  833. * @param {ASTNode} node The node to check.
  834. * @returns {ASTNode[]} The directives found in the directive prologue.
  835. */
  836. getDirectivePrologue(node) {
  837. const directives = [];
  838. // Directive prologues only occur at the top of files or functions.
  839. if (
  840. node.type === "Program" ||
  841. node.type === "FunctionDeclaration" ||
  842. node.type === "FunctionExpression" ||
  843. /*
  844. * Do not check arrow functions with implicit return.
  845. * `() => "use strict";` returns the string `"use strict"`.
  846. */
  847. (node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement")
  848. ) {
  849. const statements = node.type === "Program" ? node.body : node.body.body;
  850. for (const statement of statements) {
  851. if (
  852. statement.type === "ExpressionStatement" &&
  853. statement.expression.type === "Literal"
  854. ) {
  855. directives.push(statement);
  856. } else {
  857. break;
  858. }
  859. }
  860. }
  861. return directives;
  862. },
  863. /**
  864. * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
  865. * after the node will be parsed as a decimal point, rather than a property-access dot.
  866. * @param {ASTNode} node The node to check.
  867. * @returns {boolean} `true` if this node is a decimal integer.
  868. * @example
  869. *
  870. * 5 // true
  871. * 5. // false
  872. * 5.0 // false
  873. * 05 // false
  874. * 0x5 // false
  875. * 0b101 // false
  876. * 0o5 // false
  877. * 5e0 // false
  878. * '5' // false
  879. */
  880. isDecimalInteger(node) {
  881. return node.type === "Literal" && typeof node.value === "number" &&
  882. DECIMAL_INTEGER_PATTERN.test(node.raw);
  883. },
  884. /**
  885. * Determines whether this token is a decimal integer numeric token.
  886. * This is similar to isDecimalInteger(), but for tokens.
  887. * @param {Token} token The token to check.
  888. * @returns {boolean} `true` if this token is a decimal integer.
  889. */
  890. isDecimalIntegerNumericToken(token) {
  891. return token.type === "Numeric" && DECIMAL_INTEGER_PATTERN.test(token.value);
  892. },
  893. /**
  894. * Gets the name and kind of the given function node.
  895. *
  896. * - `function foo() {}` .................... `function 'foo'`
  897. * - `(function foo() {})` .................. `function 'foo'`
  898. * - `(function() {})` ...................... `function`
  899. * - `function* foo() {}` ................... `generator function 'foo'`
  900. * - `(function* foo() {})` ................. `generator function 'foo'`
  901. * - `(function*() {})` ..................... `generator function`
  902. * - `() => {}` ............................. `arrow function`
  903. * - `async () => {}` ....................... `async arrow function`
  904. * - `({ foo: function foo() {} })` ......... `method 'foo'`
  905. * - `({ foo: function() {} })` ............. `method 'foo'`
  906. * - `({ ['foo']: function() {} })` ......... `method 'foo'`
  907. * - `({ [foo]: function() {} })` ........... `method`
  908. * - `({ foo() {} })` ....................... `method 'foo'`
  909. * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
  910. * - `({ foo: function*() {} })` ............ `generator method 'foo'`
  911. * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
  912. * - `({ [foo]: function*() {} })` .......... `generator method`
  913. * - `({ *foo() {} })` ...................... `generator method 'foo'`
  914. * - `({ foo: async function foo() {} })` ... `async method 'foo'`
  915. * - `({ foo: async function() {} })` ....... `async method 'foo'`
  916. * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
  917. * - `({ [foo]: async function() {} })` ..... `async method`
  918. * - `({ async foo() {} })` ................. `async method 'foo'`
  919. * - `({ get foo() {} })` ................... `getter 'foo'`
  920. * - `({ set foo(a) {} })` .................. `setter 'foo'`
  921. * - `class A { constructor() {} }` ......... `constructor`
  922. * - `class A { foo() {} }` ................. `method 'foo'`
  923. * - `class A { *foo() {} }` ................ `generator method 'foo'`
  924. * - `class A { async foo() {} }` ........... `async method 'foo'`
  925. * - `class A { ['foo']() {} }` ............. `method 'foo'`
  926. * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
  927. * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
  928. * - `class A { [foo]() {} }` ............... `method`
  929. * - `class A { *[foo]() {} }` .............. `generator method`
  930. * - `class A { async [foo]() {} }` ......... `async method`
  931. * - `class A { get foo() {} }` ............. `getter 'foo'`
  932. * - `class A { set foo(a) {} }` ............ `setter 'foo'`
  933. * - `class A { static foo() {} }` .......... `static method 'foo'`
  934. * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
  935. * - `class A { static async foo() {} }` .... `static async method 'foo'`
  936. * - `class A { static get foo() {} }` ...... `static getter 'foo'`
  937. * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
  938. * @param {ASTNode} node The function node to get.
  939. * @returns {string} The name and kind of the function node.
  940. */
  941. getFunctionNameWithKind(node) {
  942. const parent = node.parent;
  943. const tokens = [];
  944. if (parent.type === "MethodDefinition" && parent.static) {
  945. tokens.push("static");
  946. }
  947. if (node.async) {
  948. tokens.push("async");
  949. }
  950. if (node.generator) {
  951. tokens.push("generator");
  952. }
  953. if (node.type === "ArrowFunctionExpression") {
  954. tokens.push("arrow", "function");
  955. } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
  956. if (parent.kind === "constructor") {
  957. return "constructor";
  958. }
  959. if (parent.kind === "get") {
  960. tokens.push("getter");
  961. } else if (parent.kind === "set") {
  962. tokens.push("setter");
  963. } else {
  964. tokens.push("method");
  965. }
  966. } else {
  967. tokens.push("function");
  968. }
  969. if (node.id) {
  970. tokens.push(`'${node.id.name}'`);
  971. } else {
  972. const name = module.exports.getStaticPropertyName(parent);
  973. if (name !== null) {
  974. tokens.push(`'${name}'`);
  975. }
  976. }
  977. return tokens.join(" ");
  978. },
  979. /**
  980. * Gets the location of the given function node for reporting.
  981. *
  982. * - `function foo() {}`
  983. * ^^^^^^^^^^^^
  984. * - `(function foo() {})`
  985. * ^^^^^^^^^^^^
  986. * - `(function() {})`
  987. * ^^^^^^^^
  988. * - `function* foo() {}`
  989. * ^^^^^^^^^^^^^
  990. * - `(function* foo() {})`
  991. * ^^^^^^^^^^^^^
  992. * - `(function*() {})`
  993. * ^^^^^^^^^
  994. * - `() => {}`
  995. * ^^
  996. * - `async () => {}`
  997. * ^^
  998. * - `({ foo: function foo() {} })`
  999. * ^^^^^^^^^^^^^^^^^
  1000. * - `({ foo: function() {} })`
  1001. * ^^^^^^^^^^^^^
  1002. * - `({ ['foo']: function() {} })`
  1003. * ^^^^^^^^^^^^^^^^^
  1004. * - `({ [foo]: function() {} })`
  1005. * ^^^^^^^^^^^^^^^
  1006. * - `({ foo() {} })`
  1007. * ^^^
  1008. * - `({ foo: function* foo() {} })`
  1009. * ^^^^^^^^^^^^^^^^^^
  1010. * - `({ foo: function*() {} })`
  1011. * ^^^^^^^^^^^^^^
  1012. * - `({ ['foo']: function*() {} })`
  1013. * ^^^^^^^^^^^^^^^^^^
  1014. * - `({ [foo]: function*() {} })`
  1015. * ^^^^^^^^^^^^^^^^
  1016. * - `({ *foo() {} })`
  1017. * ^^^^
  1018. * - `({ foo: async function foo() {} })`
  1019. * ^^^^^^^^^^^^^^^^^^^^^^^
  1020. * - `({ foo: async function() {} })`
  1021. * ^^^^^^^^^^^^^^^^^^^
  1022. * - `({ ['foo']: async function() {} })`
  1023. * ^^^^^^^^^^^^^^^^^^^^^^^
  1024. * - `({ [foo]: async function() {} })`
  1025. * ^^^^^^^^^^^^^^^^^^^^^
  1026. * - `({ async foo() {} })`
  1027. * ^^^^^^^^^
  1028. * - `({ get foo() {} })`
  1029. * ^^^^^^^
  1030. * - `({ set foo(a) {} })`
  1031. * ^^^^^^^
  1032. * - `class A { constructor() {} }`
  1033. * ^^^^^^^^^^^
  1034. * - `class A { foo() {} }`
  1035. * ^^^
  1036. * - `class A { *foo() {} }`
  1037. * ^^^^
  1038. * - `class A { async foo() {} }`
  1039. * ^^^^^^^^^
  1040. * - `class A { ['foo']() {} }`
  1041. * ^^^^^^^
  1042. * - `class A { *['foo']() {} }`
  1043. * ^^^^^^^^
  1044. * - `class A { async ['foo']() {} }`
  1045. * ^^^^^^^^^^^^^
  1046. * - `class A { [foo]() {} }`
  1047. * ^^^^^
  1048. * - `class A { *[foo]() {} }`
  1049. * ^^^^^^
  1050. * - `class A { async [foo]() {} }`
  1051. * ^^^^^^^^^^^
  1052. * - `class A { get foo() {} }`
  1053. * ^^^^^^^
  1054. * - `class A { set foo(a) {} }`
  1055. * ^^^^^^^
  1056. * - `class A { static foo() {} }`
  1057. * ^^^^^^^^^^
  1058. * - `class A { static *foo() {} }`
  1059. * ^^^^^^^^^^^
  1060. * - `class A { static async foo() {} }`
  1061. * ^^^^^^^^^^^^^^^^
  1062. * - `class A { static get foo() {} }`
  1063. * ^^^^^^^^^^^^^^
  1064. * - `class A { static set foo(a) {} }`
  1065. * ^^^^^^^^^^^^^^
  1066. * @param {ASTNode} node The function node to get.
  1067. * @param {SourceCode} sourceCode The source code object to get tokens.
  1068. * @returns {string} The location of the function node for reporting.
  1069. */
  1070. getFunctionHeadLoc(node, sourceCode) {
  1071. const parent = node.parent;
  1072. let start = null;
  1073. let end = null;
  1074. if (node.type === "ArrowFunctionExpression") {
  1075. const arrowToken = sourceCode.getTokenBefore(node.body, isArrowToken);
  1076. start = arrowToken.loc.start;
  1077. end = arrowToken.loc.end;
  1078. } else if (parent.type === "Property" || parent.type === "MethodDefinition") {
  1079. start = parent.loc.start;
  1080. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1081. } else {
  1082. start = node.loc.start;
  1083. end = getOpeningParenOfParams(node, sourceCode).loc.start;
  1084. }
  1085. return {
  1086. start: Object.assign({}, start),
  1087. end: Object.assign({}, end)
  1088. };
  1089. },
  1090. /**
  1091. * Gets next location when the result is not out of bound, otherwise returns null.
  1092. * @param {SourceCode} sourceCode The sourceCode
  1093. * @param {{line: number, column: number}} location The location
  1094. * @returns {{line: number, column: number} | null} Next location
  1095. */
  1096. getNextLocation(sourceCode, location) {
  1097. const index = sourceCode.getIndexFromLoc(location);
  1098. // Avoid out of bound location
  1099. if (index + 1 > sourceCode.text.length) {
  1100. return null;
  1101. }
  1102. return sourceCode.getLocFromIndex(index + 1);
  1103. },
  1104. /**
  1105. * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
  1106. * surrounding the node.
  1107. * @param {SourceCode} sourceCode The source code object
  1108. * @param {ASTNode} node An expression node
  1109. * @returns {string} The text representing the node, with all surrounding parentheses included
  1110. */
  1111. getParenthesisedText(sourceCode, node) {
  1112. let leftToken = sourceCode.getFirstToken(node);
  1113. let rightToken = sourceCode.getLastToken(node);
  1114. while (
  1115. sourceCode.getTokenBefore(leftToken) &&
  1116. sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
  1117. sourceCode.getTokenBefore(leftToken).value === "(" &&
  1118. sourceCode.getTokenAfter(rightToken) &&
  1119. sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
  1120. sourceCode.getTokenAfter(rightToken).value === ")"
  1121. ) {
  1122. leftToken = sourceCode.getTokenBefore(leftToken);
  1123. rightToken = sourceCode.getTokenAfter(rightToken);
  1124. }
  1125. return sourceCode.getText().slice(leftToken.range[0], rightToken.range[1]);
  1126. },
  1127. /*
  1128. * Determine if a node has a possiblity to be an Error object
  1129. * @param {ASTNode} node ASTNode to check
  1130. * @returns {boolean} True if there is a chance it contains an Error obj
  1131. */
  1132. couldBeError(node) {
  1133. switch (node.type) {
  1134. case "Identifier":
  1135. case "CallExpression":
  1136. case "NewExpression":
  1137. case "MemberExpression":
  1138. case "TaggedTemplateExpression":
  1139. case "YieldExpression":
  1140. case "AwaitExpression":
  1141. return true; // possibly an error object.
  1142. case "AssignmentExpression":
  1143. return module.exports.couldBeError(node.right);
  1144. case "SequenceExpression": {
  1145. const exprs = node.expressions;
  1146. return exprs.length !== 0 && module.exports.couldBeError(exprs[exprs.length - 1]);
  1147. }
  1148. case "LogicalExpression":
  1149. return module.exports.couldBeError(node.left) || module.exports.couldBeError(node.right);
  1150. case "ConditionalExpression":
  1151. return module.exports.couldBeError(node.consequent) || module.exports.couldBeError(node.alternate);
  1152. default:
  1153. return false;
  1154. }
  1155. },
  1156. /**
  1157. * Determines whether the given node is a `null` literal.
  1158. * @param {ASTNode} node The node to check
  1159. * @returns {boolean} `true` if the node is a `null` literal
  1160. */
  1161. isNullLiteral(node) {
  1162. /*
  1163. * Checking `node.value === null` does not guarantee that a literal is a null literal.
  1164. * When parsing values that cannot be represented in the current environment (e.g. unicode
  1165. * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
  1166. * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
  1167. * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
  1168. */
  1169. return node.type === "Literal" && node.value === null && !node.regex && !node.bigint;
  1170. },
  1171. /**
  1172. * Determines whether two tokens can safely be placed next to each other without merging into a single token
  1173. * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
  1174. * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
  1175. * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
  1176. * next to each other, behavior is undefined (although it should return `true` in most cases).
  1177. */
  1178. canTokensBeAdjacent(leftValue, rightValue) {
  1179. let leftToken;
  1180. if (typeof leftValue === "string") {
  1181. const leftTokens = espree.tokenize(leftValue, { ecmaVersion: 2015 });
  1182. leftToken = leftTokens[leftTokens.length - 1];
  1183. } else {
  1184. leftToken = leftValue;
  1185. }
  1186. const rightToken = typeof rightValue === "string" ? espree.tokenize(rightValue, { ecmaVersion: 2015 })[0] : rightValue;
  1187. if (leftToken.type === "Punctuator" || rightToken.type === "Punctuator") {
  1188. if (leftToken.type === "Punctuator" && rightToken.type === "Punctuator") {
  1189. const PLUS_TOKENS = new Set(["+", "++"]);
  1190. const MINUS_TOKENS = new Set(["-", "--"]);
  1191. return !(
  1192. PLUS_TOKENS.has(leftToken.value) && PLUS_TOKENS.has(rightToken.value) ||
  1193. MINUS_TOKENS.has(leftToken.value) && MINUS_TOKENS.has(rightToken.value)
  1194. );
  1195. }
  1196. return true;
  1197. }
  1198. if (
  1199. leftToken.type === "String" || rightToken.type === "String" ||
  1200. leftToken.type === "Template" || rightToken.type === "Template"
  1201. ) {
  1202. return true;
  1203. }
  1204. if (leftToken.type !== "Numeric" && rightToken.type === "Numeric" && rightToken.value.startsWith(".")) {
  1205. return true;
  1206. }
  1207. return false;
  1208. },
  1209. /**
  1210. * Get the `loc` object of a given name in a `/*globals` directive comment.
  1211. * @param {SourceCode} sourceCode The source code to convert index to loc.
  1212. * @param {Comment} comment The `/*globals` directive comment which include the name.
  1213. * @param {string} name The name to find.
  1214. * @returns {SourceLocation} The `loc` object.
  1215. */
  1216. getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
  1217. const namePattern = new RegExp(`[\\s,]${lodash.escapeRegExp(name)}(?:$|[\\s,:])`, "gu");
  1218. // To ignore the first text "global".
  1219. namePattern.lastIndex = comment.value.indexOf("global") + 6;
  1220. // Search a given variable name.
  1221. const match = namePattern.exec(comment.value);
  1222. // Convert the index to loc.
  1223. return sourceCode.getLocFromIndex(
  1224. comment.range[0] +
  1225. "/*".length +
  1226. (match ? match.index + 1 : 0)
  1227. );
  1228. },
  1229. /**
  1230. * Determines whether the given raw string contains an octal escape sequence.
  1231. *
  1232. * "\1", "\2" ... "\7"
  1233. * "\00", "\01" ... "\09"
  1234. *
  1235. * "\0", when not followed by a digit, is not an octal escape sequence.
  1236. * @param {string} rawString A string in its raw representation.
  1237. * @returns {boolean} `true` if the string contains at least one octal escape sequence.
  1238. */
  1239. hasOctalEscapeSequence(rawString) {
  1240. return OCTAL_ESCAPE_PATTERN.test(rawString);
  1241. }
  1242. };