Skip to main content

ifc_template_catalog/
query.rs

1//! Catalog lookup and applicability matching.
2
3use crate::catalog::Catalog;
4use crate::definition::{
5    Applicability, PropertySetType, QuantitySetType, SetTemplate, SetTemplateKind,
6};
7
8/// Semantic context in which a template would be assigned.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum ApplicabilityContext {
12    /// Values authored directly on an occurrence instance.
13    Occurrence,
14    /// Values authored on a type, inherited by its occurrences.
15    Type,
16    /// Values recording required/target performance rather than as-built state.
17    PerformanceHistory,
18}
19
20/// IFC object/type tested against catalog applicability.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct ApplicabilityTarget {
23    /// IFC entity name of the object or type being tested.
24    pub entity: String,
25    /// Predefined type of the object or type being tested, if any.
26    pub predefined_type: Option<String>,
27    /// `None` asks only the entity/predefined-type question.
28    pub context: Option<ApplicabilityContext>,
29}
30
31impl ApplicabilityTarget {
32    /// Build a target with no applicability-mode context; only entity and
33    /// predefined type are matched.
34    pub fn new(entity: impl Into<String>, predefined_type: Option<impl Into<String>>) -> Self {
35        Self {
36            entity: entity.into(),
37            predefined_type: predefined_type.map(Into::into),
38            context: None,
39        }
40    }
41
42    /// Attach an applicability-mode context, restricting matches to
43    /// templates whose `set_type` supports that context.
44    pub fn with_context(mut self, context: ApplicabilityContext) -> Self {
45        self.context = Some(context);
46        self
47    }
48}
49
50/// Minimal hierarchy seam needed by catalog queries.
51pub trait EntityHierarchy {
52    /// True when `candidate` is `expected_supertype` or a subtype of it.
53    fn is_same_or_subtype(&self, candidate: &str, expected_supertype: &str) -> bool;
54
55    /// Return `Some(false)` when the hierarchy can prove the entity is unknown.
56    fn entity_known(&self, _entity: &str) -> Option<bool> {
57        None
58    }
59}
60
61/// Exact entity matching when schema metadata is unavailable.
62#[derive(Debug, Clone, Copy, Default)]
63pub struct ExactEntityHierarchy;
64
65impl EntityHierarchy for ExactEntityHierarchy {
66    fn is_same_or_subtype(&self, candidate: &str, expected_supertype: &str) -> bool {
67        candidate.eq_ignore_ascii_case(expected_supertype)
68    }
69}
70
71#[cfg(feature = "schema")]
72impl EntityHierarchy for ifc_schema::Schema {
73    fn is_same_or_subtype(&self, candidate: &str, expected_supertype: &str) -> bool {
74        self.is_a(candidate, expected_supertype)
75    }
76
77    fn entity_known(&self, entity: &str) -> Option<bool> {
78        Some(self.entity(entity).is_some())
79    }
80}
81
82/// One selector that could not be evaluated because schema data was missing.
83#[derive(Debug, Clone, Copy)]
84#[non_exhaustive]
85pub struct UnresolvedApplicability<'a> {
86    /// The template whose selector could not be resolved.
87    pub template: &'a SetTemplate,
88    /// The specific applicability selector that was unresolved.
89    pub selector: &'a Applicability,
90}
91
92/// Structured applicability result; unknown schema entities are not conflated with no-match.
93#[derive(Debug, Default)]
94pub struct ApplicabilityQuery<'a> {
95    /// Templates whose applicability was proven to match the target.
96    pub matches: Vec<&'a SetTemplate>,
97    /// Selectors that could not be resolved because the hierarchy could not
98    /// confirm whether an involved entity name exists.
99    pub unresolved: Vec<UnresolvedApplicability<'a>>,
100}
101
102impl Catalog {
103    /// Return templates applicable to an entity and optional predefined type.
104    ///
105    /// Unknown schema entities are omitted. Use [`Catalog::query_applicability`]
106    /// when that distinction matters.
107    pub fn applicable_to<'a>(
108        &'a self,
109        target: &ApplicabilityTarget,
110        hierarchy: &impl EntityHierarchy,
111    ) -> Vec<&'a SetTemplate> {
112        self.query_applicability(target, hierarchy).matches
113    }
114
115    /// Query applicability while preserving unknown-schema outcomes.
116    pub fn query_applicability<'a>(
117        &'a self,
118        target: &ApplicabilityTarget,
119        hierarchy: &impl EntityHierarchy,
120    ) -> ApplicabilityQuery<'a> {
121        let mut result = ApplicabilityQuery::default();
122        for template in self.iter().filter(|item| context_matches(item, target)) {
123            let mut matched = false;
124            for selector in &template.applicability {
125                match selector_match(selector, target, hierarchy) {
126                    SelectorMatch::Match => matched = true,
127                    SelectorMatch::NoMatch => {}
128                    SelectorMatch::Unknown => result
129                        .unresolved
130                        .push(UnresolvedApplicability { template, selector }),
131                }
132            }
133            if matched {
134                result.matches.push(template);
135            }
136        }
137        result
138    }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142enum SelectorMatch {
143    Match,
144    NoMatch,
145    Unknown,
146}
147
148fn selector_match(
149    selector: &Applicability,
150    target: &ApplicabilityTarget,
151    hierarchy: &impl EntityHierarchy,
152) -> SelectorMatch {
153    if !hierarchy.is_same_or_subtype(&target.entity, &selector.entity) {
154        if matches!(hierarchy.entity_known(&target.entity), Some(false))
155            || matches!(hierarchy.entity_known(&selector.entity), Some(false))
156        {
157            return SelectorMatch::Unknown;
158        }
159        return SelectorMatch::NoMatch;
160    }
161    match (&selector.predefined_type, &target.predefined_type) {
162        (None, _) => SelectorMatch::Match,
163        (Some(expected), Some(actual)) if expected.eq_ignore_ascii_case(actual) => {
164            SelectorMatch::Match
165        }
166        _ => SelectorMatch::NoMatch,
167    }
168}
169
170fn context_matches(template: &SetTemplate, target: &ApplicabilityTarget) -> bool {
171    let Some(context) = target.context else {
172        return true;
173    };
174    match &template.kind {
175        SetTemplateKind::Property { set_type, .. } => match set_type {
176            PropertySetType::TypeDrivenOverride => matches!(
177                context,
178                ApplicabilityContext::Occurrence | ApplicabilityContext::Type
179            ),
180            PropertySetType::TypeDrivenOnly => matches!(context, ApplicabilityContext::Type),
181            PropertySetType::OccurrenceDriven => {
182                matches!(context, ApplicabilityContext::Occurrence)
183            }
184            PropertySetType::PerformanceDriven => {
185                matches!(context, ApplicabilityContext::PerformanceHistory)
186            }
187            PropertySetType::Unspecified => true,
188        },
189        SetTemplateKind::Quantity { set_type, .. } => match set_type {
190            QuantitySetType::TypeDrivenOverride => matches!(
191                context,
192                ApplicabilityContext::Occurrence | ApplicabilityContext::Type
193            ),
194            QuantitySetType::TypeDrivenOnly => matches!(context, ApplicabilityContext::Type),
195            QuantitySetType::OccurrenceDriven => {
196                matches!(context, ApplicabilityContext::Occurrence)
197            }
198            QuantitySetType::Unspecified => true,
199        },
200    }
201}