//! `interface`, `modport` and `clocking` as declarations and references: the //! kind an interface gets, the members another file may reach through a //! `virtual` handle, and the two constructs that only live inside an interface. //! The rules live in `docs/features/interface-semantics/README.md`. use std::path::{Path, PathBuf}; use vlog_parser::parse_source; use vlog_semantic::{ analyze, resolve_external, Def, ExternalTarget, FileFacts, Resolution, Semantics, Symbol, SymbolKind, WorkspaceIndex, }; // ---------------------------------------------------------------------- // helpers // ---------------------------------------------------------------------- fn sem(src: &str) -> Semantics { let file = parse_source(src).expect("fixture must parse"); analyze(&file, src) } fn index(files: &[(&str, &str)]) -> WorkspaceIndex { WorkspaceIndex::build(files.iter().map(|(name, src)| (PathBuf::from(name), *src))) } /// Offset of the `n`th (0-based) occurrence of `needle`. fn nth(src: &str, needle: &str, n: usize) -> u32 { src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32 } /// Offset of the first occurrence of `needle`. fn at(src: &str, needle: &str) -> u32 { nth(src, needle, 0) } /// Offset of the name written just after `prefix` — the way a cursor lands on /// the second half of `bus_if.mp` or on the tail of `vif.sig`. fn after(src: &str, prefix: &str) -> u32 { at(src, prefix) + prefix.len() as u32 } /// The resolution of the reference written at `offset`, or `None` when this /// crate recorded no reference there at all. fn resolution(s: &Semantics, offset: u32) -> Option { s.reference_at(offset).map(|r| r.resolution.clone()) } /// The declaration the in-file layer says the use at `offset` names. fn resolved(s: &Semantics, offset: u32) -> &Symbol { let id = s .reference_at(offset) .unwrap_or_else(|| panic!("no reference at {offset}")) .resolved() .unwrap_or_else(|| panic!("the reference at {offset} resolves to nothing")); s.symbol(id).expect("a resolved id names a symbol") } fn symbol<'a>(s: &'a Semantics, name: &str) -> &'a Symbol { s.symbols() .iter() .find(|sym| sym.name == name) .unwrap_or_else(|| panic!("no symbol named {name}")) } /// The workspace's answer for the use at `offset` in `src`. fn overlay_def(ws: &WorkspaceIndex, src: &str, offset: u32) -> Option { let s = sem(src); let id = s.reference_id_at(offset)?; resolve_external(&s, ws).get(id).and_then(ExternalTarget::best).cloned() } /// The text a workspace definition points at, read back out of the sources it /// was built from. fn slice<'a>(ws: &WorkspaceIndex, files: &[(&'a str, &'a str)], def: &Def) -> &'a str { let path = ws.path(def.file).expect("an indexed def names a file"); let src = files .iter() .find(|(name, _)| Path::new(name) == path) .expect("the file is one of the sources") .1; &src[def.name_span.as_range()] } // ---------------------------------------------------------------------- // the interface itself // ---------------------------------------------------------------------- #[test] fn an_interface_is_its_own_kind_and_a_program_is_not() { let src = "interface bus_if;\nendinterface\nmodule m;\nendmodule\nprogram p;\nendprogram\n"; let s = sem(src); assert_eq!(symbol(&s, "bus_if").kind, SymbolKind::Interface); assert_eq!(symbol(&s, "m").kind, SymbolKind::Module); assert_eq!( symbol(&s, "p").kind, SymbolKind::Module, "a program is a module body with another closing keyword; it gets no export rule of its own this round" ); } #[test] fn an_interface_instantiation_resolves_in_file_and_across_files() { let together = "interface bus_if;\nendinterface\nmodule top;\n bus_if u_bus ();\nendmodule\n"; let s = sem(together); assert_eq!(resolved(&s, at(together, "bus_if u_bus")).kind, SymbolKind::Interface); let sources = [ ("bus_if.sv", "interface bus_if;\nendinterface\n"), ("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"), ]; let ws = index(&sources); let use_at = at(sources[1].1, "bus_if u_bus"); assert_eq!( resolution(&sem(sources[1].1), use_at), Some(Resolution::ExternalCandidate { paths: vec!["bus_if".to_string()] }) ); let def = overlay_def(&ws, sources[1].1, use_at).expect("the unit table answers"); assert_eq!(def.kind, SymbolKind::Interface); assert_eq!(slice(&ws, &sources, &def), "bus_if"); } #[test] fn a_connection_into_an_interface_instance_names_its_port() { let src = "interface bus_if (input logic clk);\nendinterface\nmodule top;\n logic c;\n bus_if u_bus (.clk(c));\nendmodule\n"; let s = sem(src); let port = resolved(&s, after(src, "(.")); assert_eq!(port.name, "clk"); assert_eq!(port.kind, SymbolKind::Port); } #[test] fn interfaces_stay_instantiable_units_beside_modules() { let sources = [ ("bus_if.sv", "interface bus_if;\nendinterface\n"), ("top.sv", "module top;\n bus_if u_bus ();\nendmodule\n"), ]; let ws = index(&sources); let units: Vec<(&str, SymbolKind)> = ws.instantiable_units().map(|(name, def)| (name, def.kind)).collect(); assert_eq!(units, [("bus_if", SymbolKind::Interface), ("top", SymbolKind::Module)]); // The instantiation census is unchanged: an interface instance is an edge. assert_eq!(ws.instantiations_of("bus_if").len(), 1); let counts = ws.counts(); assert_eq!(counts.modules, 1, "an interface is not counted as a module"); assert_eq!(counts.interfaces, 1); } // ---------------------------------------------------------------------- // modports // ---------------------------------------------------------------------- const IFACE: &str = "interface bus_if;\n logic a;\n logic b;\n logic c;\n task drive ();\n endtask\n clocking cb @(posedge a);\n input b;\n endclocking\n modport mp (input a, output b, inout c, import drive, clocking cb);\nendinterface\n"; #[test] fn a_modport_is_a_symbol_spanning_its_own_declaration() { let s = sem(IFACE); let mp = symbol(&s, "mp"); assert_eq!(mp.kind, SymbolKind::Modport); assert_eq!(&IFACE[mp.name_span.as_range()], "mp"); assert_eq!( &IFACE[mp.decl_span.as_range()], "mp (input a, output b, inout c, import drive, clocking cb)", "the declaration span is this modport's own, not the whole `modport ...;` statement" ); } #[test] fn every_name_in_a_modport_port_list_is_a_reference_to_the_interfaces_own() { let s = sem(IFACE); for (prefix, name, kind) in [ ("modport mp (input ", "a", SymbolKind::Var), ("output ", "b", SymbolKind::Var), ("inout ", "c", SymbolKind::Var), ("import ", "drive", SymbolKind::Task), (", clocking ", "cb", SymbolKind::Clocking), ] { let target = resolved(&s, after(IFACE, prefix)); assert_eq!(target.name, name, "{prefix}"); assert_eq!(target.kind, kind, "{prefix}"); } } #[test] fn a_modport_method_prototype_names_the_interfaces_own_subroutine() { // IEEE 1800 §25.5.4. The prototype restates the header of a task the // interface declares, so hovering its name must land on that task — the // same answer the `import drive` spelling gives. let src = "interface bus_if;\n task drive(input int x);\n endtask\n function int peek();\n endfunction\n modport mp (import task drive(input int x), export function int peek());\nendinterface\n"; let s = sem(src); let drive = resolved(&s, after(src, "import task ")); assert_eq!(drive.name, "drive"); assert_eq!(drive.kind, SymbolKind::Task); assert_eq!(&src[drive.name_span.as_range()], "drive"); let peek = resolved(&s, after(src, "export function int ")); assert_eq!(peek.name, "peek"); assert_eq!(peek.kind, SymbolKind::Function); } #[test] fn a_modport_prototypes_formals_are_bound_but_do_not_leak() { // The formals are a restatement of the subroutine's own, so they belong // to a scope of the prototype's — declared (nothing goes unbound) but // invisible to the interface around it. let src = "interface bus_if;\n task drive(input int x);\n endtask\n modport mp (import task drive(input int a_formal));\nendinterface\n"; let s = sem(src); let owners: Vec<_> = s.symbols().iter().filter(|sym| sym.name == "a_formal").map(|sym| sym.kind).collect(); assert_eq!(owners, [SymbolKind::TfArg], "the formal is declared exactly once"); let iface = symbol(&s, "bus_if"); let body = iface.child_scope.and_then(|id| s.scope(id)).expect("the interface opens a scope"); assert_eq!(body.lookup_local("a_formal"), None, "the formal is not a member of the interface"); let formal = symbol(&s, "a_formal"); assert_ne!( Some(formal.scope), iface.child_scope, "the formal lives in a scope of the prototype's own" ); } #[test] fn a_modport_name_that_names_nothing_records_nothing() { // IEEE 1800 §25.5: a modport port names a member of *this* interface. A // name the interface does not declare must not be walked outward onto the // file-scope `other_if` that happens to share it — a wrong answer where // recording nothing is merely a missing one. let src = "interface other_if;\nendinterface\ninterface bus_if;\n modport mp (input other_if);\nendinterface\n"; let s = sem(src); assert_eq!(resolution(&s, after(src, "modport mp (input ")), None); } #[test] fn the_modport_half_of_a_port_type_resolves_in_file() { let src = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\n"; let s = sem(src); assert_eq!(resolved(&s, at(src, "bus_if.mp")).kind, SymbolKind::Interface); let mp = resolved(&s, after(src, "bus_if.")); assert_eq!(mp.kind, SymbolKind::Modport); assert_eq!(mp.name, "mp"); } #[test] fn the_modport_half_of_a_port_type_resolves_across_files() { let sources = [ ("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"), ("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"), ]; let ws = index(&sources); let src = sources[1].1; let tail = after(src, "bus_if."); assert_eq!( resolution(&sem(src), tail), Some(Resolution::ExternalCandidate { paths: vec!["bus_if::mp".to_string()] }) ); let def = overlay_def(&ws, src, tail).expect("the member table answers"); assert_eq!(def.kind, SymbolKind::Modport); assert_eq!(slice(&ws, &sources, &def), "mp"); } #[test] fn a_virtual_interface_handle_keeps_its_modport_reference_and_its_bare_type() { let sources = [ ("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"), ("env.sv", "class env;\n virtual bus_if.mp vif;\nendclass\n"), ]; let ws = index(&sources); let src = sources[1].1; let s = sem(src); assert_eq!( symbol(&s, "vif").type_name.as_deref(), Some("bus_if"), "a modport restricts direction, not membership: the handle's type is the interface" ); let def = overlay_def(&ws, src, after(src, "bus_if.")).expect("the member table answers"); assert_eq!(def.kind, SymbolKind::Modport); assert_eq!(slice(&ws, &sources, &def), "mp"); } #[test] fn a_modport_named_in_a_connection_resolves_through_the_instance() { let together = "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\nmodule sub (bus_if.mp bus);\nendmodule\nmodule top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"; let s = sem(together); let mp = resolved(&s, after(together, ".bus(b_if.")); assert_eq!(mp.kind, SymbolKind::Modport); let sources = [ ("bus_if.sv", "interface bus_if;\n logic a;\n modport mp (input a);\nendinterface\n"), ("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"), ]; let ws = index(&sources); let src = sources[1].1; let def = overlay_def(&ws, src, after(src, ".bus(b_if.")).expect("the member table answers"); assert_eq!(def.kind, SymbolKind::Modport); } #[test] fn two_interfaces_with_the_same_modport_name_answer_for_themselves() { let a = "interface a_if;\n logic x;\n modport mp (input x);\nendinterface\n"; let b = "interface b_if;\n logic y;\n modport mp (input y);\nendinterface\n"; let sources = [ ("a_if.sv", a), ("b_if.sv", b), ("sub.sv", "module sub (a_if.mp p, b_if.mp q);\nendmodule\n"), ]; let ws = index(&sources); let src = sources[2].1; for (prefix, want) in [("a_if.", "a_if.sv"), ("b_if.", "b_if.sv")] { let def = overlay_def(&ws, src, after(src, prefix)).expect("the member table answers"); assert_eq!(def.kind, SymbolKind::Modport); let file = ws.path(def.file).and_then(|p| p.file_name()).unwrap().to_string_lossy(); assert_eq!(file, want, "{prefix} must answer with its own interface's modport"); } } // ---------------------------------------------------------------------- // clocking blocks // ---------------------------------------------------------------------- const CLOCKED: &str = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\nendinterface\n"; #[test] fn a_named_clocking_block_is_a_symbol_typed_by_its_enclosing_unit() { let s = sem(CLOCKED); let cb = symbol(&s, "cb"); assert_eq!(cb.kind, SymbolKind::Clocking); assert_eq!( cb.type_name.as_deref(), Some("bus_if"), "a clocking signal aliases the enclosing unit's own signal, so the block's type is that unit" ); // The event and the signal list are both ordinary uses of the interface's // declarations. assert_eq!(resolved(&s, at(CLOCKED, "posedge clk") + 8).name, "clk"); assert_eq!(resolved(&s, after(CLOCKED, " input ")).name, "data"); } #[test] fn a_clocking_signal_is_reached_through_the_block_in_file_and_across_files() { let together = format!("{CLOCKED}class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n"); let s = sem(&together); let hit = resolved(&s, after(&together, "vif.cb.")); assert_eq!(hit.name, "data"); assert_eq!(hit.kind, SymbolKind::Var, "the honest answer is the signal's own declaration"); let env = "class env;\n virtual bus_if vif;\n task go ();\n if (vif.cb.data) begin\n end\n endtask\nendclass\n"; let sources = [("bus_if.sv", CLOCKED), ("env.sv", env)]; let ws = index(&sources); let tail = after(env, "vif.cb."); assert_eq!( resolution(&sem(env), tail), Some(Resolution::ExternalCandidate { paths: vec!["bus_if::cb::data".to_string()] }) ); let def = overlay_def(&ws, env, tail).expect("the member chain answers"); assert_eq!(slice(&ws, &sources, &def), "data"); } #[test] fn a_clocking_block_is_a_chain_head_inside_its_own_interface() { let src = "interface bus_if;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendinterface\n"; let s = sem(src); let hit = resolved(&s, after(src, "cb.")); assert_eq!(hit.name, "data"); assert_eq!(hit.kind, SymbolKind::Var); } #[test] fn an_anonymous_default_clocking_declares_nothing() { let src = "interface bus_if;\n logic clk;\n default clocking @(posedge clk);\n endclocking\nendinterface\n"; let s = sem(src); assert!( s.symbols().iter().all(|sym| sym.kind != SymbolKind::Clocking), "an unnamed block binds no name, so there is nothing to declare" ); assert_eq!(resolved(&s, at(src, "posedge clk") + 8).name, "clk"); } #[test] fn a_body_less_default_clocking_names_an_existing_block() { let src = "interface bus_if;\n logic clk;\n clocking cb @(posedge clk);\n endclocking\n default clocking cb;\nendinterface\n"; let s = sem(src); let hit = resolved(&s, at(src, "default clocking cb") + 17); assert_eq!(hit.kind, SymbolKind::Clocking); assert_eq!(hit.name, "cb"); } #[test] fn a_clocking_block_in_a_module_behaves_the_same_way() { let src = "module tb;\n logic clk;\n logic data;\n clocking cb @(posedge clk);\n input data;\n endclocking\n initial d = cb.data;\nendmodule\n"; let s = sem(src); assert_eq!(symbol(&s, "cb").type_name.as_deref(), Some("tb")); assert_eq!(resolved(&s, after(src, "cb.")).name, "data"); } // ---------------------------------------------------------------------- // what an interface exports // ---------------------------------------------------------------------- const EXPORTER: &str = "interface bus_if;\n parameter int WIDTH = 8;\n wire net_sig;\n logic var_sig;\n task drive ();\n endtask\nendinterface\n"; #[test] fn an_interfaces_signals_are_reachable_through_a_virtual_handle_across_files() { let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.net_sig;\n y = vif.var_sig;\n z = vif.WIDTH;\n vif.drive();\n endtask\nendclass\n"; let sources = [("bus_if.sv", EXPORTER), ("env.sv", env)]; let ws = index(&sources); for (want, kind) in [ ("net_sig", SymbolKind::Net), ("var_sig", SymbolKind::Var), ("WIDTH", SymbolKind::Param), ("drive", SymbolKind::Task), ] { let offset = at(env, &format!("vif.{want}")) + 4; let def = overlay_def(&ws, env, offset).unwrap_or_else(|| panic!("vif.{want} is unanswered")); assert_eq!(slice(&ws, &sources, &def), want); assert_eq!(def.kind, kind, "vif.{want}"); } } #[test] fn a_name_the_interface_does_not_declare_is_still_unanswered() { let env = "class env;\n virtual bus_if vif;\n task go ();\n x = vif.nope;\n endtask\nendclass\n"; let ws = index(&[("bus_if.sv", EXPORTER), ("env.sv", env)]); assert_eq!( overlay_def(&ws, env, after(env, "vif.")), None, "a signal the interface does not declare has no honest answer" ); } #[test] fn a_modules_internals_are_still_not_exported() { // The module ruling (`docs/features/class-member-access/README.md`, round // 2) is untouched: an interface's signals are its surface, a module's are // not. let sub = "module sub (input logic p);\n logic internal;\nendmodule\n"; let ws = index(&[("sub.sv", sub)]); let members: Vec<&str> = ws.members_of("sub").map(|(name, _)| name).collect(); assert_eq!(members, ["p"]); let iface = index(&[("bus_if.sv", EXPORTER)]); let members: Vec<&str> = iface.members_of("bus_if").map(|(name, _)| name).collect(); assert_eq!(members, ["WIDTH", "drive", "net_sig", "var_sig"]); } // ---------------------------------------------------------------------- // the index's own equalities, over the new declarations // ---------------------------------------------------------------------- #[test] fn an_interface_survives_encode_and_decode_unchanged() { let facts = FileFacts::of(PathBuf::from("bus_if.sv"), IFACE); let line = facts.encode().expect("a plain path encodes"); assert_eq!(FileFacts::decode(&line), Some(facts), "modport and clocking kinds round-trip"); } #[test] fn incrementally_indexing_an_interface_gives_the_index_a_build_would() { let files = [ ("bus_if.sv", IFACE), ("sub.sv", "module sub (bus_if.mp bus);\nendmodule\n"), ("top.sv", "module top;\n bus_if b_if ();\n sub u (.bus(b_if.mp));\nendmodule\n"), ]; let whole = index(&files); let mut incremental = index(&files[..1]); for (path, src) in &files[1..] { incremental.update_file(PathBuf::from(path), src); } assert_eq!(incremental.fingerprint(), whole.fingerprint()); let mut absorbed = index(&[]); absorbed.absorb(files.iter().map(|(p, s)| FileFacts::of(PathBuf::from(*p), s)).collect(), &[]); assert_eq!(absorbed.fingerprint(), whole.fingerprint()); } #[test] fn a_modport_and_a_clocking_block_are_exported_members() { let ws = index(&[("bus_if.sv", IFACE)]); let members: Vec<(&str, SymbolKind)> = ws.members_of("bus_if").map(|(name, defs)| (name, defs[0].kind)).collect(); assert!(members.contains(&("mp", SymbolKind::Modport)), "{members:?}"); assert!(members.contains(&("cb", SymbolKind::Clocking)), "{members:?}"); } // ---------------------------------------------------------------------- // measurement // ---------------------------------------------------------------------- /// What this round costs the index over the real corpus: the store's size and /// what it is *made of*, group by group, so a byte delta can be attributed /// rather than guessed at. /// /// `#[ignore]`d, asserting nothing — the house shape for a measurement probe /// (`crates/lucisv_server/src/perf.rs`), and it reads only public API so the /// same file can be dropped into a checkout of an older revision to produce /// the "before" column. Run with /// `cargo test -p vlog_semantic --release --test interfaces -- --ignored --nocapture`. #[test] #[ignore = "measurement over corpus/, printed rather than asserted"] fn what_interface_semantics_cost_the_index() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); if !root.is_dir() { eprintln!("corpus/ not checked out — skipping"); return; } let mut files = Vec::new(); collect(&root, &mut files); files.sort(); let start = std::time::Instant::now(); let (mut bytes, mut records) = (0usize, 0usize); // The record's own length-prefixed groups: units, members, references. let (mut units, mut members, mut refs) = (0usize, 0usize, 0usize); let (mut local, mut external) = (0usize, 0usize); let (mut paths, mut path_bytes) = (0usize, 0usize); for path in &files { let Ok(src) = std::fs::read_to_string(path) else { continue; }; let Some(line) = FileFacts::of(path.clone(), &src).encode() else { continue; }; bytes += line.len() + 1; records += 1; let fields: Vec<&str> = line.split('\t').collect(); let group = |tag: &str| -> usize { fields .iter() .position(|f| *f == tag) .and_then(|at| fields.get(at + 1)) .and_then(|n| n.parse().ok()) .unwrap_or(0) }; units += group("U"); members += group("M"); refs += group("R"); local += fields.iter().filter(|f| **f == "l").count(); external += fields.iter().filter(|f| **f == "e").count(); // An external fact's bytes are dominated by the paths it carries, so // the path text is counted apart from everything else. let mut at = 0; while at < fields.len() { if fields[at] == "e" { let count: usize = fields.get(at + 3).and_then(|n| n.parse().ok()).unwrap_or(0); paths += count; for i in 0..count { path_bytes += fields.get(at + 4 + i).map_or(0, |f| f.len()); } at += 4 + count + 2; } else { at += 1; } } } let elapsed = start.elapsed(); println!("corpus: {records} records, {bytes} store bytes, {elapsed:?} to read them all"); println!("corpus groups: {units} units, {members} members, {refs} references ({local} local, {external} external)"); println!("corpus paths: {paths} recorded paths, {path_bytes} bytes of path text"); } fn collect(dir: &Path, out: &mut Vec) { let Ok(entries) = std::fs::read_dir(dir) else { return; }; for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { collect(&path, out); } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) { out.push(path); } } }