Skip to main content

cscript_ffi/
lib.rs

1//! Loads a user-supplied, precompiled shared library (`.so`/`.dylib`/`.dll`) exposing three C
2//! functions and calls into it once per block instance per transient step — a dynamically-
3//! loaded, stateful escape hatch for block behavior no existing `continuous-blocks` block
4//! covers, the same role a code-generation/scripting slot plays in other block-diagram
5//! simulation tools' own extensibility mechanisms, or an `ngspice` XSPICE codemodel `.cm`
6//! plugin (see an internal gotcha note on ngspice XSPICE codemodels needing `MFBINIT` set in
7//! the environment, for that already-used pattern).
8//!
9//! **This crate is the one place in this workspace where calling into arbitrary native code is
10//! deliberately allowed.** Loading a shared library and calling into it is unsafe by
11//! construction: the code runs in-process with this program's own privileges, can corrupt
12//! memory, crash the process, or do anything a normal native program can do. That is an
13//! accepted, bounded risk of this specific opt-in feature (a user explicitly names a `.so` file
14//! in their own netlist), not something this crate tries to sandbox away — no different in kind
15//! from the XSPICE codemodel pattern already used elsewhere in this same project.
16//!
17//! ## The C-side contract
18//!
19//! A block's shared library must export:
20//!
21//! ```c
22//! // Called once, when this block instance is created. Return an opaque instance-state
23//! // pointer (typically malloc'd), or NULL if this block instance carries no state at all.
24//! void *cscript_start(void);
25//!
26//! // Called once per resolved transient step. `state` is whatever cscript_start() returned
27//! // for this instance (NULL if none); `in`/`in_len` is this step's input vector, in the
28//! // netlist's own declared order; `dt` is this step's size (seconds) -- needed for any block
29//! // that integrates over time, e.g. `state->integral += error * dt`, the same explicit-Euler
30//! // update every other stateful block in this project already uses; `out`/`out_len` is the
31//! // output vector to fill.
32//! void cscript_output(void *state, const double *in, int in_len, double dt, double *out, int out_len);
33//!
34//! // Optional. Called once when this block instance is dropped. Free anything
35//! // cscript_start() allocated. If the symbol is absent, `state` is simply leaked -- harmless
36//! // for a short-lived CLI run, but real cleanup is provided for any longer-lived host.
37//! void cscript_free(void *state);
38//!
39//! // Optional. Return a deep copy of `state` (independent memory: mutating the copy through
40//! // future cscript_output() calls must never affect the original, and vice versa). Only
41//! // needed to use this block under general-simulator's adaptive step-size control, which retries a
42//! // rejected trial step from an independent copy of every block's state -- see "Adaptive
43//! // step-size control and instance cloning" below.
44//! void *cscript_clone(void *state);
45//! ```
46//!
47//! ## The optional continuous-state (`xc`) contract
48//!
49//! A block declaring `xc_count > 0` in its netlist line owns a continuous-state vector the
50//! *solver itself* numerically integrates (RK4, one independent integration per block, the
51//! same convention [`continuous_blocks::StateSpace::rk4_step`] uses for every other dynamic
52//! block in this workspace) -- as opposed to the plain `void *state` blob above, which is
53//! never touched by anything but the block's own C code. This is a pure vector-field
54//! evaluation the solver calls, not something the block's own `cscript_output` hand-integrates
55//! itself (a block that wants to manage its own state by hand, e.g. a hand-rolled `dv/dt` Euler
56//! estimate, remains exactly as correct as before this contract existed -- this new contract is
57//! specifically for state the solver should own instead).
58//!
59//! Such a block exports **two more** functions *instead of* `cscript_output` (never both --
60//! [`CScriptRegistry::instantiate_xc`] requires exactly these two, [`CScriptRegistry::instantiate`]
61//! requires plain `cscript_output`; a library is meant to implement one contract or the other):
62//!
63//! ```c
64//! // Pure vector-field evaluation: dxc/dt = f(t, u, xc, xd). Must not
65//! // mutate `state`, `in`, or `xc` -- called up to four times per accepted step (RK4's own
66//! // k1..k4 stages), including from now-discarded trial steps under adaptive stepping (see
67//! // "Adaptive step-size control and instance cloning" below -- the same "a rejected trial's
68//! // mutation never survives" guarantee applies here, so this restriction is about correctness
69//! // of a single RK4 step's own math, not about adaptive-step safety).
70//! void cscript_derivative(void *state, const double *in, int in_len,
71//!                         const double *xc, int xc_len, double *xc_dot, int xc_dot_len);
72//!
73//! // Used instead of cscript_output. Identical role, with read access to this step's own
74//! // already-RK4-integrated xc (the *new*, post-step continuous state -- matching every other
75//! // dynamic block's own "step state, then compute output from the new state" convention). May
76//! // still mutate `state` for its own xd/bookkeeping purposes, exactly like plain
77//! // cscript_output.
78//! void cscript_output_xc(void *state, const double *in, int in_len, double dt,
79//!                        const double *xc, int xc_len, double *out, int out_len);
80//! ```
81//!
82//! `xc` itself lives in `dae-runtime`'s own `BlockState`, not inside the opaque `void *state`
83//! blob -- the one place this contract breaks the "everything is opaque to Rust" rule, and
84//! deliberately so: the solver's own RK4 stepper needs to do ordinary vector arithmetic on it
85//! between stages, which an opaque C-managed blob could never allow. `cscript_start`/
86//! `cscript_free`/`cscript_clone` are unaffected either way -- `xc`'s own initial value is
87//! always the zero vector (matching every other dynamic block's own "starts at rest"
88//! convention), and cloning it is a plain `Vec<f64>` clone, needing no C-side involvement at
89//! all.
90//!
91//! ## The optional discrete-state update function
92//!
93//! `cscript_output`/`cscript_output_xc` are permitted to mutate `state` themselves (documented
94//! above) -- fine for the common case, but it conflates two different things: computing this
95//! step's output from the block's current state, and committing that state forward to the next
96//! step. Some block-diagram tools' own code-block feature keeps these deliberately separate (an
97//! output function that's expected to be side-effect-free, plus a dedicated update function
98//! that's the only place discrete state actually advances) -- `cscript` now offers the same
99//! split, as an **entirely optional** third function:
100//!
101//! ```c
102//! // Optional. Called once per resolved (or per-sample-period, under ts=) step, immediately
103//! // after cscript_output/cscript_output_xc for that same call -- the dedicated place to
104//! // commit `state`'s own discrete bookkeeping forward to the next step, instead of doing it
105//! // inside the output function itself. `xc` is this step's own already-integrated continuous
106//! // state (`xc_len == 0` for a block with `xc_count == 0`, exactly like every other xc-aware
107//! // parameter in this contract). If this symbol is absent, a cscript block is expected to
108//! // keep updating `state` directly inside cscript_output/cscript_output_xc, exactly as before
109//! // this function existed -- nothing about the existing contract changes if you never add
110//! // this.
111//! void cscript_update(void *state, const double *in, int in_len, double dt,
112//!                      const double *xc, int xc_len);
113//! ```
114//!
115//! ## The optional block-controlled sample time
116//!
117//! A `cscript` block's own `ts=`/`freq=` fixes a period at netlist-parse time — the right
118//! choice for a controller running at a genuinely fixed rate. Some blocks instead know their
119//! own *next* execution time only at runtime (a modulator whose next switching instant depends
120//! on a live computation, an event-driven controller that only needs to re-run when something
121//! crosses a threshold). `ts=variable` in the netlist selects this mode, and **requires** the
122//! library to export one more function (checked once, up front, the same "checked once, up
123//! front" discipline `cscript_clone`'s own adaptive-stepping requirement already uses):
124//!
125//! ```c
126//! // Required when this block declares ts=variable (never called otherwise). Called
127//! // immediately after cscript_output/cscript_output_xc on every step this block actually
128//! // ran. Returns the number of seconds, *relative to this call*, until this block should
129//! // next be executed -- not an absolute time, consistent with every other cscript function
130//! // never seeing absolute time either. Must return a value > 0; dae-runtime holds this
131//! // block's last output constant (zero-order hold) for that many seconds, then calls
132//! // cscript_output/cscript_output_xc again and asks for the next interval once more.
133//! double cscript_next_sample_hit(void *state, const double *in, int in_len,
134//!                                 const double *xc, int xc_len);
135//! ```
136//!
137//! Unlike the discrete-state update function above, this one is genuinely required once opted
138//! into via `ts=variable` — a missing symbol is a load-time error
139//! (`CScriptError::MissingSymbol`), not a silent no-op, since there would otherwise be no way
140//! to ever know when to run the block at all.
141//!
142//! ## The optional checkpoint state contract
143//!
144//! `dae-runtime`'s checkpoint/resume writes every block's state to a file and reads it back
145//! later, possibly in another process. The opaque `void *state` is the one thing it cannot
146//! reach on its own — only the author's own C code knows the layout — so a library opts in by
147//! exporting **all three** of:
148//!
149//! ```c
150//! // How many bytes cscript_state_write() will produce for this state. Called with the same
151//! // `state` pointer cscript_start()/cscript_clone()/cscript_state_read() returned (NULL for a
152//! // block that keeps no state -- return 0 in that case).
153//! size_t cscript_state_size(const void *state);
154//!
155//! // Serialize `state` into `out`, which has exactly cscript_state_size(state) bytes of room.
156//! // Never called when that size is 0. Write every value the block needs to continue
157//! // *bit-identically*: a memcpy of a plain-old-data struct is the usual implementation; a
158//! // struct holding pointers must serialize what they point at, not the addresses.
159//! void cscript_state_write(const void *state, uint8_t *out);
160//!
161//! // The inverse: build a fresh, independently owned state object from `len` bytes written
162//! // by cscript_state_write() (possibly by another process), and return it. The instance's
163//! // previous state is released through cscript_free() (if exported) once this returns.
164//! void *cscript_state_read(const uint8_t *in, size_t len);
165//! ```
166//!
167//! The three are all-or-nothing: exporting none keeps today's behaviour (a run that asks for
168//! a checkpoint is refused at the first snapshot, naming the block; a run that does not is
169//! unaffected), and exporting only some is a load-time [`CScriptError::MissingSymbol`] naming
170//! the absent one — a library half-way through adopting the contract would otherwise look
171//! exactly like one that never started. [`CScriptInstance::supports_state_io`] is the
172//! up-front check, [`CScriptInstance::state_bytes`]/[`CScriptInstance::restore_state`] the two
173//! halves. `xc` needs nothing from this contract: it is a plain `Vec<f64>` on the Rust side.
174//!
175//! ## Adaptive step-size control and instance cloning
176//!
177//! general-simulator's adaptive step-size control retries a rejected trial step from scratch: every
178//! block's state is cloned before the trial, the trial runs against the clone, and if rejected
179//! the clone is discarded and a fresh one is taken for the next, smaller attempt -- never
180//! mutating the real, confirmed state until a trial is actually accepted. That is exactly
181//! correct for plain Rust block state (a `Vec<f64>` clone is a real, independent copy), but a
182//! [`CScriptInstance`]'s state is an opaque pointer this crate never reads through, so it cannot
183//! generically deep-copy it -- only the user's own C code knows its own layout. [`Clone`] for
184//! [`CScriptInstance`] is implemented in terms of `cscript_clone` for exactly this reason, and
185//! **panics** if the library didn't export it. In practice this should never fire: check
186//! [`CScriptInstance::supports_clone`] once, up front, and refuse adaptive step-size control
187//! for a netlist containing a `cscript` block whose library doesn't support it, the same way
188//! `dae-runtime` already does before entering its own adaptive loop.
189//!
190//! Everything else in the user's `.c` file — includes, `#define`s, `typedef`s, file-scope
191//! `static` helper functions and variables the user wants visible to all three of the functions
192//! above for one translation unit — needs no special support from this crate: plain C file
193//! scope already provides exactly that. The user compiles their own `.c` file into a shared
194//! library themselves (e.g. `cc -shared -fPIC -o my_block.so my_block.c`); this crate never
195//! invokes a compiler.
196//!
197//! `in_len`/`out_len` must match the netlist's own declared input/output counts for this block
198//! — nothing in this crate checks that they do; a mismatch is a plain out-of-bounds C array
199//! access, same as it would be calling `OutputSignal(9, 0)` past a declared output count in any
200//! other tool's own code-slot mechanism. This is documented, not enforced.
201//!
202//! ## Multi-instance state
203//!
204//! Two block instances naming the *same* `lib=` path share one loaded image (`dlopen` on most
205//! platforms de-duplicates repeat loads of the same path — see [`CScriptLibrary::load`]), but
206//! each instance gets its *own* `cscript_start()` call and its own returned state pointer, so
207//! per-instance state (e.g. an integrator's accumulator) is never accidentally shared between
208//! two uses of the same block in one netlist. [`CScriptRegistry`] caches loaded libraries by
209//! path for exactly this reason: cheap repeat instantiation, without repeat `dlopen`.
210
211use std::collections::BTreeMap;
212use std::ffi::c_void;
213use std::path::{Path, PathBuf};
214use std::sync::Arc;
215
216use libloading::{Library, Symbol};
217
218type StartFn = unsafe extern "C" fn() -> *mut c_void;
219type OutputFn = unsafe extern "C" fn(
220    state: *mut c_void,
221    input: *const f64,
222    in_len: i32,
223    dt: f64,
224    output: *mut f64,
225    out_len: i32,
226);
227type FreeFn = unsafe extern "C" fn(state: *mut c_void);
228type CloneFn = unsafe extern "C" fn(state: *mut c_void) -> *mut c_void;
229type DerivativeFn = unsafe extern "C" fn(
230    state: *mut c_void,
231    input: *const f64,
232    in_len: i32,
233    xc: *const f64,
234    xc_len: i32,
235    xc_dot: *mut f64,
236    xc_dot_len: i32,
237);
238type OutputXcFn = unsafe extern "C" fn(
239    state: *mut c_void,
240    input: *const f64,
241    in_len: i32,
242    dt: f64,
243    xc: *const f64,
244    xc_len: i32,
245    output: *mut f64,
246    out_len: i32,
247);
248type UpdateFn = unsafe extern "C" fn(
249    state: *mut c_void,
250    input: *const f64,
251    in_len: i32,
252    dt: f64,
253    xc: *const f64,
254    xc_len: i32,
255);
256type NextSampleHitFn = unsafe extern "C" fn(
257    state: *mut c_void,
258    input: *const f64,
259    in_len: i32,
260    xc: *const f64,
261    xc_len: i32,
262) -> f64;
263type StateSizeFn = unsafe extern "C" fn(state: *const c_void) -> usize;
264type StateWriteFn = unsafe extern "C" fn(state: *const c_void, out: *mut u8);
265type StateReadFn = unsafe extern "C" fn(input: *const u8, len: usize) -> *mut c_void;
266
267/// The three symbols of the checkpoint state contract, resolved together — see the module doc
268/// comment, "The optional checkpoint state contract." Held as one `Option<StateIo>` on the
269/// library so "partially exported" cannot be represented at all past load time.
270#[derive(Clone, Copy)]
271struct StateIo {
272    size: StateSizeFn,
273    write: StateWriteFn,
274    read: StateReadFn,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
278pub enum CScriptError {
279    Load {
280        path: PathBuf,
281        message: String,
282    },
283    MissingSymbol {
284        path: PathBuf,
285        symbol: &'static str,
286        message: String,
287    },
288    /// [`CScriptInstance::state_bytes`]/[`CScriptInstance::restore_state`] were called on an
289    /// instance whose library exports none of the checkpoint state contract's three symbols —
290    /// check [`CScriptInstance::supports_state_io`] first.
291    StateContractNotExported {
292        path: PathBuf,
293    },
294}
295
296impl std::fmt::Display for CScriptError {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        match self {
299            CScriptError::Load { path, message } => {
300                write!(
301                    f,
302                    "failed to load C-script library {}: {message}",
303                    path.display()
304                )
305            }
306            CScriptError::MissingSymbol {
307                path,
308                symbol,
309                message,
310            } => write!(
311                f,
312                "C-script library {} is missing required symbol `{symbol}`: {message}",
313                path.display()
314            ),
315            CScriptError::StateContractNotExported { path } => write!(
316                f,
317                "C-script library {} does not export the checkpoint state contract \
318                 (`cscript_state_size`/`cscript_state_write`/`cscript_state_read`)",
319                path.display()
320            ),
321        }
322    }
323}
324
325impl std::error::Error for CScriptError {}
326
327/// One loaded shared library's three FFI entry points. Kept alive for as long as any
328/// [`CScriptInstance`] built from it exists (each instance holds an `Arc` to this) — the
329/// `Library` must outlive every raw function pointer taken from it.
330pub struct CScriptLibrary {
331    // Held only to keep the mapped image alive; never read directly again after `load`.
332    _library: Library,
333    start: StartFn,
334    // `Option`, not required at load time: which of `output` or (`derivative` + `output_xc`)
335    // is actually required depends on how this library is instantiated (plain
336    // `CScriptRegistry::instantiate` vs. `instantiate_xc`) — see each one's own doc comment.
337    // `load` resolves whatever is present; the two `instantiate*` methods enforce the specific
338    // combination they each need.
339    output: Option<OutputFn>,
340    derivative: Option<DerivativeFn>,
341    output_xc: Option<OutputXcFn>,
342    // Always optional regardless of contract (plain or xc) -- see the module doc comment,
343    // "The optional discrete-state update function." Never required by either `instantiate*`
344    // method.
345    update: Option<UpdateFn>,
346    // Always optional, but *required* when this block's netlist line declares `ts=variable` --
347    // that requirement is checked by `dae-runtime`, not this crate (which has no notion of the
348    // netlist at all), by calling `CScriptInstance::supports_next_sample_hit` once at
349    // construction. See the module doc comment, "The optional block-controlled sample time."
350    next_sample_hit: Option<NextSampleHitFn>,
351    free: Option<FreeFn>,
352    clone_state: Option<CloneFn>,
353    // The checkpoint state contract, all three or none -- see the module doc comment, "The
354    // optional checkpoint state contract." A partial set is refused by `load` itself.
355    state_io: Option<StateIo>,
356    // Kept for error messages (`CScriptError::StateContractNotExported`).
357    path: PathBuf,
358}
359
360impl CScriptLibrary {
361    /// Loads `path` and resolves `cscript_start` (always required) plus every optional symbol
362    /// this crate knows about (`cscript_output`, `cscript_derivative`, `cscript_output_xc`,
363    /// `cscript_update`, `cscript_free`, `cscript_clone`, and the
364    /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple) — see the module
365    /// doc comment for what each one's absence means. Which combination is actually *required*
366    /// for a given instantiation is checked separately, by
367    /// [`CScriptRegistry::instantiate`]/[`CScriptRegistry::instantiate_xc`] — except the state
368    /// triple, which is all-or-nothing and checked here: exporting one or two of the three is
369    /// [`CScriptError::MissingSymbol`] naming the first absent one.
370    pub fn load(path: &Path) -> Result<Self, CScriptError> {
371        // SAFETY: dlopen-ing and resolving symbols from a user-specified path is exactly the
372        // unsafety this crate exists to contain -- see the module doc comment. The caller
373        // chose this path deliberately, in their own netlist.
374        let library = unsafe { Library::new(path) }.map_err(|e| CScriptError::Load {
375            path: path.to_path_buf(),
376            message: e.to_string(),
377        })?;
378
379        let start: StartFn = unsafe {
380            let symbol: Symbol<StartFn> =
381                library
382                    .get(b"cscript_start\0")
383                    .map_err(|e| CScriptError::MissingSymbol {
384                        path: path.to_path_buf(),
385                        symbol: "cscript_start",
386                        message: e.to_string(),
387                    })?;
388            *symbol
389        };
390        let output: Option<OutputFn> = unsafe {
391            library
392                .get(b"cscript_output\0")
393                .ok()
394                .map(|symbol: Symbol<OutputFn>| *symbol)
395        };
396        let derivative: Option<DerivativeFn> = unsafe {
397            library
398                .get(b"cscript_derivative\0")
399                .ok()
400                .map(|symbol: Symbol<DerivativeFn>| *symbol)
401        };
402        let output_xc: Option<OutputXcFn> = unsafe {
403            library
404                .get(b"cscript_output_xc\0")
405                .ok()
406                .map(|symbol: Symbol<OutputXcFn>| *symbol)
407        };
408        let update: Option<UpdateFn> = unsafe {
409            library
410                .get(b"cscript_update\0")
411                .ok()
412                .map(|symbol: Symbol<UpdateFn>| *symbol)
413        };
414        let next_sample_hit: Option<NextSampleHitFn> = unsafe {
415            library
416                .get(b"cscript_next_sample_hit\0")
417                .ok()
418                .map(|symbol: Symbol<NextSampleHitFn>| *symbol)
419        };
420        let free: Option<FreeFn> = unsafe {
421            library
422                .get(b"cscript_free\0")
423                .ok()
424                .map(|symbol: Symbol<FreeFn>| *symbol)
425        };
426        let clone_state: Option<CloneFn> = unsafe {
427            library
428                .get(b"cscript_clone\0")
429                .ok()
430                .map(|symbol: Symbol<CloneFn>| *symbol)
431        };
432        let state_size: Option<StateSizeFn> = unsafe {
433            library
434                .get(b"cscript_state_size\0")
435                .ok()
436                .map(|symbol: Symbol<StateSizeFn>| *symbol)
437        };
438        let state_write: Option<StateWriteFn> = unsafe {
439            library
440                .get(b"cscript_state_write\0")
441                .ok()
442                .map(|symbol: Symbol<StateWriteFn>| *symbol)
443        };
444        let state_read: Option<StateReadFn> = unsafe {
445            library
446                .get(b"cscript_state_read\0")
447                .ok()
448                .map(|symbol: Symbol<StateReadFn>| *symbol)
449        };
450        let state_io = match (state_size, state_write, state_read) {
451            (None, None, None) => None,
452            (Some(size), Some(write), Some(read)) => Some(StateIo { size, write, read }),
453            (size, write, read) => {
454                // A partial set: name the first missing one, so the author sees which of the
455                // three to add rather than a generic "checkpointing unsupported" later on.
456                let symbol = if size.is_none() {
457                    "cscript_state_size"
458                } else if write.is_none() {
459                    "cscript_state_write"
460                } else {
461                    debug_assert!(read.is_none());
462                    "cscript_state_read"
463                };
464                return Err(CScriptError::MissingSymbol {
465                    path: path.to_path_buf(),
466                    symbol,
467                    message: "the checkpoint state contract is all-or-nothing: \
468                              cscript_state_size, cscript_state_write and cscript_state_read \
469                              must all be exported, or none of them"
470                        .to_string(),
471                });
472            }
473        };
474
475        Ok(CScriptLibrary {
476            _library: library,
477            start,
478            output,
479            derivative,
480            output_xc,
481            update,
482            next_sample_hit,
483            free,
484            clone_state,
485            state_io,
486            path: path.to_path_buf(),
487        })
488    }
489}
490
491/// One block instance's own state, from one call to `cscript_start()` on a shared
492/// [`CScriptLibrary`]. `Drop` calls `cscript_free` if the library exported one.
493pub struct CScriptInstance {
494    library: Arc<CScriptLibrary>,
495    state: *mut c_void,
496}
497
498impl std::fmt::Debug for CScriptInstance {
499    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
500        f.debug_struct("CScriptInstance")
501            .field("state", &self.state)
502            .finish()
503    }
504}
505
506// The state pointer is opaque to us and only ever passed back into the same library's own
507// functions, which are the sole thing that dereferences it -- this crate never reads through
508// it, so moving the pointer between threads is exactly as safe as moving the shared library
509// handle itself. Circuit simulation in this workspace is single-threaded, so this is unused in
510// practice, but the type would otherwise fail to be `Send` at all without it.
511unsafe impl Send for CScriptInstance {}
512
513impl CScriptInstance {
514    fn new(library: Arc<CScriptLibrary>) -> Self {
515        // SAFETY: calling into user-supplied native code with no arguments, as documented in
516        // the module doc comment's C-side contract.
517        let state = unsafe { (library.start)() };
518        CScriptInstance { library, state }
519    }
520
521    /// Calls `cscript_output` with this instance's own state, `input` and `dt` as given, and
522    /// an `out_len`-length zero-initialized output buffer, returning it filled in.
523    ///
524    /// # Panics
525    /// If this instance's library doesn't export `cscript_output` — unreachable in practice,
526    /// since [`CScriptRegistry::instantiate`] (the only way to obtain an instance meant to use
527    /// this method) already requires it up front, the same "checked once, up front" discipline
528    /// [`Clone`]'s own `cscript_clone` requirement uses.
529    pub fn call(&mut self, input: &[f64], dt: f64, out_len: usize) -> Vec<f64> {
530        let output_fn = self.library.output.unwrap_or_else(|| {
531            panic!(
532                "call requires a library loaded via CScriptRegistry::instantiate (which \
533                 already requires cscript_output up front — this should be unreachable)"
534            )
535        });
536        let mut output = vec![0.0_f64; out_len];
537        // SAFETY: `input`/`output` are valid slices of the declared lengths for the duration
538        // of this call; `in_len`/`out_len` are passed through unchanged so the callee can
539        // bounds-check itself. Whether the callee actually respects them is the documented,
540        // unenforceable part of the C-side contract (see module doc comment).
541        unsafe {
542            output_fn(
543                self.state,
544                input.as_ptr(),
545                input.len() as i32,
546                dt,
547                output.as_mut_ptr(),
548                out_len as i32,
549            );
550        }
551        output
552    }
553
554    /// Calls `cscript_output_xc` with this instance's own state, `input`/`dt` as given, `xc` as
555    /// this step's own already-integrated continuous-state vector, and an `out_len`-length
556    /// zero-initialized output buffer, returning it filled in — the `xc`-owning counterpart to
557    /// [`Self::call`]. See the module doc comment, "The optional continuous-state (`xc`)
558    /// contract."
559    ///
560    /// # Panics
561    /// If this instance's library doesn't export `cscript_output_xc` — unreachable in
562    /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
563    pub fn call_xc(&mut self, input: &[f64], dt: f64, xc: &[f64], out_len: usize) -> Vec<f64> {
564        let output_xc = self.library.output_xc.unwrap_or_else(|| {
565            panic!(
566                "call_xc requires a library loaded via CScriptRegistry::instantiate_xc (which \
567                 already requires cscript_output_xc up front — this should be unreachable)"
568            )
569        });
570        let mut output = vec![0.0_f64; out_len];
571        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
572        unsafe {
573            output_xc(
574                self.state,
575                input.as_ptr(),
576                input.len() as i32,
577                dt,
578                xc.as_ptr(),
579                xc.len() as i32,
580                output.as_mut_ptr(),
581                out_len as i32,
582            );
583        }
584        output
585    }
586
587    /// Calls `cscript_update` with this instance's own state, `input`/`dt`/`xc` as given -- a
588    /// no-op if this instance's library didn't export it (see the module doc comment, "The
589    /// optional discrete-state update function"). Unlike [`Self::call`]/[`Self::call_xc`], this
590    /// is genuinely optional for *both* contracts, so there's no panic path: call it every
591    /// step it's due exactly like output, and it simply does nothing if the author never wrote
592    /// one.
593    pub fn update(&mut self, input: &[f64], dt: f64, xc: &[f64]) {
594        let Some(update_fn) = self.library.update else {
595            return;
596        };
597        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
598        unsafe {
599            update_fn(
600                self.state,
601                input.as_ptr(),
602                input.len() as i32,
603                dt,
604                xc.as_ptr(),
605                xc.len() as i32,
606            );
607        }
608    }
609
610    /// Whether this instance's library exported `cscript_next_sample_hit` — check this once, up
611    /// front, when this block's netlist line declares `ts=variable` (see the module doc
612    /// comment, "The optional block-controlled sample time") and reject the netlist with a
613    /// clear error if not, before ever calling [`Self::next_sample_hit`].
614    pub fn supports_next_sample_hit(&self) -> bool {
615        self.library.next_sample_hit.is_some()
616    }
617
618    /// Calls `cscript_next_sample_hit`, returning the number of seconds (relative to this call)
619    /// until this block should next be executed.
620    ///
621    /// # Panics
622    /// If this instance's library doesn't export `cscript_next_sample_hit` — unreachable in
623    /// practice, since a caller is expected to check [`Self::supports_next_sample_hit`] once,
624    /// up front, before ever using `ts=variable` for this block at all.
625    pub fn next_sample_hit(&self, input: &[f64], xc: &[f64]) -> f64 {
626        let next_sample_hit_fn = self.library.next_sample_hit.unwrap_or_else(|| {
627            panic!(
628                "next_sample_hit requires a library that exports cscript_next_sample_hit \
629                 (required for ts=variable — this should be unreachable, since that's checked \
630                 up front)"
631            )
632        });
633        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
634        unsafe {
635            next_sample_hit_fn(
636                self.state,
637                input.as_ptr(),
638                input.len() as i32,
639                xc.as_ptr(),
640                xc.len() as i32,
641            )
642        }
643    }
644
645    /// Evaluates `cscript_derivative` once: given this step's already-resolved inputs and a
646    /// candidate continuous-state vector `xc`, returns `dxc/dt`. Takes `&self` rather than
647    /// `&mut self` — the C-side contract documents (but, like every other rule in this crate,
648    /// cannot enforce) that this call must not mutate `state`, so the Rust type keeps that
649    /// intent honest even though the raw pointer underneath is technically mutable.
650    ///
651    /// # Panics
652    /// If this instance's library doesn't export `cscript_derivative` — unreachable in
653    /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
654    pub fn derivative(&self, input: &[f64], xc: &[f64]) -> Vec<f64> {
655        let derivative_fn = self.library.derivative.unwrap_or_else(|| {
656            panic!(
657                "derivative requires a library loaded via CScriptRegistry::instantiate_xc \
658                 (which already requires cscript_derivative up front — this should be \
659                 unreachable)"
660            )
661        });
662        let mut xc_dot = vec![0.0_f64; xc.len()];
663        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`/`xc_dot`.
664        unsafe {
665            derivative_fn(
666                self.state,
667                input.as_ptr(),
668                input.len() as i32,
669                xc.as_ptr(),
670                xc.len() as i32,
671                xc_dot.as_mut_ptr(),
672                xc_dot.len() as i32,
673            );
674        }
675        xc_dot
676    }
677
678    /// RK4-integrates `xc` forward by `dt`, holding `input` fixed across all four stages — the
679    /// same zero-order-hold convention `continuous_blocks::StateSpace::rk4_step` uses for every
680    /// other dynamic block in this workspace, so a `cscript` block's own continuous state
681    /// integrates exactly like a `Pid`/`StateSpace`/`Pmsm`'s does, not by some separate rule.
682    /// Calls [`Self::derivative`] up to four times (`k1..k4`) — see that method's own `#Panics`.
683    pub fn rk4_step_xc(&self, xc: &[f64], input: &[f64], dt: f64) -> Vec<f64> {
684        let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
685            a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
686        };
687        let k1 = self.derivative(input, xc);
688        let k2 = self.derivative(input, &add(xc, &k1, dt / 2.0));
689        let k3 = self.derivative(input, &add(xc, &k2, dt / 2.0));
690        let k4 = self.derivative(input, &add(xc, &k3, dt));
691        (0..xc.len())
692            .map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
693            .collect()
694    }
695
696    /// Whether this instance's library exported `cscript_clone` — check this once, up front,
697    /// before deciding whether a netlist using this block is eligible for adaptive step-size
698    /// control (see the module doc comment, "Adaptive step-size control and instance cloning").
699    pub fn supports_clone(&self) -> bool {
700        self.library.clone_state.is_some()
701    }
702
703    /// A real, independent deep copy of this instance's state via `cscript_clone`, or `None`
704    /// if the library didn't export it. Prefer this over [`Clone::clone`] wherever a missing
705    /// `cscript_clone` should be handled as an ordinary error rather than a panic.
706    pub fn try_clone(&self) -> Option<CScriptInstance> {
707        let clone_fn = self.library.clone_state?;
708        // SAFETY: `self.state` was returned by this same library's own `cscript_start` (or a
709        // prior `cscript_clone`); the callee is expected to return an independent copy, per
710        // the C-side contract documented in the module doc comment.
711        let state = unsafe { clone_fn(self.state) };
712        Some(CScriptInstance {
713            library: self.library.clone(),
714            state,
715        })
716    }
717
718    /// Whether this instance's library exported the
719    /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple — check this once,
720    /// up front, before deciding whether a run containing this block can be checkpointed (see
721    /// the module doc comment, "The optional checkpoint state contract"). A library exporting
722    /// none of the three is the "no" case; a partial set never loads at all.
723    pub fn supports_state_io(&self) -> bool {
724        self.library.state_io.is_some()
725    }
726
727    /// This instance's opaque state, serialized by the library's own `cscript_state_write` into
728    /// exactly `cscript_state_size` bytes — the save half of the checkpoint state contract.
729    /// Empty for a state the library reports as zero-sized (a `NULL` state, typically).
730    pub fn state_bytes(&self) -> Result<Vec<u8>, CScriptError> {
731        let io = self
732            .library
733            .state_io
734            .ok_or_else(|| CScriptError::StateContractNotExported {
735                path: self.library.path.clone(),
736            })?;
737        // SAFETY: `self.state` came from this same library's own `cscript_start`/`cscript_clone`/
738        // `cscript_state_read`; `size` is documented as read-only on it.
739        let len = unsafe { (io.size)(self.state) };
740        let mut bytes = vec![0_u8; len];
741        if len > 0 {
742            // SAFETY: `bytes` is exactly the `len` bytes the contract promises `write` room
743            // for, valid for the duration of the call.
744            unsafe { (io.write)(self.state, bytes.as_mut_ptr()) };
745        }
746        Ok(bytes)
747    }
748
749    /// Replaces this instance's state with one rebuilt by the library's own `cscript_state_read`
750    /// from `bytes` (as produced by [`Self::state_bytes`], possibly in another process) — the
751    /// load half of the checkpoint state contract. The previous state is released through
752    /// `cscript_free` if the library exported it, exactly as on drop.
753    pub fn restore_state(&mut self, bytes: &[u8]) -> Result<(), CScriptError> {
754        let io = self
755            .library
756            .state_io
757            .ok_or_else(|| CScriptError::StateContractNotExported {
758                path: self.library.path.clone(),
759            })?;
760        // SAFETY: `bytes` is a valid slice for the duration of the call; the callee is
761        // documented to return a fresh, independently owned state (or NULL for none).
762        let new_state = unsafe { (io.read)(bytes.as_ptr(), bytes.len()) };
763        if let Some(free) = self.library.free {
764            if !self.state.is_null() {
765                // SAFETY: the old `state` was returned by this same library and is released
766                // exactly once, here, before the pointer is overwritten below.
767                unsafe { free(self.state) };
768            }
769        }
770        self.state = new_state;
771        Ok(())
772    }
773}
774
775impl Clone for CScriptInstance {
776    /// # Panics
777    /// If this instance's library didn't export `cscript_clone`. See the module doc comment,
778    /// "Adaptive step-size control and instance cloning" — callers that need to handle this
779    /// without panicking should check [`CScriptInstance::supports_clone`] first, or use
780    /// [`CScriptInstance::try_clone`] directly.
781    fn clone(&self) -> Self {
782        self.try_clone().unwrap_or_else(|| {
783            panic!(
784                "cannot clone a CScriptInstance whose library does not export cscript_clone \
785                 (required for general-simulator's adaptive step-size control); either export \
786                 cscript_clone from this library or run with a fixed --dt"
787            )
788        })
789    }
790}
791
792impl Drop for CScriptInstance {
793    fn drop(&mut self) {
794        if let Some(free) = self.library.free {
795            if !self.state.is_null() {
796                // SAFETY: `state` was returned by this same library's own `cscript_start`, and
797                // this is the only place it is ever freed.
798                unsafe { free(self.state) };
799            }
800        }
801    }
802}
803
804/// Caches loaded libraries by path, so several block instances naming the same `lib=` file
805/// share one `dlopen`'d image while each still gets its own [`CScriptInstance`] (own state
806/// pointer) — see the module doc comment, "Multi-instance state."
807#[derive(Default)]
808pub struct CScriptRegistry {
809    libraries: BTreeMap<PathBuf, Arc<CScriptLibrary>>,
810}
811
812impl CScriptRegistry {
813    pub fn new() -> Self {
814        Self::default()
815    }
816
817    /// Loads `path` if not already cached (resolving every optional symbol this crate knows
818    /// about, regardless of which contract the caller ultimately needs — see
819    /// [`CScriptLibrary::load`]'s own doc comment), returning the cached/loaded `Arc`.
820    fn load_cached(&mut self, path: &Path) -> Result<Arc<CScriptLibrary>, CScriptError> {
821        if let Some(library) = self.libraries.get(path) {
822            Ok(library.clone())
823        } else {
824            let library = Arc::new(CScriptLibrary::load(path)?);
825            self.libraries.insert(path.to_path_buf(), library.clone());
826            Ok(library)
827        }
828    }
829
830    /// Loads `path` if not already cached, then creates and returns a fresh instance from it
831    /// (its own `cscript_start()` call, its own state) using the **plain** contract: requires
832    /// `cscript_output` (via [`CScriptInstance::call`]), for a block with `xc_count == 0`.
833    pub fn instantiate(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
834        let library = self.load_cached(path)?;
835        if library.output.is_none() {
836            return Err(CScriptError::MissingSymbol {
837                path: path.to_path_buf(),
838                symbol: "cscript_output",
839                message: "not found (or this library only implements the xc-owning contract \
840                          — see CScriptRegistry::instantiate_xc)"
841                    .to_string(),
842            });
843        }
844        Ok(CScriptInstance::new(library))
845    }
846
847    /// Loads `path` if not already cached, then creates and returns a fresh instance from it
848    /// using the **continuous-state (`xc`)** contract: requires `cscript_derivative` and
849    /// `cscript_output_xc` (via [`CScriptInstance::rk4_step_xc`]/[`CScriptInstance::call_xc`]),
850    /// for a block with `xc_count > 0`. See the module doc comment, "The optional
851    /// continuous-state (`xc`) contract."
852    pub fn instantiate_xc(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
853        let library = self.load_cached(path)?;
854        if library.derivative.is_none() {
855            return Err(CScriptError::MissingSymbol {
856                path: path.to_path_buf(),
857                symbol: "cscript_derivative",
858                message: "required because this block declares xc_count > 0".to_string(),
859            });
860        }
861        if library.output_xc.is_none() {
862            return Err(CScriptError::MissingSymbol {
863                path: path.to_path_buf(),
864                symbol: "cscript_output_xc",
865                message: "required because this block declares xc_count > 0".to_string(),
866            });
867        }
868        Ok(CScriptInstance::new(library))
869    }
870}