3 use ::parser::FragmentKind;
4 use syntax::{ast, AstNode, NodeOrToken, SyntaxKind::IDENT, SyntaxNode, WalkEvent, T};
5 use test_utils::assert_eq_text;
10 use syntax::{ast, AstNode};
12 use crate::ast_to_token_tree;
17 fn test_valid_arms() {
18 fn check(macro_body: &str) {
19 let m = parse_macro_arm(macro_body);
23 check("($i:ident) => ()");
24 check("($($i:ident)*) => ($_)");
25 check("($($true:ident)*) => ($true)");
26 check("($($false:ident)*) => ($false)");
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))));
37 check("invalid", "expected subtree");
39 check("$i:ident => ()", "expected subtree");
40 check("($i:ident) ()", "expected `=`");
41 check("($($i:ident)_) => ()", "invalid repeat");
43 check("($i) => ($i)", "invalid macro definition");
44 check("($i:) => ($i)", "invalid macro definition");
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(¯o_definition).ok().unwrap();
50 let macro_definition =
51 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
53 let (definition_tt, _) =
54 ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
55 crate::MacroRules::parse(&definition_tt)
59 // Good first issue (although a slightly challenging one):
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
67 fn test_token_id_shift() {
68 let expansion = parse_macro(
71 ($e:ident) => { foo bar $e }
75 .expand_tt("foobar!(baz);");
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);
84 assert_eq!(expansion.token_trees.len(), 3);
85 // {($e:ident) => { foo bar $e }}
87 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
88 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
90 // The input args of macro call include parentheses:
92 // So baz should be 12+1+1
93 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
98 let expanded = parse_macro(
100 macro_rules! foobar {
101 ($e:ident) => { fn $e() {} }
105 .expand_tt("foobar!(baz);");
107 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
108 let content = node.syntax_node().to_string();
110 let get_text = |id, kind| -> String {
111 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
114 assert_eq!(expanded.token_trees.len(), 4);
115 // {($e:ident) => { fn $e() {} }}
116 // 012345 67 8 9 T12 3
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!['{']), "{");
124 fn test_convert_tt() {
126 macro_rules! impl_froms {
127 ($e:ident: $($v:ident),*) => {
129 impl From<$v> for $e {
130 fn from(it: $v) -> $e {
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)}}"
146 fn test_convert_tt2() {
149 macro_rules! impl_froms {
150 ($e:ident: $($v:ident),*) => {
152 impl From<$v> for $e {
153 fn from(it: $v) -> $e {
163 "impl_froms!(TokenTree: Leaf, Subtree);",
219 fn test_lifetime_split() {
223 ($($t:tt)*) => { $($t)*}
228 r#"foo!(static bar: &'static str = "hello";);"#,
246 fn test_expr_order() {
247 let expanded = parse_macro(
251 fn bar() { $ i * 2; }
256 .expand_items("foo! { 1 + 1}");
258 let dump = format!("{:#?}", expanded);
278 INT_NUMBER@10..11 "1"
281 INT_NUMBER@12..13 "2"
283 R_CURLY@14..15 "}""#,
288 fn test_fail_match_pattern_by_first_token() {
304 .assert_expand_items("foo! { foo }", "mod foo {}")
305 .assert_expand_items("foo! { = bar }", "fn bar () {}")
306 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
310 fn test_fail_match_pattern_by_last_token() {
326 .assert_expand_items("foo! { foo }", "mod foo {}")
327 .assert_expand_items("foo! { bar = }", "fn bar () {}")
328 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
332 fn test_fail_match_pattern_by_word_token() {
339 (spam $ i:ident) => (
342 (eggs $ i:ident) => (
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 ;");
354 fn test_match_group_pattern_by_separator_token() {
358 ($ ($ i:ident),*) => ($ (
361 ($ ($ i:ident)#*) => ($ (
364 ($ i:ident ,# $ j:ident) => (
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 ;");
377 fn test_match_group_pattern_with_multiple_defs() {
381 ($ ($ i:ident),*) => ( struct Bar { $ (
387 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
391 fn test_match_group_pattern_with_multiple_statement() {
395 ($ ($ i:ident),*) => ( fn baz { $ (
401 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
405 fn test_match_group_pattern_with_multiple_statement_without_semi() {
409 ($ ($ i:ident),*) => ( fn baz { $ (
415 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
419 fn test_match_group_empty_fixed_token() {
423 ($ ($ i:ident)* #abc) => ( fn baz { $ (
429 .assert_expand_items("foo! {#abc}", "fn baz {}");
433 fn test_match_group_in_subtree() {
437 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
442 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
446 fn test_match_group_with_multichar_sep() {
450 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
453 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
457 fn test_match_group_zero_match() {
461 ( $($i:ident)* ) => ();
464 .assert_expand_items("foo! ();", "");
468 fn test_match_group_in_group() {
472 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
475 .assert_expand_items("foo! ( (a b) );", "(a b)");
479 fn test_expand_to_item_list() {
480 let tree = parse_macro(
482 macro_rules! structs {
484 $(struct $i { field: u32 } )*
489 .expand_items("structs!(Foo, Bar);");
491 format!("{:#?}", tree).trim(),
495 STRUCT_KW@0..6 "struct"
498 RECORD_FIELD_LIST@9..20
511 STRUCT_KW@20..26 "struct"
514 RECORD_FIELD_LIST@29..40
530 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
531 if let tt::TokenTree::Subtree(subtree) = tt {
534 unreachable!("It is not a subtree");
536 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
537 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
540 unreachable!("It is not a literal");
543 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
544 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
547 unreachable!("It is not a Punct");
551 fn test_expand_literals_to_token_tree() {
552 let expansion = parse_macro(
554 macro_rules! literals {
566 .expand_tt("literals!(foo);");
567 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
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\"");
580 fn test_attr_to_token_tree() {
581 let expansion = parse_to_token_tree_by_syntax(
588 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
590 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
591 Some(tt::DelimiterKind::Bracket)
596 fn test_two_idents() {
600 ($ i:ident, $ j:ident) => {
601 fn foo() { let a = $ i; let b = $j; }
606 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
610 fn test_tt_to_stmts() {
611 let stmts = parse_macro(
622 .expand_statements("foo!{}");
625 format!("{:#?}", stmts).trim(),
646 INT_NUMBER@9..11 "10"
649 INT_NUMBER@12..13 "1"
661 fn test_match_literal() {
671 .assert_expand_items("foo! ['('];", "fn foo () {}");
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
683 fn foo() { let a = $ i; }
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 > ;}",
696 fn test_two_paths() {
700 ($ i:path, $ j:path) => {
701 fn foo() { let a = $ i; let b = $j; }
706 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
710 fn test_path_with_path() {
715 fn foo() { let a = $ i :: bar; }
720 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
734 .assert_expand_items(
735 "foo! { 2 + 2 * baz(3).quux() }",
736 "fn bar () {2 + 2 * baz (3) . quux () ;}",
741 fn test_last_expr() {
745 ($($item:expr),*) => {
747 let mut v = Vec::new();
757 .assert_expand_items(
759 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
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 () {}"#,
905 fn test_meta_doc_comments() {
909 ($(#[$ i:meta])+) => (
918 /// Single Line Doc 1
923 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
932 ($ i:tt) => { fn foo() $ i }
936 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
944 ($($ i:tt)*) => { $($ i)* }
948 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
952 fn test_tt_composite() {
960 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
964 fn test_tt_composite2() {
965 let node = parse_macro(
968 ($($tt:tt)*) => { abs!(=> $($tt)*) }
972 .expand_items(r#"foo!{#}"#);
974 let res = format!("{:#?}", &node);
977 r###"MACRO_ITEMS@0..10
990 R_PAREN@9..10 ")""###
999 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1003 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1011 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1015 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1020 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1024 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1028 fn test_boolean_is_ident() {
1032 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1037 r#"foo!(true,false);"#,
1062 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1066 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1067 // test optional cases
1068 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1072 fn test_inner_macro_rules() {
1076 ($a:ident, $b:ident, $c:tt) => {
1090 assert_expand_items(
1092 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1096 // The following tests are based on real world situations
1099 let fixture = parse_macro(
1102 ($($item:expr),*) => {
1104 let mut v = Vec::new();
1115 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1116 .assert_expand_items(
1118 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1121 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1124 format!("{:#?}", tree).trim(),
1148 SEMICOLON@19..20 ";"
1150 METHOD_CALL_EXPR@20..32
1162 INT_NUMBER@27..31 "1u32"
1164 SEMICOLON@32..33 ";"
1166 METHOD_CALL_EXPR@33..42
1178 INT_NUMBER@40..41 "2"
1180 SEMICOLON@42..43 ";"
1186 R_CURLY@44..45 "}""#
1191 fn test_winapi_struct() {
1192 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1196 macro_rules! STRUCT {
1197 ($(#[$attrs:meta])* struct $name:ident {
1198 $($field:ident: $ftype:ty,)+
1200 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1202 $(pub $field: $ftype,)+
1204 impl Clone for $name {
1206 fn clone(&self) -> $name { *self }
1208 #[cfg(feature = "impl-default")]
1209 impl Default for $name {
1211 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1217 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1218 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1219 "# [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 ()}}}"
1221 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1222 "# [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 ()}}}"
1227 fn test_int_base() {
1230 macro_rules! int_base {
1231 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl fmt::$Trait for $T {
1234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1235 $Radix.fmt_int(*self as $U, f)
1241 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1242 "# [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)}}"
1247 fn test_generate_pattern_iterators() {
1248 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1251 macro_rules! generate_pattern_iterators {
1252 { double ended; with $(#[$common_stability_attribute:meta])*,
1253 $forward_iterator:ident,
1254 $reverse_iterator:ident, $iterty:ty
1260 ).assert_expand_items(
1261 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1267 fn test_impl_fn_for_zst() {
1268 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1271 macro_rules! impl_fn_for_zst {
1272 { $( $( #[$attr: meta] )*
1273 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1274 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1281 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1283 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1288 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1290 extern "rust-call" fn call_mut(
1292 ($( $arg, )*): ($( $ArgTy, )*)
1294 Fn::call(&*self, ($( $arg, )*))
1298 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1299 type Output = $ReturnTy;
1302 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1303 Fn::call(&self, ($( $arg, )*))
1310 ).assert_expand_items(r#"
1312 # [ derive ( Clone ) ]
1313 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1314 c . escape_debug_ext ( false )
1317 # [ derive ( Clone ) ]
1318 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1319 c . escape_unicode ( )
1321 # [ derive ( Clone ) ]
1322 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1323 c . escape_default ( )
1327 "# [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 ,))}}"
1332 fn test_impl_nonzero_fmt() {
1333 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1336 macro_rules! impl_nonzero_fmt {
1337 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1342 ).assert_expand_items(
1343 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1349 fn test_cfg_if_items() {
1350 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1353 macro_rules! __cfg_if_items {
1354 (($($not:meta,)*) ; ) => {};
1355 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1356 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1360 ).assert_expand_items(
1361 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 ; ) ) , }"#,
1362 "__cfg_if_items ! {(rustdoc ,) ;}",
1367 fn test_cfg_if_main() {
1368 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1371 macro_rules! cfg_if {
1373 if #[cfg($($meta:meta),*)] { $($it:item)* }
1379 $( ( ($($meta),*) ($($it)*) ), )*
1384 // Internal macro to Apply a cfg attribute to a list of items
1385 (@__apply $m:meta, $($it:item)*) => {
1390 ).assert_expand_items(r#"
1392 if # [ cfg ( target_env = "msvc" ) ] {
1393 // no extra unwinder support needed
1394 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1395 // no unwinder on the system!
1398 pub use libunwind :: * ;
1402 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1403 ).assert_expand_items(
1405 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1412 fn test_proptest_arbitrary() {
1413 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1416 macro_rules! arbitrary {
1417 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1418 $args: ident => $logic: expr) => {
1419 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1420 type Parameters = $params;
1421 type Strategy = $strat;
1422 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1429 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1431 VecStrategy < A :: Strategy > ,
1432 RangedParams1 < A :: Parameters > ;
1433 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1435 "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)}}}"
1440 fn test_old_ridl() {
1441 // This is from winapi 2.8, which do not have a link from github
1443 let expanded = parse_macro(
1447 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1449 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1453 $(pub unsafe fn $method(&mut self) -> $rtr {
1454 ((*self.lpVtbl).$method)(self $(,$p)*)
1460 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1461 fn GetDataSize(&mut self) -> UINT
1464 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1468 fn test_quick_error() {
1469 let expanded = parse_macro(
1471 macro_rules! quick_error {
1473 (SORT [enum $name:ident $( #[$meta:meta] )*]
1474 items [$($( #[$imeta:meta] )*
1475 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1476 {$( $ifuncs:tt )*} )* ]
1480 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1485 $iitem: $imode [$( $ivar: $ityp ),*]
1495 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1497 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1498 ] buf [] queue []) ;
1502 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1506 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1509 macro_rules! delegate_impl {
1510 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1511 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1513 // "Escaped" associated types. Stripped before making the `trait`
1514 // itself, but forwarded when delegating impls.
1516 @escape [type $assoc_name_ext:ident]
1517 // Associated types. Forwarded.
1522 $(#[$_assoc_attr:meta])*
1523 type $assoc_name:ident $(: $assoc_bound:ty)*;
1526 // Methods. Forwarded. Using $self_map!(self) around the self argument.
1527 // Methods must use receiver `self` or explicit type like `self: &Self`
1528 // &self and &mut self are _not_ supported.
1532 $(#[$_method_attr:meta])*
1533 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1536 // Arbitrary tail that is ignored when forwarding.
1542 impl<> $name for $self_wrap where $self_type: $name {
1545 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1546 $self_map!(self).$method_name($($marg),*)
1554 ).assert_expand_items(
1555 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1556 "impl <> Data for & \'a mut G where G : Data {}",
1561 fn expr_interpolation() {
1562 let expanded = parse_macro(
1571 .expand_expr("id!(x + foo);");
1573 assert_eq!(expanded.to_string(), "map(x+foo)");
1576 pub(crate) struct MacroFixture {
1581 pub(crate) fn expand_tt(&self, invocation: &str) -> tt::Subtree {
1582 self.try_expand_tt(invocation).unwrap()
1585 fn try_expand_tt(&self, invocation: &str) -> Result<tt::Subtree, ExpandError> {
1586 let source_file = ast::SourceFile::parse(invocation).tree();
1587 let macro_invocation =
1588 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
1590 let (invocation_tt, _) = ast_to_token_tree(¯o_invocation.token_tree().unwrap())
1591 .ok_or_else(|| ExpandError::ConversionError)?;
1593 self.rules.expand(&invocation_tt).result()
1596 fn assert_expand_err(&self, invocation: &str, err: &ExpandError) {
1597 assert_eq!(self.try_expand_tt(invocation).as_ref(), Err(err));
1600 fn expand_items(&self, invocation: &str) -> SyntaxNode {
1601 let expanded = self.expand_tt(invocation);
1602 token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node()
1605 fn expand_statements(&self, invocation: &str) -> SyntaxNode {
1606 let expanded = self.expand_tt(invocation);
1607 token_tree_to_syntax_node(&expanded, FragmentKind::Statements).unwrap().0.syntax_node()
1610 fn expand_expr(&self, invocation: &str) -> SyntaxNode {
1611 let expanded = self.expand_tt(invocation);
1612 token_tree_to_syntax_node(&expanded, FragmentKind::Expr).unwrap().0.syntax_node()
1615 fn assert_expand_tt(&self, invocation: &str, expected: &str) {
1616 let expansion = self.expand_tt(invocation);
1617 assert_eq!(expansion.to_string(), expected);
1620 fn assert_expand(&self, invocation: &str, expected: &str) {
1621 let expansion = self.expand_tt(invocation);
1622 let actual = format!("{:?}", expansion);
1623 test_utils::assert_eq_text!(&actual.trim(), &expected.trim());
1626 fn assert_expand_items(&self, invocation: &str, expected: &str) -> &MacroFixture {
1627 self.assert_expansion(FragmentKind::Items, invocation, expected);
1631 fn assert_expand_statements(&self, invocation: &str, expected: &str) -> &MacroFixture {
1632 self.assert_expansion(FragmentKind::Statements, invocation, expected);
1636 fn assert_expansion(&self, kind: FragmentKind, invocation: &str, expected: &str) {
1637 let expanded = self.expand_tt(invocation);
1638 assert_eq!(expanded.to_string(), expected);
1640 let expected = expected.replace("$crate", "C_C__C");
1642 // wrap the given text to a macro call
1644 let wrapped = format!("wrap_macro!( {} )", expected);
1645 let wrapped = ast::SourceFile::parse(&wrapped);
1647 wrapped.tree().syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
1648 let mut wrapped = ast_to_token_tree(&wrapped).unwrap().0;
1649 wrapped.delimiter = None;
1653 let expanded_tree = token_tree_to_syntax_node(&expanded, kind).unwrap().0.syntax_node();
1654 let expanded_tree = debug_dump_ignore_spaces(&expanded_tree).trim().to_string();
1656 let expected_tree = token_tree_to_syntax_node(&expected, kind).unwrap().0.syntax_node();
1657 let expected_tree = debug_dump_ignore_spaces(&expected_tree).trim().to_string();
1659 let expected_tree = expected_tree.replace("C_C__C", "$crate");
1661 expanded_tree, expected_tree,
1662 "\nleft:\n{}\nright:\n{}",
1663 expanded_tree, expected_tree,
1668 fn parse_macro_to_tt(ra_fixture: &str) -> tt::Subtree {
1669 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1670 let macro_definition =
1671 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
1673 let (definition_tt, _) = ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
1675 let parsed = parse_to_token_tree(
1676 &ra_fixture[macro_definition.token_tree().unwrap().syntax().text_range()],
1680 assert_eq!(definition_tt, parsed);
1685 pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
1686 let definition_tt = parse_macro_to_tt(ra_fixture);
1687 let rules = MacroRules::parse(&definition_tt).unwrap();
1688 MacroFixture { rules }
1691 pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
1692 let definition_tt = parse_macro_to_tt(ra_fixture);
1694 match MacroRules::parse(&definition_tt) {
1695 Ok(_) => panic!("Expect error"),
1700 pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
1701 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1702 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
1704 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
1705 assert_eq!(tt, parsed);
1710 fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String {
1712 let mut buf = String::new();
1713 macro_rules! indent {
1721 for event in node.preorder_with_tokens() {
1723 WalkEvent::Enter(element) => {
1725 NodeOrToken::Node(node) => {
1727 writeln!(buf, "{:?}", node.kind()).unwrap();
1729 NodeOrToken::Token(token) => match token.kind() {
1730 syntax::SyntaxKind::WHITESPACE => {}
1733 writeln!(buf, "{:?}", token.kind()).unwrap();
1739 WalkEvent::Leave(_) => level -= 1,
1747 fn test_issue_2520() {
1748 let macro_fixture = parse_macro(
1750 macro_rules! my_macro {
1753 $( [] $sname:ident : $stype:ty )?
1754 $( [$expr:expr] $nname:ident : $ntype:ty )?
1767 macro_fixture.assert_expand_items(
1769 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1776 fn test_issue_3861() {
1777 let macro_fixture = parse_macro(
1779 macro_rules! rgb_color {
1780 ($p:expr, $t: ty) => {
1782 let _ = 0 as $t << $p;
1789 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1793 fn test_repeat_bad_var() {
1794 // FIXME: the second rule of the macro should be removed and an error about
1795 // `$( $c )+` raised
1799 ($( $b:ident )+) => {
1802 ($( $b:ident )+) => {
1808 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1812 fn test_no_space_after_semi_colon() {
1813 let expanded = parse_macro(
1815 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1818 .expand_items(r#"with_std! {mod m;mod f;}"#);
1820 let dump = format!("{:#?}", expanded);
1823 r###"MACRO_ITEMS@0..52
1834 IDENT@6..13 "feature"
1836 STRING@14..19 "\"std\""
1842 SEMICOLON@25..26 ";"
1853 IDENT@32..39 "feature"
1855 STRING@40..45 "\"std\""
1861 SEMICOLON@51..52 ";""###,
1865 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1867 fn test_rustc_issue_57597() {
1868 fn test_error(fixture: &str) {
1869 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmtpyTokenTree);
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 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
1876 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
1877 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
1878 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
1879 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1880 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1881 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1882 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1883 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1887 fn test_expand_bad_literal() {
1890 macro_rules! foo { ($i:literal) => {}; }
1893 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1897 fn test_empty_comments() {
1900 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1904 r#"one_arg_macro!(/**/)"#,
1905 &ExpandError::BindingError("expected Expr".into()),