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 | var assert = require('assert');
|
37 | var defaultKeywords = require('../utils').curlyBracedKeywords;
|
38 |
|
39 | module.exports = function() {};
|
40 |
|
41 | module.exports.prototype = {
|
42 |
|
43 | configure: function(statementTypes) {
|
44 | assert(
|
45 | Array.isArray(statementTypes) || statementTypes === true,
|
46 | this.getOptionName() + ' option requires array or true value'
|
47 | );
|
48 |
|
49 | if (statementTypes === true) {
|
50 | statementTypes = defaultKeywords;
|
51 | }
|
52 |
|
53 | this._typeIndex = {};
|
54 | statementTypes.forEach(function(type) {
|
55 | this._typeIndex[type] = true;
|
56 | }.bind(this));
|
57 | },
|
58 |
|
59 | getOptionName: function() {
|
60 | return 'disallowCurlyBraces';
|
61 | },
|
62 |
|
63 | check: function(file, errors) {
|
64 |
|
65 | function isSingleBlockStatement(node) {
|
66 | return node && node.type === 'BlockStatement' &&
|
67 | node.body.length === 1;
|
68 | }
|
69 |
|
70 | function addError(typeString, entity) {
|
71 | errors.add(
|
72 | typeString + ' statement with extra curly braces',
|
73 | entity
|
74 | );
|
75 | }
|
76 |
|
77 | function checkBody(type, typeString) {
|
78 | file.iterateNodesByType(type, function(node) {
|
79 | if (isSingleBlockStatement(node.body)) {
|
80 | addError(typeString, node);
|
81 | }
|
82 | });
|
83 | }
|
84 |
|
85 | var typeIndex = this._typeIndex;
|
86 |
|
87 | if (typeIndex.if || typeIndex.else) {
|
88 | file.iterateNodesByType('IfStatement', function(node) {
|
89 | if (typeIndex.if && isSingleBlockStatement(node.consequent)) {
|
90 | addError('If', node);
|
91 | }
|
92 | if (typeIndex.else && isSingleBlockStatement(node.alternate)) {
|
93 | addError('Else', node.alternate.getFirstToken());
|
94 | }
|
95 | });
|
96 | }
|
97 |
|
98 | if (typeIndex.while) {
|
99 | checkBody('WhileStatement', 'While');
|
100 | }
|
101 |
|
102 | if (typeIndex.for) {
|
103 | checkBody('ForStatement', 'For');
|
104 | checkBody('ForInStatement', 'For in');
|
105 | checkBody('ForOfStatement', 'For of');
|
106 | }
|
107 |
|
108 | if (typeIndex.do) {
|
109 | checkBody('DoWhileStatement', 'Do while');
|
110 | }
|
111 |
|
112 | if (typeIndex.with) {
|
113 | checkBody('WithStatement', 'With');
|
114 | }
|
115 | }
|
116 |
|
117 | };
|