UNPKG

9.83 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to check empty newline after "var" statement
3 * @author Gopal Venkatesan
4 * @deprecated
5 */
6
7"use strict";
8
9//------------------------------------------------------------------------------
10// Requirements
11//------------------------------------------------------------------------------
12
13const astUtils = require("./utils/ast-utils");
14
15//------------------------------------------------------------------------------
16// Rule Definition
17//------------------------------------------------------------------------------
18
19module.exports = {
20 meta: {
21 type: "layout",
22
23 docs: {
24 description: "require or disallow an empty line after variable declarations",
25 category: "Stylistic Issues",
26 recommended: false,
27 url: "https://eslint.org/docs/rules/newline-after-var"
28 },
29 schema: [
30 {
31 enum: ["never", "always"]
32 }
33 ],
34 fixable: "whitespace",
35 messages: {
36 expected: "Expected blank line after variable declarations.",
37 unexpected: "Unexpected blank line after variable declarations."
38 },
39
40 deprecated: true,
41
42 replacedBy: ["padding-line-between-statements"]
43 },
44
45 create(context) {
46 const sourceCode = context.getSourceCode();
47
48 // Default `mode` to "always".
49 const mode = context.options[0] === "never" ? "never" : "always";
50
51 // Cache starting and ending line numbers of comments for faster lookup
52 const commentEndLine = sourceCode.getAllComments().reduce((result, token) => {
53 result[token.loc.start.line] = token.loc.end.line;
54 return result;
55 }, {});
56
57
58 //--------------------------------------------------------------------------
59 // Helpers
60 //--------------------------------------------------------------------------
61
62 /**
63 * Gets a token from the given node to compare line to the next statement.
64 *
65 * In general, the token is the last token of the node. However, the token is the second last token if the following conditions satisfy.
66 *
67 * - The last token is semicolon.
68 * - The semicolon is on a different line from the previous token of the semicolon.
69 *
70 * This behavior would address semicolon-less style code. e.g.:
71 *
72 * var foo = 1
73 *
74 * ;(a || b).doSomething()
75 *
76 * @param {ASTNode} node - The node to get.
77 * @returns {Token} The token to compare line to the next statement.
78 */
79 function getLastToken(node) {
80 const lastToken = sourceCode.getLastToken(node);
81
82 if (lastToken.type === "Punctuator" && lastToken.value === ";") {
83 const prevToken = sourceCode.getTokenBefore(lastToken);
84
85 if (prevToken.loc.end.line !== lastToken.loc.start.line) {
86 return prevToken;
87 }
88 }
89
90 return lastToken;
91 }
92
93 /**
94 * Determine if provided keyword is a variable declaration
95 * @private
96 * @param {string} keyword - keyword to test
97 * @returns {boolean} True if `keyword` is a type of var
98 */
99 function isVar(keyword) {
100 return keyword === "var" || keyword === "let" || keyword === "const";
101 }
102
103 /**
104 * Determine if provided keyword is a variant of for specifiers
105 * @private
106 * @param {string} keyword - keyword to test
107 * @returns {boolean} True if `keyword` is a variant of for specifier
108 */
109 function isForTypeSpecifier(keyword) {
110 return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
111 }
112
113 /**
114 * Determine if provided keyword is an export specifiers
115 * @private
116 * @param {string} nodeType - nodeType to test
117 * @returns {boolean} True if `nodeType` is an export specifier
118 */
119 function isExportSpecifier(nodeType) {
120 return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" ||
121 nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration";
122 }
123
124 /**
125 * Determine if provided node is the last of their parent block.
126 * @private
127 * @param {ASTNode} node - node to test
128 * @returns {boolean} True if `node` is last of their parent block.
129 */
130 function isLastNode(node) {
131 const token = sourceCode.getTokenAfter(node);
132
133 return !token || (token.type === "Punctuator" && token.value === "}");
134 }
135
136 /**
137 * Gets the last line of a group of consecutive comments
138 * @param {number} commentStartLine The starting line of the group
139 * @returns {number} The number of the last comment line of the group
140 */
141 function getLastCommentLineOfBlock(commentStartLine) {
142 const currentCommentEnd = commentEndLine[commentStartLine];
143
144 return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
145 }
146
147 /**
148 * Determine if a token starts more than one line after a comment ends
149 * @param {token} token The token being checked
150 * @param {integer} commentStartLine The line number on which the comment starts
151 * @returns {boolean} True if `token` does not start immediately after a comment
152 */
153 function hasBlankLineAfterComment(token, commentStartLine) {
154 return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1;
155 }
156
157 /**
158 * Checks that a blank line exists after a variable declaration when mode is
159 * set to "always", or checks that there is no blank line when mode is set
160 * to "never"
161 * @private
162 * @param {ASTNode} node - `VariableDeclaration` node to test
163 * @returns {void}
164 */
165 function checkForBlankLine(node) {
166
167 /*
168 * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
169 * sometimes be second-last if there is a semicolon on a different line.
170 */
171 const lastToken = getLastToken(node),
172
173 /*
174 * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
175 * is the last token of the node.
176 */
177 nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
178 nextLineNum = lastToken.loc.end.line + 1;
179
180 // Ignore if there is no following statement
181 if (!nextToken) {
182 return;
183 }
184
185 // Ignore if parent of node is a for variant
186 if (isForTypeSpecifier(node.parent.type)) {
187 return;
188 }
189
190 // Ignore if parent of node is an export specifier
191 if (isExportSpecifier(node.parent.type)) {
192 return;
193 }
194
195 /*
196 * Some coding styles use multiple `var` statements, so do nothing if
197 * the next token is a `var` statement.
198 */
199 if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
200 return;
201 }
202
203 // Ignore if it is last statement in a block
204 if (isLastNode(node)) {
205 return;
206 }
207
208 // Next statement is not a `var`...
209 const noNextLineToken = nextToken.loc.start.line > nextLineNum;
210 const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined");
211
212 if (mode === "never" && noNextLineToken && !hasNextLineComment) {
213 context.report({
214 node,
215 messageId: "unexpected",
216 data: { identifier: node.name },
217 fix(fixer) {
218 const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
219
220 return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
221 }
222 });
223 }
224
225 // Token on the next line, or comment without blank line
226 if (
227 mode === "always" && (
228 !noNextLineToken ||
229 hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum)
230 )
231 ) {
232 context.report({
233 node,
234 messageId: "expected",
235 data: { identifier: node.name },
236 fix(fixer) {
237 if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
238 return fixer.insertTextBefore(nextToken, "\n\n");
239 }
240
241 return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
242 }
243 });
244 }
245 }
246
247 //--------------------------------------------------------------------------
248 // Public
249 //--------------------------------------------------------------------------
250
251 return {
252 VariableDeclaration: checkForBlankLine
253 };
254
255 }
256};