summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/implicit-arrow-linebreak.js
blob: fb7d603a35ad58e499b1238f3ed463327b098d1a (plain)
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/**
 * @fileoverview enforce the location of arrow function bodies
 * @author Sharmila Jesupaul
 */
"use strict";

const {
    isArrowToken,
    isParenthesised,
    isOpeningParenToken
} = require("../util/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
    meta: {
        type: "layout",

        docs: {
            description: "enforce the location of arrow function bodies",
            category: "Stylistic Issues",
            recommended: false,
            url: "https://eslint.org/docs/rules/implicit-arrow-linebreak"
        },

        fixable: "whitespace",

        schema: [
            {
                enum: ["beside", "below"]
            }
        ]
    },

    create(context) {
        const sourceCode = context.getSourceCode();

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------
        /**
         * Gets the applicable preference for a particular keyword
         * @returns {string} The applicable option for the keyword, e.g. 'beside'
         */
        function getOption() {
            return context.options[0] || "beside";
        }

        /**
         * Formats the comments depending on whether it's a line or block comment.
         * @param {Comment[]} comments The array of comments between the arrow and body
         * @param {Integer} column The column number of the first token
         * @returns {string} A string of comment text joined by line breaks
         */
        function formatComments(comments, column) {
            const whiteSpaces = " ".repeat(column);

            return `${comments.map(comment => {

                if (comment.type === "Line") {
                    return `//${comment.value}`;
                }

                return `/*${comment.value}*/`;
            }).join(`\n${whiteSpaces}`)}\n${whiteSpaces}`;
        }

        /**
         * Finds the first token to prepend comments to depending on the parent type
         * @param {Node} node The validated node
         * @returns {Token|Node} The node to prepend comments to
         */
        function findFirstToken(node) {
            switch (node.parent.type) {
                case "VariableDeclarator":

                    // If the parent is first or only declarator, return the declaration, else, declarator
                    return sourceCode.getFirstToken(
                        node.parent.parent.declarations.length === 1 ||
                        node.parent.parent.declarations[0].id.name === node.parent.id.name
                            ? node.parent.parent : node.parent
                    );
                case "CallExpression":
                case "Property":

                    // find the object key
                    return sourceCode.getFirstToken(node.parent);
                default:
                    return node;
            }
        }

        /**
         * Helper function for adding parentheses fixes for nodes containing nested arrow functions
         * @param {Fixer} fixer Fixer
         * @param {Token} arrow - The arrow token
         * @param {ASTNode} arrowBody - The arrow function body
         * @returns {Function[]} autofixer -- wraps function bodies with parentheses
         */
        function addParentheses(fixer, arrow, arrowBody) {
            const parenthesesFixes = [];
            let closingParentheses = "";

            let followingBody = arrowBody;
            let currentArrow = arrow;

            while (currentArrow) {
                if (!isParenthesised(sourceCode, followingBody)) {
                    parenthesesFixes.push(
                        fixer.insertTextAfter(currentArrow, " (")
                    );

                    const paramsToken = sourceCode.getTokenBefore(currentArrow, token =>
                        isOpeningParenToken(token) || token.type === "Identifier");

                    const whiteSpaces = " ".repeat(paramsToken.loc.start.column);

                    closingParentheses = `\n${whiteSpaces})${closingParentheses}`;
                }

                currentArrow = sourceCode.getTokenAfter(currentArrow, isArrowToken);

                if (currentArrow) {
                    followingBody = sourceCode.getTokenAfter(currentArrow, token => !isOpeningParenToken(token));
                }
            }

            return [...parenthesesFixes,
                fixer.insertTextAfter(arrowBody, closingParentheses)
            ];
        }

        /**
         * Autofixes the function body to collapse onto the same line as the arrow.
         * If comments exist, prepends the comments before the arrow function.
         * If the function body contains arrow functions, appends the function bodies with parentheses.
         * @param {Token} arrowToken The arrow token.
         * @param {ASTNode} arrowBody the function body
         * @param {ASTNode} node The evaluated node
         * @returns {Function} autofixer -- validates the node to adhere to besides
         */
        function autoFixBesides(arrowToken, arrowBody, node) {
            return fixer => {
                const placeBesides = fixer.replaceTextRange([arrowToken.range[1], arrowBody.range[0]], " ");

                const comments = sourceCode.getCommentsInside(node).filter(comment =>
                    comment.loc.start.line < arrowBody.loc.start.line);

                if (comments.length) {

                    // If the grandparent is not a variable declarator
                    if (
                        arrowBody.parent &&
                        arrowBody.parent.parent &&
                        arrowBody.parent.parent.type !== "VariableDeclarator"
                    ) {

                        // If any arrow functions follow, return the necessary parens fixes.
                        if (sourceCode.getTokenAfter(arrowToken, isArrowToken) && arrowBody.parent.parent.type !== "VariableDeclarator") {
                            return addParentheses(fixer, arrowToken, arrowBody);
                        }

                        // If any arrow functions precede, the necessary fixes have already been returned, so return null.
                        if (sourceCode.getTokenBefore(arrowToken, isArrowToken) && arrowBody.parent.parent.type !== "VariableDeclarator") {
                            return null;
                        }
                    }

                    const firstToken = findFirstToken(node);

                    const commentText = formatComments(comments, firstToken.loc.start.column);

                    const commentBeforeExpression = fixer.insertTextBeforeRange(
                        firstToken.range,
                        commentText
                    );

                    return [placeBesides, commentBeforeExpression];
                }

                return placeBesides;
            };
        }

        /**
         * Validates the location of an arrow function body
         * @param {ASTNode} node The arrow function body
         * @returns {void}
         */
        function validateExpression(node) {
            const option = getOption();

            let tokenBefore = sourceCode.getTokenBefore(node.body);
            const hasParens = tokenBefore.value === "(";

            if (node.type === "BlockStatement") {
                return;
            }

            let fixerTarget = node.body;

            if (hasParens) {

                // Gets the first token before the function body that is not an open paren
                tokenBefore = sourceCode.getTokenBefore(node.body, token => token.value !== "(");
                fixerTarget = sourceCode.getTokenAfter(tokenBefore);
            }

            if (tokenBefore.loc.end.line === fixerTarget.loc.start.line && option === "below") {
                context.report({
                    node: fixerTarget,
                    message: "Expected a linebreak before this expression.",
                    fix: fixer => fixer.insertTextBefore(fixerTarget, "\n")
                });
            } else if (tokenBefore.loc.end.line !== fixerTarget.loc.start.line && option === "beside") {
                context.report({
                    node: fixerTarget,
                    message: "Expected no linebreak before this expression.",
                    fix: autoFixBesides(tokenBefore, fixerTarget, node)
                });
            }
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------
        return {
            ArrowFunctionExpression: node => validateExpression(node)
        };
    }
};