Skip to main content

libperl_macros/
lib.rs

1//! Procedural macros for libperl-rs.
2//!
3//! - `#[thx]` — function attribute that splices `my_perl: *mut
4//!   PerlInterpreter` as the first parameter in threaded builds and is a
5//!   no-op in non-threaded builds. Lets a single Rust source compile
6//!   against both `MULTIPLICITY` modes without manual `cfg` branches.
7//! - `#[xs_sub]` — function attribute that turns a high-level Rust
8//!   signature like `fn is_even(n: IV) -> bool { ... }` into a complete
9//!   XS-callable `extern "C"` trampoline. (Phase 3.2 — TBD.)
10//! - `xs_boot!` — declarative macro that emits the module's `boot_<name>`
11//!   entry. (Phase 3.3 — TBD.)
12//!
13//! Threading mode is selected at proc-macro compile time via
14//! `cfg(perl_useithreads)`, set by `build.rs`.
15
16use proc_macro::TokenStream;
17use quote::quote;
18use syn::{parse_macro_input, FnArg, ItemFn};
19
20mod xs_sub;
21mod xs_boot;
22
23/// `#[xs_sub]` — see `xs_sub` module documentation.
24#[proc_macro_attribute]
25pub fn xs_sub(attr: TokenStream, item: TokenStream) -> TokenStream {
26    xs_sub::xs_sub(attr, item)
27}
28
29/// `xs_boot!` — see `xs_boot` module documentation.
30#[proc_macro]
31pub fn xs_boot(input: TokenStream) -> TokenStream {
32    xs_boot::xs_boot(input)
33}
34
35/// `#[thx]` — splice `my_perl: *mut ::libperl_sys::PerlInterpreter` as the
36/// first parameter of `fn` in threaded builds; pass through unchanged in
37/// non-threaded builds.
38///
39/// The injected name `my_perl` matches the C convention (`aTHX_`) and the
40/// project's naming rule (see `docs/plan/README.md` §3.8). The
41/// fully-qualified path `::libperl_sys::PerlInterpreter` is hard-coded
42/// rather than `$crate::PerlInterpreter` because proc-macros emit raw
43/// tokens — the path is resolved at the *call site* of `#[thx]`.
44///
45/// Examples
46/// --------
47///
48/// Source:
49///
50/// ```ignore
51/// #[thx]
52/// fn helper(sv: *mut SV) -> i32 { /* ... */ }
53/// ```
54///
55/// Threaded expansion:
56///
57/// ```ignore
58/// fn helper(my_perl: *mut ::libperl_sys::PerlInterpreter, sv: *mut SV) -> i32 { /* ... */ }
59/// ```
60///
61/// Non-threaded expansion: identical to the input.
62#[proc_macro_attribute]
63pub fn thx(_attr: TokenStream, item: TokenStream) -> TokenStream {
64    let mut func = parse_macro_input!(item as ItemFn);
65    if cfg!(perl_useithreads) {
66        let my_perl_param: FnArg = syn::parse_quote! {
67            my_perl: *mut ::libperl_sys::PerlInterpreter
68        };
69        func.sig.inputs.insert(0, my_perl_param);
70    }
71    quote!(#func).into()
72}