ifc-constraint 0.2.1

Bounded IFC4 metric, objective, and constraint relationships.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Transaction-staged authoring for bounded IFC4 constraints.
//!
//! The rooted `IfcRelAssociatesConstraint` lives in `association.rs`.

use std::collections::HashSet;
use std::sync::Arc;

use ifc_model::{Edit, Entity, EntityId, Model, Transaction, Value};
use ifc_schema::Schema;

use crate::types::{
    Benchmark, ConstraintGrade, LogicalOperator, MetricValueDraft, ObjectiveQualifier,
};
use crate::{ConstraintError, ConstraintResult};

const METRIC: &str = "IFCMETRIC";
const OBJECTIVE: &str = "IFCOBJECTIVE";
const RESOURCE_REL: &str = "IFCRESOURCECONSTRAINTRELATIONSHIP";

/// Common inherited `IfcConstraint` fields.
#[derive(Debug, Clone, Copy)]
pub struct ConstraintBaseDraft<'a> {
    /// Required constraint name.
    pub name: &'a str,
    /// Optional description.
    pub description: Option<&'a str>,
    /// Typed constraint grade.
    pub grade: ConstraintGrade,
    /// Optional source label.
    pub source: Option<&'a str>,
    /// Optional existing or earlier-staged actor-select target.
    pub creating_actor: Option<EntityId>,
    /// Optional IFC date-time lexical value.
    pub creation_time: Option<&'a str>,
    /// Required when `grade` is user-defined.
    pub user_defined_grade: Option<&'a str>,
}

/// Draft for one `IfcMetric`.
#[derive(Debug, Clone, Copy)]
pub struct MetricDraft<'a> {
    /// Inherited constraint fields.
    pub base: ConstraintBaseDraft<'a>,
    /// Comparison benchmark.
    pub benchmark: Benchmark,
    /// Optional source label for the data value.
    pub value_source: Option<&'a str>,
    /// Optional preserved metric SELECT value.
    pub data_value: Option<MetricValueDraft<'a>>,
    /// Optional existing or earlier-staged `IfcReference`.
    pub reference_path: Option<EntityId>,
}

/// Draft for one `IfcObjective`.
#[derive(Debug, Clone, Copy)]
pub struct ObjectiveDraft<'a> {
    /// Inherited constraint fields.
    pub base: ConstraintBaseDraft<'a>,
    /// Optional non-empty ordered constraints.
    pub benchmark_values: Option<&'a [EntityId]>,
    /// Optional logical operator.
    pub logical_aggregator: Option<LogicalOperator>,
    /// Objective purpose qualifier.
    pub qualifier: ObjectiveQualifier,
    /// Required when `qualifier` is user-defined.
    pub user_defined_qualifier: Option<&'a str>,
}

/// Draft for one resource-level constraint relationship.
#[derive(Debug, Clone, Copy)]
pub struct ResourceConstraintDraft<'a> {
    /// Optional relationship name.
    pub name: Option<&'a str>,
    /// Optional relationship description.
    pub description: Option<&'a str>,
    /// Existing or earlier-staged metric/objective.
    pub relating_constraint: EntityId,
    /// Non-empty unique resource-select targets.
    pub related_resources: &'a [EntityId],
}

/// Validate and stage one metric.
pub fn create_metric(
    tx: &mut Transaction,
    model: &Model,
    draft: MetricDraft<'_>,
) -> ConstraintResult<EntityId> {
    validate_base(tx, model, METRIC, draft.base)?;
    if let Some(path) = draft.reference_path {
        validate_target(tx, model, path, "IfcReference")?;
    }
    let data_value = match draft.data_value {
        None => Value::Null,
        Some(MetricValueDraft::Entity(target)) => {
            validate_target(tx, model, target, "IfcMetricValueSelect")?;
            Value::Ref(target)
        }
        Some(MetricValueDraft::Typed { type_name, value }) => {
            if !ifc_schema::ifc4().accepts_type("IfcMetricValueSelect", type_name) {
                return Err(ConstraintError::AuthoringInvalid {
                    entity: METRIC,
                    attribute: "DataValue",
                    value: format!("type {type_name} is outside IfcMetricValueSelect"),
                });
            }
            Value::Typed {
                type_name: Arc::from(type_name.to_ascii_uppercase()),
                value: Box::new(value.clone()),
            }
        }
    };
    Ok(tx.create(Entity::new(
        METRIC,
        vec![
            text(draft.base.name),
            optional_text(draft.base.description),
            enumeration(draft.base.grade.token()),
            optional_text(draft.base.source),
            optional_ref(draft.base.creating_actor),
            optional_text(draft.base.creation_time),
            optional_text(draft.base.user_defined_grade),
            enumeration(draft.benchmark.token()),
            optional_text(draft.value_source),
            data_value,
            optional_ref(draft.reference_path),
        ],
    )))
}

/// Validate and stage one objective.
pub fn create_objective(
    tx: &mut Transaction,
    model: &Model,
    draft: ObjectiveDraft<'_>,
) -> ConstraintResult<EntityId> {
    validate_base(tx, model, OBJECTIVE, draft.base)?;
    if draft.qualifier == ObjectiveQualifier::UserDefined && draft.user_defined_qualifier.is_none()
    {
        return Err(ConstraintError::AuthoringInvalid {
            entity: OBJECTIVE,
            attribute: "WR21",
            value: "USERDEFINED qualifier requires UserDefinedQualifier".into(),
        });
    }
    let benchmarks = match draft.benchmark_values {
        None => Value::Null,
        Some([]) => {
            return Err(ConstraintError::AuthoringInvalid {
                entity: OBJECTIVE,
                attribute: "BenchmarkValues",
                value: "empty LIST [1:?]".into(),
            });
        }
        Some(values) => {
            for &target in values {
                validate_target(tx, model, target, "IfcConstraint")?;
            }
            refs(values)
        }
    };
    Ok(tx.create(Entity::new(
        OBJECTIVE,
        vec![
            text(draft.base.name),
            optional_text(draft.base.description),
            enumeration(draft.base.grade.token()),
            optional_text(draft.base.source),
            optional_ref(draft.base.creating_actor),
            optional_text(draft.base.creation_time),
            optional_text(draft.base.user_defined_grade),
            benchmarks,
            draft
                .logical_aggregator
                .map_or(Value::Null, |value| enumeration(value.token())),
            enumeration(draft.qualifier.token()),
            optional_text(draft.user_defined_qualifier),
        ],
    )))
}

/// Validate and stage one resource-level constraint relationship.
pub fn relate_resource_constraint(
    tx: &mut Transaction,
    model: &Model,
    draft: ResourceConstraintDraft<'_>,
) -> ConstraintResult<EntityId> {
    validate_target(tx, model, draft.relating_constraint, "IfcConstraint")?;
    validate_set(
        tx,
        model,
        RESOURCE_REL,
        "RelatedResourceObjects",
        draft.related_resources,
        "IfcResourceObjectSelect",
    )?;
    Ok(tx.create(Entity::new(
        RESOURCE_REL,
        vec![
            optional_text(draft.name),
            optional_text(draft.description),
            Value::Ref(draft.relating_constraint),
            refs(draft.related_resources),
        ],
    )))
}

fn validate_base(
    tx: &Transaction,
    model: &Model,
    kind: &'static str,
    draft: ConstraintBaseDraft<'_>,
) -> ConstraintResult<()> {
    if draft.grade == ConstraintGrade::UserDefined && draft.user_defined_grade.is_none() {
        return Err(ConstraintError::AuthoringInvalid {
            entity: kind,
            attribute: "WR11",
            value: "USERDEFINED grade requires UserDefinedGrade".into(),
        });
    }
    if let Some(actor) = draft.creating_actor {
        validate_target(tx, model, actor, "IfcActorSelect")?;
    }
    Ok(())
}

fn validate_set(
    tx: &Transaction,
    model: &Model,
    kind: &'static str,
    attribute: &'static str,
    targets: &[EntityId],
    expected: &'static str,
) -> ConstraintResult<()> {
    if targets.is_empty() {
        return Err(ConstraintError::AuthoringInvalid {
            entity: kind,
            attribute,
            value: "empty SET [1:?]".into(),
        });
    }
    let mut seen = HashSet::new();
    for &target in targets {
        if !seen.insert(target) {
            return Err(ConstraintError::AuthoringInvalid {
                entity: kind,
                attribute,
                value: format!("duplicate {target}"),
            });
        }
        validate_target(tx, model, target, expected)?;
    }
    Ok(())
}

/// Draft for one `IfcReference`: a path into another entity's attributes.
#[derive(Debug, Clone, Copy)]
pub struct ReferenceDraft<'a> {
    /// `TypeIdentifier`, the referenced entity's type name.
    pub type_identifier: Option<&'a str>,
    /// `AttributeIdentifier`, the attribute being addressed.
    pub attribute_identifier: Option<&'a str>,
    /// `InstanceName`, naming the addressed instance.
    pub instance_name: Option<&'a str>,
    /// `ListPositions`, 1-based indices into list-valued attributes.
    pub list_positions: &'a [i64],
    /// `InnerReference`, the next step along the path.
    pub inner_reference: Option<EntityId>,
}

/// Stage an `IfcReference`.
///
/// A reference is a path expression: it names a type, an attribute, and
/// optionally positions within a list, chaining through `InnerReference`
/// to address something nested. Every slot is OPTIONAL, so the schema
/// permits a reference that addresses nothing; that is a silently useless
/// record, so at least one slot must be set here.
///
/// `ListPositions` is `LIST [1:?] OF IfcInteger` and the positions are
/// 1-based: an empty list fails the bound, and a zero or negative index
/// addresses no element. Both are refused rather than written.
///
/// # Errors
///
/// Refuses a fully empty draft, an empty or non-positive `ListPositions`,
/// and an `inner_reference` that is not itself an `IfcReference`.
pub fn create_reference(
    tx: &mut Transaction,
    model: &Model,
    draft: ReferenceDraft<'_>,
) -> ConstraintResult<EntityId> {
    const ENTITY: &str = "IfcReference";
    let empty = draft.type_identifier.is_none()
        && draft.attribute_identifier.is_none()
        && draft.instance_name.is_none()
        && draft.list_positions.is_empty()
        && draft.inner_reference.is_none();
    if empty {
        return Err(ConstraintError::AuthoringInvalid {
            entity: ENTITY,
            attribute: "TypeIdentifier",
            value: "a reference with every slot unset addresses nothing".to_owned(),
        });
    }
    for position in draft.list_positions {
        if *position < 1 {
            return Err(ConstraintError::AuthoringInvalid {
                entity: ENTITY,
                attribute: "ListPositions",
                value: format!("{position} is not a 1-based list index"),
            });
        }
    }
    if let Some(inner) = draft.inner_reference {
        validate_target(tx, model, inner, ENTITY)?;
    }

    let positions = if draft.list_positions.is_empty() {
        // LIST [1:?]: absent stays null rather than becoming an
        // empty list, which would satisfy the type and break the bound.
        Value::Null
    } else {
        Value::List(
            draft
                .list_positions
                .iter()
                .copied()
                .map(Value::Integer)
                .collect(),
        )
    };
    Ok(tx.create(Entity::new(
        "IFCREFERENCE",
        vec![
            optional_text(draft.type_identifier),
            optional_text(draft.attribute_identifier),
            optional_text(draft.instance_name),
            positions,
            draft.inner_reference.map_or(Value::Null, Value::Ref),
        ],
    )))
}

fn validate_target(
    tx: &Transaction,
    model: &Model,
    target: EntityId,
    expected: &'static str,
) -> ConstraintResult<()> {
    validate_target_in(ifc_schema::ifc4(), tx, model, target, expected)
}

/// [`validate_target`] against `schema` instead of the IFC4 table.
pub(crate) fn validate_target_in(
    schema: &Schema,
    tx: &Transaction,
    model: &Model,
    target: EntityId,
    expected: &'static str,
) -> ConstraintResult<()> {
    let actual =
        final_type(tx, model, target).ok_or(ConstraintError::UnknownEntity { id: target })?;
    if schema.accepts_type(expected, actual) {
        Ok(())
    } else {
        Err(ConstraintError::AuthoringReferenceType {
            target,
            expected,
            actual: actual.into(),
        })
    }
}

pub(crate) fn final_type<'a>(
    tx: &'a Transaction,
    model: &'a Model,
    id: EntityId,
) -> Option<&'a str> {
    for edit in tx.edits().iter().rev() {
        match edit {
            Edit::Create {
                id: edit_id,
                entity,
            } if *edit_id == id => return Some(&entity.type_name),
            Edit::Remove { id: edit_id } if *edit_id == id => return None,
            Edit::Retype {
                id: edit_id,
                type_name,
            } if *edit_id == id => return Some(type_name),
            _ => {}
        }
    }
    model.get(id).map(|entity| entity.type_name.as_ref())
}

pub(crate) fn text(value: &str) -> Value {
    Value::Text(Arc::from(value))
}
pub(crate) fn optional_text(value: Option<&str>) -> Value {
    value.map_or(Value::Null, text)
}
pub(crate) fn optional_ref(value: Option<EntityId>) -> Value {
    value.map_or(Value::Null, Value::Ref)
}
fn enumeration(value: &str) -> Value {
    Value::Enum(Arc::from(value))
}
pub(crate) fn refs(values: &[EntityId]) -> Value {
    Value::List(values.iter().copied().map(Value::Ref).collect())
}