excel_api/lib.rs
1#![warn(missing_docs)]
2#![doc = include_str!("../README.md")]
3//!
4//! # Overview
5//!
6//! `excel-api` is the safe, high-level layer for native 64-bit Microsoft Excel
7//! XLL add-ins. It builds on [`excel_api_sys`] but does not make raw ABI
8//! ownership safe by convention: callback inputs are represented by
9//! callback-borrowed types such as [`ExcelValueRef`], while data that must outlive
10//! a callback is represented by owned semantic types such as [`ExcelValue`] and
11//! [`ExcelString`].
12//!
13//! Prefer the [`prelude`] for ordinary XLL authoring. The
14//! [`excel_function!`][crate::excel_function] and
15//! [`excel_command!`][crate::excel_command] attributes generate registration
16//! metadata and panic-contained ABI thunks when the default `macros` feature is
17//! enabled. Start with the repository's `examples/minimal-xll` example and the
18//! [user guide](https://github.com/evnekdev/excel-api/tree/master/docs/guide).
19//!
20//! # Ownership and callback lifetime
21//!
22//! Excel owns callback arguments and may reclaim them when the callback returns;
23//! they must never be retained. Convert a borrowed value with [`FromExcel`] when
24//! work must outlive the callback. Return values are planned as pointer-free
25//! [`ReturnPlan`]s and materialized into DLL-owned storage through
26//! [`ExcelReturn`], which `xlAutoFree12` later releases. Results returned by an
27//! Excel C API call are represented by [`ExcelOwnedValue`] and are released with
28//! `xlFree` according to their documented policy.
29//!
30//! # Callback capabilities and threads
31//!
32//! Typed contexts are capabilities, not claims about a thread: use
33//! [`WorksheetContext`], [`ThreadSafeContext`], [`MacroContext`], or
34//! [`LifecycleContext`] only when Excel has issued the matching callback. Worker
35//! threads must not call Excel. Async UDFs are **preview**: their worker bodies
36//! own their data and publish through `xlAsyncReturn` only under the documented
37//! lifecycle generation. The cooperative dispatcher is also **preview**: an
38//! enqueue never wakes Excel, and work runs only when a legal callback drains it.
39//!
40//! # Platform and features
41//!
42//! The stable target is 64-bit Windows Excel using the Excel 12 C API. 32-bit
43//! Excel and arbitrary background-thread Excel calls are unsupported. The
44//! default `macros` feature re-exports the authoring attributes. The
45//! `xlcontime-research` feature is experimental, doc-hidden compatibility
46//! research and is not a supported wake mechanism. RTD, general COM, Ribbon,
47//! custom task panes, and autonomous notification are outside this crate's
48//! stable 1.0 scope.
49//!
50//! # Minimal shape
51//!
52//! The code below is an XLL entry point shape, so it is `no_run`: loading and
53//! registration require a real Excel process.
54//!
55//! ```no_run
56//! use excel_api::prelude::*;
57//!
58//! #[cfg(feature = "macros")]
59//! #[excel_function(
60//! name = "RUST.ADD",
61//! thunk = "rust_add",
62//! category = "Rust",
63//! description = "Adds two numbers.",
64//! arguments(left = "First addend.", right = "Second addend.")
65//! )]
66//! fn add(left: f64, right: f64) -> f64 {
67//! left + right
68//! }
69//! # fn main() {}
70//! ```
71
72/// Preview bounded asynchronous-UDF scheduling and cancellation primitives.
73pub mod async_udf;
74/// Callback-borrowed Excel values that cannot outlive their issuing callback.
75pub mod borrowed;
76/// Typed capability tokens for legal Excel callback contexts.
77pub mod context;
78/// Conversion between callback-borrowed and owned semantic values.
79pub mod convert;
80/// Bounded, panic-contained runtime diagnostics.
81pub mod diagnostics;
82/// Preview cooperative callback-drained dispatcher with no autonomous wake.
83pub mod dispatcher;
84/// Error types returned by safe value, conversion, and return-planning APIs.
85pub mod error;
86mod excel_call;
87mod excel_owned;
88/// Owned metadata arguments used to describe registered functions and commands.
89pub mod metadata;
90/// Manual registration descriptors and signature validation.
91pub mod registration;
92mod return_alloc;
93/// Pointer-free planning of DLL-owned `XLOPER12` return storage.
94pub mod return_plan;
95/// Runtime initialization, registration, close, and cleanup state.
96pub mod runtime;
97#[doc(hidden)]
98pub mod thunk;
99/// Owned semantic Excel values with no callback-scoped pointers.
100pub mod value;
101
102pub use async_udf::{
103 AsyncCancellationToken, AsyncCompletionError, AsyncExecuteError, AsyncExecutor, AsyncJob,
104 AsyncSubmitError, ThreadPoolExecutor,
105};
106pub use borrowed::{
107 DecodeError, ExcelArrayColumns, ExcelArrayElements, ExcelArrayRows, ExcelArrayView,
108 ExcelMissing, ExcelMultiReference, ExcelNil, ExcelReference, ExcelReferenceArea,
109 ExcelReferenceAreas, ExcelSingleReference, ExcelStr, ExcelValueRef, RawExcelValue,
110};
111pub use context::{LifecycleContext, MacroContext, ThreadSafeContext, WorksheetContext};
112pub use convert::{ConversionLimits, FromExcel, IntoExcel};
113pub use diagnostics::{
114 DiagnosticCode, DiagnosticEvent, DiagnosticSeverity, DiagnosticSink, set_user_sink,
115};
116pub use dispatcher::{
117 DispatchCallbackKind, DispatchCancelOutcome, DispatchCompletionError, DispatchConfig,
118 DispatchDiagnostics, DispatchDrainReport, DispatchEnqueueError, DispatchExecutionError,
119 DispatchGeneration, DispatchOperation, DispatchRequirement, DispatchResult, DispatchTicket,
120 current_generation as current_dispatch_generation, diagnostics as dispatch_diagnostics,
121 enqueue as enqueue_dispatch,
122};
123pub use error::{
124 ConversionError, ExcelError, OwnedValueError, ReturnError, ReturnMaterializationError,
125 ThunkError, Utf16ConversionError,
126};
127pub use excel_call::{
128 AbortCheckMode, CallPermission, CoerceTarget, ExcelCallDescriptor, ExcelCallError,
129 ExcelReturnCode, ResultRoot, SdkExcel12vBackend, XL_ABORT, XL_COERCE, XL_EVENT_REGISTER,
130 XL_FREE, XL_GET_NAME, XL_SHEET_ID, XL_SHEET_NM, XLF_CALLER, XLF_REGISTER, XLF_SET_NAME,
131 XLF_UNREGISTER,
132};
133#[cfg(feature = "xlcontime-research")]
134#[doc(hidden)]
135pub use excel_call::{ExperimentalOnTimeOutcome, ExperimentalOnTimeValue, XLC_ON_TIME, XLF_NOW};
136pub use excel_owned::{
137 ExcelOwnedConversionError, ExcelOwnedValue, ExcelReleaseError, ExcelReleasePolicy,
138 ExcelXlFreeTransfer,
139};
140pub use metadata::{CountedUtf16Arg, ExcelReferenceArg, ExcelValueArg, NullTerminatedUtf16Arg};
141pub use registration::{
142 AddInDescriptor, CommandRegistration, ExcelArgumentType, ExcelReturnType, FunctionFlags,
143 FunctionRegistration, FunctionSignature, RegistrationError,
144};
145pub use return_alloc::{ExcelReturn, xl_auto_free12};
146pub use return_plan::{
147 ExcelReturnArray, ExcelReturnValue, PlannedArray, PlannedArrayElement, PlannedText,
148 PlannedValue, ReturnLimits, ReturnOwnershipStrategy, ReturnPlan, ReturnStorageTotals,
149 ReturnText,
150};
151pub use runtime::{LifecycleError, LifecycleOutcome, Runtime, RuntimeDiagnostics, RuntimePhase};
152
153/// Installs the executor for the next generated asynchronous-UDF open generation.
154///
155/// A successful async close permanently shuts that executor down. The XLL must
156/// install a fresh executor before reopening; an active or already-pending
157/// generation returns the supplied executor unchanged.
158pub fn install_async_executor(
159 executor: std::sync::Arc<dyn AsyncExecutor>,
160 maximum_in_flight: usize,
161) -> Result<(), std::sync::Arc<dyn AsyncExecutor>> {
162 async_udf::install_production_executor(executor, maximum_in_flight)
163}
164
165/// Installs bounds for the next cooperative-dispatcher runtime generation.
166///
167/// Enqueueing does not wake Excel. A successful close permanently shuts down
168/// the generation; install a fresh configuration before reopening.
169pub fn install_dispatcher(config: DispatchConfig) -> Result<(), DispatchConfig> {
170 dispatcher::install_production_config(config)
171}
172pub use value::{ExcelArray, ExcelArrayColumn, ExcelString, ExcelValue, OptionalValue};
173
174#[cfg(feature = "macros")]
175pub use excel_api_macros::{excel_command, excel_function};
176
177/// Common imports for XLL authors.
178///
179/// This intentionally exports the stable authoring vocabulary only. Contexts,
180/// low-level calls, async scheduling, and dispatch are imported explicitly so
181/// their callback and lifecycle restrictions are visible at the use site.
182pub mod prelude {
183 pub use crate::{
184 AddInDescriptor, CommandRegistration, ConversionLimits, CountedUtf16Arg, ExcelArray,
185 ExcelError, ExcelReferenceArg, ExcelReturnArray, ExcelReturnValue, ExcelString, ExcelValue,
186 ExcelValueArg, ExcelValueRef, FromExcel, FunctionFlags, FunctionRegistration, IntoExcel,
187 NullTerminatedUtf16Arg, OptionalValue, ReturnError, ReturnLimits,
188 ReturnMaterializationError, ReturnPlan, ReturnText,
189 };
190
191 #[cfg(feature = "macros")]
192 pub use excel_api_macros::{excel_command, excel_function};
193}