Skip to main content

ifc_schema/
registry.rs

1//! The assembled, queryable IFC schema.
2//!
3//! # What this owns
4//!
5//! Supertype chains, Part 21 positional attribute order, case-insensitive
6//! lookup and defined-type alias resolution. They are not IFC concepts --
7//! every EXPRESS schema serialized as Part 21 shares them -- but this crate
8//! answers them over its own declaration types, so decoding and querying a
9//! bundled table needs no parser crate. The walks follow the same rules as
10//! `openbim_step::SchemaGraph` (ISO 10303-21 §12.2.5.2 slot order,
11//! case-folded lookup, bounded chains).
12//!
13//! What is genuinely IFC here: which schema *version* a file declares (the
14//! `FILE_SCHEMA` tokens), and each version's independently bundled tables.
15//!
16//! Parsing EXPRESS text (`Schema::from_express`) needs the opt-in `express`
17//! feature. A schema can always be assembled from declarations:
18//!
19//! ```
20//! use ifc_schema::{Attribute, EntityDef, Schema};
21//!
22//! let schema = Schema::new(
23//!     "IFC4",
24//!     vec![
25//!         EntityDef::new("IfcRoot")
26//!             .with_attribute(Attribute::new("GlobalId", "IfcGloballyUniqueId")),
27//!         EntityDef::new("IfcWall")
28//!             .with_supertype("IfcRoot")
29//!             .with_attribute(Attribute::new("Name", "IfcLabel")),
30//!     ],
31//!     Vec::new(),
32//! );
33//!
34//! assert!(schema.is_a("IFCWALL", "IfcRoot"));
35//! assert_eq!(schema.attribute_names("IfcWall"), ["GlobalId", "Name"]);
36//! ```
37
38use std::collections::{HashMap, HashSet};
39
40use crate::attribute::Attribute;
41use crate::entity::EntityDef;
42use crate::types::{TypeDef, TypeKind};
43use crate::version::SchemaVersion;
44
45/// Longest supertype or alias chain walked before giving up.
46///
47/// A cyclic `SUBTYPE OF` is not legal EXPRESS, but a malformed source must
48/// not hang a consumer. Real schemas nest around a dozen levels.
49const MAX_CHAIN_DEPTH: usize = 64;
50
51/// An IFC schema: the entity and type tables, queryable.
52///
53/// Every lookup folds ASCII case: Part 21 spells `IFCWALL`, the schema
54/// `IfcWall`, and either may be passed.
55#[derive(Debug, Clone)]
56pub struct Schema {
57    name: String,
58    /// Declarations in source order. A name declared twice keeps its first
59    /// position and its last declaration.
60    entities: Vec<EntityDef>,
61    types: Vec<TypeDef>,
62    /// Upper-cased name to index into `entities` / `types`.
63    entity_index: HashMap<String, usize>,
64    type_index: HashMap<String, usize>,
65    /// Upper-cased supertype name to the declared names of its direct
66    /// subtypes, sorted. Derived once: `EntityDef` records only the upward
67    /// edge, and scanning every declaration per query is quadratic.
68    children: HashMap<String, Vec<String>>,
69    /// Per entity, parallel to `entities`: its supertype chain and its
70    /// positional attribute slots, precomputed (#352). Both are pure
71    /// functions of the declarations, so they are derived once here and
72    /// [`Self::is_a`], [`Self::supertypes`] and [`Self::attributes`] read
73    /// them instead of walking the declarations on every call.
74    lineage: Vec<Lineage>,
75}
76
77/// One entity's precomputed supertype chain and attribute layout.
78#[derive(Debug, Clone, Default)]
79struct Lineage {
80    /// [`Schema::supertypes`], nearest parent first.
81    supertypes: Box<[Ancestor]>,
82    /// [`Schema::attributes`] as `(entity index, attribute index)` pairs
83    /// into `Schema::entities`, in Part 21 positional order.
84    slots: Box<[(u32, u32)]>,
85}
86
87/// One member of a supertype chain.
88#[derive(Debug, Clone)]
89enum Ancestor {
90    /// A declared entity, by index into `Schema::entities`.
91    Declared(usize),
92    /// A supertype the schema names but never declares, as written.
93    Undeclared(Box<str>),
94}
95
96/// Equal when the name and the declarations, in order, are equal.
97impl 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    /// Assembles a schema from declarations in source order.
107    ///
108    /// A name declared more than once keeps its first position and its last
109    /// declaration, so counts are of distinct names.
110    #[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            // `SUBTYPE OF (a, a)` is illegal but must not double-report.
126            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    /// Walks one entity's supertype chain and attribute layout, once.
144    ///
145    /// These are the walks `supertypes` and `attributes` ran per call
146    /// before #352, unchanged: the same visiting order, the same
147    /// first-reached-wins rule and the same depth bound, so every answer
148    /// read from the precomputed tables is the answer the walk gave.
149    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    /// The index into `entities` of the declaration for `name`.
165    ///
166    /// Case-folded without allocating: an upper-case name (the Part 21
167    /// spelling) is looked up as given, and a short mixed-case one is
168    /// folded on the stack.
169    fn entity_position(&self, name: &str) -> Option<usize> {
170        with_folded(name, |key| self.entity_index.get(key).copied())
171    }
172
173    /// The precomputed lineage of `name`, when it is declared.
174    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    /// Parses EXPRESS source into a schema.
190    ///
191    /// Requires the `express` feature, which links the `openbim-step`
192    /// EXPRESS extractor. Its result is converted into this crate's own
193    /// types; explicit attribute redeclarations are not recorded.
194    #[cfg(feature = "express")]
195    #[must_use]
196    pub fn from_express(source: &str) -> Self {
197        crate::express::parse(source)
198    }
199
200    /// Parses EXPRESS source that is not valid UTF-8.
201    ///
202    /// The normative `IFC4.exp` is Latin-1: it contains `°` and similar in
203    /// comments. Decoding byte-per-char is correct for the ASCII structure
204    /// this parser reads and cannot fail. Requires the `express` feature.
205    #[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    /// The declared schema name, e.g. `IFC4`.
213    #[must_use]
214    pub fn name(&self) -> &str {
215        &self.name
216    }
217
218    /// The IFC schema version this table describes, when recognized.
219    ///
220    /// This is the one genuinely IFC-specific query on this type: it maps a
221    /// declared schema name onto the versions this crate knows about.
222    #[must_use]
223    pub fn version(&self) -> Option<SchemaVersion> {
224        SchemaVersion::from_header_token(&self.name)
225    }
226
227    /// How many entity declarations the schema holds.
228    #[must_use]
229    pub fn entity_count(&self) -> usize {
230        self.entities.len()
231    }
232
233    /// How many type declarations the schema holds.
234    #[must_use]
235    pub fn type_count(&self) -> usize {
236        self.types.len()
237    }
238
239    /// The entity declaration for `name`, if the schema declares one.
240    #[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    /// The type declaration for `name`, if the schema declares one.
247    #[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    /// Every entity declaration, in source order.
253    pub fn entities(&self) -> impl Iterator<Item = &EntityDef> {
254        self.entities.iter()
255    }
256
257    /// Every type declaration, in source order.
258    pub fn types(&self) -> impl Iterator<Item = &TypeDef> {
259        self.types.iter()
260    }
261
262    /// Every entity name the schema declares.
263    ///
264    /// Source order today; callers needing a particular order must sort.
265    pub fn entity_names(&self) -> impl Iterator<Item = &str> {
266        self.entities.iter().map(|entity| entity.name.as_str())
267    }
268
269    /// Whether a candidate entity or defined type satisfies a declared type.
270    ///
271    /// This walks entity inheritance, defined-type aliases, and nested SELECTs.
272    /// Unknown declarations and cyclic aliases fail closed.
273    #[must_use]
274    pub fn accepts_type(&self, declared: &str, candidate: &str) -> bool {
275        // Two distinct entities: the walk below would record the pair as
276        // seen and answer `is_a` at once, so answer it without the walk's
277        // allocations. This is the common case for an entity-typed slot.
278        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    /// Whether `name` is `ancestor`, or inherits from it.
335    ///
336    /// Reflexive for declared entities. An entity the schema never declares
337    /// is not a subtype of anything, including itself -- otherwise a typo
338    /// would silently satisfy every check made against it.
339    #[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    /// The supertype chain above `name`, nearest parent first.
352    ///
353    /// Depth-first in `SUBTYPE OF` order, each ancestor once, excluding
354    /// `name`. A supertype the schema names but never declares is reported
355    /// but cannot be walked past. Terminates on a malformed cyclic schema.
356    #[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    /// Entities declaring `SUBTYPE OF (name)` directly, sorted by name.
397    #[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    /// Every entity inheriting from `name` at any depth, excluding `name`.
405    ///
406    /// Sorted depth-first pre-order. The inverse of [`Self::is_a`].
407    #[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        // Children are pushed in reverse so the sorted first sibling pops
413        // first, which is what makes this a pre-order and not a post-order.
414        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    /// Every attribute slot in Part 21 positional order, inherited first.
426    ///
427    /// ISO 10303-21:2016 §12.2.5.2: each supertype is laid out in
428    /// `SUBTYPE OF` order, its own supertypes first, and a supertype reached
429    /// a second time contributes nothing more. Derived redeclarations are
430    /// included (they keep their slot and are written `*`); use
431    /// [`EntityDef::is_derived`] on the owning entity to tell them apart.
432    #[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    /// How many positional slots [`Self::attributes`] lists for `name`;
440    /// `0` for an entity the schema does not declare.
441    ///
442    /// Read from the precomputed layout, without allocating.
443    #[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    /// The attribute at positional `slot` of `name`, as
450    /// `attributes(name).get(slot)` answers, without allocating.
451    #[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    /// Attribute names in positional order.
487    #[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    /// Resolves a defined type to the base it ultimately aliases.
496    ///
497    /// `IfcPositiveLengthMeasure` -> `IfcLengthMeasure` -> `REAL`. Returns
498    /// the final right-hand side verbatim (including any aggregate syntax);
499    /// for a declaration that is not an alias, the type's own name. Bounded
500    /// so a cyclic alias cannot hang.
501    #[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(&current) 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(&current) {
513                return current;
514            }
515            current = next;
516        }
517        current
518    }
519}
520
521/// Longest name folded on the stack; a longer one is folded on the heap.
522const FOLD_BUFFER: usize = 128;
523
524/// Calls `f` with `name` upper-cased (ASCII), allocating only for a
525/// mixed-case name longer than [`FOLD_BUFFER`] bytes.
526///
527/// Upper-casing ASCII bytes leaves every other byte alone, so the folded
528/// buffer is valid UTF-8 whenever `name` is.
529fn 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
544/// Deduplicates declarations by case-folded name (first position, last
545/// declaration wins) and builds the lookup index.
546fn 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    /// A real three-level chain: two levels cannot catch ordering bugs.
570    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    /// A schema this crate does not recognize still assembles and queries.
605    #[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/// The owned walks must answer exactly as `openbim_step::SchemaGraph` did,
701/// which this crate delegated to before owning its types.
702#[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}