Skip to main content

ifc_occurrence/
authoring.rs

1//! Authoring built-element and distribution occurrences.
2//!
3//! # The type pairing is the interesting rule
4//!
5//! `CorrectPredefinedType` repeats what the type catalogue already
6//! enforces. `CorrectTypeAssigned` does not: it says an occurrence
7//! may be typed by at most one type, and that type must be the single
8//! class the schema pairs with it. An `IfcPump` typed by an
9//! `IfcValveType` is not a pump with an unusual type, it is a
10//! contradiction: the occurrence claims to be a pump while its shared
11//! definition describes a valve.
12//!
13//! The writer therefore resolves the referenced type entity and
14//! compares its STEP class against the pairing the model's declared
15//! release states (#214): the IFC4 and IFC4X3 WHERE rule of the class,
16//! or IFC2X3's documented pairing, which types an `IfcDoor` by an
17//! `IfcDoorStyle`. That costs a model lookup, which is why `create`
18//! takes a `&Model`: a pairing that is not checked against the real
19//! entity is not checked at all.
20//!
21//! # The release decides the layout
22//!
23//! The same `&Model` names the release the occurrence is written in
24//! (#202). Slots, the `PredefinedType` enumeration and the required
25//! attributes come from that release's table by attribute name, never
26//! from the IFC4X3 catalogue row; see `release.rs`.
27
28use ifc_model::guid::Guid;
29use ifc_model::{EntityId, Model, Transaction, Value};
30
31use crate::draft::{specific_values, OccurrenceDraft};
32use crate::error::{OccurrenceError, OccurrenceResult};
33use crate::release::{bind, require_owner_history};
34use crate::table::Occurrence;
35
36fn text(v: Option<&str>) -> Value {
37    v.map_or(Value::Null, |s| Value::Text(s.into()))
38}
39
40fn slot_ref(v: Option<EntityId>) -> Value {
41    v.map_or(Value::Null, Value::Ref)
42}
43
44/// Stage one occurrence.
45///
46/// `typed_by` is the `IfcTypeObject` this occurrence takes its shared
47/// definition from, if any. It is checked against the one class the
48/// declared release pairs with `kind`; see
49/// [`OccurrenceError::WrongTypeClass`] and
50/// [`OccurrenceError::TypeClassNotInSchema`].
51///
52/// Refuses a malformed `global_id`, a `predefined_type` outside the
53/// class enum, `USERDEFINED` without `draft.object_type`, a
54/// `typed_by` of the wrong class or one that does not resolve, a
55/// `shape_type` or `bar_role` outside its enumeration
56/// ([`OccurrenceError::UnknownToken`]), and a measure the attribute does
57/// not admit ([`OccurrenceError::InvalidMeasure`]).
58///
59/// # Release
60///
61/// Written in the model's declared release (#202), laid out by attribute
62/// name from its table; a header without `FILE_SCHEMA` binds IFC4.
63/// `predefined_type` is checked against that release's enumeration, and a
64/// class the release does not declare is refused with
65/// [`OccurrenceError::EntityNotInSchema`]. `OwnerHistory` is left `$`,
66/// which IFC4 and IFC4X3 allow and IFC2X3 does not, so an IFC2X3 model is
67/// refused with [`OccurrenceError::AuthoringRequired`]; use
68/// [`create_with_owner_history`] there. Any other attribute the release
69/// requires and the draft leaves unset (IFC2X3 `IfcStair.ShapeType`, for
70/// one) is refused the same way, and a draft value for an attribute the
71/// release does not declare on the class with
72/// [`OccurrenceError::AuthoringNotInSchema`]. The type pairing is the
73/// bound release's own.
74///
75/// # Errors
76///
77/// The refusals above; [`OccurrenceError::MultipleSchemas`] or
78/// [`OccurrenceError::UnsupportedSchema`] for a model that binds no single
79/// known release. Nothing is staged on an error.
80pub fn create(
81    tx: &mut Transaction,
82    model: &Model,
83    kind: Occurrence,
84    global_id: &str,
85    predefined_type: Option<&str>,
86    typed_by: Option<EntityId>,
87    draft: OccurrenceDraft<'_>,
88) -> OccurrenceResult<EntityId> {
89    let request = Request {
90        kind,
91        global_id,
92        predefined_type,
93        typed_by,
94        draft,
95    };
96    author(tx, model, request, None)
97}
98
99/// [`create`] with a caller-supplied `IfcOwnerHistory`, which IFC2X3
100/// requires on every `IfcRoot`.
101///
102/// `owner_history` must be in the model or staged earlier on `tx`, and must
103/// be an `IfcOwnerHistory`; one is never invented here (build it with
104/// `ifc-author`). In IFC4 and IFC4X3 the reference fills the optional slot.
105///
106/// # Errors
107///
108/// Those of [`create`] except the IFC2X3 `OwnerHistory` refusal, and
109/// [`OccurrenceError::UnresolvedOwnerHistory`] or
110/// [`OccurrenceError::NotAnOwnerHistory`] for an `owner_history` that does
111/// not resolve or is another entity. Nothing is staged on an error.
112#[allow(clippy::too_many_arguments)]
113pub fn create_with_owner_history(
114    tx: &mut Transaction,
115    model: &Model,
116    kind: Occurrence,
117    global_id: &str,
118    predefined_type: Option<&str>,
119    typed_by: Option<EntityId>,
120    draft: OccurrenceDraft<'_>,
121    owner_history: EntityId,
122) -> OccurrenceResult<EntityId> {
123    let request = Request {
124        kind,
125        global_id,
126        predefined_type,
127        typed_by,
128        draft,
129    };
130    author(tx, model, request, Some(owner_history))
131}
132
133/// The caller's arguments, bundled.
134struct Request<'a> {
135    kind: Occurrence,
136    global_id: &'a str,
137    predefined_type: Option<&'a str>,
138    typed_by: Option<EntityId>,
139    draft: OccurrenceDraft<'a>,
140}
141
142/// Stage one occurrence; `None` leaves `OwnerHistory` `$`.
143fn author(
144    tx: &mut Transaction,
145    model: &Model,
146    request: Request<'_>,
147    owner_history: Option<EntityId>,
148) -> OccurrenceResult<EntityId> {
149    let Request {
150        kind,
151        global_id,
152        predefined_type,
153        typed_by,
154        draft,
155    } = request;
156    let entity = kind.type_name;
157    if Guid::parse(global_id).is_none() {
158        return Err(OccurrenceError::MalformedGuid {
159            value: global_id.into(),
160        });
161    }
162    let layout = bind(model)?;
163    layout.require_entity(entity)?;
164    if let Some(token) = predefined_type {
165        let Some(members) = layout.members(entity, "PredefinedType") else {
166            return Err(OccurrenceError::NoPredefinedType { entity });
167        };
168        if !members.contains(&token) {
169            return Err(OccurrenceError::UnknownPredefinedType {
170                entity,
171                token: token.into(),
172            });
173        }
174        if token == "USERDEFINED" && draft.object_type.is_none_or(|s| s.trim().is_empty()) {
175            return Err(OccurrenceError::UserDefinedWithoutObjectType { entity });
176        }
177    }
178
179    if let Some(id) = typed_by {
180        let Some(expected) = layout.type_class(kind)? else {
181            if kind.type_class.is_none() {
182                return Err(OccurrenceError::TypingNotPermitted { entity });
183            }
184            return Err(OccurrenceError::TypeClassNotInSchema {
185                entity,
186                schema: layout.version(),
187            });
188        };
189        let found = model
190            .get(id)
191            .ok_or(OccurrenceError::UnresolvedType { id })?
192            .type_name
193            .to_ascii_uppercase();
194        if !layout.is_a(&found, expected) {
195            return Err(OccurrenceError::WrongTypeClass {
196                entity,
197                expected,
198                found,
199            });
200        }
201    }
202
203    let specific = specific_values(layout, entity, &draft)?;
204    if let Some(owner_history) = owner_history {
205        require_owner_history(tx, model, owner_history)?;
206    }
207    let mut values = vec![
208        ("GlobalId", Value::Text(global_id.into())),
209        ("OwnerHistory", slot_ref(owner_history)),
210        ("Name", text(draft.name)),
211        ("Description", text(draft.description)),
212        ("ObjectType", text(draft.object_type)),
213        ("ObjectPlacement", slot_ref(draft.placement)),
214        ("Representation", slot_ref(draft.representation)),
215        ("Tag", text(draft.tag)),
216        (
217            "PredefinedType",
218            predefined_type.map_or(Value::Null, |token| Value::Enum(token.into())),
219        ),
220    ];
221    values.extend(specific);
222    let record = layout.named_record(entity, values)?;
223    Ok(tx.create(record))
224}