Repository navigation
Expand file tree
/
Copy pathwalker.rs
More file actions
2557 lines (2444 loc) · 102 KB
/
Copy pathwalker.rs
File metadata and controls
2557 lines (2444 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The element walk: the schema-directed instance reader for `ADocument`
//! and every element a file yields.
//!
//! Reads the root `ADocument` class's instance data from
//! `Global/Latest` using the 100 %-classified schema produced by
//! `formats::parse_schema`. Current status: **partial**. Validated
//! cross-version on Revit 2024–2026, where the walker reads all 13
//! declared fields with 8 of 13 producing clean values and the last
//! three ElementIds (`m_ownerFamilyId`, `m_ownerFamilyContainingGroupId`,
//! `m_devBranchInfo`) matching byte-for-byte across those three
//! releases — strong cross-version validation of both the decoder
//! and the entry-point detector.
//!
//! Fields 2–5 and the 2016–2023 stream layout still need work. See
//! `docs/format-reconnaissance.md` §Q6.5 for the full decode
//! state + open questions.
//!
//! Wire encoding (observed as of v0.1.2):
//!
//! | FieldType | Wire shape |
//! |---|---|
//! | `Pointer { .. }` | 8 bytes `[u32 slot_a][u32 slot_b]` — `00 00 00 00 00 00 00 00` means NULL; `0xff…f` also NULL-like |
//! | `ElementId` / `ElementIdRef` | 8 bytes `[u32 tag_or_zero][u32 id]` — `id` is the runtime element identifier |
//! | `Container { kind: 0x0e, .. }` | 2-column — `[u32 count][count × 6-byte [u16 id][u32 mask]][u32 count2][count2 × 6-byte records]` |
//! | Other `FieldType` variants | not observed in current ADocument fixtures; retained as raw bytes until a validated wire shape is available |
use crate::control::{PROGRESS_BYTE_INTERVAL, Stage, WalkerControl};
use crate::le_bytes;
use crate::{Error, Result, RevitFile, compression, formats, streams};
/// One field's value as read by the walker.
///
/// Matches the [`formats::FieldType`] classifier's output space. The
/// walker decodes each declared field to one of these variants based
/// on the field's schema-declared type; unrecognised or unexercised
/// wire shapes fall through to [`InstanceField::Bytes`] so downstream
/// tooling can still inspect raw bytes.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum InstanceField {
/// `[u32 a][u32 b]` pointer slot. Both-zero means NULL; both-ones
/// also sometimes seen as a NULL sentinel.
Pointer { raw: [u32; 2] },
/// Typed element reference. `tag` is 0 for references that don't
/// carry a class-tag on the wire; `id` is the runtime ElementId.
ElementId { tag: u32, id: u32 },
/// Reference container, 2-column layout: `col_a` is the primary
/// id list, `col_b` is typically masks or a parallel id stream.
RefContainer { col_a: Vec<u16>, col_b: Vec<u16> },
/// Fixed-size integer primitive (u8 for kind 0x02, i16 for 0x03,
/// u32 / i32 / u64 / i64). `signed` is `true` for signed variants; `value` is the
/// widened 64-bit representation.
Integer { value: i64, signed: bool, size: u8 },
/// 32-bit or 64-bit IEEE 754 floating point.
Float { value: f64, size: u8 },
/// 1-byte boolean (stored padded on the wire; decoded as bool).
Bool(bool),
/// 16-byte GUID / UUID.
Guid([u8; 16]),
/// UTF-16LE length-prefixed string (both schema-encoded forms).
String(String),
/// Generic vector of homogeneous `InstanceField` values. Wire:
/// `[u32 count][count × element]` where element layout depends on
/// the vector's element FieldType.
Vector(Vec<InstanceField>),
/// Unused / unexercised paths return the raw bytes consumed.
Bytes(Vec<u8>),
}
/// Handle/ID index into a decompressed `Global/Latest` stream.
///
/// Built by the walker from the element table. Maps each
/// `ElementId` to the byte offset in the stream where that element's
/// record begins. Used by per-class decoders to dereference pointers
/// across the object graph.
#[derive(Debug, Clone, Default)]
pub struct HandleIndex {
map: std::collections::BTreeMap<u32, usize>,
}
impl HandleIndex {
/// Construct an empty index. Populated by walker implementations
/// (see `Self::insert`).
pub fn new() -> Self {
Self {
map: std::collections::BTreeMap::new(),
}
}
/// Record that `element_id` lives at byte `offset` in the
/// decompressed stream.
pub fn insert(&mut self, element_id: u32, offset: usize) {
self.map.insert(element_id, offset);
}
/// Resolve an ElementId to its byte offset, if known.
pub fn get(&self, element_id: u32) -> Option<usize> {
self.map.get(&element_id).copied()
}
/// Number of indexed elements.
pub fn len(&self) -> usize {
self.map.len()
}
/// True when the index has no entries.
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Iterate over (ElementId, offset) pairs in sorted ElementId
/// order.
pub fn iter(&self) -> impl Iterator<Item = (u32, usize)> + '_ {
self.map.iter().map(|(k, v)| (*k, *v))
}
}
/// Trait implemented by each per-class decoder. Converts a byte slice
/// (positioned at the start of the class's instance data) into a
/// typed `Element` of the decoder's output type, consuming schema
/// knowledge + the handle index for cross-references.
///
/// Implementations for concrete Revit classes (Wall, Floor, Door,
/// etc.) live in `src/elements/*.rs` and follow the
/// `EXTENDING_LAYER_5B.md` template. The trait gives the walker
/// generic dispatch without needing to know every class at compile
/// time.
pub trait ElementDecoder: Sync + Send {
/// The class's name as it appears in `Formats/Latest` (e.g.
/// `"Wall"`, `"Floor"`, `"Level"`, `"Door"`). Must match the
/// `ClassEntry.name` the schema parser produces.
fn class_name(&self) -> &'static str;
/// Decode a single instance of this class from its byte range.
/// `schema` is the `ClassEntry` from `parse_schema`; `bytes`
/// starts at the class's instance data; `index` resolves
/// cross-references.
fn decode(
&self,
bytes: &[u8],
schema: &formats::ClassEntry,
index: &HandleIndex,
) -> Result<DecodedElement>;
/// [`Self::decode`] under the caller's walker caps (#852). The default
/// decodes `bytes` cut to `limits.max_per_record_decode_bytes`; a
/// decoder that walks the generic decoder overrides it to pass
/// `limits` on, so a cap above the default applies too.
fn decode_with_limits(
&self,
bytes: &[u8],
schema: &formats::ClassEntry,
index: &HandleIndex,
limits: WalkerLimits,
) -> Result<DecodedElement> {
let end = limits.max_per_record_decode_bytes.min(bytes.len());
self.decode(&bytes[..end], schema, index)
}
}
/// Mirror of [`ElementDecoder`] for the write path. A per-
/// class encoder takes a `DecodedElement` (typically produced by the
/// decoder, possibly with a field or two mutated via the `writer`
/// module's patch API) and a schema entry, and emits the
/// instance-data bytes.
///
/// The default implementation [`encode_instance`] is schema-driven
/// and works for any class whose fields all map to a canonical
/// `FieldType` pattern — the same space the generic decoder covers.
/// Per-class encoders override [`Self::encode`] when a class needs
/// out-of-schema framing (ADocument's preamble, Container 2-column
/// layout, etc.).
///
/// ```
/// use rvt::walker::{ElementEncoder, DecodedElement, encode_instance};
/// use rvt::formats::ClassEntry;
///
/// struct WallEncoder;
/// impl ElementEncoder for WallEncoder {
/// fn class_name(&self) -> &'static str { "Wall" }
/// // default encode() uses encode_instance() — no override needed
/// }
/// ```
// Tracker: WRT-03.
pub trait ElementEncoder: Sync + Send {
/// The class's name as it appears in `Formats/Latest`. Must
/// match the paired `ElementDecoder::class_name` for round-trip.
fn class_name(&self) -> &'static str;
/// Serialise a single instance of this class back to its wire
/// bytes. The default implementation walks `decoded.fields` in
/// schema order and calls [`write_field_by_type`] for each,
/// producing a byte sequence identical to what the reader
/// originally consumed.
///
/// Field count mismatch between `decoded.fields` and
/// `schema.fields` is tolerated: the encoder pairs fields by
/// schema index, so extra decoded fields are ignored and
/// missing ones emit nothing (consistent with the reader's
/// best-effort philosophy).
fn encode(&self, decoded: &DecodedElement, schema: &formats::ClassEntry) -> Vec<u8> {
encode_instance(decoded, schema)
}
}
/// Inverse of [`read_field_by_type`]. Serialises a single
/// `InstanceField` value into `out` using the declared
/// [`formats::FieldType`] to pick the wire layout.
///
/// Mismatches between `value` and `ty` (e.g. `value = String` but
/// `ty = Primitive`) fall back to emitting whatever bytes the
/// variant already carries when the decoder encountered an
/// untypable field — [`InstanceField::Bytes`] is written verbatim,
/// other mismatches emit an empty slice rather than panicking.
/// The write path stays round-trip-safe for every field the
/// decoder understood cleanly.
// Tracker: WRT-03.
pub fn write_field_by_type(value: &InstanceField, ty: &formats::FieldType, out: &mut Vec<u8>) {
use formats::FieldType;
// Catch-all: if the reader fell back to Bytes because the
// FieldType / layout wasn't covered, re-emit the bytes verbatim
// regardless of `ty`. This makes any round-trip
// decode→encode→decode stable even for unknown fields.
if let InstanceField::Bytes(raw) = value {
out.extend_from_slice(raw);
return;
}
match (ty, value) {
(FieldType::Primitive { kind, size }, v) => {
let n = *size as usize;
match (*kind, *size, v) {
(0x01, _, InstanceField::Bool(b)) => {
out.push(if *b { 1 } else { 0 });
// Primitive bool on disk is always one byte — even
// when schema's declared size is greater (padding).
for _ in 1..n {
out.push(0);
}
}
(0x02, 1, InstanceField::Integer { value, .. }) => {
out.push(*value as u8);
}
(0x03, 2, InstanceField::Integer { value, .. }) => {
out.extend_from_slice(&(*value as i16).to_le_bytes());
}
(0x04, 4, InstanceField::Integer { value, .. })
| (0x05, 4, InstanceField::Integer { value, .. }) => {
out.extend_from_slice(&(*value as u32).to_le_bytes());
}
(0x06, 4, InstanceField::Float { value, .. }) => {
out.extend_from_slice(&(*value as f32).to_le_bytes());
}
(0x07, 8, InstanceField::Float { value, .. }) => {
out.extend_from_slice(&value.to_le_bytes());
}
(0x0b, 8, InstanceField::Integer { value, .. }) => {
out.extend_from_slice(&value.to_le_bytes());
}
_ => {} // shape mismatch — nothing to emit.
}
}
(FieldType::String, InstanceField::String(s)) => {
// UTF-16LE length-prefixed. Char count is (u32) number of
// UTF-16 code units, then that many × 2 bytes.
let utf16: Vec<u16> = s.encode_utf16().collect();
out.extend_from_slice(&(utf16.len() as u32).to_le_bytes());
for code in utf16 {
out.extend_from_slice(&code.to_le_bytes());
}
}
(FieldType::Guid, InstanceField::Guid(g)) => {
out.extend_from_slice(g);
}
(
FieldType::ElementId | FieldType::ElementIdRef { .. },
InstanceField::ElementId { tag, id },
) => {
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&id.to_le_bytes());
}
(FieldType::Pointer { .. }, InstanceField::Pointer { raw }) => {
out.extend_from_slice(&raw[0].to_le_bytes());
out.extend_from_slice(&raw[1].to_le_bytes());
}
(FieldType::Vector { kind, .. }, InstanceField::Vector(items)) => {
out.extend_from_slice(&(items.len() as u32).to_le_bytes());
for item in items {
match (*kind, item) {
(0x01, InstanceField::Bool(b)) => out.push(if *b { 1 } else { 0 }),
(0x04, InstanceField::Integer { value, .. })
| (0x05, InstanceField::Integer { value, .. }) => {
out.extend_from_slice(&(*value as u32).to_le_bytes());
}
(0x07, InstanceField::Float { value, .. }) => {
out.extend_from_slice(&value.to_le_bytes());
}
(0x0b, InstanceField::Integer { value, .. }) => {
out.extend_from_slice(&value.to_le_bytes());
}
// An item the reader kept as bytes (an unknown kind, or a
// number that is not physical) goes back as it came.
(_, InstanceField::Bytes(raw)) => out.extend_from_slice(raw),
(0x0d, InstanceField::Vector(point)) => {
// point = 3 × f64 — walk up to three floats
// (shape was emitted by the reader).
for p in point.iter().take(3) {
if let InstanceField::Float { value, .. } = p {
out.extend_from_slice(&value.to_le_bytes());
} else {
// Point component missing; emit zero
// to preserve the 24-byte stride.
out.extend_from_slice(&0.0_f64.to_le_bytes());
}
}
}
_ => {}
}
}
}
(FieldType::Container { kind, .. }, InstanceField::Vector(_))
if matches!(*kind, 0x01 | 0x02 | 0x04 | 0x05 | 0x07 | 0x0b | 0x0d) =>
{
// Tracker: L5B-09.5.
// A scalar-base Container round-trips through the
// same `[u32 count][count × element]` wire layout as
// Vector (reader delegates in the opposite direction).
// Recurse with a synthesised Vector FieldType so the
// reader's decoded Vector of items serialises back to
// the same bytes. Reference Containers (kind=0x0e) still
// need the explicit ADocument-side `write_adocument_field`
// path (2-column layout).
let fake_vec = FieldType::Vector {
kind: *kind,
body: Vec::new(),
};
write_field_by_type(value, &fake_vec, out);
}
(FieldType::Container { .. } | FieldType::Unknown { .. }, _) => {
// Decoder uses Bytes fallback for these — the Bytes arm
// at the top caught the Bytes case; shape-mismatched
// values (typed value but container/unknown FieldType)
// are dropped. The writer stays safe — no bytes emitted
// for ambiguous pairings.
}
// All other type+value mismatches: emit nothing.
_ => {}
}
}
/// Encode an `ADocument`-level field. Mirrors
/// `read_field` — handles `Pointer`, `ElementId` / `ElementIdRef`
/// (8-byte `tag,id` layout), and `Container { kind: 0x0e, .. }`
/// (2-column layout via [`encode_ref_container`]). All other
/// field types route through [`write_field_by_type`], which covers
/// the general wire shape.
///
/// Use this when encoding ADocument instance bytes back into
/// Global/Latest, because the ADocument reader uses `read_field`
/// rather than the generic `read_field_by_type`.
// Tracker: WRT-02.
pub fn write_adocument_field(value: &InstanceField, ft: &formats::FieldType, out: &mut Vec<u8>) {
match (ft, value) {
(formats::FieldType::Pointer { .. }, InstanceField::Pointer { raw }) => {
out.extend_from_slice(&raw[0].to_le_bytes());
out.extend_from_slice(&raw[1].to_le_bytes());
}
(
formats::FieldType::ElementId | formats::FieldType::ElementIdRef { .. },
InstanceField::ElementId { tag, id },
) => {
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&id.to_le_bytes());
}
(
formats::FieldType::Container { kind: 0x0e, .. },
InstanceField::RefContainer { col_a, col_b },
) => {
out.extend_from_slice(&encode_ref_container(col_a, col_b));
}
// Any Bytes fallback is emitted verbatim regardless of ft.
(_, InstanceField::Bytes(raw)) => {
out.extend_from_slice(raw);
}
// Everything else delegates to the generic writer.
_ => write_field_by_type(value, ft, out),
}
}
/// Encode a 2-column reference container — the inverse of
/// `read_field`'s `Container { kind: 0x0e, .. }` path. The on-
/// disk layout for this field shape is:
///
/// ```text
/// [u32 LE count_a] [count_a × (u16 LE id + 4 bytes padding)]
/// [u32 LE count_b] [count_b × (u16 LE id + 4 bytes padding)]
/// ```
///
/// When `col_a.len() != col_b.len()` the reader falls back to a
/// single-column shape. This writer always emits the full two-
/// column form — if callers want the single-column fallback, they
/// should pass an empty `col_b` (which emits an empty column with
/// `count_b = 0`, matching the on-disk shape for a missing pair).
///
/// Per-element padding is zero-filled — the reader ignores those
/// four bytes, so the value is write-time free.
// Tracker: WRT-09.
pub fn encode_ref_container(col_a: &[u16], col_b: &[u16]) -> Vec<u8> {
const ELEM_SIZE: usize = 6;
let count_a = col_a.len();
let count_b = col_b.len();
let mut out = Vec::with_capacity(2 * (4 + ELEM_SIZE * count_a.max(count_b)));
out.extend_from_slice(&(count_a as u32).to_le_bytes());
for id in col_a {
out.extend_from_slice(&id.to_le_bytes());
out.extend_from_slice(&[0u8; 4]); // padding
}
out.extend_from_slice(&(count_b as u32).to_le_bytes());
for id in col_b {
out.extend_from_slice(&id.to_le_bytes());
out.extend_from_slice(&[0u8; 4]); // padding
}
out
}
/// Serialise a whole `DecodedElement` back to its wire bytes
///. Inverse of [`decode_instance`]. Walks the schema's
/// declared fields in order and, for each, calls
/// [`write_field_by_type`] with the matching `InstanceField` from
/// `decoded.fields`.
///
/// Round-trip: `encode_instance(&decoded_instance(b, 0, schema),
/// schema) == b` for any `b` where the decoder produces a
/// non-fallback `InstanceField` for every schema field. Callers
/// should sanity-check `Completeness::typed_ratio()` before
/// relying on round-trip equality.
// Tracker: WRT-03.
pub fn encode_instance(decoded: &DecodedElement, schema: &formats::ClassEntry) -> Vec<u8> {
let mut out = Vec::with_capacity(decoded.byte_range.len());
for (idx, schema_field) in schema.fields.iter().enumerate() {
let Some((_, value)) = decoded.fields.get(idx) else {
continue;
};
if let Some(ft) = schema_field.field_type.as_ref() {
write_field_by_type(value, ft, &mut out);
} else if let InstanceField::Bytes(raw) = value {
// No FieldType declared — emit whatever the reader
// captured as raw bytes.
out.extend_from_slice(raw);
}
}
out
}
/// Why a [`DecodedElement`] exists and how strongly we trust it.
///
/// Surfaced on CLI / Python / viewer JSON so callers can explain an
/// element and hide low-confidence rows by default.
// Tracker: M3-07.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ElementProvenance {
/// Stream path inside the OLE container (e.g. `Global/Latest`,
/// `partition:/BasicFileInfo`-adjacent partition name).
pub source_stream: Option<String>,
/// Absolute byte offset of the record in that stream (often
/// matches [`DecodedElement::byte_range`].start).
pub source_offset: Option<usize>,
/// Record family: `schema_instance`, `partition_arcwall`,
/// `partition_schema_mvp`, etc.
pub record_kind: Option<String>,
/// Decoder identity (`LevelDecoder`, `generic_decode_instance`,
/// `ArcWallRecord`, `partition_schema_mvp::floor_plan_loop`, …).
pub decoder: Option<String>,
/// Trust score in `[0.0, 1.0]`. A constructor that sets none gives
/// `1.0`, meaning no doubt is recorded.
pub confidence: f32,
/// Schema / MVP fields that were required but absent.
pub missing_required_fields: Vec<String>,
/// Non-fatal decode notes.
pub warnings: Vec<String>,
}
impl Default for ElementProvenance {
fn default() -> Self {
Self {
source_stream: None,
source_offset: None,
record_kind: None,
decoder: None,
confidence: 1.0,
missing_required_fields: Vec::new(),
warnings: Vec::new(),
}
}
}
impl ElementProvenance {
/// Schema-directed generic instance walk (no typed MVP validation).
pub fn schema_generic(stream: &str, offset: usize, class: &str) -> Self {
Self {
source_stream: Some(stream.into()),
source_offset: Some(offset),
record_kind: Some("schema_instance".into()),
decoder: Some(format!("generic_decode_instance:{class}")),
confidence: 0.55,
missing_required_fields: Vec::new(),
warnings: Vec::new(),
}
}
/// Registered typed MVP decoder success.
pub fn schema_typed(stream: &str, offset: usize, decoder_name: &str) -> Self {
Self {
source_stream: Some(stream.into()),
source_offset: Some(offset),
record_kind: Some("schema_instance".into()),
decoder: Some(decoder_name.into()),
confidence: 0.9,
missing_required_fields: Vec::new(),
warnings: Vec::new(),
}
}
/// Partition MVP / ArcWall recoveries with an explicit score.
pub fn partition(
stream: &str,
offset: usize,
kind: &str,
decoder: &str,
confidence: f32,
warnings: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
Self {
source_stream: Some(stream.into()),
source_offset: Some(offset),
record_kind: Some(kind.into()),
decoder: Some(decoder.into()),
confidence: confidence.clamp(0.0, 1.0),
missing_required_fields: Vec::new(),
warnings: warnings.into_iter().map(Into::into).collect(),
}
}
pub fn to_json_value(&self) -> serde_json::Value {
serde_json::json!({
"source_stream": self.source_stream,
"source_offset": self.source_offset,
"record_kind": self.record_kind,
"decoder": self.decoder,
"confidence": self.confidence,
"missing_required_fields": self.missing_required_fields,
"warnings": self.warnings,
})
}
}
/// Default floor for “hide low-confidence” UI / export filters.
// Tracker: M3-07.
pub const DEFAULT_MIN_ELEMENT_CONFIDENCE: f32 = 0.55;
/// Result of decoding a single element's instance bytes.
///
/// Every per-class decoder returns one of these so the walker can
/// handle arbitrary class types generically while still giving
/// callers structured access to parameter values + dereference-able
/// cross-references.
#[derive(Debug, Clone)]
pub struct DecodedElement {
/// ElementId of this instance, if known.
pub id: Option<u32>,
/// Class name ("Wall", "Floor", "Level", etc.).
pub class: String,
/// Ordered list of `(field_name, value)` — one per declared
/// schema field, populated in schema order.
pub fields: Vec<(String, InstanceField)>,
/// Byte range in the decompressed stream that this element's
/// instance data occupies. For building a HandleIndex and for
/// debugging byte-level decoding issues.
pub byte_range: std::ops::Range<usize>,
/// Decode confidence and provenance.
// Tracker: M3-07.
pub provenance: ElementProvenance,
}
impl DecodedElement {
/// [`Self::id`] as an [`ElementId`](crate::ElementId), the typed id the
/// element structs carry.
pub fn element_id(&self) -> Option<crate::ElementId> {
self.id.map(crate::ElementId::from)
}
/// Attach provenance, preserving other fields.
pub fn with_provenance(mut self, provenance: ElementProvenance) -> Self {
self.provenance = provenance;
self
}
/// True when provenance confidence meets `min_confidence`.
pub fn meets_confidence(&self, min_confidence: f32) -> bool {
self.provenance.confidence + f32::EPSILON >= min_confidence
}
}
/// A stored float as [`InstanceField::Float`], or as its bytes where it is
/// not a number a model holds ([`crate::le_bytes::physical`]). Every reader
/// takes a `Float` as a number, so a NaN, an infinity or a magnitude past
/// any model reached the IFC, glTF and plan SVG as one (#1845). As bytes it
/// is read as absent and written back unchanged.
fn float_field(value: f64, size: u8, raw: &[u8]) -> InstanceField {
if le_bytes::physical(value) {
InstanceField::Float { value, size }
} else {
InstanceField::Bytes(raw.to_vec())
}
}
/// Read a single `InstanceField` value starting at `bytes[cursor]`
/// based on the declared `FieldType`. Advances `cursor` past the
/// consumed bytes. Returns `InstanceField::Bytes(rest)` when the
/// FieldType is unknown or the wire layout for that variant isn't
/// yet exercised — callers can store the raw bytes for manual
/// inspection without crashing.
///
/// This is the per-field dispatch core that a generic `decode_instance`
/// implementation uses to walk any class's fields in schema order.
pub fn read_field_by_type(
bytes: &[u8],
cursor: &mut usize,
ty: &formats::FieldType,
) -> InstanceField {
use formats::FieldType;
let rem = || bytes.get(*cursor..).unwrap_or(&[]);
match ty {
FieldType::Primitive { kind, size } => {
let n = *size as usize;
let slice = rem();
if slice.len() < n {
return InstanceField::Bytes(slice.to_vec());
}
match (*kind, *size) {
(0x01, _) => {
let b = slice[0] != 0;
*cursor += n.max(1);
InstanceField::Bool(b)
}
(0x02, 1) => {
let v = i64::from(slice[0]);
*cursor += 1;
InstanceField::Integer {
value: v,
signed: false,
size: 1,
}
}
(0x03, 2) => {
let v = i64::from(i16::from_le_bytes([slice[0], slice[1]]));
*cursor += 2;
InstanceField::Integer {
value: v,
signed: true,
size: 2,
}
}
(0x04, 4) | (0x05, 4) => {
let v = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as i64;
*cursor += 4;
InstanceField::Integer {
value: v,
signed: *kind == 0x04,
size: 4,
}
}
(0x06, 4) => {
let v = f32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as f64;
*cursor += 4;
float_field(v, 4, &slice[..4])
}
(0x07, 8) => {
let v = f64::from_le_bytes([
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6],
slice[7],
]);
*cursor += 8;
float_field(v, 8, &slice[..8])
}
(0x0b, 8) => {
let v = i64::from_le_bytes([
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6],
slice[7],
]);
*cursor += 8;
InstanceField::Integer {
value: v,
signed: true,
size: 8,
}
}
_ => {
let bytes = slice[..n.min(slice.len())].to_vec();
*cursor += n.min(slice.len());
InstanceField::Bytes(bytes)
}
}
}
FieldType::String => {
// UTF-16LE length-prefixed. Wire: [u32 char_count][2*chars bytes].
let slice = rem();
if slice.len() < 4 {
return InstanceField::Bytes(slice.to_vec());
}
let char_count = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as usize;
// Checked, not saturating: on wasm32 `usize` is 32 bits, so a garbage `char_count`
// saturates to `usize::MAX` and `4 + byte_count` wraps, slipping past the bound below.
let Some(end) = char_count.checked_mul(2).and_then(|b| b.checked_add(4)) else {
return InstanceField::Bytes(slice.to_vec());
};
if slice.len() < end {
return InstanceField::Bytes(slice.to_vec());
}
let byte_count = end - 4;
let utf16_bytes = &slice[4..end];
// Decode as UTF-16LE. encoding_rs is already in deps.
let (text, _, had_errors) = encoding_rs::UTF_16LE.decode(utf16_bytes);
*cursor += 4 + byte_count;
if had_errors {
// Fall back to raw bytes when encoding failed.
InstanceField::Bytes(utf16_bytes.to_vec())
} else {
InstanceField::String(text.into_owned())
}
}
FieldType::Guid => {
let slice = rem();
if slice.len() < 16 {
return InstanceField::Bytes(slice.to_vec());
}
let mut g = [0u8; 16];
g.copy_from_slice(&slice[..16]);
*cursor += 16;
InstanceField::Guid(g)
}
FieldType::ElementId | FieldType::ElementIdRef { .. } => {
let slice = rem();
if slice.len() < 8 {
return InstanceField::Bytes(slice.to_vec());
}
let tag = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
let id = u32::from_le_bytes([slice[4], slice[5], slice[6], slice[7]]);
*cursor += 8;
InstanceField::ElementId { tag, id }
}
FieldType::Pointer { .. } => {
let slice = rem();
if slice.len() < 8 {
return InstanceField::Bytes(slice.to_vec());
}
let a = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]);
let b = u32::from_le_bytes([slice[4], slice[5], slice[6], slice[7]]);
*cursor += 8;
InstanceField::Pointer { raw: [a, b] }
}
FieldType::Vector { kind, .. } => {
// Tracker: L5B-08.
// Decode vectors of known-size primitive elements
// into `InstanceField::Vector(Vec<InstanceField>)`. Wire
// format for these kinds: `[u32 count][count × element]`
// where element size is driven by the outer-type byte.
//
// Element-kind table (matches the Primitive table above):
//
// 0x01 = bool (1 byte), 0x07 = f64 (8 bytes),
// 0x05 = u32 (4 bytes), 0x0b = i64 (8 bytes),
// 0x0d = point = 3 × f64 (24 bytes).
//
// Unknown element kinds fall back to `InstanceField::Bytes`
// with the raw count-prefix + remaining payload so callers
// can inspect — same graceful-fallback philosophy as the
// other read paths.
let slice = rem();
if slice.len() < 4 {
return InstanceField::Bytes(slice.to_vec());
}
let count = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]) as usize;
if *kind == 0x02 {
// RE-325: a `char` is one byte, so this is a byte blob (a PNG,
// a zip, RTF) of `count` bytes. Kept whole with its count
// prefix, so it writes back verbatim, not one item per byte.
let needed = count.saturating_add(4);
if slice.len() < needed {
return InstanceField::Bytes(slice.to_vec());
}
*cursor += needed;
return InstanceField::Bytes(slice[..needed].to_vec());
}
// Per-element byte size for kinds we decode directly.
let elem_size: Option<usize> = match *kind {
0x01 => Some(1),
0x05 | 0x04 => Some(4),
0x07 | 0x0b => Some(8),
0x0d => Some(24),
_ => None,
};
let Some(esz) = elem_size else {
// Unknown element kind — consume just the count
// prefix and emit the following-bytes as raw.
let consumed = slice.len().min(4);
let out = slice[..consumed].to_vec();
*cursor += consumed;
return InstanceField::Bytes(out);
};
let needed = count
.checked_mul(esz)
.and_then(|n| n.checked_add(4))
.unwrap_or(usize::MAX);
if slice.len() < needed {
return InstanceField::Bytes(slice.to_vec());
}
let mut items = Vec::with_capacity(count);
let mut local = 4;
for _ in 0..count {
let elem_bytes = &slice[local..local + esz];
let item = match (*kind, esz) {
(0x01, 1) => InstanceField::Bool(elem_bytes[0] != 0),
(0x04, 4) | (0x05, 4) => {
let v = u32::from_le_bytes([
elem_bytes[0],
elem_bytes[1],
elem_bytes[2],
elem_bytes[3],
]) as i64;
InstanceField::Integer {
value: v,
signed: *kind == 0x04,
size: 4,
}
}
(0x07, 8) => {
let v = f64::from_le_bytes([
elem_bytes[0],
elem_bytes[1],
elem_bytes[2],
elem_bytes[3],
elem_bytes[4],
elem_bytes[5],
elem_bytes[6],
elem_bytes[7],
]);
float_field(v, 8, elem_bytes)
}
(0x0b, 8) => {
let v = i64::from_le_bytes([
elem_bytes[0],
elem_bytes[1],
elem_bytes[2],
elem_bytes[3],
elem_bytes[4],
elem_bytes[5],
elem_bytes[6],
elem_bytes[7],
]);
InstanceField::Integer {
value: v,
signed: true,
size: 8,
}
}
(0x0d, 24) => {
// point = 3 × f64. Surface as a nested Vector
// of three Float items — the inner structure
// preserves the X,Y,Z semantics without
// needing a dedicated Point variant.
let mut point = Vec::with_capacity(3);
for k in 0..3 {
let off = k * 8;
let v = f64::from_le_bytes([
elem_bytes[off],
elem_bytes[off + 1],
elem_bytes[off + 2],
elem_bytes[off + 3],
elem_bytes[off + 4],
elem_bytes[off + 5],
elem_bytes[off + 6],
elem_bytes[off + 7],
]);
point.push(float_field(v, 8, &elem_bytes[off..off + 8]));
}
// A point is read whole or not at all: one component
// that is not a number leaves the point as its bytes.
if point
.iter()
.all(|p| matches!(p, InstanceField::Float { .. }))
{
InstanceField::Vector(point)
} else {
InstanceField::Bytes(elem_bytes.to_vec())
}
}
_ => InstanceField::Bytes(elem_bytes.to_vec()),
};
items.push(item);
local += esz;
}
*cursor += 4 + count * esz;
InstanceField::Vector(items)
}
FieldType::Container { kind, .. } => {
// Tracker: L5B-09.4.
// A scalar-base Container (kinds 0x01/0x02/0x04/
// 0x05/0x07/0x0b/0x0d) use the same `[u32 count][count ×
// element]` wire layout as Vector — the sub=0x0050 tag
// only distinguishes semantic role (std::set / std::map
// keyset / …), not the scalar encoding. We reuse the
// Vector decode path by recursing with a synthesised
// Vector FieldType of the same kind.
//
// Reference containers (kind=0x0e) have a 2-column
// layout handled by the ADocument-walker-facing
// `read_field` (see `FieldType::Container { kind: 0x0e,
// .. }` arm there). Generic callers hitting the 0x0e
// arm here get 4 bytes as a fallback.
if matches!(*kind, 0x01 | 0x02 | 0x04 | 0x05 | 0x07 | 0x0b | 0x0d) {
let fake_vec = FieldType::Vector {
kind: *kind,
body: Vec::new(),
};
return read_field_by_type(bytes, cursor, &fake_vec);
}
let slice = rem();
let consumed = slice.len().min(4);
let out = slice[..consumed].to_vec();
*cursor += consumed;
InstanceField::Bytes(out)
}
// RE-264, RE-323: the pointer arrays and containers and the flagged
// fields are classified from the schema and their instances were
// measured in the native graphs, not in this walker's record shapes,
// so it reads them as it read them when they were `Unknown`.
FieldType::Unknown { .. }
| FieldType::Flagged { .. }
| FieldType::PointerArray { .. }
| FieldType::PointerContainer { .. } => {
// Forward remaining bytes. Callers can inspect them.
let slice = rem();
let out = slice.to_vec();
*cursor = bytes.len();
InstanceField::Bytes(out)
}
}
}
/// Generic instance decoder: walks each declared field of `class` in
/// schema order using `read_field_by_type`. Falls back to
/// `InstanceField::Bytes` for fields whose FieldType is unknown or
/// whose wire layout isn't yet exercised.
///
/// Used by `ElementDecoder` default implementations and by any
/// caller who wants a best-effort instance dump without writing a
/// class-specific decoder first. Returns a `DecodedElement` with
/// `id: None` (callers that can extract the ID from the record
/// header should set it after calling this).
pub fn decode_instance(bytes: &[u8], start: usize, class: &formats::ClassEntry) -> DecodedElement {
decode_instance_with_limits(bytes, start, class, WalkerLimits::default())
}
pub fn decode_instance_with_limits(
bytes: &[u8],
start: usize,
class: &formats::ClassEntry,
limits: WalkerLimits,
) -> DecodedElement {
let end = start
.checked_add(limits.max_per_record_decode_bytes)
.map(|n| n.min(bytes.len()))
.unwrap_or(bytes.len());
let bytes = bytes.get(..end).unwrap_or(bytes);
let mut cursor = start;
let mut fields = Vec::with_capacity(class.fields.len());
for field in &class.fields {
let value = match field.field_type.as_ref() {
Some(ft) => read_field_by_type(bytes, &mut cursor, ft),
None => {
// Field's type didn't classify — consume nothing,
// emit empty bytes.
InstanceField::Bytes(Vec::new())
}
};
fields.push((field.name.clone(), value));
}
DecodedElement {
id: None,
class: class.name.clone(),
fields,
byte_range: start..cursor,
provenance: ElementProvenance::schema_generic("schema", start, &class.name),
}
}