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};
pub const MAGIC: &[u8; 8] = b"MODELBIN";
pub const VERSION: u32 = 1;
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;
const MAX_DEPTH: u32 = 64;
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}"))),
})
}
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)
}
}
}
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 {
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()
}
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)
}
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(())
}
}
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) }
}
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"))
}
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[..]) {
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());
}
}