Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 1 | /** |
| 2 | * @fileoverview enforce the location of arrow function bodies |
| 3 | * @author Sharmila Jesupaul |
| 4 | */ |
| 5 | "use strict"; |
| 6 | |
| 7 | const { isCommentToken, isNotOpeningParenToken } = require("./utils/ast-utils"); |
| 8 | |
| 9 | //------------------------------------------------------------------------------ |
| 10 | // Rule Definition |
| 11 | //------------------------------------------------------------------------------ |
| 12 | module.exports = { |
| 13 | meta: { |
| 14 | type: "layout", |
| 15 | |
| 16 | docs: { |
| 17 | description: "enforce the location of arrow function bodies", |
Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame] | 18 | recommended: false, |
| 19 | url: "https://eslint.org/docs/rules/implicit-arrow-linebreak" |
| 20 | }, |
| 21 | |
| 22 | fixable: "whitespace", |
| 23 | |
| 24 | schema: [ |
| 25 | { |
| 26 | enum: ["beside", "below"] |
| 27 | } |
| 28 | ], |
| 29 | messages: { |
| 30 | expected: "Expected a linebreak before this expression.", |
| 31 | unexpected: "Expected no linebreak before this expression." |
| 32 | } |
| 33 | }, |
| 34 | |
| 35 | create(context) { |
| 36 | const sourceCode = context.getSourceCode(); |
| 37 | const option = context.options[0] || "beside"; |
| 38 | |
| 39 | /** |
| 40 | * Validates the location of an arrow function body |
| 41 | * @param {ASTNode} node The arrow function body |
| 42 | * @returns {void} |
| 43 | */ |
| 44 | function validateExpression(node) { |
| 45 | if (node.body.type === "BlockStatement") { |
| 46 | return; |
| 47 | } |
| 48 | |
| 49 | const arrowToken = sourceCode.getTokenBefore(node.body, isNotOpeningParenToken); |
| 50 | const firstTokenOfBody = sourceCode.getTokenAfter(arrowToken); |
| 51 | |
| 52 | if (arrowToken.loc.end.line === firstTokenOfBody.loc.start.line && option === "below") { |
| 53 | context.report({ |
| 54 | node: firstTokenOfBody, |
| 55 | messageId: "expected", |
| 56 | fix: fixer => fixer.insertTextBefore(firstTokenOfBody, "\n") |
| 57 | }); |
| 58 | } else if (arrowToken.loc.end.line !== firstTokenOfBody.loc.start.line && option === "beside") { |
| 59 | context.report({ |
| 60 | node: firstTokenOfBody, |
| 61 | messageId: "unexpected", |
| 62 | fix(fixer) { |
| 63 | if (sourceCode.getFirstTokenBetween(arrowToken, firstTokenOfBody, { includeComments: true, filter: isCommentToken })) { |
| 64 | return null; |
| 65 | } |
| 66 | |
| 67 | return fixer.replaceTextRange([arrowToken.range[1], firstTokenOfBody.range[0]], " "); |
| 68 | } |
| 69 | }); |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | //---------------------------------------------------------------------- |
| 74 | // Public |
| 75 | //---------------------------------------------------------------------- |
| 76 | return { |
| 77 | ArrowFunctionExpression: node => validateExpression(node) |
| 78 | }; |
| 79 | } |
| 80 | }; |