model-core 0.10.1

Language-neutral source code metamodel
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
//! Binary form of a frozen [`Model`]: its columns as they are in memory, so
//! loading copies them back instead of replaying the builder (no hashing, no
//! sorting, no index rebuild).
//!
//! Layout, all integers little-endian:
//!
//! ```text
//! magic "MODELBIN" · version u32
//! strings    bytes, offsets (u64 each)
//! languages  [string]
//! metamodel  [name, archetype u8, traits u64, fm3?, graphql_type?, graphql_root?]
//! kinds      [tag u8 (255: other + string)]
//! entities   [52-byte row]
//! props      [entity u32, map]
//! by_key, child_offsets, children                 [u32]
//! relations  [from u32, kind u16, to u32, provenance u8]
//! out_offsets, in_offsets, incoming, site_offsets [u32]
//! sites      [4 × u32] · site_flags [u8]
//! ```
//!
//! Every list is prefixed by its length (u64); a string is a length-prefixed
//! UTF-8 byte list and `?` an optional string (u8 0/1, then the string).
//!
//! Reading checks every index and offset the views rely on, so a truncated or
//! corrupted file is an [`io::ErrorKind::InvalidData`] error, never a panic.
//! The format is versioned: a reader refuses any other version.

use std::collections::BTreeMap;
use std::io::{self, Read, Write};

use crate::entity::{EntityId, EntityKind, LanguageId};
use crate::metamodel::{KindId, KindInfo, Metamodel, TraitMask};
use crate::model::{EntityRow, Model, NONE, RelRow};
use crate::relation::{Provenance, RelationKind, SiteFlags};
use crate::source::Range;
use crate::strings::{StrId, StrTable};
use crate::value::{Props, Value};

/// First bytes of a binary model; enough to tell it from JSON.
pub const MAGIC: &[u8; 8] = b"MODELBIN";

/// Format version written by [`Model::write_binary`].
pub const VERSION: u32 = 1;

/// Whether `prefix` (the first bytes of a file) starts a binary model.
pub fn is_binary(prefix: &[u8]) -> bool {
    prefix.starts_with(MAGIC)
}

const ROW_BYTES: usize = 52;
const REL_BYTES: usize = 11;
const RANGE_BYTES: usize = 16;
/// Nesting bound for [`Value`]s, so a crafted file cannot exhaust the stack.
const MAX_DEPTH: u32 = 64;
/// Up-front reservation cap: a corrupted length grows the buffer as bytes
/// actually arrive instead of allocating it all at once.
const MAX_RESERVE: u64 = 1 << 28;

fn invalid(what: impl std::fmt::Display) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, format!("binary model: {what}"))
}

fn relation_tag(k: &RelationKind) -> u8 {
    match k {
        RelationKind::Calls => 0,
        RelationKind::References => 1,
        RelationKind::Inherits => 2,
        RelationKind::Implements => 3,
        RelationKind::Imports => 4,
        RelationKind::DeclaredType => 5,
        RelationKind::Accesses => 6,
        RelationKind::Throws => 7,
        RelationKind::Overrides => 8,
        RelationKind::Other(_) => 255,
    }
}

fn provenance_tag(p: Provenance) -> u8 {
    match p {
        Provenance::TreeSitter => 0,
        Provenance::Scip => 1,
        Provenance::Frontend => 2,
        Provenance::Derived => 3,
    }
}

fn provenance_of(tag: u8) -> io::Result<Provenance> {
    Ok(match tag {
        0 => Provenance::TreeSitter,
        1 => Provenance::Scip,
        2 => Provenance::Frontend,
        3 => Provenance::Derived,
        t => return Err(invalid(format_args!("unknown provenance {t}"))),
    })
}

// ---------------------------------------------------------------- writing

struct Out<W> {
    w: W,
}

impl<W: Write> Out<W> {
    fn bytes(&mut self, b: &[u8]) -> io::Result<()> {
        self.w.write_all(b)
    }

    fn u8(&mut self, v: u8) -> io::Result<()> {
        self.bytes(&[v])
    }

    fn u32(&mut self, v: u32) -> io::Result<()> {
        self.bytes(&v.to_le_bytes())
    }

    fn u64(&mut self, v: u64) -> io::Result<()> {
        self.bytes(&v.to_le_bytes())
    }

    fn len(&mut self, n: usize) -> io::Result<()> {
        self.u64(n as u64)
    }

    fn str(&mut self, s: &str) -> io::Result<()> {
        self.len(s.len())?;
        self.bytes(s.as_bytes())
    }

    fn opt_str(&mut self, s: Option<&str>) -> io::Result<()> {
        match s {
            None => self.u8(0),
            Some(s) => {
                self.u8(1)?;
                self.str(s)
            }
        }
    }

    /// A column of fixed-size items, encoded through a reused buffer.
    fn column<T>(
        &mut self,
        items: &[T],
        size: usize,
        mut put: impl FnMut(&T, &mut Vec<u8>),
    ) -> io::Result<()> {
        self.len(items.len())?;
        let mut buf = Vec::with_capacity(size * 4096);
        for chunk in items.chunks(4096) {
            buf.clear();
            for item in chunk {
                put(item, &mut buf);
            }
            self.bytes(&buf)?;
        }
        Ok(())
    }

    fn u32s(&mut self, items: &[u32]) -> io::Result<()> {
        self.column(items, 4, |v, b| b.extend_from_slice(&v.to_le_bytes()))
    }

    fn ids(&mut self, items: &[EntityId]) -> io::Result<()> {
        self.column(items, 4, |v, b| b.extend_from_slice(&v.0.to_le_bytes()))
    }

    fn value(&mut self, v: &Value) -> io::Result<()> {
        match v {
            Value::Bool(b) => {
                self.u8(0)?;
                self.u8(*b as u8)
            }
            Value::Int(i) => {
                self.u8(1)?;
                self.bytes(&i.to_le_bytes())
            }
            Value::Str(s) => {
                self.u8(2)?;
                self.str(s)
            }
            Value::List(l) => {
                self.u8(3)?;
                self.len(l.len())?;
                l.iter().try_for_each(|v| self.value(v))
            }
            Value::Map(m) => {
                self.u8(4)?;
                self.map(m)
            }
        }
    }

    fn map(&mut self, m: &BTreeMap<String, Value>) -> io::Result<()> {
        self.len(m.len())?;
        for (k, v) in m {
            self.str(k)?;
            self.value(v)?;
        }
        Ok(())
    }
}

fn put_range(r: &Range, b: &mut Vec<u8>) {
    for v in [r.start_line, r.start_col, r.end_line, r.end_col] {
        b.extend_from_slice(&v.to_le_bytes());
    }
}

impl Model {
    /// Writes the binary form (see the [module doc](crate::binary)). Pass a
    /// buffered writer: the columns go out in many small writes.
    pub fn write_binary<W: Write>(&self, w: W) -> io::Result<()> {
        let mut o = Out { w };
        o.bytes(MAGIC)?;
        o.u32(VERSION)?;

        o.str(self.strings.bytes())?;
        let offsets = self.strings.offsets();
        o.column(offsets, 8, |v, b| {
            b.extend_from_slice(&(*v as u64).to_le_bytes())
        })?;

        o.len(self.languages.len())?;
        for l in &self.languages {
            o.str(l.as_str())?;
        }

        o.len(self.metamodel.len())?;
        for (_, k) in self.metamodel.iter() {
            o.str(&k.name)?;
            o.u8(k.archetype as u8)?;
            o.u64(k.traits.0)?;
            o.opt_str(k.fm3.as_deref())?;
            o.opt_str(k.graphql_type.as_deref())?;
            o.opt_str(k.graphql_root.as_deref())?;
        }

        o.len(self.kinds.len())?;
        for k in &self.kinds {
            o.u8(relation_tag(k))?;
            if let RelationKind::Other(name) = k {
                o.str(name)?;
            }
        }

        o.column(&self.entities, ROW_BYTES, |e, b| {
            for v in [e.key.0, e.name.0, e.file, e.parent] {
                b.extend_from_slice(&v.to_le_bytes());
            }
            put_range(&e.range, b);
            put_range(&e.name_range, b);
            b.push(e.kind.0);
            b.extend_from_slice(&e.language.to_le_bytes());
            b.push(e.flags);
        })?;

        o.len(self.props.len())?;
        for (id, props) in &self.props {
            o.u32(id.0)?;
            o.map(props)?;
        }

        o.ids(&self.by_key)?;
        o.u32s(&self.child_offsets)?;
        o.ids(&self.children)?;
        o.column(&self.relations, REL_BYTES, |r, b| {
            b.extend_from_slice(&r.from.0.to_le_bytes());
            b.extend_from_slice(&r.kind.to_le_bytes());
            b.extend_from_slice(&r.to.0.to_le_bytes());
            b.push(provenance_tag(r.provenance));
        })?;
        o.u32s(&self.out_offsets)?;
        o.u32s(&self.in_offsets)?;
        o.u32s(&self.incoming)?;
        o.u32s(&self.site_offsets)?;
        o.column(&self.sites, RANGE_BYTES, put_range)?;
        o.column(&self.site_flags, 1, |f, b| b.push(f.0))?;
        o.w.flush()
    }

    /// Reads a model written by [`Model::write_binary`], checking its
    /// indexes. Pass a buffered reader.
    pub fn read_binary<R: Read>(r: R) -> io::Result<Model> {
        let mut i = In { r };
        let mut magic = [0u8; 8];
        i.exact(&mut magic)?;
        if &magic != MAGIC {
            return Err(invalid("not a binary model (bad magic)"));
        }
        let version = i.u32()?;
        if version != VERSION {
            return Err(invalid(format_args!(
                "format version {version}, this reader knows {VERSION}"
            )));
        }

        let bytes = i.string()?;
        let offsets = i.column(8, |c| u64_at(c, 0) as usize)?;
        let strings = StrTable::from_parts(bytes, offsets)
            .ok_or_else(|| invalid("string offsets out of order or off char boundaries"))?;

        let n = i.len()?;
        let mut languages = Vec::with_capacity(n.min(1024));
        for _ in 0..n {
            languages.push(LanguageId::new(i.string()?));
        }

        let n = i.len()?;
        let mut kinds = Vec::with_capacity(n.min(256));
        for _ in 0..n {
            let name = i.string()?;
            let archetype = *EntityKind::ALL
                .get(i.u8()? as usize)
                .ok_or_else(|| invalid("unknown archetype"))?;
            kinds.push(KindInfo {
                name,
                archetype,
                traits: TraitMask(i.u64()?),
                fm3: i.opt_string()?,
                graphql_type: i.opt_string()?,
                graphql_root: i.opt_string()?,
            });
        }
        let metamodel = Metamodel::from_kinds(kinds)
            .ok_or_else(|| invalid("metamodel must start with the archetypes, ≤ 256 kinds"))?;

        let n = i.len()?;
        let mut rel_kinds = Vec::with_capacity(n.min(1024));
        for _ in 0..n {
            rel_kinds.push(match i.u8()? {
                0 => RelationKind::Calls,
                1 => RelationKind::References,
                2 => RelationKind::Inherits,
                3 => RelationKind::Implements,
                4 => RelationKind::Imports,
                5 => RelationKind::DeclaredType,
                6 => RelationKind::Accesses,
                7 => RelationKind::Throws,
                8 => RelationKind::Overrides,
                255 => RelationKind::Other(i.string()?),
                t => return Err(invalid(format_args!("unknown relation kind {t}"))),
            });
        }
        if rel_kinds.len() > u16::MAX as usize + 1 {
            return Err(invalid("too many relation kinds"));
        }

        let entities = i.column(ROW_BYTES, |c| EntityRow {
            key: StrId(u32_at(c, 0)),
            name: StrId(u32_at(c, 4)),
            file: u32_at(c, 8),
            parent: u32_at(c, 12),
            range: range_at(c, 16),
            name_range: range_at(c, 32),
            kind: KindId(c[48]),
            language: u16::from_le_bytes([c[49], c[50]]),
            flags: c[51],
        })?;

        let n = i.len()?;
        let mut props: Vec<(EntityId, Props)> = Vec::with_capacity(n.min(1 << 20));
        for _ in 0..n {
            let id = EntityId(i.u32()?);
            props.push((id, i.map(0)?));
        }

        let by_key = i.column(4, |c| EntityId(u32_at(c, 0)))?;
        let child_offsets = i.column(4, |c| u32_at(c, 0))?;
        let children = i.column(4, |c| EntityId(u32_at(c, 0)))?;
        let relations = i.column(REL_BYTES, |c| {
            (
                RelRow {
                    from: EntityId(u32_at(c, 0)),
                    kind: u16::from_le_bytes([c[4], c[5]]),
                    to: EntityId(u32_at(c, 6)),
                    provenance: Provenance::Derived,
                },
                c[10],
            )
        })?;
        let relations = relations
            .into_iter()
            .map(|(mut r, p)| {
                r.provenance = provenance_of(p)?;
                Ok(r)
            })
            .collect::<io::Result<Vec<_>>>()?;
        let out_offsets = i.column(4, |c| u32_at(c, 0))?;
        let in_offsets = i.column(4, |c| u32_at(c, 0))?;
        let incoming = i.column(4, |c| u32_at(c, 0))?;
        let site_offsets = i.column(4, |c| u32_at(c, 0))?;
        let sites = i.column(RANGE_BYTES, |c| range_at(c, 0))?;
        let site_flags = i.column(1, |c| SiteFlags(c[0]))?;

        let model = Model {
            strings,
            languages,
            metamodel,
            kinds: rel_kinds,
            entities,
            props,
            by_key,
            child_offsets,
            children,
            relations,
            out_offsets,
            in_offsets,
            incoming,
            site_offsets,
            sites,
            site_flags,
        };
        model.check().map_err(invalid)?;
        Ok(model)
    }

    /// The invariants the views index on without checking.
    fn check(&self) -> Result<(), &'static str> {
        let n = self.entities.len();
        let strings = self.strings.len();
        let in_str = |id: u32| (id as usize) < strings;
        for e in &self.entities {
            if !in_str(e.key.0) || !in_str(e.name.0) {
                return Err("entity string out of range");
            }
            if e.file != NONE && !in_str(e.file) {
                return Err("entity file out of range");
            }
            if e.parent != NONE && e.parent as usize >= n {
                return Err("entity parent out of range");
            }
            if e.kind.index() >= self.metamodel.len() {
                return Err("entity kind out of range");
            }
        }
        if !self.props.windows(2).all(|w| w[0].0 < w[1].0)
            || self.props.last().is_some_and(|p| p.0.index() >= n)
        {
            return Err("props not sorted by entity or out of range");
        }
        if self.by_key.len() != n || self.by_key.iter().any(|id| id.index() >= n) {
            return Err("key index does not match the entities");
        }
        let key = |id: &EntityId| self.strings.get(self.entities[id.index()].key);
        if !self.by_key.windows(2).all(|w| key(&w[0]) <= key(&w[1])) {
            return Err("key index not sorted");
        }
        csr(&self.child_offsets, n, self.children.len(), "children")?;
        if self.children.iter().any(|c| c.index() >= n) {
            return Err("child out of range");
        }
        let r = self.relations.len();
        if self.relations.iter().any(|rel| {
            rel.from.index() >= n || rel.to.index() >= n || rel.kind as usize >= self.kinds.len()
        }) {
            return Err("relation endpoint or kind out of range");
        }
        if !self.relations.windows(2).all(|w| w[0] < w[1]) {
            return Err("relations not sorted");
        }
        csr(&self.out_offsets, n, r, "outgoing")?;
        csr(&self.in_offsets, n, self.incoming.len(), "incoming")?;
        if self.incoming.len() != r || self.incoming.iter().any(|&i| i as usize >= r) {
            return Err("incoming index does not match the relations");
        }
        csr(&self.site_offsets, r, self.sites.len(), "sites")?;
        if self.site_flags.len() != self.sites.len() {
            return Err("site flags do not match the sites");
        }
        Ok(())
    }
}

/// `offsets` slices `len` items into `buckets` groups.
fn csr(
    offsets: &[u32],
    buckets: usize,
    len: usize,
    what: &'static str,
) -> Result<(), &'static str> {
    let ok = offsets.len() == buckets + 1
        && offsets.first() == Some(&0)
        && offsets.last().map(|&l| l as usize) == Some(len)
        && offsets.windows(2).all(|w| w[0] <= w[1]);
    if ok { Ok(()) } else { Err(what) }
}

// ---------------------------------------------------------------- reading

fn u32_at(c: &[u8], at: usize) -> u32 {
    u32::from_le_bytes([c[at], c[at + 1], c[at + 2], c[at + 3]])
}

fn u64_at(c: &[u8], at: usize) -> u64 {
    let mut b = [0u8; 8];
    b.copy_from_slice(&c[at..at + 8]);
    u64::from_le_bytes(b)
}

fn range_at(c: &[u8], at: usize) -> Range {
    Range::new(
        u32_at(c, at),
        u32_at(c, at + 4),
        u32_at(c, at + 8),
        u32_at(c, at + 12),
    )
}

struct In<R> {
    r: R,
}

impl<R: Read> In<R> {
    fn exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        self.r.read_exact(buf).map_err(|e| match e.kind() {
            io::ErrorKind::UnexpectedEof => invalid("truncated"),
            _ => e,
        })
    }

    fn u8(&mut self) -> io::Result<u8> {
        let mut b = [0u8; 1];
        self.exact(&mut b)?;
        Ok(b[0])
    }

    fn u32(&mut self) -> io::Result<u32> {
        let mut b = [0u8; 4];
        self.exact(&mut b)?;
        Ok(u32::from_le_bytes(b))
    }

    fn u64(&mut self) -> io::Result<u64> {
        let mut b = [0u8; 8];
        self.exact(&mut b)?;
        Ok(u64::from_le_bytes(b))
    }

    fn len(&mut self) -> io::Result<usize> {
        usize::try_from(self.u64()?).map_err(|_| invalid("length too large"))
    }

    /// Exactly `n` bytes, without trusting `n` for the allocation.
    fn take(&mut self, n: u64) -> io::Result<Vec<u8>> {
        let mut buf = Vec::with_capacity(n.min(MAX_RESERVE) as usize);
        (&mut self.r).take(n).read_to_end(&mut buf)?;
        if buf.len() as u64 != n {
            return Err(invalid("truncated"));
        }
        Ok(buf)
    }

    fn string(&mut self) -> io::Result<String> {
        let n = self.u64()?;
        String::from_utf8(self.take(n)?).map_err(|_| invalid("string is not UTF-8"))
    }

    fn opt_string(&mut self) -> io::Result<Option<String>> {
        match self.u8()? {
            0 => Ok(None),
            1 => self.string().map(Some),
            t => Err(invalid(format_args!("bad option tag {t}"))),
        }
    }

    fn column<T>(&mut self, size: usize, get: impl Fn(&[u8]) -> T) -> io::Result<Vec<T>> {
        let n = self.u64()?;
        let bytes = n
            .checked_mul(size as u64)
            .ok_or_else(|| invalid("length too large"))?;
        let raw = self.take(bytes)?;
        Ok(raw.chunks_exact(size).map(get).collect())
    }

    fn value(&mut self, depth: u32) -> io::Result<Value> {
        if depth > MAX_DEPTH {
            return Err(invalid("props nested too deeply"));
        }
        Ok(match self.u8()? {
            0 => Value::Bool(self.u8()? != 0),
            1 => {
                let mut b = [0u8; 8];
                self.exact(&mut b)?;
                Value::Int(i64::from_le_bytes(b))
            }
            2 => Value::Str(self.string()?),
            3 => {
                let n = self.len()?;
                let mut l = Vec::with_capacity(n.min(1024));
                for _ in 0..n {
                    l.push(self.value(depth + 1)?);
                }
                Value::List(l)
            }
            4 => Value::Map(self.map(depth + 1)?),
            t => return Err(invalid(format_args!("unknown value tag {t}"))),
        })
    }

    fn map(&mut self, depth: u32) -> io::Result<BTreeMap<String, Value>> {
        let n = self.len()?;
        let mut m = BTreeMap::new();
        for _ in 0..n {
            let k = self.string()?;
            let v = self.value(depth)?;
            m.insert(k, v);
        }
        Ok(m)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ModelBuilder, model::tests::sample};

    fn bytes(m: &Model) -> Vec<u8> {
        let mut out = Vec::new();
        m.write_binary(&mut out).unwrap();
        out
    }

    fn json(m: &Model) -> String {
        serde_json::to_string(m).unwrap()
    }

    fn rich() -> Model {
        let mut b = ModelBuilder::new();
        let rec = b.define_kind(
            "record",
            EntityKind::Class,
            TraitMask(0b101),
            Some("Famix-Java-Entities.Record"),
        );
        b.set_kind_concept(rec, Some("Record"), Some("records"));
        b.set_kind_traits(KindId::of(EntityKind::Method), TraitMask(0b10));
        let r = b.entity_of_kind("r", rec, "R");
        let m = b.entity("m", EntityKind::Method, "m");
        let f = b.entity("f", EntityKind::Field, "f");
        b.set_parent(m, Some(r));
        b.set_source(r, "src/é.java", Range::new(0, 0, 9, 1), None);
        b.set_source(
            m,
            "src/é.java",
            Range::new(1, 2, 3, 4),
            Some(Range::new(1, 6, 1, 7)),
        );
        let mut nested = BTreeMap::new();
        nested.insert(
            "deep".to_string(),
            Value::List(vec![Value::Int(-3), true.into()]),
        );
        b.set_prop(m, "x.map", Value::Map(nested));
        b.set_prop(m, "x.int", i64::MIN);
        b.set_prop(f, "x.str", "ünïcode");
        b.occurrence_flagged(
            &RelationKind::Accesses,
            m,
            f,
            Provenance::Scip,
            Range::new(2, 4, 2, 5),
            SiteFlags::READ | SiteFlags::WRITE,
        );
        b.relate(
            &RelationKind::Other("gwt-rpc".into()),
            m,
            r,
            Provenance::Frontend,
        );
        b.build()
    }

    #[test]
    fn round_trips_every_column() {
        for m in [sample(), rich(), ModelBuilder::new().build()] {
            let back = Model::read_binary(&bytes(&m)[..]).unwrap();
            assert_eq!(json(&back), json(&m));
            assert_eq!(back.metamodel(), m.metamodel());
            let (a, b) = (back.memory(), m.memory());
            assert_eq!(
                (a.entities, a.relations, a.sites, a.strings),
                (b.entities, b.relations, b.sites, b.strings)
            );
            assert!(a.heap_bytes <= b.heap_bytes, "exact capacities");
            assert_eq!(bytes(&back), bytes(&m), "stable");
        }
        let m = Model::read_binary(&bytes(&rich())[..]).unwrap();
        let method = m.by_key("m").unwrap();
        assert!(
            method.has_trait(TraitMask(0b10)),
            "default kind traits kept"
        );
        assert_eq!(method.parent().map(|p| p.kind_name()), Some("record"));
        assert_eq!(method.outgoing().next().unwrap().site_flags()[0].0, 3);
    }

    #[test]
    fn detects_its_magic() {
        assert!(is_binary(&bytes(&sample())));
        assert!(!is_binary(b"{\"entities\":[]}"));
        assert!(!is_binary(b"MODEL"));
    }

    #[test]
    fn refuses_other_versions() {
        let mut b = bytes(&sample());
        b[8] = 2;
        let e = Model::read_binary(&b[..]).unwrap_err();
        assert!(e.to_string().contains("version 2"), "{e}");
    }

    #[test]
    fn truncation_is_an_error_at_every_length() {
        let b = bytes(&rich());
        for len in 0..b.len() {
            let e = Model::read_binary(&b[..len]).unwrap_err();
            assert_eq!(e.kind(), io::ErrorKind::InvalidData, "at {len}");
        }
    }

    #[test]
    fn corruption_never_panics() {
        for m in [sample(), rich()] {
            let b = bytes(&m);
            for at in 0..b.len() {
                for x in [0x01, 0x80, 0xff] {
                    let mut c = b.clone();
                    c[at] ^= x;
                    if let Ok(m) = Model::read_binary(&c[..]) {
                        // Whatever survived the checks must be navigable.
                        let _ = json(&m);
                        for e in m.entities() {
                            let _ = (e.children().count(), e.incoming().count());
                            let _ = (e.kind_name(), e.ancestors().count());
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn huge_lengths_do_not_allocate_up_front() {
        let mut b = MAGIC.to_vec();
        b.extend_from_slice(&VERSION.to_le_bytes());
        b.extend_from_slice(&u64::MAX.to_le_bytes());
        assert!(Model::read_binary(&b[..]).is_err());
    }
}