Skip to main content

ifc_properties/pset/
root_authoring.rs

1//! `IfcRoot` authoring bound to the model's declared release (#191).
2//!
3//! `IfcRoot.OwnerHistory` is required in IFC2X3 TC1 and `OPTIONAL` from IFC4
4//! on:
5//!
6//! ```text
7//! IFC2X3_TC1   OwnerHistory : IfcOwnerHistory;
8//! IFC4         OwnerHistory : OPTIONAL IfcOwnerHistory;
9//! IFC4X3_ADD2  OwnerHistory : OPTIONAL IfcOwnerHistory;
10//! ```
11//!
12//! The writers here bind the release through `quantity/release.rs` and lay
13//! each record out by attribute name from its table. Those that leave
14//! `OwnerHistory` unset refuse an IFC2X3 model with
15//! [`PropertyError::AuthoringRequired`] instead of writing `$`. The
16//! `*_with_owner_history` variants take a caller-supplied `IfcOwnerHistory`,
17//! which must exist (in the model or staged on the transaction) and be an
18//! `IfcOwnerHistory`; one is never invented here (build it with
19//! `ifc-author`). IFC4 and IFC4X3 records are the same as before.
20//!
21//! [`add_property_set`](super::authoring::add_property_set) and
22//! [`add_element_quantity`](super::authoring::add_element_quantity) take no
23//! model and cannot refuse. So in a release that requires `OwnerHistory`,
24//! [`attach_property_set_with_owner_history`] refuses to attach a
25//! definition whose own `OwnerHistory` is unset.
26
27use ifc_model::guid::Guid;
28use ifc_model::{EntityId, Model, Transaction, Value};
29
30use super::authoring::{check_element_quantity, check_property_set, optional_text};
31use crate::quantity::release::{bind, projected, Layout};
32use crate::{PropertyError, PropertyResult};
33
34/// [`add_property_set`](crate::add_property_set) in the model's declared
35/// release, with a caller-supplied `IfcOwnerHistory`, which IFC2X3 requires.
36///
37/// # Errors
38///
39/// Those of [`add_property_set`](crate::add_property_set), and:
40/// [`PropertyError::MultipleSchemas`] or [`PropertyError::UnsupportedSchema`]
41/// if the model binds no single known release;
42/// [`PropertyError::MissingEntity`] if `owner_history` is neither in the
43/// model nor staged; [`PropertyError::AuthoringInvalid`] if it is not an
44/// `IfcOwnerHistory`. Nothing is staged on an error.
45pub fn add_property_set_with_owner_history(
46    tx: &mut Transaction,
47    model: &Model,
48    global_id: &str,
49    name: &str,
50    description: Option<&str>,
51    properties: &[(&str, EntityId)],
52    owner_history: EntityId,
53) -> PropertyResult<EntityId> {
54    const ENTITY: &str = "IFCPROPERTYSET";
55    let layout = bind(model)?;
56    check_property_set(global_id, name, properties)?;
57    require_owner_history(tx, model, layout, ENTITY, owner_history)?;
58    let record = layout.named_record(
59        ENTITY,
60        vec![
61            ("GlobalId", Value::Text(global_id.into())),
62            ("OwnerHistory", Value::Ref(owner_history)),
63            ("Name", Value::Text(name.into())),
64            ("Description", optional_text(description)),
65            (
66                "HasProperties",
67                Value::List(properties.iter().map(|(_, id)| Value::Ref(*id)).collect()),
68            ),
69        ],
70    )?;
71    Ok(tx.create(record))
72}
73
74/// [`add_element_quantity`](crate::add_element_quantity) in the model's
75/// declared release, with a caller-supplied `IfcOwnerHistory`, which IFC2X3
76/// requires.
77///
78/// # Errors
79///
80/// Those of [`add_element_quantity`](crate::add_element_quantity), and the
81/// release and owner-history refusals of
82/// [`add_property_set_with_owner_history`]. Nothing is staged on an error.
83pub fn add_element_quantity_with_owner_history(
84    tx: &mut Transaction,
85    model: &Model,
86    global_id: &str,
87    name: &str,
88    method_of_measurement: Option<&str>,
89    quantities: &[EntityId],
90    owner_history: EntityId,
91) -> PropertyResult<EntityId> {
92    const ENTITY: &str = "IFCELEMENTQUANTITY";
93    let layout = bind(model)?;
94    check_element_quantity(global_id, name, quantities)?;
95    require_owner_history(tx, model, layout, ENTITY, owner_history)?;
96    let record = layout.named_record(
97        ENTITY,
98        vec![
99            ("GlobalId", Value::Text(global_id.into())),
100            ("OwnerHistory", Value::Ref(owner_history)),
101            ("Name", Value::Text(name.into())),
102            ("MethodOfMeasurement", optional_text(method_of_measurement)),
103            ("Quantities", refs(quantities)),
104        ],
105    )?;
106    Ok(tx.create(record))
107}
108
109/// [`attach_property_set`](crate::attach_property_set) with a
110/// caller-supplied `IfcOwnerHistory`, which IFC2X3 requires.
111///
112/// # Errors
113///
114/// Those of [`attach_property_set`](crate::attach_property_set) except the
115/// IFC2X3 refusal, the owner-history refusals of
116/// [`add_property_set_with_owner_history`], and
117/// [`PropertyError::AuthoringInvalid`] on `RelatingPropertyDefinition` when
118/// the release requires `OwnerHistory` and the definition leaves it unset,
119/// as [`add_property_set`](crate::add_property_set) does. Nothing is staged
120/// on an error.
121pub fn attach_property_set_with_owner_history(
122    tx: &mut Transaction,
123    model: &Model,
124    global_id: &str,
125    objects: &[EntityId],
126    property_set: EntityId,
127    owner_history: EntityId,
128) -> PropertyResult<EntityId> {
129    attach_definition(
130        tx,
131        model,
132        global_id,
133        objects,
134        property_set,
135        Some(owner_history),
136    )
137}
138
139/// [`attach_type`](crate::attach_type) with a caller-supplied
140/// `IfcOwnerHistory`, which IFC2X3 requires.
141///
142/// # Errors
143///
144/// Those of [`attach_type`](crate::attach_type) except the IFC2X3 refusal,
145/// and the owner-history refusals of
146/// [`add_property_set_with_owner_history`]. Nothing is staged on an error.
147pub fn attach_type_with_owner_history(
148    tx: &mut Transaction,
149    model: &Model,
150    global_id: &str,
151    objects: &[EntityId],
152    relating_type: EntityId,
153    owner_history: EntityId,
154) -> PropertyResult<EntityId> {
155    attach_type_record(
156        tx,
157        model,
158        global_id,
159        objects,
160        relating_type,
161        Some(owner_history),
162    )
163}
164
165/// Stage an `IfcRelDefinesByProperties`; `None` leaves `OwnerHistory` `$`.
166pub(super) fn attach_definition(
167    tx: &mut Transaction,
168    model: &Model,
169    global_id: &str,
170    objects: &[EntityId],
171    property_set: EntityId,
172    owner_history: Option<EntityId>,
173) -> PropertyResult<EntityId> {
174    const ENTITY: &str = "IFCRELDEFINESBYPROPERTIES";
175    let layout = bind(model)?;
176    require_guid(ENTITY, global_id)?;
177    if objects.is_empty() {
178        return Err(invalid(ENTITY, "RelatedObjects", "an empty set"));
179    }
180    for object in objects {
181        let Some(entity) = model.get(*object) else {
182            return Err(PropertyError::MissingEntity { id: *object });
183        };
184        // NoRelatedTypeObject: a type carries its sets in HasPropertySets.
185        if layout.schema().is_a(&entity.type_name, "IFCTYPEOBJECT") {
186            return Err(invalid(
187                ENTITY,
188                "RelatedObjects",
189                entity.type_name.to_string(),
190            ));
191        }
192    }
193    if let Some(owner_history) = owner_history {
194        require_owner_history(tx, model, layout, ENTITY, owner_history)?;
195    }
196    let record = layout.named_record(
197        ENTITY,
198        vec![
199            ("GlobalId", Value::Text(global_id.into())),
200            (
201                "OwnerHistory",
202                owner_history.map_or(Value::Null, Value::Ref),
203            ),
204            ("RelatedObjects", refs(objects)),
205            ("RelatingPropertyDefinition", Value::Ref(property_set)),
206        ],
207    )?;
208    require_owned_definition(tx, model, layout, property_set)?;
209    Ok(tx.create(record))
210}
211
212/// Stage an `IfcRelDefinesByType`; `None` leaves `OwnerHistory` `$`.
213pub(super) fn attach_type_record(
214    tx: &mut Transaction,
215    model: &Model,
216    global_id: &str,
217    objects: &[EntityId],
218    relating_type: EntityId,
219    owner_history: Option<EntityId>,
220) -> PropertyResult<EntityId> {
221    const ENTITY: &str = "IFCRELDEFINESBYTYPE";
222    let layout = bind(model)?;
223    require_guid(ENTITY, global_id)?;
224    if objects.is_empty() {
225        return Err(invalid(ENTITY, "RelatedObjects", "empty"));
226    }
227    let is_type = |id: EntityId| {
228        model
229            .get(id)
230            .is_some_and(|entity| layout.schema().is_a(&entity.type_name, "IFCTYPEOBJECT"))
231    };
232    if !is_type(relating_type) {
233        return Err(invalid(ENTITY, "RelatingType", "not an IfcTypeObject"));
234    }
235    if objects.iter().any(|object| is_type(*object)) {
236        return Err(invalid(
237            ENTITY,
238            "RelatedObjects",
239            "a type object cannot be an occurrence",
240        ));
241    }
242    if let Some(owner_history) = owner_history {
243        require_owner_history(tx, model, layout, ENTITY, owner_history)?;
244    }
245    let record = layout.named_record(
246        ENTITY,
247        vec![
248            ("GlobalId", Value::Text(global_id.into())),
249            (
250                "OwnerHistory",
251                owner_history.map_or(Value::Null, Value::Ref),
252            ),
253            ("RelatedObjects", refs(objects)),
254            ("RelatingType", Value::Ref(relating_type)),
255        ],
256    )?;
257    Ok(tx.create(record))
258}
259
260/// Fail unless `id` is an `IfcOwnerHistory` in the model or staged on `tx`.
261pub(super) fn require_owner_history(
262    tx: &Transaction,
263    model: &Model,
264    layout: Layout,
265    entity: &'static str,
266    id: EntityId,
267) -> PropertyResult<()> {
268    let found = projected(tx, model, id).ok_or(PropertyError::MissingEntity { id })?;
269    if found.type_name.eq_ignore_ascii_case("IFCOWNERHISTORY")
270        && layout.schema().entity("IFCOWNERHISTORY").is_some()
271    {
272        return Ok(());
273    }
274    Err(invalid(
275        entity,
276        "OwnerHistory",
277        format!("#{} is a {}, not an IfcOwnerHistory", id.0, found.type_name),
278    ))
279}
280
281/// In a release that requires `IfcRoot.OwnerHistory`, refuse to attach a
282/// definition that leaves it unset: the relationship would be valid and
283/// the file it lands in would not.
284///
285/// A definition that cannot be found is left to the caller, as before.
286fn require_owned_definition(
287    tx: &Transaction,
288    model: &Model,
289    layout: Layout,
290    definition: EntityId,
291) -> PropertyResult<()> {
292    let Some(found) = projected(tx, model, definition) else {
293        return Ok(());
294    };
295    let declared = layout.schema().attributes(&found.type_name);
296    let unset = declared
297        .iter()
298        .position(|attribute| attribute.name.eq_ignore_ascii_case("OwnerHistory"))
299        .filter(|slot| !declared[*slot].optional)
300        .is_some_and(|slot| matches!(found.attributes.get(slot), None | Some(Value::Null)));
301    if !unset {
302        return Ok(());
303    }
304    Err(invalid(
305        "IFCRELDEFINESBYPROPERTIES",
306        "RelatingPropertyDefinition",
307        format!(
308            "#{} {} has no OwnerHistory, which {:?} requires",
309            definition.0,
310            found.type_name,
311            layout.version()
312        ),
313    ))
314}
315
316fn require_guid(entity: &'static str, global_id: &str) -> PropertyResult<()> {
317    if Guid::parse(global_id).is_none() {
318        return Err(invalid(entity, "GlobalId", global_id));
319    }
320    Ok(())
321}
322
323fn invalid(
324    entity: &'static str,
325    attribute: &'static str,
326    value: impl Into<String>,
327) -> PropertyError {
328    PropertyError::AuthoringInvalid {
329        entity,
330        attribute,
331        value: value.into(),
332    }
333}
334
335fn refs(ids: &[EntityId]) -> Value {
336    Value::List(ids.iter().copied().map(Value::Ref).collect())
337}