This repository was archived by the owner on Mar 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 509
/
Copy pathdisallow-curly-braces.js
117 lines (99 loc) · 2.7 KB
/
disallow-curly-braces.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
/**
* Disallows curly braces after statements.
*
* Types: `Array` or `Boolean`
*
* Values: Array of quoted keywords or `true` to disallow curly braces after the following keywords:
*
* #### Example
*
* ```js
* "disallowCurlyBraces": [
* "if",
* "else",
* "while",
* "for",
* "do",
* "with"
* ]
* ```
*
* ##### Valid
*
* ```js
* if (x) x++;
* ```
*
* ##### Invalid
*
* ```js
* if (x) {
* x++;
* }
* ```
*/
var assert = require('assert');
var defaultKeywords = require('../utils').curlyBracedKeywords;
module.exports = function() {};
module.exports.prototype = {
configure: function(statementTypes) {
assert(
Array.isArray(statementTypes) || statementTypes === true,
this.getOptionName() + ' option requires array or true value'
);
if (statementTypes === true) {
statementTypes = defaultKeywords;
}
this._typeIndex = {};
statementTypes.forEach(function(type) {
this._typeIndex[type] = true;
}.bind(this));
},
getOptionName: function() {
return 'disallowCurlyBraces';
},
check: function(file, errors) {
function isSingleBlockStatement(node) {
return node && node.type === 'BlockStatement' &&
node.body.length === 1;
}
function addError(typeString, entity) {
errors.add(
typeString + ' statement with extra curly braces',
entity
);
}
function checkBody(type, typeString) {
file.iterateNodesByType(type, function(node) {
if (isSingleBlockStatement(node.body)) {
addError(typeString, node);
}
});
}
var typeIndex = this._typeIndex;
if (typeIndex.if || typeIndex.else) {
file.iterateNodesByType('IfStatement', function(node) {
if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
addError('If', node);
}
if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
addError('Else', node.alternate.getFirstToken());
}
});
}
if (typeIndex.while) {
checkBody('WhileStatement', 'While');
}
if (typeIndex.for) {
checkBody('ForStatement', 'For');
checkBody('ForInStatement', 'For in');
checkBody('ForOfStatement', 'For of');
}
if (typeIndex.do) {
checkBody('DoWhileStatement', 'Do while');
}
if (typeIndex.with) {
checkBody('WithStatement', 'With');
}
}
};