diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 9ebb81097db..d27a3367137 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -302,6 +302,7 @@ pub enum HostRequestKind { Plusargs, FileIo, Vcd, + Scan, } impl HostRequestKind { @@ -311,6 +312,7 @@ impl HostRequestKind { Self::Plusargs => 1u64, Self::FileIo => 2, Self::Vcd => 3, + Self::Scan => 4, }; (family << 32) | site as u64 } @@ -321,6 +323,7 @@ impl HostRequestKind { 1 => Self::Plusargs, 2 => Self::FileIo, 3 => Self::Vcd, + 4 => Self::Scan, _ => return None, }; Some((family, request as u32)) @@ -1452,6 +1455,7 @@ mod tests { HostRequestKind::Plusargs, HostRequestKind::FileIo, HostRequestKind::Vcd, + HostRequestKind::Scan, ] { for site in [0, 1, u32::MAX] { assert_eq!( @@ -1460,7 +1464,7 @@ mod tests { ); } } - for invalid in [0, u32::MAX as u64, 4u64 << 32, 1u64 << 63] { + for invalid in [0, u32::MAX as u64, 5u64 << 32, 1u64 << 63] { assert_eq!(HostRequestKind::decode(invalid), None); } assert_eq!( diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index e21ddff24de..612d4cd26c3 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5988,6 +5988,8 @@ fn lower_bit_vector_function_slt( | SystemFunction::Fgetc | SystemFunction::Ungetc | SystemFunction::Feof + | SystemFunction::Sscanf + | SystemFunction::Fscanf | SystemFunction::Timeunit | SystemFunction::Timeprecision | SystemFunction::Isunbounded diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index f5068f71852..b58c9900e4f 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,6 +11,7 @@ mod file_io; mod fread; +mod scan; use super::procedural::*; use super::*; @@ -854,6 +855,15 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.file_function(*function, args)?, + Expr::Call { + callee: + sv::ir::Callee::System( + function + @ (sv::ir::SystemFunction::Sscanf | sv::ir::SystemFunction::Fscanf), + ), + args, + .. + } => self.scan_function(*function, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), args, diff --git a/crates/celox-frontend-sv/src/lowering/ff/scan.rs b/crates/celox-frontend-sv/src/lowering/ff/scan.rs new file mode 100644 index 00000000000..8c30911ec6c --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/scan.rs @@ -0,0 +1,112 @@ +use super::*; +use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + +impl Ff<'_, '_> { + pub(super) fn scan_function( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use sv::ir::Expr; + if self.kernel.is_none() { + return Err(unsupported(format!( + "{} requires Simulation scheduled execution", + function.name() + ))); + } + let mut inputs = Vec::new(); + for (position, argument) in args.iter().take(2).enumerate() { + let argument = argument + .as_ref() + .ok_or_else(|| unsupported("omitted scan source/format"))?; + let argument = self.hoist(argument)?; + let width = self + .m + .comparison_width(&argument, &argument) + .ok_or_else(|| { + unsupported("scan source/format must be a packed integral or literal string") + })?; + // File descriptors are 32-bit packed values (21.3.1), even when + // the actual expression has a wider integral type. + let width = if function == sv::ir::SystemFunction::Fscanf && position == 0 { + 32 + } else { + width + }; + let (id, _) = self.host_hidden("scan_input", &argument, width, false, true)?; + inputs.push(HostRequestValue { + float_precision: None, + id, + width, + signed: false, + is_string: function != sv::ir::SystemFunction::Fscanf || position != 0, + }); + } + let (result_id, result_name) = self.m.temp("scan_count", 32, true, false); + let mut results = vec![HostRequestValue { + float_precision: None, + id: result_id, + width: 32, + signed: true, + is_string: false, + }]; + let mut destinations = Vec::new(); + for argument in args.iter().skip(2) { + let argument = argument + .as_ref() + .ok_or_else(|| unsupported("omitted scan destination"))?; + let (lvalues, _) = self.capture_system_actual(argument)?; + let width=self.m.comparison_width(argument,argument).ok_or_else(||unsupported("scan destination must be an integral variable; string/real outputs are unsupported"))?; + let (id, name) = self.m.temp("scan_value", width, false, true); + results.push(HostRequestValue { + float_precision: None, + id, + width, + signed: false, + is_string: false, + }); + destinations.push((lvalues, Expr::Ident(name))); + } + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Scan) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: 0, + kind: HostRequestKind::Scan, + requires_timed_simulation: false, + operation: u32::from(function == sv::ir::SystemFunction::Fscanf), + args: inputs, + results, + strings: Vec::new(), + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Scan, site)) + .map_err(kernel_error)?; + // A failed or ignored output must not overwrite a previously assigned + // alias. Scan assignments are contiguous even with suppressed fields. + for (index, (lvalues, value)) in destinations.into_iter().enumerate() { + let condition = Expr::Binary { + left: Box::new(Expr::Ident(result_name.clone())), + op: sv::ir::BinaryOp::Gt, + right: Box::new(Expr::Literal(format!("32'sd{index}"))), + }; + let (condition, _) = self.eval_truth(&condition)?; + let write = self.b.new_block(); + let join = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: condition, + true_block: (write, Vec::new()), + false_block: (join, Vec::new()), + }); + self.b.switch_to_block(write); + match lvalues.as_slice() { + [one] => self.assign(one, &value)?, + parts => self.assign_concat(parts, &value)?, + }; + self.jump(join); + self.b.switch_to_block(join); + } + Ok(Expr::Ident(result_name)) + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index a2ebf2d979c..dfa181a6ef4 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -9,6 +9,7 @@ pub mod file_io; pub mod parallel; pub mod plusargs; mod reflection; +pub mod scan; mod schedule; pub mod scheduler; mod simulation; diff --git a/crates/celox-runtime/src/scan.rs b/crates/celox-runtime/src/scan.rs new file mode 100644 index 00000000000..5f7acc7bd2d --- /dev/null +++ b/crates/celox-runtime/src/scan.rs @@ -0,0 +1,441 @@ +//! Integral formatted input (IEEE 1800-2023 21.3.4.3). +//! +//! Supported conversions are `%d`, `%h`/`%x`, `%o`, `%b`, and `%c`, with +//! assignment suppression and maximum numeric field widths. `%c` reads one +//! byte without skipping whitespace. Numeric assignments retain the low bits +//! of the destination; radix X/Z digits retain their four-state representation. +//! String, real, raw binary, and time-format conversions are diagnosed rather +//! than partially interpreted. +use num_bigint::BigUint; +use std::io; + +/// A scanner uses at most one byte of pushback and leaves mismatching input unread. +pub trait Input { + fn read_byte(&mut self) -> io::Result>; + fn unread_byte(&mut self, byte: u8) -> io::Result<()>; +} + +pub struct SliceInput<'a> { + bytes: &'a [u8], + position: usize, +} +impl<'a> SliceInput<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Self { bytes, position: 0 } + } + pub fn position(&self) -> usize { + self.position + } +} +impl Input for SliceInput<'_> { + fn read_byte(&mut self) -> io::Result> { + let byte = self.bytes.get(self.position).copied(); + self.position += usize::from(byte.is_some()); + Ok(byte) + } + fn unread_byte(&mut self, byte: u8) -> io::Result<()> { + if self.position == 0 || self.bytes[self.position - 1] != byte { + return Err(io::ErrorKind::InvalidInput.into()); + } + self.position -= 1; + Ok(()) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +/// Four-state bits use `(value, mask)`: X is `(1, 1)`, Z is `(0, 1)`. +pub struct Value { + pub value: BigUint, + pub mask: BigUint, +} +#[derive(Debug, PartialEq, Eq)] +pub struct Outcome { + pub count: i32, + pub values: Vec>, +} +#[derive(Debug)] +enum Directive { + Space, + Literal(u8), + Percent, + Number { + code: u8, + width: Option, + suppress: bool, + }, +} + +fn format_directives(format: &[u8]) -> Result, String> { + let mut directives = Vec::new(); + let mut position = 0; + while let Some(&byte) = format.get(position) { + position += 1; + if byte.is_ascii_whitespace() { + directives.push(Directive::Space); + continue; + } + if byte != b'%' { + directives.push(Directive::Literal(byte)); + continue; + } + if format.get(position) == Some(&b'%') { + position += 1; + directives.push(Directive::Percent); + continue; + } + let suppress = format.get(position) == Some(&b'*'); + position += usize::from(suppress); + let start = position; + let mut maximum = 0usize; + while let Some(digit) = format.get(position).filter(|byte| byte.is_ascii_digit()) { + maximum = maximum + .checked_mul(10) + .and_then(|v| v.checked_add((digit - b'0') as usize)) + .ok_or("scan field width is too large")?; + position += 1; + } + let width = (position != start).then_some(maximum); + if width == Some(0) { + return Err("scan field width must be positive".into()); + } + let code = format + .get(position) + .copied() + .ok_or("incomplete scan conversion")? + .to_ascii_lowercase(); + position += 1; + match code { + b'd'|b'h'|b'x'|b'o'|b'b'|b'c'=>{}, + b's'=>return Err("scan string output conversion %s is unsupported; only integral numeric/character output is supported".into()), + b'e'|b'f'|b'g'=>return Err("scan real output conversions are unsupported".into()), + b't'=>return Err("scan %t requires unsupported $timeformat scaling".into()), + _=>return Err(format!("unsupported scan conversion %{}",code as char)), + } + directives.push(Directive::Number { + code, + width, + suppress, + }); + } + Ok(directives) +} + +/// Validate formats before consuming input. Excess output arguments are ignored. +pub fn validate_format(format: &[u8], destinations: usize) -> Result<(), String> { + let needed = format_directives(format)? + .iter() + .filter(|directive| { + matches!( + directive, + Directive::Number { + suppress: false, + .. + } + ) + }) + .count(); + if needed > destinations { + Err("scan format has more assignments than destination arguments".into()) + } else { + Ok(()) + } +} +fn whitespace(byte: u8, nul_is_space: bool) -> bool { + byte.is_ascii_whitespace() || (nul_is_space && byte == 0) +} +fn skip_space(input: &mut impl Input, nul_is_space: bool) -> io::Result<()> { + while let Some(byte) = input.read_byte()? { + if !whitespace(byte, nul_is_space) { + input.unread_byte(byte)?; + break; + } + } + Ok(()) +} +enum Field { + Matched(Value), + Mismatch, + Eof, +} +fn field( + input: &mut impl Input, + code: u8, + width: Option, + bits: usize, + nul_is_space: bool, +) -> io::Result { + if code != b'c' { + skip_space(input, nul_is_space)?; + } + let Some(first) = input.read_byte().unwrap_or(None) else { + return Ok(Field::Eof); + }; + if code == b'c' { + return Ok(Field::Matched(Value { + value: BigUint::from(first) & ((BigUint::from(1u8) << bits) - BigUint::from(1u8)), + mask: BigUint::default(), + })); + } + let radix = match code { + b'b' => 2, + b'o' => 8, + b'd' => 10, + _ => 16, + }; + let max = width.unwrap_or(usize::MAX); + let mut used = 1; + let mut byte = first; + let mut negative = false; + if radix == 10 && matches!(byte, b'+' | b'-') { + negative = byte == b'-'; + if used == max { + return Ok(Field::Mismatch); + } + let Some(next) = input.read_byte().unwrap_or(None) else { + return Ok(Field::Mismatch); + }; + byte = next; + used += 1; + if matches!(byte, b'x' | b'X' | b'z' | b'Z' | b'?') { + input.unread_byte(byte)?; + return Ok(Field::Mismatch); + } + } + let mut digits = Vec::new(); + loop { + let unknown = matches!(byte, b'x' | b'X' | b'z' | b'Z' | b'?'); + let valid = + (byte as char).is_digit(radix) || unknown || (byte == b'_' && !digits.is_empty()); + if !valid { + input.unread_byte(byte)?; + break; + } + digits.push(byte); + // Decimal X/Z is a single input value, not part of a digit sequence. + if radix == 10 && unknown { + break; + } + if used == max { + break; + } + let Some(next) = input.read_byte().unwrap_or(None) else { + break; + }; + byte = next; + used += 1; + } + if digits.is_empty() { + return Ok(Field::Mismatch); + } + // A decimal X/Z cannot follow ordinary digits (the offending byte is unread). + if radix == 10 + && digits.len() > 1 + && digits + .last() + .is_some_and(|b| matches!(b, b'x' | b'X' | b'z' | b'Z' | b'?')) + { + input.unread_byte(digits.pop().unwrap())?; + } + let width_mask = (BigUint::from(1u8) << bits) - BigUint::from(1u8); + let mut value = BigUint::default(); + let mut mask = BigUint::default(); + let compact: Vec<_> = digits.into_iter().filter(|byte| *byte != b'_').collect(); + if radix == 10 { + if matches!(compact[0], b'x' | b'X' | b'z' | b'Z' | b'?') { + mask = width_mask.clone(); + if matches!(compact[0], b'x' | b'X') { + value = width_mask.clone(); + } + } else { + value = BigUint::parse_bytes(&compact, 10).unwrap_or_default() & &width_mask; + if negative && value != BigUint::default() { + value = (&width_mask + BigUint::from(1u8)) - value; + } + } + } else { + let shift = match radix { + 2 => 1, + 8 => 3, + _ => 4, + }; + for &digit in &compact { + value <<= shift; + mask <<= shift; + let group = BigUint::from((1u8 << shift) - 1); + match digit { + b'z' | b'Z' | b'?' => mask |= &group, + b'x' | b'X' => { + value |= &group; + mask |= &group; + } + _ => value |= BigUint::from((digit as char).to_digit(radix).unwrap()), + } + } + let occupied = compact.len().saturating_mul(shift); + if occupied < bits && matches!(compact[0], b'x' | b'X' | b'z' | b'Z' | b'?') { + let extension = &width_mask ^ ((BigUint::from(1u8) << occupied) - BigUint::from(1u8)); + mask |= &extension; + if matches!(compact[0], b'x' | b'X') { + value |= extension; + } + } + value &= &width_mask; + mask &= &width_mask; + } + Ok(Field::Matched(Value { value, mask })) +} + +/// Scan integral fields. Suppressed conversions consume input without assigning +/// or incrementing `count`; a conversion mismatch preserves the offending byte. +pub fn scan( + input: &mut impl Input, + format: &[u8], + widths: &[usize], + nul_is_space: bool, +) -> Result { + validate_format(format, widths.len())?; + let directives = format_directives(format)?; + let mut values = vec![None; widths.len()]; + let mut count = 0i32; + let mut converted = false; + let mut target = 0; + for directive in directives { + let status: io::Result> = match directive { + Directive::Space => skip_space(input, nul_is_space).map(|()| Some(true)), + Directive::Percent => match input.read_byte() { + Ok(Some(b'%')) => { + converted = true; + Ok(Some(true)) + } + Ok(Some(actual)) => input.unread_byte(actual).map(|()| Some(false)), + Ok(None) => Ok(None), + Err(error) => Err(error), + }, + Directive::Literal(expected) => match input.read_byte() { + Ok(Some(actual)) if actual == expected => { + converted = true; + Ok(Some(true)) + } + Ok(Some(actual)) => input.unread_byte(actual).map(|()| Some(false)), + Ok(None) => Ok(None), + Err(error) => Err(error), + }, + Directive::Number { + code, + width, + suppress, + } => { + let bits = if suppress { 1 } else { widths[target] }; + match field(input, code, width, bits, nul_is_space) { + Ok(Field::Matched(value)) => { + converted = true; + if !suppress { + values[target] = Some(value); + target += 1; + count += 1; + } + Ok(Some(true)) + } + Ok(Field::Mismatch) => Ok(Some(false)), + Ok(Field::Eof) => Ok(None), + Err(error) => Err(error), + } + } + }; + // I/O failures follow the same return-count rules as end of input. + // The file manager retains the stream's error state where supported. + match status.unwrap_or(None) { + Some(true) => {} + Some(false) => break, + None => { + if !converted { + count = -1; + } + break; + } + } + } + Ok(Outcome { count, values }) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn widths_suppression_literals_and_pushback() { + let mut input = SliceInput::new(b" 12,99 ffQ"); + let result = scan(&mut input, b"%2d,%*d %h", &[32, 8], true).unwrap(); + assert_eq!(result.count, 2); + assert_eq!(result.values[0].as_ref().unwrap().value, 12u8.into()); + assert_eq!(result.values[1].as_ref().unwrap().value, 255u8.into()); + assert_eq!(input.read_byte().unwrap(), Some(b'Q')); + } + #[test] + fn failure_eof_and_unknown_values() { + for (text, format, count) in [ + ("", "%d", -1), + ("q", "%d", 0), + ("1", "%d%d", 1), + ("1", "%*d%d", 0), + ("-", "%d", 0), + ("a", "a%d", 0), + ("%", "%%%d", 0), + ] { + let result = scan( + &mut SliceInput::new(text.as_bytes()), + format.as_bytes(), + &[32, 32], + true, + ) + .unwrap(); + assert_eq!(result.count, count, "{text}/{format}"); + } + let result = scan(&mut SliceInput::new(b"x 1z"), b"%d %h", &[65, 8], true).unwrap(); + assert_eq!( + result.values[0].as_ref().unwrap().mask, + (BigUint::from(1u8) << 65) - BigUint::from(1u8) + ); + assert_eq!( + result.values[0].as_ref().unwrap().value, + result.values[0].as_ref().unwrap().mask + ); + assert_eq!(result.values[1].as_ref().unwrap().value, 16u8.into()); + assert_eq!(result.values[1].as_ref().unwrap().mask, 15u8.into()); + } + #[test] + fn format_validation_and_character_width() { + for format in [b"%s".as_slice(), b"%f", b"%t", b"%0d", b"%q"] { + assert!(validate_format(format, 1).is_err()); + } + let mut input = SliceInput::new(b"ab"); + let result = scan(&mut input, b"%2c%c", &[32, 4], false).unwrap(); + assert_eq!(result.count, 2); + assert_eq!(result.values[0].as_ref().unwrap().value, 97u8.into()); + assert_eq!(result.values[1].as_ref().unwrap().value, 2u8.into()); + } + #[test] + fn input_error_finishes_an_existing_numeric_field() { + struct ErrorAtEnd<'a>(SliceInput<'a>); + impl Input for ErrorAtEnd<'_> { + fn read_byte(&mut self) -> io::Result> { + match self.0.read_byte()? { + Some(byte) => Ok(Some(byte)), + None => Err(io::ErrorKind::UnexpectedEof.into()), + } + } + fn unread_byte(&mut self, byte: u8) -> io::Result<()> { + self.0.unread_byte(byte) + } + } + let result = scan( + &mut ErrorAtEnd(SliceInput::new(b"12")), + b"%d%d", + &[32, 32], + false, + ) + .unwrap(); + assert_eq!(result.count, 1); + assert_eq!(result.values[0].as_ref().unwrap().value, 12u8.into()); + assert!(result.values[1].is_none()); + } +} diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index bae3b1d49bf..3ffb6629f9b 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -862,6 +862,8 @@ pub(in crate::ast) fn bind_value( | SystemFunction::Fgetc | SystemFunction::Ungetc | SystemFunction::Feof + | SystemFunction::Sscanf + | SystemFunction::Fscanf | SystemFunction::UrandomRange | SystemFunction::ScopeRandomize ) { diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 69ceb94d292..6c4bed0ad19 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -64,6 +64,7 @@ pub enum SystemFunction { Random, /// `$dist_uniform` (20.14.2). DistUniform, + /// Command-line prefix query (21.6). TestPlusargs, /// Command-line value query (21.6). @@ -85,6 +86,9 @@ pub enum SystemFunction { Fgetc, Ungetc, Feof, + /// Integral formatted input (21.3.4.3). + Sscanf, + Fscanf, } /// An array query function that selects one bound of a dimension (20.7). @@ -110,6 +114,8 @@ impl SystemFunction { | Self::Fgetc | Self::Ungetc | Self::Feof + | Self::Sscanf + | Self::Fscanf | Self::TestPlusargs | Self::ValuePlusargs ) @@ -148,6 +154,7 @@ impl SystemFunction { Self::Isunknown => "$isunknown", Self::Random => "$random", Self::DistUniform => "$dist_uniform", + Self::TestPlusargs => "$test$plusargs", Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", @@ -161,6 +168,8 @@ impl SystemFunction { Self::Fgetc => "$fgetc", Self::Ungetc => "$ungetc", Self::Feof => "$feof", + Self::Sscanf => "$sscanf", + Self::Fscanf => "$fscanf", } } @@ -203,6 +212,8 @@ impl SystemFunction { | Self::Fgetc | Self::Ungetc | Self::Feof + | Self::Sscanf + | Self::Fscanf | Self::UrandomRange | Self::ScopeRandomize ) @@ -222,6 +233,7 @@ impl SystemFunction { || (matches!(self, Self::Random | Self::DistUniform) && position == 0) || (self == Self::ValuePlusargs && position == 1) || (self == Self::Fread && position == 0) + || (matches!(self, Self::Sscanf | Self::Fscanf) && position >= 2) } /// The width and signedness of a call that is lowered as an integral @@ -247,6 +259,8 @@ impl SystemFunction { | Self::Rewind | Self::Fgetc | Self::Ungetc + | Self::Sscanf + | Self::Fscanf | Self::Feof => Some((32, true)), Self::Urandom | Self::UrandomRange | Self::Stime | Self::Fopen => Some((32, false)), Self::Rtoi => Some((32, true)), @@ -735,12 +749,6 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ // 20.14 Probabilistic distribution functions function(SystemFunction::Random, 0, Some(1)), function(SystemFunction::DistUniform, 3, Some(3)), - unsupported("$dist_normal", Function), - unsupported("$dist_exponential", Function), - unsupported("$dist_poisson", Function), - unsupported("$dist_chi_square", Function), - unsupported("$dist_t", Function), - unsupported("$dist_erlang", Function), // 20.15 Stochastic analysis tasks and functions unsupported("$q_initialize", Task), unsupported("$q_add", Task), @@ -894,8 +902,8 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ function(SystemFunction::Fgetc, 1, Some(1)), function(SystemFunction::Ungetc, 2, Some(2)), unsupported("$fgets", Function), - unsupported("$fscanf", Function), - unsupported("$sscanf", Function), + function(SystemFunction::Fscanf, 2, None), + function(SystemFunction::Sscanf, 2, None), function(SystemFunction::Fread, 2, Some(4)), function(SystemFunction::Ftell, 1, Some(1)), function(SystemFunction::Fseek, 3, Some(3)), diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 5428695ec9a..a5b92a1328e 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -19,6 +19,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/binary_file_io.vtest", text: include_str!("binary_file_io.vtest"), }, + Group { + file: "src/sv/cases/scan.vtest", + text: include_str!("scan.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/scan.vtest b/crates/celox-test-suite/src/sv/cases/scan.vtest new file mode 100644 index 00000000000..a7990b9d2ec --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/scan.vtest @@ -0,0 +1,57 @@ +(group scan (category sequential)) + +; IEEE 1800-2023 21.3.4.3: field widths, suppressed fields, literal +; delimiters, character fields, and input/matching failures. +(case sscanf_integral_fields_and_failure_counts + (source "sscanf_fields.sv" #" + module Top(output logic ok); + int a,b,c,n,keep; + logic [3:0] narrow; + logic [67:0] wide; + initial begin + n=$sscanf(" 12,99 ffQ","%2d,%*d %h%c",a,b,c); + ok=n==3 && a==12 && b==255 && c==81; + n=$sscanf("123","%d",narrow); ok &= n==1 && narrow==11; + n=$sscanf("fffffffffffffffff","%h",wide); ok &= n==1 && wide=='1; + keep=77; n=$sscanf("","%d",keep); ok &= n==-1 && keep==77; + n=$sscanf("bad","%d",keep); ok &= n==0 && keep==77; + n=$sscanf("5bad","%d%d",a,keep); ok &= n==1 && a==5 && keep==77; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +(case sscanf_multiple_outputs_and_packed_input + (source "sscanf_outputs.sv" #" + module Top(output logic ok); + int a[0:1]; int n,value; logic [63:0] source; + initial begin + n=$sscanf("7 8","%d%d",a[0],a[1]); + ok=n==2 && a[0]==7 && a[1]==8; + value=1; n=$sscanf("9bad","%d%d",value,value); ok &= n==1 && value==9; + source="42";n=$sscanf(source,"%d",value);ok &= n==1 && value==42; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +(case sscanf_radix_unknowns_and_unknown_input + (four_state) + (source "sscanf_unknown.sv" #" + module Top(output logic ok); + logic [7:0] value; logic [31:0] source; int n; + initial begin + n=$sscanf("1z","%h",value);ok=n==1 && value===8'h1z; + n=$sscanf("x","%d",value);ok &= n==1 && value===8'hxx; + n=$sscanf("z","%b",value);ok &= n==1 && value===8'hzz; + source='x;value=77;n=$sscanf(source,"%d",value);ok &= n==-1 && value==77; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 303275520a1..a10353520a4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 24; +const CONTAINER_VERSION: u16 = 25; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 07e2511a00f..8783baa50fa 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -140,6 +140,7 @@ impl UnitExecutor for Simulator { } celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), celox_design::HostRequestKind::Vcd => self.run_vcd_request(request, timestamp), + celox_design::HostRequestKind::Scan => self.run_scan_request(request, timestamp), } } } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index f96124a7efc..2cecf40b355 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -38,6 +38,7 @@ mod host { mod declaration; mod file_io; mod fread; + mod scan; use super::*; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 78d20787f94..e191f3ae49f 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1734,6 +1734,16 @@ mod host { signals: Vec::new(), })); } + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Scan) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message:"formatted input requires Simulation; Simulator does not execute initial process kernels".into(),signals:Vec::new(), + })); + } if program .runtime_schema .processes diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index b5a16a235a5..68aae41ca47 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -214,7 +214,7 @@ impl Simulator { matches!( site.kind, celox_design::HostRequestKind::FileIo | celox_design::HostRequestKind::Vcd - ) + ) || (site.kind == celox_design::HostRequestKind::Scan && site.operation == 1) }) { return Err(CheckpointError::ExternalSystemTasks); diff --git a/crates/celox/src/simulator/host/scan.rs b/crates/celox/src/simulator/host/scan.rs new file mode 100644 index 00000000000..887ea07fec1 --- /dev/null +++ b/crates/celox/src/simulator/host/scan.rs @@ -0,0 +1,93 @@ +use super::*; +use celox_design::HostRequestSite; +use celox_runtime::Halt; +use celox_runtime::scan::{Input, SliceInput}; +use num_bigint::BigUint; +use num_traits::{ToPrimitive, Zero}; + +struct FileInput<'a> { + files: &'a mut celox_runtime::file_io::FileIo, + descriptor: u32, +} +impl Input for FileInput<'_> { + fn read_byte(&mut self) -> std::io::Result> { + self.files.read_byte(self.descriptor) + } + fn unread_byte(&mut self, byte: u8) -> std::io::Result<()> { + self.files.unread_byte(self.descriptor, byte) + } +} +fn packed_bytes(value: BigUint, width: usize) -> Vec { + let bytes = value.to_bytes_be(); + let size = width.div_ceil(8); + let mut result = vec![0; size.saturating_sub(bytes.len())]; + result.extend(bytes); + result +} +impl Simulator { + pub(crate) fn run_scan_request( + &mut self, + site: &HostRequestSite, + _timestamp: u64, + ) -> Result<(), Halt> { + let error = |message| { + Halt::Error(RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }; + let (source, source_mask) = self.backend.get_four_state(site.args[0].id); + let (format, format_mask) = self.backend.get_four_state(site.args[1].id); + let mut count = -1i32; + if source_mask.is_zero() && format_mask.is_zero() { + let format = packed_bytes(format, site.args[1].width); + let format = format + .iter() + .position(|byte| *byte != 0) + .map_or(&[][..], |index| &format[index..]); + let widths = site.results[1..] + .iter() + .map(|value| value.width) + .collect::>(); + let outcome = if site.operation == 0 { + // Packed strings are right-aligned; leading zero padding is + // outside their textual contents, including for %c. + let source = source.to_bytes_be(); + let source = source + .iter() + .position(|byte| *byte != 0) + .map_or(&[][..], |index| &source[index..]); + celox_runtime::scan::scan(&mut SliceInput::new(source), format, &widths, true) + } else { + let descriptor = source.to_u32().unwrap_or_default(); + celox_runtime::scan::scan( + &mut FileInput { + files: &mut self.file_io, + descriptor, + }, + format, + &widths, + false, + ) + } + .map_err(error)?; + count = outcome.count; + for (target, value) in site.results[1..].iter().zip(outcome.values) { + if let Some(value) = value { + if self.backend.layout().four_state && target.id.is_4state { + self.backend + .set_four_state(target.id, value.value, value.mask); + } else { + let mask = (BigUint::from(1u8) << target.width) - BigUint::from(1u8); + self.backend + .set_wide(target.id, value.value & (&mask ^ (value.mask & &mask))); + } + } + } + } + self.backend + .set_wide(site.results[0].id, BigUint::from(count as u32)); + self.dirty = true; + Ok(()) + } +} diff --git a/crates/celox/tests/frontends/systemverilog/scan.rs b/crates/celox/tests/frontends/systemverilog/scan.rs new file mode 100644 index 00000000000..8a9f47172ab --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/scan.rs @@ -0,0 +1,5 @@ +sv_backends! { + fn sscanf_fields(sim) { @case "scan::sscanf_integral_fields_and_failure_counts"; } + fn sscanf_outputs(sim) { @case "scan::sscanf_multiple_outputs_and_packed_input"; } + fn sscanf_unknowns(sim) { @case "scan::sscanf_radix_unknowns_and_unknown_input"; } +} diff --git a/crates/celox/tests/sv_scan.rs b/crates/celox/tests/sv_scan.rs new file mode 100644 index 00000000000..6af4bcd070b --- /dev/null +++ b/crates/celox/tests/sv_scan.rs @@ -0,0 +1,158 @@ +#![cfg(feature = "systemverilog")] +use celox::{SimBackend, Simulation}; +use std::path::Path; +fn exercise(mut simulation: Simulation) { + simulation.run_until(1).unwrap(); + for (name, expected) in [ + ("count", 3u32), + ("a", 12), + ("b", 255), + ("c", b'Q' as u32), + ("index", 2), + ("order", 1233), + ("first", 7), + ("second", 8), + ("aliased", 9), + ("alias_count", 1), + ("eof", u32::MAX), + ("failure", 0), + ("partial", 1), + ("keep", 77), + ("two_state", 0), + ] { + let signal = simulation.signal(name); + assert_eq!(simulation.get(signal), expected.into(), "{name}"); + } + let wide = simulation.signal("wide"); + assert_eq!( + simulation.get(wide), + (num_bigint::BigUint::from(1u8) << 68) - num_bigint::BigUint::from(1u8) + ); + let unknown = simulation.signal("unknown"); + assert_eq!( + simulation.get_four_state(unknown), + (16u8.into(), 15u8.into()) + ); +} +const SOURCE: &str = r#"module Top(output int count,a,b,c,index,order,first,second,aliased,alias_count,eof,failure,partial,keep, + output logic [67:0] wide,output logic [7:0] unknown,output bit [7:0] two_state); + int values[0:1]; + function automatic [31:0] scan_source(); order=order*10+1; scan_source="7 8"; endfunction + function automatic [31:0] scan_format(); order=order*10+2; scan_format="%d%d"; endfunction + function automatic int next_index(); order=order*10+3; next_index=index; index+=1; endfunction + initial begin + count=$sscanf(" 12,99 ffQ","%2d,%*d %h%c",a,b,c); + index=0; order=0; count=count+$sscanf(scan_source(),scan_format(),values[next_index()],values[next_index()])-2; + first=values[0];second=values[1]; + aliased=1;alias_count=$sscanf("9","%d",aliased,aliased); + count=count+$sscanf("fffffffffffffffff","%h",wide)-1; + count=count+$sscanf("1z","%h",unknown)-1; + count=count+$sscanf("z","%h",two_state)-1; + keep=77;eof=$sscanf("","%d",keep);failure=$sscanf("bad","%d",keep); + partial=$sscanf("5bad","%d%d",a,keep); + a=12; + end endmodule"#; +macro_rules! backend { + ($name:ident,$build:ident) => { + #[test] + fn $name() { + exercise( + Simulation::from_sv_sources(vec![(SOURCE, Path::new("scan.sv"))], "Top") + .four_state(true) + .$build() + .unwrap(), + ); + } + }; +} +backend!(interpreter, build_interpreter); +backend!(cranelift, build_cranelift); +backend!(wasm, build_wasm); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +backend!(native, build_native); + +#[test] +fn fscanf_preserves_mismatch_lookahead_and_rejects_checkpoint() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.txt"); + std::fs::write(&path, b"12 34Q 7").unwrap(); + let source = format!( + r#"module Top(output int n,a,b,c,fail,last,eof);int fd; + initial begin fd=$fopen("{}","r");n=$fscanf({{32'h12345678,fd}},"%d",a); + n=n+$fscanf({{96'h123456789abcdef123456789,fd}},"%d",b); + fail=$fscanf(fd,"%d",b);n=n+$fscanf(fd,"%c%d",c,last); + eof=$fscanf(fd,"%d",b);end endmodule"#, + path.display() + ); + fn check(mut simulation: Simulation) { + simulation.run_until(1).unwrap(); + for (name, value) in [ + ("n", 4u32), + ("b", 34), + ("a", 12), + ("c", 81), + ("last", 7), + ("fail", 0), + ("eof", u32::MAX), + ] { + let signal = simulation.signal(name); + assert_eq!(simulation.get(signal), value.into(), "{name}"); + } + assert!( + format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks") + ); + } + let build = || Simulation::from_sv_sources(vec![(&source, Path::new("scan.sv"))], "Top"); + check(build().build_interpreter().unwrap()); + check(build().build_cranelift().unwrap()); + check(build().build_wasm().unwrap()); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap()); +} +#[test] +fn pure_sscanf_allows_checkpoint_and_untimed_build_is_rejected() { + let source = + "module Top(output int result);int a;initial result=$sscanf(\"12\",\"%d\",a);endmodule"; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("scan.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + assert!(simulation.checkpoint().is_ok()); + assert!(simulation.save_state().is_ok()); + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("scan.sv"))], "Top") + .build_interpreter() + .unwrap_err(); + assert!(format!("{error:?}").contains("formatted input requires Simulation")); +} +#[test] +fn rejected_formats_are_explicit() { + for (format, expected) in [ + ("%s", "string output"), + ("%f", "real output"), + ("%t", "$timeformat"), + ("%q", "unsupported scan conversion"), + ] { + let source = format!( + r#"module Top;int a,n;initial n=$sscanf("1","{}",a);endmodule"#, + format + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("scan.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!(format!("{:?}", simulation.run_until(1).unwrap_err()).contains(expected)); + } +} + +#[test] +fn fscanf_on_standard_input_rejects_snapshots_before_execution() { + let source = r#"module Top; int n, value; + initial begin #1; n = $fscanf(32'h80000000, "%d", value); end + endmodule"#; + let mut simulation = + Simulation::from_sv_sources(vec![(source, Path::new("scan_stdin.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!(format!("{:?}", simulation.checkpoint().unwrap_err()).contains("ExternalSystemTasks")); + assert!(simulation.save_state().is_err()); +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 679dcc8b678..c1b830eb36c 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -130,6 +130,8 @@ mod packed_structs; mod procedural; #[path = "frontends/systemverilog/review_regressions.rs"] mod review_regressions; +#[path = "frontends/systemverilog/scan.rs"] +mod scan; #[path = "frontends/systemverilog/suite.rs"] mod suite; #[path = "frontends/systemverilog/synthesizable.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index d9ed15c1766..5540ed2fde1 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -397,6 +397,17 @@ flushes all open files. Invalid flush descriptors produce a runtime error. These operations run in timed `Simulation` processes and use file descriptors for input and positioning; multichannel descriptors support output and flush. +### Formatted input + +`$sscanf(source, format, outputs...)` and `$fscanf(fd, format, outputs...)` +support integral `%d`, `%h`/`%x`, `%o`, `%b`, and `%c` conversions, numeric field widths, +assignment suppression, literal matching and whitespace (IEEE 1800-2023 +21.3.4.3). Source and format can be string literals or packed integral values. +The result counts assigned outputs; unmatched outputs retain their values. +Real conversions, `%s` string outputs and `%t` time scaling are unsupported. +Both functions require timed `Simulation` execution. Pure `$sscanf` state can +be checkpointed; `$fscanf` uses external file state and prevents checkpoints. + ### Runtime file output `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and their `b` / `o` / `h` diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index b86407e773d..3a1f32d52dc 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -278,6 +278,16 @@ offset を使い、先頭(0)、現在位置(1)、末尾(2)を基準 無効な flush descriptor は実行時エラーです。これらは時間付き `Simulation` で実行し、 入力と位置変更には file descriptor を使います。 +### 書式付き入力 + +`$sscanf(source, format, outputs...)` と `$fscanf(fd, format, outputs...)` は +整数の `%d`、`%h` / `%x`、`%o`、`%b`、`%c` 変換、数値フィールド幅、代入抑制、 +リテラル照合と空白を扱います(IEEE 1800-2023 21.3.4.3)。入力と書式には +文字列リテラルまたは packed 整数を使用できます。戻り値は代入した出力の数で、 +照合できなかった出力は保持します。実数変換、文字列出力の `%s`、時間倍率を +扱う `%t` は未対応です。両関数とも timed `Simulation` で実行します。 +`$sscanf` はチェックポイントに対応し、外部ファイルを使う `$fscanf` は拒否します。 + ### 実行時のファイル出力 `$fopen`、`$fclose`、`$fdisplay` / `$fwrite` とその `b` / `o` / `h` 形は、