Skip to content
Closed
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
41 changes: 39 additions & 2 deletions crates/celox-frontend-veryl/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use celox_testbench::{
TestbenchStatement as GenericTestbenchStatement, TestbenchTarget,
};
use fxhash::{FxHashMap as HashMap, FxHashSet};
use num_traits::ToPrimitive as _;
use num_traits::{ToPrimitive as _, Zero as _};
use veryl_analyzer::ir::{
ArrayLiteralItem, AssertKind, CasePattern, Expression, Factor, ForBound, ForRange, Function,
FunctionCall, HierAssignDestination, HierVarRef, Op as VerylOp, Statement, SystemFunctionInput,
Expand Down Expand Up @@ -1190,6 +1190,31 @@ impl ExprCompiler<'_> {
};
match expr {
Expression::Term(f) => {
// A fill literal (`'0`, `'1`, `'x`, `'z`) fills its context
// (IEEE 1800-2023 5.7.1).
if let (Some(context), Factor::Value(comptime)) = (context, f.as_ref())
&& comptime.get_value().is_ok_and(|value| value.width() == 0)
&& let Some((payload, mask, width, _)) =
crate::bitaccess::celox_value_from_comptime_in_context(
comptime,
Some(context.width),
)
{
if mask.is_zero() {
ops.push(if width <= 64 {
TbOpcode::ConstU64(payload.to_u64().unwrap_or(0))
} else {
TbOpcode::ConstWide(payload)
});
} else {
ops.push(TbOpcode::ConstLogic {
payload,
mask,
width,
});
}
return context;
}
self.emit_factor(f, ops);
let source = ValueContext {
width: self.natural_width(expr),
Expand Down Expand Up @@ -1283,6 +1308,9 @@ impl ExprCompiler<'_> {
signed: cast.source_signed,
}),
);
if cast.result_is_2state && !cast.source_is_2state {
ops.push(TbOpcode::ToTwoState);
}
let casted = ValueContext {
width: source.width,
signed: cast.result_signed,
Expand Down Expand Up @@ -1570,7 +1598,16 @@ impl ExprCompiler<'_> {
value: &veryl_analyzer::value::Value,
ops: &mut Vec<UnboundTbOpcode>,
) {
if value.width() <= 64 {
let mask = value.mask_xz();
if !mask.is_zero() {
// Celox encodes an X bit as (1, 1) and a Z bit as (0, 1); the
// analyzer has the opposite value bits.
ops.push(TbOpcode::ConstLogic {
payload: value.payload().as_ref() ^ mask.as_ref(),
mask: mask.into_owned(),
width: value.width().max(1),
});
} else if value.width() <= 64 {
ops.push(TbOpcode::ConstU64(value.payload_u64()));
} else {
ops.push(TbOpcode::ConstWide(value.payload().into_owned()));
Expand Down
28 changes: 2 additions & 26 deletions crates/celox-runtime/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,8 @@ fn bind_component<B: SimBackend>(
fn bind_assert_arg<B: SimBackend>(
backend: &Binding<'_, B>,
arg: SemanticArgument<AbsoluteAddr>,
) -> Option<ExecutableArgument<SignalRef>> {
let stored = arg
.expr
.plain_load()
.and_then(|load| stored_signal(backend, load));
) -> Option<ExecutableArgument> {
Some(ExecutableArgument {
stored,
expr: bind_expr(backend, arg.expr)?,
width: arg.width,
signed: arg.signed,
Expand All @@ -115,29 +110,10 @@ fn bind_assert_arg<B: SimBackend>(
})
}

/// The signal a plain load reads and the bit the load starts at in its
/// value: a variable, or part of one, such as an element of an array.
fn stored_signal<B: SimBackend>(
backend: &Binding<'_, B>,
load: celox_testbench::PlainLoad<&celox_testbench::StateLocation<AbsoluteAddr>>,
) -> Option<(SignalRef, usize)> {
let signal = backend.resolve_signal(&load.location.address);
let bit = load.location.byte_offset * 8
+ load.bit
+ load.element.map_or(Some(0), |element| {
element
.index
.checked_mul(element.stride_bits)?
.checked_add(element.base_bit_offset)
})?;
// Bit offsets name packed storage, not an element-strided array's.
(signal.array_layout.is_none() && bit + load.width <= signal.width).then_some((signal, bit))
}

fn bind_assert_message<B: SimBackend>(
backend: &Binding<'_, B>,
message: GenericAssertMessage<SemanticArgument<AbsoluteAddr>>,
) -> Option<ExecutableAssertMessage<SignalRef>> {
) -> Option<ExecutableAssertMessage> {
match message {
GenericAssertMessage::Formatted { template, args } => {
let args = args
Expand Down
33 changes: 31 additions & 2 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ pub(super) struct AnalysisState {
foreign_arguments: RefCell<Vec<(String, classes::specializations::BoundArguments)>>,
foreign_names: RefCell<Vec<(String, classes::specializations::BoundArguments, String)>>,
foreign_error: RefCell<Option<AnalyzerError>>,
scope: scope::State,
interfaces: interface_ast::State,
dimensions: dimensions::State,
root_subroutines: std::cell::Cell<bool>,
Expand Down Expand Up @@ -71,10 +70,15 @@ pub(super) struct AnalysisState {

/// Syntax and specialization bindings for one scope within an analysis session.
/// Child modules share the session and receive their own parameter bindings.
#[derive(Clone)]
struct AnalysisContext<'a> {
syntax_tree: &'a SyntaxTree,
state: std::rc::Rc<AnalysisState>,
parameter_overrides: Cow<'a, HashMap<String, ConstExpr>>,
/// The symbols the scope being analyzed imports (IEEE 1800-2023 26.3).
imported: Arc<scope::ScopeSymbols>,
/// The package being analyzed, inside which `p::x` names its own item.
package: Option<Arc<str>>,
}

impl<'a> AnalysisContext<'a> {
Expand All @@ -87,6 +91,8 @@ impl<'a> AnalysisContext<'a> {
syntax_tree,
state: std::rc::Rc::default(),
parameter_overrides: Cow::Borrowed(parameter_overrides),
imported: Arc::default(),
package: None,
}
}

Expand All @@ -95,6 +101,8 @@ impl<'a> AnalysisContext<'a> {
syntax_tree,
state: std::rc::Rc::default(),
parameter_overrides: Cow::Owned(HashMap::default()),
imported: Arc::default(),
package: None,
}
}

Expand All @@ -109,6 +117,8 @@ impl<'a> AnalysisContext<'a> {
..AnalysisState::default()
}),
parameter_overrides: Cow::Owned(HashMap::default()),
imported: Arc::default(),
package: None,
}
}

Expand All @@ -121,6 +131,25 @@ impl<'a> AnalysisContext<'a> {
syntax_tree,
state: self.state.clone(),
parameter_overrides: Cow::Borrowed(parameter_overrides),
imported: self.imported.clone(),
package: self.package.clone(),
}
}

/// This context analyzing a scope that imports `symbols`.
fn importing(&self, symbols: Arc<scope::ScopeSymbols>) -> Self {
Self {
imported: symbols,
..self.clone()
}
}

/// This context analyzing package `name`, inside which `name::x` names
/// its own item `x`.
fn in_package(&self, name: &str) -> Self {
Self {
package: Some(name.into()),
..self.clone()
}
}
}
Expand Down Expand Up @@ -782,10 +811,10 @@ impl Module {
};
let specialization =
syntax_tree.child(syntax_tree.syntax_tree, applicable_parameter_overrides);
let specialization = specialization.importing(imported.clone());
let syntax_tree = &specialization;
// The collectors below each elaborate the same generate scopes.
let _elaborations = generate::memoize(syntax_tree);
let _imported = scope::install(&syntax_tree.state, imported.clone());
let with_imported = |mut functions: const_functions::ConstantFunctions| {
functions.extend_missing(&imported.constant_functions);
functions
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/array_parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ fn array_parameters_from_declaration(
) -> Result<Vec<ArrayParameter>, AnalyzerError> {
let mut parameters = Vec::new();
for &native in authored {
let bound = scope::imported(&tree.state)
let bound = scope::imported(tree)
.pattern_parameter_bindings
.get(&native.id)
.cloned();
Expand Down
6 changes: 3 additions & 3 deletions crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option<String>
}
}
// A class an import makes visible (IEEE 1800-2023 26.3).
let imported = scope::imported(&tree.state);
let imported = scope::imported(tree);
if let Some(alias) = imported.aliases.get(name) {
let class = imported
.type_aliases
Expand Down Expand Up @@ -662,7 +662,7 @@ pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option<Type
/// Class `name` as the scope that declares it laid it out, when the current
/// scope uses that scope (see `scope::ScopeSymbols::classes`).
fn imported(tree: &AnalysisContext<'_>, name: &str) -> Option<Rc<Class>> {
scope::imported(&tree.state)
scope::imported(tree)
.classes
.iter()
.find(|class| class.name == name)
Expand All @@ -675,7 +675,7 @@ pub(super) fn visible_classes(tree: &AnalysisContext<'_>) -> Vec<String> {
let mut names = scope_declarations(tree)
.flat_map(|declaration| specializations_of(tree, declaration))
.collect::<Vec<_>>();
for class in &scope::imported(&tree.state).classes {
for class in &scope::imported(tree).classes {
if !names.contains(&class.name) {
names.push(class.name.clone());
}
Expand Down
9 changes: 7 additions & 2 deletions crates/celox-sv-analyzer/src/ast/classes/foreign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,10 +317,12 @@ impl Registry {
syntax_tree: &owner.tree,
state: state.clone(),
parameter_overrides: Cow::Owned(HashMap::default()),
imported: Arc::default(),
// Inside the package, `p::x` names its own item `x`.
package: Some(name.into()),
};
let _timescales =
timescales::install_for_tree(&state.timescales, owner.timescales.clone(), &owner.tree)?;
let _package = scope::enter_package(&state, name);
let mut imports = owner.imports.clone();
if let Some(caller) = caller {
// Preserve the owner's existing bindings when caller metadata also
Expand Down Expand Up @@ -382,7 +384,10 @@ impl Registry {
None,
)?;
if self_qualified {
drop(_package);
let context = AnalysisContext {
package: None,
..context.clone()
};
// Class statics already have qualified names. Unlike ordinary
// package variables, their new declarations would collide with
// the first pass's imported storage.
Expand Down
10 changes: 5 additions & 5 deletions crates/celox-sv-analyzer/src/ast/classes/specializations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ fn inherit(
if let Some(scope) = tree.state.foreign.declarations(name) {
scope.apply(env, aliases);
}
if let Some(members) = scope::imported(&tree.state).class_member_types.get(name) {
if let Some(members) = scope::imported(tree).class_member_types.get(name) {
aliases.extend(members.clone());
}
}
Expand Down Expand Up @@ -357,7 +357,7 @@ pub(in crate::ast) fn member_type(
.flatten()
})
.or_else(|| {
scope::imported(&tree.state)
scope::imported(tree)
.class_member_types
.get(name)?
.get(member)
Expand All @@ -372,7 +372,7 @@ pub(in crate::ast) fn member_type(
pub(in crate::ast) fn export_member_types(
tree: &AnalysisContext<'_>,
) -> HashMap<String, HashMap<String, Type>> {
let imported = scope::imported(&tree.state);
let imported = scope::imported(tree);
let mut result = imported.class_member_types.clone();
for declaration in super::scope_declarations(tree) {
for name in super::specializations_of(tree, declaration) {
Expand Down Expand Up @@ -1187,7 +1187,7 @@ pub(in crate::ast) fn scoped_type(
None => Some(class),
}
} else {
let qualified = scope::qualified_name(&tree.state, &scope, &member);
let qualified = scope::qualified_name(tree, &scope, &member);
return Ok(context.type_aliases.get(&qualified).cloned().or_else(
|| match qualified.as_str() {
"std::process" => Some(super::handle(super::super::processes::CLASS)),
Expand Down Expand Up @@ -1465,7 +1465,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens
for name in tree.state.foreign.names() {
names.entry(name.clone()).or_insert(name);
}
for (alias, name) in &scope::imported(&tree.state).aliases {
for (alias, name) in &scope::imported(tree).aliases {
if tree.state.foreign.contains(name) {
names.entry(alias.clone()).or_insert(name.clone());
}
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/comb_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub(super) fn comb_processes_from_scope(
let active = generate::items(syntax_tree, const_env, &packed_dimensions.type_aliases)?;
let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals);
for (creation_order, item) in active.iter().enumerate() {
let _interface_scope = item.interface_scope();
let syntax_tree = &item.scoped(syntax_tree);
if !matches!(
&syntax_tree.declarations().body_item(item.id).kind,
celox_sv_syntax::BodyItemKind::Assign(_)
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/const_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ pub(super) fn symbolic_module_constant_functions(
symbolic_parameters,
)
});
roots.extend_missing(&scope::imported(&tree.state).constant_functions);
roots.extend_missing(&scope::imported(tree).constant_functions);
let _installed = install(&tree.state, roots);
collect_module_constant_functions(
tree,
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/constant_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ fn bind_in_context(
let name = arguments
.first()
.and_then(|a| a.value)
.and_then(|id| expression_binding::native_name(&tree.state, id, native))
.and_then(|id| expression_binding::native_name(tree, id, native))
.ok_or_else(|| AnalyzerError::InvalidSystemTfCall {
name: "$isunbounded".into(),
detail: "argument must name a value parameter".into(),
Expand Down
8 changes: 2 additions & 6 deletions crates/celox-sv-analyzer/src/ast/constants/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,8 @@ fn native_constant_calls_preserve_contextual_operand_shapes() {
.expression_nodes()
.find_map(|(id, expr)| match expr.kind {
celox_sv_syntax::ExprKind::Call { expression, .. }
if expression_binding::native_name(
&tree.state,
expression,
tree.declarations(),
)
.as_deref()
if expression_binding::native_name(&tree, expression, tree.declarations())
.as_deref()
== Some("f") =>
{
Some(id)
Expand Down
4 changes: 2 additions & 2 deletions crates/celox-sv-analyzer/src/ast/declarations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ pub(super) fn parameters_from_scope(
) -> Result<Vec<Parameter>, AnalyzerError> {
let mut parameters = Vec::new();
let mut environment = parameters::ParameterEnvironment::new(
&syntax_tree.state,
syntax_tree,
&parameters,
base_const_env,
&parameters::ownership::scope_names(syntax_tree)?,
Expand Down Expand Up @@ -286,7 +286,7 @@ pub(super) fn signals_from_scope_with_declaration_ranges(
) -> Result<Vec<Signal>, AnalyzerError> {
let mut signals = Vec::new();
for mut item in generate::items(syntax_tree, const_env, type_aliases)? {
let _interface_scope = item.interface_scope();
let syntax_tree = &item.scoped(syntax_tree);
if preserve_parameters {
let names = item.env.keys().cloned().collect::<Vec<_>>();
for name in names {
Expand Down
4 changes: 2 additions & 2 deletions crates/celox-sv-analyzer/src/ast/dimensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ pub(super) use query_binding::{
};

/// Imported interface member shapes remain visible during native discovery.
fn extend_interface_dimensions(state: &AnalysisState, dimensions: &mut PackedDimensions) {
let imported = scope::imported(state);
fn extend_interface_dimensions(tree: &AnalysisContext<'_>, dimensions: &mut PackedDimensions) {
let imported = scope::imported(tree);
if imported.interface_members.is_empty() {
return;
}
Expand Down
Loading
Loading