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)]
11pub enum ExcelArgumentType {
13 Number,
15 Boolean,
17 Integer,
19 GeneralValue,
21 GeneralReference,
23 CountedUtf16,
25 NullTerminatedUtf16,
27 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)]
47pub enum ExcelReturnType {
49 Number,
51 Boolean,
53 Integer,
55 Xloper12,
57 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)]
74pub struct FunctionSignature {
76 pub result: ExcelReturnType,
78 pub arguments: &'static [ExcelArgumentType],
80}
81
82impl FunctionSignature {
83 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)]
90pub struct FunctionFlags {
92 pub volatile: bool,
94 pub thread_safe: bool,
96 pub macro_type: bool,
98 pub cluster_safe: bool,
100}
101
102#[derive(Clone, Copy, Debug)]
103pub struct FunctionRegistration {
105 pub rust_symbol: &'static str,
107 pub excel_name: &'static str,
109 pub signature: FunctionSignature,
111 pub category: Option<&'static str>,
113 pub description: Option<&'static str>,
115 pub argument_names: &'static [&'static str],
117 pub argument_descriptions: &'static [&'static str],
119 pub flags: FunctionFlags,
121}
122
123#[derive(Clone, Copy, Debug)]
126pub struct CommandRegistration {
127 pub rust_symbol: &'static str,
129 pub excel_name: &'static str,
131 pub description: Option<&'static str>,
133 pub shortcut: Option<&'static str>,
135}
136
137impl CommandRegistration {
138 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 pub const fn description(mut self, description: &'static str) -> Self {
150 self.description = Some(description);
151 self
152 }
153
154 pub const fn shortcut(mut self, shortcut: &'static str) -> Self {
156 self.shortcut = Some(shortcut);
157 self
158 }
159
160 pub const fn type_text(&self) -> &'static str {
163 "I"
164 }
165
166 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 pub const fn is_asynchronous(&self) -> bool {
181 matches!(self.signature.result, ExcelReturnType::AsyncVoid)
182 }
183
184 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 pub const fn category(mut self, category: &'static str) -> Self {
209 self.category = Some(category);
210 self
211 }
212
213 pub const fn description(mut self, description: &'static str) -> Self {
215 self.description = Some(description);
216 self
217 }
218
219 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 pub const fn flags(mut self, flags: FunctionFlags) -> Self {
232 self.flags = flags;
233 self
234 }
235
236 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 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 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)]
293pub struct AddInDescriptor {
295 pub name: &'static str,
297 pub description: &'static str,
299 pub functions: &'static [FunctionRegistration],
301 pub commands: &'static [CommandRegistration],
303}
304
305impl AddInDescriptor {
306 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 pub const fn commands(mut self, commands: &'static [CommandRegistration]) -> Self {
322 self.commands = commands;
323 self
324 }
325
326 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)]
342pub enum RegistrationError {
344 EmptyAddInName,
346 EmptyRustSymbol,
348 EmptyExcelName,
350 SignatureArgumentLengthMismatch,
352 ArgumentMetadataLengthMismatch,
354 IncompatibleFlags,
356 InvalidAsyncSignature,
358 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}