blob: f75f59191aae40820394b1c5a52177059ffe6683 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
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// Helpers
10//------------------------------------------------------------------------------
11
12/*
13 * plain-English description of the following regexp:
14 * 0. `^` fix the match at the beginning of the string
Tim van der Lippe0fb47802021-11-08 16:23:10 +000015 * 1. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
16 * 1.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
17 * 1.1. `\\.`: an escape sequence
18 * 1.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
19 * 2. `$`: fix the match at the end of the string
Yang Guo4fd355c2019-09-19 10:59:03 +020020 */
Tim van der Lippe0fb47802021-11-08 16:23:10 +000021const regex = /^([^\\[]|\\.|\[([^\\\]]|\\.)+\])*$/u;
Yang Guo4fd355c2019-09-19 10:59:03 +020022
23//------------------------------------------------------------------------------
24// Rule Definition
25//------------------------------------------------------------------------------
26
Tim van der Lippe0ceb4652022-01-06 14:23:36 +010027/** @type {import('../shared/types').Rule} */
Yang Guo4fd355c2019-09-19 10:59:03 +020028module.exports = {
29 meta: {
30 type: "problem",
31
32 docs: {
33 description: "disallow empty character classes in regular expressions",
Yang Guo4fd355c2019-09-19 10:59:03 +020034 recommended: true,
35 url: "https://eslint.org/docs/rules/no-empty-character-class"
36 },
37
38 schema: [],
39
40 messages: {
41 unexpected: "Empty class."
42 }
43 },
44
45 create(context) {
Yang Guo4fd355c2019-09-19 10:59:03 +020046 return {
Tim van der Lippe0fb47802021-11-08 16:23:10 +000047 "Literal[regex]"(node) {
48 if (!regex.test(node.regex.pattern)) {
Yang Guo4fd355c2019-09-19 10:59:03 +020049 context.report({ node, messageId: "unexpected" });
50 }
51 }
Yang Guo4fd355c2019-09-19 10:59:03 +020052 };
53
54 }
55};