UNPKG

1.52 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//------------------------------------------------------------------------------
7// Rule Definition
8//------------------------------------------------------------------------------
9
10module.exports = function(context) {
11
12 "use strict";
13
14 return {
15
16 "Literal": function(node) {
17 var tokens = context.getTokens(node);
18 tokens.forEach(function (token) {
19 /*
20 plain-English description of the following regexp:
21 0. `^` fix the match at the beginning of the string
22 1. `\/`: the `/` that begins the regexp
23 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following
24 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes)
25 2.1. `\\.`: an escape sequence
26 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty
27 3. `\/` the `/` that ends the regexp
28 4. `[gimy]*`: optional regexp flags
29 5. `$`: fix the match at the end of the string
30 */
31 if (token.type === "RegularExpression" &&
32 !/^\/([^\\[]|\\.|\[([^\\\]]|\\.)+\])*\/[gimy]*$/.test(token.value)) {
33 context.report(node, "Empty class.");
34 }
35 });
36 }
37
38 };
39
40};