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: &str) {
37 let m = parse_macro_arm(macro_body);
38 assert_eq!(m, Err(ParseError::Expected(String::from(err))));
41 check("invalid", "expected subtree");
43 check("$i:ident => ()", "expected subtree");
44 check("($i:ident) ()", "expected `=`");
45 check("($($i:ident)_) => ()", "invalid repeat");
47 check("($i) => ($i)", "invalid macro definition");
48 check("($i:) => ($i)", "invalid macro definition");
51 fn parse_macro_arm(arm_definition: &str) -> Result<crate::MacroRules, ParseError> {
52 let macro_definition = format!(" macro_rules! m {{ {} }} ", arm_definition);
53 let source_file = ast::SourceFile::parse(¯o_definition).ok().unwrap();
54 let macro_definition =
55 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
57 let (definition_tt, _) =
58 ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
59 crate::MacroRules::parse(&definition_tt)
63 // Good first issue (although a slightly challenging one):
65 // * Pick a random test from here
66 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
67 // * Port the test to rust and add it to this module
71 fn test_token_id_shift() {
72 let expansion = parse_macro(
75 ($e:ident) => { foo bar $e }
79 .expand_tt("foobar!(baz);");
81 fn get_id(t: &tt::TokenTree) -> Option<u32> {
82 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
83 return Some(ident.id.0);
88 assert_eq!(expansion.token_trees.len(), 3);
89 // {($e:ident) => { foo bar $e }}
91 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
92 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
94 // The input args of macro call include parentheses:
96 // So baz should be 12+1+1
97 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
101 fn test_token_map() {
102 let expanded = parse_macro(
104 macro_rules! foobar {
105 ($e:ident) => { fn $e() {} }
109 .expand_tt("foobar!(baz);");
111 let (node, token_map) = token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap();
112 let content = node.syntax_node().to_string();
114 let get_text = |id, kind| -> String {
115 content[token_map.range_by_token(id).unwrap().by_kind(kind).unwrap()].to_string()
118 assert_eq!(expanded.token_trees.len(), 4);
119 // {($e:ident) => { fn $e() {} }}
120 // 012345 67 8 9 T12 3
122 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
123 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
124 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
128 fn test_convert_tt() {
130 macro_rules! impl_froms {
131 ($e:ident: $($v:ident),*) => {
133 impl From<$v> for $e {
134 fn from(it: $v) -> $e {
143 "impl_froms!(TokenTree: Leaf, Subtree);",
144 "impl From <Leaf > for TokenTree {fn from (it : Leaf) -> TokenTree {TokenTree ::Leaf (it)}} \
145 impl From <Subtree > for TokenTree {fn from (it : Subtree) -> TokenTree {TokenTree ::Subtree (it)}}"
150 fn test_convert_tt2() {
153 macro_rules! impl_froms {
154 ($e:ident: $($v:ident),*) => {
156 impl From<$v> for $e {
157 fn from(it: $v) -> $e {
167 "impl_froms!(TokenTree: Leaf, Subtree);",
223 fn test_lifetime_split() {
227 ($($t:tt)*) => { $($t)*}
232 r#"foo!(static bar: &'static str = "hello";);"#,
250 fn test_expr_order() {
251 let expanded = parse_macro(
255 fn bar() { $ i * 2; }
260 .expand_items("foo! { 1 + 1}");
262 let dump = format!("{:#?}", expanded);
281 INT_NUMBER@10..11 "1"
284 INT_NUMBER@12..13 "2"
286 R_CURLY@14..15 "}""#,
292 fn test_fail_match_pattern_by_first_token() {
308 .assert_expand_items("foo! { foo }", "mod foo {}")
309 .assert_expand_items("foo! { = bar }", "fn bar () {}")
310 .assert_expand_items("foo! { + Baz }", "struct Baz ;");
314 fn test_fail_match_pattern_by_last_token() {
330 .assert_expand_items("foo! { foo }", "mod foo {}")
331 .assert_expand_items("foo! { bar = }", "fn bar () {}")
332 .assert_expand_items("foo! { Baz + }", "struct Baz ;");
336 fn test_fail_match_pattern_by_word_token() {
343 (spam $ i:ident) => (
346 (eggs $ i:ident) => (
352 .assert_expand_items("foo! { foo }", "mod foo {}")
353 .assert_expand_items("foo! { spam bar }", "fn bar () {}")
354 .assert_expand_items("foo! { eggs Baz }", "struct Baz ;");
358 fn test_match_group_pattern_by_separator_token() {
362 ($ ($ i:ident),*) => ($ (
365 ($ ($ i:ident)#*) => ($ (
368 ($ i:ident ,# $ j:ident) => (
375 .assert_expand_items("foo! { foo, bar }", "mod foo {} mod bar {}")
376 .assert_expand_items("foo! { foo# bar }", "fn foo () {} fn bar () {}")
377 .assert_expand_items("foo! { Foo,# Bar }", "struct Foo ; struct Bar ;");
381 fn test_match_group_pattern_with_multiple_defs() {
385 ($ ($ i:ident),*) => ( struct Bar { $ (
391 .assert_expand_items("foo! { foo, bar }", "struct Bar {fn foo {} fn bar {}}");
395 fn test_match_group_pattern_with_multiple_statement() {
399 ($ ($ i:ident),*) => ( fn baz { $ (
405 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ; bar () ;}");
409 fn test_match_group_pattern_with_multiple_statement_without_semi() {
413 ($ ($ i:ident),*) => ( fn baz { $ (
419 .assert_expand_items("foo! { foo, bar }", "fn baz {foo () ;bar ()}");
423 fn test_match_group_empty_fixed_token() {
427 ($ ($ i:ident)* #abc) => ( fn baz { $ (
433 .assert_expand_items("foo! {#abc}", "fn baz {}");
437 fn test_match_group_in_subtree() {
441 (fn $name:ident {$($i:ident)*} ) => ( fn $name() { $ (
446 .assert_expand_items("foo! {fn baz {a b} }", "fn baz () {a () ; b () ;}");
450 fn test_match_group_with_multichar_sep() {
454 (fn $name:ident {$($i:literal)*} ) => ( fn $name() -> bool { $($i)&&*} );
457 .assert_expand_items("foo! (fn baz {true true} );", "fn baz () -> bool {true &&true}");
461 fn test_match_group_zero_match() {
465 ( $($i:ident)* ) => ();
468 .assert_expand_items("foo! ();", "");
472 fn test_match_group_in_group() {
476 { $( ( $($i:ident)* ) )* } => ( $( ( $($i)* ) )* );
479 .assert_expand_items("foo! ( (a b) );", "(a b)");
483 fn test_expand_to_item_list() {
484 let tree = parse_macro(
486 macro_rules! structs {
488 $(struct $i { field: u32 } )*
493 .expand_items("structs!(Foo, Bar);");
495 format!("{:#?}", tree).trim(),
499 STRUCT_KW@0..6 "struct"
502 RECORD_FIELD_LIST@9..20
515 STRUCT_KW@20..26 "struct"
518 RECORD_FIELD_LIST@29..40
534 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
535 if let tt::TokenTree::Subtree(subtree) = tt {
538 unreachable!("It is not a subtree");
540 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
541 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
544 unreachable!("It is not a literal");
547 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
548 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
551 unreachable!("It is not a Punct");
555 fn test_expand_literals_to_token_tree() {
556 let expansion = parse_macro(
558 macro_rules! literals {
570 .expand_tt("literals!(foo);");
571 let stm_tokens = &to_subtree(&expansion.token_trees[0]).token_trees;
573 // [let] [a] [=] ['c'] [;]
574 assert_eq!(to_literal(&stm_tokens[3]).text, "'c'");
575 // [let] [c] [=] [1000] [;]
576 assert_eq!(to_literal(&stm_tokens[5 + 3]).text, "1000");
577 // [let] [f] [=] [12E+99_f64] [;]
578 assert_eq!(to_literal(&stm_tokens[10 + 3]).text, "12E+99_f64");
579 // [let] [s] [=] ["rust1"] [;]
580 assert_eq!(to_literal(&stm_tokens[15 + 3]).text, "\"rust1\"");
584 fn test_attr_to_token_tree() {
585 let expansion = parse_to_token_tree_by_syntax(
592 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
594 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
595 Some(tt::DelimiterKind::Bracket)
600 fn test_two_idents() {
604 ($ i:ident, $ j:ident) => {
605 fn foo() { let a = $ i; let b = $j; }
610 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
614 fn test_tt_to_stmts() {
615 let stmts = parse_macro(
626 .expand_statements("foo!{}");
629 format!("{:#?}", stmts).trim(),
650 INT_NUMBER@9..11 "10"
653 INT_NUMBER@12..13 "1"
665 fn test_match_literal() {
675 .assert_expand_items("foo! ['('];", "fn foo () {}");
679 fn test_parse_macro_def_simple() {
680 mark::check!(parse_macro_def_simple);
684 macro foo($id:ident) {
689 .assert_expand_items("foo!(bar);", "fn bar () {}");
693 fn test_parse_macro_def_rules() {
694 mark::check!(parse_macro_def_rules);
705 .assert_expand_items("foo!(bar);", "fn bar () {}");
708 // The following tests are port from intellij-rust directly
709 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
717 fn foo() { let a = $ i; }
722 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
723 .assert_expand_items(
724 "foo! { bar::<u8>::baz::<u8> }",
725 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
730 fn test_two_paths() {
734 ($ i:path, $ j:path) => {
735 fn foo() { let a = $ i; let b = $j; }
740 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
744 fn test_path_with_path() {
749 fn foo() { let a = $ i :: bar; }
754 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
768 .assert_expand_items(
769 "foo! { 2 + 2 * baz(3).quux() }",
770 "fn bar () {2 + 2 * baz (3) . quux () ;}",
775 fn test_last_expr() {
779 ($($item:expr),*) => {
781 let mut v = Vec::new();
791 .assert_expand_items(
793 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
798 fn test_expr_with_attr() {
806 .assert_expand_items("m!(#[allow(a)]())", "0");
815 fn bar() -> $ i { unimplemented!() }
820 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
824 fn test_ty_with_complex_type() {
829 fn bar() -> $ i { unimplemented!() }
834 // Reference lifetime struct with generic type
835 .assert_expand_items(
836 "foo! { &'a Baz<u8> }",
837 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
839 // extern "Rust" func type
840 .assert_expand_items(
841 r#"foo! { extern "Rust" fn() -> Ret }"#,
842 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
851 ($ i:pat) => { fn foo() { let $ i; } }
855 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
869 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
870 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
874 fn test_single_item() {
884 .assert_expand_items("foo! {mod c {}}", "mod c {}");
888 fn test_all_items() {
892 ($ ($ i:item)*) => ($ (
916 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 ;"#,
925 ($ i:block) => { fn foo() $ i }
929 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
944 .assert_expand_items(
945 r#"foo! { cfg(target_os = "windows") }"#,
946 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
951 fn test_meta_doc_comments() {
955 ($(#[$ i:meta])+) => (
964 /// Single Line Doc 1
969 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\\\n MultiLines Doc\\\\n \"] fn bar () {}",
978 ($ i:tt) => { fn foo() $ i }
982 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
990 ($($ i:tt)*) => { $($ i)* }
994 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
998 fn test_tt_composite() {
1006 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1010 fn test_tt_composite2() {
1011 let node = parse_macro(
1014 ($($tt:tt)*) => { abs!(=> $($tt)*) }
1018 .expand_items(r#"foo!{#}"#);
1020 let res = format!("{:#?}", &node);
1022 r###"MACRO_ITEMS@0..10
1035 R_PAREN@9..10 ")""###,
1041 fn test_tt_with_composite_without_space() {
1045 ($ op:tt, $j:path) => (
1051 // Test macro input without any spaces
1052 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
1053 .assert_expand_items("foo!(==,Foo::Bool)", "0");
1057 fn test_underscore() {
1065 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
1069 fn test_underscore_not_greedily() {
1073 ($($a:ident)* _) => {0};
1077 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
1078 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
1083 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
1087 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
1088 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
1092 fn test_underscore_as_type() {
1100 // Underscore is a type
1101 .assert_expand_items(r#"q![_]"#, r#"0"#);
1105 fn test_vertical_bar_with_pat() {
1109 (| $pat:pat | ) => { 0 }
1113 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
1117 fn test_dollar_crate_lhs_is_not_meta() {
1126 .assert_expand_items(r#"foo!{}"#, r#"0"#);
1130 fn test_lifetime() {
1134 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
1138 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
1146 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1150 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
1155 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
1159 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
1163 fn test_boolean_is_ident() {
1167 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
1172 r#"foo!(true,false);"#,
1197 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
1201 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
1202 // test optional cases
1203 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
1207 fn test_inner_macro_rules() {
1211 ($a:ident, $b:ident, $c:tt) => {
1225 assert_expand_items(
1227 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
1232 fn test_expr_after_path_colons() {
1233 assert!(parse_macro(
1242 .expand_statements(r#"m!(C("0"))"#)
1244 .find(|token| token.kind() == ERROR)
1248 // The following tests are based on real world situations
1251 let fixture = parse_macro(
1254 ($($item:expr),*) => {
1256 let mut v = Vec::new();
1267 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
1268 .assert_expand_items(
1270 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
1273 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
1276 format!("{:#?}", tree).trim(),
1300 SEMICOLON@19..20 ";"
1302 METHOD_CALL_EXPR@20..32
1314 INT_NUMBER@27..31 "1u32"
1316 SEMICOLON@32..33 ";"
1318 METHOD_CALL_EXPR@33..42
1330 INT_NUMBER@40..41 "2"
1332 SEMICOLON@42..43 ";"
1338 R_CURLY@44..45 "}""#
1343 fn test_winapi_struct() {
1344 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
1348 macro_rules! STRUCT {
1349 ($(#[$attrs:meta])* struct $name:ident {
1350 $($field:ident: $ftype:ty,)+
1352 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
1354 $(pub $field: $ftype,)+
1356 impl Clone for $name {
1358 fn clone(&self) -> $name { *self }
1360 #[cfg(feature = "impl-default")]
1361 impl Default for $name {
1363 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
1369 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
1370 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
1371 "# [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 ()}}}"
1373 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
1374 "# [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 ()}}}"
1379 fn test_int_base() {
1382 macro_rules! int_base {
1383 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl fmt::$Trait for $T {
1386 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1387 $Radix.fmt_int(*self as $U, f)
1393 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
1394 "# [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)}}"
1399 fn test_generate_pattern_iterators() {
1400 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1403 macro_rules! generate_pattern_iterators {
1404 { double ended; with $(#[$common_stability_attribute:meta])*,
1405 $forward_iterator:ident,
1406 $reverse_iterator:ident, $iterty:ty
1412 ).assert_expand_items(
1413 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1419 fn test_impl_fn_for_zst() {
1420 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1423 macro_rules! impl_fn_for_zst {
1424 { $( $( #[$attr: meta] )*
1425 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1426 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1433 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1435 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1440 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1442 extern "rust-call" fn call_mut(
1444 ($( $arg, )*): ($( $ArgTy, )*)
1446 Fn::call(&*self, ($( $arg, )*))
1450 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1451 type Output = $ReturnTy;
1454 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1455 Fn::call(&self, ($( $arg, )*))
1462 ).assert_expand_items(r#"
1464 # [ derive ( Clone ) ]
1465 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1466 c . escape_debug_ext ( false )
1469 # [ derive ( Clone ) ]
1470 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1471 c . escape_unicode ( )
1473 # [ derive ( Clone ) ]
1474 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1475 c . escape_default ( )
1479 "# [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 ,))}}"
1484 fn test_impl_nonzero_fmt() {
1485 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1488 macro_rules! impl_nonzero_fmt {
1489 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1494 ).assert_expand_items(
1495 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1501 fn test_cfg_if_items() {
1502 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1505 macro_rules! __cfg_if_items {
1506 (($($not:meta,)*) ; ) => {};
1507 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1508 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1512 ).assert_expand_items(
1513 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 ; ) ) , }"#,
1514 "__cfg_if_items ! {(rustdoc ,) ;}",
1519 fn test_cfg_if_main() {
1520 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1523 macro_rules! cfg_if {
1525 if #[cfg($($meta:meta),*)] { $($it:item)* }
1531 $( ( ($($meta),*) ($($it)*) ), )*
1536 // Internal macro to Apply a cfg attribute to a list of items
1537 (@__apply $m:meta, $($it:item)*) => {
1542 ).assert_expand_items(r#"
1544 if # [ cfg ( target_env = "msvc" ) ] {
1545 // no extra unwinder support needed
1546 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1547 // no unwinder on the system!
1550 pub use libunwind :: * ;
1554 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1555 ).assert_expand_items(
1557 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1564 fn test_proptest_arbitrary() {
1565 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1568 macro_rules! arbitrary {
1569 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1570 $args: ident => $logic: expr) => {
1571 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1572 type Parameters = $params;
1573 type Strategy = $strat;
1574 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1581 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1583 VecStrategy < A :: Strategy > ,
1584 RangedParams1 < A :: Parameters > ;
1585 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1587 "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)}}}"
1592 fn test_old_ridl() {
1593 // This is from winapi 2.8, which do not have a link from github
1595 let expanded = parse_macro(
1599 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1601 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1605 $(pub unsafe fn $method(&mut self) -> $rtr {
1606 ((*self.lpVtbl).$method)(self $(,$p)*)
1612 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1613 fn GetDataSize(&mut self) -> UINT
1616 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1620 fn test_quick_error() {
1621 let expanded = parse_macro(
1623 macro_rules! quick_error {
1625 (SORT [enum $name:ident $( #[$meta:meta] )*]
1626 items [$($( #[$imeta:meta] )*
1627 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1628 {$( $ifuncs:tt )*} )* ]
1632 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1637 $iitem: $imode [$( $ivar: $ityp ),*]
1647 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1649 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1650 ] buf [] queue []) ;
1654 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1658 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1661 macro_rules! delegate_impl {
1662 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1663 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1665 // "Escaped" associated types. Stripped before making the `trait`
1666 // itself, but forwarded when delegating impls.
1668 @escape [type $assoc_name_ext:ident]
1669 // Associated types. Forwarded.
1674 $(#[$_assoc_attr:meta])*
1675 type $assoc_name:ident $(: $assoc_bound:ty)*;
1678 // Methods. Forwarded. Using $self_map!(self) around the self argument.
1679 // Methods must use receiver `self` or explicit type like `self: &Self`
1680 // &self and &mut self are _not_ supported.
1684 $(#[$_method_attr:meta])*
1685 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1688 // Arbitrary tail that is ignored when forwarding.
1694 impl<> $name for $self_wrap where $self_type: $name {
1697 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1698 $self_map!(self).$method_name($($marg),*)
1706 ).assert_expand_items(
1707 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1708 "impl <> Data for & \'a mut G where G : Data {}",
1713 fn expr_interpolation() {
1714 let expanded = parse_macro(
1723 .expand_expr("id!(x + foo);");
1725 assert_eq!(expanded.to_string(), "map(x+foo)");
1728 pub(crate) struct MacroFixture {
1732 pub(crate) struct MacroFixture2 {
1736 macro_rules! impl_fixture {
1739 pub(crate) fn expand_tt(&self, invocation: &str) -> tt::Subtree {
1740 self.try_expand_tt(invocation).unwrap()
1743 fn try_expand_tt(&self, invocation: &str) -> Result<tt::Subtree, ExpandError> {
1744 let source_file = ast::SourceFile::parse(invocation).tree();
1745 let macro_invocation =
1746 source_file.syntax().descendants().find_map(ast::MacroCall::cast).unwrap();
1748 let (invocation_tt, _) = ast_to_token_tree(¯o_invocation.token_tree().unwrap())
1749 .ok_or_else(|| ExpandError::ConversionError)?;
1751 self.rules.expand(&invocation_tt).result()
1755 fn assert_expand_err(&self, invocation: &str, err: &ExpandError) {
1756 assert_eq!(self.try_expand_tt(invocation).as_ref(), Err(err));
1760 fn expand_items(&self, invocation: &str) -> SyntaxNode {
1761 let expanded = self.expand_tt(invocation);
1762 token_tree_to_syntax_node(&expanded, FragmentKind::Items).unwrap().0.syntax_node()
1766 fn expand_statements(&self, invocation: &str) -> SyntaxNode {
1767 let expanded = self.expand_tt(invocation);
1768 token_tree_to_syntax_node(&expanded, FragmentKind::Statements)
1775 fn expand_expr(&self, invocation: &str) -> SyntaxNode {
1776 let expanded = self.expand_tt(invocation);
1777 token_tree_to_syntax_node(&expanded, FragmentKind::Expr).unwrap().0.syntax_node()
1781 fn assert_expand_tt(&self, invocation: &str, expected: &str) {
1782 let expansion = self.expand_tt(invocation);
1783 assert_eq!(expansion.to_string(), expected);
1787 fn assert_expand(&self, invocation: &str, expected: &str) {
1788 let expansion = self.expand_tt(invocation);
1789 let actual = format!("{:?}", expansion);
1790 test_utils::assert_eq_text!(&expected.trim(), &actual.trim());
1793 fn assert_expand_items(&self, invocation: &str, expected: &str) -> &$name {
1794 self.assert_expansion(FragmentKind::Items, invocation, expected);
1799 fn assert_expand_statements(&self, invocation: &str, expected: &str) -> &$name {
1800 self.assert_expansion(FragmentKind::Statements, invocation, expected);
1804 fn assert_expansion(&self, kind: FragmentKind, invocation: &str, expected: &str) {
1805 let expanded = self.expand_tt(invocation);
1806 assert_eq!(expanded.to_string(), expected);
1808 let expected = expected.replace("$crate", "C_C__C");
1810 // wrap the given text to a macro call
1812 let wrapped = format!("wrap_macro!( {} )", expected);
1813 let wrapped = ast::SourceFile::parse(&wrapped);
1814 let wrapped = wrapped
1818 .find_map(ast::TokenTree::cast)
1820 let mut wrapped = ast_to_token_tree(&wrapped).unwrap().0;
1821 wrapped.delimiter = None;
1826 token_tree_to_syntax_node(&expanded, kind).unwrap().0.syntax_node();
1827 let expanded_tree = debug_dump_ignore_spaces(&expanded_tree).trim().to_string();
1830 token_tree_to_syntax_node(&expected, kind).unwrap().0.syntax_node();
1831 let expected_tree = debug_dump_ignore_spaces(&expected_tree).trim().to_string();
1833 let expected_tree = expected_tree.replace("C_C__C", "$crate");
1835 expanded_tree, expected_tree,
1836 "\nleft:\n{}\nright:\n{}",
1837 expanded_tree, expected_tree,
1844 impl_fixture!(MacroFixture);
1845 impl_fixture!(MacroFixture2);
1847 fn parse_macro_rules_to_tt(ra_fixture: &str) -> tt::Subtree {
1848 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1849 let macro_definition =
1850 source_file.syntax().descendants().find_map(ast::MacroRules::cast).unwrap();
1852 let (definition_tt, _) = ast_to_token_tree(¯o_definition.token_tree().unwrap()).unwrap();
1854 let parsed = parse_to_token_tree(
1855 &ra_fixture[macro_definition.token_tree().unwrap().syntax().text_range()],
1859 assert_eq!(definition_tt, parsed);
1864 fn parse_macro_def_to_tt(ra_fixture: &str) -> tt::Subtree {
1865 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1866 let macro_definition =
1867 source_file.syntax().descendants().find_map(ast::MacroDef::cast).unwrap();
1869 let (definition_tt, _) = ast_to_token_tree(¯o_definition.body().unwrap()).unwrap();
1872 parse_to_token_tree(&ra_fixture[macro_definition.body().unwrap().syntax().text_range()])
1875 assert_eq!(definition_tt, parsed);
1880 pub(crate) fn parse_macro(ra_fixture: &str) -> MacroFixture {
1881 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1882 let rules = MacroRules::parse(&definition_tt).unwrap();
1883 MacroFixture { rules }
1886 pub(crate) fn parse_macro2(ra_fixture: &str) -> MacroFixture2 {
1887 let definition_tt = parse_macro_def_to_tt(ra_fixture);
1888 let rules = MacroDef::parse(&definition_tt).unwrap();
1889 MacroFixture2 { rules }
1892 pub(crate) fn parse_macro_error(ra_fixture: &str) -> ParseError {
1893 let definition_tt = parse_macro_rules_to_tt(ra_fixture);
1895 match MacroRules::parse(&definition_tt) {
1896 Ok(_) => panic!("Expect error"),
1901 pub(crate) fn parse_to_token_tree_by_syntax(ra_fixture: &str) -> tt::Subtree {
1902 let source_file = ast::SourceFile::parse(ra_fixture).ok().unwrap();
1903 let tt = syntax_node_to_token_tree(source_file.syntax()).unwrap().0;
1905 let parsed = parse_to_token_tree(ra_fixture).unwrap().0;
1906 assert_eq!(tt, parsed);
1911 fn debug_dump_ignore_spaces(node: &syntax::SyntaxNode) -> String {
1913 let mut buf = String::new();
1914 macro_rules! indent {
1922 for event in node.preorder_with_tokens() {
1924 WalkEvent::Enter(element) => {
1926 NodeOrToken::Node(node) => {
1928 writeln!(buf, "{:?}", node.kind()).unwrap();
1930 NodeOrToken::Token(token) => match token.kind() {
1931 syntax::SyntaxKind::WHITESPACE => {}
1934 writeln!(buf, "{:?}", token.kind()).unwrap();
1940 WalkEvent::Leave(_) => level -= 1,
1948 fn test_issue_2520() {
1949 let macro_fixture = parse_macro(
1951 macro_rules! my_macro {
1954 $( [] $sname:ident : $stype:ty )?
1955 $( [$expr:expr] $nname:ident : $ntype:ty )?
1968 macro_fixture.assert_expand_items(
1970 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1977 fn test_issue_3861() {
1978 let macro_fixture = parse_macro(
1980 macro_rules! rgb_color {
1981 ($p:expr, $t: ty) => {
1983 let _ = 0 as $t << $p;
1990 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1994 fn test_repeat_bad_var() {
1995 // FIXME: the second rule of the macro should be removed and an error about
1996 // `$( $c )+` raised
2000 ($( $b:ident )+) => {
2003 ($( $b:ident )+) => {
2009 .assert_expand_items("foo!(b0 b1);", "b0 b1");
2013 fn test_no_space_after_semi_colon() {
2014 let expanded = parse_macro(
2016 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
2019 .expand_items(r#"with_std! {mod m;mod f;}"#);
2021 let dump = format!("{:#?}", expanded);
2023 r###"MACRO_ITEMS@0..52
2034 IDENT@6..13 "feature"
2036 STRING@14..19 "\"std\""
2042 SEMICOLON@25..26 ";"
2053 IDENT@32..39 "feature"
2055 STRING@40..45 "\"std\""
2061 SEMICOLON@51..52 ";""###,
2066 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
2068 fn test_rustc_issue_57597() {
2069 fn test_error(fixture: &str) {
2070 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
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)+)?)*) => {}; }");
2084 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
2088 fn test_expand_bad_literal() {
2091 macro_rules! foo { ($i:literal) => {}; }
2094 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
2098 fn test_empty_comments() {
2101 macro_rules! one_arg_macro { ($fmt:expr) => (); }
2105 r#"one_arg_macro!(/**/)"#,
2106 &ExpandError::BindingError("expected Expr".into()),