3 use ra_parser::FragmentKind;
4 use ra_syntax::{ast, AstNode, NodeOrToken, SyntaxKind::IDENT, SyntaxNode, WalkEvent, T};
5 use test_utils::assert_eq_text;
10 use ra_syntax::{ast, AstNode};
13 use crate::ast_to_token_tree;
16 fn test_valid_arms() {
17 fn check(macro_body: &str) {
18 let m = parse_macro_arm(macro_body);
22 check("($i:ident) => ()");
23 check("($($i:ident)*) => ($_)");
24 check("($($true:ident)*) => ($true)");
25 check("($($false:ident)*) => ($false)");
30 fn test_invalid_arms() {
31 fn check(macro_body: &str, err: &str) {
32 let m = parse_macro_arm(macro_body);
33 assert_eq!(m, Err(ParseError::Expected(String::from(err))));
36 check("invalid", "expected subtree");
38 check("$i:ident => ()", "expected subtree");
39 check("($i:ident) ()", "expected `=`");
40 check("($($i:ident)_) => ()", "invalid repeat");
42 check("($i) => ($i)", "invalid macro definition");
43 check("($i:) => ($i)", "invalid macro definition");
46 fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
47 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
48 let source_file = ast::SourceFile::parse(¯o_definition).ok().unwrap();
49 let macro_definition =
50 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
52 let (definition_tt, _) =
53 ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
54 crate::MacroRules::parse(&definition_tt)
58 // Good first issue (although a slightly challenging one):
60 // * Pick a random test from here
61 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
62 // * Port the test to rust and add it to this module
66 fn test_token_id_shift() {
67 let expansion = parse_macro(
70 ($e:ident) => { foo bar $e }
74 .expand_tt("foobar!(baz);");
76 fn get_id(t: &tt::TokenTree) -> Option<u32> {
77 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
78 return Some(ident.id.0);
83 assert_eq!(expansion.token_trees.len(), 3);
84 // {($e:ident) => { foo bar $e }}
86 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
87 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
89 // The input args of macro call include parentheses:
91 // So baz should be 12+1+1
92 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
97 let expanded = parse_macro(
100 ($e:ident) => { fn $e() {} }
104 .expand_tt("foobar!(baz);");
106 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
107 let content = node.syntax_node().to_string();
109 let get_text = |id, kind| -> String {
110 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
113 assert_eq!(expanded.token_trees.len(), 4);
114 // {($e:ident) => { fn $e() {} }}
115 // 012345 67 8 9 T12 3
117 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
118 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
119 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
123 fn test_convert_tt() {
125 macro_rules! impl_froms {
126 ($e:ident: $($v:ident),*) => {
128 impl From<$v> for $e {
129 fn from(it: $v) -> $e {
138 "impl_froms!(TokenTree: Leaf, Subtree);",
139 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
140 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
145 fn test_convert_tt2() {
148 macro_rules! impl_froms {
149 ($e:ident: $($v:ident),*) => {
151 impl From<$v> for $e {
152 fn from(it: $v) -> $e {
162 "impl_froms!(TokenTree: Leaf, Subtree);",
218 fn test_lifetime_split() {
222 ($($t:tt)*) => { $($t)*}
227 r#"foo!(static bar: &'static str = "hello";);"#,
245 fn test_expr_order() {
246 let expanded = parse_macro(
250 fn bar() { $ i * 2; }
255 .expand_items("foo! { 1 + 1}");
257 let dump = format!("{:#?}", expanded);
277 INT_NUMBER@10..11 "1"
280 INT_NUMBER@12..13 "2"
282 R_CURLY@14..15 "}""#,
287 fn test_fail_match_pattern_by_first_token() {
303 .assert_expand_items("foo! { foo }", "mod foo {}")
304 .assert_expand_items("foo! { = bar }", "fn bar () {}")
305 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
309 fn test_fail_match_pattern_by_last_token() {
325 .assert_expand_items("foo! { foo }", "mod foo {}")
326 .assert_expand_items("foo! { bar = }", "fn bar () {}")
327 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
331 fn test_fail_match_pattern_by_word_token() {
338 (spam $ i:ident) => (
341 (eggs $ i:ident) => (
347 .assert_expand_items("foo! { foo }", "mod foo {}")
348 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
349 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
353 fn test_match_group_pattern_by_separator_token() {
357 ($ ($ i:ident),*) => ($ (
360 ($ ($ i:ident)#*) => ($ (
363 ($ i:ident ,# $ j:ident) => (
370 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
371 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
372 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
376 fn test_match_group_pattern_with_multiple_defs() {
380 ($ ($ i:ident),*) => ( struct Bar { $ (
386 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
390 fn test_match_group_pattern_with_multiple_statement() {
394 ($ ($ i:ident),*) => ( fn baz { $ (
400 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
404 fn test_match_group_pattern_with_multiple_statement_without_semi() {
408 ($ ($ i:ident),*) => ( fn baz { $ (
414 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
418 fn test_match_group_empty_fixed_token() {
422 ($ ($ i:ident)* #abc) => ( fn baz { $ (
428 .assert_expand_items("foo! {#abc}", "fn baz {}");
432 fn test_match_group_in_subtree() {
436 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
441 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
445 fn test_match_group_with_multichar_sep() {
449 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
452 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
456 fn test_match_group_zero_match() {
460 ( $($i:ident)* ) => ();
463 .assert_expand_items("foo! ();", "");
467 fn test_match_group_in_group() {
471 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
474 .assert_expand_items("foo! ( (a b) );", "(a b)");
478 fn test_expand_to_item_list() {
479 let tree = parse_macro(
481 macro_rules! structs {
483 $(struct $i { field: u32 } )*
488 .expand_items("structs!(Foo, Bar);");
490 format!("{:#?}", tree).trim(),
494 STRUCT_KW@0..6 "struct"
497 RECORD_FIELD_LIST@9..20
510 STRUCT_KW@20..26 "struct"
513 RECORD_FIELD_LIST@29..40
529 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
530 if let tt::TokenTree::Subtree(subtree) = tt {
533 unreachable!("It is not a subtree");
535 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
536 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
539 unreachable!("It is not a literal");
542 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
543 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
546 unreachable!("It is not a Punct");
550 fn test_expand_literals_to_token_tree() {
551 let expansion = parse_macro(
553 macro_rules! literals {
565 .expand_tt("literals!(foo);");
566 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
568 // [let] [a] [=] ['c'] [;]
569 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
570 // [let] [c] [=] [1000] [;]
571 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
572 // [let] [f] [=] [12E+99_f64] [;]
573 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
574 // [let] [s] [=] ["rust1"] [;]
575 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
579 fn test_attr_to_token_tree() {
580 let expansion = parse_to_token_tree_by_syntax(
587 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
589 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
590 Some(tt::DelimiterKind::Bracket)
595 fn test_two_idents() {
599 ($ i:ident, $ j:ident) => {
600 fn foo() { let a = $ i; let b = $j; }
605 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
609 fn test_tt_to_stmts() {
610 let stmts = parse_macro(
621 .expand_statements("foo!{}");
624 format!("{:#?}", stmts).trim(),
645 INT_NUMBER@9..11 "10"
648 INT_NUMBER@12..13 "1"
660 fn test_match_literal() {
670 .assert_expand_items("foo! ['('];", "fn foo () {}");
673 // The following tests are port from intellij-rust directly
674 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
682 fn foo() { let a = $ i; }
687 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
688 .assert_expand_items(
689 "foo! { bar::<u8>::baz::<u8> }",
690 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
695 fn test_two_paths() {
699 ($ i:path, $ j:path) => {
700 fn foo() { let a = $ i; let b = $j; }
705 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
709 fn test_path_with_path() {
714 fn foo() { let a = $ i :: bar; }
719 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
733 .assert_expand_items(
734 "foo! { 2 + 2 * baz(3).quux() }",
735 "fn bar () {2 + 2 * baz (3) . quux () ;}",
740 fn test_last_expr() {
744 ($($item:expr),*) => {
746 let mut v = Vec::new();
756 .assert_expand_items(
758 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
768 fn bar() -> $ i { unimplemented!() }
773 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
777 fn test_ty_with_complex_type() {
782 fn bar() -> $ i { unimplemented!() }
787 // Reference lifetime struct with generic type
788 .assert_expand_items(
789 "foo! { &'a Baz<u8> }",
790 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
792 // extern "Rust" func type
793 .assert_expand_items(
794 r#"foo! { extern "Rust" fn() -> Ret }"#,
795 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
804 ($ i:pat) => { fn foo() { let $ i; } }
808 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
822 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
823 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
827 fn test_single_item() {
837 .assert_expand_items("foo! {mod c {}}", "mod c {}");
841 fn test_all_items() {
845 ($ ($ i:item)*) => ($ (
869 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 ;"#,
878 ($ i:block) => { fn foo() $ i }
882 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
897 .assert_expand_items(
898 r#"foo! { cfg(target_os = "windows") }"#,
899 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
904 fn test_meta_doc_comments() {
908 ($(#[$ i:meta])+) => (
917 /// Single Line Doc 1
922 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
931 ($ i:tt) => { fn foo() $ i }
935 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
943 ($($ i:tt)*) => { $($ i)* }
947 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
951 fn test_tt_composite() {
959 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
963 fn test_tt_composite2() {
964 let node = parse_macro(
967 ($($tt:tt)*) => { abs!(=> $($tt)*) }
971 .expand_items(r#"foo!{#}"#);
973 let res = format!("{:#?}", &node);
976 r###"MACRO_ITEMS@0..10
989 R_PAREN@9..10 ")""###
998 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1002 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1010 ($ type:ty $ lit:literal) => { const VALUE: $ type = $ lit;};
1014 .assert_expand_items(r#"foo!(u8 0);"#, r#"const VALUE : u8 = 0 ;"#);
1018 fn test_boolean_is_ident() {
1022 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1027 r#"foo!(true,false);"#,
1052 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1056 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1057 // test optional cases
1058 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1062 fn test_inner_macro_rules() {
1066 ($a:ident, $b:ident, $c:tt) => {
1080 assert_expand_items(
1082 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1086 // The following tests are based on real world situations
1089 let fixture = parse_macro(
1092 ($($item:expr),*) => {
1094 let mut v = Vec::new();
1105 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1106 .assert_expand_items(
1108 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1111 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1114 format!("{:#?}", tree).trim(),
1138 SEMICOLON@19..20 ";"
1140 METHOD_CALL_EXPR@20..32
1152 INT_NUMBER@27..31 "1u32"
1154 SEMICOLON@32..33 ";"
1156 METHOD_CALL_EXPR@33..42
1168 INT_NUMBER@40..41 "2"
1170 SEMICOLON@42..43 ";"
1176 R_CURLY@44..45 "}""#
1181 fn test_winapi_struct() {
1182 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1186 macro_rules! STRUCT {
1187 ($(#[$attrs:meta])* struct $name:ident {
1188 $($field:ident: $ftype:ty,)+
1190 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1192 $(pub $field: $ftype,)+
1194 impl Clone for $name {
1196 fn clone(&self) -> $name { *self }
1198 #[cfg(feature = "impl-default")]
1199 impl Default for $name {
1201 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1207 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1208 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1209 "# [repr (C)] # [derive (Copy)] pub struct D3DVSHADERCAPS2_0 {pub Caps : u8 ,} impl Clone for D3DVSHADERCAPS2_0 {# [inline] fn clone (& self) -> D3DVSHADERCAPS2_0 {* self}} # [cfg (feature = \"impl-default\")] impl Default for D3DVSHADERCAPS2_0 {# [inline] fn default () -> D3DVSHADERCAPS2_0 {unsafe {$crate :: _core :: mem :: zeroed ()}}}"
1211 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1212 "# [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 ()}}}"
1217 fn test_int_base() {
1220 macro_rules! int_base {
1221 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl fmt::$Trait for $T {
1224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225 $Radix.fmt_int(*self as $U, f)
1231 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1232 "# [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)}}"
1237 fn test_generate_pattern_iterators() {
1238 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1241 macro_rules! generate_pattern_iterators {
1242 { double ended; with $(#[$common_stability_attribute:meta])*,
1243 $forward_iterator:ident,
1244 $reverse_iterator:ident, $iterty:ty
1250 ).assert_expand_items(
1251 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1257 fn test_impl_fn_for_zst() {
1258 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1261 macro_rules! impl_fn_for_zst {
1262 { $( $( #[$attr: meta] )*
1263 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1264 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1271 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1273 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1278 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1280 extern "rust-call" fn call_mut(
1282 ($( $arg, )*): ($( $ArgTy, )*)
1284 Fn::call(&*self, ($( $arg, )*))
1288 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1289 type Output = $ReturnTy;
1292 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1293 Fn::call(&self, ($( $arg, )*))
1300 ).assert_expand_items(r#"
1302 # [ derive ( Clone ) ]
1303 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1304 c . escape_debug_ext ( false )
1307 # [ derive ( Clone ) ]
1308 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1309 c . escape_unicode ( )
1311 # [ derive ( Clone ) ]
1312 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1313 c . escape_default ( )
1317 "# [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 ,))}}"
1322 fn test_impl_nonzero_fmt() {
1323 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1326 macro_rules! impl_nonzero_fmt {
1327 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1332 ).assert_expand_items(
1333 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1339 fn test_cfg_if_items() {
1340 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1343 macro_rules! __cfg_if_items {
1344 (($($not:meta,)*) ; ) => {};
1345 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1346 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1350 ).assert_expand_items(
1351 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 ; ) ) , }"#,
1352 "__cfg_if_items ! {(rustdoc ,) ;}",
1357 fn test_cfg_if_main() {
1358 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1361 macro_rules! cfg_if {
1363 if #[cfg($($meta:meta),*)] { $($it:item)* }
1369 $( ( ($($meta),*) ($($it)*) ), )*
1374 // Internal macro to Apply a cfg attribute to a list of items
1375 (@__apply $m:meta, $($it:item)*) => {
1380 ).assert_expand_items(r#"
1382 if # [ cfg ( target_env = "msvc" ) ] {
1383 // no extra unwinder support needed
1384 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1385 // no unwinder on the system!
1388 pub use libunwind :: * ;
1392 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1393 ).assert_expand_items(
1395 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1402 fn test_proptest_arbitrary() {
1403 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1406 macro_rules! arbitrary {
1407 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1408 $args: ident => $logic: expr) => {
1409 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1410 type Parameters = $params;
1411 type Strategy = $strat;
1412 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1419 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1421 VecStrategy < A :: Strategy > ,
1422 RangedParams1 < A :: Parameters > ;
1423 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1425 "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)}}}"
1430 fn test_old_ridl() {
1431 // This is from winapi 2.8, which do not have a link from github
1433 let expanded = parse_macro(
1437 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1439 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1443 $(pub unsafe fn $method(&mut self) -> $rtr {
1444 ((*self.lpVtbl).$method)(self $(,$p)*)
1450 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1451 fn GetDataSize(&mut self) -> UINT
1454 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1458 fn test_quick_error() {
1459 let expanded = parse_macro(
1461 macro_rules! quick_error {
1463 (SORT [enum $name:ident $( #[$meta:meta] )*]
1464 items [$($( #[$imeta:meta] )*
1465 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1466 {$( $ifuncs:tt )*} )* ]
1470 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1475 $iitem: $imode [$( $ivar: $ityp ),*]
1485 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1487 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1488 ] buf [] queue []) ;
1492 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1496 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1499 macro_rules! delegate_impl {
1500 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1501 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1503 // "Escaped" associated types. Stripped before making the `trait`
1504 // itself, but forwarded when delegating impls.
1506 @escape [type $assoc_name_ext:ident]
1507 // Associated types. Forwarded.
1512 $(#[$_assoc_attr:meta])*
1513 type $assoc_name:ident $(: $assoc_bound:ty)*;
1516 // Methods. Forwarded. Using $self_map!(self) around the self argument.
1517 // Methods must use receiver `self` or explicit type like `self: &Self`
1518 // &self and &mut self are _not_ supported.
1522 $(#[$_method_attr:meta])*
1523 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1526 // Arbitrary tail that is ignored when forwarding.
1532 impl<> $name for $self_wrap where $self_type: $name {
1535 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1536 $self_map!(self).$method_name($($marg),*)
1544 ).assert_expand_items(
1545 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1546 "impl <> Data for & \'a mut G where G : Data {}",
1551 fn expr_interpolation() {
1552 let expanded = parse_macro(
1561 .expand_expr("id!(x + foo);");
1563 assert_eq!(expanded.to_string(), "map(x+foo)");
1566 pub(crate) struct MacroFixture {
1571 pub(crate) fn expand_tt(&self, invocation: &str) -> tt::Subtree {
1572 self.try_expand_tt(invocation).unwrap()
1575 fn try_expand_tt(&self, invocation: &str) -> Result<tt::Subtree, ExpandError> {
1576 let source_file = ast::SourceFile::parse(invocation).tree();
1577 let macro_invocation =
1578 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
1580 let (invocation_tt, _) = ast_to_token_tree(¯o_invocation.token_tree().unwrap())
1581 .ok_or_else(|| ExpandError::ConversionError)?;
1583 self.rules.expand(&invocation_tt).result()
1586 fn assert_expand_err(&self, invocation: &str, err: &ExpandError) {
1587 assert_eq!(self.try_expand_tt(invocation).as_ref(), Err(err));
1590 fn expand_items(&self, invocation: &str) -> SyntaxNode {
1591 let expanded = self.expand_tt(invocation);
1592 token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node()
1595 fn expand_statements(&self, invocation: &str) -> SyntaxNode {
1596 let expanded = self.expand_tt(invocation);
1597 token_tree_to_syntax_node(&expanded, FragmentKind::Statements).unwrap().0.syntax_node()
1600 fn expand_expr(&self, invocation: &str) -> SyntaxNode {
1601 let expanded = self.expand_tt(invocation);
1602 token_tree_to_syntax_node(&expanded, FragmentKind::Expr).unwrap().0.syntax_node()
1605 fn assert_expand_tt(&self, invocation: &str, expected: &str) {
1606 let expansion = self.expand_tt(invocation);
1607 assert_eq!(expansion.to_string(), expected);
1610 fn assert_expand(&self, invocation: &str, expected: &str) {
1611 let expansion = self.expand_tt(invocation);
1612 let actual = format!("{:?}", expansion);
1613 test_utils::assert_eq_text!(&actual.trim(), &expected.trim());
1616 fn assert_expand_items(&self, invocation: &str, expected: &str) -> &MacroFixture {
1617 self.assert_expansion(FragmentKind::Items, invocation, expected);
1621 fn assert_expand_statements(&self, invocation: &str, expected: &str) -> &MacroFixture {
1622 self.assert_expansion(FragmentKind::Statements, invocation, expected);
1626 fn assert_expansion(&self, kind: FragmentKind, invocation: &str, expected: &str) {
1627 let expanded = self.expand_tt(invocation);
1628 assert_eq!(expanded.to_string(), expected);
1630 let expected = expected.replace("$crate", "C_C__C");
1632 // wrap the given text to a macro call
1634 let wrapped = format!("wrap_macro!( {} )", expected);
1635 let wrapped = ast::SourceFile::parse(&wrapped);
1637 wrapped.tree().syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
1638 let mut wrapped = ast_to_token_tree(&wrapped).unwrap().0;
1639 wrapped.delimiter = None;
1643 let expanded_tree = token_tree_to_syntax_node(&expanded, kind).unwrap().0.syntax_node();
1644 let expanded_tree = debug_dump_ignore_spaces(&expanded_tree).trim().to_string();
1646 let expected_tree = token_tree_to_syntax_node(&expected, kind).unwrap().0.syntax_node();
1647 let expected_tree = debug_dump_ignore_spaces(&expected_tree).trim().to_string();
1649 let expected_tree = expected_tree.replace("C_C__C", "$crate");
1651 expanded_tree, expected_tree,
1652 "\nleft:\n{}\nright:\n{}",
1653 expanded_tree, expected_tree,
1658 fn parse_macro_to_tt(ra_fixture: &str) -> tt::Subtree {
1659 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1660 let macro_definition =
1661 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
1663 let (definition_tt, _) = ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
1665 let parsed = parse_to_token_tree(
1666 &ra_fixture[macro_definition.token_tree().unwrap().syntax().text_range()],
1670 assert_eq!(definition_tt, parsed);
1675 pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
1676 let definition_tt = parse_macro_to_tt(ra_fixture);
1677 let rules = MacroRules::parse(&definition_tt).unwrap();
1678 MacroFixture { rules }
1681 pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
1682 let definition_tt = parse_macro_to_tt(ra_fixture);
1684 match MacroRules::parse(&definition_tt) {
1685 Ok(_) => panic!("Expect error"),
1690 pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
1691 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1692 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
1694 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
1695 assert_eq!(tt, parsed);
1700 fn debug_dump_ignore_spaces(node: &ra_syntax::SyntaxNode) -> String {
1702 let mut buf = String::new();
1703 macro_rules! indent {
1711 for event in node.preorder_with_tokens() {
1713 WalkEvent::Enter(element) => {
1715 NodeOrToken::Node(node) => {
1717 writeln!(buf, "{:?}", node.kind()).unwrap();
1719 NodeOrToken::Token(token) => match token.kind() {
1720 ra_syntax::SyntaxKind::WHITESPACE => {}
1723 writeln!(buf, "{:?}", token.kind()).unwrap();
1729 WalkEvent::Leave(_) => level -= 1,
1737 fn test_issue_2520() {
1738 let macro_fixture = parse_macro(
1740 macro_rules! my_macro {
1743 $( [] $sname:ident : $stype:ty )?
1744 $( [$expr:expr] $nname:ident : $ntype:ty )?
1757 macro_fixture.assert_expand_items(
1759 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1766 fn test_issue_3861() {
1767 let macro_fixture = parse_macro(
1769 macro_rules! rgb_color {
1770 ($p:expr, $t: ty) => {
1772 let _ = 0 as $t << $p;
1779 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1783 fn test_repeat_bad_var() {
1784 // FIXME: the second rule of the macro should be removed and an error about
1785 // `$( $c )+` raised
1789 ($( $b:ident )+) => {
1792 ($( $b:ident )+) => {
1798 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1802 fn test_no_space_after_semi_colon() {
1803 let expanded = parse_macro(
1805 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1808 .expand_items(r#"with_std! {mod m;mod f;}"#);
1810 let dump = format!("{:#?}", expanded);
1813 r###"MACRO_ITEMS@0..52
1824 IDENT@6..13 "feature"
1826 STRING@14..19 "\"std\""
1832 SEMICOLON@25..26 ";"
1843 IDENT@32..39 "feature"
1845 STRING@40..45 "\"std\""
1851 SEMICOLON@51..52 ";""###,
1855 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1857 fn test_rustc_issue_57597() {
1858 fn test_error(fixture: &str) {
1859 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmtpyTokenTree);
1862 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
1863 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
1864 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
1865 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
1866 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
1867 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
1868 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
1869 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1870 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1871 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1872 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1873 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1877 fn test_expand_bad_literal() {
1880 macro_rules! foo { ($i:literal) => {}; }
1883 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1887 fn test_empty_comments() {
1890 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1894 r#"one_arg_macro!(/**/)"#,
1895 &ExpandError::BindingError("expected Expr".into()),