wolfram-export-macros 0.6.0-alpha.6

Procedural macros for #[export] and #[init]
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
//! Codegen for the three `#[export]` modes: native, `wstp`, and `wxf`.
//!
//! The emitted code names items under one of two host crates:
//! - `::wolfram_export::*`    — preferred (new canonical home, with feature flags)
//! - `::wolfram_library_link::*` — back-compat for older user crates
//!
//! [`resolve_host_crate`] inspects the *user's* `Cargo.toml` at expansion time
//! (via [`proc_macro_crate`]) and picks whichever crate they actually depend
//! on. This is how a single proc-macro crate can serve both the new and legacy
//! call sites without forcing users to choose at macro-name level.

use proc_macro::TokenStream;
use proc_macro2::{Delimiter, TokenStream as TokenStream2, TokenTree};

use proc_macro_crate::{crate_name, FoundCrate};
use quote::{format_ident, quote};
use syn::{spanned::Spanned, Error, Ident, Item, Meta, NestedMeta};

/// A parsed, not-yet-quoted `args = (...)`/`ret = ...` signature from
/// `#[export(margs, args = ..., ret = ...)]`. `args` has already been split
/// into one raw token-fragment per parameter (from inside the parens); `ret`
/// is the single raw fragment as-is. Each fragment is spliced verbatim into a
/// `wolfram_expr::expr!(..)` call at codegen time — see [`export_margs_function`].
pub(crate) struct MargsSignature {
    pub args: Vec<TokenStream2>,
    pub ret: TokenStream2,
}

/// Split a flat token stream on top-level commas. Bracketed/braced/parenthesized
/// groups (`[...]`, `(...)`, `{...}`) are already atomic `TokenTree::Group`s at
/// this level, so commas nested inside them are never mistaken for separators.
/// A trailing comma produces no extra empty segment.
fn split_top_level_commas(tokens: TokenStream2) -> Vec<TokenStream2> {
    let mut segments: Vec<TokenStream2> = vec![TokenStream2::new()];
    for tt in tokens {
        match &tt {
            TokenTree::Punct(p) if p.as_char() == ',' => {
                segments.push(TokenStream2::new())
            },
            _ => segments.last_mut().unwrap().extend(std::iter::once(tt)),
        }
    }
    if segments.last().is_some_and(TokenStream2::is_empty) {
        segments.pop();
    }
    segments
}

/// Pull the `args = ...`/`ret = ...` keyword arguments (if any) out of
/// `#[export(...)]`'s raw attribute token stream, returning the remaining
/// tokens (everything else, still comma-separated, ready for the existing
/// `syn::AttributeArgs`-based parser) plus each one's raw value tokens.
///
/// These two keys can't go through `syn::AttributeArgs`/`Meta` at all — that
/// grammar only accepts `key = <literal>`, and `args`/`ret` need arbitrary
/// `expr!`-style token trees (`::List[::Real, ::Real]`, `(::Real, ::Real)`,
/// …) as their value, which isn't a `syn::Lit`. So this runs as a raw
/// token-level pre-pass before any `syn` parsing happens.
pub(crate) fn extract_args_ret_tokens(
    attrs: TokenStream2,
) -> Result<(TokenStream2, Option<TokenStream2>, Option<TokenStream2>), Error> {
    let mut passthrough: Vec<TokenStream2> = Vec::new();
    let mut args_tokens: Option<TokenStream2> = None;
    let mut ret_tokens: Option<TokenStream2> = None;

    for segment in split_top_level_commas(attrs) {
        let mut iter = segment.clone().into_iter();
        let key_and_eq = match (iter.next(), iter.next()) {
            (Some(TokenTree::Ident(key)), Some(TokenTree::Punct(eq)))
                if eq.as_char() == '=' =>
            {
                Some(key)
            },
            _ => None,
        };
        let Some(key) = key_and_eq else {
            passthrough.push(segment);
            continue;
        };
        let key_name = key.to_string();
        if key_name != "args" && key_name != "ret" {
            passthrough.push(segment);
            continue;
        }

        let slot = if key_name == "args" {
            &mut args_tokens
        } else {
            &mut ret_tokens
        };
        if slot.is_some() {
            return Err(Error::new(
                key.span(),
                format!("duplicate `{key_name}` export attribute argument"),
            ));
        }
        let value: TokenStream2 = iter.collect();
        if value.is_empty() {
            return Err(Error::new(
                key.span(),
                format!("expected an expression after `{key_name} =`"),
            ));
        }
        *slot = Some(value);
    }

    let mut remaining = TokenStream2::new();
    for (i, segment) in passthrough.into_iter().enumerate() {
        if i > 0 {
            remaining.extend(std::iter::once(TokenTree::Punct(proc_macro2::Punct::new(
                ',',
                proc_macro2::Spacing::Alone,
            ))));
        }
        remaining.extend(segment);
    }

    Ok((remaining, args_tokens, ret_tokens))
}

/// Validate and shape the raw `args`/`ret` tokens extracted by
/// [`extract_args_ret_tokens`] into a [`MargsSignature`], enforcing that:
/// - they're only used with `Mode::Margs` (every other mode has its own
///   signature source: `FromArg`/`IntoArg` types, or a fixed wire shape);
/// - when given, both `args` and `ret` are given together;
/// - `args`'s value is a parenthesized, comma-separated list — `(t1, t2, ..)`
///   — one raw fragment per parameter (an empty `()` is a valid 0-arg spec).
pub(crate) fn parse_margs_signature(
    mode: Mode,
    args_tokens: Option<TokenStream2>,
    ret_tokens: Option<TokenStream2>,
) -> Result<Option<MargsSignature>, Error> {
    if mode != Mode::Margs {
        if let Some(bad) = args_tokens.or(ret_tokens) {
            return Err(Error::new_spanned(
                bad,
                "`args`/`ret` are only valid with `#[export(margs)]` — every \
                other mode gets its signature from Rust types (`FromArg`/`IntoArg`) \
                or has a fixed wire shape",
            ));
        }
        return Ok(None);
    }

    let (args_tokens, ret_tokens) = match (args_tokens, ret_tokens) {
        (Some(a), Some(r)) => (a, r),
        (None, None) => return Ok(None),
        (a, r) => {
            return Err(Error::new_spanned(
                a.or(r).unwrap(),
                "`#[export(margs, ...)]` requires both `args` and `ret` together, or neither",
            ));
        },
    };

    let mut iter = args_tokens.clone().into_iter();
    let group = match (iter.next(), iter.next()) {
        (Some(TokenTree::Group(g)), None) if g.delimiter() == Delimiter::Parenthesis => g,
        _ => {
            return Err(Error::new_spanned(
                args_tokens,
                "expected `args = (<type>, <type>, ..)` — a parenthesized, \
                comma-separated list of `expr!`-style argument type specs, one \
                per parameter",
            ));
        },
    };
    let args = split_top_level_commas(group.stream());

    Ok(Some(MargsSignature {
        args,
        ret: ret_tokens,
    }))
}

/// Which export shape (native MArgument / raw MArgument / WSTP Link / typed
/// WXF) the macro is generating.
#[derive(Copy, Clone, PartialEq, Eq)]
pub(crate) enum Mode {
    Native,
    Margs,
    Wstp,
    Wxf,
}

/// Path prefix the macro emits — points at the host crate that re-exports
/// the runtime helpers (`call_native_wolfram_library_function`, `ExportEntry`,
/// `inventory`, …). Determined dynamically at expansion time by inspecting
/// the user's `Cargo.toml` so both new users (on `wolfram-export`) and legacy
/// users (on `wolfram-library-link`) see correctly-resolving paths.
pub(crate) struct Prefix {
    pub crate_path: proc_macro2::TokenStream,
}

impl Prefix {
    /// Dynamic host-crate resolution. Prefers `wolfram-export` (the new
    /// canonical crate) and falls back to `wolfram-library-link` for back-
    /// compat. Returns a token stream usable as an absolute path prefix
    /// (`::wolfram_export`, `::wolfram_library_link`, or `crate` if the
    /// macro is called from inside one of those crates itself).
    pub fn resolve() -> Self {
        if let Some(tokens) = found_as("wolfram-export") {
            return Self { crate_path: tokens };
        }
        if let Some(tokens) = found_as("wolfram-library-link") {
            return Self { crate_path: tokens };
        }
        // Neither in the user's deps. Emit a path that will produce a clear
        // unresolved-import compile error at the use-site.
        Self {
            crate_path: quote! { ::__wolfram_export_or_wolfram_library_link_must_be_a_dependency },
        }
    }
}

/// Look up one crate name in the caller's `Cargo.toml`. Returns the path-prefix
/// token stream (`::<rename>`) if found, `None` otherwise.
///
/// We always emit an absolute external path, even when `proc-macro-crate`
/// returns `Itself` (meaning the caller's package owns this crate). Examples,
/// doctests, and integration tests within the same package all compile as
/// separate crates that import the library externally, so `crate::` would
/// resolve to the wrong root. The `#[export]` macro is only ever invoked from
/// those external-import contexts, never from within the library's own source.
fn found_as(name: &str) -> Option<TokenStream2> {
    let renamed = match crate_name(name).ok()? {
        FoundCrate::Itself => name.replace('-', "_"),
        FoundCrate::Name(n) => n,
    };
    let ident = format_ident!("{}", renamed);
    Some(quote! { ::#ident })
}

/// Identifier of the const-assert function the macro emits to surface a clear
/// compile error when the user picked the wrong feature on their host crate.
/// E.g. `Mode::Wxf` → `__assert_wxf_enabled`.
fn assert_fn_ident(mode: Mode) -> Ident {
    match mode {
        Mode::Native => format_ident!("__assert_native_enabled"),
        Mode::Margs => format_ident!("__assert_margs_enabled"),
        Mode::Wstp => format_ident!("__assert_wstp_enabled"),
        Mode::Wxf => format_ident!("__assert_wxf_enabled"),
    }
}

/// Detect the export mode from the keyword args: `margs`, `wstp`, `wxf`, or
/// native (default).
pub(crate) fn detect_mode_from_args(attrs: &syn::AttributeArgs) -> Mode {
    for attr in attrs {
        if let NestedMeta::Meta(Meta::Path(path)) = attr {
            if path.is_ident("margs") {
                return Mode::Margs;
            }
            if path.is_ident("wstp") {
                return Mode::Wstp;
            }
            if path.is_ident("wxf") {
                return Mode::Wxf;
            }
        }
    }
    Mode::Native
}

/// Drop the mode keyword (`margs`, `wstp`, `wxf`) from the arg list — only
/// meaningful to the dispatch shim; the regular arg parser would reject them.
pub(crate) fn strip_wstp_arg(attrs: syn::AttributeArgs) -> syn::AttributeArgs {
    attrs
        .into_iter()
        .filter(|attr| match attr {
            NestedMeta::Meta(Meta::Path(path)) => {
                !path.is_ident("margs") && !path.is_ident("wstp") && !path.is_ident("wxf")
            },
            _ => true,
        })
        .collect()
}

pub(crate) fn export(
    mode: Mode,
    attrs: syn::AttributeArgs,
    item: TokenStream,
    margs_signature: Option<MargsSignature>,
) -> Result<TokenStream2, Error> {
    let prefix = &Prefix::resolve();
    let ExportArgs {
        exported_name,
        hidden,
    } = parse_export_attribute_args(attrs)?;

    let item: Item = syn::parse(item)?;
    let func = match item {
        Item::Fn(func) => func,
        _ => {
            return Err(Error::new(
                proc_macro2::Span::call_site(),
                "this attribute can only be applied to `fn(..) {..}` items",
            ));
        },
    };

    if let Some(async_) = func.sig.asyncness {
        return Err(Error::new(
            async_.span(),
            "exported function cannot be `async`",
        ));
    }
    if let Some(lt) = func.sig.generics.lt_token {
        return Err(Error::new(lt.span(), "exported function cannot be generic"));
    }

    let name = func.sig.ident.clone();
    let exported_name: Ident = match exported_name {
        Some(name) => name,
        None => func.sig.ident.clone(),
    };
    let params = func.sig.inputs.clone();

    let wrapper = match mode {
        Mode::Native => {
            export_native_function(&name, &exported_name, params.len(), hidden, prefix)
        },
        Mode::Margs => {
            export_margs_function(&name, &exported_name, hidden, prefix, margs_signature)
        },
        Mode::Wstp => export_wstp_function(&name, &exported_name, params, hidden, prefix),
        Mode::Wxf => export_wxf_function(&name, &exported_name, params, hidden, prefix),
    };

    Ok(quote! {
        // Include the user's function in the output unchanged.
        #func

        #wrapper
    })
}

//--------------------------------------
// Native (MArgument) wrapper
//--------------------------------------

fn export_native_function(
    name: &Ident,
    exported_name: &Ident,
    parameter_count: usize,
    hidden: bool,
    prefix: &Prefix,
) -> TokenStream2 {
    let params = vec![quote! { _ }; parameter_count];
    let p = &prefix.crate_path;

    let assert_fn = assert_fn_ident(Mode::Native);
    let mut tokens = quote! {
        const _: () = #p::#assert_fn();

        mod #name {
            #[no_mangle]
            pub unsafe extern "C" fn #exported_name(
                lib: #p::sys::WolframLibraryData,
                argc: #p::sys::mint,
                args: *mut #p::sys::MArgument,
                res: #p::sys::MArgument,
            ) -> std::os::raw::c_int {
                let func: fn(#(#params),*) -> _ = super::#name;
                #p::macro_utils::call_native_wolfram_library_function(
                    lib,
                    args,
                    argc,
                    res,
                    func
                )
            }
        }
    };

    if !hidden && cfg!(feature = "automate-function-loading-boilerplate") {
        tokens.extend(quote! {
            #p::inventory::submit! {
                #p::macro_utils::LibraryLinkFunction::Native {
                    name: stringify!(#exported_name),
                    signature: || {
                        let func: fn(#(#params),*) -> _ = #name;
                        let func: &dyn #p::NativeFunction<'_> = &func;
                        func.signature()
                    }
                }
            }
        });
    }

    tokens
}

//--------------------------------------
// Margs (raw MArgument) wrapper
//--------------------------------------

/// Like [`export_native_function`], but the wrapped function always has the
/// fixed signature `fn(&[MArgument], MArgument)` — the user takes full manual
/// control over argument/return marshaling instead of going through
/// `FromArg`/`IntoArg`. Same C ABI as native mode, so it reuses
/// `call_native_wolfram_library_function`; only the signature handed to the
/// user's function differs.
fn export_margs_function(
    name: &Ident,
    exported_name: &Ident,
    hidden: bool,
    prefix: &Prefix,
    signature: Option<MargsSignature>,
) -> TokenStream2 {
    let p = &prefix.crate_path;

    // Emitted only when unannotated, and only inside this function's own
    // `mod #name { .. }` below — NOT at the shared outer scope, which is
    // common to every `#[export(margs)]` function in the file and would
    // collide on this constant's name across more than one of them.
    let missing_signature_warning = if signature.is_none() {
        quote! {
            #[deprecated(note = "\
                `#[export(margs)]` without `args`/`ret` defaults its LibraryFunctionLoad \
                signature to `LinkObject`/`LinkObject` (the same fixed placeholder \
                `#[export(wstp)]` uses) — add `args = (..)` and `ret = ..` to this \
                attribute to declare the real signature")]
            const __MARGS_SIGNATURE_MISSING: () = ();
            const _: () = __MARGS_SIGNATURE_MISSING;
        }
    } else {
        TokenStream2::new()
    };

    let assert_fn = assert_fn_ident(Mode::Margs);
    let mut tokens = quote! {
        const _: () = #p::#assert_fn();

        mod #name {
            #missing_signature_warning

            #[no_mangle]
            pub unsafe extern "C" fn #exported_name(
                lib: #p::sys::WolframLibraryData,
                argc: #p::sys::mint,
                args: *mut #p::sys::MArgument,
                res: #p::sys::MArgument,
            ) -> std::os::raw::c_int {
                // Underscores, not an explicit `&[MArgument]` annotation: a
                // written-out reference type elaborates to a higher-ranked
                // (`for<'r> fn(&'r [MArgument], _)`) fn pointer, which the
                // `NativeFunction<'a>` impl (generic over a *free* lifetime)
                // doesn't unify with. Inferring from `super::#name` instead
                // picks the same non-HRTB instantiation the plain native-mode
                // codegen below relies on.
                let func: fn(_, _) -> _ = super::#name;
                #p::macro_utils::call_native_wolfram_library_function(
                    lib,
                    args,
                    argc,
                    res,
                    func
                )
            }
        }
    };

    // `signature()` always returns a real `(Vec<Expr>, Expr)` — either built
    // from the user's `args = (..)`/`ret = ..` tokens (spliced verbatim into
    // `expr!` calls), or, when omitted, a default of the same fixed
    // `LinkObject`/`LinkObject` placeholder `#[export(wstp)]` uses (with a
    // compile-time nudge to add a real one, since a raw MArgument function
    // certainly doesn't actually take a WSTP `LinkObject`).
    //
    // `expr!` is referenced directly at its defining crate (`wolfram_expr`),
    // not through the `#p` host-crate indirection used elsewhere in this
    // file — a user annotating `args`/`ret` needs `wolfram-expr` as a direct
    // dependency regardless (it's the only place `Expr`/`expr!` come from).
    let signature_fn = match &signature {
        Some(MargsSignature { args, ret }) => quote! {
            || (
                ::std::vec![ #( ::wolfram_expr::expr!(#args) ),* ],
                ::wolfram_expr::expr!(#ret),
            )
        },
        None => quote! {
            || (
                ::std::vec![ ::wolfram_expr::expr!(::LinkObject) ],
                ::wolfram_expr::expr!(::LinkObject),
            )
        },
    };

    if !hidden && cfg!(feature = "automate-function-loading-boilerplate") {
        tokens.extend(quote! {
            #p::inventory::submit! {
                #p::macro_utils::LibraryLinkFunction::Margs {
                    name: stringify!(#exported_name),
                    signature: #signature_fn,
                }
            }
        });
    }

    tokens
}

//--------------------------------------
// WSTP (Link) wrapper
//--------------------------------------

fn export_wstp_function(
    name: &Ident,
    exported_name: &Ident,
    parameter_tys: syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
    hidden: bool,
    prefix: &Prefix,
) -> TokenStream2 {
    let p = &prefix.crate_path;
    let assert_fn = assert_fn_ident(Mode::Wstp);
    let mut tokens = quote! {
        const _: () = #p::#assert_fn();

        mod #name {
            use super::*;

            #[no_mangle]
            pub unsafe extern "C" fn #exported_name(
                lib: #p::sys::WolframLibraryData,
                raw_link: #p::wstp::sys::WSLINK,
            ) -> std::os::raw::c_int {
                let func: fn(#parameter_tys) -> _ = super::#name;
                #p::macro_utils::call_wstp_wolfram_library_function(
                    lib,
                    raw_link,
                    func
                )
            }
        }
    };

    if !hidden && cfg!(feature = "automate-function-loading-boilerplate") {
        tokens.extend(quote! {
            #p::inventory::submit! {
                #p::macro_utils::LibraryLinkFunction::Wstp {
                    name: stringify!(#exported_name)
                }
            }
        });
    }

    tokens
}

//--------------------------------------
// WXF (typed-arg ByteArray) wrapper
//--------------------------------------

fn export_wxf_function(
    name: &Ident,
    exported_name: &Ident,
    params: syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>,
    hidden: bool,
    prefix: &Prefix,
) -> TokenStream2 {
    let p = &prefix.crate_path;
    let n = params.len();
    let n_u64 = n as u64;

    // The user's parameter types, in declaration order. `self` (Receiver) is
    // not expected for free functions but we filter it out defensively.
    let param_types: Vec<&syn::Type> = params
        .iter()
        .filter_map(|arg| match arg {
            syn::FnArg::Typed(pt) => Some(&*pt.ty),
            _ => None,
        })
        .collect();

    let arg_idents: Vec<_> = (0..n).map(|i| quote::format_ident!("__arg{}", i)).collect();

    // Tuple-pattern with a trailing comma for the 1-arity case (Rust syntax).
    let tuple_pat = match arg_idents.len() {
        0 => quote! { () },
        1 => {
            let id = &arg_idents[0];
            quote! { (#id,) }
        },
        _ => quote! { (#(#arg_idents),*) },
    };
    // Tuple-expression of `<Ti as FromWXF>::from_wxf(__c)?` calls.
    let from_cursor_calls: Vec<_> = param_types
        .iter()
        .map(|t| {
            quote! { <#t as #p::macro_utils::FromWXF>::from_wxf(__c)? }
        })
        .collect();
    let tuple_read = match from_cursor_calls.len() {
        0 => quote! { () },
        1 => {
            let c = &from_cursor_calls[0];
            quote! { (#c,) }
        },
        _ => quote! { (#(#from_cursor_calls),*) },
    };

    let assert_fn = assert_fn_ident(Mode::Wxf);
    let mut tokens = quote! {
        const _: () = #p::#assert_fn();

        mod #name {
            use super::*;

            // Single ByteArray arg containing a WXF-serialized `List[args…]`.
            // The kernel retains ownership of the buffer (Constant mode), so
            // we take a reference. Panics (including deserialization failures
            // not caught explicitly) are converted to WXF-encoded Failure[]
            // expressions by `call_and_encode_panic`.
            fn __wxf_bridge(__input: &#p::macro_utils::NumericArray<u8>) -> #p::macro_utils::NumericArray<u8> {
                #p::macro_utils::call_and_encode_panic(|| {
                    // Read args, call the user fn, and serialize the result —
                    // ALL inside the closure, where the borrows into the input
                    // buffer are live. The closure returns an owned
                    // `NumericArray<u8>` (serialized in place, no intermediate
                    // Vec), which does not borrow the buffer, so zero-copy
                    // `&str` / `&[u8]` arguments are sound.
                    let __decoded = #p::macro_utils::decode_args(__input, #n_u64, |__c| {
                        let #tuple_pat = #tuple_read;
                        let __result = super::#name(#(#arg_idents),*);
                        #p::macro_utils::encode_result(&__result)
                    });
                    match __decoded {
                        ::core::result::Result::Ok(__bytes) => __bytes,
                        // Arg decoding failed: build a `Failure["ArgumentError", …]`
                        // from the `wolfram_serialize::Error` (it isn't a Failure itself).
                        ::core::result::Result::Err(__err) => {
                            #p::macro_utils::encode_arg_error(__err)
                        }
                    }
                })
            }

            #[no_mangle]
            pub unsafe extern "C" fn #exported_name(
                lib: #p::sys::WolframLibraryData,
                argc: #p::sys::mint,
                args: *mut #p::sys::MArgument,
                res: #p::sys::MArgument,
            ) -> std::os::raw::c_int {
                let func: fn(_) -> _ = __wxf_bridge;
                #p::macro_utils::call_wxf_wolfram_library_function(
                    lib,
                    args,
                    argc,
                    res,
                    func,
                )
            }
        }
    };

    if !hidden && cfg!(feature = "automate-function-loading-boilerplate") {
        tokens.extend(quote! {
            #p::inventory::submit! {
                #p::macro_utils::LibraryLinkFunction::Wxf {
                    name: stringify!(#exported_name),
                    signature: || #p::macro_utils::wxf_signature(),
                }
            }
        });
    }

    tokens
}

//======================================
// Parse `#[export(<attrs>)]` arguments
//======================================

/// Attribute arguments recognized by all three `#[export*]` macros (the `wstp`
/// mode keyword is no longer accepted — pick `#[export]` from the right
/// runtime crate instead).
struct ExportArgs {
    exported_name: Option<Ident>,
    hidden: bool,
}

fn parse_export_attribute_args(attrs: syn::AttributeArgs) -> Result<ExportArgs, Error> {
    let mut hidden = false;
    let mut exported_name: Option<Ident> = None;

    for attr in attrs {
        match attr {
            NestedMeta::Meta(ref meta) => match meta {
                Meta::Path(path) if path.is_ident("hidden") => {
                    if hidden {
                        return Err(Error::new(
                            attr.span(),
                            "duplicate export `hidden` attribute argument",
                        ));
                    }
                    hidden = true;
                },
                Meta::List(_) | Meta::Path(_) => {
                    return Err(Error::new(
                        attr.span(),
                        "unrecognized export attribute argument",
                    ));
                },
                Meta::NameValue(syn::MetaNameValue { path, lit, .. }) => {
                    if path.is_ident("name") {
                        if exported_name.is_some() {
                            return Err(Error::new(
                                attr.span(),
                                "duplicate definition for `name`",
                            ));
                        }
                        let lit_str = match lit {
                            syn::Lit::Str(str) => str,
                            _ => {
                                return Err(Error::new(
                                    lit.span(),
                                    "expected `name = \"...\"`",
                                ))
                            },
                        };
                        exported_name = Some(
                            lit_str
                                .parse::<Ident>()
                                .map_err(|err| Error::new(lit_str.span(), err))?,
                        );
                    } else {
                        return Err(Error::new(
                            path.span(),
                            "unrecognized export attribute named argument",
                        ));
                    }
                },
            },
            NestedMeta::Lit(_) => {
                return Err(Error::new(
                    attr.span(),
                    "unrecognized export attribute literal argument",
                ));
            },
        }
    }

    Ok(ExportArgs {
        exported_name,
        hidden,
    })
}