Skip to main content

ifc_validate/express/
rules.rs

1//! [`ExpressRules`]: the rules of one release, read from its EXPRESS text.
2
3use std::collections::BTreeSet;
4use std::sync::Arc;
5
6use ifc_schema::Schema;
7
8use super::coverage::{self, Coverage};
9use super::error::ExpressError;
10use super::options::EvalLimits;
11use super::resolve::{self, Globals};
12use super::tables::Tables;
13
14/// The WHERE rules, type rules, global rules and functions of one IFC
15/// release, ready to evaluate.
16///
17/// # Where the rule text comes from
18///
19/// The IFC schemas are published by buildingSMART under CC BY-ND 4.0, and
20/// this crate does not redistribute them or anything derived from their
21/// rule text: the bundled tables carry rule labels only. The caller
22/// supplies the release's `.exp` file -- `scripts/fetch-ifc-schemas.sh`
23/// fetches and checksums the five releases -- and this type reads it at run
24/// time.
25///
26/// # Pairing with the tables
27///
28/// The text must declare the same schema as the bundled tables it is
29/// paired with, and agree with them on every entity's attribute layout:
30/// [`ExpressRules::parse`] refuses `IFC4.exp` paired with IFC4X3 tables,
31/// and a modified file whose slots would be read wrong.
32///
33/// Cheap to clone: the parsed schema is shared. `Send` and `Sync`, so one
34/// parse serves every thread.
35#[derive(Clone)]
36pub struct ExpressRules {
37    pub(crate) tables: Arc<Tables>,
38    pub(crate) limits: EvalLimits,
39    ids: Arc<BTreeSet<String>>,
40}
41
42impl std::fmt::Debug for ExpressRules {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("ExpressRules")
45            .field("schema", &self.schema_name())
46            .field("rules", &self.ids.len())
47            .field("limits", &self.limits)
48            .finish()
49    }
50}
51
52impl ExpressRules {
53    /// Reads `source`, the EXPRESS text of `schema`'s release.
54    ///
55    /// # Errors
56    ///
57    /// [`ExpressError`] when the text does not parse, names another schema,
58    /// disagrees with the tables, or uses a name that binds to nothing.
59    pub fn parse(source: &str, schema: &Schema) -> Result<Self, ExpressError> {
60        let mut decl = super::parse::schema(source)?;
61        if !decl.name.eq_ignore_ascii_case(schema.name()) {
62            return Err(ExpressError::SchemaMismatch {
63                source: decl.name.to_string(),
64                tables: schema.name().to_owned(),
65            });
66        }
67        let globals = Globals::new(&decl);
68        resolve::schema(&mut decl, &globals)?;
69        let tables = Tables::new(decl, globals, schema)?;
70        let mut ids = BTreeSet::new();
71        for entity in &tables.schema.entities {
72            for rule in &entity.rules {
73                ids.insert(format!("{}.{}", entity.spelling, rule.label));
74            }
75        }
76        for decl in &tables.schema.types {
77            for rule in &decl.rules {
78                ids.insert(format!("{}.{}", decl.spelling, rule.label));
79            }
80        }
81        for rule in &tables.schema.rules {
82            ids.insert(format!("global.{}", rule.spelling));
83        }
84        Ok(Self {
85            tables: Arc::new(tables),
86            limits: EvalLimits::DEFAULT,
87            ids: Arc::new(ids),
88        })
89    }
90
91    /// Reads EXPRESS text that is not UTF-8.
92    ///
93    /// The normative IFC files are ASCII, but some copies are Latin-1
94    /// (a `°` in a remark); each byte is read as one character, which is
95    /// exact for everything outside remarks and string literals.
96    ///
97    /// # Errors
98    ///
99    /// As [`Self::parse`].
100    pub fn parse_bytes(bytes: &[u8], schema: &Schema) -> Result<Self, ExpressError> {
101        let text: String = bytes.iter().map(|&byte| char::from(byte)).collect();
102        Self::parse(&text, schema)
103    }
104
105    /// The same rules evaluated under other limits.
106    #[must_use]
107    pub fn with_limits(mut self, limits: EvalLimits) -> Self {
108        self.limits = limits;
109        self
110    }
111
112    /// The limits evaluation runs under.
113    #[must_use]
114    pub fn limits(&self) -> EvalLimits {
115        self.limits
116    }
117
118    /// The schema name the text declares (`IFC4X3_ADD2`).
119    #[must_use]
120    pub fn schema_name(&self) -> &str {
121        &self.tables.schema.name
122    }
123
124    /// Every rule id these rules can report, sorted: `Entity.Label` for an
125    /// entity WHERE rule, `Type.Label` for a type WHERE rule, and
126    /// `global.Rule` for a global rule.
127    pub fn rule_ids(&self) -> impl Iterator<Item = &str> {
128        self.ids.iter().map(String::as_str)
129    }
130
131    /// Whether these rules report under `id`; a hand-written rule with the
132    /// same id is superseded by them.
133    #[must_use]
134    pub fn covers(&self, id: &str) -> bool {
135        self.ids.contains(id) || self.ids.contains(&format!("global.{id}"))
136    }
137
138    /// How many declarations this evaluator can evaluate, and which it
139    /// cannot, by name.
140    #[must_use]
141    pub fn coverage(&self) -> Coverage {
142        coverage::measure(&self.tables)
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::ExpressRules;
149
150    #[test]
151    fn rules_can_be_shared_between_threads() {
152        fn shared<T: Send + Sync>() {}
153        shared::<ExpressRules>();
154    }
155}