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