cscript-ffi 0.6.0

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

use std::collections::BTreeMap;
use std::ffi::c_void;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use libloading::{Library, Symbol};

type StartFn = unsafe extern "C" fn() -> *mut c_void;
type OutputFn = unsafe extern "C" fn(
    state: *mut c_void,
    input: *const f64,
    in_len: i32,
    dt: f64,
    output: *mut f64,
    out_len: i32,
);
type FreeFn = unsafe extern "C" fn(state: *mut c_void);
type CloneFn = unsafe extern "C" fn(state: *mut c_void) -> *mut c_void;
type DerivativeFn = unsafe extern "C" fn(
    state: *mut c_void,
    input: *const f64,
    in_len: i32,
    xc: *const f64,
    xc_len: i32,
    xc_dot: *mut f64,
    xc_dot_len: i32,
);
type OutputXcFn = unsafe extern "C" fn(
    state: *mut c_void,
    input: *const f64,
    in_len: i32,
    dt: f64,
    xc: *const f64,
    xc_len: i32,
    output: *mut f64,
    out_len: i32,
);
type UpdateFn = unsafe extern "C" fn(
    state: *mut c_void,
    input: *const f64,
    in_len: i32,
    dt: f64,
    xc: *const f64,
    xc_len: i32,
);
type NextSampleHitFn = unsafe extern "C" fn(
    state: *mut c_void,
    input: *const f64,
    in_len: i32,
    xc: *const f64,
    xc_len: i32,
) -> f64;
/// `int cscript_arity(int *in_len, int *out_len)` — optional, see the module doc comment,
/// "The optional arity declaration." Returns 0 to declare, non-zero to decline.
type ArityFn = unsafe extern "C" fn(in_len: *mut i32, out_len: *mut i32) -> i32;
type StateSizeFn = unsafe extern "C" fn(state: *const c_void) -> usize;
type StateWriteFn = unsafe extern "C" fn(state: *const c_void, out: *mut u8);
type StateReadFn = unsafe extern "C" fn(input: *const u8, len: usize) -> *mut c_void;

/// The three symbols of the checkpoint state contract, resolved together — see the module doc
/// comment, "The optional checkpoint state contract." Held as one `Option<StateIo>` on the
/// library so "partially exported" cannot be represented at all past load time.
#[derive(Clone, Copy)]
struct StateIo {
    size: StateSizeFn,
    write: StateWriteFn,
    read: StateReadFn,
}

/// What a library says about its own input and output counts.
///
/// Returned by [`CScriptInstance::declared_arity`]. A side is `None` when the library wrote a
/// negative value for it, which means "I am not declaring this one" — a block genuinely
/// variadic on one side can still pin the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeclaredArity {
    pub inputs: Option<usize>,
    pub outputs: Option<usize>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CScriptError {
    Load {
        path: PathBuf,
        message: String,
    },
    MissingSymbol {
        path: PathBuf,
        symbol: &'static str,
        message: String,
    },
    /// [`CScriptInstance::state_bytes`]/[`CScriptInstance::restore_state`] were called on an
    /// instance whose library exports none of the checkpoint state contract's three symbols —
    /// check [`CScriptInstance::supports_state_io`] first.
    StateContractNotExported {
        path: PathBuf,
    },
}

impl std::fmt::Display for CScriptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CScriptError::Load { path, message } => {
                write!(
                    f,
                    "failed to load C-script library {}: {message}",
                    path.display()
                )
            }
            CScriptError::MissingSymbol {
                path,
                symbol,
                message,
            } => write!(
                f,
                "C-script library {} is missing required symbol `{symbol}`: {message}",
                path.display()
            ),
            CScriptError::StateContractNotExported { path } => write!(
                f,
                "C-script library {} does not export the checkpoint state contract \
                 (`cscript_state_size`/`cscript_state_write`/`cscript_state_read`)",
                path.display()
            ),
        }
    }
}

impl std::error::Error for CScriptError {}

/// One loaded shared library's three FFI entry points. Kept alive for as long as any
/// [`CScriptInstance`] built from it exists (each instance holds an `Arc` to this) — the
/// `Library` must outlive every raw function pointer taken from it.
pub struct CScriptLibrary {
    // Held only to keep the mapped image alive; never read directly again after `load`.
    _library: Library,
    start: StartFn,
    // `Option`, not required at load time: which of `output` or (`derivative` + `output_xc`)
    // is actually required depends on how this library is instantiated (plain
    // `CScriptRegistry::instantiate` vs. `instantiate_xc`) — see each one's own doc comment.
    // `load` resolves whatever is present; the two `instantiate*` methods enforce the specific
    // combination they each need.
    output: Option<OutputFn>,
    derivative: Option<DerivativeFn>,
    output_xc: Option<OutputXcFn>,
    // Always optional regardless of contract (plain or xc) -- see the module doc comment,
    // "The optional discrete-state update function." Never required by either `instantiate*`
    // method.
    update: Option<UpdateFn>,
    // Always optional, but *required* when this block's netlist line declares `ts=variable` --
    // that requirement is checked by `dae-runtime`, not this crate (which has no notion of the
    // netlist at all), by calling `CScriptInstance::supports_next_sample_hit` once at
    // construction. See the module doc comment, "The optional block-controlled sample time."
    next_sample_hit: Option<NextSampleHitFn>,
    // Always optional. When present, `dae-runtime` checks it against the netlist's own
    // declared input/output counts before the first step -- this crate has no notion of a
    // netlist, so it only resolves and calls the symbol. See the module doc comment, "The
    // optional arity declaration."
    arity: Option<ArityFn>,
    free: Option<FreeFn>,
    clone_state: Option<CloneFn>,
    // The checkpoint state contract, all three or none -- see the module doc comment, "The
    // optional checkpoint state contract." A partial set is refused by `load` itself.
    state_io: Option<StateIo>,
    // Kept for error messages (`CScriptError::StateContractNotExported`).
    path: PathBuf,
}

impl CScriptLibrary {
    /// Loads `path` and resolves `cscript_start` (always required) plus every optional symbol
    /// this crate knows about (`cscript_output`, `cscript_derivative`, `cscript_output_xc`,
    /// `cscript_update`, `cscript_free`, `cscript_clone`, and the
    /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple) — see the module
    /// doc comment for what each one's absence means. Which combination is actually *required*
    /// for a given instantiation is checked separately, by
    /// [`CScriptRegistry::instantiate`]/[`CScriptRegistry::instantiate_xc`] — except the state
    /// triple, which is all-or-nothing and checked here: exporting one or two of the three is
    /// [`CScriptError::MissingSymbol`] naming the first absent one.
    pub fn load(path: &Path) -> Result<Self, CScriptError> {
        // SAFETY: dlopen-ing and resolving symbols from a user-specified path is exactly the
        // unsafety this crate exists to contain -- see the module doc comment. The caller
        // chose this path deliberately, in their own netlist.
        let library = unsafe { Library::new(path) }.map_err(|e| CScriptError::Load {
            path: path.to_path_buf(),
            message: e.to_string(),
        })?;

        let start: StartFn = unsafe {
            let symbol: Symbol<StartFn> =
                library
                    .get(b"cscript_start\0")
                    .map_err(|e| CScriptError::MissingSymbol {
                        path: path.to_path_buf(),
                        symbol: "cscript_start",
                        message: e.to_string(),
                    })?;
            *symbol
        };
        let output: Option<OutputFn> = unsafe {
            library
                .get(b"cscript_output\0")
                .ok()
                .map(|symbol: Symbol<OutputFn>| *symbol)
        };
        let derivative: Option<DerivativeFn> = unsafe {
            library
                .get(b"cscript_derivative\0")
                .ok()
                .map(|symbol: Symbol<DerivativeFn>| *symbol)
        };
        let output_xc: Option<OutputXcFn> = unsafe {
            library
                .get(b"cscript_output_xc\0")
                .ok()
                .map(|symbol: Symbol<OutputXcFn>| *symbol)
        };
        let update: Option<UpdateFn> = unsafe {
            library
                .get(b"cscript_update\0")
                .ok()
                .map(|symbol: Symbol<UpdateFn>| *symbol)
        };
        let next_sample_hit: Option<NextSampleHitFn> = unsafe {
            library
                .get(b"cscript_next_sample_hit\0")
                .ok()
                .map(|symbol: Symbol<NextSampleHitFn>| *symbol)
        };
        let arity: Option<ArityFn> = unsafe {
            library
                .get(b"cscript_arity\0")
                .ok()
                .map(|symbol: Symbol<ArityFn>| *symbol)
        };
        let free: Option<FreeFn> = unsafe {
            library
                .get(b"cscript_free\0")
                .ok()
                .map(|symbol: Symbol<FreeFn>| *symbol)
        };
        let clone_state: Option<CloneFn> = unsafe {
            library
                .get(b"cscript_clone\0")
                .ok()
                .map(|symbol: Symbol<CloneFn>| *symbol)
        };
        let state_size: Option<StateSizeFn> = unsafe {
            library
                .get(b"cscript_state_size\0")
                .ok()
                .map(|symbol: Symbol<StateSizeFn>| *symbol)
        };
        let state_write: Option<StateWriteFn> = unsafe {
            library
                .get(b"cscript_state_write\0")
                .ok()
                .map(|symbol: Symbol<StateWriteFn>| *symbol)
        };
        let state_read: Option<StateReadFn> = unsafe {
            library
                .get(b"cscript_state_read\0")
                .ok()
                .map(|symbol: Symbol<StateReadFn>| *symbol)
        };
        let state_io = match (state_size, state_write, state_read) {
            (None, None, None) => None,
            (Some(size), Some(write), Some(read)) => Some(StateIo { size, write, read }),
            (size, write, read) => {
                // A partial set: name the first missing one, so the author sees which of the
                // three to add rather than a generic "checkpointing unsupported" later on.
                let symbol = if size.is_none() {
                    "cscript_state_size"
                } else if write.is_none() {
                    "cscript_state_write"
                } else {
                    debug_assert!(read.is_none());
                    "cscript_state_read"
                };
                return Err(CScriptError::MissingSymbol {
                    path: path.to_path_buf(),
                    symbol,
                    message: "the checkpoint state contract is all-or-nothing: \
                              cscript_state_size, cscript_state_write and cscript_state_read \
                              must all be exported, or none of them"
                        .to_string(),
                });
            }
        };

        Ok(CScriptLibrary {
            _library: library,
            start,
            output,
            derivative,
            output_xc,
            update,
            next_sample_hit,
            arity,
            free,
            clone_state,
            state_io,
            path: path.to_path_buf(),
        })
    }
}

/// One block instance's own state, from one call to `cscript_start()` on a shared
/// [`CScriptLibrary`]. `Drop` calls `cscript_free` if the library exported one.
pub struct CScriptInstance {
    library: Arc<CScriptLibrary>,
    state: *mut c_void,
}

impl std::fmt::Debug for CScriptInstance {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CScriptInstance")
            .field("state", &self.state)
            .finish()
    }
}

// The state pointer is opaque to us and only ever passed back into the same library's own
// functions, which are the sole thing that dereferences it -- this crate never reads through
// it, so moving the pointer between threads is exactly as safe as moving the shared library
// handle itself. Circuit simulation in this workspace is single-threaded, so this is unused in
// practice, but the type would otherwise fail to be `Send` at all without it.
unsafe impl Send for CScriptInstance {}

impl CScriptInstance {
    fn new(library: Arc<CScriptLibrary>) -> Self {
        // SAFETY: calling into user-supplied native code with no arguments, as documented in
        // the module doc comment's C-side contract.
        let state = unsafe { (library.start)() };
        CScriptInstance { library, state }
    }

    /// Calls `cscript_output` with this instance's own state, `input` and `dt` as given, and
    /// an `out_len`-length zero-initialized output buffer, returning it filled in.
    ///
    /// # Panics
    /// If this instance's library doesn't export `cscript_output` — unreachable in practice,
    /// since [`CScriptRegistry::instantiate`] (the only way to obtain an instance meant to use
    /// this method) already requires it up front, the same "checked once, up front" discipline
    /// [`Clone`]'s own `cscript_clone` requirement uses.
    pub fn call(&mut self, input: &[f64], dt: f64, out_len: usize) -> Vec<f64> {
        let output_fn = self.library.output.unwrap_or_else(|| {
            panic!(
                "call requires a library loaded via CScriptRegistry::instantiate (which \
                 already requires cscript_output up front — this should be unreachable)"
            )
        });
        let mut output = vec![0.0_f64; out_len];
        // SAFETY: `input`/`output` are valid slices of the declared lengths for the duration
        // of this call; `in_len`/`out_len` are passed through unchanged so the callee can
        // bounds-check itself. Whether the callee actually respects them is the documented,
        // unenforceable part of the C-side contract (see module doc comment).
        unsafe {
            output_fn(
                self.state,
                input.as_ptr(),
                input.len() as i32,
                dt,
                output.as_mut_ptr(),
                out_len as i32,
            );
        }
        output
    }

    /// Calls `cscript_output_xc` with this instance's own state, `input`/`dt` as given, `xc` as
    /// this step's own already-integrated continuous-state vector, and an `out_len`-length
    /// zero-initialized output buffer, returning it filled in — the `xc`-owning counterpart to
    /// [`Self::call`]. See the module doc comment, "The optional continuous-state (`xc`)
    /// contract."
    ///
    /// # Panics
    /// If this instance's library doesn't export `cscript_output_xc` — unreachable in
    /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
    pub fn call_xc(&mut self, input: &[f64], dt: f64, xc: &[f64], out_len: usize) -> Vec<f64> {
        let output_xc = self.library.output_xc.unwrap_or_else(|| {
            panic!(
                "call_xc requires a library loaded via CScriptRegistry::instantiate_xc (which \
                 already requires cscript_output_xc up front — this should be unreachable)"
            )
        });
        let mut output = vec![0.0_f64; out_len];
        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
        unsafe {
            output_xc(
                self.state,
                input.as_ptr(),
                input.len() as i32,
                dt,
                xc.as_ptr(),
                xc.len() as i32,
                output.as_mut_ptr(),
                out_len as i32,
            );
        }
        output
    }

    /// Calls `cscript_update` with this instance's own state, `input`/`dt`/`xc` as given -- a
    /// no-op if this instance's library didn't export it (see the module doc comment, "The
    /// optional discrete-state update function"). Unlike [`Self::call`]/[`Self::call_xc`], this
    /// is genuinely optional for *both* contracts, so there's no panic path: call it every
    /// step it's due exactly like output, and it simply does nothing if the author never wrote
    /// one.
    pub fn update(&mut self, input: &[f64], dt: f64, xc: &[f64]) {
        let Some(update_fn) = self.library.update else {
            return;
        };
        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
        unsafe {
            update_fn(
                self.state,
                input.as_ptr(),
                input.len() as i32,
                dt,
                xc.as_ptr(),
                xc.len() as i32,
            );
        }
    }

    /// Whether this instance's library exported `cscript_next_sample_hit` — check this once, up
    /// front, when this block's netlist line declares `ts=variable` (see the module doc
    /// comment, "The optional block-controlled sample time") and reject the netlist with a
    /// clear error if not, before ever calling [`Self::next_sample_hit`].
    pub fn supports_next_sample_hit(&self) -> bool {
        self.library.next_sample_hit.is_some()
    }

    /// What this library declares its own arity to be, if it declares one.
    ///
    /// `None` when `cscript_arity` is absent, or present and returns non-zero — a library may
    /// decline, and declining is not an error. `Some` carries each side separately, because a
    /// negative value means "not declaring this one".
    ///
    /// This crate only asks the question. Comparing the answer against a netlist's declared
    /// port counts is `dae-runtime`'s, since nothing here knows what a netlist is.
    pub fn declared_arity(&self) -> Option<DeclaredArity> {
        let arity = self.library.arity?;
        let mut in_len: i32 = -1;
        let mut out_len: i32 = -1;
        // SAFETY: both pointers are to live locals of the right type, and the contract is that
        // the callee writes through them and returns 0, or leaves them alone and returns
        // non-zero. Either way nothing is read back unless it returned 0.
        let status = unsafe { arity(&mut in_len, &mut out_len) };
        if status != 0 {
            return None;
        }
        Some(DeclaredArity {
            inputs: usize::try_from(in_len).ok(),
            outputs: usize::try_from(out_len).ok(),
        })
    }

    /// Calls `cscript_next_sample_hit`, returning the number of seconds (relative to this call)
    /// until this block should next be executed.
    ///
    /// # Panics
    /// If this instance's library doesn't export `cscript_next_sample_hit` — unreachable in
    /// practice, since a caller is expected to check [`Self::supports_next_sample_hit`] once,
    /// up front, before ever using `ts=variable` for this block at all.
    pub fn next_sample_hit(&self, input: &[f64], xc: &[f64]) -> f64 {
        let next_sample_hit_fn = self.library.next_sample_hit.unwrap_or_else(|| {
            panic!(
                "next_sample_hit requires a library that exports cscript_next_sample_hit \
                 (required for ts=variable — this should be unreachable, since that's checked \
                 up front)"
            )
        });
        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`.
        unsafe {
            next_sample_hit_fn(
                self.state,
                input.as_ptr(),
                input.len() as i32,
                xc.as_ptr(),
                xc.len() as i32,
            )
        }
    }

    /// Evaluates `cscript_derivative` once: given this step's already-resolved inputs and a
    /// candidate continuous-state vector `xc`, returns `dxc/dt`. Takes `&self` rather than
    /// `&mut self` — the C-side contract documents (but, like every other rule in this crate,
    /// cannot enforce) that this call must not mutate `state`, so the Rust type keeps that
    /// intent honest even though the raw pointer underneath is technically mutable.
    ///
    /// # Panics
    /// If this instance's library doesn't export `cscript_derivative` — unreachable in
    /// practice, since [`CScriptRegistry::instantiate_xc`] already requires it up front.
    pub fn derivative(&self, input: &[f64], xc: &[f64]) -> Vec<f64> {
        let derivative_fn = self.library.derivative.unwrap_or_else(|| {
            panic!(
                "derivative requires a library loaded via CScriptRegistry::instantiate_xc \
                 (which already requires cscript_derivative up front — this should be \
                 unreachable)"
            )
        });
        let mut xc_dot = vec![0.0_f64; xc.len()];
        // SAFETY: same reasoning as `call`'s own SAFETY comment, extended to `xc`/`xc_dot`.
        unsafe {
            derivative_fn(
                self.state,
                input.as_ptr(),
                input.len() as i32,
                xc.as_ptr(),
                xc.len() as i32,
                xc_dot.as_mut_ptr(),
                xc_dot.len() as i32,
            );
        }
        xc_dot
    }

    /// RK4-integrates `xc` forward by `dt`, holding `input` fixed across all four stages — the
    /// same zero-order-hold convention `continuous_blocks::StateSpace::rk4_step` uses for every
    /// other dynamic block in this workspace, so a `cscript` block's own continuous state
    /// integrates exactly like a `Pid`/`StateSpace`/`Pmsm`'s does, not by some separate rule.
    /// Calls [`Self::derivative`] up to four times (`k1..k4`) — see that method's own `#Panics`.
    pub fn rk4_step_xc(&self, xc: &[f64], input: &[f64], dt: f64) -> Vec<f64> {
        let add = |a: &[f64], b: &[f64], scale: f64| -> Vec<f64> {
            a.iter().zip(b).map(|(ai, bi)| ai + scale * bi).collect()
        };
        let k1 = self.derivative(input, xc);
        let k2 = self.derivative(input, &add(xc, &k1, dt / 2.0));
        let k3 = self.derivative(input, &add(xc, &k2, dt / 2.0));
        let k4 = self.derivative(input, &add(xc, &k3, dt));
        (0..xc.len())
            .map(|i| xc[i] + (dt / 6.0) * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]))
            .collect()
    }

    /// Whether this instance's library exported `cscript_clone` — check this once, up front,
    /// before deciding whether a netlist using this block is eligible for adaptive step-size
    /// control (see the module doc comment, "Adaptive step-size control and instance cloning").
    pub fn supports_clone(&self) -> bool {
        self.library.clone_state.is_some()
    }

    /// A real, independent deep copy of this instance's state via `cscript_clone`, or `None`
    /// if the library didn't export it. Prefer this over [`Clone::clone`] wherever a missing
    /// `cscript_clone` should be handled as an ordinary error rather than a panic.
    pub fn try_clone(&self) -> Option<CScriptInstance> {
        let clone_fn = self.library.clone_state?;
        // SAFETY: `self.state` was returned by this same library's own `cscript_start` (or a
        // prior `cscript_clone`); the callee is expected to return an independent copy, per
        // the C-side contract documented in the module doc comment.
        let state = unsafe { clone_fn(self.state) };
        Some(CScriptInstance {
            library: self.library.clone(),
            state,
        })
    }

    /// Whether this instance's library exported the
    /// `cscript_state_size`/`cscript_state_write`/`cscript_state_read` triple — check this once,
    /// up front, before deciding whether a run containing this block can be checkpointed (see
    /// the module doc comment, "The optional checkpoint state contract"). A library exporting
    /// none of the three is the "no" case; a partial set never loads at all.
    pub fn supports_state_io(&self) -> bool {
        self.library.state_io.is_some()
    }

    /// This instance's opaque state, serialized by the library's own `cscript_state_write` into
    /// exactly `cscript_state_size` bytes — the save half of the checkpoint state contract.
    /// Empty for a state the library reports as zero-sized (a `NULL` state, typically).
    pub fn state_bytes(&self) -> Result<Vec<u8>, CScriptError> {
        let io = self
            .library
            .state_io
            .ok_or_else(|| CScriptError::StateContractNotExported {
                path: self.library.path.clone(),
            })?;
        // SAFETY: `self.state` came from this same library's own `cscript_start`/`cscript_clone`/
        // `cscript_state_read`; `size` is documented as read-only on it.
        let len = unsafe { (io.size)(self.state) };
        let mut bytes = vec![0_u8; len];
        if len > 0 {
            // SAFETY: `bytes` is exactly the `len` bytes the contract promises `write` room
            // for, valid for the duration of the call.
            unsafe { (io.write)(self.state, bytes.as_mut_ptr()) };
        }
        Ok(bytes)
    }

    /// Replaces this instance's state with one rebuilt by the library's own `cscript_state_read`
    /// from `bytes` (as produced by [`Self::state_bytes`], possibly in another process) — the
    /// load half of the checkpoint state contract. The previous state is released through
    /// `cscript_free` if the library exported it, exactly as on drop.
    pub fn restore_state(&mut self, bytes: &[u8]) -> Result<(), CScriptError> {
        let io = self
            .library
            .state_io
            .ok_or_else(|| CScriptError::StateContractNotExported {
                path: self.library.path.clone(),
            })?;
        // SAFETY: `bytes` is a valid slice for the duration of the call; the callee is
        // documented to return a fresh, independently owned state (or NULL for none).
        let new_state = unsafe { (io.read)(bytes.as_ptr(), bytes.len()) };
        if let Some(free) = self.library.free {
            if !self.state.is_null() {
                // SAFETY: the old `state` was returned by this same library and is released
                // exactly once, here, before the pointer is overwritten below.
                unsafe { free(self.state) };
            }
        }
        self.state = new_state;
        Ok(())
    }
}

impl Clone for CScriptInstance {
    /// # Panics
    /// If this instance's library didn't export `cscript_clone`. See the module doc comment,
    /// "Adaptive step-size control and instance cloning" — callers that need to handle this
    /// without panicking should check [`CScriptInstance::supports_clone`] first, or use
    /// [`CScriptInstance::try_clone`] directly.
    fn clone(&self) -> Self {
        self.try_clone().unwrap_or_else(|| {
            panic!(
                "cannot clone a CScriptInstance whose library does not export cscript_clone \
                 (required for general-simulator's adaptive step-size control); either export \
                 cscript_clone from this library or run with a fixed --dt"
            )
        })
    }
}

impl Drop for CScriptInstance {
    fn drop(&mut self) {
        if let Some(free) = self.library.free {
            if !self.state.is_null() {
                // SAFETY: `state` was returned by this same library's own `cscript_start`, and
                // this is the only place it is ever freed.
                unsafe { free(self.state) };
            }
        }
    }
}

/// Caches loaded libraries by path, so several block instances naming the same `lib=` file
/// share one `dlopen`'d image while each still gets its own [`CScriptInstance`] (own state
/// pointer) — see the module doc comment, "Multi-instance state."
#[derive(Default)]
pub struct CScriptRegistry {
    libraries: BTreeMap<PathBuf, Arc<CScriptLibrary>>,
}

impl CScriptRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Loads `path` if not already cached (resolving every optional symbol this crate knows
    /// about, regardless of which contract the caller ultimately needs — see
    /// [`CScriptLibrary::load`]'s own doc comment), returning the cached/loaded `Arc`.
    fn load_cached(&mut self, path: &Path) -> Result<Arc<CScriptLibrary>, CScriptError> {
        if let Some(library) = self.libraries.get(path) {
            Ok(library.clone())
        } else {
            let library = Arc::new(CScriptLibrary::load(path)?);
            self.libraries.insert(path.to_path_buf(), library.clone());
            Ok(library)
        }
    }

    /// Loads `path` if not already cached, then creates and returns a fresh instance from it
    /// (its own `cscript_start()` call, its own state) using the **plain** contract: requires
    /// `cscript_output` (via [`CScriptInstance::call`]), for a block with `xc_count == 0`.
    pub fn instantiate(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
        let library = self.load_cached(path)?;
        if library.output.is_none() {
            return Err(CScriptError::MissingSymbol {
                path: path.to_path_buf(),
                symbol: "cscript_output",
                message: "not found (or this library only implements the xc-owning contract \
                          — see CScriptRegistry::instantiate_xc)"
                    .to_string(),
            });
        }
        Ok(CScriptInstance::new(library))
    }

    /// Loads `path` if not already cached, then creates and returns a fresh instance from it
    /// using the **continuous-state (`xc`)** contract: requires `cscript_derivative` and
    /// `cscript_output_xc` (via [`CScriptInstance::rk4_step_xc`]/[`CScriptInstance::call_xc`]),
    /// for a block with `xc_count > 0`. See the module doc comment, "The optional
    /// continuous-state (`xc`) contract."
    pub fn instantiate_xc(&mut self, path: &Path) -> Result<CScriptInstance, CScriptError> {
        let library = self.load_cached(path)?;
        if library.derivative.is_none() {
            return Err(CScriptError::MissingSymbol {
                path: path.to_path_buf(),
                symbol: "cscript_derivative",
                message: "required because this block declares xc_count > 0".to_string(),
            });
        }
        if library.output_xc.is_none() {
            return Err(CScriptError::MissingSymbol {
                path: path.to_path_buf(),
                symbol: "cscript_output_xc",
                message: "required because this block declares xc_count > 0".to_string(),
            });
        }
        Ok(CScriptInstance::new(library))
    }
}