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
15 changes: 13 additions & 2 deletions crates/celox-sv-analyzer/src/ast/constant_binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,9 +267,20 @@ fn bind_in_context(
})
{
let value = indexed_expression(id, native, tree, query_dimensions)?;
values.push(
let value = if query_dimensions
.array_parameter_values
.contains_key(&name_key)
{
selects::indexed_expression_value(
&tree.state,
value,
query_dimensions,
)
} else {
expr_to_index_const(&tree.state, value, query_dimensions)
.ok_or_else(|| unsupported("parameter selection shape"))?,
};
values.push(
value.ok_or_else(|| unsupported("parameter selection shape"))?,
);
continue;
}
Expand Down
86 changes: 82 additions & 4 deletions crates/celox-sv-analyzer/src/ast/instances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,60 @@ pub(crate) fn normalize_identifier(text: &str) -> String {
}
}

/// Keep whole-array conditional arguments out of the scalar constant path.
/// Traverse branch types iteratively, including branches a constant condition
/// does not select. Array sizes and integral element types must agree.
fn array_argument_shape(
root: celox_sv_syntax::ExprId,
tree: &AnalysisContext<'_>,
dims: &PackedDimensions,
) -> Option<VariableDimensions> {
use celox_sv_syntax::{ExprId, ExprKind};
enum Job {
Enter(ExprId),
Conditional,
}
let native = tree.declarations();
let mut jobs = vec![Job::Enter(root)];
let mut values = Vec::<VariableDimensions>::new();
while let Some(job) = jobs.pop() {
match job {
Job::Enter(id) => {
let id = expression_binding::ungroup(id, native);
if let ExprKind::Conditional {
then_expression,
else_expression,
..
} = native.expression(id).kind
{
jobs.push(Job::Conditional);
jobs.push(Job::Enter(else_expression));
jobs.push(Job::Enter(then_expression));
} else {
values.push(array_compatibility::native_unpacked_shape(
id, native, dims,
)?);
}
}
Job::Conditional => {
let right = values.pop()?;
let left = values.pop()?;
let left_type = array_compatibility::unpacked_array_type(&tree.state, &left, dims)?;
let right_type =
array_compatibility::unpacked_array_type(&tree.state, &right, dims)?;
if left_type != right_type
|| left.packed != right.packed
|| left.members != right.members
{
return None;
}
values.push(left);
}
}
}
values.pop()
}

/// One `.name(expr)` binding: a `parameter type` when `expr` is a data type or
/// the name of a type, a value otherwise.
fn parameter_override(
Expand Down Expand Up @@ -383,11 +437,35 @@ fn parameter_override(
}
pending.extend(parameters::skipped::children(id, declarations));
}
if let Some(shape) =
array_compatibility::native_unpacked_shape(native, declarations, packed_dimensions)
{
if let Some(shape) = array_argument_shape(native, syntax_tree, packed_dimensions) {
// Aggregate conditional expressions require equivalent branch types
// (11.4.11). A known condition selects a whole array before element
// binding; treating it as a packed mux would use the wrong X merge rule.
let mut selected = root;
while let ExprKind::Conditional {
condition,
then_expression,
else_expression,
} = declarations.expression(selected).kind
{
let condition = constant_binding::bind(condition, syntax_tree, packed_dimensions)?
.and_then(|value| {
eval_ast_const_expr(&syntax_tree.state, &value, &packed_dimensions.const_env)
})
.ok_or_else(|| {
unsupported("nonconstant or ambiguous condition in array parameter argument")
})?;
selected = expression_binding::ungroup(
if condition != 0 {
then_expression
} else {
else_expression
},
declarations,
);
}
let pattern =
bound_patterns::from_array_parameter(native, syntax_tree, packed_dimensions, &shape)?;
bound_patterns::from_array_parameter(selected, syntax_tree, packed_dimensions, &shape)?;
let mut bound = ParameterOverride::new(name, None);
bound.bound_pattern = Some(pattern);
return Ok(bound);
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast/packed_structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ mod selects;
#[cfg(test)]
mod tests;

pub(super) use layout::native_type;
pub(super) use layout::{AggregateKind, native_type};
pub(super) use selects::{select_member, whole_member};

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down
20 changes: 14 additions & 6 deletions crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

use super::*;

#[derive(Clone, Copy)]
pub(in crate::ast) enum AggregateKind {
Struct,
HardUnion,
SoftUnion,
}

/// Freeze member bounds in the declaration environment before generated scopes
/// can shadow their parameter names. Shared by both syntax owners.
pub(in crate::ast) fn capture_member_type(
Expand Down Expand Up @@ -30,7 +37,7 @@ pub(in crate::ast) fn capture_member_type(
/// Syntax-independent IEEE7.2.1/7.3.1 layout kernel.
pub(in crate::ast) fn native_type(
state: &AnalysisState,
union: bool,
kind: AggregateKind,
signed: bool,
owner: Arc<str>,
fields: Vec<(String, Type)>,
Expand All @@ -52,11 +59,11 @@ pub(in crate::ast) fn native_type(
})
})
.collect::<Option<Vec<_>>>()?;
finish_type(state, union, signed, members, ranges, env)
finish_type(state, kind, signed, members, ranges, env)
}
fn finish_type(
state: &AnalysisState,
union: bool,
kind: AggregateKind,
signed: bool,
mut members: Vec<PackedMember>,
ranges: Vec<PackedRange>,
Expand All @@ -66,13 +73,14 @@ fn finish_type(
// The first declared member occupies the most significant bits.
for member in members.iter_mut().rev() {
let member_width = expr_type_from_type(state, &member.r#type, const_env)?.width;
if union {
if !matches!(kind, AggregateKind::Struct) {
// IEEE 1800-2023 7.3.1: hard packed members share all bits
// and must have the same width.
if width != 0 && width != member_width {
if matches!(kind, AggregateKind::HardUnion) && width != 0 && width != member_width {
return None;
}
width = member_width;
// Soft members are right-justified in the largest member width.
width = width.max(member_width);
} else {
member.offset = width;
width = width.checked_add(member_width)?;
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ fn preserves_layout_signedness_and_state_kind() {
mixed_t mixed;
union packed signed { logic signed [7:0] a; bit [7:0] b; } mixed_union;
union packed { bit [129:0] a; bit [129:0] b; } wide_union;
union soft { bit [3:0] narrow_value; bit [15:0] wide_value; } soft_union;
union soft packed signed { logic [15:0] wide_value; bit [3:0] narrow_value; } signed_soft;
union soft { bit [2:0] narrow_value; union soft { bit [129:0] wide; bit flag; } nested; } nested_soft;
signed_t signed_value;
struct packed { byte a; shortint b; int c; longint d; } atoms;
endmodule
Expand All @@ -26,6 +29,9 @@ fn preserves_layout_signedness_and_state_kind() {
("atoms", 120, false, ir::TypeKind::Bit),
("mixed_union", 8, true, ir::TypeKind::Logic),
("wide_union", 130, false, ir::TypeKind::Bit),
("soft_union", 16, false, ir::TypeKind::Bit),
("signed_soft", 16, true, ir::TypeKind::Logic),
("nested_soft", 130, false, ir::TypeKind::Bit),
] {
let ty = signals
.iter()
Expand All @@ -44,6 +50,9 @@ fn rejects_invalid_or_unsupported_struct_shapes() {
"struct { logic a; } value;",
"union packed { logic a; logic [1:0] b; } value;",
"union tagged packed { logic a; logic b; } value;",
"union soft { real a; bit [63:0] b; } value;",
"union soft { logic a[2]; logic b; } value;",
"union soft { logic a; logic a; } value;",
"union packed { logic a; logic b; } value; always_comb value = '{a: 1'b1, b: 1'b0};",
"struct packed { real a; } value;",
"struct packed { logic a[2]; } value;",
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-sv-analyzer/src/ast/selects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1058,6 +1058,9 @@ fn substitute_indexed_parameter_values(
expression: Expr,
dimensions: &PackedDimensions,
) -> Expr {
// Unpacked parameter values use the declared array layout, while selections
// have already been translated to bit offsets in that layout.
let expression = substitute_expr_idents(expression, &dimensions.array_parameter_values);
// Known values come from the current environment, which may include a
// generate index shadowing a parameter. Supply expressions only for values
// absent from that numeric environment, including X/Z parameters.
Expand Down
14 changes: 12 additions & 2 deletions crates/celox-sv-analyzer/src/ast/type_binding/binding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub(in crate::ast) fn bind_in(
Aggregate {
owner: Arc<str>,
union: bool,
soft: bool,
signed: bool,
names: Vec<String>,
ranges: Vec<PackedRange>,
Expand Down Expand Up @@ -89,11 +90,12 @@ pub(in crate::ast) fn bind_in(
}
DataTypeKind::Struct {
union,
soft,
tagged,
packed,
fields,
} => {
if !packed || *tagged {
if (!packed && !soft) || *tagged {
return Ok(None);
}
let mut names = Vec::new();
Expand Down Expand Up @@ -125,6 +127,7 @@ pub(in crate::ast) fn bind_in(
jobs.push(Job::Aggregate {
owner,
union: *union,
soft: *soft,
signed: data.signed.unwrap_or(false),
names,
ranges,
Expand Down Expand Up @@ -169,6 +172,7 @@ pub(in crate::ast) fn bind_in(
Job::Aggregate {
owner,
union,
soft,
signed,
names,
ranges,
Expand All @@ -180,7 +184,13 @@ pub(in crate::ast) fn bind_in(
let fields = names.into_iter().zip(values.split_off(start)).collect();
let Some(ty) = packed_structs::native_type(
&tree.state,
union,
if soft {
packed_structs::AggregateKind::SoftUnion
} else if union {
packed_structs::AggregateKind::HardUnion
} else {
packed_structs::AggregateKind::Struct
},
signed,
owner,
fields,
Expand Down
18 changes: 18 additions & 0 deletions crates/celox-sv-syntax/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,12 @@ fn lex_with_context(
"::", "+:", "-:", "~&", "~|", "~^", "^~", "->", "=>", "*>", "##", "@@", ":=",
":/", ".*", "(*", "*)",
];
// `:` followed by a comment (`3'b0://`, `x:/*`) is not `:/`.
let comment_after_colon = source[at..].starts_with(":/")
&& matches!(bytes.get(at + 2), Some(b'/' | b'*'));
let length = OPERATORS
.iter()
.filter(|op| !(comment_after_colon && **op == ":/"))
.find(|op| source[at..].starts_with(**op))
.map_or(1, |op| op.len());
at += length;
Expand Down Expand Up @@ -403,6 +407,20 @@ mod tests {
}
}

#[test]
fn colon_before_comment_is_not_dist_weight() {
let text = "3'b0://c\n3'b1:/*c*/ x :/ 2";
let mut sources = SourceMap::default();
let file = sources.add("colon.sv", text);
let tokens = lex(&sources, file).unwrap();
let significant = tokens
.iter()
.filter(|token| !token.is_trivia())
.map(|token| token.text.as_str())
.collect::<Vec<_>>();
assert_eq!(significant, ["3'b0", ":", "3'b1", ":", "x", ":/", "2"]);
}

#[test]
fn strings_and_longest_operators_preserve_lexical_boundaries() {
let text = "\"continued\\\r\nstring\" \"continued\\\nstring\" \"\"\"multi\nline\"\"\" <<<= >>>= |-> |=> ->> <->";
Expand Down
1 change: 1 addition & 0 deletions crates/celox-sv-syntax/src/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ pub enum DataTypeKind {
TypeOf(ExprId),
Struct {
union: bool,
soft: bool,
tagged: bool,
packed: bool,
fields: Vec<Field>,
Expand Down
38 changes: 38 additions & 0 deletions crates/celox-sv-syntax/src/parser/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,33 @@ impl Parser<'_> {
self.at += 1;
}
}
// A macro can supply the digits of a based literal
// (`5'd`WIDTH`), leaving them in separate tokens; a
// body such as `0f` lexes as `0` and `f`, adjacent
// in their spelling.
if let ExprKind::Literal(value) = &mut kind
&& numeric
&& based_without_digits(value)
{
let mut previous: Option<crate::source::Span> = None;
while let Some(next) = self.token()
&& matches!(
next.kind,
TokenKind::Number | TokenKind::Identifier
)
&& next.text.bytes().all(|b| {
b.is_ascii_alphanumeric() || matches!(b, b'_' | b'?')
})
&& previous.is_none_or(|span| {
span.file == next.origin.spelling.file
&& span.end == next.origin.spelling.start
})
{
value.push_str(&next.text);
previous = Some(next.origin.spelling);
self.at += 1;
}
}
if numeric
&& matches!(&kind, ExprKind::Literal(value) if !super::numbers::literal(value))
{
Expand Down Expand Up @@ -1591,6 +1618,17 @@ pub(super) fn builtin(word: &str) -> bool {
)
}

/// A sized or unsized based literal spelled up to its base, such as `5'd`.
fn based_without_digits(value: &str) -> bool {
let based = value
.trim_start_matches(|c: char| c.is_ascii_digit() || c == '_' || c.is_ascii_whitespace());
let Some(base) = based.strip_prefix('\'') else {
return false;
};
let base = base.strip_prefix(['s', 'S']).unwrap_or(base);
matches!(base, "b" | "B" | "o" | "O" | "d" | "D" | "h" | "H")
}

fn constant_dimension_operands(dimension: &Dimension, pending: &mut Vec<ExprId>) {
match dimension.kind {
DimensionKind::Index(value) => pending.push(value),
Expand Down
Loading
Loading