function-paren-newline.js 9.11 KB
Newer Older
liang ce committed
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 233
/**
 * @fileoverview enforce consistent line breaks inside function parentheses
 * @author Teddy Katz
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("../util/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        type: "layout",

        docs: {
            description: "enforce consistent line breaks inside function parentheses",
            category: "Stylistic Issues",
            recommended: false,
            url: "https://eslint.org/docs/rules/function-paren-newline"
        },

        fixable: "whitespace",

        schema: [
            {
                oneOf: [
                    {
                        enum: ["always", "never", "consistent", "multiline"]
                    },
                    {
                        type: "object",
                        properties: {
                            minItems: {
                                type: "integer",
                                minimum: 0
                            }
                        },
                        additionalProperties: false
                    }
                ]
            }
        ],

        messages: {
            expectedBefore: "Expected newline before ')'.",
            expectedAfter: "Expected newline after '('.",
            unexpectedBefore: "Unexpected newline before '('.",
            unexpectedAfter: "Unexpected newline after ')'."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        const rawOption = context.options[0] || "multiline";
        const multilineOption = rawOption === "multiline";
        const consistentOption = rawOption === "consistent";
        let minItems;

        if (typeof rawOption === "object") {
            minItems = rawOption.minItems;
        } else if (rawOption === "always") {
            minItems = 0;
        } else if (rawOption === "never") {
            minItems = Infinity;
        } else {
            minItems = null;
        }

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        /**
         * Determines whether there should be newlines inside function parens
         * @param {ASTNode[]} elements The arguments or parameters in the list
         * @param {boolean} hasLeftNewline `true` if the left paren has a newline in the current code.
         * @returns {boolean} `true` if there should be newlines inside the function parens
         */
        function shouldHaveNewlines(elements, hasLeftNewline) {
            if (multilineOption) {
                return elements.some((element, index) => index !== elements.length - 1 && element.loc.end.line !== elements[index + 1].loc.start.line);
            }
            if (consistentOption) {
                return hasLeftNewline;
            }
            return elements.length >= minItems;
        }

        /**
         * Validates a list of arguments or parameters
         * @param {Object} parens An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token
         * @param {ASTNode[]} elements The arguments or parameters in the list
         * @returns {void}
         */
        function validateParens(parens, elements) {
            const leftParen = parens.leftParen;
            const rightParen = parens.rightParen;
            const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParen);
            const tokenBeforeRightParen = sourceCode.getTokenBefore(rightParen);
            const hasLeftNewline = !astUtils.isTokenOnSameLine(leftParen, tokenAfterLeftParen);
            const hasRightNewline = !astUtils.isTokenOnSameLine(tokenBeforeRightParen, rightParen);
            const needsNewlines = shouldHaveNewlines(elements, hasLeftNewline);

            if (hasLeftNewline && !needsNewlines) {
                context.report({
                    node: leftParen,
                    messageId: "unexpectedAfter",
                    fix(fixer) {
                        return sourceCode.getText().slice(leftParen.range[1], tokenAfterLeftParen.range[0]).trim()

                            // If there is a comment between the ( and the first element, don't do a fix.
                            ? null
                            : fixer.removeRange([leftParen.range[1], tokenAfterLeftParen.range[0]]);
                    }
                });
            } else if (!hasLeftNewline && needsNewlines) {
                context.report({
                    node: leftParen,
                    messageId: "expectedAfter",
                    fix: fixer => fixer.insertTextAfter(leftParen, "\n")
                });
            }

            if (hasRightNewline && !needsNewlines) {
                context.report({
                    node: rightParen,
                    messageId: "unexpectedBefore",
                    fix(fixer) {
                        return sourceCode.getText().slice(tokenBeforeRightParen.range[1], rightParen.range[0]).trim()

                            // If there is a comment between the last element and the ), don't do a fix.
                            ? null
                            : fixer.removeRange([tokenBeforeRightParen.range[1], rightParen.range[0]]);
                    }
                });
            } else if (!hasRightNewline && needsNewlines) {
                context.report({
                    node: rightParen,
                    messageId: "expectedBefore",
                    fix: fixer => fixer.insertTextBefore(rightParen, "\n")
                });
            }
        }

        /**
         * Gets the left paren and right paren tokens of a node.
         * @param {ASTNode} node The node with parens
         * @returns {Object} An object with keys `leftParen` for the left paren token, and `rightParen` for the right paren token.
         * Can also return `null` if an expression has no parens (e.g. a NewExpression with no arguments, or an ArrowFunctionExpression
         * with a single parameter)
         */
        function getParenTokens(node) {
            switch (node.type) {
                case "NewExpression":
                    if (!node.arguments.length && !(
                        astUtils.isOpeningParenToken(sourceCode.getLastToken(node, { skip: 1 })) &&
                        astUtils.isClosingParenToken(sourceCode.getLastToken(node))
                    )) {

                        // If the NewExpression does not have parens (e.g. `new Foo`), return null.
                        return null;
                    }

                    // falls through

                case "CallExpression":
                    return {
                        leftParen: sourceCode.getTokenAfter(node.callee, astUtils.isOpeningParenToken),
                        rightParen: sourceCode.getLastToken(node)
                    };

                case "FunctionDeclaration":
                case "FunctionExpression": {
                    const leftParen = sourceCode.getFirstToken(node, astUtils.isOpeningParenToken);
                    const rightParen = node.params.length
                        ? sourceCode.getTokenAfter(node.params[node.params.length - 1], astUtils.isClosingParenToken)
                        : sourceCode.getTokenAfter(leftParen);

                    return { leftParen, rightParen };
                }

                case "ArrowFunctionExpression": {
                    const firstToken = sourceCode.getFirstToken(node);

                    if (!astUtils.isOpeningParenToken(firstToken)) {

                        // If the ArrowFunctionExpression has a single param without parens, return null.
                        return null;
                    }

                    return {
                        leftParen: firstToken,
                        rightParen: sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken)
                    };
                }

                default:
                    throw new TypeError(`unexpected node with type ${node.type}`);
            }
        }

        /**
         * Validates the parentheses for a node
         * @param {ASTNode} node The node with parens
         * @returns {void}
         */
        function validateNode(node) {
            const parens = getParenTokens(node);

            if (parens) {
                validateParens(parens, astUtils.isFunction(node) ? node.params : node.arguments);
            }
        }

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {
            ArrowFunctionExpression: validateNode,
            CallExpression: validateNode,
            FunctionDeclaration: validateNode,
            FunctionExpression: validateNode,
            NewExpression: validateNode
        };
    }
};