logical-assignment-operators.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. * falsyness 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 logical operator shorthand",
  144. recommended: false,
  145. url: "https://eslint.org/docs/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. // eslint-disable-next-line eslint-plugin/require-meta-has-suggestions -- Does not detect conditional suggestions
  172. hasSuggestions: true,
  173. messages: {
  174. assignment: "Assignment (=) can be replaced with operator assignment ({{operator}}).",
  175. useLogicalOperator: "Convert this assignment to use the operator {{ operator }}.",
  176. logical: "Logical expression can be replaced with an assignment ({{ operator }}).",
  177. convertLogical: "Replace this logical expression with an assignment with the operator {{ operator }}.",
  178. if: "'if' statement can be replaced with a logical operator assignment with operator {{ operator }}.",
  179. convertIf: "Replace this 'if' statement with a logical assignment with operator {{ operator }}.",
  180. unexpected: "Unexpected logical operator assignment ({{operator}}) shorthand.",
  181. separate: "Separate the logical assignment into an assignment with a logical operator."
  182. }
  183. },
  184. create(context) {
  185. const mode = context.options[0] === "never" ? "never" : "always";
  186. const checkIf = mode === "always" && context.options.length > 1 && context.options[1].enforceForIfStatements;
  187. const sourceCode = context.getSourceCode();
  188. const isStrict = context.getScope().isStrict;
  189. /**
  190. * Returns false if the access could be a getter
  191. * @param {ASTNode} node Assignment expression
  192. * @returns {boolean} True iff the fix is safe
  193. */
  194. function cannotBeGetter(node) {
  195. return node.type === "Identifier" &&
  196. (isStrict || !isInsideWithBlock(node));
  197. }
  198. /**
  199. * Check whether only a single property is accessed
  200. * @param {ASTNode} node reference
  201. * @returns {boolean} True iff a single property is accessed
  202. */
  203. function accessesSingleProperty(node) {
  204. if (!isStrict && isInsideWithBlock(node)) {
  205. return node.type === "Identifier";
  206. }
  207. return node.type === "MemberExpression" &&
  208. baseTypes.has(node.object.type) &&
  209. (!node.computed || (node.property.type !== "MemberExpression" && node.property.type !== "ChainExpression"));
  210. }
  211. /**
  212. * Adds a fixer or suggestion whether on the fix is safe.
  213. * @param {{ messageId: string, node: ASTNode }} descriptor Report descriptor without fix or suggest
  214. * @param {{ messageId: string, fix: Function }} suggestion Adds the fix or the whole suggestion as only element in "suggest" to suggestion
  215. * @param {boolean} shouldBeFixed Fix iff the condition is true
  216. * @returns {Object} Descriptor with either an added fix or suggestion
  217. */
  218. function createConditionalFixer(descriptor, suggestion, shouldBeFixed) {
  219. if (shouldBeFixed) {
  220. return {
  221. ...descriptor,
  222. fix: suggestion.fix
  223. };
  224. }
  225. return {
  226. ...descriptor,
  227. suggest: [suggestion]
  228. };
  229. }
  230. /**
  231. * Returns the operator token for assignments and binary expressions
  232. * @param {ASTNode} node AssignmentExpression or BinaryExpression
  233. * @returns {import('eslint').AST.Token} Operator token between the left and right expression
  234. */
  235. function getOperatorToken(node) {
  236. return sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
  237. }
  238. if (mode === "never") {
  239. return {
  240. // foo ||= bar
  241. "AssignmentExpression"(assignment) {
  242. if (!astUtils.isLogicalAssignmentOperator(assignment.operator)) {
  243. return;
  244. }
  245. const descriptor = {
  246. messageId: "unexpected",
  247. node: assignment,
  248. data: { operator: assignment.operator }
  249. };
  250. const suggestion = {
  251. messageId: "separate",
  252. *fix(ruleFixer) {
  253. if (sourceCode.getCommentsInside(assignment).length > 0) {
  254. return;
  255. }
  256. const operatorToken = getOperatorToken(assignment);
  257. // -> foo = bar
  258. yield ruleFixer.replaceText(operatorToken, "=");
  259. const assignmentText = sourceCode.getText(assignment.left);
  260. const operator = assignment.operator.slice(0, -1);
  261. // -> foo = foo || bar
  262. yield ruleFixer.insertTextAfter(operatorToken, ` ${assignmentText} ${operator}`);
  263. const precedence = astUtils.getPrecedence(assignment.right) <= astUtils.getPrecedence({ type: "LogicalExpression", operator });
  264. // ?? and || / && cannot be mixed but have same precedence
  265. const mixed = assignment.operator === "??=" && astUtils.isLogicalExpression(assignment.right);
  266. if (!astUtils.isParenthesised(sourceCode, assignment.right) && (precedence || mixed)) {
  267. // -> foo = foo || (bar)
  268. yield ruleFixer.insertTextBefore(assignment.right, "(");
  269. yield ruleFixer.insertTextAfter(assignment.right, ")");
  270. }
  271. }
  272. };
  273. context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left)));
  274. }
  275. };
  276. }
  277. return {
  278. // foo = foo || bar
  279. "AssignmentExpression[operator='='][right.type='LogicalExpression']"(assignment) {
  280. if (!astUtils.isSameReference(assignment.left, assignment.right.left)) {
  281. return;
  282. }
  283. const descriptor = {
  284. messageId: "assignment",
  285. node: assignment,
  286. data: { operator: `${assignment.right.operator}=` }
  287. };
  288. const suggestion = {
  289. messageId: "useLogicalOperator",
  290. data: { operator: `${assignment.right.operator}=` },
  291. *fix(ruleFixer) {
  292. if (sourceCode.getCommentsInside(assignment).length > 0) {
  293. return;
  294. }
  295. // No need for parenthesis around the assignment based on precedence as the precedence stays the same even with changed operator
  296. const assignmentOperatorToken = getOperatorToken(assignment);
  297. // -> foo ||= foo || bar
  298. yield ruleFixer.insertTextBefore(assignmentOperatorToken, assignment.right.operator);
  299. // -> foo ||= bar
  300. const logicalOperatorToken = getOperatorToken(assignment.right);
  301. const firstRightOperandToken = sourceCode.getTokenAfter(logicalOperatorToken);
  302. yield ruleFixer.removeRange([assignment.right.range[0], firstRightOperandToken.range[0]]);
  303. }
  304. };
  305. context.report(createConditionalFixer(descriptor, suggestion, cannotBeGetter(assignment.left)));
  306. },
  307. // foo || (foo = bar)
  308. 'LogicalExpression[right.type="AssignmentExpression"][right.operator="="]'(logical) {
  309. // Right side has to be parenthesized, otherwise would be parsed as (foo || foo) = bar which is illegal
  310. if (isReference(logical.left) && astUtils.isSameReference(logical.left, logical.right.left)) {
  311. const descriptor = {
  312. messageId: "logical",
  313. node: logical,
  314. data: { operator: `${logical.operator}=` }
  315. };
  316. const suggestion = {
  317. messageId: "convertLogical",
  318. data: { operator: `${logical.operator}=` },
  319. *fix(ruleFixer) {
  320. if (sourceCode.getCommentsInside(logical).length > 0) {
  321. return;
  322. }
  323. const requiresOuterParenthesis = logical.parent.type !== "ExpressionStatement" &&
  324. (astUtils.getPrecedence({ type: "AssignmentExpression" }) < astUtils.getPrecedence(logical.parent));
  325. if (!astUtils.isParenthesised(sourceCode, logical) && requiresOuterParenthesis) {
  326. yield ruleFixer.insertTextBefore(logical, "(");
  327. yield ruleFixer.insertTextAfter(logical, ")");
  328. }
  329. // Also removes all opening parenthesis
  330. yield ruleFixer.removeRange([logical.range[0], logical.right.range[0]]); // -> foo = bar)
  331. // Also removes all ending parenthesis
  332. yield ruleFixer.removeRange([logical.right.range[1], logical.range[1]]); // -> foo = bar
  333. const operatorToken = getOperatorToken(logical.right);
  334. yield ruleFixer.insertTextBefore(operatorToken, logical.operator); // -> foo ||= bar
  335. }
  336. };
  337. const fix = cannotBeGetter(logical.left) || accessesSingleProperty(logical.left);
  338. context.report(createConditionalFixer(descriptor, suggestion, fix));
  339. }
  340. },
  341. // if (foo) foo = bar
  342. "IfStatement[alternate=null]"(ifNode) {
  343. if (!checkIf) {
  344. return;
  345. }
  346. const hasBody = ifNode.consequent.type === "BlockStatement";
  347. if (hasBody && ifNode.consequent.body.length !== 1) {
  348. return;
  349. }
  350. const body = hasBody ? ifNode.consequent.body[0] : ifNode.consequent;
  351. const scope = context.getScope();
  352. const existence = getExistence(ifNode.test, scope);
  353. if (
  354. body.type === "ExpressionStatement" &&
  355. body.expression.type === "AssignmentExpression" &&
  356. body.expression.operator === "=" &&
  357. existence !== null &&
  358. astUtils.isSameReference(existence.reference, body.expression.left)
  359. ) {
  360. const descriptor = {
  361. messageId: "if",
  362. node: ifNode,
  363. data: { operator: `${existence.operator}=` }
  364. };
  365. const suggestion = {
  366. messageId: "convertIf",
  367. data: { operator: `${existence.operator}=` },
  368. *fix(ruleFixer) {
  369. if (sourceCode.getCommentsInside(ifNode).length > 0) {
  370. return;
  371. }
  372. const firstBodyToken = sourceCode.getFirstToken(body);
  373. const prevToken = sourceCode.getTokenBefore(ifNode);
  374. if (
  375. prevToken !== null &&
  376. prevToken.value !== ";" &&
  377. prevToken.value !== "{" &&
  378. firstBodyToken.type !== "Identifier" &&
  379. firstBodyToken.type !== "Keyword"
  380. ) {
  381. // Do not fix if the fixed statement could be part of the previous statement (eg. fn() if (a == null) (a) = b --> fn()(a) ??= b)
  382. return;
  383. }
  384. const operatorToken = getOperatorToken(body.expression);
  385. yield ruleFixer.insertTextBefore(operatorToken, existence.operator); // -> if (foo) foo ||= bar
  386. yield ruleFixer.removeRange([ifNode.range[0], body.range[0]]); // -> foo ||= bar
  387. yield ruleFixer.removeRange([body.range[1], ifNode.range[1]]); // -> foo ||= bar, only present if "if" had a body
  388. const nextToken = sourceCode.getTokenAfter(body.expression);
  389. if (hasBody && (nextToken !== null && nextToken.value !== ";")) {
  390. yield ruleFixer.insertTextAfter(ifNode, ";");
  391. }
  392. }
  393. };
  394. const shouldBeFixed = cannotBeGetter(existence.reference) ||
  395. (ifNode.test.type !== "LogicalExpression" && accessesSingleProperty(existence.reference));
  396. context.report(createConditionalFixer(descriptor, suggestion, shouldBeFixed));
  397. }
  398. }
  399. };
  400. }
  401. };