1use std::collections::{HashMap, HashSet};
39
40use crate::attribute::Attribute;
41use crate::entity::EntityDef;
42use crate::types::{TypeDef, TypeKind};
43use crate::version::SchemaVersion;
44
45const MAX_CHAIN_DEPTH: usize = 64;
50
51#[derive(Debug, Clone)]
56pub struct Schema {
57 name: String,
58 entities: Vec<EntityDef>,
61 types: Vec<TypeDef>,
62 entity_index: HashMap<String, usize>,
64 type_index: HashMap<String, usize>,
65 children: HashMap<String, Vec<String>>,
69 lineage: Vec<Lineage>,
75}
76
77#[derive(Debug, Clone, Default)]
79struct Lineage {
80 supertypes: Box<[Ancestor]>,
82 slots: Box<[(u32, u32)]>,
85}
86
87#[derive(Debug, Clone)]
89enum Ancestor {
90 Declared(usize),
92 Undeclared(Box<str>),
94}
95
96impl PartialEq for Schema {
98 fn eq(&self, other: &Self) -> bool {
99 self.name == other.name && self.entities == other.entities && self.types == other.types
100 }
101}
102
103impl Eq for Schema {}
104
105impl Schema {
106 #[must_use]
111 pub fn new(name: impl Into<String>, entities: Vec<EntityDef>, types: Vec<TypeDef>) -> Self {
112 let (entities, entity_index) = index_by_name(entities, |entity| &entity.name);
113 let (types, type_index) = index_by_name(types, |type_def| &type_def.name);
114 let mut children: HashMap<String, Vec<String>> = HashMap::new();
115 for entity in &entities {
116 for supertype in &entity.supertypes {
117 children
118 .entry(supertype.to_ascii_uppercase())
119 .or_default()
120 .push(entity.name.clone());
121 }
122 }
123 for names in children.values_mut() {
124 names.sort_unstable_by_key(|name| name.to_ascii_uppercase());
125 names.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
127 }
128 let mut schema = Self {
129 name: name.into(),
130 entities,
131 types,
132 entity_index,
133 type_index,
134 children,
135 lineage: Vec::new(),
136 };
137 schema.lineage = (0..schema.entities.len())
138 .map(|index| schema.derive_lineage(index))
139 .collect();
140 schema
141 }
142
143 fn derive_lineage(&self, index: usize) -> Lineage {
150 let name = self.entities[index].name.as_str();
151 let mut seen = HashSet::new();
152 seen.insert(name.to_ascii_uppercase());
153 let mut supertypes = Vec::new();
154 self.collect_supertypes(name, 0, &mut seen, &mut supertypes);
155 let mut seen = HashSet::new();
156 let mut slots = Vec::new();
157 self.collect_attributes(name, 0, &mut seen, &mut slots);
158 Lineage {
159 supertypes: supertypes.into_boxed_slice(),
160 slots: slots.into_boxed_slice(),
161 }
162 }
163
164 fn entity_position(&self, name: &str) -> Option<usize> {
170 with_folded(name, |key| self.entity_index.get(key).copied())
171 }
172
173 fn lineage_of(&self, name: &str) -> Option<&Lineage> {
175 self.entity_position(name).map(|index| &self.lineage[index])
176 }
177
178 fn ancestor_name<'s>(&'s self, ancestor: &'s Ancestor) -> &'s str {
179 match ancestor {
180 Ancestor::Declared(index) => self.entities[*index].name.as_str(),
181 Ancestor::Undeclared(name) => name,
182 }
183 }
184
185 fn slot(&self, (entity, attribute): (u32, u32)) -> &Attribute {
186 &self.entities[entity as usize].attributes[attribute as usize]
187 }
188
189 #[cfg(feature = "express")]
195 #[must_use]
196 pub fn from_express(source: &str) -> Self {
197 crate::express::parse(source)
198 }
199
200 #[cfg(feature = "express")]
206 #[must_use]
207 pub fn from_express_bytes(bytes: &[u8]) -> Self {
208 let text: String = bytes.iter().map(|&byte| byte as char).collect();
209 Self::from_express(&text)
210 }
211
212 #[must_use]
214 pub fn name(&self) -> &str {
215 &self.name
216 }
217
218 #[must_use]
223 pub fn version(&self) -> Option<SchemaVersion> {
224 SchemaVersion::from_header_token(&self.name)
225 }
226
227 #[must_use]
229 pub fn entity_count(&self) -> usize {
230 self.entities.len()
231 }
232
233 #[must_use]
235 pub fn type_count(&self) -> usize {
236 self.types.len()
237 }
238
239 #[must_use]
241 pub fn entity(&self, name: &str) -> Option<&EntityDef> {
242 self.entity_position(name)
243 .map(|index| &self.entities[index])
244 }
245
246 #[must_use]
248 pub fn type_def(&self, name: &str) -> Option<&TypeDef> {
249 with_folded(name, |key| self.type_index.get(key).copied()).map(|index| &self.types[index])
250 }
251
252 pub fn entities(&self) -> impl Iterator<Item = &EntityDef> {
254 self.entities.iter()
255 }
256
257 pub fn types(&self) -> impl Iterator<Item = &TypeDef> {
259 self.types.iter()
260 }
261
262 pub fn entity_names(&self) -> impl Iterator<Item = &str> {
266 self.entities.iter().map(|entity| entity.name.as_str())
267 }
268
269 #[must_use]
274 pub fn accepts_type(&self, declared: &str, candidate: &str) -> bool {
275 if !declared.eq_ignore_ascii_case(candidate)
279 && self.entity_position(declared).is_some()
280 && self.entity_position(candidate).is_some()
281 {
282 return self.is_a(candidate, declared);
283 }
284 self.accepts_type_inner(declared, candidate, &mut HashSet::new(), 32)
285 }
286
287 fn accepts_type_inner(
288 &self,
289 declared: &str,
290 candidate: &str,
291 seen: &mut HashSet<(String, String)>,
292 depth: usize,
293 ) -> bool {
294 if declared.eq_ignore_ascii_case(candidate) {
295 return self.entity(declared).is_some() || self.type_def(declared).is_some();
296 }
297 if depth == 0
298 || !seen.insert((
299 declared.to_ascii_uppercase(),
300 candidate.to_ascii_uppercase(),
301 ))
302 {
303 return false;
304 }
305 if self.entity(declared).is_some() && self.entity(candidate).is_some() {
306 return self.is_a(candidate, declared);
307 }
308 if let Some(definition) = self.type_def(declared) {
309 match &definition.kind {
310 TypeKind::Defined(alias) => {
311 if self.accepts_type_inner(alias, candidate, seen, depth - 1) {
312 return true;
313 }
314 }
315 TypeKind::Select(members) => {
316 if members
317 .iter()
318 .any(|member| self.accepts_type_inner(member, candidate, seen, depth - 1))
319 {
320 return true;
321 }
322 }
323 TypeKind::Enumeration(_) => {}
324 }
325 }
326 if let Some(definition) = self.type_def(candidate) {
327 if let TypeKind::Defined(alias) = &definition.kind {
328 return self.accepts_type_inner(declared, alias, seen, depth - 1);
329 }
330 }
331 false
332 }
333
334 #[must_use]
340 pub fn is_a(&self, name: &str, ancestor: &str) -> bool {
341 let Some(lineage) = self.lineage_of(name) else {
342 return false;
343 };
344 name.eq_ignore_ascii_case(ancestor)
345 || lineage.supertypes.iter().any(|super_name| {
346 self.ancestor_name(super_name)
347 .eq_ignore_ascii_case(ancestor)
348 })
349 }
350
351 #[must_use]
357 pub fn supertypes(&self, name: &str) -> Vec<&str> {
358 self.lineage_of(name)
359 .map(|lineage| {
360 lineage
361 .supertypes
362 .iter()
363 .map(|ancestor| self.ancestor_name(ancestor))
364 .collect()
365 })
366 .unwrap_or_default()
367 }
368
369 fn collect_supertypes(
370 &self,
371 name: &str,
372 depth: usize,
373 seen: &mut HashSet<String>,
374 out: &mut Vec<Ancestor>,
375 ) {
376 if depth >= MAX_CHAIN_DEPTH {
377 return;
378 }
379 let Some(def) = self.entity(name) else {
380 return;
381 };
382 for supertype in &def.supertypes {
383 if !seen.insert(supertype.to_ascii_uppercase()) {
384 continue;
385 }
386 match self.entity_position(supertype) {
387 Some(parent) => {
388 out.push(Ancestor::Declared(parent));
389 self.collect_supertypes(&self.entities[parent].name, depth + 1, seen, out);
390 }
391 None => out.push(Ancestor::Undeclared(supertype.as_str().into())),
392 }
393 }
394 }
395
396 #[must_use]
398 pub fn direct_subtypes(&self, name: &str) -> Vec<&str> {
399 with_folded(name, |key| self.children.get(key))
400 .map(|names| names.iter().map(String::as_str).collect())
401 .unwrap_or_default()
402 }
403
404 #[must_use]
408 pub fn subtypes(&self, name: &str) -> Vec<&str> {
409 let mut seen = HashSet::new();
410 seen.insert(name.to_ascii_uppercase());
411 let mut out = Vec::new();
412 let mut stack: Vec<&str> = self.direct_subtypes(name).into_iter().rev().collect();
415 while let Some(current) = stack.pop() {
416 if !seen.insert(current.to_ascii_uppercase()) {
417 continue;
418 }
419 out.push(current);
420 stack.extend(self.direct_subtypes(current).into_iter().rev());
421 }
422 out
423 }
424
425 #[must_use]
433 pub fn attributes(&self, name: &str) -> Vec<&Attribute> {
434 self.lineage_of(name)
435 .map(|lineage| lineage.slots.iter().map(|&slot| self.slot(slot)).collect())
436 .unwrap_or_default()
437 }
438
439 #[must_use]
444 pub fn attribute_count(&self, name: &str) -> usize {
445 self.lineage_of(name)
446 .map_or(0, |lineage| lineage.slots.len())
447 }
448
449 #[must_use]
452 pub fn attribute_at(&self, name: &str, slot: usize) -> Option<&Attribute> {
453 let lineage = self.lineage_of(name)?;
454 lineage.slots.get(slot).map(|&at| self.slot(at))
455 }
456
457 fn collect_attributes(
458 &self,
459 name: &str,
460 depth: usize,
461 seen: &mut HashSet<String>,
462 out: &mut Vec<(u32, u32)>,
463 ) {
464 if depth > MAX_CHAIN_DEPTH {
465 return;
466 }
467 let Some(index) = self.entity_position(name) else {
468 return;
469 };
470 let def = &self.entities[index];
471 if !seen.insert(def.name.to_ascii_uppercase()) {
472 return;
473 }
474 for supertype in &def.supertypes {
475 self.collect_attributes(supertype, depth + 1, seen, out);
476 }
477 let owner = u32::try_from(index).expect("fewer than 2^32 entity declarations");
478 out.extend((0..def.attributes.len()).map(|attribute| {
479 (
480 owner,
481 u32::try_from(attribute).expect("fewer than 2^32 attributes"),
482 )
483 }));
484 }
485
486 #[must_use]
488 pub fn attribute_names(&self, name: &str) -> Vec<&str> {
489 self.attributes(name)
490 .into_iter()
491 .map(|attribute| attribute.name.as_str())
492 .collect()
493 }
494
495 #[must_use]
502 pub fn resolve_defined(&self, name: &str) -> String {
503 let mut current = name.to_string();
504 for _ in 0..MAX_CHAIN_DEPTH {
505 let Some(def) = self.type_def(¤t) else {
506 return current;
507 };
508 let TypeKind::Defined(target) = &def.kind else {
509 return current;
510 };
511 let next = target.trim().to_string();
512 if next.eq_ignore_ascii_case(¤t) {
513 return current;
514 }
515 current = next;
516 }
517 current
518 }
519}
520
521const FOLD_BUFFER: usize = 128;
523
524fn with_folded<R>(name: &str, f: impl FnOnce(&str) -> R) -> R {
530 if !name.bytes().any(|byte| byte.is_ascii_lowercase()) {
531 return f(name);
532 }
533 if name.len() <= FOLD_BUFFER {
534 let mut buffer = [0u8; FOLD_BUFFER];
535 let folded = &mut buffer[..name.len()];
536 folded.copy_from_slice(name.as_bytes());
537 folded.make_ascii_uppercase();
538 let folded = std::str::from_utf8(folded).expect("ASCII folding keeps UTF-8 valid");
539 return f(folded);
540 }
541 f(&name.to_ascii_uppercase())
542}
543
544fn index_by_name<T>(
547 declarations: Vec<T>,
548 name: impl Fn(&T) -> &String,
549) -> (Vec<T>, HashMap<String, usize>) {
550 let mut kept: Vec<T> = Vec::with_capacity(declarations.len());
551 let mut index = HashMap::with_capacity(declarations.len());
552 for declaration in declarations {
553 let key = name(&declaration).to_ascii_uppercase();
554 match index.get(&key) {
555 Some(&position) => kept[position] = declaration,
556 None => {
557 index.insert(key, kept.len());
558 kept.push(declaration);
559 }
560 }
561 }
562 (kept, index)
563}
564
565#[cfg(test)]
566mod tests {
567 use super::*;
568
569 fn chain() -> Schema {
571 Schema::new(
572 "IFC4",
573 vec![
574 EntityDef::new("IfcRoot")
575 .abstract_entity()
576 .with_attribute(Attribute::new("GlobalId", "IfcGloballyUniqueId"))
577 .with_attribute(Attribute::new("OwnerHistory", "IfcOwnerHistory").optional())
578 .with_attribute(Attribute::new("Name", "IfcLabel").optional())
579 .with_attribute(Attribute::new("Description", "IfcText").optional()),
580 EntityDef::new("IfcObjectDefinition")
581 .abstract_entity()
582 .with_supertype("IfcRoot"),
583 EntityDef::new("IfcObject")
584 .with_supertype("IfcObjectDefinition")
585 .with_attribute(Attribute::new("ObjectType", "IfcLabel").optional()),
586 ],
587 vec![
588 TypeDef::new("IfcLengthMeasure", TypeKind::Defined("REAL".into())),
589 TypeDef::new(
590 "IfcPositiveLengthMeasure",
591 TypeKind::Defined("IfcLengthMeasure".into()),
592 ),
593 ],
594 )
595 }
596
597 #[test]
598 fn the_declared_schema_name_maps_onto_a_known_ifc_version() {
599 let schema = chain();
600 assert_eq!(schema.name(), "IFC4");
601 assert_eq!(schema.version(), Some(SchemaVersion::Ifc4));
602 }
603
604 #[test]
606 fn an_unrecognized_schema_name_has_no_version_but_still_works() {
607 let schema = Schema::new(
608 "AP242",
609 vec![EntityDef::new("Product").with_attribute(Attribute::new("Id", "Identifier"))],
610 Vec::new(),
611 );
612 assert_eq!(schema.version(), None, "not an IFC schema");
613 assert_eq!(schema.attribute_names("Product"), ["Id"]);
614 }
615
616 #[test]
617 fn inherited_attributes_come_first_in_positional_order() {
618 assert_eq!(
619 chain().attribute_names("IFCOBJECT"),
620 [
621 "GlobalId",
622 "OwnerHistory",
623 "Name",
624 "Description",
625 "ObjectType"
626 ],
627 );
628 }
629
630 #[test]
631 fn defined_types_resolve_through_the_alias_chain() {
632 assert_eq!(chain().resolve_defined("IfcPositiveLengthMeasure"), "REAL");
633 }
634
635 #[test]
636 fn subtype_tests_cross_intermediate_levels_and_are_reflexive_only_when_declared() {
637 let schema = chain();
638 assert!(schema.is_a("IFCOBJECT", "IfcRoot"));
639 assert!(schema.is_a("IfcObject", "IfcObject"));
640 assert!(!schema.is_a("IfcRoot", "IfcObject"));
641 assert!(!schema.is_a("NotAThing", "NotAThing"));
642 assert_eq!(
643 schema.subtypes("ifcroot"),
644 ["IfcObjectDefinition", "IfcObject"]
645 );
646 assert_eq!(
647 schema.supertypes("IfcObject"),
648 ["IfcObjectDefinition", "IfcRoot"]
649 );
650 }
651
652 #[test]
653 fn cyclic_chains_terminate() {
654 let schema = Schema::new(
655 "S",
656 vec![
657 EntityDef::new("A").with_supertype("B"),
658 EntityDef::new("B").with_supertype("A"),
659 ],
660 vec![
661 TypeDef::new("X", TypeKind::Defined("Y".into())),
662 TypeDef::new("Y", TypeKind::Defined("X".into())),
663 ],
664 );
665 assert_eq!(schema.supertypes("A"), ["B"]);
666 assert_eq!(schema.subtypes("A"), ["B"]);
667 let resolved = schema.resolve_defined("X");
668 assert!(resolved == "X" || resolved == "Y");
669 }
670
671 #[test]
672 fn an_undeclared_supertype_is_still_named_in_both_directions() {
673 let schema = Schema::new(
674 "S",
675 vec![EntityDef::new("A").with_supertype("Missing")],
676 Vec::new(),
677 );
678 assert_eq!(schema.supertypes("A"), ["Missing"]);
679 assert!(schema.is_a("A", "Missing"));
680 assert_eq!(schema.subtypes("Missing"), ["A"]);
681 }
682
683 #[test]
684 fn a_repeated_name_keeps_its_first_position_and_last_declaration() {
685 let schema = Schema::new(
686 "S",
687 vec![
688 EntityDef::new("A"),
689 EntityDef::new("B"),
690 EntityDef::new("a").with_attribute(Attribute::new("X", "INTEGER")),
691 ],
692 Vec::new(),
693 );
694 assert_eq!(schema.entity_count(), 2);
695 assert_eq!(schema.entity_names().collect::<Vec<_>>(), ["a", "B"]);
696 assert_eq!(schema.attribute_names("A"), ["X"]);
697 }
698}
699
700#[cfg(all(test, feature = "express"))]
703mod parity_with_step {
704 use super::*;
705
706 const TREE: &str = "\
707SCHEMA TREE;
708ENTITY Root; Id : INTEGER; END_ENTITY;
709ENTITY Wall SUBTYPE OF (Root); Name : OPTIONAL STRING; END_ENTITY;
710ENTITY Door SUBTYPE OF (Root); END_ENTITY;
711ENTITY WallStandardCase SUBTYPE OF (Wall); Tag : LIST [1:?] OF STRING; END_ENTITY;
712ENTITY WallElementedCase SUBTYPE OF (Wall); END_ENTITY;
713ENTITY Orphan SUBTYPE OF (Missing); END_ENTITY;
714ENTITY Unrelated; END_ENTITY;
715TYPE Count = INTEGER; END_TYPE;
716TYPE PositiveCount = Count; END_TYPE;
717TYPE Colour = ENUMERATION OF (RED, GREEN); END_TYPE;
718END_SCHEMA;";
719
720 #[test]
721 fn every_query_matches_the_step_schema_graph() {
722 let owned = Schema::from_express(TREE);
723 let graph = openbim_step::SchemaGraph::from_express(TREE);
724 assert_eq!(owned.name(), graph.name());
725 assert_eq!(owned.entity_count(), graph.entity_count());
726 assert_eq!(owned.type_count(), graph.type_count());
727 let mut names: Vec<&str> = graph.entity_names().collect();
728 names.extend(["Missing", "NotAThing"]);
729 for &name in &names {
730 assert_eq!(owned.supertypes(name), graph.supertypes(name), "{name}");
731 assert_eq!(owned.subtypes(name), graph.subtypes(name), "{name}");
732 assert_eq!(
733 owned.direct_subtypes(name),
734 graph.direct_subtypes(name),
735 "{name}"
736 );
737 assert_eq!(
738 owned.attribute_names(name),
739 graph.attribute_names(name),
740 "{name}"
741 );
742 for &ancestor in &names {
743 assert_eq!(
744 owned.is_a(name, ancestor),
745 graph.is_a(name, ancestor),
746 "{name} / {ancestor}"
747 );
748 }
749 }
750 for name in ["PositiveCount", "Colour", "Count", "Unknown"] {
751 assert_eq!(owned.resolve_defined(name), graph.resolve_defined(name));
752 }
753 }
754}