1 | /**
|
---|
2 | * @fileoverview Rule to flag the use of empty character classes in regular expressions
|
---|
3 | * @author Ian Christian Myers
|
---|
4 | */
|
---|
5 |
|
---|
6 | "use strict";
|
---|
7 |
|
---|
8 | //------------------------------------------------------------------------------
|
---|
9 | // Requirements
|
---|
10 | //------------------------------------------------------------------------------
|
---|
11 |
|
---|
12 | const { RegExpParser, visitRegExpAST } = require("@eslint-community/regexpp");
|
---|
13 |
|
---|
14 | //------------------------------------------------------------------------------
|
---|
15 | // Helpers
|
---|
16 | //------------------------------------------------------------------------------
|
---|
17 |
|
---|
18 | const parser = new RegExpParser();
|
---|
19 | const QUICK_TEST_REGEX = /\[\]/u;
|
---|
20 |
|
---|
21 | //------------------------------------------------------------------------------
|
---|
22 | // Rule Definition
|
---|
23 | //------------------------------------------------------------------------------
|
---|
24 |
|
---|
25 | /** @type {import('../shared/types').Rule} */
|
---|
26 | module.exports = {
|
---|
27 | meta: {
|
---|
28 | type: "problem",
|
---|
29 |
|
---|
30 | docs: {
|
---|
31 | description: "Disallow empty character classes in regular expressions",
|
---|
32 | recommended: true,
|
---|
33 | url: "https://eslint.org/docs/latest/rules/no-empty-character-class"
|
---|
34 | },
|
---|
35 |
|
---|
36 | schema: [],
|
---|
37 |
|
---|
38 | messages: {
|
---|
39 | unexpected: "Empty class."
|
---|
40 | }
|
---|
41 | },
|
---|
42 |
|
---|
43 | create(context) {
|
---|
44 | return {
|
---|
45 | "Literal[regex]"(node) {
|
---|
46 | const { pattern, flags } = node.regex;
|
---|
47 |
|
---|
48 | if (!QUICK_TEST_REGEX.test(pattern)) {
|
---|
49 | return;
|
---|
50 | }
|
---|
51 |
|
---|
52 | let regExpAST;
|
---|
53 |
|
---|
54 | try {
|
---|
55 | regExpAST = parser.parsePattern(pattern, 0, pattern.length, {
|
---|
56 | unicode: flags.includes("u"),
|
---|
57 | unicodeSets: flags.includes("v")
|
---|
58 | });
|
---|
59 | } catch {
|
---|
60 |
|
---|
61 | // Ignore regular expressions that regexpp cannot parse
|
---|
62 | return;
|
---|
63 | }
|
---|
64 |
|
---|
65 | visitRegExpAST(regExpAST, {
|
---|
66 | onCharacterClassEnter(characterClass) {
|
---|
67 | if (!characterClass.negate && characterClass.elements.length === 0) {
|
---|
68 | context.report({ node, messageId: "unexpected" });
|
---|
69 | }
|
---|
70 | }
|
---|
71 | });
|
---|
72 | }
|
---|
73 | };
|
---|
74 |
|
---|
75 | }
|
---|
76 | };
|
---|