Skip to main content

openbim_ifc_binding_core/
coerce.rs

1//! Plain host values written by name, coerced against the declared type
2//! (#342).
3//!
4//! A tagged value says exactly what it is: `Text` or `Enum`, `Integer` or
5//! `Real`, `IFCLABEL('x')` or `'x'`. A host's plain value does not: Python's
6//! `"STANDARD"` could be either of the first pair, `1` either of the second.
7//! [`IfcModel::set_attribute_by_name_plain`] settles it from the attribute's
8//! declared EXPRESS type in the release the header declares
9//! (`ifc::attribute_type`), and refuses what the declaration cannot settle.
10//!
11//! # The rules
12//!
13//! | Plain value | Declared type | Written |
14//! | --- | --- | --- |
15//! | any | through a defined type | as for the type it aliases, bare: `IfcLabel` takes `'x'` |
16//! | string | `STRING` | text |
17//! | string | an enumeration | the item it names (any case), else `type-mismatch` |
18//! | integer | `INTEGER`, `NUMBER` | integer |
19//! | integer | `REAL` | real, when exact (within 2^53), else `type-mismatch` |
20//! | float | `REAL`, `NUMBER` | real |
21//! | bool | `BOOLEAN`, `LOGICAL` | `.T.` / `.F.` |
22//! | list | an aggregate | each element coerced against the element type |
23//! | entity handle | an entity | a reference, when the target exists (`missing-reference`) and is of the type or a subtype (`type-mismatch`) |
24//! | entity handle | a SELECT | a reference, when an entity member accepts the target |
25//! | other | a SELECT | the one member that accepts it, as a typed parameter (`IFCLABEL('x')`); several: `ambiguous-value`, naming them |
26//! | null | any | `$` |
27//!
28//! Anything else is `type-mismatch`: a float for an `INTEGER`, a string for
29//! a `REAL`, any plain value for `BINARY` (write a `binary` explicitly). A
30//! declared type the tables do not resolve is `unsupported`. Typed
31//! parameters appear only in a SELECT, as ISO 10303-21 §12.1.8 writes them;
32//! everywhere else the value is bare (§12.1.6, §12.1.7).
33//!
34//! [`Plain::Exact`] carries a tagged value through unchanged, nested in a
35//! list too, so a caller keeps exact control where it wants it.
36
37use ifc::{attribute_type, DeclaredType, EntityId, Model, Schema, SimpleType};
38
39use crate::value::{Tagged, MAX_NESTING};
40use crate::{BindingError, IfcModel};
41
42/// A host value before coercion: what a host language holds without
43/// saying which IFC type it means.
44#[derive(Debug, Clone, PartialEq)]
45pub enum Plain {
46    /// `None` / `null`: written `$`.
47    Null,
48    /// A boolean.
49    Bool(bool),
50    /// An integer.
51    Integer(i64),
52    /// A float.
53    Real(f64),
54    /// A string.
55    Text(String),
56    /// An entity handle: entity `#id` of the same model.
57    Ref(u64),
58    /// A sequence.
59    List(Vec<Plain>),
60    /// A tagged value, written exactly as given.
61    Exact(Tagged),
62}
63
64/// Integers a REAL holds exactly.
65const EXACT_IN_REAL: i64 = 1 << 53;
66
67impl IfcModel {
68    /// The tagged value [`Self::set_attribute_by_name_plain`] would write
69    /// for `value` into attribute `name` (any case) of entity `id`, without
70    /// writing it.
71    ///
72    /// Refused as [`Self::attribute_by_name`] is, with `derived-attribute`
73    /// for a derived slot, and by the rules of the [module](self).
74    pub fn coerce_attribute(
75        &self,
76        id: u64,
77        name: &str,
78        value: Plain,
79    ) -> Result<Tagged, BindingError> {
80        let schema = self.declared_schema()?;
81        let type_name = &self.entity(id)?.type_name;
82        let (slot, declared) =
83            attribute_type(schema, type_name, name).map_err(crate::attribute::refused)?;
84        if slot.derived {
85            return Err(BindingError::DerivedAttribute(format!(
86                "{}.{} is derived (written `*`) and cannot be set",
87                schema
88                    .entity(type_name)
89                    .map_or(&**type_name, |e| e.name.as_str()),
90                slot.name
91            )));
92        }
93        let context = Context {
94            model: &self.inner,
95            schema,
96        };
97        context.coerce(&declared, value, 0)
98    }
99
100    /// Set attribute `name` (any case) of entity `id` from a plain host
101    /// value, coerced against its declared type (see the
102    /// [module](self)); returns the previous value. Every check runs
103    /// before the write, so a refusal changes nothing.
104    pub fn set_attribute_by_name_plain(
105        &mut self,
106        id: u64,
107        name: &str,
108        value: Plain,
109    ) -> Result<Tagged, BindingError> {
110        self.tracked(|this| {
111            let value = this.coerce_attribute(id, name, value)?;
112            this.set_attribute_by_name(id, name, value)
113        })
114    }
115}
116
117struct Context<'a> {
118    model: &'a Model,
119    schema: &'a Schema,
120}
121
122fn mismatch(value: &Plain, declared: &DeclaredType<'_>) -> BindingError {
123    BindingError::TypeMismatch(format!(
124        "{} does not fit {}",
125        describe(value),
126        describe_type(declared)
127    ))
128}
129
130fn describe(value: &Plain) -> String {
131    match value {
132        Plain::Null => "null".to_owned(),
133        Plain::Bool(b) => format!("the boolean {b}"),
134        Plain::Integer(i) => format!("the integer {i}"),
135        Plain::Real(r) => format!("the float {r}"),
136        Plain::Text(s) => format!("the string {s:?}"),
137        Plain::Ref(id) => format!("entity #{id}"),
138        Plain::List(_) => "a list".to_owned(),
139        Plain::Exact(_) => "an exact value".to_owned(),
140    }
141}
142
143fn describe_type(declared: &DeclaredType<'_>) -> String {
144    match declared {
145        DeclaredType::Simple(simple) => simple.keyword().to_owned(),
146        DeclaredType::Defined { name, underlying } => {
147            format!("{name} ({})", describe_type(underlying))
148        }
149        DeclaredType::Enumeration { name, items } => {
150            format!("{name} (one of {})", items.join(", "))
151        }
152        DeclaredType::Aggregate { element, .. } => {
153            format!("an aggregate of {}", describe_type(element))
154        }
155        other => other
156            .name()
157            .map_or_else(|| format!("{other:?}"), str::to_owned),
158    }
159}
160
161impl Context<'_> {
162    fn coerce(
163        &self,
164        declared: &DeclaredType<'_>,
165        value: Plain,
166        depth: usize,
167    ) -> Result<Tagged, BindingError> {
168        if depth > MAX_NESTING {
169            return Err(BindingError::InvalidValue(format!(
170                "nesting deeper than {MAX_NESTING}"
171            )));
172        }
173        let value = match value {
174            Plain::Exact(tagged) => return Ok(tagged),
175            Plain::Null => return Ok(Tagged::Null),
176            // STEP has no NaN or infinity; refused before any SELECT member
177            // could be said to take it.
178            Plain::Real(r) if !r.is_finite() => {
179                return Err(BindingError::InvalidValue(format!(
180                    "real {r} is not finite"
181                )))
182            }
183            value => value,
184        };
185        match declared {
186            DeclaredType::Simple(simple) => simple_value(*simple, value, declared),
187            DeclaredType::Defined { underlying, .. } => self.coerce(underlying, value, depth + 1),
188            DeclaredType::Enumeration { items, .. } => match &value {
189                Plain::Text(text) => items
190                    .iter()
191                    .find(|item| item.eq_ignore_ascii_case(text))
192                    .map(|item| Tagged::Enum(item.to_ascii_uppercase()))
193                    .ok_or_else(|| mismatch(&value, declared)),
194                _ => Err(mismatch(&value, declared)),
195            },
196            DeclaredType::Entity(name) => match value {
197                Plain::Ref(id) => self.reference(id, &[name]),
198                value => Err(mismatch(&value, declared)),
199            },
200            DeclaredType::Aggregate { element, .. } => match value {
201                Plain::List(items) => Ok(Tagged::List(
202                    items
203                        .into_iter()
204                        .map(|item| self.coerce(element, item, depth + 1))
205                        .collect::<Result<_, _>>()?,
206                )),
207                value => Err(mismatch(&value, declared)),
208            },
209            DeclaredType::Select { name, .. } => self.select(name, declared, value, depth),
210            DeclaredType::Unresolved(token) => Err(BindingError::Unsupported(format!(
211                "the declared type {token} is not in the tables; write an exact value"
212            ))),
213            // A declaration form added to the facade later.
214            other => Err(BindingError::Unsupported(format!(
215                "the declared type {other:?} has no plain coercion; write an exact value"
216            ))),
217        }
218    }
219
220    /// `#id`, when it exists and is one of `accepted` or a subtype.
221    fn reference(&self, id: u64, accepted: &[&str]) -> Result<Tagged, BindingError> {
222        let target = self.model.get(EntityId(id)).ok_or_else(|| {
223            BindingError::MissingReference(format!("entity #{id} is not in the model"))
224        })?;
225        if accepted
226            .iter()
227            .any(|name| self.schema.is_a(&target.type_name, name))
228        {
229            Ok(Tagged::Ref(id))
230        } else {
231            Err(BindingError::TypeMismatch(format!(
232                "#{id} is an {}, not {}",
233                target.type_name,
234                accepted.join(" or ")
235            )))
236        }
237    }
238
239    /// A SELECT: a reference when an entity member accepts it; otherwise
240    /// the one member whose type takes the value, as a typed parameter.
241    fn select(
242        &self,
243        name: &str,
244        declared: &DeclaredType<'_>,
245        value: Plain,
246        depth: usize,
247    ) -> Result<Tagged, BindingError> {
248        let mut leaves = Vec::new();
249        leaves_of(declared, &mut leaves);
250        if let Plain::Ref(id) = value {
251            let entities: Vec<&str> = leaves
252                .iter()
253                .filter_map(|leaf| match leaf {
254                    DeclaredType::Entity(entity) => Some(*entity),
255                    _ => None,
256                })
257                .collect();
258            if entities.is_empty() {
259                return Err(BindingError::TypeMismatch(format!(
260                    "{name} admits no entity reference"
261                )));
262            }
263            return self.reference(id, &entities);
264        }
265        let mut fits: Vec<(&str, Tagged)> = Vec::new();
266        for leaf in &leaves {
267            let (Some(member), false) = (leaf.name(), matches!(leaf, DeclaredType::Entity(_)))
268            else {
269                continue;
270            };
271            if fits
272                .iter()
273                .any(|(seen, _)| seen.eq_ignore_ascii_case(member))
274            {
275                continue;
276            }
277            if let Ok(inner) = self.coerce(leaf, value.clone(), depth + 1) {
278                fits.push((member, inner));
279            }
280        }
281        match fits.len() {
282            0 => Err(BindingError::TypeMismatch(format!(
283                "{} fits no member of {name}",
284                describe(&value)
285            ))),
286            1 => {
287                let (member, inner) = fits.pop().expect("one fit");
288                Ok(Tagged::Typed {
289                    type_name: member.to_ascii_uppercase(),
290                    value: Box::new(inner),
291                })
292            }
293            _ => Err(BindingError::AmbiguousValue(format!(
294                "{} fits {} members of {name}: {}",
295                describe(&value),
296                fits.len(),
297                fits.iter()
298                    .map(|(member, _)| *member)
299                    .collect::<Vec<_>>()
300                    .join(", ")
301            ))),
302        }
303    }
304}
305
306/// The members of a SELECT that are not SELECTs themselves, nested ones
307/// flattened, in declaration order.
308fn leaves_of<'d, 's>(declared: &'d DeclaredType<'s>, out: &mut Vec<&'d DeclaredType<'s>>) {
309    match declared {
310        DeclaredType::Select { members, .. } => {
311            for member in members {
312                leaves_of(member, out);
313            }
314        }
315        // A defined type aliasing a SELECT is encoded as that SELECT
316        // (ISO 10303-21 §12.1.8).
317        DeclaredType::Defined { underlying, .. }
318            if matches!(**underlying, DeclaredType::Select { .. }) =>
319        {
320            leaves_of(underlying, out);
321        }
322        leaf => out.push(leaf),
323    }
324}
325
326fn simple_value(
327    simple: SimpleType,
328    value: Plain,
329    declared: &DeclaredType<'_>,
330) -> Result<Tagged, BindingError> {
331    Ok(match (simple, value) {
332        (SimpleType::Integer | SimpleType::Number, Plain::Integer(i)) => Tagged::Integer(i),
333        (SimpleType::Real, Plain::Integer(i)) if (-EXACT_IN_REAL..=EXACT_IN_REAL).contains(&i) => {
334            #[allow(clippy::cast_precision_loss)] // Bounded above: exact.
335            Tagged::Real(i as f64)
336        }
337        (SimpleType::Real | SimpleType::Number, Plain::Real(r)) => Tagged::Real(r),
338        (SimpleType::String, Plain::Text(s)) => Tagged::Text(s),
339        (SimpleType::Boolean | SimpleType::Logical, Plain::Bool(b)) => Tagged::Bool(b),
340        (_, value) => return Err(mismatch(&value, declared)),
341    })
342}