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
9 changes: 9 additions & 0 deletions crates/celox-frontend-sv/src/warning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub enum FrontendWarningKind {
/// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations.
#[error("mixed explicit and default time units or precisions across design elements")]
MixedTimescale,
#[error("`$size` on an interface array is a language extension")]
InterfaceArrayQuery,
/// IEEE 1800-2023 9.2.2.4 restricts writes by other processes.
#[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")]
MultipleAlwaysFfDrivers { module: String, signal: String },
Expand Down Expand Up @@ -96,6 +98,9 @@ pub(crate) fn analyzer_warnings(
found: &[celox_sv_analyzer::ir::AnalyzerWarning],
) -> impl Iterator<Item = PendingWarning> + '_ {
found.iter().map(|warning| match warning {
celox_sv_analyzer::ir::AnalyzerWarning::InterfaceArrayQuery { site } => {
(FrontendWarningKind::InterfaceArrayQuery, site.clone())
}
celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => {
(FrontendWarningKind::MixedTimescale, None)
}
Expand Down Expand Up @@ -149,6 +154,7 @@ impl miette::Diagnostic for FrontendWarning {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new(match self.kind {
FrontendWarningKind::MixedTimescale => "mixed_timescale",
FrontendWarningKind::InterfaceArrayQuery => "interface_array_query",
FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers",
FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default",
FrontendWarningKind::InferredLatch => "inferred_latch",
Expand All @@ -166,6 +172,9 @@ impl miette::Diagnostic for FrontendWarning {
FrontendWarningKind::InferredLatch => {
"assign every output on every path, or configure diagnostics.inferred_latch as warn or allow"
}
FrontendWarningKind::InterfaceArrayQuery => {
"interface arrays are not data arrays in IEEE 1800-2023 20.7; set interface_array_query=warn or allow for compatibility"
}
FrontendWarningKind::MixedTimescale => {
"declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed"
}
Expand Down
63 changes: 42 additions & 21 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub(super) struct AnalysisState {
root_subroutines: std::cell::Cell<bool>,
next_call_site: std::rc::Rc<std::cell::Cell<usize>>,
timescales: timescales::State,
diagnostics: RefCell<Vec<warnings::AnalyzerWarning>>,
/// Classes laid out so far, by name.
classes: std::cell::RefCell<HashMap<String, std::rc::Rc<classes::Class>>>,
}
Expand Down Expand Up @@ -249,6 +250,7 @@ impl InterfaceLookup<'_> {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Source {
modules: Vec<Module>,
diagnostics: Vec<warnings::AnalyzerWarning>,
}

/// Overrides supplied by one instantiation. Types have been resolved in its scope.
Expand Down Expand Up @@ -298,16 +300,21 @@ impl Source {
&packages,
packages.unit(Path::new("")),
)?;
modules.push(Module::from_scope_with_parameter_overrides(
syntax_tree,
module_name,
&parameter_overrides,
&InterfaceLookup {
local: &interfaces,
extra: &ModuleInterfaces::default(),
},
Arc::new(imported),
)?);
modules.push(
Module::from_scope_with_parameter_overrides(
syntax_tree,
module_name,
&parameter_overrides,
&InterfaceLookup {
local: &interfaces,
extra: &ModuleInterfaces::default(),
},
Arc::new(imported),
)
.map_err(|error| {
error.with_warnings(context.state.diagnostics.borrow().clone())
})?,
);
}
celox_sv_syntax::PortStyle::NonAnsi => {
return Err(AnalyzerError::Unsupported(
Expand All @@ -318,7 +325,10 @@ impl Source {
}
}

Ok(Self { modules })
Ok(Self {
modules,
diagnostics: context.state.diagnostics.borrow().clone(),
})
}

pub(crate) fn from_syntax_module_with_parameter_overrides(
Expand Down Expand Up @@ -426,18 +436,26 @@ impl Source {
},
&interfaces,
imported.clone(),
)? {
)
.map_err(|error| {
error.with_warnings(context.state.diagnostics.borrow().clone())
})? {
module.name = module_name.to_string();
modules.push(module);
continue;
}
modules.push(Module::from_scope_with_parameter_overrides(
syntax_tree,
module_name,
bindings.values,
&interfaces,
Arc::new(imported),
)?);
modules.push(
Module::from_scope_with_parameter_overrides(
syntax_tree,
module_name,
bindings.values,
&interfaces,
Arc::new(imported),
)
.map_err(|error| {
error.with_warnings(context.state.diagnostics.borrow().clone())
})?,
);
}
celox_sv_syntax::PortStyle::NonAnsi if syntax_tree.root_name()? == module_name => {
return Err(AnalyzerError::Unsupported(
Expand All @@ -447,7 +465,10 @@ impl Source {
_ => {}
}
}
Ok(Self { modules })
Ok(Self {
modules,
diagnostics: context.state.diagnostics.borrow().clone(),
})
}

pub(crate) fn module_names_from_syntax(
Expand Down Expand Up @@ -492,7 +513,7 @@ impl Source {
}

pub(crate) fn warnings(&self) -> Vec<warnings::AnalyzerWarning> {
let mut warnings = Vec::new();
let mut warnings = self.diagnostics.clone();
for module in &self.modules {
warnings::append(&mut warnings, module.constant_functions.warnings());
}
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-analyzer/src/ast/const_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ impl ConstantFunctions {
) => std::cmp::Ordering::Equal,
(super::warnings::AnalyzerWarning::MixedTimescale, _) => std::cmp::Ordering::Less,
(_, super::warnings::AnalyzerWarning::MixedTimescale) => std::cmp::Ordering::Greater,
// This collector emits only ExitOutsideProgram warnings.
_ => std::cmp::Ordering::Equal,
});
warnings
}
Expand Down
88 changes: 88 additions & 0 deletions crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,17 @@ pub(in crate::ast) fn query_value(
let argument = arguments[0].value.unwrap();
let context = query_context_for_operand(argument, tree, context)?;
reject_unbounded(argument, function, tree, &context)?;
if function == SystemFunction::Size
&& let Some(value) = interface_array_size(
root,
argument,
arguments.get(1).and_then(|a| a.value),
tree,
&context,
)?
{
return Ok(Some(value));
}
let shape = shape(argument, tree, &context)?;
let dimension = if let Some(argument) = arguments.get(1) {
Some(expression_binding::bind(
Expand Down Expand Up @@ -216,6 +227,83 @@ pub(in crate::ast) fn query_value(
.ok_or_else(|| unsupported(format!("operand of `{}`", name.spelling)))
}

/// Query interface array metadata without admitting interface handles as data
/// expressions. This extension supports `$size` only; it adds no packed rank.
fn interface_array_size(
call: ExprId,
mut argument: ExprId,
dimension: Option<ExprId>,
tree: &AnalysisContext<'_>,
context: &PackedDimensions,
) -> Converted<Option<Expr>> {
let native = tree.declarations();
let mut selected = Vec::new();
loop {
argument = expression_binding::ungroup(argument, native);
match &native.expression(argument).kind {
ExprKind::Select {
expression,
dimension,
} => {
let DimensionKind::Index(index) = dimension.kind else {
return Ok(None);
};
selected.push(index);
argument = *expression;
}
_ => break,
}
}
let Ok(handle) = interface_binding::actual_handle_key(
argument,
tree,
&context.const_env,
&context.type_aliases,
) else {
return Ok(None);
};
let receiver = handle.split(['.', '[']).next().unwrap_or(&handle);
if context.get(receiver).is_some()
Comment on lines +265 to +266

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 Preserve escaped identifiers when checking shadowing

When an interface array has an escaped name containing . or [, such as \lanes.bank, splitting the normalized handle treats part of the identifier as a hierarchy separator. If a function then declares an ordinary data array with the same escaped name, context.get(receiver) misses that local declaration and the lookup incorrectly resolves the outer interface array, returning its size and emitting the extension warning instead of preserving normal data-object shadowing. Derive the receiver from the expression structure, where escaped identifier boundaries are still known, rather than splitting its serialized handle.

Useful? React with 👍 / 👎.

|| context.const_env.contains_key(receiver)
|| context.parameter_values.contains_key(receiver)
{
return Ok(None);
}
let imported = scope::imported(&tree.state);
let Some(array) = imported.interface_arrays.get(&handle) else {
return Ok(None);
};
let Some(shape) = array
.shape
.get(selected.len()..)
.filter(|shape| !shape.is_empty())
else {
return Ok(None);
};
for index in selected {
validate_index(index, tree, context)?;
}
let dimension = match dimension {
Some(id) => constant_binding::bind(id, tree, context)?
.and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env))
.ok_or_else(|| unsupported("nonconstant interface array query dimension"))?,
None => 1,
};
let value = usize::try_from(dimension)
.ok()
.and_then(|d| d.checked_sub(1))
.and_then(|index| shape.get(index))
.map(|size| integer(*size as i128))
.unwrap_or_else(|| Expr::Literal("32'sbx".into()));
warnings::append(
&mut tree.state.diagnostics.borrow_mut(),
[warnings::AnalyzerWarning::InterfaceArrayQuery {
site: procedural::source_span(native.expression(call).tokens, tree),
}],
);
Ok(Some(value))
}

fn parameter_dimension_count(
mut root: ExprId,
tree: &AnalysisContext<'_>,
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/interface_ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,7 @@ pub(super) fn signature(
module.instances.clear();
let ir = crate::analyze::analyze_source(Source {
modules: vec![module],
diagnostics: Vec::new(),
})?;
ir.modules()
.first()
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-analyzer/src/ast/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,7 @@ fn analyze_package_scope(
} else {
let ir = crate::analyze::analyze_source(Source {
modules: vec![module],
diagnostics: Vec::new(),
})?;
ir.modules().first().cloned()
};
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-sv-analyzer/src/ast/warnings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use crate::procedural::SourceSpan;
pub enum AnalyzerWarning {
/// Explicit and implementation-default time scales occur in one design.
MixedTimescale,
/// `$size` on an interface array is a compatibility extension to 20.7.
InterfaceArrayQuery { site: Option<SourceSpan> },
/// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7).
ExitOutsideProgram { site: Option<SourceSpan> },
}
Expand Down
61 changes: 61 additions & 0 deletions crates/celox-vpi/tests/run_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,3 +540,64 @@ fn source_file_is_relative_to_celox_manifest_from_another_directory() {
.unwrap();
assert!(output.status.success(), "{output:?}");
}

#[cfg(feature = "systemverilog")]
#[test]
fn interface_array_query_policy_flows_through_manifest_and_cli_overrides() {
let project = tempfile::tempdir().unwrap();
std::fs::write(
project.path().join("top.sv"),
r#"
interface Lane; logic v; endinterface
module Top;
Lane lanes[3:2]();
localparam N=$size(lanes);
initial begin
assert(N==2) else $fatal(1,"size");
$display("size=%0d",N);
$finish;
end
endmodule
"#,
)
.unwrap();
let manifest = project.path().join("celox.toml");
for (configured, overridden, success, warning) in [
(None, None, false, false),
(Some("warn"), None, true, true),
(Some("allow"), None, true, false),
(Some("warn"), Some("error"), false, false),
(Some("error"), Some("allow"), true, false),
] {
let mut config = "sources=['top.sv']\ntop='Top'\n".to_string();
if let Some(level) = configured {
config.push_str(&format!("[diagnostics]\ninterface_array_query='{level}'\n"));
}
std::fs::write(&manifest, config).unwrap();
let mut cmd = Command::new(env!("CARGO_BIN_EXE_celox"));
cmd.args(["run", "--project"])
.arg(&manifest)
.args(["--backend", "interpreter"])
.env("RUST_LOG", "warn");
if let Some(level) = overridden {
cmd.args(["--diagnostic", &format!("interface_array_query={level}")]);
}
let output = cmd.output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(
output.status.success(),
success,
"{configured:?}/{overridden:?}: {output:?}"
);
if success {
assert_eq!(output.stdout, b"size=2\n", "{output:?}");
assert_eq!(
stderr.contains("interface_array_query"),
warning,
"{stderr}"
);
} else {
assert!(stderr.contains("interface_array_query"), "{stderr}");
}
}
}
1 change: 1 addition & 0 deletions crates/celox/src/diagnostic_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ impl DiagnosticPolicy {
if matches!(
code,
"mixed_timescale"
| "interface_array_query"
| "unpacked_port_default"
| "multiple_always_ff_drivers"
| "inferred_latch"
Expand Down
Loading
Loading