max-lines-per-function.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. /**
  2. * @fileoverview A rule to set the maximum number of line of code in a function.
  3. * @author Pete Ward <peteward44@gmail.com>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const { upperCaseFirst } = require("../shared/string-utils");
  11. //------------------------------------------------------------------------------
  12. // Constants
  13. //------------------------------------------------------------------------------
  14. const OPTIONS_SCHEMA = {
  15. type: "object",
  16. properties: {
  17. max: {
  18. type: "integer",
  19. minimum: 0,
  20. },
  21. skipComments: {
  22. type: "boolean",
  23. },
  24. skipBlankLines: {
  25. type: "boolean",
  26. },
  27. IIFEs: {
  28. type: "boolean",
  29. },
  30. },
  31. additionalProperties: false,
  32. };
  33. const OPTIONS_OR_INTEGER_SCHEMA = {
  34. oneOf: [
  35. OPTIONS_SCHEMA,
  36. {
  37. type: "integer",
  38. minimum: 1,
  39. },
  40. ],
  41. };
  42. /**
  43. * Given a list of comment nodes, return a map with numeric keys (source code line numbers) and comment token values.
  44. * @param {Array} comments An array of comment nodes.
  45. * @returns {Map<string, Node>} A map with numeric keys (source code line numbers) and comment token values.
  46. */
  47. function getCommentLineNumbers(comments) {
  48. const map = new Map();
  49. comments.forEach(comment => {
  50. for (let i = comment.loc.start.line; i <= comment.loc.end.line; i++) {
  51. map.set(i, comment);
  52. }
  53. });
  54. return map;
  55. }
  56. //------------------------------------------------------------------------------
  57. // Rule Definition
  58. //------------------------------------------------------------------------------
  59. /** @type {import('../types').Rule.RuleModule} */
  60. module.exports = {
  61. meta: {
  62. type: "suggestion",
  63. docs: {
  64. description:
  65. "Enforce a maximum number of lines of code in a function",
  66. recommended: false,
  67. url: "https://eslint.org/docs/latest/rules/max-lines-per-function",
  68. },
  69. schema: [OPTIONS_OR_INTEGER_SCHEMA],
  70. messages: {
  71. exceed: "{{name}} has too many lines ({{lineCount}}). Maximum allowed is {{maxLines}}.",
  72. },
  73. },
  74. create(context) {
  75. const sourceCode = context.sourceCode;
  76. const lines = sourceCode.lines;
  77. const option = context.options[0];
  78. let maxLines = 50;
  79. let skipComments = false;
  80. let skipBlankLines = false;
  81. let IIFEs = false;
  82. if (typeof option === "object") {
  83. maxLines = typeof option.max === "number" ? option.max : 50;
  84. skipComments = !!option.skipComments;
  85. skipBlankLines = !!option.skipBlankLines;
  86. IIFEs = !!option.IIFEs;
  87. } else if (typeof option === "number") {
  88. maxLines = option;
  89. }
  90. const commentLineNumbers = getCommentLineNumbers(
  91. sourceCode.getAllComments(),
  92. );
  93. //--------------------------------------------------------------------------
  94. // Helpers
  95. //--------------------------------------------------------------------------
  96. /**
  97. * Tells if a comment encompasses the entire line.
  98. * @param {string} line The source line with a trailing comment
  99. * @param {number} lineNumber The one-indexed line number this is on
  100. * @param {ASTNode} comment The comment to remove
  101. * @returns {boolean} If the comment covers the entire line
  102. */
  103. function isFullLineComment(line, lineNumber, comment) {
  104. const start = comment.loc.start,
  105. end = comment.loc.end,
  106. isFirstTokenOnLine =
  107. start.line === lineNumber &&
  108. !line.slice(0, start.column).trim(),
  109. isLastTokenOnLine =
  110. end.line === lineNumber && !line.slice(end.column).trim();
  111. return (
  112. comment &&
  113. (start.line < lineNumber || isFirstTokenOnLine) &&
  114. (end.line > lineNumber || isLastTokenOnLine)
  115. );
  116. }
  117. /**
  118. * Identifies is a node is a FunctionExpression which is part of an IIFE
  119. * @param {ASTNode} node Node to test
  120. * @returns {boolean} True if it's an IIFE
  121. */
  122. function isIIFE(node) {
  123. return (
  124. (node.type === "FunctionExpression" ||
  125. node.type === "ArrowFunctionExpression") &&
  126. node.parent &&
  127. node.parent.type === "CallExpression" &&
  128. node.parent.callee === node
  129. );
  130. }
  131. /**
  132. * Identifies is a node is a FunctionExpression which is embedded within a MethodDefinition or Property
  133. * @param {ASTNode} node Node to test
  134. * @returns {boolean} True if it's a FunctionExpression embedded within a MethodDefinition or Property
  135. */
  136. function isEmbedded(node) {
  137. if (!node.parent) {
  138. return false;
  139. }
  140. if (node !== node.parent.value) {
  141. return false;
  142. }
  143. if (node.parent.type === "MethodDefinition") {
  144. return true;
  145. }
  146. if (node.parent.type === "Property") {
  147. return (
  148. node.parent.method === true ||
  149. node.parent.kind === "get" ||
  150. node.parent.kind === "set"
  151. );
  152. }
  153. return false;
  154. }
  155. /**
  156. * Count the lines in the function
  157. * @param {ASTNode} funcNode Function AST node
  158. * @returns {void}
  159. * @private
  160. */
  161. function processFunction(funcNode) {
  162. const node = isEmbedded(funcNode) ? funcNode.parent : funcNode;
  163. if (!IIFEs && isIIFE(node)) {
  164. return;
  165. }
  166. let lineCount = 0;
  167. for (let i = node.loc.start.line - 1; i < node.loc.end.line; ++i) {
  168. const line = lines[i];
  169. if (skipComments) {
  170. if (
  171. commentLineNumbers.has(i + 1) &&
  172. isFullLineComment(
  173. line,
  174. i + 1,
  175. commentLineNumbers.get(i + 1),
  176. )
  177. ) {
  178. continue;
  179. }
  180. }
  181. if (skipBlankLines) {
  182. if (line.match(/^\s*$/u)) {
  183. continue;
  184. }
  185. }
  186. lineCount++;
  187. }
  188. if (lineCount > maxLines) {
  189. const name = upperCaseFirst(
  190. astUtils.getFunctionNameWithKind(funcNode),
  191. );
  192. context.report({
  193. node,
  194. messageId: "exceed",
  195. data: { name, lineCount, maxLines },
  196. });
  197. }
  198. }
  199. //--------------------------------------------------------------------------
  200. // Public API
  201. //--------------------------------------------------------------------------
  202. return {
  203. FunctionDeclaration: processFunction,
  204. FunctionExpression: processFunction,
  205. ArrowFunctionExpression: processFunction,
  206. };
  207. },
  208. };