Skip to main content

ifc_author/builder/
entity.rs

1//! Build one entity by naming its attributes.
2//!
3//! # The problem this solves
4//!
5//! `Model::push` takes a positional `Vec<Value>`. Authoring an `IfcAnnotation`
6//! therefore means knowing that it has seven slots, that slot 0 is the
7//! GlobalId, slot 2 the name, and that slots 1 and 3..6 are optional. Get the
8//! count wrong and the file still writes -- and is rejected downstream.
9//!
10//! Here the caller names attributes and the schema decides the positions.
11//!
12//! # Attribute names match case-insensitively
13//!
14//! Names are compared with `eq_ignore_ascii_case`, so an IFC4 and IFC4X3
15//! spelling that differs only in case resolves to the same slot and is not a
16//! bug. A true rename between releases is a different name and is refused as
17//! unknown in the release that lacks it.
18
19use ifc_model::{Entity, Value};
20use ifc_schema::Schema;
21
22use crate::check::{
23    aggregate_element, describe_value, enumerations_of, is_derived_slot, judge_value, Verdict,
24};
25use crate::error::{AuthorError, AuthorResult};
26
27/// A partially-specified entity, checked against the schema on [`build`].
28///
29/// [`build`]: EntityBuilder::build
30#[derive(Debug, Clone)]
31pub struct EntityBuilder<'a> {
32    schema: &'a Schema,
33    entity: String,
34    /// Attribute name and value, in the order the caller set them. Kept as a
35    /// list rather than a map so a duplicate set is detectable and the error
36    /// can name the attribute.
37    set: Vec<(String, Value)>,
38}
39
40impl<'a> EntityBuilder<'a> {
41    /// Start building `entity`, whose type must be declared by `schema`.
42    ///
43    /// The type is not checked here: an unknown type is reported by [`build`],
44    /// so that a caller assembling several entities gets every failure at the
45    /// same point in its code rather than some at construction and some later.
46    ///
47    /// [`build`]: EntityBuilder::build
48    pub fn new(schema: &'a Schema, entity: impl Into<String>) -> Self {
49        Self {
50            schema,
51            entity: entity.into(),
52            set: Vec::new(),
53        }
54    }
55
56    /// Set one attribute by its declared name.
57    ///
58    /// Names are matched case-insensitively, because EXPRESS declares
59    /// `GlobalId` while STEP files and much prose write `GLOBALID`.
60    #[must_use]
61    pub fn set(mut self, attribute: impl Into<String>, value: Value) -> Self {
62        self.set.push((attribute.into(), value));
63        self
64    }
65
66    /// Set a text attribute.
67    pub fn text(self, attribute: impl Into<String>, text: impl Into<std::sync::Arc<str>>) -> Self {
68        self.set(attribute, Value::Text(text.into()))
69    }
70
71    /// Set a real-valued attribute.
72    pub fn real(self, attribute: impl Into<String>, value: f64) -> Self {
73        self.set(attribute, Value::Real(value))
74    }
75
76    /// Set an entity-reference attribute.
77    pub fn reference(self, attribute: impl Into<String>, id: ifc_model::EntityId) -> Self {
78        self.set(attribute, Value::Ref(id))
79    }
80
81    /// Set an enumeration attribute (written `.PLAN_VIEW.` in STEP).
82    pub fn enumeration(
83        self,
84        attribute: impl Into<String>,
85        constant: impl Into<std::sync::Arc<str>>,
86    ) -> Self {
87        self.set(attribute, Value::Enum(constant.into()))
88    }
89}
90
91impl EntityBuilder<'_> {
92    /// Resolve every named attribute to its STEP slot and produce the entity.
93    ///
94    /// # Errors
95    ///
96    /// Refuses an unknown entity type, an attribute the schema does not
97    /// declare, an attribute set twice, a required attribute left unset, a
98    /// scalar/aggregate confusion, a value whose shape contradicts the declared
99    /// type, and a malformed GlobalId.
100    pub fn build(self) -> AuthorResult<Entity> {
101        let declared = self.schema.attributes(&self.entity);
102        if declared.is_empty() && self.schema.entity(&self.entity).is_none() {
103            return Err(AuthorError::UnknownEntity {
104                entity: self.entity,
105            });
106        }
107
108        // Positional order comes from the schema: inherited attributes first,
109        // which is what makes a STEP record readable by anything else. A slot
110        // the schema derives for this entity is written `*` unless set.
111        let mut slots: Vec<Value> = declared
112            .iter()
113            .map(|attribute| {
114                if is_derived_slot(self.schema, &self.entity, &attribute.name) {
115                    Value::Derived
116                } else {
117                    Value::Null
118                }
119            })
120            .collect();
121        let mut filled = vec![false; declared.len()];
122
123        for (name, value) in &self.set {
124            let Some(index) = declared
125                .iter()
126                .position(|a| a.name.eq_ignore_ascii_case(name))
127            else {
128                return Err(AuthorError::UnknownAttribute {
129                    entity: self.entity.clone(),
130                    attribute: name.clone(),
131                    known: declared.iter().map(|a| a.name.clone()).collect(),
132                });
133            };
134            if filled[index] {
135                return Err(AuthorError::DuplicateAttribute {
136                    entity: self.entity.clone(),
137                    attribute: declared[index].name.clone(),
138                });
139            }
140            check_value(self.schema, &self.entity, declared[index], value)?;
141            slots[index] = value.clone();
142            filled[index] = true;
143        }
144
145        for (index, attribute) in declared.iter().enumerate() {
146            if !filled[index] && !attribute.optional && !matches!(slots[index], Value::Derived) {
147                return Err(AuthorError::MissingRequired {
148                    entity: self.entity.clone(),
149                    attribute: attribute.name.clone(),
150                });
151            }
152        }
153
154        Ok(Entity::new(self.entity.to_ascii_uppercase(), slots))
155    }
156
157    /// Build the entity and append it to `model`, returning its new id.
158    ///
159    /// The model is left untouched when construction fails, so a rejected
160    /// entity cannot leave a half-written record behind.
161    ///
162    /// # Errors
163    ///
164    /// Any failure from [`build`](EntityBuilder::build).
165    pub fn insert(self, model: &mut ifc_model::Model) -> AuthorResult<ifc_model::EntityId> {
166        let entity = self.build()?;
167        Ok(model.push(entity))
168    }
169}
170
171/// Check one value against one declared attribute.
172///
173/// Split out as a free function because it borrows the schema and the entity
174/// name while the builder's `set` list is being consumed.
175pub(crate) fn check_value(
176    schema: &Schema,
177    entity: &str,
178    attribute: &ifc_schema::Attribute,
179    value: &Value,
180) -> AuthorResult<()> {
181    // A derived slot admits exactly `*`, and `*` fits nowhere else.
182    let derived = is_derived_slot(schema, entity, &attribute.name);
183    match (derived, value) {
184        (true, Value::Derived) => return Ok(()),
185        (true, other) => {
186            return Err(AuthorError::DerivedAttribute {
187                entity: entity.to_owned(),
188                attribute: attribute.name.clone(),
189                found: describe_value(other),
190            })
191        }
192        (false, Value::Derived) => {
193            return Err(AuthorError::NotDerived {
194                entity: entity.to_owned(),
195                attribute: attribute.name.clone(),
196            })
197        }
198        (false, _) => {}
199    }
200
201    // An aggregate declaration wants a list and a scalar declaration does not.
202    // The `LIST` may sit in the attribute declaration or in a defined type the
203    // attribute is declared as (`IfcCompoundPlaneAngleMeasure`). `$` is exempt:
204    // an unset optional aggregate is still `$`, not `()`.
205    //
206    // An empty `()` is invalid for a `LIST [1:?]` / `SET [1:?]` attribute: a
207    // caller writes `$` when the attribute is optional and must not build the
208    // entity when it is required. That cannot be refused here, because the
209    // schema tables keep no aggregate bounds. TODO(#111)
210    let aliased = if attribute.aggregate {
211        None
212    } else {
213        aggregate_element(schema, &attribute.type_name)
214    };
215    let expected_aggregate = attribute.aggregate || aliased.is_some();
216    if !matches!(value, Value::Null) {
217        let supplied_aggregate = matches!(value, Value::List(_));
218        if supplied_aggregate != expected_aggregate {
219            return Err(AuthorError::AggregateMismatch {
220                entity: entity.to_owned(),
221                attribute: attribute.name.clone(),
222                expected_aggregate,
223            });
224        }
225    }
226
227    // GlobalId is the one attribute whose *content* is worth checking here: it
228    // is the only stable cross-file identity an element has, and a malformed
229    // one silently breaks diffing and issue tracking rather than failing loudly.
230    if attribute.name.eq_ignore_ascii_case("GlobalId") {
231        if let Value::Text(text) = value {
232            if ifc_model::guid::Guid::parse(text).is_none() {
233                return Err(AuthorError::InvalidGlobalId {
234                    entity: entity.to_owned(),
235                    found: text.to_string(),
236                });
237            }
238        }
239    }
240
241    // Aggregate element types are checked per item; the declaration names the
242    // element type, not the container. For an aliased aggregate the element
243    // type is the alias's, e.g. `INTEGER` for `IfcCompoundPlaneAngleMeasure`.
244    //
245    // The first refused item is the one reported; a wrong type is reported
246    // before a wrong form, since rewrapping would not fix it.
247    //
248    // A nested aggregate (`LIST [1:?] OF LIST [3:3] OF IfcLengthMeasure`) is
249    // walked level by level down to its elements; a level that should hold
250    // aggregates and holds a scalar is a shape mismatch.
251    let element_type = aliased.as_deref().unwrap_or(&attribute.type_name);
252    let verdicts: Vec<(Verdict, &Value)> = match value {
253        Value::List(_) => {
254            let mut elements = Vec::new();
255            let levels = attribute.aggregation.len().max(1);
256            if !elements_at(value, levels, &mut elements) {
257                return Err(AuthorError::AggregateMismatch {
258                    entity: entity.to_owned(),
259                    attribute: attribute.name.clone(),
260                    expected_aggregate: true,
261                });
262            }
263            elements
264                .into_iter()
265                .map(|item| (judge_value(schema, element_type, item), item))
266                .collect()
267        }
268        scalar => vec![(judge_value(schema, &attribute.type_name, scalar), scalar)],
269    };
270    if verdicts
271        .iter()
272        .any(|(verdict, _)| *verdict == Verdict::WrongType)
273    {
274        return Err(AuthorError::TypeMismatch {
275            entity: entity.to_owned(),
276            attribute: attribute.name.clone(),
277            expected: attribute.type_name.clone(),
278            found: describe_value(value),
279        });
280    }
281    if let Some((Verdict::NotMember { enumeration }, offending)) = verdicts
282        .iter()
283        .find(|(verdict, _)| matches!(verdict, Verdict::NotMember { .. }))
284    {
285        let enumerations = enumerations_of(schema, enumeration, 16);
286        // A typed parameter (`IFCNULLSTYLE(.BOGUS.)`) wraps the constant.
287        let mut constant = *offending;
288        while let Value::Typed { value, .. } = constant {
289            constant = value;
290        }
291        return Err(AuthorError::NotEnumerationMember {
292            entity: entity.to_owned(),
293            attribute: attribute.name.clone(),
294            enumeration: enumerations
295                .iter()
296                .map(|(name, _)| *name)
297                .collect::<Vec<_>>()
298                .join(" | "),
299            constant: match constant {
300                Value::Enum(text) => text.to_string(),
301                other => describe_value(other),
302            },
303            allowed: enumerations
304                .iter()
305                .flat_map(|(_, members)| members.iter().cloned())
306                .collect(),
307        });
308    }
309    if let Some((Verdict::WrongForm { typed_required }, offending)) = verdicts
310        .into_iter()
311        .find(|(verdict, _)| matches!(verdict, Verdict::WrongForm { .. }))
312    {
313        return Err(AuthorError::ValueForm {
314            entity: entity.to_owned(),
315            attribute: attribute.name.clone(),
316            declared: element_type.to_owned(),
317            typed_required,
318            found: describe_value(offending),
319        });
320    }
321    Ok(())
322}
323
324/// Collect the elements of `value`, an aggregate of `levels` nested levels;
325/// `false` when a level that should hold aggregates holds a scalar.
326fn elements_at<'v>(value: &'v Value, levels: usize, out: &mut Vec<&'v Value>) -> bool {
327    match value {
328        Value::List(items) if levels > 0 => {
329            items.iter().all(|item| elements_at(item, levels - 1, out))
330        }
331        _ if levels == 0 => {
332            out.push(value);
333            true
334        }
335        _ => false,
336    }
337}