UNPKG

2.76 kBJavaScriptView Raw
1/**
2 * Disallows curly braces after statements.
3 *
4 * Types: `Array` or `Boolean`
5 *
6 * Values: Array of quoted keywords or `true` to disallow curly braces after the following keywords:
7 *
8 * #### Example
9 *
10 * ```js
11 * "disallowCurlyBraces": [
12 * "if",
13 * "else",
14 * "while",
15 * "for",
16 * "do",
17 * "with"
18 * ]
19 * ```
20 *
21 * ##### Valid
22 *
23 * ```js
24 * if (x) x++;
25 * ```
26 *
27 * ##### Invalid
28 *
29 * ```js
30 * if (x) {
31 * x++;
32 * }
33 * ```
34 */
35
36var assert = require('assert');
37var defaultKeywords = require('../utils').curlyBracedKeywords;
38
39module.exports = function() {};
40
41module.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};