Add dpi-export: DPI-C import/export and package export

import "DPI-C" [context|pure] function/task prototypes, export "DPI-C" function/task, and export pkg::*; / pkg::item.

Coverage loop round 1, cluster 2: 661 -> 671 / 820 (80.6% -> 81.8%).
Feature README: docs/features/dpi-export/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-20 23:09:49 -07:00
1 parent f52beff48f
commit 8007a71932
8 files changed
+801 -12

No files matched your search

+10 -1
View File
@@ -347,6 +347,11 @@ Basic Verilog-2001 and the common synthesizable SystemVerilog subset:
empty literal (`q = {};`), `new[expr]`, `$`-bound indexing (`q[$]`,
`q[$-1]`) and queue method calls. See
`docs/features/dynamic-types/README.md`
- DPI: `import "DPI-C" [context|pure] [c_name =] function|task ...;` — a
function/task prototype with a linkage prefix, so the argument list breaks
like any other; `export "DPI-C" [c_name =] function|task name;`; and package
re-exports `export pkg::*;` / `export pkg::a, pkg::b;` / `export *::*;`. See
`docs/features/dpi-export/README.md`
- Named function/task call arguments (`csr_wr(.ptr(p), .value(v))`,
`.flag()`), `case (expr) inside` with `[lo:hi]` range labels, and bare
event controls (`@ev;`, `@hier.name;`)
@@ -430,7 +435,11 @@ corpus baseline this ordering comes from:
same construct inside an *instantiation's* `#( ... )` overrides or an
instance's `( ... )` connections, which unblocked the remaining 6 files.
**No corpus file is blocked on a compiler directive any more**
7. DPI, concurrent assertions (`assert property`), non-simple casts
7. ~~DPI~~ — **done**; see `docs/features/dpi-export/README.md`. DPI imports
and exports plus package re-exports unblocked 10 corpus files and moved the
parse rate from 80.6% to 81.8%; the 11th advanced to a `foreach` blocker in
the dv-statements bucket. Still open in this item: concurrent assertions
(`assert property`), non-simple casts
8. Interfaces/modports, `case ... inside`, streaming operators, specify
blocks, `let`/`checker`, sequences — rare in the corpus RTL
+38
View File
@@ -980,6 +980,7 @@ impl<'a> Fmt<'a> {
// argument group supplies the line breaks.
ItemKind::ElabTask(e) => concat(vec![self.expr(e), text(";")]),
ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))),
ItemKind::Export(e) => Self::export(e),
ItemKind::Timeunit(t) => text(format!("{t};")),
ItemKind::Typedef(t) => self.typedef(t),
ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d, align), text(";")]),
@@ -1960,8 +1961,27 @@ impl<'a> Fmt<'a> {
concat(docs)
}
/// `export "DPI-C" function f;` / `export pkg::*;` — one line either way;
/// no list here is long enough to be worth a breakable group.
fn export(e: &ExportDecl) -> Doc {
match e {
ExportDecl::Dpi(d) => {
let mut head = format!("export {} ", d.spec);
if let Some(c) = &d.c_identifier {
head.push_str(&c.text);
head.push_str(" = ");
}
text(format!("{head}{} {};", d.kw, d.name.text))
}
ExportDecl::Package(paths) => text(format!("export {};", join_paths(paths))),
}
}
fn function(&self, f: &FunctionDecl) -> Doc {
let mut header = Vec::new();
if let Some(d) = &f.dpi {
header.push(text(dpi_import_prefix(d)));
}
for q in &f.prefix {
header.push(text(format!("{q} ")));
}
@@ -2004,6 +2024,9 @@ impl<'a> Fmt<'a> {
fn task(&self, t: &TaskDecl) -> Doc {
let mut header = Vec::new();
if let Some(d) = &t.dpi {
header.push(text(dpi_import_prefix(d)));
}
for q in &t.prefix {
header.push(text(format!("{q} ")));
}
@@ -2711,6 +2734,21 @@ fn join_paths(paths: &[ImportPath]) -> String {
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
}
/// `import "DPI-C" [context|pure ][c_name = ]` — the linkage prefix a DPI
/// import writes in front of the function or task prototype it declares.
fn dpi_import_prefix(d: &DpiImport) -> String {
let mut s = format!("import {} ", d.spec);
if let Some(p) = &d.property {
s.push_str(p);
s.push(' ');
}
if let Some(c) = &d.c_identifier {
s.push_str(&c.text);
s.push_str(" = ");
}
s
}
/// Drop up to `n` leading spaces or tabs.
/// True if any line break in `text` falls inside a string literal, making
/// every byte of the following line part of that string's value rather than
@@ -0,0 +1,282 @@
# a DPI import split across lines collapses onto one when it fits
# corpus/ibex/dv/cs_registers/env/env_dpi.sv:7
package p;
import "DPI-C"
function void env_final();
endpackage
----
package p;
import "DPI-C" function void env_final();
endpackage
====
# a DPI import's argument list breaks like any other, one per line
# corpus/ibex/dv/cs_registers/reg_driver/reg_dpi.sv:8
package p;
import "DPI-C"
function void monitor_tick (
input string name,
input bit rst_n,
input bit [1:0] csr_op,
input bit [11:0] csr_addr,
input bit [31:0] csr_wdata,
input bit [31:0] csr_rdata);
endpackage
----
package p;
import "DPI-C" function void monitor_tick(
input string name,
input bit rst_n,
input bit [1:0] csr_op,
input bit [11:0] csr_addr,
input bit [31:0] csr_wdata,
input bit [31:0] csr_rdata
);
endpackage
====
# a DPI import with no port list at all, returning `chandle`
# corpus/ibex/dv/verilator/simple_system_cosim/ibex_simple_system_cosim_checker.sv:29
module m;
import "DPI-C" function chandle get_spike_cosim;
endmodule
----
module m;
import "DPI-C" function chandle get_spike_cosim;
endmodule
====
# `context` keeps its place, and packed multi-dimensional argument types survive
# corpus/ibex/vendor/lowrisc_ip/ip/prim/dv/prim_ascon/ascon_model_dpi/ascon_model_dpi_pkg.sv:8
package p;
import "DPI-C" context function void c_dpi_ascon_round(
input bit[4:0][7:0][7:0] data_i,
input bit[7:0] round_i,
output bit[4:0][7:0][7:0] data_o
);
endpackage
----
package p;
import "DPI-C" context function void c_dpi_ascon_round(
input bit [4:0][7:0][7:0] data_i,
input bit [7:0] round_i,
output bit [4:0][7:0][7:0] data_o
);
endpackage
====
# arguments without a direction keyword, and an unsized unpacked dimension
# corpus/ibex/vendor/lowrisc_ip/ip/prim/dv/prim_present/crypto_dpi_present/crypto_dpi_present_pkg.sv:12
package p;
import "DPI-C" function chandle c_dpi_present_mk(int unsigned key_size,
bit [127:0] key);
import "DPI-C" context function void c_dpi_aead_encrypt(output byte unsigned ct[],
input byte unsigned msg[]);
endpackage
----
package p;
import "DPI-C" function chandle c_dpi_present_mk(int unsigned key_size, bit [127:0] key);
import "DPI-C" context function void c_dpi_aead_encrypt(
output byte unsigned ct [],
input byte unsigned msg []
);
endpackage
====
# `longint unsigned` returns and arguments
# corpus/ibex/vendor/lowrisc_ip/ip/prim/dv/prim_prince/crypto_dpi_prince/crypto_dpi_prince_pkg.sv:14
package p;
import "DPI-C" context function longint c_dpi_prince_encrypt(
input longint unsigned data,
input int unsigned num_half_rounds
);
endpackage
----
package p;
import "DPI-C" context function longint c_dpi_prince_encrypt(
input longint unsigned data,
input int unsigned num_half_rounds
);
endpackage
====
# a `pure` DPI import, and a DPI-imported task
package p;
import "DPI-C" pure function int clog2( input int x );
import "DPI-C" context task tick(input int cycles);
endpackage
----
package p;
import "DPI-C" pure function int clog2(input int x);
import "DPI-C" context task tick(input int cycles);
endpackage
====
# the `c_identifier =` linkage-name spelling, on an import and on an export
package p;
import "DPI-C" my_c_name=function void f(input int x);
import "DPI-C" context other_name = task t();
export "DPI-C" exported_c_name = function f;
endpackage
----
package p;
import "DPI-C" my_c_name = function void f(input int x);
import "DPI-C" context other_name = task t();
export "DPI-C" exported_c_name = function f;
endpackage
====
# a DPI export next to the function it names
# corpus/ibex/examples/simple_system/rtl/ibex_simple_system.sv:369
module m;
export "DPI-C" function mhpmcounter_num;
function automatic int unsigned mhpmcounter_num();
return 0;
endfunction
endmodule
----
module m;
export "DPI-C" function mhpmcounter_num;
function automatic int unsigned mhpmcounter_num();
return 0;
endfunction
endmodule
====
# a DPI export inside a generate block, under a directive
# corpus/ibex/rtl/ibex_if_stage.sv:378
module m;
if (1) begin : g
`ifndef SYNTHESIS
export "DPI-C" function simutil_get_scramble_key;
export "DPI-C" task simutil_tick;
`endif
end
endmodule
----
module m;
if (1) begin : g
`ifndef SYNTHESIS
export "DPI-C" function simutil_get_scramble_key;
export "DPI-C" task simutil_tick;
`endif
end
endmodule
====
# a wildcard package re-export
# corpus/ibex/dv/uvm/core_ibex/common/ibex_mem_intf_agent/ibex_mem_intf_agent_pkg.sv:28
package p;
export ibex_mem_intf_pkg::* ;
endpackage
----
package p;
export ibex_mem_intf_pkg::*;
endpackage
====
# a package re-export naming individual items
# corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/csr_utils_pkg.sv:10
package p;
import dv_base_reg_pkg::*;
export dv_base_reg_pkg::csr_field_t,dv_base_reg_pkg::decode_csr_or_field;
endpackage
----
package p;
import dv_base_reg_pkg::*;
export dv_base_reg_pkg::csr_field_t, dv_base_reg_pkg::decode_csr_or_field;
endpackage
====
# `export *::*;` — the LRM's re-export-everything form (no corpus hits)
package p;
export * :: *;
endpackage
----
package p;
export *::*;
endpackage
====
# comments cling to a DPI import: leading, trailing, and inside the arg list
package p;
// what it does
import "DPI-C" function void f( // opens
input int a, // first
// about b
input int b /* before comma */,
input int c
); // done
endpackage
----
package p;
// what it does
import "DPI-C" function void f(
// opens
input int a, // first
// about b
input int b /* before comma */,
input int c
); // done
endpackage
====
# a DPI import and a DPI export inside a `verilog_format: off` fence stay byte-exact
package p;
// verilog_format: off
import "DPI-C" function void f( input int a );
export "DPI-C" function f;
export p2::*;
// verilog_format: on
import "DPI-C" function void g();
endpackage
----
package p;
// verilog_format: off
import "DPI-C" function void f( input int a );
export "DPI-C" function f;
export p2::*;
// verilog_format: on
import "DPI-C" function void g();
endpackage
====
# the header fits at exactly 100 columns and breaks at 101
package p;
import "DPI-C" context function void aaaaaaaaaaaaaaaaaaaaaaaaaa(input int bbbbbbbbb, int ccccccc);
import "DPI-C" context function void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(input int bbbbbbbbb, int ccccccc);
endpackage
----
package p;
import "DPI-C" context function void aaaaaaaaaaaaaaaaaaaaaaaaaa(input int bbbbbbbbb, int ccccccc);
import "DPI-C" context function void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(
input int bbbbbbbbb,
int ccccccc
);
endpackage
====
# an ordinary package import is untouched by the DPI spelling next to it
package p;
import q::*;
import "DPI-C" function void f();
import r::t , s::u;
endpackage
----
package p;
import q::*;
import "DPI-C" function void f();
import r::t, s::u;
endpackage
====
# DPI imports and exports inside a class body
class c;
import "DPI-C" function int c_get(input int i);
export "DPI-C" function sv_put;
function void sv_put(int v);
endfunction
endclass
----
class c;
import "DPI-C" function int c_get(input int i);
export "DPI-C" function sv_put;
function void sv_put(int v);
endfunction
endclass
====
# at compilation-unit scope, outside any package or module
import "DPI-C" function void f(input int a);
export "DPI-C" function g;
export p::*;
----
import "DPI-C" function void f(input int a);
export "DPI-C" function g;
export p::*;
====
+47 -2
View File
@@ -49,6 +49,43 @@ impl ImportPath {
}
}
/// The `import "DPI-C" [context|pure] [c_name =]` prefix that makes a function
/// or task prototype a DPI import (IEEE 1800 §35.5). A DPI import *is* a
/// prototype, so it is modelled as [`FunctionDecl`] / [`TaskDecl`] with this
/// hung off it rather than as an item kind of its own.
#[derive(Debug, Clone)]
pub struct DpiImport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The DPI import property, when written: `context` or `pure`.
pub property: Option<String>,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
}
/// An `export` item: a DPI export or a package re-export.
#[derive(Debug)]
pub enum ExportDecl {
/// `export "DPI-C" [c_name =] function|task name;` (IEEE 1800 §35.5.4).
Dpi(DpiExport),
/// `export pkg::item, pkg::*;` (IEEE 1800 §26.6). The LRM's `export *::*;`
/// is one path whose package half is `*` as well.
Package(Vec<ImportPath>),
}
/// One `export "DPI-C" ... ;` declaration.
#[derive(Debug)]
pub struct DpiExport {
/// The linkage spec string as written, quotes included: `"DPI-C"`.
pub spec: String,
/// The linkage name of the `c_name = function ...` spelling.
pub c_identifier: Option<Name>,
/// `function` or `task`.
pub kw: String,
/// The exported SystemVerilog task or function name.
pub name: Name,
}
#[derive(Debug, Clone, Default)]
pub struct Meta {
pub leading: Vec<Comment>,
@@ -163,6 +200,8 @@ pub enum ItemKind {
/// position is special.
ElabTask(Expr),
Import(Vec<ImportPath>),
/// `export "DPI-C" function f;` or `export pkg::*;`.
Export(ExportDecl),
Timeunit(String),
Typedef(Typedef),
ParamDecl(ParamDecl),
@@ -747,13 +786,17 @@ pub struct ClassExtends {
#[derive(Debug)]
pub struct FunctionDecl {
/// `Some` when this is a DPI import — `import "DPI-C" function ...;` —
/// which is a prototype with a linkage prefix.
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `function` keyword, in
/// source order: `virtual`, `local`, `protected`, `static`, `pure`,
/// `extern`. Empty outside a class body.
pub prefix: Vec<String>,
pub qualifiers: Vec<String>,
/// True for a body-less prototype — `extern function ...;` or
/// `pure virtual function ...;` — which has no `endfunction`.
/// True for a body-less prototype — `extern function ...;`,
/// `pure virtual function ...;` or a DPI import — which has no
/// `endfunction`.
pub is_prototype: bool,
/// The `my_class::` written before the name when an `extern` method is
/// *defined* outside its class body. Kept apart from `name` so
@@ -776,6 +819,8 @@ pub struct FunctionDecl {
#[derive(Debug)]
pub struct TaskDecl {
/// `Some` when this is a DPI import; see [`FunctionDecl::dpi`].
pub dpi: Option<DpiImport>,
/// Class-member qualifiers written *before* the `task` keyword; see
/// [`FunctionDecl::prefix`].
pub prefix: Vec<String>,
+217 -7
View File
@@ -1070,9 +1070,15 @@ impl<'a> Parser<'a> {
"module" | "macromodule" => self.parse_module().map(ItemKind::Module),
"package" => self.parse_package(),
"import" => {
// A string right after `import` is a DPI linkage spec, not a
// package name: `import "DPI-C" function void f();`.
if self.nth(1).kind == TokenKind::String {
return self.parse_dpi_import();
}
let paths = self.parse_import_list()?;
Ok(ItemKind::Import(paths))
}
"export" => self.parse_export().map(ItemKind::Export),
"timeunit" | "timeprecision" => {
let mut parts: Vec<String> = Vec::new();
while !self.cur().is_sym(";") && !self.at_eof() {
@@ -1242,9 +1248,25 @@ impl<'a> Parser<'a> {
fn parse_import_list(&mut self) -> PResult<Vec<ImportPath>> {
self.expect_kw("import")?;
let paths = self.parse_package_paths(false)?;
self.expect_sym(";")?;
Ok(paths)
}
/// The comma-separated `pkg::item` / `pkg::*` list of an `import` or an
/// `export`, without the leading keyword or the closing `;`.
/// `allow_star_pkg` admits `export *::*;`, whose left half is a wildcard
/// too — no `import` spells that.
fn parse_package_paths(&mut self, allow_star_pkg: bool) -> PResult<Vec<ImportPath>> {
let mut paths = Vec::new();
loop {
let pkg = self.expect_name()?;
let star = self.cur().span;
let pkg = if allow_star_pkg && self.cur().is_sym("*") {
self.bump();
Name { text: "*".to_string(), span: star }
} else {
self.expect_name()?
};
self.expect_sym("::")?;
let star = self.cur().span;
let item = if self.eat_sym("*") {
@@ -1257,10 +1279,79 @@ impl<'a> Parser<'a> {
break;
}
}
self.expect_sym(";")?;
Ok(paths)
}
// ------------------------------------------------------------------
// DPI (IEEE 1800 §35.5) and package export (§26.6)
// ------------------------------------------------------------------
/// `import "DPI-C" [context|pure] [c_name =] function|task <prototype>;`.
/// The declaration is a function/task prototype with a linkage prefix, so
/// it becomes an ordinary [`FunctionDecl`] / [`TaskDecl`] carrying that
/// prefix — every consumer that already knows about functions sees one.
fn parse_dpi_import(&mut self) -> PResult<ItemKind> {
self.expect_kw("import")?;
let spec = self.expect_dpi_spec()?;
// `context` is not a reserved word, so it is only the property when an
// `=` does not turn it into the linkage name instead.
let property = if self.cur().is_kw("pure")
|| (self.cur().kind == TokenKind::Ident
&& self.cur().text == "context"
&& !self.nth(1).is_sym("="))
{
Some(self.bump().text)
} else {
None
};
let c_identifier = self.parse_dpi_c_identifier();
let dpi = DpiImport { spec, property, c_identifier };
if self.cur().is_kw("task") {
self.parse_task_decl(Some(dpi)).map(ItemKind::Task)
} else {
self.parse_function_decl(Some(dpi)).map(ItemKind::Function)
}
}
/// `export "DPI-C" [c_name =] function|task name;` or a package re-export
/// `export pkg::item, pkg::*;`.
fn parse_export(&mut self) -> PResult<ExportDecl> {
self.expect_kw("export")?;
if self.cur().kind == TokenKind::String {
let spec = self.expect_dpi_spec()?;
let c_identifier = self.parse_dpi_c_identifier();
if !self.cur().is_kw("function") && !self.cur().is_kw("task") {
return self.error("expected `function` or `task` in a DPI export");
}
let kw = self.bump().text;
let name = self.expect_name()?;
self.expect_sym(";")?;
return Ok(ExportDecl::Dpi(DpiExport { spec, c_identifier, kw, name }));
}
let paths = self.parse_package_paths(true)?;
self.expect_sym(";")?;
Ok(ExportDecl::Package(paths))
}
fn expect_dpi_spec(&mut self) -> PResult<String> {
if self.cur().kind == TokenKind::String {
Ok(self.bump().text)
} else {
self.error("expected a DPI linkage spec string")
}
}
/// The optional `c_name =` that gives the linkage symbol a name of its own.
fn parse_dpi_c_identifier(&mut self) -> Option<Name> {
if self.cur().kind != TokenKind::Ident || !self.nth(1).is_sym("=") {
return None;
}
let span = self.cur().span;
let name = Name { text: self.bump().text, span };
self.bump();
Some(name)
}
// ------------------------------------------------------------------
// Classes
// ------------------------------------------------------------------
@@ -2453,11 +2544,15 @@ impl<'a> Parser<'a> {
// ------------------------------------------------------------------
fn parse_function(&mut self) -> PResult<FunctionDecl> {
self.parse_function_decl(None)
}
fn parse_function_decl(&mut self, dpi: Option<DpiImport>) -> PResult<FunctionDecl> {
let prefix = self.take_member_prefix();
// `extern` and `pure virtual` introduce a prototype: a header, a `;`,
// and no `endfunction`. The body is written elsewhere (or, for a pure
// virtual, nowhere at all).
let is_prototype = prefix.iter().any(|q| q == "extern" || q == "pure");
// `extern`, `pure virtual` and a DPI import all introduce a prototype:
// a header, a `;`, and no `endfunction`. The body is written elsewhere
// (in C for a DPI import, nowhere at all for a pure virtual).
let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("function")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
@@ -2490,6 +2585,7 @@ impl<'a> Parser<'a> {
};
let (end_label, end_label_span) = split_label(end);
Ok(FunctionDecl {
dpi,
prefix,
qualifiers,
is_prototype,
@@ -2507,8 +2603,12 @@ impl<'a> Parser<'a> {
}
fn parse_task(&mut self) -> PResult<TaskDecl> {
self.parse_task_decl(None)
}
fn parse_task_decl(&mut self, dpi: Option<DpiImport>) -> PResult<TaskDecl> {
let prefix = self.take_member_prefix();
let is_prototype = prefix.iter().any(|q| q == "extern" || q == "pure");
let is_prototype = dpi.is_some() || prefix.iter().any(|q| q == "extern" || q == "pure");
self.expect_kw("task")?;
let mut qualifiers = Vec::new();
while self.cur().is_kw("automatic") || self.cur().is_kw("static") {
@@ -2525,6 +2625,7 @@ impl<'a> Parser<'a> {
};
let (end_label, end_label_span) = split_label(end);
Ok(TaskDecl {
dpi,
prefix,
qualifiers,
is_prototype,
@@ -3554,6 +3655,15 @@ mod tests {
}
}
/// The message of the parse error `src` must produce.
fn parse_err(src: &str) -> String {
let toks = tokenize(src).expect("lex error");
match parse(toks, src) {
Ok(_) => panic!("expected a parse error in {src:?}"),
Err(e) => e.message,
}
}
/// Parse on a thread with a generous stack. Nesting all the way to
/// [`MAX_NESTING_DEPTH`] peaks around 4 MiB in an unoptimized build,
/// which is more than the 2 MiB a default test thread gets — the shipped
@@ -4507,6 +4617,106 @@ mod tests {
assert!(!u.is_prototype);
}
#[test]
fn a_dpi_import_is_a_function_prototype_with_a_linkage_prefix() {
let f = parse_ok(
"package p;\n import \"DPI-C\"\n function void env_final();\n \
import \"DPI-C\" context function chandle mk(int unsigned k);\n \
import \"DPI-C\" pure my_c_name = task tick(input int n);\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Function(a) = &items[0].kind else { panic!("expected a function") };
let dpi = a.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.spec, "\"DPI-C\"");
assert_eq!(dpi.property, None);
assert!(dpi.c_identifier.is_none());
assert!(a.is_prototype && a.stmts.is_empty() && a.has_parens);
assert_eq!(a.name, "env_final");
let ItemKind::Function(b) = &items[1].kind else { panic!("expected a function") };
assert_eq!(b.dpi.as_ref().and_then(|d| d.property.clone()), Some("context".to_string()));
assert_eq!(b.ret.as_ref().map(|t| t.name.clone()), Some("chandle".to_string()));
assert_eq!(b.args.len(), 1);
assert!(b.args[0].dir.is_none());
let ItemKind::Task(c) = &items[2].kind else { panic!("expected a task") };
let dpi = c.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.property, Some("pure".to_string()));
assert_eq!(dpi.c_identifier.as_ref().map(|n| n.text.clone()), Some("my_c_name".into()));
assert!(c.is_prototype);
}
#[test]
fn a_dpi_import_without_a_port_list_has_no_parens() {
let f = parse_ok("module m;\n import \"DPI-C\" function chandle get;\nendmodule\n");
let ItemKind::Module(m) = &f.items[0].kind else { panic!("expected a module") };
let ItemKind::Function(g) = &m.items[0].kind else { panic!("expected a function") };
assert!(!g.has_parens && g.args.is_empty());
assert_eq!(g.name, "get");
}
#[test]
fn context_is_a_linkage_name_when_an_equals_sign_follows_it() {
let f =
parse_ok("package p;\n import \"DPI-C\" context = function void f();\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Function(g) = &items[0].kind else { panic!("expected a function") };
let dpi = g.dpi.as_ref().expect("DPI prefix");
assert_eq!(dpi.property, None);
assert_eq!(dpi.c_identifier.as_ref().map(|n| n.text.clone()), Some("context".into()));
}
#[test]
fn exports_split_into_dpi_and_package_re_exports() {
let f = parse_ok(
"package p;\n export \"DPI-C\" function f;\n export \"DPI-C\" cn = task t;\n \
export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
);
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let kinds: Vec<String> = items
.iter()
.map(|i| match &i.kind {
ItemKind::Export(ExportDecl::Dpi(d)) => {
let c = d.c_identifier.as_ref().map(|n| n.text.as_str()).unwrap_or("-");
format!("dpi {} {} {} {}", d.spec, c, d.kw, d.name.text)
}
ItemKind::Export(ExportDecl::Package(paths)) => format!(
"pkg {}",
paths.iter().map(ImportPath::text).collect::<Vec<_>>().join(", ")
),
_ => "other".to_string(),
})
.collect();
assert_eq!(
kinds,
[
"dpi \"DPI-C\" - function f",
"dpi \"DPI-C\" cn task t",
"pkg q::*",
"pkg r::a, s::b",
"pkg *::*",
]
);
}
#[test]
fn a_plain_package_import_is_still_a_package_import() {
let f = parse_ok("package p;\n import q::*, r::t;\nendpackage\n");
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
let ItemKind::Import(paths) = &items[0].kind else { panic!("expected an import") };
assert_eq!(paths.len(), 2);
// `import *::*;` is not a thing; only `export` writes a wildcard package.
assert!(
parse_err("package p;\n import *::*;\nendpackage\n").contains("expected identifier")
);
}
#[test]
fn a_dpi_export_needs_a_function_or_task_keyword() {
let msg = parse_err("package p;\n export \"DPI-C\" f;\nendpackage\n");
assert!(msg.contains("expected `function` or `task` in a DPI export"), "{msg}");
}
#[test]
fn an_out_of_body_method_keeps_its_class_scope_apart_from_its_name() {
let f = parse_ok("function void my_class::configure(int x);\nendfunction\n");
+17
View File
@@ -75,6 +75,8 @@ const SOURCES: &[&str] = &[
// named call arguments, `case ... inside`, a bare event control.
"class c;\n string q[$] = {};\n rand int offset[];\n logic hits[*];\n string lut[string];\n item_t #(A, B) rq[NumInp-1:0][$:8];\n function void f(string ops[$], output int outs[]);\n q[$].label = ops[$-1];\n offset = new[n];\n endfunction\nendclass\n",
"module m;\n typedef bit [3:0] q_t[$];\n task t;\n csr_wr(.ptr(ral.ovrd), .value({a, b}), .flag());\n @hier.tick;\n case (x) inside\n [A:B], C: y = 1;\n default: y = 0;\n endcase\n endtask\nendmodule\n",
// DPI imports and exports, plus package re-exports.
"package p;\n import \"DPI-C\"\n function void env_final();\n import \"DPI-C\" context function chandle mk(int unsigned k, bit [7:0] v);\n import \"DPI-C\" function chandle get;\n import \"DPI-C\" pure c_name = task tick(input int n);\n export \"DPI-C\" function f;\n export \"DPI-C\" ex_name = task t;\n export q::*;\n export r::a, s::b;\n export *::*;\nendpackage\n",
];
/// A token or a comment, in source order.
@@ -374,6 +376,12 @@ fn check_names(src: &str, what: &str, names: &[Name], parent: TextRange) {
}
}
fn check_dpi_import(src: &str, dpi: Option<&DpiImport>, parent: TextRange) {
if let Some(c) = dpi.and_then(|d| d.c_identifier.as_ref()) {
check_name(src, "DPI import linkage name", &c.text, c.span, parent);
}
}
fn check_import_paths(src: &str, paths: &[ImportPath], parent: TextRange) {
for p in paths {
check_name(src, "import package", &p.pkg.text, p.pkg.span, parent);
@@ -590,6 +598,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
ItemKind::Verbatim(_) => {}
ItemKind::Function(f) => {
check_name(src, "function name", &f.name, f.name_span, here);
check_dpi_import(src, f.dpi.as_ref(), here);
check_opt_name(src, "endfunction label", f.end_label.as_ref(), f.end_label_span, here);
for a in &f.args {
assert_inside(src, "argument", a.span, here);
@@ -601,6 +610,7 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
}
ItemKind::Task(t) => {
check_name(src, "task name", &t.name, t.name_span, here);
check_dpi_import(src, t.dpi.as_ref(), here);
check_opt_name(src, "endtask label", t.end_label.as_ref(), t.end_label_span, here);
for a in &t.args {
assert_inside(src, "argument", a.span, here);
@@ -617,6 +627,13 @@ fn check_item(src: &str, item: &Item, parent: TextRange) {
}
}
ItemKind::Import(paths) => check_import_paths(src, paths, here),
ItemKind::Export(ExportDecl::Package(paths)) => check_import_paths(src, paths, here),
ItemKind::Export(ExportDecl::Dpi(d)) => {
check_name(src, "DPI export name", &d.name.text, d.name.span, here);
if let Some(c) = &d.c_identifier {
check_name(src, "DPI export linkage name", &c.text, c.span, here);
}
}
ItemKind::Genvar(names) => check_names(src, "genvar name", names, here),
ItemKind::Timeunit(_) => {}
// Leaves; only error-tolerant parsing produces the last one, which
+8 -2
View File
@@ -284,8 +284,14 @@ impl<'a> Binder<'a> {
// Opaque leaves: verbatim text this crate makes no claims about.
// `Verbatim` is a constraint or covergroup body — no symbol is
// bound for its name and nothing inside it is scanned, the same
// contract macro invocations have.
ItemKind::Directive(_)
// contract macro invocations have. `Export` is a leaf too: a DPI
// export names a function declared elsewhere in the same scope,
// and a package re-export does not bring the name into this scope
// (an `import` alongside it does that). Resolving either one is a
// vlog_semantic decision, not the parser's — see
// `docs/features/dpi-export/README.md` Handshakes.
ItemKind::Export(_)
| ItemKind::Directive(_)
| ItemKind::MacroItem(_)
| ItemKind::Timeunit(_)
| ItemKind::Error(_)
+182
View File
@@ -0,0 +1,182 @@
# dpi-export
## Goal
Parse and format the three constructs the `dpi-export` corpus bucket is made
of: DPI **imports** (`import "DPI-C" [context|pure] [c_name =] function|task
...;`, IEEE 1800 §35.5.1–2), DPI **exports** (`export "DPI-C" [c_name =]
function|task name;`, §35.5.4) and package **re-exports** (`export pkg::*;`,
§26.6). All three are one-line declarations that a real design writes at
package, module, generate-block or class scope; before this change every one
of them was a hard parse error, so 11 corpus files produced no output at all.
A DPI import is grammatically a function/task *prototype* with a linkage
prefix, so it is modelled as one — which means the argument list breaks with
the same rules as any other function header, and every consumer that already
understands `ItemKind::Function` sees a DPI-imported function without being
taught anything new.
## Assumptions
- **`import` followed by a string literal is always a DPI import.** No package
is named by a string, so the one-token lookahead in `parse_keyword_item` is
unambiguous. Any linkage spec string is accepted, not just `"DPI-C"` —
`"DPI-SV"` is legal and the LRM lets an implementation define others; the
string is stored and reprinted verbatim, never interpreted.
- **`context` is not promoted to a keyword.** It is a plain identifier
everywhere else, and adding it to the keyword table would break any signal or
port named `context`. It is recognised positionally, and only when an `=`
does *not* follow it — `import "DPI-C" context = function void f();` is a
linkage name spelled `context`, not the property. `pure` already is a
keyword (it is in `MEMBER_QUALIFIERS`), so the property check tests both
spellings.
- **`export` was already a keyword** (`token.rs`'s `is_keyword`), so nothing in
the lexer changed and no file's tokenization moved. Grepping the 820-file
corpus for a bare `export` used as an identifier found none: every hit is a
*suffix* of a longer name (`analysis_export`, `seq_item_export`), which lexes
as one identifier and is unaffected.
- **DPI arguments always carry a name.** The LRM allows an unnamed formal
(`function void f(input int);`); `parse_tf_ports` requires a name and this
work did not change that, so the unnamed form is still a parse error. Zero
corpus files write it. Fixing it is a `parse_tf_ports` change that would
affect ordinary functions too, which is outside this feature's scope.
- **Import and export lists are printed on one line.** `ItemKind::Import`
already does this, and no corpus `export` list is long enough for a breakable
group to earn its keep. A DPI import's *argument* list is a normal breakable
group, because those do get long.
- **A DPI import declares a prototype**, so `is_prototype` is true and there is
no `endfunction`/`endtask` — the same shape `extern` and `pure virtual`
already produced.
## Handshakes
**Consumed**
- `Parser::parse_function_decl` / `parse_task_decl` (renamed from
`parse_function` / `parse_task`, which now delegate) — the DPI import path
reuses ANSI argument parsing, the return-type sniffing and the prototype
handling wholesale.
- `Parser::parse_package_paths` — factored out of `parse_import_list` so
`export` can share the `pkg::item` / `pkg::*` loop. `import` calls it with
`allow_star_pkg: false`; only `export` admits `*::*`.
- `Fmt::tf_args` and `Fmt::delimited` for the argument group.
**Promised**
- `FunctionDecl` and `TaskDecl` gained `dpi: Option<DpiImport>`. Both are
constructed only in `parser.rs`, so nothing outside had to change; a consumer
that ignores the field keeps its old behavior exactly. `is_prototype` is now
true for DPI imports as well as `extern`/`pure virtual` — its documented
meaning ("body-less, no `end*` keyword") is unchanged.
- `ItemKind::Export(ExportDecl)` is a new variant. Exhaustive matches over
`ItemKind` live in `vlog_semantic/src/bind.rs` (one arm added, see below) and
`vlog_parser/tests/spans.rs` (arms added). `vlog_linter/src/visit.rs` has a
`_ => {}` fallback and needed no change.
**Requests to other modules** (not done here, deliberately)
- **vlog_semantic**: `ItemKind::Export` is bound as an opaque leaf. Two things
a `bind.rs` owner may want later: (a) a package re-export's `pkg::item`
halves are real references and would resolve for go-to-definition with the
same `bind_import_path` an `import` uses — but a re-export does *not* bring
the name into the exporting scope, so reusing `bind_import_path` as-is would
also push a scope import, which is a semantics change I did not want to make
unasked; (b) a DPI export's `name` refers to a function declared elsewhere in
the same scope and could be a `use_name`. Note the `*::*` form has `"*"` as
its **package** name, which no existing code expects.
- **vlog_semantic / vlog_linter**: DPI-imported functions and tasks now arrive
as ordinary `ItemKind::Function` / `ItemKind::Task` with `stmts` empty and
`is_prototype` set, so `bind_function` already declares them as symbols — a
DPI-imported function is a known name for go-to-definition with no further
work. If a rule ever wants to treat them differently, `decl.dpi.is_some()`
is the test.
- **dv-statements owner**: `corpus/ibex/vendor/lowrisc_ip/dv/sv/csr_utils/
csr_utils_pkg.sv` was in this bucket; its `export` at line 10 now parses and
the file advanced to `foreach (paths[0].slices[i])` at line 290 — a `foreach`
loop-variable list with an indexed expression, which is a dv-statements
blocker, not mine.
## Status / TODO
- [x] `import "DPI-C" function <ret> <name> (<ansi args>);`, including the
form split across lines (env_dpi.sv:7) and the no-parens form
(ibex_simple_system_cosim_checker.sv:29)
- [x] `context` and `pure` properties (ascon_model_dpi_pkg.sv:8,
crypto_dpi_prince_pkg.sv:14)
- [x] `chandle` and `longint unsigned` return types; arguments with no
direction keyword; packed multi-dimensional and unsized-unpacked
argument types (crypto_dpi_present_pkg.sv:12, ascon_model_dpi_pkg.sv:15)
- [x] DPI-imported `task`
- [x] `c_identifier =` linkage names on both import and export (zero corpus
hits; same grammar, so supported and tested)
- [x] `export "DPI-C" function|task name;` at module scope and inside a
generate block under an `` `ifdef`` (ibex_simple_system.sv:369,
ibex_if_stage.sv:378)
- [x] `export pkg::*;` and `export pkg::a, pkg::b;`
(ibex_mem_intf_agent_pkg.sv:28, csr_utils_pkg.sv:10)
- [x] `export *::*;` (LRM form, zero corpus hits)
- [x] Case table `crates/vlog_formatter/tests/cases/dpi_export.cases` (19
cases: one per corpus shape, plus comments, a `verilog_format: off`
fence, the 100/101-column boundary, a class body, compilation-unit
scope, and an ordinary package `import` next to a DPI one)
- [x] Parser unit tests and a `tests/spans.rs` source covering every shape
- [ ] Unnamed DPI formals (`function void f(input int);`) — see Assumptions;
needs a `parse_tf_ports` change that touches ordinary functions
## Work log
**2026-08-20** — Implemented the whole bucket.
- Baseline: `{"passing":661,"total":820,"pct":80.6,"failures_by_category":
{"interface":31,"bind":28,"dv-statements":25,"expressions":19,
"directive-split":14,"assertions":13,"dpi-export":11,"types-decls":11,
"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`
- After: `{"passing":671,"total":820,"pct":81.8,"failures_by_category":
{"interface":31,"bind":28,"dv-statements":26,"expressions":19,
"directive-split":14,"assertions":13,"types-decls":11,
"invalid-or-fragment":3,"lex-macro-number":2,"not-verilog":1,"other":1}}`
— `dpi-export` is gone; the passing set is a strict superset of the
baseline's (checked with `comm` on the two TSVs: zero regressions, ten new
passes). `dv-statements` 25 → 26 is csr_utils_pkg.sv arriving from this
bucket at its next blocker, described in Handshakes.
**Key decision — modelling.** Two shapes were possible for a DPI import: a new
`ItemKind::DpiImport` node, or a `FunctionDecl`/`TaskDecl` with a linkage
field. I chose the field. A new item kind would have forced arms in every
exhaustive `ItemKind` match, and — worse — would have hidden DPI-imported
functions from `bind_function`, `visit.rs`'s function walk and every rule that
looks for functions, so a DPI-imported function would not be a symbol. The
field costs one `Option` on two structs, both built in one file, and makes the
formatter's job a two-line prefix. Export is genuinely a different construct
(it declares nothing and has no arguments), so it is a new `ItemKind`.
**Key decision — one `ExportDecl` enum, not two item kinds.** `export` reads
its next token to decide: a string literal is DPI, anything else starts a
package path list. Keeping both under one variant keeps the new-arm cost at one
per exhaustive match.
**Lexer.** Untouched. `export` was already a keyword; `context` deliberately is
not (see Assumptions). `chandle` was already a type keyword, so
`function chandle get;` needed nothing special — the ordinary return-type path
handles it.
**Formatting decisions.** The linkage prefix is emitted as flat text in front
of the existing function/task header (`Fmt::dpi_import_prefix`), so a DPI
import lays out exactly like the prototype it is: header on one line, argument
list a breakable group that goes one-per-line when it does not fit. The
multi-line `import "DPI-C"` / `function ...` spelling the ibex DV files use
collapses onto one line, which is what every other multi-line header in vfmt
does. Exports print flat.
**Safety net.** `verify.rs` was not touched and did not need to be: every one
of these constructs is printed by re-emitting exactly the tokens the source
wrote (the linkage string verbatim, the property, the linkage name, the
keyword, the names, the paths), so the equivalence check passes on token
identity, not on forgiveness. No new normalization, so no masked-corruption
attack tests are owed under CLAUDE.md invariant 4.
**Checks.** `cargo fmt --all` clean, `cargo clippy --all-targets` clean,
`cargo test` green (509 formatter cases, spans, verification, linter, server).
## QA log
## Review