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
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/comb_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub(super) fn comb_processes_from_module_node(
if !relevant {
continue;
}
let _constant_functions = item.enter();
let start = processes.len();
let (dimensions, literals) = views.get(item);
comb_processes_from_module_or_generate_item(
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/ast/const_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,10 @@ impl ConstantFunctions {
.retain(|name, _| keep(name));
}

pub(super) fn contains(&self, name: &str) -> bool {
self.functions.contains_key(name) || self.errors.by_name.contains_key(name)
}

/// Make the function `target` callable as `name` too.
pub(super) fn alias(&mut self, name: &str, target: &str) {
if let Some(function) = self.functions.get(target).cloned() {
Expand Down
3 changes: 2 additions & 1 deletion crates/celox-sv-analyzer/src/ast/declarations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,11 +430,12 @@ pub(super) fn signals_from_module_node(
}
ScopeItem::Package(_) => continue,
};
let _constant_functions = item.enter();
let start = signals.len();
signals_from_module_or_generate_item(
node,
syntax_tree,
type_aliases,
&item.type_aliases(type_aliases),
&item.env,
None,
&mut signals,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/ff_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub(super) fn ff_processes_from_module_node(
) {
continue;
}
let _constant_functions = item.enter();
let start = processes.len();
let (dimensions, literals) = views.get(item);
ff_processes_from_module_or_generate_item(
Expand Down
6 changes: 4 additions & 2 deletions crates/celox-sv-analyzer/src/ast/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,16 @@ pub(super) fn functions_from_module_node(
packed_dimensions: &PackedDimensions,
) -> Result<HashMap<String, Function>, AnalyzerError> {
let mut functions = HashMap::default();
let type_aliases =
let module_type_aliases =
type_aliases_from_module_node_with_env(node.clone(), syntax_tree, const_env)?;
let active = generate::items(node.clone(), syntax_tree, const_env, &type_aliases)?;
let active = generate::items(node.clone(), syntax_tree, const_env, &module_type_aliases)?;
let mut views = generate::ScopeViews::new(packed_dimensions);
for (item, child) in active
.iter()
.flat_map(|item| item.node.node().into_iter().map(move |child| (item, child)))
{
let _constant_functions = item.enter();
let type_aliases = item.type_aliases(&module_type_aliases);
if let RefNode::TaskDeclaration(declaration) = child {
let task_dimensions = views.dimensions(item);
let const_env = &item.env;
Expand Down
161 changes: 153 additions & 8 deletions crates/celox-sv-analyzer/src/ast/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,111 @@ pub(super) struct Item<'a> {
pub literals: SharedMap<Expr>,
parameter_dimensions: Arc<VariablePackedDimensions>,
names: SharedMap<String>,
imports: SharedMap<String>,
shadowed: Arc<HashSet<String>>,
scope: String,
}

/// The names the imports of the enclosing generate blocks bind to another
/// declaration than the module does (see `imports::resolve_imports`), unless
/// a declaration of an inner block hides them again. The module-wide tables
/// hold those declarations under their qualified names.
#[derive(Clone, Copy)]
struct BlockImports<'s> {
names: &'s HashMap<String, String>,
imports: &'s HashMap<String, String>,
/// The names the blocks declare or import.
shadowed: &'s HashSet<String>,
}

impl<'s> BlockImports<'s> {
fn bindings(self) -> impl Iterator<Item = (&'s String, &'s String)> {
self.imports
.iter()
.filter(move |(name, target)| self.names.get(*name) == Some(*target))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove type aliases hidden by local declarations

When a generate-local value declaration hides an inherited imported type, this filter drops the import from bindings() but leaves the module's simple-name type alias visible. For example, if the module imports q::T, an outer generate block imports and uses p::T, a child declares localparam T, and a grandchild declares T n, the newly accepted design lowers n as q::T; the local parameter should instead hide both outer type bindings, making T n invalid. Preserve the declaration's shadowing information so type_aliases removes T rather than falling back to the module alias.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b78b0f5. BlockImports::type_aliases now uses the generate scope's shadowed set: any name the enclosing blocks declare or import hides the module's type alias of that name, and imported types are then re-added under their name. With the import chain you describe, a child localparam T makes a grandchild's T n; invalid, and it is now rejected. The same was true without any import: a module typedef T was never hidden by a generate-local localparam T or logic T, so that case is fixed too. The lookup walks the smaller of the alias table and the shadowed set. Covered by generate_block_declarations_hide_outer_types, which fails without the fix.

}

/// The type aliases visible here: a name the blocks declare or import
/// hides the module's type of that name, and an imported name denotes
/// the type of its declaration.
fn type_aliases<'m>(
self,
aliases: &'m HashMap<String, Type>,
) -> Cow<'m, HashMap<String, Type>> {
let mut visible = Cow::Borrowed(aliases);
let hidden: Vec<&String> = if aliases.len() <= self.shadowed.len() {
aliases
.keys()
.filter(|name| self.shadowed.contains(*name))
.collect()
} else {
self.shadowed
.iter()
.filter(|name| aliases.contains_key(*name))
.collect()
};
for name in hidden {
visible.to_mut().remove(name);
}
for (name, target) in self.bindings() {
if let Some(r#type) = aliases.get(target) {
visible.to_mut().insert(name.clone(), r#type.clone());
}
Comment on lines +102 to +105

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove type aliases hidden by non-type imports

When a module sees a typedef such as q::T but a generate block imports a value or subroutine p::T, this loop leaves the module's T entry untouched because p::T is absent from the alias table. The block import still owns that name, so declarations such as T n must not resolve to the outer typedef; retaining it can silently give the declaration the wrong type instead of rejecting the non-type name. Remove the simple-name alias whenever an effective block import targets a non-type declaration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 80ea43a: when a block import binds a name to something that is not a type, BlockImports::type_aliases now removes the module's type alias of that name, so a block declaration T n; can no longer take the outer typedef. With a module typedef q::T and a block import of localparam int T from p, T n; in the block is rejected, and assign a = T; there still reads p::T. Both are covered in generate_block_imports_bind_their_own_types.

}
visible
}

/// Make each imported name call the constant function of its
/// declaration, until the guard is dropped; a name that imports no
/// constant function calls none. Calls in the bodies of the functions it
/// hides keep their definition-site meaning.
fn install_constant_functions(self) -> Option<const_functions::Installed> {
let installed = const_functions::installed();
let rebound: Vec<_> = self
.bindings()
.filter(|(name, target)| installed.contains(name) || installed.contains(target))
.collect();
if rebound.is_empty() {
return None;
Comment on lines +116 to +121

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hide outer constant functions for every effective import

If a module has a constant function f and a generate block imports a same-named declaration that is not in the installed constant-function table—most notably a DPI function, or a function whose table has only a global conversion error—this filter drops the binding entirely and the early return leaves the module's f installed. A block-local parameter or width expression calling f can therefore execute the outer function and produce a wrong elaborated value instead of binding to or rejecting the imported declaration. The outer binding must be hidden even when the target cannot be installed as a constant function.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 80ea43a: install_constant_functions now also covers block imports whose target is not in the constant-function table, as long as the name hides an outer constant function. That outer function is renamed away and nothing is installed under the name. A block localparam int Y = f(1); with a DPI-C p::f is now rejected ("user constant function call") instead of running the module's f, whether the module declares f or imports q::f. For a target with only a module-wide conversion error, a call of the hidden name reports that error. Covered by generate_block_dpi_imports_hide_outer_constant_functions in sv_dpi.rs.

}
let hidden: HashMap<String, String> = rebound
.iter()
.filter(|(name, _)| installed.contains(name))
.map(|(name, _)| ((*name).clone(), format!("{OUTER_BINDING}{name}")))
.collect();
let rename = scope::Renamer { names: &hidden };
let mut visible =
installed.renamed(&mut |name| rename.name(name), &mut |stmt| rename.stmt(stmt));
for (name, target) in rebound {
visible.alias(name, target);
}
Some(const_functions::install(visible))
}
}

impl Item<'_> {
fn block_imports(&self) -> BlockImports<'_> {
BlockImports {
names: &self.names,
imports: &self.imports,
shadowed: &self.shadowed,
}
}

/// The type aliases this item sees, given the module's.
pub fn type_aliases<'m>(
&self,
aliases: &'m HashMap<String, Type>,
) -> Cow<'m, HashMap<String, Type>> {
self.block_imports().type_aliases(aliases)
}

/// Make the constant functions this item sees the installed ones, until
/// the guard is dropped.
pub fn enter(&self) -> Option<const_functions::Installed> {
self.block_imports().install_constant_functions()
}

pub fn common(&self) -> Option<&sv_parser::ModuleCommonItem> {
match self.node {
ScopeItem::Module(sv_parser::ModuleOrGenerateItem::ModuleItem(item)) => {
Expand Down Expand Up @@ -140,6 +240,9 @@ impl Item<'_> {
self.function_aliases(dimensions.function_return_types.clone());
}
}
if let Cow::Owned(aliases) = self.type_aliases(&dimensions.type_aliases) {
local.type_aliases = aliases;
}
let mut signedness = dimensions.expression_signedness.clone();
for name in self.shadowed.iter() {
let protected = format!("{OUTER_BINDING}{name}");
Expand Down Expand Up @@ -340,12 +443,25 @@ struct Scope {
parameters: Vec<Parameter>,
parameter_dimensions: Arc<VariablePackedDimensions>,
names: SharedMap<String>,
imports: SharedMap<String>,
shadowed: Arc<HashSet<String>>,
}

impl Scope {
fn block_imports(&self) -> BlockImports<'_> {
BlockImports {
names: &self.names,
imports: &self.imports,
shadowed: &self.shadowed,
}
}
}

struct Elaborator<'a, 'b> {
tree: &'a SyntaxTree,
aliases: &'b HashMap<String, Type>,
module_aliases: &'b HashMap<String, Type>,
/// The type aliases of the scope being elaborated.
aliases: Cow<'b, HashMap<String, Type>>,
remaining: usize,
functions: HashMap<String, Function>,
items: Vec<Item<'a>>,
Expand Down Expand Up @@ -397,7 +513,8 @@ fn items_with_literal_use<'a>(
) -> Result<Vec<Item<'a>>, AnalyzerError> {
let mut elaborator = Elaborator {
tree,
aliases,
module_aliases: aliases,
aliases: Cow::Borrowed(aliases),
remaining: MAX_GENERATE_LOOP_EXPANSION,
functions: HashMap::default(),
items: Vec::new(),
Expand Down Expand Up @@ -541,7 +658,7 @@ impl<'a> Elaborator<'a, '_> {
RefNode::ConstantExpression(expr),
self.tree,
&scope.env,
self.aliases,
&self.aliases,
)?
else {
return Ok(None);
Expand All @@ -565,6 +682,16 @@ impl<'a> Elaborator<'a, '_> {
for arg in args {
self.expand_constant_calls(arg, scope)?;
}
// A block import binds the call to the qualified declaration,
// which the installed constant functions evaluate.
if let Callee::Subroutine(name) = callee
&& let Some(target) = scope
.block_imports()
.bindings()
.find_map(|(imported, target)| (imported == name).then_some(target))
{
*name = target.clone();
}
if let Callee::Subroutine(name) = callee
&& self.functions.contains_key(name)
{
Expand Down Expand Up @@ -908,6 +1035,7 @@ impl<'a> Elaborator<'a, '_> {
literals: scope.literals.clone(),
parameter_dimensions: scope.parameter_dimensions.clone(),
names: scope.names.clone(),
imports: scope.imports.clone(),
shadowed: scope.shadowed.clone(),
scope: scope.path.clone(),
});
Expand Down Expand Up @@ -1140,7 +1268,7 @@ impl<'a> Elaborator<'a, '_> {
signals_from_module_or_generate_item(
item,
self.tree,
self.aliases,
&self.aliases,
&scope.env,
Some(&name),
&mut signals,
Expand Down Expand Up @@ -1200,7 +1328,7 @@ impl<'a> Elaborator<'a, '_> {
&mut scope.parameters,
true,
&base,
self.aliases,
&self.aliases,
&HashMap::default(),
&mut environment,
)?;
Expand Down Expand Up @@ -1249,7 +1377,7 @@ impl<'a> Elaborator<'a, '_> {
&mut scope.parameters,
true,
&scope.env,
self.aliases,
&self.aliases,
&HashMap::default(),
)?;
let parameter = scope
Expand Down Expand Up @@ -1327,6 +1455,22 @@ impl<'a> Elaborator<'a, '_> {
bind_import(&mut scope, name, target);
}
}
// The declarations and nested blocks are elaborated with the types and
// constant functions those imports bind.
let _constant_functions = scope.block_imports().install_constant_functions();
let aliases = scope.block_imports().type_aliases(self.module_aliases);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear inherited overrides when an inner import restores the module binding

When a module imports q::t, an outer generate block imports p::t, and a nested block imports q::t again, resolve_imports omits the nested binding because it matches the module-level target. The nested Scope is cloned from its parent, however, so this lookup still sees the inherited p::t entry and declarations such as t n use the outer block's type (for example, 4 bits instead of 8). Applying a nested import that returns to the module binding must remove the inherited override rather than leaving it active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in cd8ca9c. The bug was in resolve_imports: it skipped an inner block's import whenever that import matched the module's binding. It now records the import when an enclosing block imports another declaration or declares the name, so the inner block no longer inherits the outer override. This was already wrong for plain values since #1184 (an inner import q::* under an outer import p::* read p::X), and also when an outer block declared localparam X and an inner block did import q::X. nested_generate_block_imports_restore_the_module_binding covers values, types, constant and runtime calls, an alternating p/q/p chain, and the outer-declaration case. All five cases fail without the fix.

let outer = std::mem::replace(&mut self.aliases, aliases);
let elaborated = self.block_contents(children, scope, index);
self.aliases = outer;
elaborated
}

fn block_contents(
&mut self,
children: Vec<&'a sv_parser::GenerateItem>,
mut scope: Scope,
index: Option<(&str, i128)>,
) -> Result<(), AnalyzerError> {
// Bind all declarations before lowering expressions, including forward references.
let mut declared = HashSet::default();
if let Some((genvar, value)) = index {
Expand All @@ -1352,7 +1496,7 @@ impl<'a> Elaborator<'a, '_> {
signals_from_module_or_generate_item(
item,
self.tree,
self.aliases,
&self.aliases,
&scope.env,
None,
&mut signals,
Expand Down Expand Up @@ -1404,7 +1548,7 @@ impl<'a> Elaborator<'a, '_> {
signals_from_module_or_generate_item(
item,
self.tree,
self.aliases,
&self.aliases,
&scope.env,
None,
&mut signals,
Expand Down Expand Up @@ -1450,6 +1594,7 @@ fn bind_import(scope: &mut Scope, name: &str, target: &str) {
let imported = scope::imported();
Arc::make_mut(&mut scope.shadowed).insert(name.to_string());
scope.names.insert(name.to_string(), target.to_string());
scope.imports.insert(name.to_string(), target.to_string());
// The constant value and type markers of the item, under the name.
let names = |key: &str| -> Option<String> {
if key == target {
Expand Down
48 changes: 22 additions & 26 deletions crates/celox-sv-analyzer/src/ast/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1271,9 +1271,9 @@ pub(super) fn resolve_imports(
}
// A name the generate blocks import is a name of the whole module when
// nothing else gives it a meaning; otherwise each block that imports
// another declaration names it there.
// another declaration than the one visible around it names it there.
let mut generate_imports: HashMap<usize, HashMap<String, String>> = HashMap::default();
for (name, uses) in scoped {
for (name, mut uses) in scoped {
let outside = bindings
.iter()
.find(|binding| binding.name == name)
Expand All @@ -1296,34 +1296,30 @@ pub(super) fn resolve_imports(
});
continue;
}
for (block, target) in uses {
if outside.as_ref() == Some(&target) {
uses.sort_unstable();
uses.dedup();
// A block around `block` that imports another declaration, or
// declares the name, hides the module's binding there.
let encloses =
|scope: &GenerateScope, block: usize| scope.start < block && scope.contains(block);
let hidden = |block: usize, target: &String| {
uses.iter().any(|(outer, other)| {
other != target
&& all_scopes
.iter()
.any(|scope| scope.start == *outer && encloses(scope, block))
}) || all_scopes
.iter()
.any(|scope| scope.declared.contains(&name) && encloses(scope, block))
};
for (block, target) in &uses {
if outside.as_ref() == Some(target) && !hidden(*block, target) {
continue;
}
// Types, and the formal names and shapes of subroutines, are
// looked up module-wide.
if symbols.type_aliases.contains_key(&target) {
return Err(AnalyzerError::Unsupported(format!(
"type `{name}` that a generate block imports as another declaration than \
its module"
)));
}
if symbols.subroutine_params.contains_key(&target)
|| symbols.functions.contains_key(&target)
|| symbols
.dpi_imports
.iter()
.any(|import| import.name() == target.as_str())
{
return Err(AnalyzerError::Unsupported(format!(
"subroutine `{name}` that a generate block imports as another declaration \
than its module"
)));
}
generate_imports
.entry(block)
.entry(*block)
.or_default()
.insert(name.clone(), target);
.insert(name.clone(), target.clone());
}
}
symbols.generate_imports = generate_imports;
Expand Down
Loading
Loading