class-methods-use-this.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. /**
  2. * @fileoverview Rule to enforce that all class methods use 'this'.
  3. * @author Patrick Williams
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "Enforce that class methods utilize `this`",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/class-methods-use-this"
  21. },
  22. schema: [{
  23. type: "object",
  24. properties: {
  25. exceptMethods: {
  26. type: "array",
  27. items: {
  28. type: "string"
  29. }
  30. },
  31. enforceForClassFields: {
  32. type: "boolean",
  33. default: true
  34. }
  35. },
  36. additionalProperties: false
  37. }],
  38. messages: {
  39. missingThis: "Expected 'this' to be used by class {{name}}."
  40. }
  41. },
  42. create(context) {
  43. const config = Object.assign({}, context.options[0]);
  44. const enforceForClassFields = config.enforceForClassFields !== false;
  45. const exceptMethods = new Set(config.exceptMethods || []);
  46. const stack = [];
  47. /**
  48. * Push `this` used flag initialized with `false` onto the stack.
  49. * @returns {void}
  50. */
  51. function pushContext() {
  52. stack.push(false);
  53. }
  54. /**
  55. * Pop `this` used flag from the stack.
  56. * @returns {boolean | undefined} `this` used flag
  57. */
  58. function popContext() {
  59. return stack.pop();
  60. }
  61. /**
  62. * Initializes the current context to false and pushes it onto the stack.
  63. * These booleans represent whether 'this' has been used in the context.
  64. * @returns {void}
  65. * @private
  66. */
  67. function enterFunction() {
  68. pushContext();
  69. }
  70. /**
  71. * Check if the node is an instance method
  72. * @param {ASTNode} node node to check
  73. * @returns {boolean} True if its an instance method
  74. * @private
  75. */
  76. function isInstanceMethod(node) {
  77. switch (node.type) {
  78. case "MethodDefinition":
  79. return !node.static && node.kind !== "constructor";
  80. case "PropertyDefinition":
  81. return !node.static && enforceForClassFields;
  82. default:
  83. return false;
  84. }
  85. }
  86. /**
  87. * Check if the node is an instance method not excluded by config
  88. * @param {ASTNode} node node to check
  89. * @returns {boolean} True if it is an instance method, and not excluded by config
  90. * @private
  91. */
  92. function isIncludedInstanceMethod(node) {
  93. if (isInstanceMethod(node)) {
  94. if (node.computed) {
  95. return true;
  96. }
  97. const hashIfNeeded = node.key.type === "PrivateIdentifier" ? "#" : "";
  98. const name = node.key.type === "Literal"
  99. ? astUtils.getStaticStringValue(node.key)
  100. : (node.key.name || "");
  101. return !exceptMethods.has(hashIfNeeded + name);
  102. }
  103. return false;
  104. }
  105. /**
  106. * Checks if we are leaving a function that is a method, and reports if 'this' has not been used.
  107. * Static methods and the constructor are exempt.
  108. * Then pops the context off the stack.
  109. * @param {ASTNode} node A function node that was entered.
  110. * @returns {void}
  111. * @private
  112. */
  113. function exitFunction(node) {
  114. const methodUsesThis = popContext();
  115. if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) {
  116. context.report({
  117. node,
  118. loc: astUtils.getFunctionHeadLoc(node, context.getSourceCode()),
  119. messageId: "missingThis",
  120. data: {
  121. name: astUtils.getFunctionNameWithKind(node)
  122. }
  123. });
  124. }
  125. }
  126. /**
  127. * Mark the current context as having used 'this'.
  128. * @returns {void}
  129. * @private
  130. */
  131. function markThisUsed() {
  132. if (stack.length) {
  133. stack[stack.length - 1] = true;
  134. }
  135. }
  136. return {
  137. FunctionDeclaration: enterFunction,
  138. "FunctionDeclaration:exit": exitFunction,
  139. FunctionExpression: enterFunction,
  140. "FunctionExpression:exit": exitFunction,
  141. /*
  142. * Class field value are implicit functions.
  143. */
  144. "PropertyDefinition > *.key:exit": pushContext,
  145. "PropertyDefinition:exit": popContext,
  146. /*
  147. * Class static blocks are implicit functions. They aren't required to use `this`,
  148. * but we have to push context so that it captures any use of `this` in the static block
  149. * separately from enclosing contexts, because static blocks have their own `this` and it
  150. * shouldn't count as used `this` in enclosing contexts.
  151. */
  152. StaticBlock: pushContext,
  153. "StaticBlock:exit": popContext,
  154. ThisExpression: markThisUsed,
  155. Super: markThisUsed,
  156. ...(
  157. enforceForClassFields && {
  158. "PropertyDefinition > ArrowFunctionExpression.value": enterFunction,
  159. "PropertyDefinition > ArrowFunctionExpression.value:exit": exitFunction
  160. }
  161. )
  162. };
  163. }
  164. };