• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         * @param {ASTNode} node The node to get.
76         * @returns {Token} The token to compare line to the next statement.
77         */
78        function getLastToken(node) {
79            const lastToken = sourceCode.getLastToken(node);
80
81            if (lastToken.type === "Punctuator" && lastToken.value === ";") {
82                const prevToken = sourceCode.getTokenBefore(lastToken);
83
84                if (prevToken.loc.end.line !== lastToken.loc.start.line) {
85                    return prevToken;
86                }
87            }
88
89            return lastToken;
90        }
91
92        /**
93         * Determine if provided keyword is a variable declaration
94         * @private
95         * @param {string} keyword keyword to test
96         * @returns {boolean} True if `keyword` is a type of var
97         */
98        function isVar(keyword) {
99            return keyword === "var" || keyword === "let" || keyword === "const";
100        }
101
102        /**
103         * Determine if provided keyword is a variant of for specifiers
104         * @private
105         * @param {string} keyword keyword to test
106         * @returns {boolean} True if `keyword` is a variant of for specifier
107         */
108        function isForTypeSpecifier(keyword) {
109            return keyword === "ForStatement" || keyword === "ForInStatement" || keyword === "ForOfStatement";
110        }
111
112        /**
113         * Determine if provided keyword is an export specifiers
114         * @private
115         * @param {string} nodeType nodeType to test
116         * @returns {boolean} True if `nodeType` is an export specifier
117         */
118        function isExportSpecifier(nodeType) {
119            return nodeType === "ExportNamedDeclaration" || nodeType === "ExportSpecifier" ||
120                nodeType === "ExportDefaultDeclaration" || nodeType === "ExportAllDeclaration";
121        }
122
123        /**
124         * Determine if provided node is the last of their parent block.
125         * @private
126         * @param {ASTNode} node node to test
127         * @returns {boolean} True if `node` is last of their parent block.
128         */
129        function isLastNode(node) {
130            const token = sourceCode.getTokenAfter(node);
131
132            return !token || (token.type === "Punctuator" && token.value === "}");
133        }
134
135        /**
136         * Gets the last line of a group of consecutive comments
137         * @param {number} commentStartLine The starting line of the group
138         * @returns {number} The number of the last comment line of the group
139         */
140        function getLastCommentLineOfBlock(commentStartLine) {
141            const currentCommentEnd = commentEndLine[commentStartLine];
142
143            return commentEndLine[currentCommentEnd + 1] ? getLastCommentLineOfBlock(currentCommentEnd + 1) : currentCommentEnd;
144        }
145
146        /**
147         * Determine if a token starts more than one line after a comment ends
148         * @param  {token}   token            The token being checked
149         * @param {integer}  commentStartLine The line number on which the comment starts
150         * @returns {boolean}                 True if `token` does not start immediately after a comment
151         */
152        function hasBlankLineAfterComment(token, commentStartLine) {
153            return token.loc.start.line > getLastCommentLineOfBlock(commentStartLine) + 1;
154        }
155
156        /**
157         * Checks that a blank line exists after a variable declaration when mode is
158         * set to "always", or checks that there is no blank line when mode is set
159         * to "never"
160         * @private
161         * @param {ASTNode} node `VariableDeclaration` node to test
162         * @returns {void}
163         */
164        function checkForBlankLine(node) {
165
166            /*
167             * lastToken is the last token on the node's line. It will usually also be the last token of the node, but it will
168             * sometimes be second-last if there is a semicolon on a different line.
169             */
170            const lastToken = getLastToken(node),
171
172                /*
173                 * If lastToken is the last token of the node, nextToken should be the token after the node. Otherwise, nextToken
174                 * is the last token of the node.
175                 */
176                nextToken = lastToken === sourceCode.getLastToken(node) ? sourceCode.getTokenAfter(node) : sourceCode.getLastToken(node),
177                nextLineNum = lastToken.loc.end.line + 1;
178
179            // Ignore if there is no following statement
180            if (!nextToken) {
181                return;
182            }
183
184            // Ignore if parent of node is a for variant
185            if (isForTypeSpecifier(node.parent.type)) {
186                return;
187            }
188
189            // Ignore if parent of node is an export specifier
190            if (isExportSpecifier(node.parent.type)) {
191                return;
192            }
193
194            /*
195             * Some coding styles use multiple `var` statements, so do nothing if
196             * the next token is a `var` statement.
197             */
198            if (nextToken.type === "Keyword" && isVar(nextToken.value)) {
199                return;
200            }
201
202            // Ignore if it is last statement in a block
203            if (isLastNode(node)) {
204                return;
205            }
206
207            // Next statement is not a `var`...
208            const noNextLineToken = nextToken.loc.start.line > nextLineNum;
209            const hasNextLineComment = (typeof commentEndLine[nextLineNum] !== "undefined");
210
211            if (mode === "never" && noNextLineToken && !hasNextLineComment) {
212                context.report({
213                    node,
214                    messageId: "unexpected",
215                    data: { identifier: node.name },
216                    fix(fixer) {
217                        const linesBetween = sourceCode.getText().slice(lastToken.range[1], nextToken.range[0]).split(astUtils.LINEBREAK_MATCHER);
218
219                        return fixer.replaceTextRange([lastToken.range[1], nextToken.range[0]], `${linesBetween.slice(0, -1).join("")}\n${linesBetween[linesBetween.length - 1]}`);
220                    }
221                });
222            }
223
224            // Token on the next line, or comment without blank line
225            if (
226                mode === "always" && (
227                    !noNextLineToken ||
228                    hasNextLineComment && !hasBlankLineAfterComment(nextToken, nextLineNum)
229                )
230            ) {
231                context.report({
232                    node,
233                    messageId: "expected",
234                    data: { identifier: node.name },
235                    fix(fixer) {
236                        if ((noNextLineToken ? getLastCommentLineOfBlock(nextLineNum) : lastToken.loc.end.line) === nextToken.loc.start.line) {
237                            return fixer.insertTextBefore(nextToken, "\n\n");
238                        }
239
240                        return fixer.insertTextBeforeRange([nextToken.range[0] - nextToken.loc.start.column, nextToken.range[1]], "\n");
241                    }
242                });
243            }
244        }
245
246        //--------------------------------------------------------------------------
247        // Public
248        //--------------------------------------------------------------------------
249
250        return {
251            VariableDeclaration: checkForBlankLine
252        };
253
254    }
255};
256