Skip to main content

goish_macros/
lib.rs

1//! goish-macros: internal proc-macro support for the main `goish` crate.
2//!
3//! Exposes `rewrite_go_body!` — parses a goroutine body, walks the AST, and
4//! rewrites goish's sync API calls into their async equivalents:
5//!
6//!   .Send(x)  →  .send(x).await
7//!   .Recv()   →  .recv().await
8//!   .Wait()   →  .wait().await
9//!
10//! This is what lets a `go!{ c.Send(v); let (x, _) = d.Recv(); }` call site
11//! read identically to a non-goroutine caller. The rewrite is purely
12//! syntactic — there's no type information — so any user method named
13//! `Send`/`Recv`/`Wait` inside a `go!{}` body will also be rewritten.
14//! Collateral damage is the cost of transparent async.
15
16use proc_macro::TokenStream;
17use proc_macro2::TokenStream as TokenStream2;
18use quote::{format_ident, quote};
19use syn::parse::{Parse, ParseStream};
20use syn::visit_mut::{self, VisitMut};
21use syn::{parenthesized, parse_macro_input, parse_quote, Block, Expr, ExprAwait, Ident, Token};
22
23/// Walks the AST, rewriting known goish sync calls into async form.
24struct GoRewriter;
25
26impl VisitMut for GoRewriter {
27    fn visit_expr_mut(&mut self, node: &mut Expr) {
28        // Recurse into children first (so e.g. `a.Send(b.Recv())` rewrites
29        // the inner `Recv` before the outer `Send`).
30        visit_mut::visit_expr_mut(self, node);
31
32        // Rewrite `expr.{Send,Recv,Wait}(...)` → `expr.{send,recv,wait}(...).await`.
33        if let Expr::MethodCall(method_call) = node {
34            let name = method_call.method.to_string();
35            let new_name = match name.as_str() {
36                "Send" => Some("send"),
37                "Recv" => Some("recv"),
38                "Wait" => Some("wait"),
39                _ => None,
40            };
41            if let Some(renamed) = new_name {
42                method_call.method = syn::Ident::new(renamed, method_call.method.span());
43                // Wrap the whole method call in .await.
44                let inner = std::mem::replace(node, parse_quote! { () });
45                *node = Expr::Await(ExprAwait {
46                    attrs: vec![],
47                    base: Box::new(inner),
48                    dot_token: Default::default(),
49                    await_token: Default::default(),
50                });
51            }
52        }
53    }
54}
55
56/// `rewrite_go_body!(stmts...)` — used by `goish::go!{}` macro_rules to
57/// preprocess the user's body. Accepts raw statements, walks them, emits
58/// the rewritten tokens.
59#[proc_macro]
60pub fn rewrite_go_body(input: TokenStream) -> TokenStream {
61    let ts = TokenStream2::from(input);
62    // Wrap in braces so syn can parse as a Block.
63    let mut block: syn::Block = parse_quote!({ #ts });
64    GoRewriter.visit_block_mut(&mut block);
65    let stmts = &block.stmts;
66    let out = quote! { #(#stmts)* };
67    out.into()
68}
69
70// ── select! proc macro ────────────────────────────────────────────────
71//
72// Implements Go's `select` statement with Go-faithful semantics:
73//   - arm expressions evaluated exactly once, in source order;
74//   - no-default parking via `flume::Selector` (one scheduler cycle
75//     wake, no polling);
76//   - uniform-random arbitration among ready arms (flume's built-in);
77//   - `send(closed_chan, v)` always participates in the pick — will
78//     panic even if another recv arm is ready (Go spec compliance).
79//
80// Emission strategy: per-arm payload `Cell`s carry recv data from the
81// Selector's `FnMut` handlers into a post-`wait()` `match __tag.get()`,
82// where the user's arm body runs OUTSIDE all closures and therefore
83// keeps full `&mut` access to its captured environment. This sidesteps
84// the `macro_rules!` attempt's FnMut-borrow conflicts on shared body
85// state (e.g. `w.Write` from two arms of an HTTP handler).
86//
87// See issue #119 for the CSP-derived bug list this macro fixes.
88
89enum Arm {
90    RecvNoBind { ch: Expr, body: Block },
91    RecvOne    { ch: Expr, v: Ident, body: Block },
92    RecvTwo    { ch: Expr, v: Ident, ok: Ident, body: Block },
93    Send       { ch: Expr, val: Expr, body: Block },
94    Default    { body: Block },
95}
96
97struct SelectInput {
98    arms: Vec<Arm>,
99}
100
101impl Parse for SelectInput {
102    fn parse(input: ParseStream) -> syn::Result<Self> {
103        let mut arms = Vec::new();
104        while !input.is_empty() {
105            arms.push(parse_arm(input)?);
106            if input.is_empty() { break; }
107            input.parse::<Token![,]>()?;
108        }
109        Ok(SelectInput { arms })
110    }
111}
112
113fn parse_arm(input: ParseStream) -> syn::Result<Arm> {
114    let kw: Ident = input.parse()?;
115    match kw.to_string().as_str() {
116        "recv" => parse_recv(input),
117        "send" => parse_send(input),
118        "default" => {
119            input.parse::<Token![=>]>()?;
120            let body: Block = input.parse()?;
121            Ok(Arm::Default { body })
122        }
123        _ => Err(syn::Error::new(
124            kw.span(),
125            format!("select! arms must start with `recv`, `send`, or `default`, got `{}`", kw),
126        )),
127    }
128}
129
130fn parse_recv(input: ParseStream) -> syn::Result<Arm> {
131    let content;
132    parenthesized!(content in input);
133    let ch: Expr = content.parse()?;
134    if input.peek(Token![|]) {
135        input.parse::<Token![|]>()?;
136        let v: Ident = input.parse()?;
137        if input.peek(Token![,]) {
138            input.parse::<Token![,]>()?;
139            let ok: Ident = input.parse()?;
140            input.parse::<Token![|]>()?;
141            input.parse::<Token![=>]>()?;
142            let body: Block = input.parse()?;
143            Ok(Arm::RecvTwo { ch, v, ok, body })
144        } else {
145            input.parse::<Token![|]>()?;
146            input.parse::<Token![=>]>()?;
147            let body: Block = input.parse()?;
148            Ok(Arm::RecvOne { ch, v, body })
149        }
150    } else {
151        input.parse::<Token![=>]>()?;
152        let body: Block = input.parse()?;
153        Ok(Arm::RecvNoBind { ch, body })
154    }
155}
156
157fn parse_send(input: ParseStream) -> syn::Result<Arm> {
158    let content;
159    parenthesized!(content in input);
160    let ch: Expr = content.parse()?;
161    content.parse::<Token![,]>()?;
162    let val: Expr = content.parse()?;
163    input.parse::<Token![=>]>()?;
164    let body: Block = input.parse()?;
165    Ok(Arm::Send { ch, val, body })
166}
167
168#[proc_macro]
169pub fn select(input: TokenStream) -> TokenStream {
170    let SelectInput { arms } = parse_macro_input!(input as SelectInput);
171    let mut channel_arms = Vec::new();
172    let mut default_body: Option<Block> = None;
173    for arm in arms {
174        match arm {
175            Arm::Default { body } => {
176                if default_body.is_some() {
177                    return syn::Error::new_spanned(
178                        &body, "select! may have at most one `default` arm",
179                    ).to_compile_error().into();
180                }
181                default_body = Some(body);
182            }
183            other => channel_arms.push(other),
184        }
185    }
186    if let Some(def) = default_body {
187        emit_with_default(&channel_arms, &def).into()
188    } else {
189        emit_no_default(&channel_arms).into()
190    }
191}
192
193fn emit_with_default(arms: &[Arm], default_body: &Block) -> TokenStream2 {
194    // Phase 1: evaluate every arm's channel + send-value expression once,
195    // in source order (Go spec). Phase 2: non-blocking try each arm; if
196    // none fires, run default.
197    let mut setup = TokenStream2::new();
198    let mut tries = TokenStream2::new();
199    for (i, arm) in arms.iter().enumerate() {
200        let ch = format_ident!("__arm_{}_ch", i);
201        let val = format_ident!("__arm_{}_val", i);
202        match arm {
203            Arm::RecvNoBind { ch: e, body } => {
204                setup.extend(quote! { let #ch = &(#e); });
205                tries.extend(quote! {
206                    if !__fired {
207                        if #ch.__select_try_recv().is_some() {
208                            #body
209                            __fired = true;
210                        }
211                    }
212                });
213            }
214            Arm::RecvOne { ch: e, v, body } => {
215                setup.extend(quote! { let #ch = &(#e); });
216                tries.extend(quote! {
217                    if !__fired {
218                        if let ::std::option::Option::Some((#v, _)) = #ch.__select_try_recv() {
219                            #body
220                            __fired = true;
221                        }
222                    }
223                });
224            }
225            Arm::RecvTwo { ch: e, v, ok, body } => {
226                setup.extend(quote! { let #ch = &(#e); });
227                tries.extend(quote! {
228                    if !__fired {
229                        if let ::std::option::Option::Some((#v, #ok)) = #ch.__select_try_recv() {
230                            #body
231                            __fired = true;
232                        }
233                    }
234                });
235            }
236            Arm::Send { ch: e, val: vexpr, body } => {
237                setup.extend(quote! {
238                    let #ch = &(#e);
239                    let mut #val = ::std::option::Option::Some(#vexpr);
240                });
241                tries.extend(quote! {
242                    if !__fired {
243                        if let ::std::option::Option::Some(__v) = #val.take() {
244                            match #ch.__select_try_send(__v) {
245                                ::std::result::Result::Ok(()) => {
246                                    #body
247                                    __fired = true;
248                                }
249                                ::std::result::Result::Err(__returned) => {
250                                    // Buffer full; drop the returned value.
251                                    // (Go spec: send evaluated, not committed.)
252                                    let _ = __returned;
253                                }
254                            }
255                        }
256                    }
257                });
258            }
259            Arm::Default { .. } => unreachable!(),
260        }
261    }
262    quote! {{
263        #setup
264        #[allow(unused_mut, unused_assignments)]
265        let mut __fired = false;
266        #tries
267        if !__fired {
268            #default_body
269        }
270    }}
271}
272
273fn emit_no_default(arms: &[Arm]) -> TokenStream2 {
274    // Phase 1: evaluate expressions once. Phase 2: build flume::Selector
275    // with two arms per input (main chan + shadow close_rx). Phase 3:
276    // dispatch by tag AFTER .wait() so user bodies run outside FnMut
277    // closures.
278    let mut setup = TokenStream2::new();
279    let mut chain = TokenStream2::new();
280    let mut dispatch = TokenStream2::new();
281    for (i, arm) in arms.iter().enumerate() {
282        let ch = format_ident!("__arm_{}_ch", i);
283        let val = format_ident!("__arm_{}_val", i);
284        let payload = format_ident!("__arm_{}_payload", i);
285        let tag = i as u32;
286        match arm {
287            Arm::RecvNoBind { ch: e, body } => {
288                setup.extend(quote! { let #ch = &(#e); });
289                chain.extend(quote! {
290                    .recv(#ch.__flume_rx(), |__res| {
291                        __tag.set(#tag);
292                        // consume and drop the value
293                        let _ = __res;
294                    })
295                    .recv(#ch.__flume_close_rx(), |_: ::std::result::Result<(), ::goish::__flume::RecvError>| {
296                        __tag.set(#tag);
297                        let _ = #ch.__flume_rx().try_recv();
298                    })
299                });
300                dispatch.extend(quote! {
301                    #tag => #body,
302                });
303            }
304            Arm::RecvOne { ch: e, v, body } => {
305                setup.extend(quote! {
306                    let #ch = &(#e);
307                    let #payload: ::std::cell::Cell<::std::option::Option<_>> =
308                        ::std::cell::Cell::new(::std::option::Option::None);
309                });
310                chain.extend(quote! {
311                    .recv(#ch.__flume_rx(), |__res| {
312                        __tag.set(#tag);
313                        let __p: (_, bool) = match __res {
314                            ::std::result::Result::Ok(__x) => (__x, true),
315                            ::std::result::Result::Err(_) => (::std::default::Default::default(), false),
316                        };
317                        #payload.set(::std::option::Option::Some(__p));
318                    })
319                    .recv(#ch.__flume_close_rx(), |_: ::std::result::Result<(), ::goish::__flume::RecvError>| {
320                        __tag.set(#tag);
321                        let __p: (_, bool) = match #ch.__flume_rx().try_recv() {
322                            ::std::result::Result::Ok(__x) => (__x, true),
323                            ::std::result::Result::Err(_) => (::std::default::Default::default(), false),
324                        };
325                        #payload.set(::std::option::Option::Some(__p));
326                    })
327                });
328                dispatch.extend(quote! {
329                    #tag => {
330                        let (#v, _) = #payload.take().expect("select! arm fired but payload missing");
331                        #body
332                    },
333                });
334            }
335            Arm::RecvTwo { ch: e, v, ok, body } => {
336                setup.extend(quote! {
337                    let #ch = &(#e);
338                    let #payload: ::std::cell::Cell<::std::option::Option<_>> =
339                        ::std::cell::Cell::new(::std::option::Option::None);
340                });
341                chain.extend(quote! {
342                    .recv(#ch.__flume_rx(), |__res| {
343                        __tag.set(#tag);
344                        let __p: (_, bool) = match __res {
345                            ::std::result::Result::Ok(__x) => (__x, true),
346                            ::std::result::Result::Err(_) => (::std::default::Default::default(), false),
347                        };
348                        #payload.set(::std::option::Option::Some(__p));
349                    })
350                    .recv(#ch.__flume_close_rx(), |_: ::std::result::Result<(), ::goish::__flume::RecvError>| {
351                        __tag.set(#tag);
352                        let __p: (_, bool) = match #ch.__flume_rx().try_recv() {
353                            ::std::result::Result::Ok(__x) => (__x, true),
354                            ::std::result::Result::Err(_) => (::std::default::Default::default(), false),
355                        };
356                        #payload.set(::std::option::Option::Some(__p));
357                    })
358                });
359                dispatch.extend(quote! {
360                    #tag => {
361                        let (#v, #ok) = #payload.take().expect("select! arm fired but payload missing");
362                        #body
363                    },
364                });
365            }
366            Arm::Send { ch: e, val: vexpr, body } => {
367                setup.extend(quote! {
368                    let #ch = &(#e);
369                    // Go spec: send on closed channel is "always ready" and
370                    // panics. Pre-check before entering Selector so the
371                    // panic fires even if another arm would also be ready.
372                    if #ch.__is_closed() {
373                        ::std::panic!("send on closed channel");
374                    }
375                    let #val = #vexpr;
376                });
377                chain.extend(quote! {
378                    .send(#ch.__flume_tx(), #val, |__res| {
379                        __tag.set(#tag);
380                        // Re-check: channel may have closed between Selector
381                        // build and handler fire. At the flume level the
382                        // main tx is still alive (we only drop the shadow
383                        // sender on Close), so flume's send may report Ok
384                        // even though our close flag is set.
385                        if #ch.__is_closed() || __res.is_err() {
386                            ::std::panic!("send on closed channel");
387                        }
388                    })
389                    .recv(#ch.__flume_close_rx(), |_: ::std::result::Result<(), ::goish::__flume::RecvError>| {
390                        // Shadow close_rx disconnected → channel closed
391                        // during Selector wait. Panic per Go spec.
392                        ::std::panic!("send on closed channel");
393                    })
394                });
395                dispatch.extend(quote! {
396                    #tag => #body,
397                });
398            }
399            Arm::Default { .. } => unreachable!(),
400        }
401    }
402    quote! {{
403        #setup
404        let __tag: ::std::cell::Cell<u32> = ::std::cell::Cell::new(::std::u32::MAX);
405        ::goish::__flume::Selector::new()
406            #chain
407            .wait();
408        match __tag.get() {
409            #dispatch
410            _ => ::std::unreachable!("select! wait() returned without firing any arm"),
411        }
412    }}
413}