Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 1 | /** |
| 2 | * @fileoverview Rule to flag when regex literals are not wrapped in parens |
| 3 | * @author Matt DuVall <http://www.mattduvall.com> |
| 4 | */ |
| 5 | |
| 6 | "use strict"; |
| 7 | |
| 8 | //------------------------------------------------------------------------------ |
| 9 | // Rule Definition |
| 10 | //------------------------------------------------------------------------------ |
| 11 | |
| 12 | module.exports = { |
| 13 | meta: { |
| 14 | type: "layout", |
| 15 | |
| 16 | docs: { |
| 17 | description: "require parenthesis around regex literals", |
| 18 | category: "Stylistic Issues", |
| 19 | recommended: false, |
| 20 | url: "https://eslint.org/docs/rules/wrap-regex" |
| 21 | }, |
| 22 | |
| 23 | schema: [], |
| 24 | fixable: "code", |
| 25 | |
| 26 | messages: { |
| 27 | requireParens: "Wrap the regexp literal in parens to disambiguate the slash." |
| 28 | } |
| 29 | }, |
| 30 | |
| 31 | create(context) { |
| 32 | const sourceCode = context.getSourceCode(); |
| 33 | |
| 34 | return { |
| 35 | |
| 36 | Literal(node) { |
| 37 | const token = sourceCode.getFirstToken(node), |
| 38 | nodeType = token.type; |
| 39 | |
| 40 | if (nodeType === "RegularExpression") { |
| 41 | const beforeToken = sourceCode.getTokenBefore(node); |
| 42 | const afterToken = sourceCode.getTokenAfter(node); |
| 43 | const ancestors = context.getAncestors(); |
| 44 | const grandparent = ancestors[ancestors.length - 1]; |
| 45 | |
| 46 | if (grandparent.type === "MemberExpression" && grandparent.object === node && |
| 47 | !(beforeToken && beforeToken.value === "(" && afterToken && afterToken.value === ")")) { |
| 48 | context.report({ |
| 49 | node, |
| 50 | messageId: "requireParens", |
| 51 | fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`) |
| 52 | }); |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | }; |
| 57 | |
| 58 | } |
| 59 | }; |