ifc-structural 0.2.1

Structural analysis model: members, connections, actions, reactions, loads.
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Selected schema-resolved structural authoring.

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

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

use crate::error::{StructuralError, StructuralResult};
use crate::AnalysisModelType;

mod action;
mod condition;
mod item;
mod load_group;
mod reaction;
mod relation;
mod stiffness;

pub use action::{stage_action, ActionDraft, ActionDraftKind, ProjectedOrTrue};
pub use condition::{
    stage_boundary_condition, stage_boundary_condition_in, stage_connection_condition,
    BoundaryConditionDraft, ConnectionConditionDraft,
};
pub use item::{
    stage_connection, stage_member, ConnectionDraft, ConnectionDraftKind, MemberDraft,
    MemberDraftKind, MemberPredefinedType, StructuralRootDraft,
};
pub use load_group::{stage_load_group, LoadGroupDraft, LoadGroupKind};
pub use reaction::{
    stage_reaction, stage_result_group, ReactionDraft, ReactionDraftKind, ResultGroupDraft,
};
pub use relation::{
    stage_activity_assignment, stage_member_connection, ActivityAssignmentDraft,
    MemberConnectionDraft, RelationshipRootDraft,
};

/// Staged fields for creating an `IfcStructuralAnalysisModel` via [`stage_analysis_model`].
#[derive(Debug, Clone)]
pub struct AnalysisModelDraft {
    /// `GlobalId`; must parse as a 22-character IFC GUID.
    pub global_id: String,
    /// `OwnerHistory`, validated against the model/transaction if present.
    pub owner_history: Option<EntityId>,
    /// `Name`.
    pub name: Option<String>,
    /// `Description`.
    pub description: Option<String>,
    /// `ObjectType`; required non-blank when `predefined_type` is `UserDefined`.
    pub object_type: Option<String>,
    /// `PredefinedType`.
    pub predefined_type: AnalysisModelType,
    /// `OrientationOf2DPlane`, an `IfcAxis2Placement3D` reference.
    pub orientation_of_2d_plane: Option<EntityId>,
    /// `LoadedBy`, `IfcStructuralLoadGroup` references; members must be unique.
    pub loaded_by: Vec<EntityId>,
    /// `HasResults`, `IfcStructuralResultGroup` references; members must be unique.
    pub result_groups: Vec<EntityId>,
    /// `SharedPlacement`; only staged when the target schema declares the attribute.
    pub shared_placement: Option<EntityId>,
}

impl Default for AnalysisModelDraft {
    fn default() -> Self {
        Self {
            global_id: "0000000000000000000000".to_owned(),
            owner_history: None,
            name: None,
            description: None,
            object_type: None,
            predefined_type: AnalysisModelType::NotDefined,
            orientation_of_2d_plane: None,
            loaded_by: Vec::new(),
            result_groups: Vec::new(),
            shared_placement: None,
        }
    }
}

/// Staged fields for creating one core `IfcStructuralLoadStatic` subtype via [`stage_load`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LoadDraft {
    /// Stages an `IfcStructuralLoadSingleForce`.
    SingleForce {
        /// `Name`.
        name: Option<String>,
        /// `ForceX`/`ForceY`/`ForceZ`.
        force: [Option<f64>; 3],
        /// `MomentX`/`MomentY`/`MomentZ`.
        moment: [Option<f64>; 3],
    },
    /// Stages an `IfcStructuralLoadLinearForce`.
    LinearForce {
        /// `Name`.
        name: Option<String>,
        /// `LinearForceX`/`LinearForceY`/`LinearForceZ`.
        force: [Option<f64>; 3],
        /// `LinearMomentX`/`LinearMomentY`/`LinearMomentZ`.
        moment: [Option<f64>; 3],
    },
    /// Stages an `IfcStructuralLoadPlanarForce`.
    PlanarForce {
        /// `Name`.
        name: Option<String>,
        /// `PlanarForceX`/`PlanarForceY`/`PlanarForceZ`.
        force: [Option<f64>; 3],
    },
    /// Stages an `IfcStructuralLoadTemperature`.
    Temperature {
        /// `Name`.
        name: Option<String>,
        /// Constant, through-Y and through-Z temperature deltas (`DeltaTConstant`/`DeltaTY`/`DeltaTZ`,
        /// or the underscored equivalents in schemas that name them that way).
        delta: [Option<f64>; 3],
    },
    /// Stages an `IfcStructuralLoadSingleForceWarping`.
    ///
    /// Extends the single force with the bimoment that restrained
    /// warping produces in an open thin-walled section.
    SingleForceWarping {
        /// `Name`.
        name: Option<String>,
        /// `ForceX`/`ForceY`/`ForceZ`.
        force: [Option<f64>; 3],
        /// `MomentX`/`MomentY`/`MomentZ`.
        moment: [Option<f64>; 3],
        /// `WarpingMoment`.
        warping_moment: Option<f64>,
    },
    /// Stages an `IfcStructuralLoadSingleDisplacement`.
    ///
    /// A prescribed movement of a point: three translations and three
    /// rotations. The distortion form below extends this with a
    /// seventh slot; this supertype stops at six.
    SingleDisplacement {
        /// `Name`.
        name: Option<String>,
        /// `DisplacementX`/`DisplacementY`/`DisplacementZ`.
        displacement: [Option<f64>; 3],
        /// `RotationalDisplacementRX`/`RY`/`RZ`.
        rotation: [Option<f64>; 3],
    },
    /// Stages an `IfcStructuralLoadSingleDisplacementDistortion`.
    ///
    /// The displacement counterpart of the warping force: a prescribed
    /// movement rather than an applied load.
    SingleDisplacementDistortion {
        /// `Name`.
        name: Option<String>,
        /// `DisplacementX`/`DisplacementY`/`DisplacementZ`.
        displacement: [Option<f64>; 3],
        /// `RotationalDisplacementRX`/`RY`/`RZ`.
        rotation: [Option<f64>; 3],
        /// `Distortion`.
        distortion: Option<f64>,
    },
    /// Stages an `IfcSurfaceReinforcementArea`.
    ///
    /// Areas are measures, not coordinates: the schema requires each
    /// to be non-negative, and requires at least one of the three to
    /// be present so the record says something.
    SurfaceReinforcementArea {
        /// `Name`.
        name: Option<String>,
        /// `SurfaceReinforcement1`, two or three entries.
        surface_1: Option<Vec<f64>>,
        /// `SurfaceReinforcement2`, two or three entries.
        surface_2: Option<Vec<f64>>,
        /// `ShearReinforcement`.
        shear: Option<f64>,
    },
    /// Stages an `IfcStructuralLoadConfiguration`.
    ///
    /// A list of loads with optional sample locations. When locations
    /// are given the schema requires one per value, so the pairing is
    /// checked here rather than left to a downstream reader.
    Configuration {
        /// `Name`.
        name: Option<String>,
        /// `Values`: the loads sampled, at least one.
        values: Vec<EntityId>,
        /// `Locations`: one coordinate pair per value, or none.
        locations: Option<Vec<[f64; 2]>>,
    },
}

/// Stage an `IfcStructuralAnalysisModel` create edit on `tx`.
///
/// Fails with [`StructuralError::InvalidGlobalId`] if `draft.global_id` is not
/// a valid GUID, [`StructuralError::SemanticViolation`] if `predefined_type`
/// is `UserDefined` without a non-blank `object_type`, and with reference
/// validation errors ([`StructuralError::DanglingReference`],
/// [`StructuralError::WrongReferenceType`], [`StructuralError::InvalidDraftValue`])
/// if any referenced entity is missing, of the wrong type, or a SET contains
/// duplicates. Returns the id staged for the new entity.
pub fn stage_analysis_model(
    tx: &mut Transaction,
    model: &Model,
    schema: &Schema,
    draft: AnalysisModelDraft,
) -> StructuralResult<EntityId> {
    if Guid::parse(&draft.global_id).is_none() {
        return Err(StructuralError::InvalidGlobalId);
    }
    if draft.predefined_type == AnalysisModelType::UserDefined
        && draft
            .object_type
            .as_deref()
            .is_none_or(|value| value.trim().is_empty())
    {
        return Err(StructuralError::SemanticViolation {
            entity: None,
            rule: "USERDEFINED analysis model requires ObjectType",
        });
    }

    validate_unique_set_members(&draft.loaded_by, "IfcStructuralAnalysisModel", "LoadedBy")?;
    validate_unique_set_members(
        &draft.result_groups,
        "IfcStructuralAnalysisModel",
        "HasResults",
    )?;
    validate_optional_ref(tx, model, schema, draft.owner_history, "IfcOwnerHistory")?;
    validate_optional_ref(
        tx,
        model,
        schema,
        draft.orientation_of_2d_plane,
        "IfcAxis2Placement3D",
    )?;
    validate_refs(
        tx,
        model,
        schema,
        &draft.loaded_by,
        "IfcStructuralLoadGroup",
    )?;
    validate_refs(
        tx,
        model,
        schema,
        &draft.result_groups,
        "IfcStructuralResultGroup",
    )?;
    validate_optional_ref(
        tx,
        model,
        schema,
        draft.shared_placement,
        "IfcObjectPlacement",
    )?;

    let mut fields = vec![
        ("GlobalId", Value::Text(Arc::from(draft.global_id))),
        ("Name", optional_text(draft.name)),
        ("Description", optional_text(draft.description)),
        ("ObjectType", optional_text(draft.object_type)),
        (
            "PredefinedType",
            Value::Enum(Arc::from(draft.predefined_type.token())),
        ),
        (
            "OrientationOf2DPlane",
            optional_ref(draft.orientation_of_2d_plane),
        ),
        ("LoadedBy", optional_refs(draft.loaded_by)),
        ("HasResults", optional_refs(draft.result_groups)),
    ];
    if let Some(owner_history) = draft.owner_history {
        fields.push(("OwnerHistory", Value::Ref(owner_history)));
    }
    if schema
        .attribute_names("IfcStructuralAnalysisModel")
        .iter()
        .any(|name| name.eq_ignore_ascii_case("SharedPlacement"))
    {
        fields.push(("SharedPlacement", optional_ref(draft.shared_placement)));
    } else if draft.shared_placement.is_some() {
        return Err(StructuralError::UnsupportedAttribute {
            entity_type: "IfcStructuralAnalysisModel".to_owned(),
            attribute: "SharedPlacement".to_owned(),
        });
    }

    let entity = build_named(schema, "IfcStructuralAnalysisModel", fields)?;
    Ok(tx.create(entity))
}

/// Stage one core `IfcStructuralLoadStatic` subtype create edit on `tx`.
///
/// Fails with [`StructuralError::InvalidDraftValue`] if any numeric component
/// is set to a non-finite value. Returns the id staged for the new entity.
pub fn stage_load(
    tx: &mut Transaction,
    schema: &Schema,
    draft: LoadDraft,
) -> StructuralResult<EntityId> {
    // Two subtypes carry list-valued attributes and WHERE rules of
    // their own, so they cannot ride the shared scalar path below.

    let (entity_type, name, attributes, values): (&str, Option<String>, &[&str], Vec<Option<f64>>) =
        match draft {
            LoadDraft::SurfaceReinforcementArea {
                name,
                surface_1,
                surface_2,
                shear,
            } => return stage_surface_reinforcement(tx, schema, name, surface_1, surface_2, shear),
            LoadDraft::Configuration {
                name,
                values,
                locations,
            } => return stage_load_configuration(tx, schema, name, values, locations),
            LoadDraft::SingleForce {
                name,
                force,
                moment,
            } => (
                "IfcStructuralLoadSingleForce",
                name,
                &[
                    "ForceX", "ForceY", "ForceZ", "MomentX", "MomentY", "MomentZ",
                ],
                force.into_iter().chain(moment).collect(),
            ),
            LoadDraft::LinearForce {
                name,
                force,
                moment,
            } => (
                "IfcStructuralLoadLinearForce",
                name,
                &[
                    "LinearForceX",
                    "LinearForceY",
                    "LinearForceZ",
                    "LinearMomentX",
                    "LinearMomentY",
                    "LinearMomentZ",
                ],
                force.into_iter().chain(moment).collect(),
            ),
            LoadDraft::PlanarForce { name, force } => (
                "IfcStructuralLoadPlanarForce",
                name,
                &["PlanarForceX", "PlanarForceY", "PlanarForceZ"],
                force.to_vec(),
            ),
            LoadDraft::Temperature { name, delta } => {
                let attributes: &[&str] = if schema
                    .attribute_names("IfcStructuralLoadTemperature")
                    .iter()
                    .any(|attribute| attribute.eq_ignore_ascii_case("DeltaTConstant"))
                {
                    &["DeltaTConstant", "DeltaTY", "DeltaTZ"]
                } else {
                    &["DeltaT_Constant", "DeltaT_Y", "DeltaT_Z"]
                };
                (
                    "IfcStructuralLoadTemperature",
                    name,
                    attributes,
                    delta.to_vec(),
                )
            }
            LoadDraft::SingleForceWarping {
                name,
                force,
                moment,
                warping_moment,
            } => (
                "IfcStructuralLoadSingleForceWarping",
                name,
                &[
                    "ForceX",
                    "ForceY",
                    "ForceZ",
                    "MomentX",
                    "MomentY",
                    "MomentZ",
                    "WarpingMoment",
                ],
                force
                    .into_iter()
                    .chain(moment)
                    .chain([warping_moment])
                    .collect(),
            ),
            LoadDraft::SingleDisplacement {
                name,
                displacement,
                rotation,
            } => (
                "IfcStructuralLoadSingleDisplacement",
                name,
                &[
                    "DisplacementX",
                    "DisplacementY",
                    "DisplacementZ",
                    "RotationalDisplacementRX",
                    "RotationalDisplacementRY",
                    "RotationalDisplacementRZ",
                ],
                displacement.into_iter().chain(rotation).collect(),
            ),
            LoadDraft::SingleDisplacementDistortion {
                name,
                displacement,
                rotation,
                distortion,
            } => (
                "IfcStructuralLoadSingleDisplacementDistortion",
                name,
                &[
                    "DisplacementX",
                    "DisplacementY",
                    "DisplacementZ",
                    "RotationalDisplacementRX",
                    "RotationalDisplacementRY",
                    "RotationalDisplacementRZ",
                    "Distortion",
                ],
                displacement
                    .into_iter()
                    .chain(rotation)
                    .chain([distortion])
                    .collect(),
            ),
        };
    for (attribute, value) in attributes.iter().zip(&values) {
        if value.is_some_and(|number| !number.is_finite()) {
            return Err(StructuralError::InvalidDraftValue {
                entity_type,
                attribute,
                expected: "finite load value or null",
            });
        }
    }
    let mut fields = vec![("Name", optional_text(name))];
    fields.extend(
        attributes
            .iter()
            .zip(values)
            .map(|(name, value)| (*name, value.map_or(Value::Null, Value::Real))),
    );
    Ok(tx.create(build_named(schema, entity_type, fields)?))
}

/// Stage an `IfcSurfaceReinforcementArea`, enforcing its four WHERE rules.
///
/// `NonnegativeArea1..3` reject a negative area; `SurfaceAndOrShearArea`
/// rejects a record that specifies nothing at all.
fn stage_surface_reinforcement(
    tx: &mut Transaction,
    schema: &Schema,
    name: Option<String>,
    surface_1: Option<Vec<f64>>,
    surface_2: Option<Vec<f64>>,
    shear: Option<f64>,
) -> StructuralResult<EntityId> {
    const ENTITY: &str = "IfcSurfaceReinforcementArea";

    if surface_1.is_none() && surface_2.is_none() && shear.is_none() {
        return Err(StructuralError::InvalidDraftValue {
            entity_type: ENTITY,
            attribute: "SurfaceReinforcement1",
            expected: "at least one reinforcement area to be specified",
        });
    }

    for (attribute, area) in [
        ("SurfaceReinforcement1", surface_1.as_ref()),
        ("SurfaceReinforcement2", surface_2.as_ref()),
    ] {
        let Some(area) = area else { continue };
        if !(2..=3).contains(&area.len()) {
            return Err(StructuralError::InvalidDraftValue {
                entity_type: ENTITY,
                attribute,
                expected: "two or three area values",
            });
        }
        if area.iter().any(|value| !value.is_finite() || *value < 0.0) {
            return Err(StructuralError::InvalidDraftValue {
                entity_type: ENTITY,
                attribute,
                expected: "finite non-negative area values",
            });
        }
    }

    if shear.is_some_and(|value| !value.is_finite() || value < 0.0) {
        return Err(StructuralError::InvalidDraftValue {
            entity_type: ENTITY,
            attribute: "ShearReinforcement",
            expected: "a finite non-negative area",
        });
    }

    let reals = |values: Option<Vec<f64>>| {
        values.map_or(Value::Null, |values| {
            Value::List(values.into_iter().map(Value::Real).collect())
        })
    };
    let fields = vec![
        ("Name", optional_text(name)),
        ("SurfaceReinforcement1", reals(surface_1)),
        ("SurfaceReinforcement2", reals(surface_2)),
        ("ShearReinforcement", shear.map_or(Value::Null, Value::Real)),
    ];
    Ok(tx.create(build_named(schema, ENTITY, fields)?))
}

/// Stage an `IfcStructuralLoadConfiguration`, enforcing `ValidListSize`.
///
/// Locations are optional, but when present the schema requires exactly
/// one per value: a mismatched pair silently misattributes every sample
/// after the first gap, so it is refused here.
fn stage_load_configuration(
    tx: &mut Transaction,
    schema: &Schema,
    name: Option<String>,
    values: Vec<EntityId>,
    locations: Option<Vec<[f64; 2]>>,
) -> StructuralResult<EntityId> {
    const ENTITY: &str = "IfcStructuralLoadConfiguration";

    if values.is_empty() {
        return Err(StructuralError::InvalidDraftValue {
            entity_type: ENTITY,
            attribute: "Values",
            expected: "at least one load",
        });
    }
    if let Some(locations) = locations.as_ref() {
        if locations.len() != values.len() {
            return Err(StructuralError::InvalidDraftValue {
                entity_type: ENTITY,
                attribute: "Locations",
                expected: "one location per value",
            });
        }
        if locations
            .iter()
            .any(|pair| pair.iter().any(|value| !value.is_finite()))
        {
            return Err(StructuralError::InvalidDraftValue {
                entity_type: ENTITY,
                attribute: "Locations",
                expected: "finite coordinates",
            });
        }
    }

    let fields = vec![
        ("Name", optional_text(name)),
        (
            "Values",
            Value::List(values.into_iter().map(Value::Ref).collect()),
        ),
        (
            "Locations",
            locations.map_or(Value::Null, |locations| {
                Value::List(
                    locations
                        .into_iter()
                        .map(|pair| Value::List(pair.into_iter().map(Value::Real).collect()))
                        .collect(),
                )
            }),
        ),
    ];
    Ok(tx.create(build_named(schema, ENTITY, fields)?))
}

pub(super) fn build_named(
    schema: &Schema,
    entity_type: &str,
    fields: Vec<(&str, Value)>,
) -> StructuralResult<Entity> {
    let attributes = schema.attributes(entity_type);
    if attributes.is_empty() {
        return Err(StructuralError::UnsupportedSchema {
            token: schema.name().to_owned(),
        });
    }
    let mut values = vec![Value::Null; attributes.len()];
    for (name, value) in fields {
        let slot = attributes
            .iter()
            .position(|attribute| attribute.name.eq_ignore_ascii_case(name))
            .ok_or_else(|| StructuralError::UnsupportedAttribute {
                entity_type: entity_type.to_owned(),
                attribute: name.to_owned(),
            })?;
        values[slot] = value;
    }
    for (attribute, value) in attributes.iter().zip(&values) {
        if !attribute.optional && matches!(value, Value::Null) {
            return Err(StructuralError::MissingRequired {
                entity_type: entity_type.to_owned(),
                attribute: attribute.name.clone(),
            });
        }
    }
    Ok(Entity::new(entity_type.to_ascii_uppercase(), values))
}

pub(super) fn optional_text(value: Option<String>) -> Value {
    value.map_or(Value::Null, |value| Value::Text(Arc::from(value)))
}

pub(super) fn optional_ref(value: Option<EntityId>) -> Value {
    value.map_or(Value::Null, Value::Ref)
}

fn optional_refs(values: Vec<EntityId>) -> Value {
    if values.is_empty() {
        Value::Null
    } else {
        Value::List(values.into_iter().map(Value::Ref).collect())
    }
}

pub(super) fn validate_optional_ref(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: Option<EntityId>,
    expected: &'static str,
) -> StructuralResult<()> {
    if let Some(target) = target {
        validate_ref(tx, model, schema, target, expected)?;
    }
    Ok(())
}

fn validate_refs(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    targets: &[EntityId],
    expected: &'static str,
) -> StructuralResult<()> {
    for target in targets {
        validate_ref(tx, model, schema, *target, expected)?;
    }
    Ok(())
}

fn validate_unique_set_members(
    targets: &[EntityId],
    entity_type: &'static str,
    attribute: &'static str,
) -> StructuralResult<()> {
    let mut unique = HashSet::with_capacity(targets.len());
    if targets.iter().all(|target| unique.insert(*target)) {
        return Ok(());
    }
    Err(StructuralError::InvalidDraftValue {
        entity_type,
        attribute,
        expected: "SET of unique entity references",
    })
}

pub(super) fn validate_ref(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: EntityId,
    expected: &'static str,
) -> StructuralResult<()> {
    validate_ref_select(tx, model, schema, target, expected, &[expected])
}

pub(super) fn validate_ref_select(
    tx: &Transaction,
    model: &Model,
    schema: &Schema,
    target: EntityId,
    expected: &'static str,
    members: &[&str],
) -> StructuralResult<()> {
    let entity = projected_entity(tx, model, target).ok_or(StructuralError::DanglingReference {
        entity: EntityId(0),
        attribute: "draft reference",
        target,
    })?;
    if !members
        .iter()
        .any(|member| schema.is_a(&entity.type_name, member))
    {
        return Err(StructuralError::WrongReferenceType {
            entity: EntityId(0),
            attribute: "draft reference",
            target,
            expected,
            actual: entity.type_name.to_string(),
        });
    }
    Ok(())
}

pub(super) fn projected_entity(
    tx: &Transaction,
    model: &Model,
    target: EntityId,
) -> Option<Entity> {
    let mut projected = model.get(target).cloned();
    for edit in tx.edits() {
        match edit {
            Edit::Create { id, entity } if *id == target => projected = Some(entity.clone()),
            Edit::SetAttribute { id, slot, value } if *id == target => {
                let entity = projected.as_mut()?;
                let attribute = entity.attributes.get_mut(*slot)?;
                *attribute = value.clone();
            }
            Edit::Retype { id, type_name } if *id == target => {
                projected.as_mut()?.type_name = type_name.clone();
            }
            Edit::Remove { id } if *id == target => projected = None,
            _ => {}
        }
    }
    projected
}