From c1b6cdb20521720bb0c98a85e75a7a07fc1dab22 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 31 Oct 2026 19:53:58 +0900 Subject: [PATCH] feat(cli)!: share SystemVerilog compilation units across ordered source files `celox run -f rtlmeter.f` previously restarted preprocessing for every source, so macros defined in a configuration header disappeared before later RTL files. The CLI now treats its ordered source list as one compilation unit by default. Definitions, undefinitions, directives and unit declarations carry forward; relative includes resolve against their own source files. Lists accept .h, .vh and .svh headers alongside .v/.sv sources, including a leading header. Use --separate-units or single_unit = false in celox.toml to retain per-file isolation; --single-unit overrides a project setting. Both run and vpi build use the same selection. Rust source-list APIs keep their existing per-file contract; syntax::preprocess_sources explicitly preprocesses a shared unit. IEEE 1800-2023 3.12.1 requires both compilation models and leaves the default to tools. Preserve file boundaries in expanded text with line directives. Separate tokens introduced by expansions so a macro's unary minus followed by -1 remains - -1, rather than becoming the decrement --1. Explicit token pastes remain intact; macro substitution in based literals remains supported. Comments do not terminate escaped identifiers: expansion boundaries insert actual whitespace before comments, and EOF line comments end before an included file's caller. Closes #2128. Validation: project_cli (22 passed), syntax crate (137 passed), compilation_units (3 passed), analyzer syntax tests (7 passed), analyzer doctests, affected-crate clippy and cargo fmt. With #2133, RTLmeter hello passes in four-state on E902 (native, 5392 cycles) and E906 (native and tiered, 9816 cycles). After the token serialization fix, both designs retain their effective token streams (174054 and 497628 tokens; based-literal whitespace normalized per IEEE 5.7.1). Change-Id: I9acd28e899919795f02894d6fcc118ef68667d63 --- crates/celox-sv-analyzer/src/syntax.rs | 46 +++++- .../tests/compilation_units.rs | 91 +++++++++++ crates/celox-sv-syntax/src/preprocess.rs | 100 +++++++++++- crates/celox-vpi/src/bin/celox/project.rs | 64 ++++++-- crates/celox-vpi/tests/project_cli.rs | 149 ++++++++++++++++++ docs/guide/cocotb.md | 18 ++- docs/ja/guide/cocotb.md | 16 ++ 7 files changed, 460 insertions(+), 24 deletions(-) create mode 100644 crates/celox-sv-analyzer/tests/compilation_units.rs diff --git a/crates/celox-sv-analyzer/src/syntax.rs b/crates/celox-sv-analyzer/src/syntax.rs index 7c792a9eba9..2f0ae73441b 100644 --- a/crates/celox-sv-analyzer/src/syntax.rs +++ b/crates/celox-sv-analyzer/src/syntax.rs @@ -17,6 +17,39 @@ pub fn preprocess_source( macros: &[(String, Option)], includes: &[&Path], ) -> Result { + preprocessor(macros, includes)? + .preprocess(code, path) + .map(|source| source.text()) + .map_err(|error| AnalyzerError::Parse(error.to_string())) +} + +/// Expand ordered source files as one compilation unit (IEEE 1800-2023 3.12.1). +/// Macros, including definitions and undefinitions in headers, survive between +/// files. Each call starts a fresh unit with the supplied command-line macros. +/// The returned text retains file boundaries through `line directives. +pub fn preprocess_sources( + sources: &[(&str, &Path)], + macros: &[(String, Option)], + includes: &[&Path], +) -> Result { + let mut preprocessor = preprocessor(macros, includes)?; + let mut expanded = String::new(); + for (code, path) in sources { + let source = preprocessor + .preprocess(code, path) + .map_err(|error| AnalyzerError::Parse(error.to_string()))?; + // A newline also separates files ending in a line comment or token. + expanded.push_str(&format!("\n`line 1 {:?} 0\n", path.to_string_lossy())); + expanded.push_str(&source.text()); + expanded.push('\n'); + } + Ok(expanded) +} + +fn preprocessor( + macros: &[(String, Option)], + includes: &[&Path], +) -> Result { let mut preprocessor = celox_sv_syntax::Preprocessor::new(celox_sv_syntax::Options { include_paths: includes.iter().map(|path| path.to_path_buf()).collect(), ..Default::default() @@ -27,10 +60,7 @@ pub fn preprocess_source( .preprocess(&definition, Path::new("")) .map_err(|error| AnalyzerError::Parse(error.to_string()))?; } - preprocessor - .preprocess(code, path) - .map(|source| source.text()) - .map_err(|error| AnalyzerError::Parse(error.to_string())) + Ok(preprocessor) } /// Parse native source syntax with authored tokens and original source origins. @@ -209,7 +239,13 @@ mod tests { &[], ) .unwrap(); - assert!(expanded.contains("N=7+1"), "{expanded}"); + assert!( + expanded + .split_whitespace() + .collect::() + .contains("N=7+1"), + "{expanded}" + ); let separate = preprocess_source( "`ifdef LOCAL\nmodule Leaked; endmodule\n`else\nmodule Separate; endmodule\n`endif\n", path, diff --git a/crates/celox-sv-analyzer/tests/compilation_units.rs b/crates/celox-sv-analyzer/tests/compilation_units.rs new file mode 100644 index 00000000000..768d303ab5f --- /dev/null +++ b/crates/celox-sv-analyzer/tests/compilation_units.rs @@ -0,0 +1,91 @@ +use celox_sv_analyzer::syntax::{parse_source, preprocess_sources}; +use std::path::Path; + +#[test] +fn ordered_files_share_macros_and_directives_but_separate_calls_do_not() { + let sources = [ + ( + "`define WIDTH 8\n`define PLUS(x) ((x)+1)\n`default_nettype none\n", + Path::new("defs.sv"), + ), + ( + "module M(output logic [`WIDTH-1:0] q); assign q=`PLUS(40); endmodule\n`undef WIDTH\n", + Path::new("consumer.sv"), + ), + ( + "`ifdef WIDTH\ninvalid\n`endif\nmodule N; endmodule // no trailing newline", + Path::new("last.sv"), + ), + ]; + let text = preprocess_sources(&sources, &[], &[]).unwrap(); + assert!( + text.split_whitespace() + .collect::() + .contains("[8-1:0]"), + "{text}" + ); + assert!( + text.split_whitespace() + .collect::() + .contains("((40)+1)"), + "{text}" + ); + assert!(!text.contains("invalid"), "{text}"); + let parsed = parse_source(&text, Path::new("unit.sv")).unwrap(); + assert_eq!(parsed.units.len(), 2); + assert!( + preprocess_sources( + &[( + "module M; localparam N=`PLUS(0); endmodule", + Path::new("separate.sv") + )], + &[], + &[] + ) + .is_err() + ); + assert!(preprocess_sources(&sources[1..], &[], &[]).is_err()); +} + +#[test] +fn later_files_retain_builtin_locations_and_preprocessing_diagnostics() { + let sources = [ + ("`define VALUE 42\n", Path::new("defs.sv")), + ( + "module M;\nlocalparam int N=`__LINE__;\ninitial $display(\"%s %d\", `__FILE__, `VALUE); endmodule", + Path::new("later.sv"), + ), + ]; + let text = preprocess_sources(&sources, &[], &[]).unwrap(); + assert!( + text.split_whitespace().collect::().contains("N=2"), + "{text}" + ); + assert!(text.contains("\"later.sv\""), "{text}"); + parse_source(&text, Path::new("defs.sv")).unwrap(); + let error = preprocess_sources(&[("`MISSING", Path::new("bad.sv"))], &[], &[]) + .unwrap_err() + .to_string(); + assert!(error.contains("bad.sv"), "{error}"); +} + +#[test] +fn serialized_macro_operators_remain_distinct_tokens() { + for sources in [ + vec![( + "`define NEG -\nmodule M(output int y); assign y=`NEG-1; endmodule", + Path::new("one.sv"), + )], + vec![ + ("`define NEG -\n", Path::new("defs.h")), + ( + "module M(output int y); assign y=`NEG-1; endmodule", + Path::new("two.sv"), + ), + ], + ] { + let expanded = preprocess_sources(&sources, &[], &[]).unwrap(); + assert!(!expanded.contains("--1"), "{expanded}"); + parse_source(&expanded, Path::new("unit.sv")).unwrap(); + } +} diff --git a/crates/celox-sv-syntax/src/preprocess.rs b/crates/celox-sv-syntax/src/preprocess.rs index e619d16855f..9944667d155 100644 --- a/crates/celox-sv-syntax/src/preprocess.rs +++ b/crates/celox-sv-syntax/src/preprocess.rs @@ -80,11 +80,45 @@ impl Preprocessed { /// A compatibility view for text-based consumers. Syntax consumers should /// use tokens and their original origins instead of parsing this text again. + /// Separators at expansion boundaries prevent adjacent tokens from merging. pub fn text(&self) -> String { - self.tokens - .iter() - .map(|token| token.text.as_str()) - .collect() + let mut text = String::new(); + let mut previous: Option<&Token> = None; + for token in &self.tokens { + if let Some(left) = previous { + // Authored adjacent tokens already have the right lexical + // boundaries. Expansion/argument boundaries need a separator: + // for example, a macro's `-` followed by `-1` must not become + // a decrement. Explicit token pastes remain a single token. + let authored_adjacent = left.origin.expansion == token.origin.expansion + && left.origin.spelling.file == token.origin.spelling.file + && left.origin.spelling.end == token.origin.spelling.start + && left.contributors.is_empty() + && token.contributors.is_empty(); + // Retained compiler directives require the name immediately + // after the backtick, even when a macro supplied that name. + let directive_name = left.text == "`" && token.identifier().is_some(); + // Comments are not terminating whitespace for escaped + // identifiers (IEEE 1800-2023 5.6.1), and a preceding slash + // can also join their opening delimiter. Only actual white + // space safely separates every token kind. + let whitespace = matches!(token.kind, TokenKind::Whitespace | TokenKind::Newline); + if left.kind == TokenKind::Comment + && left.text.starts_with("//") + && token.kind != TokenKind::Newline + { + // An included file may end in a line comment without a + // newline; terminate it before rendering its caller. + text.push('\n'); + } else if !left.is_trivia() && !whitespace && !authored_adjacent && !directive_name + { + text.push(' '); + } + } + text.push_str(&token.text); + previous = Some(token); + } + text } } @@ -1498,7 +1532,13 @@ mod tests { ..Options::default() }); let output = pp.preprocess(code, directory.join("top.sv")).unwrap(); - assert!(output.text().contains("wire included = 19;")); + assert!( + output + .text() + .split_whitespace() + .collect::() + .contains("wireincluded=19;") + ); assert_eq!(output.tokens.iter().filter(|t| t.text == "19").count(), 2); let wire = output.tokens.iter().find(|t| t.text == "wire").unwrap(); assert_eq!( @@ -1567,3 +1607,53 @@ mod tests { ); } } + +#[cfg(test)] +mod serialization_tests { + use super::*; + + #[test] + fn serialized_file_end_comments_cannot_consume_following_tokens() { + let mut pp = Preprocessor::default(); + let mut source = pp + .preprocess("// header without final newline", "header.svh") + .unwrap(); + source.merge(pp.preprocess("module M; endmodule", "caller.sv").unwrap()); + let text = source.text(); + let mut files = SourceMap::default(); + let file = files.add("serialized.sv", text.as_str()); + let tokens = lex(&files, file).unwrap(); + assert_eq!( + tokens + .iter() + .filter(|t| !t.is_trivia()) + .map(|t| t.text.as_str()) + .collect::>(), + ["module", "M", ";", "endmodule"], + "{text}" + ); + } + + #[test] + fn text_round_trip_preserves_expansion_token_boundaries() { + let code = "`define NEG -\n`define POS +\n`define LT <\n`define SLASH /\n`define EMPTY()\n`define NUM() 1\n`define ESC \\escaped\n`define CAT(a,b) a``b\n`NEG-1; `POS+1; `LT<=1; `SLASH*2; `SLASH/*block*/2; `SLASH//line\n2; `NUM().2; `NUM()e+2; `ESC+1; `ESC/*block*/ ; `ESC//line\n; \\literal/*part*/ ; `CAT(foo,bar); 1`EMPTY().2;"; + let mut pp = Preprocessor::default(); + let source = pp.preprocess(code, "tokens.sv").unwrap(); + let text = source.text(); + let mut files = SourceMap::default(); + let file = files.add("serialized.sv", text.as_str()); + let tokens = lex(&files, file).unwrap(); + let significant = |tokens: &[Token]| { + tokens + .iter() + .filter(|t| !t.is_trivia()) + .map(|t| (t.kind, t.text.clone())) + .collect::>() + }; + assert_eq!(significant(&tokens), significant(&source.tokens), "{text}"); + assert!( + text.contains("foobar"), + "explicit pasting must stay intact: {text}" + ); + } +} diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 6ef505b7af2..5e12651b1b9 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -60,6 +60,12 @@ pub(super) struct DesignArgs { /// Ordered SV file list; relative entries resolve from the list's directory. #[arg(short = 'f', long = "filelist", value_name = "FILE")] filelists: Vec, + /// Treat ordered SV files as one compilation unit (default; overrides project). + #[arg(long, conflicts_with = "separate_units")] + single_unit: bool, + /// Treat each SV file as a separate compilation unit, isolating source macros. + #[arg(long)] + separate_units: bool, /// SystemVerilog include search directory (repeatable). #[arg(short = 'I', long = "include-dir", value_name = "DIR")] include_dirs: Vec, @@ -106,6 +112,7 @@ struct Manifest { filelists: Vec, include_dirs: Vec, defines: BTreeMap, + single_unit: Option, parameters: BTreeMap, top: Option, opt_level: Option, @@ -140,6 +147,7 @@ struct Target { filelists: Vec, include_dirs: Vec, defines: BTreeMap, + single_unit: Option, parameters: BTreeMap, top: Option, opt_level: Option, @@ -157,6 +165,7 @@ pub(super) struct Design { pub sources: Vec, pub include_dirs: Vec, pub defines: BTreeMap, + single_unit: Option, pub parameters: BTreeMap, sv_parameters: BTreeMap, pub top: String, @@ -329,6 +338,7 @@ impl DesignArgs { config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; design.four_state = config.four_state; + design.single_unit = config.single_unit; if let Some(target) = selected { design.extend_parameters(&target.parameters)?; design.diagnostics.0.extend(target.diagnostics.0.clone()); @@ -352,6 +362,7 @@ impl DesignArgs { } design.max_steps = target.max_steps.or(design.max_steps); design.four_state = target.four_state.or(design.four_state); + design.single_unit = target.single_unit.or(design.single_unit); } design.timescale = timescale.map(str::parse).transpose()?; design.opt_level = opt_level @@ -382,6 +393,12 @@ impl DesignArgs { if let Some(timescale) = self.timescale { design.timescale = Some(timescale.parse()?); } + if self.single_unit { + design.single_unit = Some(true); + } + if self.separate_units { + design.single_unit = Some(false); + } if self.two_state { design.four_state = Some(false); } @@ -438,6 +455,9 @@ impl DesignArgs { if design.top.trim().is_empty() { return Err("provide --top MODULE or set top in celox.toml".to_string()); } + if !design.is_sv() && design.single_unit.is_some() { + return Err("compilation-unit options require SystemVerilog sources".into()); + } if !design.is_sv() && design.timescale.is_some() { return Err("timescale requires SystemVerilog sources".into()); } @@ -591,10 +611,15 @@ impl Design { } pub fn is_sv(&self) -> bool { - !self.sources.is_empty() + let is_module_source = |path: &PathBuf| { + path.extension() + .is_some_and(|extension| extension == "sv" || extension == "v") + }; + self.sources.iter().any(is_module_source) && self.sources.iter().all(|path| { - path.extension() - .is_some_and(|extension| extension == "sv" || extension == "v") + path.extension().is_some_and(|extension| { + matches!(extension.to_str(), Some("sv" | "v" | "svh" | "vh" | "h")) + }) }) } @@ -705,19 +730,36 @@ impl Design { .iter() .map(PathBuf::as_path) .collect::>(); + if self.single_unit.unwrap_or(true) { + let sources = self + .sources + .iter() + .map(|path| { + std::fs::read_to_string(path) + .map(|text| (text, path)) + .map_err(|error| format!("failed to read {}: {error}", path.display())) + }) + .collect::, _>>()?; + let borrowed = sources + .iter() + .map(|(text, path)| (text.as_str(), path.as_path())) + .collect::>(); + let text = celox_sv_analyzer::syntax::preprocess_sources(&borrowed, ¯os, &includes) + .map_err(|error| format!("preprocessing compilation unit failed: {error}"))?; + return Ok(vec![( + text, + self.sources.first().cloned().unwrap_or_default(), + )]); + } self.sources .iter() .map(|path| { let text = std::fs::read_to_string(path) .map_err(|error| format!("failed to read {}: {error}", path.display()))?; - let text = if macros.is_empty() && includes.is_empty() { - text - } else { - celox_sv_analyzer::syntax::preprocess_source(&text, path, ¯os, &includes) - .map_err(|error| { - format!("preprocessing {} failed: {error}", path.display()) - })? - }; + let text = celox_sv_analyzer::syntax::preprocess_source( + &text, path, ¯os, &includes, + ) + .map_err(|error| format!("preprocessing {} failed: {error}", path.display()))?; Ok((text, path.clone())) }) .collect() diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index bda55094afe..f645b57dad3 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -882,3 +882,152 @@ fn attached_simulation(executable: &Path) -> celox::Simulation