diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 72556af556b..183da81ab40 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -223,6 +223,7 @@ mod dimensions; mod dpi; mod enums; mod expression_binding; +mod expression_types; mod expressions; mod ff_process; mod functions; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 63805b64113..3d4acc5d059 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -7,7 +7,7 @@ mod direct; mod enums; mod format_patterns; mod lvalues; -mod objects; +pub(super) mod objects; mod references; #[cfg(test)] mod selected; diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index e3228a4f890..ac19baf73c3 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -37,98 +37,8 @@ pub(in crate::ast) fn native_class( native: &Declarations, dimensions: &PackedDimensions, ) -> Option { - let id = ungroup(id, native); - if let ExprKind::Call { expression, .. } = &native.expression(id).kind - && let ExprKind::Member { - expression: base, - separator, - name, - } = &native.expression(*expression).kind - && separator == "::" - && name.spelling == "self" - && super::super::processes::scope(tree, session, *base, native, dimensions) - { - return Some(super::super::processes::CLASS.to_owned()); - } - // The result of a function or method that returns a class handle, whose - // members the call may select (IEEE 1800-2023 8.4). - if let ExprKind::Call { expression, .. } = &native.expression(id).kind { - let name = match method(tree, session, *expression, native, dimensions) { - Ok(Some((name, ..))) => name, - Ok(None) => super::direct::callable_name(tree, *expression, native)?, - Err(_) => return None, - }; - return dimensions.function_return_types.get(&name)?.class.clone(); - } - // A class handle member of an unpacked structure variable. - if let Some(name) = unpacked_structs::native_member(ungroup(id, native), native, dimensions) { - return dimensions.get(&name)?.class.clone(); - } - // A class handle member of a container element of unpacked structure type. - if let Ok(Some((ty, _))) = containers::element_member(id, native, tree, session, dimensions) { - return ty.class().map(str::to_owned); - } - let expression = native.expression(ungroup(id, native)); - if let ExprKind::Select { - expression, - dimension, - } = &expression.kind - && matches!(dimension.kind, celox_sv_syntax::DimensionKind::Index(_)) - { - if let Some(ty) = containers::native_type(*expression, native, tree, session, dimensions) - .ok() - .flatten() - { - return ty.element.class().map(str::to_owned); - } - let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind else { - return None; - }; - let ty = dimensions.get(&instances::normalize_identifier(&name.spelling))?; - return ty - .container - .as_ref() - .and_then(|ty| ty.element.class().map(str::to_owned)) - .or_else(|| ty.class.clone().filter(|_| !ty.unpacked.is_empty())); - } - if let ExprKind::Name(name) = &expression.kind { - let name = instances::normalize_identifier(&name.spelling); - if let Some(ty) = dimensions.get(&name) { - return ty.class.clone(); - } - if name == "super" { - return super_class(tree, session, dimensions); - } - } - // The receiver of `h.p` is resolved once for both kinds of property, so - // a chain `a.b.c` takes one walk. - if let ExprKind::Member { - expression: receiver, - separator, - name, - } = &expression.kind - && separator == "." - // Otherwise a member of a property of unpacked structure type, found - // as a property below. - && let Some(owner) = native_class(tree, session, *receiver, native, dimensions) - { - let member = instances::normalize_identifier(&name.spelling); - let receiver = (!is_super(*receiver, native)).then_some(*receiver); - if let Some((property, _)) = - property_in(tree, session, dimensions, &owner, &member, receiver).ok()? - { - return property.r#type.class().map(str::to_owned); - } - return class(tree, session, dimensions, &owner) - .ok()? - .static_property(&member) - .and_then(|property| property.r#type.class().map(str::to_owned)); - } - if let Some(class) = static_property_class(tree, session, id, native, dimensions).ok()? { - return Some(class); - } - let (property, _) = property(tree, session, id, native, dimensions).ok()??; - property.r#type.class().map(str::to_owned) + let ty = expression_types::type_of(tree, session, id, native, dimensions)?; + expression_types::class_name(&session.types, ty) } /// Access depends on the lexical class, not the class of the receiver (8.18). @@ -173,10 +83,10 @@ pub(in crate::ast) fn scope_class(dimensions: &PackedDimensions) -> Option, - session: &mut Session, dimensions: &PackedDimensions, + session: &mut Session, ) -> Option { dimensions.get(THIS)?; class(tree, session, dimensions, &scope_class(dimensions)?) @@ -187,7 +97,7 @@ fn super_class( /// Whether native expression `id` is `super`, which passes the enclosing /// method's `this`. -fn is_super(id: ExprId, native: &Declarations) -> bool { +pub(in crate::ast) fn is_super(id: ExprId, native: &Declarations) -> bool { matches!(&native.expression(ungroup(id, native)).kind, ExprKind::Name(name) if name.spelling == "super") } @@ -413,6 +323,19 @@ fn static_property_class( native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { + Ok(static_property_type(tree, id, native, dimensions, session)? + .and_then(|ty| ty.class().map(str::to_owned))) +} + +/// The type of the static property that native expression `id` names, +/// `h.p` or `C::p`. +pub(in crate::ast) fn static_property_type( + tree: &AnalysisContext<'_>, + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, + session: &mut Session, +) -> Converted> { let ExprKind::Member { expression, separator, @@ -431,7 +354,28 @@ fn static_property_class( }; Ok(class(tree, session, dimensions, &class_name)? .static_property(&instances::normalize_identifier(&name.spelling)) - .and_then(|property| property.r#type.class().map(str::to_owned))) + .map(|property| property.r#type.clone())) +} + +/// The type of property `member` of class `owner`, an instance property +/// read through `receiver` or a static one. +pub(in crate::ast) fn member_type( + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + owner: &str, + member: &str, + receiver: Option, + session: &mut Session, +) -> Option { + if let Some((property, _)) = + property_in(tree, session, dimensions, owner, member, receiver).ok()? + { + return Some(property.r#type); + } + class(tree, session, dimensions, owner) + .ok()? + .static_property(member) + .map(|property| property.r#type.clone()) } /// The property that native expression `id` names, `h.p` or an unqualified diff --git a/crates/celox-sv-analyzer/src/ast/expression_types.rs b/crates/celox-sv-analyzer/src/ast/expression_types.rs new file mode 100644 index 00000000000..d5aec1467ff --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_types.rs @@ -0,0 +1,152 @@ +//! The self-determined types of native expressions, judged before they are +//! bound, as semantic types. +//! +//! Each kind of operand is resolved from what declares it: a variable from +//! its shape, a property from its class, a call from the type its function +//! returns, an element from the array it selects from. An operand that this +//! does not resolve yet has no type, and checks that need one skip it. + +use super::*; +use celox_sv_syntax::{Declarations, DimensionKind, ExprId, ExprKind}; +use expression_binding::{objects, ungroup}; +use semantic_types::{Decl, TyData, TyId}; + +/// The type of native expression `id`. +pub(super) fn type_of( + tree: &AnalysisContext<'_>, + session: &mut Session, + id: ExprId, + native: &Declarations, + dims: &PackedDimensions, +) -> Option { + let of_type = |session: &mut Session, ty: &Type| { + semantic_types::of_type(&mut session.types, &tree.functions, ty, &dims.const_env) + }; + let of_shape = |session: &mut Session, shape: &VariableDimensions| { + semantic_types::of_shape(&mut session.types, &tree.functions, shape, &dims.const_env) + }; + let class = |session: &mut Session, name: &str| { + session + .types + .intern(TyData::Class(Decl::Class(name.into()))) + }; + let id = ungroup(id, native); + if let ExprKind::Call { expression, .. } = &native.expression(id).kind { + // `process::self()` (9.7). + if let ExprKind::Member { + expression: base, + separator, + name, + } = &native.expression(*expression).kind + && separator == "::" + && name.spelling == "self" + && processes::scope(tree, session, *base, native, dims) + { + return Some(class(session, processes::CLASS)); + } + // What the function or method returns. + let name = match objects::method(tree, session, *expression, native, dims) { + Ok(Some((name, ..))) => name, + Ok(None) => expression_binding::callable_name(tree, *expression, native)?, + Err(_) => return None, + }; + let returns = dims.function_return_types.get(&name)?; + return match &returns.class { + Some(name) => Some(class(session, name)), + None if returns.string => Some(session.types.intern(TyData::String)), + None => None, + }; + } + // A member of an unpacked structure variable. + if let Some(name) = unpacked_structs::native_member(id, native, dims) { + return of_shape(session, dims.get(&name)?); + } + // A member of a container element of unpacked structure type. + if let Ok(Some((ty, _))) = containers::element_member(id, native, tree, session, dims) { + return of_type(session, &ty); + } + match &native.expression(id).kind { + ExprKind::Select { + expression, + dimension, + } if matches!(dimension.kind, DimensionKind::Index(_)) => { + if let Some(container) = + containers::native_type(*expression, native, tree, session, dims) + .ok() + .flatten() + { + return of_type(session, &container.element); + } + let ExprKind::Name(name) = &native.expression(ungroup(*expression, native)).kind else { + return None; + }; + let shape = dims.get(&instances::normalize_identifier(&name.spelling))?; + if let Some(container) = &shape.container { + return of_type(session, &container.element); + } + let array = of_shape(session, shape)?; + match session.types.data(array) { + TyData::Array { element, .. } => Some(*element), + _ => None, + } + } + ExprKind::Name(name) => { + let name = instances::normalize_identifier(&name.spelling); + if let Some(shape) = dims.get(&name) { + return of_shape(session, shape); + } + if name == "super" { + let base = objects::super_class(tree, dims, session)?; + return Some(class(session, &base)); + } + property_type(tree, session, id, native, dims) + } + // The receiver of `h.p` is resolved once for both kinds of property, + // so a chain `a.b.c` takes one walk. + ExprKind::Member { + expression: receiver, + separator, + name, + } if separator == "." + // Otherwise a member of a property of unpacked structure type, + // found as a property below. + && let Some(owner) = type_of(tree, session, *receiver, native, dims) + .and_then(|receiver| class_name(&session.types, receiver)) => + { + let member = instances::normalize_identifier(&name.spelling); + let receiver = (!objects::is_super(*receiver, native)).then_some(*receiver); + let ty = objects::member_type(tree, dims, &owner, &member, receiver, session)?; + of_type(session, &ty) + } + _ => property_type(tree, session, id, native, dims), + } +} + +/// The type of the property that native expression `id` names: a static +/// property `h.p` or `C::p`, or an instance property. +fn property_type( + tree: &AnalysisContext<'_>, + session: &mut Session, + id: ExprId, + native: &Declarations, + dims: &PackedDimensions, +) -> Option { + let ty = match objects::static_property_type(tree, id, native, dims, session).ok()? { + Some(ty) => ty, + None => { + objects::property(tree, session, id, native, dims) + .ok()?? + .0 + .r#type + } + }; + semantic_types::of_type(&mut session.types, &tree.functions, &ty, &dims.const_env) +} + +/// The class of a handle of type `id`. +pub(super) fn class_name(table: &semantic_types::TyTable, id: TyId) -> Option { + match table.data(id) { + TyData::Class(Decl::Class(name)) => Some(name.to_string()), + _ => None, + } +} diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types.rs b/crates/celox-sv-analyzer/src/ast/semantic_types.rs index 95f64014b47..de71fc72147 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types.rs @@ -17,7 +17,7 @@ mod spelling; #[cfg(test)] mod tests; -pub(super) use conversion::of_shape; +pub(super) use conversion::{of_shape, of_type}; /// An interned semantic type of a [`TyTable`]. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] 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