Skip to main content

openbim_ifc_binding_core/
classification.rs

1//! Classification references (feature `classification`, #123).
2//!
3//! The facade's classification view resolves the classifications that
4//! apply to an object: those associated with it directly, and those
5//! associated with its type object. Each crosses as one record naming the
6//! relationship, the classification it points at (a reference, a whole
7//! system, or an IFC2X3 notation), the reference's code and name, the
8//! references above it, and the system at the top. Records are read
9//! against the release the header declares, IFC2X3, IFC4 or IFC4X3; any
10//! other is refused with `unsupported-schema`.
11
12use crate::record::{Field, Record, ToRecord};
13use crate::{BindingError, IfcModel};
14
15/// One classification that applies to an object.
16#[derive(Debug, Clone, PartialEq)]
17pub struct Classification {
18    /// The `IfcRelAssociatesClassification`.
19    pub relationship: u64,
20    /// The relationship's `GlobalId`.
21    pub global_id: Option<String>,
22    /// `occurrence`: associated with the queried object; `type`: with its
23    /// type object.
24    pub source: String,
25    /// For `type`, the type object's id.
26    pub type_object: Option<u64>,
27    /// The `RelatingClassification`.
28    pub target: u64,
29    /// `reference` (an `IfcClassificationReference`), `system` (an
30    /// `IfcClassification`) or `notation` (an IFC2X3
31    /// `IfcClassificationNotation`).
32    pub kind: String,
33    /// A reference's `Identification` (IFC2X3 `ItemReference`).
34    pub identification: Option<String>,
35    /// A reference's `Name`.
36    pub name: Option<String>,
37    /// A reference's `Location`.
38    pub location: Option<String>,
39    /// A notation's facet values, in file order; empty otherwise.
40    pub notation: Vec<String>,
41    /// The references above a `reference` target, nearest first.
42    pub parents: Vec<u64>,
43    /// The system at the top: the target itself for `system`, the end of
44    /// the `ReferencedSource` chain for `reference` when it ends in one.
45    pub system: Option<ClassificationSystem>,
46}
47
48/// An `IfcClassification`.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ClassificationSystem {
51    /// Its entity id.
52    pub id: u64,
53    /// `Name`.
54    pub name: String,
55    /// `Source`: the publisher.
56    pub source: Option<String>,
57    /// `Edition`.
58    pub edition: Option<String>,
59}
60
61impl IfcModel {
62    /// The classifications that apply to `object`: its own associations,
63    /// then its type object's, in relationship id order.
64    ///
65    /// Refused with `missing-entity` for an id not in the model,
66    /// `unsupported-schema` for a release other than IFC2X3, IFC4 or
67    /// IFC4X3, `invalid-model` for malformed or ambiguous associations,
68    /// `missing-reference` for a dangling one, `budget-exceeded` for a
69    /// reference chain that cycles or runs deeper than 64, and
70    /// `feature-disabled` without the `classification` feature.
71    pub fn classifications(&self, object: u64) -> Result<Vec<Classification>, BindingError> {
72        #[cfg(feature = "classification")]
73        {
74            read::classifications(self, object)
75        }
76        #[cfg(not(feature = "classification"))]
77        {
78            let _ = object;
79            Err(BindingError::FeatureDisabled("classification"))
80        }
81    }
82}
83
84#[cfg(feature = "classification")]
85mod read {
86    use ifc::classification::{
87        classification_schema, ClassificationAssignment, ClassificationError, ClassificationView,
88    };
89    use ifc::{Budget, EntityId};
90
91    use super::{Classification, ClassificationSystem};
92    use crate::{BindingError, IfcModel};
93
94    pub(super) fn classifications(
95        model: &IfcModel,
96        object: u64,
97    ) -> Result<Vec<Classification>, BindingError> {
98        if !model.inner.contains(EntityId(object)) {
99            return Err(BindingError::MissingEntity(object));
100        }
101        classification_schema(&model.inner).map_err(error)?;
102        let view = ClassificationView::new(&model.inner);
103        let effective = view
104            .effective_classifications(EntityId(object))
105            .map_err(error)?;
106        let mut out = Vec::new();
107        for assignment in &effective.occurrence {
108            out.push(one(model, view, *assignment, "occurrence", None)?);
109        }
110        let type_object = effective.type_object.map(|EntityId(id)| id);
111        for assignment in &effective.inherited {
112            out.push(one(model, view, *assignment, "type", type_object)?);
113        }
114        Ok(out)
115    }
116
117    fn one(
118        model: &IfcModel,
119        view: ClassificationView<'_>,
120        assignment: ClassificationAssignment<'_>,
121        source: &str,
122        type_object: Option<u64>,
123    ) -> Result<Classification, BindingError> {
124        let target = assignment.relating_classification_id().map_err(error)?;
125        let mut record = Classification {
126            relationship: assignment.id().0,
127            global_id: Some(assignment.global_id().map_err(error)?.to_owned()),
128            source: source.to_owned(),
129            type_object,
130            target: target.0,
131            kind: String::new(),
132            identification: None,
133            name: None,
134            location: None,
135            notation: Vec::new(),
136            parents: Vec::new(),
137            system: None,
138        };
139        let type_name = model.type_of(target.0)?;
140        match type_name {
141            "IFCCLASSIFICATIONREFERENCE" => {
142                record.kind = "reference".to_owned();
143                let hierarchy = view
144                    .hierarchy_from(target, Budget::DEFAULT)
145                    .map_err(error)?;
146                if let Some(reference) = hierarchy.references.first() {
147                    let owned = |text: Option<&str>| text.map(str::to_owned);
148                    record.identification = owned(reference.identification().map_err(error)?);
149                    record.name = owned(reference.name().map_err(error)?);
150                    record.location = owned(reference.location().map_err(error)?);
151                }
152                record.parents = hierarchy
153                    .references
154                    .iter()
155                    .skip(1)
156                    .map(|reference| reference.id().0)
157                    .collect();
158                record.system = hierarchy.system.map(system).transpose()?;
159            }
160            "IFCCLASSIFICATION" => {
161                record.kind = "system".to_owned();
162                let found = view.systems().find(|candidate| candidate.id() == target);
163                record.system = found.map(system).transpose()?;
164            }
165            "IFCCLASSIFICATIONNOTATION" => {
166                record.kind = "notation".to_owned();
167                record.notation = view
168                    .notation_values(target)
169                    .map_err(error)?
170                    .into_iter()
171                    .map(str::to_owned)
172                    .collect();
173            }
174            other => {
175                return Err(BindingError::Unsupported(format!(
176                    "#{} classifies by {other}, which this binding does not read",
177                    assignment.id().0
178                )))
179            }
180        }
181        Ok(record)
182    }
183
184    fn system(
185        system: ifc::classification::ClassificationSystem<'_>,
186    ) -> Result<ClassificationSystem, BindingError> {
187        let owned = |text: Option<&str>| text.map(str::to_owned);
188        Ok(ClassificationSystem {
189            id: system.id().0,
190            name: system.name().map_err(error)?.to_owned(),
191            source: owned(system.source().map_err(error)?),
192            edition: owned(system.edition().map_err(error)?),
193        })
194    }
195
196    fn error(error: ClassificationError) -> BindingError {
197        use ClassificationError as E;
198        let detail = error.to_string();
199        match error {
200            E::UnsupportedSchema { schema } => BindingError::UnsupportedSchema(schema),
201            E::MultipleSchemas { .. } => BindingError::UnsupportedSchema(detail),
202            E::UnknownEntity { id } => BindingError::MissingEntity(id.0),
203            E::DanglingReference { .. } => BindingError::MissingReference(detail),
204            E::Cycle { .. } | E::BudgetExceeded { .. } => BindingError::BudgetExceeded(detail),
205            E::WrongEntityType { .. } => BindingError::WrongEntityType(detail),
206            _ => BindingError::InvalidModel(detail),
207        }
208    }
209}
210
211impl ToRecord for Classification {
212    fn to_record(&self) -> Record {
213        Record::new(
214            "Classification",
215            vec![
216                ("relationship", Field::Id(self.relationship)),
217                ("global_id", Field::text(self.global_id.clone())),
218                ("source", Field::Text(self.source.clone())),
219                ("type_object", Field::id(self.type_object)),
220                ("target", Field::Id(self.target)),
221                ("kind", Field::Text(self.kind.clone())),
222                ("identification", Field::text(self.identification.clone())),
223                ("name", Field::text(self.name.clone())),
224                ("location", Field::text(self.location.clone())),
225                (
226                    "notation",
227                    Field::List(self.notation.iter().cloned().map(Field::Text).collect()),
228                ),
229                ("parents", Field::ids(self.parents.iter().copied())),
230                ("system", Field::record(self.system.as_ref())),
231            ],
232        )
233    }
234}
235
236impl ToRecord for ClassificationSystem {
237    fn to_record(&self) -> Record {
238        Record::new(
239            "ClassificationSystem",
240            vec![
241                ("id", Field::Id(self.id)),
242                ("name", Field::Text(self.name.clone())),
243                ("source", Field::text(self.source.clone())),
244                ("edition", Field::text(self.edition.clone())),
245            ],
246        )
247    }
248}