prefer-destructuring.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. /**
  2. * @fileoverview Prefer destructuring from arrays and objects
  3. * @author Alex LaFroscia
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. const PRECEDENCE_OF_ASSIGNMENT_EXPR = astUtils.getPrecedence({
  14. type: "AssignmentExpression",
  15. });
  16. //------------------------------------------------------------------------------
  17. // Rule Definition
  18. //------------------------------------------------------------------------------
  19. /** @type {import('../types').Rule.RuleModule} */
  20. module.exports = {
  21. meta: {
  22. type: "suggestion",
  23. docs: {
  24. description: "Require destructuring from arrays and/or objects",
  25. recommended: false,
  26. frozen: true,
  27. url: "https://eslint.org/docs/latest/rules/prefer-destructuring",
  28. },
  29. fixable: "code",
  30. schema: [
  31. {
  32. /*
  33. * old support {array: Boolean, object: Boolean}
  34. * new support {VariableDeclarator: {}, AssignmentExpression: {}}
  35. */
  36. oneOf: [
  37. {
  38. type: "object",
  39. properties: {
  40. VariableDeclarator: {
  41. type: "object",
  42. properties: {
  43. array: {
  44. type: "boolean",
  45. },
  46. object: {
  47. type: "boolean",
  48. },
  49. },
  50. additionalProperties: false,
  51. },
  52. AssignmentExpression: {
  53. type: "object",
  54. properties: {
  55. array: {
  56. type: "boolean",
  57. },
  58. object: {
  59. type: "boolean",
  60. },
  61. },
  62. additionalProperties: false,
  63. },
  64. },
  65. additionalProperties: false,
  66. },
  67. {
  68. type: "object",
  69. properties: {
  70. array: {
  71. type: "boolean",
  72. },
  73. object: {
  74. type: "boolean",
  75. },
  76. },
  77. additionalProperties: false,
  78. },
  79. ],
  80. },
  81. {
  82. type: "object",
  83. properties: {
  84. enforceForRenamedProperties: {
  85. type: "boolean",
  86. },
  87. },
  88. additionalProperties: false,
  89. },
  90. ],
  91. messages: {
  92. preferDestructuring: "Use {{type}} destructuring.",
  93. },
  94. },
  95. create(context) {
  96. const enabledTypes = context.options[0];
  97. const enforceForRenamedProperties =
  98. context.options[1] &&
  99. context.options[1].enforceForRenamedProperties;
  100. let normalizedOptions = {
  101. VariableDeclarator: { array: true, object: true },
  102. AssignmentExpression: { array: true, object: true },
  103. };
  104. if (enabledTypes) {
  105. normalizedOptions =
  106. typeof enabledTypes.array !== "undefined" ||
  107. typeof enabledTypes.object !== "undefined"
  108. ? {
  109. VariableDeclarator: enabledTypes,
  110. AssignmentExpression: enabledTypes,
  111. }
  112. : enabledTypes;
  113. }
  114. //--------------------------------------------------------------------------
  115. // Helpers
  116. //--------------------------------------------------------------------------
  117. /**
  118. * Checks if destructuring type should be checked.
  119. * @param {string} nodeType "AssignmentExpression" or "VariableDeclarator"
  120. * @param {string} destructuringType "array" or "object"
  121. * @returns {boolean} `true` if the destructuring type should be checked for the given node
  122. */
  123. function shouldCheck(nodeType, destructuringType) {
  124. return (
  125. normalizedOptions &&
  126. normalizedOptions[nodeType] &&
  127. normalizedOptions[nodeType][destructuringType]
  128. );
  129. }
  130. /**
  131. * Determines if the given node is accessing an array index
  132. *
  133. * This is used to differentiate array index access from object property
  134. * access.
  135. * @param {ASTNode} node the node to evaluate
  136. * @returns {boolean} whether or not the node is an integer
  137. */
  138. function isArrayIndexAccess(node) {
  139. return Number.isInteger(node.property.value);
  140. }
  141. /**
  142. * Report that the given node should use destructuring
  143. * @param {ASTNode} reportNode the node to report
  144. * @param {string} type the type of destructuring that should have been done
  145. * @param {Function|null} fix the fix function or null to pass to context.report
  146. * @returns {void}
  147. */
  148. function report(reportNode, type, fix) {
  149. context.report({
  150. node: reportNode,
  151. messageId: "preferDestructuring",
  152. data: { type },
  153. fix,
  154. });
  155. }
  156. /**
  157. * Determines if a node should be fixed into object destructuring
  158. *
  159. * The fixer only fixes the simplest case of object destructuring,
  160. * like: `let x = a.x`;
  161. *
  162. * Assignment expression is not fixed.
  163. * Array destructuring is not fixed.
  164. * Renamed property is not fixed.
  165. * @param {ASTNode} node the node to evaluate
  166. * @returns {boolean} whether or not the node should be fixed
  167. */
  168. function shouldFix(node) {
  169. return (
  170. node.type === "VariableDeclarator" &&
  171. node.id.type === "Identifier" &&
  172. node.init.type === "MemberExpression" &&
  173. !node.init.computed &&
  174. node.init.property.type === "Identifier" &&
  175. node.id.name === node.init.property.name
  176. );
  177. }
  178. /**
  179. * Fix a node into object destructuring.
  180. * This function only handles the simplest case of object destructuring,
  181. * see {@link shouldFix}.
  182. * @param {SourceCodeFixer} fixer the fixer object
  183. * @param {ASTNode} node the node to be fixed.
  184. * @returns {Object} a fix for the node
  185. */
  186. function fixIntoObjectDestructuring(fixer, node) {
  187. const rightNode = node.init;
  188. const sourceCode = context.sourceCode;
  189. // Don't fix if that would remove any comments. Only comments inside `rightNode.object` can be preserved.
  190. if (
  191. sourceCode.getCommentsInside(node).length >
  192. sourceCode.getCommentsInside(rightNode.object).length
  193. ) {
  194. return null;
  195. }
  196. let objectText = sourceCode.getText(rightNode.object);
  197. if (
  198. astUtils.getPrecedence(rightNode.object) <
  199. PRECEDENCE_OF_ASSIGNMENT_EXPR
  200. ) {
  201. objectText = `(${objectText})`;
  202. }
  203. return fixer.replaceText(
  204. node,
  205. `{${rightNode.property.name}} = ${objectText}`,
  206. );
  207. }
  208. /**
  209. * Check that the `prefer-destructuring` rules are followed based on the
  210. * given left- and right-hand side of the assignment.
  211. *
  212. * Pulled out into a separate method so that VariableDeclarators and
  213. * AssignmentExpressions can share the same verification logic.
  214. * @param {ASTNode} leftNode the left-hand side of the assignment
  215. * @param {ASTNode} rightNode the right-hand side of the assignment
  216. * @param {ASTNode} reportNode the node to report the error on
  217. * @returns {void}
  218. */
  219. function performCheck(leftNode, rightNode, reportNode) {
  220. if (
  221. rightNode.type !== "MemberExpression" ||
  222. rightNode.object.type === "Super" ||
  223. rightNode.property.type === "PrivateIdentifier"
  224. ) {
  225. return;
  226. }
  227. if (isArrayIndexAccess(rightNode)) {
  228. if (shouldCheck(reportNode.type, "array")) {
  229. report(reportNode, "array", null);
  230. }
  231. return;
  232. }
  233. const fix = shouldFix(reportNode)
  234. ? fixer => fixIntoObjectDestructuring(fixer, reportNode)
  235. : null;
  236. if (
  237. shouldCheck(reportNode.type, "object") &&
  238. enforceForRenamedProperties
  239. ) {
  240. report(reportNode, "object", fix);
  241. return;
  242. }
  243. if (shouldCheck(reportNode.type, "object")) {
  244. const property = rightNode.property;
  245. if (
  246. (property.type === "Literal" &&
  247. leftNode.name === property.value) ||
  248. (property.type === "Identifier" &&
  249. leftNode.name === property.name &&
  250. !rightNode.computed)
  251. ) {
  252. report(reportNode, "object", fix);
  253. }
  254. }
  255. }
  256. /**
  257. * Check if a given variable declarator is coming from an property access
  258. * that should be using destructuring instead
  259. * @param {ASTNode} node the variable declarator to check
  260. * @returns {void}
  261. */
  262. function checkVariableDeclarator(node) {
  263. // Skip if variable is declared without assignment
  264. if (!node.init) {
  265. return;
  266. }
  267. // Variable declarations using explicit resource management cannot use destructuring (parse error)
  268. if (
  269. node.parent.kind === "using" ||
  270. node.parent.kind === "await using"
  271. ) {
  272. return;
  273. }
  274. // We only care about member expressions past this point
  275. if (node.init.type !== "MemberExpression") {
  276. return;
  277. }
  278. performCheck(node.id, node.init, node);
  279. }
  280. /**
  281. * Run the `prefer-destructuring` check on an AssignmentExpression
  282. * @param {ASTNode} node the AssignmentExpression node
  283. * @returns {void}
  284. */
  285. function checkAssignmentExpression(node) {
  286. if (node.operator === "=") {
  287. performCheck(node.left, node.right, node);
  288. }
  289. }
  290. //--------------------------------------------------------------------------
  291. // Public
  292. //--------------------------------------------------------------------------
  293. return {
  294. VariableDeclarator: checkVariableDeclarator,
  295. AssignmentExpression: checkAssignmentExpression,
  296. };
  297. },
  298. };