diff --git a/src/lib.rs b/src/lib.rs index 8f0203b..71b3b01 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -254,6 +254,10 @@ pub mod __rt { /// [`ToTokens`]: trait.ToTokens.html /// [Syn]: https://github.com/dtolnay/syn /// +/// You can also use `#{expr}` to interpolate an arbitrary expression, so long +/// as the result implements the [`ToTokens`] trait. For example `#{1 + 3}` will +/// interpolate `4i32`. +/// /// Repetition is done using `#(...)*` or `#(...),*` again similar to /// `macro_rules!`. This iterates through the elements of any variable /// interpolated within the repetition and inserts a copy of the repetition body @@ -579,6 +583,11 @@ macro_rules! quote_each_token { quote_each_token!($tokens $span $($rest)*); }; + ($tokens:ident $span:ident # { $val:expr } $($rest:tt)*) => { + $crate::ToTokens::to_tokens(&$val, &mut $tokens); + quote_each_token!($tokens $span $($rest)*); + }; + ($tokens:ident $span:ident # $first:ident $($rest:tt)*) => { $crate::ToTokens::to_tokens(&$first, &mut $tokens); quote_each_token!($tokens $span $($rest)*); diff --git a/tests/test.rs b/tests/test.rs index f832da5..5833bce 100644 --- a/tests/test.rs +++ b/tests/test.rs @@ -293,3 +293,19 @@ fn test_append_tokens() { a.append_all(b); assert_eq!("a b", a.to_string()); } + +#[test] +fn whole_exprs() { + let x = X; + let tokens = quote!(#{x}); + assert_eq!(tokens.to_string(), "X"); + + let tokens = quote!(#{1 + 2}); + assert_eq!(tokens.to_string(), "3i32"); + + struct A { b: X } + let x = A { b: X }; + + let tokens = quote!(#{x.b}); + assert_eq!(tokens.to_string(), "X"); +}