Skip to content

Commit 1997797

Browse files
committed
Factor out rules parsing
1 parent 998ed13 commit 1997797

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

crates/ra_mbe/src/lib.rs

+20-24
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,18 @@ impl_froms!(TokenTree: Leaf, Subtree);
161161
)
162162
}
163163

164+
fn create_rules(macro_definition: &str) -> MacroRules {
165+
let source_file = ast::SourceFile::parse(macro_definition);
166+
let macro_definition = source_file
167+
.syntax()
168+
.descendants()
169+
.find_map(ast::MacroCall::cast)
170+
.unwrap();
171+
172+
let definition_tt = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap();
173+
crate::MacroRules::parse(&definition_tt).unwrap()
174+
}
175+
164176
fn assert_expansion(rules: &MacroRules, invocation: &str, expansion: &str) {
165177
let source_file = ast::SourceFile::parse(invocation);
166178
let macro_invocation = source_file
@@ -177,7 +189,8 @@ impl_froms!(TokenTree: Leaf, Subtree);
177189

178190
#[test]
179191
fn test_fail_match_pattern_by_first_token() {
180-
let macro_definition = r#"
192+
let rules = create_rules(
193+
r#"
181194
macro_rules! foo {
182195
($ i:ident) => (
183196
mod $ i {}
@@ -189,17 +202,8 @@ impl_froms!(TokenTree: Leaf, Subtree);
189202
struct $ i;
190203
)
191204
}
192-
"#;
193-
194-
let source_file = ast::SourceFile::parse(macro_definition);
195-
let macro_definition = source_file
196-
.syntax()
197-
.descendants()
198-
.find_map(ast::MacroCall::cast)
199-
.unwrap();
200-
201-
let definition_tt = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap();
202-
let rules = crate::MacroRules::parse(&definition_tt).unwrap();
205+
"#,
206+
);
203207

204208
assert_expansion(&rules, "foo! { foo }", "mod foo {}");
205209
assert_expansion(&rules, "foo! { = bar }", "fn bar () {}");
@@ -208,7 +212,8 @@ impl_froms!(TokenTree: Leaf, Subtree);
208212

209213
#[test]
210214
fn test_fail_match_pattern_by_last_token() {
211-
let macro_definition = r#"
215+
let rules = create_rules(
216+
r#"
212217
macro_rules! foo {
213218
($ i:ident) => (
214219
mod $ i {}
@@ -220,17 +225,8 @@ impl_froms!(TokenTree: Leaf, Subtree);
220225
struct $ i;
221226
)
222227
}
223-
"#;
224-
225-
let source_file = ast::SourceFile::parse(macro_definition);
226-
let macro_definition = source_file
227-
.syntax()
228-
.descendants()
229-
.find_map(ast::MacroCall::cast)
230-
.unwrap();
231-
232-
let definition_tt = ast_to_token_tree(macro_definition.token_tree().unwrap()).unwrap();
233-
let rules = crate::MacroRules::parse(&definition_tt).unwrap();
228+
"#,
229+
);
234230

235231
assert_expansion(&rules, "foo! { foo }", "mod foo {}");
236232
assert_expansion(&rules, "foo! { bar = }", "fn bar () {}");

0 commit comments

Comments
 (0)