diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index f2c0fc7c47d..c5e36c0a10e 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1087,8 +1087,8 @@ chapter-5/5.9-string-word-assignment.sv 2state pass chapter-5/5.9-string-word-assignment.sv 4state pass chapter-5/5.9.1-string-special-chars.sv 2state pass chapter-5/5.9.1-string-special-chars.sv 4state pass -chapter-6/6.10--implicit_continuous_assignment.sv 2state fail -chapter-6/6.10--implicit_continuous_assignment.sv 4state fail +chapter-6/6.10--implicit_continuous_assignment.sv 2state pass +chapter-6/6.10--implicit_continuous_assignment.sv 4state pass chapter-6/6.10--implicit_port.sv 2state pass chapter-6/6.10--implicit_port.sv 4state pass chapter-6/6.10--implicit_port_connection.sv 2state pass diff --git a/crates/celox-sv-syntax/src/parser.rs b/crates/celox-sv-syntax/src/parser.rs index 9d66cd41a71..7cca39d37ab 100644 --- a/crates/celox-sv-syntax/src/parser.rs +++ b/crates/celox-sv-syntax/src/parser.rs @@ -12,6 +12,7 @@ mod declarations; mod dpi; mod expressions; mod generate; +mod implicit_nets; mod instances; mod keywords; mod modports; @@ -131,6 +132,7 @@ impl Declarations { subroutines: Vec::new(), class_stack: Vec::new(), classes: Vec::new(), + default_nettype: Some("wire".to_string()), }; let units = parser.units()?; let source_items = parser.source_items; @@ -347,6 +349,9 @@ struct Parser<'a> { /// Classes whose `endclass` is still ahead, innermost last. class_stack: Vec, classes: Vec, + /// The net type of implicit nets (IEEE 1800-2023 22.8), `None` after + /// `default_nettype none`. + default_nettype: Option, } impl Parser<'_> { diff --git a/crates/celox-sv-syntax/src/parser/declarations.rs b/crates/celox-sv-syntax/src/parser/declarations.rs index 7e2293ace91..9b16ce4c5fa 100644 --- a/crates/celox-sv-syntax/src/parser/declarations.rs +++ b/crates/celox-sv-syntax/src/parser/declarations.rs @@ -538,6 +538,7 @@ impl Parser<'_> { return Err(self.error("unfinished generate body item")); } frame.unit.items = std::mem::take(&mut frame.builder.roots); + self.declare_implicit_nets(&mut frame.unit)?; frame.unit.body = self.range(frame.body_start); if !frame.unit.external { self.expect(frame.end)?; @@ -1340,6 +1341,7 @@ impl Parser<'_> { return Ok(true); } if name == "resetall" { + self.default_nettype = Some("wire".to_string()); self.time_directives.push(TimeDirective { kind: TimeDirectiveKind::Reset, tokens: self.range(start), @@ -1364,6 +1366,9 @@ impl Parser<'_> { { return Err(self.error("invalid default_nettype value")); } + "default_nettype" => { + self.default_nettype = (self.peek() != "none").then(|| self.peek().to_string()); + } "unconnected_drive" if !matches!(self.peek(), "pull0" | "pull1") => { return Err(self.error("unconnected_drive requires pull0 or pull1")); } diff --git a/crates/celox-sv-syntax/src/parser/implicit_nets.rs b/crates/celox-sv-syntax/src/parser/implicit_nets.rs new file mode 100644 index 00000000000..09924c7691c --- /dev/null +++ b/crates/celox-sv-syntax/src/parser/implicit_nets.rs @@ -0,0 +1,334 @@ +//! Implicit nets of continuous assignment targets (IEEE 1800-2023 6.10). +//! +//! An identifier on the left-hand side of a continuous assignment that the +//! scope of the assignment does not declare names an implicit scalar net of +//! the default net type, declared in that scope. The net gets a net +//! declaration at the start of the scope, so semantic consumers see it like +//! an authored one. Under `default_nettype none` such an identifier is an +//! error (22.8). +use fxhash::FxHashSet as HashSet; + +use super::*; + +/// Marks a scope whose wildcard imports may supply any name. +const WILDCARD: &str = "*"; + +/// The implicit nets of one scope: the unit (`None`) or a generate block. +type ScopeNets = (Option, Vec<(Name, TokenRange)>); + +/// What one scope declares and holds, borrowed from the parser. +#[derive(Default)] +struct ScopeItems<'p> { + declared: HashSet<&'p str>, + /// Items whose declared names are not known here: any identifier among + /// their tokens counts as declared. + opaque: Vec, + assigns: Vec, + /// The generate blocks in the scope, each a scope of its own. + blocks: Vec, +} + +impl Parser<'_> { + /// Declare the implicit nets of the continuous assignments of `unit`. + pub(super) fn declare_implicit_nets(&mut self, unit: &mut Unit) -> Result<()> { + // Implicit nets of interfaces stay unsupported. + if unit.external + || !matches!(unit.kind, UnitKind::Module | UnitKind::Program) + || unit.assign_statements.is_empty() + { + return Ok(()); + } + let implicit = self.implicit_nets(unit); + let net_type = self.default_nettype.clone(); + if let (None, Some((_, nets))) = (&net_type, implicit.first()) { + let (name, tokens) = &nets[0]; + self.at = self.indices.partition_point(|&index| index < tokens.start); + return Err(self.error(format!( + "continuous assignment to undeclared `{}` under `default_nettype none", + name.value() + ))); + } + let net_type = net_type.as_deref().unwrap_or("wire"); + for (block, nets) in implicit { + let mut items = Vec::with_capacity(nets.len()); + for (name, tokens) in nets { + let item = self.implicit_net(name, tokens, net_type)?; + if let BodyItemKind::Net(id) = self.body_items[item.0].kind { + unit.net_declarations.push(id); + } + items.push(item); + } + let scope = match block { + None => &mut unit.items, + Some(block) => match &mut self.body_items[block.0].kind { + BodyItemKind::Block { items, .. } => items, + _ => unreachable!("a scope is a block"), + }, + }; + scope.splice(0..0, items); + } + Ok(()) + } + + /// The undeclared continuous assignment targets of `unit`, by the scope + /// (`None` for the unit, or a generate block) that declares them. + fn implicit_nets(&self, unit: &Unit) -> Vec { + let mut header = ScopeItems::default(); + for &imports in &unit.imports { + if self.tokens[imports.range()] + .iter() + .any(|token| token.text == "*") + { + header.declared.insert(WILDCARD); + } + } + for parameter in unit.parameters.iter().flatten() { + header.declared.insert(parameter.name.value()); + } + for port in &unit.ports { + match &port.kind { + PortKind::Named(name) | PortKind::Explicit { name, .. } => { + header.declared.insert(name.value()); + } + PortKind::NonAnsi(Some(expression)) => { + header.opaque.push(self.expressions[expression.0].tokens); + } + PortKind::NonAnsi(None) | PortKind::Wildcard => {} + } + } + // The names each enclosing scope declares, outermost first, and + // whether a wildcard import reaches it; a generate block at depth `d` + // sees `chain[..d]`. Nested scopes are visited depth first from an + // explicit stack. + let header_wildcard = header.declared.contains(WILDCARD); + let mut chain = vec![(header, header_wildcard)]; + let mut pending: Vec<(Option, usize)> = vec![(None, 1)]; + let mut implicit = Vec::new(); + while let Some((block, depth)) = pending.pop() { + chain.truncate(depth); + let items = match block { + None => &unit.items, + Some(block) => match &self.body_items[block.0].kind { + BodyItemKind::Block { items, .. } => items, + _ => continue, + }, + }; + let mut scope = self.scope_items(items); + let wildcard = + scope.declared.contains(WILDCARD) || chain.last().is_some_and(|(_, wild)| *wild); + let mut nets: Vec<(&Name, TokenRange)> = Vec::new(); + for &id in scope.assigns.iter().filter(|_| !wildcard) { + for assignment in &self.assign_statements[id.0].assignments { + for (name, tokens) in self.target_names(assignment.left) { + let value = name.value(); + if !self.declares(&scope, value) + && !chain.iter().any(|(outer, _)| self.declares(outer, value)) + && !nets.iter().any(|(other, _)| other.value() == value) + { + nets.push((name, tokens)); + } + } + } + } + scope + .declared + .extend(nets.iter().map(|(name, _)| name.value())); + if !nets.is_empty() { + let nets = nets + .into_iter() + .map(|(name, tokens)| (name.clone(), tokens)); + implicit.push((block, nets.collect())); + } + pending.extend(scope.blocks.drain(..).map(|block| (Some(block), depth + 1))); + chain.push((scope, wildcard)); + } + implicit + } + + /// The names the items of one scope declare, its continuous assignments + /// and its generate blocks. + fn scope_items(&self, items: &[BodyItemId]) -> ScopeItems<'_> { + let mut scope = ScopeItems::default(); + // Items of the scope, and whether each is the body of a generate + // construct without `begin`/`end`. + let mut work: Vec<(BodyItemId, bool)> = + items.iter().rev().map(|&item| (item, false)).collect(); + while let Some((item, generate_body)) = work.pop() { + let declared = &mut scope.declared; + let opaque = &mut scope.opaque; + match &self.body_items[item.0].kind { + BodyItemKind::Block { + leading_label, + label, + .. + } => { + if let Some(label) = leading_label.as_ref().or(label.as_ref()) { + insert(declared, label); + } + scope.blocks.push(item); + } + BodyItemKind::Conditional { + then_body, + otherwise, + .. + } => { + work.extend(otherwise.iter().map(|&body| (body, true))); + work.push((*then_body, true)); + } + BodyItemKind::Case { arms, .. } => { + work.extend(arms.iter().rev().map(|arm| (arm.body, true))); + } + BodyItemKind::Loop { variable, body, .. } => { + insert(declared, variable); + work.push((*body, true)); + } + BodyItemKind::Region(items) => { + work.extend(items.iter().rev().map(|&item| (item, generate_body))); + } + // A generate item without `begin`/`end` is a scope of its + // own that this pass does not extend; its names count as + // declared, so that it declares no nets elsewhere. + _ if generate_body => opaque.push(self.body_items[item.0].tokens), + BodyItemKind::Data(id) => match &self.data_declarations[id.0] { + DataDeclaration::Variables(variables) + | DataDeclaration::Constructed(variables) => { + variables + .variables + .iter() + .for_each(|variable| insert(declared, &variable.name)); + } + DataDeclaration::Unconverted(tokens) => opaque.push(*tokens), + }, + BodyItemKind::Net(id) => { + self.net_declarations[id.0] + .variables + .iter() + .for_each(|variable| insert(declared, &variable.name)); + } + BodyItemKind::Instance(id) => { + self.instantiations[id.0] + .instances + .iter() + .for_each(|instance| insert(declared, &instance.name)); + } + BodyItemKind::Dpi(id) => insert(declared, &self.dpi_declarations[id.0].name), + BodyItemKind::Parameter(id) => { + self.parameter_declarations[id.0] + .parameters + .iter() + .for_each(|parameter| insert(declared, ¶meter.name)); + } + BodyItemKind::Assign(id) => scope.assigns.push(*id), + BodyItemKind::Subroutine(id) => insert(declared, &self.subroutines[id.0].name), + BodyItemKind::TypeAlias(id) => insert(declared, &self.type_aliases[id.0].name), + BodyItemKind::PackageBinding(id) => { + for binding in &self.package_bindings[id.0].items { + match &binding.kind { + PackageBindingItemKind::Named { name, .. } => insert(declared, name), + // The names a wildcard import makes visible are + // not known here. + PackageBindingItemKind::Wildcard(_) | PackageBindingItemKind::All => { + add_wildcard(declared); + } + } + } + } + BodyItemKind::Modport(id) => { + self.modport_declarations[id.0] + .modports + .iter() + .for_each(|modport| insert(declared, &modport.name)); + } + // Unconverted declarations (genvars, events, classes, ...) + // declare names this pass does not know; any identifier in + // them counts as declared. + BodyItemKind::Unconverted { .. } => opaque.push(self.body_items[item.0].tokens), + BodyItemKind::Procedure(_) | BodyItemKind::Time(_) | BodyItemKind::Unit(_) => {} + } + } + scope + } + + /// The identifiers of an assignment target that name a whole object: + /// a name, the name a select applies to, or those of a concatenation. + fn target_names(&self, target: ExprId) -> Vec<(&Name, TokenRange)> { + let mut names = Vec::new(); + let mut work = vec![target]; + while let Some(expression) = work.pop() { + let node = &self.expressions[expression.0]; + match &node.kind { + ExprKind::Name(name) => names.push((name, node.tokens)), + ExprKind::Select { expression, .. } => work.push(*expression), + ExprKind::Concatenation(parts) => work.extend(parts.iter().rev()), + ExprKind::Group(inner) => work.push(*inner), + _ => {} + } + } + names + } + + /// Whether `scope` declares `name`, or may through an opaque item. + fn declares(&self, scope: &ScopeItems<'_>, name: &str) -> bool { + scope.declared.contains(name) + || scope.opaque.iter().any(|tokens| { + self.tokens[tokens.range()].iter().any(|token| { + matches!( + token.kind, + TokenKind::Identifier | TokenKind::EscapedIdentifier + ) && token.text.strip_prefix('\\').unwrap_or(&token.text) == name + }) + }) + } + + /// A scalar net declaration of `name` of type `net_type`. + fn implicit_net( + &mut self, + name: Name, + tokens: TokenRange, + net_type: &str, + ) -> Result { + if self.types.len() >= 1_000_000 { + return Err(self.unsupported("native type arena exceeds one million nodes")); + } + let data_type = TypeId(self.types.len()); + self.types.push(DataType { + kind: DataTypeKind::Implicit, + signed: None, + packed_dimensions: Vec::new(), + tokens, + }); + let id = NetDeclarationId(self.net_declarations.len()); + self.net_declarations.push(NetDeclaration { + net_type: net_type.to_string(), + strength: None, + vector: None, + data_type, + delay: None, + variables: vec![VariableDeclarator { + name, + dimensions: Vec::new(), + value: None, + tokens, + }], + tokens, + }); + if self.body_items.len() >= 1_000_000 { + return Err(self.unsupported("native body-item arena exceeds one million entries")); + } + let item = BodyItemId(self.body_items.len()); + self.body_items.push(BodyItem { + kind: BodyItemKind::Net(id), + tokens, + }); + Ok(item) + } +} + +fn insert<'p>(declared: &mut HashSet<&'p str>, name: &'p Name) { + declared.insert(name.value()); +} + +/// Mark a scope whose wildcard imports may supply any name. +fn add_wildcard(declared: &mut HashSet<&str>) { + declared.insert(WILDCARD); +} diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index f3729a98254..7372cf06afb 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -1381,6 +1381,58 @@ fn deep_generate_bodies_parse_clone_and_drop_on_the_default_stack() { } } +#[test] +fn deep_generate_blocks_declare_implicit_nets_on_the_default_stack() { + let syntax = parse(&format!( + "module M;logic a;{}assign x=a;{}endmodule", + "if(1) begin:g ".repeat(10_000), + "end ".repeat(10_000) + )); + let nets: Vec<_> = syntax + .net_declarations + .iter() + .flat_map(|net| &net.variables) + .map(|variable| variable.name.value()) + .collect(); + assert_eq!(nets, ["x"]); +} + +#[test] +fn continuous_assignment_targets_declare_implicit_nets_in_their_scope() { + let syntax = parse( + "module M(input a);wire d;assign {p,q[0]}=a;assign d=a;\ + if(1) begin:g assign w=a;assign p=a; end endmodule", + ); + let names = |items: &[BodyItemId]| -> Vec { + items + .iter() + .filter_map(|&item| match syntax.body_item(item).kind { + BodyItemKind::Net(id) => Some( + syntax.net_declarations[id.0].variables[0] + .name + .value() + .to_string(), + ), + _ => None, + }) + .collect() + }; + let unit = &syntax.units[0]; + assert_eq!(names(&unit.items), ["p", "q", "d"]); + let block = unit + .items + .iter() + .find_map(|&item| match &syntax.body_item(item).kind { + BodyItemKind::Conditional { then_body, .. } => Some(*then_body), + _ => None, + }) + .unwrap(); + let BodyItemKind::Block { items, .. } = &syntax.body_item(block).kind else { + panic!("generate block"); + }; + assert_eq!(names(items), ["w"]); +} + #[test] fn ordinary_net_declarations_retain_qualifiers_types_dimensions_and_values() { let code = "module M;wire signed[7:0] a[2:1],b=3+2;trireg(small)scalared[3:0]c;tri(strong0,weak1)vectored logic[4:0]#(1:2:3,4,5)d;wire T[3:0]#1 e;input wire p;C child();if(1)begin:g uwire bit q;end endmodule interface I;tri t;endinterface"; diff --git a/crates/celox-test-suite/src/sv/cases/synthesizable.vtest b/crates/celox-test-suite/src/sv/cases/synthesizable.vtest index 2874947e7fe..03cac57f448 100644 --- a/crates/celox-test-suite/src/sv/cases/synthesizable.vtest +++ b/crates/celox-test-suite/src/sv/cases/synthesizable.vtest @@ -888,3 +888,30 @@ endmodule (assert_eq default_u_bits 8) (assert_eq default_whole_negative (>= (& value 15) 8)) (assert_eq default_element_negative 0))) + +; An undeclared identifier on the left-hand side of a continuous assignment +; is an implicit scalar net of the scope of the assignment (IEEE 1800-2023 +; 6.10): here in the module, in a concatenation, and in a generate block, +; read by continuous assignments and an event list. +(case continuous_assignment_targets_declare_implicit_nets + (source "implicit_nets.sv" #" + module Top(input logic [1:0] a, output logic y, output logic [1:0] pq, + output logic g_out, output logic z); + assign x = a[1]; + assign {p, q} = a; + assign y = x; + assign pq = {p, q}; + if (1) begin : g + assign w = ~a[0]; + assign g_out = w; + end + always @(x or q) z = x ^ q; + endmodule + "#) + (top Top) + (for value (list 0 1 2 3) + (modify (set a value)) + (assert_eq y (>> value 1)) + (assert_eq pq value) + (assert_eq g_out (== (& value 1) 0)) + (assert_eq z (^ (>> value 1) (& value 1))))) diff --git a/crates/celox/tests/frontends/systemverilog/synthesizable.rs b/crates/celox/tests/frontends/systemverilog/synthesizable.rs index db5c6a7c056..bbf260b50c3 100644 --- a/crates/celox/tests/frontends/systemverilog/synthesizable.rs +++ b/crates/celox/tests/frontends/systemverilog/synthesizable.rs @@ -211,3 +211,26 @@ fn dpi_imports_need_the_sv_dpi_feature() { .to_string(); assert!(error.contains("sv-dpi"), "{error}"); } + +sv_backends! { + fn continuous_assignment_targets_declare_implicit_nets(sim) { + @case "synthesizable::continuous_assignment_targets_declare_implicit_nets"; + } +} + +// `default_nettype none` disables implicit nets (IEEE 1800-2023 22.8), so an +// undeclared continuous assignment target stays an error. +#[test] +fn default_nettype_none_rejects_undeclared_assignment_targets() { + let source = "`default_nettype none + module Top(input logic a, output logic y); + assign x = a; + assign y = x; + endmodule + `default_nettype wire"; + let error = Simulator::from_sv_sources(vec![(source, Path::new("none.sv"))], "Top") + .build_cranelift() + .expect_err("an undeclared target under `default_nettype none` is rejected") + .to_string(); + assert!(error.contains("undeclared `x`"), "{error}"); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index aa944c98e4d..80c763a727f 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -16,7 +16,7 @@ synthesis and is tested at the design level. | Area | Supported | | --- | --- | -| Modules | ANSI ports, `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | +| Modules | ANSI ports, `parameter` / `localparam`, type parameters (`parameter type`), named and positional port and parameter connections, implicit nets of output port connections and continuous assignment targets (`default_nettype none` disables them), hierarchy, instance arrays (a connection is broadcast, or split between the elements when it is as wide as all of them) | | Programs | `program` declarations with ports and parameters, instantiated from modules like a module; their `initial` procedures run in the reactive region set (see [Programs](#programs)) | | Generate | `for` (with `genvar`), `if`, `case`; constant expressions including `**` | | Packages | types, parameters, enums and functions, through `import p::*;`, `import p::x;` and `p::x` |