Repository navigation
Expand file tree
/
Copy pathrust_type.rs
More file actions
4022 lines (3814 loc) · 190 KB
/
Copy pathrust_type.rs
File metadata and controls
4022 lines (3814 loc) · 190 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 rust type vocabulary (`RustType`/`ConceptualRustType` and friends).
//!
//! Known exceptions to the intermediate->generation module boundary: the type-naming methods here
//! reach back into `generation` — the `table_type` import below and the
//! `crate::generation::rust_crate_struct_from_wasm` calls in `for_rust_member_ct`/`name_for_rust_map`.
//! Full inversion is a bigger job (the `from_wasm` flag threads through type naming), so these stay
//! as the boundary's documented leaks rather than being "fixed" here.
use super::*;
use crate::{generation::table_type, rust_reserved::RUST_KEYWORDS, utils::is_valid_rust_ident};
use std::num::NonZeroU32;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Representation {
Array,
Map,
}
#[derive(Clone, Debug, PartialEq)]
pub enum FixedValue {
Null,
Undefined,
Bool(bool),
Nint(i128),
Uint(u64),
Float(f64),
Text(String),
/// A decoded CDDL byte-string literal. Keep bytes, rather than a source spelling, so h'…'
/// and '…' share the wire identity and non-text values never pass through UTF-8.
Bytes(Vec<u8>),
}
fn convert_to_alphanumeric(input: &str) -> String {
input
.chars()
.filter(|c| c.is_ascii_alphanumeric())
.collect()
}
impl FixedValue {
/// A typed, owned Rust byte-vector literal. The explicit carrier is needed for `h''`, whose
/// bare `vec![]` has no element type in generated serialization code.
pub fn bytes_rust_expr(bytes: &[u8]) -> String {
format!("Vec::<u8>::from({bytes:?})")
}
/// A total, Rust-identifier-safe spelling for a nominal fixed-value singleton. This is an
/// identity, not a display label: text uses UTF-8 bytes and floats use their IEEE bits so that
/// values which happen to print alike (notably `-0.0`) cannot share an owner.
pub fn singleton_name_fragment(&self) -> String {
match self {
Self::Null => "Null".to_owned(),
Self::Undefined => "Undefined".to_owned(),
Self::Bool(true) => "BoolTrue".to_owned(),
Self::Bool(false) => "BoolFalse".to_owned(),
Self::Uint(value) => format!("Uint{value}"),
Self::Nint(value) => format!("Nint{}", value.unsigned_abs()),
Self::Float(value) => format!("Float{:016X}", value.to_bits()),
Self::Text(value) if value.is_empty() => "TextEmpty".to_owned(),
Self::Text(value) => format!(
"Text{}",
value
.as_bytes()
.iter()
.map(|byte| format!("{byte:02X}"))
.collect::<String>()
),
Self::Bytes(value) if value.is_empty() => "BytesEmpty".to_owned(),
Self::Bytes(value) => format!(
"Bytes{}",
value
.iter()
.map(|byte| format!("{byte:02X}"))
.collect::<String>()
),
}
}
/// The choice-arm spelling keeps each established, spellable public name. A fixed literal
/// whose old display-derived spelling cannot be emitted as a Rust variant uses the canonical
/// fixed-value identity instead: it is total, kind-prefixed, and value-exact for floats/text.
/// This is deliberately here, at the one fixed-value minter shared by type and group choices,
/// rather than a parser-side repair at either consumer.
fn for_variant(&self) -> VariantIdent {
let legacy = match self {
FixedValue::Null => VariantIdent::new_custom("Null"),
FixedValue::Undefined => VariantIdent::new_custom("Undefined"),
FixedValue::Bool(b) => VariantIdent::new_custom(match b {
true => "True",
false => "False",
}),
FixedValue::Nint(i) => VariantIdent::new_custom(format!("U{i}")),
FixedValue::Uint(u) => VariantIdent::new_custom(format!("I{u}")),
FixedValue::Float(f) => VariantIdent::new_custom(format!("F{f}")),
FixedValue::Text(s) => {
VariantIdent::new_custom(convert_to_alphanumeric(&convert_to_camel_case(s)))
}
FixedValue::Bytes(bytes) if bytes.is_empty() => VariantIdent::new_custom("BytesEmpty"),
FixedValue::Bytes(bytes) => VariantIdent::new_custom(format!(
"Bytes{}",
bytes
.iter()
.map(|byte| format!("{byte:02X}"))
.collect::<String>()
)),
}
.to_string();
if is_valid_rust_ident(&legacy) && !RUST_KEYWORDS.contains(&legacy.as_str()) {
VariantIdent::new_custom(legacy)
} else {
VariantIdent::new_custom(self.singleton_name_fragment())
}
}
// `pub(crate)`: the codegen-time canonical key merge for open struct-maps
// (`generation/records.rs`) renders a declared field's canonical key bytes as a `vec![..]`
// literal, fed to the same length-first comparator the runtime uses — so an open struct and its
// closed equivalent canonicalize identically.
pub(crate) fn to_bytes(&self) -> Vec<u8> {
let mut buf = cbor_event::se::Serializer::new_vec();
match self {
FixedValue::Null => buf.write_special(cbor_event::Special::Null),
FixedValue::Undefined => buf.write_special(cbor_event::Special::Undefined),
FixedValue::Bool(b) => buf.write_special(cbor_event::Special::Bool(*b)),
// Nint holds i128, whose values below i64::MIN don't fit the plain
// write_negative_integer endpoint's i64 argument; the _sz form
// takes i128 and encodes the full CBOR nint range. Passing Sz::canonical(magnitude)
// reproduces the default endpoint's byte-for-byte canonical layout (write_type_definite
// derives the same Sz from the magnitude when no Sz is supplied).
FixedValue::Nint(i) => {
let magnitude = (-(*i + 1)) as u64;
buf.write_negative_integer_sz(*i, cbor_event::Sz::canonical(magnitude))
}
FixedValue::Uint(u) => buf.write_unsigned_integer(*u),
FixedValue::Float(f) => buf.write_special(Special::Float(*f)),
FixedValue::Text(s) => buf.write_text(s),
FixedValue::Bytes(bytes) => buf.write_bytes(bytes),
}
.expect("Unable to serialize key for canonical ordering");
buf.finalize()
}
/// Converts a literal to a valid rust expression capable of initializing a Primitive
/// e.g. Text is an actual String, etc
pub fn to_primitive_str_assign(&self) -> String {
match self {
FixedValue::Null => "None".to_owned(),
// `undefined` has no Rust primitive representation. This helper only serves the
// primitive-default/comparison paths, which reject it before rendering an expression.
FixedValue::Undefined => unreachable!("undefined is not a Rust primitive"),
FixedValue::Bool(b) => b.to_string(),
FixedValue::Nint(i) => i.to_string(),
FixedValue::Uint(u) => u.to_string(),
// `{:?}`, not Display: Display on a whole-valued f64 drops the decimal point
// (3.0 -> "3"), rendering an integer literal in a float position (E0308). Debug
// round-trips (3.0 -> "3.0"); unsuffixed so the literal also types as f32 where
// the target is f32.
FixedValue::Float(f) => format!("{f:?}"),
FixedValue::Text(s) => format!("\"{}\".to_owned()", escape_rust_str(s)),
FixedValue::Bytes(bytes) => Self::bytes_rust_expr(bytes),
}
}
/// How the value is spelled in CDDL SOURCE, for rejection messages the user reads against
/// their own spec (`5`, `true`, `null`, `"v1"`) — not the rust-literal renderings above, whose
/// escaping / `to_owned()` framing belongs to emitted code. Every message naming a bare fixed
/// value routes through this one helper so the alias-position and member-position rejections
/// can't drift in how they quote the value back.
pub fn cddl_source_desc(&self) -> String {
match self {
FixedValue::Null => "null".to_owned(),
FixedValue::Undefined => "undefined".to_owned(),
FixedValue::Bool(b) => b.to_string(),
FixedValue::Nint(i) => i.to_string(),
FixedValue::Uint(u) => u.to_string(),
// `{:?}`, not Display: Display on a whole-valued f64 drops the decimal point, which
// would quote `3.0` back to the user as `3`.
FixedValue::Float(f) => format!("{f:?}"),
FixedValue::Text(s) => format!("\"{s}\""),
FixedValue::Bytes(bytes) => format!(
"h'{}'",
bytes
.iter()
.map(|byte| format!("{byte:02X}"))
.collect::<String>()
),
}
}
/// Converts a literal to a valid rust comparison valid for comparisons
/// e.g. Text can be &str to avoid creating a String
pub fn to_primitive_str_compare(&self) -> String {
match self {
FixedValue::Text(s) => format!("\"{}\"", escape_rust_str(s)),
FixedValue::Bytes(_) => self.to_primitive_str_assign(),
_ => self.to_primitive_str_assign(),
}
}
}
impl RustType {
/// The one semantic recognition of an exact CDDL byte-string length. `.size N` is parsed as
/// an equal bounds window, except that the non-negative zero lower endpoint is normalized
/// away by `with_value_bounds`. A plain upper bound (`bytes .le N`) is deliberately not exact.
///
/// Rust array lengths are emitted as `usize` literals. CDDL's source integer is wider, so a
/// non-representable value is left for the parser's graceful-rejection owner rather than being
/// truncated here.
pub fn exact_byte_array_len(&self) -> Option<Result<usize, i128>> {
if !matches!(
self.conceptual_type.resolve_alias_shallow(),
ConceptualRustType::Primitive(Primitive::Bytes)
) {
return None;
}
exact_array_len_from_bounds(self.config.value_bounds())
}
/// The checked, already parser-validated exact byte length used by generated type spelling.
/// A failed conversion is an input rejection, never an invitation to silently widen to Vec.
pub fn exact_byte_array_len_checked(&self) -> Option<usize> {
self.exact_byte_array_len().map(|result| {
result.expect("exact byte array length must be validated before generation")
})
}
pub(crate) fn collection_view(&self) -> CollectionTypeView<'_> {
CollectionTypeView::new(&self.conceptual_type, &self.config)
}
/// The one semantic recognition of an exact homogeneous CDDL array occurrence. As with an
/// exact byte `.size`, CDDL normalizes the zero lower endpoint away, so both `0*0` and `*0`
/// arrive as `(None, Some(0))`. Unlike bytes this is an occurrence constraint, and unlike a
/// reject-duplicates set its cardinality is the *only* invariant: `[T; N]` cannot encode a
/// wrong length but cannot encode uniqueness either.
///
/// This is alias-aware for invariant decisions. Raw spelling decisions keep using the
/// conceptual-array check at their own seam so an authored alias remains an alias at a member
/// site.
pub fn exact_homogeneous_array_len(&self) -> Option<Result<usize, i128>> {
self.collection_view().exact_array_len()
}
/// The checked, parser-validated static-array length used by generated Rust spelling.
pub fn exact_homogeneous_array_len_checked(&self) -> Option<usize> {
self.exact_homogeneous_array_len().map(|result| {
result.expect("exact homogeneous array length must be validated before generation")
})
}
/// Whether this type contains a native exact array wider than the pinned serde/schemars trait
/// implementations. This is independent of its JSON position; callers decide whether an
/// adapter owns that position or it must be refused before code generation.
pub fn contains_wide_static_array(&self) -> bool {
const PINNED_ARRAY_TRAIT_MAX: usize = 32;
fn contains_wide_static_array(ty: &RustType) -> bool {
ty.exact_homogeneous_array_len_checked()
.is_some_and(|len| len > PINNED_ARRAY_TRAIT_MAX)
|| match ty.conceptual_type.resolve_alias_shallow() {
ConceptualRustType::Array(inner) | ConceptualRustType::Optional(inner) => {
contains_wide_static_array(inner)
}
ConceptualRustType::Map(key, value) => {
contains_wide_static_array(key) || contains_wide_static_array(value)
}
_ => false,
}
}
contains_wide_static_array(self)
}
/// Whether this JSON-derived type would require serde/schemars traits on a wide (`> 32`)
/// native exact array at a position our generated adapters do not yet own. The adapters cover
/// a direct static array plus every loose, nonempty, or bounded sequence/set tree and map-value
/// tree. Object-map keys remain deliberately outside that ownership: JSON member names cannot
/// faithfully carry a native exact array. Pair maps are positional, so both sides are owned.
/// Keep this shape
/// predicate in the IR, beside the carrier recognition,
/// so a graceful parser/finalize refusal and the roadmap describe the same boundary.
pub fn has_unadapted_wide_static_array_json_shape(&self) -> bool {
fn supported_tree(ty: &RustType) -> bool {
match ty.conceptual_type.resolve_alias_shallow() {
ConceptualRustType::Array(inner) => supported_tree(inner),
ConceptualRustType::Optional(inner) => supported_tree(inner),
ConceptualRustType::Map(key, value) => {
(ty.is_preserve_pair_map()
|| (!key.contains_wide_static_array()
&& !key.contains_exact_natural_any_static_array()))
&& supported_tree(key)
&& supported_tree(value)
}
_ => true,
}
}
if !self.contains_wide_static_array() {
return false;
}
!supported_tree(self)
}
/// Whether this type contains an exact static array whose leaf element is CDDL `any`. Such an
/// array always needs a natural-JSON adapter: the typed serde/schema impl for `AnyCbor` is
/// deliberately tagged instead. Keep the recognition in the IR so the adapter selection and
/// its pre-codegen refusal boundary cannot drift.
pub fn contains_exact_natural_any_static_array(&self) -> bool {
fn walk(ty: &RustType, under_exact: bool) -> bool {
match ty.conceptual_type.resolve_alias_shallow() {
ConceptualRustType::Any => under_exact,
ConceptualRustType::Array(inner) => walk(
inner,
under_exact || ty.exact_homogeneous_array_len_checked().is_some(),
),
ConceptualRustType::Optional(inner) => walk(inner, under_exact),
// Maps are deliberately traversed for DETECTION: a natural-any descendant under an
// exact ancestor must reach the map/set JSON boundary refusal, not silently fall
// through to AnyCbor's tagged codec.
ConceptualRustType::Map(key, value) => {
walk(key, under_exact) || walk(value, under_exact)
}
_ => false,
}
}
walk(self, false)
}
/// Natural JSON has a separate adapter family for an exact static array whose ELEMENT is CDDL
/// `any`. A direct `[any; N]`, every sequence/set tree, and map-value tree are owned by the
/// recursive descriptor. Object-map keys remain refused; pair-map keys are positional and are
/// adapted too rather than falling back to `AnyCbor`'s tagged serde/schema implementation.
pub fn has_unadapted_natural_any_static_array_json_shape(&self) -> bool {
fn supported_tree(ty: &RustType) -> bool {
match ty.conceptual_type.resolve_alias_shallow() {
ConceptualRustType::Array(inner) => supported_tree(inner),
ConceptualRustType::Optional(inner) => supported_tree(inner),
ConceptualRustType::Map(key, value) => {
(ty.is_preserve_pair_map()
|| (!key.contains_wide_static_array()
&& !key.contains_exact_natural_any_static_array()))
&& supported_tree(key)
&& supported_tree(value)
}
_ => true,
}
}
self.contains_exact_natural_any_static_array() && !supported_tree(self)
}
/// Exact-array endpoints in the legacy occurrence-wrapper vocabulary. This is only for
/// preserving the established wasm structural class identity (`U64ListMin3Max3`); the native
/// carrier itself is `[T; 3]`, not `BoundedVec<T, 3, 3>`.
pub fn exact_homogeneous_array_u64_bounds(&self) -> Option<(u64, u64)> {
let len = self.exact_homogeneous_array_len_checked()?;
let len = u64::try_from(len).expect("portable Rust array length fits u64");
Some((len, len))
}
/// A total, identifier-safe spelling of the configuration that changes this type's semantic
/// identity. Synthesized nominals append this to an otherwise historic structural spelling:
/// the empty configuration remains empty, so existing unconstrained names stay stable.
///
/// Delimit every field and encode signed/float values without punctuation. This is an
/// identity rather than a display name: two type arguments that serialize or constrain values
/// differently must never choose one generated owner based on parse order.
fn canonical_config_identity_suffix(&self) -> String {
let mut out = String::new();
for operation in &self.encodings {
match operation {
CBOREncodingOperation::Tagged(tag) => out.push_str(&format!("__Tag{tag}")),
CBOREncodingOperation::OptionallyTagged(tag) => {
out.push_str(&format!("__OptionalTag{tag}"));
}
CBOREncodingOperation::CBORBytes => out.push_str("__CborBytes"),
}
}
if let Some(default) = &self.config.default {
out.push_str("__Default");
out.push_str(&default.singleton_name_fragment());
}
let endpoint = |value: Option<i128>| match value {
None => "None".to_owned(),
Some(value) if value < 0 => format!("Neg{}", value.unsigned_abs()),
Some(value) => format!("Pos{value}"),
};
if let Some((min, max)) = self.config.raw_bounds() {
out.push_str(&format!("__BoundsMin{}Max{}", endpoint(min), endpoint(max)));
}
if let Some((min, max)) = self.config.float_bounds {
let endpoint = |value: Option<(f64, bool)>| match value {
Some((value, exclusive)) => format!(
"Some{:016X}{}",
value.to_bits(),
if exclusive { "Exclusive" } else { "Inclusive" }
),
None => "None".to_owned(),
};
out.push_str(&format!(
"__FloatBoundsMin{}Max{}",
endpoint(min),
endpoint(max)
));
}
if let Some(policy) = self.config.duplicates {
out.push_str(match policy {
DuplicatesPolicy::Preserve => "__DuplicatesPreserve",
DuplicatesPolicy::Reject => "__DuplicatesReject",
});
}
if self.config.basic_override {
out.push_str("__BasicOverride");
}
out
}
/// A total identifier fragment for a synthesized nominal fixed-value owner. It includes the
/// entire wire shape, not merely the CBOR value: `true` and `#6.7(true)` are distinct Rust
/// values with distinct codecs, and must never deduplicate to one owner based on parse order.
///
/// This deliberately spells the small, closed encoding-operation vocabulary rather than using
/// a hash. The spelling is injective (and therefore cannot turn a hash collision into a
/// silent wire change), Rust-identifier-safe, and preserves the historic bare-value names.
pub fn fixed_singleton_name_fragment(&self) -> String {
let fixed = match self.conceptual_type.resolve_alias_shallow() {
ConceptualRustType::Fixed(fixed) => fixed,
other => panic!("fixed singleton name requested for {other:?}"),
};
let mut out = fixed.singleton_name_fragment();
// Fixed values normally have default config, but retaining every field makes this identity
// correct if a future fixed-value control operator attaches one.
for operation in &self.encodings {
match operation {
CBOREncodingOperation::Tagged(tag) => out.push_str(&format!("__Tag{tag}")),
CBOREncodingOperation::OptionallyTagged(tag) => {
out.push_str(&format!("__OptionalTag{tag}"));
}
CBOREncodingOperation::CBORBytes => out.push_str("__CborBytes"),
}
}
if let Some(default) = &self.config.default {
out.push_str("__Default");
out.push_str(&default.singleton_name_fragment());
}
if let Some((min, max)) = self.config.raw_bounds() {
out.push_str(&format!(
"__Bounds{}_{}",
min.map_or_else(|| "None".to_owned(), |value| format!("Some{value}")),
max.map_or_else(|| "None".to_owned(), |value| format!("Some{value}")),
));
}
if let Some((min, max)) = self.config.float_bounds {
let bound = |value: Option<(f64, bool)>| match value {
Some((value, exclusive)) => format!(
"Some{:016X}{}",
value.to_bits(),
if exclusive { "Exclusive" } else { "Inclusive" }
),
None => "None".to_owned(),
};
out.push_str(&format!("__FloatBounds{}_{}", bound(min), bound(max)));
}
if let Some(policy) = self.config.duplicates {
out.push_str(&format!("__Duplicates{policy:?}"));
}
if self.config.basic_override {
out.push_str("__BasicOverride");
}
out
}
/// A canonical, occurrence-aware generic-argument identity fragment. `for_variant()` remains
/// the base, retaining every historic unconstrained spelling (`1` stays `I1`); a deterministic
/// path-qualified decoration walk records every codec/config distinction that the base omits.
/// That makes `[ *5 [* uint] ]` and `[* [*5 uint]]` distinct rather than merely suffixing the
/// whole tree ambiguously.
///
/// An authored alias remains opaque: `set<xs_int>` and `set<[* int]>` deliberately have
/// different nominal identities even when `xs_int` resolves to that shape. The alias's OWN
/// config is still recorded, but its target is not structurally merged into this spelling.
pub fn generic_argument_identity_fragment(&self) -> String {
fn append_config_identity(ty: &RustType, path: &str, out: &mut String) {
let suffix = ty.canonical_config_identity_suffix();
if !suffix.is_empty() {
out.push_str("__");
out.push_str(path);
out.push_str(suffix.trim_start_matches("__"));
}
match &ty.conceptual_type {
ConceptualRustType::Array(inner) => {
append_config_identity(inner, &format!("{path}ArrayElement"), out)
}
ConceptualRustType::Optional(inner) => {
append_config_identity(inner, &format!("{path}OptionalInner"), out)
}
ConceptualRustType::Map(key, value) => {
append_config_identity(key, &format!("{path}MapKey"), out);
append_config_identity(value, &format!("{path}MapValue"), out);
}
// The authored spelling is identity for generic arguments. Do not recurse through
// an alias: that would merge it with an inline structural spelling.
ConceptualRustType::Alias(_, _)
| ConceptualRustType::Fixed(_)
| ConceptualRustType::Primitive(_)
| ConceptualRustType::Rust(_)
| ConceptualRustType::Any => {}
}
}
let mut out = self.conceptual_type.for_variant().to_string();
append_config_identity(self, "", &mut out);
out
}
}
/// Checked `u64` form of an occurrence window: an absent minimum is `0`, an absent maximum is
/// `u64::MAX`, and a window whose endpoints do not fit or whose minimum exceeds its maximum is
/// `None`. Occurrence endpoints are non-negative parse quantities; the checked conversion keeps a
/// future wider parser carrier from being silently truncated.
pub(crate) fn occurrence_window_u64((min, max): IntWindow) -> Option<(u64, u64)> {
let min = u64::try_from(min.unwrap_or(0)).ok()?;
let max = max.map(u64::try_from).transpose().ok()?.unwrap_or(u64::MAX);
(min <= max).then_some((min, max))
}
/// Inclusive `u64` window held by a type-enforced bounded carrier. Loose `*`, NonEmpty `+`,
/// exact occurrences (according to the caller's static-carrier verdict), and invalid windows
/// have no bounded carrier.
pub(crate) fn type_enforced_bounded_window(bounds: IntWindow, exact: bool) -> Option<(u64, u64)> {
let window = OccurrenceWindow::from_raw(bounds);
if exact || window.is_loose() || window.is_non_empty() {
return None;
}
window.checked_u64()
}
/// The occurrence-window suffix of a structural wasm class name: `{infix}Max{max}` for a zero
/// minimum, `{infix}Min{min}` for an unbounded maximum (including `(0, u64::MAX)`, which renders as
/// `Min0`), and `{infix}Min{min}Max{max}` otherwise.
fn window_name_suffix(infix: &str, min: u64, max: u64) -> String {
match (min, max == u64::MAX) {
(0, false) => format!("{infix}Max{max}"),
(_, true) => format!("{infix}Min{min}"),
_ => format!("{infix}Min{min}Max{max}"),
}
}
/// Bounds-only half of the exact static-array recognizers. Primitive decode owns only a copied
/// config window, so keep the tuple interpretation here instead of duplicating it there.
pub fn exact_array_len_from_bounds(bounds: Option<IntWindow>) -> Option<Result<usize, i128>> {
let (min, max) = bounds?;
let exact = match (min, max) {
(Some(min), Some(max)) if min == max => min,
(None, Some(0)) => 0,
_ => return None,
};
// Generated crates are checked for wasm32 as well as the generator host. Rust requires an
// array layout/object size to fit target `isize`, so use the shared 32-bit `isize::MAX` floor
// rather than accepting host-only or layout-invalid consts.
// A negative window is never a byte-string size, even though it can fit in an `i32`.
// Check the semantic lower bound before the representation conversion: casting `-1_i32`
// to `usize` would otherwise produce a host-sized, silently enormous array length.
Some(
(0..=i128::from(i32::MAX))
.contains(&exact)
.then_some(exact as usize)
.ok_or(exact),
)
}
/// Const-generic argument for a bounded carrier's upper bound. `u64::MAX` is not a literal token, so
/// the unbounded case must be a braced const expression.
pub(crate) fn bound_const_arg(max: u64) -> String {
if max == u64::MAX {
"{ u64::MAX }".to_owned()
} else {
max.to_string()
}
}
#[cfg(test)]
mod exact_byte_array_len_tests {
use super::*;
#[test]
fn bounded_window_helper_matches_the_carrier_rules() {
assert_eq!(
type_enforced_bounded_window((Some(2), Some(5)), false),
Some((2, 5))
);
for bounds in [(None, None), (Some(1), None), (Some(3), Some(3))] {
assert_eq!(
type_enforced_bounded_window(bounds, bounds == (Some(3), Some(3))),
None
);
}
assert_eq!(
type_enforced_bounded_window((Some(3), Some(2)), false),
None
);
assert_eq!(
type_enforced_bounded_window((None, Some(3)), false),
Some((0, 3))
);
}
#[test]
fn tagged_bounds_keep_legacy_debug_and_distinct_roles() {
for raw in [
(None, None),
(Some(0), Some(i128::from(u64::MAX))),
(Some(1), None),
IntBounds::exclusion(-1),
(Some(-2), Some(-3)),
] {
let value = TypeBounds::Value(ValueWindow::from_raw(raw));
let occurrence = TypeBounds::Occurrence(OccurrenceWindow::from_raw(raw));
assert_ne!(
value, occurrence,
"equal endpoints cannot erase their semantic role"
);
assert_eq!(format!("{:?}", Some(value)), format!("{:?}", Some(raw)));
assert_eq!(
format!("{:#?}", Some(occurrence)),
format!("{:#?}", Some(raw))
);
let cfg = RustTypeSerializeConfig {
bounds: Some(occurrence),
..Default::default()
};
assert_eq!(cfg.value_bounds(), None);
assert_eq!(cfg.occurrence_bounds(), Some(raw));
}
let row = RestOccurrenceWindow::from_raw((1, u64::MAX));
assert_eq!(
format!("{:#?}", Some(row)),
format!("{:#?}", Some((1_u64, u64::MAX)))
);
}
#[test]
fn authored_max_and_invalid_windows_keep_carrier_identity() {
let inner = || RustType::new(ConceptualRustType::Primitive(Primitive::U64));
let array = |window| {
RustType::new(ConceptualRustType::Array(Box::new(inner())))
.with_occurrence_bounds(window)
};
assert!(array((Some(1), None)).is_non_empty_array());
assert!(array((Some(1), Some(i128::from(u64::MAX)))).is_bounded_array());
assert!(array((Some(0), Some(i128::from(u64::MAX)))).is_bounded_array());
assert_eq!(
OccurrenceWindow::from_raw((Some(-1), Some(2))).checked_u64(),
None
);
assert_eq!(
OccurrenceWindow::from_raw((Some(3), Some(2))).checked_u64(),
None
);
// A raw factory does not turn inverted occurrence into the scalar exclusion interpretation.
assert_eq!(
OccurrenceWindow::from_raw(IntBounds::exclusion(-1)).raw(),
(Some(0), Some(-2))
);
}
#[test]
fn recognizes_only_size_windows_including_normalized_zero_and_wasm_limit() {
let exact = |bounds| {
RustType::new(ConceptualRustType::Primitive(Primitive::Bytes)).with_value_bounds(bounds)
};
assert_eq!(
exact((Some(4), Some(4))).exact_byte_array_len(),
Some(Ok(4))
);
assert_eq!(
exact((Some(0), Some(0))).exact_byte_array_len(),
Some(Ok(0))
);
assert_eq!(exact((None, Some(4))).exact_byte_array_len(), None);
assert_eq!(
exact((Some(-1), Some(-1))).exact_byte_array_len(),
Some(Err(-1))
);
assert_eq!(
exact((Some(33), Some(33))).exact_byte_array_len(),
Some(Ok(33))
);
assert_eq!(
exact((
Some(i128::from(i32::MAX) + 1),
Some(i128::from(i32::MAX) + 1)
))
.exact_byte_array_len(),
Some(Err(i128::from(i32::MAX) + 1))
);
}
#[test]
fn exact_homogeneous_arrays_are_static_but_bytes_and_reject_sets_are_not() {
let array = |bounds| {
RustType::new(ConceptualRustType::Array(Box::new(RustType::new(
ConceptualRustType::Primitive(Primitive::U64),
))))
.with_occurrence_bounds(bounds)
};
assert_eq!(
array((Some(3), Some(3))).exact_homogeneous_array_len(),
Some(Ok(3))
);
assert_eq!(
array((Some(0), Some(0))).exact_homogeneous_array_len(),
Some(Ok(0))
);
assert_eq!(array((None, Some(3))).exact_homogeneous_array_len(), None);
assert_eq!(
array((
Some(i128::from(i32::MAX) + 1),
Some(i128::from(i32::MAX) + 1)
))
.exact_homogeneous_array_len(),
Some(Err(i128::from(i32::MAX) + 1))
);
let reject =
array((Some(3), Some(3))).with_duplicates_policy(Some(DuplicatesPolicy::Reject));
assert_eq!(reject.exact_homogeneous_array_len(), None);
let bytes = RustType::new(ConceptualRustType::Primitive(Primitive::Bytes))
.with_value_bounds((Some(3), Some(3)));
assert_eq!(bytes.exact_homogeneous_array_len(), None);
}
}
#[cfg(test)]
mod collection_view_tests {
use super::*;
fn collection(map: bool, bounds: IntWindow, duplicates: Option<DuplicatesPolicy>) -> RustType {
let elem = || Box::new(RustType::new(ConceptualRustType::Primitive(Primitive::U64)));
let mut ty = RustType::new(if map {
ConceptualRustType::Map(elem(), elem())
} else {
ConceptualRustType::Array(elem())
});
// Direct public configuration preserves malformed and authored endpoint identity.
ty.config.bounds = Some(TypeBounds::Occurrence(OccurrenceWindow::from_raw(bounds)));
ty.config.duplicates = duplicates;
ty
}
#[test]
fn raw_and_checked_windows_keep_distinct_invalid_state_policies() {
for bounds in [
(Some(-1), Some(3)),
(Some(4), Some(3)),
(None, Some(i128::from(u64::MAX) + 1)),
] {
let ty = collection(true, bounds, Some(DuplicatesPolicy::Preserve));
assert_eq!(ty.collection_view().raw_bounded_window(), Some(bounds));
assert_eq!(ty.bounded_map_u64_bounds(), None);
}
for bounds in [(None, None), (Some(1), None)] {
let ty = collection(true, bounds, None);
assert_eq!(ty.collection_view().raw_bounded_window(), None);
}
for min in [0, 1] {
let bounds = (Some(min), Some(i128::from(u64::MAX)));
let ty = collection(true, bounds, None);
assert_eq!(ty.collection_view().raw_bounded_window(), Some(bounds));
assert_eq!(ty.bounded_map_u64_bounds(), Some((min as u64, u64::MAX)));
}
}
#[test]
fn aliases_keep_authored_shape_while_invariants_resolve_the_target() {
for map in [false, true] {
let mut ty = collection(map, (Some(1), None), None);
ty.conceptual_type = ConceptualRustType::Alias(
AliasIdent::Rust(RustIdent::new(CDDLIdent::new(
"named_collection".to_owned(),
))),
Box::new(ty.conceptual_type),
);
assert!(!ty.is_non_empty_array());
assert!(!ty.is_non_empty_map());
assert!(ty.is_type_enforced_non_empty());
assert_eq!(ty.collection_view().raw_bounded_window(), None);
}
let mut ty = collection(true, (Some(2), Some(3)), None);
ty.conceptual_type = ConceptualRustType::Alias(
AliasIdent::Rust(RustIdent::new(CDDLIdent::new("bounded_alias".to_owned()))),
Box::new(ty.conceptual_type),
);
assert!(!ty.is_bounded_map());
assert_eq!(ty.type_enforced_bounded_map_u64_bounds(), Some((2, 3)));
}
#[test]
fn exact_arrays_reject_sets_and_scalar_windows_keep_distinct_carriers() {
let bounds = (Some(2), Some(2));
let ordinary = collection(false, bounds, None);
assert_eq!(ordinary.exact_homogeneous_array_len(), Some(Ok(2)));
assert!(!ordinary.is_bounded_array());
let reject = collection(false, bounds, Some(DuplicatesPolicy::Reject));
assert_eq!(reject.exact_homogeneous_array_len(), None);
assert_eq!(reject.bounded_array_u64_bounds(), Some((2, 2)));
let map = collection(true, bounds, None);
assert_eq!(map.exact_homogeneous_array_len(), None);
assert_eq!(map.bounded_map_u64_bounds(), Some((2, 2)));
let scalar = RustType::new(ConceptualRustType::Primitive(Primitive::Bytes))
.with_value_bounds(bounds);
assert_eq!(scalar.collection_view().raw_bounded_window(), None);
assert_eq!(scalar.exact_homogeneous_array_len(), None);
assert_eq!(scalar.exact_byte_array_len(), Some(Ok(2)));
let huge = collection(
false,
(
Some(i128::from(i32::MAX) + 1),
Some(i128::from(i32::MAX) + 1),
),
None,
);
assert_eq!(
huge.exact_homogeneous_array_len(),
Some(Err(i128::from(i32::MAX) + 1))
);
}
}
/// Escape a CDDL fixed text value for safe interpolation into an emitted Rust string literal.
/// CDDL text literals may legally contain `"` or `\`; without escaping, those emit invalid Rust
/// (rustfmt then fails on the generated source). Plain values are unchanged.
pub fn escape_rust_str(s: &str) -> String {
s.escape_default().to_string()
}
/// The CDDL float prelude names are SIX distinct VALUE classes, not two carrier widths, and not
/// wire-encoding constraints. RFC 8610 §2.2.3 is explicit that the `#7.x` notation "is about a set
/// of values at the data model level … it does not mandate that these values also do have to be
/// serialized as half-precision floats: CDDL does not provide any language means to restrict the
/// choice of serialization variants". The six names PARTITION the float values by their shortest
/// lossless form: `float16` is the values whose shortest form is `#7.25`, `float32` `#7.26`,
/// `float64` `#7.27`, with `float16-32`/`float32-64` spanning two and `float` all three. The classes
/// are disjoint — `1.5` is a `float16` and not a `float32` — which is the only reading under which
/// `float16-32`/`float32-64` are not redundant spellings.
///
/// The Rust CARRIER is a function of the class window (`f32` when every value in the class fits it),
/// so two classes can share a carrier and still be distinct types — which is why `float` and
/// `float64` cannot share one identity: both carry `f64`, but `float` is every float value and
/// `float64` only those needing all eight bytes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Primitive {
Bool,
/// CDDL `float` (`float = float16-32 / float64`) — UNCONSTRAINED: every float value.
Float,
/// CDDL `float64` — the values whose shortest lossless form is `#7.27` (`fb`).
F64,
/// CDDL `float32` — the values whose shortest lossless form is `#7.26` (`fa`).
F32,
/// CDDL `float16` — the values whose shortest lossless form is `#7.25` (`f9`). Carried as
/// `f32`: every such value widens into it exactly.
F16,
/// CDDL `float16-32` — shortest lossless form `#7.25` or `#7.26`.
F16To32,
/// CDDL `float32-64` — shortest lossless form `#7.26` or `#7.27`.
F32To64,
// u8 in our cddl
U8,
// i8 in our cddl
I8,
// u16 in our cddl
U16,
// i16 in our cddl
I16,
// u32 in our cddl
U32,
// i32 in our cddl
I32,
// uint - also u64 in our cddl
U64,
// i64 in our cddl
I64,
// nint
N64,
Str,
Bytes,
}
impl std::fmt::Display for Primitive {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Primitive::Bool => "bool",
Primitive::F16 | Primitive::F32 | Primitive::F16To32 => "f32",
Primitive::F64 | Primitive::F32To64 | Primitive::Float => "f64",
Primitive::U8 => "u8",
Primitive::I8 => "i8",
Primitive::U16 => "u16",
Primitive::I16 => "i16",
Primitive::U32 => "u32",
Primitive::I32 => "i32",
Primitive::U64 => "u64",
Primitive::I64 => "i64",
Primitive::N64 => "u64",
Primitive::Str => "String",
Primitive::Bytes => "Vec<u8>",
}
)
}
}
/// The `cbor_event::Sz` variant name of a float head width, as emitted code spells it.
pub fn float_head_name(sz: cbor_event::Sz) -> &'static str {
match sz {
cbor_event::Sz::Two => "Two",
cbor_event::Sz::Four => "Four",
cbor_event::Sz::Eight => "Eight",
other => unreachable!("{other:?} is not a float head width"),
}
}
// TODO: impl display or fmt or whatever rust uses
impl Primitive {
/// The window of SHORTEST-LOSSLESS-FORM widths this primitive's CDDL float class spans, as its
/// narrowest and widest `cbor_event::Sz` — or `None` when it is not a float.
/// A value belongs to the class exactly when `smallest_float_sz(value)` lands inside the window,
/// which is what lets both directions express the class as a pair of bounds: decode accepts any
/// head and rejects a VALUE whose shortest form falls outside, and a write emits that same
/// shortest form (RFC 8949 §4.1 preferred serialization), which for a member is its declared
/// width by construction. The window is always contiguous in width order (`Two` < `Four` <
/// `Eight`).
pub fn float_class_window(self) -> Option<(cbor_event::Sz, cbor_event::Sz)> {
use cbor_event::Sz::{Eight, Four, Two};
Some(match self {
Primitive::F16 => (Two, Two),
Primitive::F32 => (Four, Four),
Primitive::F64 => (Eight, Eight),
Primitive::F16To32 => (Two, Four),
Primitive::F32To64 => (Four, Eight),
Primitive::Float => (Two, Eight),
_ => return None,
})
}
/// Whether this is one of the six float classes.
pub fn is_float(self) -> bool {
self.float_class_window().is_some()
}
/// Whether a float class's Rust carrier is `f32` — true exactly when every VALUE it admits fits
/// an `f32` exactly (`float16`, `float32`, `float16-32`). The wire domain is `f64` either way,
/// so an `f32`-carried class narrows after a read and widens before a write; both conversions
/// are exact by construction and go through the runtime's `narrow_f32` /
/// `cbor_event::se::f32_to_f64_exact` (never an `as` cast, whose NaN-payload behavior is both
/// platform-dependent and const-fold-dependent within one binary).
pub fn float_carrier_is_f32(self) -> bool {
matches!(self, Primitive::F16 | Primitive::F32 | Primitive::F16To32)
}
pub fn to_variant(self) -> VariantIdent {
VariantIdent::new_custom(match self {
Primitive::Bool => "Bool",
Primitive::Float => "Float",
Primitive::F16 => "F16",
Primitive::F32 => "F32",
Primitive::F64 => "F64",
Primitive::F16To32 => "F16To32",
Primitive::F32To64 => "F32To64",
Primitive::U8 => "U8",
Primitive::I8 => "I8",
Primitive::U16 => "U16",
Primitive::I16 => "I16",
Primitive::U32 => "U32",
Primitive::I32 => "I32",
Primitive::U64 => "U64",
Primitive::I64 => "I64",
Primitive::N64 => "N64",
Primitive::Str => "Text",
Primitive::Bytes => "Bytes",
})
}
/// All POSSIBLE outermost CBOR types this can encode to
pub fn cbor_types(&self) -> Vec<CBORType> {
match self {
Primitive::Bool => vec![CBORType::Special],
// Every float class is major type 7 regardless of which VALUES it admits — class
// membership is checked after the type dispatch, not by it.
Primitive::Float
| Primitive::F16
| Primitive::F32
| Primitive::F64
| Primitive::F16To32
| Primitive::F32To64 => vec![CBORType::Special],
Primitive::U8 => vec![CBORType::UnsignedInteger],
Primitive::I8 => vec![CBORType::UnsignedInteger, CBORType::NegativeInteger],
Primitive::U16 => vec![CBORType::UnsignedInteger],
Primitive::I16 => vec![CBORType::UnsignedInteger, CBORType::NegativeInteger],
Primitive::U32 => vec![CBORType::UnsignedInteger],
Primitive::I32 => vec![CBORType::UnsignedInteger, CBORType::NegativeInteger],
Primitive::U64 => vec![CBORType::UnsignedInteger],