rustdv-gpi 0.1.0

Safe wrapper over the simulator interface: handles, values, callbacks, sim time. All unsafe code in the rustdv workspace lives here (design-doc §3.3).
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
//! # rustdv-gpi
//!
//! Safe wrapper over the simulator programming interface (design-doc §3.3).
//! Invariants upheld here so everything above is safe Rust:
//!
//! 1. Handles are opaque and non-null; fallible acquisition is `Result`.
//! 2. Object-handle lifetime = simulation lifetime (freely `Copy`able IDs).
//!    Callback handles invalidate on removal/fire — modeled by RAII
//!    ([`CallbackHandle`]): dropping an unfired handle removes the callback.
//! 3. Strings are copied at the boundary, every call.
//! 4. No unwinding across FFI: every trampoline wraps the closure in
//!    `catch_unwind`; panics are routed to the panic sink.
//! 5. Callback user-data ownership: an `Rc` whose C-side reference is
//!    reclaimed exactly once (on fire for one-shots, on removal otherwise).
//!
//! Thread affinity (§3.4): all types here hold raw pointers and are
//! therefore `!Send`/`!Sync` — the compiler rejects moving them off the
//! simulator thread.

use std::cell::{Cell, RefCell};
use std::ffi::{CStr, CString};
use std::fmt;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::rc::Rc;

use rustdv_gpi_sys as sys;

// Test executables need vpi_* symbol definitions (the simulator provides
// them for the real cdylib) — see rustdv-vpi-stubs.
#[cfg(test)]
use rustdv_vpi_stubs as _;

pub mod value;
pub use value::{Logic, LogicArray};

// ===========================================================================
// Errors
// ===========================================================================

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HandleError {
    /// Name did not resolve (cocotb raises AttributeError here; rustdv
    /// returns this — design-doc §0.6).
    NotFound { name: String, scope: String },
    /// Handle exists but is not the requested kind.
    WrongKind { name: String, expected: &'static str, actual: String },
    NoTopModule,
}

impl fmt::Display for HandleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HandleError::NotFound { name, scope } => {
                write!(f, "no object named '{name}' in scope '{scope}'")
            }
            HandleError::WrongKind { name, expected, actual } => {
                write!(f, "'{name}' is a {actual}, expected {expected}")
            }
            HandleError::NoTopModule => write!(f, "no top-level module found"),
        }
    }
}
impl std::error::Error for HandleError {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueError {
    /// Value contains x/z bits and was asked for as an integer.
    FourState(String),
    Width { want: u32, have: usize },
}

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValueError::FourState(s) => write!(f, "value '{s}' has x/z bits"),
            ValueError::Width { want, have } => write!(f, "width mismatch: want {want}, have {have}"),
        }
    }
}
impl std::error::Error for ValueError {}

// ===========================================================================
// Handles
// ===========================================================================

/// Raw non-null simulator object handle. Valid for the whole simulation
/// (invariant 2), hence `Copy`. `!Send` because it wraps a raw pointer.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct ObjHandle(sys::vpiHandle);

impl ObjHandle {
    fn new(h: sys::vpiHandle) -> Option<Self> {
        if h.is_null() { None } else { Some(ObjHandle(h)) }
    }
    fn get(self, prop: i32) -> i32 {
        unsafe { sys::vpi_get(prop, self.0) }
    }
    fn get_str(self, prop: i32) -> String {
        // Invariant 3: copy immediately.
        unsafe {
            let p = sys::vpi_get_str(prop, self.0);
            if p.is_null() {
                String::new()
            } else {
                CStr::from_ptr(p).to_string_lossy().into_owned()
            }
        }
    }
}

/// Any simulator object, classified by type (design-doc §3.3 downcasting).
#[derive(Copy, Clone)]
pub enum AnyHandle {
    Hierarchy(HierarchyHandle),
    Logic(LogicHandle),
    Other(ObjHandle),
}

impl AnyHandle {
    pub fn classify(h: ObjHandle) -> AnyHandle {
        match h.get(sys::vpiType) {
            sys::vpiModule => AnyHandle::Hierarchy(HierarchyHandle { h }),
            sys::vpiNet | sys::vpiReg | sys::vpiIntegerVar | sys::vpiPort | sys::vpiMemory
            | sys::vpiLongIntVar | sys::vpiShortIntVar | sys::vpiIntVar | sys::vpiByteVar
            | sys::vpiEnumVar | sys::vpiBitVar => {
                AnyHandle::Logic(LogicHandle { h })
            }
            _ => AnyHandle::Other(h),
        }
    }

    pub fn as_logic(self) -> Result<LogicHandle, HandleError> {
        match self {
            AnyHandle::Logic(l) => Ok(l),
            AnyHandle::Hierarchy(h) => Err(HandleError::WrongKind {
                name: h.full_name(),
                expected: "signal",
                actual: "module".into(),
            }),
            AnyHandle::Other(o) => Err(HandleError::WrongKind {
                name: o.get_str(sys::vpiFullName),
                expected: "signal",
                actual: format!("vpiType {}", o.get(sys::vpiType)),
            }),
        }
    }

    pub fn as_hierarchy(self) -> Result<HierarchyHandle, HandleError> {
        match self {
            AnyHandle::Hierarchy(h) => Ok(h),
            AnyHandle::Logic(l) => Err(HandleError::WrongKind {
                name: l.full_name(),
                expected: "module",
                actual: "signal".into(),
            }),
            AnyHandle::Other(o) => Err(HandleError::WrongKind {
                name: o.get_str(sys::vpiFullName),
                expected: "module",
                actual: format!("vpiType {}", o.get(sys::vpiType)),
            }),
        }
    }
}

/// A module/scope handle. Port of cocotb's HierarchyObject
/// (cocotb: handle.py), with `Result`-returning lookup (mapping row 19).
#[derive(Copy, Clone)]
pub struct HierarchyHandle {
    h: ObjHandle,
}

impl HierarchyHandle {
    /// A handle to nothing, for unit tests that need a `RustdvCtx` but never
    /// touch the DUT. Any VPI call through it goes to `rustdv-vpi-stubs`,
    /// which panics — so a test that *does* touch the DUT fails loudly
    /// instead of reading garbage.
    pub fn null_for_test() -> HierarchyHandle {
        HierarchyHandle { h: ObjHandle(std::ptr::null_mut()) }
    }

    /// Dynamic child lookup: `dut.child("clk")?` (design-doc OQ-6 lean).
    pub fn child(&self, name: &str) -> Result<AnyHandle, HandleError> {
        let cname = CString::new(name).expect("NUL in signal name");
        let h = unsafe { sys::vpi_handle_by_name(cname.as_ptr(), self.h.0) };
        match ObjHandle::new(h) {
            Some(h) => Ok(AnyHandle::classify(h)),
            None => Err(HandleError::NotFound { name: name.into(), scope: self.full_name() }),
        }
    }

    /// Shorthand: child that must be a signal.
    pub fn signal(&self, name: &str) -> Result<LogicHandle, HandleError> {
        self.child(name)?.as_logic()
    }

    pub fn name(&self) -> String {
        self.h.get_str(sys::vpiName)
    }
    pub fn full_name(&self) -> String {
        self.h.get_str(sys::vpiFullName)
    }

    /// Iterate child objects (modules, nets, regs) — serves the
    /// `visit_children` debug-print role at the DUT level.
    pub fn children(&self) -> Vec<AnyHandle> {
        let mut out = Vec::new();
        for t in [sys::vpiModule, sys::vpiNet, sys::vpiReg] {
            unsafe {
                let it = sys::vpi_iterate(t, self.h.0);
                if it.is_null() {
                    continue;
                }
                loop {
                    let c = sys::vpi_scan(it);
                    if c.is_null() {
                        break; // scan returning NULL frees the iterator
                    }
                    if let Some(h) = ObjHandle::new(c) {
                        out.push(AnyHandle::classify(h));
                    }
                }
            }
        }
        out
    }
}

/// A value-bearing signal handle (net/reg/var). Port of cocotb's
/// LogicObject surface: explicit `get()`/`set()` (mapping row 20).
/// Buffered-write semantics live a layer up in rustdv-sim; the methods
/// here apply values immediately.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct LogicHandle {
    h: ObjHandle,
}

impl LogicHandle {
    pub fn name(&self) -> String {
        self.h.get_str(sys::vpiName)
    }
    pub fn full_name(&self) -> String {
        self.h.get_str(sys::vpiFullName)
    }
    pub fn size(&self) -> u32 {
        self.h.get(sys::vpiSize).max(0) as u32
    }

    /// Current value as a binary string, e.g. "0101", "xxxx".
    pub fn get_binstr(&self) -> String {
        let mut val = sys::t_vpi_value {
            format: sys::vpiBinStrVal,
            value: sys::u_vpi_value_union { integer: 0 },
        };
        unsafe {
            sys::vpi_get_value(self.h.0, &mut val);
            let p = val.value.str_;
            if p.is_null() {
                String::new()
            } else {
                CStr::from_ptr(p).to_string_lossy().into_owned()
            }
        }
    }

    /// Current value as a LogicArray (4-state).
    pub fn get(&self) -> LogicArray {
        LogicArray::from_binstr(&self.get_binstr())
    }

    /// Current value as u64; `Err` if any bit is x/z (design-doc §0.6:
    /// conversion failures are Results, not exceptions).
    pub fn get_u64(&self) -> Result<u64, ValueError> {
        let s = self.get_binstr();
        let mut v: u64 = 0;
        for c in s.chars() {
            match c {
                '0' => v <<= 1,
                '1' => v = (v << 1) | 1,
                _ => return Err(ValueError::FourState(s)),
            }
        }
        Ok(v)
    }

    fn put_binstr_flags(&self, bin: &str, flags: i32) {
        let c = CString::new(bin).expect("NUL in binstr");
        let mut val = sys::t_vpi_value {
            format: sys::vpiBinStrVal,
            value: sys::u_vpi_value_union { str_: c.as_ptr() as *mut _ },
        };
        unsafe {
            sys::vpi_put_value(self.h.0, &mut val, std::ptr::null_mut(), flags);
        }
    }

    /// Immediate (NoDelay) write of an integer value, zero-extended /
    /// truncated to the signal width. This is the "setimmediatevalue"
    /// analog; scheduled writes are layered above (design-doc §4.1(4)).
    pub fn set_u64_now(&self, v: u64) {
        let w = self.size().max(1) as usize;
        let mut s = String::with_capacity(w);
        for i in (0..w).rev() {
            s.push(if (v >> i) & 1 == 1 { '1' } else { '0' });
        }
        self.put_binstr_flags(&s, sys::vpiNoDelay);
    }

    /// Immediate write of a 4-state value.
    pub fn set_now(&self, v: &LogicArray) {
        self.put_binstr_flags(&v.to_binstr(), sys::vpiNoDelay);
    }
}

/// All top-level modules in the design.
pub fn top_modules() -> Vec<HierarchyHandle> {
    let mut out = Vec::new();
    unsafe {
        let it = sys::vpi_iterate(sys::vpiModule, std::ptr::null_mut());
        if it.is_null() {
            return out;
        }
        loop {
            let m = sys::vpi_scan(it);
            if m.is_null() {
                break;
            }
            if let Some(h) = ObjHandle::new(m) {
                out.push(HierarchyHandle { h });
            }
        }
    }
    out
}

/// The first top-level module (the DUT in single-top designs).
pub fn top_module() -> Result<HierarchyHandle, HandleError> {
    top_modules().into_iter().next().ok_or(HandleError::NoTopModule)
}

// ===========================================================================
// Time
// ===========================================================================

/// Current simulation time in simulator precision steps.
pub fn sim_time_steps() -> u64 {
    let mut t = sys::t_vpi_time { type_: sys::vpiSimTime, high: 0, low: 0, real: 0.0 };
    unsafe { sys::vpi_get_time(std::ptr::null_mut(), &mut t) };
    ((t.high as u64) << 32) | (t.low as u64)
}

/// Simulator time precision as a power of ten (e.g. -9 = 1 ns).
pub fn time_precision() -> i32 {
    thread_local! {
        static PREC: Cell<Option<i32>> = const { Cell::new(None) };
    }
    PREC.with(|p| match p.get() {
        Some(v) => v,
        None => {
            let v = unsafe { sys::vpi_get(sys::vpiTimePrecision, std::ptr::null_mut()) };
            p.set(Some(v));
            v
        }
    })
}

/// End the simulation (vpi_control(vpiFinish)).
pub fn finish() {
    unsafe {
        sys::vpi_control(sys::vpiFinish, 0i32);
    }
}

// ===========================================================================
// Panic sink (invariant 4)
// ===========================================================================

thread_local! {
    static PANIC_SINK: RefCell<Option<Box<dyn Fn(String)>>> = const { RefCell::new(None) };
}

/// Install the handler invoked when a callback closure panics (the runner
/// routes this to "fail the current test", mirroring cocotb catching
/// BaseException per task).
pub fn set_panic_sink(f: Box<dyn Fn(String)>) {
    PANIC_SINK.with(|s| *s.borrow_mut() = Some(f));
}

fn report_panic(payload: Box<dyn std::any::Any + Send>) {
    let msg = if let Some(s) = payload.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "panic (non-string payload)".to_string()
    };
    PANIC_SINK.with(|s| {
        if let Some(f) = s.borrow().as_ref() {
            f(msg.clone());
        } else {
            eprintln!("rustdv: panic in simulator callback: {msg}");
        }
    });
}

// ===========================================================================
// Callbacks (invariant 5)
// ===========================================================================

enum CbKind {
    OneShot,
    Recurring,
}

struct CbShared {
    kind: CbKind,
    /// True once the C-side Rc reference has been reclaimed (fired one-shot
    /// or removed callback). Guards against double-free.
    released: Cell<bool>,
    once: RefCell<Option<Box<dyn FnOnce()>>>,
    repeat: RefCell<Option<Box<dyn FnMut()>>>,
}

/// RAII callback registration. Dropping an unfired/live handle removes the
/// simulator callback — this is what makes drop-based task cancellation
/// (design-doc §4.6) clean up trigger registrations for free.
pub struct CallbackHandle {
    shared: Rc<CbShared>,
    raw: *const CbShared,
    vpi_h: sys::vpiHandle,
}

impl CallbackHandle {
    /// Detach: let the callback live for the rest of the simulation
    /// (recurring singletons like the phase hub).
    pub fn forget(self) {
        std::mem::forget(self);
    }
}

impl Drop for CallbackHandle {
    fn drop(&mut self) {
        if !self.shared.released.get() {
            self.shared.released.set(true);
            unsafe {
                sys::vpi_remove_cb(self.vpi_h);
                // Reclaim the C-side reference.
                drop(Rc::from_raw(self.raw));
            }
        }
    }
}

extern "C" fn trampoline(cb: *mut sys::t_cb_data) -> i32 {
    unsafe {
        let ud = (*cb).user_data as *const CbShared;
        if ud.is_null() {
            return 0;
        }
        // Hold our own reference for the duration of the call so that
        // closures dropping the CallbackHandle can't free us mid-flight.
        Rc::increment_strong_count(ud);
        let shared: Rc<CbShared> = Rc::from_raw(ud);
        match shared.kind {
            CbKind::OneShot => {
                if !shared.released.get() {
                    shared.released.set(true);
                    let f = shared.once.borrow_mut().take();
                    // Reclaim the C-side reference before running user code.
                    drop(Rc::from_raw(ud));
                    if let Some(f) = f {
                        if let Err(p) = catch_unwind(AssertUnwindSafe(f)) {
                            report_panic(p);
                        }
                    }
                }
            }
            CbKind::Recurring => {
                let mut guard = shared.repeat.borrow_mut();
                if let Some(f) = guard.as_mut() {
                    if let Err(p) = catch_unwind(AssertUnwindSafe(|| f())) {
                        report_panic(p);
                    }
                }
            }
        }
        drop(shared);
    }
    0
}

fn register(
    kind: CbKind,
    once: Option<Box<dyn FnOnce()>>,
    repeat: Option<Box<dyn FnMut()>>,
    reason: i32,
    obj: sys::vpiHandle,
    time: Option<sys::t_vpi_time>,
) -> CallbackHandle {
    let shared = Rc::new(CbShared {
        kind,
        released: Cell::new(false),
        once: RefCell::new(once),
        repeat: RefCell::new(repeat),
    });
    // C-side reference:
    let raw = Rc::into_raw(shared.clone());

    let mut t = time.unwrap_or(sys::t_vpi_time {
        type_: sys::vpiSuppressTime,
        high: 0,
        low: 0,
        real: 0.0,
    });
    // value: NULL — closures read signal values themselves; Icarus rejects
    // vpiSuppressVal on value-change callbacks ("format 10 not supported").
    let mut cb = sys::t_cb_data {
        reason,
        cb_rtn: Some(trampoline),
        obj,
        time: &mut t,
        value: std::ptr::null_mut(),
        index: 0,
        user_data: raw as *mut _,
    };
    let vpi_h = unsafe { sys::vpi_register_cb(&mut cb) };
    assert!(!vpi_h.is_null(), "vpi_register_cb failed (reason {reason})");
    CallbackHandle { shared, raw, vpi_h }
}

fn simtime(steps: u64) -> sys::t_vpi_time {
    sys::t_vpi_time {
        type_: sys::vpiSimTime,
        high: (steps >> 32) as u32,
        low: (steps & 0xFFFF_FFFF) as u32,
        real: 0.0,
    }
}

/// One-shot callback after `steps` precision units (cbAfterDelay).
pub fn register_timer(steps: u64, f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbAfterDelay, std::ptr::null_mut(), Some(simtime(steps)))
}

/// Recurring callback on any value change of `sig` (cbValueChange). The
/// closure reads the signal itself; edge filtering happens in rustdv-sim.
pub fn register_value_change(sig: LogicHandle, f: Box<dyn FnMut()>) -> CallbackHandle {
    register(
        CbKind::Recurring,
        None,
        Some(f),
        sys::cbValueChange,
        sig.h.0,
        Some(simtime(0)),
    )
}

/// One-shot callback at the next ReadWrite synch point.
pub fn register_read_write(f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbReadWriteSynch, std::ptr::null_mut(), Some(simtime(0)))
}

/// One-shot callback at the next ReadOnly synch point.
pub fn register_read_only(f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbReadOnlySynch, std::ptr::null_mut(), Some(simtime(0)))
}

/// One-shot callback at the next simulation time step.
pub fn register_next_sim_time(f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbNextSimTime, std::ptr::null_mut(), None)
}

/// One-shot callback at start of simulation (the bootstrap hook).
pub fn register_start_of_simulation(f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbStartOfSimulation, std::ptr::null_mut(), None)
}

/// One-shot callback at end of simulation.
pub fn register_end_of_simulation(f: Box<dyn FnOnce()>) -> CallbackHandle {
    register(CbKind::OneShot, Some(f), None, sys::cbEndOfSimulation, std::ptr::null_mut(), None)
}