Skip to main content

ifc_properties/pset/
authoring.rs

1//! Transactional authoring of property sets and their attachment.
2//!
3//! Reading lives in the sibling modules; this is the write side.
4//! Slot order is resolved from the bundled IFC4X3 schema, not
5//! from memory: a pset writes HasProperties at slot 4 because
6//! four IfcRoot fields precede it.
7//!
8//! The `IfcRoot` writers that take the model, and the
9//! `*_with_owner_history` variants, are bound to the declared release in
10//! `root_authoring.rs` (#191).
11//!
12//! # Why the schema WHERE rules are enforced here
13//!
14//! IfcPropertySet states ExistsName and UniquePropertyNames.
15//! A nameless pset cannot be looked up, and duplicate property
16//! names make a lookup ambiguous: both parse, both corrupt.
17use ifc_model::{Entity, EntityId, Model, Transaction, Value};
18
19use ifc_model::guid::Guid;
20
21use crate::{PropertyError, PropertyResult};
22
23use super::value_form::{require_ifc_value, require_ifc_values};
24
25/// `IfcPropertySet` slots.
26pub mod pset_slot {
27    /// `GlobalId` (from `IfcRoot`).
28    pub const GLOBAL_ID: usize = 0;
29    /// `Name` (from `IfcRoot`). Required by the ExistsName rule.
30    pub const NAME: usize = 2;
31    /// `Description` (from `IfcRoot`).
32    pub const DESCRIPTION: usize = 3;
33    /// `HasProperties`. Required.
34    pub const HAS_PROPERTIES: usize = 4;
35}
36
37/// `IfcPropertySingleValue` slots.
38pub mod single_value_slot {
39    /// `Name` (from `IfcProperty`). Required.
40    pub const NAME: usize = 0;
41    /// `Specification` (from `IfcProperty`).
42    pub const SPECIFICATION: usize = 1;
43    /// `NominalValue`.
44    pub const NOMINAL_VALUE: usize = 2;
45    /// `Unit`.
46    pub const UNIT: usize = 3;
47}
48
49/// `IfcRelDefinesByProperties` slots.
50pub mod defines_slot {
51    /// `GlobalId` (from `IfcRoot`).
52    pub const GLOBAL_ID: usize = 0;
53    /// `RelatedObjects`. Required.
54    pub const RELATED_OBJECTS: usize = 4;
55    /// `RelatingPropertyDefinition`. Required.
56    pub const RELATING_DEFINITION: usize = 5;
57}
58
59/// Stage an `IfcPropertySingleValue`.
60///
61/// `value` is an `IfcValue`: a measure-wrapped scalar such as
62/// `Value::Typed { type_name: IFCLENGTHMEASURE, .. }`. `IfcValue` is a
63/// SELECT, so ISO 10303-21 writes its value as a typed parameter naming
64/// the member; this crate will not invent a measure for a bare literal.
65///
66/// `specification` is `IfcProperty.Specification`: prose describing
67/// what the property means, kept distinct from its value.
68///
69/// # Errors
70///
71/// Refuses a blank name: IfcProperty.Name is required, and a
72/// whitespace-only name satisfies EXISTS while naming nothing. Refuses a
73/// bare literal with [`PropertyError::ValueForm`], and a value that is no
74/// `IfcValue` (a reference, an aggregate, an enumeration constant) with
75/// [`PropertyError::AuthoringInvalid`].
76pub fn add_property_single_value(
77    tx: &mut Transaction,
78    name: &str,
79    specification: Option<&str>,
80    value: Option<Value>,
81    unit: Option<EntityId>,
82) -> PropertyResult<EntityId> {
83    if name.trim().is_empty() {
84        return Err(PropertyError::AuthoringInvalid {
85            entity: "IFCPROPERTYSINGLEVALUE",
86            attribute: "Name",
87            value: name.to_owned(),
88        });
89    }
90    if let Some(value) = value.as_ref() {
91        require_ifc_value("IFCPROPERTYSINGLEVALUE", "NominalValue", value)?;
92    }
93    let mut attributes = vec![Value::Null; single_value_slot::UNIT + 1];
94    attributes[single_value_slot::NAME] = Value::Text(name.into());
95    attributes[single_value_slot::SPECIFICATION] = optional_text(specification);
96    attributes[single_value_slot::NOMINAL_VALUE] = value.unwrap_or(Value::Null);
97    attributes[single_value_slot::UNIT] = unit.map_or(Value::Null, Value::Ref);
98    Ok(tx.create(Entity::new("IFCPROPERTYSINGLEVALUE", attributes)))
99}
100
101/// Stage an `IfcPropertySet`.
102///
103/// # Release
104///
105/// `OwnerHistory` is left `$`, which IFC4 and IFC4X3 allow and IFC2X3
106/// forbids. This function takes no model, so it cannot see the release and
107/// cannot refuse an IFC2X3 one; for IFC2X3 use
108/// [`add_property_set_with_owner_history`](crate::add_property_set_with_owner_history).
109/// [`attach_property_set_with_owner_history`](crate::attach_property_set_with_owner_history)
110/// refuses to attach, in IFC2X3, a set written here.
111///
112/// # Errors
113///
114/// Refuses a blank name (ExistsName), an empty property list
115/// (HasProperties is required), and duplicate property names
116/// (UniquePropertyNames).
117///
118/// Properties are passed as `(name, id)` pairs rather than bare ids:
119/// the uniqueness rule is stated over names, and a staged entity
120/// cannot be read back out of the transaction to recover them.
121pub fn add_property_set(
122    tx: &mut Transaction,
123    global_id: &str,
124    name: &str,
125    description: Option<&str>,
126    properties: &[(&str, EntityId)],
127) -> PropertyResult<EntityId> {
128    check_property_set(global_id, name, properties)?;
129    let refs = properties.iter().map(|(_, id)| Value::Ref(*id)).collect();
130    let mut attributes = vec![Value::Null; pset_slot::HAS_PROPERTIES + 1];
131    attributes[pset_slot::GLOBAL_ID] = Value::Text(global_id.into());
132    attributes[pset_slot::NAME] = Value::Text(name.into());
133    attributes[pset_slot::DESCRIPTION] = optional_text(description);
134    attributes[pset_slot::HAS_PROPERTIES] = Value::List(refs);
135    Ok(tx.create(Entity::new("IFCPROPERTYSET", attributes)))
136}
137
138/// The `IfcPropertySet` rules [`add_property_set`] enforces, shared with its
139/// release-bound variant.
140pub(super) fn check_property_set(
141    global_id: &str,
142    name: &str,
143    properties: &[(&str, EntityId)],
144) -> PropertyResult<()> {
145    if Guid::parse(global_id).is_none() {
146        return Err(PropertyError::AuthoringInvalid {
147            entity: "IFCPROPERTYSET",
148            attribute: "GlobalId",
149            value: global_id.to_owned(),
150        });
151    }
152    if name.trim().is_empty() {
153        return Err(PropertyError::AuthoringInvalid {
154            entity: "IFCPROPERTYSET",
155            attribute: "Name",
156            value: name.to_owned(),
157        });
158    }
159    if properties.is_empty() {
160        return Err(PropertyError::AuthoringInvalid {
161            entity: "IFCPROPERTYSET",
162            attribute: "HasProperties",
163            value: String::from("an empty set"),
164        });
165    }
166    let mut seen = std::collections::BTreeSet::new();
167    for (property_name, _) in properties {
168        if !seen.insert(*property_name) {
169            return Err(PropertyError::AuthoringInvalid {
170                entity: "IFCPROPERTYSET",
171                attribute: "HasProperties",
172                value: (*property_name).to_owned(),
173            });
174        }
175    }
176    Ok(())
177}
178
179pub(super) fn optional_text(value: Option<&str>) -> Value {
180    value.map_or(Value::Null, |text| Value::Text(text.into()))
181}
182
183/// Stage an `IfcRelDefinesByProperties` attaching a set to objects.
184///
185/// # Release
186///
187/// Bound to the model's declared release (`quantity/release.rs`): the
188/// record is laid out by attribute name from its table, and the
189/// NoRelatedTypeObject check uses its inheritance. `OwnerHistory` is left
190/// `$`, which IFC4 and IFC4X3 allow; IFC2X3 requires it, so an IFC2X3 model
191/// is refused with [`PropertyError::AuthoringRequired`]. Use
192/// [`attach_property_set_with_owner_history`](crate::attach_property_set_with_owner_history)
193/// there.
194///
195/// # Errors
196///
197/// Refuses an empty object list, and any object whose type is an
198/// `IfcTypeObject` subtype. The schema states NoRelatedTypeObject:
199/// a type carries properties through IfcRelDefinesByType instead, and
200/// attaching here would be read by nothing that walks type properties.
201/// Refuses a model that binds no single known release with
202/// [`PropertyError::MultipleSchemas`] or
203/// [`PropertyError::UnsupportedSchema`], and an IFC2X3 model with
204/// [`PropertyError::AuthoringRequired`]. Nothing is staged on an error.
205///
206/// Needs the model because the rule is stated over the related
207/// objects types, which only the committed model knows.
208pub fn attach_property_set(
209    tx: &mut Transaction,
210    model: &Model,
211    global_id: &str,
212    objects: &[EntityId],
213    property_set: EntityId,
214) -> PropertyResult<EntityId> {
215    super::root_authoring::attach_definition(tx, model, global_id, objects, property_set, None)
216}
217
218/// `IfcPropertyEnumeratedValue` slots.
219pub mod enumerated_slot {
220    /// `Name`. Required.
221    pub const NAME: usize = 0;
222    /// `Specification`.
223    pub const SPECIFICATION: usize = 1;
224    /// `EnumerationValues`.
225    pub const VALUES: usize = 2;
226    /// `EnumerationReference`.
227    pub const REFERENCE: usize = 3;
228}
229
230/// `IfcPropertyBoundedValue` slots.
231pub mod bounded_slot {
232    /// `Name`. Required.
233    pub const NAME: usize = 0;
234    /// `Specification`.
235    pub const SPECIFICATION: usize = 1;
236    /// `UpperBoundValue`.
237    pub const UPPER: usize = 2;
238    /// `LowerBoundValue`.
239    pub const LOWER: usize = 3;
240    /// `Unit`.
241    pub const UNIT: usize = 4;
242    /// `SetPointValue`.
243    pub const SET_POINT: usize = 5;
244}
245
246/// `IfcPropertyListValue` slots.
247pub mod list_slot {
248    /// `Name`. Required.
249    pub const NAME: usize = 0;
250    /// `Specification`.
251    pub const SPECIFICATION: usize = 1;
252    /// `ListValues`.
253    pub const VALUES: usize = 2;
254    /// `Unit`.
255    pub const UNIT: usize = 3;
256}
257
258/// `IfcPropertyTableValue` slots.
259pub mod table_slot {
260    /// `Name`. Required.
261    pub const NAME: usize = 0;
262    /// `Specification`.
263    pub const SPECIFICATION: usize = 1;
264    /// `DefiningValues`, the independent variable.
265    pub const DEFINING: usize = 2;
266    /// `DefinedValues`, the dependent variable.
267    pub const DEFINED: usize = 3;
268    /// `Expression`.
269    pub const EXPRESSION: usize = 4;
270    /// `DefiningUnit`.
271    pub const DEFINING_UNIT: usize = 5;
272    /// `DefinedUnit`.
273    pub const DEFINED_UNIT: usize = 6;
274    /// `CurveInterpolation`.
275    pub const INTERPOLATION: usize = 7;
276}
277
278/// `IfcPropertyReferenceValue` slots.
279pub mod reference_slot {
280    /// `Name`. Required.
281    pub const NAME: usize = 0;
282    /// `Specification`.
283    pub const SPECIFICATION: usize = 1;
284    /// `UsageName`.
285    pub const USAGE_NAME: usize = 2;
286    /// `PropertyReference`.
287    pub const REFERENCE: usize = 3;
288}
289
290/// `IfcComplexProperty` slots.
291pub mod complex_slot {
292    /// `Name`. Required.
293    pub const NAME: usize = 0;
294    /// `Specification`.
295    pub const SPECIFICATION: usize = 1;
296    /// `UsageName`. Required.
297    pub const USAGE_NAME: usize = 2;
298    /// `HasProperties`. Required.
299    pub const HAS_PROPERTIES: usize = 3;
300}
301
302/// Refuse a blank property name.
303///
304/// `IfcProperty.Name` is required and is the key every lookup uses. A
305/// whitespace-only name satisfies the schema's EXISTS check and still
306/// names nothing.
307pub(super) fn require_name(entity: &'static str, name: &str) -> PropertyResult<()> {
308    if name.trim().is_empty() {
309        return Err(PropertyError::AuthoringInvalid {
310            entity,
311            attribute: "Name",
312            value: name.to_owned(),
313        });
314    }
315    Ok(())
316}
317
318/// Stage an `IfcPropertyEnumeratedValue`.
319///
320/// # Errors
321///
322/// Refuses a blank name, and an empty value list: the schema types
323/// `EnumerationValues` as `LIST [1:?]`, so an empty aggregate is
324/// malformed where omission is legal. Each value is an `IfcValue`,
325/// refused as [`add_property_single_value`] refuses one.
326pub fn add_property_enumerated_value(
327    tx: &mut Transaction,
328    name: &str,
329    specification: Option<&str>,
330    values: Option<Vec<Value>>,
331    enumeration: Option<EntityId>,
332) -> PropertyResult<EntityId> {
333    require_name("IFCPROPERTYENUMERATEDVALUE", name)?;
334    if let Some(values) = values.as_ref() {
335        if values.is_empty() {
336            return Err(PropertyError::AuthoringInvalid {
337                entity: "IFCPROPERTYENUMERATEDVALUE",
338                attribute: "EnumerationValues",
339                value: "empty".to_owned(),
340            });
341        }
342        require_ifc_values("IFCPROPERTYENUMERATEDVALUE", "EnumerationValues", values)?;
343    }
344    let mut attributes = vec![Value::Null; enumerated_slot::REFERENCE + 1];
345    attributes[enumerated_slot::NAME] = Value::Text(name.into());
346    attributes[enumerated_slot::SPECIFICATION] = optional_text(specification);
347    attributes[enumerated_slot::VALUES] = values.map_or(Value::Null, Value::List);
348    attributes[enumerated_slot::REFERENCE] = enumeration.map_or(Value::Null, Value::Ref);
349    Ok(tx.create(Entity::new("IFCPROPERTYENUMERATEDVALUE", attributes)))
350}
351
352/// The declared measure of a value, when it wears one.
353///
354/// `Value::Typed { type_name, .. }` is how a measure-wrapped scalar
355/// reaches this crate. A bare literal has no measure and compares
356/// equal to any other bare literal.
357fn measure_of(value: &Value) -> Option<&str> {
358    match value {
359        Value::Typed { type_name, .. } => Some(type_name.as_ref()),
360        _ => None,
361    }
362}
363
364/// Stage an `IfcPropertyBoundedValue`.
365///
366/// # Errors
367///
368/// Refuses a blank name, and bounds whose measures disagree. The
369/// schema states SameUnitUpperLower, SameUnitLowerSet and
370/// SameUnitUpperSet: mixing a length lower bound with a mass upper
371/// bound parses and then compares two different quantities. Each bound
372/// is an `IfcValue`, refused as [`add_property_single_value`] refuses
373/// one.
374pub fn add_property_bounded_value(
375    tx: &mut Transaction,
376    name: &str,
377    specification: Option<&str>,
378    upper: Option<Value>,
379    lower: Option<Value>,
380    set_point: Option<Value>,
381    unit: Option<EntityId>,
382) -> PropertyResult<EntityId> {
383    require_name("IFCPROPERTYBOUNDEDVALUE", name)?;
384    for (attribute, value) in [
385        ("UpperBoundValue", upper.as_ref()),
386        ("LowerBoundValue", lower.as_ref()),
387        ("SetPointValue", set_point.as_ref()),
388    ] {
389        if let Some(value) = value {
390            require_ifc_value("IFCPROPERTYBOUNDEDVALUE", attribute, value)?;
391        }
392    }
393    let stated: Vec<(&str, &Value)> = [
394        ("UpperBoundValue", upper.as_ref()),
395        ("LowerBoundValue", lower.as_ref()),
396        ("SetPointValue", set_point.as_ref()),
397    ]
398    .into_iter()
399    .filter_map(|(label, value)| value.map(|value| (label, value)))
400    .collect();
401    if let Some(((_, first), rest)) = stated.split_first() {
402        let want = measure_of(first);
403        for (label, value) in rest {
404            if measure_of(value) != want {
405                return Err(PropertyError::AuthoringInvalid {
406                    entity: "IFCPROPERTYBOUNDEDVALUE",
407                    attribute: "SameUnit",
408                    value: (*label).to_owned(),
409                });
410            }
411        }
412    }
413    let mut attributes = vec![Value::Null; bounded_slot::SET_POINT + 1];
414    attributes[bounded_slot::NAME] = Value::Text(name.into());
415    attributes[bounded_slot::SPECIFICATION] = optional_text(specification);
416    attributes[bounded_slot::UPPER] = upper.unwrap_or(Value::Null);
417    attributes[bounded_slot::LOWER] = lower.unwrap_or(Value::Null);
418    attributes[bounded_slot::UNIT] = unit.map_or(Value::Null, Value::Ref);
419    attributes[bounded_slot::SET_POINT] = set_point.unwrap_or(Value::Null);
420    Ok(tx.create(Entity::new("IFCPROPERTYBOUNDEDVALUE", attributes)))
421}
422
423/// Stage an `IfcPropertyListValue`.
424///
425/// # Errors
426///
427/// Refuses a blank name and an empty list, which the schema types as
428/// `LIST [1:?]`. Each value is an `IfcValue`, refused as
429/// [`add_property_single_value`] refuses one.
430pub fn add_property_list_value(
431    tx: &mut Transaction,
432    name: &str,
433    specification: Option<&str>,
434    values: Option<Vec<Value>>,
435    unit: Option<EntityId>,
436) -> PropertyResult<EntityId> {
437    require_name("IFCPROPERTYLISTVALUE", name)?;
438    if let Some(values) = values.as_ref() {
439        if values.is_empty() {
440            return Err(PropertyError::AuthoringInvalid {
441                entity: "IFCPROPERTYLISTVALUE",
442                attribute: "ListValues",
443                value: "empty".to_owned(),
444            });
445        }
446        require_ifc_values("IFCPROPERTYLISTVALUE", "ListValues", values)?;
447    }
448    let mut attributes = vec![Value::Null; list_slot::UNIT + 1];
449    attributes[list_slot::NAME] = Value::Text(name.into());
450    attributes[list_slot::SPECIFICATION] = optional_text(specification);
451    attributes[list_slot::VALUES] = values.map_or(Value::Null, Value::List);
452    attributes[list_slot::UNIT] = unit.map_or(Value::Null, Value::Ref);
453    Ok(tx.create(Entity::new("IFCPROPERTYLISTVALUE", attributes)))
454}
455
456/// Authored fields for `IfcPropertyTableValue`.
457///
458/// A struct rather than a parameter list: the entity carries two
459/// columns, two units and two free-text fields, and positional
460/// arguments of the same types are easy to transpose silently.
461#[derive(Debug, Default)]
462#[non_exhaustive]
463pub struct TableValueDraft<'a> {
464    /// `Name`. Required, and the key every lookup uses.
465    pub name: &'a str,
466    /// `Specification`.
467    pub specification: Option<&'a str>,
468    /// `DefiningValues`, the independent variable.
469    pub defining: Option<Vec<Value>>,
470    /// `DefinedValues`, the dependent variable.
471    pub defined: Option<Vec<Value>>,
472    /// `DefiningUnit`.
473    pub defining_unit: Option<EntityId>,
474    /// `DefinedUnit`.
475    pub defined_unit: Option<EntityId>,
476    /// `Expression`, the closed form when one exists.
477    pub expression: Option<&'a str>,
478    /// `CurveInterpolation`, an `IfcCurveInterpolationEnum` token.
479    pub interpolation: Option<&'a str>,
480}
481
482/// Stage an `IfcPropertyTableValue`.
483///
484/// A lookup table: `defining` is the independent variable, `defined`
485/// the dependent one, and row `i` pairs `defining[i]` with
486/// `defined[i]`.
487///
488/// # Errors
489///
490/// Refuses a blank name. Enforces the schema's three table rules:
491/// WR21, the two columns must be the same length, since a row whose
492/// input has no output is not a row; WR22 and WR23, each column must
493/// be homogeneous, since a column mixing lengths and masses cannot be
494/// interpolated. Each value is an `IfcValue`, refused as
495/// [`add_property_single_value`] refuses one.
496pub fn add_property_table_value(
497    tx: &mut Transaction,
498    draft: TableValueDraft<'_>,
499) -> PropertyResult<EntityId> {
500    let TableValueDraft {
501        name,
502        specification,
503        defining,
504        defined,
505        defining_unit,
506        defined_unit,
507        expression,
508        interpolation,
509    } = draft;
510    require_name("IFCPROPERTYTABLEVALUE", name)?;
511    let sizes = (
512        defining.as_ref().map(Vec::len),
513        defined.as_ref().map(Vec::len),
514    );
515    if let (Some(left), Some(right)) = sizes {
516        if left != right {
517            return Err(PropertyError::AuthoringInvalid {
518                entity: "IFCPROPERTYTABLEVALUE",
519                attribute: "DefiningValues",
520                value: format!("{left} defining against {right} defined"),
521            });
522        }
523    }
524    for (label, column) in [
525        ("DefiningValues", defining.as_ref()),
526        ("DefinedValues", defined.as_ref()),
527    ] {
528        let Some(column) = column else { continue };
529        if column.is_empty() {
530            return Err(PropertyError::AuthoringInvalid {
531                entity: "IFCPROPERTYTABLEVALUE",
532                attribute: label,
533                value: "empty".to_owned(),
534            });
535        }
536        require_ifc_values("IFCPROPERTYTABLEVALUE", label, column)?;
537        let want = measure_of(&column[0]);
538        if column.iter().any(|value| measure_of(value) != want) {
539            return Err(PropertyError::AuthoringInvalid {
540                entity: "IFCPROPERTYTABLEVALUE",
541                attribute: label,
542                value: "mixed measures".to_owned(),
543            });
544        }
545    }
546    let mut attributes = vec![Value::Null; table_slot::INTERPOLATION + 1];
547    attributes[table_slot::NAME] = Value::Text(name.into());
548    attributes[table_slot::SPECIFICATION] = optional_text(specification);
549    attributes[table_slot::DEFINING] = defining.map_or(Value::Null, Value::List);
550    attributes[table_slot::DEFINED] = defined.map_or(Value::Null, Value::List);
551    attributes[table_slot::EXPRESSION] = optional_text(expression);
552    attributes[table_slot::DEFINING_UNIT] = defining_unit.map_or(Value::Null, Value::Ref);
553    attributes[table_slot::DEFINED_UNIT] = defined_unit.map_or(Value::Null, Value::Ref);
554    attributes[table_slot::INTERPOLATION] =
555        interpolation.map_or(Value::Null, |token| Value::Enum(token.into()));
556    Ok(tx.create(Entity::new("IFCPROPERTYTABLEVALUE", attributes)))
557}
558
559/// Stage an `IfcPropertyReferenceValue`.
560///
561/// Points at another entity rather than carrying a scalar: a table,
562/// a document reference, a time series.
563///
564/// # Errors
565///
566/// Refuses a blank name.
567pub fn add_property_reference_value(
568    tx: &mut Transaction,
569    name: &str,
570    specification: Option<&str>,
571    usage_name: Option<&str>,
572    reference: Option<EntityId>,
573) -> PropertyResult<EntityId> {
574    require_name("IFCPROPERTYREFERENCEVALUE", name)?;
575    let mut attributes = vec![Value::Null; reference_slot::REFERENCE + 1];
576    attributes[reference_slot::NAME] = Value::Text(name.into());
577    attributes[reference_slot::SPECIFICATION] = optional_text(specification);
578    attributes[reference_slot::USAGE_NAME] = optional_text(usage_name);
579    attributes[reference_slot::REFERENCE] = reference.map_or(Value::Null, Value::Ref);
580    Ok(tx.create(Entity::new("IFCPROPERTYREFERENCEVALUE", attributes)))
581}
582
583/// Stage an `IfcComplexProperty`.
584///
585/// Groups properties under one name, so a U-value can carry its own
586/// measurement conditions as nested properties.
587///
588/// # Errors
589///
590/// Refuses a blank name or usage name, an empty `HasProperties` (the
591/// schema types it `SET [1:?]`), duplicate nested names, and a
592/// property listed as its own child. The schema states WR21 as
593/// `SELF :=: temp`, forbidding direct self-containment: a complex
594/// property inside itself is a cycle that a recursive reader cannot
595/// terminate on.
596pub fn add_complex_property(
597    tx: &mut Transaction,
598    name: &str,
599    specification: Option<&str>,
600    usage_name: &str,
601    properties: &[(&str, EntityId)],
602) -> PropertyResult<EntityId> {
603    require_name("IFCCOMPLEXPROPERTY", name)?;
604    if usage_name.trim().is_empty() {
605        return Err(PropertyError::AuthoringInvalid {
606            entity: "IFCCOMPLEXPROPERTY",
607            attribute: "UsageName",
608            value: usage_name.to_owned(),
609        });
610    }
611    if properties.is_empty() {
612        return Err(PropertyError::AuthoringInvalid {
613            entity: "IFCCOMPLEXPROPERTY",
614            attribute: "HasProperties",
615            value: "empty".to_owned(),
616        });
617    }
618    let mut seen = std::collections::BTreeSet::new();
619    for (property_name, _) in properties {
620        if !seen.insert(*property_name) {
621            return Err(PropertyError::AuthoringInvalid {
622                entity: "IFCCOMPLEXPROPERTY",
623                attribute: "HasProperties",
624                value: (*property_name).to_owned(),
625            });
626        }
627    }
628    let refs = properties.iter().map(|(_, id)| Value::Ref(*id)).collect();
629    let mut attributes = vec![Value::Null; complex_slot::HAS_PROPERTIES + 1];
630    attributes[complex_slot::NAME] = Value::Text(name.into());
631    attributes[complex_slot::SPECIFICATION] = optional_text(specification);
632    attributes[complex_slot::USAGE_NAME] = Value::Text(usage_name.into());
633    attributes[complex_slot::HAS_PROPERTIES] = Value::List(refs);
634    // WR21 forbids SELF among HasProperties. The id is only known after
635    // staging, so the check runs here; the refusal abandons the staged
636    // record, which commit never sees because the caller drops the error.
637    let own = tx.create(Entity::new("IFCCOMPLEXPROPERTY", attributes));
638    if properties.iter().any(|(_, id)| *id == own) {
639        return Err(PropertyError::AuthoringInvalid {
640            entity: "IFCCOMPLEXPROPERTY",
641            attribute: "HasProperties",
642            value: "self reference".to_owned(),
643        });
644    }
645    Ok(own)
646}
647
648/// `IfcElementQuantity` slots.
649pub mod element_quantity_slot {
650    /// `GlobalId` (from `IfcRoot`). Required.
651    pub const GLOBAL_ID: usize = 0;
652    /// `Name` (from `IfcRoot`).
653    pub const NAME: usize = 2;
654    /// `Description` (from `IfcRoot`).
655    pub const DESCRIPTION: usize = 3;
656    /// `MethodOfMeasurement`.
657    pub const METHOD: usize = 4;
658    /// `Quantities`. Required.
659    pub const QUANTITIES: usize = 5;
660}
661
662/// `IfcPhysicalComplexQuantity` slots.
663pub mod complex_quantity_slot {
664    /// `Name`. Required.
665    pub const NAME: usize = 0;
666    /// `Description`.
667    pub const DESCRIPTION: usize = 1;
668    /// `HasQuantities`. Required.
669    pub const HAS_QUANTITIES: usize = 2;
670    /// `Discrimination`. Required.
671    pub const DISCRIMINATION: usize = 3;
672    /// `Quality`.
673    pub const QUALITY: usize = 4;
674    /// `Usage`.
675    pub const USAGE: usize = 5;
676}
677
678/// Stage an `IfcElementQuantity`.
679///
680/// The quantity-takeoff counterpart of a property set: a named group
681/// of measured quantities attached to an object through
682/// [`attach_property_set`], which accepts any
683/// `IfcPropertySetDefinition`.
684///
685/// # Release
686///
687/// `OwnerHistory` is left `$`, which IFC4 and IFC4X3 allow and IFC2X3
688/// forbids. This function takes no model, so it cannot refuse an IFC2X3
689/// one; there use
690/// [`add_element_quantity_with_owner_history`](crate::add_element_quantity_with_owner_history).
691///
692/// # Errors
693///
694/// Refuses a malformed GUID and an empty quantity list, which the
695/// schema types as `SET [1:?]`.
696pub fn add_element_quantity(
697    tx: &mut Transaction,
698    global_id: &str,
699    name: &str,
700    method_of_measurement: Option<&str>,
701    quantities: &[EntityId],
702) -> PropertyResult<EntityId> {
703    check_element_quantity(global_id, name, quantities)?;
704    let mut attributes = vec![Value::Null; element_quantity_slot::QUANTITIES + 1];
705    attributes[element_quantity_slot::GLOBAL_ID] = Value::Text(global_id.into());
706    attributes[element_quantity_slot::NAME] = Value::Text(name.into());
707    attributes[element_quantity_slot::METHOD] = optional_text(method_of_measurement);
708    attributes[element_quantity_slot::QUANTITIES] =
709        Value::List(quantities.iter().copied().map(Value::Ref).collect());
710    Ok(tx.create(Entity::new("IFCELEMENTQUANTITY", attributes)))
711}
712
713/// The `IfcElementQuantity` rules [`add_element_quantity`] enforces, shared
714/// with its release-bound variant.
715pub(super) fn check_element_quantity(
716    global_id: &str,
717    name: &str,
718    quantities: &[EntityId],
719) -> PropertyResult<()> {
720    if Guid::parse(global_id).is_none() {
721        return Err(PropertyError::AuthoringInvalid {
722            entity: "IFCELEMENTQUANTITY",
723            attribute: "GlobalId",
724            value: global_id.to_owned(),
725        });
726    }
727    require_name("IFCELEMENTQUANTITY", name)?;
728    if quantities.is_empty() {
729        return Err(PropertyError::AuthoringInvalid {
730            entity: "IFCELEMENTQUANTITY",
731            attribute: "Quantities",
732            value: "empty".to_owned(),
733        });
734    }
735    Ok(())
736}
737
738/// Stage an `IfcPhysicalComplexQuantity`.
739///
740/// Groups quantities that share a discrimination, so a wall's gross
741/// and net areas can sit under one heading.
742///
743/// # Errors
744///
745/// Refuses a blank name or discrimination, and an empty
746/// `HasQuantities`, typed `SET [1:?]` by the schema.
747pub fn add_physical_complex_quantity(
748    tx: &mut Transaction,
749    name: &str,
750    description: Option<&str>,
751    quantities: &[EntityId],
752    discrimination: &str,
753) -> PropertyResult<EntityId> {
754    require_name("IFCPHYSICALCOMPLEXQUANTITY", name)?;
755    if discrimination.trim().is_empty() {
756        return Err(PropertyError::AuthoringInvalid {
757            entity: "IFCPHYSICALCOMPLEXQUANTITY",
758            attribute: "Discrimination",
759            value: discrimination.to_owned(),
760        });
761    }
762    if quantities.is_empty() {
763        return Err(PropertyError::AuthoringInvalid {
764            entity: "IFCPHYSICALCOMPLEXQUANTITY",
765            attribute: "HasQuantities",
766            value: "empty".to_owned(),
767        });
768    }
769    let mut attributes = vec![Value::Null; complex_quantity_slot::USAGE + 1];
770    attributes[complex_quantity_slot::NAME] = Value::Text(name.into());
771    attributes[complex_quantity_slot::DESCRIPTION] = optional_text(description);
772    attributes[complex_quantity_slot::HAS_QUANTITIES] =
773        Value::List(quantities.iter().copied().map(Value::Ref).collect());
774    attributes[complex_quantity_slot::DISCRIMINATION] = Value::Text(discrimination.into());
775    Ok(tx.create(Entity::new("IFCPHYSICALCOMPLEXQUANTITY", attributes)))
776}
777
778mod builders;