Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 95 additions & 13 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ fn interface_signatures_collecting(
&[],
LevelLists::Processes,
&HashMap::default(),
&HashMap::default(),
)?;
Ok(InterfaceSignature {
name: prototype.name,
Expand Down Expand Up @@ -949,6 +950,7 @@ fn lower_package_states(
&[],
LevelLists::Processes,
&HashMap::default(),
&HashMap::default(),
)?;
lowered.sim_module.time_precision = Some(
celox_design::TimePrecision::try_from(packages.global_time_precision())
Expand Down Expand Up @@ -3171,24 +3173,44 @@ fn demote_level_lists(
changed
}

// Use elaboration provenance rather than treating every '$' as a separator:
// legal authored identifiers may themselves contain '$'.
// Candidate indices only locate a declaration; source provenance decides
// whether this is an interface path. Authored '$' names stay intact.
fn restore_interface_path(
name: &str,
paths: &HashMap<String, sv::InterfaceMemberPath>,
) -> Option<Vec<String>> {
if let Some(path) = paths.get(name) {
return path.restore(name);
}
for (separator, _) in name.match_indices('$') {
let member = &name[separator + 1..];
let mut handle = &name[..separator];
while let Some(indexed) = handle.strip_suffix(']') {
let Some((base, index)) = indexed.rsplit_once('[') else {
break;
};
if index.parse::<i128>().is_err() {
break;
}
let key = format!("{base}${member}");
if let Some(path) = paths.get(&key).filter(|path| path.arrayed)
&& let Some(restored) = path.restore(name)
{
return Some(restored);
}
handle = base;
}
}
None
}

fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvModule) {
for variable in module.variables.values_mut() {
variable.path = variable
.path
.iter()
.flat_map(|segment| {
source
.interface_member_paths
.get(segment)
.and_then(|path| path.restore(segment))
.or_else(|| {
source
.interface_member_paths
.values()
.find_map(|path| path.restore(segment))
})
restore_interface_path(segment, &source.interface_member_paths)
.unwrap_or_else(|| vec![segment.clone()])
})
.collect();
Expand Down Expand Up @@ -3367,6 +3389,7 @@ fn specialize_module(
&local_forces,
level_lists,
hierarchical.foreign_writes,
&module.interface_member_paths,
)?;
propagate_force_signals(&mut lowered.instances, &key.force_signals);
lowered.sim_module.time_precision = Some(
Expand Down Expand Up @@ -3480,6 +3503,7 @@ fn lower_module(
force_signals: &[String],
level_lists: LevelLists<'_>,
foreign_writes: &HashMap<String, hierarchy::ForeignWrites>,
reflected_paths: &HashMap<String, sv::InterfaceMemberPath>,
) -> Result<LoweredSvModule, sv::AnalyzerError> {
lower_module_with_overrides(
module,
Expand All @@ -3491,6 +3515,7 @@ fn lower_module(
force_signals,
level_lists,
foreign_writes,
reflected_paths,
)
}

Expand Down Expand Up @@ -3573,6 +3598,7 @@ fn lower_module_with_overrides(
force_signals: &[String],
level_lists: LevelLists<'_>,
foreign_writes: &HashMap<String, hierarchy::ForeignWrites>,
reflected_paths: &HashMap<String, sv::InterfaceMemberPath>,
) -> Result<LoweredSvModule, sv::AnalyzerError> {
let parameter_types = module_parameter_types(module);
let constants = module_constants_with_overrides(module, parameter_overrides);
Expand Down Expand Up @@ -3777,7 +3803,14 @@ fn lower_module_with_overrides(
// Retain integral parameters for external observation, without adding them
// to name_to_id: HDL expressions must still fold parameter references as
// constants rather than introduce runtime loads.
for parameter in module.parameters() {
// Interface declarations are flattened into imported symbols, rather
// than authored module parameters. Retain their instance-local values as
// well; package imports remain owned by their package (IEEE 37.10).
let interface_parameters = module
.imported_parameters()
.iter()
.filter(|parameter| restore_interface_path(parameter.name(), reflected_paths).is_some());
for parameter in module.parameters().iter().chain(interface_parameters) {
let Some(width) = parameter.resolved_width().filter(|width| *width > 0) else {
continue;
};
Expand Down Expand Up @@ -11289,3 +11322,52 @@ endmodule
);
}
}

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

#[test]
fn indexed_interface_paths_require_declaration_provenance() {
let paths = [
(
"authored$bus$extra$width",
["authored$bus", "extra$width"],
false,
),
("lanes$extra$width", ["lanes", "extra$width"], true),
("g[3].lanes$W", ["g[3].lanes", "W"], true),
]
.into_iter()
.map(|(key, segments, arrayed)| {
(
key.to_string(),
sv::InterfaceMemberPath {
segments: segments.into_iter().map(str::to_string).collect(),
arrayed,
},
)
})
.collect();
for (name, expected) in [
("authored$bus$extra$width", ["authored$bus", "extra$width"]),
("lanes[1][-2]$extra$width", ["lanes[1][-2]", "extra$width"]),
("g[3].lanes[7]$W", ["g[3].lanes[7]", "W"]),
] {
assert_eq!(
restore_interface_path(name, &paths),
Some(expected.into_iter().map(str::to_string).collect()),
"{name}"
);
}
for name in [
"lanes$not_declared",
"lanes[foo]$extra$width",
"authored$bus[0]$extra$width",
"normal$parameter",
"g[2].lanes[7]$W",
] {
assert_eq!(restore_interface_path(name, &paths), None, "{name}");
}
}
}
122 changes: 115 additions & 7 deletions crates/celox-sv-analyzer/src/ast/classes/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,43 @@ pub(in crate::ast) fn specialize(
}
depth.set(depth.get() + 1);
let _nesting = Nesting(depth);
// Parameter binding and body construction have large temporary values.
// Keep those phases off the stack while resolving an inherited class.
let pending = match prepare(tree, generic, arguments, context)? {
Preparation::Existing(name) => return Ok(name),
Preparation::Pending(pending) => pending,
};
tree.state
.class_specializations_building
.borrow_mut()
.push(pending.name.clone());
let _building = Building(&tree.state.class_specializations_building);
let bases = bind_bases(tree, generic, &pending.env, &pending.aliases)?;
finish_specialization(tree, generic, pending, bases)
}

struct PendingSpecialization {
name: String,
parameters: Parameters,
env: HashMap<String, i128>,
aliases: HashMap<String, Type>,
}

enum Preparation {
Existing(String),
Pending(Box<PendingSpecialization>),
}

// These boundaries keep the recursive inheritance frame small in debug and
// optimized builds alike; the specialization limit must produce a diagnostic
// before the host thread runs out of stack.
#[inline(never)]
fn prepare(
tree: &AnalysisContext<'_>,
generic: &str,
arguments: &[Argument],
context: &PackedDimensions,
) -> Converted<Preparation> {
let native = tree.declarations();
let declaration = super::declaration(tree, generic)
.ok_or_else(|| unsupported(format!("class `{generic}`")))?;
Expand Down Expand Up @@ -375,7 +412,7 @@ pub(in crate::ast) fn specialize(
.borrow()
.contains(&name)
{
return Ok(name);
return Ok(Preparation::Existing(name));
}
if tree.state.class_specializations_frozen.get() {
return Err(unsupported(format!(
Expand All @@ -387,11 +424,24 @@ pub(in crate::ast) fn specialize(
"more than {MAX_SPECIALIZATIONS} class specializations"
)));
}
tree.state
.class_specializations_building
.borrow_mut()
.push(name.clone());
let _building = Building(&tree.state.class_specializations_building);
Ok(Preparation::Pending(Box::new(PendingSpecialization {
name,
parameters,
env,
aliases,
})))
}

#[inline(never)]
fn bind_bases(
tree: &AnalysisContext<'_>,
generic: &str,
env: &HashMap<String, i128>,
aliases: &HashMap<String, Type>,
) -> Converted<Vec<String>> {
let native = tree.declarations();
let declaration = super::declaration(tree, generic)
.ok_or_else(|| unsupported(format!("class `{generic}`")))?;
// The bases are named in the scope of the parameters; a class does not
// inherit the declarations of the interface classes it implements.
let inherited = match &declaration.base {
Expand All @@ -401,12 +451,31 @@ pub(in crate::ast) fn specialize(
};
let mut bases = Vec::new();
for id in inherited {
if let Some(base) = type_binding::procedural_type(id, native, tree, &env, &aliases)?
if let Some(base) = type_binding::procedural_type(id, native, tree, env, aliases)?
.and_then(|ty| ty.class().map(str::to_owned))
{
bases.push(base);
}
}
Ok(bases)
}

#[inline(never)]
fn finish_specialization(
tree: &AnalysisContext<'_>,
generic: &str,
pending: Box<PendingSpecialization>,
bases: Vec<String>,
) -> Converted<String> {
let PendingSpecialization {
name,
mut parameters,
mut env,
mut aliases,
} = *pending;
let native = tree.declarations();
let declaration = super::declaration(tree, generic)
.ok_or_else(|| unsupported(format!("class `{generic}`")))?;
// The body sees the parameters and types of the bases, hidden by the
// class's own, and the scope of the specialization (8.25.1).
for base in &bases {
Expand Down Expand Up @@ -1088,3 +1157,42 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens
}
}
}

#[cfg(test)]
mod tests {
use std::path::Path;

#[test]
fn inheritance_specialization_uses_the_default_thread_stack() {
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(|| {
let mut source = String::from("module Top;");
for index in 0..16 {
source.push_str(&format!(
"class Layer{index} #(int N = 0) extends Layer{}#(N + 1); endclass ",
index + 1,
));
}
source.push_str(
"class Layer16 #(int N = 0); localparam int VALUE = N; endclass
Layer0#() object; initial $display(Layer0#()::VALUE); endmodule",
);
crate::analyze_source(&source, Path::new("deep-class-inheritance.sv")).unwrap();

let error = crate::analyze_source(
"module Top;
class Recursive #(int N = 0) extends Recursive#(N + 1); endclass
Recursive object; endmodule",
Path::new("unbounded-class-inheritance.sv"),
)
.unwrap_err()
.to_string();
assert!(error.contains("nested more than 64 deep"), "{error}");
assert!(error.contains("class `Recursive`"), "{error}");
})
.unwrap()
.join()
.unwrap();
}
}
16 changes: 13 additions & 3 deletions crates/celox-sv-analyzer/src/ast/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,8 @@ struct InterfaceDecl {
/// Whether the declaration refers to compilation-unit items of its file.
uses_unit_items: bool,
parameters: Vec<InterfaceParameter>,
/// Value parameters and localparams whose instance paths VPI can observe.
reflected_parameters: Vec<String>,
type_parameters: Vec<String>,
parameter_order: Vec<String>,
items: Vec<Item>,
Expand Down Expand Up @@ -2423,6 +2425,7 @@ impl InterfaceDecl {
uses_unit_items: false,
uses_macros: has_directive(file.text(span)),
parameters: Vec::new(),
reflected_parameters: Vec::new(),
type_parameters: Vec::new(),
parameter_order: Vec::new(),
items: Vec::new(),
Expand Down Expand Up @@ -2614,6 +2617,7 @@ impl InterfaceDecl {
});
return Ok(());
};
self.reflected_parameters.push(native_name(&parameter.name));
if local {
self.declare(native_name(&parameter.name))?;
self.items.push(Item::Constant {
Expand Down Expand Up @@ -3506,11 +3510,17 @@ pub fn plan_interfaces_with_member_paths(
let mut member_paths = HashMap::default();
for (handle_name, declarations) in &handles.by_name {
for (_, handle) in declarations {
for member in &design.interfaces[&handle.interface].members {
let interface = &design.interfaces[&handle.interface];
for member in interface
.members
.iter()
.map(|member| &member.name)
.chain(&interface.reflected_parameters)
{
member_paths.insert(
format!("{handle_name}{SEPARATOR}{}", member.name),
format!("{handle_name}{SEPARATOR}{member}"),
InterfaceMemberPath {
segments: vec![handle_name.clone(), member.name.clone()],
segments: vec![handle_name.clone(), member.clone()],
arrayed: handle.arrayed,
},
);
Expand Down
Loading
Loading