chiark / gitweb /
W
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Fri, 10 May 2024 12:32:19 +0000 (13:32 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Fri, 10 May 2024 12:32:19 +0000 (13:32 +0100)
macros/macros.rs
src/main.rs

index 81489d1cca5b33b93b66e0707c8162661fc1bcc1..70d8da7d583cf02f93ee2794586ebe6179715c9e 100644 (file)
@@ -1,30 +1,28 @@
-use proc_macro::TokenStream;
-use quote::{quote, ToTokens};
-use proc_macro2::Delimiter;
+use proc_macro::{Group, TokenStream, TokenTree};
 
 #[proc_macro]
 pub fn dbg_dump(input: TokenStream) -> TokenStream {
     dbg!(&input);
-dbg!(input.to_string());
+    dbg!(input.to_string());
     input
 }
 
 #[proc_macro]
-pub fn define_struct_procmacro(input: TokenStream) -> TokenStream {
-    let ty: syn::Type = syn::parse(input).unwrap();
-    let ty = proc_macro2::Group::new(
-        Delimiter::None,
-        ty.to_token_stream(),
-    );
-    let out: TokenStream = quote! {
-        struct FromProcMacro {
-            field: &'static #ty,
-        }
-    }.into();
-
-    dbg!(&out);
-
-dbg!(out.to_string());
-
-    out
+pub fn reconstruct_group(input: TokenStream) -> TokenStream {
+    let mut output = TokenStream::new();
+    dbg!(&input);
+    for tt in input {
+        let tt = match tt {
+            TokenTree::Group(g) => {
+                let delim = g.delimiter();
+                dbg!(&delim);
+                TokenTree::Group(Group::new(delim, g.stream()))
+            },
+            other => other,
+        };
+        output.extend([tt]);
+    }
+    dbg!(&output);
+    dbg!(&output.to_string());
+    output
 }
index 89c73299e8c8813e9b3ce914f937fb61819f700b..2dbd8ed3956a431ae055db0174d3c377bf9b7f8b 100644 (file)
@@ -1,17 +1,19 @@
 #![allow(dead_code)]
 use foo_macros::*;
-use std::fmt::Display;
 
-macro_rules! define_struct_pattern { { $ftype:ty } => {
-    foo_macros::dbg_dump! {
-        struct FromPatternMacro {
-            field: &'static $ftype,
-        }
-    }
+macro_rules! one_plus { { $v:expr } => {
+    1 + $v
+} }
+macro_rules! one_plus_dbg { { $v:expr } => {
+    dbg_dump!(1 + $v)
+} }
+macro_rules! one_plus_reconstruct { { $v:expr } => {
+    dbg_dump!(1 + reconstruct_group!($v))
 } }
 
-define_struct_pattern!{ dyn Display + 'static }
-
-define_struct_procmacro!{ dyn Display + 'static }
-
-fn main() {}
+fn main() {
+    println!("1 + (2<<3) should be 17");
+//    println!("{} without proc_macro", one_plus!(2 << 3));
+//    println!("{} dbg_dump", one_plus_dbg!(2 << 3));
+    println!("{} reconstruct", one_plus_reconstruct!(2 << 3));
+}