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