3 use ::parser::FragmentKind;
5 ast, AstNode, NodeOrToken,
6 SyntaxKind::{ERROR, IDENT},
7 SyntaxNode, WalkEvent, T,
9 use test_utils::{assert_eq_text, mark};
14 use syntax::{ast, AstNode};
16 use crate::ast_to_token_tree;
21 fn test_valid_arms() {
22 fn check(macro_body: &str) {
23 let m = parse_macro_arm(macro_body);
27 check("($i:ident) => ()");
28 check("($($i:ident)*) => ($_)");
29 check("($($true:ident)*) => ($true)");
30 check("($($false:ident)*) => ($false)");
35 fn test_invalid_arms() {
36 fn check(macro_body: &str, err: ParseError) {
37 let m = parse_macro_arm(macro_body);
38 assert_eq!(m, Err(err.into()));
40 check("invalid", ParseError::Expected("expected subtree".into()));
42 check("$i:ident => ()", ParseError::Expected("expected subtree".into()));
43 check("($i:ident) ()", ParseError::Expected("expected `=`".into()));
44 check("($($i:ident)_) => ()", ParseError::InvalidRepeat);
46 check("($i) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
47 check("($i:) => ($i)", ParseError::UnexpectedToken("bad fragment specifier 1".into()));
50 fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
51 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
52 let source_file = ast::SourceFile::parse(¯o_definition).ok().unwrap();
53 let macro_definition =
54 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
56 let (definition_tt, _) =
57 ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
58 crate::MacroRules::parse(&definition_tt)
62 // Good first issue (although a slightly challenging one):
64 // * Pick a random test from here
65 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
66 // * Port the test to rust and add it to this module
70 fn test_token_id_shift() {
71 let expansion = parse_macro(
74 ($e:ident) => { foo bar $e }
78 .expand_tt("foobar!(baz);");
80 fn get_id(t: &tt::TokenTree) -> Option<u32> {
81 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
82 return Some(ident.id.0);
87 assert_eq!(expansion.token_trees.len(), 3);
88 // {($e:ident) => { foo bar $e }}
90 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
91 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
93 // The input args of macro call include parentheses:
95 // So baz should be 12+1+1
96 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
100 fn test_token_map() {
101 let expanded = parse_macro(
103 macro_rules! foobar {
104 ($e:ident) => { fn $e() {} }
108 .expand_tt("foobar!(baz);");
110 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
111 let content = node.syntax_node().to_string();
113 let get_text = |id, kind| -> String {
114 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
117 assert_eq!(expanded.token_trees.len(), 4);
118 // {($e:ident) => { fn $e() {} }}
119 // 012345 67 8 9 T12 3
121 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
122 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
123 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
127 fn test_convert_tt() {
129 macro_rules! impl_froms {
130 ($e:ident: $($v:ident),*) => {
132 impl From<$v> for $e {
133 fn from(it: $v) -> $e {
142 "impl_froms!(TokenTree: Leaf, Subtree);",
143 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
144 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
149 fn test_convert_tt2() {
152 macro_rules! impl_froms {
153 ($e:ident: $($v:ident),*) => {
155 impl From<$v> for $e {
156 fn from(it: $v) -> $e {
166 "impl_froms!(TokenTree: Leaf, Subtree);",
222 fn test_lifetime_split() {
226 ($($t:tt)*) => { $($t)*}
231 r#"foo!(static bar: &'static str = "hello";);"#,
249 fn test_expr_order() {
250 let expanded = parse_macro(
254 fn bar() { $ i * 2; }
259 .expand_items("foo! { 1 + 1}");
261 let dump = format!("{:#?}", expanded);
280 INT_NUMBER@10..11 "1"
283 INT_NUMBER@12..13 "2"
285 R_CURLY@14..15 "}""#,
291 fn test_fail_match_pattern_by_first_token() {
307 .assert_expand_items("foo! { foo }", "mod foo {}")
308 .assert_expand_items("foo! { = bar }", "fn bar () {}")
309 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
313 fn test_fail_match_pattern_by_last_token() {
329 .assert_expand_items("foo! { foo }", "mod foo {}")
330 .assert_expand_items("foo! { bar = }", "fn bar () {}")
331 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
335 fn test_fail_match_pattern_by_word_token() {
342 (spam $ i:ident) => (
345 (eggs $ i:ident) => (
351 .assert_expand_items("foo! { foo }", "mod foo {}")
352 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
353 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
357 fn test_match_group_pattern_by_separator_token() {
361 ($ ($ i:ident),*) => ($ (
364 ($ ($ i:ident)#*) => ($ (
367 ($ i:ident ,# $ j:ident) => (
374 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
375 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
376 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
380 fn test_match_group_pattern_with_multiple_defs() {
384 ($ ($ i:ident),*) => ( struct Bar { $ (
390 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
394 fn test_match_group_pattern_with_multiple_statement() {
398 ($ ($ i:ident),*) => ( fn baz { $ (
404 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
408 fn test_match_group_pattern_with_multiple_statement_without_semi() {
412 ($ ($ i:ident),*) => ( fn baz { $ (
418 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
422 fn test_match_group_empty_fixed_token() {
426 ($ ($ i:ident)* #abc) => ( fn baz { $ (
432 .assert_expand_items("foo! {#abc}", "fn baz {}");
436 fn test_match_group_in_subtree() {
440 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
445 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
449 fn test_match_group_with_multichar_sep() {
453 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
456 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
460 fn test_match_group_zero_match() {
464 ( $($i:ident)* ) => ();
467 .assert_expand_items("foo! ();", "");
471 fn test_match_group_in_group() {
475 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
478 .assert_expand_items("foo! ( (a b) );", "(a b)");
482 fn test_expand_to_item_list() {
483 let tree = parse_macro(
485 macro_rules! structs {
487 $(struct $i { field: u32 } )*
492 .expand_items("structs!(Foo, Bar);");
494 format!("{:#?}", tree).trim(),
498 STRUCT_KW@0..6 "struct"
501 RECORD_FIELD_LIST@9..20
514 STRUCT_KW@20..26 "struct"
517 RECORD_FIELD_LIST@29..40
533 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
534 if let tt::TokenTree::Subtree(subtree) = tt {
537 unreachable!("It is not a subtree");
539 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
540 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
543 unreachable!("It is not a literal");
546 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
547 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
550 unreachable!("It is not a Punct");
554 fn test_expand_literals_to_token_tree() {
555 let expansion = parse_macro(
557 macro_rules! literals {
569 .expand_tt("literals!(foo);");
570 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
572 // [let] [a] [=] ['c'] [;]
573 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
574 // [let] [c] [=] [1000] [;]
575 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
576 // [let] [f] [=] [12E+99_f64] [;]
577 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
578 // [let] [s] [=] ["rust1"] [;]
579 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
583 fn test_attr_to_token_tree() {
584 let expansion = parse_to_token_tree_by_syntax(
591 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
593 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
594 Some(tt::DelimiterKind::Bracket)
599 fn test_two_idents() {
603 ($ i:ident, $ j:ident) => {
604 fn foo() { let a = $ i; let b = $j; }
609 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
613 fn test_tt_to_stmts() {
614 let stmts = parse_macro(
625 .expand_statements("foo!{}");
628 format!("{:#?}", stmts).trim(),
649 INT_NUMBER@9..11 "10"
652 INT_NUMBER@12..13 "1"
664 fn test_match_literal() {
674 .assert_expand_items("foo! ['('];", "fn foo () {}");
678 fn test_parse_macro_def_simple() {
679 mark::check!(parse_macro_def_simple);
683 macro foo($id:ident) {
688 .assert_expand_items("foo!(bar);", "fn bar () {}");
692 fn test_parse_macro_def_rules() {
693 mark::check!(parse_macro_def_rules);
704 .assert_expand_items("foo!(bar);", "fn bar () {}");
707 // The following tests are port from intellij-rust directly
708 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
716 fn foo() { let a = $ i; }
721 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
722 .assert_expand_items(
723 "foo! { bar::<u8>::baz::<u8> }",
724 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
729 fn test_two_paths() {
733 ($ i:path, $ j:path) => {
734 fn foo() { let a = $ i; let b = $j; }
739 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
743 fn test_path_with_path() {
748 fn foo() { let a = $ i :: bar; }
753 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
767 .assert_expand_items(
768 "foo! { 2 + 2 * baz(3).quux() }",
769 "fn bar () {2 + 2 * baz (3) . quux () ;}",
774 fn test_last_expr() {
778 ($($item:expr),*) => {
780 let mut v = Vec::new();
790 .assert_expand_items(
792 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
797 fn test_expr_with_attr() {
805 .assert_expand_items("m!(#[allow(a)]())", "0");
814 fn bar() -> $ i { unimplemented!() }
819 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
823 fn test_ty_with_complex_type() {
828 fn bar() -> $ i { unimplemented!() }
833 // Reference lifetime struct with generic type
834 .assert_expand_items(
835 "foo! { &'a Baz<u8> }",
836 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
838 // extern "Rust" func type
839 .assert_expand_items(
840 r#"foo! { extern "Rust" fn() -> Ret }"#,
841 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
850 ($ i:pat) => { fn foo() { let $ i; } }
854 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
868 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
869 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
873 fn test_single_item() {
883 .assert_expand_items("foo! {mod c {}}", "mod c {}");
887 fn test_all_items() {
891 ($ ($ i:item)*) => ($ (
915 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 ;"#,
924 ($ i:block) => { fn foo() $ i }
928 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
943 .assert_expand_items(
944 r#"foo! { cfg(target_os = "windows") }"#,
945 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
950 fn test_meta_doc_comments() {
954 ($(#[$ i:meta])+) => (
963 /// Single Line Doc 1
968 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
977 ($ i:tt) => { fn foo() $ i }
981 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
989 ($($ i:tt)*) => { $($ i)* }
993 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
997 fn test_tt_composite() {
1005 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1009 fn test_tt_composite2() {
1010 let node = parse_macro(
1013 ($($tt:tt)*) => { abs!(=> $($tt)*) }
1017 .expand_items(r#"foo!{#}"#);
1019 let res = format!("{:#?}", &node);
1021 r###"MACRO_ITEMS@0..10
1034 R_PAREN@9..10 ")""###,
1040 fn test_tt_with_composite_without_space() {
1044 ($ op:tt, $j:path) => (
1050 // Test macro input without any spaces
1051 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
1052 .assert_expand_items("foo!(==,Foo::Bool)", "0");
1056 fn test_underscore() {
1064 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1068 fn test_underscore_not_greedily() {
1072 ($($a:ident)* _) => {0};
1076 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
1077 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
1082 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
1086 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
1087 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
1091 fn test_underscore_as_type() {
1099 // Underscore is a type
1100 .assert_expand_items(r#"q![_]"#, r#"0"#);
1104 fn test_vertical_bar_with_pat() {
1108 (| $pat:pat | ) => { 0 }
1112 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1116 fn test_dollar_crate_lhs_is_not_meta() {
1125 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1129 fn test_lifetime() {
1133 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1137 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1145 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1149 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1154 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1158 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1162 fn test_boolean_is_ident() {
1166 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1171 r#"foo!(true,false);"#,
1196 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1200 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1201 // test optional cases
1202 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1206 fn test_inner_macro_rules() {
1210 ($a:ident, $b:ident, $c:tt) => {
1224 assert_expand_items(
1226 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1231 fn test_expr_after_path_colons() {
1232 assert!(parse_macro(
1241 .expand_statements(r#"m!(C("0"))"#)
1243 .find(|token| token.kind() == ERROR)
1247 // The following tests are based on real world situations
1250 let fixture = parse_macro(
1253 ($($item:expr),*) => {
1255 let mut v = Vec::new();
1266 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1267 .assert_expand_items(
1269 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1272 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1275 format!("{:#?}", tree).trim(),
1299 SEMICOLON@19..20 ";"
1301 METHOD_CALL_EXPR@20..32
1313 INT_NUMBER@27..31 "1u32"
1315 SEMICOLON@32..33 ";"
1317 METHOD_CALL_EXPR@33..42
1329 INT_NUMBER@40..41 "2"
1331 SEMICOLON@42..43 ";"
1337 R_CURLY@44..45 "}""#
1342 fn test_winapi_struct() {
1343 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1347 macro_rules! STRUCT {
1348 ($(#[$attrs:meta])* struct $name:ident {
1349 $($field:ident: $ftype:ty,)+
1351 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1353 $(pub $field: $ftype,)+
1355 impl Clone for $name {
1357 fn clone(&self) -> $name { *self }
1359 #[cfg(feature = "impl-default")]
1360 impl Default for $name {
1362 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1368 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1369 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1370 "# [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 ()}}}"
1372 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1373 "# [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 ()}}}"
1378 fn test_int_base() {
1381 macro_rules! int_base {
1382 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl fmt::$Trait for $T {
1385 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1386 $Radix.fmt_int(*self as $U, f)
1392 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1393 "# [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)}}"
1398 fn test_generate_pattern_iterators() {
1399 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1402 macro_rules! generate_pattern_iterators {
1403 { double ended; with $(#[$common_stability_attribute:meta])*,
1404 $forward_iterator:ident,
1405 $reverse_iterator:ident, $iterty:ty
1411 ).assert_expand_items(
1412 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1418 fn test_impl_fn_for_zst() {
1419 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1422 macro_rules! impl_fn_for_zst {
1423 { $( $( #[$attr: meta] )*
1424 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1425 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1432 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1434 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1439 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1441 extern "rust-call" fn call_mut(
1443 ($( $arg, )*): ($( $ArgTy, )*)
1445 Fn::call(&*self, ($( $arg, )*))
1449 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1450 type Output = $ReturnTy;
1453 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1454 Fn::call(&self, ($( $arg, )*))
1461 ).assert_expand_items(r#"
1463 # [ derive ( Clone ) ]
1464 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1465 c . escape_debug_ext ( false )
1468 # [ derive ( Clone ) ]
1469 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1470 c . escape_unicode ( )
1472 # [ derive ( Clone ) ]
1473 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1474 c . escape_default ( )
1478 "# [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 ,))}}"
1483 fn test_impl_nonzero_fmt() {
1484 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1487 macro_rules! impl_nonzero_fmt {
1488 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1493 ).assert_expand_items(
1494 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1500 fn test_cfg_if_items() {
1501 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1504 macro_rules! __cfg_if_items {
1505 (($($not:meta,)*) ; ) => {};
1506 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1507 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1511 ).assert_expand_items(
1512 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 ; ) ) , }"#,
1513 "__cfg_if_items ! {(rustdoc ,) ;}",
1518 fn test_cfg_if_main() {
1519 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1522 macro_rules! cfg_if {
1524 if #[cfg($($meta:meta),*)] { $($it:item)* }
1530 $( ( ($($meta),*) ($($it)*) ), )*
1535 // Internal macro to Apply a cfg attribute to a list of items
1536 (@__apply $m:meta, $($it:item)*) => {
1541 ).assert_expand_items(r#"
1543 if # [ cfg ( target_env = "msvc" ) ] {
1544 // no extra unwinder support needed
1545 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1546 // no unwinder on the system!
1549 pub use libunwind :: * ;
1553 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1554 ).assert_expand_items(
1556 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1563 fn test_proptest_arbitrary() {
1564 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1567 macro_rules! arbitrary {
1568 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1569 $args: ident => $logic: expr) => {
1570 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1571 type Parameters = $params;
1572 type Strategy = $strat;
1573 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1580 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1582 VecStrategy < A :: Strategy > ,
1583 RangedParams1 < A :: Parameters > ;
1584 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1586 "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)}}}"
1591 fn test_old_ridl() {
1592 // This is from winapi 2.8, which do not have a link from github
1594 let expanded = parse_macro(
1598 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1600 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1604 $(pub unsafe fn $method(&mut self) -> $rtr {
1605 ((*self.lpVtbl).$method)(self $(,$p)*)
1611 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1612 fn GetDataSize(&mut self) -> UINT
1615 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1619 fn test_quick_error() {
1620 let expanded = parse_macro(
1622 macro_rules! quick_error {
1624 (SORT [enum $name:ident $( #[$meta:meta] )*]
1625 items [$($( #[$imeta:meta] )*
1626 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1627 {$( $ifuncs:tt )*} )* ]
1631 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1636 $iitem: $imode [$( $ivar: $ityp ),*]
1646 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1648 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1649 ] buf [] queue []) ;
1653 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1657 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1660 macro_rules! delegate_impl {
1661 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1662 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1664 // "Escaped" associated types. Stripped before making the `trait`
1665 // itself, but forwarded when delegating impls.
1667 @escape [type $assoc_name_ext:ident]
1668 // Associated types. Forwarded.
1673 $(#[$_assoc_attr:meta])*
1674 type $assoc_name:ident $(: $assoc_bound:ty)*;
1677 // Methods. Forwarded. Using $self_map!(self) around the self argument.
1678 // Methods must use receiver `self` or explicit type like `self: &Self`
1679 // &self and &mut self are _not_ supported.
1683 $(#[$_method_attr:meta])*
1684 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1687 // Arbitrary tail that is ignored when forwarding.
1693 impl<> $name for $self_wrap where $self_type: $name {
1696 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1697 $self_map!(self).$method_name($($marg),*)
1705 ).assert_expand_items(
1706 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1707 "impl <> Data for & \'a mut G where G : Data {}",
1712 fn expr_interpolation() {
1713 let expanded = parse_macro(
1722 .expand_expr("id!(x + foo);");
1724 assert_eq!(expanded.to_string(), "map(x+foo)");
1727 pub(crate) struct MacroFixture {
1731 pub(crate) struct MacroFixture2 {
1735 macro_rules! impl_fixture {
1738 pub(crate) fn expand_tt(&self, invocation: &str) -> tt::Subtree {
1739 self.try_expand_tt(invocation).unwrap()
1742 fn try_expand_tt(&self, invocation: &str) -> Result<tt::Subtree, ExpandError> {
1743 let source_file = ast::SourceFile::parse(invocation).tree();
1744 let macro_invocation =
1745 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
1747 let (invocation_tt, _) = ast_to_token_tree(¯o_invocation.token_tree().unwrap())
1748 .ok_or_else(|| ExpandError::ConversionError)?;
1750 self.rules.expand(&invocation_tt).result()
1754 fn assert_expand_err(&self, invocation: &str, err: &ExpandError) {
1755 assert_eq!(self.try_expand_tt(invocation).as_ref(), Err(err));
1759 fn expand_items(&self, invocation: &str) -> SyntaxNode {
1760 let expanded = self.expand_tt(invocation);
1761 token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node()
1765 fn expand_statements(&self, invocation: &str) -> SyntaxNode {
1766 let expanded = self.expand_tt(invocation);
1767 token_tree_to_syntax_node(&expanded, FragmentKind::Statements)
1774 fn expand_expr(&self, invocation: &str) -> SyntaxNode {
1775 let expanded = self.expand_tt(invocation);
1776 token_tree_to_syntax_node(&expanded, FragmentKind::Expr).unwrap().0.syntax_node()
1780 fn assert_expand_tt(&self, invocation: &str, expected: &str) {
1781 let expansion = self.expand_tt(invocation);
1782 assert_eq!(expansion.to_string(), expected);
1786 fn assert_expand(&self, invocation: &str, expected: &str) {
1787 let expansion = self.expand_tt(invocation);
1788 let actual = format!("{:?}", expansion);
1789 test_utils::assert_eq_text!(&expected.trim(), &actual.trim());
1792 fn assert_expand_items(&self, invocation: &str, expected: &str) -> &$name {
1793 self.assert_expansion(FragmentKind::Items, invocation, expected);
1798 fn assert_expand_statements(&self, invocation: &str, expected: &str) -> &$name {
1799 self.assert_expansion(FragmentKind::Statements, invocation, expected);
1803 fn assert_expansion(&self, kind: FragmentKind, invocation: &str, expected: &str) {
1804 let expanded = self.expand_tt(invocation);
1805 assert_eq!(expanded.to_string(), expected);
1807 let expected = expected.replace("$crate", "C_C__C");
1809 // wrap the given text to a macro call
1811 let wrapped = format!("wrap_macro!( {} )", expected);
1812 let wrapped = ast::SourceFile::parse(&wrapped);
1813 let wrapped = wrapped
1817 .find_map(ast::TokenTree::cast)
1819 let mut wrapped = ast_to_token_tree(&wrapped).unwrap().0;
1820 wrapped.delimiter = None;
1825 token_tree_to_syntax_node(&expanded, kind).unwrap().0.syntax_node();
1826 let expanded_tree = debug_dump_ignore_spaces(&expanded_tree).trim().to_string();
1829 token_tree_to_syntax_node(&expected, kind).unwrap().0.syntax_node();
1830 let expected_tree = debug_dump_ignore_spaces(&expected_tree).trim().to_string();
1832 let expected_tree = expected_tree.replace("C_C__C", "$crate");
1834 expanded_tree, expected_tree,
1835 "\nleft:\n{}\nright:\n{}",
1836 expanded_tree, expected_tree,
1843 impl_fixture!(MacroFixture);
1844 impl_fixture!(MacroFixture2);
1846 fn parse_macro_rules_to_tt(ra_fixture: &str) -> tt::Subtree {
1847 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1848 let macro_definition =
1849 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
1851 let (definition_tt, _) = ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
1853 let parsed = parse_to_token_tree(
1854 &ra_fixture[macro_definition.token_tree().unwrap().syntax().text_range()],
1858 assert_eq!(definition_tt, parsed);
1863 fn parse_macro_def_to_tt(ra_fixture: &str) -> tt::Subtree {
1864 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1865 let macro_definition =
1866 source_file.syntax().descendants().find_map(ast::MacroDef::cast).unwrap();
1868 let (definition_tt, _) = ast_to_token_tree(¯o_definition.body().unwrap()).unwrap();
1871 parse_to_token_tree(&ra_fixture[macro_definition.body().unwrap().syntax().text_range()])
1874 assert_eq!(definition_tt, parsed);
1879 pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
1880 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1881 let rules = MacroRules::parse(&definition_tt).unwrap();
1882 MacroFixture { rules }
1885 pub(crate) fn parse_macro2(ra_fixture: &str) -> MacroFixture2 {
1886 let definition_tt = parse_macro_def_to_tt(ra_fixture);
1887 let rules = MacroDef::parse(&definition_tt).unwrap();
1888 MacroFixture2 { rules }
1891 pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
1892 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1894 match MacroRules::parse(&definition_tt) {
1895 Ok(_) => panic!("Expect error"),
1900 pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
1901 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1902 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
1904 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
1905 assert_eq!(tt, parsed);
1910 fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String {
1912 let mut buf = String::new();
1913 macro_rules! indent {
1921 for event in node.preorder_with_tokens() {
1923 WalkEvent::Enter(element) => {
1925 NodeOrToken::Node(node) => {
1927 writeln!(buf, "{:?}", node.kind()).unwrap();
1929 NodeOrToken::Token(token) => match token.kind() {
1930 syntax::SyntaxKind::WHITESPACE => {}
1933 writeln!(buf, "{:?}", token.kind()).unwrap();
1939 WalkEvent::Leave(_) => level -= 1,
1947 fn test_issue_2520() {
1948 let macro_fixture = parse_macro(
1950 macro_rules! my_macro {
1953 $( [] $sname:ident : $stype:ty )?
1954 $( [$expr:expr] $nname:ident : $ntype:ty )?
1967 macro_fixture.assert_expand_items(
1969 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1976 fn test_issue_3861() {
1977 let macro_fixture = parse_macro(
1979 macro_rules! rgb_color {
1980 ($p:expr, $t: ty) => {
1982 let _ = 0 as $t << $p;
1989 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1993 fn test_repeat_bad_var() {
1994 // FIXME: the second rule of the macro should be removed and an error about
1995 // `$( $c )+` raised
1999 ($( $b:ident )+) => {
2002 ($( $b:ident )+) => {
2008 .assert_expand_items("foo!(b0 b1);", "b0 b1");
2012 fn test_no_space_after_semi_colon() {
2013 let expanded = parse_macro(
2015 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
2018 .expand_items(r#"with_std! {mod m;mod f;}"#);
2020 let dump = format!("{:#?}", expanded);
2022 r###"MACRO_ITEMS@0..52
2033 IDENT@6..13 "feature"
2035 STRING@14..19 "\"std\""
2041 SEMICOLON@25..26 ";"
2052 IDENT@32..39 "feature"
2054 STRING@40..45 "\"std\""
2060 SEMICOLON@51..52 ";""###,
2065 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
2067 fn test_rustc_issue_57597() {
2068 fn test_error(fixture: &str) {
2069 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
2072 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
2073 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
2074 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
2075 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
2076 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
2077 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
2078 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
2079 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
2080 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
2081 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
2082 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
2083 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
2087 fn test_expand_bad_literal() {
2090 macro_rules! foo { ($i:literal) => {}; }
2093 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
2097 fn test_empty_comments() {
2100 macro_rules! one_arg_macro { ($fmt:expr) => (); }
2104 r#"one_arg_macro!(/**/)"#,
2105 &ExpandError::BindingError("expected Expr".into()),