aboutsummaryrefslogtreecommitdiff
path: root/crates/mbe/src/tests
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2021-03-18 09:23:54 +0000
committerGitHub <[email protected]>2021-03-18 09:23:54 +0000
commit80d497e5415e9826cfe0596b6be88c6733f56cb5 (patch)
treef6611126ae81a874f139e04f9756f6c9fe808b28 /crates/mbe/src/tests
parentd704750ba982153d92ccff90cf236121641b9da3 (diff)
parent49b876de094db571d1ae10577ce2405909d3bd3e (diff)
Merge #8081
8081: Reorganize mbe tests r=edwin0cheng a=edwin0cheng bors r+ Co-authored-by: Edwin Cheng <[email protected]>
Diffstat (limited to 'crates/mbe/src/tests')
-rw-r--r--crates/mbe/src/tests/expand.rs1872
-rw-r--r--crates/mbe/src/tests/rule.rs45
2 files changed, 1917 insertions, 0 deletions
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}