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-keywords-on-new-line.js
131 lines (117 loc) · 2.86 KB
/
disallow-keywords-on-new-line.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/**
* Disallows placing keywords on a new line.
*
* Types: `Array`
*
* Values:
*
* - `Array` specifies quoted keywords which are disallowed from being placed on a new line
*
* #### Example
*
* ```js
* "disallowKeywordsOnNewLine": ["else"]
* ```
*
* ##### Valid
*
* ```js
* if (x < 0) {
* x++;
* } else {
* x--;
* }
* ```
* ```js
* if (x < 0)
* x++;
* else
* x--;
* ```
* ```js
* if (x < 0) {
* x++;
* }
* // comments
* else {
* x--;
* }
* ```
* ```js
* do {
* x++;
* } while(x < 0);
* ```
* ```js
* do
* x++;
* while(x < 0);
* ```
* ```js
* do {
* x++;
* }
* // comments
* while(x < 0);
* ```
*
* ##### Invalid
*
* ```js
* if (x < 0) {
* x++;
* }
* else {
* x--;
* }
* ```
*/
var assert = require('assert');
function isPreviousTokenAComment(token) {
var prevToken = token.getPreviousNonWhitespaceToken();
return (prevToken.type === 'CommentLine' || prevToken.type === 'CommentBlock');
}
module.exports = function() {};
module.exports.prototype = {
configure: function(keywords) {
assert(Array.isArray(keywords), this.getOptionName() + ' option requires array value');
this._keywords = keywords;
},
getOptionName: function() {
return 'disallowKeywordsOnNewLine';
},
check: function(file, errors) {
file.iterateTokensByTypeAndValue('Keyword', this._keywords, function(token) {
var prevToken = token.getPreviousCodeToken();
if (token.value === 'else') {
if (prevToken.value !== '}') {
// Special case for #905, even though it contradicts rule meaning,
// it makes more sense that way.
return;
}
if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
// Special cases for #885, using while as the keyword contradicts rule meaning
// but it is more efficient and reduces complexity of the code in this rule
if (token.value === 'while') {
var parentElement = token.parentElement;
// "while" that is part of a do will not return nodes as it is not a start token
if (parentElement.type !== 'DoWhileStatement' || prevToken.value !== '}') {
// allow "while" that is part of a "do while" with no braces to succeed
return;
}
if (isPreviousTokenAComment(token)) {
// Special case for #1421, to handle comments before the else
return;
}
}
errors.assert.sameLine({
token: prevToken,
nextToken: token
});
});
}
};