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//! ## Adaptive step-size control and instance cloning
143//!
144//! general-simulator's adaptive step-size control retries a rejected trial step from scratch: every
145//! block's state is cloned before the trial, the trial runs against the clone, and if rejected
146//! the clone is discarded and a fresh one is taken for the next, smaller attempt -- never
147//! mutating the real, confirmed state until a trial is actually accepted. That is exactly
148//! correct for plain Rust block state (a `Vec<f64>` clone is a real, independent copy), but a
149//! [`CScriptInstance`]'s state is an opaque pointer this crate never reads through, so it cannot
150//! generically deep-copy it -- only the user's own C code knows its own layout. [`Clone`] for
151//! [`CScriptInstance`] is implemented in terms of `cscript_clone` for exactly this reason, and
152//! **panics** if the library didn't export it. In practice this should never fire: check
153//! [`CScriptInstance::supports_clone`] once, up front, and refuse adaptive step-size control
154//! for a netlist containing a `cscript` block whose library doesn't support it, the same way
155//! `dae-runtime` already does before entering its own adaptive loop.
156//!
157//! Everything else in the user's `.c` file — includes, `#define`s, `typedef`s, file-scope
158//! `static` helper functions and variables the user wants visible to all three of the functions
159//! above for one translation unit — needs no special support from this crate: plain C file
160//! scope already provides exactly that. The user compiles their own `.c` file into a shared
161//! library themselves (e.g. `cc -shared -fPIC -o my_block.so my_block.c`); this crate never
162//! invokes a compiler.
163//!
164//! `in_len`/`out_len` must match the netlist's own declared input/output counts for this block
165//! — nothing in this crate checks that they do; a mismatch is a plain out-of-bounds C array
166//! access, same as it would be calling `OutputSignal(9, 0)` past a declared output count in any
167//! other tool's own code-slot mechanism. This is documented, not enforced.
168//!
169//! ## Multi-instance state
170//!
171//! Two block instances naming the *same* `lib=` path share one loaded image (`dlopen` on most
172//! platforms de-duplicates repeat loads of the same path — see [`CScriptLibrary::load`]), but
173//! each instance gets its *own* `cscript_start()` call and its own returned state pointer, so
174//! per-instance state (e.g. an integrator's accumulator) is never accidentally shared between
175//! two uses of the same block in one netlist. [`CScriptRegistry`] caches loaded libraries by
176//! path for exactly this reason: cheap repeat instantiation, without repeat `dlopen`.
177
178use std::collections::BTreeMap;
179use std::ffi::c_void;
180use std::path::{Path, PathBuf};
181use std::sync::Arc;
182
183use libloading::{Library, Symbol};
184
185type StartFn = unsafe extern "C" fn() -> *mut c_void;
186type OutputFn = unsafe extern "C" fn(
187 state: *mut c_void,
188 input: *const f64,
189 in_len: i32,
190 dt: f64,
191 output: *mut f64,
192 out_len: i32,
193);
194type FreeFn = unsafe extern "C" fn(state: *mut c_void);
195type CloneFn = unsafe extern "C" fn(state: *mut c_void) -> *mut c_void;
196type DerivativeFn = unsafe extern "C" fn(
197 state: *mut c_void,
198 input: *const f64,
199 in_len: i32,
200 xc: *const f64,
201 xc_len: i32,
202 xc_dot: *mut f64,
203 xc_dot_len: i32,
204);
205type OutputXcFn = unsafe extern "C" fn(
206 state: *mut c_void,
207 input: *const f64,
208 in_len: i32,
209 dt: f64,
210 xc: *const f64,
211 xc_len: i32,
212 output: *mut f64,
213 out_len: i32,
214);
215type UpdateFn = unsafe extern "C" fn(
216 state: *mut c_void,
217 input: *const f64,
218 in_len: i32,
219 dt: f64,
220 xc: *const f64,
221 xc_len: i32,
222);
223type NextSampleHitFn = unsafe extern "C" fn(
224 state: *mut c_void,
225 input: *const f64,
226 in_len: i32,
227 xc: *const f64,
228 xc_len: i32,
229) -> f64;
230
231#[derive(Debug, Clone, PartialEq, Eq)]
232pub enum CScriptError {
233 Load {
234 path: PathBuf,
235 message: String,
236 },
237 MissingSymbol {
238 path: PathBuf,
239 symbol: &'static str,
240 message: String,
241 },
242}
243
244impl std::fmt::Display for CScriptError {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 match self {
247 CScriptError::Load { path, message } => {
248 write!(
249 f,
250 "failed to load C-script library {}: {message}",
251 path.display()
252 )
253 }
254 CScriptError::MissingSymbol {
255 path,
256 symbol,
257 message,
258 } => write!(
259 f,
260 "C-script library {} is missing required symbol `{symbol}`: {message}",
261 path.display()
262 ),
263 }
264 }
265}
266
267impl std::error::Error for CScriptError {}
268
269/// One loaded shared library's three FFI entry points. Kept alive for as long as any
270/// [`CScriptInstance`] built from it exists (each instance holds an `Arc` to this) — the
271/// `Library` must outlive every raw function pointer taken from it.
272pub struct CScriptLibrary {
273 // Held only to keep the mapped image alive; never read directly again after `load`.
274 _library: Library,
275 start: StartFn,
276 // `Option`, not required at load time: which of `output` or (`derivative` + `output_xc`)
277 // is actually required depends on how this library is instantiated (plain
278 // `CScriptRegistry::instantiate` vs. `instantiate_xc`) — see each one's own doc comment.
279 // `load` resolves whatever is present; the two `instantiate*` methods enforce the specific
280 // combination they each need.
281 output: Option<OutputFn>,
282 derivative: Option<DerivativeFn>,
283 output_xc: Option<OutputXcFn>,
284 // Always optional regardless of contract (plain or xc) -- see the module doc comment,
285 // "The optional discrete-state update function." Never required by either `instantiate*`
286 // method.
287 update: Option<UpdateFn>,
288 // Always optional, but *required* when this block's netlist line declares `ts=variable` --
289 // that requirement is checked by `dae-runtime`, not this crate (which has no notion of the
290 // netlist at all), by calling `CScriptInstance::supports_next_sample_hit` once at
291 // construction. See the module doc comment, "The optional block-controlled sample time."
292 next_sample_hit: Option<NextSampleHitFn>,
293 free: Option<FreeFn>,
294 clone_state: Option<CloneFn>,
295}
296
297impl CScriptLibrary {
298 /// Loads `path` and resolves `cscript_start` (always required) plus every optional symbol
299 /// this crate knows about (`cscript_output`, `cscript_derivative`, `cscript_output_xc`,
300 /// `cscript_update`, `cscript_free`, `cscript_clone`) — see the module doc comment for what
301 /// each one's absence means. Which combination is actually *required* for a given
302 /// instantiation is checked separately, by
303 /// [`CScriptRegistry::instantiate`]/[`CScriptRegistry::instantiate_xc`].
304 pub fn load(path: &Path) -> Result<Self, CScriptError> {
305 // SAFETY: dlopen-ing and resolving symbols from a user-specified path is exactly the
306 // unsafety this crate exists to contain -- see the module doc comment. The caller
307 // chose this path deliberately, in their own netlist.
308 let library = unsafe { Library::new(path) }.map_err(|e| CScriptError::Load {
309 path: path.to_path_buf(),
310 message: e.to_string(),
311 })?;
312
313 let start: StartFn = unsafe {
314 let symbol: Symbol<StartFn> =
315 library
316 .get(b"cscript_start\0")
317 .map_err(|e| CScriptError::MissingSymbol {
318 path: path.to_path_buf(),
319 symbol: "cscript_start",
320 message: e.to_string(),
321 })?;
322 *symbol
323 };
324 let output: Option<OutputFn> = unsafe {
325 library
326 .get(b"cscript_output\0")
327 .ok()
328 .map(|symbol: Symbol<OutputFn>| *symbol)
329 };
330 let derivative: Option<DerivativeFn> = unsafe {
331 library
332 .get(b"cscript_derivative\0")
333 .ok()
334 .map(|symbol: Symbol<DerivativeFn>| *symbol)
335 };
336 let output_xc: Option<OutputXcFn> = unsafe {
337 library
338 .get(b"cscript_output_xc\0")
339 .ok()
340 .map(|symbol: Symbol<OutputXcFn>| *symbol)
341 };
342 let update: Option<UpdateFn> = unsafe {
343 library
344 .get(b"cscript_update\0")
345 .ok()
346 .map(|symbol: Symbol<UpdateFn>| *symbol)
347 };
348 let next_sample_hit: Option<NextSampleHitFn> = unsafe {
349 library
350 .get(b"cscript_next_sample_hit\0")
351 .ok()
352 .map(|symbol: Symbol<NextSampleHitFn>| *symbol)
353 };
354 let free: Option<FreeFn> = unsafe {
355 library
356 .get(b"cscript_free\0")
357 .ok()
358 .map(|symbol: Symbol<FreeFn>| *symbol)
359 };
360 let clone_state: Option<CloneFn> = unsafe {
361 library
362 .get(b"cscript_clone\0")
363 .ok()
364 .map(|symbol: Symbol<CloneFn>| *symbol)
365 };
366
367 Ok(CScriptLibrary {
368 _library: library,
369 start,
370 output,
371 derivative,
372 output_xc,
373 update,
374 next_sample_hit,
375 free,
376 clone_state,
377 })
378 }
379}
380
381/// One block instance's own state, from one call to `cscript_start()` on a shared
382/// [`CScriptLibrary`]. `Drop` calls `cscript_free` if the library exported one.
383pub struct CScriptInstance {
384 library: Arc<CScriptLibrary>,
385 state: *mut c_void,
386}
387
388impl std::fmt::Debug for CScriptInstance {
389 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390 f.debug_struct("CScriptInstance")
391 .field("state", &self.state)
392 .finish()
393 }
394}
395
396// The state pointer is opaque to us and only ever passed back into the same library's own
397// functions, which are the sole thing that dereferences it -- this crate never reads through
398// it, so moving the pointer between threads is exactly as safe as moving the shared library
399// handle itself. Circuit simulation in this workspace is single-threaded, so this is unused in
400// practice, but the type would otherwise fail to be `Send` at all without it.
401unsafe impl Send for CScriptInstance {}
402
403impl CScriptInstance {
404 fn new(library: Arc<CScriptLibrary>) -> Self {
405 // SAFETY: calling into user-supplied native code with no arguments, as documented in
406 // the module doc comment's C-side contract.
407 let state = unsafe { (library.start)() };
408 CScriptInstance { library, state }
409 }
410
411 /// Calls `cscript_output` with this instance's own state, `input` and `dt` as given, and
412 /// an `out_len`-length zero-initialized output buffer, returning it filled in.
413 ///
414 /// # Panics
415 /// If this instance's library doesn't export `cscript_output` — unreachable in practice,
416 /// since [`CScriptRegistry::instantiate`] (the only way to obtain an instance meant to use
417 /// this method) already requires it up front, the same "checked once, up front" discipline
418 /// [`Clone`]'s own `cscript_clone` requirement uses.
419 pub fn call(&mut self, input: &[f64], dt: f64, out_len: usize) -> Vec<f64> {
420 let output_fn = self.library.output.unwrap_or_else(|| {
421 panic!(
422 "call requires a library loaded via CScriptRegistry::instantiate (which \
423 already requires cscript_output up front — this should be unreachable)"
424 )
425 });
426 let mut output = vec![0.0_f64; out_len];
427 // SAFETY: `input`/`output` are valid slices of the declared lengths for the duration
428 // of this call; `in_len`/`out_len` are passed through unchanged so the callee can
429 // bounds-check itself. Whether the callee actually respects them is the documented,
430 // unenforceable part of the C-side contract (see module doc comment).
431 unsafe {
432 output_fn(
433 self.state,
434 input.as_ptr(),
435 input.len() as i32,
436 dt,
437 output.as_mut_ptr(),
438 out_len as i32,
439 );
440 }
441 output
442 }
443
444 /// Calls `cscript_output_xc` with this instance's own state, `input`/`dt` as given, `xc` as
445 /// this step's own already-integrated continuous-state vector, and an `out_len`-length
446 /// zero-initialized output buffer, returning it filled in — the `xc`-owning counterpart to
447 /// [`Self::call`]. See the module doc comment, "The optional continuous-state (`xc`)
448 /// contract."
449 ///
450 /// # Panics
451 /// If this instance's library doesn't export `cscript_output_xc` — unreachable in
452 /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
453 pub fn call_xc(&mut self, input: &[f64], dt: f64, xc: &[f64], out_len: usize) -> Vec<f64> {
454 let output_xc = self.library.output_xc.unwrap_or_else(|| {
455 panic!(
456 "call_xc requires a library loaded via CScriptRegistry::instantiate_xc (which \
457 already requires cscript_output_xc up front — this should be unreachable)"
458 )
459 });
460 let mut output = vec![0.0_f64; out_len];
461 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
462 unsafe {
463 output_xc(
464 self.state,
465 input.as_ptr(),
466 input.len() as i32,
467 dt,
468 xc.as_ptr(),
469 xc.len() as i32,
470 output.as_mut_ptr(),
471 out_len as i32,
472 );
473 }
474 output
475 }
476
477 /// Calls `cscript_update` with this instance's own state, `input`/`dt`/`xc` as given -- a
478 /// no-op if this instance's library didn't export it (see the module doc comment, "The
479 /// optional discrete-state update function"). Unlike [`Self::call`]/[`Self::call_xc`], this
480 /// is genuinely optional for *both* contracts, so there's no panic path: call it every
481 /// step it's due exactly like output, and it simply does nothing if the author never wrote
482 /// one.
483 pub fn update(&mut self, input: &[f64], dt: f64, xc: &[f64]) {
484 let Some(update_fn) = self.library.update else {
485 return;
486 };
487 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
488 unsafe {
489 update_fn(
490 self.state,
491 input.as_ptr(),
492 input.len() as i32,
493 dt,
494 xc.as_ptr(),
495 xc.len() as i32,
496 );
497 }
498 }
499
500 /// Whether this instance's library exported `cscript_next_sample_hit` — check this once, up
501 /// front, when this block's netlist line declares `ts=variable` (see the module doc
502 /// comment, "The optional block-controlled sample time") and reject the netlist with a
503 /// clear error if not, before ever calling [`Self::next_sample_hit`].
504 pub fn supports_next_sample_hit(&self) -> bool {
505 self.library.next_sample_hit.is_some()
506 }
507
508 /// Calls `cscript_next_sample_hit`, returning the number of seconds (relative to this call)
509 /// until this block should next be executed.
510 ///
511 /// # Panics
512 /// If this instance's library doesn't export `cscript_next_sample_hit` — unreachable in
513 /// practice, since a caller is expected to check [`Self::supports_next_sample_hit`] once,
514 /// up front, before ever using `ts=variable` for this block at all.
515 pub fn next_sample_hit(&self, input: &[f64], xc: &[f64]) -> f64 {
516 let next_sample_hit_fn = self.library.next_sample_hit.unwrap_or_else(|| {
517 panic!(
518 "next_sample_hit requires a library that exports cscript_next_sample_hit \
519 (required for ts=variable — this should be unreachable, since that's checked \
520 up front)"
521 )
522 });
523 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
524 unsafe {
525 next_sample_hit_fn(
526 self.state,
527 input.as_ptr(),
528 input.len() as i32,
529 xc.as_ptr(),
530 xc.len() as i32,
531 )
532 }
533 }
534
535 /// Evaluates `cscript_derivative` once: given this step's already-resolved inputs and a
536 /// candidate continuous-state vector `xc`, returns `dxc/dt`. Takes `&self` rather than
537 /// `&mut self` — the C-side contract documents (but, like every other rule in this crate,
538 /// cannot enforce) that this call must not mutate `state`, so the Rust type keeps that
539 /// intent honest even though the raw pointer underneath is technically mutable.
540 ///
541 /// # Panics
542 /// If this instance's library doesn't export `cscript_derivative` — unreachable in
543 /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
544 pub fn derivative(&self, input: &[f64], xc: &[f64]) -> Vec<f64> {
545 let derivative_fn = self.library.derivative.unwrap_or_else(|| {
546 panic!(
547 "derivative requires a library loaded via CScriptRegistry::instantiate_xc \
548 (which already requires cscript_derivative up front — this should be \
549 unreachable)"
550 )
551 });
552 let mut xc_dot = vec![0.0_f64; xc.len()];
553 // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`/`xc_dot`.
554 unsafe {
555 derivative_fn(
556 self.state,
557 input.as_ptr(),
558 input.len() as i32,
559 xc.as_ptr(),
560 xc.len() as i32,
561 xc_dot.as_mut_ptr(),
562 xc_dot.len() as i32,
563 );
564 }
565 xc_dot
566 }
567
568 /// RK4-integrates `xc` forward by `dt`, holding `input` fixed across all four stages — the
569 /// same zero-order-hold convention `continuous_blocks::StateSpace::rk4_step` uses for every
570 /// other dynamic block in this workspace, so a `cscript` block's own continuous state
571 /// integrates exactly like a `Pid`/`StateSpace`/`Pmsm`'s does, not by some separate rule.
572 /// Calls [`Self::derivative`] up to four times (`k1..k4`) — see that method's own `#Panics`.
573 pub fn rk4_step_xc(&self, xc: &[f64], input: &[f64], dt: f64) -> Vec<f64> {
574 let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
575 a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
576 };
577 let k1 = self.derivative(input, xc);
578 let k2 = self.derivative(input, &add(xc, &k1, dt / 2.0));
579 let k3 = self.derivative(input, &add(xc, &k2, dt / 2.0));
580 let k4 = self.derivative(input, &add(xc, &k3, dt));
581 (0..xc.len())
582 .map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
583 .collect()
584 }
585
586 /// Whether this instance's library exported `cscript_clone` — check this once, up front,
587 /// before deciding whether a netlist using this block is eligible for adaptive step-size
588 /// control (see the module doc comment, "Adaptive step-size control and instance cloning").
589 pub fn supports_clone(&self) -> bool {
590 self.library.clone_state.is_some()
591 }
592
593 /// A real, independent deep copy of this instance's state via `cscript_clone`, or `None`
594 /// if the library didn't export it. Prefer this over [`Clone::clone`] wherever a missing
595 /// `cscript_clone` should be handled as an ordinary error rather than a panic.
596 pub fn try_clone(&self) -> Option<CScriptInstance> {
597 let clone_fn = self.library.clone_state?;
598 // SAFETY: `self.state` was returned by this same library's own `cscript_start` (or a
599 // prior `cscript_clone`); the callee is expected to return an independent copy, per
600 // the C-side contract documented in the module doc comment.
601 let state = unsafe { clone_fn(self.state) };
602 Some(CScriptInstance {
603 library: self.library.clone(),
604 state,
605 })
606 }
607}
608
609impl Clone for CScriptInstance {
610 /// # Panics
611 /// If this instance's library didn't export `cscript_clone`. See the module doc comment,
612 /// "Adaptive step-size control and instance cloning" — callers that need to handle this
613 /// without panicking should check [`CScriptInstance::supports_clone`] first, or use
614 /// [`CScriptInstance::try_clone`] directly.
615 fn clone(&self) -> Self {
616 self.try_clone().unwrap_or_else(|| {
617 panic!(
618 "cannot clone a CScriptInstance whose library does not export cscript_clone \
619 (required for general-simulator's adaptive step-size control); either export \
620 cscript_clone from this library or run with a fixed --dt"
621 )
622 })
623 }
624}
625
626impl Drop for CScriptInstance {
627 fn drop(&mut self) {
628 if let Some(free) = self.library.free {
629 if !self.state.is_null() {
630 // SAFETY: `state` was returned by this same library's own `cscript_start`, and
631 // this is the only place it is ever freed.
632 unsafe { free(self.state) };
633 }
634 }
635 }
636}
637
638/// Caches loaded libraries by path, so several block instances naming the same `lib=` file
639/// share one `dlopen`'d image while each still gets its own [`CScriptInstance`] (own state
640/// pointer) — see the module doc comment, "Multi-instance state."
641#[derive(Default)]
642pub struct CScriptRegistry {
643 libraries: BTreeMap<PathBuf, Arc<CScriptLibrary>>,
644}
645
646impl CScriptRegistry {
647 pub fn new() -> Self {
648 Self::default()
649 }
650
651 /// Loads `path` if not already cached (resolving every optional symbol this crate knows
652 /// about, regardless of which contract the caller ultimately needs — see
653 /// [`CScriptLibrary::load`]'s own doc comment), returning the cached/loaded `Arc`.
654 fn load_cached(&mut self, path: &Path) -> Result<Arc<CScriptLibrary>, CScriptError> {
655 if let Some(library) = self.libraries.get(path) {
656 Ok(library.clone())
657 } else {
658 let library = Arc::new(CScriptLibrary::load(path)?);
659 self.libraries.insert(path.to_path_buf(), library.clone());
660 Ok(library)
661 }
662 }
663
664 /// Loads `path` if not already cached, then creates and returns a fresh instance from it
665 /// (its own `cscript_start()` call, its own state) using the **plain** contract: requires
666 /// `cscript_output` (via [`CScriptInstance::call`]), for a block with `xc_count == 0`.
667 pub fn instantiate(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
668 let library = self.load_cached(path)?;
669 if library.output.is_none() {
670 return Err(CScriptError::MissingSymbol {
671 path: path.to_path_buf(),
672 symbol: "cscript_output",
673 message: "not found (or this library only implements the xc-owning contract \
674 — see CScriptRegistry::instantiate_xc)"
675 .to_string(),
676 });
677 }
678 Ok(CScriptInstance::new(library))
679 }
680
681 /// Loads `path` if not already cached, then creates and returns a fresh instance from it
682 /// using the **continuous-state (`xc`)** contract: requires `cscript_derivative` and
683 /// `cscript_output_xc` (via [`CScriptInstance::rk4_step_xc`]/[`CScriptInstance::call_xc`]),
684 /// for a block with `xc_count > 0`. See the module doc comment, "The optional
685 /// continuous-state (`xc`) contract."
686 pub fn instantiate_xc(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
687 let library = self.load_cached(path)?;
688 if library.derivative.is_none() {
689 return Err(CScriptError::MissingSymbol {
690 path: path.to_path_buf(),
691 symbol: "cscript_derivative",
692 message: "required because this block declares xc_count > 0".to_string(),
693 });
694 }
695 if library.output_xc.is_none() {
696 return Err(CScriptError::MissingSymbol {
697 path: path.to_path_buf(),
698 symbol: "cscript_output_xc",
699 message: "required because this block declares xc_count > 0".to_string(),
700 });
701 }
702 Ok(CScriptInstance::new(library))
703 }
704}