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