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