ifc_control/read.rs
1//! Borrowed read views of the four controls this crate authors (#100).
2//!
3//! # Read by name in the declared release
4//!
5//! A view binds the model's declared release exactly as the
6//! `*_with_owner_history` writers do (`release.rs`): one recognised
7//! `FILE_SCHEMA` binds its table, IFC4X1, IFC4X2 and unknown tokens fail
8//! with [`ControlError::UnsupportedSchema`], several declarations with
9//! [`ControlError::MultipleSchemas`], and a header with none reads as IFC4.
10//! Every accessor then finds its slot by attribute name in that table, so
11//! an IFC2X3 `IfcPermit` (`PermitID` after `ObjectType`) is never read
12//! through IFC4's positions, where slot 6 is the permit's `PredefinedType`.
13//!
14//! From the EXPRESS sources, after the four `IfcRoot` slots and
15//! `ObjectType`:
16//!
17//! ```text
18//! IFC2X3_TC1 IfcPermit PermitID
19//! IFC2X3_TC1 IfcActionRequest RequestID
20//! IFC2X3_TC1 IfcProjectOrder ID, PredefinedType, Status
21//! IFC2X3_TC1 IfcPerformanceHistory LifeCyclePhase
22//! IFC4, IFC4X3 IfcPermit Identification, PredefinedType, Status, LongDescription
23//! IFC4, IFC4X3 IfcActionRequest Identification, PredefinedType, Status, LongDescription
24//! IFC4, IFC4X3 IfcProjectOrder Identification, PredefinedType, Status, LongDescription
25//! IFC4, IFC4X3 IfcPerformanceHistory Identification, LifeCyclePhase, PredefinedType
26//! ```
27//!
28//! [`Control::identification`] answers IFC2X3's `PermitID`, `RequestID`
29//! and `ID`, which IFC4 renamed to `Identification`. An attribute the
30//! release does not declare reads as `None`; [`Control::declares`] tells
31//! that apart from an unset value.
32//!
33//! # Checked once, then infallible
34//!
35//! A view is built only from a record that fits its release: no more
36//! attributes than declared, every required one set
37//! ([`ControlError::MissingAttribute`]), and every set one a value its
38//! declaration can hold ([`ControlError::InvalidAttribute`]), an enum
39//! token included. A record that does not fit is refused, never read as
40//! absent, so the accessors need no error of their own.
41
42use ifc_model::{Entity, EntityId, Model, Value};
43use ifc_schema::{Schema, SchemaVersion};
44
45use crate::authoring::ControlKind;
46use crate::error::{ControlError, ControlResult};
47use crate::release::{bind, conforms, release_name};
48
49const RELATION: &str = "IFCRELASSIGNSTOCONTROL";
50
51/// A borrowed, release-bound view of one `IfcPermit`, `IfcProjectOrder`,
52/// `IfcActionRequest` or `IfcPerformanceHistory`.
53#[derive(Debug, Clone, Copy)]
54pub struct Control<'m> {
55 model: &'m Model,
56 id: EntityId,
57 entity: &'m Entity,
58 kind: ControlKind,
59 release: Bound,
60 global_id: &'m str,
61}
62
63/// The table a view reads against and the release it describes.
64#[derive(Debug, Clone, Copy)]
65struct Bound {
66 schema: &'static Schema,
67 version: SchemaVersion,
68}
69
70impl Bound {
71 fn of(model: &Model) -> ControlResult<Self> {
72 let schema = bind(model)?.schema();
73 let version = schema
74 .version()
75 .ok_or_else(|| ControlError::UnsupportedSchema {
76 schema: schema.name().to_owned(),
77 })?;
78 Ok(Self { schema, version })
79 }
80
81 fn slot(self, entity: &str, attribute: &'static str) -> Option<usize> {
82 let name = release_name(Some(self.version), entity, attribute);
83 self.schema
84 .attribute_names(entity)
85 .iter()
86 .position(|declared| declared.eq_ignore_ascii_case(name))
87 }
88
89 /// The value at `attribute`'s slot, `None` when undeclared or unset.
90 fn value<'m>(
91 self,
92 entity: &str,
93 record: &'m Entity,
94 attribute: &'static str,
95 ) -> Option<&'m Value> {
96 match record.attribute(self.slot(entity, attribute)?)? {
97 Value::Null => None,
98 value => Some(value),
99 }
100 }
101
102 fn text<'m>(
103 self,
104 entity: &str,
105 record: &'m Entity,
106 attribute: &'static str,
107 ) -> Option<&'m str> {
108 self.value(entity, record, attribute)?
109 .unwrap_typed()
110 .as_text()
111 }
112
113 /// Refuse a record that does not fit `entity`'s declaration here.
114 fn check(self, entity: &'static str, id: EntityId, record: &Entity) -> ControlResult<()> {
115 let declared = self.schema.attributes(entity);
116 if record.attributes.len() > declared.len() {
117 return Err(ControlError::ExtraAttributes {
118 entity,
119 id,
120 declared: declared.len(),
121 found: record.attributes.len(),
122 schema: self.schema.name().to_owned(),
123 });
124 }
125 for (slot, attribute) in declared.into_iter().enumerate() {
126 match record.attribute(slot).unwrap_or(&Value::Null) {
127 Value::Null if !attribute.optional => {
128 return Err(ControlError::MissingAttribute {
129 entity,
130 id,
131 attribute: attribute.name.as_str(),
132 })
133 }
134 Value::Null => {}
135 value if !conforms(self.schema, attribute, value) => {
136 return Err(ControlError::InvalidAttribute {
137 entity,
138 id,
139 attribute: attribute.name.as_str(),
140 declared: attribute.type_name.clone(),
141 schema: self.schema.name().to_owned(),
142 })
143 }
144 _ => {}
145 }
146 }
147 Ok(())
148 }
149}
150
151/// Read the control `id` against `model`'s declared release.
152///
153/// # Errors
154///
155/// [`ControlError::UnsupportedSchema`] or [`ControlError::MultipleSchemas`]
156/// if the model binds no single release this crate is verified against;
157/// [`ControlError::UnknownEntity`] if `id` is absent;
158/// [`ControlError::ForeignControl`] if it is not one of the four
159/// [`ControlKind`]s; and the record refusals of the module documentation
160/// ([`ControlError::ExtraAttributes`], [`ControlError::MissingAttribute`],
161/// [`ControlError::InvalidAttribute`]).
162pub fn read_control(model: &Model, id: EntityId) -> ControlResult<Control<'_>> {
163 let release = Bound::of(model)?;
164 let entity = model.get(id).ok_or(ControlError::UnknownEntity { id })?;
165 let kind = ControlKind::from_type_name(&entity.type_name).ok_or_else(|| {
166 ControlError::ForeignControl {
167 id,
168 actual: entity.type_name.to_string(),
169 }
170 })?;
171 Control::bound(model, id, entity, kind, release)
172}
173
174/// Every control of `kind` in `model`, in file order, read against its
175/// declared release.
176///
177/// # Errors
178///
179/// Those of [`read_control`] except the identity refusals: the first
180/// record of `kind` that does not fit its release fails the whole call
181/// rather than being skipped.
182pub fn read_controls(model: &Model, kind: ControlKind) -> ControlResult<Vec<Control<'_>>> {
183 let release = Bound::of(model)?;
184 model
185 .of_type(kind.type_name())
186 .map(|(id, entity)| Control::bound(model, id, entity, kind, release))
187 .collect()
188}
189
190impl<'m> Control<'m> {
191 fn bound(
192 model: &'m Model,
193 id: EntityId,
194 entity: &'m Entity,
195 kind: ControlKind,
196 release: Bound,
197 ) -> ControlResult<Self> {
198 let name = kind.type_name();
199 release.check(name, id, entity)?;
200 // Required by every release and checked above to be text.
201 let global_id =
202 release
203 .text(name, entity, "GlobalId")
204 .ok_or(ControlError::MissingAttribute {
205 entity: name,
206 id,
207 attribute: "GlobalId",
208 })?;
209 Ok(Self {
210 model,
211 id,
212 entity,
213 kind,
214 release,
215 global_id,
216 })
217 }
218
219 fn text(&self, attribute: &'static str) -> Option<&'m str> {
220 self.release
221 .text(self.kind.type_name(), self.entity, attribute)
222 }
223
224 /// The entity id in the file.
225 #[must_use]
226 pub fn id(&self) -> EntityId {
227 self.id
228 }
229
230 /// Which of the four controls this is.
231 #[must_use]
232 pub fn kind(&self) -> ControlKind {
233 self.kind
234 }
235
236 /// The release the record is read against.
237 #[must_use]
238 pub fn release(&self) -> SchemaVersion {
239 self.release.version
240 }
241
242 /// Whether the release declares `attribute`, named by its IFC4 name as
243 /// the accessors are (`Identification` covers IFC2X3's `PermitID`,
244 /// `RequestID` and `ID`). An undeclared attribute reads as `None`; this
245 /// tells it apart from one left unset.
246 #[must_use]
247 pub fn declares(&self, attribute: &'static str) -> bool {
248 self.release
249 .slot(self.kind.type_name(), attribute)
250 .is_some()
251 }
252
253 /// `GlobalId`.
254 #[must_use]
255 pub fn global_id(&self) -> &'m str {
256 self.global_id
257 }
258
259 /// `OwnerHistory`: optional from IFC4 on, required in IFC2X3.
260 #[must_use]
261 pub fn owner_history(&self) -> Option<EntityId> {
262 match self
263 .release
264 .value(self.kind.type_name(), self.entity, "OwnerHistory")?
265 {
266 Value::Ref(id) => Some(*id),
267 _ => None,
268 }
269 }
270
271 /// `Name`.
272 #[must_use]
273 pub fn name(&self) -> Option<&'m str> {
274 self.text("Name")
275 }
276
277 /// `Description`.
278 #[must_use]
279 pub fn description(&self) -> Option<&'m str> {
280 self.text("Description")
281 }
282
283 /// `ObjectType`: the name a `USERDEFINED` predefined type stands for.
284 #[must_use]
285 pub fn object_type(&self) -> Option<&'m str> {
286 self.text("ObjectType")
287 }
288
289 /// `Identification`, or the IFC2X3 identifier IFC4 renamed to it
290 /// (`PermitID`, `RequestID`, `ID`). IFC2X3 `IfcPerformanceHistory`
291 /// declares none.
292 #[must_use]
293 pub fn identification(&self) -> Option<&'m str> {
294 self.text("Identification")
295 }
296
297 /// The `PredefinedType` token without its dots, e.g. `WORKORDER`.
298 /// IFC2X3 declares one only for `IfcProjectOrder`, where it is required.
299 #[must_use]
300 pub fn predefined_type(&self) -> Option<&'m str> {
301 match self
302 .release
303 .value(self.kind.type_name(), self.entity, "PredefinedType")?
304 {
305 Value::Enum(token) => Some(token),
306 _ => None,
307 }
308 }
309
310 /// `Status`. Declared by neither performance history, nor in IFC2X3 by
311 /// a permit or an action request.
312 #[must_use]
313 pub fn status(&self) -> Option<&'m str> {
314 self.text("Status")
315 }
316
317 /// `LongDescription`. Not declared by IFC2X3 or by a performance
318 /// history.
319 #[must_use]
320 pub fn long_description(&self) -> Option<&'m str> {
321 self.text("LongDescription")
322 }
323
324 /// `LifeCyclePhase`. Declared, and required, only by a performance
325 /// history.
326 #[must_use]
327 pub fn life_cycle_phase(&self) -> Option<&'m str> {
328 self.text("LifeCyclePhase")
329 }
330
331 /// Every `IfcRelAssignsToControl` whose `RelatingControl` is this
332 /// control, in file order.
333 ///
334 /// # Errors
335 ///
336 /// The record refusals of [`read_control`] for a relationship that
337 /// names this control but does not fit its release. Relationships
338 /// naming other controls are not inspected.
339 pub fn assignments(&self) -> ControlResult<Vec<ControlAssignment<'m>>> {
340 let release = self.release;
341 let Some(relating) = release.slot(RELATION, "RelatingControl") else {
342 return Ok(Vec::new());
343 };
344 let mut out = Vec::new();
345 for (id, entity) in self.model.of_type(RELATION) {
346 if entity.attribute(relating) != Some(&Value::Ref(self.id)) {
347 continue;
348 }
349 release.check(RELATION, id, entity)?;
350 let global_id = release.text(RELATION, entity, "GlobalId").ok_or(
351 ControlError::MissingAttribute {
352 entity: RELATION,
353 id,
354 attribute: "GlobalId",
355 },
356 )?;
357 out.push(ControlAssignment {
358 id,
359 entity,
360 release,
361 global_id,
362 });
363 }
364 Ok(out)
365 }
366}
367
368/// A borrowed view of one `IfcRelAssignsToControl` relating work to a
369/// [`Control`], checked against the same release.
370#[derive(Debug, Clone, Copy)]
371pub struct ControlAssignment<'m> {
372 id: EntityId,
373 entity: &'m Entity,
374 release: Bound,
375 global_id: &'m str,
376}
377
378impl<'m> ControlAssignment<'m> {
379 /// The relationship's entity id.
380 #[must_use]
381 pub fn id(&self) -> EntityId {
382 self.id
383 }
384
385 /// `GlobalId`.
386 #[must_use]
387 pub fn global_id(&self) -> &'m str {
388 self.global_id
389 }
390
391 /// `OwnerHistory`.
392 #[must_use]
393 pub fn owner_history(&self) -> Option<EntityId> {
394 match self.release.value(RELATION, self.entity, "OwnerHistory")? {
395 Value::Ref(id) => Some(*id),
396 _ => None,
397 }
398 }
399
400 /// `Name`.
401 #[must_use]
402 pub fn name(&self) -> Option<&'m str> {
403 self.release.text(RELATION, self.entity, "Name")
404 }
405
406 /// `Description`.
407 #[must_use]
408 pub fn description(&self) -> Option<&'m str> {
409 self.release.text(RELATION, self.entity, "Description")
410 }
411
412 /// `RelatedObjects`: the work the control governs, in stored order.
413 #[must_use]
414 pub fn related_objects(&self) -> Vec<EntityId> {
415 self.release
416 .value(RELATION, self.entity, "RelatedObjects")
417 .and_then(Value::as_list)
418 .unwrap_or_default()
419 .iter()
420 .filter_map(|item| match item {
421 Value::Ref(id) => Some(*id),
422 _ => None,
423 })
424 .collect()
425 }
426}