1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use super::Context;
use super::LintRule;
use crate::swc_ecma_ast;
use crate::swc_ecma_ast::Regex;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;
pub struct NoEmptyCharacterClass;
impl LintRule for NoEmptyCharacterClass {
fn new() -> Box<Self> {
Box::new(NoEmptyCharacterClass)
}
fn code(&self) -> &'static str {
"no-empty-character-class"
}
fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) {
let mut visitor = NoEmptyCharacterClassVisitor::new(context);
visitor.visit_module(&module, &module);
}
}
struct NoEmptyCharacterClassVisitor {
context: Context,
}
impl NoEmptyCharacterClassVisitor {
pub fn new(context: Context) -> Self {
Self { context }
}
}
impl Visit for NoEmptyCharacterClassVisitor {
fn visit_regex(&mut self, regex: &Regex, _parent: &dyn Node) {
let raw_regex = self
.context
.source_map
.span_to_snippet(regex.span)
.expect("error in loading snippet");
lazy_static! {
static ref RULE_REGEX: regex::Regex = regex::Regex::new(
r"(?u)^/([^\\\[]|\\.|\[([^\\\]]|\\.)+\])*/[gimuys]*$"
)
.unwrap();
}
if !RULE_REGEX.is_match(&raw_regex) {
self.context.add_diagnostic(
regex.span,
"no-empty-character-class",
"empty character class in RegExp is not allowed",
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::*;
#[test]
fn no_empty_character_class() {
assert_lint_err::<NoEmptyCharacterClass>(r#"const foo = /^abc[]/;"#, 12);
assert_lint_err::<NoEmptyCharacterClass>(r#"const foo = /foo[]bar/;"#, 12);
assert_lint_err::<NoEmptyCharacterClass>(r#"const foo = /[]]/;"#, 12);
assert_lint_err::<NoEmptyCharacterClass>(r#"const foo = /\[[]/;"#, 12);
assert_lint_err::<NoEmptyCharacterClass>(
r#"const foo = /\\[\\[\\]a-z[]/;"#,
12,
);
}
#[test]
fn no_empty_character_class_match() {
assert_lint_err::<NoEmptyCharacterClass>(r#"/^abc[]/.test("abcdefg");"#, 0);
assert_lint_err::<NoEmptyCharacterClass>(
r#"if (foo.match(/^abc[]/)) {}"#,
14,
);
}
#[test]
fn no_empty_character_class_test() {
assert_lint_err::<NoEmptyCharacterClass>(
r#""abcdefg".match(/^abc[]/);"#,
16,
);
assert_lint_err::<NoEmptyCharacterClass>(
r#"if (/^abc[]/.test(foo)) {}"#,
4,
);
}
#[test]
fn no_empty_character_class_valid() {
assert_lint_ok::<NoEmptyCharacterClass>(
r#"
const foo = /^abc[a-zA-Z]/;
const regExp = new RegExp("^abc[]");
const foo = /^abc/;
const foo = /[\\[]/;
const foo = /[\\]]/;
const foo = /[a-zA-Z\\[]/;
const foo = /[[]/;
const foo = /[\\[a-z[]]/;
const foo = /[\-\[\]\/\{\}\(\)\*\+\?\.\\^\$\|]/g;
const foo = /\[/g;
const foo = /\]/i;
"#,
);
}
}