ripopt 0.7.1

A memory-safe interior point optimizer in Rust
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
//! AMPL imported (external) function support via the `funcadd_ASL` ABI.
//!
//! This module implements enough of AMPL's `funcadd.h` ABI to:
//!
//! 1. `dlopen` a user-supplied shared library;
//! 2. resolve the `funcadd_ASL` symbol and call it;
//! 3. receive registration callbacks of the form `Addfunc(name, rfunc, type,
//!    nargs, funcinfo, ae)` and record them;
//! 4. later call back into the registered `rfunc` with an `arglist` to obtain
//!    function values, gradients, and Hessians.
//!
//! The `AmplExports` and `Arglist` struct layouts are taken from
//! AMPL-MP/ASL `funcadd.h`; cross-checked against the ctypes mapping in
//! `pyomo.core.base.external`. Fields we don't populate are left null —
//! Pyomo does the same and it is sufficient for IDAES's Helmholtz library
//! (see issue #15).
//!
//! All unsafe FFI is contained in this module. Public surface is safe.

use std::collections::HashMap;
use std::ffi::{c_char, c_int, c_long, c_void, CStr, CString};
use std::path::Path;
use std::ptr;
use std::sync::{Arc, Mutex, OnceLock};

use libloading::{Library, Symbol};

/// Process-wide lock serialising every call that crosses the AMPL external
/// ABI. Real AMPL libraries (e.g. IDAES general_helmholtz) keep mutable
/// global state (cached parameters, tabulated lookups) and are not safe for
/// concurrent entry. Python's `pyomo.core.base.external` relies on the GIL
/// for the same guarantee.
fn ampl_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

/// FUNCADD_TYPE bits (mirrors `funcadd.h`).
pub const FUNCADD_REAL_VALUED: i32 = 0;
/// Set if the function consumes string arguments. Value is still real.
pub const FUNCADD_STRING_ARGS: i32 = 1;
/// Set if the function is allowed to have a variable number of args.
pub const FUNCADD_OUTPUT_ARGS: i32 = 2;
pub const FUNCADD_RANDOM_VALUED: i32 = 4;

/// The `arglist` struct from AMPL's `funcadd.h`. Layout must match exactly.
#[repr(C)]
pub struct Arglist {
    pub n: c_int,                        // number of args
    pub nr: c_int,                       // number of real input args
    pub at: *mut c_int,                  // argument types
    pub ra: *mut f64,                    // pure real args (IN/OUT/INOUT)
    pub sa: *mut *const c_char,          // symbolic IN args
    pub derivs: *mut f64,                // partial derivatives (if non-null)
    pub hes: *mut f64,                   // second partials (if non-null)
    pub dig: *mut c_char,                // skip-derivatives flags
    pub funcinfo: *mut c_void,           // per-function cookie (set by Addfunc)
    pub ae: *mut AmplExports,            // points back at our AmplExports
    pub f: *mut c_void,                  // AMPL-internal
    pub tva: *mut c_void,                // AMPL-internal
    pub errmsg: *mut c_char,             // error description set by the function
    pub tmi: *mut c_void,                // Tempmem cookie
    pub private: *mut c_char,
    pub nin: c_int,
    pub nout: c_int,
    pub nsin: c_int,
    pub nsout: c_int,
}

/// Pointer to a user-defined real-valued function, matching
/// `typedef real (*rfunc)(arglist*)`.
pub type Rfunc = unsafe extern "C" fn(*mut Arglist) -> f64;

/// Pointer to the `Addfunc` callback provided by the caller.
pub type AddfuncFn = unsafe extern "C" fn(
    name: *const c_char,
    f: Rfunc,
    ty: c_int,
    nargs: c_int,
    funcinfo: *mut c_void,
    ae: *mut AmplExports,
);

/// Pointer to the `RandSeedSetter` callback.
pub type RandSeedSetter = unsafe extern "C" fn(*mut c_void, std::os::raw::c_ulong);

/// Pointer to the `Addrandinit` callback.
pub type AddrandinitFn = unsafe extern "C" fn(
    ae: *mut AmplExports,
    setter: RandSeedSetter,
    v: *mut c_void,
);

/// Pointer to the `AtReset` callback.
pub type AtResetFn = unsafe extern "C" fn(
    ae: *mut AmplExports,
    f: *mut c_void,
    v: *mut c_void,
);

/// The `AmplExports` struct from AMPL's `funcadd.h`. Layout must match
/// exactly. Function pointers we don't implement are held as `*mut c_void`
/// (null) — AMPL's ABI does not require a caller to populate them unless the
/// loaded library actually invokes them.
#[repr(C)]
pub struct AmplExports {
    pub std_err: *mut c_void,
    pub addfunc: Option<AddfuncFn>,
    pub asl_date: c_long,
    pub fprintf: *mut c_void,
    pub printf: *mut c_void,
    pub sprintf: *mut c_void,
    pub vfprintf: *mut c_void,
    pub vsprintf: *mut c_void,
    pub strtod: *mut c_void,
    pub crypto: *mut c_void,
    pub asl: *mut c_char,
    pub at_exit: *mut c_void,
    pub at_reset: Option<AtResetFn>,
    pub tempmem: *mut c_void,
    pub add_table_handler: *mut c_void,
    pub private_ae: *mut c_char,
    pub qsortv: *mut c_void,

    pub std_in: *mut c_void,
    pub std_out: *mut c_void,
    pub clearerr: *mut c_void,
    pub fclose: *mut c_void,
    pub fdopen: *mut c_void,
    pub feof: *mut c_void,
    pub ferror: *mut c_void,
    pub fflush: *mut c_void,
    pub fgetc: *mut c_void,
    pub fgets: *mut c_void,
    pub fileno: *mut c_void,
    pub fopen: *mut c_void,
    pub fputc: *mut c_void,
    pub fputs: *mut c_void,
    pub fread: *mut c_void,
    pub freopen: *mut c_void,
    pub fscanf: *mut c_void,
    pub fseek: *mut c_void,
    pub ftell: *mut c_void,
    pub fwrite: *mut c_void,
    pub pclose: *mut c_void,
    pub perror: *mut c_void,
    pub popen: *mut c_void,
    pub puts: *mut c_void,
    pub rewind: *mut c_void,
    pub scanf: *mut c_void,
    pub setbuf: *mut c_void,
    pub setvbuf: *mut c_void,
    pub sscanf: *mut c_void,
    pub tempnam: *mut c_void,
    pub tmpfile: *mut c_void,
    pub tmpnam: *mut c_void,
    pub ungetc: *mut c_void,
    pub ai: *mut c_void,
    pub getenv: *mut c_void,
    pub breakfunc: *mut c_void,
    pub breakarg: *mut c_char,

    // Items available with ASLdate >= 20020501.
    pub snprintf: *mut c_void,
    pub vsnprintf: *mut c_void,

    pub addrand: *mut c_void,
    pub addrandinit: Option<AddrandinitFn>,
}

// SAFETY: AmplExports itself contains only raw pointers and integers. The
// library never reads/writes it from another thread concurrently with us
// (AMPL's model is single-threaded per problem), and we never share it
// across threads. The Send/Sync bounds only matter because we box the
// registry inside Arcs.
unsafe impl Send for AmplExports {}
unsafe impl Sync for AmplExports {}

/// A function registered by a library via `Addfunc`. Mirrors the ASL
/// `FUNCADD_TYPE` bits in `funcadd.h`.
#[derive(Debug, Clone)]
pub struct RegisteredFunc {
    pub name: String,
    pub rfunc: Rfunc,
    /// OR of FUNCADD_TYPE bits.
    pub ty: i32,
    /// Declared arg count. >=0 means exactly that many, <=-1 means "at least
    /// -(nargs+1) args".
    pub nargs: i32,
    /// Cookie set by the library; must be passed through to arglist.funcinfo.
    pub funcinfo: *mut c_void,
}

// SAFETY: funcinfo is an opaque cookie owned by the library. We never
// dereference it; we only pass it back to the library's functions, which
// expect it. No thread-safety contract is violated by sending the struct.
unsafe impl Send for RegisteredFunc {}
unsafe impl Sync for RegisteredFunc {}

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

/// A loaded external-function library plus its registered functions.
pub struct ExternalLibrary {
    /// Keep the library alive — it owns the code pages the function pointers
    /// reference. Arc so `LoadedExternals` can share it.
    _lib: Arc<Library>,
    /// The AmplExports we handed to `funcadd_ASL`. Must be kept alive (pinned
    /// in a Box) because some libraries may capture its address for later
    /// use (e.g. for `AtReset` bookkeeping).
    _ae: Box<AmplExports>,
    /// Registrations collected during `funcadd_ASL`.
    funcs: HashMap<String, RegisteredFunc>,
}

impl ExternalLibrary {
    /// Open a shared library at `path` and invoke its `funcadd_ASL` entry
    /// point, collecting all functions it registers.
    pub fn load(path: &Path) -> Result<Self, String> {
        // Serialise all ABI crossings: library init code and registration
        // may touch global state that isn't safe under concurrent entry.
        let _guard = ampl_lock().lock().unwrap_or_else(|e| e.into_inner());
        // SAFETY: libloading::Library::new is unsafe because it can run
        // arbitrary initialisers from the shared object. We trust the user's
        // AMPLFUNC path the same way AMPL/IPOPT do.
        let lib = unsafe { Library::new(path) }
            .map_err(|e| format!("failed to open '{}': {}", path.display(), e))?;

        // Resolve `funcadd_ASL`. AMPL's macro `#define funcadd funcadd_ASL`
        // means every conforming library exports this symbol.
        type FuncaddFn = unsafe extern "C" fn(*mut AmplExports);
        let funcadd: Symbol<FuncaddFn> = unsafe { lib.get(b"funcadd_ASL\0") }
            .map_err(|e| format!("no funcadd_ASL in '{}': {}", path.display(), e))?;

        // Build an AmplExports. Most fields null — the library doesn't call
        // them (same assumption Pyomo makes). Only the three hooks we can
        // realistically service are set.
        let mut ae = Box::new(AmplExports {
            std_err: ptr::null_mut(),
            addfunc: Some(trampoline_addfunc),
            // ASLdate >= 20020501 unlocks the SnprintF/VsnprintF slots.
            // Pyomo uses 20160307; mirror that.
            asl_date: 20160307,
            fprintf: ptr::null_mut(),
            printf: ptr::null_mut(),
            sprintf: ptr::null_mut(),
            vfprintf: ptr::null_mut(),
            vsprintf: ptr::null_mut(),
            strtod: ptr::null_mut(),
            crypto: ptr::null_mut(),
            asl: ptr::null_mut(),
            at_exit: ptr::null_mut(),
            at_reset: Some(trampoline_atreset),
            tempmem: ptr::null_mut(),
            add_table_handler: ptr::null_mut(),
            private_ae: ptr::null_mut(),
            qsortv: ptr::null_mut(),
            std_in: ptr::null_mut(),
            std_out: ptr::null_mut(),
            clearerr: ptr::null_mut(),
            fclose: ptr::null_mut(),
            fdopen: ptr::null_mut(),
            feof: ptr::null_mut(),
            ferror: ptr::null_mut(),
            fflush: ptr::null_mut(),
            fgetc: ptr::null_mut(),
            fgets: ptr::null_mut(),
            fileno: ptr::null_mut(),
            fopen: ptr::null_mut(),
            fputc: ptr::null_mut(),
            fputs: ptr::null_mut(),
            fread: ptr::null_mut(),
            freopen: ptr::null_mut(),
            fscanf: ptr::null_mut(),
            fseek: ptr::null_mut(),
            ftell: ptr::null_mut(),
            fwrite: ptr::null_mut(),
            pclose: ptr::null_mut(),
            perror: ptr::null_mut(),
            popen: ptr::null_mut(),
            puts: ptr::null_mut(),
            rewind: ptr::null_mut(),
            scanf: ptr::null_mut(),
            setbuf: ptr::null_mut(),
            setvbuf: ptr::null_mut(),
            sscanf: ptr::null_mut(),
            tempnam: ptr::null_mut(),
            tmpfile: ptr::null_mut(),
            tmpnam: ptr::null_mut(),
            ungetc: ptr::null_mut(),
            ai: ptr::null_mut(),
            getenv: ptr::null_mut(),
            breakfunc: ptr::null_mut(),
            breakarg: ptr::null_mut(),
            snprintf: ptr::null_mut(),
            vsnprintf: ptr::null_mut(),
            addrand: ptr::null_mut(),
            addrandinit: Some(trampoline_addrandinit),
        });

        // Drive registrations into a thread-local sink so the C trampoline
        // has somewhere to deposit them without capturing Rust state.
        REGISTRY_SINK.with(|sink| {
            let mut guard = sink.borrow_mut();
            assert!(guard.is_none(), "nested ExternalLibrary::load is not supported");
            *guard = Some(HashMap::new());
        });

        // SAFETY: funcadd is a valid C function from the loaded library; we
        // pass it a correctly-shaped AmplExports.
        unsafe { funcadd(ae.as_mut()) };

        let funcs = REGISTRY_SINK
            .with(|sink| sink.borrow_mut().take())
            .unwrap_or_default();

        Ok(ExternalLibrary {
            _lib: Arc::new(lib),
            _ae: ae,
            funcs,
        })
    }

    /// Names of all functions registered by this library.
    pub fn function_names(&self) -> impl Iterator<Item = &str> {
        self.funcs.keys().map(|s| s.as_str())
    }

    /// Look up a registered function by name.
    pub fn get(&self, name: &str) -> Option<&RegisteredFunc> {
        self.funcs.get(name)
    }

    /// Evaluate a registered function with the given positional arguments.
    ///
    /// Arguments are encoded per the AMPL `arglist` ABI: real args are stored
    /// in `ra[]`, string args in `sa[]`, and `at[i]` maps argument position
    /// `i` to either a real-slot index (`at[i] >= 0`) or a string-slot index
    /// (`at[i] < 0`, decoded as `-(at[i]+1)`).
    ///
    /// If `want_derivs` is set, a length-`nr` derivative buffer is allocated
    /// and returned on success. If `want_hes` is set, a length-`nr*(nr+1)/2`
    /// Hessian buffer is also allocated and returned. The library is told to
    /// fill both by the non-null `arglist.derivs` / `arglist.hes` pointers.
    pub fn eval(
        &self,
        name: &str,
        args: &[ExternalArg<'_>],
        want_derivs: bool,
        want_hes: bool,
    ) -> Result<EvalResult, String> {
        let rf = self
            .funcs
            .get(name)
            .ok_or_else(|| format!("no such external function '{name}'"))?;

        // Validate arity against the registered signature.
        let n = args.len() as i32;
        if rf.nargs >= 0 {
            if rf.nargs != n {
                return Err(format!(
                    "external '{name}' expects {} args, got {}",
                    rf.nargs, n
                ));
            }
        } else {
            // Negative: minimum -(nargs+1) args.
            let min_args = -(rf.nargs + 1);
            if n < min_args {
                return Err(format!(
                    "external '{name}' expects at least {min_args} args, got {n}"
                ));
            }
        }

        // Bucket args: build at[], ra[], sa[] in lockstep with their indices.
        let mut at_vec: Vec<c_int> = Vec::with_capacity(args.len());
        let mut ra_vec: Vec<f64> = Vec::new();
        let mut sa_owned: Vec<CString> = Vec::new();
        for a in args {
            match a {
                ExternalArg::Real(x) => {
                    at_vec.push(ra_vec.len() as c_int);
                    ra_vec.push(*x);
                }
                ExternalArg::Str(s) => {
                    let cs = CString::new(*s)
                        .map_err(|_| format!("external '{name}' string arg contains NUL"))?;
                    at_vec.push(-(sa_owned.len() as c_int + 1));
                    sa_owned.push(cs);
                }
            }
        }
        let nr = ra_vec.len() as c_int;
        let sa_ptrs: Vec<*const c_char> = sa_owned.iter().map(|s| s.as_ptr()).collect();

        // If the library declared FUNCADD_STRING_ARGS we let it see sa; if it
        // did not, the library shouldn't be called with strings. Surface that.
        let has_strings = !sa_owned.is_empty();
        if has_strings && (rf.ty & FUNCADD_STRING_ARGS) == 0 {
            return Err(format!(
                "external '{name}' is not declared FUNCADD_STRING_ARGS but was \
                 called with string arguments"
            ));
        }

        // Optional output buffers.
        let mut derivs_buf: Vec<f64> = if want_derivs {
            vec![0.0; nr as usize]
        } else {
            Vec::new()
        };
        let hes_len = if want_hes {
            (nr as usize) * ((nr as usize) + 1) / 2
        } else {
            0
        };
        let mut hes_buf: Vec<f64> = if want_hes { vec![0.0; hes_len] } else { Vec::new() };

        // Space for a library-set error message.
        let mut errmsg_buf: Vec<c_char> = vec![0; 1024];

        // Build the arglist. Pointers into Rust-owned buffers are valid for
        // the duration of the call since we hold those Vecs in this stack
        // frame and the callee runs synchronously.
        let mut al = Arglist {
            n,
            nr,
            at: if at_vec.is_empty() {
                ptr::null_mut()
            } else {
                at_vec.as_mut_ptr()
            },
            ra: if ra_vec.is_empty() {
                ptr::null_mut()
            } else {
                ra_vec.as_mut_ptr()
            },
            sa: if sa_ptrs.is_empty() {
                ptr::null_mut()
            } else {
                sa_ptrs.as_ptr() as *mut *const c_char
            },
            derivs: if want_derivs {
                derivs_buf.as_mut_ptr()
            } else {
                ptr::null_mut()
            },
            hes: if want_hes {
                hes_buf.as_mut_ptr()
            } else {
                ptr::null_mut()
            },
            dig: ptr::null_mut(),
            funcinfo: rf.funcinfo,
            // Some libraries read arglist.ae (e.g. to call fprintf); point at
            // the same AmplExports we handed to funcadd_ASL.
            ae: self._ae_ptr(),
            f: ptr::null_mut(),
            tva: ptr::null_mut(),
            errmsg: errmsg_buf.as_mut_ptr(),
            tmi: ptr::null_mut(),
            private: ptr::null_mut(),
            nin: 0,
            nout: 0,
            nsin: 0,
            nsout: 0,
        };

        // SAFETY: rfunc is a valid extern "C" function pointer provided by
        // the loaded library; arglist layout matches funcadd.h exactly.
        // The AMPL lock serialises concurrent entry into the library.
        let _guard = ampl_lock().lock().unwrap_or_else(|e| e.into_inner());
        let value = unsafe { (rf.rfunc)(&mut al as *mut Arglist) };
        drop(_guard);

        // If the library wrote into errmsg, surface that. AMPL convention:
        // if errmsg[0] != 0 after the call, treat as error.
        if errmsg_buf[0] != 0 {
            // SAFETY: errmsg_buf is a NUL-terminated C buffer (we allocated
            // and zeroed it); the library only writes a C string there.
            let msg = unsafe { CStr::from_ptr(errmsg_buf.as_ptr()) }
                .to_string_lossy()
                .into_owned();
            return Err(format!("external '{name}' reported: {msg}"));
        }

        Ok(EvalResult {
            value,
            derivs: if want_derivs { Some(derivs_buf) } else { None },
            hessian: if want_hes { Some(hes_buf) } else { None },
        })
    }

    // Raw mutable pointer to the owned AmplExports. Used when building an
    // arglist so the library can call back through the same table it was
    // registered with. The Box is pinned for the lifetime of self.
    fn _ae_ptr(&self) -> *mut AmplExports {
        // Cast away the const; we never mutate the AmplExports ourselves.
        (&*self._ae as *const AmplExports) as *mut AmplExports
    }
}

/// One positional argument to an external function.
#[derive(Debug, Clone, Copy)]
pub enum ExternalArg<'a> {
    Real(f64),
    Str(&'a str),
}

/// Return value from [`ExternalLibrary::eval`].
#[derive(Debug, Clone)]
pub struct EvalResult {
    /// Function value.
    pub value: f64,
    /// `df/dx_i` for each real argument, in `ra[]` order, if `want_derivs`.
    pub derivs: Option<Vec<f64>>,
    /// Packed upper-triangular Hessian in AMPL's convention,
    /// `hes[i + j*(j+1)/2]` for `0 <= i <= j < nr`, if `want_hes`.
    pub hessian: Option<Vec<f64>>,
}

// ---------------------------------------------------------------------------
// Registration trampoline.
//
// `funcadd_ASL` can call Addfunc multiple times (once per registered name).
// Rust closures can't be converted to `extern "C"` function pointers, so we
// route each call through a free function that deposits into a thread-local
// sink populated by `ExternalLibrary::load`.
// ---------------------------------------------------------------------------

thread_local! {
    static REGISTRY_SINK: std::cell::RefCell<Option<HashMap<String, RegisteredFunc>>> =
        std::cell::RefCell::new(None);
}

/// C-callable trampoline that receives Addfunc calls from the shared library.
unsafe extern "C" fn trampoline_addfunc(
    name: *const c_char,
    f: Rfunc,
    ty: c_int,
    nargs: c_int,
    funcinfo: *mut c_void,
    _ae: *mut AmplExports,
) {
    if name.is_null() {
        return;
    }
    // SAFETY: AMPL guarantees name is a NUL-terminated C string.
    let cname = unsafe { CStr::from_ptr(name) };
    let name_str = match cname.to_str() {
        Ok(s) => s.to_owned(),
        Err(_) => return, // non-UTF8 name — skip; real libs use ASCII.
    };
    REGISTRY_SINK.with(|sink| {
        if let Some(map) = sink.borrow_mut().as_mut() {
            map.insert(
                name_str.clone(),
                RegisteredFunc {
                    name: name_str,
                    rfunc: f,
                    ty: ty as i32,
                    nargs: nargs as i32,
                    funcinfo,
                },
            );
        }
    });
}

/// Stub — some libraries ask us to register an AtReset callback. Pyomo logs a
/// warning and does nothing. We do the same.
unsafe extern "C" fn trampoline_atreset(
    _ae: *mut AmplExports,
    _f: *mut c_void,
    _v: *mut c_void,
) {
    log::debug!("external library registered an AtReset callback; ignoring");
}

/// Stub — invoked by libraries that use random-valued externals. We just
/// seed with 1 (matches Pyomo's default; no randomness in KKT paths).
unsafe extern "C" fn trampoline_addrandinit(
    _ae: *mut AmplExports,
    setter: RandSeedSetter,
    v: *mut c_void,
) {
    unsafe { setter(v, 1) };
}

#[cfg(test)]
mod tests {
    use super::*;

    fn idaes_dylib() -> Option<std::path::PathBuf> {
        let home = std::env::var_os("HOME")?;
        let p = std::path::PathBuf::from(home)
            .join(".idaes/bin/general_helmholtz_external.dylib");
        if p.exists() {
            Some(p)
        } else {
            None
        }
    }

    fn idaes_functions_dylib() -> Option<std::path::PathBuf> {
        let home = std::env::var_os("HOME")?;
        let p = std::path::PathBuf::from(home).join(".idaes/bin/functions.dylib");
        if p.exists() { Some(p) } else { None }
    }

    fn idaes_params_dir() -> Option<String> {
        let home = std::env::var_os("HOME")?;
        let p = std::path::PathBuf::from(home).join(
            "Dropbox/uv/.venv/lib/python3.12/site-packages/idaes/\
             models/properties/general_helmholtz/components/parameters/",
        );
        if p.exists() {
            p.to_str().map(|s| s.to_owned())
        } else {
            None
        }
    }

    /// Opening the IDAES Helmholtz dylib (when present locally) should
    /// surface the three functions used by the issue #15 fixture.
    #[test]
    fn load_idaes_helmholtz_dylib_registers_known_functions() {
        let Some(path) = idaes_dylib() else {
            eprintln!("skipping: IDAES dylib not present");
            return;
        };

        let lib = ExternalLibrary::load(&path).expect("load should succeed");
        let names: Vec<String> = lib.function_names().map(|s| s.to_owned()).collect();

        for required in &["vf_hp", "h_liq_hp", "h_vap_hp"] {
            assert!(
                names.iter().any(|n| n == required),
                "expected {required} in registered names: {names:?}"
            );
        }
    }

    /// Evaluate vf_hp at the NL fixture's initial guess. We don't assert the
    /// exact numeric value (that's an IDAES invariant, not a ripopt one), but
    /// the return value must be finite and the call must not set errmsg.
    #[test]
    fn eval_vf_hp_at_fixture_initial_point() {
        let Some(path) = idaes_dylib() else {
            eprintln!("skipping: IDAES dylib not present");
            return;
        };
        let Some(params_dir) = idaes_params_dir() else {
            eprintln!("skipping: IDAES parameters directory not present");
            return;
        };

        let lib = ExternalLibrary::load(&path).expect("load");
        // Fixture initial guess: h = 1878.71 kJ/kg-scaled, p = 101.325 kPa
        // (the scaled values actually passed through the v3/v4 slots are
        // 1878.71 * 0.0555... and 101325 * 0.001 respectively; using raw
        // values here, the function should still return a finite number).
        let args = [
            ExternalArg::Str("h2o"),
            ExternalArg::Real(1878.71 * 0.055508472036052976),
            ExternalArg::Real(101325.0 * 0.001),
            ExternalArg::Str(&params_dir),
        ];
        let res = lib.eval("vf_hp", &args, false, false).expect("eval");
        assert!(
            res.value.is_finite(),
            "vf_hp returned non-finite value {}",
            res.value
        );
    }

    /// Same call path, but asking for first derivatives. derivs must be a
    /// length-2 buffer (nr=2) of finite values.
    #[test]
    fn eval_vf_hp_with_derivatives() {
        let Some(path) = idaes_dylib() else {
            eprintln!("skipping: IDAES dylib not present");
            return;
        };
        let Some(params_dir) = idaes_params_dir() else {
            eprintln!("skipping: IDAES parameters directory not present");
            return;
        };

        let lib = ExternalLibrary::load(&path).expect("load");
        let args = [
            ExternalArg::Str("h2o"),
            ExternalArg::Real(1878.71 * 0.055508472036052976),
            ExternalArg::Real(101325.0 * 0.001),
            ExternalArg::Str(&params_dir),
        ];
        let res = lib.eval("vf_hp", &args, true, false).expect("eval");
        let derivs = res.derivs.expect("derivs requested");
        assert_eq!(derivs.len(), 2, "nr=2 reals -> 2 derivatives");
        for (i, d) in derivs.iter().enumerate() {
            assert!(d.is_finite(), "derivs[{i}] = {d} not finite");
        }
    }

    /// Also request the packed Hessian. For nr=2 reals, that's 3 entries
    /// (H00, H01, H11) in AMPL's packed upper-triangular layout.
    #[test]
    fn eval_vf_hp_with_hessian() {
        let Some(path) = idaes_dylib() else {
            eprintln!("skipping: IDAES dylib not present");
            return;
        };
        let Some(params_dir) = idaes_params_dir() else {
            eprintln!("skipping: IDAES parameters directory not present");
            return;
        };

        let lib = ExternalLibrary::load(&path).expect("load");
        let args = [
            ExternalArg::Str("h2o"),
            ExternalArg::Real(1878.71 * 0.055508472036052976),
            ExternalArg::Real(101325.0 * 0.001),
            ExternalArg::Str(&params_dir),
        ];
        let res = lib.eval("vf_hp", &args, true, true).expect("eval");
        let hes = res.hessian.expect("hessian requested");
        assert_eq!(hes.len(), 3, "nr=2 -> packed Hessian of length 3");
        for (i, h) in hes.iter().enumerate() {
            assert!(h.is_finite(), "hes[{i}] = {h} not finite");
        }
    }

    /// cbrt from IDAES functions.dylib is type=0 (no strings), nargs=1
    /// (exact positive arity) — a code path the Helmholtz fixture never
    /// exercises. Verify value, derivative, and second derivative match
    /// the closed form at x = 8: cbrt(8) = 2, d/dx = 1/12, d2/dx2 = -1/144.
    #[test]
    fn eval_cbrt_matches_closed_form() {
        let Some(path) = idaes_functions_dylib() else {
            eprintln!("skipping: IDAES functions.dylib not present");
            return;
        };
        let lib = ExternalLibrary::load(&path).expect("load");
        let rf = lib.get("cbrt").expect("cbrt registered");
        assert_eq!(rf.ty, 0, "cbrt should be FUNCADD_REAL_VALUED (type=0)");
        assert_eq!(rf.nargs, 1, "cbrt should have exact arity 1");

        let args = [ExternalArg::Real(8.0)];
        let res = lib.eval("cbrt", &args, true, true).expect("eval");
        let derivs = res.derivs.expect("derivs requested");
        let hes = res.hessian.expect("hessian requested");
        assert_eq!(derivs.len(), 1);
        assert_eq!(hes.len(), 1, "nr=1 -> packed Hessian length 1");

        // cbrt(8) = 2
        assert!((res.value - 2.0).abs() < 1e-12, "value {}", res.value);
        // d/dx cbrt(x) = 1/(3 x^(2/3)); at x=8, that's 1/12
        assert!((derivs[0] - 1.0 / 12.0).abs() < 1e-12, "deriv {}", derivs[0]);
        // d2/dx2 cbrt(x) = -2/(9 x^(5/3)); at x=8, that's -2/288 = -1/144
        assert!((hes[0] + 1.0 / 144.0).abs() < 1e-12, "hes {}", hes[0]);
    }

    /// Exact positive arity is enforced: cbrt expects nargs=1, so calling
    /// with 0 or 2 reals must error cleanly.
    #[test]
    fn eval_cbrt_arity_mismatch_errors() {
        let Some(path) = idaes_functions_dylib() else {
            eprintln!("skipping: IDAES functions.dylib not present");
            return;
        };
        let lib = ExternalLibrary::load(&path).expect("load");
        let too_few: [ExternalArg; 0] = [];
        assert!(lib.eval("cbrt", &too_few, false, false).is_err());
        let too_many = [ExternalArg::Real(1.0), ExternalArg::Real(2.0)];
        assert!(lib.eval("cbrt", &too_many, false, false).is_err());
    }

    /// cbrt is type=0 — no string args allowed. Passing a string must be
    /// rejected by our eval, not forwarded to the library.
    #[test]
    fn eval_cbrt_rejects_string_arg() {
        let Some(path) = idaes_functions_dylib() else {
            eprintln!("skipping: IDAES functions.dylib not present");
            return;
        };
        let lib = ExternalLibrary::load(&path).expect("load");
        let args = [ExternalArg::Str("nope")];
        let err = lib
            .eval("cbrt", &args, false, false)
            .err()
            .expect("string arg to type=0 function must error");
        assert!(
            err.to_lowercase().contains("string"),
            "error should mention strings, got: {err}"
        );
    }
}