Skip to main content

excel_api/
registration.rs

1use core::fmt;
2
3use excel_api_sys::{
4    XLL_MODIFIER_CLUSTER_SAFE, XLL_MODIFIER_MACRO_SHEET, XLL_MODIFIER_THREAD_SAFE,
5    XLL_MODIFIER_VOLATILE, XLL_TYPE_ASYNC_HANDLE, XLL_TYPE_ASYNC_VOID, XLL_TYPE_BOOL,
6    XLL_TYPE_DOUBLE, XLL_TYPE_I32, XLL_TYPE_XCHAR_COUNTED, XLL_TYPE_XCHAR_NULL_TERMINATED,
7    XLL_TYPE_XLOPER12_REFERENCE, XLL_TYPE_XLOPER12_VALUE,
8};
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11/// One Excel registration type code for a generated function parameter.
12pub enum ExcelArgumentType {
13    /// `B`: 64-bit floating-point number.
14    Number,
15    /// `A`: Boolean.
16    Boolean,
17    /// `J`: 32-bit integer.
18    Integer,
19    /// `Q`: value-only `XLOPER12` argument.
20    GeneralValue,
21    /// `U`: reference-preserving `XLOPER12` argument.
22    GeneralReference,
23    /// `D%`: counted direct UTF-16 argument.
24    CountedUtf16,
25    /// `C%`: NUL-terminated direct UTF-16 argument.
26    NullTerminatedUtf16,
27    /// `X`: internal asynchronous completion handle.
28    AsyncHandle,
29}
30
31impl ExcelArgumentType {
32    const fn code(self) -> &'static str {
33        match self {
34            Self::Number => XLL_TYPE_DOUBLE,
35            Self::Boolean => XLL_TYPE_BOOL,
36            Self::Integer => XLL_TYPE_I32,
37            Self::GeneralValue => XLL_TYPE_XLOPER12_VALUE,
38            Self::GeneralReference => XLL_TYPE_XLOPER12_REFERENCE,
39            Self::CountedUtf16 => XLL_TYPE_XCHAR_COUNTED,
40            Self::NullTerminatedUtf16 => XLL_TYPE_XCHAR_NULL_TERMINATED,
41            Self::AsyncHandle => XLL_TYPE_ASYNC_HANDLE,
42        }
43    }
44}
45
46#[derive(Clone, Copy, Debug, Eq, PartialEq)]
47/// Excel registration type code for a generated function result.
48pub enum ExcelReturnType {
49    /// `B`: 64-bit floating-point number.
50    Number,
51    /// `A`: Boolean.
52    Boolean,
53    /// `J`: 32-bit integer.
54    Integer,
55    /// `Q`: an `XLOPER12` return root.
56    Xloper12,
57    /// `>`: asynchronous void result completed through `xlAsyncReturn`.
58    AsyncVoid,
59}
60
61impl ExcelReturnType {
62    const fn code(self) -> &'static str {
63        match self {
64            Self::Number => XLL_TYPE_DOUBLE,
65            Self::Boolean => XLL_TYPE_BOOL,
66            Self::Integer => XLL_TYPE_I32,
67            Self::Xloper12 => XLL_TYPE_XLOPER12_VALUE,
68            Self::AsyncVoid => XLL_TYPE_ASYNC_VOID,
69        }
70    }
71}
72
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74/// Result and argument type metadata used to construct registration type text.
75pub struct FunctionSignature {
76    /// Excel-visible result type.
77    pub result: ExcelReturnType,
78    /// Excel-visible and internal argument types in declaration order.
79    pub arguments: &'static [ExcelArgumentType],
80}
81
82impl FunctionSignature {
83    /// Creates a static function signature.
84    pub const fn new(result: ExcelReturnType, arguments: &'static [ExcelArgumentType]) -> Self {
85        Self { result, arguments }
86    }
87}
88
89#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
90/// Optional Excel registration modifiers for a worksheet function.
91pub struct FunctionFlags {
92    /// Adds the volatile modifier.
93    pub volatile: bool,
94    /// Requests Excel's thread-safe registration modifier.
95    pub thread_safe: bool,
96    /// Marks the function as macro-sheet equivalent.
97    pub macro_type: bool,
98    /// Requests the cluster-safe modifier when otherwise legal.
99    pub cluster_safe: bool,
100}
101
102#[derive(Clone, Copy, Debug)]
103/// Complete static registration metadata for one worksheet function.
104pub struct FunctionRegistration {
105    /// Unmangled Rust-export thunk name.
106    pub rust_symbol: &'static str,
107    /// Excel-visible worksheet-function name.
108    pub excel_name: &'static str,
109    /// Result and parameter type codes.
110    pub signature: FunctionSignature,
111    /// Optional Excel category.
112    pub category: Option<&'static str>,
113    /// Optional Excel-visible function description.
114    pub description: Option<&'static str>,
115    /// Excel-visible parameter names excluding the internal async handle.
116    pub argument_names: &'static [&'static str],
117    /// Excel-visible parameter help, parallel to [`Self::argument_names`].
118    pub argument_descriptions: &'static [&'static str],
119    /// Registration modifiers.
120    pub flags: FunctionFlags,
121}
122
123/// Registration metadata for an XLL command, which is deliberately distinct
124/// from a worksheet-function descriptor.
125#[derive(Clone, Copy, Debug)]
126pub struct CommandRegistration {
127    /// Unmangled Rust-export command thunk name.
128    pub rust_symbol: &'static str,
129    /// Excel-visible command name.
130    pub excel_name: &'static str,
131    /// Optional Excel-visible command description.
132    pub description: Option<&'static str>,
133    /// Optional command shortcut text.
134    pub shortcut: Option<&'static str>,
135}
136
137impl CommandRegistration {
138    /// Creates command metadata with no optional help or shortcut.
139    pub const fn new(rust_symbol: &'static str, excel_name: &'static str) -> Self {
140        Self {
141            rust_symbol,
142            excel_name,
143            description: None,
144            shortcut: None,
145        }
146    }
147
148    /// Adds Excel-visible command help text.
149    pub const fn description(mut self, description: &'static str) -> Self {
150        self.description = Some(description);
151        self
152    }
153
154    /// Adds the Excel shortcut text.
155    pub const fn shortcut(mut self, shortcut: &'static str) -> Self {
156        self.shortcut = Some(shortcut);
157        self
158    }
159
160    /// `I` is the documented 16-bit command return ABI; commands have no
161    /// Excel-visible arguments and use macro type 2 during registration.
162    pub const fn type_text(&self) -> &'static str {
163        "I"
164    }
165
166    /// Validates command metadata before lifecycle registration.
167    pub fn validate(&self) -> Result<(), RegistrationError> {
168        if self.rust_symbol.is_empty() {
169            return Err(RegistrationError::EmptyRustSymbol);
170        }
171        if self.excel_name.is_empty() {
172            return Err(RegistrationError::EmptyExcelName);
173        }
174        Ok(())
175    }
176}
177
178impl FunctionRegistration {
179    /// Returns whether this descriptor has the verified async `>`/`X` shape.
180    pub const fn is_asynchronous(&self) -> bool {
181        matches!(self.signature.result, ExcelReturnType::AsyncVoid)
182    }
183
184    /// Creates function metadata with no optional category, help, or modifiers.
185    pub const fn new(
186        rust_symbol: &'static str,
187        excel_name: &'static str,
188        signature: FunctionSignature,
189    ) -> Self {
190        Self {
191            rust_symbol,
192            excel_name,
193            signature,
194            category: None,
195            description: None,
196            argument_names: &[],
197            argument_descriptions: &[],
198            flags: FunctionFlags {
199                volatile: false,
200                thread_safe: false,
201                macro_type: false,
202                cluster_safe: false,
203            },
204        }
205    }
206
207    /// Adds the Excel category.
208    pub const fn category(mut self, category: &'static str) -> Self {
209        self.category = Some(category);
210        self
211    }
212
213    /// Adds Excel-visible function help text.
214    pub const fn description(mut self, description: &'static str) -> Self {
215        self.description = Some(description);
216        self
217    }
218
219    /// Adds parameter names and matching Excel-visible help text.
220    pub const fn arguments(
221        mut self,
222        names: &'static [&'static str],
223        descriptions: &'static [&'static str],
224    ) -> Self {
225        self.argument_names = names;
226        self.argument_descriptions = descriptions;
227        self
228    }
229
230    /// Sets registration modifiers after validating them with [`Self::validate`].
231    pub const fn flags(mut self, flags: FunctionFlags) -> Self {
232        self.flags = flags;
233        self
234    }
235
236    /// Builds canonical Excel registration type text after validation.
237    pub fn type_text(&self) -> Result<String, RegistrationError> {
238        self.validate()?;
239        let mut text = String::from(self.signature.result.code());
240        for argument in self.signature.arguments {
241            text.push_str(argument.code());
242        }
243        // Microsoft specifies modifiers after the parameter codes. This
244        // canonical order makes descriptors deterministic.
245        if self.flags.volatile {
246            text.push(XLL_MODIFIER_VOLATILE);
247        }
248        if self.flags.macro_type {
249            text.push(XLL_MODIFIER_MACRO_SHEET);
250        }
251        if self.flags.thread_safe {
252            text.push(XLL_MODIFIER_THREAD_SAFE);
253        }
254        if self.flags.cluster_safe {
255            text.push(XLL_MODIFIER_CLUSTER_SAFE);
256        }
257        Ok(text)
258    }
259
260    /// Validates names, argument metadata, modifiers, and async shape.
261    pub fn validate(&self) -> Result<(), RegistrationError> {
262        if self.rust_symbol.is_empty() {
263            return Err(RegistrationError::EmptyRustSymbol);
264        }
265        if self.excel_name.is_empty() {
266            return Err(RegistrationError::EmptyExcelName);
267        }
268        let async_handles = self
269            .signature
270            .arguments
271            .iter()
272            .filter(|argument| **argument == ExcelArgumentType::AsyncHandle)
273            .count();
274        let visible_arguments = self.signature.arguments.len() - async_handles;
275        if visible_arguments != self.argument_names.len() {
276            return Err(RegistrationError::SignatureArgumentLengthMismatch);
277        }
278        if self.argument_names.len() != self.argument_descriptions.len() {
279            return Err(RegistrationError::ArgumentMetadataLengthMismatch);
280        }
281        if self.flags.macro_type && (self.flags.thread_safe || self.flags.cluster_safe) {
282            return Err(RegistrationError::IncompatibleFlags);
283        }
284        let asynchronous = self.signature.result == ExcelReturnType::AsyncVoid;
285        if asynchronous != (async_handles == 1) || (asynchronous && self.flags.cluster_safe) {
286            return Err(RegistrationError::InvalidAsyncSignature);
287        }
288        Ok(())
289    }
290}
291
292#[derive(Clone, Copy, Debug)]
293/// Static metadata for one XLL and its generated registrations.
294pub struct AddInDescriptor {
295    /// Excel-visible add-in name.
296    pub name: &'static str,
297    /// Excel-visible add-in description.
298    pub description: &'static str,
299    /// Worksheet function registrations.
300    pub functions: &'static [FunctionRegistration],
301    /// Command registrations.
302    pub commands: &'static [CommandRegistration],
303}
304
305impl AddInDescriptor {
306    /// Creates add-in metadata without commands.
307    pub const fn new(
308        name: &'static str,
309        description: &'static str,
310        functions: &'static [FunctionRegistration],
311    ) -> Self {
312        Self {
313            name,
314            description,
315            functions,
316            commands: &[],
317        }
318    }
319
320    /// Adds static command metadata to this descriptor.
321    pub const fn commands(mut self, commands: &'static [CommandRegistration]) -> Self {
322        self.commands = commands;
323        self
324    }
325
326    /// Validates the add-in and every contained registration descriptor.
327    pub fn validate(&self) -> Result<(), RegistrationError> {
328        if self.name.is_empty() {
329            return Err(RegistrationError::EmptyAddInName);
330        }
331        for function in self.functions {
332            function.validate()?;
333        }
334        for command in self.commands {
335            command.validate()?;
336        }
337        Ok(())
338    }
339}
340
341#[derive(Clone, Copy, Debug, Eq, PartialEq)]
342/// Static registration metadata is inconsistent or exceeds Excel limits.
343pub enum RegistrationError {
344    /// The add-in name was empty.
345    EmptyAddInName,
346    /// The exported Rust thunk symbol was empty.
347    EmptyRustSymbol,
348    /// The Excel-visible name was empty.
349    EmptyExcelName,
350    /// Visible signature parameters and supplied names have different lengths.
351    SignatureArgumentLengthMismatch,
352    /// Parameter names and descriptions have different lengths.
353    ArgumentMetadataLengthMismatch,
354    /// Macro-sheet registration conflicts with thread-safe or cluster-safe flags.
355    IncompatibleFlags,
356    /// The `>` result and single `X` handle contract was not satisfied.
357    InvalidAsyncSignature,
358    /// Generated registration text exceeds Excel's counted-string limit.
359    StringTooLong,
360}
361
362impl fmt::Display for RegistrationError {
363    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
364        formatter.write_str(match self {
365            Self::EmptyAddInName => "add-in name must not be empty",
366            Self::EmptyRustSymbol => "Rust symbol must not be empty",
367            Self::EmptyExcelName => "Excel function name must not be empty",
368            Self::SignatureArgumentLengthMismatch => {
369                "signature and argument metadata lengths differ"
370            }
371            Self::ArgumentMetadataLengthMismatch => {
372                "argument names and descriptions must have the same length"
373            }
374            Self::IncompatibleFlags => {
375                "a function cannot be both thread-safe and macro-sheet equivalent"
376            }
377            Self::InvalidAsyncSignature => {
378                "an asynchronous function requires `>` plus exactly one `X` argument and cannot be cluster-safe"
379            }
380            Self::StringTooLong => "registration text exceeds Excel's counted-string limit",
381        })
382    }
383}
384
385impl std::error::Error for RegistrationError {}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    const TWO_NUMBERS: &[ExcelArgumentType] =
392        &[ExcelArgumentType::Number, ExcelArgumentType::Number];
393
394    #[test]
395    fn exact_type_text_is_generated_from_the_signature() {
396        let function = FunctionRegistration::new(
397            "rust_add",
398            "RUST.ADD",
399            FunctionSignature::new(ExcelReturnType::Xloper12, TWO_NUMBERS),
400        )
401        .arguments(&["x", "y"], &["x", "y"])
402        .flags(FunctionFlags {
403            volatile: true,
404            thread_safe: true,
405            macro_type: false,
406            cluster_safe: true,
407        });
408        assert_eq!(function.type_text().as_deref(), Ok("QBB!$&"));
409    }
410
411    #[test]
412    fn q_and_u_and_direct_wide_strings_remain_distinct() {
413        const ARGS: &[ExcelArgumentType] = &[
414            ExcelArgumentType::GeneralValue,
415            ExcelArgumentType::GeneralReference,
416            ExcelArgumentType::CountedUtf16,
417            ExcelArgumentType::NullTerminatedUtf16,
418        ];
419        let function = FunctionRegistration::new(
420            "probe",
421            "PROBE",
422            FunctionSignature::new(ExcelReturnType::Xloper12, ARGS),
423        )
424        .arguments(&["q", "u", "d", "c"], &["", "", "", ""]);
425        assert_eq!(function.type_text().as_deref(), Ok("QQUD%C%"));
426    }
427
428    #[test]
429    fn incompatible_flags_and_mismatched_metadata_are_rejected() {
430        let mismatch = FunctionRegistration::new(
431            "add",
432            "RUST.ADD",
433            FunctionSignature::new(ExcelReturnType::Number, TWO_NUMBERS),
434        )
435        .arguments(&["x"], &["x"]);
436        assert_eq!(
437            mismatch.validate(),
438            Err(RegistrationError::SignatureArgumentLengthMismatch)
439        );
440
441        let incompatible = FunctionRegistration::new(
442            "f",
443            "F",
444            FunctionSignature::new(ExcelReturnType::Number, &[]),
445        )
446        .flags(FunctionFlags {
447            volatile: false,
448            thread_safe: true,
449            macro_type: true,
450            cluster_safe: false,
451        });
452        assert_eq!(
453            incompatible.validate(),
454            Err(RegistrationError::IncompatibleFlags)
455        );
456    }
457
458    #[test]
459    fn async_registration_requires_exact_void_handle_pair() {
460        let valid = FunctionRegistration::new(
461            "async_probe",
462            "ASYNC.PROBE",
463            FunctionSignature::new(
464                ExcelReturnType::AsyncVoid,
465                &[ExcelArgumentType::Number, ExcelArgumentType::AsyncHandle],
466            ),
467        )
468        .arguments(&["value"], &["value"])
469        .flags(FunctionFlags {
470            thread_safe: true,
471            ..FunctionFlags::default()
472        });
473        assert_eq!(valid.type_text().as_deref(), Ok(">BX$"));
474
475        let missing = FunctionRegistration::new(
476            "bad",
477            "BAD",
478            FunctionSignature::new(ExcelReturnType::AsyncVoid, &[ExcelArgumentType::Number]),
479        )
480        .arguments(&["value"], &["value"]);
481        assert_eq!(
482            missing.validate(),
483            Err(RegistrationError::InvalidAsyncSignature)
484        );
485
486        let stray = FunctionRegistration::new(
487            "bad",
488            "BAD",
489            FunctionSignature::new(ExcelReturnType::Number, &[ExcelArgumentType::AsyncHandle]),
490        );
491        assert_eq!(
492            stray.validate(),
493            Err(RegistrationError::InvalidAsyncSignature)
494        );
495    }
496}