forked from eslint/eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-empty.js
118 lines (100 loc) · 3.81 KB
/
no-empty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* @fileoverview Rule to flag use of an empty block statement
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
hasSuggestions: true,
type: "suggestion",
docs: {
description: "Disallow empty block statements",
recommended: true,
url: "https://eslint.org/docs/rules/no-empty"
},
schema: [
{
type: "object",
properties: {
allowEmptyCatch: {
type: "boolean",
default: false
}
},
additionalProperties: false
}
],
messages: {
unexpected: "Empty {{type}} statement.",
suggestComment: "Add comment inside empty {{type}} statement."
}
},
create(context) {
const options = context.options[0] || {},
allowEmptyCatch = options.allowEmptyCatch || false;
const sourceCode = context.getSourceCode();
return {
BlockStatement(node) {
const range = [node.range[0] + 1, node.range[1] - 1];
// if the body is not empty, we can just return immediately
if (node.body.length !== 0) {
return;
}
// a function is generally allowed to be empty
if (astUtils.isFunction(node.parent)) {
return;
}
if (allowEmptyCatch && node.parent.type === "CatchClause") {
return;
}
// any other block is only allowed to be empty, if it contains a comment
if (sourceCode.getCommentsInside(node).length > 0) {
return;
}
context.report({
node,
messageId: "unexpected",
data: { type: "block" },
suggest: [
{
messageId: "suggestComment",
data: { type: "block" },
fix(fixer) {
return fixer.replaceTextRange(range, " /* empty */ ");
}
}
]
});
},
SwitchStatement(node) {
const closingCurly = sourceCode.getLastToken(node);
const openingCurly = sourceCode.getTokenBefore(node.cases.length ? node.cases[0] : closingCurly);
const range = [openingCurly.range[0] + 1, closingCurly.range[1] - 1];
if (typeof node.cases === "undefined" || node.cases.length === 0) {
context.report({
node,
messageId: "unexpected",
data: { type: "switch" },
suggest: [
{
messageId: "suggestComment",
data: { type: "switch" },
fix(fixer) {
return fixer.replaceTextRange(range, " /* empty */ ");
}
}
]
});
}
}
};
}
};