aboutsummaryrefslogtreecommitdiff
path: root/crates/mbe/src
diff options
context:
space:
mode:
authorEdwin Cheng <[email protected]>2021-03-18 09:22:52 +0000
committerEdwin Cheng <[email protected]>2021-03-18 09:22:52 +0000
commit49b876de094db571d1ae10577ce2405909d3bd3e (patch)
tree8b10a91888d48fea3329f8544435bdf4c1976502 /crates/mbe/src
parentf7fbea509f1e5f840e715c912ee38aa997d1bfbc (diff)
Reorganize mbe tests
Diffstat (limited to 'crates/mbe/src')
-rw-r--r--crates/mbe/src/tests.rs1994
-rw-r--r--crates/mbe/src/tests/expand.rs1872
-rw-r--r--crates/mbe/src/tests/rule.rs45
3 files changed, 1952 insertions, 1959 deletions
diff --git a/crates/mbe/src/tests.rs b/crates/mbe/src/tests.rs
index 25c374b9b..6da18ecf4 100644
--- a/crates/mbe/src/tests.rs
+++ b/crates/mbe/src/tests.rs
@@ -1,1775 +1,14 @@
1mod expand;
2mod rule;
3
1use std::fmt::Write; 4use std::fmt::Write;
2 5
3use ::parser::FragmentKind; 6use ::parser::FragmentKind;
4use syntax::{ 7use syntax::{ast, AstNode, NodeOrToken, SyntaxNode, WalkEvent};
5 ast, AstNode, NodeOrToken,
6 SyntaxKind::{ERROR, IDENT},
7 SyntaxNode, WalkEvent, T,
8};
9use test_utils::assert_eq_text; 8use test_utils::assert_eq_text;
10 9
11use super::*; 10use super::*;
12 11
13mod rule_parsing {
14 use syntax::{ast, AstNode};
15
16 use crate::ast_to_token_tree;
17
18 use super::*;
19
20 #[test]
21 fn test_valid_arms() {
22 fn check(macro_body: &str) {
23 let m = parse_macro_arm(macro_body);
24 m.unwrap();
25 }
26
27 check("($i:ident) => ()");
28 check("($($i:ident)*) => ($_)");
29 check("($($true:ident)*) => ($true)");
30 check("($($false:ident)*) => ($false)");
31 check("($) => ($)");
32 }
33
34 #[test]
35 fn test_invalid_arms() {
36 fn check(macro_body: &str, err: ParseError) {
37 let m = parse_macro_arm(macro_body);
38 assert_eq!(m, Err(err));
39 }
40 check("invalid", ParseError::Expected("expected subtree".into()));
41
42 check("$i:ident => ()", ParseError::Expected("expected subtree".into()));
43 check("($i:ident) ()", ParseError::Expected("expected `=`".into()));
44 check("($($i:ident)_) => ()", ParseError::InvalidRepeat);
45
46 check("($i) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
47 check("($i:) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
48 }
49
50 fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
51 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
52 let source_file = ast::SourceFile::parse(&macro_definition).ok().unwrap();
53 let macro_definition =
54 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
55
56 let (definition_tt, _) =
57 ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
58 crate::MacroRules::parse(&definition_tt)
59 }
60}
61
62// Good first issue (although a slightly challenging one):
63//
64// * Pick a random test from here
65// https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
66// * Port the test to rust and add it to this module
67// * Make it pass :-)
68
69#[test]
70fn test_token_id_shift() {
71 let expansion = parse_macro(
72 r#"
73macro_rules! foobar {
74 ($e:ident) => { foo bar $e }
75}
76"#,
77 )
78 .expand_tt("foobar!(baz);");
79
80 fn get_id(t: &tt::TokenTree) -> Option<u32> {
81 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
82 return Some(ident.id.0);
83 }
84 None
85 }
86
87 assert_eq!(expansion.token_trees.len(), 3);
88 // {($e:ident) => { foo bar $e }}
89 // 012345 67 8 9 T 12
90 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
91 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
92
93 // The input args of macro call include parentheses:
94 // (baz)
95 // So baz should be 12+1+1
96 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
97}
98
99#[test]
100fn test_token_map() {
101 let expanded = parse_macro(
102 r#"
103macro_rules! foobar {
104 ($e:ident) => { fn $e() {} }
105}
106"#,
107 )
108 .expand_tt("foobar!(baz);");
109
110 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
111 let content = node.syntax_node().to_string();
112
113 let get_text = |id, kind| -> String {
114 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
115 };
116
117 assert_eq!(expanded.token_trees.len(), 4);
118 // {($e:ident) => { fn $e() {} }}
119 // 012345 67 8 9 T12 3
120
121 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
122 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
123 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
124}
125
126#[test]
127fn test_convert_tt() {
128 parse_macro(r#"
129macro_rules! impl_froms {
130 ($e:ident: $($v:ident),*) => {
131 $(
132 impl From<$v> for $e {
133 fn from(it: $v) -> $e {
134 $e::$v(it)
135 }
136 }
137 )*
138 }
139}
140"#)
141 .assert_expand_tt(
142 "impl_froms!(TokenTree: Leaf, Subtree);",
143 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
144 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
145 );
146}
147
148#[test]
149fn test_convert_tt2() {
150 parse_macro(
151 r#"
152macro_rules! impl_froms {
153 ($e:ident: $($v:ident),*) => {
154 $(
155 impl From<$v> for $e {
156 fn from(it: $v) -> $e {
157 $e::$v(it)
158 }
159 }
160 )*
161 }
162}
163"#,
164 )
165 .assert_expand(
166 "impl_froms!(TokenTree: Leaf, Subtree);",
167 r#"
168SUBTREE $
169 IDENT impl 20
170 IDENT From 21
171 PUNCH < [joint] 22
172 IDENT Leaf 53
173 PUNCH > [alone] 25
174 IDENT for 26
175 IDENT TokenTree 51
176 SUBTREE {} 29
177 IDENT fn 30
178 IDENT from 31
179 SUBTREE () 32
180 IDENT it 33
181 PUNCH : [alone] 34
182 IDENT Leaf 53
183 PUNCH - [joint] 37
184 PUNCH > [alone] 38
185 IDENT TokenTree 51
186 SUBTREE {} 41
187 IDENT TokenTree 51
188 PUNCH : [joint] 44
189 PUNCH : [joint] 45
190 IDENT Leaf 53
191 SUBTREE () 48
192 IDENT it 49
193 IDENT impl 20
194 IDENT From 21
195 PUNCH < [joint] 22
196 IDENT Subtree 55
197 PUNCH > [alone] 25
198 IDENT for 26
199 IDENT TokenTree 51
200 SUBTREE {} 29
201 IDENT fn 30
202 IDENT from 31
203 SUBTREE () 32
204 IDENT it 33
205 PUNCH : [alone] 34
206 IDENT Subtree 55
207 PUNCH - [joint] 37
208 PUNCH > [alone] 38
209 IDENT TokenTree 51
210 SUBTREE {} 41
211 IDENT TokenTree 51
212 PUNCH : [joint] 44
213 PUNCH : [joint] 45
214 IDENT Subtree 55
215 SUBTREE () 48
216 IDENT it 49
217"#,
218 );
219}
220
221#[test]
222fn test_lifetime_split() {
223 parse_macro(
224 r#"
225macro_rules! foo {
226 ($($t:tt)*) => { $($t)*}
227}
228"#,
229 )
230 .assert_expand(
231 r#"foo!(static bar: &'static str = "hello";);"#,
232 r#"
233SUBTREE $
234 IDENT static 17
235 IDENT bar 18
236 PUNCH : [alone] 19
237 PUNCH & [alone] 20
238 PUNCH ' [joint] 21
239 IDENT static 22
240 IDENT str 23
241 PUNCH = [alone] 24
242 LITERAL "hello" 25
243 PUNCH ; [joint] 26
244"#,
245 );
246}
247
248#[test]
249fn test_expr_order() {
250 let expanded = parse_macro(
251 r#"
252 macro_rules! foo {
253 ($ i:expr) => {
254 fn bar() { $ i * 2; }
255 }
256 }
257"#,
258 )
259 .expand_items("foo! { 1 + 1}");
260
261 let dump = format!("{:#?}", expanded);
262 assert_eq_text!(
263 r#"[email protected]
264 [email protected]
265 [email protected] "fn"
266 [email protected]
267 [email protected] "bar"
268 [email protected]
269 [email protected] "("
270 [email protected] ")"
271 [email protected]
272 [email protected] "{"
273 [email protected]
274 [email protected]
275 [email protected]
276 [email protected]
277 [email protected] "1"
278 [email protected] "+"
279 [email protected]
280 [email protected] "1"
281 [email protected] "*"
282 [email protected]
283 [email protected] "2"
284 [email protected] ";"
285 [email protected] "}""#,
286 dump.trim()
287 );
288}
289
290#[test]
291fn test_fail_match_pattern_by_first_token() {
292 parse_macro(
293 r#"
294 macro_rules! foo {
295 ($ i:ident) => (
296 mod $ i {}
297 );
298 (= $ i:ident) => (
299 fn $ i() {}
300 );
301 (+ $ i:ident) => (
302 struct $ i;
303 )
304 }
305"#,
306 )
307 .assert_expand_items("foo! { foo }", "mod foo {}")
308 .assert_expand_items("foo! { = bar }", "fn bar () {}")
309 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
310}
311
312#[test]
313fn test_fail_match_pattern_by_last_token() {
314 parse_macro(
315 r#"
316 macro_rules! foo {
317 ($ i:ident) => (
318 mod $ i {}
319 );
320 ($ i:ident =) => (
321 fn $ i() {}
322 );
323 ($ i:ident +) => (
324 struct $ i;
325 )
326 }
327"#,
328 )
329 .assert_expand_items("foo! { foo }", "mod foo {}")
330 .assert_expand_items("foo! { bar = }", "fn bar () {}")
331 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
332}
333
334#[test]
335fn test_fail_match_pattern_by_word_token() {
336 parse_macro(
337 r#"
338 macro_rules! foo {
339 ($ i:ident) => (
340 mod $ i {}
341 );
342 (spam $ i:ident) => (
343 fn $ i() {}
344 );
345 (eggs $ i:ident) => (
346 struct $ i;
347 )
348 }
349"#,
350 )
351 .assert_expand_items("foo! { foo }", "mod foo {}")
352 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
353 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
354}
355
356#[test]
357fn test_match_group_pattern_by_separator_token() {
358 parse_macro(
359 r#"
360 macro_rules! foo {
361 ($ ($ i:ident),*) => ($ (
362 mod $ i {}
363 )*);
364 ($ ($ i:ident)#*) => ($ (
365 fn $ i() {}
366 )*);
367 ($ i:ident ,# $ j:ident) => (
368 struct $ i;
369 struct $ j;
370 )
371 }
372"#,
373 )
374 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
375 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
376 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
377}
378
379#[test]
380fn test_match_group_pattern_with_multiple_defs() {
381 parse_macro(
382 r#"
383 macro_rules! foo {
384 ($ ($ i:ident),*) => ( struct Bar { $ (
385 fn $ i {}
386 )*} );
387 }
388"#,
389 )
390 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
391}
392
393#[test]
394fn test_match_group_pattern_with_multiple_statement() {
395 parse_macro(
396 r#"
397 macro_rules! foo {
398 ($ ($ i:ident),*) => ( fn baz { $ (
399 $ i ();
400 )*} );
401 }
402"#,
403 )
404 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
405}
406
407#[test]
408fn test_match_group_pattern_with_multiple_statement_without_semi() {
409 parse_macro(
410 r#"
411 macro_rules! foo {
412 ($ ($ i:ident),*) => ( fn baz { $ (
413 $i()
414 );*} );
415 }
416"#,
417 )
418 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
419}
420
421#[test]
422fn test_match_group_empty_fixed_token() {
423 parse_macro(
424 r#"
425 macro_rules! foo {
426 ($ ($ i:ident)* #abc) => ( fn baz { $ (
427 $ i ();
428 )*} );
429 }
430"#,
431 )
432 .assert_expand_items("foo! {#abc}", "fn baz {}");
433}
434
435#[test]
436fn test_match_group_in_subtree() {
437 parse_macro(
438 r#"
439 macro_rules! foo {
440 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
441 $ i ();
442 )*} );
443 }"#,
444 )
445 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
446}
447
448#[test]
449fn test_match_group_with_multichar_sep() {
450 parse_macro(
451 r#"
452 macro_rules! foo {
453 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
454 }"#,
455 )
456 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
457}
458
459#[test]
460fn test_match_group_with_multichar_sep2() {
461 parse_macro(
462 r#"
463 macro_rules! foo {
464 (fn $name:ident {$($i:literal)&&*} ) => ( fn $name() -> bool { $($i)&&*} );
465 }"#,
466 )
467 .assert_expand_items("foo! (fn baz {true && true} );", "fn baz () -> bool {true &&true}");
468}
469
470#[test]
471fn test_match_group_zero_match() {
472 parse_macro(
473 r#"
474 macro_rules! foo {
475 ( $($i:ident)* ) => ();
476 }"#,
477 )
478 .assert_expand_items("foo! ();", "");
479}
480
481#[test]
482fn test_match_group_in_group() {
483 parse_macro(
484 r#"
485 macro_rules! foo {
486 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
487 }"#,
488 )
489 .assert_expand_items("foo! ( (a b) );", "(a b)");
490}
491
492#[test]
493fn test_expand_to_item_list() {
494 let tree = parse_macro(
495 "
496 macro_rules! structs {
497 ($($i:ident),*) => {
498 $(struct $i { field: u32 } )*
499 }
500 }
501 ",
502 )
503 .expand_items("structs!(Foo, Bar);");
504 assert_eq!(
505 format!("{:#?}", tree).trim(),
506 r#"
507[email protected]
508 [email protected]
509 [email protected] "struct"
510 [email protected]
511 [email protected] "Foo"
512 [email protected]
513 [email protected] "{"
514 [email protected]
515 [email protected]
516 [email protected] "field"
517 [email protected] ":"
518 [email protected]
519 [email protected]
520 [email protected]
521 [email protected]
522 [email protected] "u32"
523 [email protected] "}"
524 [email protected]
525 [email protected] "struct"
526 [email protected]
527 [email protected] "Bar"
528 [email protected]
529 [email protected] "{"
530 [email protected]
531 [email protected]
532 [email protected] "field"
533 [email protected] ":"
534 [email protected]
535 [email protected]
536 [email protected]
537 [email protected]
538 [email protected] "u32"
539 [email protected] "}""#
540 .trim()
541 );
542}
543
544fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
545 if let tt::TokenTree::Subtree(subtree) = tt {
546 return &subtree;
547 }
548 unreachable!("It is not a subtree");
549}
550fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
551 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
552 return lit;
553 }
554 unreachable!("It is not a literal");
555}
556
557fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
558 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
559 return lit;
560 }
561 unreachable!("It is not a Punct");
562}
563
564#[test]
565fn test_expand_literals_to_token_tree() {
566 let expansion = parse_macro(
567 r#"
568 macro_rules! literals {
569 ($i:ident) => {
570 {
571 let a = 'c';
572 let c = 1000;
573 let f = 12E+99_f64;
574 let s = "rust1";
575 }
576 }
577 }
578 "#,
579 )
580 .expand_tt("literals!(foo);");
581 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
582
583 // [let] [a] [=] ['c'] [;]
584 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
585 // [let] [c] [=] [1000] [;]
586 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
587 // [let] [f] [=] [12E+99_f64] [;]
588 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
589 // [let] [s] [=] ["rust1"] [;]
590 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
591}
592
593#[test]
594fn test_attr_to_token_tree() {
595 let expansion = parse_to_token_tree_by_syntax(
596 r#"
597 #[derive(Copy)]
598 struct Foo;
599 "#,
600 );
601
602 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
603 assert_eq!(
604 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
605 Some(tt::DelimiterKind::Bracket)
606 );
607}
608
609#[test]
610fn test_two_idents() {
611 parse_macro(
612 r#"
613 macro_rules! foo {
614 ($ i:ident, $ j:ident) => {
615 fn foo() { let a = $ i; let b = $j; }
616 }
617 }
618"#,
619 )
620 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
621}
622
623#[test]
624fn test_tt_to_stmts() {
625 let stmts = parse_macro(
626 r#"
627 macro_rules! foo {
628 () => {
629 let a = 0;
630 a = 10 + 1;
631 a
632 }
633 }
634"#,
635 )
636 .expand_statements("foo!{}");
637
638 assert_eq!(
639 format!("{:#?}", stmts).trim(),
640 r#"[email protected]
641 [email protected]
642 [email protected] "let"
643 [email protected]
644 [email protected]
645 [email protected] "a"
646 [email protected] "="
647 [email protected]
648 [email protected] "0"
649 [email protected] ";"
650 [email protected]
651 [email protected]
652 [email protected]
653 [email protected]
654 [email protected]
655 [email protected]
656 [email protected] "a"
657 [email protected] "="
658 [email protected]
659 [email protected]
660 [email protected] "10"
661 [email protected] "+"
662 [email protected]
663 [email protected] "1"
664 [email protected] ";"
665 [email protected]
666 [email protected]
667 [email protected]
668 [email protected]
669 [email protected] "a""#,
670 );
671}
672
673#[test]
674fn test_match_literal() {
675 parse_macro(
676 r#"
677 macro_rules! foo {
678 ('(') => {
679 fn foo() {}
680 }
681 }
682"#,
683 )
684 .assert_expand_items("foo! ['('];", "fn foo () {}");
685}
686
687#[test]
688fn test_parse_macro_def_simple() {
689 cov_mark::check!(parse_macro_def_simple);
690
691 parse_macro2(
692 r#"
693macro foo($id:ident) {
694 fn $id() {}
695}
696"#,
697 )
698 .assert_expand_items("foo!(bar);", "fn bar () {}");
699}
700
701#[test]
702fn test_parse_macro_def_rules() {
703 cov_mark::check!(parse_macro_def_rules);
704
705 parse_macro2(
706 r#"
707macro foo {
708 ($id:ident) => {
709 fn $id() {}
710 }
711}
712"#,
713 )
714 .assert_expand_items("foo!(bar);", "fn bar () {}");
715}
716
717// The following tests are port from intellij-rust directly
718// https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
719
720#[test]
721fn test_path() {
722 parse_macro(
723 r#"
724 macro_rules! foo {
725 ($ i:path) => {
726 fn foo() { let a = $ i; }
727 }
728 }
729"#,
730 )
731 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
732 .assert_expand_items(
733 "foo! { bar::<u8>::baz::<u8> }",
734 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
735 );
736}
737
738#[test]
739fn test_two_paths() {
740 parse_macro(
741 r#"
742 macro_rules! foo {
743 ($ i:path, $ j:path) => {
744 fn foo() { let a = $ i; let b = $j; }
745 }
746 }
747"#,
748 )
749 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
750}
751
752#[test]
753fn test_path_with_path() {
754 parse_macro(
755 r#"
756 macro_rules! foo {
757 ($ i:path) => {
758 fn foo() { let a = $ i :: bar; }
759 }
760 }
761"#,
762 )
763 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
764}
765
766#[test]
767fn test_expr() {
768 parse_macro(
769 r#"
770 macro_rules! foo {
771 ($ i:expr) => {
772 fn bar() { $ i; }
773 }
774 }
775"#,
776 )
777 .assert_expand_items(
778 "foo! { 2 + 2 * baz(3).quux() }",
779 "fn bar () {2 + 2 * baz (3) . quux () ;}",
780 );
781}
782
783#[test]
784fn test_last_expr() {
785 parse_macro(
786 r#"
787 macro_rules! vec {
788 ($($item:expr),*) => {
789 {
790 let mut v = Vec::new();
791 $(
792 v.push($item);
793 )*
794 v
795 }
796 };
797 }
798"#,
799 )
800 .assert_expand_items(
801 "vec!(1,2,3);",
802 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
803 );
804}
805
806#[test]
807fn test_expr_with_attr() {
808 parse_macro(
809 r#"
810macro_rules! m {
811 ($a:expr) => {0}
812}
813"#,
814 )
815 .assert_expand_items("m!(#[allow(a)]())", "0");
816}
817
818#[test]
819fn test_ty() {
820 parse_macro(
821 r#"
822 macro_rules! foo {
823 ($ i:ty) => (
824 fn bar() -> $ i { unimplemented!() }
825 )
826 }
827"#,
828 )
829 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
830}
831
832#[test]
833fn test_ty_with_complex_type() {
834 parse_macro(
835 r#"
836 macro_rules! foo {
837 ($ i:ty) => (
838 fn bar() -> $ i { unimplemented!() }
839 )
840 }
841"#,
842 )
843 // Reference lifetime struct with generic type
844 .assert_expand_items(
845 "foo! { &'a Baz<u8> }",
846 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
847 )
848 // extern "Rust" func type
849 .assert_expand_items(
850 r#"foo! { extern "Rust" fn() -> Ret }"#,
851 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
852 );
853}
854
855#[test]
856fn test_pat_() {
857 parse_macro(
858 r#"
859 macro_rules! foo {
860 ($ i:pat) => { fn foo() { let $ i; } }
861 }
862"#,
863 )
864 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
865}
866
867#[test]
868fn test_stmt() {
869 parse_macro(
870 r#"
871 macro_rules! foo {
872 ($ i:stmt) => (
873 fn bar() { $ i; }
874 )
875 }
876"#,
877 )
878 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
879 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
880}
881
882#[test]
883fn test_single_item() {
884 parse_macro(
885 r#"
886 macro_rules! foo {
887 ($ i:item) => (
888 $ i
889 )
890 }
891"#,
892 )
893 .assert_expand_items("foo! {mod c {}}", "mod c {}");
894}
895
896#[test]
897fn test_all_items() {
898 parse_macro(
899 r#"
900 macro_rules! foo {
901 ($ ($ i:item)*) => ($ (
902 $ i
903 )*)
904 }
905"#,
906 ).
907 assert_expand_items(
908 r#"
909 foo! {
910 extern crate a;
911 mod b;
912 mod c {}
913 use d;
914 const E: i32 = 0;
915 static F: i32 = 0;
916 impl G {}
917 struct H;
918 enum I { Foo }
919 trait J {}
920 fn h() {}
921 extern {}
922 type T = u8;
923 }
924"#,
925 r#"extern crate a ; mod b ; mod c {} use d ; const E : i32 = 0 ; static F : i32 = 0 ; impl G {} struct H ; enum I {Foo} trait J {} fn h () {} extern {} type T = u8 ;"#,
926 );
927}
928
929#[test]
930fn test_block() {
931 parse_macro(
932 r#"
933 macro_rules! foo {
934 ($ i:block) => { fn foo() $ i }
935 }
936"#,
937 )
938 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
939}
940
941#[test]
942fn test_meta() {
943 parse_macro(
944 r#"
945 macro_rules! foo {
946 ($ i:meta) => (
947 #[$ i]
948 fn bar() {}
949 )
950 }
951"#,
952 )
953 .assert_expand_items(
954 r#"foo! { cfg(target_os = "windows") }"#,
955 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
956 )
957 .assert_expand_items(r#"foo! { hello::world }"#, r#"# [hello :: world] fn bar () {}"#);
958}
959
960#[test]
961fn test_meta_doc_comments() {
962 parse_macro(
963 r#"
964 macro_rules! foo {
965 ($(#[$ i:meta])+) => (
966 $(#[$ i])+
967 fn bar() {}
968 )
969 }
970"#,
971 ).
972 assert_expand_items(
973 r#"foo! {
974 /// Single Line Doc 1
975 /**
976 MultiLines Doc
977 */
978 }"#,
979 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
980 );
981}
982
983#[test]
984fn test_meta_doc_comments_non_latin() {
985 parse_macro(
986 r#"
987 macro_rules! foo {
988 ($(#[$ i:meta])+) => (
989 $(#[$ i])+
990 fn bar() {}
991 )
992 }
993"#,
994 ).
995 assert_expand_items(
996 r#"foo! {
997 /// 錦瑟無端五十弦,一弦一柱思華年。
998 /**
999 莊生曉夢迷蝴蝶,望帝春心託杜鵑。
1000 */
1001 }"#,
1002 "# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\\\n \"] fn bar () {}",
1003 );
1004}
1005
1006#[test]
1007fn test_tt_block() {
1008 parse_macro(
1009 r#"
1010 macro_rules! foo {
1011 ($ i:tt) => { fn foo() $ i }
1012 }
1013 "#,
1014 )
1015 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
1016}
1017
1018#[test]
1019fn test_tt_group() {
1020 parse_macro(
1021 r#"
1022 macro_rules! foo {
1023 ($($ i:tt)*) => { $($ i)* }
1024 }
1025 "#,
1026 )
1027 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
1028}
1029
1030#[test]
1031fn test_tt_composite() {
1032 parse_macro(
1033 r#"
1034 macro_rules! foo {
1035 ($i:tt) => { 0 }
1036 }
1037 "#,
1038 )
1039 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1040}
1041
1042#[test]
1043fn test_tt_composite2() {
1044 let node = parse_macro(
1045 r#"
1046 macro_rules! foo {
1047 ($($tt:tt)*) => { abs!(=> $($tt)*) }
1048 }
1049 "#,
1050 )
1051 .expand_items(r#"foo!{#}"#);
1052
1053 let res = format!("{:#?}", &node);
1054 assert_eq_text!(
1055 r###"[email protected]
1056 [email protected]
1057 [email protected]
1058 [email protected]
1059 [email protected]
1060 [email protected] "abs"
1061 [email protected] "!"
1062 [email protected]
1063 [email protected] "("
1064 [email protected] "="
1065 [email protected] ">"
1066 [email protected] " "
1067 [email protected] "#"
1068 [email protected] ")""###,
1069 res.trim()
1070 );
1071}
1072
1073#[test]
1074fn test_tt_with_composite_without_space() {
1075 parse_macro(
1076 r#"
1077 macro_rules! foo {
1078 ($ op:tt, $j:path) => (
1079 0
1080 )
1081 }
1082"#,
1083 )
1084 // Test macro input without any spaces
1085 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
1086 .assert_expand_items("foo!(==,Foo::Bool)", "0");
1087}
1088
1089#[test]
1090fn test_underscore() {
1091 parse_macro(
1092 r#"
1093 macro_rules! foo {
1094 ($_:tt) => { 0 }
1095 }
1096 "#,
1097 )
1098 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1099}
1100
1101#[test]
1102fn test_underscore_not_greedily() {
1103 parse_macro(
1104 r#"
1105macro_rules! q {
1106 ($($a:ident)* _) => {0};
1107}
1108"#,
1109 )
1110 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
1111 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
1112
1113 parse_macro(
1114 r#"
1115macro_rules! q {
1116 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
1117}
1118"#,
1119 )
1120 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
1121 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
1122}
1123
1124#[test]
1125fn test_underscore_as_type() {
1126 parse_macro(
1127 r#"
1128macro_rules! q {
1129 ($a:ty) => {0};
1130}
1131"#,
1132 )
1133 // Underscore is a type
1134 .assert_expand_items(r#"q![_]"#, r#"0"#);
1135}
1136
1137#[test]
1138fn test_vertical_bar_with_pat() {
1139 parse_macro(
1140 r#"
1141 macro_rules! foo {
1142 (| $pat:pat | ) => { 0 }
1143 }
1144 "#,
1145 )
1146 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1147}
1148
1149#[test]
1150fn test_dollar_crate_lhs_is_not_meta() {
1151 parse_macro(
1152 r#"
1153macro_rules! foo {
1154 ($crate) => {};
1155 () => {0};
1156}
1157 "#,
1158 )
1159 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1160}
1161
1162#[test]
1163fn test_lifetime() {
1164 parse_macro(
1165 r#"
1166 macro_rules! foo {
1167 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1168 }
1169"#,
1170 )
1171 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1172}
1173
1174#[test]
1175fn test_literal() {
1176 parse_macro(
1177 r#"
1178 macro_rules! foo {
1179 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1180 }
1181"#,
1182 )
1183 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1184
1185 parse_macro(
1186 r#"
1187 macro_rules! foo {
1188 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1189 }
1190"#,
1191 )
1192 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1193}
1194
1195#[test]
1196fn test_boolean_is_ident() {
1197 parse_macro(
1198 r#"
1199 macro_rules! foo {
1200 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1201 }
1202"#,
1203 )
1204 .assert_expand(
1205 r#"foo!(true,false);"#,
1206 r#"
1207SUBTREE $
1208 IDENT const 14
1209 IDENT VALUE 15
1210 PUNCH : [alone] 16
1211 SUBTREE () 17
1212 IDENT bool 18
1213 PUNCH , [alone] 19
1214 IDENT bool 20
1215 PUNCH = [alone] 21
1216 SUBTREE () 22
1217 IDENT true 29
1218 PUNCH , [joint] 25
1219 IDENT false 31
1220 PUNCH ; [alone] 28
1221"#,
1222 );
1223}
1224
1225#[test]
1226fn test_vis() {
1227 parse_macro(
1228 r#"
1229 macro_rules! foo {
1230 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1231 }
1232"#,
1233 )
1234 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1235 // test optional cases
1236 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1237}
1238
1239#[test]
1240fn test_inner_macro_rules() {
1241 parse_macro(
1242 r#"
1243macro_rules! foo {
1244 ($a:ident, $b:ident, $c:tt) => {
1245
1246 macro_rules! bar {
1247 ($bi:ident) => {
1248 fn $bi() -> u8 {$c}
1249 }
1250 }
1251
1252 bar!($a);
1253 fn $b() -> u8 {$c}
1254 }
1255}
1256"#,
1257 ).
1258 assert_expand_items(
1259 r#"foo!(x,y, 1);"#,
1260 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1261 );
1262}
1263
1264#[test]
1265fn test_expr_after_path_colons() {
1266 assert!(parse_macro(
1267 r#"
1268macro_rules! m {
1269 ($k:expr) => {
1270 f(K::$k);
1271 }
1272}
1273"#,
1274 )
1275 .expand_statements(r#"m!(C("0"))"#)
1276 .descendants()
1277 .find(|token| token.kind() == ERROR)
1278 .is_some());
1279}
1280
1281#[test]
1282fn test_match_is_not_greedy() {
1283 parse_macro(
1284 r#"
1285macro_rules! foo {
1286 ($($i:ident $(,)*),*) => {};
1287}
1288"#,
1289 )
1290 .assert_expand_items(r#"foo!(a,b);"#, r#""#);
1291}
1292
1293// The following tests are based on real world situations
1294#[test]
1295fn test_vec() {
1296 let fixture = parse_macro(
1297 r#"
1298 macro_rules! vec {
1299 ($($item:expr),*) => {
1300 {
1301 let mut v = Vec::new();
1302 $(
1303 v.push($item);
1304 )*
1305 v
1306 }
1307 };
1308}
1309"#,
1310 );
1311 fixture
1312 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1313 .assert_expand_items(
1314 r#"vec![1u32,2];"#,
1315 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1316 );
1317
1318 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1319
1320 assert_eq!(
1321 format!("{:#?}", tree).trim(),
1322 r#"[email protected]
1323 [email protected] "{"
1324 [email protected]
1325 [email protected] "let"
1326 [email protected]
1327 [email protected] "mut"
1328 [email protected]
1329 [email protected] "v"
1330 [email protected] "="
1331 [email protected]
1332 [email protected]
1333 [email protected]
1334 [email protected]
1335 [email protected]
1336 [email protected]
1337 [email protected] "Vec"
1338 [email protected] "::"
1339 [email protected]
1340 [email protected]
1341 [email protected] "new"
1342 [email protected]
1343 [email protected] "("
1344 [email protected] ")"
1345 [email protected] ";"
1346 [email protected]
1347 [email protected]
1348 [email protected]
1349 [email protected]
1350 [email protected]
1351 [email protected]
1352 [email protected] "v"
1353 [email protected] "."
1354 [email protected]
1355 [email protected] "push"
1356 [email protected]
1357 [email protected] "("
1358 [email protected]
1359 [email protected] "1u32"
1360 [email protected] ")"
1361 [email protected] ";"
1362 [email protected]
1363 [email protected]
1364 [email protected]
1365 [email protected]
1366 [email protected]
1367 [email protected]
1368 [email protected] "v"
1369 [email protected] "."
1370 [email protected]
1371 [email protected] "push"
1372 [email protected]
1373 [email protected] "("
1374 [email protected]
1375 [email protected] "2"
1376 [email protected] ")"
1377 [email protected] ";"
1378 [email protected]
1379 [email protected]
1380 [email protected]
1381 [email protected]
1382 [email protected] "v"
1383 [email protected] "}""#
1384 );
1385}
1386
1387#[test]
1388fn test_winapi_struct() {
1389 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1390
1391 parse_macro(
1392 r#"
1393macro_rules! STRUCT {
1394 ($(#[$attrs:meta])* struct $name:ident {
1395 $($field:ident: $ftype:ty,)+
1396 }) => (
1397 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1398 pub struct $name {
1399 $(pub $field: $ftype,)+
1400 }
1401 impl Clone for $name {
1402 #[inline]
1403 fn clone(&self) -> $name { *self }
1404 }
1405 #[cfg(feature = "impl-default")]
1406 impl Default for $name {
1407 #[inline]
1408 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1409 }
1410 );
1411}
1412"#,
1413 ).
1414 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1415 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1416 "# [repr (C)] # [derive (Copy)] pub struct D3DVSHADERCAPS2_0 {pub Caps : u8 ,} impl Clone for D3DVSHADERCAPS2_0 {# [inline] fn clone (& self) -> D3DVSHADERCAPS2_0 {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DVSHADERCAPS2_0 {# [inline] fn default () -> D3DVSHADERCAPS2_0 {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1417 )
1418 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1419 "# [repr (C)] # [derive (Copy)] # [cfg_attr (target_arch = \"x86\" , repr (packed))] pub struct D3DCONTENTPROTECTIONCAPS {pub Caps : u8 ,} impl Clone for D3DCONTENTPROTECTIONCAPS {# [inline] fn clone (& self) -> D3DCONTENTPROTECTIONCAPS {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DCONTENTPROTECTIONCAPS {# [inline] fn default () -> D3DCONTENTPROTECTIONCAPS {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1420 );
1421}
1422
1423#[test]
1424fn test_int_base() {
1425 parse_macro(
1426 r#"
1427macro_rules! int_base {
1428 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl fmt::$Trait for $T {
1431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1432 $Radix.fmt_int(*self as $U, f)
1433 }
1434 }
1435 }
1436}
1437"#,
1438 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1439 "# [stable (feature = \"rust1\" , since = \"1.0.0\")] impl fmt ::Binary for isize {fn fmt (& self , f : & mut fmt :: Formatter < \'_ >) -> fmt :: Result {Binary . fmt_int (* self as usize , f)}}"
1440 );
1441}
1442
1443#[test]
1444fn test_generate_pattern_iterators() {
1445 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1446 parse_macro(
1447 r#"
1448macro_rules! generate_pattern_iterators {
1449 { double ended; with $(#[$common_stability_attribute:meta])*,
1450 $forward_iterator:ident,
1451 $reverse_iterator:ident, $iterty:ty
1452 } => {
1453 fn foo(){}
1454 }
1455}
1456"#,
1457 ).assert_expand_items(
1458 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1459 "fn foo () {}",
1460 );
1461}
1462
1463#[test]
1464fn test_impl_fn_for_zst() {
1465 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1466 parse_macro(
1467 r#"
1468macro_rules! impl_fn_for_zst {
1469 { $( $( #[$attr: meta] )*
1470 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1471 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1472$body: block; )+
1473 } => {
1474 $(
1475 $( #[$attr] )*
1476 struct $Name;
1477
1478 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1479 #[inline]
1480 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1481 $body
1482 }
1483 }
1484
1485 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1486 #[inline]
1487 extern "rust-call" fn call_mut(
1488 &mut self,
1489 ($( $arg, )*): ($( $ArgTy, )*)
1490 ) -> $ReturnTy {
1491 Fn::call(&*self, ($( $arg, )*))
1492 }
1493 }
1494
1495 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1496 type Output = $ReturnTy;
1497
1498 #[inline]
1499 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1500 Fn::call(&self, ($( $arg, )*))
1501 }
1502 }
1503 )+
1504}
1505 }
1506"#,
1507 ).assert_expand_items(r#"
1508impl_fn_for_zst ! {
1509 # [ derive ( Clone ) ]
1510 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1511 c . escape_debug_ext ( false )
1512 } ;
1513
1514 # [ derive ( Clone ) ]
1515 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1516 c . escape_unicode ( )
1517 } ;
1518 # [ derive ( Clone ) ]
1519 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1520 c . escape_default ( )
1521 } ;
1522 }
1523"#,
1524 "# [derive (Clone)] struct CharEscapeDebugContinue ; impl Fn < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDebug {{c . escape_debug_ext (false)}}} impl FnMut < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDebugContinue {type Output = char :: EscapeDebug ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeUnicode ; impl Fn < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeUnicode {{c . escape_unicode ()}}} impl FnMut < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeUnicode {type Output = char :: EscapeUnicode ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeDefault ; impl Fn < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDefault {{c . escape_default ()}}} impl FnMut < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDefault {type Output = char :: EscapeDefault ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (& self , (c ,))}}"
1525 );
1526}
1527
1528#[test]
1529fn test_impl_nonzero_fmt() {
1530 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1531 parse_macro(
1532 r#"
1533 macro_rules! impl_nonzero_fmt {
1534 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1535 fn foo () {}
1536 }
1537 }
1538"#,
1539 ).assert_expand_items(
1540 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1541 "fn foo () {}",
1542 );
1543}
1544
1545#[test]
1546fn test_cfg_if_items() {
1547 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1548 parse_macro(
1549 r#"
1550 macro_rules! __cfg_if_items {
1551 (($($not:meta,)*) ; ) => {};
1552 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1553 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1554 }
1555 }
1556"#,
1557 ).assert_expand_items(
1558 r#"__cfg_if_items ! { ( rustdoc , ) ; ( ( ) ( # [ cfg ( any ( target_os = "redox" , unix ) ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as unix ; # [ cfg ( windows ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as windows ; # [ cfg ( any ( target_os = "linux" , target_os = "l4re" ) ) ] pub mod linux ; ) ) , }"#,
1559 "__cfg_if_items ! {(rustdoc ,) ;}",
1560 );
1561}
1562
1563#[test]
1564fn test_cfg_if_main() {
1565 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1566 parse_macro(
1567 r#"
1568 macro_rules! cfg_if {
1569 ($(
1570 if #[cfg($($meta:meta),*)] { $($it:item)* }
1571 ) else * else {
1572 $($it2:item)*
1573 }) => {
1574 __cfg_if_items! {
1575 () ;
1576 $( ( ($($meta),*) ($($it)*) ), )*
1577 ( () ($($it2)*) ),
1578 }
1579 };
1580
1581 // Internal macro to Apply a cfg attribute to a list of items
1582 (@__apply $m:meta, $($it:item)*) => {
1583 $(#[$m] $it)*
1584 };
1585 }
1586"#,
1587 ).assert_expand_items(r#"
1588cfg_if ! {
1589 if # [ cfg ( target_env = "msvc" ) ] {
1590 // no extra unwinder support needed
1591 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1592 // no unwinder on the system!
1593 } else {
1594 mod libunwind ;
1595 pub use libunwind :: * ;
1596 }
1597 }
1598"#,
1599 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1600 ).assert_expand_items(
1601 r#"
1602cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1603"#,
1604 "",
1605 );
1606}
1607
1608#[test]
1609fn test_proptest_arbitrary() {
1610 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1611 parse_macro(
1612 r#"
1613macro_rules! arbitrary {
1614 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1615 $args: ident => $logic: expr) => {
1616 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1617 type Parameters = $params;
1618 type Strategy = $strat;
1619 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1620 $logic
1621 }
1622 }
1623 };
1624
1625}"#,
1626 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1627 Vec < A > ,
1628 VecStrategy < A :: Strategy > ,
1629 RangedParams1 < A :: Parameters > ;
1630 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1631 ) ;"#,
1632 "impl <A : Arbitrary > $crate :: arbitrary :: Arbitrary for Vec < A > {type Parameters = RangedParams1 < A :: Parameters > ; type Strategy = VecStrategy < A :: Strategy > ; fn arbitrary_with (args : Self :: Parameters) -> Self :: Strategy {{let product_unpack ! [range , a] = args ; vec (any_with :: < A > (a) , range)}}}"
1633 );
1634}
1635
1636#[test]
1637fn test_old_ridl() {
1638 // This is from winapi 2.8, which do not have a link from github
1639 //
1640 let expanded = parse_macro(
1641 r#"
1642#[macro_export]
1643macro_rules! RIDL {
1644 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1645 {$(
1646 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1647 ),+}
1648 ) => {
1649 impl $interface {
1650 $(pub unsafe fn $method(&mut self) -> $rtr {
1651 ((*self.lpVtbl).$method)(self $(,$p)*)
1652 })+
1653 }
1654 };
1655}"#,
1656 ).expand_tt(r#"
1657 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1658 fn GetDataSize(&mut self) -> UINT
1659 }}"#);
1660
1661 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1662}
1663
1664#[test]
1665fn test_quick_error() {
1666 let expanded = parse_macro(
1667 r#"
1668macro_rules! quick_error {
1669
1670 (SORT [enum $name:ident $( #[$meta:meta] )*]
1671 items [$($( #[$imeta:meta] )*
1672 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1673 {$( $ifuncs:tt )*} )* ]
1674 buf [ ]
1675 queue [ ]
1676 ) => {
1677 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1678 body []
1679 queue [$(
1680 $( #[$imeta] )*
1681 =>
1682 $iitem: $imode [$( $ivar: $ityp ),*]
1683 )*]
1684 );
1685};
1686
1687}
1688"#,
1689 )
1690 .expand_tt(
1691 r#"
1692quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1693 => One : UNIT [] {}
1694 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1695 ] buf [] queue []) ;
1696"#,
1697 );
1698
1699 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1700}
1701
1702#[test]
1703fn test_empty_repeat_vars_in_empty_repeat_vars() {
1704 parse_macro(
1705 r#"
1706macro_rules! delegate_impl {
1707 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1708 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1709
1710 // "Escaped" associated types. Stripped before making the `trait`
1711 // itself, but forwarded when delegating impls.
1712 $(
1713 @escape [type $assoc_name_ext:ident]
1714 // Associated types. Forwarded.
1715 )*
1716 $(
1717 @section type
1718 $(
1719 $(#[$_assoc_attr:meta])*
1720 type $assoc_name:ident $(: $assoc_bound:ty)*;
1721 )+
1722 )*
1723 // Methods. Forwarded. Using $self_map!(self) around the self argument.
1724 // Methods must use receiver `self` or explicit type like `self: &Self`
1725 // &self and &mut self are _not_ supported.
1726 $(
1727 @section self
1728 $(
1729 $(#[$_method_attr:meta])*
1730 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1731 )+
1732 )*
1733 // Arbitrary tail that is ignored when forwarding.
1734 $(
1735 @section nodelegate
1736 $($tail:tt)*
1737 )*
1738 }) => {
1739 impl<> $name for $self_wrap where $self_type: $name {
1740 $(
1741 $(
1742 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1743 $self_map!(self).$method_name($($marg),*)
1744 }
1745 )*
1746 )*
1747 }
1748 }
1749}
1750"#,
1751 ).assert_expand_items(
1752 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1753 "impl <> Data for & \'a mut G where G : Data {}",
1754 );
1755}
1756
1757#[test]
1758fn expr_interpolation() {
1759 let expanded = parse_macro(
1760 r#"
1761 macro_rules! id {
1762 ($expr:expr) => {
1763 map($expr)
1764 }
1765 }
1766 "#,
1767 )
1768 .expand_expr("id!(x + foo);");
1769
1770 assert_eq!(expanded.to_string(), "map(x+foo)");
1771}
1772
1773pub(crate) struct MacroFixture { 12pub(crate) struct MacroFixture {
1774 rules: MacroRules, 13 rules: MacroRules,
1775} 14}
@@ -1889,6 +128,37 @@ macro_rules! impl_fixture {
1889impl_fixture!(MacroFixture); 128impl_fixture!(MacroFixture);
1890impl_fixture!(MacroFixture2); 129impl_fixture!(MacroFixture2);
1891 130
131pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
132 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
133 let rules = MacroRules::parse(&definition_tt).unwrap();
134 MacroFixture { rules }
135}
136
137pub(crate) fn parse_macro2(ra_fixture: &str) -> MacroFixture2 {
138 let definition_tt = parse_macro_def_to_tt(ra_fixture);
139 let rules = MacroDef::parse(&definition_tt).unwrap();
140 MacroFixture2 { rules }
141}
142
143pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
144 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
145
146 match MacroRules::parse(&definition_tt) {
147 Ok(_) => panic!("Expect error"),
148 Err(err) => err,
149 }
150}
151
152pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
153 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
154 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
155
156 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
157 assert_eq!(tt, parsed);
158
159 parsed
160}
161
1892fn parse_macro_rules_to_tt(ra_fixture: &str) -> tt::Subtree { 162fn parse_macro_rules_to_tt(ra_fixture: &str) -> tt::Subtree {
1893 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap(); 163 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1894 let macro_definition = 164 let macro_definition =
@@ -1922,37 +192,6 @@ fn parse_macro_def_to_tt(ra_fixture: &str) -> tt::Subtree {
1922 definition_tt 192 definition_tt
1923} 193}
1924 194
1925pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
1926 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1927 let rules = MacroRules::parse(&definition_tt).unwrap();
1928 MacroFixture { rules }
1929}
1930
1931pub(crate) fn parse_macro2(ra_fixture: &str) -> MacroFixture2 {
1932 let definition_tt = parse_macro_def_to_tt(ra_fixture);
1933 let rules = MacroDef::parse(&definition_tt).unwrap();
1934 MacroFixture2 { rules }
1935}
1936
1937pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
1938 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1939
1940 match MacroRules::parse(&definition_tt) {
1941 Ok(_) => panic!("Expect error"),
1942 Err(err) => err,
1943 }
1944}
1945
1946pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
1947 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1948 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
1949
1950 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
1951 assert_eq!(tt, parsed);
1952
1953 parsed
1954}
1955
1956fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String { 195fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String {
1957 let mut level = 0; 196 let mut level = 0;
1958 let mut buf = String::new(); 197 let mut buf = String::new();
@@ -1988,166 +227,3 @@ fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String {
1988 227
1989 buf 228 buf
1990} 229}
1991
1992#[test]
1993fn test_issue_2520() {
1994 let macro_fixture = parse_macro(
1995 r#"
1996 macro_rules! my_macro {
1997 {
1998 ( $(
1999 $( [] $sname:ident : $stype:ty )?
2000 $( [$expr:expr] $nname:ident : $ntype:ty )?
2001 ),* )
2002 } => {
2003 Test {
2004 $(
2005 $( $sname, )?
2006 )*
2007 }
2008 };
2009 }
2010 "#,
2011 );
2012
2013 macro_fixture.assert_expand_items(
2014 r#"my_macro ! {
2015 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
2016 }"#,
2017 "Test {p1 , k0 ,}",
2018 );
2019}
2020
2021#[test]
2022fn test_issue_3861() {
2023 let macro_fixture = parse_macro(
2024 r#"
2025 macro_rules! rgb_color {
2026 ($p:expr, $t: ty) => {
2027 pub fn new() {
2028 let _ = 0 as $t << $p;
2029 }
2030 };
2031 }
2032 "#,
2033 );
2034
2035 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
2036}
2037
2038#[test]
2039fn test_repeat_bad_var() {
2040 // FIXME: the second rule of the macro should be removed and an error about
2041 // `$( $c )+` raised
2042 parse_macro(
2043 r#"
2044 macro_rules! foo {
2045 ($( $b:ident )+) => {
2046 $( $c )+
2047 };
2048 ($( $b:ident )+) => {
2049 $( $b )+
2050 }
2051 }
2052 "#,
2053 )
2054 .assert_expand_items("foo!(b0 b1);", "b0 b1");
2055}
2056
2057#[test]
2058fn test_no_space_after_semi_colon() {
2059 let expanded = parse_macro(
2060 r#"
2061 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
2062 "#,
2063 )
2064 .expand_items(r#"with_std! {mod m;mod f;}"#);
2065
2066 let dump = format!("{:#?}", expanded);
2067 assert_eq_text!(
2068 r###"[email protected]
2069 [email protected]
2070 [email protected]
2071 [email protected] "#"
2072 [email protected] "["
2073 [email protected]
2074 [email protected]
2075 [email protected]
2076 [email protected] "cfg"
2077 [email protected]
2078 [email protected] "("
2079 [email protected] "feature"
2080 [email protected] "="
2081 [email protected] "\"std\""
2082 [email protected] ")"
2083 [email protected] "]"
2084 [email protected] "mod"
2085 [email protected]
2086 [email protected] "m"
2087 [email protected] ";"
2088 [email protected]
2089 [email protected]
2090 [email protected] "#"
2091 [email protected] "["
2092 [email protected]
2093 [email protected]
2094 [email protected]
2095 [email protected] "cfg"
2096 [email protected]
2097 [email protected] "("
2098 [email protected] "feature"
2099 [email protected] "="
2100 [email protected] "\"std\""
2101 [email protected] ")"
2102 [email protected] "]"
2103 [email protected] "mod"
2104 [email protected]
2105 [email protected] "f"
2106 [email protected] ";""###,
2107 dump.trim()
2108 );
2109}
2110
2111// https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
2112#[test]
2113fn test_rustc_issue_57597() {
2114 fn test_error(fixture: &str) {
2115 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
2116 }
2117
2118 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
2119 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
2120 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
2121 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
2122 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
2123 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
2124 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
2125 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
2126 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
2127 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
2128 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
2129 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
2130}
2131
2132#[test]
2133fn test_expand_bad_literal() {
2134 parse_macro(
2135 r#"
2136 macro_rules! foo { ($i:literal) => {}; }
2137 "#,
2138 )
2139 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
2140}
2141
2142#[test]
2143fn test_empty_comments() {
2144 parse_macro(
2145 r#"
2146 macro_rules! one_arg_macro { ($fmt:expr) => (); }
2147 "#,
2148 )
2149 .assert_expand_err(
2150 r#"one_arg_macro!(/**/)"#,
2151 &ExpandError::BindingError("expected Expr".into()),
2152 );
2153}
diff --git a/crates/mbe/src/tests/expand.rs b/crates/mbe/src/tests/expand.rs
new file mode 100644
index 000000000..9dd8ff75b
--- /dev/null
+++ b/crates/mbe/src/tests/expand.rs
@@ -0,0 +1,1872 @@
1use ::parser::FragmentKind;
2use syntax::{
3 SyntaxKind::{ERROR, IDENT},
4 T,
5};
6use test_utils::assert_eq_text;
7
8use super::*;
9
10// Good first issue (although a slightly challenging one):
11//
12// * Pick a random test from here
13// https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
14// * Port the test to rust and add it to this module
15// * Make it pass :-)
16
17#[test]
18fn test_token_id_shift() {
19 let expansion = parse_macro(
20 r#"
21macro_rules! foobar {
22 ($e:ident) => { foo bar $e }
23}
24"#,
25 )
26 .expand_tt("foobar!(baz);");
27
28 fn get_id(t: &tt::TokenTree) -> Option<u32> {
29 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
30 return Some(ident.id.0);
31 }
32 None
33 }
34
35 assert_eq!(expansion.token_trees.len(), 3);
36 // {($e:ident) => { foo bar $e }}
37 // 012345 67 8 9 T 12
38 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
39 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
40
41 // The input args of macro call include parentheses:
42 // (baz)
43 // So baz should be 12+1+1
44 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
45}
46
47#[test]
48fn test_token_map() {
49 let expanded = parse_macro(
50 r#"
51macro_rules! foobar {
52 ($e:ident) => { fn $e() {} }
53}
54"#,
55 )
56 .expand_tt("foobar!(baz);");
57
58 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
59 let content = node.syntax_node().to_string();
60
61 let get_text = |id, kind| -> String {
62 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
63 };
64
65 assert_eq!(expanded.token_trees.len(), 4);
66 // {($e:ident) => { fn $e() {} }}
67 // 012345 67 8 9 T12 3
68
69 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
70 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
71 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
72}
73
74#[test]
75fn test_convert_tt() {
76 parse_macro(r#"
77macro_rules! impl_froms {
78 ($e:ident: $($v:ident),*) => {
79 $(
80 impl From<$v> for $e {
81 fn from(it: $v) -> $e {
82 $e::$v(it)
83 }
84 }
85 )*
86 }
87}
88"#)
89 .assert_expand_tt(
90 "impl_froms!(TokenTree: Leaf, Subtree);",
91 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
92 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
93 );
94}
95
96#[test]
97fn test_convert_tt2() {
98 parse_macro(
99 r#"
100macro_rules! impl_froms {
101 ($e:ident: $($v:ident),*) => {
102 $(
103 impl From<$v> for $e {
104 fn from(it: $v) -> $e {
105 $e::$v(it)
106 }
107 }
108 )*
109 }
110}
111"#,
112 )
113 .assert_expand(
114 "impl_froms!(TokenTree: Leaf, Subtree);",
115 r#"
116SUBTREE $
117 IDENT impl 20
118 IDENT From 21
119 PUNCH < [joint] 22
120 IDENT Leaf 53
121 PUNCH > [alone] 25
122 IDENT for 26
123 IDENT TokenTree 51
124 SUBTREE {} 29
125 IDENT fn 30
126 IDENT from 31
127 SUBTREE () 32
128 IDENT it 33
129 PUNCH : [alone] 34
130 IDENT Leaf 53
131 PUNCH - [joint] 37
132 PUNCH > [alone] 38
133 IDENT TokenTree 51
134 SUBTREE {} 41
135 IDENT TokenTree 51
136 PUNCH : [joint] 44
137 PUNCH : [joint] 45
138 IDENT Leaf 53
139 SUBTREE () 48
140 IDENT it 49
141 IDENT impl 20
142 IDENT From 21
143 PUNCH < [joint] 22
144 IDENT Subtree 55
145 PUNCH > [alone] 25
146 IDENT for 26
147 IDENT TokenTree 51
148 SUBTREE {} 29
149 IDENT fn 30
150 IDENT from 31
151 SUBTREE () 32
152 IDENT it 33
153 PUNCH : [alone] 34
154 IDENT Subtree 55
155 PUNCH - [joint] 37
156 PUNCH > [alone] 38
157 IDENT TokenTree 51
158 SUBTREE {} 41
159 IDENT TokenTree 51
160 PUNCH : [joint] 44
161 PUNCH : [joint] 45
162 IDENT Subtree 55
163 SUBTREE () 48
164 IDENT it 49
165"#,
166 );
167}
168
169#[test]
170fn test_lifetime_split() {
171 parse_macro(
172 r#"
173macro_rules! foo {
174 ($($t:tt)*) => { $($t)*}
175}
176"#,
177 )
178 .assert_expand(
179 r#"foo!(static bar: &'static str = "hello";);"#,
180 r#"
181SUBTREE $
182 IDENT static 17
183 IDENT bar 18
184 PUNCH : [alone] 19
185 PUNCH & [alone] 20
186 PUNCH ' [joint] 21
187 IDENT static 22
188 IDENT str 23
189 PUNCH = [alone] 24
190 LITERAL "hello" 25
191 PUNCH ; [joint] 26
192"#,
193 );
194}
195
196#[test]
197fn test_expr_order() {
198 let expanded = parse_macro(
199 r#"
200 macro_rules! foo {
201 ($ i:expr) => {
202 fn bar() { $ i * 2; }
203 }
204 }
205"#,
206 )
207 .expand_items("foo! { 1 + 1}");
208
209 let dump = format!("{:#?}", expanded);
210 assert_eq_text!(
211 r#"[email protected]
212 [email protected]
213 [email protected] "fn"
214 [email protected]
215 [email protected] "bar"
216 [email protected]
217 [email protected] "("
218 [email protected] ")"
219 [email protected]
220 [email protected] "{"
221 [email protected]
222 [email protected]
223 [email protected]
224 [email protected]
225 [email protected] "1"
226 [email protected] "+"
227 [email protected]
228 [email protected] "1"
229 [email protected] "*"
230 [email protected]
231 [email protected] "2"
232 [email protected] ";"
233 [email protected] "}""#,
234 dump.trim()
235 );
236}
237
238#[test]
239fn test_fail_match_pattern_by_first_token() {
240 parse_macro(
241 r#"
242 macro_rules! foo {
243 ($ i:ident) => (
244 mod $ i {}
245 );
246 (= $ i:ident) => (
247 fn $ i() {}
248 );
249 (+ $ i:ident) => (
250 struct $ i;
251 )
252 }
253"#,
254 )
255 .assert_expand_items("foo! { foo }", "mod foo {}")
256 .assert_expand_items("foo! { = bar }", "fn bar () {}")
257 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
258}
259
260#[test]
261fn test_fail_match_pattern_by_last_token() {
262 parse_macro(
263 r#"
264 macro_rules! foo {
265 ($ i:ident) => (
266 mod $ i {}
267 );
268 ($ i:ident =) => (
269 fn $ i() {}
270 );
271 ($ i:ident +) => (
272 struct $ i;
273 )
274 }
275"#,
276 )
277 .assert_expand_items("foo! { foo }", "mod foo {}")
278 .assert_expand_items("foo! { bar = }", "fn bar () {}")
279 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
280}
281
282#[test]
283fn test_fail_match_pattern_by_word_token() {
284 parse_macro(
285 r#"
286 macro_rules! foo {
287 ($ i:ident) => (
288 mod $ i {}
289 );
290 (spam $ i:ident) => (
291 fn $ i() {}
292 );
293 (eggs $ i:ident) => (
294 struct $ i;
295 )
296 }
297"#,
298 )
299 .assert_expand_items("foo! { foo }", "mod foo {}")
300 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
301 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
302}
303
304#[test]
305fn test_match_group_pattern_by_separator_token() {
306 parse_macro(
307 r#"
308 macro_rules! foo {
309 ($ ($ i:ident),*) => ($ (
310 mod $ i {}
311 )*);
312 ($ ($ i:ident)#*) => ($ (
313 fn $ i() {}
314 )*);
315 ($ i:ident ,# $ j:ident) => (
316 struct $ i;
317 struct $ j;
318 )
319 }
320"#,
321 )
322 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
323 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
324 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
325}
326
327#[test]
328fn test_match_group_pattern_with_multiple_defs() {
329 parse_macro(
330 r#"
331 macro_rules! foo {
332 ($ ($ i:ident),*) => ( struct Bar { $ (
333 fn $ i {}
334 )*} );
335 }
336"#,
337 )
338 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
339}
340
341#[test]
342fn test_match_group_pattern_with_multiple_statement() {
343 parse_macro(
344 r#"
345 macro_rules! foo {
346 ($ ($ i:ident),*) => ( fn baz { $ (
347 $ i ();
348 )*} );
349 }
350"#,
351 )
352 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
353}
354
355#[test]
356fn test_match_group_pattern_with_multiple_statement_without_semi() {
357 parse_macro(
358 r#"
359 macro_rules! foo {
360 ($ ($ i:ident),*) => ( fn baz { $ (
361 $i()
362 );*} );
363 }
364"#,
365 )
366 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
367}
368
369#[test]
370fn test_match_group_empty_fixed_token() {
371 parse_macro(
372 r#"
373 macro_rules! foo {
374 ($ ($ i:ident)* #abc) => ( fn baz { $ (
375 $ i ();
376 )*} );
377 }
378"#,
379 )
380 .assert_expand_items("foo! {#abc}", "fn baz {}");
381}
382
383#[test]
384fn test_match_group_in_subtree() {
385 parse_macro(
386 r#"
387 macro_rules! foo {
388 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
389 $ i ();
390 )*} );
391 }"#,
392 )
393 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
394}
395
396#[test]
397fn test_match_group_with_multichar_sep() {
398 parse_macro(
399 r#"
400 macro_rules! foo {
401 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
402 }"#,
403 )
404 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
405}
406
407#[test]
408fn test_match_group_with_multichar_sep2() {
409 parse_macro(
410 r#"
411 macro_rules! foo {
412 (fn $name:ident {$($i:literal)&&*} ) => ( fn $name() -> bool { $($i)&&*} );
413 }"#,
414 )
415 .assert_expand_items("foo! (fn baz {true && true} );", "fn baz () -> bool {true &&true}");
416}
417
418#[test]
419fn test_match_group_zero_match() {
420 parse_macro(
421 r#"
422 macro_rules! foo {
423 ( $($i:ident)* ) => ();
424 }"#,
425 )
426 .assert_expand_items("foo! ();", "");
427}
428
429#[test]
430fn test_match_group_in_group() {
431 parse_macro(
432 r#"
433 macro_rules! foo {
434 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
435 }"#,
436 )
437 .assert_expand_items("foo! ( (a b) );", "(a b)");
438}
439
440#[test]
441fn test_expand_to_item_list() {
442 let tree = parse_macro(
443 "
444 macro_rules! structs {
445 ($($i:ident),*) => {
446 $(struct $i { field: u32 } )*
447 }
448 }
449 ",
450 )
451 .expand_items("structs!(Foo, Bar);");
452 assert_eq!(
453 format!("{:#?}", tree).trim(),
454 r#"
455[email protected]
456 [email protected]
457 [email protected] "struct"
458 [email protected]
459 [email protected] "Foo"
460 [email protected]
461 [email protected] "{"
462 [email protected]
463 [email protected]
464 [email protected] "field"
465 [email protected] ":"
466 [email protected]
467 [email protected]
468 [email protected]
469 [email protected]
470 [email protected] "u32"
471 [email protected] "}"
472 [email protected]
473 [email protected] "struct"
474 [email protected]
475 [email protected] "Bar"
476 [email protected]
477 [email protected] "{"
478 [email protected]
479 [email protected]
480 [email protected] "field"
481 [email protected] ":"
482 [email protected]
483 [email protected]
484 [email protected]
485 [email protected]
486 [email protected] "u32"
487 [email protected] "}""#
488 .trim()
489 );
490}
491
492fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
493 if let tt::TokenTree::Subtree(subtree) = tt {
494 return &subtree;
495 }
496 unreachable!("It is not a subtree");
497}
498fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
499 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
500 return lit;
501 }
502 unreachable!("It is not a literal");
503}
504
505fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
506 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
507 return lit;
508 }
509 unreachable!("It is not a Punct");
510}
511
512#[test]
513fn test_expand_literals_to_token_tree() {
514 let expansion = parse_macro(
515 r#"
516 macro_rules! literals {
517 ($i:ident) => {
518 {
519 let a = 'c';
520 let c = 1000;
521 let f = 12E+99_f64;
522 let s = "rust1";
523 }
524 }
525 }
526 "#,
527 )
528 .expand_tt("literals!(foo);");
529 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
530
531 // [let] [a] [=] ['c'] [;]
532 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
533 // [let] [c] [=] [1000] [;]
534 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
535 // [let] [f] [=] [12E+99_f64] [;]
536 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
537 // [let] [s] [=] ["rust1"] [;]
538 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
539}
540
541#[test]
542fn test_attr_to_token_tree() {
543 let expansion = parse_to_token_tree_by_syntax(
544 r#"
545 #[derive(Copy)]
546 struct Foo;
547 "#,
548 );
549
550 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
551 assert_eq!(
552 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
553 Some(tt::DelimiterKind::Bracket)
554 );
555}
556
557#[test]
558fn test_two_idents() {
559 parse_macro(
560 r#"
561 macro_rules! foo {
562 ($ i:ident, $ j:ident) => {
563 fn foo() { let a = $ i; let b = $j; }
564 }
565 }
566"#,
567 )
568 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
569}
570
571#[test]
572fn test_tt_to_stmts() {
573 let stmts = parse_macro(
574 r#"
575 macro_rules! foo {
576 () => {
577 let a = 0;
578 a = 10 + 1;
579 a
580 }
581 }
582"#,
583 )
584 .expand_statements("foo!{}");
585
586 assert_eq!(
587 format!("{:#?}", stmts).trim(),
588 r#"[email protected]
589 [email protected]
590 [email protected] "let"
591 [email protected]
592 [email protected]
593 [email protected] "a"
594 [email protected] "="
595 [email protected]
596 [email protected] "0"
597 [email protected] ";"
598 [email protected]
599 [email protected]
600 [email protected]
601 [email protected]
602 [email protected]
603 [email protected]
604 [email protected] "a"
605 [email protected] "="
606 [email protected]
607 [email protected]
608 [email protected] "10"
609 [email protected] "+"
610 [email protected]
611 [email protected] "1"
612 [email protected] ";"
613 [email protected]
614 [email protected]
615 [email protected]
616 [email protected]
617 [email protected] "a""#,
618 );
619}
620
621#[test]
622fn test_match_literal() {
623 parse_macro(
624 r#"
625 macro_rules! foo {
626 ('(') => {
627 fn foo() {}
628 }
629 }
630"#,
631 )
632 .assert_expand_items("foo! ['('];", "fn foo () {}");
633}
634
635#[test]
636fn test_parse_macro_def_simple() {
637 cov_mark::check!(parse_macro_def_simple);
638
639 parse_macro2(
640 r#"
641macro foo($id:ident) {
642 fn $id() {}
643}
644"#,
645 )
646 .assert_expand_items("foo!(bar);", "fn bar () {}");
647}
648
649#[test]
650fn test_parse_macro_def_rules() {
651 cov_mark::check!(parse_macro_def_rules);
652
653 parse_macro2(
654 r#"
655macro foo {
656 ($id:ident) => {
657 fn $id() {}
658 }
659}
660"#,
661 )
662 .assert_expand_items("foo!(bar);", "fn bar () {}");
663}
664
665#[test]
666fn test_path() {
667 parse_macro(
668 r#"
669 macro_rules! foo {
670 ($ i:path) => {
671 fn foo() { let a = $ i; }
672 }
673 }
674"#,
675 )
676 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
677 .assert_expand_items(
678 "foo! { bar::<u8>::baz::<u8> }",
679 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
680 );
681}
682
683#[test]
684fn test_two_paths() {
685 parse_macro(
686 r#"
687 macro_rules! foo {
688 ($ i:path, $ j:path) => {
689 fn foo() { let a = $ i; let b = $j; }
690 }
691 }
692"#,
693 )
694 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
695}
696
697#[test]
698fn test_path_with_path() {
699 parse_macro(
700 r#"
701 macro_rules! foo {
702 ($ i:path) => {
703 fn foo() { let a = $ i :: bar; }
704 }
705 }
706"#,
707 )
708 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
709}
710
711#[test]
712fn test_expr() {
713 parse_macro(
714 r#"
715 macro_rules! foo {
716 ($ i:expr) => {
717 fn bar() { $ i; }
718 }
719 }
720"#,
721 )
722 .assert_expand_items(
723 "foo! { 2 + 2 * baz(3).quux() }",
724 "fn bar () {2 + 2 * baz (3) . quux () ;}",
725 );
726}
727
728#[test]
729fn test_last_expr() {
730 parse_macro(
731 r#"
732 macro_rules! vec {
733 ($($item:expr),*) => {
734 {
735 let mut v = Vec::new();
736 $(
737 v.push($item);
738 )*
739 v
740 }
741 };
742 }
743"#,
744 )
745 .assert_expand_items(
746 "vec!(1,2,3);",
747 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
748 );
749}
750
751#[test]
752fn test_expr_with_attr() {
753 parse_macro(
754 r#"
755macro_rules! m {
756 ($a:expr) => {0}
757}
758"#,
759 )
760 .assert_expand_items("m!(#[allow(a)]())", "0");
761}
762
763#[test]
764fn test_ty() {
765 parse_macro(
766 r#"
767 macro_rules! foo {
768 ($ i:ty) => (
769 fn bar() -> $ i { unimplemented!() }
770 )
771 }
772"#,
773 )
774 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
775}
776
777#[test]
778fn test_ty_with_complex_type() {
779 parse_macro(
780 r#"
781 macro_rules! foo {
782 ($ i:ty) => (
783 fn bar() -> $ i { unimplemented!() }
784 )
785 }
786"#,
787 )
788 // Reference lifetime struct with generic type
789 .assert_expand_items(
790 "foo! { &'a Baz<u8> }",
791 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
792 )
793 // extern "Rust" func type
794 .assert_expand_items(
795 r#"foo! { extern "Rust" fn() -> Ret }"#,
796 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
797 );
798}
799
800#[test]
801fn test_pat_() {
802 parse_macro(
803 r#"
804 macro_rules! foo {
805 ($ i:pat) => { fn foo() { let $ i; } }
806 }
807"#,
808 )
809 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
810}
811
812#[test]
813fn test_stmt() {
814 parse_macro(
815 r#"
816 macro_rules! foo {
817 ($ i:stmt) => (
818 fn bar() { $ i; }
819 )
820 }
821"#,
822 )
823 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
824 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
825}
826
827#[test]
828fn test_single_item() {
829 parse_macro(
830 r#"
831 macro_rules! foo {
832 ($ i:item) => (
833 $ i
834 )
835 }
836"#,
837 )
838 .assert_expand_items("foo! {mod c {}}", "mod c {}");
839}
840
841#[test]
842fn test_all_items() {
843 parse_macro(
844 r#"
845 macro_rules! foo {
846 ($ ($ i:item)*) => ($ (
847 $ i
848 )*)
849 }
850"#,
851 ).
852 assert_expand_items(
853 r#"
854 foo! {
855 extern crate a;
856 mod b;
857 mod c {}
858 use d;
859 const E: i32 = 0;
860 static F: i32 = 0;
861 impl G {}
862 struct H;
863 enum I { Foo }
864 trait J {}
865 fn h() {}
866 extern {}
867 type T = u8;
868 }
869"#,
870 r#"extern crate a ; mod b ; mod c {} use d ; const E : i32 = 0 ; static F : i32 = 0 ; impl G {} struct H ; enum I {Foo} trait J {} fn h () {} extern {} type T = u8 ;"#,
871 );
872}
873
874#[test]
875fn test_block() {
876 parse_macro(
877 r#"
878 macro_rules! foo {
879 ($ i:block) => { fn foo() $ i }
880 }
881"#,
882 )
883 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
884}
885
886#[test]
887fn test_meta() {
888 parse_macro(
889 r#"
890 macro_rules! foo {
891 ($ i:meta) => (
892 #[$ i]
893 fn bar() {}
894 )
895 }
896"#,
897 )
898 .assert_expand_items(
899 r#"foo! { cfg(target_os = "windows") }"#,
900 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
901 )
902 .assert_expand_items(r#"foo! { hello::world }"#, r#"# [hello :: world] fn bar () {}"#);
903}
904
905#[test]
906fn test_meta_doc_comments() {
907 parse_macro(
908 r#"
909 macro_rules! foo {
910 ($(#[$ i:meta])+) => (
911 $(#[$ i])+
912 fn bar() {}
913 )
914 }
915"#,
916 ).
917 assert_expand_items(
918 r#"foo! {
919 /// Single Line Doc 1
920 /**
921 MultiLines Doc
922 */
923 }"#,
924 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
925 );
926}
927
928#[test]
929fn test_meta_doc_comments_non_latin() {
930 parse_macro(
931 r#"
932 macro_rules! foo {
933 ($(#[$ i:meta])+) => (
934 $(#[$ i])+
935 fn bar() {}
936 )
937 }
938"#,
939 ).
940 assert_expand_items(
941 r#"foo! {
942 /// 錦瑟無端五十弦,一弦一柱思華年。
943 /**
944 莊生曉夢迷蝴蝶,望帝春心託杜鵑。
945 */
946 }"#,
947 "# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\\\n \"] fn bar () {}",
948 );
949}
950
951#[test]
952fn test_tt_block() {
953 parse_macro(
954 r#"
955 macro_rules! foo {
956 ($ i:tt) => { fn foo() $ i }
957 }
958 "#,
959 )
960 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
961}
962
963#[test]
964fn test_tt_group() {
965 parse_macro(
966 r#"
967 macro_rules! foo {
968 ($($ i:tt)*) => { $($ i)* }
969 }
970 "#,
971 )
972 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
973}
974
975#[test]
976fn test_tt_composite() {
977 parse_macro(
978 r#"
979 macro_rules! foo {
980 ($i:tt) => { 0 }
981 }
982 "#,
983 )
984 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
985}
986
987#[test]
988fn test_tt_composite2() {
989 let node = parse_macro(
990 r#"
991 macro_rules! foo {
992 ($($tt:tt)*) => { abs!(=> $($tt)*) }
993 }
994 "#,
995 )
996 .expand_items(r#"foo!{#}"#);
997
998 let res = format!("{:#?}", &node);
999 assert_eq_text!(
1000 r###"[email protected]
1001 [email protected]
1002 [email protected]
1003 [email protected]
1004 [email protected]
1005 [email protected] "abs"
1006 [email protected] "!"
1007 [email protected]
1008 [email protected] "("
1009 [email protected] "="
1010 [email protected] ">"
1011 [email protected] " "
1012 [email protected] "#"
1013 [email protected] ")""###,
1014 res.trim()
1015 );
1016}
1017
1018#[test]
1019fn test_tt_with_composite_without_space() {
1020 parse_macro(
1021 r#"
1022 macro_rules! foo {
1023 ($ op:tt, $j:path) => (
1024 0
1025 )
1026 }
1027"#,
1028 )
1029 // Test macro input without any spaces
1030 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
1031 .assert_expand_items("foo!(==,Foo::Bool)", "0");
1032}
1033
1034#[test]
1035fn test_underscore() {
1036 parse_macro(
1037 r#"
1038 macro_rules! foo {
1039 ($_:tt) => { 0 }
1040 }
1041 "#,
1042 )
1043 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1044}
1045
1046#[test]
1047fn test_underscore_not_greedily() {
1048 parse_macro(
1049 r#"
1050macro_rules! q {
1051 ($($a:ident)* _) => {0};
1052}
1053"#,
1054 )
1055 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
1056 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
1057
1058 parse_macro(
1059 r#"
1060macro_rules! q {
1061 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
1062}
1063"#,
1064 )
1065 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
1066 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
1067}
1068
1069#[test]
1070fn test_underscore_as_type() {
1071 parse_macro(
1072 r#"
1073macro_rules! q {
1074 ($a:ty) => {0};
1075}
1076"#,
1077 )
1078 // Underscore is a type
1079 .assert_expand_items(r#"q![_]"#, r#"0"#);
1080}
1081
1082#[test]
1083fn test_vertical_bar_with_pat() {
1084 parse_macro(
1085 r#"
1086 macro_rules! foo {
1087 (| $pat:pat | ) => { 0 }
1088 }
1089 "#,
1090 )
1091 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1092}
1093
1094#[test]
1095fn test_dollar_crate_lhs_is_not_meta() {
1096 parse_macro(
1097 r#"
1098macro_rules! foo {
1099 ($crate) => {};
1100 () => {0};
1101}
1102 "#,
1103 )
1104 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1105}
1106
1107#[test]
1108fn test_lifetime() {
1109 parse_macro(
1110 r#"
1111 macro_rules! foo {
1112 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1113 }
1114"#,
1115 )
1116 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1117}
1118
1119#[test]
1120fn test_literal() {
1121 parse_macro(
1122 r#"
1123 macro_rules! foo {
1124 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1125 }
1126"#,
1127 )
1128 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1129
1130 parse_macro(
1131 r#"
1132 macro_rules! foo {
1133 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1134 }
1135"#,
1136 )
1137 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1138}
1139
1140#[test]
1141fn test_boolean_is_ident() {
1142 parse_macro(
1143 r#"
1144 macro_rules! foo {
1145 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1146 }
1147"#,
1148 )
1149 .assert_expand(
1150 r#"foo!(true,false);"#,
1151 r#"
1152SUBTREE $
1153 IDENT const 14
1154 IDENT VALUE 15
1155 PUNCH : [alone] 16
1156 SUBTREE () 17
1157 IDENT bool 18
1158 PUNCH , [alone] 19
1159 IDENT bool 20
1160 PUNCH = [alone] 21
1161 SUBTREE () 22
1162 IDENT true 29
1163 PUNCH , [joint] 25
1164 IDENT false 31
1165 PUNCH ; [alone] 28
1166"#,
1167 );
1168}
1169
1170#[test]
1171fn test_vis() {
1172 parse_macro(
1173 r#"
1174 macro_rules! foo {
1175 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1176 }
1177"#,
1178 )
1179 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1180 // test optional cases
1181 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1182}
1183
1184#[test]
1185fn test_inner_macro_rules() {
1186 parse_macro(
1187 r#"
1188macro_rules! foo {
1189 ($a:ident, $b:ident, $c:tt) => {
1190
1191 macro_rules! bar {
1192 ($bi:ident) => {
1193 fn $bi() -> u8 {$c}
1194 }
1195 }
1196
1197 bar!($a);
1198 fn $b() -> u8 {$c}
1199 }
1200}
1201"#,
1202 ).
1203 assert_expand_items(
1204 r#"foo!(x,y, 1);"#,
1205 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1206 );
1207}
1208
1209#[test]
1210fn test_expr_after_path_colons() {
1211 assert!(parse_macro(
1212 r#"
1213macro_rules! m {
1214 ($k:expr) => {
1215 f(K::$k);
1216 }
1217}
1218"#,
1219 )
1220 .expand_statements(r#"m!(C("0"))"#)
1221 .descendants()
1222 .find(|token| token.kind() == ERROR)
1223 .is_some());
1224}
1225
1226#[test]
1227fn test_match_is_not_greedy() {
1228 parse_macro(
1229 r#"
1230macro_rules! foo {
1231 ($($i:ident $(,)*),*) => {};
1232}
1233"#,
1234 )
1235 .assert_expand_items(r#"foo!(a,b);"#, r#""#);
1236}
1237
1238// The following tests are based on real world situations
1239#[test]
1240fn test_vec() {
1241 let fixture = parse_macro(
1242 r#"
1243 macro_rules! vec {
1244 ($($item:expr),*) => {
1245 {
1246 let mut v = Vec::new();
1247 $(
1248 v.push($item);
1249 )*
1250 v
1251 }
1252 };
1253}
1254"#,
1255 );
1256 fixture
1257 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1258 .assert_expand_items(
1259 r#"vec![1u32,2];"#,
1260 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1261 );
1262
1263 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1264
1265 assert_eq!(
1266 format!("{:#?}", tree).trim(),
1267 r#"[email protected]
1268 [email protected] "{"
1269 [email protected]
1270 [email protected] "let"
1271 [email protected]
1272 [email protected] "mut"
1273 [email protected]
1274 [email protected] "v"
1275 [email protected] "="
1276 [email protected]
1277 [email protected]
1278 [email protected]
1279 [email protected]
1280 [email protected]
1281 [email protected]
1282 [email protected] "Vec"
1283 [email protected] "::"
1284 [email protected]
1285 [email protected]
1286 [email protected] "new"
1287 [email protected]
1288 [email protected] "("
1289 [email protected] ")"
1290 [email protected] ";"
1291 [email protected]
1292 [email protected]
1293 [email protected]
1294 [email protected]
1295 [email protected]
1296 [email protected]
1297 [email protected] "v"
1298 [email protected] "."
1299 [email protected]
1300 [email protected] "push"
1301 [email protected]
1302 [email protected] "("
1303 [email protected]
1304 [email protected] "1u32"
1305 [email protected] ")"
1306 [email protected] ";"
1307 [email protected]
1308 [email protected]
1309 [email protected]
1310 [email protected]
1311 [email protected]
1312 [email protected]
1313 [email protected] "v"
1314 [email protected] "."
1315 [email protected]
1316 [email protected] "push"
1317 [email protected]
1318 [email protected] "("
1319 [email protected]
1320 [email protected] "2"
1321 [email protected] ")"
1322 [email protected] ";"
1323 [email protected]
1324 [email protected]
1325 [email protected]
1326 [email protected]
1327 [email protected] "v"
1328 [email protected] "}""#
1329 );
1330}
1331
1332#[test]
1333fn test_winapi_struct() {
1334 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1335
1336 parse_macro(
1337 r#"
1338macro_rules! STRUCT {
1339 ($(#[$attrs:meta])* struct $name:ident {
1340 $($field:ident: $ftype:ty,)+
1341 }) => (
1342 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1343 pub struct $name {
1344 $(pub $field: $ftype,)+
1345 }
1346 impl Clone for $name {
1347 #[inline]
1348 fn clone(&self) -> $name { *self }
1349 }
1350 #[cfg(feature = "impl-default")]
1351 impl Default for $name {
1352 #[inline]
1353 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1354 }
1355 );
1356}
1357"#,
1358 ).
1359 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1360 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1361 "# [repr (C)] # [derive (Copy)] pub struct D3DVSHADERCAPS2_0 {pub Caps : u8 ,} impl Clone for D3DVSHADERCAPS2_0 {# [inline] fn clone (& self) -> D3DVSHADERCAPS2_0 {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DVSHADERCAPS2_0 {# [inline] fn default () -> D3DVSHADERCAPS2_0 {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1362 )
1363 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1364 "# [repr (C)] # [derive (Copy)] # [cfg_attr (target_arch = \"x86\" , repr (packed))] pub struct D3DCONTENTPROTECTIONCAPS {pub Caps : u8 ,} impl Clone for D3DCONTENTPROTECTIONCAPS {# [inline] fn clone (& self) -> D3DCONTENTPROTECTIONCAPS {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DCONTENTPROTECTIONCAPS {# [inline] fn default () -> D3DCONTENTPROTECTIONCAPS {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1365 );
1366}
1367
1368#[test]
1369fn test_int_base() {
1370 parse_macro(
1371 r#"
1372macro_rules! int_base {
1373 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl fmt::$Trait for $T {
1376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1377 $Radix.fmt_int(*self as $U, f)
1378 }
1379 }
1380 }
1381}
1382"#,
1383 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1384 "# [stable (feature = \"rust1\" , since = \"1.0.0\")] impl fmt ::Binary for isize {fn fmt (& self , f : & mut fmt :: Formatter < \'_ >) -> fmt :: Result {Binary . fmt_int (* self as usize , f)}}"
1385 );
1386}
1387
1388#[test]
1389fn test_generate_pattern_iterators() {
1390 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1391 parse_macro(
1392 r#"
1393macro_rules! generate_pattern_iterators {
1394 { double ended; with $(#[$common_stability_attribute:meta])*,
1395 $forward_iterator:ident,
1396 $reverse_iterator:ident, $iterty:ty
1397 } => {
1398 fn foo(){}
1399 }
1400}
1401"#,
1402 ).assert_expand_items(
1403 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1404 "fn foo () {}",
1405 );
1406}
1407
1408#[test]
1409fn test_impl_fn_for_zst() {
1410 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1411 parse_macro(
1412 r#"
1413macro_rules! impl_fn_for_zst {
1414 { $( $( #[$attr: meta] )*
1415 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1416 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1417$body: block; )+
1418 } => {
1419 $(
1420 $( #[$attr] )*
1421 struct $Name;
1422
1423 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1424 #[inline]
1425 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1426 $body
1427 }
1428 }
1429
1430 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1431 #[inline]
1432 extern "rust-call" fn call_mut(
1433 &mut self,
1434 ($( $arg, )*): ($( $ArgTy, )*)
1435 ) -> $ReturnTy {
1436 Fn::call(&*self, ($( $arg, )*))
1437 }
1438 }
1439
1440 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1441 type Output = $ReturnTy;
1442
1443 #[inline]
1444 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1445 Fn::call(&self, ($( $arg, )*))
1446 }
1447 }
1448 )+
1449}
1450 }
1451"#,
1452 ).assert_expand_items(r#"
1453impl_fn_for_zst ! {
1454 # [ derive ( Clone ) ]
1455 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1456 c . escape_debug_ext ( false )
1457 } ;
1458
1459 # [ derive ( Clone ) ]
1460 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1461 c . escape_unicode ( )
1462 } ;
1463 # [ derive ( Clone ) ]
1464 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1465 c . escape_default ( )
1466 } ;
1467 }
1468"#,
1469 "# [derive (Clone)] struct CharEscapeDebugContinue ; impl Fn < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDebug {{c . escape_debug_ext (false)}}} impl FnMut < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDebugContinue {type Output = char :: EscapeDebug ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeUnicode ; impl Fn < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeUnicode {{c . escape_unicode ()}}} impl FnMut < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeUnicode {type Output = char :: EscapeUnicode ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeDefault ; impl Fn < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDefault {{c . escape_default ()}}} impl FnMut < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDefault {type Output = char :: EscapeDefault ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (& self , (c ,))}}"
1470 );
1471}
1472
1473#[test]
1474fn test_impl_nonzero_fmt() {
1475 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1476 parse_macro(
1477 r#"
1478 macro_rules! impl_nonzero_fmt {
1479 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1480 fn foo () {}
1481 }
1482 }
1483"#,
1484 ).assert_expand_items(
1485 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1486 "fn foo () {}",
1487 );
1488}
1489
1490#[test]
1491fn test_cfg_if_items() {
1492 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1493 parse_macro(
1494 r#"
1495 macro_rules! __cfg_if_items {
1496 (($($not:meta,)*) ; ) => {};
1497 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1498 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1499 }
1500 }
1501"#,
1502 ).assert_expand_items(
1503 r#"__cfg_if_items ! { ( rustdoc , ) ; ( ( ) ( # [ cfg ( any ( target_os = "redox" , unix ) ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as unix ; # [ cfg ( windows ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as windows ; # [ cfg ( any ( target_os = "linux" , target_os = "l4re" ) ) ] pub mod linux ; ) ) , }"#,
1504 "__cfg_if_items ! {(rustdoc ,) ;}",
1505 );
1506}
1507
1508#[test]
1509fn test_cfg_if_main() {
1510 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1511 parse_macro(
1512 r#"
1513 macro_rules! cfg_if {
1514 ($(
1515 if #[cfg($($meta:meta),*)] { $($it:item)* }
1516 ) else * else {
1517 $($it2:item)*
1518 }) => {
1519 __cfg_if_items! {
1520 () ;
1521 $( ( ($($meta),*) ($($it)*) ), )*
1522 ( () ($($it2)*) ),
1523 }
1524 };
1525
1526 // Internal macro to Apply a cfg attribute to a list of items
1527 (@__apply $m:meta, $($it:item)*) => {
1528 $(#[$m] $it)*
1529 };
1530 }
1531"#,
1532 ).assert_expand_items(r#"
1533cfg_if ! {
1534 if # [ cfg ( target_env = "msvc" ) ] {
1535 // no extra unwinder support needed
1536 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1537 // no unwinder on the system!
1538 } else {
1539 mod libunwind ;
1540 pub use libunwind :: * ;
1541 }
1542 }
1543"#,
1544 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1545 ).assert_expand_items(
1546 r#"
1547cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1548"#,
1549 "",
1550 );
1551}
1552
1553#[test]
1554fn test_proptest_arbitrary() {
1555 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1556 parse_macro(
1557 r#"
1558macro_rules! arbitrary {
1559 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1560 $args: ident => $logic: expr) => {
1561 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1562 type Parameters = $params;
1563 type Strategy = $strat;
1564 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1565 $logic
1566 }
1567 }
1568 };
1569
1570}"#,
1571 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1572 Vec < A > ,
1573 VecStrategy < A :: Strategy > ,
1574 RangedParams1 < A :: Parameters > ;
1575 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1576 ) ;"#,
1577 "impl <A : Arbitrary > $crate :: arbitrary :: Arbitrary for Vec < A > {type Parameters = RangedParams1 < A :: Parameters > ; type Strategy = VecStrategy < A :: Strategy > ; fn arbitrary_with (args : Self :: Parameters) -> Self :: Strategy {{let product_unpack ! [range , a] = args ; vec (any_with :: < A > (a) , range)}}}"
1578 );
1579}
1580
1581#[test]
1582fn test_old_ridl() {
1583 // This is from winapi 2.8, which do not have a link from github
1584 //
1585 let expanded = parse_macro(
1586 r#"
1587#[macro_export]
1588macro_rules! RIDL {
1589 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1590 {$(
1591 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1592 ),+}
1593 ) => {
1594 impl $interface {
1595 $(pub unsafe fn $method(&mut self) -> $rtr {
1596 ((*self.lpVtbl).$method)(self $(,$p)*)
1597 })+
1598 }
1599 };
1600}"#,
1601 ).expand_tt(r#"
1602 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1603 fn GetDataSize(&mut self) -> UINT
1604 }}"#);
1605
1606 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1607}
1608
1609#[test]
1610fn test_quick_error() {
1611 let expanded = parse_macro(
1612 r#"
1613macro_rules! quick_error {
1614
1615 (SORT [enum $name:ident $( #[$meta:meta] )*]
1616 items [$($( #[$imeta:meta] )*
1617 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1618 {$( $ifuncs:tt )*} )* ]
1619 buf [ ]
1620 queue [ ]
1621 ) => {
1622 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1623 body []
1624 queue [$(
1625 $( #[$imeta] )*
1626 =>
1627 $iitem: $imode [$( $ivar: $ityp ),*]
1628 )*]
1629 );
1630};
1631
1632}
1633"#,
1634 )
1635 .expand_tt(
1636 r#"
1637quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1638 => One : UNIT [] {}
1639 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1640 ] buf [] queue []) ;
1641"#,
1642 );
1643
1644 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1645}
1646
1647#[test]
1648fn test_empty_repeat_vars_in_empty_repeat_vars() {
1649 parse_macro(
1650 r#"
1651macro_rules! delegate_impl {
1652 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1653 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1654
1655 $(
1656 @escape [type $assoc_name_ext:ident]
1657 )*
1658 $(
1659 @section type
1660 $(
1661 $(#[$_assoc_attr:meta])*
1662 type $assoc_name:ident $(: $assoc_bound:ty)*;
1663 )+
1664 )*
1665 $(
1666 @section self
1667 $(
1668 $(#[$_method_attr:meta])*
1669 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1670 )+
1671 )*
1672 $(
1673 @section nodelegate
1674 $($tail:tt)*
1675 )*
1676 }) => {
1677 impl<> $name for $self_wrap where $self_type: $name {
1678 $(
1679 $(
1680 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1681 $self_map!(self).$method_name($($marg),*)
1682 }
1683 )*
1684 )*
1685 }
1686 }
1687}
1688"#,
1689 ).assert_expand_items(
1690 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1691 "impl <> Data for & \'a mut G where G : Data {}",
1692 );
1693}
1694
1695#[test]
1696fn expr_interpolation() {
1697 let expanded = parse_macro(
1698 r#"
1699 macro_rules! id {
1700 ($expr:expr) => {
1701 map($expr)
1702 }
1703 }
1704 "#,
1705 )
1706 .expand_expr("id!(x + foo);");
1707
1708 assert_eq!(expanded.to_string(), "map(x+foo)");
1709}
1710
1711#[test]
1712fn test_issue_2520() {
1713 let macro_fixture = parse_macro(
1714 r#"
1715 macro_rules! my_macro {
1716 {
1717 ( $(
1718 $( [] $sname:ident : $stype:ty )?
1719 $( [$expr:expr] $nname:ident : $ntype:ty )?
1720 ),* )
1721 } => {
1722 Test {
1723 $(
1724 $( $sname, )?
1725 )*
1726 }
1727 };
1728 }
1729 "#,
1730 );
1731
1732 macro_fixture.assert_expand_items(
1733 r#"my_macro ! {
1734 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1735 }"#,
1736 "Test {p1 , k0 ,}",
1737 );
1738}
1739
1740#[test]
1741fn test_issue_3861() {
1742 let macro_fixture = parse_macro(
1743 r#"
1744 macro_rules! rgb_color {
1745 ($p:expr, $t: ty) => {
1746 pub fn new() {
1747 let _ = 0 as $t << $p;
1748 }
1749 };
1750 }
1751 "#,
1752 );
1753
1754 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1755}
1756
1757#[test]
1758fn test_repeat_bad_var() {
1759 // FIXME: the second rule of the macro should be removed and an error about
1760 // `$( $c )+` raised
1761 parse_macro(
1762 r#"
1763 macro_rules! foo {
1764 ($( $b:ident )+) => {
1765 $( $c )+
1766 };
1767 ($( $b:ident )+) => {
1768 $( $b )+
1769 }
1770 }
1771 "#,
1772 )
1773 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1774}
1775
1776#[test]
1777fn test_no_space_after_semi_colon() {
1778 let expanded = parse_macro(
1779 r#"
1780 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1781 "#,
1782 )
1783 .expand_items(r#"with_std! {mod m;mod f;}"#);
1784
1785 let dump = format!("{:#?}", expanded);
1786 assert_eq_text!(
1787 r###"[email protected]
1788 [email protected]
1789 [email protected]
1790 [email protected] "#"
1791 [email protected] "["
1792 [email protected]
1793 [email protected]
1794 [email protected]
1795 [email protected] "cfg"
1796 [email protected]
1797 [email protected] "("
1798 [email protected] "feature"
1799 [email protected] "="
1800 [email protected] "\"std\""
1801 [email protected] ")"
1802 [email protected] "]"
1803 [email protected] "mod"
1804 [email protected]
1805 [email protected] "m"
1806 [email protected] ";"
1807 [email protected]
1808 [email protected]
1809 [email protected] "#"
1810 [email protected] "["
1811 [email protected]
1812 [email protected]
1813 [email protected]
1814 [email protected] "cfg"
1815 [email protected]
1816 [email protected] "("
1817 [email protected] "feature"
1818 [email protected] "="
1819 [email protected] "\"std\""
1820 [email protected] ")"
1821 [email protected] "]"
1822 [email protected] "mod"
1823 [email protected]
1824 [email protected] "f"
1825 [email protected] ";""###,
1826 dump.trim()
1827 );
1828}
1829
1830// https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1831#[test]
1832fn test_rustc_issue_57597() {
1833 fn test_error(fixture: &str) {
1834 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
1835 }
1836
1837 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
1838 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
1839 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
1840 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
1841 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
1842 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
1843 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
1844 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1845 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1846 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1847 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1848 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1849}
1850
1851#[test]
1852fn test_expand_bad_literal() {
1853 parse_macro(
1854 r#"
1855 macro_rules! foo { ($i:literal) => {}; }
1856 "#,
1857 )
1858 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1859}
1860
1861#[test]
1862fn test_empty_comments() {
1863 parse_macro(
1864 r#"
1865 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1866 "#,
1867 )
1868 .assert_expand_err(
1869 r#"one_arg_macro!(/**/)"#,
1870 &ExpandError::BindingError("expected Expr".into()),
1871 );
1872}
diff --git a/crates/mbe/src/tests/rule.rs b/crates/mbe/src/tests/rule.rs
new file mode 100644
index 000000000..07277966d
--- /dev/null
+++ b/crates/mbe/src/tests/rule.rs
@@ -0,0 +1,45 @@
1use syntax::{ast, AstNode};
2
3use crate::ast_to_token_tree;
4
5use super::*;
6
7#[test]
8fn test_valid_arms() {
9 fn check(macro_body: &str) {
10 let m = parse_macro_arm(macro_body);
11 m.unwrap();
12 }
13
14 check("($i:ident) => ()");
15 check("($($i:ident)*) => ($_)");
16 check("($($true:ident)*) => ($true)");
17 check("($($false:ident)*) => ($false)");
18 check("($) => ($)");
19}
20
21#[test]
22fn test_invalid_arms() {
23 fn check(macro_body: &str, err: ParseError) {
24 let m = parse_macro_arm(macro_body);
25 assert_eq!(m, Err(err));
26 }
27 check("invalid", ParseError::Expected("expected subtree".into()));
28
29 check("$i:ident => ()", ParseError::Expected("expected subtree".into()));
30 check("($i:ident) ()", ParseError::Expected("expected `=`".into()));
31 check("($($i:ident)_) => ()", ParseError::InvalidRepeat);
32
33 check("($i) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
34 check("($i:) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
35}
36
37fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
38 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
39 let source_file = ast::SourceFile::parse(&macro_definition).ok().unwrap();
40 let macro_definition =
41 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
42
43 let (definition_tt, _) = ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
44 crate::MacroRules::parse(&definition_tt)
45}