Skip to main content

excel_api_macros/
lib.rs

1#![warn(missing_docs)]
2#![doc = include_str!("../README.md")]
3//!
4//! # Excel authoring attributes
5//!
6//! This crate supplies the attributes re-exported by `excel-api`'s default
7//! `macros` feature. They retain the annotated Rust function, generate a fixed
8//! registration descriptor, and emit a panic-contained Excel ABI thunk with the
9//! requested exported name. They accept a deliberately closed signature model;
10//! unsupported types and incompatible context/flag combinations are rejected at
11//! compile time.
12//!
13//! See the repository [macro reference](https://github.com/evnekdev/excel-api/blob/master/docs/guide/macro-reference.md)
14//! for the complete syntax, mapping tables, and compile-fail examples. The
15//! `trybuild` suite is the normative regression test for diagnostic text.
16
17use std::collections::BTreeMap;
18
19use proc_macro::TokenStream;
20use proc_macro2::Span;
21use quote::{format_ident, quote};
22use syn::{
23    Expr, FnArg, GenericArgument, Ident, ItemFn, Lit, LitStr, Meta, MetaNameValue, Pat,
24    PathArguments, ReturnType, Token, Type, parse_macro_input, punctuated::Punctuated,
25};
26
27#[derive(Default)]
28struct FunctionAttributes {
29    name: Option<LitStr>,
30    category: Option<LitStr>,
31    description: Option<LitStr>,
32    thunk: Option<LitStr>,
33    return_type: Option<LitStr>,
34    volatile: bool,
35    thread_safe: bool,
36    macro_type: bool,
37    cluster_safe: bool,
38    asynchronous: bool,
39    arguments: BTreeMap<String, LitStr>,
40}
41
42#[derive(Clone, Copy, Debug, Eq, PartialEq)]
43enum ArgumentKind {
44    Number,
45    Boolean,
46    Integer,
47    GeneralValue,
48    GeneralReference,
49    CountedUtf16,
50    NullTerminatedUtf16,
51}
52
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54enum ResultKind {
55    Number,
56    Boolean,
57    Integer,
58    Xloper12,
59}
60
61#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62enum ContextKind {
63    Worksheet,
64    ThreadSafe,
65    Macro,
66    Async,
67}
68
69enum InvocationArgument {
70    Excel(Ident),
71    Context,
72}
73
74struct ThunkArgument {
75    ident: Ident,
76    ty: Type,
77    kind: ArgumentKind,
78}
79
80/// Generate deterministic worksheet-function registration metadata and an ABI thunk.
81///
82/// The ordinary function is preserved. The generated metadata constant is
83/// named `__EXCEL_FUNCTION_METADATA_<FUNCTION_NAME_IN_UPPERCASE>` and the
84/// Rust-visible thunk item is named
85/// `__excel_function_thunk_<function_name_in_lowercase>`.
86#[proc_macro_attribute]
87pub fn excel_function(attribute: TokenStream, item: TokenStream) -> TokenStream {
88    let attributes = parse_macro_input!(
89        attribute with Punctuated::<Meta, Token![,]>::parse_terminated
90    );
91    let function = parse_macro_input!(item as ItemFn);
92    match expand_excel_function(attributes, function) {
93        Ok(tokens) => tokens.into(),
94        Err(error) => error.into_compile_error().into(),
95    }
96}
97
98fn expand_excel_function(
99    raw_attributes: Punctuated<Meta, Token![,]>,
100    function: ItemFn,
101) -> syn::Result<proc_macro2::TokenStream> {
102    let attributes = parse_attributes(raw_attributes)?;
103    validate_function_shape(&function)?;
104
105    let excel_name = attributes.name.ok_or_else(|| {
106        syn::Error::new(
107            function.sig.ident.span(),
108            "missing required `name = \"...\"`",
109        )
110    })?;
111    let thunk = attributes.thunk.ok_or_else(|| {
112        syn::Error::new(
113            function.sig.ident.span(),
114            "missing required future `thunk = \"...\"` symbol association",
115        )
116    })?;
117    validate_export_name(&thunk)?;
118
119    let mut excel_arguments = Vec::new();
120    let mut thunk_arguments = Vec::new();
121    let mut invocation_arguments = Vec::new();
122    let mut argument_names = Vec::new();
123    let mut argument_help = Vec::new();
124    let mut context = None;
125
126    for input in &function.sig.inputs {
127        let FnArg::Typed(argument) = input else {
128            return Err(syn::Error::new_spanned(input, "methods are not supported"));
129        };
130        let Pat::Ident(pattern) = argument.pat.as_ref() else {
131            return Err(syn::Error::new_spanned(
132                &argument.pat,
133                "destructuring arguments are not supported",
134            ));
135        };
136        if pattern.by_ref.is_some() || pattern.subpat.is_some() {
137            return Err(syn::Error::new_spanned(
138                &argument.pat,
139                "argument patterns must be plain identifiers",
140            ));
141        }
142
143        if let Some(kind) = context_kind(&argument.ty) {
144            if context.replace(kind).is_some() {
145                return Err(syn::Error::new_spanned(
146                    &argument.ty,
147                    "only one injected context is supported",
148                ));
149            }
150            invocation_arguments.push(InvocationArgument::Context);
151            continue;
152        }
153
154        let kind = map_argument_type(&argument.ty)?;
155        if attributes.asynchronous && !async_argument_is_owned(&argument.ty, kind) {
156            return Err(syn::Error::new_spanned(
157                &argument.ty,
158                "asynchronous functions accept only owned, `Send + 'static` inputs; references and callback-borrowed wrappers cannot escape",
159            ));
160        }
161        excel_arguments.push(kind);
162        let name = pattern.ident.to_string();
163        let help = attributes.arguments.get(&name).ok_or_else(|| {
164            syn::Error::new(
165                pattern.ident.span(),
166                format!("missing `arguments({name} = \"help\")` entry"),
167            )
168        })?;
169        argument_names.push(LitStr::new(&name, pattern.ident.span()));
170        argument_help.push(help.clone());
171        thunk_arguments.push(ThunkArgument {
172            ident: pattern.ident.clone(),
173            ty: (*argument.ty).clone(),
174            kind,
175        });
176        invocation_arguments.push(InvocationArgument::Excel(pattern.ident.clone()));
177    }
178
179    if attributes.arguments.len() != argument_names.len() {
180        return Err(syn::Error::new(
181            Span::call_site(),
182            "argument help must name every Excel-visible argument exactly once",
183        ));
184    }
185    if matches!(context, Some(ContextKind::ThreadSafe)) && !attributes.thread_safe {
186        return Err(syn::Error::new(
187            function.sig.ident.span(),
188            "`ThreadSafeContext` requires the `thread_safe` flag",
189        ));
190    }
191    if matches!(context, Some(ContextKind::Worksheet)) && attributes.thread_safe {
192        return Err(syn::Error::new(
193            function.sig.ident.span(),
194            "thread-safe functions must inject `ThreadSafeContext`, not `WorksheetContext`",
195        ));
196    }
197    if matches!(context, Some(ContextKind::Macro)) && !attributes.macro_type {
198        return Err(syn::Error::new(
199            function.sig.ident.span(),
200            "`MacroContext` requires the `macro_type` flag",
201        ));
202    }
203    if attributes.asynchronous && context.is_some() && context != Some(ContextKind::Async) {
204        return Err(syn::Error::new(
205            function.sig.ident.span(),
206            "asynchronous functions can inject only `AsyncCancellationToken`, not an Excel callback context",
207        ));
208    }
209    if !attributes.asynchronous && matches!(context, Some(ContextKind::Async)) {
210        return Err(syn::Error::new(
211            function.sig.ident.span(),
212            "`AsyncCancellationToken` requires the `asynchronous` flag",
213        ));
214    }
215    if attributes.macro_type && (attributes.thread_safe || attributes.cluster_safe) {
216        return Err(syn::Error::new(
217            function.sig.ident.span(),
218            "macro-sheet functions cannot be thread-safe or cluster-safe",
219        ));
220    }
221    if attributes.cluster_safe
222        && excel_arguments
223            .iter()
224            .any(|kind| matches!(kind, ArgumentKind::GeneralReference))
225    {
226        return Err(syn::Error::new(
227            function.sig.ident.span(),
228            "`cluster_safe` functions cannot accept `ExcelReferenceArg` (U); use a value-only `ExcelValueArg` (Q) or remove `cluster_safe`",
229        ));
230    }
231    if attributes.asynchronous && (attributes.cluster_safe || attributes.macro_type) {
232        return Err(syn::Error::new(
233            function.sig.ident.span(),
234            "asynchronous functions cannot be cluster-safe or macro-sheet equivalent",
235        ));
236    }
237
238    if attributes.asynchronous && attributes.return_type.is_some() {
239        return Err(syn::Error::new(
240            function.sig.ident.span(),
241            "asynchronous functions always register a void return; remove `return_type`",
242        ));
243    }
244    let inferred_result = map_result_type(&function.sig.output)?;
245    let result = match attributes.return_type {
246        Some(value) => {
247            let result = parse_result_override(&value)?;
248            if result != inferred_result && result != ResultKind::Xloper12 {
249                return Err(syn::Error::new_spanned(
250                    value,
251                    "a scalar return_type override must match the Rust result; use `xloper12` for a general Excel return",
252                ));
253            }
254            result
255        }
256        None => inferred_result,
257    };
258
259    let function_ident = &function.sig.ident;
260    let metadata_ident = format_ident!(
261        "__EXCEL_FUNCTION_METADATA_{}",
262        function_ident.to_string().to_uppercase(),
263        span = function_ident.span()
264    );
265    let thunk_ident = format_ident!(
266        "__excel_function_thunk_{}",
267        function_ident.to_string().to_lowercase(),
268        span = function_ident.span()
269    );
270    let asynchronous = attributes.asynchronous;
271    let result_metadata = if asynchronous {
272        quote!(::excel_api::ExcelReturnType::AsyncVoid)
273    } else {
274        result_tokens(result)
275    };
276    let mut arguments: Vec<_> = excel_arguments
277        .iter()
278        .copied()
279        .map(argument_tokens)
280        .collect();
281    if asynchronous {
282        arguments.push(quote!(::excel_api::ExcelArgumentType::AsyncHandle));
283    }
284    let category = attributes
285        .category
286        .map(|value| quote!(.category(#value)))
287        .unwrap_or_default();
288    let description = attributes
289        .description
290        .map(|value| quote!(.description(#value)))
291        .unwrap_or_default();
292    let volatile = attributes.volatile;
293    let thread_safe = attributes.thread_safe;
294    let macro_type = attributes.macro_type;
295    let cluster_safe = attributes.cluster_safe;
296    let mut raw_arguments: Vec<_> = thunk_arguments.iter().map(raw_argument_tokens).collect();
297    if asynchronous {
298        raw_arguments.push(quote!(__excel_async_handle: ::excel_api::thunk::RawXloper12));
299    }
300    let conversions: Vec<_> = thunk_arguments.iter().map(conversion_tokens).collect();
301    let async_conversions = conversions.clone();
302    let invoke_arguments = invocation_arguments.iter().map(|argument| match argument {
303        InvocationArgument::Excel(ident) => quote!(#ident),
304        InvocationArgument::Context => quote!(__excel_context),
305    });
306    let invoke = quote!(#function_ident(#(#invoke_arguments),*));
307    let invoke = match context {
308        Some(ContextKind::Worksheet) => {
309            quote!(__excel_scope.with_worksheet_context(|__excel_context| #invoke))
310        }
311        Some(ContextKind::ThreadSafe) => {
312            quote!(__excel_scope.with_thread_safe_context(|__excel_context| #invoke))
313        }
314        Some(ContextKind::Macro) => {
315            quote!(__excel_scope.with_macro_context(|__excel_context| #invoke))
316        }
317        Some(ContextKind::Async) => invoke,
318        None => invoke,
319    };
320    let unwrap_result = if result_error_type(&function.sig.output).is_some() {
321        quote! {
322            let __excel_result = __excel_result
323                .map_err(::excel_api::thunk::function_error)?;
324        }
325    } else {
326        proc_macro2::TokenStream::new()
327    };
328    let converted_result = if asynchronous {
329        quote!(::excel_api::thunk::IntoThunkReturn::into_thunk_return(
330            __excel_result
331        ))
332    } else {
333        match result {
334            ResultKind::Number => quote!(Ok(__excel_result)),
335            ResultKind::Boolean => quote!(Ok(if __excel_result { 1_i16 } else { 0_i16 })),
336            ResultKind::Integer => quote!(Ok(i32::from(__excel_result))),
337            ResultKind::Xloper12 => quote!(::excel_api::thunk::IntoThunkReturn::into_thunk_return(
338                __excel_result
339            )),
340        }
341    };
342    let thunk_body = quote! {
343        ::excel_api::thunk::with_callback(|__excel_scope| {
344            #(#conversions)*
345            let __excel_result = #invoke;
346            #unwrap_result
347            #converted_result
348        })
349    };
350    let thunk_return = if asynchronous {
351        quote!(())
352    } else {
353        match result {
354            ResultKind::Number => quote!(f64),
355            ResultKind::Boolean => quote!(i16),
356            ResultKind::Integer => quote!(i32),
357            ResultKind::Xloper12 => quote!(::excel_api::thunk::RawXloper12),
358        }
359    };
360    let thunk_execution = if asynchronous {
361        let async_invoke_arguments = invocation_arguments.iter().map(|argument| match argument {
362            InvocationArgument::Excel(ident) => quote!(#ident),
363            InvocationArgument::Context => quote!(__excel_cancel),
364        });
365        let async_invoke = quote!(#function_ident(#(#async_invoke_arguments),*));
366        let async_unwrap = if result_error_type(&function.sig.output).is_some() {
367            quote! {
368                let __excel_result = __excel_result
369                    .map_err(::excel_api::thunk::function_error)?;
370            }
371        } else {
372            proc_macro2::TokenStream::new()
373        };
374        quote! {
375            ::excel_api::thunk::async_thunk(__excel_async_handle, || {
376                ::excel_api::thunk::with_callback(|__excel_scope| {
377                    #(#async_conversions)*
378                    let __excel_task: ::excel_api::thunk::AsyncTask = Box::new(move |__excel_cancel| {
379                        let __excel_result = #async_invoke;
380                        #async_unwrap
381                        ::excel_api::thunk::IntoThunkReturn::into_thunk_return(__excel_result)
382                    });
383                    Ok(__excel_task)
384                })
385            })
386        }
387    } else {
388        match result {
389            ResultKind::Number => quote!(::excel_api::thunk::scalar_thunk(0.0_f64, || #thunk_body)),
390            ResultKind::Boolean => quote!(::excel_api::thunk::scalar_thunk(0_i16, || #thunk_body)),
391            ResultKind::Integer => quote!(::excel_api::thunk::scalar_thunk(0_i32, || #thunk_body)),
392            ResultKind::Xloper12 => quote!(::excel_api::thunk::xloper12_thunk(|| #thunk_body)),
393        }
394    };
395
396    Ok(quote! {
397        #function
398
399        #[doc(hidden)]
400        #[doc = "# Safety"]
401        #[doc = "Pointer arguments must be the live callback-owned values described by the generated registration signature."]
402        #[unsafe(export_name = #thunk)]
403        pub unsafe extern "system" fn #thunk_ident(#(#raw_arguments),*) -> #thunk_return {
404            #thunk_execution
405        }
406
407        #[doc(hidden)]
408        #[allow(non_upper_case_globals)]
409        pub const #metadata_ident: ::excel_api::FunctionRegistration =
410            ::excel_api::FunctionRegistration::new(
411                #thunk,
412                #excel_name,
413                ::excel_api::FunctionSignature::new(#result_metadata, &[#(#arguments),*]),
414            )
415            #category
416            #description
417            .arguments(&[#(#argument_names),*], &[#(#argument_help),*])
418            .flags(::excel_api::FunctionFlags {
419                volatile: #volatile,
420                thread_safe: #thread_safe,
421                macro_type: #macro_type,
422                cluster_safe: #cluster_safe,
423            });
424    })
425}
426
427fn raw_argument_tokens(argument: &ThunkArgument) -> proc_macro2::TokenStream {
428    let ident = &argument.ident;
429    let ty = match argument.kind {
430        ArgumentKind::Number => quote!(f64),
431        ArgumentKind::Boolean => quote!(i16),
432        ArgumentKind::Integer => quote!(i32),
433        ArgumentKind::GeneralValue | ArgumentKind::GeneralReference => {
434            quote!(::excel_api::thunk::RawXloper12)
435        }
436        ArgumentKind::CountedUtf16 | ArgumentKind::NullTerminatedUtf16 => {
437            quote!(*mut ::excel_api::thunk::RawXchar)
438        }
439    };
440    quote!(#ident: #ty)
441}
442
443fn conversion_tokens(argument: &ThunkArgument) -> proc_macro2::TokenStream {
444    let ident = &argument.ident;
445    let ty = &argument.ty;
446    match argument.kind {
447        ArgumentKind::Number => quote!(let #ident: #ty = #ident;),
448        ArgumentKind::Boolean => quote!(let #ident: #ty = #ident != 0;),
449        ArgumentKind::Integer => quote! {
450            let #ident: #ty = ::excel_api::thunk::from_excel(
451                ::excel_api::ExcelValueRef::Integer(#ident)
452            )?;
453        },
454        ArgumentKind::GeneralValue | ArgumentKind::GeneralReference => quote! {
455            // SAFETY: forwarded from the generated exported thunk contract.
456            let #ident = unsafe { __excel_scope.decode(#ident) }?;
457            let #ident: #ty = ::excel_api::thunk::from_excel(#ident)?;
458        },
459        ArgumentKind::CountedUtf16 => quote! {
460            // SAFETY: forwarded from the generated exported thunk contract.
461            let #ident: #ty = unsafe { __excel_scope.counted_utf16(#ident) }?;
462        },
463        ArgumentKind::NullTerminatedUtf16 => quote! {
464            // SAFETY: forwarded from the generated exported thunk contract.
465            let #ident: #ty = unsafe { __excel_scope.null_terminated_utf16(#ident) }?;
466        },
467    }
468}
469
470fn parse_attributes(raw: Punctuated<Meta, Token![,]>) -> syn::Result<FunctionAttributes> {
471    let mut parsed = FunctionAttributes::default();
472    for meta in raw {
473        match meta {
474            Meta::NameValue(value) if value.path.is_ident("name") => {
475                set_once(&mut parsed.name, string_value(&value)?, &value)?;
476            }
477            Meta::NameValue(value) if value.path.is_ident("category") => {
478                set_once(&mut parsed.category, string_value(&value)?, &value)?;
479            }
480            Meta::NameValue(value) if value.path.is_ident("description") => {
481                set_once(&mut parsed.description, string_value(&value)?, &value)?;
482            }
483            Meta::NameValue(value) if value.path.is_ident("thunk") => {
484                set_once(&mut parsed.thunk, string_value(&value)?, &value)?;
485            }
486            Meta::NameValue(value) if value.path.is_ident("return_type") => {
487                set_once(&mut parsed.return_type, string_value(&value)?, &value)?;
488            }
489            Meta::Path(path) if path.is_ident("volatile") => set_flag(&mut parsed.volatile, path)?,
490            Meta::Path(path) if path.is_ident("thread_safe") => {
491                set_flag(&mut parsed.thread_safe, path)?;
492            }
493            Meta::Path(path) if path.is_ident("macro_type") => {
494                set_flag(&mut parsed.macro_type, path)?;
495            }
496            Meta::Path(path) if path.is_ident("cluster_safe") => {
497                set_flag(&mut parsed.cluster_safe, path)?;
498            }
499            Meta::Path(path) if path.is_ident("asynchronous") => {
500                set_flag(&mut parsed.asynchronous, path)?;
501            }
502            Meta::List(list) if list.path.is_ident("arguments") => {
503                let values =
504                    list.parse_args_with(Punctuated::<MetaNameValue, Token![,]>::parse_terminated)?;
505                for value in values {
506                    let Some(ident) = value.path.get_ident() else {
507                        return Err(syn::Error::new_spanned(
508                            value.path,
509                            "argument help keys must be identifiers",
510                        ));
511                    };
512                    let name = ident.to_string();
513                    let help = string_value(&value)?;
514                    if parsed.arguments.insert(name.clone(), help).is_some() {
515                        return Err(syn::Error::new_spanned(
516                            ident,
517                            format!("duplicate help for argument `{name}`"),
518                        ));
519                    }
520                }
521            }
522            unsupported => {
523                return Err(syn::Error::new_spanned(
524                    unsupported,
525                    "unsupported `excel_function` attribute option",
526                ));
527            }
528        }
529    }
530    Ok(parsed)
531}
532
533fn set_once<T>(slot: &mut Option<T>, value: T, source: &MetaNameValue) -> syn::Result<()> {
534    if slot.replace(value).is_some() {
535        Err(syn::Error::new_spanned(
536            source,
537            "duplicate attribute option",
538        ))
539    } else {
540        Ok(())
541    }
542}
543
544fn set_flag(slot: &mut bool, path: syn::Path) -> syn::Result<()> {
545    if std::mem::replace(slot, true) {
546        Err(syn::Error::new_spanned(path, "duplicate flag"))
547    } else {
548        Ok(())
549    }
550}
551
552fn string_value(value: &MetaNameValue) -> syn::Result<LitStr> {
553    if let Expr::Lit(expression) = &value.value {
554        if let Lit::Str(string) = &expression.lit {
555            return Ok(string.clone());
556        }
557    }
558    Err(syn::Error::new_spanned(
559        &value.value,
560        "expected a string literal",
561    ))
562}
563
564fn validate_export_name(value: &LitStr) -> syn::Result<()> {
565    let name = value.value();
566    let mut characters = name.chars();
567    let valid_start = characters
568        .next()
569        .is_some_and(|character| character == '_' || character.is_ascii_alphabetic());
570    if !valid_start
571        || !characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
572    {
573        return Err(syn::Error::new_spanned(
574            value,
575            "thunk must be a non-empty ASCII x64 export identifier",
576        ));
577    }
578    Ok(())
579}
580
581fn validate_function_shape(function: &ItemFn) -> syn::Result<()> {
582    let signature = &function.sig;
583    if signature
584        .inputs
585        .iter()
586        .any(|input| matches!(input, FnArg::Receiver(_)))
587    {
588        return Err(syn::Error::new_spanned(
589            signature,
590            "methods are not supported",
591        ));
592    }
593    if signature.variadic.is_some() {
594        return Err(syn::Error::new_spanned(
595            signature,
596            "variadic functions are not supported",
597        ));
598    }
599    if signature.asyncness.is_some() {
600        return Err(syn::Error::new_spanned(
601            signature,
602            "async functions are not supported",
603        ));
604    }
605    if signature.unsafety.is_some() {
606        return Err(syn::Error::new_spanned(
607            signature,
608            "unsafe functions are not supported",
609        ));
610    }
611    if signature.abi.is_some() {
612        return Err(syn::Error::new_spanned(
613            signature,
614            "ABI functions are not supported; use an ordinary Rust function and let `#[excel_function]` generate the Excel thunk",
615        ));
616    }
617    if !signature.generics.params.is_empty() || signature.generics.where_clause.is_some() {
618        return Err(syn::Error::new_spanned(
619            signature,
620            "generic functions are not supported",
621        ));
622    }
623    Ok(())
624}
625
626fn context_kind(ty: &Type) -> Option<ContextKind> {
627    if let Type::Path(path) = ty {
628        if path.path.segments.last()?.ident == "AsyncCancellationToken" {
629            return Some(ContextKind::Async);
630        }
631    }
632    let Type::Reference(reference) = ty else {
633        return None;
634    };
635    if reference.mutability.is_some() {
636        return None;
637    }
638    let Type::Path(path) = reference.elem.as_ref() else {
639        return None;
640    };
641    match path.path.segments.last()?.ident.to_string().as_str() {
642        "WorksheetContext" => Some(ContextKind::Worksheet),
643        "ThreadSafeContext" => Some(ContextKind::ThreadSafe),
644        "MacroContext" => Some(ContextKind::Macro),
645        _ => None,
646    }
647}
648
649fn async_argument_is_owned(ty: &Type, kind: ArgumentKind) -> bool {
650    if matches!(
651        kind,
652        ArgumentKind::GeneralReference
653            | ArgumentKind::CountedUtf16
654            | ArgumentKind::NullTerminatedUtf16
655    ) {
656        return false;
657    }
658    let Type::Path(path) = ty else {
659        return false;
660    };
661    let Some(segment) = path.path.segments.last() else {
662        return false;
663    };
664    if segment.ident == "ExcelValueArg" {
665        return false;
666    }
667    if segment.ident == "Option" || segment.ident == "OptionalValue" {
668        return one_type_argument(segment, ty).ok().is_some_and(|inner_ty| {
669            map_argument_type(inner_ty)
670                .is_ok_and(|inner_kind| async_argument_is_owned(inner_ty, inner_kind))
671        });
672    }
673    true
674}
675
676fn map_argument_type(ty: &Type) -> syn::Result<ArgumentKind> {
677    let Type::Path(path) = ty else {
678        return Err(unsupported_type(ty));
679    };
680    let segment = path
681        .path
682        .segments
683        .last()
684        .ok_or_else(|| unsupported_type(ty))?;
685    let name = segment.ident.to_string();
686    match name.as_str() {
687        "f64" => Ok(ArgumentKind::Number),
688        "bool" => Ok(ArgumentKind::Boolean),
689        "i16" | "i32" | "u16" => Ok(ArgumentKind::Integer),
690        "ExcelString" | "String" | "ExcelArray" | "ExcelValue" | "ExcelValueArg" => {
691            Ok(ArgumentKind::GeneralValue)
692        }
693        "ExcelReferenceArg" => Ok(ArgumentKind::GeneralReference),
694        "CountedUtf16Arg" => Ok(ArgumentKind::CountedUtf16),
695        "NullTerminatedUtf16Arg" => Ok(ArgumentKind::NullTerminatedUtf16),
696        "ExcelValueRef" => Err(syn::Error::new_spanned(
697            ty,
698            "ambiguous `ExcelValueRef` input; use `ExcelValueArg` (Q) or `ExcelReferenceArg` (U)",
699        )),
700        "Option" | "OptionalValue" => {
701            let inner = one_type_argument(segment, ty)?;
702            match map_argument_type(inner)? {
703                ArgumentKind::GeneralReference => Ok(ArgumentKind::GeneralReference),
704                ArgumentKind::CountedUtf16 | ArgumentKind::NullTerminatedUtf16 => Err(
705                    syn::Error::new_spanned(ty, "direct UTF-16 arguments cannot be optional"),
706                ),
707                _ => Ok(ArgumentKind::GeneralValue),
708            }
709        }
710        _ => Err(unsupported_type(ty)),
711    }
712}
713
714fn map_result_type(output: &ReturnType) -> syn::Result<ResultKind> {
715    let ReturnType::Type(_, ty) = output else {
716        return Err(syn::Error::new_spanned(
717            output,
718            "worksheet functions must return a supported value",
719        ));
720    };
721    map_result_type_inner(ty)
722}
723
724fn result_error_type(output: &ReturnType) -> Option<&Type> {
725    let ReturnType::Type(_, ty) = output else {
726        return None;
727    };
728    let Type::Path(path) = ty.as_ref() else {
729        return None;
730    };
731    let segment = path.path.segments.last()?;
732    (segment.ident == "Result")
733        .then(|| two_type_arguments(segment, ty).ok().map(|(_, error)| error))
734        .flatten()
735}
736
737fn map_result_type_inner(ty: &Type) -> syn::Result<ResultKind> {
738    if matches!(ty, Type::Reference(_)) {
739        return Err(syn::Error::new_spanned(
740            ty,
741            "borrowed returns are not supported",
742        ));
743    }
744    let Type::Path(path) = ty else {
745        return Err(unsupported_type(ty));
746    };
747    let segment = path
748        .path
749        .segments
750        .last()
751        .ok_or_else(|| unsupported_type(ty))?;
752    match segment.ident.to_string().as_str() {
753        "f64" => Ok(ResultKind::Number),
754        "bool" => Ok(ResultKind::Boolean),
755        "i16" | "i32" | "u16" => Ok(ResultKind::Integer),
756        "ExcelString" | "String" | "ExcelArray" | "ExcelValue" | "ExcelReturnValue"
757        | "ExcelError" => Ok(ResultKind::Xloper12),
758        "Result" => {
759            let (success, error) = two_type_arguments(segment, ty)?;
760            validate_result_error(error)?;
761            map_result_type_inner(success)
762        }
763        "ExcelStr" | "CountedUtf16Arg" | "NullTerminatedUtf16Arg" => Err(syn::Error::new_spanned(
764            ty,
765            "direct dynamic-string returns are not supported",
766        )),
767        _ => Err(unsupported_type(ty)),
768    }
769}
770
771fn validate_result_error(ty: &Type) -> syn::Result<()> {
772    let Type::Path(path) = ty else {
773        return Err(syn::Error::new_spanned(
774            ty,
775            "unsupported Result error; use a documented excel-api error type",
776        ));
777    };
778    let Some(segment) = path.path.segments.last() else {
779        return Err(unsupported_type(ty));
780    };
781    match segment.ident.to_string().as_str() {
782        "ExcelError"
783        | "ConversionError"
784        | "ReturnError"
785        | "ReturnMaterializationError"
786        | "ThunkError" => Ok(()),
787        _ => Err(syn::Error::new_spanned(
788            ty,
789            "unsupported Result error; use ExcelError, ConversionError, ReturnError, ReturnMaterializationError, or ThunkError",
790        )),
791    }
792}
793
794fn one_type_argument<'a>(segment: &'a syn::PathSegment, ty: &Type) -> syn::Result<&'a Type> {
795    let PathArguments::AngleBracketed(arguments) = &segment.arguments else {
796        return Err(unsupported_type(ty));
797    };
798    let mut types = arguments.args.iter().filter_map(|argument| match argument {
799        GenericArgument::Type(ty) => Some(ty),
800        _ => None,
801    });
802    let first = types.next().ok_or_else(|| unsupported_type(ty))?;
803    if types.next().is_some() {
804        return Err(unsupported_type(ty));
805    }
806    Ok(first)
807}
808
809fn two_type_arguments<'a>(
810    segment: &'a syn::PathSegment,
811    ty: &Type,
812) -> syn::Result<(&'a Type, &'a Type)> {
813    let PathArguments::AngleBracketed(arguments) = &segment.arguments else {
814        return Err(unsupported_type(ty));
815    };
816    let types = arguments
817        .args
818        .iter()
819        .filter_map(|argument| match argument {
820            GenericArgument::Type(ty) => Some(ty),
821            _ => None,
822        })
823        .collect::<Vec<_>>();
824    if types.len() != 2 {
825        return Err(unsupported_type(ty));
826    }
827    Ok((types[0], types[1]))
828}
829
830fn parse_result_override(value: &LitStr) -> syn::Result<ResultKind> {
831    match value.value().as_str() {
832        "number" => Ok(ResultKind::Number),
833        "boolean" => Ok(ResultKind::Boolean),
834        "integer" => Ok(ResultKind::Integer),
835        "xloper12" => Ok(ResultKind::Xloper12),
836        _ => Err(syn::Error::new_spanned(
837            value,
838            "return_type must be `number`, `boolean`, `integer`, or `xloper12`",
839        )),
840    }
841}
842
843fn unsupported_type(ty: &Type) -> syn::Error {
844    syn::Error::new_spanned(
845        ty,
846        "type is not supported by the closed Excel metadata mapping",
847    )
848}
849
850fn argument_tokens(kind: ArgumentKind) -> proc_macro2::TokenStream {
851    let variant = match kind {
852        ArgumentKind::Number => quote!(Number),
853        ArgumentKind::Boolean => quote!(Boolean),
854        ArgumentKind::Integer => quote!(Integer),
855        ArgumentKind::GeneralValue => quote!(GeneralValue),
856        ArgumentKind::GeneralReference => quote!(GeneralReference),
857        ArgumentKind::CountedUtf16 => quote!(CountedUtf16),
858        ArgumentKind::NullTerminatedUtf16 => quote!(NullTerminatedUtf16),
859    };
860    quote!(::excel_api::ExcelArgumentType::#variant)
861}
862
863fn result_tokens(kind: ResultKind) -> proc_macro2::TokenStream {
864    let variant = match kind {
865        ResultKind::Number => quote!(Number),
866        ResultKind::Boolean => quote!(Boolean),
867        ResultKind::Integer => quote!(Integer),
868        ResultKind::Xloper12 => quote!(Xloper12),
869    };
870    quote!(::excel_api::ExcelReturnType::#variant)
871}
872
873/// Mark a Rust function for future command registration.
874///
875/// Command metadata and thunks remain deferred to M12.
876#[proc_macro_attribute]
877pub fn excel_command(_attribute: TokenStream, item: TokenStream) -> TokenStream {
878    let attributes = parse_macro_input!(
879        _attribute with Punctuated::<Meta, Token![,]>::parse_terminated
880    );
881    let command = parse_macro_input!(item as ItemFn);
882    match expand_excel_command(attributes, command) {
883        Ok(tokens) => tokens.into(),
884        Err(error) => error.into_compile_error().into(),
885    }
886}
887
888fn expand_excel_command(
889    raw_attributes: Punctuated<Meta, Token![,]>,
890    command: ItemFn,
891) -> syn::Result<proc_macro2::TokenStream> {
892    let attributes = parse_attributes(raw_attributes)?;
893    validate_function_shape(&command)?;
894    if attributes.category.is_some()
895        || attributes.return_type.is_some()
896        || attributes.volatile
897        || attributes.thread_safe
898        || attributes.macro_type
899        || attributes.cluster_safe
900        || !attributes.arguments.is_empty()
901    {
902        return Err(syn::Error::new_spanned(
903            &command.sig,
904            "commands accept only name, thunk, and description metadata",
905        ));
906    }
907    let excel_name = attributes.name.ok_or_else(|| {
908        syn::Error::new(
909            command.sig.ident.span(),
910            "missing required `name = \"...\"`",
911        )
912    })?;
913    let thunk = attributes.thunk.ok_or_else(|| {
914        syn::Error::new(
915            command.sig.ident.span(),
916            "missing required `thunk = \"...\"`",
917        )
918    })?;
919    validate_export_name(&thunk)?;
920    if command.sig.inputs.len() != 1
921        || !matches!(command.sig.inputs.first(), Some(FnArg::Typed(argument)) if context_kind(&argument.ty) == Some(ContextKind::Macro))
922    {
923        return Err(syn::Error::new_spanned(
924            &command.sig.inputs,
925            "commands must take exactly one `&MacroContext` argument",
926        ));
927    }
928    let result_error = match &command.sig.output {
929        ReturnType::Default => None,
930        ReturnType::Type(_, ty) if matches!(ty.as_ref(), Type::Tuple(tuple) if tuple.elems.is_empty()) => {
931            None
932        }
933        ReturnType::Type(_, ty) => {
934            let Type::Path(path) = ty.as_ref() else {
935                return Err(syn::Error::new_spanned(
936                    ty,
937                    "commands must return `()` or `Result<(), E>`",
938                ));
939            };
940            let segment = path
941                .path
942                .segments
943                .last()
944                .ok_or_else(|| unsupported_type(ty))?;
945            let (success, error) = two_type_arguments(segment, ty)?;
946            if segment.ident != "Result"
947                || !matches!(success, Type::Tuple(tuple) if tuple.elems.is_empty())
948            {
949                return Err(syn::Error::new_spanned(
950                    ty,
951                    "commands must return `()` or `Result<(), E>`",
952                ));
953            }
954            validate_result_error(error)?;
955            Some(error)
956        }
957    };
958    let function_ident = &command.sig.ident;
959    let metadata_ident = format_ident!(
960        "__EXCEL_COMMAND_METADATA_{}",
961        function_ident.to_string().to_uppercase(),
962        span = function_ident.span()
963    );
964    let thunk_ident = format_ident!(
965        "__excel_command_thunk_{}",
966        function_ident.to_string().to_lowercase(),
967        span = function_ident.span()
968    );
969    let description = attributes
970        .description
971        .map(|value| quote!(.description(#value)))
972        .unwrap_or_default();
973    let invoke = if result_error.is_some() {
974        quote! {
975            #function_ident(__excel_context)
976                .map_err(::excel_api::thunk::function_error)?;
977        }
978    } else {
979        quote!(#function_ident(__excel_context);)
980    };
981    Ok(quote! {
982        #command
983
984        #[doc(hidden)]
985        #[unsafe(export_name = #thunk)]
986        pub extern "system" fn #thunk_ident() -> i16 {
987            ::excel_api::thunk::scalar_thunk(0_i16, || {
988                ::excel_api::thunk::with_callback(|__excel_scope| {
989                    __excel_scope.with_macro_context(|__excel_context| {
990                        #invoke
991                        Ok(1_i16)
992                    })
993                })
994            })
995        }
996
997        #[doc(hidden)]
998        #[allow(non_upper_case_globals)]
999        pub const #metadata_ident: ::excel_api::CommandRegistration =
1000            ::excel_api::CommandRegistration::new(#thunk, #excel_name)
1001                #description;
1002    })
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007    use super::*;
1008    use syn::parse_quote;
1009
1010    fn shape_error(function: ItemFn) -> String {
1011        validate_function_shape(&function).unwrap_err().to_string()
1012    }
1013
1014    #[test]
1015    fn rejects_unsupported_function_shapes() {
1016        assert!(
1017            shape_error(parse_quote!(
1018                async fn f() -> i32 {
1019                    0
1020                }
1021            ))
1022            .contains("async")
1023        );
1024        assert!(
1025            shape_error(parse_quote!(
1026                fn f<T>() -> i32 {
1027                    0
1028                }
1029            ))
1030            .contains("generic")
1031        );
1032        assert!(
1033            shape_error(parse_quote!(
1034                fn f(&self) -> i32 {
1035                    0
1036                }
1037            ))
1038            .contains("methods")
1039        );
1040        assert!(
1041            shape_error(parse_quote!(
1042                unsafe extern "C" fn f(_: i32, ...) -> i32 {
1043                    0
1044                }
1045            ))
1046            .contains("variadic")
1047        );
1048    }
1049
1050    #[test]
1051    fn rejects_unsupported_and_ambiguous_types() {
1052        let impl_trait: Type = parse_quote!(impl Iterator<Item = i32>);
1053        let ambiguous: Type = parse_quote!(ExcelValueRef<'_>);
1054        let borrowed: ReturnType = parse_quote!(-> &str);
1055        let direct_string: ReturnType = parse_quote!(-> CountedUtf16Arg<'_>);
1056        assert!(map_argument_type(&impl_trait).is_err());
1057        assert!(
1058            map_argument_type(&ambiguous)
1059                .unwrap_err()
1060                .to_string()
1061                .contains("ambiguous")
1062        );
1063        assert!(
1064            map_result_type(&borrowed)
1065                .unwrap_err()
1066                .to_string()
1067                .contains("borrowed")
1068        );
1069        assert!(
1070            map_result_type(&direct_string)
1071                .unwrap_err()
1072                .to_string()
1073                .contains("dynamic-string")
1074        );
1075    }
1076
1077    #[test]
1078    fn rejects_destructuring_and_unlisted_result_errors() {
1079        let function: ItemFn = parse_quote!(
1080            fn f((left, right): (i32, i32)) -> i32 {
1081                left + right
1082            }
1083        );
1084        let attributes: Punctuated<Meta, Token![,]> =
1085            parse_quote!(name = "F", thunk = "f_thunk", arguments(left = "left"));
1086        assert!(
1087            expand_excel_function(attributes, function)
1088                .unwrap_err()
1089                .to_string()
1090                .contains("destructuring")
1091        );
1092
1093        let unsupported: ReturnType = parse_quote!(-> Result<i32, String>);
1094        assert!(map_result_type(&unsupported).is_err());
1095    }
1096
1097    #[test]
1098    fn rejects_invalid_exports_and_incompatible_scalar_overrides() {
1099        let function: ItemFn = parse_quote!(
1100            fn value() -> f64 {
1101                1.0
1102            }
1103        );
1104        let invalid_export: Punctuated<Meta, Token![,]> =
1105            parse_quote!(name = "VALUE", thunk = "not-an-export");
1106        assert!(
1107            expand_excel_function(invalid_export, function.clone())
1108                .unwrap_err()
1109                .to_string()
1110                .contains("ASCII x64 export")
1111        );
1112
1113        let invalid_override: Punctuated<Meta, Token![,]> =
1114            parse_quote!(name = "VALUE", thunk = "value", return_type = "boolean");
1115        assert!(
1116            expand_excel_function(invalid_override, function)
1117                .unwrap_err()
1118                .to_string()
1119                .contains("must match")
1120        );
1121    }
1122
1123    #[test]
1124    fn deterministic_metadata_and_exact_xloper12_thunk_are_generated() {
1125        let function: ItemFn = parse_quote!(
1126            fn add(x: f64, y: f64) -> f64 {
1127                x + y
1128            }
1129        );
1130        let attributes: Punctuated<Meta, Token![,]> = parse_quote!(
1131            name = "RUST.ADD",
1132            category = "Rust",
1133            description = "Adds",
1134            thunk = "rust_add",
1135            return_type = "xloper12",
1136            thread_safe,
1137            arguments(x = "x", y = "y")
1138        );
1139        let expanded = expand_excel_function(attributes, function)
1140            .unwrap()
1141            .to_string();
1142        assert!(expanded.contains("__EXCEL_FUNCTION_METADATA_ADD"));
1143        assert!(expanded.contains("__excel_function_thunk_add"));
1144        assert!(expanded.contains("FunctionRegistration"));
1145        assert!(expanded.contains("export_name = \"rust_add\""));
1146        assert!(expanded.contains("unsafe extern \"system\""));
1147        assert!(expanded.contains("f64 , y : f64"));
1148        assert!(expanded.contains("thunk :: RawXloper12"));
1149        assert!(expanded.contains("thunk :: xloper12_thunk"));
1150        assert!(expanded.contains("thunk :: with_callback"));
1151    }
1152
1153    #[test]
1154    fn scalar_and_pointer_abi_signatures_come_from_the_registration_model() {
1155        let function: ItemFn = parse_quote!(
1156            fn probe(flag: bool, integer: i16, value: ExcelValueArg<'_>) -> bool {
1157                let _ = (integer, value);
1158                flag
1159            }
1160        );
1161        let attributes: Punctuated<Meta, Token![,]> = parse_quote!(
1162            name = "PROBE",
1163            thunk = "probe_export",
1164            arguments(flag = "flag", integer = "integer", value = "value")
1165        );
1166        let expanded = expand_excel_function(attributes, function)
1167            .unwrap()
1168            .to_string();
1169        assert!(expanded.contains("flag : i16"));
1170        assert!(expanded.contains("integer : i32"));
1171        assert!(expanded.contains("value : :: excel_api :: thunk :: RawXloper12"));
1172        assert!(expanded.contains("-> i16"));
1173        assert!(expanded.contains("ExcelArgumentType :: Boolean"));
1174        assert!(expanded.contains("ExcelArgumentType :: Integer"));
1175        assert!(expanded.contains("ExcelArgumentType :: GeneralValue"));
1176    }
1177
1178    #[test]
1179    fn asynchronous_thunk_is_void_owned_and_handle_terminated() {
1180        let function: ItemFn = parse_quote!(
1181            fn delayed(value: ExcelString, cancel: AsyncCancellationToken) -> ExcelString {
1182                let _ = cancel;
1183                value
1184            }
1185        );
1186        let attributes: Punctuated<Meta, Token![,]> = parse_quote!(
1187            name = "ASYNC.DELAYED",
1188            thunk = "async_delayed",
1189            asynchronous,
1190            thread_safe,
1191            arguments(value = "value")
1192        );
1193        let expanded = expand_excel_function(attributes, function)
1194            .unwrap()
1195            .to_string();
1196        assert!(expanded.contains("ExcelReturnType :: AsyncVoid"));
1197        assert!(expanded.contains("ExcelArgumentType :: AsyncHandle"));
1198        assert!(expanded.contains("async_thunk"));
1199        assert!(expanded.contains("AsyncTask"));
1200        assert!(expanded.contains("-> ()"));
1201
1202        let borrowed: ItemFn = parse_quote!(
1203            fn bad(value: ExcelValueArg<'_>) -> ExcelString {
1204                let _ = value;
1205                ExcelString::from("bad")
1206            }
1207        );
1208        let attributes: Punctuated<Meta, Token![,]> = parse_quote!(
1209            name = "ASYNC.BAD",
1210            thunk = "async_bad",
1211            asynchronous,
1212            arguments(value = "value")
1213        );
1214        assert!(
1215            expand_excel_function(attributes, borrowed)
1216                .unwrap_err()
1217                .to_string()
1218                .contains("only owned")
1219        );
1220    }
1221}