Skip to main content

ifc_constraint/
association.rs

1//! `IfcRelAssociatesConstraint`, the one rooted record of this crate.
2//!
3//! It is the one writer bound to the model's declared release (see
4//! `release.rs`), because it carries `IfcRoot.OwnerHistory`, which IFC2X3
5//! requires.
6
7use std::collections::HashSet;
8
9use ifc_model::guid::Guid;
10use ifc_model::{EntityId, Model, Transaction, Value};
11
12use crate::authoring::{final_type, optional_ref, optional_text, refs, text, validate_target_in};
13use crate::release::{bind, require_owner_history};
14use crate::{ConstraintError, ConstraintResult};
15
16const ASSIGNMENT: &str = "IFCRELASSOCIATESCONSTRAINT";
17
18/// Draft for one rooted constraint association.
19#[derive(Debug, Clone, Copy)]
20#[non_exhaustive]
21pub struct ConstraintAssociationDraft<'a> {
22    /// Compressed IFC GlobalId.
23    pub global_id: &'a str,
24    /// Optional relationship name.
25    pub name: Option<&'a str>,
26    /// Optional relationship description.
27    pub description: Option<&'a str>,
28    /// Non-empty unique definition-select targets.
29    pub related_objects: &'a [EntityId],
30    /// Optional association intent.
31    pub intent: Option<&'a str>,
32    /// Existing or earlier-staged metric/objective.
33    pub relating_constraint: EntityId,
34}
35
36impl<'a> ConstraintAssociationDraft<'a> {
37    /// Starts a draft from its required fields; every other field is unset.
38    #[must_use]
39    pub fn new(
40        global_id: &'a str,
41        related_objects: &'a [EntityId],
42        relating_constraint: EntityId,
43    ) -> Self {
44        Self {
45            global_id,
46            name: None,
47            description: None,
48            related_objects,
49            intent: None,
50            relating_constraint,
51        }
52    }
53
54    /// Sets `name`: Optional relationship name.
55    #[must_use]
56    pub fn name(mut self, value: &'a str) -> Self {
57        self.name = Some(value);
58        self
59    }
60
61    /// Sets `description`: Optional relationship description.
62    #[must_use]
63    pub fn description(mut self, value: &'a str) -> Self {
64        self.description = Some(value);
65        self
66    }
67
68    /// Sets `intent`: Optional association intent.
69    #[must_use]
70    pub fn intent(mut self, value: &'a str) -> Self {
71        self.intent = Some(value);
72        self
73    }
74}
75
76/// Validate and stage one rooted constraint association.
77///
78/// # Release
79///
80/// Bound to the model's declared release (#202): the record is laid out by
81/// attribute name from that release's table, and its references are checked
82/// against it (`RelatedObjects` is `IfcDefinitionSelect` in IFC4 and IFC4X3,
83/// `IfcRoot` restricted by WR21 in IFC2X3). `OwnerHistory` is left `$`,
84/// which IFC4 and IFC4X3 allow and IFC2X3 does not, so an IFC2X3 model is
85/// refused with [`ConstraintError::AuthoringRequired`]. Use
86/// [`associate_constraint_with_owner_history`] there. IFC2X3 also requires
87/// `Intent`, which IFC4 made optional.
88///
89/// # Errors
90///
91/// A malformed GlobalId, a relating constraint that is not an
92/// `IfcConstraint`, an empty, duplicated or out-of-type `RelatedObjects`; a
93/// model that binds no single known release
94/// ([`ConstraintError::MultipleSchemas`],
95/// [`ConstraintError::UnsupportedSchema`]), and an IFC2X3 model. Nothing is
96/// staged on an error.
97pub fn associate_constraint(
98    tx: &mut Transaction,
99    model: &Model,
100    draft: ConstraintAssociationDraft<'_>,
101) -> ConstraintResult<EntityId> {
102    associate(tx, model, draft, None)
103}
104
105/// [`associate_constraint`] with a caller-supplied `IfcOwnerHistory`, which
106/// IFC2X3 requires on every `IfcRoot`.
107///
108/// `owner_history` must be in the model or staged earlier on `tx`, and must
109/// be an `IfcOwnerHistory`; one is never invented here (build it with
110/// `ifc-author`). In IFC4 and IFC4X3 the reference fills the optional slot.
111///
112/// # Errors
113///
114/// Those of [`associate_constraint`] except the IFC2X3 `OwnerHistory`
115/// refusal (an IFC2X3 association without `intent` is still refused with
116/// [`ConstraintError::AuthoringRequired`]), and
117/// [`ConstraintError::UnknownEntity`] for an `owner_history` that does not
118/// resolve or [`ConstraintError::AuthoringReferenceType`] for one that is
119/// not an `IfcOwnerHistory`. Nothing is staged on an error.
120pub fn associate_constraint_with_owner_history(
121    tx: &mut Transaction,
122    model: &Model,
123    draft: ConstraintAssociationDraft<'_>,
124    owner_history: EntityId,
125) -> ConstraintResult<EntityId> {
126    associate(tx, model, draft, Some(owner_history))
127}
128
129/// Stage an `IfcRelAssociatesConstraint`; `None` leaves `OwnerHistory` `$`.
130fn associate(
131    tx: &mut Transaction,
132    model: &Model,
133    draft: ConstraintAssociationDraft<'_>,
134    owner_history: Option<EntityId>,
135) -> ConstraintResult<EntityId> {
136    let layout = bind(model)?;
137    if Guid::parse(draft.global_id).is_none() {
138        return Err(ConstraintError::AuthoringInvalid {
139            entity: ASSIGNMENT,
140            attribute: "GlobalId",
141            value: draft.global_id.into(),
142        });
143    }
144    validate_target_in(
145        layout.schema(),
146        tx,
147        model,
148        draft.relating_constraint,
149        "IfcConstraint",
150    )?;
151    if draft.related_objects.is_empty() {
152        return Err(ConstraintError::AuthoringInvalid {
153            entity: ASSIGNMENT,
154            attribute: "RelatedObjects",
155            value: "empty SET [1:?]".into(),
156        });
157    }
158    let mut seen = HashSet::new();
159    for &target in draft.related_objects {
160        if !seen.insert(target) {
161            return Err(ConstraintError::AuthoringInvalid {
162                entity: ASSIGNMENT,
163                attribute: "RelatedObjects",
164                value: format!("duplicate {target}"),
165            });
166        }
167        let actual =
168            final_type(tx, model, target).ok_or(ConstraintError::UnknownEntity { id: target })?;
169        if !layout.is_definition(actual) {
170            return Err(ConstraintError::AuthoringReferenceType {
171                target,
172                expected: "IfcDefinitionSelect",
173                actual: actual.into(),
174            });
175        }
176    }
177    if let Some(owner_history) = owner_history {
178        require_owner_history(tx, model, owner_history)?;
179    }
180    let record = layout.named_record(
181        ASSIGNMENT,
182        vec![
183            ("GlobalId", text(draft.global_id)),
184            ("OwnerHistory", optional_ref(owner_history)),
185            ("Name", optional_text(draft.name)),
186            ("Description", optional_text(draft.description)),
187            ("RelatedObjects", refs(draft.related_objects)),
188            ("Intent", optional_text(draft.intent)),
189            ("RelatingConstraint", Value::Ref(draft.relating_constraint)),
190        ],
191    )?;
192    Ok(tx.create(record))
193}