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