ridl-ir 0.16.0

The RIDL intermediate representation: the typl surface plus the ridl interaction layer, generated from a versioned protobuf schema.
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
//! The FlatBuffers projection, carried whole, plus the wire kind of every
//! slot and the names of the induced tables (design note D-7).
//!
//! [`crate::projection::flatbuffers`] already computes the layouts, the
//! discriminant, the bound and the root. What is added here is what the `.fbs`
//! emitter and the payload codec each derive from the IR and must agree on
//! byte for byte: the wire kind of every slot with the scalar's FlatBuffers
//! type and byte width, and the names of the induced tables — `<Name>Box`,
//! `<Union><Arm>Box`, `<path>Entry`, and a tuple's table — which the schema
//! emitter spells and the codec repeats in its function names.
//!
//! The walk order is the `.fbs` emitter's own: the declared tables in
//! declaration order, then the induced tables in the order the walk reached
//! them, with a repeated name collapsed to one table. A tuple the lowering
//! named that the declaration walk did not reach — a call's argument or reply
//! struct, a tuple written at a parameter, a tuple inside a fixed payload's
//! array — is queued after that walk has run, in the order `Model.tuples`
//! holds it, because a call's payload is a named type the codec encodes like
//! any other (driftsys/ridl#713).
//!
//! The set of named tuples is the lowering's, handed to [`project`] as
//! [`NamedTuple`]; the projection never re-derives which tuples exist or what
//! they are called. A name is built in one place, which is the lowering.
//!
//! Two spellings of one induced name run through this walk. The `.fbs`
//! emitter inserts `Entry` at a map position and the model's wire induced
//! name does not (design note §3.2 gives the proto3 rule, which the
//! FlatBuffers emitter follows everywhere but there), so a table carries the
//! emitter's name and is keyed back into the model by the model's.

use std::collections::{HashMap, HashSet};

use super::names::joined_camel;
use super::resolve::Scope;
use super::unbounded;
use super::v1;
use crate::projection::flatbuffers as fb;
use crate::v2;

/// The projection plus the lookups the rest of the lowering patches back into
/// the model.
pub(crate) struct Projected {
    pub projection: v1::FlatBuffersProjection,
    /// A tuple's table, by the wire induced name the model carries.
    pub tuple_tables: HashMap<String, u32>,
    /// A map's entry table, by the wire induced name of the map's position.
    pub entry_tables: HashMap<String, u32>,
    /// A union arm's box table, by `(declaration index, arm index)`.
    pub arm_boxes: HashMap<(u32, u32), u32>,
}

/// One table the projection induces, before its slots are filled.
#[derive(Clone)]
enum Spec<'a> {
    Struct {
        decl: u32,
        def: &'a v2::StructDef,
    },
    UnionWrapper {
        decl: u32,
    },
    /// A union arm's box (ADR-0019 decision 2) or a declaration's root box
    /// (decision 8): one table shape, holding one resolved value.
    Boxed {
        decl: u32,
        arm: Option<u32>,
        wrapped: String,
    },
    Tuple {
        tuple: Option<u32>,
        /// Owned: an induced interaction struct is synthesized and lives in
        /// no package, so a tuple the walk carries cannot borrow from one.
        source: v2::TupleType,
        wire: String,
    },
    Entry {
        map: v2::MapType,
        wire: String,
    },
}

#[derive(Clone)]
struct Table<'a> {
    name: String,
    spec: Spec<'a>,
    home: &'a v2::Package,
}

/// The name a container induced at one position takes, in both spellings.
#[derive(Clone)]
struct Hints {
    fbs: String,
    wire: String,
}

impl Hints {
    fn same(name: String) -> Self {
        Self {
            fbs: name.clone(),
            wire: name,
        }
    }

    fn extend(&self, suffix: &str) -> Self {
        Self {
            fbs: format!("{}{suffix}", self.fbs),
            wire: format!("{}{suffix}", self.wire),
        }
    }
}

/// One tuple the lowering lifted out of the type graph and named, as the
/// projection needs it: the name to spell the table under, the index to key
/// the table back into `Model.tuples`, the tuple itself, and the package the
/// position that reached it was written in.
///
/// The type is declared here, where it is consumed, because it states what
/// the projection needs rather than what the lowering happens to hold: the
/// lowering's own tuple entry carries a path, a Rust name and a lowered form
/// the projection has no use for.
pub(crate) struct NamedTuple<'a> {
    /// The index in `Model.tuples`.
    pub index: u32,
    /// The wire induced name, which is both the table's name and the key the
    /// model's tuple is joined by.
    pub wire: &'a str,
    pub source: &'a v2::TupleType,
    pub home: &'a v2::Package,
    /// Whether the tuple crosses the wire on its own, which is what makes it
    /// a FlatBuffers root. A call's argument struct and a query's reply
    /// struct do; a tuple nested inside a parameter or inside a fixed
    /// payload's array does not.
    pub root: bool,
}

pub(crate) fn project<'a>(
    scope: Scope<'a>,
    named: &[NamedTuple<'a>],
    foreign_index: &HashMap<(String, String), u32>,
) -> Projected {
    let tuple_index: HashMap<&str, u32> = named
        .iter()
        .map(|tuple| (tuple.wire, tuple.index))
        .collect();
    let mut walk = Walk {
        scope,
        tables: Vec::new(),
        claimed: HashMap::new(),
        tuple_wires: HashSet::new(),
        queue: Vec::new(),
        tuple_index: &tuple_index,
        foreign_index,
    };
    walk.declared();
    walk.drain();
    // Every named tuple the declaration walk did not reach, under the name
    // the lowering gave it. Draining again fills the containers written
    // inside one of them.
    walk.unclaimed_tuples(named);
    walk.drain();
    walk.finish(named)
}

struct Walk<'a, 'i> {
    scope: Scope<'a>,
    tables: Vec<Table<'a>>,
    claimed: HashMap<String, u32>,
    /// The wire induced name of every tuple a pushed table stands for. A
    /// tuple reached through a map position is claimed under the emitter's
    /// spelling, which inserts `Entry`, so the table's name alone does not
    /// say which tuples are already covered.
    tuple_wires: HashSet<String>,
    queue: Vec<Table<'a>>,
    tuple_index: &'i HashMap<&'i str, u32>,
    foreign_index: &'i HashMap<(String, String), u32>,
}

impl<'a> Walk<'a, '_> {
    /// The tables a declaration writes itself: a struct's own, and a union's
    /// wrapper. A named scalar, an enum and an enum set are rooted in a box,
    /// which is induced.
    fn declared(&mut self) {
        let package = self.scope.package;
        for (index, decl) in package.decls.iter().enumerate() {
            let index = index as u32;
            match &decl.kind {
                Some(v2::decl::Kind::StructDef(def)) => {
                    self.push(Table {
                        name: decl.name.clone(),
                        spec: Spec::Struct { decl: index, def },
                        home: package,
                    });
                    for member in &def.members {
                        if let Some(v2::struct_member::Member::Field(field)) = &member.member
                            && let Some(ty) = field.r#type.as_ref()
                        {
                            let hints =
                                Hints::same(format!("{}{}", decl.name, joined_camel(&field.name)));
                            self.discover(package, ty, &hints);
                        }
                    }
                }
                Some(v2::decl::Kind::UnionDef(def)) => {
                    self.push(Table {
                        name: decl.name.clone(),
                        spec: Spec::UnionWrapper { decl: index },
                        home: package,
                    });
                    for (arm_index, arm) in def.arms.iter().enumerate() {
                        if self.arm_needs_box(package, &arm.type_ref) {
                            self.queue.push(Table {
                                name: format!("{}{}Box", decl.name, joined_camel(&arm.name)),
                                spec: Spec::Boxed {
                                    decl: index,
                                    arm: Some(arm_index as u32),
                                    wrapped: arm.type_ref.clone(),
                                },
                                home: package,
                            });
                        }
                    }
                }
                Some(
                    v2::decl::Kind::TypeDef(_)
                    | v2::decl::Kind::EnumDef(_)
                    | v2::decl::Kind::EnumSetDef(_),
                ) => {
                    self.queue.push(Table {
                        name: format!("{}Box", decl.name),
                        spec: Spec::Boxed {
                            decl: index,
                            arm: None,
                            wrapped: decl.name.clone(),
                        },
                        home: package,
                    });
                }
                _ => {}
            }
        }
    }

    /// Every tuple the lowering named that no pushed table already stands
    /// for, in the order `Model.tuples` holds it. The declaration walk
    /// reaches a tuple written inside a declaration and names it identically,
    /// so what is left here is the tuples reached from an interaction: a
    /// call's argument struct, a query's reply struct, and a tuple written at
    /// a parameter, a reply or a fixed payload (driftsys/ridl#713).
    fn unclaimed_tuples(&mut self, named: &[NamedTuple<'a>]) {
        for tuple in named {
            if self.tuple_wires.contains(tuple.wire) {
                continue;
            }
            self.queue.push(Table {
                name: tuple.wire.to_string(),
                spec: Spec::Tuple {
                    tuple: Some(tuple.index),
                    source: tuple.source.clone(),
                    wire: tuple.wire.to_string(),
                },
                home: tuple.home,
            });
        }
    }

    fn arm_needs_box(&self, home: &'a v2::Package, reference: &str) -> bool {
        matches!(
            self.scope
                .resolve(home, reference)
                .map(|(decl, _)| &decl.kind),
            Some(Some(
                v2::decl::Kind::TypeDef(_)
                    | v2::decl::Kind::EnumDef(_)
                    | v2::decl::Kind::EnumSetDef(_)
            ))
        )
    }

    /// The containers one type position induces a table for.
    fn discover(&mut self, home: &'a v2::Package, ty: &v2::FieldType, hints: &Hints) {
        match ty.kind.as_ref() {
            Some(v2::field_type::Kind::Array(array)) => {
                if let Some(element) = array.element.as_deref() {
                    self.discover(home, element, &hints.extend("Element"));
                }
            }
            Some(v2::field_type::Kind::Map(map)) => {
                self.queue.push(Table {
                    name: format!("{}Entry", hints.fbs),
                    spec: Spec::Entry {
                        map: (**map).clone(),
                        wire: hints.wire.clone(),
                    },
                    home,
                });
            }
            Some(v2::field_type::Kind::Tuple(tuple)) => {
                self.queue.push(Table {
                    name: hints.fbs.clone(),
                    spec: Spec::Tuple {
                        tuple: self.tuple_index.get(hints.wire.as_str()).copied(),
                        source: tuple.clone(),
                        wire: hints.wire.clone(),
                    },
                    home,
                });
            }
            _ => {}
        }
    }

    fn push(&mut self, table: Table<'a>) -> bool {
        if self.claimed.contains_key(&table.name) {
            return false;
        }
        if let Spec::Tuple { wire, .. } = &table.spec {
            self.tuple_wires.insert(wire.clone());
        }
        self.claimed
            .insert(table.name.clone(), self.tables.len() as u32);
        self.tables.push(table);
        true
    }

    /// The induced worklist, drained rather than iterated once: filling one
    /// induced table can discover a container nested inside it.
    fn drain(&mut self) {
        let mut index = 0;
        while index < self.queue.len() {
            let table = self.queue[index].clone();
            index += 1;
            if !self.push(table.clone()) {
                continue;
            }
            let home = table.home;
            match &table.spec {
                Spec::Tuple { source, wire, .. } => {
                    for (position, field) in source.fields.iter().enumerate() {
                        if let Some(ty) = field.r#type.as_ref() {
                            let suffix = format!("Field{}", position + 1);
                            self.discover(
                                home,
                                ty,
                                &Hints {
                                    fbs: format!("{}{suffix}", table.name),
                                    wire: format!("{wire}{suffix}"),
                                },
                            );
                        }
                    }
                }
                Spec::Entry { map, wire } => {
                    if let Some(key) = map.key.as_deref() {
                        self.discover(
                            home,
                            key,
                            &Hints {
                                fbs: format!("{}Key", table.name),
                                wire: format!("{wire}Key"),
                            },
                        );
                    }
                    if let Some(value) = map.value.as_deref() {
                        self.discover(
                            home,
                            value,
                            &Hints {
                                fbs: format!("{}Value", table.name),
                                wire: format!("{wire}Value"),
                            },
                        );
                    }
                }
                _ => {}
            }
        }
    }

    fn finish(self, named: &[NamedTuple<'_>]) -> Projected {
        let Walk {
            scope,
            tables,
            claimed,
            foreign_index,
            ..
        } = self;
        let mut tuple_tables = HashMap::new();
        let mut entry_tables = HashMap::new();
        let mut arm_boxes = HashMap::new();
        let filler = Filler {
            scope,
            claimed: &claimed,
            foreign_index,
        };

        let mut out = Vec::with_capacity(tables.len());
        for (index, table) in tables.iter().enumerate() {
            let index = index as u32;
            match &table.spec {
                Spec::Tuple { wire, .. } => {
                    tuple_tables.insert(wire.clone(), index);
                }
                Spec::Entry { wire, .. } => {
                    entry_tables.insert(wire.clone(), index);
                }
                Spec::Boxed {
                    decl,
                    arm: Some(arm),
                    ..
                } => {
                    arm_boxes.insert((*decl, *arm), index);
                }
                _ => {}
            }
            out.push(filler.table(table));
        }

        Projected {
            projection: v1::FlatBuffersProjection {
                roots: roots(scope, named),
                tables: out,
            },
            tuple_tables,
            entry_tables,
            arm_boxes,
        }
    }
}

/// Fills one table's slots, once every table has an index.
struct Filler<'a, 'c> {
    scope: Scope<'a>,
    claimed: &'c HashMap<String, u32>,
    foreign_index: &'c HashMap<(String, String), u32>,
}

impl Filler<'_, '_> {
    fn table(&self, table: &Table<'_>) -> v1::FbTable {
        let (layout, slots, source) = match &table.spec {
            Spec::Struct { decl, def } => {
                let layout = fb::struct_table(&table.name, def)
                    .unwrap_or(fb::TableLayout { slots: Vec::new() });
                let slots = self.struct_slots(table.home, &table.name, &layout, def);
                (
                    layout,
                    slots,
                    v1::fb_table::Source::StructDeclaration(*decl),
                )
            }
            Spec::UnionWrapper { decl } => {
                let layout = fb::union_wrapper_table();
                let slots = layout
                    .slots
                    .iter()
                    .map(|slot| v1::FbSlot {
                        id: slot.id,
                        // The wrapper's value slot holds the FlatBuffers union
                        // itself; its arms are on `Union.arms`, each with the
                        // box it is isolated in, so there is no one wire kind
                        // to state here.
                        wire: None,
                        needs_null_default: false,
                        source: Some(v1::fb_slot::Source::Wrapped(true)),
                    })
                    .collect();
                (layout, slots, v1::fb_table::Source::UnionWrapper(*decl))
            }
            Spec::Boxed { decl, arm, wrapped } => {
                let layout = fb::union_arm_box_table();
                let (wire, needs_null_default) = self.reference_wire(table.home, wrapped);
                let slots = layout
                    .slots
                    .iter()
                    .map(|slot| v1::FbSlot {
                        id: slot.id,
                        wire: wire.clone(),
                        needs_null_default,
                        source: Some(v1::fb_slot::Source::Wrapped(true)),
                    })
                    .collect();
                let source = match arm {
                    Some(arm) => v1::fb_table::Source::ArmBox(v1::ArmBox {
                        declaration: *decl,
                        arm: *arm,
                    }),
                    None => v1::fb_table::Source::RootBox(*decl),
                };
                (layout, slots, source)
            }
            Spec::Tuple { tuple, source, .. } => {
                let layout = fb::tuple_table(&table.name, source)
                    .unwrap_or(fb::TableLayout { slots: Vec::new() });
                let slots = layout
                    .slots
                    .iter()
                    .zip(source.fields.iter())
                    .map(|(slot, field)| {
                        let position = match slot.source {
                            fb::SlotSource::TupleField { position } => position,
                            _ => 0,
                        };
                        let (wire, needs_null_default) = self.type_wire(
                            table.home,
                            field.r#type.as_ref(),
                            &format!("{}Field{position}", table.name),
                        );
                        v1::FbSlot {
                            id: slot.id,
                            wire,
                            needs_null_default,
                            source: Some(v1::fb_slot::Source::TuplePosition(position)),
                        }
                    })
                    .collect();
                (
                    layout,
                    slots,
                    v1::fb_table::Source::Tuple(tuple.unwrap_or_default()),
                )
            }
            Spec::Entry { map, .. } => {
                let layout = fb::map_entry_table();
                let (key_wire, key_null) = self.type_wire(
                    table.home,
                    map.key.as_deref(),
                    &format!("{}Key", table.name),
                );
                let (value_wire, value_null) = self.type_wire(
                    table.home,
                    map.value.as_deref(),
                    &format!("{}Value", table.name),
                );
                let slots = vec![
                    v1::FbSlot {
                        id: fb::MAP_ENTRY_KEY_ID,
                        wire: key_wire,
                        needs_null_default: key_null,
                        source: Some(v1::fb_slot::Source::Key(true)),
                    },
                    v1::FbSlot {
                        id: fb::MAP_ENTRY_VALUE_ID,
                        wire: value_wire,
                        needs_null_default: value_null,
                        source: Some(v1::fb_slot::Source::Value(true)),
                    },
                ];
                (
                    layout,
                    slots,
                    v1::fb_table::Source::MapEntry(v1::MapEntry {
                        path: vec![table.name.clone()],
                    }),
                )
            }
        };
        v1::FbTable {
            name: table.name.clone(),
            slots,
            vtable_slots: u32::try_from(layout.vtable_slots()).unwrap_or(u32::MAX),
            source: Some(source),
        }
    }

    fn struct_slots(
        &self,
        home: &v2::Package,
        owner: &str,
        layout: &fb::TableLayout,
        def: &v2::StructDef,
    ) -> Vec<v1::FbSlot> {
        let members: Vec<&v2::struct_member::Member> = def
            .members
            .iter()
            .filter_map(|member| member.member.as_ref())
            .collect();
        layout
            .slots
            .iter()
            .enumerate()
            .map(|(index, slot)| match members.get(index) {
                Some(v2::struct_member::Member::Field(field)) => {
                    let hint = format!("{owner}{}", joined_camel(&field.name));
                    let (wire, needs_null_default) =
                        self.type_wire(home, field.r#type.as_ref(), &hint);
                    v1::FbSlot {
                        id: slot.id,
                        wire,
                        needs_null_default,
                        source: Some(v1::fb_slot::Source::Field(index as u32)),
                    }
                }
                Some(v2::struct_member::Member::Reserved(reserved)) => v1::FbSlot {
                    id: slot.id,
                    // The placeholder holding a retired ordinal is a `ubyte`,
                    // marked deprecated.
                    wire: Some(scalar_wire(v1::FbScalarType::Ubyte, 1)),
                    needs_null_default: false,
                    source: Some(v1::fb_slot::Source::RetiredOrdinal(reserved.ordinal)),
                },
                None => v1::FbSlot {
                    id: slot.id,
                    wire: None,
                    needs_null_default: false,
                    source: None,
                },
            })
            .collect()
    }

    /// What one type position holds on the wire, and whether a field at that
    /// position needs an explicit `= null` default: a field typed by an enum
    /// with no zero member (ADR-0019 decision 6), and an optional field that
    /// holds a scalar or an enum, the two kinds a FlatBuffers default applies
    /// to (decision 9). An array's element drops its marker, because a vector
    /// element carries no default.
    ///
    /// A reference into another package resolves to a table this package's
    /// schema does not declare, so no wire kind is stated for it; the
    /// reference itself is on the owning field's `TypeRef`.
    fn type_wire(
        &self,
        home: &v2::Package,
        ty: Option<&v2::FieldType>,
        hint: &str,
    ) -> (Option<v1::FbWire>, bool) {
        let Some(ty) = ty else {
            return (None, false);
        };
        let (wire, needs_null_default) = self.position_wire(home, ty, hint);
        let holds_a_default = matches!(
            wire.as_ref().and_then(|wire| wire.kind.as_ref()),
            Some(v1::fb_wire::Kind::Scalar(_)) | Some(v1::fb_wire::Kind::Enum(_))
        );
        (wire, needs_null_default || (ty.optional && holds_a_default))
    }

    /// [`Filler::type_wire`] before the optional rule: the wire kind, and the
    /// `= null` ADR-0019 decision 6 calls for.
    fn position_wire(
        &self,
        home: &v2::Package,
        ty: &v2::FieldType,
        hint: &str,
    ) -> (Option<v1::FbWire>, bool) {
        match ty.kind.as_ref() {
            Some(v2::field_type::Kind::Primitive(primitive)) => {
                (Some(primitive_wire(*primitive)), false)
            }
            Some(v2::field_type::Kind::InlineScalar(td)) => (Some(scalar_def_wire(td)), false),
            Some(v2::field_type::Kind::Named(reference)) => self.reference_wire(home, reference),
            Some(v2::field_type::Kind::Array(array)) => {
                let (element, _) =
                    self.type_wire(home, array.element.as_deref(), &format!("{hint}Element"));
                let wire = element.map(|element| v1::FbWire {
                    kind: Some(v1::fb_wire::Kind::Vector(Box::new(v1::FbVector {
                        element: Some(Box::new(element)),
                        min: array.min,
                        max: array.max,
                    }))),
                });
                (wire, false)
            }
            Some(v2::field_type::Kind::Map(map)) => {
                let wire = self
                    .claimed
                    .get(&format!("{hint}Entry"))
                    .map(|entry| v1::FbWire {
                        kind: Some(v1::fb_wire::Kind::Map(v1::FbMap {
                            entry_table: *entry,
                            min: map.min,
                            max: map.max,
                        })),
                    });
                (wire, false)
            }
            Some(v2::field_type::Kind::Tuple(_)) => {
                let wire = self.claimed.get(hint).map(|table| v1::FbWire {
                    kind: Some(v1::fb_wire::Kind::Table(*table)),
                });
                (wire, false)
            }
            _ => (None, false),
        }
    }

    /// Where the model holds the declaration `name` of `declaring`: its own
    /// index for a declaration of the package being lowered, and the index
    /// the lowering gave it in `Model.foreign` otherwise.
    fn declaration_index(&self, declaring: &v2::Package, name: &str, local: bool) -> u32 {
        if local {
            declaring
                .decls
                .iter()
                .position(|decl| decl.name == name)
                .unwrap_or(0) as u32
        } else {
            self.foreign_index
                .get(&(declaring.name.clone(), name.to_string()))
                .copied()
                .unwrap_or(0)
        }
    }

    fn reference_wire(&self, home: &v2::Package, reference: &str) -> (Option<v1::FbWire>, bool) {
        let Some((decl, declaring)) = self.scope.resolve(home, reference) else {
            return (None, false);
        };
        let local = declaring.name == self.scope.package.name;
        match &decl.kind {
            Some(v2::decl::Kind::TypeDef(td)) => (Some(scalar_def_wire(td)), false),
            // A FlatBuffers enum field names the enum, and every typl enum is
            // emitted at one underlying width, `long`. `foreign` and `index`
            // follow the one rule `Lowering::type_ref` states: the declaring
            // package against the package being lowered.
            Some(v2::decl::Kind::EnumDef(def)) => (
                Some(v1::FbWire {
                    kind: Some(v1::fb_wire::Kind::Enum(v1::FbEnum {
                        r#type: Some(v1::TypeRef {
                            reference: reference.to_string(),
                            resolved: true,
                            package: declaring.name.clone(),
                            foreign: !local,
                            index: self.declaration_index(declaring, &decl.name, local),
                            kind: v1::DeclKind::Enum as i32,
                        }),
                        width_bytes: 8,
                    })),
                }),
                fb::enum_field_needs_null_default(def),
            ),
            Some(v2::decl::Kind::EnumSetDef(def)) => (Some(int_width_wire(def.width)), false),
            Some(v2::decl::Kind::StructDef(_)) if local => (
                self.claimed.get(&decl.name).map(|index| v1::FbWire {
                    kind: Some(v1::fb_wire::Kind::Table(*index)),
                }),
                false,
            ),
            Some(v2::decl::Kind::UnionDef(_)) if local => (
                self.claimed.get(&decl.name).map(|index| v1::FbWire {
                    kind: Some(v1::fb_wire::Kind::UnionWrapper(*index)),
                }),
                false,
            ),
            _ => (None, false),
        }
    }
}

/// One root per declaration `root_table` names, in declaration order, then
/// one per named tuple that crosses the wire on its own, in the order
/// `Model.tuples` holds it. The bound is `max_size` over the whole scope —
/// the number the codec emits as `MAX_SIZE` — and a missing bound is
/// attributed over the package alone, which is what the Rust backend does
/// today (design note §9 item 7).
///
/// An induced root carries its tuple's index in `tuple`, and its
/// `declaration` is written as 0 and must be ignored, which is the contract
/// `FbRoot.tuple` states.
fn roots(scope: Scope<'_>, named: &[NamedTuple<'_>]) -> Vec<v1::FbRoot> {
    let package = scope.package;
    let others = scope.projection_others(package);
    let packages = fb::Packages {
        package,
        others: &others,
    };
    let mut roots: Vec<v1::FbRoot> = package
        .decls
        .iter()
        .enumerate()
        .filter_map(|(index, decl)| {
            let root = fb::root_table(decl)?;
            let kind = match root {
                fb::RootTable::Own => v1::FbRootKind::Own,
                fb::RootTable::UnionWrapper => v1::FbRootKind::UnionWrapper,
                fb::RootTable::Box => v1::FbRootKind::Box,
            };
            let bound = match fb::max_size(packages, decl) {
                Some(size) => v1::fb_root::Bound::MaxSize(u32::try_from(size).unwrap_or(u32::MAX)),
                None => v1::fb_root::Bound::Unbounded(unbounded::attribute(package, decl)),
            };
            Some(v1::FbRoot {
                declaration: index as u32,
                root: kind as i32,
                tuple: None,
                bound: Some(bound),
            })
        })
        .collect();
    // An induced argument or reply struct crosses the wire on its own, so it
    // is a root like a declared payload: its `Payload` impl is what a
    // reservation row's `MAX_SIZE` names (driftsys/ridl#713).
    for tuple in named.iter().filter(|tuple| tuple.root) {
        let bound = match fb::tuple_max_size(packages, tuple.source) {
            Some(size) => v1::fb_root::Bound::MaxSize(u32::try_from(size).unwrap_or(u32::MAX)),
            None => v1::fb_root::Bound::Unbounded(unbounded::attribute(
                package,
                &tuple_stand_in(tuple.wire, tuple.source),
            )),
        };
        roots.push(v1::FbRoot {
            // An induced struct has no declaration of its own; `tuple` is
            // what names it.
            declaration: 0,
            root: v1::FbRootKind::Own as i32,
            tuple: Some(tuple.index),
            bound: Some(bound),
        });
    }
    roots
}

/// An induced struct as the struct declaration it would be, so that the
/// attribution of a missing bound can name the field that is unbounded. One
/// field per tuple field, in declaration order, on consecutive ordinals.
fn tuple_stand_in(name: &str, tuple: &v2::TupleType) -> v2::Decl {
    v2::Decl {
        name: name.to_string(),
        kind: Some(v2::decl::Kind::StructDef(v2::StructDef {
            members: tuple
                .fields
                .iter()
                .enumerate()
                .map(|(position, field)| v2::StructMember {
                    member: Some(v2::struct_member::Member::Field(Box::new(v2::Field {
                        name: field.name.clone(),
                        ordinal: position as u32 + 1,
                        r#type: field.r#type.clone(),
                        ..Default::default()
                    }))),
                })
                .collect(),
            fixed_layout: false,
        })),
        ..Default::default()
    }
}

fn primitive_wire(primitive: i32) -> v1::FbWire {
    match v2::PrimitiveType::try_from(primitive).unwrap_or(v2::PrimitiveType::Unspecified) {
        v2::PrimitiveType::Boolean => scalar_wire(v1::FbScalarType::Bool, 1),
        v2::PrimitiveType::Integer => scalar_wire(v1::FbScalarType::Long, 8),
        v2::PrimitiveType::Float => scalar_wire(v1::FbScalarType::Double, 8),
        v2::PrimitiveType::Bytes => v1::FbWire {
            kind: Some(v1::fb_wire::Kind::Bytes(true)),
        },
        v2::PrimitiveType::String | v2::PrimitiveType::Unspecified => v1::FbWire {
            kind: Some(v1::fb_wire::Kind::Text(true)),
        },
    }
}

/// The wire kind of a named or inline scalar, at the width the IR derived —
/// the table `fbs_scalar` spells as a keyword.
fn scalar_def_wire(td: &v2::TypeDef) -> v1::FbWire {
    match &td.width {
        Some(v2::type_def::Width::IntWidth(width)) => int_width_wire(*width),
        Some(v2::type_def::Width::FloatWidth(width)) => {
            match v2::FloatWidth::try_from(*width).unwrap_or(v2::FloatWidth::Unspecified) {
                v2::FloatWidth::F32 => scalar_wire(v1::FbScalarType::Float, 4),
                _ => scalar_wire(v1::FbScalarType::Double, 8),
            }
        }
        None => match td
            .backing
            .as_ref()
            .and_then(|backing| backing.kind.as_ref())
        {
            Some(v2::backing::Kind::Primitive(primitive)) => {
                match v2::PrimitiveType::try_from(*primitive)
                    .unwrap_or(v2::PrimitiveType::Unspecified)
                {
                    v2::PrimitiveType::Boolean => scalar_wire(v1::FbScalarType::Bool, 1),
                    v2::PrimitiveType::Bytes => v1::FbWire {
                        kind: Some(v1::fb_wire::Kind::Bytes(true)),
                    },
                    _ => v1::FbWire {
                        kind: Some(v1::fb_wire::Kind::Text(true)),
                    },
                }
            }
            _ => v1::FbWire {
                kind: Some(v1::fb_wire::Kind::Text(true)),
            },
        },
    }
}

fn int_width_wire(width: i32) -> v1::FbWire {
    match v2::IntWidth::try_from(width).unwrap_or(v2::IntWidth::Unspecified) {
        v2::IntWidth::U8 => scalar_wire(v1::FbScalarType::Ubyte, 1),
        v2::IntWidth::I8 => scalar_wire(v1::FbScalarType::Byte, 1),
        v2::IntWidth::U16 => scalar_wire(v1::FbScalarType::Ushort, 2),
        v2::IntWidth::I16 => scalar_wire(v1::FbScalarType::Short, 2),
        v2::IntWidth::U32 => scalar_wire(v1::FbScalarType::Uint, 4),
        v2::IntWidth::I32 => scalar_wire(v1::FbScalarType::Int, 4),
        v2::IntWidth::U64 => scalar_wire(v1::FbScalarType::Ulong, 8),
        _ => scalar_wire(v1::FbScalarType::Long, 8),
    }
}

fn scalar_wire(kind: v1::FbScalarType, width: u32) -> v1::FbWire {
    v1::FbWire {
        kind: Some(v1::fb_wire::Kind::Scalar(v1::FbScalar {
            r#type: kind as i32,
            width_bytes: width,
        })),
    }
}