diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 709bd4be783..01eb4020587 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -342,10 +342,38 @@ pub fn eval_const_expr_with_types( constants: &HashMap, types: &HashMap, ) -> Option { + // Substitution only replaces the identifiers of typed constants. + if !has_typed_constant(expr, constants, types) { + return eval_const_expr(expr, constants); + } let expr = substitute_typed_constants(expr.clone(), constants, types); eval_const_expr(&expr, constants) } +/// Whether `expr` names a constant that has a type, which +/// [`substitute_typed_constants`] replaces with a sized literal. +fn has_typed_constant( + expr: &ConstExpr, + constants: &HashMap, + types: &HashMap, +) -> bool { + let has = |expr| has_typed_constant(expr, constants, types); + match expr { + ConstExpr::Ident(name) => constants.contains_key(name) && types.contains_key(name), + ConstExpr::Literal(_) => false, + ConstExpr::SelectRange { expr, msb, lsb, .. } => has(expr) || has(msb) || has(lsb), + ConstExpr::Select { expr, bit } => has(expr) || has(bit), + ConstExpr::Function { args, .. } => args.iter().any(has), + ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => has(expr), + ConstExpr::Binary { left, right, .. } => has(left) || has(right), + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => has(condition) || has(then_expr) || has(else_expr), + } +} + /// Evaluate a numeric constant expression in a real context. /// /// Integral subexpressions retain their integer arithmetic before conversion. @@ -1588,6 +1616,70 @@ pub(crate) fn integral_literal_type_metadata(value: &str) -> Option<(usize, bool } pub fn parse_integral_literal(value: &str) -> Option { + parse_small_literal(value).or_else(|| parse_any_integral_literal(value)) +} + +/// Parses a literal of plain digits whose value fits in 128 bits, the form +/// constant substitution produces, without big-integer arithmetic. `None` +/// leaves the literal to [`parse_any_integral_literal`], which gives the +/// same result for the literals this accepts. +fn parse_small_literal(value: &str) -> Option { + let Some((size, based)) = value.split_once('\'') else { + if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let value = value.parse::().ok()?; + return Some(IntegralLiteral { + width: (128 - value.leading_zeros() as usize).max(32), + signed: true, + value: BigUint::from(value), + mask: BigUint::default(), + }); + }; + if !size.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + let width = if size.is_empty() { + None + } else { + Some(size.parse::().ok()?.max(1)) + }; + let (signed, based) = match based.as_bytes().first()? { + b's' | b'S' => (true, &based[1..]), + _ => (false, based), + }; + let (radix, bits_per_digit) = match based.as_bytes().first()? { + b'b' | b'B' => (2, 1), + b'o' | b'O' => (8, 3), + b'd' | b'D' => (10, 0), + b'h' | b'H' => (16, 4), + _ => return None, + }; + let digits = &based[1..]; + if digits.is_empty() || !digits.bytes().all(|byte| (byte as char).is_digit(radix)) { + return None; + } + let value = u128::from_str_radix(digits, radix).ok()?; + let natural_width = if bits_per_digit == 0 { + (128 - value.leading_zeros() as usize).max(32) + } else { + digits.len().checked_mul(bits_per_digit)? + }; + let width = width.unwrap_or_else(|| natural_width.max(32)); + let value = if width < 128 { + value & ((1u128 << width) - 1) + } else { + value + }; + Some(IntegralLiteral { + width, + signed, + value: BigUint::from(value), + mask: BigUint::default(), + }) +} + +fn parse_any_integral_literal(value: &str) -> Option { if value.trim().starts_with('"') { return parse_string_literal(value.trim()); } @@ -1889,6 +1981,104 @@ fn extension_for_leading_digit(ch: char) -> (bool, bool) { mod literal_tests { use super::*; + /// Expressions without typed constants evaluate as their substituted + /// copies do, and typed constants still take their declared type. + #[test] + fn typed_evaluation_substitutes_only_typed_constants() { + let lit = |text: &str| ConstExpr::Literal(text.into()); + let ident = |name: &str| ConstExpr::Ident(name.into()); + let binary = |left, op, right| ConstExpr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let constants: HashMap = [("N".to_string(), 255), ("M".to_string(), 3)] + .into_iter() + .collect(); + let types: HashMap = + [("N".to_string(), (8, false))].into_iter().collect(); + let untyped = [ + lit("7"), + binary(lit("4'hf"), BinaryOp::Add, lit("1")), + binary(ident("M"), BinaryOp::Mul, lit("8")), + binary(lit("8'sd200"), BinaryOp::Lt, lit("0")), + ]; + for expr in &untyped { + assert!(!has_typed_constant(expr, &constants, &types)); + let substituted = substitute_typed_constants(expr.clone(), &constants, &types); + assert_eq!( + eval_const_expr_with_types(expr, &constants, &types), + eval_const_expr(&substituted, &constants), + "{expr:?}" + ); + } + // An 8-bit unsigned N wraps to 0 when incremented in its own width. + let typed = binary(ident("N"), BinaryOp::Add, lit("8'd1")); + assert!(has_typed_constant(&typed, &constants, &types)); + assert_eq!( + eval_const_expr_with_types(&typed, &constants, &types), + Some(0) + ); + assert_eq!(eval_const_expr(&typed, &constants), Some(256)); + } + + /// The fast parser of plain-digit literals agrees with the general one. + #[test] + fn small_literals_parse_like_any_literal() { + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |bound: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % bound as u64) as usize + }; + let sizes = [ + "", "0", "1", "3", "7", "8", "16", "31", "32", "33", "63", "64", "65", "100", "127", + "128", "129", "200", + ]; + let bases = ["b", "o", "d", "h", "B", "O", "D", "H"]; + let mut fast = 0; + for _ in 0..20_000 { + let base = bases[next(bases.len())]; + let radix = match base.to_ascii_lowercase().as_str() { + "b" => 2, + "o" => 8, + "d" => 10, + _ => 16, + }; + let digits: String = (0..1 + next(42)) + .map(|_| { + // Mostly leading zeros or small values, sometimes a + // digit the general parser treats specially. + match next(40) { + 0 => 'x', + 1 => 'z', + 2 => '_', + _ => std::char::from_digit(next(radix) as u32, radix as u32).unwrap(), + } + }) + .collect(); + let signing = ["", "s", "S"][next(3)]; + let literal = match next(4) { + 0 => digits + .chars() + .filter(char::is_ascii_digit) + .collect::(), + _ => format!("{}'{signing}{base}{digits}", sizes[next(sizes.len())]), + }; + let small = parse_small_literal(&literal); + fast += usize::from(small.is_some()); + if let Some(small) = small { + assert_eq!( + Some(small), + parse_any_integral_literal(&literal), + "{literal}" + ); + } + } + assert!(fast > 5_000, "{fast} literals took the fast path"); + } + #[test] fn evaluates_deep_constant_casts_without_repeated_context_walks() { for (value, expected) in [("32'h12", "32'h12"), ("32'h1z", "32'h1x")] {