ifc_lite_git/
adapter.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! From one entity's content projection to its nodes and tree entry.
6//!
7//! This is the seam between the diff engine and the object layer. It takes the
8//! projection the diff engine already defines — `DataFingerprintInput` — and
9//! produces the nodes plus the [`crate::tree::TreeEntry`] that names them.
10//!
11//! Reusing that input rather than restating it is deliberate: "what counts as
12//! an entity's content" is a long argued question with its reasoning recorded
13//! in `rust/diff`'s own docs (a type assignment is identified by name and
14//! class, never by the type's `GlobalId`; `Tag` participates for type objects
15//! only; absent and empty name bags are identical). Restating it here would
16//! fork that decision into two places, and the fork would be silent.
17//!
18//! # The key does not reach a node
19//!
20//! Every node this produces is addressed by content alone. The key arrives as a
21//! separate argument and lands only in the returned tree entry, which is the
22//! whole of the GUID-agnostic design (`crate::tree`). The tests assert it: the
23//! same projection under two different keys yields byte-identical node
24//! addresses.
25//!
26//! # What this does not do yet
27//!
28//! Geometry and relationships. `DataFingerprintInput` carries neither — a
29//! geometry hash reaches the diff engine through `EntityFingerprint`, from the
30//! mesh pass, and relationships reach it only as derived components. Both want
31//! their own adapter and are deferred rather than approximated here. The
32//! relationship adapter also has a decision to wait for: endpoints by node
33//! address drop which of two coincident duplicates the source named, and the
34//! spec set holds that equivalence policy open (`02-graph-object-model.md`
35//! §2.8).
36
37use ifc_lite_diff::fingerprint::canonical_value_string;
38use ifc_lite_diff::input::{DataFingerprintInput, PropertyEntryInput, PropertyValue};
39use ifc_lite_diff::sparse_collection::SparseCollection;
40use ifc_lite_diff::JsString;
41
42use crate::node::{Component, Field, FieldValue, Node, SetKind};
43use crate::tree::TreeEntry;
44
45/// Why an entity could not be converted.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum AdapterError {
48    /// A string in the projection is not well-formed Unicode — it holds an
49    /// unpaired surrogate, so it has no Rust `&str` form and no NFC form
50    /// either.
51    ///
52    /// Refused rather than coerced. The lossy conversion would map every
53    /// unpaired surrogate to the replacement character, collapsing strings
54    /// that are genuinely distinct into one node — which is the defect class
55    /// the diff engine's own UTF-16 work exists to prevent. A caller that
56    /// meets this has malformed input and should hear about it.
57    NotWellFormed {
58        /// Where in the projection, e.g. `pset name` or `property value`.
59        field: &'static str,
60    },
61    /// The projection carries an array hole — an absent index — and the node
62    /// encoding has no form for one.
63    ///
64    /// Refused rather than skipped, because a hole is *content*: the diff
65    /// engine counts holes in `SparseCollection` precisely so that a 2-member
66    /// set with a gap is not equal to a 2-member set without one (#8042,
67    /// #8114). Iterating only the present records would give both the same
68    /// node address, which is a silent collision in the one layer whose whole
69    /// job is that addresses separate what differs.
70    ///
71    /// Representing them is a canonical-encoding change, and index §6.1 holds
72    /// that question open, so this refuses and says why instead of inventing
73    /// an encoding here.
74    Hole {
75        /// Where in the projection, e.g. `property sets` or `property members`.
76        field: &'static str,
77        /// How many absent indices the collection carries.
78        count: usize,
79    },
80}
81
82impl std::fmt::Display for AdapterError {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        match self {
85            AdapterError::NotWellFormed { field } => write!(
86                f,
87                "{field} holds an unpaired surrogate, so it has no well-formed \
88                 Unicode form; refusing rather than collapsing it"
89            ),
90            AdapterError::Hole { field, count } => write!(
91                f,
92                "{field} carries {count} array hole(s), which are content to the \
93                 diff engine; the node encoding has no form for one, and dropping \
94                 them would collide two different projections on one address"
95            ),
96        }
97    }
98}
99
100impl std::error::Error for AdapterError {}
101
102/// One entity's conversion: the nodes it is made of, and the entry naming it.
103#[derive(Debug, Clone, PartialEq)]
104pub struct EntityNodes {
105    /// Every node produced, component nodes first and the element last, so a
106    /// caller can store them in order and never reference an absent child.
107    pub nodes: Vec<Node>,
108    /// The entry a tree carries for this entity.
109    pub entry: TreeEntry,
110}
111
112fn text(value: &JsString, field: &'static str) -> Result<String, AdapterError> {
113    value
114        .as_str()
115        .map(str::to_owned)
116        .ok_or(AdapterError::NotWellFormed { field })
117}
118
119fn optional_text(
120    value: &Option<JsString>,
121    field: &'static str,
122) -> Result<Option<String>, AdapterError> {
123    match value {
124        None => Ok(None),
125        Some(inner) => Ok(Some(text(inner, field)?)),
126    }
127}
128
129/// Lift a property value into a field value.
130///
131/// A number is **carried, not rendered** — the encoder writes its raw bits, so
132/// no text form has to be chosen here. Non-finite values are mapped to their
133/// token text instead, matching the fingerprint layer: `NaN` and the
134/// infinities have no JSON literal, and leaving them as bits would let a
135/// signalling and a quiet `NaN` differ while comparing equal.
136fn value_of(value: &PropertyValue, field: &'static str) -> Result<FieldValue, AdapterError> {
137    if matches!(value, PropertyValue::Array(_) | PropertyValue::Object(_)) { validate_value_strings(value, field)?; }
138    Ok(match value {
139        PropertyValue::Null => FieldValue::Absent,
140        PropertyValue::Bool(flag) => FieldValue::Bool(*flag),
141        PropertyValue::Number(number) if number.is_finite() => FieldValue::Number(*number),
142        _ => FieldValue::Text(text(&canonical_value_string(value).expect("text-normalized value"), field)?),
143    })
144}
145
146/// Validate source strings before JSON escaping hides malformed UTF-16.
147fn validate_value_strings(value: &PropertyValue, field: &'static str) -> Result<(), AdapterError> {
148    let mut pending = vec![value];
149    while let Some(next) = pending.pop() {
150        match next {
151            PropertyValue::String(value) if value.as_str().is_none() => return Err(AdapterError::NotWellFormed { field }),
152            PropertyValue::Array(values) => pending.extend(values),
153            PropertyValue::Object(entries) => {
154                for (key, value) in entries {
155                    if key.as_str().is_none() { return Err(AdapterError::NotWellFormed { field }); }
156                    pending.push(value);
157                }
158            }
159            _ => {}
160        }
161    }
162    Ok(())
163}
164
165/// A hole is content (see [`AdapterError::Hole`]); refuse rather than skip.
166fn refuse_holes(count: usize, field: &'static str) -> Result<(), AdapterError> {
167    if count > 0 {
168        return Err(AdapterError::Hole { field, count });
169    }
170    Ok(())
171}
172
173fn members(
174    entries: &SparseCollection<PropertyEntryInput>,
175    name_field: &'static str,
176    value_field: &'static str,
177) -> Result<Vec<Field>, AdapterError> {
178    refuse_holes(entries.holes(), "property members")?;
179    entries
180        .present()
181        .map(|entry| {
182            Ok(Field {
183                name: text(&entry.name, name_field)?,
184                value: value_of(&entry.value, value_field)?,
185            })
186        })
187        .collect()
188}
189
190/// The direct-attribute slice, as its own node.
191///
192/// Mirrors the diff engine's `attr:core` projection exactly — type, name,
193/// description, object type, predefined type, tag — because that component is
194/// a collision guard on the whole-entity hash and only guards while the two
195/// project identically.
196fn attributes_node(input: &DataFingerprintInput) -> Result<Node, AdapterError> {
197    let field = |name: &str, value: Option<String>| Field {
198        name: name.to_owned(),
199        value: value.map_or(FieldValue::Absent, FieldValue::Text),
200    };
201    Ok(Node::Set {
202        kind: SetKind::Attributes,
203        name: "core".to_owned(),
204        members: vec![
205            field("Type", Some(text(&input.ifc_type, "ifcType")?)),
206            field("Name", optional_text(&input.name, "name")?),
207            field(
208                "Description",
209                optional_text(&input.description, "description")?,
210            ),
211            field(
212                "ObjectType",
213                optional_text(&input.object_type, "objectType")?,
214            ),
215            field(
216                "PredefinedType",
217                optional_text(&input.predefined_type, "predefinedType")?,
218            ),
219            field("Tag", optional_text(&input.tag, "tag")?),
220        ],
221    })
222}
223
224fn name_bag(kind: &str, names: &[JsString], field: &'static str) -> Result<Option<Node>, AdapterError> {
225    let names = names.iter().filter(|name| !name.is_blank())
226        .map(|name| text(name, field)).collect::<Result<Vec<_>, _>>()?;
227    Ok((!names.is_empty()).then(|| Node::NameBag { kind: kind.to_owned(), names }))
228}
229
230/// Convert one entity.
231///
232/// `key` is the entity's identity in *this* version — typically its
233/// `GlobalId`. It reaches the tree entry and nothing else.
234pub fn entity_nodes(key: &str, input: &DataFingerprintInput) -> Result<EntityNodes, AdapterError> {
235    let mut nodes = Vec::new();
236    let mut components = Vec::new();
237
238    let attributes = attributes_node(input)?;
239    components.push(Component {
240        key: "attr:core".to_owned(),
241        node: attributes.address(),
242    });
243    nodes.push(attributes);
244
245    refuse_holes(input.property_sets.holes(), "property sets")?;
246    for set in input.property_sets.present() {
247        let name = text(&set.name, "pset name")?;
248        let node = Node::Set {
249            kind: SetKind::Property,
250            name: name.clone(),
251            members: members(&set.properties, "property name", "property value")?,
252        };
253        components.push(Component {
254            key: format!("pset:{name}"),
255            node: node.address(),
256        });
257        nodes.push(node);
258    }
259
260    refuse_holes(input.quantity_sets.holes(), "quantity sets")?;
261    for set in input.quantity_sets.present() {
262        let name = text(&set.name, "qset name")?;
263        let node = Node::Set {
264            kind: SetKind::Quantity,
265            name: name.clone(),
266            members: members(&set.quantities, "quantity name", "quantity value")?,
267        };
268        components.push(Component {
269            key: format!("qset:{name}"),
270            node: node.address(),
271        });
272        nodes.push(node);
273    }
274
275    refuse_holes(input.type_assignments.holes(), "type assignments")?;
276    if input.type_assignments.present().next().is_some() {
277        // Semantic identity only: class and name, never the type's own
278        // `GlobalId`. A from-scratch re-export regenerates that id, and
279        // hashing it would move the fingerprint of every typed element on
280        // exactly the re-export this design exists to see through.
281        let mut assignments = Vec::new();
282        for assignment in input.type_assignments.present() {
283            assignments.push(Field {
284                name: optional_text(&assignment.type_name, "type class")?.unwrap_or_default(),
285                value: FieldValue::Text(
286                    optional_text(&assignment.name, "type name")?.unwrap_or_default(),
287                ),
288            });
289        }
290        let node = Node::Set {
291            kind: SetKind::TypeAssignment,
292            name: String::new(),
293            members: assignments,
294        };
295        components.push(Component {
296            key: "type-assignment".to_owned(),
297            node: node.address(),
298        });
299        nodes.push(node);
300    }
301
302    // Absent and empty are one case for a name bag, so an entity that names no
303    // material carries no `material` component rather than an empty one. The
304    // diff engine makes the same choice, for the same reason: an
305    // unconditional key would have moved the fingerprint of every
306    // material-less entity the day the field shipped.
307    if let Some(node) = name_bag("material", &input.materials, "material name")? {
308        components.push(Component {
309            key: "material".to_owned(),
310            node: node.address(),
311        });
312        nodes.push(node);
313    }
314    if let Some(node) = name_bag("classification", &input.classifications, "classification")? {
315        components.push(Component {
316            key: "classification".to_owned(),
317            node: node.address(),
318        });
319        nodes.push(node);
320    }
321
322    let ifc_type = text(&input.ifc_type, "ifcType")?;
323    let element = Node::Element {
324        ifc_type: ifc_type.clone(),
325        components,
326    };
327    let entry = TreeEntry {
328        key: key.to_owned(),
329        node: element.address(),
330        ifc_type,
331    };
332    nodes.push(element);
333
334    Ok(EntityNodes { nodes, entry })
335}
336
337#[cfg(test)]
338#[path = "adapter_tests.rs"]
339mod tests;