1 use ::parser::ParserEntryPoint;
3 SyntaxKind::{ERROR, IDENT},
6 use test_utils::assert_eq_text;
10 // Good first issue (although a slightly challenging one):
12 // * Pick a random test from here
13 // https://github.com/intellij-rust/intellij-rust/blob/c4e9feee4ad46e7953b1948c112533360b6087bb/src/test/kotlin/org/rust/lang/core/macros/RsMacroExpansionTest.kt
14 // * Port the test to rust and add it to this module
18 fn test_token_id_shift() {
19 let expansion = parse_macro(
22 ($e:ident) => { foo bar $e }
26 .expand_tt("foobar!(baz);");
28 fn get_id(t: &tt::TokenTree) -> Option<u32> {
29 if let tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) = t {
30 return Some(ident.id.0);
35 assert_eq!(expansion.token_trees.len(), 3);
36 // {($e:ident) => { foo bar $e }}
38 assert_eq!(get_id(&expansion.token_trees[0]), Some(9));
39 assert_eq!(get_id(&expansion.token_trees[1]), Some(10));
41 // The input args of macro call include parentheses:
43 // So baz should be 12+1+1
44 assert_eq!(get_id(&expansion.token_trees[2]), Some(14));
49 let expanded = parse_macro(
52 ($e:ident) => { fn $e() {} }
56 .expand_tt("foobar!(baz);");
58 let (node, token_map) = token_tree_to_syntax_node(&expanded, ParserEntryPoint::Items).unwrap();
59 let content = node.syntax_node().to_string();
61 let get_text = |id, kind| -> String {
62 content[token_map.first_range_by_token(id, kind).unwrap()].to_string()
65 assert_eq!(expanded.token_trees.len(), 4);
66 // {($e:ident) => { fn $e() {} }}
67 // 012345 67 8 9 T12 3
69 assert_eq!(get_text(tt::TokenId(9), IDENT), "fn");
70 assert_eq!(get_text(tt::TokenId(12), T!['(']), "(");
71 assert_eq!(get_text(tt::TokenId(13), T!['{']), "{");
74 fn to_subtree(tt: &tt::TokenTree) -> &tt::Subtree {
75 if let tt::TokenTree::Subtree(subtree) = tt {
78 unreachable!("It is not a subtree");
80 fn to_literal(tt: &tt::TokenTree) -> &tt::Literal {
81 if let tt::TokenTree::Leaf(tt::Leaf::Literal(lit)) = tt {
84 unreachable!("It is not a literal");
87 fn to_punct(tt: &tt::TokenTree) -> &tt::Punct {
88 if let tt::TokenTree::Leaf(tt::Leaf::Punct(lit)) = tt {
91 unreachable!("It is not a Punct");
95 fn test_attr_to_token_tree() {
96 let expansion = parse_to_token_tree_by_syntax(
103 assert_eq!(to_punct(&expansion.token_trees[0]).char, '#');
105 to_subtree(&expansion.token_trees[1]).delimiter_kind(),
106 Some(tt::DelimiterKind::Bracket)
111 fn test_two_idents() {
115 ($ i:ident, $ j:ident) => {
116 fn foo() { let a = $ i; let b = $j; }
121 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
125 fn test_tt_to_stmts() {
126 let stmts = parse_macro(
137 .expand_statements("foo!{}");
140 format!("{:#?}", stmts).trim(),
161 INT_NUMBER@9..11 "10"
164 INT_NUMBER@12..13 "1"
175 fn test_match_literal() {
185 .assert_expand_items("foo! ['('];", "fn foo () {}");
189 fn test_parse_macro_def_simple() {
190 cov_mark::check!(parse_macro_def_simple);
194 macro foo($id:ident) {
199 .assert_expand_items("foo!(bar);", "fn bar () {}");
203 fn test_parse_macro_def_rules() {
204 cov_mark::check!(parse_macro_def_rules);
215 .assert_expand_items("foo!(bar);", "fn bar () {}");
219 fn test_macro_2_0_panic_2015() {
230 .assert_expand_items("panic_2015!(bar);", "");
239 fn foo() { let a = $ i; }
244 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo ;}")
245 .assert_expand_items(
246 "foo! { bar::<u8>::baz::<u8> }",
247 "fn foo () {let a = bar ::< u8 >:: baz ::< u8 > ;}",
252 fn test_two_paths() {
256 ($ i:path, $ j:path) => {
257 fn foo() { let a = $ i; let b = $j; }
262 .assert_expand_items("foo! { foo, bar }", "fn foo () {let a = foo ; let b = bar ;}");
266 fn test_path_with_path() {
271 fn foo() { let a = $ i :: bar; }
276 .assert_expand_items("foo! { foo }", "fn foo () {let a = foo :: bar ;}");
290 .assert_expand_items(
291 "foo! { 2 + 2 * baz(3).quux() }",
292 "fn bar () {2 + 2 * baz (3) . quux () ;}",
297 fn test_last_expr() {
301 ($($item:expr),*) => {
303 let mut v = Vec::new();
313 .assert_expand_items(
315 "{let mut v = Vec :: new () ; v . push (1) ; v . push (2) ; v . push (3) ; v}",
320 fn test_expr_with_attr() {
328 .assert_expand_items("m!(#[allow(a)]())", "0");
337 fn bar() -> $ i { unimplemented!() }
342 .assert_expand_items("foo! { Baz<u8> }", "fn bar () -> Baz < u8 > {unimplemented ! ()}");
346 fn test_ty_with_complex_type() {
351 fn bar() -> $ i { unimplemented!() }
356 // Reference lifetime struct with generic type
357 .assert_expand_items(
358 "foo! { &'a Baz<u8> }",
359 "fn bar () -> & 'a Baz < u8 > {unimplemented ! ()}",
361 // extern "Rust" func type
362 .assert_expand_items(
363 r#"foo! { extern "Rust" fn() -> Ret }"#,
364 r#"fn bar () -> extern "Rust" fn () -> Ret {unimplemented ! ()}"#,
373 ($ i:pat) => { fn foo() { let $ i; } }
377 .assert_expand_items("foo! { (a, b) }", "fn foo () {let (a , b) ;}");
391 .assert_expand_items("foo! { 2 }", "fn bar () {2 ;}")
392 .assert_expand_items("foo! { let a = 0 }", "fn bar () {let a = 0 ;}");
396 fn test_single_item() {
406 .assert_expand_items("foo! {mod c {}}", "mod c {}");
410 fn test_all_items() {
414 ($ ($ i:item)*) => ($ (
438 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 ;"#,
447 ($ i:block) => { fn foo() $ i }
451 .assert_expand_statements("foo! { { 1; } }", "fn foo () {1 ;}");
466 .assert_expand_items(
467 r#"foo! { cfg(target_os = "windows") }"#,
468 r#"# [cfg (target_os = "windows")] fn bar () {}"#,
470 .assert_expand_items(r#"foo! { hello::world }"#, r#"# [hello :: world] fn bar () {}"#);
474 fn test_meta_doc_comments() {
478 ($(#[$ i:meta])+) => (
487 /// Single Line Doc 1
492 "# [doc = \" Single Line Doc 1\"] # [doc = \"\\n MultiLines Doc\\n \"] fn bar () {}",
497 fn test_meta_extended_key_value_attributes() {
508 .assert_expand_items(
509 r#"foo! { #[doc = concat!("The `", "bla", "` lang item.")] }"#,
510 r#"# [doc = concat ! ("The `" , "bla" , "` lang item.")] fn bar () {}"#,
515 fn test_meta_doc_comments_non_latin() {
519 ($(#[$ i:meta])+) => (
533 "# [doc = \" 錦瑟無端五十弦,一弦一柱思華年。\"] # [doc = \"\\n 莊生曉夢迷蝴蝶,望帝春心託杜鵑。\\n \"] fn bar () {}",
538 fn test_meta_doc_comments_escaped_characters() {
542 ($(#[$ i:meta])+) => (
549 .assert_expand_items(
553 r#"# [doc = " \\ \" \'"] fn bar () {}"#,
562 ($ i:tt) => { fn foo() $ i }
566 .assert_expand_items(r#"foo! { { 1; } }"#, r#"fn foo () {1 ;}"#);
574 ($($ i:tt)*) => { $($ i)* }
578 .assert_expand_items(r#"foo! { fn foo() {} }"#, r#"fn foo () {}"#);
582 fn test_tt_composite() {
590 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
594 fn test_tt_composite2() {
595 let node = parse_macro(
598 ($($tt:tt)*) => { abs!(=> $($tt)*) }
602 .expand_items(r#"foo!{#}"#);
604 let res = format!("{:#?}", &node);
606 r###"MACRO_ITEMS@0..10
619 R_PAREN@9..10 ")""###,
625 fn test_tt_with_composite_without_space() {
629 ($ op:tt, $j:path) => (
635 // Test macro input without any spaces
636 // See https://github.com/rust-analyzer/rust-analyzer/issues/6692
637 .assert_expand_items("foo!(==,Foo::Bool)", "0");
641 fn test_underscore() {
649 .assert_expand_items(r#"foo! { => }"#, r#"0"#);
653 fn test_underscore_not_greedily() {
657 ($($a:ident)* _) => {0};
661 // `_` overlaps with `$a:ident` but rustc matches it under the `_` token
662 .assert_expand_items(r#"q![a b c d _]"#, r#"0"#);
667 ($($a:expr => $b:ident)* _ => $c:expr) => {0};
671 // `_ => ou` overlaps with `$a:expr => $b:ident` but rustc matches it under `_ => $c:expr`
672 .assert_expand_items(r#"q![a => b c => d _ => ou]"#, r#"0"#);
676 fn test_underscore_as_type() {
684 // Underscore is a type
685 .assert_expand_items(r#"q![_]"#, r#"0"#);
689 fn test_underscore_lifetime() {
690 parse_macro(r#"macro_rules! q { ($a:lifetime) => {0}; }"#)
691 .assert_expand_items(r#"q!['_]"#, r#"0"#);
695 fn test_vertical_bar_with_pat() {
699 (| $pat:pat | ) => { 0 }
703 .assert_expand_items(r#"foo! { | x | }"#, r#"0"#);
707 fn test_dollar_crate_lhs_is_not_meta() {
716 .assert_expand_items(r#"foo!{}"#, r#"0"#);
724 ($ lt:lifetime) => { struct Ref<$ lt>{ s: &$ lt str } }
728 .assert_expand_items(r#"foo!{'a}"#, r#"struct Ref <'a > {s : &'a str}"#);
736 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
740 .assert_expand_items(r#"foo!(u8,0);"#, r#"const VALUE : u8 = 0 ;"#);
745 ($ type:ty , $ lit:literal) => { const VALUE: $ type = $ lit;};
749 .assert_expand_items(r#"foo!(i32,-1);"#, r#"const VALUE : i32 = - 1 ;"#);
753 fn test_boolean_is_ident() {
757 ($lit0:literal, $lit1:literal) => { const VALUE: (bool,bool) = ($lit0,$lit1); };
762 r#"foo!(true,false);"#,
787 ($ vis:vis $ name:ident) => { $ vis fn $ name() {}};
791 .assert_expand_items(r#"foo!(pub foo);"#, r#"pub fn foo () {}"#)
792 // test optional cases
793 .assert_expand_items(r#"foo!(foo);"#, r#"fn foo () {}"#);
797 fn test_inner_macro_rules() {
801 ($a:ident, $b:ident, $c:tt) => {
817 r#"macro_rules ! bar {($ bi : ident) => {fn $ bi () -> u8 {1}}} bar ! (x) ; fn y () -> u8 {1}"#,
822 fn test_expr_after_path_colons() {
832 .expand_statements(r#"m!(C("0"))"#)
834 .any(|token| token.kind() == ERROR));
838 fn test_match_is_not_greedy() {
842 ($($i:ident $(,)*),*) => {};
846 .assert_expand_items(r#"foo!(a,b);"#, r#""#);
849 // The following tests are based on real world situations
852 let fixture = parse_macro(
855 ($($item:expr),*) => {
857 let mut v = Vec::new();
868 .assert_expand_items(r#"vec!();"#, r#"{let mut v = Vec :: new () ; v}"#)
869 .assert_expand_items(
871 r#"{let mut v = Vec :: new () ; v . push (1u32) ; v . push (2) ; v}"#,
874 let tree = fixture.expand_expr(r#"vec![1u32,2];"#);
877 &format!("{:#?}", tree),
904 METHOD_CALL_EXPR@20..32
916 INT_NUMBER@27..31 "1u32"
920 METHOD_CALL_EXPR@33..42
932 INT_NUMBER@40..41 "2"
946 fn test_winapi_struct() {
947 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/macros.rs#L366
951 macro_rules! STRUCT {
952 ($(#[$attrs:meta])* struct $name:ident {
953 $($field:ident: $ftype:ty,)+
955 #[repr(C)] #[derive(Copy)] $(#[$attrs])*
957 $(pub $field: $ftype,)+
959 impl Clone for $name {
961 fn clone(&self) -> $name { *self }
963 #[cfg(feature = "impl-default")]
964 impl Default for $name {
966 fn default() -> $name { unsafe { $crate::_core::mem::zeroed() } }
972 // from https://github.com/retep998/winapi-rs/blob/a7ef2bca086aae76cf6c4ce4c2552988ed9798ad/src/shared/d3d9caps.rs
973 assert_expand_items(r#"STRUCT!{struct D3DVSHADERCAPS2_0 {Caps: u8,}}"#,
974 "# [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 ()}}}"
976 .assert_expand_items(r#"STRUCT!{#[cfg_attr(target_arch = "x86", repr(packed))] struct D3DCONTENTPROTECTIONCAPS {Caps : u8 ,}}"#,
977 "# [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 ()}}}"
985 macro_rules! int_base {
986 ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
987 #[stable(feature = "rust1", since = "1.0.0")]
988 impl fmt::$Trait for $T {
989 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 $Radix.fmt_int(*self as $U, f)
996 ).assert_expand_items(r#" int_base!{Binary for isize as usize -> Binary}"#,
997 "# [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)}}"
1002 fn test_generate_pattern_iterators() {
1003 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/str/mod.rs
1006 macro_rules! generate_pattern_iterators {
1007 { double ended; with $(#[$common_stability_attribute:meta])*,
1008 $forward_iterator:ident,
1009 $reverse_iterator:ident, $iterty:ty
1015 ).assert_expand_items(
1016 r#"generate_pattern_iterators ! ( double ended ; with # [ stable ( feature = "rust1" , since = "1.0.0" ) ] , Split , RSplit , & 'a str );"#,
1022 fn test_impl_fn_for_zst() {
1023 // from https://github.com/rust-lang/rust/blob/5d20ff4d2718c820632b38c1e49d4de648a9810b/src/libcore/internal_macros.rs
1026 macro_rules! impl_fn_for_zst {
1027 { $( $( #[$attr: meta] )*
1028 struct $Name: ident impl$( <$( $lifetime : lifetime ),+> )? Fn =
1029 |$( $arg: ident: $ArgTy: ty ),*| -> $ReturnTy: ty
1036 impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name {
1038 extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1043 impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name {
1045 extern "rust-call" fn call_mut(
1047 ($( $arg, )*): ($( $ArgTy, )*)
1049 Fn::call(&*self, ($( $arg, )*))
1053 impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name {
1054 type Output = $ReturnTy;
1057 extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy {
1058 Fn::call(&self, ($( $arg, )*))
1065 ).assert_expand_items(r#"
1067 # [ derive ( Clone ) ]
1068 struct CharEscapeDebugContinue impl Fn = | c : char | -> char :: EscapeDebug {
1069 c . escape_debug_ext ( false )
1072 # [ derive ( Clone ) ]
1073 struct CharEscapeUnicode impl Fn = | c : char | -> char :: EscapeUnicode {
1074 c . escape_unicode ( )
1076 # [ derive ( Clone ) ]
1077 struct CharEscapeDefault impl Fn = | c : char | -> char :: EscapeDefault {
1078 c . escape_default ( )
1082 "# [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 ,))}}"
1087 fn test_impl_nonzero_fmt() {
1088 // from https://github.com/rust-lang/rust/blob/316a391dcb7d66dc25f1f9a4ec9d368ef7615005/src/libcore/num/mod.rs#L12
1091 macro_rules! impl_nonzero_fmt {
1092 ( #[$stability: meta] ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
1097 ).assert_expand_items(
1098 r#"impl_nonzero_fmt! { # [stable(feature= "nonzero",since="1.28.0")] (Debug,Display,Binary,Octal,LowerHex,UpperHex) for NonZeroU8}"#,
1104 fn test_cfg_if_items() {
1105 // from https://github.com/rust-lang/rust/blob/33fe1131cadba69d317156847be9a402b89f11bb/src/libstd/macros.rs#L986
1108 macro_rules! __cfg_if_items {
1109 (($($not:meta,)*) ; ) => {};
1110 (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => {
1111 __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* }
1115 ).assert_expand_items(
1116 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 ; ) ) , }"#,
1117 "__cfg_if_items ! {(rustdoc ,) ;}",
1122 fn test_cfg_if_main() {
1123 // from https://github.com/rust-lang/rust/blob/3d211248393686e0f73851fc7548f6605220fbe1/src/libpanic_unwind/macros.rs#L9
1126 macro_rules! cfg_if {
1128 if #[cfg($($meta:meta),*)] { $($it:item)* }
1134 $( ( ($($meta),*) ($($it)*) ), )*
1139 // Internal macro to Apply a cfg attribute to a list of items
1140 (@__apply $m:meta, $($it:item)*) => {
1145 ).assert_expand_items(r#"
1147 if # [ cfg ( target_env = "msvc" ) ] {
1148 // no extra unwinder support needed
1149 } else if # [ cfg ( all ( target_arch = "wasm32" , not ( target_os = "emscripten" ) ) ) ] {
1150 // no unwinder on the system!
1153 pub use libunwind :: * ;
1157 "__cfg_if_items ! {() ; ((target_env = \"msvc\") ()) , ((all (target_arch = \"wasm32\" , not (target_os = \"emscripten\"))) ()) , (() (mod libunwind ; pub use libunwind :: * ;)) ,}"
1158 ).assert_expand_items(
1160 cfg_if ! { @ __apply cfg ( all ( not ( any ( not ( any ( target_os = "solaris" , target_os = "illumos" ) ) ) ) ) ) , }
1167 fn test_proptest_arbitrary() {
1168 // from https://github.com/AltSysrq/proptest/blob/d1c4b049337d2f75dd6f49a095115f7c532e5129/proptest/src/arbitrary/macros.rs#L16
1171 macro_rules! arbitrary {
1172 ([$($bounds : tt)*] $typ: ty, $strat: ty, $params: ty;
1173 $args: ident => $logic: expr) => {
1174 impl<$($bounds)*> $crate::arbitrary::Arbitrary for $typ {
1175 type Parameters = $params;
1176 type Strategy = $strat;
1177 fn arbitrary_with($args: Self::Parameters) -> Self::Strategy {
1184 ).assert_expand_items(r#"arbitrary ! ( [ A : Arbitrary ]
1186 VecStrategy < A :: Strategy > ,
1187 RangedParams1 < A :: Parameters > ;
1188 args => { let product_unpack ! [ range , a ] = args ; vec ( any_with :: < A > ( a ) , range ) }
1190 "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)}}}"
1195 fn test_old_ridl() {
1196 // This is from winapi 2.8, which do not have a link from github
1198 let expanded = parse_macro(
1202 (interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident)
1204 fn $method:ident(&mut self $(,$p:ident : $t:ty)*) -> $rtr:ty
1208 $(pub unsafe fn $method(&mut self) -> $rtr {
1209 ((*self.lpVtbl).$method)(self $(,$p)*)
1215 RIDL!{interface ID3D11Asynchronous(ID3D11AsynchronousVtbl): ID3D11DeviceChild(ID3D11DeviceChildVtbl) {
1216 fn GetDataSize(&mut self) -> UINT
1219 assert_eq!(expanded.to_string(), "impl ID3D11Asynchronous {pub unsafe fn GetDataSize (& mut self) -> UINT {((* self . lpVtbl) .GetDataSize) (self)}}");
1223 fn test_quick_error() {
1224 let expanded = parse_macro(
1226 macro_rules! quick_error {
1228 (SORT [enum $name:ident $( #[$meta:meta] )*]
1229 items [$($( #[$imeta:meta] )*
1230 => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*]
1231 {$( $ifuncs:tt )*} )* ]
1235 quick_error!(ENUMINITION [enum $name $( #[$meta] )*]
1240 $iitem: $imode [$( $ivar: $ityp ),*]
1250 quick_error ! (SORT [enum Wrapped # [derive (Debug)]] items [
1252 => Two : TUPLE [s :String] {display ("two: {}" , s) from ()}
1253 ] buf [] queue []) ;
1257 assert_eq!(expanded.to_string(), "quick_error ! (ENUMINITION [enum Wrapped # [derive (Debug)]] body [] queue [=> One : UNIT [] => Two : TUPLE [s : String]]) ;");
1261 fn test_empty_repeat_vars_in_empty_repeat_vars() {
1264 macro_rules! delegate_impl {
1265 ([$self_type:ident, $self_wrap:ty, $self_map:ident]
1266 pub trait $name:ident $(: $sup:ident)* $(+ $more_sup:ident)* {
1269 @escape [type $assoc_name_ext:ident]
1274 $(#[$_assoc_attr:meta])*
1275 type $assoc_name:ident $(: $assoc_bound:ty)*;
1281 $(#[$_method_attr:meta])*
1282 fn $method_name:ident(self $(: $self_selftype:ty)* $(,$marg:ident : $marg_ty:ty)*) -> $mret:ty;
1290 impl<> $name for $self_wrap where $self_type: $name {
1293 fn $method_name(self $(: $self_selftype)* $(,$marg: $marg_ty)*) -> $mret {
1294 $self_map!(self).$method_name($($marg),*)
1302 ).assert_expand_items(
1303 r#"delegate_impl ! {[G , & 'a mut G , deref] pub trait Data : GraphBase {@ section type type NodeWeight ;}}"#,
1304 "impl <> Data for & \'a mut G where G : Data {}",
1309 fn expr_interpolation() {
1310 let expanded = parse_macro(
1319 .expand_expr("id!(x + foo);");
1321 assert_eq!(expanded.to_string(), "map(x+foo)");
1325 fn test_issue_2520() {
1326 let macro_fixture = parse_macro(
1328 macro_rules! my_macro {
1331 $( [] $sname:ident : $stype:ty )?
1332 $( [$expr:expr] $nname:ident : $ntype:ty )?
1345 macro_fixture.assert_expand_items(
1347 ([] p1 : u32 , [|_| S0K0] s : S0K0 , [] k0 : i32)
1354 fn test_issue_3861() {
1355 let macro_fixture = parse_macro(
1357 macro_rules! rgb_color {
1358 ($p:expr, $t: ty) => {
1360 let _ = 0 as $t << $p;
1367 macro_fixture.expand_items(r#"rgb_color!(8 + 8, u32);"#);
1371 fn test_repeat_bad_var() {
1372 // FIXME: the second rule of the macro should be removed and an error about
1373 // `$( $c )+` raised
1377 ($( $b:ident )+) => {
1380 ($( $b:ident )+) => {
1386 .assert_expand_items("foo!(b0 b1);", "b0 b1");
1390 fn test_no_space_after_semi_colon() {
1391 let expanded = parse_macro(
1393 macro_rules! with_std { ($($i:item)*) => ($(#[cfg(feature = "std")]$i)*) }
1396 .expand_items(r#"with_std! {mod m;mod f;}"#);
1398 let dump = format!("{:#?}", expanded);
1400 r###"MACRO_ITEMS@0..52
1412 IDENT@6..13 "feature"
1414 STRING@14..19 "\"std\""
1420 SEMICOLON@25..26 ";"
1432 IDENT@32..39 "feature"
1434 STRING@40..45 "\"std\""
1440 SEMICOLON@51..52 ";""###,
1445 // https://github.com/rust-lang/rust/blob/master/src/test/ui/issues/issue-57597.rs
1447 fn test_rustc_issue_57597() {
1448 fn test_error(fixture: &str) {
1449 assert_eq!(parse_macro_error(fixture), ParseError::RepetitionEmptyTokenTree);
1452 test_error("macro_rules! foo { ($($($i:ident)?)+) => {}; }");
1453 test_error("macro_rules! foo { ($($($i:ident)?)*) => {}; }");
1454 test_error("macro_rules! foo { ($($($i:ident)?)?) => {}; }");
1455 test_error("macro_rules! foo { ($($($($i:ident)?)?)?) => {}; }");
1456 test_error("macro_rules! foo { ($($($($i:ident)*)?)?) => {}; }");
1457 test_error("macro_rules! foo { ($($($($i:ident)?)*)?) => {}; }");
1458 test_error("macro_rules! foo { ($($($($i:ident)?)?)*) => {}; }");
1459 test_error("macro_rules! foo { ($($($($i:ident)*)*)?) => {}; }");
1460 test_error("macro_rules! foo { ($($($($i:ident)?)*)*) => {}; }");
1461 test_error("macro_rules! foo { ($($($($i:ident)?)*)+) => {}; }");
1462 test_error("macro_rules! foo { ($($($($i:ident)+)?)*) => {}; }");
1463 test_error("macro_rules! foo { ($($($($i:ident)+)*)?) => {}; }");
1467 fn test_expand_bad_literal() {
1470 macro_rules! foo { ($i:literal) => {}; }
1473 .assert_expand_err(r#"foo!(&k");"#, &ExpandError::BindingError("".into()));
1477 fn test_empty_comments() {
1480 macro_rules! one_arg_macro { ($fmt:expr) => (); }
1484 r#"one_arg_macro!(/**/)"#,
1485 &ExpandError::BindingError("expected Expr".into()),