1use std::collections::BTreeMap;
29use std::io::{self, Read, Write};
30
31use crate::entity::{EntityId, EntityKind, LanguageId};
32use crate::metamodel::{KindId, KindInfo, Metamodel, TraitMask};
33use crate::model::{EntityRow, Model, NONE, RelRow};
34use crate::relation::{Provenance, RelationKind, SiteFlags};
35use crate::source::Range;
36use crate::strings::{StrId, StrTable};
37use crate::value::{Props, Value};
38
39pub const MAGIC: &[u8; 8] = b"MODELBIN";
41
42pub const VERSION: u32 = 1;
44
45pub fn is_binary(prefix: &[u8]) -> bool {
47 prefix.starts_with(MAGIC)
48}
49
50const ROW_BYTES: usize = 52;
51const REL_BYTES: usize = 11;
52const RANGE_BYTES: usize = 16;
53const MAX_DEPTH: u32 = 64;
55const MAX_RESERVE: u64 = 1 << 28;
58
59fn invalid(what: impl std::fmt::Display) -> io::Error {
60 io::Error::new(io::ErrorKind::InvalidData, format!("binary model: {what}"))
61}
62
63fn relation_tag(k: &RelationKind) -> u8 {
64 match k {
65 RelationKind::Calls => 0,
66 RelationKind::References => 1,
67 RelationKind::Inherits => 2,
68 RelationKind::Implements => 3,
69 RelationKind::Imports => 4,
70 RelationKind::DeclaredType => 5,
71 RelationKind::Accesses => 6,
72 RelationKind::Throws => 7,
73 RelationKind::Overrides => 8,
74 RelationKind::Other(_) => 255,
75 }
76}
77
78fn provenance_tag(p: Provenance) -> u8 {
79 match p {
80 Provenance::TreeSitter => 0,
81 Provenance::Scip => 1,
82 Provenance::Frontend => 2,
83 Provenance::Derived => 3,
84 }
85}
86
87fn provenance_of(tag: u8) -> io::Result<Provenance> {
88 Ok(match tag {
89 0 => Provenance::TreeSitter,
90 1 => Provenance::Scip,
91 2 => Provenance::Frontend,
92 3 => Provenance::Derived,
93 t => return Err(invalid(format_args!("unknown provenance {t}"))),
94 })
95}
96
97struct Out<W> {
100 w: W,
101}
102
103impl<W: Write> Out<W> {
104 fn bytes(&mut self, b: &[u8]) -> io::Result<()> {
105 self.w.write_all(b)
106 }
107
108 fn u8(&mut self, v: u8) -> io::Result<()> {
109 self.bytes(&[v])
110 }
111
112 fn u32(&mut self, v: u32) -> io::Result<()> {
113 self.bytes(&v.to_le_bytes())
114 }
115
116 fn u64(&mut self, v: u64) -> io::Result<()> {
117 self.bytes(&v.to_le_bytes())
118 }
119
120 fn len(&mut self, n: usize) -> io::Result<()> {
121 self.u64(n as u64)
122 }
123
124 fn str(&mut self, s: &str) -> io::Result<()> {
125 self.len(s.len())?;
126 self.bytes(s.as_bytes())
127 }
128
129 fn opt_str(&mut self, s: Option<&str>) -> io::Result<()> {
130 match s {
131 None => self.u8(0),
132 Some(s) => {
133 self.u8(1)?;
134 self.str(s)
135 }
136 }
137 }
138
139 fn column<T>(
141 &mut self,
142 items: &[T],
143 size: usize,
144 mut put: impl FnMut(&T, &mut Vec<u8>),
145 ) -> io::Result<()> {
146 self.len(items.len())?;
147 let mut buf = Vec::with_capacity(size * 4096);
148 for chunk in items.chunks(4096) {
149 buf.clear();
150 for item in chunk {
151 put(item, &mut buf);
152 }
153 self.bytes(&buf)?;
154 }
155 Ok(())
156 }
157
158 fn u32s(&mut self, items: &[u32]) -> io::Result<()> {
159 self.column(items, 4, |v, b| b.extend_from_slice(&v.to_le_bytes()))
160 }
161
162 fn ids(&mut self, items: &[EntityId]) -> io::Result<()> {
163 self.column(items, 4, |v, b| b.extend_from_slice(&v.0.to_le_bytes()))
164 }
165
166 fn value(&mut self, v: &Value) -> io::Result<()> {
167 match v {
168 Value::Bool(b) => {
169 self.u8(0)?;
170 self.u8(*b as u8)
171 }
172 Value::Int(i) => {
173 self.u8(1)?;
174 self.bytes(&i.to_le_bytes())
175 }
176 Value::Str(s) => {
177 self.u8(2)?;
178 self.str(s)
179 }
180 Value::List(l) => {
181 self.u8(3)?;
182 self.len(l.len())?;
183 l.iter().try_for_each(|v| self.value(v))
184 }
185 Value::Map(m) => {
186 self.u8(4)?;
187 self.map(m)
188 }
189 }
190 }
191
192 fn map(&mut self, m: &BTreeMap<String, Value>) -> io::Result<()> {
193 self.len(m.len())?;
194 for (k, v) in m {
195 self.str(k)?;
196 self.value(v)?;
197 }
198 Ok(())
199 }
200}
201
202fn put_range(r: &Range, b: &mut Vec<u8>) {
203 for v in [r.start_line, r.start_col, r.end_line, r.end_col] {
204 b.extend_from_slice(&v.to_le_bytes());
205 }
206}
207
208impl Model {
209 pub fn write_binary<W: Write>(&self, w: W) -> io::Result<()> {
212 let mut o = Out { w };
213 o.bytes(MAGIC)?;
214 o.u32(VERSION)?;
215
216 o.str(self.strings.bytes())?;
217 let offsets = self.strings.offsets();
218 o.column(offsets, 8, |v, b| {
219 b.extend_from_slice(&(*v as u64).to_le_bytes())
220 })?;
221
222 o.len(self.languages.len())?;
223 for l in &self.languages {
224 o.str(l.as_str())?;
225 }
226
227 o.len(self.metamodel.len())?;
228 for (_, k) in self.metamodel.iter() {
229 o.str(&k.name)?;
230 o.u8(k.archetype as u8)?;
231 o.u64(k.traits.0)?;
232 o.opt_str(k.fm3.as_deref())?;
233 o.opt_str(k.graphql_type.as_deref())?;
234 o.opt_str(k.graphql_root.as_deref())?;
235 }
236
237 o.len(self.kinds.len())?;
238 for k in &self.kinds {
239 o.u8(relation_tag(k))?;
240 if let RelationKind::Other(name) = k {
241 o.str(name)?;
242 }
243 }
244
245 o.column(&self.entities, ROW_BYTES, |e, b| {
246 for v in [e.key.0, e.name.0, e.file, e.parent] {
247 b.extend_from_slice(&v.to_le_bytes());
248 }
249 put_range(&e.range, b);
250 put_range(&e.name_range, b);
251 b.push(e.kind.0);
252 b.extend_from_slice(&e.language.to_le_bytes());
253 b.push(e.flags);
254 })?;
255
256 o.len(self.props.len())?;
257 for (id, props) in &self.props {
258 o.u32(id.0)?;
259 o.map(props)?;
260 }
261
262 o.ids(&self.by_key)?;
263 o.u32s(&self.child_offsets)?;
264 o.ids(&self.children)?;
265 o.column(&self.relations, REL_BYTES, |r, b| {
266 b.extend_from_slice(&r.from.0.to_le_bytes());
267 b.extend_from_slice(&r.kind.to_le_bytes());
268 b.extend_from_slice(&r.to.0.to_le_bytes());
269 b.push(provenance_tag(r.provenance));
270 })?;
271 o.u32s(&self.out_offsets)?;
272 o.u32s(&self.in_offsets)?;
273 o.u32s(&self.incoming)?;
274 o.u32s(&self.site_offsets)?;
275 o.column(&self.sites, RANGE_BYTES, put_range)?;
276 o.column(&self.site_flags, 1, |f, b| b.push(f.0))?;
277 o.w.flush()
278 }
279
280 pub fn read_binary<R: Read>(r: R) -> io::Result<Model> {
283 let mut i = In { r };
284 let mut magic = [0u8; 8];
285 i.exact(&mut magic)?;
286 if &magic != MAGIC {
287 return Err(invalid("not a binary model (bad magic)"));
288 }
289 let version = i.u32()?;
290 if version != VERSION {
291 return Err(invalid(format_args!(
292 "format version {version}, this reader knows {VERSION}"
293 )));
294 }
295
296 let bytes = i.string()?;
297 let offsets = i.column(8, |c| u64_at(c, 0) as usize)?;
298 let strings = StrTable::from_parts(bytes, offsets)
299 .ok_or_else(|| invalid("string offsets out of order or off char boundaries"))?;
300
301 let n = i.len()?;
302 let mut languages = Vec::with_capacity(n.min(1024));
303 for _ in 0..n {
304 languages.push(LanguageId::new(i.string()?));
305 }
306
307 let n = i.len()?;
308 let mut kinds = Vec::with_capacity(n.min(256));
309 for _ in 0..n {
310 let name = i.string()?;
311 let archetype = *EntityKind::ALL
312 .get(i.u8()? as usize)
313 .ok_or_else(|| invalid("unknown archetype"))?;
314 kinds.push(KindInfo {
315 name,
316 archetype,
317 traits: TraitMask(i.u64()?),
318 fm3: i.opt_string()?,
319 graphql_type: i.opt_string()?,
320 graphql_root: i.opt_string()?,
321 });
322 }
323 let metamodel = Metamodel::from_kinds(kinds)
324 .ok_or_else(|| invalid("metamodel must start with the archetypes, ≤ 256 kinds"))?;
325
326 let n = i.len()?;
327 let mut rel_kinds = Vec::with_capacity(n.min(1024));
328 for _ in 0..n {
329 rel_kinds.push(match i.u8()? {
330 0 => RelationKind::Calls,
331 1 => RelationKind::References,
332 2 => RelationKind::Inherits,
333 3 => RelationKind::Implements,
334 4 => RelationKind::Imports,
335 5 => RelationKind::DeclaredType,
336 6 => RelationKind::Accesses,
337 7 => RelationKind::Throws,
338 8 => RelationKind::Overrides,
339 255 => RelationKind::Other(i.string()?),
340 t => return Err(invalid(format_args!("unknown relation kind {t}"))),
341 });
342 }
343 if rel_kinds.len() > u16::MAX as usize + 1 {
344 return Err(invalid("too many relation kinds"));
345 }
346
347 let entities = i.column(ROW_BYTES, |c| EntityRow {
348 key: StrId(u32_at(c, 0)),
349 name: StrId(u32_at(c, 4)),
350 file: u32_at(c, 8),
351 parent: u32_at(c, 12),
352 range: range_at(c, 16),
353 name_range: range_at(c, 32),
354 kind: KindId(c[48]),
355 language: u16::from_le_bytes([c[49], c[50]]),
356 flags: c[51],
357 })?;
358
359 let n = i.len()?;
360 let mut props: Vec<(EntityId, Props)> = Vec::with_capacity(n.min(1 << 20));
361 for _ in 0..n {
362 let id = EntityId(i.u32()?);
363 props.push((id, i.map(0)?));
364 }
365
366 let by_key = i.column(4, |c| EntityId(u32_at(c, 0)))?;
367 let child_offsets = i.column(4, |c| u32_at(c, 0))?;
368 let children = i.column(4, |c| EntityId(u32_at(c, 0)))?;
369 let relations = i.column(REL_BYTES, |c| {
370 (
371 RelRow {
372 from: EntityId(u32_at(c, 0)),
373 kind: u16::from_le_bytes([c[4], c[5]]),
374 to: EntityId(u32_at(c, 6)),
375 provenance: Provenance::Derived,
376 },
377 c[10],
378 )
379 })?;
380 let relations = relations
381 .into_iter()
382 .map(|(mut r, p)| {
383 r.provenance = provenance_of(p)?;
384 Ok(r)
385 })
386 .collect::<io::Result<Vec<_>>>()?;
387 let out_offsets = i.column(4, |c| u32_at(c, 0))?;
388 let in_offsets = i.column(4, |c| u32_at(c, 0))?;
389 let incoming = i.column(4, |c| u32_at(c, 0))?;
390 let site_offsets = i.column(4, |c| u32_at(c, 0))?;
391 let sites = i.column(RANGE_BYTES, |c| range_at(c, 0))?;
392 let site_flags = i.column(1, |c| SiteFlags(c[0]))?;
393
394 let model = Model {
395 strings,
396 languages,
397 metamodel,
398 kinds: rel_kinds,
399 entities,
400 props,
401 by_key,
402 child_offsets,
403 children,
404 relations,
405 out_offsets,
406 in_offsets,
407 incoming,
408 site_offsets,
409 sites,
410 site_flags,
411 };
412 model.check().map_err(invalid)?;
413 Ok(model)
414 }
415
416 fn check(&self) -> Result<(), &'static str> {
418 let n = self.entities.len();
419 let strings = self.strings.len();
420 let in_str = |id: u32| (id as usize) < strings;
421 for e in &self.entities {
422 if !in_str(e.key.0) || !in_str(e.name.0) {
423 return Err("entity string out of range");
424 }
425 if e.file != NONE && !in_str(e.file) {
426 return Err("entity file out of range");
427 }
428 if e.parent != NONE && e.parent as usize >= n {
429 return Err("entity parent out of range");
430 }
431 if e.kind.index() >= self.metamodel.len() {
432 return Err("entity kind out of range");
433 }
434 }
435 if !self.props.windows(2).all(|w| w[0].0 < w[1].0)
436 || self.props.last().is_some_and(|p| p.0.index() >= n)
437 {
438 return Err("props not sorted by entity or out of range");
439 }
440 if self.by_key.len() != n || self.by_key.iter().any(|id| id.index() >= n) {
441 return Err("key index does not match the entities");
442 }
443 let key = |id: &EntityId| self.strings.get(self.entities[id.index()].key);
444 if !self.by_key.windows(2).all(|w| key(&w[0]) <= key(&w[1])) {
445 return Err("key index not sorted");
446 }
447 csr(&self.child_offsets, n, self.children.len(), "children")?;
448 if self.children.iter().any(|c| c.index() >= n) {
449 return Err("child out of range");
450 }
451 let r = self.relations.len();
452 if self.relations.iter().any(|rel| {
453 rel.from.index() >= n || rel.to.index() >= n || rel.kind as usize >= self.kinds.len()
454 }) {
455 return Err("relation endpoint or kind out of range");
456 }
457 if !self.relations.windows(2).all(|w| w[0] < w[1]) {
458 return Err("relations not sorted");
459 }
460 csr(&self.out_offsets, n, r, "outgoing")?;
461 csr(&self.in_offsets, n, self.incoming.len(), "incoming")?;
462 if self.incoming.len() != r || self.incoming.iter().any(|&i| i as usize >= r) {
463 return Err("incoming index does not match the relations");
464 }
465 csr(&self.site_offsets, r, self.sites.len(), "sites")?;
466 if self.site_flags.len() != self.sites.len() {
467 return Err("site flags do not match the sites");
468 }
469 Ok(())
470 }
471}
472
473fn csr(
475 offsets: &[u32],
476 buckets: usize,
477 len: usize,
478 what: &'static str,
479) -> Result<(), &'static str> {
480 let ok = offsets.len() == buckets + 1
481 && offsets.first() == Some(&0)
482 && offsets.last().map(|&l| l as usize) == Some(len)
483 && offsets.windows(2).all(|w| w[0] <= w[1]);
484 if ok { Ok(()) } else { Err(what) }
485}
486
487fn u32_at(c: &[u8], at: usize) -> u32 {
490 u32::from_le_bytes([c[at], c[at + 1], c[at + 2], c[at + 3]])
491}
492
493fn u64_at(c: &[u8], at: usize) -> u64 {
494 let mut b = [0u8; 8];
495 b.copy_from_slice(&c[at..at + 8]);
496 u64::from_le_bytes(b)
497}
498
499fn range_at(c: &[u8], at: usize) -> Range {
500 Range::new(
501 u32_at(c, at),
502 u32_at(c, at + 4),
503 u32_at(c, at + 8),
504 u32_at(c, at + 12),
505 )
506}
507
508struct In<R> {
509 r: R,
510}
511
512impl<R: Read> In<R> {
513 fn exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
514 self.r.read_exact(buf).map_err(|e| match e.kind() {
515 io::ErrorKind::UnexpectedEof => invalid("truncated"),
516 _ => e,
517 })
518 }
519
520 fn u8(&mut self) -> io::Result<u8> {
521 let mut b = [0u8; 1];
522 self.exact(&mut b)?;
523 Ok(b[0])
524 }
525
526 fn u32(&mut self) -> io::Result<u32> {
527 let mut b = [0u8; 4];
528 self.exact(&mut b)?;
529 Ok(u32::from_le_bytes(b))
530 }
531
532 fn u64(&mut self) -> io::Result<u64> {
533 let mut b = [0u8; 8];
534 self.exact(&mut b)?;
535 Ok(u64::from_le_bytes(b))
536 }
537
538 fn len(&mut self) -> io::Result<usize> {
539 usize::try_from(self.u64()?).map_err(|_| invalid("length too large"))
540 }
541
542 fn take(&mut self, n: u64) -> io::Result<Vec<u8>> {
544 let mut buf = Vec::with_capacity(n.min(MAX_RESERVE) as usize);
545 (&mut self.r).take(n).read_to_end(&mut buf)?;
546 if buf.len() as u64 != n {
547 return Err(invalid("truncated"));
548 }
549 Ok(buf)
550 }
551
552 fn string(&mut self) -> io::Result<String> {
553 let n = self.u64()?;
554 String::from_utf8(self.take(n)?).map_err(|_| invalid("string is not UTF-8"))
555 }
556
557 fn opt_string(&mut self) -> io::Result<Option<String>> {
558 match self.u8()? {
559 0 => Ok(None),
560 1 => self.string().map(Some),
561 t => Err(invalid(format_args!("bad option tag {t}"))),
562 }
563 }
564
565 fn column<T>(&mut self, size: usize, get: impl Fn(&[u8]) -> T) -> io::Result<Vec<T>> {
566 let n = self.u64()?;
567 let bytes = n
568 .checked_mul(size as u64)
569 .ok_or_else(|| invalid("length too large"))?;
570 let raw = self.take(bytes)?;
571 Ok(raw.chunks_exact(size).map(get).collect())
572 }
573
574 fn value(&mut self, depth: u32) -> io::Result<Value> {
575 if depth > MAX_DEPTH {
576 return Err(invalid("props nested too deeply"));
577 }
578 Ok(match self.u8()? {
579 0 => Value::Bool(self.u8()? != 0),
580 1 => {
581 let mut b = [0u8; 8];
582 self.exact(&mut b)?;
583 Value::Int(i64::from_le_bytes(b))
584 }
585 2 => Value::Str(self.string()?),
586 3 => {
587 let n = self.len()?;
588 let mut l = Vec::with_capacity(n.min(1024));
589 for _ in 0..n {
590 l.push(self.value(depth + 1)?);
591 }
592 Value::List(l)
593 }
594 4 => Value::Map(self.map(depth + 1)?),
595 t => return Err(invalid(format_args!("unknown value tag {t}"))),
596 })
597 }
598
599 fn map(&mut self, depth: u32) -> io::Result<BTreeMap<String, Value>> {
600 let n = self.len()?;
601 let mut m = BTreeMap::new();
602 for _ in 0..n {
603 let k = self.string()?;
604 let v = self.value(depth)?;
605 m.insert(k, v);
606 }
607 Ok(m)
608 }
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614 use crate::{ModelBuilder, model::tests::sample};
615
616 fn bytes(m: &Model) -> Vec<u8> {
617 let mut out = Vec::new();
618 m.write_binary(&mut out).unwrap();
619 out
620 }
621
622 fn json(m: &Model) -> String {
623 serde_json::to_string(m).unwrap()
624 }
625
626 fn rich() -> Model {
627 let mut b = ModelBuilder::new();
628 let rec = b.define_kind(
629 "record",
630 EntityKind::Class,
631 TraitMask(0b101),
632 Some("Famix-Java-Entities.Record"),
633 );
634 b.set_kind_concept(rec, Some("Record"), Some("records"));
635 b.set_kind_traits(KindId::of(EntityKind::Method), TraitMask(0b10));
636 let r = b.entity_of_kind("r", rec, "R");
637 let m = b.entity("m", EntityKind::Method, "m");
638 let f = b.entity("f", EntityKind::Field, "f");
639 b.set_parent(m, Some(r));
640 b.set_source(r, "src/é.java", Range::new(0, 0, 9, 1), None);
641 b.set_source(
642 m,
643 "src/é.java",
644 Range::new(1, 2, 3, 4),
645 Some(Range::new(1, 6, 1, 7)),
646 );
647 let mut nested = BTreeMap::new();
648 nested.insert(
649 "deep".to_string(),
650 Value::List(vec![Value::Int(-3), true.into()]),
651 );
652 b.set_prop(m, "x.map", Value::Map(nested));
653 b.set_prop(m, "x.int", i64::MIN);
654 b.set_prop(f, "x.str", "ünïcode");
655 b.occurrence_flagged(
656 &RelationKind::Accesses,
657 m,
658 f,
659 Provenance::Scip,
660 Range::new(2, 4, 2, 5),
661 SiteFlags::READ | SiteFlags::WRITE,
662 );
663 b.relate(
664 &RelationKind::Other("gwt-rpc".into()),
665 m,
666 r,
667 Provenance::Frontend,
668 );
669 b.build()
670 }
671
672 #[test]
673 fn round_trips_every_column() {
674 for m in [sample(), rich(), ModelBuilder::new().build()] {
675 let back = Model::read_binary(&bytes(&m)[..]).unwrap();
676 assert_eq!(json(&back), json(&m));
677 assert_eq!(back.metamodel(), m.metamodel());
678 let (a, b) = (back.memory(), m.memory());
679 assert_eq!(
680 (a.entities, a.relations, a.sites, a.strings),
681 (b.entities, b.relations, b.sites, b.strings)
682 );
683 assert!(a.heap_bytes <= b.heap_bytes, "exact capacities");
684 assert_eq!(bytes(&back), bytes(&m), "stable");
685 }
686 let m = Model::read_binary(&bytes(&rich())[..]).unwrap();
687 let method = m.by_key("m").unwrap();
688 assert!(
689 method.has_trait(TraitMask(0b10)),
690 "default kind traits kept"
691 );
692 assert_eq!(method.parent().map(|p| p.kind_name()), Some("record"));
693 assert_eq!(method.outgoing().next().unwrap().site_flags()[0].0, 3);
694 }
695
696 #[test]
697 fn detects_its_magic() {
698 assert!(is_binary(&bytes(&sample())));
699 assert!(!is_binary(b"{\"entities\":[]}"));
700 assert!(!is_binary(b"MODEL"));
701 }
702
703 #[test]
704 fn refuses_other_versions() {
705 let mut b = bytes(&sample());
706 b[8] = 2;
707 let e = Model::read_binary(&b[..]).unwrap_err();
708 assert!(e.to_string().contains("version 2"), "{e}");
709 }
710
711 #[test]
712 fn truncation_is_an_error_at_every_length() {
713 let b = bytes(&rich());
714 for len in 0..b.len() {
715 let e = Model::read_binary(&b[..len]).unwrap_err();
716 assert_eq!(e.kind(), io::ErrorKind::InvalidData, "at {len}");
717 }
718 }
719
720 #[test]
721 fn corruption_never_panics() {
722 for m in [sample(), rich()] {
723 let b = bytes(&m);
724 for at in 0..b.len() {
725 for x in [0x01, 0x80, 0xff] {
726 let mut c = b.clone();
727 c[at] ^= x;
728 if let Ok(m) = Model::read_binary(&c[..]) {
729 let _ = json(&m);
731 for e in m.entities() {
732 let _ = (e.children().count(), e.incoming().count());
733 let _ = (e.kind_name(), e.ancestors().count());
734 }
735 }
736 }
737 }
738 }
739 }
740
741 #[test]
742 fn huge_lengths_do_not_allocate_up_front() {
743 let mut b = MAGIC.to_vec();
744 b.extend_from_slice(&VERSION.to_le_bytes());
745 b.extend_from_slice(&u64::MAX.to_le_bytes());
746 assert!(Model::read_binary(&b[..]).is_err());
747 }
748}