logical-assignment-operators.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /**
  2. * @fileoverview Rule to replace assignment expressions with logical operator assignment
  3. * @author Daniel Martens
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils.js");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const baseTypes = new Set(["Identifier", "Super", "ThisExpression"]);
  14. /**
  15. * Returns true iff either "undefined" or a void expression (eg. "void 0")
  16. * @param {ASTNode} expression Expression to check
  17. * @param {import('eslint-scope').Scope} scope Scope of the expression
  18. * @returns {boolean} True iff "undefined" or "void ..."
  19. */
  20. function isUndefined(expression, scope) {
  21. if (expression.type === "Identifier" && expression.name === "undefined") {
  22. return astUtils.isReferenceToGlobalVariable(scope, expression);
  23. }
  24. return expression.type === "UnaryExpression" &&
  25. expression.operator === "void" &&
  26. expression.argument.type === "Literal" &&
  27. expression.argument.value === 0;
  28. }
  29. /**
  30. * Returns true iff the reference is either an identifier or member expression
  31. * @param {ASTNode} expression Expression to check
  32. * @returns {boolean} True for identifiers and member expressions
  33. */
  34. function isReference(expression) {
  35. return (expression.type === "Identifier" && expression.name !== "undefined") ||
  36. expression.type === "MemberExpression";
  37. }
  38. /**
  39. * Returns true iff the expression checks for nullish with loose equals.
  40. * Examples: value == null, value == void 0
  41. * @param {ASTNode} expression Test condition
  42. * @param {import('eslint-scope').Scope} scope Scope of the expression
  43. * @returns {boolean} True iff implicit nullish comparison
  44. */
  45. function isImplicitNullishComparison(expression, scope) {
  46. if (expression.type !== "BinaryExpression" || expression.operator !== "==") {
  47. return false;
  48. }
  49. const reference = isReference(expression.left) ? "left" : "right";
  50. const nullish = reference === "left" ? "right" : "left";
  51. return isReference(expression[reference]) &&
  52. (astUtils.isNullLiteral(expression[nullish]) || isUndefined(expression[nullish], scope));
  53. }
  54. /**
  55. * Condition with two equal comparisons.
  56. * @param {ASTNode} expression Condition
  57. * @returns {boolean} True iff matches ? === ? || ? === ?
  58. */
  59. function isDoubleComparison(expression) {
  60. return expression.type === "LogicalExpression" &&
  61. expression.operator === "||" &&
  62. expression.left.type === "BinaryExpression" &&
  63. expression.left.operator === "===" &&
  64. expression.right.type === "BinaryExpression" &&
  65. expression.right.operator === "===";
  66. }
  67. /**
  68. * Returns true iff the expression checks for undefined and null.
  69. * Example: value === null || value === undefined
  70. * @param {ASTNode} expression Test condition
  71. * @param {import('eslint-scope').Scope} scope Scope of the expression
  72. * @returns {boolean} True iff explicit nullish comparison
  73. */
  74. function isExplicitNullishComparison(expression, scope) {
  75. if (!isDoubleComparison(expression)) {
  76. return false;
  77. }
  78. const leftReference = isReference(expression.left.left) ? "left" : "right";
  79. const leftNullish = leftReference === "left" ? "right" : "left";
  80. const rightReference = isReference(expression.right.left) ? "left" : "right";
  81. const rightNullish = rightReference === "left" ? "right" : "left";
  82. return astUtils.isSameReference(expression.left[leftReference], expression.right[rightReference]) &&
  83. ((astUtils.isNullLiteral(expression.left[leftNullish]) && isUndefined(expression.right[rightNullish], scope)) ||
  84. (isUndefined(expression.left[leftNullish], scope) && astUtils.isNullLiteral(expression.right[rightNullish])));
  85. }
  86. /**
  87. * Returns true for Boolean(arg) calls
  88. * @param {ASTNode} expression Test condition
  89. * @param {import('eslint-scope').Scope} scope Scope of the expression
  90. * @returns {boolean} Whether the expression is a boolean cast
  91. */
  92. function isBooleanCast(expression, scope) {
  93. return expression.type === "CallExpression" &&
  94. expression.callee.name === "Boolean" &&
  95. expression.arguments.length === 1 &&
  96. astUtils.isReferenceToGlobalVariable(scope, expression.callee);
  97. }
  98. /**
  99. * Returns true for:
  100. * truthiness checks: value, Boolean(value), !!value
  101. * falsiness checks: !value, !Boolean(value)
  102. * nullish checks: value == null, value === undefined || value === null
  103. * @param {ASTNode} expression Test condition
  104. * @param {import('eslint-scope').Scope} scope Scope of the expression
  105. * @returns {?{ reference: ASTNode, operator: '??'|'||'|'&&'}} Null if not a known existence
  106. */
  107. function getExistence(expression, scope) {
  108. const isNegated = expression.type === "UnaryExpression" && expression.operator === "!";
  109. const base = isNegated ? expression.argument : expression;
  110. switch (true) {
  111. case isReference(base):
  112. return { reference: base, operator: isNegated ? "||" : "&&" };
  113. case base.type === "UnaryExpression" && base.operator === "!" && isReference(base.argument):
  114. return { reference: base.argument, operator: "&&" };
  115. case isBooleanCast(base, scope) && isReference(base.arguments[0]):
  116. return { reference: base.arguments[0], operator: isNegated ? "||" : "&&" };
  117. case isImplicitNullishComparison(expression, scope):
  118. return { reference: isReference(expression.left) ? expression.left : expression.right, operator: "??" };
  119. case isExplicitNullishComparison(expression, scope):
  120. return { reference: isReference(expression.left.left) ? expression.left.left : expression.left.right, operator: "??" };
  121. default: return null;
  122. }
  123. }
  124. /**
  125. * Returns true iff the node is inside a with block
  126. * @param {ASTNode} node Node to check
  127. * @returns {boolean} True iff passed node is inside a with block
  128. */
  129. function isInsideWithBlock(node) {
  130. if (node.type === "Program") {
  131. return false;
  132. }
  133. return node.parent.type === "WithStatement" && node.parent.body === node ? true : isInsideWithBlock(node.parent);
  134. }
  135. //------------------------------------------------------------------------------
  136. // Rule Definition
  137. //------------------------------------------------------------------------------
  138. /** @type {import('../shared/types').Rule} */
  139. module.exports = {
  140. meta: {
  141. type: "suggestion",
  142. docs: {
  143. description: "Require or disallow logical assignment operator shorthand",
  144. recommended: false,
  145. url: "https://eslint.org/docs/latest/rules/logical-assignment-operators"
  146. },
  147. schema: {
  148. type: "array",
  149. oneOf: [{
  150. items: [
  151. { const: "always" },
  152. {
  153. type: "object",
  154. properties: {
  155. enforceForIfStatements: {
  156. type: "boolean"
  157. }
  158. },
  159. additionalProperties: false
  160. }
  161. ],
  162. minItems: 0, // 0 for allowing passing no options
  163. maxItems: 2
  164. }, {
  165. items: [{ const: "never" }],
  166. minItems: 1,
  167. maxItems: 1
  168. }]
  169. },
  170. fixable: "code",
  171. hasSuggestions: true,
  172. messages: {
  173. assignment: "Assignment (=) can be replaced with operator assignment ({{operator}}).",
  174. useLogicalOperator: "Convert this assignment to use the operator {{ operator }}.",
  175. logical: "Logical expression can be replaced with an assignment ({{ operator }}).",
  176. convertLogical: "Replace this logical expression with an assignment with the operator {{ operator }}.",
  177. if: "'if' statement can be replaced with a logical operator assignment with operator {{ operator }}.",
  178. convertIf: "Replace this 'if' statement with a logical assignment with operator {{ operator }}.",
  179. unexpected: "Unexpected logical operator assignment ({{operator}}) shorthand.",
  180. separate: "Separate the logical assignment into an assignment with a logical operator."
  181. }
  182. },
  183. create(context) {
  184. const mode = context.options[0] === "never" ? "never" : "always";
  185. const checkIf = mode === "always" && context.options.length > 1 && context.options[1].enforceForIfStatements;
  186. const sourceCode = context.sourceCode;
  187. const isStrict = sourceCode.getScope(sourceCode.ast).isStrict;
  188. /**
  189. * Returns false if the access could be a getter
  190. * @param {ASTNode} node Assignment expression
  191. * @returns {boolean} True iff the fix is safe
  192. */
  193. function cannotBeGetter(node) {
  194. return node.type === "Identifier" &&
  195. (isStrict || !isInsideWithBlock(node));
  196. }
  197. /**
  198. * Check whether only a single property is accessed
  199. * @param {ASTNode} node reference
  200. * @returns {boolean} True iff a single property is accessed
  201. */
  202. function accessesSingleProperty(node) {
  203. if (!isStrict && isInsideWithBlock(node)) {
  204. return node.type === "Identifier";
  205. }
  206. return node.type === "MemberExpression" &&
  207. baseTypes.has(node.object.type) &&
  208. (!node.computed || (node.property.type !== "MemberExpression" && node.property.type !== "ChainExpression"));
  209. }
  210. /**
  211. * Adds a fixer or suggestion whether on the fix is safe.
  212. * @param {{ messageId: string, node: ASTNode }} descriptor Report descriptor without fix or suggest
  213. * @param {{ messageId: string, fix: Function }} suggestion Adds the fix or the whole suggestion as only element in "suggest" to suggestion
  214. * @param {boolean} shouldBeFixed Fix iff the condition is true
  215. * @returns {Object} Descriptor with either an added fix or suggestion
  216. */
  217. function createConditionalFixer(descriptor, suggestion, shouldBeFixed) {
  218. if (shouldBeFixed) {
  219. return {
  220. ...descriptor,
  221. fix: suggestion.fix
  222. };
  223. }
  224. return {
  225. ...descriptor,
  226. suggest: [suggestion]
  227. };
  228. }
  229. /**
  230. * Returns the operator token for assignments and binary expressions
  231. * @param {ASTNode} node AssignmentExpression or BinaryExpression
  232. * @returns {import('eslint').AST.Token} Operator token between the left and right expression
  233. */
  234. function getOperatorToken(node) {
  235. return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  236. }
  237. if (mode === "never") {
  238. return {
  239. // foo ||= bar
  240. "AssignmentExpression"(assignment) {
  241. if (!astUtils.isLogicalAssignmentOperator(assignment.operator)) {
  242. return;
  243. }
  244. const descriptor = {
  245. messageId: "unexpected",
  246. node: assignment,
  247. data: { operator: assignment.operator }
  248. };
  249. const suggestion = {
  250. messageId: "separate",
  251. *fix(ruleFixer) {
  252. if (sourceCode.getCommentsInside(assignment).length > 0) {
  253. return;
  254. }
  255. const operatorToken = getOperatorToken(assignment);
  256. // -> foo = bar
  257. yield ruleFixer.replaceText(operatorToken, "=");
  258. const assignmentText = sourceCode.getText(assignment.left);
  259. const operator = assignment.operator.slice(0, -1);
  260. // -> foo = foo || bar
  261. yield ruleFixer.insertTextAfter(operatorToken, ` ${assignmentText} ${operator}`);
  262. const precedence = astUtils.getPrecedence(assignment.right) <= astUtils.getPrecedence({ type: "LogicalExpression", operator });
  263. // ?? and || / && cannot be mixed but have same precedence
  264. const mixed = assignment.operator === "??=" && astUtils.isLogicalExpression(assignment.right);
  265. if (!astUtils.isParenthesised(sourceCode, assignment.right) && (precedence || mixed)) {
  266. // -> foo = foo || (bar)
  267. yield ruleFixer.insertTextBefore(assignment.right, "(");
  268. yield ruleFixer.insertTextAfter(assignment.right, ")");
  269. }
  270. }
  271. };
  272. context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left)));
  273. }
  274. };
  275. }
  276. return {
  277. // foo = foo || bar
  278. "AssignmentExpression[operator='='][right.type='LogicalExpression']"(assignment) {
  279. if (!astUtils.isSameReference(assignment.left, assignment.right.left)) {
  280. return;
  281. }
  282. const descriptor = {
  283. messageId: "assignment",
  284. node: assignment,
  285. data: { operator: `${assignment.right.operator}=` }
  286. };
  287. const suggestion = {
  288. messageId: "useLogicalOperator",
  289. data: { operator: `${assignment.right.operator}=` },
  290. *fix(ruleFixer) {
  291. if (sourceCode.getCommentsInside(assignment).length > 0) {
  292. return;
  293. }
  294. // No need for parenthesis around the assignment based on precedence as the precedence stays the same even with changed operator
  295. const assignmentOperatorToken = getOperatorToken(assignment);
  296. // -> foo ||= foo || bar
  297. yield ruleFixer.insertTextBefore(assignmentOperatorToken, assignment.right.operator);
  298. // -> foo ||= bar
  299. const logicalOperatorToken = getOperatorToken(assignment.right);
  300. const firstRightOperandToken = sourceCode.getTokenAfter(logicalOperatorToken);
  301. yield ruleFixer.removeRange([assignment.right.range[0], firstRightOperandToken.range[0]]);
  302. }
  303. };
  304. context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left)));
  305. },
  306. // foo || (foo = bar)
  307. 'LogicalExpression[right.type="AssignmentExpression"][right.operator="="]'(logical) {
  308. // Right side has to be parenthesized, otherwise would be parsed as (foo || foo) = bar which is illegal
  309. if (isReference(logical.left) && astUtils.isSameReference(logical.left, logical.right.left)) {
  310. const descriptor = {
  311. messageId: "logical",
  312. node: logical,
  313. data: { operator: `${logical.operator}=` }
  314. };
  315. const suggestion = {
  316. messageId: "convertLogical",
  317. data: { operator: `${logical.operator}=` },
  318. *fix(ruleFixer) {
  319. if (sourceCode.getCommentsInside(logical).length > 0) {
  320. return;
  321. }
  322. const parentPrecedence = astUtils.getPrecedence(logical.parent);
  323. const requiresOuterParenthesis = logical.parent.type !== "ExpressionStatement" && (
  324. parentPrecedence === -1 ||
  325. astUtils.getPrecedence({ type: "AssignmentExpression" }) < parentPrecedence
  326. );
  327. if (!astUtils.isParenthesised(sourceCode, logical) && requiresOuterParenthesis) {
  328. yield ruleFixer.insertTextBefore(logical, "(");
  329. yield ruleFixer.insertTextAfter(logical, ")");
  330. }
  331. // Also removes all opening parenthesis
  332. yield ruleFixer.removeRange([logical.range[0], logical.right.range[0]]); // -> foo = bar)
  333. // Also removes all ending parenthesis
  334. yield ruleFixer.removeRange([logical.right.range[1], logical.range[1]]); // -> foo = bar
  335. const operatorToken = getOperatorToken(logical.right);
  336. yield ruleFixer.insertTextBefore(operatorToken, logical.operator); // -> foo ||= bar
  337. }
  338. };
  339. const fix = cannotBeGetter(logical.left) || accessesSingleProperty(logical.left);
  340. context.report(createConditionalFixer(descriptor, suggestion, fix));
  341. }
  342. },
  343. // if (foo) foo = bar
  344. "IfStatement[alternate=null]"(ifNode) {
  345. if (!checkIf) {
  346. return;
  347. }
  348. const hasBody = ifNode.consequent.type === "BlockStatement";
  349. if (hasBody && ifNode.consequent.body.length !== 1) {
  350. return;
  351. }
  352. const body = hasBody ? ifNode.consequent.body[0] : ifNode.consequent;
  353. const scope = sourceCode.getScope(ifNode);
  354. const existence = getExistence(ifNode.test, scope);
  355. if (
  356. body.type === "ExpressionStatement" &&
  357. body.expression.type === "AssignmentExpression" &&
  358. body.expression.operator === "=" &&
  359. existence !== null &&
  360. astUtils.isSameReference(existence.reference, body.expression.left)
  361. ) {
  362. const descriptor = {
  363. messageId: "if",
  364. node: ifNode,
  365. data: { operator: `${existence.operator}=` }
  366. };
  367. const suggestion = {
  368. messageId: "convertIf",
  369. data: { operator: `${existence.operator}=` },
  370. *fix(ruleFixer) {
  371. if (sourceCode.getCommentsInside(ifNode).length > 0) {
  372. return;
  373. }
  374. const firstBodyToken = sourceCode.getFirstToken(body);
  375. const prevToken = sourceCode.getTokenBefore(ifNode);
  376. if (
  377. prevToken !== null &&
  378. prevToken.value !== ";" &&
  379. prevToken.value !== "{" &&
  380. firstBodyToken.type !== "Identifier" &&
  381. firstBodyToken.type !== "Keyword"
  382. ) {
  383. // Do not fix if the fixed statement could be part of the previous statement (eg. fn() if (a == null) (a) = b --> fn()(a) ??= b)
  384. return;
  385. }
  386. const operatorToken = getOperatorToken(body.expression);
  387. yield ruleFixer.insertTextBefore(operatorToken, existence.operator); // -> if (foo) foo ||= bar
  388. yield ruleFixer.removeRange([ifNode.range[0], body.range[0]]); // -> foo ||= bar
  389. yield ruleFixer.removeRange([body.range[1], ifNode.range[1]]); // -> foo ||= bar, only present if "if" had a body
  390. const nextToken = sourceCode.getTokenAfter(body.expression);
  391. if (hasBody && (nextToken !== null && nextToken.value !== ";")) {
  392. yield ruleFixer.insertTextAfter(ifNode, ";");
  393. }
  394. }
  395. };
  396. const shouldBeFixed = cannotBeGetter(existence.reference) ||
  397. (ifNode.test.type !== "LogicalExpression" && accessesSingleProperty(existence.reference));
  398. context.report(createConditionalFixer(descriptor, suggestion, shouldBeFixed));
  399. }
  400. }
  401. };
  402. }
  403. };