Skip to main content

openbim_ifc_binding_core/
attribute.rs

1//! Entity attributes by name (#326).
2//!
3//! The positional operations ([`IfcModel::attribute`],
4//! [`IfcModel::set_attribute`]) read and write a slot of the STEP record.
5//! These resolve a name to its slot first, against the release the file's
6//! header declares (`ifc::attribute_slots`): `IfcTask.Status` is slot 6 in
7//! an IFC2X3 file and slot 7 in an IFC4 one, and asking an IFC4 task for
8//! IFC2X3's `TaskId` is refused, never answered from another release.
9//!
10//! - Names match ASCII case-insensitively, as EXPRESS identifiers do;
11//!   answers spell them as the schema declares (`GlobalId`).
12//! - The slots are the explicit attributes, inherited first: exactly what a
13//!   STEP record holds. A new `DERIVE` attribute has no slot and is an
14//!   unknown name. An `INVERSE` attribute has no slot either: a read
15//!   resolves it through the reverse index ([`crate::inverse`], #462) and a
16//!   write is refused with `inverse-attribute`.
17//! - An inherited attribute a subtype redeclares as derived keeps its slot,
18//!   is listed with `derived` set, reads as stored (normally `*`) and is
19//!   refused on write with `derived-attribute`.
20//!
21//! Refusals: `missing-entity`; `unsupported-schema` when the header names
22//! no release this build bundles, or the release does not declare the
23//! entity's type; `unknown-attribute`; `derived-attribute`;
24//! `inverse-attribute` for a write to an `INVERSE` name; `invalid-model`
25//! for a single-valued inverse several entities reference.
26
27use ifc::{EntityId, NamedAttributeError};
28
29use crate::record::{Field, Record, ToRecord};
30use crate::value::Tagged;
31use crate::{BindingError, IfcModel};
32
33/// One explicit attribute of an entity, as its declared release defines it.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct AttributeInfo {
36    /// The declared name, in the schema's spelling.
37    pub name: String,
38    /// Zero-based slot in the STEP record: the `index` of
39    /// [`IfcModel::attribute`].
40    pub index: usize,
41    /// The declared type, or an aggregate's innermost element type.
42    pub type_name: String,
43    /// Whether `$` is a valid value.
44    pub optional: bool,
45    /// Whether the type is a `LIST`, `SET`, `BAG` or `ARRAY`.
46    pub aggregate: bool,
47    /// Whether the slot is derived for this entity (written `*`; not
48    /// writable).
49    pub derived: bool,
50    /// The entity whose declaration introduces the attribute.
51    pub declared_by: String,
52}
53
54impl ToRecord for AttributeInfo {
55    fn to_record(&self) -> Record {
56        Record::new(
57            "AttributeInfo",
58            vec![
59                ("name", Field::Text(self.name.clone())),
60                ("index", Field::Count(self.index)),
61                ("type_name", Field::Text(self.type_name.clone())),
62                ("optional", Field::Bool(self.optional)),
63                ("aggregate", Field::Bool(self.aggregate)),
64                ("derived", Field::Bool(self.derived)),
65                ("declared_by", Field::Text(self.declared_by.clone())),
66            ],
67        )
68    }
69}
70
71pub(crate) fn refused(error: NamedAttributeError) -> BindingError {
72    match error {
73        NamedAttributeError::MissingEntity(EntityId(id)) => BindingError::MissingEntity(id),
74        NamedAttributeError::UnknownEntity { .. } => {
75            BindingError::UnsupportedSchema(error.to_string())
76        }
77        NamedAttributeError::UnknownAttribute { .. } => {
78            BindingError::UnknownAttribute(error.to_string())
79        }
80        NamedAttributeError::DerivedAttribute { .. } => {
81            BindingError::DerivedAttribute(error.to_string())
82        }
83        NamedAttributeError::InverseAttribute { .. } => {
84            BindingError::InverseAttribute(error.to_string())
85        }
86        // `NamedAttributeError` is non-exhaustive; a new refusal is
87        // reported, never dropped, until it earns a code of its own.
88        other => BindingError::InvalidModel(other.to_string()),
89    }
90}
91
92impl IfcModel {
93    /// Every explicit attribute of entity `id` in slot order, inherited
94    /// first, resolved against the declared release.
95    pub fn attribute_names(&self, id: u64) -> Result<Vec<AttributeInfo>, BindingError> {
96        let schema = self.declared_schema()?;
97        let type_name = &self.entity(id)?.type_name;
98        Ok(ifc::attribute_slots(schema, type_name)
99            .map_err(refused)?
100            .into_iter()
101            .map(|slot| AttributeInfo {
102                name: slot.name.to_owned(),
103                index: slot.index,
104                type_name: slot.type_name.to_owned(),
105                optional: slot.optional,
106                aggregate: slot.aggregate,
107                derived: slot.derived,
108                declared_by: slot.declared_by.to_owned(),
109            })
110            .collect())
111    }
112
113    /// Attribute `name` (any case) of entity `id`; `null` when the record
114    /// stops before its slot, as for [`Self::attribute`]. An `INVERSE`
115    /// name reads the entities referencing `id` through it
116    /// ([`crate::inverse`]): a `list` of `ref`s for a `SET` or `BAG`, a
117    /// `ref` or `null` for a single-valued one.
118    pub fn attribute_by_name(&self, id: u64, name: &str) -> Result<Tagged, BindingError> {
119        let schema = self.declared_schema()?;
120        match ifc::attribute_by_name(&self.inner, schema, EntityId(id), name) {
121            Ok(value) => Ok(value.map_or(Tagged::Null, Tagged::from_value)),
122            Err(NamedAttributeError::InverseAttribute { .. }) => self.inverse_by_name(id, name),
123            Err(error) => Err(refused(error)),
124        }
125    }
126
127    /// Set attribute `name` (any case) of entity `id`, returning the
128    /// previous value. The value is checked as for [`Self::set_attribute`];
129    /// every check runs before the write, so a refusal changes nothing.
130    pub fn set_attribute_by_name(
131        &mut self,
132        id: u64,
133        name: &str,
134        value: Tagged,
135    ) -> Result<Tagged, BindingError> {
136        let value = value.into_value()?;
137        let schema = self.declared_schema()?;
138        self.tracked(|this| {
139            ifc::set_attribute_by_name(&mut this.inner, schema, EntityId(id), name, value)
140                .map(|previous| Tagged::from_value(&previous))
141                .map_err(refused)
142        })
143    }
144}