From 919d7a14e76edb37f5c06ebde1a6a4bc4bfd25bf Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:31:45 +0900 Subject: [PATCH 1/3] feat(sv)!: support binary input and file positioning Support $fgetc, $ungetc, $feof, $ftell, $fseek, $rewind, $fread and $fflush in timed Simulation. Binary reads preserve untouched bits on partial input and capture destination selectors once. $fread accepts packed integrals and one-dimensional static integral memories. Validation: file-related backend regressions (95 tests), runtime unit tests, focused Icarus/Verilator cases, formatting and integrated all-target Clippy. The integrated tree also passed NAPI/JS boundary tests. sv-tests: reviewed the full official CI report (2,054 mode runs) and updated the six EOF, flush and file-position expectation rows that now pass. No regressions or other verdict changes were observed. BREAKING CHANGE: Adds variants to the public SystemFunction and SystemTask enums. Native images must be regenerated for container version 21. Change-Id: I292f8ab91f7714c74737aa666b9bc27fbd928403 --- conformance/sv-tests/README.md | 5 + conformance/sv-tests/expected.tsv | 12 +- crates/celox-frontend-sv/src/lowering.rs | 7 + crates/celox-frontend-sv/src/lowering/ff.rs | 20 + .../src/lowering/ff/file_io.rs | 74 +++- .../src/lowering/ff/fread.rs | 93 +++++ .../src/lowering/procedural.rs | 1 + crates/celox-runtime/src/file_io.rs | 377 +++++++++++++++++- .../src/ast/expression_binding/direct.rs | 44 +- .../celox-sv-analyzer/src/system_functions.rs | 105 ++++- .../src/sv/cases/binary_file_io.vtest | 21 + .../src/sv/cases/file_core.vtest | 23 ++ crates/celox-test-suite/src/sv/cases/mod.rs | 8 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/host/file_io.rs | 66 +++ crates/celox/src/simulator/host/fread.rs | 102 +++++ .../frontends/systemverilog/binary_file_io.rs | 171 ++++++++ .../frontends/systemverilog/file_core.rs | 194 +++++++++ crates/celox/tests/systemverilog.rs | 4 + docs/guide/systemverilog-reference.md | 29 +- docs/ja/guide/systemverilog-reference.md | 27 +- 22 files changed, 1349 insertions(+), 37 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/fread.rs create mode 100644 crates/celox-test-suite/src/sv/cases/binary_file_io.vtest create mode 100644 crates/celox-test-suite/src/sv/cases/file_core.vtest create mode 100644 crates/celox/src/simulator/host/fread.rs create mode 100644 crates/celox/tests/frontends/systemverilog/binary_file_io.rs create mode 100644 crates/celox/tests/frontends/systemverilog/file_core.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 3d1321ebb2a..9c7ea0eefc7 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -112,6 +112,11 @@ strict by default. The `9.2.2.3--always_latch` probe still fails because it uses an unsupported nonblocking latch assignment (`<=`). The full pinned run reviewed all 2054 case/mode rows; no other expectation rows changed. +The integral file-input extension updates six expectation rows: `21.3--feof`, +`21.3--fflush` and `21.3--fpos` now pass simulation in both state modes. The +remaining file-input probes retain their measured verdicts; several still use +unsupported `final` constructs. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 04b6294aafa..80bf4ffdc7a 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -781,12 +781,12 @@ chapter-21/21.3--fdisplay-boh.sv 2state fail chapter-21/21.3--fdisplay-boh.sv 4state fail chapter-21/21.3--fdisplay.sv 2state fail chapter-21/21.3--fdisplay.sv 4state fail -chapter-21/21.3--feof.sv 2state fail -chapter-21/21.3--feof.sv 4state fail +chapter-21/21.3--feof.sv 2state pass +chapter-21/21.3--feof.sv 4state pass chapter-21/21.3--ferror.sv 2state fail chapter-21/21.3--ferror.sv 4state fail -chapter-21/21.3--fflush.sv 2state fail -chapter-21/21.3--fflush.sv 4state fail +chapter-21/21.3--fflush.sv 2state pass +chapter-21/21.3--fflush.sv 4state pass chapter-21/21.3--fgetc.sv 2state fail chapter-21/21.3--fgetc.sv 4state fail chapter-21/21.3--fgets.sv 2state fail @@ -795,8 +795,8 @@ chapter-21/21.3--file.sv 2state pass chapter-21/21.3--file.sv 4state pass chapter-21/21.3--fmonitor.sv 2state fail chapter-21/21.3--fmonitor.sv 4state fail -chapter-21/21.3--fpos.sv 2state fail -chapter-21/21.3--fpos.sv 4state fail +chapter-21/21.3--fpos.sv 2state pass +chapter-21/21.3--fpos.sv 4state pass chapter-21/21.3--fread.sv 2state fail chapter-21/21.3--fread.sv 4state fail chapter-21/21.3--fscanf.sv 2state fail diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b1105551afe..e21ddff24de 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5981,6 +5981,13 @@ fn lower_bit_vector_function_slt( | SystemFunction::UrandomRange | SystemFunction::Fopen | SystemFunction::ScopeRandomize + | SystemFunction::Fread + | SystemFunction::Ftell + | SystemFunction::Fseek + | SystemFunction::Rewind + | SystemFunction::Fgetc + | SystemFunction::Ungetc + | SystemFunction::Feof | 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 b2f960480a9..f5068f71852 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -10,6 +10,7 @@ //! four-state semantics identical to the combinational lowering. mod file_io; +mod fread; use super::procedural::*; use super::*; @@ -835,6 +836,24 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), + args, + .. + } => self.fread(args)?, + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::Ftell + | sv::ir::SystemFunction::Fseek + | sv::ir::SystemFunction::Rewind + | sv::ir::SystemFunction::Fgetc + | sv::ir::SystemFunction::Ungetc + | sv::ir::SystemFunction::Feof), + ), + args, + .. + } => self.file_function(*function, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), args, @@ -2631,6 +2650,7 @@ impl<'p, 'a> Ff<'p, 'a> { if matches!( task, sv::ir::SystemTask::Fclose + | sv::ir::SystemTask::Fflush | sv::ir::SystemTask::Fdisplay(_) | sv::ir::SystemTask::Fwrite(_) | sv::ir::SystemTask::Writemem(_) diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs index 81852f26cc2..9116792f2d7 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -2,7 +2,7 @@ use super::*; use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; impl Ff<'_, '_> { - fn file_io_arg( + pub(super) fn file_io_arg( &mut self, arg: &sv::ir::SystemTaskArg, ) -> Result, sv::AnalyzerError> { @@ -45,7 +45,20 @@ impl Ff<'_, '_> { }) } - fn file_io_request( + fn file_descriptor_arg( + &mut self, + arg: &sv::ir::SystemTaskArg, + ) -> Result, sv::AnalyzerError> { + match arg { + sv::ir::SystemTaskArg::Expr(expr) => { + let expr = self.int_formal(expr.clone()); + self.file_io_arg(&sv::ir::SystemTaskArg::Expr(expr)) + } + _ => self.file_io_arg(arg), + } + } + + pub(super) fn file_io_request( &mut self, operation: u32, args: Vec>, @@ -100,6 +113,56 @@ impl Ff<'_, '_> { Ok(sv::ir::Expr::Ident(name)) } + pub(super) fn file_function( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use sv::ir::SystemFunction; + if self.kernel.is_none() { + return Err(unsupported(format!( + "system function `{function}` requires a scheduled process" + ))); + } + let operation = match function { + SystemFunction::Ftell => 7, + SystemFunction::Fseek => 8, + SystemFunction::Rewind => 9, + SystemFunction::Fgetc => 10, + SystemFunction::Ungetc => 11, + SystemFunction::Feof => 12, + _ => unreachable!(), + }; + let mut values = Vec::new(); + for (index, arg) in args.iter().enumerate() { + let expr = arg + .as_ref() + .ok_or_else(|| unsupported(format!("omitted argument of `{function}`")))?; + let signed = function == SystemFunction::Fseek && index > 0 + || function == SystemFunction::Ungetc && index == 0; + // Extend using the actual's signedness before interpreting the + // resulting 32 bits as the formal int/int-unsigned argument. + let expr = self.int_formal(expr.clone()); + let mut value = self.file_io_arg(&sv::ir::SystemTaskArg::Expr(expr))?; + value.signed = signed; + values.push(value); + } + let (id, name) = self.m.temp("file_result", 32, true, false); + self.file_io_request( + operation, + values, + vec![HostRequestValue { + float_precision: None, + id, + width: 32, + signed: true, + is_string: false, + }], + Vec::new(), + )?; + Ok(sv::ir::Expr::Ident(name)) + } + pub(super) fn file_task( &mut self, task: sv::ir::SystemTask, @@ -110,6 +173,13 @@ impl Ff<'_, '_> { return Err(unsupported(format!("`{task}` outside a scheduled process"))); } match task { + SystemTask::Fflush => { + let mut values = Vec::new(); + for arg in args { + values.push(self.file_descriptor_arg(arg)?); + } + self.file_io_request(6, values, Vec::new(), Vec::new())?; + } SystemTask::Fclose => { let descriptor = self.file_io_arg(&args[0])?; self.file_io_request(1, vec![descriptor], Vec::new(), Vec::new())?; diff --git a/crates/celox-frontend-sv/src/lowering/ff/fread.rs b/crates/celox-frontend-sv/src/lowering/ff/fread.rs new file mode 100644 index 00000000000..1a63b5ab2d0 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/fread.rs @@ -0,0 +1,93 @@ +use super::*; +use celox_design::HostRequestValue; + +impl Ff<'_, '_> { + pub(super) fn fread( + &mut self, + args: &[Option], + ) -> Result { + let destination = args + .first() + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("$fread destination"))?; + let memory = match destination { + sv::ir::Expr::Ident(name) => self + .m + .id(name) + .filter(|id| !self.m.var(*id).array_dims.is_empty()), + _ => None, + }; + let (left, right, element_width, width) = if let Some(id) = memory { + if self.m.var(id).array_dims.len() != 1 { + return Err(unsupported( + "$fread requires a one-dimensional static memory", + )); + } + let (left, right, width) = self.m.file_memory_shape(id)?; + (left, right, width, self.m.var(id).width) + } else { + let width = self + .m + .comparison_width(destination, destination) + .ok_or_else(|| unsupported("packed integral $fread destination"))?; + (0, 0, width, width) + }; + // Evaluate the reference once, then all value operands, then snapshot + // the referenced storage so partial reads retain argument side effects. + let (lvalues, captured) = self.capture_system_actual(destination)?; + let mut values = Vec::new(); + for (position, arg) in args.iter().enumerate().skip(1) { + if let Some(arg) = arg { + let expr = sv::ir::Expr::Resize { + expr: Box::new(arg.clone()), + width: 32, + signed: self.expr_signed(arg), + }; + let mut value = self.file_io_arg(&sv::ir::SystemTaskArg::Expr(expr))?; + value.signed = position > 1; + values.push(value); + } else if position == 1 { + return Err(unsupported("$fread file descriptor")); + } else { + // Missing addressing operands retain their positions in metadata. + let literal = sv::ir::Expr::Literal("0".into()); + values.push(self.file_io_arg(&sv::ir::SystemTaskArg::Expr(literal))?); + } + } + let (data_id, data) = self.host_hidden("fread_data", &captured, width, false, true)?; + let (result_id, result_name) = self.m.temp("fread_count", 32, true, false); + self.file_io_request( + 13, + values, + vec![ + HostRequestValue { + float_precision: None, + id: result_id, + width: 32, + signed: true, + is_string: false, + }, + HostRequestValue { + float_precision: None, + id: data_id, + width, + signed: false, + is_string: false, + }, + ], + vec![ + left.to_string(), + right.to_string(), + element_width.to_string(), + u8::from(memory.is_some()).to_string(), + u8::from(args.get(2).is_some_and(Option::is_some)).to_string(), + u8::from(args.get(3).is_some_and(Option::is_some)).to_string(), + ], + )?; + match lvalues.as_slice() { + [target] => self.assign(target, &data)?, + targets => self.assign_concat(targets, &data)?, + } + Ok(sv::ir::Expr::Ident(result_name)) + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 6cca5f14476..f491b0efeba 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -1000,6 +1000,7 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option, - descriptors: BTreeMap, + descriptors: BTreeMap, + stdin_input: InputState, stdin_open: bool, stdout_open: bool, stderr_open: bool, } +#[derive(Debug, Default)] +struct InputState { + eof: bool, + pushed: Option, +} + +#[derive(Debug)] +struct InputFile { + file: File, + readable: bool, + input: InputState, +} + impl Default for FileIo { fn default() -> Self { Self { channels: BTreeMap::new(), descriptors: BTreeMap::new(), + stdin_input: InputState::default(), stdin_open: true, stdout_open: true, stderr_open: true, @@ -57,11 +72,11 @@ impl FileIo { } _ => return 0, } - let (table, key) = if mode.is_some() { + let key = if mode.is_some() { let Some(key) = (3..FD_FLAG).find(|key| !self.descriptors.contains_key(key)) else { return 0; }; - (&mut self.descriptors, key) + key } else { let Some(key) = (1..31) .map(|bit| 1u32 << bit) @@ -69,13 +84,30 @@ impl FileIo { else { return 0; }; - (&mut self.channels, key) + key }; - let Ok(file) = options.open(path) else { + let Ok(mut file) = options.open(path) else { return 0; }; - table.insert(key, file); - if mode.is_some() { key | FD_FLAG } else { key } + if let Some(mode) = mode { + // Table 21-6 places the initial position at EOF for append modes, + // including the read position of update streams (a+). + if mode.starts_with('a') && file.seek(SeekFrom::End(0)).is_err() { + return 0; + } + self.descriptors.insert( + key, + InputFile { + file, + readable: mode.starts_with('r') || mode.contains('+'), + input: InputState::default(), + }, + ); + key | FD_FLAG + } else { + self.channels.insert(key, file); + key + } } /// Close every selected MCD channel, or one FD. Closing a standard stream @@ -102,7 +134,7 @@ impl FileIo { let Some(mut file) = self.descriptors.remove(&key) else { return Err(invalid_descriptor()); }; - return file.flush(); + return file.file.flush(); } let mut error = None; if descriptor & 1 != 0 && !std::mem::replace(&mut self.stdout_open, false) { @@ -146,6 +178,7 @@ impl FileIo { self.descriptors .get_mut(&key) .ok_or_else(invalid_descriptor)? + .file .write_all(bytes)?; Ok(false) } @@ -180,6 +213,169 @@ impl FileIo { (stdout, result) } + /// Read a byte from an FD. EOF is latched only after a read reaches it; + /// a pushed-back byte is returned before the underlying file is read. + pub fn read_byte(&mut self, descriptor: u32) -> io::Result> { + if descriptor == FD_FLAG && self.stdin_open { + return read_input_byte(&mut io::stdin().lock(), &mut self.stdin_input); + } + let file = self.readable_file(descriptor)?; + read_input_byte(&mut file.file, &mut file.input) + } + + /// Push back one character without changing the file. One byte is + /// guaranteed, as with C stdio; another unread before a read is rejected. + pub fn unread_byte(&mut self, descriptor: u32, byte: u8) -> io::Result<()> { + let input = if descriptor == FD_FLAG && self.stdin_open { + &mut self.stdin_input + } else { + &mut self.readable_file(descriptor)?.input + }; + if input.pushed.is_some() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "file pushback buffer is full", + )); + } + input.pushed = Some(byte); + input.eof = false; + Ok(()) + } + + /// Whether a previous read encountered EOF (21.3.8). + pub fn eof(&mut self, descriptor: u32) -> io::Result { + if descriptor == FD_FLAG && self.stdin_open { + return Ok(self.stdin_input.eof); + } + Ok(self.readable_file(descriptor)?.input.eof) + } + + /// Byte position of the next read/write, accounting for pushback. + pub fn tell(&mut self, descriptor: u32) -> io::Result { + let file = self.positioned_file(descriptor)?; + file.file + .stream_position()? + .checked_sub(u64::from(file.input.pushed.is_some())) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "pushback precedes beginning of file", + ) + }) + } + + /// Seek relative to start (0), logical current position (1), or end (2). + /// Successful positioning clears both pushback and the EOF indicator. + pub fn seek(&mut self, descriptor: u32, offset: i64, operation: i32) -> io::Result<()> { + let file = self.positioned_file(descriptor)?; + let position = match operation { + 0 => SeekFrom::Start(u64::try_from(offset).map_err(|_| { + io::Error::new(io::ErrorKind::InvalidInput, "negative file position") + })?), + 1 => { + let current = file + .file + .stream_position()? + .checked_sub(u64::from(file.input.pushed.is_some())) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "pushback precedes beginning of file", + ) + })?; + let target = current.checked_add_signed(offset).ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidInput, "file position out of range") + })?; + SeekFrom::Start(target) + } + 2 => SeekFrom::End(offset), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid seek operation", + )); + } + }; + file.file.seek(position)?; + file.input = InputState::default(); + Ok(()) + } + + /// Reposition to the beginning, clearing EOF and pushback. + pub fn rewind(&mut self, descriptor: u32) -> io::Result<()> { + self.seek(descriptor, 0, 0) + } + + /// Flush one FD/MCD, or all open output files when no descriptor is given. + /// Attempt every selected channel even if another selected channel fails. + pub fn flush(&mut self, descriptor: Option) -> io::Result<()> { + if let Some(descriptor) = descriptor { + if descriptor == 0 { + return Err(invalid_descriptor()); + } + if descriptor & FD_FLAG != 0 { + return match descriptor & !FD_FLAG { + 0 if self.stdin_open => Ok(()), + 1 if self.stdout_open => io::stdout().lock().flush(), + 2 if self.stderr_open => io::stderr().lock().flush(), + _ => self.positioned_file(descriptor)?.file.flush(), + }; + } + } + let mut error = None; + let mut attempt = |result: io::Result<()>| { + if let Err(err) = result { + error = Some(err); + } + }; + if descriptor.is_none() || descriptor.is_some_and(|bits| bits & 1 != 0) { + if self.stdout_open { + attempt(io::stdout().lock().flush()); + } else if descriptor.is_some() { + attempt(Err(invalid_descriptor())); + } + } + if descriptor.is_none() && self.stderr_open { + attempt(io::stderr().lock().flush()); + } + for bit in 1..31 { + let key = 1u32 << bit; + if descriptor.is_none() || descriptor.is_some_and(|bits| bits & key != 0) { + match self.channels.get_mut(&key) { + Some(file) => attempt(file.flush()), + None if descriptor.is_some() => attempt(Err(invalid_descriptor())), + None => {} + } + } + } + if descriptor.is_none() { + for file in self.descriptors.values_mut() { + attempt(file.file.flush()); + } + } + error.map_or(Ok(()), Err) + } + + fn positioned_file(&mut self, descriptor: u32) -> io::Result<&mut InputFile> { + if descriptor & FD_FLAG == 0 { + return Err(invalid_descriptor()); + } + self.descriptors + .get_mut(&(descriptor & !FD_FLAG)) + .ok_or_else(invalid_descriptor) + } + + fn readable_file(&mut self, descriptor: u32) -> io::Result<&mut InputFile> { + let file = self.positioned_file(descriptor)?; + if !file.readable { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "file is not open for reading", + )); + } + Ok(file) + } + /// Write a static unpacked memory snapshot, without address specifiers /// (21.5.3). The caller supplies elements in the requested address order. pub fn write_memory<'a>( @@ -200,6 +396,27 @@ impl FileIo { } } +fn read_input_byte(reader: &mut impl Read, input: &mut InputState) -> io::Result> { + if let Some(byte) = input.pushed.take() { + return Ok(Some(byte)); + } + if input.eof { + return Ok(None); + } + let mut byte = [0]; + loop { + match reader.read(&mut byte) { + Ok(0) => { + input.eof = true; + return Ok(None); + } + Ok(_) => return Ok(Some(byte[0])), + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), + } + } +} + fn invalid_descriptor() -> io::Error { io::Error::new( io::ErrorKind::InvalidInput, @@ -212,6 +429,148 @@ mod tests { use super::*; use num_bigint::BigUint; + #[test] + fn byte_input_tracks_eof_pushback_and_logical_position() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input"); + std::fs::write(&path, [0, 255, b'Z']).unwrap(); + let mut files = FileIo::default(); + let fd = files.open(&path, Some("rb")); + assert!(!files.eof(fd).unwrap()); + assert_eq!(files.tell(fd).unwrap(), 0); + assert_eq!(files.read_byte(fd).unwrap(), Some(0)); + assert_eq!(files.read_byte(fd).unwrap(), Some(255)); + files.unread_byte(fd, b'Q').unwrap(); + assert_eq!(files.tell(fd).unwrap(), 1); + assert!(files.unread_byte(fd, b'R').is_err()); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'Q')); + assert_eq!(files.tell(fd).unwrap(), 2); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'Z')); + assert!(!files.eof(fd).unwrap()); + assert_eq!(files.read_byte(fd).unwrap(), None); + assert!(files.eof(fd).unwrap()); + files.unread_byte(fd, b'X').unwrap(); + assert!(!files.eof(fd).unwrap()); + files.seek(fd, 0, 1).unwrap(); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'Z')); + assert_eq!(files.read_byte(fd).unwrap(), None); + files.rewind(fd).unwrap(); + assert!(!files.eof(fd).unwrap()); + assert_eq!(files.tell(fd).unwrap(), 0); + assert_eq!(files.read_byte(fd).unwrap(), Some(0)); + files.close(fd).unwrap(); + assert!(files.read_byte(fd).is_err()); + assert!(files.eof(fd).is_err()); + assert!(files.unread_byte(fd, 0).is_err()); + assert!(files.tell(fd).is_err()); + assert_eq!(std::fs::read(path).unwrap(), [0, 255, b'Z']); + } + + #[test] + fn eof_remains_latched_when_another_descriptor_appends_data() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("growing"); + std::fs::write(&path, []).unwrap(); + let mut files = FileIo::default(); + let reader = files.open(&path, Some("r")); + assert_eq!(files.read_byte(reader).unwrap(), None); + let writer = files.open(&path, Some("a")); + files.write(writer, b"new").unwrap(); + assert_eq!(files.read_byte(reader).unwrap(), None); + assert!(files.eof(reader).unwrap()); + files.seek(reader, 0, 1).unwrap(); + assert!(!files.eof(reader).unwrap()); + assert_eq!(files.read_byte(reader).unwrap(), Some(b'n')); + } + + #[test] + fn append_modes_open_at_eof_without_latching_eof_until_read() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("append-position"); + std::fs::write(&path, b"ab").unwrap(); + let mut files = FileIo::default(); + for mode in ["a", "ab", "a+", "a+b", "ab+"] { + let fd = files.open(&path, Some(mode)); + assert_ne!(fd, 0, "{mode}"); + assert_eq!(files.tell(fd).unwrap(), 2, "{mode}"); + if mode.contains('+') { + assert!(!files.eof(fd).unwrap(), "{mode}"); + assert_eq!(files.read_byte(fd).unwrap(), None, "{mode}"); + assert!(files.eof(fd).unwrap(), "{mode}"); + files.rewind(fd).unwrap(); + assert!(!files.eof(fd).unwrap(), "{mode}"); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'a'), "{mode}"); + } + files.close(fd).unwrap(); + } + assert_eq!(std::fs::read(path).unwrap(), b"ab"); + } + + #[test] + fn position_errors_preserve_pushback_and_append_ignores_seek_for_writes() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("append"); + std::fs::write(&path, b"ab").unwrap(); + let mut files = FileIo::default(); + let fd = files.open(&path, Some("a+b")); + files.rewind(fd).unwrap(); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'a')); + files.unread_byte(fd, b'Q').unwrap(); + assert!(files.seek(fd, -1, 0).is_err()); + assert!(files.seek(fd, 0, 9).is_err()); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'Q')); + files.rewind(fd).unwrap(); + files.write(fd, b"c").unwrap(); + assert_eq!(files.tell(fd).unwrap(), 3); + files.seek(fd, -1, 2).unwrap(); + assert_eq!(files.read_byte(fd).unwrap(), Some(b'c')); + files.close(fd).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"abc"); + } + + #[test] + fn flush_validates_fanout_and_keeps_streams_open() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("output"); + let mut files = FileIo::default(); + let channel = files.open(&path, None); + files.write(channel, b"a").unwrap(); + files.flush(Some(channel | 1)).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"a"); + assert!(files.flush(Some(channel | (1 << 30))).is_err()); + files.write(channel, b"b").unwrap(); + files.flush(None).unwrap(); + files.close(channel).unwrap(); + assert!(files.flush(Some(channel)).is_err()); + assert_eq!(std::fs::read(path).unwrap(), b"ab"); + files.close(FD_FLAG | 1).unwrap(); + assert!(files.flush(Some(FD_FLAG | 1)).is_err()); + assert!(files.flush(Some(1)).is_err()); + // Flush-all skips closed handles. + files.flush(None).unwrap(); + } + + #[test] + fn reads_and_positions_reject_mcds_and_write_only_handles() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("output"); + let mut files = FileIo::default(); + let mcd = files.open(&path, None); + assert!(files.read_byte(mcd).is_err()); + assert!(files.unread_byte(mcd, 1).is_err()); + assert!(files.eof(mcd).is_err()); + assert!(files.tell(mcd).is_err()); + assert!(files.rewind(mcd).is_err()); + let fd = files.open(&path, Some("w")); + assert!(files.read_byte(fd).is_err()); + assert!(files.unread_byte(fd, 1).is_err()); + assert!(files.eof(fd).is_err()); + assert_eq!(files.tell(fd).unwrap(), 0); + assert!(files.read_byte(FD_FLAG | 1).is_err()); + files.close(FD_FLAG).unwrap(); + assert!(files.read_byte(FD_FLAG).is_err()); + } + #[test] fn descriptors_modes_channels_and_reuse() { let dir = tempfile::tempdir().unwrap(); 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 e4c0f6cd94f..bae3b1d49bf 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -812,7 +812,43 @@ pub(in crate::ast) fn bind_value( system, } => { if let Some(function) = system { - if matches!( + if function == SystemFunction::Fread { + let mut operands = operands.into_iter(); + let mut values = Vec::new(); + for (position, id) in args.into_iter().enumerate() { + let value = if id.is_some() { + Some(operands.next().ok_or_else(disagreement)?) + } else { + None + }; + if position < 2 && value.is_none() { + return Err(unsupported( + "omitted $fread destination or descriptor", + )); + } + if let Some(value) = &value { + if position == 0 { + if !expressions::query_actual_is_writable( + value, dimensions, + ) { + return Err(unsupported( + "writable $fread destination", + )); + } + } else if expr_static_width(&tree.state, value, dimensions) + .is_none() + { + return Err(unsupported("integral $fread argument")); + } + } + values.push(value); + } + Expr::Call { + callee: Callee::System(function), + args: values, + arg_order: Vec::new(), + } + } else if matches!( function, SystemFunction::Urandom | SystemFunction::Random @@ -820,6 +856,12 @@ pub(in crate::ast) fn bind_value( | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs | SystemFunction::Fopen + | SystemFunction::Ftell + | SystemFunction::Fseek + | SystemFunction::Rewind + | SystemFunction::Fgetc + | SystemFunction::Ungetc + | SystemFunction::Feof | 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 83956d1a7d0..69ceb94d292 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -76,6 +76,15 @@ pub enum SystemFunction { UrandomRange, /// `$fopen` (21.3.1). Fopen, + /// Binary input into packed integers or a static memory (21.3.4.4). + Fread, + /// File position and byte input functions (21.3.4–8). + Ftell, + Fseek, + Rewind, + Fgetc, + Ungetc, + Feof, } /// An array query function that selects one bound of a dimension (20.7). @@ -91,7 +100,19 @@ pub enum ArrayQuery { impl SystemFunction { /// Calls that return through the timed scheduler's host boundary. pub fn is_host_request(self) -> bool { - matches!(self, Self::Fopen | Self::TestPlusargs | Self::ValuePlusargs) + matches!( + self, + Self::Fopen + | Self::Fread + | Self::Ftell + | Self::Fseek + | Self::Rewind + | Self::Fgetc + | Self::Ungetc + | Self::Feof + | Self::TestPlusargs + | Self::ValuePlusargs + ) } /// The built-in name (`$` functions or `std::randomize`). @@ -133,6 +154,13 @@ impl SystemFunction { Self::ScopeRandomize => "std::randomize", Self::UrandomRange => "$urandom_range", Self::Fopen => "$fopen", + Self::Fread => "$fread", + Self::Ftell => "$ftell", + Self::Fseek => "$fseek", + Self::Rewind => "$rewind", + Self::Fgetc => "$fgetc", + Self::Ungetc => "$ungetc", + Self::Feof => "$feof", } } @@ -168,6 +196,13 @@ impl SystemFunction { | Self::ValuePlusargs | Self::Urandom | Self::Fopen + | Self::Fread + | Self::Ftell + | Self::Fseek + | Self::Rewind + | Self::Fgetc + | Self::Ungetc + | Self::Feof | Self::UrandomRange | Self::ScopeRandomize ) @@ -186,6 +221,7 @@ impl SystemFunction { self == Self::ScopeRandomize || (matches!(self, Self::Random | Self::DistUniform) && position == 0) || (self == Self::ValuePlusargs && position == 1) + || (self == Self::Fread && position == 0) } /// The width and signedness of a call that is lowered as an integral @@ -201,9 +237,17 @@ impl SystemFunction { | Self::Countones | Self::ScopeRandomize => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), - Self::Random | Self::DistUniform | Self::TestPlusargs | Self::ValuePlusargs => { - Some((32, true)) - } + Self::Random + | Self::DistUniform + | Self::TestPlusargs + | Self::ValuePlusargs + | Self::Fread + | Self::Ftell + | Self::Fseek + | Self::Rewind + | Self::Fgetc + | Self::Ungetc + | Self::Feof => Some((32, true)), Self::Urandom | Self::UrandomRange | Self::Stime | Self::Fopen => Some((32, false)), Self::Rtoi => Some((32, true)), Self::Itor | Self::Bitstoreal | Self::Realtobits => Some((64, false)), @@ -254,6 +298,8 @@ pub enum SystemTask { Vcd(VcdTask), /// File output tasks (21.3). Fclose, + /// Flush selected output files or all open files (21.3.6). + Fflush, Fdisplay(Radix), Fwrite(Radix), /// Memory snapshot output (21.5). @@ -328,7 +374,12 @@ impl SystemTask { pub fn is_host_request(self) -> bool { matches!( self, - Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) | Self::Vcd(_) + Self::Fclose + | Self::Fflush + | Self::Fdisplay(_) + | Self::Fwrite(_) + | Self::Writemem(_) + | Self::Vcd(_) ) } @@ -353,6 +404,7 @@ impl SystemTask { Self::Write(Octal) => "$writeo", Self::Write(Hexadecimal) => "$writeh", Self::Fclose => "$fclose", + Self::Fflush => "$fflush", Self::Fdisplay(Decimal) => "$fdisplay", Self::Fdisplay(Binary) => "$fdisplayb", Self::Fdisplay(Octal) => "$fdisplayo", @@ -839,18 +891,18 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$swriteh", Task), unsupported("$sformat", Task), unsupported("$sformatf", Function), - unsupported("$fgetc", Function), - unsupported("$ungetc", Function), + function(SystemFunction::Fgetc, 1, Some(1)), + function(SystemFunction::Ungetc, 2, Some(2)), unsupported("$fgets", Function), unsupported("$fscanf", Function), unsupported("$sscanf", Function), - unsupported("$fread", Function), - unsupported("$ftell", Function), - unsupported("$fseek", Function), - unsupported("$rewind", Function), - unsupported("$fflush", Task), + function(SystemFunction::Fread, 2, Some(4)), + function(SystemFunction::Ftell, 1, Some(1)), + function(SystemFunction::Fseek, 3, Some(3)), + function(SystemFunction::Rewind, 1, Some(1)), + task(SystemTask::Fflush, ProceduralAndInitial, 0, Some(1)), unsupported("$ferror", Function), - unsupported("$feof", Function), + function(SystemFunction::Feof, 1, Some(1)), // 21.4 Loading memory array data from a file task( SystemTask::Readmem(MemoryFormat::Binary), @@ -1065,10 +1117,13 @@ pub fn check_call( detail: format!("expected {}, found {count}", expected_arguments(tf)), }); } - // A function takes a value for each argument; only tasks such as - // `$display(a,,b)` may leave one out. + // Functions require values, except the optional addressing operands of + // `$fread` (21.3.4.4). Tasks such as `$display(a,,b)` may omit operands. if tf.kind != Task - && let Some(position) = args.iter().position(|arg| *arg == Arg::Omitted) + && let Some(position) = args.iter().enumerate().position(|(position, arg)| { + *arg == Arg::Omitted + && !(checked == SystemCall::Function(SystemFunction::Fread) && position >= 2) + }) { return Err(AnalyzerError::InvalidSystemTfCall { name: name.to_string(), @@ -1103,6 +1158,24 @@ fn expected_arguments(tf: &SystemTf) -> String { mod tests { use super::*; + #[test] + fn fread_allows_only_optional_address_operands_to_be_omitted() { + use Arg::{Given, Omitted}; + for args in [ + vec![Given, Given, Omitted, Given], + vec![Given, Given, Given, Omitted], + ] { + assert_eq!( + check_function_call("$fread", Some(&args)).unwrap(), + SystemFunction::Fread + ); + } + for args in [vec![Omitted, Given], vec![Given, Omitted]] { + assert!(check_function_call("$fread", Some(&args)).is_err()); + } + assert!(check_function_call("$fseek", Some(&[Given, Omitted, Given])).is_err()); + } + #[test] fn names_are_unique_and_well_formed() { let mut names = fxhash::FxHashSet::default(); diff --git a/crates/celox-test-suite/src/sv/cases/binary_file_io.vtest b/crates/celox-test-suite/src/sv/cases/binary_file_io.vtest new file mode 100644 index 00000000000..1143fb86924 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/binary_file_io.vtest @@ -0,0 +1,21 @@ +(group binary_file_io (category sequential)) + +(case zero_count_preserves_memory + (source "binary_zero_count.sv" #" + module Top(output bit ok); + logic [8:0] memory [3:1]; + int count; + initial begin + memory[1] = 9'h123; + memory[2] = 9'h045; + memory[3] = 9'h067; + count = $fread(memory, 32'h8000ffff, 1, 0); + ok = count == 0 && memory[1] == 9'h123 + && memory[2] == 9'h045 && memory[3] == 9'h067 + && $bits(count) == 32; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox-test-suite/src/sv/cases/file_core.vtest b/crates/celox-test-suite/src/sv/cases/file_core.vtest new file mode 100644 index 00000000000..7f4482799e9 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/file_core.vtest @@ -0,0 +1,23 @@ +(group file_core (category sequential)) + +(case flush_preserves_stdout_order_and_integral_return_types + (source "file_core_types.sv" #" + module Top(output bit ok); + initial begin + ok = $bits($fgetc(32'h80000000)) == 32 + && $bits($ungetc(65, 32'h80000000)) == 32 + && $bits($ftell(32'h80000001)) == 32 + && $bits($fseek(32'h80000001, 0, 0)) == 32 + && $bits($rewind(32'h80000001)) == 32 + && $bits($feof(32'h80000000)) == 32; + $display("before"); + $fflush(); + $fwrite(1, "after"); + $fflush(1); + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1) + (expect_output "before\nafter")) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 2373c65c9b0..5428695ec9a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -15,6 +15,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/floating_point.vtest", text: include_str!("floating_point.vtest"), }, + Group { + file: "src/sv/cases/binary_file_io.vtest", + text: include_str!("binary_file_io.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), @@ -71,6 +75,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/synthesizable.vtest", text: include_str!("synthesizable.vtest"), }, + Group { + file: "src/sv/cases/file_core.vtest", + text: include_str!("file_core.vtest"), + }, Group { file: "src/sv/cases/file_io.vtest", text: include_str!("file_io.vtest"), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index b037898381b..303275520a1 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 = 23; +const CONTAINER_VERSION: u16 = 24; 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/simulator.rs b/crates/celox/src/simulator.rs index bc708bb142d..f96124a7efc 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -37,6 +37,7 @@ pub use state_file::{StateError, StateMismatch, StateSchema}; mod host { mod declaration; mod file_io; + mod fread; use super::*; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index d6ad77dace0..31f0dcb65b7 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -8,6 +8,9 @@ impl Simulator { site: &HostRequestSite, timestamp: u64, ) -> Result<(), Halt> { + if site.operation == 13 { + return self.run_fread_request(site); + } let error = |message: String| { Halt::Error(SimulatorErrorCode::Runtime { message, @@ -125,6 +128,69 @@ impl Simulator { } write_result.map_err(|err| error(format!("file output: {err}")))?; } + 6 => { + let descriptor = if site.args.is_empty() { + None + } else { + Some(number(0)?) + }; + self.file_io + .flush(descriptor) + .map_err(|err| error(format!("$fflush: {err}")))?; + } + 7..=12 => { + let descriptor = number(usize::from(site.operation == 11))?; + let code: i32 = match site.operation { + 7 => self + .file_io + .tell(descriptor) + .ok() + .and_then(|position| i32::try_from(position).ok()) + .unwrap_or(-1), + 8 => { + let offset = number(1)? as i32; + let operation = number(2)? as i32; + if self + .file_io + .seek(descriptor, i64::from(offset), operation) + .is_ok() + { + 0 + } else { + -1 + } + } + 9 => { + if self.file_io.rewind(descriptor).is_ok() { + 0 + } else { + -1 + } + } + 10 => self + .file_io + .read_byte(descriptor) + .ok() + .flatten() + .map_or(-1, i32::from), + 11 => { + let character = number(0)?; + if character != u32::MAX + && self + .file_io + .unread_byte(descriptor, character as u8) + .is_ok() + { + 0 + } else { + -1 + } + } + 12 => i32::from(self.file_io.eof(descriptor).unwrap_or(false)), + _ => unreachable!(), + }; + self.backend.set(site.results[0].id, code); + } 4 | 5 => { let path = string(0)?; let left: i128 = site.strings[0] diff --git a/crates/celox/src/simulator/host/fread.rs b/crates/celox/src/simulator/host/fread.rs new file mode 100644 index 00000000000..3d23aa40594 --- /dev/null +++ b/crates/celox/src/simulator/host/fread.rs @@ -0,0 +1,102 @@ +use super::*; +use celox_design::HostRequestSite; +use celox_runtime::{Halt, SimulatorErrorCode}; + +impl Simulator { + pub(crate) fn run_fread_request( + &mut self, + site: &HostRequestSite, + ) -> Result<(), Halt> { + let error = |message: &str| { + Halt::Error(SimulatorErrorCode::Runtime { + message: message.into(), + signals: Vec::new(), + }) + }; + let integer = |index: usize| -> Result { + let arg = &site.args[index]; + let (value, mask) = self.backend.get_four_state(arg.id); + if mask != BigUint::default() { + return Err(error("$fread descriptor/address contains X or Z")); + } + let mut value = num_bigint::BigInt::from(value); + if arg.signed && arg.width > 0 && value.bit(arg.width as u64 - 1) { + value -= num_bigint::BigInt::from(1u8) << arg.width; + } + value + .try_into() + .map_err(|_| error("$fread argument exceeds supported integer range")) + }; + let fd = integer(0)? as u32; + let metadata = |index: usize| { + site.strings[index] + .parse::() + .map_err(|_| error("invalid $fread memory metadata")) + }; + let (left, right, width) = (metadata(0)?, metadata(1)?, metadata(2)? as usize); + let memory = metadata(3)? != 0; + let start = if memory && metadata(4)? != 0 { + integer(1)? + } else { + left.min(right) + }; + let available = left.max(right) - start + 1; + if start < left.min(right) || start > left.max(right) { + return Err(error("$fread start outside array bounds")); + } + let count = if memory && metadata(5)? != 0 { + let count = integer(2)?; + if count < 0 { + return Err(error("negative $fread count")); + } + count.min(available) + } else { + available + }; + let target = site.results[1].id; + let (data, unknown) = self.backend.get_four_state(target); + let mut data = data.to_bytes_le(); + let mut unknown = unknown.to_bytes_le(); + data.resize(target.width.div_ceil(8), 0); + unknown.resize(target.width.div_ceil(8), 0); + let whole_mask = (BigUint::from(1u8) << target.width) - BigUint::from(1u8); + let mut read = 0u32; + let mut failed = false; + 'words: for index in start..start + count { + let base = index.abs_diff(left) as usize * width; + for byte_index in 0..width.div_ceil(8) { + let byte = match self.file_io.read_byte(fd) { + Ok(Some(byte)) => byte, + Ok(None) => break 'words, + Err(_) => { + failed = true; + break 'words; + } + }; + let shift = (width.div_ceil(8) - byte_index - 1) * 8; + let bits = 8.min(width - shift); + // Array elements need not be byte aligned (for example 9-bit + // words). Update only the received bits, including partial EOF. + for bit in 0..bits { + let offset = base + shift + bit; + let flag = 1u8 << (offset % 8); + data[offset / 8] = + (data[offset / 8] & !flag) | (((byte >> bit) & 1) << (offset % 8)); + unknown[offset / 8] &= !flag; + } + read = read.wrapping_add(1); + } + } + let data = BigUint::from_bytes_le(&data); + let unknown = BigUint::from_bytes_le(&unknown); + if self.backend.layout().four_state && target.is_4state { + self.backend.set_four_state(target, data, unknown); + } else { + self.backend + .set_wide(target, data & (&whole_mask ^ unknown)); + } + self.backend + .set(site.results[0].id, if failed { 0 } else { read }); + Ok(()) + } +} diff --git a/crates/celox/tests/frontends/systemverilog/binary_file_io.rs b/crates/celox/tests/frontends/systemverilog/binary_file_io.rs new file mode 100644 index 00000000000..5c11a1c1a76 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/binary_file_io.rs @@ -0,0 +1,171 @@ +use super::*; + +sv_backends! { + fn zero_count_preserves_memory(sim) { @case "binary_file_io::zero_count_preserves_memory"; } + + fn packed_partial_reads_and_integer_descriptor_conversion(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0xab, 0xcd, 0xef, 0x12, 0x34]).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd, count; + logic [23:0] data; + initial begin + fd = $fopen("{}", "rb"); + data = 0; + count = $fread(data, {{128'h1234, fd}}); + ok = count == 3 && data == 24'habcdef; + data = 24'h987654; + count = $fread(data, fd, -100, -1); + ok &= count == 2 && data == 24'h123454 && $feof(fd) != 0; + count = $fread(data, fd); + ok &= count == 0 && data == 24'h123454; + count = $fread(data, 32'h8000ffff); + ok &= count == 0 && data == 24'h123454; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("binary_packed.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + + fn unsigned_addresses_and_ascending_negative_bounds(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0xab, 0xcd, 0xef]).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd, count; + logic [7:0] start, limit; + logic [7:0] high [128:128]; + logic [7:0] negative [-2:-1]; + initial begin + fd = $fopen("{}", "rb"); + start = 8'h80; limit = 8'hff; + count = $fread(high, fd, start, limit); + ok = count == 1 && high[128] == 8'hab; + count = $fread(negative, fd); + ok &= count == 2 && negative[-2] == 8'hcd && negative[-1] == 8'hef; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("binary_addresses.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + + fn descending_non_byte_memory_bounds_and_partial_word(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0xab, 0xcd, 0x12, 0x34, 0x56]).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd, count; + logic [8:0] mem [3:1]; + initial begin + fd = $fopen("{}", "rb"); + mem[1] = 9'h155; mem[2] = 9'h155; mem[3] = 9'h155; + count = $fread(mem, fd,, 2); + ok = count == 4 && mem[1] == 9'h1cd && mem[2] == 9'h034 && mem[3] == 9'h155; + count = $fread(mem, fd, 3, 1); + ok &= count == 1 && mem[3] == 9'h055; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("binary_memory.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + + fn destination_selector_is_captured_before_descriptor_side_effects(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0xab]).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd, count, index, calls; + logic [15:0] mem [0:1]; + function automatic int select_index(); calls++; return index; endfunction + function automatic int descriptor(); index = 1; mem[0] = 16'h1234; return fd; endfunction + initial begin + fd = $fopen("{}", "rb"); + index = 0; calls = 0; mem[0] = 0; mem[1] = 16'h5678; + count = $fread(mem[select_index()], descriptor()); + ok = count == 1 && calls == 1 && index == 1 && mem[0] == 16'hab34 && mem[1] == 16'h5678; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("binary_reference.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } +} + +#[test] +fn fread_rejects_read_only_and_multidimensional_destinations() { + for destination in ["32'h0", "mem"] { + let source = format!( + "module Top; logic [7:0] mem [0:1][0:1]; int n; initial n = $fread({destination}, 32'h80000001); endmodule" + ); + assert!( + celox::Simulation::from_sv_sources( + vec![(&source, Path::new("binary_invalid.sv"))], + "Top" + ) + .build_interpreter() + .is_err(), + "{destination}" + ); + } +} + +#[test] +fn partial_binary_reads_preserve_unknown_bits_on_every_backend() { + fn check(mut sim: celox::Simulation, four_state: bool) { + sim.run_until(0).unwrap(); + let (value, mask) = sim.get_four_state(sim.signal("data")); + if four_state { + assert_eq!(mask, BigUint::from(255u16)); + assert_eq!(value >> 8, BigUint::from(0xabu8)); + } else { + assert_eq!(value, BigUint::from(0xab00u16)); + assert_eq!(mask, BigUint::from(0u8)); + } + } + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0xab]).unwrap(); + let source = format!( + r#"module Top(output logic [15:0] data); + int fd, count; + initial begin + fd = $fopen("{}", "rb"); data = 'x; + count = $fread(data, fd); $fclose(fd); + end + endmodule"#, + path.display() + ); + for four_state in [false, true] { + let build = || { + celox::Simulation::from_sv_sources( + vec![(&source, Path::new("binary_unknown.sv"))], + "Top", + ) + .four_state(four_state) + }; + check(build().build_interpreter().unwrap(), four_state); + check(build().build_native().unwrap(), four_state); + check(build().build_cranelift().unwrap(), four_state); + check(build().build_wasm().unwrap(), four_state); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/file_core.rs b/crates/celox/tests/frontends/systemverilog/file_core.rs new file mode 100644 index 00000000000..5d23c54340d --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/file_core.rs @@ -0,0 +1,194 @@ +use super::*; + +sv_backends! { + fn byte_reads_pushback_position_and_eof(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("input.bin"); + std::fs::write(&path, [0, 255, b'A', b'B']).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd; + initial begin + ok = 1; + fd = $fopen("{}", "rb"); + ok &= fd != 0 && $feof(fd) == 0 && $ftell(fd) == 0; + ok &= $fgetc(fd) == 0 && $ftell(fd) == 1; + ok &= $fgetc(fd) == 255 && $ftell(fd) == 2; + ok &= $ungetc(127, fd) == 0 && $ftell(fd) == 1; + ok &= $fgetc(fd) == 127 && $ftell(fd) == 2; + ok &= $fseek(fd, -1, 1) == 0 && $fgetc(fd) == 255; + ok &= $fseek(fd, -1, 2) == 0 && $fgetc(fd) == 66; + ok &= $feof(fd) == 0 && $fgetc(fd) == -1 && $feof(fd) != 0; + ok &= $ungetc(90, fd) == 0 && $feof(fd) == 0 && $ftell(fd) == 3; + ok &= $fseek(fd, 0, 1) == 0 && $fgetc(fd) == 66; + ok &= $fgetc(fd) == -1 && $rewind(fd) == 0; + ok &= $feof(fd) == 0 && $ftell(fd) == 0 && $fgetc(fd) == 0; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_core_bytes.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + assert_eq!(std::fs::read(path).unwrap(), [0, 255, b'A', b'B']); + } + + fn flush_update_seek_gap_and_append_modes(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("output.bin"); + let source = format!(r#"module Top(output bit ok); + int fd; + initial begin + ok = 1; + fd = $fopen("{}", "w+b"); + $fwrite(fd, "a"); + $fflush(fd); + ok &= $ftell(fd) == 1 && $fseek(fd, 3, 0) == 0; + $fwrite(fd, "z"); + $fflush(); + ok &= $rewind(fd) == 0; + ok &= $fgetc(fd) == 97 && $fgetc(fd) == 0 && $fgetc(fd) == 0 && $fgetc(fd) == 122; + $fclose(fd); + fd = $fopen("{}", "a+b"); + ok &= $ftell(fd) == 4 && $feof(fd) == 0; + ok &= $fgetc(fd) == -1 && $feof(fd) != 0; + ok &= $fseek(fd, 0, 0) == 0 && $feof(fd) == 0; + $fwrite(fd, "!"); + $fflush(fd); + ok &= $ftell(fd) == 5 && $rewind(fd) == 0 && $fgetc(fd) == 97; + $fclose(fd); + end + endmodule"#, path.display(), path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_core_update.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + assert_eq!(std::fs::read(path).unwrap(), b"a\0\0z!"); + } + + fn input_and_position_failures_return_status_without_stopping_process(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("writeonly.bin"); + let source = format!(r#"module Top(output bit ok, done); + int fd; + initial begin + fd = $fopen("{}", "w"); + ok = $fgetc(fd) == -1 && $ungetc(65, fd) == -1 && $feof(fd) == 0; + ok &= $fseek(fd, -1, 0) == -1 && $ftell(fd) == 0; + ok &= $fseek(fd, 0, 9) == -1 && $ftell(fd) == 0; + $fclose(fd); + ok &= $fgetc(fd) == -1 && $ungetc(65, fd) == -1; + ok &= $ftell(fd) == -1 && $rewind(fd) == -1 && $fseek(fd, 0, 0) == -1; + ok &= $fgetc(1) == -1 && $ungetc(-1, 32'h80000000) == -1; + done = 1; + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_core_status.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + let done = sim.signal("done"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + assert_eq!(sim.get(done), BigUint::from(1u8)); + } + + fn unsigned_byte_seek_offsets_zero_extend_and_signed_offsets_sign_extend(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("offset.bin"); + std::fs::write(&path, []).unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd; + byte unsigned positive = 8'h80; + byte negative = -1; + initial begin + fd = $fopen("{}", "r+"); + ok = $fseek(fd, positive, 0) == 0 && $ftell(fd) == 128; + ok &= $fseek(fd, negative, 1) == 0 && $ftell(fd) == 127; + ok &= $fseek(fd, 8'hff, 0) == 0 && $ftell(fd) == 255; + ok &= $fseek(fd, 8'shff, 1) == 0 && $ftell(fd) == 254; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_core_offset_types.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + + fn new_file_functions_truncate_descriptor_actuals_before_testing_unknown_bits(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("descriptor.bin"); + std::fs::write(&path, b"a").unwrap(); + let source = format!(r#"module Top(output bit ok); + int fd; + logic [127:0] wide; + initial begin + fd = $fopen("{}", "r"); + wide = {{96'hx, fd}}; + ok = $ftell(wide) == 0; + $fflush(wide); + ok &= $fgetc(wide) == 97 && $feof(wide) == 0; + ok &= $fseek(wide, 0, 0) == 0 && $ungetc(65, wide) == 0; + ok &= $rewind(wide) == 0 && $fgetc(wide) == 97; + $fclose(fd); + end + endmodule"#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_core_descriptor_types.sv"))], "Top").four_state(true); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + } + + fn flush_and_file_function_types(sim) { @case "file_core::flush_preserves_stdout_order_and_integral_return_types"; } +} + +#[test] +fn invalid_flush_reports_a_runtime_error() { + let source = "module Top; initial $fflush(32'h8000ffff); endmodule"; + let mut simulation = + celox::Simulation::from_sv_sources(vec![(source, Path::new("invalid_flush.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!( + simulation + .run_until(0) + .unwrap_err() + .to_string() + .contains("$fflush: invalid or closed") + ); +} + +#[test] +fn byte_function_calls_reject_invalid_arity_and_combinational_execution() { + for call in [ + "$fgetc()", + "$ungetc(1)", + "$ftell(1, 2)", + "$fseek(1, 2)", + "$rewind()", + "$feof()", + ] { + let source = format!("module Top(output int result); initial result = {call}; endmodule"); + assert!( + celox::Simulation::from_sv_sources(vec![(&source, Path::new("arity.sv"))], "Top") + .build_interpreter() + .is_err(), + "{call}" + ); + } + let source = + "module Top(output int result); always_comb result = $ftell(32'h80000001); endmodule"; + let message = Simulator::from_sv_sources(vec![(source, Path::new("comb.sv"))], "Top") + .build_interpreter() + .unwrap_err() + .to_string(); + assert!(message.contains("$ftell"), "{message}"); +} diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 04e858e8c40..679dcc8b678 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -100,8 +100,12 @@ macro_rules! sv_backends { #[path = "frontends/systemverilog/always_comb.rs"] mod always_comb; +#[path = "frontends/systemverilog/binary_file_io.rs"] +mod binary_file_io; #[path = "frontends/systemverilog/edges.rs"] mod edges; +#[path = "frontends/systemverilog/file_core.rs"] +mod file_core; #[path = "frontends/systemverilog/file_io.rs"] mod file_io; #[path = "frontends/systemverilog/generate.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 7c65ee96ee8..d9ed15c1766 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -126,7 +126,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: ([#456](https://github.com/celox-sim/celox/issues/456)). - System tasks and functions: Celox knows every name IEEE 1800-2023 defines, including the optional ones of its Annex D. One it does not support where it is called, such as - `$realtime` in an expression or `$fgetc`, is + `$realtime` in an expression or `$fgets`, is reported with its name wherever it is written, including in an unused parameter and in a function body. A `$` name that is not a system task or function, a call with the wrong number of arguments, an omitted argument @@ -370,6 +370,33 @@ is an error. Without directives, a word-count mismatch is a compilation warning (`Simulator::warnings()`): excess words are ignored, and missing words leave memory unchanged. +### Binary input + +`$fread` reads big-endian bytes into a packed integral destination or a +one-dimensional static integral memory (IEEE 1800-2023 21.3.4.4). Memory reads +start at the lowest index by default and proceed through increasing indices; +optional start and count operands select the range. Packed destinations ignore +those operands. Partial reads preserve bits that received no input, including +X/Z bits. The return value is the number of bytes read, or zero on an I/O error. + +### Byte input and file positioning + +`$fgetc(fd)` returns the next byte as an integer from 0 to 255, or -1 on EOF +or error. `$ungetc(character, fd)` pushes back one byte without modifying the +file and returns zero, or -1 on error. One byte of pushback is supported. +`$feof(fd)` tests whether a previous read detected EOF; reading the final byte +alone does not set it. Successful pushback and repositioning clear EOF. + +`$ftell(fd)` returns the logical byte position, accounting for pushback, or -1 +on error. `$fseek(fd, offset, operation)` accepts signed 32-bit offsets relative +to the start (0), current position (1), or end (2). `$rewind(fd)` seeks to the +start. Both positioning functions return zero on success or -1 on error; +successful seeks discard pushback. Position results beyond signed 32-bit range +return -1. `$fflush(fd_or_mcd)` flushes selected output channels; `$fflush()` +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. + ### 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 e4026a44536..b86407e773d 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -114,7 +114,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - 式:ストリーミング連結([#447](https://github.com/celox-sim/celox/issues/447))、パラメータ式での リダクション演算子([#456](https://github.com/celox-sim/celox/issues/456))。 - システムタスクとシステム関数:Celox は IEEE 1800-2023 が定義するすべての名前を、 - 附属書 D の任意のものも含めて知っています。呼び出した位置で対応していないもの(式の中の `$realtime`、`$fgetc` など)は、 + 附属書 D の任意のものも含めて知っています。呼び出した位置で対応していないもの(式の中の `$realtime`、`$fgets` など)は、 使われていないパラメータや関数本体の中を含め、書かれた 場所にかかわらず名前を示して報告します。システムタスクでもシステム関数でもない `$` 名、 引数の数が誤っている呼び出し、既定値のない引数の省略、値として使ったタスクはエラーです。 @@ -253,6 +253,31 @@ static なローカル変数は未対応です。`automatic` と宣言してく アドレス指定がなくワード数が範囲と合わない場合はコンパイル警告(`Simulator::warnings()`)に なり、余ったワードは無視され、足りない分のメモリは変わりません。 +### バイナリ入力 + +`$fread` はバイト列をビッグエンディアン順で packed 整数または1次元の静的な +整数メモリへ読み込みます(IEEE 1800-2023 21.3.4.4)。メモリは既定で最小の +添字から昇順に読み込み、開始位置と要素数を省略可能な引数で指定できます。 +packed 整数ではこれらの引数を無視します。部分的な読み込みでは、入力を +受け取らなかったビットとその X/Z を保持します。戻り値は読み込んだバイト数、 +I/O エラー時はゼロです。 + +### バイト入力とファイル位置 + +`$fgetc(fd)` は次のバイトを0〜255の整数で返し、EOF またはエラーでは -1 を返します。 +`$ungetc(character, fd)` はファイルを書き換えずに1バイトを戻し、成功時0、失敗時 -1 を +返します。pushback は1バイトに対応します。`$feof(fd)` は以前の読み取りで EOF に +達したかを調べます。最後のバイトを読んだだけでは EOF になりません。成功した +pushback と位置変更は EOF を解除します。 + +`$ftell(fd)` は pushback を考慮したバイト位置を返し、エラーまたは符号付き32ビットの +範囲を超える位置では -1 を返します。`$fseek(fd, offset, operation)` は符号付き32ビットの +offset を使い、先頭(0)、現在位置(1)、末尾(2)を基準に移動します。`$rewind(fd)` は +先頭に戻します。位置変更は成功時0、失敗時 -1 を返し、成功すると pushback を破棄します。 +`$fflush(fd_or_mcd)` は指定した出力先を、`$fflush()` は開いている全ファイルを flush します。 +無効な flush descriptor は実行時エラーです。これらは時間付き `Simulation` で実行し、 +入力と位置変更には file descriptor を使います。 + ### 実行時のファイル出力 `$fopen`、`$fclose`、`$fdisplay` / `$fwrite` とその `b` / `o` / `h` 形は、 From 1f42ca3590451745212d66cbef203b1d4bd45057 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:34:14 +0900 Subject: [PATCH 2/3] feat(sv)!: support integral formatted input Add `$sscanf` and `$fscanf` with integral numeric and character conversions, numeric field widths, assignment suppression and literal matching. Unmatched outputs retain their values and destination selectors are evaluated once. Both functions require timed `Simulation`; pure `$sscanf` supports checkpoints, while `$fscanf` rejects them even for standard input. Dynamic strings, string outputs, real conversions and `%t` remain unsupported. Validation: scanner API (8 tests), shared backend variants (15 tests), scanner/runtime and host-request encoding tests. Icarus passed 3 shared cases; Verilator passed 2 with one existing four-state adapter restriction. Formatting and integrated all-target Clippy passed. BREAKING CHANGE: Adds variants to the public SystemFunction and HostRequestKind enums. Native images must be regenerated for container version 22. Change-Id: I31d742e86892a979389fe667a7715acf0fbc44ee --- crates/celox-design/src/lib.rs | 6 +- crates/celox-frontend-sv/src/lowering.rs | 2 + crates/celox-frontend-sv/src/lowering/ff.rs | 10 + .../celox-frontend-sv/src/lowering/ff/scan.rs | 112 +++++ crates/celox-runtime/src/lib.rs | 1 + crates/celox-runtime/src/scan.rs | 441 ++++++++++++++++++ .../src/ast/expression_binding/direct.rs | 2 + .../celox-sv-analyzer/src/system_functions.rs | 24 +- crates/celox-test-suite/src/sv/cases/mod.rs | 4 + .../celox-test-suite/src/sv/cases/scan.vtest | 57 +++ crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 1 + crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/builder.rs | 10 + crates/celox/src/simulator/checkpoint.rs | 2 +- crates/celox/src/simulator/host/scan.rs | 93 ++++ .../tests/frontends/systemverilog/scan.rs | 5 + crates/celox/tests/sv_scan.rs | 158 +++++++ crates/celox/tests/systemverilog.rs | 2 + docs/guide/systemverilog-reference.md | 11 + docs/ja/guide/systemverilog-reference.md | 10 + 21 files changed, 943 insertions(+), 11 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/scan.rs create mode 100644 crates/celox-runtime/src/scan.rs create mode 100644 crates/celox-test-suite/src/sv/cases/scan.vtest create mode 100644 crates/celox/src/simulator/host/scan.rs create mode 100644 crates/celox/tests/frontends/systemverilog/scan.rs create mode 100644 crates/celox/tests/sv_scan.rs 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` 形は、 From a7cebae47250349883480e632860d885596c1205 Mon Sep 17 00:00:00 2001 From: tignear Date: Wed, 21 Oct 2026 08:36:04 +0900 Subject: [PATCH 3/3] feat(sv)!: add Annex N integer distribution functions Support `$dist_normal`, `$dist_exponential`, `$dist_poisson`, `$dist_chi_square`, `$dist_t` and `$dist_erlang` in timed `Simulation`. Use the Annex N algorithms with signed 32-bit formals and results, evaluate seed selectors once, and preserve deterministic checkpoint replay. Invalid positive parameters report an error without updating the seed. Validate native image serialization with both formatted-input and distribution host requests; container version 23 distinguishes the extended host schema. Validation: runtime reference vectors (3 tests), API tests across four backends and both state modes (21 tests), shared backend variants (10 tests), native image roundtrip, and host-request encoding tests. Two cases each passed Icarus and Verilator. Integrated Clippy, formatting and NAPI/JS boundary tests passed. sv-tests: reviewed the full official CI report (2,054 mode runs) and updated twelve distribution expectation rows that now pass in both state modes. The file-input improvements are retained by the lower PR; no regressions or other verdict changes were observed. BREAKING CHANGE: Adds variants to the public SystemFunction and HostRequestKind enums. Native images must be regenerated for container version 23. Change-Id: I5e156a7970741d8649b8ef33497ca1d1b54b3280 --- conformance/sv-tests/README.md | 6 + conformance/sv-tests/expected.tsv | 24 +-- crates/celox-design/src/lib.rs | 6 +- crates/celox-frontend-sv/src/lowering.rs | 6 + crates/celox-frontend-sv/src/lowering/ff.rs | 86 ++++++++ crates/celox-runtime/src/distribution.rs | 199 ++++++++++++++++++ crates/celox-runtime/src/lib.rs | 1 + .../src/ast/expression_binding/direct.rs | 6 + .../celox-sv-analyzer/src/system_functions.rs | 48 ++++- .../src/sv/cases/distributions.vtest | 67 ++++++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 3 + crates/celox/src/simulator.rs | 1 + crates/celox/src/simulator/builder.rs | 54 +++++ .../celox/src/simulator/host/distribution.rs | 40 ++++ .../systemverilog/system_functions.rs | 9 + crates/celox/tests/sv_distributions.rs | 170 +++++++++++++++ docs/guide/systemverilog-reference.md | 11 + docs/ja/guide/systemverilog-reference.md | 9 + 20 files changed, 737 insertions(+), 15 deletions(-) create mode 100644 crates/celox-runtime/src/distribution.rs create mode 100644 crates/celox-test-suite/src/sv/cases/distributions.vtest create mode 100644 crates/celox/src/simulator/host/distribution.rs create mode 100644 crates/celox/tests/sv_distributions.rs diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 9c7ea0eefc7..2964661cb26 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -117,6 +117,12 @@ The integral file-input extension updates six expectation rows: `21.3--feof`, remaining file-input probes retain their measured verdicts; several still use unsupported `final` constructs. +The six Annex N distribution probes (`20.15--dist_normal`, `dist_exponential`, +`dist_poisson`, `dist_chi_square`, `dist_t` and `dist_erlang`) now pass simulation +in both state modes, updating twelve more expectation rows. The scanner probes +retain failures caused by unsupported `final` constructs or internal data types; +no scanner expectation is changed. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 80bf4ffdc7a..01dce0b551b 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -681,18 +681,18 @@ chapter-20/20.10--warning.sv 2state pass chapter-20/20.10--warning.sv 4state pass chapter-20/20.14--coverage.sv 2state fail chapter-20/20.14--coverage.sv 4state fail -chapter-20/20.15--dist_chi_square.sv 2state fail -chapter-20/20.15--dist_chi_square.sv 4state fail -chapter-20/20.15--dist_erlang.sv 2state fail -chapter-20/20.15--dist_erlang.sv 4state fail -chapter-20/20.15--dist_exponential.sv 2state fail -chapter-20/20.15--dist_exponential.sv 4state fail -chapter-20/20.15--dist_normal.sv 2state fail -chapter-20/20.15--dist_normal.sv 4state fail -chapter-20/20.15--dist_poisson.sv 2state fail -chapter-20/20.15--dist_poisson.sv 4state fail -chapter-20/20.15--dist_t.sv 2state fail -chapter-20/20.15--dist_t.sv 4state fail +chapter-20/20.15--dist_chi_square.sv 2state pass +chapter-20/20.15--dist_chi_square.sv 4state pass +chapter-20/20.15--dist_erlang.sv 2state pass +chapter-20/20.15--dist_erlang.sv 4state pass +chapter-20/20.15--dist_exponential.sv 2state pass +chapter-20/20.15--dist_exponential.sv 4state pass +chapter-20/20.15--dist_normal.sv 2state pass +chapter-20/20.15--dist_normal.sv 4state pass +chapter-20/20.15--dist_poisson.sv 2state pass +chapter-20/20.15--dist_poisson.sv 4state pass +chapter-20/20.15--dist_t.sv 2state pass +chapter-20/20.15--dist_t.sv 4state pass chapter-20/20.15--dist_uniform.sv 2state pass chapter-20/20.15--dist_uniform.sv 4state pass chapter-20/20.15--random.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index d27a3367137..513374414a3 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -303,6 +303,7 @@ pub enum HostRequestKind { FileIo, Vcd, Scan, + Distribution, } impl HostRequestKind { @@ -313,6 +314,7 @@ impl HostRequestKind { Self::FileIo => 2, Self::Vcd => 3, Self::Scan => 4, + Self::Distribution => 5, }; (family << 32) | site as u64 } @@ -324,6 +326,7 @@ impl HostRequestKind { 2 => Self::FileIo, 3 => Self::Vcd, 4 => Self::Scan, + 5 => Self::Distribution, _ => return None, }; Some((family, request as u32)) @@ -1456,6 +1459,7 @@ mod tests { HostRequestKind::FileIo, HostRequestKind::Vcd, HostRequestKind::Scan, + HostRequestKind::Distribution, ] { for site in [0, 1, u32::MAX] { assert_eq!( @@ -1464,7 +1468,7 @@ mod tests { ); } } - for invalid in [0, u32::MAX as u64, 5u64 << 32, 1u64 << 63] { + for invalid in [0, u32::MAX as u64, 6u64 << 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 612d4cd26c3..45e824749e0 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -5975,6 +5975,12 @@ fn lower_bit_vector_function_slt( | SystemFunction::Stime | SystemFunction::Random | SystemFunction::DistUniform + | SystemFunction::DistNormal + | SystemFunction::DistExponential + | SystemFunction::DistPoisson + | SystemFunction::DistChiSquare + | SystemFunction::DistT + | SystemFunction::DistErlang | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs | SystemFunction::Urandom diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b58c9900e4f..bf950285f04 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -918,6 +918,19 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.plusargs(*function, args)?, + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::DistNormal + | sv::ir::SystemFunction::DistExponential + | sv::ir::SystemFunction::DistPoisson + | sv::ir::SystemFunction::DistChiSquare + | sv::ir::SystemFunction::DistT + | sv::ir::SystemFunction::DistErlang), + ), + args, + .. + } => self.distribution(*function, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::DistUniform), args, @@ -1822,6 +1835,79 @@ impl<'p, 'a> Ff<'p, 'a> { Ok((id, sv::ir::Expr::Ident(name))) } + fn distribution( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + use sv::ir::{Expr, SystemFunction as F}; + if self.kernel.is_none() { + return Err(unsupported(format!( + "{} outside a timed process", + function.name() + ))); + } + let operation = match function { + F::DistNormal => 0, + F::DistExponential => 1, + F::DistPoisson => 2, + F::DistChiSquare => 3, + F::DistT => 4, + F::DistErlang => 5, + _ => unreachable!(), + }; + let seed = args + .first() + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("distribution seed"))?; + // Capture selectors once before evaluating the other actuals, and + // suspend with an int formal rather than writing the caller's storage. + let (lvalues, captured) = self.capture_system_actual(seed)?; + let formal = self.int_formal(captured); + let (seed_id, seed_result) = + self.host_hidden("distribution_seed", &formal, 32, true, true)?; + let value = |id| HostRequestValue { + float_precision: None, + id, + width: 32, + signed: true, + is_string: false, + }; + let mut operands = vec![value(seed_id)]; + for arg in args.iter().skip(1) { + let arg = self.hoist( + arg.as_ref() + .ok_or_else(|| unsupported("distribution argument"))?, + )?; + let formal = self.int_formal(arg); + let (id, _) = self.host_hidden("distribution_arg", &formal, 32, true, true)?; + operands.push(value(id)); + } + let (ret_id, ret_name) = self.m.temp("distribution_result", 32, true, false); + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Distribution) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: 0, + kind: HostRequestKind::Distribution, + requires_timed_simulation: false, + operation, + args: operands, + results: vec![value(ret_id), value(seed_id)], + strings: Vec::new(), + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Distribution, site)) + .map_err(kernel_error)?; + match lvalues.as_slice() { + [lvalue] => self.assign(lvalue, &seed_result)?, + parts => self.assign_concat(parts, &seed_result)?, + } + Ok(Expr::Ident(ret_name)) + } + fn plusargs( &mut self, function: sv::ir::SystemFunction, diff --git a/crates/celox-runtime/src/distribution.rs b/crates/celox-runtime/src/distribution.rs new file mode 100644 index 00000000000..aa4e4db54ba --- /dev/null +++ b/crates/celox-runtime/src/distribution.rs @@ -0,0 +1,199 @@ +//! Integer probabilistic distributions (IEEE 1800-2023 20.14.2, Annex N). +//! +//! The seed transition wraps at 32 bits. Floating point is only an internal +//! implementation detail; all SystemVerilog formals and results are signed int. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Distribution { + Normal, + Exponential, + Poisson, + ChiSquare, + T, + Erlang, +} + +impl Distribution { + pub fn from_code(code: u32) -> Option { + Some(match code { + 0 => Self::Normal, + 1 => Self::Exponential, + 2 => Self::Poisson, + 3 => Self::ChiSquare, + 4 => Self::T, + 5 => Self::Erlang, + _ => return None, + }) + } + + pub fn name(self) -> &'static str { + match self { + Self::Normal => "$dist_normal", + Self::Exponential => "$dist_exponential", + Self::Poisson => "$dist_poisson", + Self::ChiSquare => "$dist_chi_square", + Self::T => "$dist_t", + Self::Erlang => "$dist_erlang", + } + } + + /// Draw one value, updating `seed` only after validating the int formals. + pub fn sample(self, seed: &mut i32, args: &[i32]) -> Result { + let arity = if matches!(self, Self::Normal | Self::Erlang) { + 2 + } else { + 1 + }; + if args.len() != arity { + return Err(format!( + "{} requires {arity} distribution parameters", + self.name() + )); + } + if self != Self::Normal && args.iter().any(|value| *value <= 0) { + return Err(format!( + "{} requires positive distribution parameters", + self.name() + )); + } + let sample = match self { + Self::Normal => normal(seed) * f64::from(args[1]) + f64::from(args[0]), + Self::Exponential => exponential(seed) * f64::from(args[0]), + Self::Poisson => return Ok(poisson(seed, args[0])), + Self::ChiSquare => chi_square(seed, args[0]), + Self::T => { + let chi = chi_square(seed, args[0]); + normal(seed) / (chi / f64::from(args[0])).sqrt() + } + Self::Erlang => { + let mut product = 1.0; + for _ in 0..args[0] { + product *= uniform(seed, 0.0, 1.0); + } + -f64::from(args[1]) * product.ln() / f64::from(args[0]) + } + }; + // Annex N rounds symmetrically, halfway away from zero. Its 32-bit + // C conversion produces INT_MIN on an out-of-range result on the + // reference targets; make that behavior explicit instead of relying + // on Rust's saturating float-to-int conversion. + let rounded = sample.round(); + Ok( + if !rounded.is_finite() + || rounded < f64::from(i32::MIN) + || rounded > f64::from(i32::MAX) + { + i32::MIN + } else { + rounded as i32 + }, + ) + } +} + +fn uniform(seed: &mut i32, start: f64, end: f64) -> f64 { + if *seed == 0 { + *seed = 259_341_593; + } + *seed = seed.wrapping_mul(69_069).wrapping_add(1); + let base = f64::from(f32::from_bits(((*seed as u32) >> 9) | 0x3f80_0000)); + let adjusted = base + base * (1.0 / 8_388_608.0); + (end - start) * (adjusted - 1.0) + start +} + +fn normal(seed: &mut i32) -> f64 { + loop { + let first = uniform(seed, -1.0, 1.0); + let second = uniform(seed, -1.0, 1.0); + let radius = first * first + second * second; + if radius < 1.0 && radius != 0.0 { + return first * (-2.0 * radius.ln() / radius).sqrt(); + } + } +} + +fn exponential(seed: &mut i32) -> f64 { + let value = uniform(seed, 0.0, 1.0); + if value == 0.0 { 0.0 } else { -value.ln() } +} + +fn poisson(seed: &mut i32, mean: i32) -> i32 { + let threshold = (-f64::from(mean)).exp(); + let mut product = uniform(seed, 0.0, 1.0); + let mut count = 0; + while threshold < product { + count += 1; + product *= uniform(seed, 0.0, 1.0); + } + count +} + +fn chi_square(seed: &mut i32, degrees: i32) -> f64 { + let mut result = if degrees % 2 != 0 { + normal(seed).powi(2) + } else { + 0.0 + }; + for _ in 0..degrees / 2 { + result += 2.0 * exponential(seed); + } + result +} + +#[cfg(test)] +mod tests { + use super::Distribution::*; + + #[test] + fn annex_n_fixed_seed_vectors() { + for (distribution, args, expected, next) in [ + (Normal, vec![0, 10], -4, -642_763_923), + (Exponential, vec![10], 82, 1_174_174), + (Poisson, vec![10], 3, -642_763_923), + (ChiSquare, vec![5], 2, -1_369_077_693), + (T, vec![5], 0, -434_453_879), + (Erlang, vec![3, 10], 33, 861_173_020), + ] { + let mut seed = 17; + assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected); + assert_eq!(seed, next); + } + } + + #[test] + fn zero_negative_seeds_and_small_shape_parameters() { + for (distribution, initial, args, expected, next) in [ + (Normal, 0, vec![-3, 5], -1, 1_082_744_015), + (Exponential, -1, vec![10], 0, -69_068), + (Poisson, -1, vec![1], 3, 1_486_841_147), + (ChiSquare, 1, vec![2], 22, 69_070), + (T, 1, vec![1], -4, 2_044_158_073), + (Erlang, 0, vec![1, 3], 2, -1_844_104_698), + ] { + let mut seed = initial; + assert_eq!(distribution.sample(&mut seed, &args).unwrap(), expected); + assert_eq!(seed, next); + } + } + + #[test] + fn invalid_parameters_do_not_advance_seed() { + for (distribution, args) in [ + (Exponential, vec![0]), + (Poisson, vec![-1]), + (ChiSquare, vec![0]), + (T, vec![-2]), + (Erlang, vec![0, 10]), + (Erlang, vec![2, 0]), + ] { + let mut seed = 17; + assert!( + distribution + .sample(&mut seed, &args) + .unwrap_err() + .contains("positive") + ); + assert_eq!(seed, 17); + } + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index dfa181a6ef4..2d2b872cc15 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -2,6 +2,7 @@ pub mod backend; mod derived_tick; +pub mod distribution; mod edge; mod error; mod event_buffer; 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 3ffb6629f9b..22a1180b48f 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -853,6 +853,12 @@ pub(in crate::ast) fn bind_value( SystemFunction::Urandom | SystemFunction::Random | SystemFunction::DistUniform + | SystemFunction::DistNormal + | SystemFunction::DistExponential + | SystemFunction::DistPoisson + | SystemFunction::DistChiSquare + | SystemFunction::DistT + | SystemFunction::DistErlang | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs | SystemFunction::Fopen diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 6c4bed0ad19..80f13c40ff6 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -64,6 +64,12 @@ pub enum SystemFunction { Random, /// `$dist_uniform` (20.14.2). DistUniform, + DistNormal, + DistExponential, + DistPoisson, + DistChiSquare, + DistT, + DistErlang, /// Command-line prefix query (21.6). TestPlusargs, @@ -118,6 +124,12 @@ impl SystemFunction { | Self::Fscanf | Self::TestPlusargs | Self::ValuePlusargs + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang ) } @@ -154,6 +166,12 @@ impl SystemFunction { Self::Isunknown => "$isunknown", Self::Random => "$random", Self::DistUniform => "$dist_uniform", + Self::DistNormal => "$dist_normal", + Self::DistExponential => "$dist_exponential", + Self::DistPoisson => "$dist_poisson", + Self::DistChiSquare => "$dist_chi_square", + Self::DistT => "$dist_t", + Self::DistErlang => "$dist_erlang", Self::TestPlusargs => "$test$plusargs", Self::ValuePlusargs => "$value$plusargs", @@ -201,6 +219,12 @@ impl SystemFunction { self, Self::Random | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang | Self::TestPlusargs | Self::ValuePlusargs | Self::Urandom @@ -230,7 +254,17 @@ impl SystemFunction { /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { self == Self::ScopeRandomize - || (matches!(self, Self::Random | Self::DistUniform) && position == 0) + || (matches!( + self, + Self::Random + | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang + ) && position == 0) || (self == Self::ValuePlusargs && position == 1) || (self == Self::Fread && position == 0) || (matches!(self, Self::Sscanf | Self::Fscanf) && position >= 2) @@ -251,6 +285,12 @@ impl SystemFunction { Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), Self::Random | Self::DistUniform + | Self::DistNormal + | Self::DistExponential + | Self::DistPoisson + | Self::DistChiSquare + | Self::DistT + | Self::DistErlang | Self::TestPlusargs | Self::ValuePlusargs | Self::Fread @@ -749,6 +789,12 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ // 20.14 Probabilistic distribution functions function(SystemFunction::Random, 0, Some(1)), function(SystemFunction::DistUniform, 3, Some(3)), + function(SystemFunction::DistNormal, 3, Some(3)), + function(SystemFunction::DistExponential, 2, Some(2)), + function(SystemFunction::DistPoisson, 2, Some(2)), + function(SystemFunction::DistChiSquare, 2, Some(2)), + function(SystemFunction::DistT, 2, Some(2)), + function(SystemFunction::DistErlang, 3, Some(3)), // 20.15 Stochastic analysis tasks and functions unsupported("$q_initialize", Task), unsupported("$q_add", Task), diff --git a/crates/celox-test-suite/src/sv/cases/distributions.vtest b/crates/celox-test-suite/src/sv/cases/distributions.vtest new file mode 100644 index 00000000000..1a2769cb1f9 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/distributions.vtest @@ -0,0 +1,67 @@ +(group distributions (category sequential)) + +; IEEE 1800-2023 20.14.2 and normative Annex N: signed int values and +; exact explicit-seed transitions, independently corroborated with Icarus. +(case annex_n_reference_values + (source "distributions.sv" #" + module Top(output logic ok); + int seed, value; + initial begin + ok = 1; + seed = 17; value = $dist_normal(seed, 0, 10); + ok &= value == -4 && seed == -642763923; + seed = 17; value = $dist_exponential(seed, 10); + ok &= value == 82 && seed == 1174174; + seed = 17; value = $dist_poisson(seed, 10); + ok &= value == 3 && seed == -642763923; + seed = 17; value = $dist_chi_square(seed, 5); + ok &= value == 2 && seed == -1369077693; + seed = 17; value = $dist_t(seed, 5); + ok &= value == 0 && seed == -434453879; + seed = 17; value = $dist_erlang(seed, 3, 10); + ok &= value == 33 && seed == 861173020; + seed = 0; value = $dist_normal(seed, -3, 5); + ok &= value == -1 && seed == 1082744015; + seed = -1; value = $dist_exponential(seed, 10); + ok &= value == 0 && seed == -69068; + seed = -1; value = $dist_poisson(seed, 1); + ok &= value == 3 && seed == 1486841147; + seed = 1; value = $dist_chi_square(seed, 2); + ok &= value == 22 && seed == 69070; + seed = 1; value = $dist_t(seed, 1); + ok &= value == -4 && seed == 2044158073; + seed = 0; value = $dist_erlang(seed, 1, 3); + ok &= value == 2 && seed == -1844104698; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +(case replay_and_normal_parameters + (source "distribution_replay.sv" #" + module Top(output logic ok); + int a, b, seed, replay; + initial begin + seed = 0; replay = 0; ok = 1; + for (int i = 0; i < 4; i++) begin + a = $dist_normal(seed, -17, 0); b = $dist_normal(replay, -17, 0); + ok &= a == -17 && a == b && seed == replay; + a = $dist_exponential(seed, 7); b = $dist_exponential(replay, 7); + ok &= a == b && seed == replay; + a = $dist_poisson(seed, 8); b = $dist_poisson(replay, 8); + ok &= a == b && seed == replay; + a = $dist_chi_square(seed, 2); b = $dist_chi_square(replay, 2); + ok &= a == b && seed == replay; + a = $dist_t(seed, 1); b = $dist_t(replay, 1); + ok &= a == b && seed == replay; + a = $dist_erlang(seed, 2, 9); b = $dist_erlang(replay, 2, 9); + ok &= a == b && seed == replay; + end + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index a5b92a1328e..6e73b02bedf 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -23,6 +23,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/scan.vtest", text: include_str!("scan.vtest"), }, + Group { + file: "src/sv/cases/distributions.vtest", + text: include_str!("distributions.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a10353520a4..d06e3ac5f3c 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 = 25; +const CONTAINER_VERSION: u16 = 26; 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 8783baa50fa..4d0022f33ef 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -138,6 +138,9 @@ impl UnitExecutor for Simulator { celox_design::HostRequestKind::Plusargs => { self.run_plusargs_request(request, timestamp) } + celox_design::HostRequestKind::Distribution => { + self.run_distribution_request(request, timestamp) + } 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 2cecf40b355..efb2aef7073 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -36,6 +36,7 @@ pub use state_file::{StateError, StateMismatch, StateSchema}; #[cfg(feature = "host-runtime")] mod host { mod declaration; + mod distribution; mod file_io; mod fread; mod scan; diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index e191f3ae49f..804edbd5c5a 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1723,6 +1723,17 @@ mod host { fn validate_untimed_host_requests( program: &crate::ir::RuntimeProgram, ) -> Result<(), SimulatorError> { + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Distribution) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message: "probabilistic distributions require Simulation; Simulator does not execute scheduled process kernels".into(), + signals: Vec::new(), + })); + } if program .runtime_schema .host_request_sites @@ -3801,6 +3812,49 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) + ))] + #[test] + fn extended_host_requests_survive_native_image_roundtrip() { + let source = r#"module Top(output bit ok); + int seed, value, parsed, count; + initial begin + seed = 17; + value = $dist_normal(seed, 0, 10); + count = $sscanf("42", "%d", parsed); + ok = value == -4 && parsed == 42 && count == 1; + end + endmodule"#; + let (program, warnings, options, _, _) = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("host_image.sv"))], + "Top", + ) + .emit_triggers() + .into_laid_out_program(crate::MemoryLayoutMode::ElementStrided) + .unwrap(); + let image = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let image = + crate::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let runtime = image.runtime_program(); + // SAFETY: this image was compiled from the trusted source above. + let backend = unsafe { crate::backend::native::NativeBackend::from_image(image) }.unwrap(); + let mut simulator = + crate::Simulator::with_backend_and_program_for_simulation(backend, runtime, warnings); + simulator.apply_initial_values(); + simulator.modify(|_| {}).unwrap(); + let mut sim = crate::Simulation::new(simulator); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("ok")), num_bigint::BigUint::from(1u8)); + } + #[cfg(all( test, feature = "systemverilog", diff --git a/crates/celox/src/simulator/host/distribution.rs b/crates/celox/src/simulator/host/distribution.rs new file mode 100644 index 00000000000..ef17534251b --- /dev/null +++ b/crates/celox/src/simulator/host/distribution.rs @@ -0,0 +1,40 @@ +use super::*; +use celox_design::HostRequestSite; +use celox_runtime::{Halt, SimulatorErrorCode, distribution::Distribution}; + +impl Simulator { + pub(crate) fn run_distribution_request( + &mut self, + site: &HostRequestSite, + _timestamp: u64, + ) -> Result<(), Halt> { + let error = |message| { + Halt::Error(SimulatorErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }; + let distribution = Distribution::from_code(site.operation) + .ok_or_else(|| error("invalid distribution operation".into()))?; + let values: Vec = site + .args + .iter() + .map(|arg| { + let (value, mask) = self.backend.get_four_state(arg.id); + // The reference integer arithmetic has no X/Z representation; + // coerce each unknown bit to zero, as for integral random seeds. + let known = value & (BigUint::from(u32::MAX) ^ mask); + known.to_u32_digits().first().copied().unwrap_or(0) as i32 + }) + .collect(); + let mut seed = values[0]; + let value = distribution + .sample(&mut seed, &values[1..]) + .map_err(error)?; + self.backend + .set_wide(site.results[0].id, BigUint::from(value as u32)); + self.backend + .set_wide(site.results[1].id, BigUint::from(seed as u32)); + Ok(()) + } +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index ea78f60de55..5e75bdb4124 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -472,6 +472,15 @@ sv_backends! { fn dist_uniform_bounds_seed_and_replay(sim) { @case "random_plusargs::dist_uniform_bounds_seed_and_replay"; } +} + +sv_backends! { + fn distribution_annex_n_reference_values(sim) { + @case "distributions::annex_n_reference_values"; + } + fn distribution_replay_and_normal_parameters(sim) { + @case "distributions::replay_and_normal_parameters"; + } fn dist_uniform_reference_sequence(sim) { @case "random_plusargs::dist_uniform_reference_sequence"; } diff --git a/crates/celox/tests/sv_distributions.rs b/crates/celox/tests/sv_distributions.rs new file mode 100644 index 00000000000..d9c00c69507 --- /dev/null +++ b/crates/celox/tests/sv_distributions.rs @@ -0,0 +1,170 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +const DISTRIBUTIONS: [(&str, &str, i32, i32); 6] = [ + ("$dist_normal", "0, 10", -4, -642_763_923), + ("$dist_exponential", "10", 82, 1_174_174), + ("$dist_poisson", "10", 3, -642_763_923), + ("$dist_chi_square", "5", 2, -1_369_077_693), + ("$dist_t", "5", 0, -434_453_879), + ("$dist_erlang", "3, 10", 33, 861_173_020), +]; + +fn actuals_source() -> String { + let mut body = String::new(); + for (name, parameters, expected, next) in DISTRIBUTIONS { + body.push_str(&format!( + r#" + seeds[0] = 17; seeds[1] = 91; calls = 0; + value = {name}(seeds[index()], {parameters}); + ok &= value == {expected} && calls == 1 && seeds[0] == {next} && seeds[1] == 91; + narrow = -1; reference = -1; + value = {name}(narrow, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && narrow == reference[7:0]; + unsigned_seed = 255; reference = 255; + value = {name}(unsigned_seed, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && unsigned_seed == reference[7:0]; + wide = 64'h1234567800000011; reference = 17; + value = {name}(wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && wide == extended; + wide = 64'hxxxxxxxx00000011; reference = 17; + value = {name}(wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && wide === extended; + unsigned_wide = 17; reference = 17; + value = {name}(unsigned_wide, {parameters}); other = {name}(reference, {parameters}); + extended = reference; + ok &= value == other && unsigned_wide == extended; + masked = 32'hxxxxxxxx; reference = 0; + value = {name}(masked, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && masked === reference && !$isunknown(masked); + masked = 32'h0000x011; reference = 17; + value = {name}(masked, {parameters}); other = {name}(reference, {parameters}); + ok &= value == other && masked === reference && !$isunknown(masked); + "# + )); + } + format!( + r#"module Top(output bit ok); + int seeds[0:1], calls, value, other, reference; + logic signed [7:0] narrow; + logic [7:0] unsigned_seed; + logic [63:0] unsigned_wide; + logic [31:0] masked; + longint wide, extended; + function automatic int index(); calls = calls + 1; return calls - 1; endfunction + initial begin ok = 1; {body} end + endmodule"# + ) +} + +macro_rules! distribution_backends { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + #[test] + fn distribution_int_formals_capture_and_masks() { + let source = actuals_source(); + for four_state in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_actuals.sv"))], "Top", + ).four_state(four_state).$backend().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("ok")), 1u8.into(), "four_state={four_state}"); + } + } + + #[test] + fn distribution_rejects_invalid_positive_formals_without_copyout() { + for (function, parameters) in [ + ("$dist_exponential", "0"), ("$dist_poisson", "-1"), + ("$dist_chi_square", "0"), ("$dist_t", "-1"), + ("$dist_erlang", "0, 10"), ("$dist_erlang", "2, 0"), + ] { + let source = format!(r#"module Top(output longint seed, output int value); + initial begin seed = 64'h1234567800000011; + value = {function}(seed, {parameters}); end + endmodule"#); + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_invalid.sv"))], "Top", + ).$backend().unwrap(); + let error = sim.run_until(0).unwrap_err(); + assert!(error.to_string().contains("requires positive distribution parameters"), "{error}"); + assert_eq!(sim.get(sim.signal("seed")), 0x1234567800000011u64.into()); + } + } + + #[test] + fn distribution_checkpoint_replays_seed_and_return_slots() { + let source = r#"module Top(output int value, seed); + timeunit 1ps; timeprecision 1ps; + initial seed = 17; + always begin #1; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("distribution_checkpoint.sv"))], "Top", + ).$backend().unwrap(); + sim.run_until(0).unwrap(); + let checkpoint = sim.checkpoint().unwrap(); + sim.run_until(2).unwrap(); + let expected_seed = sim.get(sim.signal("seed")); + let expected_value = sim.get(sim.signal("value")); + sim.restore(&checkpoint).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("seed")), expected_seed); + assert_eq!(sim.get(sim.signal("value")), expected_value); + } + + #[test] + fn distribution_initial_requires_timed_simulation() { + let source = r#"module Top(output int value); + int seed; + initial begin seed = 17; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let error = celox::Simulator::from_sv_sources( + vec![(source, Path::new("distribution_initial.sv"))], "Top", + ).$backend().err().expect("untimed initial distribution accepted"); + assert!(error.to_string().contains("distributions require Simulation")); + } + + #[test] + fn distribution_edge_requires_timed_simulation() { + let source = r#"module Top(input bit clk, output int value); + int seed; + always_ff @(posedge clk) begin seed = 17; value = $dist_normal(seed, 0, 10); end + endmodule"#; + let error = celox::Simulator::from_sv_sources( + vec![(source, Path::new("distribution_edge.sv"))], "Top", + ).$backend().err().expect("untimed distribution accepted"); + assert!(error.to_string().contains("require Simulation")); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("distribution_edge.sv"))], "Top", + ).$backend().unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("value")), (u32::MAX - 3).into()); + } + } + }; +} +distribution_backends!(interpreter, build_interpreter); +distribution_backends!(cranelift, build); +#[cfg(target_arch = "x86_64")] +distribution_backends!(native, build_native); +distribution_backends!(wasm, build_wasm); + +#[test] +fn distribution_seed_is_an_integral_inout_variable() { + for (name, parameters, _, _) in DISTRIBUTIONS { + let source = + format!("module Top; int value; initial value = {name}(17, {parameters}); endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("distribution_seed.sv"))], + "Top", + ) + .build_interpreter() + .expect_err("literal inout seed accepted"); + assert!(error.to_string().contains("output/inout"), "{error}"); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 5540ed2fde1..4f2bcd15a00 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -530,6 +530,17 @@ the whole design. its integral seed variable and includes both bounds. Equal or reversed bounds return `start` without advancing the seed. +`$dist_normal`, `$dist_exponential`, `$dist_poisson`, `$dist_chi_square`, +`$dist_t` and `$dist_erlang` use the Annex N distributions in timed +`Simulation` processes and their subroutines. Arguments and results are signed +32-bit integers; the integral inout seed is converted to an int and copied +back once, including when its actual is an indexed element. Exponential and +Poisson means, chi-square and t degrees of freedom, and both Erlang parameters +must be positive; invalid parameters report a runtime error without updating +the seed. Normal accepts any integer mean and standard deviation. These +functions do not require an SV `real` type. Their seed is design state, so +checkpoints replay their sequence. + ## Mixing Veryl and SystemVerilog {#mixed-language} `Simulator::from_mixed_sources`combines both source lists in one simulation. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 3a1f32d52dc..b7e4c3e542e 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -349,6 +349,15 @@ checkpoint と状態ファイルの保存・復元はエラーになります。 `$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 両端を含み、境界が同じ値か逆順なら seed を進めず `start` を返します。 +`$dist_normal`、`$dist_exponential`、`$dist_poisson`、`$dist_chi_square`、 +`$dist_t`、`$dist_erlang` は時間付き `Simulation` のプロセスとそのサブルーチンで +Annex N の分布を使います。引数と戻り値は符号付き32ビット整数です。 +整数の inout seed は int に変換し、添字付き要素の場合も一度だけ書き戻します。 +指数・Poisson分布の mean、カイ二乗・t分布の自由度、Erlang分布の両引数は正値が必要です。 +不正な値は seed を更新せず実行時エラーとして診断します。正規分布の mean と標準偏差は +任意の整数を受け付けます。SV の `real` 型は必要ありません。seed はデザインの状態なので、 +checkpoint の復元で乱数列を再現できます。 + ## 時刻と精度 {#time-and-precision} `$timeunit` と `$timeprecision` は秒を基準とする指数を32ビットの符号付き整数で