1 use ::parser::FragmentKind;
3 SyntaxKind::{ERROR, IDENT},
6 use test_utils::assert_eq_text;
10 // Good first issue (although a slightly challenging one):
12 // * Pick a random test from here
13 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
14 // * Port the test to rust and add it to this module
18 fn test_token_id_shift() {
19 let expansion = parse_macro(
22 ($e:ident) => { foo bar $e }
26 .expand_tt("foobar!(baz);");
28 fn get_id(t: &tt::TokenTree) -> Option<u32> {
29 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
30 return Some(ident.id.0);
35 assert_eq!(expansion.token_trees.len(), 3);
36 // {($e:ident) => { foo bar $e }}
38 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
39 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
41 // The input args of macro call include parentheses:
43 // So baz should be 12+1+1
44 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
49 let expanded = parse_macro(
52 ($e:ident) => { fn $e() {} }
56 .expand_tt("foobar!(baz);");
58 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
59 let content = node.syntax_node().to_string();
61 let get_text = |id, kind| -> String {
62 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
65 assert_eq!(expanded.token_trees.len(), 4);
66 // {($e:ident) => { fn $e() {} }}
67 // 012345 67 8 9 T12 3
69 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
70 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
71 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
75 fn test_convert_tt() {
77 macro_rules! impl_froms {
78 ($e:ident: $($v:ident),*) => {
80 impl From<$v> for $e {
81 fn from(it: $v) -> $e {
90 "impl_froms!(TokenTree: Leaf, Subtree);",
91 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
92 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
97 fn test_convert_tt2() {
100 macro_rules! impl_froms {
101 ($e:ident: $($v:ident),*) => {
103 impl From<$v> for $e {
104 fn from(it: $v) -> $e {
114 "impl_froms!(TokenTree: Leaf, Subtree);",
170 fn test_lifetime_split() {
174 ($($t:tt)*) => { $($t)*}
179 r#"foo!(static bar: &'static str = "hello";);"#,
197 fn test_expr_order() {
198 let expanded = parse_macro(
202 fn bar() { $ i * 2; }
207 .expand_items("foo! { 1 + 1}");
209 let dump = format!("{:#?}", expanded);
228 INT_NUMBER@10..11 "1"
231 INT_NUMBER@12..13 "2"
233 R_CURLY@14..15 "}""#,
239 fn test_fail_match_pattern_by_first_token() {
255 .assert_expand_items("foo! { foo }", "mod foo {}")
256 .assert_expand_items("foo! { = bar }", "fn bar () {}")
257 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
261 fn test_fail_match_pattern_by_last_token() {
277 .assert_expand_items("foo! { foo }", "mod foo {}")
278 .assert_expand_items("foo! { bar = }", "fn bar () {}")
279 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
283 fn test_fail_match_pattern_by_word_token() {
290 (spam $ i:ident) => (
293 (eggs $ i:ident) => (
299 .assert_expand_items("foo! { foo }", "mod foo {}")
300 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
301 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
305 fn test_match_group_pattern_by_separator_token() {
309 ($ ($ i:ident),*) => ($ (
312 ($ ($ i:ident)#*) => ($ (
315 ($ i:ident ,# $ j:ident) => (
322 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
323 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
324 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
328 fn test_match_group_pattern_with_multiple_defs() {
332 ($ ($ i:ident),*) => ( struct Bar { $ (
338 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
342 fn test_match_group_pattern_with_multiple_statement() {
346 ($ ($ i:ident),*) => ( fn baz { $ (
352 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
356 fn test_match_group_pattern_with_multiple_statement_without_semi() {
360 ($ ($ i:ident),*) => ( fn baz { $ (
366 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
370 fn test_match_group_empty_fixed_token() {
374 ($ ($ i:ident)* #abc) => ( fn baz { $ (
380 .assert_expand_items("foo! {#abc}", "fn baz {}");
384 fn test_match_group_in_subtree() {
388 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
393 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
397 fn test_match_group_with_multichar_sep() {
401 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
404 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
408 fn test_match_group_with_multichar_sep2() {
412 (fn $name:ident {$($i:literal)&&*} ) => ( fn $name() -> bool { $($i)&&*} );
415 .assert_expand_items("foo! (fn baz {true && true} );", "fn baz () -> bool {true &&true}");
419 fn test_match_group_zero_match() {
423 ( $($i:ident)* ) => ();
426 .assert_expand_items("foo! ();", "");
430 fn test_match_group_in_group() {
434 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
437 .assert_expand_items("foo! ( (a b) );", "(a b)");
441 fn test_expand_to_item_list() {
442 let tree = parse_macro(
444 macro_rules! structs {
446 $(struct $i { field: u32 } )*
451 .expand_items("structs!(Foo, Bar);");
453 format!("{:#?}", tree).trim(),
457 STRUCT_KW@0..6 "struct"
460 RECORD_FIELD_LIST@9..20
473 STRUCT_KW@20..26 "struct"
476 RECORD_FIELD_LIST@29..40
492 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
493 if let tt::TokenTree::Subtree(subtree) = tt {
496 unreachable!("It is not a subtree");
498 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
499 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
502 unreachable!("It is not a literal");
505 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
506 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
509 unreachable!("It is not a Punct");
513 fn test_expand_literals_to_token_tree() {
514 let expansion = parse_macro(
516 macro_rules! literals {
528 .expand_tt("literals!(foo);");
529 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
531 // [let] [a] [=] ['c'] [;]
532 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
533 // [let] [c] [=] [1000] [;]
534 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
535 // [let] [f] [=] [12E+99_f64] [;]
536 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
537 // [let] [s] [=] ["rust1"] [;]
538 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
542 fn test_attr_to_token_tree() {
543 let expansion = parse_to_token_tree_by_syntax(
550 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
552 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
553 Some(tt::DelimiterKind::Bracket)
558 fn test_two_idents() {
562 ($ i:ident, $ j:ident) => {
563 fn foo() { let a = $ i; let b = $j; }
568 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
572 fn test_tt_to_stmts() {
573 let stmts = parse_macro(
584 .expand_statements("foo!{}");
587 format!("{:#?}", stmts).trim(),
608 INT_NUMBER@9..11 "10"
611 INT_NUMBER@12..13 "1"
622 fn test_match_literal() {
632 .assert_expand_items("foo! ['('];", "fn foo () {}");
636 fn test_parse_macro_def_simple() {
637 cov_mark::check!(parse_macro_def_simple);
641 macro foo($id:ident) {
646 .assert_expand_items("foo!(bar);", "fn bar () {}");
650 fn test_parse_macro_def_rules() {
651 cov_mark::check!(parse_macro_def_rules);
662 .assert_expand_items("foo!(bar);", "fn bar () {}");
671 fn foo() { let a = $ i; }
676 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
677 .assert_expand_items(
678 "foo! { bar::<u8>::baz::<u8> }",
679 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
684 fn test_two_paths() {
688 ($ i:path, $ j:path) => {
689 fn foo() { let a = $ i; let b = $j; }
694 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
698 fn test_path_with_path() {
703 fn foo() { let a = $ i :: bar; }
708 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
722 .assert_expand_items(
723 "foo! { 2 + 2 * baz(3).quux() }",
724 "fn bar () {2 + 2 * baz (3) . quux () ;}",
729 fn test_last_expr() {
733 ($($item:expr),*) => {
735 let mut v = Vec::new();
745 .assert_expand_items(
747 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
752 fn test_expr_with_attr() {
760 .assert_expand_items("m!(#[allow(a)]())", "0");
769 fn bar() -> $ i { unimplemented!() }
774 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
778 fn test_ty_with_complex_type() {
783 fn bar() -> $ i { unimplemented!() }
788 // Reference lifetime struct with generic type
789 .assert_expand_items(
790 "foo! { &'a Baz<u8> }",
791 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
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 ! ()}"#,
805 ($ i:pat) => { fn foo() { let $ i; } }
809 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
823 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
824 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
828 fn test_single_item() {
838 .assert_expand_items("foo! {mod c {}}", "mod c {}");
842 fn test_all_items() {
846 ($ ($ i:item)*) => ($ (
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 ;"#,
879 ($ i:block) => { fn foo() $ i }
883 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
898 .assert_expand_items(
899 r#"foo! { cfg(target_os = "windows") }"#,
900 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
902 .assert_expand_items(r#"foo! { hello::world }"#, r#"# [hello :: world] fn bar () {}"#);
906 fn test_meta_doc_comments() {
910 ($(#[$ i:meta])+) => (
919 /// Single Line Doc 1
924 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
929 fn test_meta_doc_comments_non_latin() {
933 ($(#[$ i:meta])+) => (
947 "# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\\\n \"] fn bar () {}",
956 ($ i:tt) => { fn foo() $ i }
960 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
968 ($($ i:tt)*) => { $($ i)* }
972 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
976 fn test_tt_composite() {
984 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
988 fn test_tt_composite2() {
989 let node = parse_macro(
992 ($($tt:tt)*) => { abs!(=> $($tt)*) }
996 .expand_items(r#"foo!{#}"#);
998 let res = format!("{:#?}", &node);
1000 r###"MACRO_ITEMS@0..10
1013 R_PAREN@9..10 ")""###,
1019 fn test_tt_with_composite_without_space() {
1023 ($ op:tt, $j:path) => (
1029 // Test macro input without any spaces
1030 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
1031 .assert_expand_items("foo!(==,Foo::Bool)", "0");
1035 fn test_underscore() {
1043 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1047 fn test_underscore_not_greedily() {
1051 ($($a:ident)* _) => {0};
1055 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
1056 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
1061 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
1065 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
1066 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
1070 fn test_underscore_as_type() {
1078 // Underscore is a type
1079 .assert_expand_items(r#"q![_]"#, r#"0"#);
1083 fn test_underscore_lifetime() {
1084 parse_macro(r#"macro_rules! q { ($a:lifetime) => {0}; }"#)
1085 .assert_expand_items(r#"q!['_]"#, r#"0"#);
1089 fn test_vertical_bar_with_pat() {
1093 (| $pat:pat | ) => { 0 }
1097 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1101 fn test_dollar_crate_lhs_is_not_meta() {
1110 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1114 fn test_lifetime() {
1118 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1122 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1130 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1134 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1139 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1143 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1147 fn test_boolean_is_ident() {
1151 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1156 r#"foo!(true,false);"#,
1181 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1185 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1186 // test optional cases
1187 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1191 fn test_inner_macro_rules() {
1195 ($a:ident, $b:ident, $c:tt) => {
1209 assert_expand_items(
1211 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1216 fn test_expr_after_path_colons() {
1217 assert!(parse_macro(
1226 .expand_statements(r#"m!(C("0"))"#)
1228 .any(|token| token.kind() == ERROR));
1232 fn test_match_is_not_greedy() {
1236 ($($i:ident $(,)*),*) => {};
1240 .assert_expand_items(r#"foo!(a,b);"#, r#""#);
1243 // The following tests are based on real world situations
1246 let fixture = parse_macro(
1249 ($($item:expr),*) => {
1251 let mut v = Vec::new();
1262 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1263 .assert_expand_items(
1265 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1268 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1271 format!("{:#?}", tree).trim(),
1295 SEMICOLON@19..20 ";"
1297 METHOD_CALL_EXPR@20..32
1309 INT_NUMBER@27..31 "1u32"
1311 SEMICOLON@32..33 ";"
1313 METHOD_CALL_EXPR@33..42
1325 INT_NUMBER@40..41 "2"
1327 SEMICOLON@42..43 ";"
1333 R_CURLY@44..45 "}""#
1338 fn test_winapi_struct() {
1339 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1343 macro_rules! STRUCT {
1344 ($(#[$attrs:meta])* struct $name:ident {
1345 $($field:ident: $ftype:ty,)+
1347 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1349 $(pub $field: $ftype,)+
1351 impl Clone for $name {
1353 fn clone(&self) -> $name { *self }
1355 #[cfg(feature = "impl-default")]
1356 impl Default for $name {
1358 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1364 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1365 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1366 "# [repr (C)] # [derive (Copy)] pub struct D3DVSHADERCAPS2_0 {pub Caps : u8 ,} impl Clone for D3DVSHADERCAPS2_0 {# [inline] fn clone (& self) -> D3DVSHADERCAPS2_0 {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DVSHADERCAPS2_0 {# [inline] fn default () -> D3DVSHADERCAPS2_0 {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1368 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1369 "# [repr (C)] # [derive (Copy)] # [cfg_attr (target_arch = \"x86\" , repr (packed))] pub struct D3DCONTENTPROTECTIONCAPS {pub Caps : u8 ,} impl Clone for D3DCONTENTPROTECTIONCAPS {# [inline] fn clone (& self) -> D3DCONTENTPROTECTIONCAPS {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DCONTENTPROTECTIONCAPS {# [inline] fn default () -> D3DCONTENTPROTECTIONCAPS {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1374 fn test_int_base() {
1377 macro_rules! int_base {
1378 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl fmt::$Trait for $T {
1381 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1382 $Radix.fmt_int(*self as $U, f)
1388 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1389 "# [stable (feature = \"rust1\" , since = \"1.0.0\")] impl fmt ::Binary for isize {fn fmt (& self , f : & mut fmt :: Formatter < \'_ >) -> fmt :: Result {Binary . fmt_int (* self as usize , f)}}"
1394 fn test_generate_pattern_iterators() {
1395 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1398 macro_rules! generate_pattern_iterators {
1399 { double ended; with $(#[$common_stability_attribute:meta])*,
1400 $forward_iterator:ident,
1401 $reverse_iterator:ident, $iterty:ty
1407 ).assert_expand_items(
1408 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1414 fn test_impl_fn_for_zst() {
1415 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1418 macro_rules! impl_fn_for_zst {
1419 { $( $( #[$attr: meta] )*
1420 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1421 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1428 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1430 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1435 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1437 extern "rust-call" fn call_mut(
1439 ($( $arg, )*): ($( $ArgTy, )*)
1441 Fn::call(&*self, ($( $arg, )*))
1445 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1446 type Output = $ReturnTy;
1449 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1450 Fn::call(&self, ($( $arg, )*))
1457 ).assert_expand_items(r#"
1459 # [ derive ( Clone ) ]
1460 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1461 c . escape_debug_ext ( false )
1464 # [ derive ( Clone ) ]
1465 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1466 c . escape_unicode ( )
1468 # [ derive ( Clone ) ]
1469 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1470 c . escape_default ( )
1474 "# [derive (Clone)] struct CharEscapeDebugContinue ; impl Fn < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDebug {{c . escape_debug_ext (false)}}} impl FnMut < (char ,) > for CharEscapeDebugContinue {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDebugContinue {type Output = char :: EscapeDebug ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDebug {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeUnicode ; impl Fn < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeUnicode {{c . escape_unicode ()}}} impl FnMut < (char ,) > for CharEscapeUnicode {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeUnicode {type Output = char :: EscapeUnicode ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeUnicode {Fn :: call (& self , (c ,))}} # [derive (Clone)] struct CharEscapeDefault ; impl Fn < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call (& self , (c ,) : (char ,)) -> char :: EscapeDefault {{c . escape_default ()}}} impl FnMut < (char ,) > for CharEscapeDefault {# [inline] extern \"rust-call\" fn call_mut (& mut self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (&* self , (c ,))}} impl FnOnce < (char ,) > for CharEscapeDefault {type Output = char :: EscapeDefault ; # [inline] extern \"rust-call\" fn call_once (self , (c ,) : (char ,)) -> char :: EscapeDefault {Fn :: call (& self , (c ,))}}"
1479 fn test_impl_nonzero_fmt() {
1480 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1483 macro_rules! impl_nonzero_fmt {
1484 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1489 ).assert_expand_items(
1490 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1496 fn test_cfg_if_items() {
1497 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1500 macro_rules! __cfg_if_items {
1501 (($($not:meta,)*) ; ) => {};
1502 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1503 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1507 ).assert_expand_items(
1508 r#"__cfg_if_items ! { ( rustdoc , ) ; ( ( ) ( # [ cfg ( any ( target_os = "redox" , unix ) ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as unix ; # [ cfg ( windows ) ] # [ stable ( feature = "rust1" , since = "1.0.0" ) ] pub use sys :: ext as windows ; # [ cfg ( any ( target_os = "linux" , target_os = "l4re" ) ) ] pub mod linux ; ) ) , }"#,
1509 "__cfg_if_items ! {(rustdoc ,) ;}",
1514 fn test_cfg_if_main() {
1515 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1518 macro_rules! cfg_if {
1520 if #[cfg($($meta:meta),*)] { $($it:item)* }
1526 $( ( ($($meta),*) ($($it)*) ), )*
1531 // Internal macro to Apply a cfg attribute to a list of items
1532 (@__apply $m:meta, $($it:item)*) => {
1537 ).assert_expand_items(r#"
1539 if # [ cfg ( target_env = "msvc" ) ] {
1540 // no extra unwinder support needed
1541 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1542 // no unwinder on the system!
1545 pub use libunwind :: * ;
1549 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1550 ).assert_expand_items(
1552 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1559 fn test_proptest_arbitrary() {
1560 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1563 macro_rules! arbitrary {
1564 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1565 $args: ident => $logic: expr) => {
1566 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1567 type Parameters = $params;
1568 type Strategy = $strat;
1569 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1576 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1578 VecStrategy < A :: Strategy > ,
1579 RangedParams1 < A :: Parameters > ;
1580 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1582 "impl <A : Arbitrary > $crate :: arbitrary :: Arbitrary for Vec < A > {type Parameters = RangedParams1 < A :: Parameters > ; type Strategy = VecStrategy < A :: Strategy > ; fn arbitrary_with (args : Self :: Parameters) -> Self :: Strategy {{let product_unpack ! [range , a] = args ; vec (any_with :: < A > (a) , range)}}}"
1587 fn test_old_ridl() {
1588 // This is from winapi 2.8, which do not have a link from github
1590 let expanded = parse_macro(
1594 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1596 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1600 $(pub unsafe fn $method(&mut self) -> $rtr {
1601 ((*self.lpVtbl).$method)(self $(,$p)*)
1607 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1608 fn GetDataSize(&mut self) -> UINT
1611 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1615 fn test_quick_error() {
1616 let expanded = parse_macro(
1618 macro_rules! quick_error {
1620 (SORT [enum $name:ident $( #[$meta:meta] )*]
1621 items [$($( #[$imeta:meta] )*
1622 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1623 {$( $ifuncs:tt )*} )* ]
1627 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1632 $iitem: $imode [$( $ivar: $ityp ),*]
1642 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1644 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1645 ] buf [] queue []) ;
1649 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1653 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1656 macro_rules! delegate_impl {
1657 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1658 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1661 @escape [type $assoc_name_ext:ident]
1666 $(#[$_assoc_attr:meta])*
1667 type $assoc_name:ident $(: $assoc_bound:ty)*;
1673 $(#[$_method_attr:meta])*
1674 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1682 impl<> $name for $self_wrap where $self_type: $name {
1685 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1686 $self_map!(self).$method_name($($marg),*)
1694 ).assert_expand_items(
1695 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1696 "impl <> Data for & \'a mut G where G : Data {}",
1701 fn expr_interpolation() {
1702 let expanded = parse_macro(
1711 .expand_expr("id!(x + foo);");
1713 assert_eq!(expanded.to_string(), "map(x+foo)");
1717 fn test_issue_2520() {
1718 let macro_fixture = parse_macro(
1720 macro_rules! my_macro {
1723 $( [] $sname:ident : $stype:ty )?
1724 $( [$expr:expr] $nname:ident : $ntype:ty )?
1737 macro_fixture.assert_expand_items(
1739 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1746 fn test_issue_3861() {
1747 let macro_fixture = parse_macro(
1749 macro_rules! rgb_color {
1750 ($p:expr, $t: ty) => {
1752 let _ = 0 as $t << $p;
1759 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1763 fn test_repeat_bad_var() {
1764 // FIXME: the second rule of the macro should be removed and an error about
1765 // `$( $c )+` raised
1769 ($( $b:ident )+) => {
1772 ($( $b:ident )+) => {
1778 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1782 fn test_no_space_after_semi_colon() {
1783 let expanded = parse_macro(
1785 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1788 .expand_items(r#"with_std! {mod m;mod f;}"#);
1790 let dump = format!("{:#?}", expanded);
1792 r###"MACRO_ITEMS@0..52
1803 IDENT@6..13 "feature"
1805 STRING@14..19 "\"std\""
1811 SEMICOLON@25..26 ";"
1822 IDENT@32..39 "feature"
1824 STRING@40..45 "\"std\""
1830 SEMICOLON@51..52 ";""###,
1835 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1837 fn test_rustc_issue_57597() {
1838 fn test_error(fixture: &str) {
1839 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
1842 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
1843 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
1844 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
1845 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
1846 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
1847 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
1848 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
1849 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1850 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1851 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1852 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1853 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1857 fn test_expand_bad_literal() {
1860 macro_rules! foo { ($i:literal) => {}; }
1863 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1867 fn test_empty_comments() {
1870 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1874 r#"one_arg_macro!(/**/)"#,
1875 &ExpandError::BindingError("expected Expr".into()),