UNPKG

1.76 kBJavaScriptView Raw
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// Helpers
10//------------------------------------------------------------------------------
11
12/*
13plain-English description of the following regexp:
140. `^` fix the match at the beginning of the string
151. `\/`: the `/` that begins the regexp
162. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
17 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
18 2.1. `\\.`: an escape sequence
19 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
203. `\/` the `/` that ends the regexp
214. `[gimuy]*`: optional regexp flags
225. `$`: fix the match at the end of the string
23*/
24const regex = /^\/([^\\[]|\\.|\[([^\\\]]|\\.)+])*\/[gimuy]*$/;
25
26//------------------------------------------------------------------------------
27// Rule Definition
28//------------------------------------------------------------------------------
29
30module.exports = {
31 meta: {
32 docs: {
33 description: "disallow empty character classes in regular expressions",
34 category: "Possible Errors",
35 recommended: true
36 },
37
38 schema: []
39 },
40
41 create(context) {
42 const sourceCode = context.getSourceCode();
43
44 return {
45
46 Literal(node) {
47 const token = sourceCode.getFirstToken(node);
48
49 if (token.type === "RegularExpression" && !regex.test(token.value)) {
50 context.report({ node, message: "Empty class." });
51 }
52 }
53
54 };
55
56 }
57};