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//! ## The optional arity declaration
198//!
199//! `in_len`/`out_len` are whatever the netlist declared for this block. If the `.c` file was
200//! written for a different number, nothing here notices: the block indexes a buffer sized by
201//! the netlist against the size it expected, which is an out-of-bounds read or write, not a
202//! failed run. A wrong answer at best, memory corruption at worst, and in neither case a
203//! message naming the block.
204//!
205//! A library can close that by saying what it was built for:
206//!
207//! ```c
208//! // Optional. Write the counts this block expects and return 0. Return non-zero to decline,
209//! // which is treated exactly like not exporting the symbol at all.
210//! int cscript_arity(int *in_len, int *out_len) {
211//! *in_len = 2;
212//! *out_len = 1;
213//! return 0;
214//! }
215//! ```
216//!
217//! When present, `dae-runtime` compares it against the netlist before the first step and
218//! refuses a disagreement with `DaeError::CScriptArityMismatch`, naming the block and both
219//! counts. This crate only resolves and calls the symbol — see
220//! [`CScriptInstance::declared_arity`] — because nothing here knows what a netlist is.
221//!
222//! A negative value means "not declaring this side", so a block that genuinely takes any
223//! number of inputs can still pin its output count:
224//!
225//! ```c
226//! int cscript_arity(int *in_len, int *out_len) {
227//! *in_len = -1; // any number
228//! *out_len = 1;
229//! return 0;
230//! }
231//! ```
232//!
233//! The symbol is optional on purpose. Every library written before it existed keeps loading and
234//! running unchanged, with the old "documented, not enforced" behaviour — the check is
235//! something a library opts into, not a new requirement.
236//!
237//! ## Multi-instance state
238//!
239//! Two block instances naming the *same* `lib=` path share one loaded image (`dlopen` on most
240//! platforms de-duplicates repeat loads of the same path — see [`CScriptLibrary::load`]), but
241//! each instance gets its *own* `cscript_start()` call and its own returned state pointer, so
242//! per-instance state (e.g. an integrator's accumulator) is never accidentally shared between
243//! two uses of the same block in one netlist. [`CScriptRegistry`] caches loaded libraries by
244//! path for exactly this reason: cheap repeat instantiation, without repeat `dlopen`.
245
246use std::collections::BTreeMap;
247use std::ffi::c_void;
248use std::path::{Path, PathBuf};
249use std::sync::Arc;
250
251use libloading::{Library, Symbol};
252
253type StartFn = unsafe extern "C" fn() -> *mut c_void;
254type OutputFn = unsafe extern "C" fn(
255 state: *mut c_void,
256 input: *const f64,
257 in_len: i32,
258 dt: f64,
259 output: *mut f64,
260 out_len: i32,
261);
262type FreeFn = unsafe extern "C" fn(state: *mut c_void);
263type CloneFn = unsafe extern "C" fn(state: *mut c_void) -> *mut c_void;
264type DerivativeFn = unsafe extern "C" fn(
265 state: *mut c_void,
266 input: *const f64,
267 in_len: i32,
268 xc: *const f64,
269 xc_len: i32,
270 xc_dot: *mut f64,
271 xc_dot_len: i32,
272);
273type OutputXcFn = unsafe extern "C" fn(
274 state: *mut c_void,
275 input: *const f64,
276 in_len: i32,
277 dt: f64,
278 xc: *const f64,
279 xc_len: i32,
280 output: *mut f64,
281 out_len: i32,
282);
283type UpdateFn = unsafe extern "C" fn(
284 state: *mut c_void,
285 input: *const f64,
286 in_len: i32,
287 dt: f64,
288 xc: *const f64,
289 xc_len: i32,
290);
291type NextSampleHitFn = unsafe extern "C" fn(
292 state: *mut c_void,
293 input: *const f64,
294 in_len: i32,
295 xc: *const f64,
296 xc_len: i32,
297) -> f64;
298/// `int cscript_arity(int *in_len, int *out_len)` — optional, see the module doc comment,
299/// "The optional arity declaration." Returns 0 to declare, non-zero to decline.
300type ArityFn = unsafe extern "C" fn(in_len: *mut i32, out_len: *mut i32) -> i32;
301type StateSizeFn = unsafe extern "C" fn(state: *const c_void) -> usize;
302type StateWriteFn = unsafe extern "C" fn(state: *const c_void, out: *mut u8);
303type StateReadFn = unsafe extern "C" fn(input: *const u8, len: usize) -> *mut c_void;
304
305/// The three symbols of the checkpoint state contract, resolved together — see the module doc
306/// comment, "The optional checkpoint state contract." Held as one `Option<StateIo>` on the
307/// library so "partially exported" cannot be represented at all past load time.
308#[derive(Clone, Copy)]
309struct StateIo {
310 size: StateSizeFn,
311 write: StateWriteFn,
312 read: StateReadFn,
313}
314
315/// What a library says about its own input and output counts.
316///
317/// Returned by [`CScriptInstance::declared_arity`]. A side is `None` when the library wrote a
318/// negative value for it, which means "I am not declaring this one" — a block genuinely
319/// variadic on one side can still pin the other.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub struct DeclaredArity {
322 pub inputs: Option<usize>,
323 pub outputs: Option<usize>,
324}
325
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub enum CScriptError {
328 Load {
329 path: PathBuf,
330 message: String,
331 },
332 MissingSymbol {
333 path: PathBuf,
334 symbol: &'static str,
335 message: String,
336 },
337 /// [`CScriptInstance::state_bytes`]/[`CScriptInstance::restore_state`] were called on an
338 /// instance whose library exports none of the checkpoint state contract's three symbols —
339 /// check [`CScriptInstance::supports_state_io`] first.
340 StateContractNotExported {
341 path: PathBuf,
342 },
343}
344
345impl std::fmt::Display for CScriptError {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 match self {
348 CScriptError::Load { path, message } => {
349 write!(
350 f,
351 "failed to load C-script library {}: {message}",
352 path.display()
353 )
354 }
355 CScriptError::MissingSymbol {
356 path,
357 symbol,
358 message,
359 } => write!(
360 f,
361 "C-script library {} is missing required symbol `{symbol}`: {message}",
362 path.display()
363 ),
364 CScriptError::StateContractNotExported { path } => write!(
365 f,
366 "C-script library {} does not export the checkpoint state contract \
367 (`cscript_state_size`/`cscript_state_write`/`cscript_state_read`)",
368 path.display()
369 ),
370 }
371 }
372}
373
374impl std::error::Error for CScriptError {}
375
376/// One loaded shared library's three FFI entry points. Kept alive for as long as any
377/// [`CScriptInstance`] built from it exists (each instance holds an `Arc` to this) — the
378/// `Library` must outlive every raw function pointer taken from it.
379pub struct CScriptLibrary {
380 // Held only to keep the mapped image alive; never read directly again after `load`.
381 _library: Library,
382 start: StartFn,
383 // `Option`, not required at load time: which of `output` or (`derivative` + `output_xc`)
384 // is actually required depends on how this library is instantiated (plain
385 // `CScriptRegistry::instantiate` vs. `instantiate_xc`) — see each one's own doc comment.
386 // `load` resolves whatever is present; the two `instantiate*` methods enforce the specific
387 // combination they each need.
388 output: Option<OutputFn>,
389 derivative: Option<DerivativeFn>,
390 output_xc: Option<OutputXcFn>,
391 // Always optional regardless of contract (plain or xc) -- see the module doc comment,
392 // "The optional discrete-state update function." Never required by either `instantiate*`
393 // method.
394 update: Option<UpdateFn>,
395 // Always optional, but *required* when this block's netlist line declares `ts=variable` --
396 // that requirement is checked by `dae-runtime`, not this crate (which has no notion of the
397 // netlist at all), by calling `CScriptInstance::supports_next_sample_hit` once at
398 // construction. See the module doc comment, "The optional block-controlled sample time."
399 next_sample_hit: Option<NextSampleHitFn>,
400 // Always optional. When present, `dae-runtime` checks it against the netlist's own
401 // declared input/output counts before the first step -- this crate has no notion of a
402 // netlist, so it only resolves and calls the symbol. See the module doc comment, "The
403 // optional arity declaration."
404 arity: Option<ArityFn>,
405 free: Option<FreeFn>,
406 clone_state: Option<CloneFn>,
407 // The checkpoint state contract, all three or none -- see the module doc comment, "The
408 // optional checkpoint state contract." A partial set is refused by `load` itself.
409 state_io: Option<StateIo>,
410 // Kept for error messages (`CScriptError::StateContractNotExported`).
411 path: PathBuf,
412}
413
414impl CScriptLibrary {
415 /// Loads `path` and resolves `cscript_start` (always required) plus every optional symbol
416 /// this crate knows about (`cscript_output`, `cscript_derivative`, `cscript_output_xc`,
417 /// `cscript_update`, `cscript_free`, `cscript_clone`, and the
418 /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple) — see the module
419 /// doc comment for what each one's absence means. Which combination is actually *required*
420 /// for a given instantiation is checked separately, by
421 /// [`CScriptRegistry::instantiate`]/[`CScriptRegistry::instantiate_xc`] — except the state
422 /// triple, which is all-or-nothing and checked here: exporting one or two of the three is
423 /// [`CScriptError::MissingSymbol`] naming the first absent one.
424 pub fn load(path: &Path) -> Result<Self, CScriptError> {
425 // SAFETY: dlopen-ing and resolving symbols from a user-specified path is exactly the
426 // unsafety this crate exists to contain -- see the module doc comment. The caller
427 // chose this path deliberately, in their own netlist.
428 let library = unsafe { Library::new(path) }.map_err(|e| CScriptError::Load {
429 path: path.to_path_buf(),
430 message: e.to_string(),
431 })?;
432
433 let start: StartFn = unsafe {
434 let symbol: Symbol<StartFn> =
435 library
436 .get(b"cscript_start\0")
437 .map_err(|e| CScriptError::MissingSymbol {
438 path: path.to_path_buf(),
439 symbol: "cscript_start",
440 message: e.to_string(),
441 })?;
442 *symbol
443 };
444 let output: Option<OutputFn> = unsafe {
445 library
446 .get(b"cscript_output\0")
447 .ok()
448 .map(|symbol: Symbol<OutputFn>| *symbol)
449 };
450 let derivative: Option<DerivativeFn> = unsafe {
451 library
452 .get(b"cscript_derivative\0")
453 .ok()
454 .map(|symbol: Symbol<DerivativeFn>| *symbol)
455 };
456 let output_xc: Option<OutputXcFn> = unsafe {
457 library
458 .get(b"cscript_output_xc\0")
459 .ok()
460 .map(|symbol: Symbol<OutputXcFn>| *symbol)
461 };
462 let update: Option<UpdateFn> = unsafe {
463 library
464 .get(b"cscript_update\0")
465 .ok()
466 .map(|symbol: Symbol<UpdateFn>| *symbol)
467 };
468 let next_sample_hit: Option<NextSampleHitFn> = unsafe {
469 library
470 .get(b"cscript_next_sample_hit\0")
471 .ok()
472 .map(|symbol: Symbol<NextSampleHitFn>| *symbol)
473 };
474 let arity: Option<ArityFn> = unsafe {
475 library
476 .get(b"cscript_arity\0")
477 .ok()
478 .map(|symbol: Symbol<ArityFn>| *symbol)
479 };
480 let free: Option<FreeFn> = unsafe {
481 library
482 .get(b"cscript_free\0")
483 .ok()
484 .map(|symbol: Symbol<FreeFn>| *symbol)
485 };
486 let clone_state: Option<CloneFn> = unsafe {
487 library
488 .get(b"cscript_clone\0")
489 .ok()
490 .map(|symbol: Symbol<CloneFn>| *symbol)
491 };
492 let state_size: Option<StateSizeFn> = unsafe {
493 library
494 .get(b"cscript_state_size\0")
495 .ok()
496 .map(|symbol: Symbol<StateSizeFn>| *symbol)
497 };
498 let state_write: Option<StateWriteFn> = unsafe {
499 library
500 .get(b"cscript_state_write\0")
501 .ok()
502 .map(|symbol: Symbol<StateWriteFn>| *symbol)
503 };
504 let state_read: Option<StateReadFn> = unsafe {
505 library
506 .get(b"cscript_state_read\0")
507 .ok()
508 .map(|symbol: Symbol<StateReadFn>| *symbol)
509 };
510 let state_io = match (state_size, state_write, state_read) {
511 (None, None, None) => None,
512 (Some(size), Some(write), Some(read)) => Some(StateIo { size, write, read }),
513 (size, write, read) => {
514 // A partial set: name the first missing one, so the author sees which of the
515 // three to add rather than a generic "checkpointing unsupported" later on.
516 let symbol = if size.is_none() {
517 "cscript_state_size"
518 } else if write.is_none() {
519 "cscript_state_write"
520 } else {
521 debug_assert!(read.is_none());
522 "cscript_state_read"
523 };
524 return Err(CScriptError::MissingSymbol {
525 path: path.to_path_buf(),
526 symbol,
527 message: "the checkpoint state contract is all-or-nothing: \
528 cscript_state_size, cscript_state_write and cscript_state_read \
529 must all be exported, or none of them"
530 .to_string(),
531 });
532 }
533 };
534
535 Ok(CScriptLibrary {
536 _library: library,
537 start,
538 output,
539 derivative,
540 output_xc,
541 update,
542 next_sample_hit,
543 arity,
544 free,
545 clone_state,
546 state_io,
547 path: path.to_path_buf(),
548 })
549 }
550}
551
552/// One block instance's own state, from one call to `cscript_start()` on a shared
553/// [`CScriptLibrary`]. `Drop` calls `cscript_free` if the library exported one.
554pub struct CScriptInstance {
555 library: Arc<CScriptLibrary>,
556 state: *mut c_void,
557}
558
559impl std::fmt::Debug for CScriptInstance {
560 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
561 f.debug_struct("CScriptInstance")
562 .field("state", &self.state)
563 .finish()
564 }
565}
566
567// The state pointer is opaque to us and only ever passed back into the same library's own
568// functions, which are the sole thing that dereferences it -- this crate never reads through
569// it, so moving the pointer between threads is exactly as safe as moving the shared library
570// handle itself. Circuit simulation in this workspace is single-threaded, so this is unused in
571// practice, but the type would otherwise fail to be `Send` at all without it.
572unsafe impl Send for CScriptInstance {}
573
574impl CScriptInstance {
575 fn new(library: Arc<CScriptLibrary>) -> Self {
576 // SAFETY: calling into user-supplied native code with no arguments, as documented in
577 // the module doc comment's C-side contract.
578 let state = unsafe { (library.start)() };
579 CScriptInstance { library, state }
580 }
581
582 /// Calls `cscript_output` with this instance's own state, `input` and `dt` as given, and
583 /// an `out_len`-length zero-initialized output buffer, returning it filled in.
584 ///
585 /// # Panics
586 /// If this instance's library doesn't export `cscript_output` — unreachable in practice,
587 /// since [`CScriptRegistry::instantiate`] (the only way to obtain an instance meant to use
588 /// this method) already requires it up front, the same "checked once, up front" discipline
589 /// [`Clone`]'s own `cscript_clone` requirement uses.
590 pub fn call(&mut self, input: &[f64], dt: f64, out_len: usize) -> Vec<f64> {
591 let output_fn = self.library.output.unwrap_or_else(|| {
592 panic!(
593 "call requires a library loaded via CScriptRegistry::instantiate (which \
594 already requires cscript_output up front — this should be unreachable)"
595 )
596 });
597 let mut output = vec![0.0_f64; out_len];
598 // SAFETY: `input`/`output` are valid slices of the declared lengths for the duration
599 // of this call; `in_len`/`out_len` are passed through unchanged so the callee can
600 // bounds-check itself. Whether the callee actually respects them is the documented,
601 // unenforceable part of the C-side contract (see module doc comment).
602 unsafe {
603 output_fn(
604 self.state,
605 input.as_ptr(),
606 input.len() as i32,
607 dt,
608 output.as_mut_ptr(),
609 out_len as i32,
610 );
611 }
612 output
613 }
614
615 /// Calls `cscript_output_xc` with this instance's own state, `input`/`dt` as given, `xc` as
616 /// this step's own already-integrated continuous-state vector, and an `out_len`-length
617 /// zero-initialized output buffer, returning it filled in — the `xc`-owning counterpart to
618 /// [`Self::call`]. See the module doc comment, "The optional continuous-state (`xc`)
619 /// contract."
620 ///
621 /// # Panics
622 /// If this instance's library doesn't export `cscript_output_xc` — unreachable in
623 /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
624 pub fn call_xc(&mut self, input: &[f64], dt: f64, xc: &[f64], out_len: usize) -> Vec<f64> {
625 let output_xc = self.library.output_xc.unwrap_or_else(|| {
626 panic!(
627 "call_xc requires a library loaded via CScriptRegistry::instantiate_xc (which \
628 already requires cscript_output_xc up front — this should be unreachable)"
629 )
630 });
631 let mut output = vec![0.0_f64; out_len];
632 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
633 unsafe {
634 output_xc(
635 self.state,
636 input.as_ptr(),
637 input.len() as i32,
638 dt,
639 xc.as_ptr(),
640 xc.len() as i32,
641 output.as_mut_ptr(),
642 out_len as i32,
643 );
644 }
645 output
646 }
647
648 /// Calls `cscript_update` with this instance's own state, `input`/`dt`/`xc` as given -- a
649 /// no-op if this instance's library didn't export it (see the module doc comment, "The
650 /// optional discrete-state update function"). Unlike [`Self::call`]/[`Self::call_xc`], this
651 /// is genuinely optional for *both* contracts, so there's no panic path: call it every
652 /// step it's due exactly like output, and it simply does nothing if the author never wrote
653 /// one.
654 pub fn update(&mut self, input: &[f64], dt: f64, xc: &[f64]) {
655 let Some(update_fn) = self.library.update else {
656 return;
657 };
658 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
659 unsafe {
660 update_fn(
661 self.state,
662 input.as_ptr(),
663 input.len() as i32,
664 dt,
665 xc.as_ptr(),
666 xc.len() as i32,
667 );
668 }
669 }
670
671 /// Whether this instance's library exported `cscript_next_sample_hit` — check this once, up
672 /// front, when this block's netlist line declares `ts=variable` (see the module doc
673 /// comment, "The optional block-controlled sample time") and reject the netlist with a
674 /// clear error if not, before ever calling [`Self::next_sample_hit`].
675 pub fn supports_next_sample_hit(&self) -> bool {
676 self.library.next_sample_hit.is_some()
677 }
678
679 /// What this library declares its own arity to be, if it declares one.
680 ///
681 /// `None` when `cscript_arity` is absent, or present and returns non-zero — a library may
682 /// decline, and declining is not an error. `Some` carries each side separately, because a
683 /// negative value means "not declaring this one".
684 ///
685 /// This crate only asks the question. Comparing the answer against a netlist's declared
686 /// port counts is `dae-runtime`'s, since nothing here knows what a netlist is.
687 pub fn declared_arity(&self) -> Option<DeclaredArity> {
688 let arity = self.library.arity?;
689 let mut in_len: i32 = -1;
690 let mut out_len: i32 = -1;
691 // SAFETY: both pointers are to live locals of the right type, and the contract is that
692 // the callee writes through them and returns 0, or leaves them alone and returns
693 // non-zero. Either way nothing is read back unless it returned 0.
694 let status = unsafe { arity(&mut in_len, &mut out_len) };
695 if status != 0 {
696 return None;
697 }
698 Some(DeclaredArity {
699 inputs: usize::try_from(in_len).ok(),
700 outputs: usize::try_from(out_len).ok(),
701 })
702 }
703
704 /// Calls `cscript_next_sample_hit`, returning the number of seconds (relative to this call)
705 /// until this block should next be executed.
706 ///
707 /// # Panics
708 /// If this instance's library doesn't export `cscript_next_sample_hit` — unreachable in
709 /// practice, since a caller is expected to check [`Self::supports_next_sample_hit`] once,
710 /// up front, before ever using `ts=variable` for this block at all.
711 pub fn next_sample_hit(&self, input: &[f64], xc: &[f64]) -> f64 {
712 let next_sample_hit_fn = self.library.next_sample_hit.unwrap_or_else(|| {
713 panic!(
714 "next_sample_hit requires a library that exports cscript_next_sample_hit \
715 (required for ts=variable — this should be unreachable, since that's checked \
716 up front)"
717 )
718 });
719 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
720 unsafe {
721 next_sample_hit_fn(
722 self.state,
723 input.as_ptr(),
724 input.len() as i32,
725 xc.as_ptr(),
726 xc.len() as i32,
727 )
728 }
729 }
730
731 /// Evaluates `cscript_derivative` once: given this step's already-resolved inputs and a
732 /// candidate continuous-state vector `xc`, returns `dxc/dt`. Takes `&self` rather than
733 /// `&mut self` — the C-side contract documents (but, like every other rule in this crate,
734 /// cannot enforce) that this call must not mutate `state`, so the Rust type keeps that
735 /// intent honest even though the raw pointer underneath is technically mutable.
736 ///
737 /// # Panics
738 /// If this instance's library doesn't export `cscript_derivative` — unreachable in
739 /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
740 pub fn derivative(&self, input: &[f64], xc: &[f64]) -> Vec<f64> {
741 let derivative_fn = self.library.derivative.unwrap_or_else(|| {
742 panic!(
743 "derivative requires a library loaded via CScriptRegistry::instantiate_xc \
744 (which already requires cscript_derivative up front — this should be \
745 unreachable)"
746 )
747 });
748 let mut xc_dot = vec![0.0_f64; xc.len()];
749 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`/`xc_dot`.
750 unsafe {
751 derivative_fn(
752 self.state,
753 input.as_ptr(),
754 input.len() as i32,
755 xc.as_ptr(),
756 xc.len() as i32,
757 xc_dot.as_mut_ptr(),
758 xc_dot.len() as i32,
759 );
760 }
761 xc_dot
762 }
763
764 /// RK4-integrates `xc` forward by `dt`, holding `input` fixed across all four stages — the
765 /// same zero-order-hold convention `continuous_blocks::StateSpace::rk4_step` uses for every
766 /// other dynamic block in this workspace, so a `cscript` block's own continuous state
767 /// integrates exactly like a `Pid`/`StateSpace`/`Pmsm`'s does, not by some separate rule.
768 /// Calls [`Self::derivative`] up to four times (`k1..k4`) — see that method's own `#Panics`.
769 pub fn rk4_step_xc(&self, xc: &[f64], input: &[f64], dt: f64) -> Vec<f64> {
770 let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
771 a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
772 };
773 let k1 = self.derivative(input, xc);
774 let k2 = self.derivative(input, &add(xc, &k1, dt / 2.0));
775 let k3 = self.derivative(input, &add(xc, &k2, dt / 2.0));
776 let k4 = self.derivative(input, &add(xc, &k3, dt));
777 (0..xc.len())
778 .map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
779 .collect()
780 }
781
782 /// Whether this instance's library exported `cscript_clone` — check this once, up front,
783 /// before deciding whether a netlist using this block is eligible for adaptive step-size
784 /// control (see the module doc comment, "Adaptive step-size control and instance cloning").
785 pub fn supports_clone(&self) -> bool {
786 self.library.clone_state.is_some()
787 }
788
789 /// A real, independent deep copy of this instance's state via `cscript_clone`, or `None`
790 /// if the library didn't export it. Prefer this over [`Clone::clone`] wherever a missing
791 /// `cscript_clone` should be handled as an ordinary error rather than a panic.
792 pub fn try_clone(&self) -> Option<CScriptInstance> {
793 let clone_fn = self.library.clone_state?;
794 // SAFETY: `self.state` was returned by this same library's own `cscript_start` (or a
795 // prior `cscript_clone`); the callee is expected to return an independent copy, per
796 // the C-side contract documented in the module doc comment.
797 let state = unsafe { clone_fn(self.state) };
798 Some(CScriptInstance {
799 library: self.library.clone(),
800 state,
801 })
802 }
803
804 /// Whether this instance's library exported the
805 /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple — check this once,
806 /// up front, before deciding whether a run containing this block can be checkpointed (see
807 /// the module doc comment, "The optional checkpoint state contract"). A library exporting
808 /// none of the three is the "no" case; a partial set never loads at all.
809 pub fn supports_state_io(&self) -> bool {
810 self.library.state_io.is_some()
811 }
812
813 /// This instance's opaque state, serialized by the library's own `cscript_state_write` into
814 /// exactly `cscript_state_size` bytes — the save half of the checkpoint state contract.
815 /// Empty for a state the library reports as zero-sized (a `NULL` state, typically).
816 pub fn state_bytes(&self) -> Result<Vec<u8>, CScriptError> {
817 let io = self
818 .library
819 .state_io
820 .ok_or_else(|| CScriptError::StateContractNotExported {
821 path: self.library.path.clone(),
822 })?;
823 // SAFETY: `self.state` came from this same library's own `cscript_start`/`cscript_clone`/
824 // `cscript_state_read`; `size` is documented as read-only on it.
825 let len = unsafe { (io.size)(self.state) };
826 let mut bytes = vec![0_u8; len];
827 if len > 0 {
828 // SAFETY: `bytes` is exactly the `len` bytes the contract promises `write` room
829 // for, valid for the duration of the call.
830 unsafe { (io.write)(self.state, bytes.as_mut_ptr()) };
831 }
832 Ok(bytes)
833 }
834
835 /// Replaces this instance's state with one rebuilt by the library's own `cscript_state_read`
836 /// from `bytes` (as produced by [`Self::state_bytes`], possibly in another process) — the
837 /// load half of the checkpoint state contract. The previous state is released through
838 /// `cscript_free` if the library exported it, exactly as on drop.
839 pub fn restore_state(&mut self, bytes: &[u8]) -> Result<(), CScriptError> {
840 let io = self
841 .library
842 .state_io
843 .ok_or_else(|| CScriptError::StateContractNotExported {
844 path: self.library.path.clone(),
845 })?;
846 // SAFETY: `bytes` is a valid slice for the duration of the call; the callee is
847 // documented to return a fresh, independently owned state (or NULL for none).
848 let new_state = unsafe { (io.read)(bytes.as_ptr(), bytes.len()) };
849 if let Some(free) = self.library.free {
850 if !self.state.is_null() {
851 // SAFETY: the old `state` was returned by this same library and is released
852 // exactly once, here, before the pointer is overwritten below.
853 unsafe { free(self.state) };
854 }
855 }
856 self.state = new_state;
857 Ok(())
858 }
859}
860
861impl Clone for CScriptInstance {
862 /// # Panics
863 /// If this instance's library didn't export `cscript_clone`. See the module doc comment,
864 /// "Adaptive step-size control and instance cloning" — callers that need to handle this
865 /// without panicking should check [`CScriptInstance::supports_clone`] first, or use
866 /// [`CScriptInstance::try_clone`] directly.
867 fn clone(&self) -> Self {
868 self.try_clone().unwrap_or_else(|| {
869 panic!(
870 "cannot clone a CScriptInstance whose library does not export cscript_clone \
871 (required for general-simulator's adaptive step-size control); either export \
872 cscript_clone from this library or run with a fixed --dt"
873 )
874 })
875 }
876}
877
878impl Drop for CScriptInstance {
879 fn drop(&mut self) {
880 if let Some(free) = self.library.free {
881 if !self.state.is_null() {
882 // SAFETY: `state` was returned by this same library's own `cscript_start`, and
883 // this is the only place it is ever freed.
884 unsafe { free(self.state) };
885 }
886 }
887 }
888}
889
890/// Caches loaded libraries by path, so several block instances naming the same `lib=` file
891/// share one `dlopen`'d image while each still gets its own [`CScriptInstance`] (own state
892/// pointer) — see the module doc comment, "Multi-instance state."
893#[derive(Default)]
894pub struct CScriptRegistry {
895 libraries: BTreeMap<PathBuf, Arc<CScriptLibrary>>,
896}
897
898impl CScriptRegistry {
899 pub fn new() -> Self {
900 Self::default()
901 }
902
903 /// Loads `path` if not already cached (resolving every optional symbol this crate knows
904 /// about, regardless of which contract the caller ultimately needs — see
905 /// [`CScriptLibrary::load`]'s own doc comment), returning the cached/loaded `Arc`.
906 fn load_cached(&mut self, path: &Path) -> Result<Arc<CScriptLibrary>, CScriptError> {
907 if let Some(library) = self.libraries.get(path) {
908 Ok(library.clone())
909 } else {
910 let library = Arc::new(CScriptLibrary::load(path)?);
911 self.libraries.insert(path.to_path_buf(), library.clone());
912 Ok(library)
913 }
914 }
915
916 /// Loads `path` if not already cached, then creates and returns a fresh instance from it
917 /// (its own `cscript_start()` call, its own state) using the **plain** contract: requires
918 /// `cscript_output` (via [`CScriptInstance::call`]), for a block with `xc_count == 0`.
919 pub fn instantiate(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
920 let library = self.load_cached(path)?;
921 if library.output.is_none() {
922 return Err(CScriptError::MissingSymbol {
923 path: path.to_path_buf(),
924 symbol: "cscript_output",
925 message: "not found (or this library only implements the xc-owning contract \
926 — see CScriptRegistry::instantiate_xc)"
927 .to_string(),
928 });
929 }
930 Ok(CScriptInstance::new(library))
931 }
932
933 /// Loads `path` if not already cached, then creates and returns a fresh instance from it
934 /// using the **continuous-state (`xc`)** contract: requires `cscript_derivative` and
935 /// `cscript_output_xc` (via [`CScriptInstance::rk4_step_xc`]/[`CScriptInstance::call_xc`]),
936 /// for a block with `xc_count > 0`. See the module doc comment, "The optional
937 /// continuous-state (`xc`) contract."
938 pub fn instantiate_xc(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
939 let library = self.load_cached(path)?;
940 if library.derivative.is_none() {
941 return Err(CScriptError::MissingSymbol {
942 path: path.to_path_buf(),
943 symbol: "cscript_derivative",
944 message: "required because this block declares xc_count > 0".to_string(),
945 });
946 }
947 if library.output_xc.is_none() {
948 return Err(CScriptError::MissingSymbol {
949 path: path.to_path_buf(),
950 symbol: "cscript_output_xc",
951 message: "required because this block declares xc_count > 0".to_string(),
952 });
953 }
954 Ok(CScriptInstance::new(library))
955 }
956}