openbim_ifc_binding_core/authoring.rs
1//! Schema-checked entity creation (#330, feature `author`).
2//!
3//! A batch of [`AuthorOp`]s runs as one checked transaction through the
4//! facade's `ifc::apply_authoring`, against the release the header
5//! declares: every operation, in order, or, when any is refused, none, and
6//! the model is unchanged. The operations: create an entity by type and
7//! named attributes; edit named attributes; remove an entity with its
8//! relationships; the builders -- the project, a spatial element
9//! aggregated under its parent, a product placed, contained and typed, a
10//! type object, a type assignment, a containment, an aggregation, a local
11//! placement and an owner history; and the shape representation operations
12//! (#481) -- assemble one from items in a context, its type checked
13//! against them or inferred, assign it to a product or (as a
14//! representation map) a type, unassign, copy and remove it; and the copy
15//! operations (#479) -- a product with what it solely owns, and an entity
16//! by an explicit share/copy policy ([`IfcModel::copy_product`],
17//! [`IfcModel::append`] from another model).
18//!
19//! An operation names an entity an earlier one produced by its handle,
20//! [`HANDLE_BASE`] plus the operation's position ([`handle`]), anywhere an id
21//! goes, attribute values included. The result reports per operation the id
22//! the produced entity received.
23//!
24//! Hosts carry an operation in their own idiom and convert it field by
25//! field, guided by [`OPS`], into the tape form [`AuthorOp::from_tagged`]
26//! reads (see the `ops` module).
27//!
28//! Refusals: `unsupported-schema` for a release this build does not bundle,
29//! or a type it does not declare; `unknown-attribute`; `derived-attribute`;
30//! `missing-attribute` for a required attribute left unset; `invalid-value`
31//! for a value of the wrong type, form or cardinality, a duplicate
32//! `GlobalId`, a seed reused for a second batch whose derived `GlobalId`s
33//! the model already holds, a malformed operation or handle, or a placement the schema
34//! cannot hold; `wrong-entity-type` for an abstract type, a type of the
35//! wrong kind for its builder, or a reference to an entity the attribute
36//! does not accept; `missing-entity` for an edited or removed entity that
37//! does not exist; `missing-reference` for a reference to one;
38//! `invalid-model` for an object given a second containment, decomposition
39//! or type, or a second `IfcProject`, a representation that already has its
40//! one use, a product definition shape other products share, or a
41//! representation not assigned where it is unassigned from;
42//! `invalid-value` also for a representation type its items do not fit,
43//! items no type fits, or a missing representation identifier;
44//! `unsupported` for a type check needing a curve dimension that cannot be
45//! derived; `still-referenced` for a removal an entity other than a
46//! relationship still needs; `feature-disabled` without the `author`
47//! feature. The message names the refused operation's
48//! position.
49
50mod copying;
51mod ops;
52mod removal;
53
54pub use copying::{AppendOptions, CopiedEntity, CopyProductOptions, CopyReport};
55pub use ops::{op_spec, FieldKind, FieldSpec, OpSpec, OPS};
56pub use removal::{KeptEntity, PurgeOptions, RemovalReport, RemoveProductOptions, RemovedEntity};
57
58use crate::record::{Field, Record, ToRecord};
59use crate::value::Tagged;
60use crate::{BindingError, IfcModel};
61
62/// The first id of the handle range: `HANDLE_BASE + i` names the entity
63/// operation `i` of a batch produced. 2^62, inside every host's signed
64/// 64-bit integer.
65pub const HANDLE_BASE: u64 = 1 << 62;
66
67// Restated so builds without the feature still have it; it is the facade's.
68#[cfg(feature = "author")]
69const _: () = assert!(HANDLE_BASE == ifc::HANDLE_BASE);
70
71/// The handle of operation `index`'s entity.
72///
73/// # Errors
74///
75/// `out-of-range` for an index past the handle range.
76pub fn handle(index: u64) -> Result<u64, BindingError> {
77 HANDLE_BASE
78 .checked_add(index)
79 .filter(|_| index < HANDLE_BASE)
80 .ok_or_else(|| BindingError::OutOfRange(format!("handle index {index}")))
81}
82
83/// One operation of a batch, read from its tape form.
84#[derive(Debug, Clone)]
85pub struct AuthorOp(Inner);
86
87#[cfg(feature = "author")]
88type Inner = ifc::AuthorOp;
89#[cfg(not(feature = "author"))]
90type Inner = std::convert::Infallible;
91
92impl AuthorOp {
93 /// Read the tape form: a `LIST` of the operation's `ENUM` name, then
94 /// field names and values (see the `ops` module).
95 ///
96 /// # Errors
97 ///
98 /// `invalid-value` for a malformed operation; `feature-disabled`
99 /// without the `author` feature.
100 pub fn from_tagged(value: &Tagged) -> Result<Self, BindingError> {
101 let fields = ops::read(value)?;
102 #[cfg(feature = "author")]
103 {
104 convert::op(fields).map(Self)
105 }
106 #[cfg(not(feature = "author"))]
107 {
108 let _ = fields;
109 Err(BindingError::FeatureDisabled("author"))
110 }
111 }
112}
113
114/// What a committed batch did.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct AuthoringResult {
117 /// Per operation, the id of the entity it produced; `None` for a
118 /// removal.
119 pub ids: Vec<Option<u64>>,
120 /// Entities created, in commit order.
121 pub created: Vec<u64>,
122 /// Entities removed.
123 pub removed: Vec<u64>,
124}
125
126impl ToRecord for AuthoringResult {
127 fn to_record(&self) -> Record {
128 Record::new(
129 "AuthoringResult",
130 vec![
131 (
132 "ids",
133 Field::List(self.ids.iter().map(|id| Field::id(*id)).collect()),
134 ),
135 ("created", Field::ids(self.created.iter().copied())),
136 ("removed", Field::ids(self.removed.iter().copied())),
137 ],
138 )
139 }
140}
141
142impl IfcModel {
143 /// Apply `ops` as one checked transaction, with `GlobalId`s drawn from
144 /// a fresh seed. See the module docs for the refusals.
145 pub fn author(&mut self, ops: Vec<AuthorOp>) -> Result<AuthoringResult, BindingError> {
146 #[cfg(feature = "author")]
147 {
148 let seed = crate::relations::fresh_seed()?;
149 self.tracked(|this| this.author_seeded(ops, seed))
150 }
151 #[cfg(not(feature = "author"))]
152 {
153 let _ = ops;
154 Err(BindingError::FeatureDisabled("author"))
155 }
156 }
157
158 /// [`Self::author`] with the seed new `GlobalId`s derive from: a host
159 /// with entropy of its own (the browser) passes it. The seed names the
160 /// batch: a fixed seed reproduces its `GlobalId`s, also after a
161 /// write/read cycle; reusing it for another batch on the same model may
162 /// be refused (`invalid-value`).
163 pub fn author_seeded(
164 &mut self,
165 ops: Vec<AuthorOp>,
166 seed: u128,
167 ) -> Result<AuthoringResult, BindingError> {
168 #[cfg(feature = "author")]
169 {
170 let schema = self.declared_schema()?;
171 let ops: Vec<ifc::AuthorOp> = ops.into_iter().map(|AuthorOp(op)| op).collect();
172 let outcome = self
173 .tracked(|this| ifc::apply_authoring(&mut this.inner, schema, &ops, seed))
174 .map_err(convert::error)?;
175 let ids = |ids: Vec<ifc::EntityId>| ids.into_iter().map(|id| id.0).collect();
176 Ok(AuthoringResult {
177 ids: outcome
178 .ids
179 .into_iter()
180 .map(|id| id.map(|id| id.0))
181 .collect(),
182 created: ids(outcome.created),
183 removed: ids(outcome.removed),
184 })
185 }
186 #[cfg(not(feature = "author"))]
187 {
188 let _ = (ops, seed);
189 Err(BindingError::FeatureDisabled("author"))
190 }
191 }
192
193 /// Create one entity of `type_name` from named attributes: a batch of
194 /// one `create`. Returns its id.
195 pub fn create_entity(
196 &mut self,
197 type_name: &str,
198 attributes: Vec<(String, Tagged)>,
199 ) -> Result<u64, BindingError> {
200 let pairs = attributes
201 .into_iter()
202 .map(|(name, value)| Tagged::List(vec![Tagged::Text(name), value]))
203 .collect();
204 let op = AuthorOp::from_tagged(&Tagged::List(vec![
205 Tagged::Enum("CREATE".into()),
206 Tagged::Text("type".into()),
207 Tagged::Text(type_name.to_owned()),
208 Tagged::Text("attributes".into()),
209 Tagged::List(pairs),
210 ]))?;
211 let result = self.tracked(|this| this.author(vec![op]))?;
212 result
213 .ids
214 .first()
215 .copied()
216 .flatten()
217 .ok_or_else(|| BindingError::InvalidModel("the batch created nothing".into()))
218 }
219
220 /// Remove entity `id` with its relationships: a batch of one `remove`.
221 /// Unlike [`Self::remove`], it leaves nothing dangling, and is refused
222 /// with `still-referenced` while an entity that is not a relationship
223 /// needs `id`.
224 pub fn remove_with_relationships(&mut self, id: u64) -> Result<(), BindingError> {
225 let op = AuthorOp::from_tagged(&Tagged::List(vec![
226 Tagged::Enum("REMOVE".into()),
227 Tagged::Text("entity".into()),
228 Tagged::Ref(id),
229 ]))?;
230 self.tracked(|this| this.author(vec![op])).map(drop)
231 }
232}
233
234#[cfg(feature = "author")]
235mod convert;