ifc_lite_git/
node.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//! Nodes: the vertices of the versioned IFC graph.
6//!
7//! A node exists where a change should be **attributable on its own**;
8//! everything else is a field of its owner. See
9//! `docs/architecture/ifc-git/02-graph-object-model.md` §2.2.
10//!
11//! # The one thing this does differently from node-hash v0
12//!
13//! v0 encodes the `element` node as "header, `key` (string — the entity's
14//! stable identity, typically `GlobalId`), `ifcType`, `componentCount`, then
15//! components sorted by `componentKey`". The key is **inside the hashed byte
16//! stream**, so a from-scratch re-export that regenerates every `GlobalId`
17//! changes every element address, and therefore every tree and commit — the
18//! exact case GUID-agnostic identity exists to prevent.
19//!
20//! Here the key is **not** hashed. A node address is its content; the key lives
21//! in the `tree` that points at it (a later PR on #8262). That is git's arrangement — a blob
22//! is content, a tree maps names to blobs, two identical files share one blob —
23//! and it makes a re-GUID a change of tree keys and no change of node
24//! addresses. Measured end to end by `tools/ifc-git-corpus`: 116 regenerated
25//! `GlobalId`s, 39 added and 39 deleted when paired by key, nothing at all once
26//! identity is content-derived.
27
28use crate::address::{canonical_f64, sort_key, Address, CanonicalWriter};
29
30/// Magic announcing this node format. A wire-format change mints a new one.
31pub const NODE_MAGIC: &[u8; 4] = b"IGN1";
32/// Format version within [`NODE_MAGIC`].
33pub const NODE_FORMAT_VERSION: u8 = 0;
34
35/// What a node is.
36///
37/// Tags are stable and may not be renumbered: a tag is part of the hashed
38/// header, so changing one rewrites every address of that kind.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
40#[repr(u8)]
41pub enum NodeKind {
42    /// One element's folded components. Composite.
43    Element = 1,
44    /// A named set of properties. Shared by many occurrences through
45    /// `IfcRelDefinesByProperties`, which is why it is a node: one edit must be
46    /// one change, not N.
47    PropertySet = 2,
48    /// A named set of quantities. Same argument.
49    QuantitySet = 3,
50    /// A named IFC relationship. Its identity is its endpoints, which are node
51    /// addresses — see [`Node::Relationship`] for what that drops.
52    Relationship = 4,
53    /// Tessellated or parametric geometry for one element, by tier.
54    Geometry = 5,
55    /// A resolved name bag: materials or classification references.
56    NameBag = 6,
57    /// One element's direct attributes, the `attr:core` component.
58    Attributes = 7,
59    /// An element's assigned types, by name and class.
60    TypeAssignment = 8,
61}
62
63/// What one field of a node holds.
64///
65/// A number is carried as an `f64` rather than pre-rendered text, so the
66/// encoder can write its raw bits (v0 section 3) and no rendering has to be
67/// chosen. `Absent` is distinct from `Text(String::new())` in both the
68/// encoding and the ordering.
69#[derive(Debug, Clone, PartialEq)]
70pub enum FieldValue {
71    Absent,
72    Text(String),
73    Number(f64),
74    Bool(bool),
75}
76
77impl FieldValue {
78    /// Tag byte written before the payload, so no two variants can produce
79    /// the same bytes.
80    fn tag(&self) -> u8 {
81        match self {
82            FieldValue::Absent => 0,
83            FieldValue::Text(_) => 1,
84            FieldValue::Number(_) => 2,
85            FieldValue::Bool(_) => 3,
86        }
87    }
88}
89
90/// One scalar field of a node, as a name/value pair.
91#[derive(Debug, Clone, PartialEq)]
92pub struct Field {
93    pub name: String,
94    pub value: FieldValue,
95}
96
97/// One component of an element: a key and the address of the node carrying it.
98///
99/// The key vocabulary is shared with `@ifc-lite/diff` and `@ifc-lite/merge` —
100/// `attr:core`, `pset:<Name>`, `qset:<Name>`, `type-assignment`, `material`,
101/// `classification`, `placement`, `geometry:<tier>`, `child:<name>` — so diff
102/// keys and op keys have one spelling.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Component {
105    pub key: String,
106    pub node: Address,
107}
108
109/// A node, before it is addressed.
110// No `Eq`: a `Field` can hold an `f64`, which has no total equality. Node
111// identity is its address, not structural equality, so nothing needs `Eq`.
112#[derive(Debug, Clone, PartialEq)]
113pub enum Node {
114    /// A fold of component addresses. **Carries no key** — see the module docs.
115    Element {
116        /// Exact IFC EXPRESS PascalCase class, e.g. `IfcWallStandardCase`.
117        ifc_type: String,
118        components: Vec<Component>,
119    },
120    /// A named set of scalar members.
121    Set {
122        kind: SetKind,
123        name: String,
124        members: Vec<Field>,
125    },
126    /// A relationship: a class and its roles, each role a set of targets.
127    ///
128    /// Targets are **node addresses**, which keeps the node content-only and
129    /// is also where this encoding drops information the source records: two
130    /// coincident duplicates have distinct `GlobalId`s and the source
131    /// relationship names one of them, but they share one address, so a
132    /// relationship naming either names both. Whether such duplicates are one
133    /// node or must be separated — and by what, if not a `GlobalId` — is the
134    /// spec set's **open** equivalence policy (`02-graph-object-model.md`
135    /// §2.8); node-address endpoints are the current proposal, not a decision.
136    /// A forthcoming dedup-boundary integration suite on #8262 measures this.
137    Relationship { ifc_type: String, roles: Vec<Role> },
138    /// Geometry for one tier, addressed by the digest the geometry pass already
139    /// produces rather than re-hashed here.
140    Geometry { tier: String, digest: String },
141    /// A bag of resolved names: materials, classification references.
142    NameBag { kind: String, names: Vec<String> },
143}
144
145/// Which set kind a [`Node::Set`] is.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum SetKind {
148    Property,
149    Quantity,
150    /// Direct attributes. A distinct kind rather than a reserved name, so a
151    /// property set legitimately called `core` cannot collide with it.
152    Attributes,
153    /// Assigned types, each member a class with its type name as the value.
154    TypeAssignment,
155}
156
157/// One relationship role and the nodes it points at.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct Role {
160    pub name: String,
161    pub targets: Vec<Address>,
162    /// Whether `targets`' order is content. Most IFC roles are sets — e.g.
163    /// `IfcRelAggregates.RelatedObjects` — where reference order is an
164    /// authoring artifact and must not reach the address (review on #8265:
165    /// §2.5 preserves order for a role whose attribute is declared `LIST`,
166    /// e.g. `IfcRelNests.RelatedObjects` for alignment segments, where
167    /// `[seg1, seg2]` and `[seg2, seg1]` are different content). `false`
168    /// sorts `targets` before encoding, exactly as every role did before this
169    /// field existed; `true` encodes them as given.
170    pub ordered: bool,
171}
172
173impl Node {
174    /// The kind tag written into the header.
175    pub fn kind(&self) -> NodeKind {
176        match self {
177            Node::Element { .. } => NodeKind::Element,
178            Node::Set {
179                kind: SetKind::Property,
180                ..
181            } => NodeKind::PropertySet,
182            Node::Set {
183                kind: SetKind::Quantity,
184                ..
185            } => NodeKind::QuantitySet,
186            Node::Set {
187                kind: SetKind::Attributes,
188                ..
189            } => NodeKind::Attributes,
190            Node::Set {
191                kind: SetKind::TypeAssignment,
192                ..
193            } => NodeKind::TypeAssignment,
194            Node::Relationship { .. } => NodeKind::Relationship,
195            Node::Geometry { .. } => NodeKind::Geometry,
196            Node::NameBag { .. } => NodeKind::NameBag,
197        }
198    }
199
200    /// Canonical bytes and the resulting address.
201    ///
202    /// Sets are sorted; lists whose order is content are not. Sorting is by
203    /// NFC-normalized UTF-8 bytes (see [`sort_key`]) — the same bytes the
204    /// encoder writes — so neither input order nor the producer's choice of
205    /// Unicode spelling can reach the hash.
206    pub fn encode(&self) -> (Address, Vec<u8>) {
207        let mut w = CanonicalWriter::new(NODE_MAGIC, self.kind() as u8, NODE_FORMAT_VERSION);
208        match self {
209            Node::Element {
210                ifc_type,
211                components,
212            } => {
213                w.string(ifc_type);
214                let mut sorted: Vec<&Component> = components.iter().collect();
215                // Key first, then the child address, for the same reason the
216                // set branch tie-breaks on value: `Node` is public and
217                // enforces no uniqueness, and duplicate same-named property
218                // sets are a real IFC shape (#8136). Sorting on the key alone
219                // with a stable sort let the caller's order decide the bytes.
220                //
221                // `sort_by_cached_key` rather than `sort_by`: `sort_key` NFC-
222                // normalizes and allocates, and calling it from inside a
223                // `sort_by` comparator re-derives both sides on every
224                // comparison. The cached-key form calls the key function once
225                // per component (review on #8265).
226                sorted.sort_by_cached_key(|component| (sort_key(&component.key), component.node));
227                w.u32(count(sorted.len()));
228                for component in sorted {
229                    w.string(&component.key);
230                    w.address(&component.node);
231                }
232            }
233            Node::Set {
234                kind: _,
235                name,
236                members,
237            } => {
238                w.string(name);
239                let mut sorted: Vec<&Field> = members.iter().collect();
240                // Name first, then value, so two members sharing a name are
241                // still totally ordered and input order cannot leak in. Cached
242                // key for the same reason as the element branch above.
243                sorted.sort_by_cached_key(|field| (sort_key(&field.name), value_key(&field.value)));
244                w.u32(count(sorted.len()));
245                for field in sorted {
246                    w.string(&field.name);
247                    w.u8(field.value.tag());
248                    match &field.value {
249                        FieldValue::Absent => {}
250                        FieldValue::Text(text) => {
251                            w.string(text);
252                        }
253                        FieldValue::Number(number) => {
254                            w.f64_bits(*number);
255                        }
256                        FieldValue::Bool(flag) => {
257                            w.u8(u8::from(*flag));
258                        }
259                    }
260                }
261            }
262            Node::Relationship { ifc_type, roles } => {
263                w.string(ifc_type);
264                // A role whose attribute is a set has no content order, so its
265                // targets are sorted before anything else runs — comparing
266                // unsorted targets, or re-sorting inside the role comparator,
267                // would either leak input order or re-sort on every
268                // comparison. A role whose attribute is an ordered `LIST`
269                // (`ordered: true`, e.g. `IfcRelNests.RelatedObjects`) keeps
270                // its targets exactly as given instead: that order is content
271                // (review on #8265).
272                let mut sorted: Vec<(String, bool, Vec<Address>)> = roles
273                    .iter()
274                    .map(|role| {
275                        let mut targets = role.targets.clone();
276                        if !role.ordered {
277                            targets.sort();
278                        }
279                        (role.name.clone(), role.ordered, targets)
280                    })
281                    .collect();
282                // Name, then those targets, then `ordered`, so two roles
283                // sharing a name and targets but differing only in `ordered`
284                // are still totally ordered — `Node` is public and enforces
285                // no uniqueness there, and the flag is written to the bytes,
286                // so leaving it out of the key would let input order decide
287                // them (review on #8265). Cached key for the same reason as
288                // above; the extra `targets.clone()` this needs is one Vec of
289                // `Address` per role, once, not a re-sort per comparison.
290                sorted.sort_by_cached_key(|(name, ordered, targets)| {
291                    (sort_key(name), targets.clone(), *ordered)
292                });
293                w.u32(count(sorted.len()));
294                for (name, ordered, targets) in &sorted {
295                    w.string(name);
296                    w.u8(u8::from(*ordered));
297                    w.u32(count(targets.len()));
298                    for target in targets {
299                        w.address(target);
300                    }
301                }
302            }
303            Node::Geometry { tier, digest } => {
304                w.string(tier);
305                w.string(digest);
306            }
307            Node::NameBag { kind, names } => {
308                w.string(kind);
309                // Duplicates are kept: cardinality is content. Cached key for
310                // the same reason as the branches above.
311                let mut sorted: Vec<&String> = names.iter().collect();
312                sorted.sort_by_cached_key(|name| sort_key(name));
313                w.u32(count(sorted.len()));
314                for name in sorted {
315                    w.string(name);
316                }
317            }
318        }
319        w.finish()
320    }
321
322    /// The node's content address.
323    pub fn address(&self) -> Address {
324        self.encode().0
325    }
326}
327
328/// A member count, checked rather than truncated. `as u32` on `usize::MAX`
329/// members would wrap to a wrong but valid-looking count instead of failing;
330/// no real IFC file reaches this, so the cost of checking is only ever paid
331/// once, right before the fixed-width field is written (review on #8265).
332fn count(len: usize) -> u32 {
333    u32::try_from(len).expect("more than u32::MAX members in one node's list")
334}
335
336/// Sort key for a field value, keeping the variants apart and total.
337///
338/// `Absent` sorts below every present value, including empty text. Collapsing
339/// them would make a member's absence indistinguishable from an empty value in
340/// the ordering, which the encoding is careful to distinguish in its bytes. A
341/// number sorts by the bit pattern of its canonicalized value — the same
342/// value `f64_bits` writes — so two numbers that encode identically also
343/// compare identically; sorting on the raw bits would let `-0.0` vs `0.0`, or
344/// a signed vs unsigned `NaN`, disagree with the bytes on order alone (review
345/// on #8265).
346fn value_key(value: &FieldValue) -> (u8, Vec<u8>, u64) {
347    match value {
348        FieldValue::Absent => (0, Vec::new(), 0),
349        FieldValue::Text(text) => (1, sort_key(text), 0),
350        FieldValue::Number(number) => (2, Vec::new(), canonical_f64(*number).to_bits()),
351        FieldValue::Bool(flag) => (3, Vec::new(), u64::from(*flag)),
352    }
353}
354
355#[cfg(test)]
356#[path = "node_tests.rs"]
357mod tests;