aboutsummaryrefslogtreecommitdiff
path: root/crates/mbe/src/tests
diff options
context:
space:
mode:
Diffstat (limited to 'crates/mbe/src/tests')
-rw-r--r--crates/mbe/src/tests/expand.rs1877
-rw-r--r--crates/mbe/src/tests/rule.rs49
2 files changed, 1926 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..8951f3813
--- /dev/null
+++ b/crates/mbe/src/tests/expand.rs
@@ -0,0 +1,1877 @@
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_underscore_lifetime() {
1084 parse_macro(r#"macro_rules! q { ($a:lifetime) => {0}; }"#)
1085 .assert_expand_items(r#"q!['_]"#, r#"0"#);
1086}
1087
1088#[test]
1089fn test_vertical_bar_with_pat() {
1090 parse_macro(
1091 r#"
1092 macro_rules! foo {
1093 (| $pat:pat | ) => { 0 }
1094 }
1095 "#,
1096 )
1097 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1098}
1099
1100#[test]
1101fn test_dollar_crate_lhs_is_not_meta() {
1102 parse_macro(
1103 r#"
1104macro_rules! foo {
1105 ($crate) => {};
1106 () => {0};
1107}
1108 "#,
1109 )
1110 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1111}
1112
1113#[test]
1114fn test_lifetime() {
1115 parse_macro(
1116 r#"
1117 macro_rules! foo {
1118 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1119 }
1120"#,
1121 )
1122 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1123}
1124
1125#[test]
1126fn test_literal() {
1127 parse_macro(
1128 r#"
1129 macro_rules! foo {
1130 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1131 }
1132"#,
1133 )
1134 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1135
1136 parse_macro(
1137 r#"
1138 macro_rules! foo {
1139 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1140 }
1141"#,
1142 )
1143 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1144}
1145
1146#[test]
1147fn test_boolean_is_ident() {
1148 parse_macro(
1149 r#"
1150 macro_rules! foo {
1151 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1152 }
1153"#,
1154 )
1155 .assert_expand(
1156 r#"foo!(true,false);"#,
1157 r#"
1158SUBTREE $
1159 IDENT const 14
1160 IDENT VALUE 15
1161 PUNCH : [alone] 16
1162 SUBTREE () 17
1163 IDENT bool 18
1164 PUNCH , [alone] 19
1165 IDENT bool 20
1166 PUNCH = [alone] 21
1167 SUBTREE () 22
1168 IDENT true 29
1169 PUNCH , [joint] 25
1170 IDENT false 31
1171 PUNCH ; [alone] 28
1172"#,
1173 );
1174}
1175
1176#[test]
1177fn test_vis() {
1178 parse_macro(
1179 r#"
1180 macro_rules! foo {
1181 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1182 }
1183"#,
1184 )
1185 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1186 // test optional cases
1187 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1188}
1189
1190#[test]
1191fn test_inner_macro_rules() {
1192 parse_macro(
1193 r#"
1194macro_rules! foo {
1195 ($a:ident, $b:ident, $c:tt) => {
1196
1197 macro_rules! bar {
1198 ($bi:ident) => {
1199 fn $bi() -> u8 {$c}
1200 }
1201 }
1202
1203 bar!($a);
1204 fn $b() -> u8 {$c}
1205 }
1206}
1207"#,
1208 ).
1209 assert_expand_items(
1210 r#"foo!(x,y, 1);"#,
1211 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1212 );
1213}
1214
1215#[test]
1216fn test_expr_after_path_colons() {
1217 assert!(parse_macro(
1218 r#"
1219macro_rules! m {
1220 ($k:expr) => {
1221 f(K::$k);
1222 }
1223}
1224"#,
1225 )
1226 .expand_statements(r#"m!(C("0"))"#)
1227 .descendants()
1228 .any(|token| token.kind() == ERROR));
1229}
1230
1231#[test]
1232fn test_match_is_not_greedy() {
1233 parse_macro(
1234 r#"
1235macro_rules! foo {
1236 ($($i:ident $(,)*),*) => {};
1237}
1238"#,
1239 )
1240 .assert_expand_items(r#"foo!(a,b);"#, r#""#);
1241}
1242
1243// The following tests are based on real world situations
1244#[test]
1245fn test_vec() {
1246 let fixture = parse_macro(
1247 r#"
1248 macro_rules! vec {
1249 ($($item:expr),*) => {
1250 {
1251 let mut v = Vec::new();
1252 $(
1253 v.push($item);
1254 )*
1255 v
1256 }
1257 };
1258}
1259"#,
1260 );
1261 fixture
1262 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1263 .assert_expand_items(
1264 r#"vec![1u32,2];"#,
1265 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1266 );
1267
1268 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1269
1270 assert_eq!(
1271 format!("{:#?}", tree).trim(),
1272 r#"[email protected]
1273 [email protected] "{"
1274 [email protected]
1275 [email protected] "let"
1276 [email protected]
1277 [email protected] "mut"
1278 [email protected]
1279 [email protected] "v"
1280 [email protected] "="
1281 [email protected]
1282 [email protected]
1283 [email protected]
1284 [email protected]
1285 [email protected]
1286 [email protected]
1287 [email protected] "Vec"
1288 [email protected] "::"
1289 [email protected]
1290 [email protected]
1291 [email protected] "new"
1292 [email protected]
1293 [email protected] "("
1294 [email protected] ")"
1295 [email protected] ";"
1296 [email protected]
1297 [email protected]
1298 [email protected]
1299 [email protected]
1300 [email protected]
1301 [email protected]
1302 [email protected] "v"
1303 [email protected] "."
1304 [email protected]
1305 [email protected] "push"
1306 [email protected]
1307 [email protected] "("
1308 [email protected]
1309 [email protected] "1u32"
1310 [email protected] ")"
1311 [email protected] ";"
1312 [email protected]
1313 [email protected]
1314 [email protected]
1315 [email protected]
1316 [email protected]
1317 [email protected]
1318 [email protected] "v"
1319 [email protected] "."
1320 [email protected]
1321 [email protected] "push"
1322 [email protected]
1323 [email protected] "("
1324 [email protected]
1325 [email protected] "2"
1326 [email protected] ")"
1327 [email protected] ";"
1328 [email protected]
1329 [email protected]
1330 [email protected]
1331 [email protected]
1332 [email protected] "v"
1333 [email protected] "}""#
1334 );
1335}
1336
1337#[test]
1338fn test_winapi_struct() {
1339 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1340
1341 parse_macro(
1342 r#"
1343macro_rules! STRUCT {
1344 ($(#[$attrs:meta])* struct $name:ident {
1345 $($field:ident: $ftype:ty,)+
1346 }) => (
1347 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1348 pub struct $name {
1349 $(pub $field: $ftype,)+
1350 }
1351 impl Clone for $name {
1352 #[inline]
1353 fn clone(&self) -> $name { *self }
1354 }
1355 #[cfg(feature = "impl-default")]
1356 impl Default for $name {
1357 #[inline]
1358 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1359 }
1360 );
1361}
1362"#,
1363 ).
1364 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1365 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1366 "# [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 ()}}}"
1367 )
1368 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1369 "# [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 ()}}}"
1370 );
1371}
1372
1373#[test]
1374fn test_int_base() {
1375 parse_macro(
1376 r#"
1377macro_rules! int_base {
1378 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl fmt::$Trait for $T {
1381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1382 $Radix.fmt_int(*self as $U, f)
1383 }
1384 }
1385 }
1386}
1387"#,
1388 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1389 "# [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)}}"
1390 );
1391}
1392
1393#[test]
1394fn test_generate_pattern_iterators() {
1395 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1396 parse_macro(
1397 r#"
1398macro_rules! generate_pattern_iterators {
1399 { double ended; with $(#[$common_stability_attribute:meta])*,
1400 $forward_iterator:ident,
1401 $reverse_iterator:ident, $iterty:ty
1402 } => {
1403 fn foo(){}
1404 }
1405}
1406"#,
1407 ).assert_expand_items(
1408 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1409 "fn foo () {}",
1410 );
1411}
1412
1413#[test]
1414fn test_impl_fn_for_zst() {
1415 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1416 parse_macro(
1417 r#"
1418macro_rules! impl_fn_for_zst {
1419 { $( $( #[$attr: meta] )*
1420 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1421 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1422$body: block; )+
1423 } => {
1424 $(
1425 $( #[$attr] )*
1426 struct $Name;
1427
1428 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1429 #[inline]
1430 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1431 $body
1432 }
1433 }
1434
1435 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1436 #[inline]
1437 extern "rust-call" fn call_mut(
1438 &mut self,
1439 ($( $arg, )*): ($( $ArgTy, )*)
1440 ) -> $ReturnTy {
1441 Fn::call(&*self, ($( $arg, )*))
1442 }
1443 }
1444
1445 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1446 type Output = $ReturnTy;
1447
1448 #[inline]
1449 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1450 Fn::call(&self, ($( $arg, )*))
1451 }
1452 }
1453 )+
1454}
1455 }
1456"#,
1457 ).assert_expand_items(r#"
1458impl_fn_for_zst ! {
1459 # [ derive ( Clone ) ]
1460 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1461 c . escape_debug_ext ( false )
1462 } ;
1463
1464 # [ derive ( Clone ) ]
1465 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1466 c . escape_unicode ( )
1467 } ;
1468 # [ derive ( Clone ) ]
1469 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1470 c . escape_default ( )
1471 } ;
1472 }
1473"#,
1474 "# [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 ,))}}"
1475 );
1476}
1477
1478#[test]
1479fn test_impl_nonzero_fmt() {
1480 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1481 parse_macro(
1482 r#"
1483 macro_rules! impl_nonzero_fmt {
1484 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1485 fn foo () {}
1486 }
1487 }
1488"#,
1489 ).assert_expand_items(
1490 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1491 "fn foo () {}",
1492 );
1493}
1494
1495#[test]
1496fn test_cfg_if_items() {
1497 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1498 parse_macro(
1499 r#"
1500 macro_rules! __cfg_if_items {
1501 (($($not:meta,)*) ; ) => {};
1502 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1503 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1504 }
1505 }
1506"#,
1507 ).assert_expand_items(
1508 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 ; ) ) , }"#,
1509 "__cfg_if_items ! {(rustdoc ,) ;}",
1510 );
1511}
1512
1513#[test]
1514fn test_cfg_if_main() {
1515 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1516 parse_macro(
1517 r#"
1518 macro_rules! cfg_if {
1519 ($(
1520 if #[cfg($($meta:meta),*)] { $($it:item)* }
1521 ) else * else {
1522 $($it2:item)*
1523 }) => {
1524 __cfg_if_items! {
1525 () ;
1526 $( ( ($($meta),*) ($($it)*) ), )*
1527 ( () ($($it2)*) ),
1528 }
1529 };
1530
1531 // Internal macro to Apply a cfg attribute to a list of items
1532 (@__apply $m:meta, $($it:item)*) => {
1533 $(#[$m] $it)*
1534 };
1535 }
1536"#,
1537 ).assert_expand_items(r#"
1538cfg_if ! {
1539 if # [ cfg ( target_env = "msvc" ) ] {
1540 // no extra unwinder support needed
1541 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1542 // no unwinder on the system!
1543 } else {
1544 mod libunwind ;
1545 pub use libunwind :: * ;
1546 }
1547 }
1548"#,
1549 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1550 ).assert_expand_items(
1551 r#"
1552cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1553"#,
1554 "",
1555 );
1556}
1557
1558#[test]
1559fn test_proptest_arbitrary() {
1560 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1561 parse_macro(
1562 r#"
1563macro_rules! arbitrary {
1564 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1565 $args: ident => $logic: expr) => {
1566 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1567 type Parameters = $params;
1568 type Strategy = $strat;
1569 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1570 $logic
1571 }
1572 }
1573 };
1574
1575}"#,
1576 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1577 Vec < A > ,
1578 VecStrategy < A :: Strategy > ,
1579 RangedParams1 < A :: Parameters > ;
1580 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1581 ) ;"#,
1582 "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)}}}"
1583 );
1584}
1585
1586#[test]
1587fn test_old_ridl() {
1588 // This is from winapi 2.8, which do not have a link from github
1589 //
1590 let expanded = parse_macro(
1591 r#"
1592#[macro_export]
1593macro_rules! RIDL {
1594 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1595 {$(
1596 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1597 ),+}
1598 ) => {
1599 impl $interface {
1600 $(pub unsafe fn $method(&mut self) -> $rtr {
1601 ((*self.lpVtbl).$method)(self $(,$p)*)
1602 })+
1603 }
1604 };
1605}"#,
1606 ).expand_tt(r#"
1607 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1608 fn GetDataSize(&mut self) -> UINT
1609 }}"#);
1610
1611 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1612}
1613
1614#[test]
1615fn test_quick_error() {
1616 let expanded = parse_macro(
1617 r#"
1618macro_rules! quick_error {
1619
1620 (SORT [enum $name:ident $( #[$meta:meta] )*]
1621 items [$($( #[$imeta:meta] )*
1622 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1623 {$( $ifuncs:tt )*} )* ]
1624 buf [ ]
1625 queue [ ]
1626 ) => {
1627 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1628 body []
1629 queue [$(
1630 $( #[$imeta] )*
1631 =>
1632 $iitem: $imode [$( $ivar: $ityp ),*]
1633 )*]
1634 );
1635};
1636
1637}
1638"#,
1639 )
1640 .expand_tt(
1641 r#"
1642quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1643 => One : UNIT [] {}
1644 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1645 ] buf [] queue []) ;
1646"#,
1647 );
1648
1649 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1650}
1651
1652#[test]
1653fn test_empty_repeat_vars_in_empty_repeat_vars() {
1654 parse_macro(
1655 r#"
1656macro_rules! delegate_impl {
1657 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1658 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1659
1660 $(
1661 @escape [type $assoc_name_ext:ident]
1662 )*
1663 $(
1664 @section type
1665 $(
1666 $(#[$_assoc_attr:meta])*
1667 type $assoc_name:ident $(: $assoc_bound:ty)*;
1668 )+
1669 )*
1670 $(
1671 @section self
1672 $(
1673 $(#[$_method_attr:meta])*
1674 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1675 )+
1676 )*
1677 $(
1678 @section nodelegate
1679 $($tail:tt)*
1680 )*
1681 }) => {
1682 impl<> $name for $self_wrap where $self_type: $name {
1683 $(
1684 $(
1685 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1686 $self_map!(self).$method_name($($marg),*)
1687 }
1688 )*
1689 )*
1690 }
1691 }
1692}
1693"#,
1694 ).assert_expand_items(
1695 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1696 "impl <> Data for & \'a mut G where G : Data {}",
1697 );
1698}
1699
1700#[test]
1701fn expr_interpolation() {
1702 let expanded = parse_macro(
1703 r#"
1704 macro_rules! id {
1705 ($expr:expr) => {
1706 map($expr)
1707 }
1708 }
1709 "#,
1710 )
1711 .expand_expr("id!(x + foo);");
1712
1713 assert_eq!(expanded.to_string(), "map(x+foo)");
1714}
1715
1716#[test]
1717fn test_issue_2520() {
1718 let macro_fixture = parse_macro(
1719 r#"
1720 macro_rules! my_macro {
1721 {
1722 ( $(
1723 $( [] $sname:ident : $stype:ty )?
1724 $( [$expr:expr] $nname:ident : $ntype:ty )?
1725 ),* )
1726 } => {
1727 Test {
1728 $(
1729 $( $sname, )?
1730 )*
1731 }
1732 };
1733 }
1734 "#,
1735 );
1736
1737 macro_fixture.assert_expand_items(
1738 r#"my_macro ! {
1739 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1740 }"#,
1741 "Test {p1 , k0 ,}",
1742 );
1743}
1744
1745#[test]
1746fn test_issue_3861() {
1747 let macro_fixture = parse_macro(
1748 r#"
1749 macro_rules! rgb_color {
1750 ($p:expr, $t: ty) => {
1751 pub fn new() {
1752 let _ = 0 as $t << $p;
1753 }
1754 };
1755 }
1756 "#,
1757 );
1758
1759 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1760}
1761
1762#[test]
1763fn test_repeat_bad_var() {
1764 // FIXME: the second rule of the macro should be removed and an error about
1765 // `$( $c )+` raised
1766 parse_macro(
1767 r#"
1768 macro_rules! foo {
1769 ($( $b:ident )+) => {
1770 $( $c )+
1771 };
1772 ($( $b:ident )+) => {
1773 $( $b )+
1774 }
1775 }
1776 "#,
1777 )
1778 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1779}
1780
1781#[test]
1782fn test_no_space_after_semi_colon() {
1783 let expanded = parse_macro(
1784 r#"
1785 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1786 "#,
1787 )
1788 .expand_items(r#"with_std! {mod m;mod f;}"#);
1789
1790 let dump = format!("{:#?}", expanded);
1791 assert_eq_text!(
1792 r###"[email protected]
1793 [email protected]
1794 [email protected]
1795 [email protected] "#"
1796 [email protected] "["
1797 [email protected]
1798 [email protected]
1799 [email protected]
1800 [email protected] "cfg"
1801 [email protected]
1802 [email protected] "("
1803 [email protected] "feature"
1804 [email protected] "="
1805 [email protected] "\"std\""
1806 [email protected] ")"
1807 [email protected] "]"
1808 [email protected] "mod"
1809 [email protected]
1810 [email protected] "m"
1811 [email protected] ";"
1812 [email protected]
1813 [email protected]
1814 [email protected] "#"
1815 [email protected] "["
1816 [email protected]
1817 [email protected]
1818 [email protected]
1819 [email protected] "cfg"
1820 [email protected]
1821 [email protected] "("
1822 [email protected] "feature"
1823 [email protected] "="
1824 [email protected] "\"std\""
1825 [email protected] ")"
1826 [email protected] "]"
1827 [email protected] "mod"
1828 [email protected]
1829 [email protected] "f"
1830 [email protected] ";""###,
1831 dump.trim()
1832 );
1833}
1834
1835// https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1836#[test]
1837fn test_rustc_issue_57597() {
1838 fn test_error(fixture: &str) {
1839 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
1840 }
1841
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 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1850 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1851 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1852 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1853 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1854}
1855
1856#[test]
1857fn test_expand_bad_literal() {
1858 parse_macro(
1859 r#"
1860 macro_rules! foo { ($i:literal) => {}; }
1861 "#,
1862 )
1863 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1864}
1865
1866#[test]
1867fn test_empty_comments() {
1868 parse_macro(
1869 r#"
1870 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1871 "#,
1872 )
1873 .assert_expand_err(
1874 r#"one_arg_macro!(/**/)"#,
1875 &ExpandError::BindingError("expected Expr".into()),
1876 );
1877}
diff --git a/crates/mbe/src/tests/rule.rs b/crates/mbe/src/tests/rule.rs
new file mode 100644
index 000000000..bf48112b3
--- /dev/null
+++ b/crates/mbe/src/tests/rule.rs
@@ -0,0 +1,49 @@
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("($(x),*) => ()");
16 check("($(x)_*) => ()");
17 check("($(x)i*) => ()");
18 check("($($i:ident)*) => ($_)");
19 check("($($true:ident)*) => ($true)");
20 check("($($false:ident)*) => ($false)");
21 check("($) => ($)");
22}
23
24#[test]
25fn test_invalid_arms() {
26 fn check(macro_body: &str, err: ParseError) {
27 let m = parse_macro_arm(macro_body);
28 assert_eq!(m, Err(err));
29 }
30 check("invalid", ParseError::Expected("expected subtree".into()));
31
32 check("$i:ident => ()", ParseError::Expected("expected subtree".into()));
33 check("($i:ident) ()", ParseError::Expected("expected `=`".into()));
34 check("($($i:ident)_) => ()", ParseError::InvalidRepeat);
35
36 check("($i) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
37 check("($i:) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
38 check("($i:_) => ()", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
39}
40
41fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
42 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
43 let source_file = ast::SourceFile::parse(&macro_definition).ok().unwrap();
44 let macro_definition =
45 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
46
47 let (definition_tt, _) = ast_to_token_tree(&macro_definition.token_tree().unwrap()).unwrap();
48 crate::MacroRules::parse(&definition_tt)
49}