UNPKG

2.43 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag use of an empty block statement
3 * @author Nicholas C. Zakas
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const astUtils = require("../ast-utils");
12
13//------------------------------------------------------------------------------
14// Rule Definition
15//------------------------------------------------------------------------------
16
17module.exports = {
18 meta: {
19 docs: {
20 description: "disallow empty block statements",
21 category: "Possible Errors",
22 recommended: true,
23 url: "https://eslint.org/docs/rules/no-empty"
24 },
25
26 schema: [
27 {
28 type: "object",
29 properties: {
30 allowEmptyCatch: {
31 type: "boolean"
32 }
33 },
34 additionalProperties: false
35 }
36 ],
37
38 messages: {
39 unexpected: "Empty {{type}} statement."
40 }
41 },
42
43 create(context) {
44 const options = context.options[0] || {},
45 allowEmptyCatch = options.allowEmptyCatch || false;
46
47 const sourceCode = context.getSourceCode();
48
49 return {
50 BlockStatement(node) {
51
52 // if the body is not empty, we can just return immediately
53 if (node.body.length !== 0) {
54 return;
55 }
56
57 // a function is generally allowed to be empty
58 if (astUtils.isFunction(node.parent)) {
59 return;
60 }
61
62 if (allowEmptyCatch && node.parent.type === "CatchClause") {
63 return;
64 }
65
66 // any other block is only allowed to be empty, if it contains a comment
67 if (sourceCode.getCommentsInside(node).length > 0) {
68 return;
69 }
70
71 context.report({ node, messageId: "unexpected", data: { type: "block" } });
72 },
73
74 SwitchStatement(node) {
75
76 if (typeof node.cases === "undefined" || node.cases.length === 0) {
77 context.report({ node, messageId: "unexpected", data: { type: "switch" } });
78 }
79 }
80 };
81
82 }
83};