ifc_lite_geometry/representation/walk.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//! The visitor walk over a product's representation items and the
6//! `IfcMappedItem`s among them: `Items → MappingSource → MappedRepresentation →
7//! Items`, in DFS pre-order and list order.
8//!
9//! Decoder-only. The walk meshes nothing and owns no cache; what a visit does
10//! (mesh, vote, count, slice) is the caller's [`WalkVisitor`]. Mapped nesting
11//! is bounded by a depth cap AND a path-scoped visited set (AGENTS.md "Bounding
12//! walks"): the set is entered on `enter_map` and left on `leave_map`, so a
13//! source reached twice along different branches is a shared DAG node, not a
14//! cycle. The nesting is at most [`MAX_MAPPED_ITEM_DEPTH`](ifc_lite_core::MAX_MAPPED_ITEM_DEPTH)
15//! levels for geometry callers. An explicit task stack avoids native recursion;
16//! a finite expansion budget also bounds branching acyclic DAGs.
17
18use super::{product_shape, Select, ShapeError};
19use ifc_lite_core::slot::IfcRepresentationMap;
20use ifc_lite_core::{DecodedEntity, EntityDecoder};
21
22mod engine;
23
24#[cfg(test)]
25mod engine_tests;
26
27/// What an `IfcMappedItem` among the items means to the walk.
28#[derive(Clone, Copy)]
29pub enum NestedMaps {
30 /// Descend into every mapped item, in list order, to `max_depth` levels
31 /// (the mesh walks). `max_levels` independently caps mapped-level attempts
32 /// and materialized Items members across one walk. Every mapped attempt
33 /// pays, since each expands a shared source. A first read of a distinct
34 /// Items list pays only for its repeated references (#9102); every
35 /// further read pays in full. Exhaustion reports [`WalkRefusal::Budget`]
36 /// and stops globally.
37 Expand { max_depth: u32, max_levels: u32 },
38 /// A nested map ends the walk with [`WalkRefusal::TooDeep`] and nothing
39 /// after it is visited: the source is not shareable (don't-bake instancing).
40 Refuse,
41 /// Hand the `IfcMappedItem` itself to `item` and do not descend (direct
42 /// walks that delegate mapped items).
43 Leaf,
44 /// Descend into the FIRST mapped item of each level only, after the level's
45 /// own non-mapped items; never branches (the RTC vote).
46 FirstChain { max_depth: u32 },
47}
48
49/// A visitor's answer.
50#[derive(Clone, Copy, PartialEq, Eq, Debug)]
51pub enum Flow {
52 Continue,
53 /// Do not descend into this mapped source (answer to `enter_map`); an
54 /// ordinary item treats it as `Continue`.
55 SkipChildren,
56 /// End the whole walk.
57 Stop,
58}
59
60pub use super::refusal::{WalkBudgetRefusal, WalkRefusal};
61
62/// Recommended default for both independent Expand work meters.
63pub const MAX_WALK_LEVELS: u32 = 1 << 16;
64
65/// One `IfcMappedItem → IfcRepresentationMap → MappedRepresentation` level.
66#[derive(Clone)]
67pub struct MappedLevel {
68 /// The `IfcMappedItem`.
69 pub item: DecodedEntity,
70 /// Its `IfcRepresentationMap`: the key of the shared source.
71 pub map: DecodedEntity,
72 /// The map's `MappedRepresentation`.
73 pub mapped_rep: DecodedEntity,
74}
75
76impl MappedLevel {
77 /// `MappingTarget · MappingOrigin` of this level, unscaled (file units);
78 /// `None` when neither contributes. Callers scale: the router with its
79 /// `scale_transform`, the symbolic walk with its unit scale.
80 pub fn local_transform(
81 &self,
82 decoder: &mut EntityDecoder,
83 ) -> crate::Result<Option<nalgebra::Matrix4<f64>>> {
84 super::mapped_transform::mapped_item_local_transform(&self.item, &self.map, decoder)
85 }
86}
87
88/// Where a visit happens.
89pub struct WalkCtx<'a> {
90 /// The product being walked; `None` when entered at a map or mapped item.
91 pub element: Option<&'a DecodedEntity>,
92 /// The representation holding the item; `None` when entered below the top.
93 pub shape_rep: Option<&'a DecodedEntity>,
94 /// The mapped levels entered so far, outermost first; empty for a direct item.
95 pub path: &'a [MappedLevel],
96}
97
98pub trait WalkVisitor {
99 /// A representation of the product, before its items.
100 fn shape_rep(&mut self, _rep: &DecodedEntity) -> Flow {
101 Flow::Continue
102 }
103 /// A representation item. Under every policy but [`NestedMaps::Leaf`] it is
104 /// never an `IfcMappedItem`.
105 fn item(&mut self, item: &DecodedEntity, at: &WalkCtx<'_>, decoder: &mut EntityDecoder)
106 -> Flow;
107 /// The source and mapped representation resolved. Only `Continue` reads,
108 /// charges and decodes its Items, after this callback; `SkipChildren` and
109 /// `Stop` suppress those operations and their errors. The level entities
110 /// are snapshots, but child references resolve through the decoder as
111 /// mutated by this callback.
112 fn enter_map(
113 &mut self,
114 _level: &MappedLevel,
115 _at: &WalkCtx<'_>,
116 _decoder: &mut EntityDecoder,
117 ) -> Flow {
118 Flow::Continue
119 }
120 /// Pairs every `enter_map`, whatever it answered and however the level's
121 /// items ended.
122 fn leave_map(&mut self, _level: &MappedLevel) {}
123 /// A refused mapped item, or the holding representation for a root-list
124 /// budget refusal. `ctx.path` excludes the refused level. Nested Items
125 /// failures follow `enter_map` and are paired with `leave_map`; source,
126 /// depth, cycle and level-budget failures occur before entry.
127 /// Implementors must report refusal or explicitly abstain; `Ok(())` does
128 /// not certify that every item was visited.
129 fn refused(&mut self, item: &DecodedEntity, why: WalkRefusal, ctx: &WalkCtx<'_>);
130}
131
132/// The walk: which representations ([`Select`]) and how mapped items nest.
133pub struct RepresentationWalk {
134 pub select: Select,
135 pub nested: NestedMaps,
136}
137
138struct Run<'a, V> {
139 visitor: &'a mut V,
140 element: Option<&'a DecodedEntity>,
141 /// The levels entered, outermost first: also the path-scoped visited set
142 /// (at most `max_depth` entries, so a scan is the cheapest set).
143 path: smallvec::SmallVec<[MappedLevel; 1]>,
144 /// Mapped-level attempts admitted after depth/cycle checks (Expand only).
145 levels: u32,
146 /// Items members admitted before allocating/decoding a list, per occurrence.
147 items: u32,
148 /// Items lists this walk has read: a re-read pays in full (#9102).
149 seen: super::first_seen::FirstSeen,
150}
151
152impl RepresentationWalk {
153 /// Walk the selected representations of `element`.
154 pub fn product<V: WalkVisitor>(
155 &self,
156 element: &DecodedEntity,
157 decoder: &mut EntityDecoder,
158 visitor: &mut V,
159 ) -> Result<(), ShapeError> {
160 self.product_lists(
161 element,
162 decoder,
163 visitor,
164 |walk, run, rep, items, decoder| walk.items(run, Some(rep), &items, decoder),
165 )
166 }
167
168 pub(crate) fn product_admission(
169 &self,
170 element: &DecodedEntity,
171 decoder: &mut EntityDecoder,
172 visitor: &mut super::product_budget::ProductItems,
173 ) -> Result<(), ShapeError> {
174 self.product_lists(element, decoder, visitor, Self::admit_roots)
175 }
176
177 fn product_lists<V: WalkVisitor>(
178 &self,
179 element: &DecodedEntity,
180 decoder: &mut EntityDecoder,
181 visitor: &mut V,
182 mut visit: impl FnMut(
183 &Self,
184 &mut Run<'_, V>,
185 &DecodedEntity,
186 Vec<DecodedEntity>,
187 &mut EntityDecoder,
188 ) -> Flow,
189 ) -> Result<(), ShapeError> {
190 let Some(shape) = product_shape(element, decoder)? else {
191 return Ok(());
192 };
193 let mut run = Run {
194 visitor,
195 element: Some(element),
196 path: smallvec::SmallVec::new(),
197 levels: 0,
198 items: 0,
199 seen: Default::default(),
200 };
201 for rep in shape.select(element, self.select) {
202 if run.visitor.shape_rep(rep) == Flow::Stop {
203 break;
204 }
205 let Some(items) = self.root_items(&mut run, rep, decoder)? else {
206 break;
207 };
208 if visit(self, &mut run, rep, items, decoder) == Flow::Stop {
209 break;
210 }
211 }
212 Ok(())
213 }
214
215 /// Continue strict retained root admission without decoding or charging
216 /// those members twice. Skipped representations have already paid too.
217 pub(crate) fn admitted_product(
218 &self,
219 element: &DecodedEntity,
220 decoder: &mut EntityDecoder,
221 visitor: &mut super::product_budget::ProductItems,
222 roots: super::product_budget::AdmittedRoots,
223 ) {
224 let mut run = Run {
225 visitor,
226 element: Some(element),
227 path: smallvec::SmallVec::new(),
228 levels: 0,
229 items: roots.items,
230 seen: roots.seen,
231 };
232 for (rep, items) in roots.representations {
233 if run.visitor.shape_rep(&rep) == Flow::Stop
234 || self.admit_roots(&mut run, &rep, items, decoder) == Flow::Stop
235 {
236 break;
237 }
238 }
239 }
240
241 fn admit_roots(
242 &self,
243 run: &mut Run<'_, super::product_budget::ProductItems>,
244 rep: &DecodedEntity,
245 items: Vec<DecodedEntity>,
246 decoder: &mut EntityDecoder,
247 ) -> Flow {
248 if items
249 .iter()
250 .all(|item| item.ifc_type != ifc_lite_core::IfcType::IfcMappedItem)
251 {
252 run.visitor.direct_items(items)
253 } else {
254 self.items(run, Some(rep), &items, decoder)
255 }
256 }
257
258 /// Walk the items of an `IfcRepresentationMap`'s mapped representation (a
259 /// shared source, a type's map).
260 pub fn map<V: WalkVisitor>(
261 &self,
262 map: &DecodedEntity,
263 decoder: &mut EntityDecoder,
264 visitor: &mut V,
265 ) -> Result<(), ShapeError> {
266 let Some(rep) = map
267 .get(IfcRepresentationMap::MAPPED_REPRESENTATION.index())
268 .map(|a| decoder.resolve_ref(a))
269 .transpose()?
270 .flatten()
271 else {
272 return Err(ShapeError::MissingItems);
273 };
274 let mut run = Run {
275 visitor,
276 element: None,
277 path: smallvec::SmallVec::new(),
278 levels: 0,
279 items: 0,
280 seen: Default::default(),
281 };
282 let Some(items) = self.root_items(&mut run, &rep, decoder)? else {
283 return Ok(());
284 };
285 self.items(&mut run, Some(&rep), &items, decoder);
286 Ok(())
287 }
288
289 /// Walk from one `IfcMappedItem` (the item's own level is the first entered).
290 pub fn mapped_item<V: WalkVisitor>(
291 &self,
292 item: &DecodedEntity,
293 decoder: &mut EntityDecoder,
294 visitor: &mut V,
295 ) {
296 let mut run = Run {
297 visitor,
298 element: None,
299 path: smallvec::SmallVec::new(),
300 levels: 0,
301 items: 0,
302 seen: Default::default(),
303 };
304 self.execute(&mut run, engine::Task::Enter(item.clone()), decoder);
305 }
306
307 /// Private continuation for roots already admitted for this product. This
308 /// walk's actual traversal meters remain separate from product admission.
309 pub(crate) fn items_of<V: WalkVisitor>(
310 &self,
311 rep: &DecodedEntity,
312 items: &[DecodedEntity],
313 decoder: &mut EntityDecoder,
314 visitor: &mut V,
315 ) {
316 let mut run = Run {
317 visitor,
318 element: None,
319 path: smallvec::SmallVec::new(),
320 levels: 0,
321 items: 0,
322 seen: Default::default(),
323 };
324 self.items(&mut run, Some(rep), items, decoder);
325 }
326}