2 * @fileoverview Rule to disallow empty functions.
3 * @author Toru Nagashima
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
18 const ALLOW_OPTIONS = Object.freeze([
30 * Gets the kind of a given function node.
31 * @param {ASTNode} node A function node to get. This is one of
32 * an ArrowFunctionExpression, a FunctionDeclaration, or a
34 * @returns {string} The kind of the function. This is one of "functions",
35 * "arrowFunctions", "generatorFunctions", "asyncFunctions", "methods",
36 * "generatorMethods", "asyncMethods", "getters", "setters", and
39 function getKind(node) {
40 const parent = node.parent;
43 if (node.type === "ArrowFunctionExpression") {
44 return "arrowFunctions";
48 if (parent.type === "Property") {
49 if (parent.kind === "get") {
52 if (parent.kind === "set") {
55 kind = parent.method ? "methods" : "functions";
57 } else if (parent.type === "MethodDefinition") {
58 if (parent.kind === "get") {
61 if (parent.kind === "set") {
64 if (parent.kind === "constructor") {
65 return "constructors";
78 } else if (node.async) {
83 return prefix + kind[0].toUpperCase() + kind.slice(1);
86 //------------------------------------------------------------------------------
88 //------------------------------------------------------------------------------
95 description: "disallow empty functions",
96 category: "Best Practices",
98 url: "https://eslint.org/docs/rules/no-empty-function"
107 items: { enum: ALLOW_OPTIONS },
111 additionalProperties: false
116 unexpected: "Unexpected empty {{name}}."
121 const options = context.options[0] || {};
122 const allowed = options.allow || [];
124 const sourceCode = context.getSourceCode();
127 * Reports a given function node if the node matches the following patterns.
129 * - Not allowed by options.
130 * - The body is empty.
131 * - The body doesn't have any comments.
132 * @param {ASTNode} node A function node to report. This is one of
133 * an ArrowFunctionExpression, a FunctionDeclaration, or a
134 * FunctionExpression.
137 function reportIfEmpty(node) {
138 const kind = getKind(node);
139 const name = astUtils.getFunctionNameWithKind(node);
140 const innerComments = sourceCode.getTokens(node.body, {
141 includeComments: true,
142 filter: astUtils.isCommentToken
145 if (allowed.indexOf(kind) === -1 &&
146 node.body.type === "BlockStatement" &&
147 node.body.body.length === 0 &&
148 innerComments.length === 0
152 loc: node.body.loc.start,
153 messageId: "unexpected",
160 ArrowFunctionExpression: reportIfEmpty,
161 FunctionDeclaration: reportIfEmpty,
162 FunctionExpression: reportIfEmpty