Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions crates/constraints/src/duplicate_type_paths.rs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Records and entities share one type namespace, enforced by builder validation and the new DuplicateTypePaths base constraint.

Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use quent_schema::visitor::{Cursor, Element, Visitor};
use std::collections::HashSet;

/// Reports paths declared by both a record and an entity.
#[derive(Default)]
pub(crate) struct DuplicateTypePaths {
found: Vec<String>,
}

impl Visitor for DuplicateTypePaths {
type Output = Vec<String>;

fn visit(&mut self, cursor: &Cursor) {
let Element::Schema(schema) = cursor.current() else {
return;
};
let records: HashSet<_> = schema.records().map(|record| record.path()).collect();
self.found.extend(
schema
.entities()
.filter(|entity| records.contains(entity.path()))
.map(|entity| entity.path().to_string()),
);
}

fn finish(self) -> Self::Output {
self.found
}
}

#[cfg(test)]
mod tests {
use super::*;
use quent_schema::test_utils::{entity, event, record, unchecked_schema};

#[test]
fn reports_a_path_used_by_both_type_kinds() {
let schema = unchecked_schema(
"Schema",
[
entity("Shared", [event("event", [])]),
entity("Foo::Q", [event("event", [])]),
entity("Bar::Q", [event("event", [])]),
],
[
record("Shared", []),
record("Foo::R", []),
record("Bar::R", []),
],
);

assert_eq!(
schema.walk(DuplicateTypePaths::default()),
["Shared".to_string()]
);
}
}
2 changes: 1 addition & 1 deletion crates/constraints/src/entities_without_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ impl Visitor for EntitiesWithoutEvents {
if let Element::Entity(entity) = cursor.current()
&& entity.events().len() == 0
{
self.entities.push(entity.name().to_string());
self.entities.push(entity.path().to_string());
}
}

Expand Down
10 changes: 9 additions & 1 deletion crates/constraints/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

pub mod utils;

mod duplicate_type_paths;
mod entities_without_events;
mod recursive_record;
mod unregistered_constraints;
Expand Down Expand Up @@ -53,6 +54,8 @@ pub struct BaseConstraintsError {
pub recursive_records: Vec<String>,
/// Entities that declare no events.
pub entities_without_events: Vec<String>,
/// Paths declared by both a record and an entity.
pub duplicate_type_paths: Vec<String>,
}
impl Display for BaseConstraintsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand All @@ -63,6 +66,7 @@ impl Display for BaseConstraintsError {
utils::bullet_list(&self.invalid_references),
utils::bullet_list(&self.recursive_records),
utils::bullet_list(&self.entities_without_events),
utils::bullet_list(&self.duplicate_type_paths),
]
.join("\n")
)
Expand Down Expand Up @@ -129,12 +133,14 @@ pub fn validate<C: Constraints>(schema: &Schema) -> Report<C::Output> {
unregistered_constraints,
recursive_records,
entities_without_events,
duplicate_type_paths,
results,
) = schema.walk((
unresolved_refs::UnresolvedReferences::default(),
unregistered_constraints::UnregisteredConstraints::new(C::NAMES),
recursive_record::RecursiveRecords::default(),
entities_without_events::EntitiesWithoutEvents::default(),
duplicate_type_paths::DuplicateTypePaths::default(),
C::default(),
));
Report {
Expand All @@ -143,12 +149,14 @@ pub fn validate<C: Constraints>(schema: &Schema) -> Report<C::Output> {
invalid_references.len(),
recursive_records.len(),
entities_without_events.len(),
duplicate_type_paths.len(),
) {
(0, 0, 0) => Ok(()),
(0, 0, 0, 0) => Ok(()),
_ => Err(BaseConstraintsError {
invalid_references,
recursive_records,
entities_without_events,
duplicate_type_paths,
}),
},
results,
Expand Down
47 changes: 28 additions & 19 deletions crates/constraints/src/recursive_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::collections::BTreeSet;

use petgraph::{algo::tarjan_scc, graphmap::DiGraphMap};
use quent_schema::{
DataType, Identifier,
DataType, Path,
visitor::{Cursor, Element, Visitor},
};
use rustc_hash::FxHashMap;
Expand All @@ -15,7 +15,7 @@ use rustc_hash::FxHashMap;
#[derive(Default)]
pub(crate) struct RecursiveRecords {
// Record name -> the records its fields reference.
edges: FxHashMap<Identifier, Vec<Identifier>>,
edges: FxHashMap<Path, Vec<Path>>,
}

impl Visitor for RecursiveRecords {
Expand All @@ -29,21 +29,21 @@ impl Visitor for RecursiveRecords {
&& let [_, Element::Record(source), ..] = cursor.elements()
{
self.edges
.entry(source.name().clone())
.entry(source.path().clone())
.or_default()
.push(target.clone());
}
}

fn finish(self) -> Self::Output {
// Construct a graph of all records referencing all other records.
let graph: DiGraphMap<&Identifier, ()> = self
let graph: DiGraphMap<&Path, ()> = self
.edges
.iter()
.flat_map(|(source, targets)| targets.iter().map(move |target| (source, target)))
.collect();

let mut recursive: BTreeSet<&Identifier> = BTreeSet::new();
let mut recursive: BTreeSet<&Path> = BTreeSet::new();
// Records in a strongly connected component of more than one node are
// mutually recursive.
for scc in tarjan_scc(&graph) {
Expand All @@ -66,7 +66,7 @@ impl Visitor for RecursiveRecords {
mod tests {
use super::*;
use quent_schema::Schema;
use quent_schema::test_utils::{entity, event, field, ident, record, schema};
use quent_schema::test_utils::{entity, event, field, record, record_type, schema};

fn walk(schema: &Schema) -> Vec<String> {
schema.walk(RecursiveRecords::default())
Expand All @@ -79,7 +79,7 @@ mod tests {
"S",
vec![],
vec![
record("S", vec![field("f", DataType::Record(ident("R")))]),
record("S", vec![field("f", record_type("R"))]),
record("R", vec![field("g", DataType::U64)]),
],
);
Expand All @@ -91,7 +91,7 @@ mod tests {
let s = schema(
"S",
vec![],
vec![record("R", vec![field("f", DataType::Record(ident("R")))])],
vec![record("R", vec![field("f", record_type("R"))])],
);
assert_eq!(walk(&s), vec!["R".to_string()]);
}
Expand All @@ -102,8 +102,8 @@ mod tests {
"S",
vec![],
vec![
record("A", vec![field("f", DataType::Record(ident("B")))]),
record("B", vec![field("g", DataType::Record(ident("A")))]),
record("A", vec![field("f", record_type("B"))]),
record("B", vec![field("g", record_type("A"))]),
],
);
assert_eq!(walk(&s), vec!["A".to_string(), "B".to_string()]);
Expand All @@ -112,16 +112,11 @@ mod tests {
#[test]
fn recursion_through_option_and_list_wrappers_is_reported() {
let cases = [
(
"A",
DataType::Option(Box::new(DataType::Record(ident("A")))),
),
("B", DataType::List(Box::new(DataType::Record(ident("B"))))),
("A", DataType::Option(Box::new(record_type("A")))),
("B", DataType::List(Box::new(record_type("B")))),
(
"C",
DataType::List(Box::new(DataType::Option(Box::new(DataType::Record(
ident("C"),
))))),
DataType::List(Box::new(DataType::Option(Box::new(record_type("C"))))),
),
];
for (name, ty) in cases {
Expand All @@ -136,10 +131,24 @@ mod tests {
"S",
vec![entity(
"E",
vec![event("Ev", vec![field("f", DataType::Record(ident("R")))])],
vec![event("Ev", vec![field("f", record_type("R"))])],
)],
vec![record("R", vec![field("g", DataType::U64)])],
);
assert!(walk(&s).is_empty());
}

#[test]
fn recursion_across_namespaces_is_reported() {
let s = schema(
"S",
[],
[
record("Foo::A", [field("b", record_type("Bar::B"))]),
record("Bar::B", [field("a", record_type("Foo::A"))]),
],
);

assert_eq!(walk(&s), ["Bar::B".to_string(), "Foo::A".to_string()]);
}
}
29 changes: 19 additions & 10 deletions crates/constraints/src/unresolved_refs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ impl Visitor for UnresolvedReferences {
mod tests {
use super::*;
use quent_schema::Schema;
use quent_schema::test_utils::{entity, event, field, ident, record, schema};
use quent_schema::test_utils::{entity, event, field, record, record_type, schema};

fn unresolved(schema: &Schema) -> Vec<String> {
schema.walk(UnresolvedReferences::default())
Expand All @@ -47,7 +47,7 @@ mod tests {
"E",
vec![event("Ev", vec![field("f", DataType::U64)])],
)],
vec![record("R", vec![field("rf", DataType::Record(ident("R")))])],
vec![record("R", vec![field("rf", record_type("R"))])],
);
assert!(unresolved(&s).is_empty());
}
Expand All @@ -58,10 +58,7 @@ mod tests {
"S",
vec![entity(
"E",
vec![event(
"Ev",
vec![field("f", DataType::Record(ident("ghost")))],
)],
vec![event("Ev", vec![field("f", record_type("ghost"))])],
)],
vec![],
);
Expand All @@ -77,7 +74,7 @@ mod tests {
"S",
vec![entity(
"E",
vec![event("Ev", vec![field("f", DataType::Record(ident("R")))])],
vec![event("Ev", vec![field("f", record_type("R"))])],
)],
vec![record("R", vec![])],
);
Expand All @@ -86,14 +83,26 @@ mod tests {

#[test]
fn references_into_nested_data_types_are_checked() {
let ty = DataType::Option(Box::new(DataType::List(Box::new(DataType::Record(ident(
"ghost",
))))));
let ty = DataType::Option(Box::new(DataType::List(Box::new(record_type("ghost")))));
let s = schema(
"S",
vec![entity("E", vec![event("Ev", vec![field("f", ty)])])],
vec![],
);
assert!(unresolved(&s).iter().any(|r| r.contains("ghost")));
}

#[test]
fn qualified_record_reference_resolves() {
let s = schema(
"S",
[entity(
"Bar::E",
[event("Ev", [field("f", record_type("Foo::R"))])],
)],
[record("Foo::R", [])],
);

assert!(unresolved(&s).is_empty());
}
}
9 changes: 4 additions & 5 deletions crates/constraints/tests/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use quent_constraints::{Constraint, validate};
use quent_schema::{
Annotations, Cardinality, DataType, Field, Schema,
builder::{AnnotationsBuilder, EntityBuilder, EventBuilder, RecordBuilder, SchemaBuilder},
test_utils::{self, entity, event, eventless_entity, field, ident, record, schema},
test_utils::{
self, entity, event, eventless_entity, field, ident, record, record_type, schema,
},
visitor::{Cursor, Visitor},
};

Expand All @@ -26,10 +28,7 @@ fn ghost_ref_schema() -> Schema {
"S",
vec![entity(
"E",
vec![event(
"Ev",
vec![field("f", DataType::Record(ident("ghost")))],
)],
vec![event("Ev", vec![field("f", record_type("ghost"))])],
)],
vec![],
)
Expand Down
14 changes: 7 additions & 7 deletions crates/fsm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::collections::HashSet;

use quent_constraints::Constraint;
use quent_schema::builder::{AnnotationsBuilder, BuilderError, EntityBuilder, EventBuilder};
use quent_schema::{Annotations, Cardinality, Entity, Field, Identifier};
use quent_schema::{Annotations, Cardinality, Entity, Field, Identifier, Path};
use thiserror::Error;

use crate::{ExitStates, Fsm, FsmConstraint, FsmError, Transition, check_entity};
Expand All @@ -30,7 +30,7 @@ pub struct StateDecl {
/// [`Self::build`] validates the topology with the same checks as
/// [`crate::FsmConstraint`], so a built entity is always valid.
pub struct FsmEntityBuilder {
id: Identifier,
path: Path,
annotations: AnnotationsBuilder,
states: Vec<StateDecl>,
}
Expand Down Expand Up @@ -58,10 +58,10 @@ pub enum FsmEntityBuilderError {
}

impl FsmEntityBuilder {
/// Begin an FSM entity named `id`.
pub fn new(id: Identifier) -> Self {
/// Begin an FSM entity at `path`.
pub fn new(path: impl Into<Path>) -> Self {
Self {
id,
path: path.into(),
annotations: AnnotationsBuilder::new(),
states: Vec::new(),
}
Expand Down Expand Up @@ -99,7 +99,7 @@ impl FsmEntityBuilder {
/// topology is invalid.
pub fn build(self) -> Result<Entity, FsmEntityBuilderError> {
let Self {
id,
path,
mut annotations,
states,
} = self;
Expand Down Expand Up @@ -148,7 +148,7 @@ impl FsmEntityBuilder {
ExitStates::new(first_exit.clone(), other_exits.to_vec()),
);

let mut entity = EntityBuilder::new(id);
let mut entity = EntityBuilder::new(path);
for state in states {
// An isolated state has no place on the topology; the FSM constraint
// reports it, so `Once` here is only a stand-in.
Expand Down
Loading