cadmpeg-asm 0.6.1

Parse and write Autodesk Shape Manager record streams.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
// SPDX-License-Identifier: Apache-2.0
//! Token-space cursor and subtype walkers over framed [`Token`] payloads.
//!
//! These walkers mirror the byte readers in [`crate::nurbs::reader`] and the
//! subtype walkers in [`crate::nurbs::subtypes`]. The framer resolves integer
//! width and retains payload identifiers, so the walkers use token names and
//! positions. Token positions identify fields within a record payload without
//! depending on serialized byte offsets.

#[cfg(any(test, feature = "test-support"))]
use crate::kernel_header::RefWidth;
use crate::nurbs::reader::{checked_knot_layout, BsplineMarker, Nullable};
use crate::sab::Token;

/// A cursor over one record's payload tokens.
///
/// `take_*` methods consume one token or counted group and return its value.
/// A failed type match leaves the cursor position unchanged.
#[derive(Clone, Copy)]
pub struct Cur<'a> {
    toks: &'a [Token],
    pos: usize,
}

impl<'a> Cur<'a> {
    /// A cursor over `toks` starting at token index `pos`.
    pub fn at(toks: &'a [Token], pos: usize) -> Self {
        Self { toks, pos }
    }

    /// Current token index.
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// Move the cursor to token index `pos`.
    pub(super) fn set_pos(&mut self, pos: usize) {
        self.pos = pos;
    }

    /// The full token slice the cursor walks.
    pub(super) fn toks(&self) -> &'a [Token] {
        self.toks
    }

    /// The token at the cursor, without consuming it.
    pub(super) fn peek(&self) -> Option<&'a Token> {
        self.toks.get(self.pos)
    }

    /// Whether the cursor is at the closing token of this complete subtype
    /// span, with no unconsumed field before or token after it.
    pub(super) fn at_scope_end(&self) -> bool {
        self.pos + 1 == self.toks.len()
            && matches!(self.toks.get(self.pos), Some(Token::SubtypeClose))
    }

    /// Consume one token of any kind.
    pub(super) fn bump(&mut self) -> Option<&'a Token> {
        let token = self.toks.get(self.pos)?;
        self.pos += 1;
        Some(token)
    }

    /// The remaining tokens from the cursor onward.
    pub(super) fn rest(&self) -> &'a [Token] {
        self.toks.get(self.pos..).unwrap_or(&[])
    }

    pub(super) fn take_f64(&mut self) -> Option<f64> {
        match self.peek()? {
            Token::Double(value) => {
                self.pos += 1;
                Some(*value)
            }
            _ => None,
        }
    }

    pub(super) fn take_long(&mut self) -> Option<i64> {
        match self.peek()? {
            Token::Long(value) => {
                self.pos += 1;
                Some(*value)
            }
            _ => None,
        }
    }

    pub(super) fn take_enum(&mut self) -> Option<i64> {
        match self.peek()? {
            Token::Enum(value) => {
                self.pos += 1;
                Some(*value)
            }
            _ => None,
        }
    }

    pub(super) fn take_bool(&mut self) -> Option<bool> {
        match self.peek()? {
            Token::True => {
                self.pos += 1;
                Some(true)
            }
            Token::False => {
                self.pos += 1;
                Some(false)
            }
            _ => None,
        }
    }

    pub(super) fn take_str(&mut self) -> Option<&'a str> {
        match self.peek()? {
            Token::Str(value) => {
                self.pos += 1;
                Some(value)
            }
            _ => None,
        }
    }

    /// Consume one payload identifier (`Ident` or `SubIdent`).
    pub(super) fn take_ident(&mut self) -> Option<&'a str> {
        match self.peek()? {
            Token::Ident(value) | Token::SubIdent(value) => {
                self.pos += 1;
                Some(value)
            }
            _ => None,
        }
    }

    /// Consume one `0x13` position triple.
    pub(super) fn take_position(&mut self) -> Option<[f64; 3]> {
        match self.peek()? {
            Token::Position(value) => {
                self.pos += 1;
                Some(*value)
            }
            _ => None,
        }
    }

    /// Consume one `0x14` vector triple.
    pub(super) fn take_vector3(&mut self) -> Option<[f64; 3]> {
        match self.peek()? {
            Token::Vector3(value) => {
                self.pos += 1;
                Some(*value)
            }
            _ => None,
        }
    }

    /// Consume a `Long` count followed by that many `Double`s.
    pub(super) fn take_float_array(
        &mut self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Option<Result<Vec<f64>, cadmpeg_core::CodecError>> {
        let mark = self.pos;
        let Some(count) = self.take_long().and_then(|c| usize::try_from(c).ok()) else {
            self.pos = mark;
            return None;
        };
        let mut values = match ctx.collection_vec(count, "ASM counted float array") {
            Ok(values) => values,
            Err(error) => return Some(Err(error)),
        };
        for _ in 0..count {
            let Some(value) = self.take_f64() else {
                self.pos = mark;
                return None;
            };
            values.push(value);
        }
        Some(Ok(values))
    }

    /// Consume an optional leading boolean, then one `Double`: the range-bound
    /// form whose presence flag some releases serialize and some omit.
    pub(super) fn take_range_value(&mut self) -> Option<f64> {
        let mark = self.pos;
        if matches!(self.peek(), Some(Token::True | Token::False)) {
            self.pos += 1;
        }
        let Some(value) = self.take_f64() else {
            self.pos = mark;
            return None;
        };
        Some(value)
    }

    /// Consume one optional range bound: `True` + `Double` or a bare `Double`
    /// is a present bound, `False` is an absent bound. The outer `None` is a
    /// parse failure.
    pub(super) fn take_optional_range_value(&mut self) -> Option<Nullable<f64>> {
        let mark = self.pos;
        match self.peek()? {
            Token::True => {
                self.pos += 1;
                let Some(value) = self.take_f64() else {
                    self.pos = mark;
                    return None;
                };
                Some(Nullable::Value(value))
            }
            Token::False => {
                self.pos += 1;
                Some(Nullable::Null)
            }
            Token::Double(_) => self.take_f64().map(Nullable::Value),
            _ => None,
        }
    }
}

/// Read a knot table of `n` `(knot, multiplicity)` pairs from the cursor.
///
/// Expansion adds one to each endpoint multiplicity. The pole count is
/// `sum(mult) - (degree - 1)`.
pub(super) fn take_knot_table(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    cur: &mut Cur<'_>,
    n: usize,
    degree: i64,
) -> Option<Result<(Vec<f64>, usize), cadmpeg_core::CodecError>> {
    // Each typed pair comes from a complete double and integer field. The
    // retained token boundary provides enough fields for at least n pairs.
    if n > cur.rest().len() / 2 {
        return None;
    }
    let Some(work) = cadmpeg_core::decode::u64_from_index(n).checked_mul(3) else {
        return Some(Err(ctx.refuse_codec_limit(
            "ASM unique knot work",
            u64::MAX,
            u64::MAX,
        )));
    };
    if let Err(error) = ctx.charge_work(work, "read ASM unique knot pairs") {
        return Some(Err(error));
    }
    let mut scratch = match ctx.reserve_scoped(0, "ASM knot expansion inputs") {
        Ok(scratch) => scratch,
        Err(error) => return Some(Err(error)),
    };
    let mut values = match scratch.with_storage(|| ctx.collection_vec(n, "ASM unique knot values"))
    {
        Ok(values) => values,
        Err(error) => return Some(Err(error)),
    };
    let mut mults = match scratch.with_storage(|| ctx.collection_vec(n, "ASM knot multiplicities"))
    {
        Ok(mults) => mults,
        Err(error) => return Some(Err(error)),
    };
    for _ in 0..n {
        values.push(cur.take_f64()?);
        mults.push(cur.take_long()?);
    }
    let expansion = checked_knot_layout(&mults, degree)?;
    if let Err(error) = ctx.charge_work(
        cadmpeg_core::decode::u64_from_index(expansion.expanded_len()),
        "expand ASM knots",
    ) {
        return Some(Err(error));
    }
    let mut expanded = match ctx.collection_vec(expansion.expanded_len(), "ASM expanded knots") {
        Ok(expanded) => expanded,
        Err(error) => return Some(Err(error)),
    };
    for (index, (value, multiplicity)) in values.iter().zip(&mults).enumerate() {
        let run_length = usize::try_from(*multiplicity).ok()?
            + usize::from(index == 0 || index + 1 == mults.len());
        for _ in 0..run_length {
            expanded.push(*value);
        }
    }
    Some(Ok((expanded, expansion.n_poles)))
}

/// The B-spline marker at token `pos`, if any.
pub(super) fn marker_at(toks: &[Token], pos: usize) -> Option<BsplineMarker> {
    match toks.get(pos)? {
        Token::Ident(name) if name == "nubs" => Some(BsplineMarker::Nubs),
        Token::Ident(name) if name == "nurbs" => Some(BsplineMarker::Nurbs),
        _ => None,
    }
}

/// Token indices of the `nubs`/`nurbs` markers `toks` itself owns: those
/// outside every construction nested within it. The span's outer
/// `SubtypeOpen` sets the initial nesting depth.
///
/// A `SubtypeClose` with no open scope is a malformed token stream and is
/// refused: pinning the depth at zero would make every later marker read as one
/// this span owns.
pub(super) fn owned_marker_positions(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
) -> Option<Result<Vec<usize>, cadmpeg_core::CodecError>> {
    let (out, balanced) = match walk_owned_markers(ctx, toks) {
        Ok(value) => value,
        Err(error) => return Some(Err(error)),
    };
    balanced.then_some(Ok(out))
}

/// The owned-marker walk, with the balance it observed.
///
/// The second element is `false` when the walk met a `SubtypeClose` that no
/// open in `toks` matches. A balanced stream always answers `true`, so a caller
/// holding a [`SubtypeScope`] reads the first element alone.
fn walk_owned_markers(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
) -> Result<(Vec<usize>, bool), cadmpeg_core::CodecError> {
    let mut out = Vec::new();
    let mut depth = 0usize;
    // The span's own leading `SubtypeOpen` is skipped, so the close that
    // matches it is the one close this walk admits at depth zero.
    let mut outer = usize::from(matches!(toks.first(), Some(Token::SubtypeOpen)));
    for (pos, token) in toks.iter().enumerate().skip(outer) {
        match token {
            Token::SubtypeOpen => depth += 1,
            Token::SubtypeClose => match depth.checked_sub(1) {
                Some(next) => depth = next,
                None => match outer.checked_sub(1) {
                    Some(next) => outer = next,
                    None => return Ok((out, false)),
                },
            },
            _ => {
                if depth == 0 && marker_at(toks, pos).is_some() {
                    ctx.push_vec(&mut out, pos, "ASM owned spline markers")?;
                }
            }
        }
    }
    Ok((out, true))
}

/// Token indices and names of the subtype definitions `toks` itself owns: the
/// `SubtypeOpen`s at the outermost nesting level whose next token is an
/// identifier, in order, `ref` included. A definition inside a nested scope
/// belongs to that scope's construction, not to `toks`.
///
/// A `SubtypeClose` with no open scope is a malformed token stream and is
/// refused.
pub(super) fn owned_subtype_defs<'a>(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &'a [Token],
) -> Option<Result<Vec<(usize, &'a str)>, cadmpeg_core::CodecError>> {
    let mut owned = Vec::new();
    let mut depth = 0usize;
    for (pos, token) in toks.iter().enumerate() {
        match token {
            Token::SubtypeOpen => {
                if depth == 0 {
                    if let Some(Token::Ident(name) | Token::SubIdent(name)) = toks.get(pos + 1) {
                        if let Err(error) = ctx.push_vec(
                            &mut owned,
                            (pos, name.as_str()),
                            "ASM owned subtype definitions",
                        ) {
                            return Some(Err(error));
                        }
                    }
                }
                depth += 1;
            }
            Token::SubtypeClose => depth = depth.checked_sub(1)?,
            _ => {}
        }
    }
    Some(Ok(owned))
}

/// Token index of the first subtype definition `toks` owns whose name matches
/// one of `names`, with the matched name. Names are tried in order; the first
/// name with a hit wins.
///
/// A construction owns a record through its own definition. Nested definitions
/// belong to their enclosing construction, so this function ignores matching
/// markers in nested scopes.
pub(super) fn find_owned_subtype_marker<'n>(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    names: &[&'n str],
) -> Option<Result<(usize, &'n str), cadmpeg_core::CodecError>> {
    let mut owned_storage = match ctx.reserve_scoped(0, "ASM owned construction index") {
        Ok(storage) => storage,
        Err(error) => return Some(Err(error)),
    };
    let owned = match owned_storage.with_storage(|| owned_subtype_defs(ctx, toks).transpose()) {
        Ok(Some(value)) => value,
        Ok(None) => return None,
        Err(error) => return Some(Err(error)),
    };
    names.iter().copied().find_map(|name| {
        owned
            .iter()
            .find(|(_, owned_name)| *owned_name == name)
            .map(|(start, _)| Ok((*start, name)))
    })
}

/// The construction `toks` is, under its modern name: the first subtype
/// definition `toks` owns other than `ref`, canonicalized.
pub fn owned_construction_subtype(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
) -> Option<Result<String, cadmpeg_core::CodecError>> {
    let mut owned_storage = match ctx.reserve_scoped(0, "ASM owned construction index") {
        Ok(storage) => storage,
        Err(error) => return Some(Err(error)),
    };
    let owned = match owned_storage.with_storage(|| owned_subtype_defs(ctx, toks).transpose()) {
        Ok(Some(value)) => value,
        Ok(None) => return None,
        Err(error) => return Some(Err(error)),
    };
    owned
        .into_iter()
        .map(|(_, name)| name)
        .find(|name| *name != "ref")
        .map(|name| {
            let name = canonical_intcurve_kind(name);
            ctx.copy_retained_text(name, "ASM construction subtype name")
        })
}

/// The token span that carries `toks`'s cache, or `None` when the record
/// states none.
///
/// `docs/formats/asm.md`: "the outer non-`ref` procedural subtype owns the
/// record's solved curve or surface cache. A B-spline block inside a subtype
/// nested by that construction belongs to the nested support, source, guide,
/// or child field and is not a candidate for the outer construction's cache."
/// A scope is cache-bearing when it directly owns at least one B-spline
/// marker. The sentence states a construction's ownership, so it decides where
/// the record owns a construction:
///
/// * Exactly one non-`ref` scope the record owns directly is cache-bearing:
///   that scope is the cache span.
/// * More than one is cache-bearing: the record names no single owner, so it
///   states no cache span.
/// * The record owns non-`ref` scopes and none is cache-bearing: the
///   construction's cache is absent. Every remaining block sits in a nested
///   support, source, guide or child scope, which the sentence excludes, so
///   the record states no cache span.
/// * The record owns no non-`ref` scope: it states no construction, so no
///   construction owns its blocks and the record's own stream is the cache
///   span. This last case is the decoder's decision, not the sentence's. The
///   sentence states what a construction owns, so a record that states no
///   construction is outside it. The nearest sentence that bears on it is
///   `docs/formats/asm.md:403`, `exact_int_cur`: "the solved `nubs`/`nurbs`
///   curve cache is the authoritative exact construction payload" — the cache
///   is the record's own payload there — but that sentence names one subtype,
///   and this case covers every record that states no owned construction,
///   including the `ref` forms whose subtype is named in the subtype table. No
///   sentence in `asm.md` states the general case. What states it is the
///   routes that exercise it: the four f3d writer round trips
///   `writer::tests::source_less_nurbs::
///   generated_source_less_face_writes_nurbs_surface_carrier`,
///   `..._writes_rational_nurbs_surface_carrier`,
///   `..._writes_rational_nurbs_edge_curve` and
///   `generated_source_less_multi_face_writes_nurbs_carriers_and_pcurve` in
///   `cadmpeg-codec-f3d`, which encode a source-less NURBS body and decode it
///   back. The written record owns no procedural subtype at all, so its
///   B-spline block is the record's geometry and not a construction's cache.
///   Removing this arm fails all four on `solved carrier`.
///
/// This is the one answer; every reader of a record cache calls it and none
/// states a fallback of its own.
///
/// A malformed token stream is refused, not worked around: `owned_subtype_defs`
/// answers `None` rather than passing over the scope that stated it.
pub(super) fn cache_scope<'a>(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &'a [Token],
) -> Option<Result<&'a [Token], cadmpeg_core::CodecError>> {
    let mut constructions = 0usize;
    let mut cache_bearing = Vec::new();
    let mut owned_storage = match ctx.reserve_scoped(0, "ASM owned construction index") {
        Ok(storage) => storage,
        Err(error) => return Some(Err(error)),
    };
    let owned = match owned_storage.with_storage(|| owned_subtype_defs(ctx, toks).transpose()) {
        Ok(Some(value)) => value,
        Ok(None) => return None,
        Err(error) => return Some(Err(error)),
    };
    for (start, _) in owned.into_iter().filter(|(_, name)| *name != "ref") {
        constructions += 1;
        let Some(scope) = subtype_span(toks, start) else {
            continue;
        };
        let markers = match scope.owned_marker_positions(ctx) {
            Ok(value) => value,
            Err(error) => return Some(Err(error)),
        };
        if !markers.is_empty() {
            if let Err(error) = ctx.push_vec(
                &mut cache_bearing,
                scope.tokens(),
                "ASM cache bearing scopes",
            ) {
                return Some(Err(error));
            }
        }
    }
    match (cache_bearing.as_slice(), constructions) {
        ([scope], _) => Some(Ok(scope)),
        ([], 0) => Some(Ok(toks)),
        _ => None,
    }
}

fn canonical_intcurve_kind(name: &str) -> &str {
    super::subtypes::INTCURVE_ALIASES
        .iter()
        .find_map(|(modern, legacy)| (*legacy == name).then_some(*modern))
        .unwrap_or(name)
}

/// Token index of the `intcurve` subtype definition `toks` owns, given the
/// subtype's modern name. The legacy spelling of the same construction is
/// accepted as a second candidate.
pub(super) fn find_owned_intcurve_subtype(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    toks: &[Token],
    modern: &str,
) -> Option<Result<usize, cadmpeg_core::CodecError>> {
    if modern.is_empty() {
        return None;
    }
    let legacy = super::subtypes::INTCURVE_ALIASES
        .iter()
        .find_map(|(name, alias)| (*name == modern).then_some(*alias));
    let found = match legacy {
        Some(legacy) => find_owned_subtype_marker(ctx, toks, &[modern, legacy]),
        None => find_owned_subtype_marker(ctx, toks, &[modern]),
    };
    found.map(|result| result.map(|(marker, _)| marker))
}

/// A balanced subtype scope in token space.
///
/// `subtype_span` is the only constructor: the field is private and the type
/// has no `From` and no `Deref`. Every value therefore states one scope whose
/// every `SubtypeClose` has a matching open within the span, and whose final
/// token is the close that balances it. The walks that refuse an unbalanced
/// stream are total over this type.
///
/// The fields are not reachable from another module:
///
/// ```compile_fail
/// use cadmpeg_asm::nurbs::toks::SubtypeScope;
/// use cadmpeg_asm::sab::Token;
///
/// let toks = [Token::SubtypeOpen, Token::SubtypeClose];
/// let scope = SubtypeScope { tokens: &toks[..] };
/// ```
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SubtypeScope<'a> {
    tokens: &'a [Token],
}

impl<'a> SubtypeScope<'a> {
    /// The scope's tokens, both delimiters included.
    pub fn tokens(&self) -> &'a [Token] {
        self.tokens
    }

    /// The tokens the scope encloses: everything between its opening token and
    /// the close that balances it. For a scope that names a construction the
    /// first of these is the identifier that names it, and the rest are the
    /// fields the construction states.
    ///
    /// Total: `subtype_span` is the only constructor. It refuses unless the
    /// token at `start` is the scope's own `SubtypeOpen`, and it builds
    /// `tokens` as `toks[start..=pos]` with `pos > start`, so the slice holds
    /// at least the opening and the closing delimiter and this range is in
    /// bounds. The proof is the constructor's, not the caller's.
    pub fn interior(&self) -> &'a [Token] {
        &self.tokens[1..self.tokens.len() - 1]
    }

    /// Token indices of the `nubs`/`nurbs` markers the scope itself owns: those
    /// outside every construction nested within it. The scope's outer
    /// `SubtypeOpen` sets the initial nesting depth.
    ///
    /// Direct ownership is the format's rule. `docs/formats/asm.md:395`: "the
    /// outer non-`ref` procedural subtype owns the record's solved curve or
    /// surface cache. A B-spline block inside a subtype nested by that
    /// construction belongs to the nested support, source, guide, or child
    /// field and is not a candidate for the outer construction's cache", and
    /// the owning block's ordinal is fixed "among the B-spline blocks directly
    /// owned by the construction".
    ///
    /// The walk skips one leading `SubtypeOpen`, which over these tokens is the
    /// scope's own. A caller that passed the slice after the scope's name token
    /// instead made the walk skip the open of a *first nested* scope and
    /// collect that nested construction's markers as owned; that shape was the
    /// defect, and no caller states it now.
    ///
    /// Total: the unbalanced stream that `owned_marker_positions` refuses is
    /// a state this type cannot hold.
    pub fn owned_marker_positions(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    ) -> Result<Vec<usize>, cadmpeg_core::CodecError> {
        Ok(walk_owned_markers(ctx, self.tokens)?.0)
    }
}

/// The balanced subtype scope opening at `start`, inclusive of both delimiters.
///
/// `None` unless the token at `start` is a `SubtypeOpen`. A scope opens at its
/// own opening delimiter, so a `start` that names another token names no
/// scope, and the span is then at least two tokens.
pub(super) fn subtype_span(toks: &[Token], start: usize) -> Option<SubtypeScope<'_>> {
    matches!(toks.get(start), Some(Token::SubtypeOpen)).then_some(())?;
    let mut depth = 0usize;
    for (pos, token) in toks.iter().enumerate().skip(start) {
        match token {
            Token::SubtypeOpen => depth += 1,
            Token::SubtypeClose => {
                depth = depth.checked_sub(1)?;
                if depth == 0 {
                    // `pos > start`: reaching depth one needs a `SubtypeOpen`
                    // at or after `start`, so the close that returns depth to
                    // zero is never the token at `start` itself. Both slices
                    // are therefore in range.
                    return Some(SubtypeScope {
                        tokens: toks.get(start..=pos)?,
                    });
                }
            }
            _ => {}
        }
    }
    None
}

/// Subtype-table reference indices in `toks`, in token order: the
/// `{ref N}` form (`SubtypeOpen`, `Ident("ref")`, `Long(N)`) and the bare
/// index form (`SubtypeOpen`, `Long(N)`, `SubtypeClose`).
pub(super) fn subtype_refs(toks: &[Token]) -> impl Iterator<Item = usize> + '_ {
    toks.iter().enumerate().filter_map(|(pos, token)| {
        if !matches!(token, Token::SubtypeOpen) {
            return None;
        }
        match (toks.get(pos + 1), toks.get(pos + 2)) {
            (Some(Token::Ident(name)), Some(Token::Long(index)))
                if name == "ref" && *index >= 0 =>
            {
                usize::try_from(*index).ok()
            }
            (Some(Token::Long(index)), Some(Token::SubtypeClose)) if *index >= 0 => {
                usize::try_from(*index).ok()
            }
            _ => None,
        }
    })
}

/// The subtype scope at payload chunk `chunk_index` when its immediately
/// following identifier is `expected`.
///
/// The scope carries its own balance proof, so a caller that walks it needs no
/// walk of its own to establish one. The identifier this function matched is
/// the first token of [`SubtypeScope::interior`].
pub fn payload_subtype_toks<'r>(
    record: &'r crate::sab::Record,
    chunk_index: usize,
    expected: &str,
) -> Option<SubtypeScope<'r>> {
    let mut chunk = 0usize;
    let mut open = None;
    for (pos, token) in record.tokens.iter().enumerate() {
        if token.is_payload_ident() {
            continue;
        }
        if chunk == chunk_index {
            open = Some(pos);
            break;
        }
        chunk += 1;
    }
    let open = open?;
    if !matches!(record.tokens.get(open), Some(Token::SubtypeOpen)) {
        return None;
    }
    let (Token::Ident(name) | Token::SubIdent(name)) = record.tokens.get(open + 1)? else {
        return None;
    };
    if name != expected {
        return None;
    }
    subtype_span(&record.tokens, open)
}

/// Token positions of the stream's subtype definitions, in stream order.
///
/// A subtype definition opens as `SubtypeOpen` followed by an identifier other
/// than `ref`, at any nesting depth; `{ref N}` references resolve to the `N`-th
/// entry. Each entry holds the owning record's shared payload tokens and the
/// definition's token index within them, so resolution needs no side channel
/// back to the record table.
pub struct SubtypeTable {
    defs: Vec<(std::sync::Arc<[Token]>, usize)>,
    /// The stream's ASM save format version from the `asmheader` record. Tokens
    /// omit this value, so the table carries it into token-space decoders.
    save_format_version: Option<u32>,
}

impl SubtypeTable {
    /// Build the table over each framed record's payload tokens, in order.
    pub fn from_records(
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        records: &[crate::sab::Record],
    ) -> Result<Self, cadmpeg_core::CodecError> {
        let mut defs = Vec::new();
        for record in records {
            for (pos, token) in record.tokens.iter().enumerate() {
                if matches!(token, Token::SubtypeOpen) {
                    if let Some(Token::Ident(name) | Token::SubIdent(name)) =
                        record.tokens.get(pos + 1)
                    {
                        if name != "ref" {
                            ctx.reserve_vec(&mut defs, 1, "index ASM subtype definitions")?;
                            defs.push((record.tokens.clone(), pos));
                        }
                    }
                }
            }
        }
        Ok(Self {
            defs,
            save_format_version: None,
        })
    }

    /// Attach the stream's ASM save format version.
    #[must_use]
    pub fn with_save_format_version(mut self, version: Option<u32>) -> Self {
        self.save_format_version = version;
        self
    }

    /// The stream's ASM save format version, when known.
    pub(super) fn save_format_version(&self) -> Option<u32> {
        self.save_format_version
    }

    /// The balanced scope of definition `index`, sliced from its owning record.
    pub(super) fn span(&self, index: usize) -> Option<SubtypeScope<'_>> {
        let (tokens, token_pos) = self.defs.get(index)?;
        subtype_span(tokens, *token_pos)
    }
}

/// Admit every subtype-reference walk before semantic candidates read the
/// table. The stack holds policy depth guards for the active reference path.
pub(crate) fn admit_subtype_references(
    ctx: &cadmpeg_core::decode::DecodeContext<'_>,
    records: &[crate::sab::Record],
    table: &SubtypeTable,
) -> Result<(), cadmpeg_core::CodecError> {
    for record in records {
        ctx.charge_work(
            cadmpeg_core::decode::u64_from_index(record.tokens.len()),
            "scan ASM subtype references",
        )?;
        let mut visited = std::collections::HashSet::new();
        let mut pending = Vec::new();
        let mut scratch = ctx.reserve_scoped(0, "walk ASM subtype references")?;
        let root = (subtype_refs(&record.tokens), None);
        ctx.push_scoped_vec(&mut scratch, &mut pending, root, "walk ASM subtype stack")?;
        while let Some((references, _guard)) = pending.last_mut() {
            let Some(index) = references.next() else {
                pending.pop();
                continue;
            };
            ctx.charge_work(1, "follow ASM subtype reference")?;
            if visited.contains(&index) {
                continue;
            }
            let visited_slot_bytes =
                cadmpeg_core::decode::u64_from_index(std::mem::size_of::<usize>());
            scratch.grow(visited_slot_bytes)?;

            ctx.insert_hash_set(&mut visited, index, "visit ASM subtype reference")?;
            let Some((tokens, _)) = table.defs.get(index) else {
                continue;
            };
            ctx.charge_work(
                cadmpeg_core::decode::u64_from_index(tokens.len()),
                "scan ASM subtype definition",
            )?;
            let Some(target) = table.span(index) else {
                continue;
            };
            let guard = ctx.enter_nested("follow ASM subtype reference")?;
            let frame = (subtype_refs(target.tokens()), Some(guard));
            ctx.push_scoped_vec(&mut scratch, &mut pending, frame, "walk ASM subtype stack")?;
        }
    }
    Ok(())
}

/// Lex a bare byte span (a subtype scope or block without a record name or
/// terminator) into payload tokens, for tests that build byte fixtures.
///
/// # Errors
///
/// Refuses malformed tokens and bytes that frame as more than one record.
#[cfg(any(test, feature = "test-support"))]
pub fn lex_test_span(
    bytes: &[u8],
    ref_width: RefWidth,
) -> Result<std::sync::Arc<[Token]>, crate::stream_error::StreamError> {
    let mut wrapped = vec![0x0d, 1, b'x'];
    wrapped.extend_from_slice(bytes);
    wrapped.push(0x11);
    let records = crate::test_support::sab::frame(&wrapped, 0, wrapped.len(), ref_width)?;
    let [record]: [crate::sab::Record; 1] =
        records
            .try_into()
            .map_err(|records: Vec<_>| crate::stream_error::StreamError {
                format: crate::stream_error::StreamFormat::Binary,
                offset: 0,
                reason: format!(
                    "bare payload frames as {} records, expected one",
                    records.len()
                ),
            })?;
    Ok(record.tokens)
}

/// Build a [`SubtypeTable`] over a bare byte span, for tests.
#[cfg(any(test, feature = "test-support"))]
pub fn test_table(
    bytes: &[u8],
    ref_width: RefWidth,
) -> Result<SubtypeTable, crate::stream_error::StreamError> {
    let record = crate::sab::Record {
        index: 0,
        name: String::new(),

        tokens: lex_test_span(bytes, ref_width)?,
        offset: 0,
        len: 0,
    };
    let arena = cadmpeg_core::decode::DecodeArena::new();
    let policy = cadmpeg_core::decode::DecodePolicy::service();
    let (ctx, _) = cadmpeg_core::decode::DecodeContext::from_root_bytes(&[], &arena, &policy)
        .map_err(|error| crate::stream_error::StreamError {
            format: crate::stream_error::StreamFormat::Binary,
            offset: 0,
            reason: error.to_string(),
        })?;
    SubtypeTable::from_records(&ctx, &[record]).map_err(|error| crate::stream_error::StreamError {
        format: crate::stream_error::StreamFormat::Binary,
        offset: 0,
        reason: error.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::{
        cache_scope as cache_scope_ctx, lex_test_span, marker_at,
        owned_construction_subtype as owned_construction_subtype_ctx,
        owned_marker_positions as owned_marker_positions_ctx,
        owned_subtype_defs as owned_subtype_defs_ctx, subtype_refs, subtype_span, test_table, Cur,
    };
    use crate::kernel_header::RefWidth;
    use crate::nurbs::reader::BsplineMarker;
    use crate::sab::Token;

    fn with_ctx<T>(f: impl FnOnce(&cadmpeg_core::decode::DecodeContext<'_>) -> T) -> T {
        let arena = cadmpeg_core::decode::DecodeArena::new();
        let policy = cadmpeg_core::decode::DecodePolicy::service();
        let (ctx, _) =
            cadmpeg_core::decode::DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        f(&ctx)
    }

    fn owned_subtype_defs(toks: &[Token]) -> Option<Vec<(usize, &str)>> {
        with_ctx(|ctx| owned_subtype_defs_ctx(ctx, toks).transpose().unwrap())
    }

    fn owned_marker_positions(toks: &[Token]) -> Option<Vec<usize>> {
        with_ctx(|ctx| owned_marker_positions_ctx(ctx, toks).transpose().unwrap())
    }

    fn owned_construction_subtype(toks: &[Token]) -> Option<String> {
        with_ctx(|ctx| {
            owned_construction_subtype_ctx(ctx, toks)
                .transpose()
                .unwrap()
        })
    }

    #[test]
    fn owned_construction_subtype_refuses_retained_string_limit() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;

        let tokens = [
            Token::SubtypeOpen,
            Token::Ident("arbitrary".into()),
            Token::SubtypeClose,
        ];
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_retained_bytes = 8;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy)
            .expect("empty test input fits input limit");
        let error = owned_construction_subtype_ctx(&ctx, &tokens)
            .expect("subtype exists")
            .expect_err("subtype name exceeds retained limit");
        let CodecError::ResourceLimit(refusal) = error else {
            panic!("expected resource refusal, got {error:?}");
        };
        assert_eq!(refusal.dimension, ResourceDimension::RetainedBytes);
        assert_eq!(refusal.operation, "ASM construction subtype name");
    }

    fn cache_scope(toks: &[Token]) -> Option<&[Token]> {
        with_ctx(|ctx| cache_scope_ctx(ctx, toks).transpose().unwrap())
    }

    #[test]
    fn owned_marker_vector_refuses_collection_limit() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 0;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let tokens = [
            Token::SubtypeOpen,
            Token::Ident("nubs".into()),
            Token::SubtypeClose,
        ];
        let error = owned_marker_positions_ctx(&ctx, &tokens)
            .unwrap()
            .unwrap_err();
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal: {error:?}")
        };
        assert_eq!(limit.dimension, ResourceDimension::CollectionItems);
        assert_eq!(limit.operation, "ASM owned spline markers");
    }

    #[test]
    fn owned_subtype_vector_refuses_collection_limit() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 0;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let tokens = [
            Token::SubtypeOpen,
            Token::Ident("exactcur".into()),
            Token::SubtypeClose,
        ];
        let error = owned_subtype_defs_ctx(&ctx, &tokens).unwrap().unwrap_err();
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal: {error:?}")
        };
        assert_eq!(limit.dimension, ResourceDimension::CollectionItems);
        assert_eq!(limit.operation, "ASM owned subtype definitions");
    }

    #[test]
    fn cache_bearing_vector_refuses_collection_limit() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 2;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let tokens = [
            Token::SubtypeOpen,
            Token::Ident("exactcur".into()),
            Token::Ident("nubs".into()),
            Token::SubtypeClose,
        ];
        let error = cache_scope_ctx(&ctx, &tokens).unwrap().unwrap_err();
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal: {error:?}")
        };
        assert_eq!(limit.dimension, ResourceDimension::CollectionItems);
        assert_eq!(limit.operation, "ASM cache bearing scopes");
    }

    #[test]
    fn subtype_table_vector_refuses_collection_limit() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 0;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let record = crate::sab::Record {
            index: 0,
            name: "spline".into(),
            tokens: vec![
                Token::SubtypeOpen,
                Token::Ident("exactcur".into()),
                Token::SubtypeClose,
            ]
            .into(),
            offset: 0,
            len: 0,
        };
        let error = super::SubtypeTable::from_records(&ctx, &[record])
            .err()
            .expect("resource refusal");
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal: {error:?}")
        };
        assert_eq!(limit.dimension, ResourceDimension::CollectionItems);
        assert_eq!(limit.operation, "index ASM subtype definitions");
    }

    #[test]
    fn subtype_reference_walk_refuses_depth_before_following_next_definition() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;

        let records: Vec<crate::sab::Record> = (0..3)
            .map(|index| {
                let mut tokens = vec![Token::SubtypeOpen, Token::Ident("node".into())];
                if index < 2 {
                    tokens.extend([
                        Token::SubtypeOpen,
                        Token::Ident("ref".into()),
                        Token::Long(index + 1),
                        Token::SubtypeClose,
                    ]);
                }
                tokens.push(Token::SubtypeClose);
                crate::sab::Record {
                    index: usize::try_from(index).expect("test value fits"),
                    name: "node".into(),
                    tokens: tokens.into(),
                    offset: 0,
                    len: 0,
                }
            })
            .collect();
        let table = with_ctx(|ctx| super::SubtypeTable::from_records(ctx, &records).unwrap());
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_recursion_depth = 1;
        let (ctx, _) = DecodeContext::from_root_bytes(&[0], &arena, &policy).unwrap();
        let error = super::admit_subtype_references(&ctx, &records, &table)
            .expect_err("second followed reference exceeds depth one");
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal, got {error:?}");
        };
        assert_eq!(limit.dimension, ResourceDimension::RecursionDepth);
        assert_eq!(limit.operation, "follow ASM subtype reference");

        let arena = DecodeArena::new();
        let policy = DecodePolicy::service();
        let (ctx, _) = DecodeContext::from_root_bytes(&[0], &arena, &policy).unwrap();
        super::admit_subtype_references(&ctx, &records, &table)
            .expect("service profile admits finite chain");
    }

    #[test]
    fn subtype_reference_walk_refuses_work_before_following_reference() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;

        let tokens: std::sync::Arc<[Token]> = vec![
            Token::SubtypeOpen,
            Token::Ident("node".into()),
            Token::SubtypeOpen,
            Token::Ident("ref".into()),
            Token::Long(0),
            Token::SubtypeClose,
            Token::SubtypeClose,
        ]
        .into();
        let record = crate::sab::Record {
            index: 0,
            name: "node".into(),
            tokens,
            offset: 0,
            len: 0,
        };
        let records = [record];
        let table = with_ctx(|ctx| super::SubtypeTable::from_records(ctx, &records).unwrap());
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_work_units =
            cadmpeg_core::decode::u64_from_index(records[0].tokens.len());
        let (ctx, _) = DecodeContext::from_root_bytes(&[0], &arena, &policy).unwrap();
        let error = super::admit_subtype_references(&ctx, &records, &table)
            .expect_err("following the reference exceeds scan work");
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected resource refusal, got {error:?}");
        };
        assert_eq!(limit.dimension, ResourceDimension::WorkUnits);
        assert_eq!(limit.operation, "follow ASM subtype reference");
    }

    fn ident(name: &str) -> Token {
        Token::Ident(name.to_string())
    }

    #[test]
    fn bare_payload_admission_preserves_empty_and_single_token_payloads() {
        for width in [RefWidth::Four, RefWidth::Eight] {
            assert!(lex_test_span(&[], width).unwrap().is_empty());
            assert_eq!(&*lex_test_span(&[0x0a], width).unwrap(), &[Token::True]);
        }
    }

    #[test]
    fn bare_payload_admission_refuses_truncated_tokens() {
        for width in [RefWidth::Four, RefWidth::Eight] {
            assert!(lex_test_span(&[0x06], width).is_err());
            assert!(test_table(&[0x06], width).is_err());
        }
    }

    #[test]
    fn bare_payload_admission_refuses_an_extra_record() {
        for width in [RefWidth::Four, RefWidth::Eight] {
            let bytes = [0x11, 0x0d, 1, b'y'];
            let error = lex_test_span(&bytes, width).unwrap_err();
            assert!(error.reason.contains("2 records"), "{error}");
            assert!(test_table(&bytes, width).is_err());
        }
    }

    #[test]
    fn cursor_take_methods_do_not_advance_on_mismatch() {
        let toks = [Token::Double(2.5), Token::True, Token::Long(7)];
        let mut cur = Cur::at(&toks, 0);
        assert_eq!(cur.take_long(), None);
        assert_eq!(cur.take_f64(), Some(2.5));
        assert_eq!(cur.take_bool(), Some(true));
        assert_eq!(cur.take_long(), Some(7));
        assert_eq!(cur.bump(), None);
    }

    #[test]
    fn float_array_restores_position_on_a_truncated_body() {
        let arena = cadmpeg_core::decode::DecodeArena::new();
        let (ctx, _) = cadmpeg_core::decode::DecodeContext::from_root_bytes(
            &[],
            &arena,
            &cadmpeg_core::decode::DecodePolicy::default(),
        )
        .expect("test decode context");
        let toks = [Token::Long(2), Token::Double(1.0), Token::True];
        let mut cur = Cur::at(&toks, 0);
        assert_eq!(
            cur.take_float_array(&ctx)
                .transpose()
                .expect("resource allocation"),
            None
        );
        assert_eq!(cur.pos(), 0);
    }

    #[test]
    fn counted_float_array_refuses_collection_limit_before_reading_values() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;

        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 1;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let toks = [Token::Long(2), Token::Double(1.0), Token::Double(2.0)];
        let mut cur = Cur::at(&toks, 0);
        let error = cur
            .take_float_array(&ctx)
            .expect("counted float array")
            .expect_err("two floats exceed one item");
        let CodecError::ResourceLimit(limit) = error else {
            panic!("expected collection refusal: {error:?}");
        };
        assert_eq!(limit.dimension, ResourceDimension::CollectionItems);
        assert_eq!(cur.pos(), 1);
    }

    #[test]
    fn scope_end_requires_the_terminal_close() {
        let toks = [Token::SubtypeOpen, ident("x"), Token::SubtypeClose];
        assert!(Cur::at(&toks, 2).at_scope_end());
        assert!(!Cur::at(&toks, 1).at_scope_end());

        let trailing = [
            Token::SubtypeOpen,
            ident("x"),
            Token::SubtypeClose,
            Token::Double(1.0),
        ];
        assert!(!Cur::at(&trailing, 2).at_scope_end());
    }

    #[test]
    fn owned_defs_skip_nested_constructions() {
        // The ref belongs to the nested `ref` scope.
        let toks = [
            Token::SubtypeOpen,
            ident("exactcur"),
            Token::SubtypeOpen,
            ident("ref"),
            Token::Long(3),
            Token::SubtypeClose,
            Token::SubtypeClose,
        ];
        assert_eq!(owned_subtype_defs(&toks), Some(vec![(0, "exactcur")]));
        assert_eq!(subtype_refs(&toks).collect::<Vec<_>>(), vec![3]);
        assert_eq!(
            owned_construction_subtype(&toks),
            Some("exact_int_cur".to_string())
        );
        assert_eq!(
            subtype_span(&toks, 2).map(|scope| scope.tokens()),
            Some(&toks[2..=5])
        );
    }

    #[test]
    fn owned_markers_ignore_nested_scopes_and_a_leading_open() {
        let toks = [
            Token::SubtypeOpen,
            ident("nubs"),
            Token::SubtypeOpen,
            ident("nurbs"),
            Token::SubtypeClose,
        ];
        // Leading open is the span's own scope: the first `nubs` is owned, the
        // `nurbs` inside the nested scope is not.
        assert_eq!(owned_marker_positions(&toks), Some(vec![1]));
        assert_eq!(marker_at(&toks, 1), Some(BsplineMarker::Nubs));
        assert_eq!(marker_at(&toks, 3), Some(BsplineMarker::Nurbs));
    }

    #[test]
    fn a_scope_yields_its_owned_markers_with_no_refusal_to_answer() {
        // Two nested constructions inside one scope. The call binds a
        // `Vec<usize>` directly: `SubtypeScope::owned_marker_positions` states
        // no `Option`, because the type has already proven the balance the
        // raw-stream walk refuses.
        let toks = [
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nubs"),
            Token::SubtypeOpen,
            ident("ref"),
            Token::SubtypeOpen,
            ident("nurbs"),
            Token::SubtypeClose,
            Token::SubtypeClose,
            ident("nurbs"),
            Token::SubtypeClose,
        ];
        let scope = subtype_span(&toks, 0).expect("balanced scope");
        let owned: Vec<usize> = with_ctx(|ctx| scope.owned_marker_positions(ctx).unwrap());
        assert_eq!(owned, vec![2, 9]);
        assert_eq!(scope.tokens(), &toks[..]);
    }

    /// A scope opens at its own `SubtypeOpen`. An index that names another
    /// token names no scope, so `interior()` is total by construction: the
    /// constructor never hands back a span whose first token is not the open.
    #[test]
    fn a_span_that_does_not_open_at_start_is_not_a_scope() {
        let toks = [
            ident("x"),
            Token::SubtypeOpen,
            ident("exactcur"),
            Token::SubtypeClose,
        ];

        assert_eq!(subtype_span(&toks, 0), None);
        assert_eq!(subtype_span(&toks, 2), None);
        assert_eq!(subtype_span(&toks, 3), None);
        assert_eq!(subtype_span(&toks, 4), None);
        let scope = subtype_span(&toks, 1).expect("balanced scope");
        assert_eq!(scope.tokens(), &toks[1..=3]);
        assert_eq!(scope.interior(), &toks[2..3]);
    }

    #[test]
    fn a_first_nested_scope_does_not_own_the_outer_scopes_markers() {
        // The interior opens with a nested marker-bearing construction. Only
        // the outer scope's own `nurbs` is directly owned; the nested `nubs`
        // belongs to the nested construction (`docs/formats/asm.md:395`).
        let toks = [
            Token::SubtypeOpen,
            ident("exactcur"),
            Token::SubtypeOpen,
            ident("support"),
            ident("nubs"),
            Token::SubtypeClose,
            ident("nurbs"),
            Token::SubtypeClose,
        ];
        let scope = subtype_span(&toks, 0).expect("balanced scope");
        assert_eq!(
            with_ctx(|ctx| scope.owned_marker_positions(ctx).unwrap()),
            vec![6]
        );
        assert_eq!(scope.interior(), &toks[1..7]);

        // The slice after the scope's name token opens with the nested scope,
        // so the free walk skips that nested open and reports the nested
        // marker as owned. That is the shape the scope type replaces.
        assert_eq!(owned_marker_positions(&toks[2..7]), Some(vec![2, 4]));
    }

    #[test]
    fn one_cache_bearing_scope_is_the_cache_scope_and_two_are_ambiguous() {
        // `exactcur` owns a `nubs` marker; the `ref` scope is skipped by name.
        let one = [
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nubs"),
            Token::SubtypeClose,
            Token::SubtypeOpen,
            ident("ref"),
            Token::Long(3),
            Token::SubtypeClose,
        ];
        assert_eq!(cache_scope(&one), Some(&one[0..=3]));

        // A second scope owning a marker leaves no unique carrier.
        let two = [
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nubs"),
            Token::SubtypeClose,
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nurbs"),
            Token::SubtypeClose,
        ];
        assert_eq!(cache_scope(&two), None);

        // A scope owning no marker is not a candidate, and leaves the one
        // that does as the answer.
        let bare = [
            Token::SubtypeOpen,
            ident("exactcur"),
            Token::SubtypeClose,
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nubs"),
            Token::SubtypeClose,
        ];
        assert_eq!(cache_scope(&bare), Some(&bare[3..=6]));
    }

    #[test]
    fn an_unbalanced_close_refuses_the_cache_scope_rather_than_moving_to_another() {
        // The stream states one close more than it opens, so no scope is
        // chosen at all.
        let toks = [
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nubs"),
            Token::SubtypeClose,
            Token::SubtypeClose,
            Token::SubtypeOpen,
            ident("exactcur"),
            ident("nurbs"),
            Token::SubtypeClose,
        ];
        assert_eq!(owned_subtype_defs(&toks), None);
        assert_eq!(cache_scope(&toks), None);
    }

    #[test]
    fn one_unbalanced_close_refuses_the_owned_walks() {
        // One close more than the stream opens. Everything after it sits
        // outside every scope, so a walk that pinned the depth at zero
        // reported the trailing `nurbs` as a marker this span owns.
        let toks = [
            Token::SubtypeOpen,
            ident("exactcur"),
            Token::SubtypeOpen,
            ident("ref"),
            Token::SubtypeClose,
            Token::SubtypeClose,
            Token::SubtypeClose,
            ident("nurbs"),
        ];
        assert_eq!(owned_marker_positions(&toks), None);
        assert_eq!(owned_subtype_defs(&toks), None);
    }
    #[test]
    fn subtype_table_walks_wide_strings_at_the_stream_ref_width() {
        fn t_ident(b: &mut Vec<u8>, s: &str) {
            b.push(0x0d);
            b.push(u8::try_from(s.len()).expect("test value fits"));
            b.extend_from_slice(s.as_bytes());
        }

        for ref_width in [
            crate::kernel_header::RefWidth::Four,
            crate::kernel_header::RefWidth::Eight,
        ] {
            // The last four payload bytes spell a definition opening. Only a walker
            // that consumes the length prefix at `ref_width` steps past them.
            let payload = [b'0', b'1', b'2', b'3', 0x0f, 0x0d, 0x01, b'x'];

            let mut active = Vec::new();
            t_ident(&mut active, "tspl");
            active.push(0x09);
            active.extend_from_slice(&payload.len().to_le_bytes()[..ref_width.bytes()]);
            active.extend_from_slice(&payload);
            active.extend_from_slice(b"\x0f\x0d\x08real_def\x10");
            active.push(0x11);

            let records = crate::test_support::sab::frame(&active, 0, active.len(), ref_width)
                .expect("wide-string record frames at its declared width");
            let table = with_ctx(|ctx| super::SubtypeTable::from_records(ctx, &records).unwrap());
            assert_eq!(table.defs.len(), 1);
            assert!(matches!(table.span(0).expect("real definition").tokens(),
            [Token::SubtypeOpen, Token::Ident(name), Token::SubtypeClose] if name == "real_def"));
        }
    }
}