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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use serde::{Deserialize, Serialize};
use crate::rule_config::Rule;
use ast_grep_core::language::Language;
use ast_grep_core::meta_var::MetaVarEnv;
use ast_grep_core::meta_var::MetaVarMatchers;
use ast_grep_core::{KindMatcher, Matcher, MetaVarMatcher, Node, Pattern};
use bit_set::BitSet;
use regex::Regex;
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub enum SerializableMetaVarMatcher {
Regex(String),
Pattern(String),
Kind(String),
}
#[derive(Debug)]
pub enum SerializeError {
InvalidRegex(regex::Error),
InvalidKind(String),
}
pub fn try_from_serializable<L: Language>(
meta_var: SerializableMetaVarMatcher,
lang: L,
) -> Result<MetaVarMatcher<L>, SerializeError> {
use SerializableMetaVarMatcher as S;
match meta_var {
S::Regex(s) => match Regex::new(&s) {
Ok(r) => Ok(MetaVarMatcher::Regex(r)),
Err(e) => Err(SerializeError::InvalidRegex(e)),
},
S::Kind(p) => {
let kind = KindMatcher::new(&p, lang);
if kind.is_invalid() {
Err(SerializeError::InvalidKind(p))
} else {
Ok(MetaVarMatcher::Kind(kind))
}
}
S::Pattern(p) => Ok(MetaVarMatcher::Pattern(Pattern::new(&p, lang))),
}
}
pub fn try_deserialize_matchers<L: Language>(
meta_vars: HashMap<String, SerializableMetaVarMatcher>,
lang: L,
) -> Result<MetaVarMatchers<L>, SerializeError> {
let mut map = MetaVarMatchers::new();
for (key, matcher) in meta_vars {
map.insert(key, try_from_serializable(matcher, lang.clone())?);
}
Ok(map)
}
pub struct RuleWithConstraint<L: Language> {
pub rule: Rule<L>,
pub matchers: MetaVarMatchers<L>,
}
impl<L: Language> Default for RuleWithConstraint<L> {
fn default() -> Self {
Self {
rule: Rule::default(),
matchers: MetaVarMatchers::default(),
}
}
}
impl<L: Language> Matcher<L> for RuleWithConstraint<L> {
fn match_node_with_env<'tree>(
&self,
node: Node<'tree, L>,
env: &mut MetaVarEnv<'tree, L>,
) -> Option<Node<'tree, L>> {
self.rule.match_node_with_env(node, env)
}
fn get_meta_var_env<'tree>(&self) -> MetaVarEnv<'tree, L> {
MetaVarEnv::from_matchers(self.matchers.clone())
}
fn potential_kinds(&self) -> Option<BitSet> {
self.rule.potential_kinds()
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::from_str;
use crate::test::TypeScript;
macro_rules! cast {
($reg: expr, $pattern: path) => {
match $reg {
$pattern(a) => a,
_ => panic!("non-matching variant"),
}
};
}
#[test]
fn test_rule_with_constraints() {
let mut matchers = MetaVarMatchers::new();
matchers.insert(
"A".to_string(),
MetaVarMatcher::Regex(Regex::new("a").unwrap()),
);
let rule = RuleWithConstraint {
rule: Rule::Pattern(Pattern::new("$A", TypeScript::Tsx)),
matchers,
};
let grep = TypeScript::Tsx.ast_grep("a");
assert!(grep.root().find(&rule).is_some());
let grep = TypeScript::Tsx.ast_grep("bbb");
assert!(grep.root().find(&rule).is_none());
}
#[test]
fn test_serializable_regex() {
let yaml = from_str("regex: a").expect("must parse");
let matcher = try_from_serializable(yaml, TypeScript::Tsx).expect("should parse");
let reg = cast!(matcher, MetaVarMatcher::Regex);
assert!(reg.is_match("aaaaa"));
assert!(!reg.is_match("bbb"));
}
#[test]
fn test_non_serializable_regex() {
let yaml = from_str("regex: '*'").expect("must parse");
let matcher = try_from_serializable(yaml, TypeScript::Tsx);
assert!(matches!(matcher, Err(SerializeError::InvalidRegex(_))));
}
#[test]
fn test_serializable_pattern() {
let yaml = from_str("pattern: var a = 1").expect("must parse");
let matcher = try_from_serializable(yaml, TypeScript::Tsx).expect("should parse");
let pattern = cast!(matcher, MetaVarMatcher::Pattern);
let matched = TypeScript::Tsx.ast_grep("var a = 1");
assert!(matched.root().find(&pattern).is_some());
let non_matched = TypeScript::Tsx.ast_grep("var b = 2");
assert!(non_matched.root().find(&pattern).is_none());
}
#[test]
fn test_serializable_kind() {
let yaml = from_str("kind: class_body").expect("must parse");
let matcher = try_from_serializable(yaml, TypeScript::Tsx).expect("should parse");
let pattern = cast!(matcher, MetaVarMatcher::Kind);
let matched = TypeScript::Tsx.ast_grep("class A {}");
assert!(matched.root().find(&pattern).is_some());
let non_matched = TypeScript::Tsx.ast_grep("function b() {}");
assert!(non_matched.root().find(&pattern).is_none());
}
#[test]
fn test_non_serializable_kind() {
let yaml = from_str("kind: IMPOSSIBLE_KIND").expect("must parse");
let matcher = try_from_serializable(yaml, TypeScript::Tsx);
let error = match matcher {
Err(SerializeError::InvalidKind(s)) => s,
_ => panic!("serialization should fail for invalid kind"),
};
assert_eq!(error, "IMPOSSIBLE_KIND");
}
}