use std::ffi::{CStr, CString};
use std::mem::ManuallyDrop;
use crate::{check_error, Error, Format, Handle, LogicVal, OneToMany, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ForeignKind {
Arch,
Func,
Proc,
Lib,
App,
}
impl From<ForeignKind> for vhpi_sys::vhpiForeignKindT {
fn from(kind: ForeignKind) -> Self {
match kind {
ForeignKind::Arch => vhpi_sys::vhpiForeignKindT_vhpiArchF,
ForeignKind::Func => vhpi_sys::vhpiForeignKindT_vhpiFuncF,
ForeignKind::Proc => vhpi_sys::vhpiForeignKindT_vhpiProcF,
ForeignKind::Lib => vhpi_sys::vhpiForeignKindT_vhpiLibF,
ForeignKind::App => vhpi_sys::vhpiForeignKindT_vhpiAppF,
}
}
}
impl TryFrom<vhpi_sys::vhpiForeignKindT> for ForeignKind {
type Error = vhpi_sys::vhpiForeignKindT;
fn try_from(raw: vhpi_sys::vhpiForeignKindT) -> Result<Self, Self::Error> {
match raw {
vhpi_sys::vhpiForeignKindT_vhpiArchF => Ok(ForeignKind::Arch),
vhpi_sys::vhpiForeignKindT_vhpiFuncF => Ok(ForeignKind::Func),
vhpi_sys::vhpiForeignKindT_vhpiProcF => Ok(ForeignKind::Proc),
vhpi_sys::vhpiForeignKindT_vhpiLibF => Ok(ForeignKind::Lib),
vhpi_sys::vhpiForeignKindT_vhpiAppF => Ok(ForeignKind::App),
other => Err(other),
}
}
}
#[repr(transparent)]
pub struct ForeignExecData(vhpi_sys::vhpiCbDataS);
impl ForeignExecData {
#[must_use]
pub fn obj(&self) -> ManuallyDrop<Handle> {
ManuallyDrop::new(Handle::from_raw(self.0.obj))
}
#[must_use]
pub fn reason(&self) -> i32 {
self.0.reason
}
#[must_use]
pub fn get_foreignf_arg(&self, index: u32, format: Format) -> Option<Value> {
let index: i32 = index.try_into().ok()?;
let handle = self.obj().handle_by_index(OneToMany::ParamDecls, index)?;
handle.get_value(format).ok()
}
#[must_use]
pub fn get_foreignf_args(&self, formats: impl AsRef<[Format]>) -> Vec<Option<Value>> {
formats
.as_ref()
.iter()
.enumerate()
.map(|(index, format)| self.get_foreignf_arg(index as u32, *format))
.collect()
}
#[must_use]
pub fn has_return_value_buffer(&self) -> bool {
!self.0.value.is_null()
}
#[must_use]
pub fn return_value_format(&self) -> Option<Format> {
let raw = self.0.value;
if raw.is_null() {
None
} else {
Some(unsafe { Format::from((*raw).format) })
}
}
#[must_use]
pub fn return_value_num_elems(&self) -> Option<i32> {
let raw = self.0.value;
if raw.is_null() {
None
} else {
Some(unsafe { (*raw).numElems })
}
}
pub fn try_put_return_value(&self, value: Value) -> Result<(), Error> {
let raw = self.0.value;
if raw.is_null() {
return Err("foreignf: simulator did not provide return-value buffer".into());
}
let raw = unsafe { &mut *raw };
let format = Format::from(raw.format);
match value {
Value::Int(v) => {
if !matches!(format, Format::Int | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for Int: got {format:?}"
)
.as_str()
.into());
}
raw.value.intg = v;
Ok(())
}
Value::LongInt(v) => {
if !matches!(format, Format::LongInt | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for LongInt: got {format:?}"
)
.as_str()
.into());
}
raw.value.longintg = v;
Ok(())
}
Value::Real(v) => {
if !matches!(format, Format::Real | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for Real: got {format:?}"
)
.as_str()
.into());
}
raw.value.real = v;
Ok(())
}
Value::Char(v) => {
if !matches!(format, Format::Char | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for Char: got {format:?}"
)
.as_str()
.into());
}
raw.value.ch = v as u8;
Ok(())
}
Value::Logic(v) => {
if !matches!(format, Format::Logic | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for Logic: got {format:?}"
)
.as_str()
.into());
}
raw.value.enumv = v.into();
Ok(())
}
Value::LogicVec(values) => {
if !matches!(format, Format::LogicVec | Format::ObjType) {
return Err(format!(
"foreignf: return-value format mismatch for LogicVec: got {format:?}"
)
.as_str()
.into());
}
if raw.numElems < 0 {
return Err("foreignf: simulator reported negative return vector length".into());
}
let expected_len = raw.numElems as usize;
if expected_len != values.len() {
return Err(format!(
"foreignf: return vector length mismatch: simulator expects {}, got {}",
expected_len,
values.len()
)
.as_str()
.into());
}
let out_ptr = unsafe { raw.value.enumvs };
if out_ptr.is_null() {
return Err(
"foreignf: simulator provided null return vector buffer pointer".into(),
);
}
let out = unsafe { std::slice::from_raw_parts_mut(out_ptr, expected_len) };
for (dst, src) in out.iter_mut().zip(values.iter()) {
*dst = <vhpi_sys::vhpiEnumT as From<LogicVal>>::from(*src);
}
Ok(())
}
other => Err(format!(
"foreignf: unsupported return-value kind for direct buffer write: {other:?}"
)
.as_str()
.into()),
}
}
}
pub type ForeignCallback = unsafe extern "C" fn(&ForeignExecData);
#[derive(Debug, Clone)]
pub struct ForeignData {
kind: ForeignKind,
library_name: CString,
model_name: CString,
elab: Option<ForeignCallback>,
exec: Option<ForeignCallback>,
}
impl ForeignData {
#[must_use]
pub fn new(kind: ForeignKind, library_name: &str, model_name: &str) -> Self {
Self {
kind,
library_name: CString::new(library_name).unwrap_or_default(),
model_name: CString::new(model_name).unwrap_or_default(),
elab: None,
exec: None,
}
}
#[must_use]
pub fn elab(mut self, f: ForeignCallback) -> Self {
self.elab = Some(f);
self
}
#[must_use]
pub fn exec(mut self, f: ForeignCallback) -> Self {
self.exec = Some(f);
self
}
}
#[derive(Debug, Clone)]
pub struct ForeignInfo {
pub kind: ForeignKind,
pub library_name: Option<String>,
pub model_name: Option<String>,
pub elab: Option<ForeignCallback>,
pub exec: Option<ForeignCallback>,
}
pub fn register_foreignf(data: &ForeignData) -> Result<Handle, Error> {
let mut raw = vhpi_sys::vhpiForeignDataT {
kind: data.kind.into(),
libraryName: data.library_name.as_ptr().cast_mut(),
modelName: data.model_name.as_ptr().cast_mut(),
elabf: unsafe {
std::mem::transmute::<
Option<unsafe extern "C" fn(&ForeignExecData)>,
Option<unsafe extern "C" fn(*const vhpi_sys::vhpiCbDataS)>,
>(data.elab)
},
execf: unsafe {
std::mem::transmute::<
Option<unsafe extern "C" fn(&ForeignExecData)>,
Option<unsafe extern "C" fn(*const vhpi_sys::vhpiCbDataS)>,
>(data.exec)
},
};
let handle = unsafe { vhpi_sys::vhpi_register_foreignf(&raw mut raw) };
if handle.is_null() {
Err(check_error().unwrap_or_else(|| "vhpi_register_foreignf failed".into()))
} else {
Ok(Handle::from_raw(handle))
}
}
pub fn get_foreignf_info(handle: &Handle) -> Result<ForeignInfo, Error> {
let mut raw: vhpi_sys::vhpiForeignDataT = unsafe { std::mem::zeroed() };
let rc = unsafe { vhpi_sys::vhpi_get_foreignf_info(handle.as_raw(), &raw mut raw) };
if rc != 0 {
return Err(check_error().unwrap_or_else(|| "vhpi_get_foreignf_info failed".into()));
}
let kind = ForeignKind::try_from(raw.kind)
.map_err(|v| Error::from(format!("unknown vhpiForeignKindT value: {v}").as_str()))?;
let library_name = unsafe {
raw.libraryName
.as_ref()
.map(|p| CStr::from_ptr(p).to_string_lossy().into_owned())
};
let model_name = unsafe {
raw.modelName
.as_ref()
.map(|p| CStr::from_ptr(p).to_string_lossy().into_owned())
};
Ok(ForeignInfo {
kind,
library_name,
model_name,
elab: unsafe {
std::mem::transmute::<
Option<unsafe extern "C" fn(*const vhpi_sys::vhpiCbDataS)>,
Option<unsafe extern "C" fn(&ForeignExecData)>,
>(raw.elabf)
},
exec: unsafe {
std::mem::transmute::<
Option<unsafe extern "C" fn(*const vhpi_sys::vhpiCbDataS)>,
Option<unsafe extern "C" fn(&ForeignExecData)>,
>(raw.execf)
},
})
}
impl Handle {
pub fn get_foreignf_info(&self) -> Result<ForeignInfo, Error> {
get_foreignf_info(self)
}
}