1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | module.exports = {
|
13 | meta: {
|
14 | docs: {
|
15 | description: "require parenthesis around regex literals",
|
16 | category: "Stylistic Issues",
|
17 | recommended: false
|
18 | },
|
19 |
|
20 | schema: [],
|
21 |
|
22 | fixable: "code"
|
23 | },
|
24 |
|
25 | create(context) {
|
26 | const sourceCode = context.getSourceCode();
|
27 |
|
28 | return {
|
29 |
|
30 | Literal(node) {
|
31 | const token = sourceCode.getFirstToken(node),
|
32 | nodeType = token.type;
|
33 |
|
34 | if (nodeType === "RegularExpression") {
|
35 | const source = sourceCode.getTokenBefore(node);
|
36 | const ancestors = context.getAncestors();
|
37 | const grandparent = ancestors[ancestors.length - 1];
|
38 |
|
39 | if (grandparent.type === "MemberExpression" && grandparent.object === node &&
|
40 | (!source || source.value !== "(")) {
|
41 | context.report({
|
42 | node,
|
43 | message: "Wrap the regexp literal in parens to disambiguate the slash.",
|
44 | fix: fixer => fixer.replaceText(node, `(${sourceCode.getText(node)})`)
|
45 | });
|
46 | }
|
47 | }
|
48 | }
|
49 | };
|
50 |
|
51 | }
|
52 | };
|