Skip to main content

aft_store/content/
mod.rs

1//! Content records: everything parsing one file content yields, stored once
2//! per content and shared by every checkout and path that holds it.
3//!
4//! A record has two parts. The **surface** is what other files may read
5//! about this one when they are resolved: its symbols, exports, default
6//! export, entry points and type facts. The **body** is what only this
7//! file's own resolution reads: its references, imports, Python bindings and
8//! method-call sites. Resolving a file reads its own body and the surfaces it
9//! depends on, never another file's body.
10//!
11//! Configuration files are stored as their raw bytes: how they are
12//! interpreted depends on the checkout they configure.
13//!
14//! Records hold no paths. Positions (lines, columns, byte ranges, syntax-tree
15//! ordinals) are within the content, so they are the same wherever the
16//! content appears.
17//!
18//! A record can also hold the content's TODO markers ([`TodoMarkers`]),
19//! found in its comments when it was parsed, so counting a checkout's TODOs
20//! never parses a file. They are written in the first part, right after
21//! the record's kind, though no other file reads them: that part is stored
22//! uncompressed, so a count reads each file's markers
23//! ([`ContentRecord::todos_of`]) without unpacking its body. Files the call
24//! graph does not parse but whose comments are counted (Markdown, minified
25//! bundles) get a record holding only their markers ([`RecordBody::Markers`]).
26
27pub mod codec;
28mod sections;
29mod stage;
30
31pub use sections::{
32    ContentReadError, ContentSectionsBuilder, ContentSegment, EncodedRecord, KNOWN,
33    SECTIONS_VERSION, write_folded,
34};
35pub use stage::{PackedRecord, Stage, StageWriter, StagedUnit, write_staged};
36
37use codec::{Decoder, Encoder};
38
39use crate::ids::{ContentKey, Digest128};
40
41/// The key of a content record: the content, the language it is parsed as,
42/// and the extractor version. The same bytes at a `.ts` and a `.js` path are
43/// two records; a new extractor version never reads an old one.
44#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
45pub struct RecordKey(Digest128);
46
47impl RecordKey {
48    #[must_use]
49    pub fn new(content: ContentKey, language: &str, extractor_version: &str) -> Self {
50        let mut hasher = blake3::Hasher::new_derive_key("aft-store 2026-11 content record key");
51        hasher.update(content.digest().as_bytes());
52        for part in [language, extractor_version] {
53            hasher.update(&(part.len() as u64).to_le_bytes());
54            hasher.update(part.as_bytes());
55        }
56        Self(Digest128::from_hash(&hasher.finalize()))
57    }
58
59    /// A key read back from storage.
60    #[must_use]
61    pub const fn from_digest(digest: Digest128) -> Self {
62        Self(digest)
63    }
64
65    #[must_use]
66    pub const fn digest(&self) -> Digest128 {
67        self.0
68    }
69}
70
71/// Why stored bytes are not a well-formed record.
72#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
73#[error("content record does not decode: {0}")]
74pub struct DecodeError(pub &'static str);
75
76/// One symbol a file defines.
77#[derive(Clone, PartialEq, Eq, Debug)]
78pub struct Symbol {
79    pub is_test: Option<bool>,
80    /// The syntax-tree pre-order position of the defining node.
81    pub ordinal: u32,
82    pub name: String,
83    pub scoped_name: String,
84    pub kind: String,
85    pub exported: bool,
86    pub is_default_export: bool,
87    pub start_line: u32,
88    pub start_col: u32,
89    pub end_line: u32,
90    pub end_col: u32,
91    pub signature: Option<String>,
92    /// Whether the program starts at this symbol, as its language defines
93    /// it (`fn main`, `func main` in a Go `package main`, a Go
94    /// `func init()`, a C `main`).
95    pub program_start: bool,
96    /// The entry attribute or decorator extraction recorded on the symbol,
97    /// such as `no_mangle` or `tauri::command`.
98    pub entry_attribute: Option<String>,
99}
100
101/// The parse-level class of a reference.
102#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
103pub enum RefKind {
104    Construction,
105    CallbackRef,
106    Call,
107    ValueRef,
108    Import,
109    Module,
110    Reexport,
111    ExportAlias,
112    /// A name inside a Rust macro whose tokens could not be parsed as
113    /// Rust: a possible call the graph cannot see.
114    MacroMention,
115}
116
117impl RefKind {
118    const ALL: [Self; 9] = [
119        Self::Construction,
120        Self::CallbackRef,
121        Self::Call,
122        Self::ValueRef,
123        Self::Import,
124        Self::Module,
125        Self::Reexport,
126        Self::ExportAlias,
127        Self::MacroMention,
128    ];
129
130    fn code(self) -> u8 {
131        Self::ALL
132            .iter()
133            .position(|kind| *kind == self)
134            .and_then(|index| u8::try_from(index).ok())
135            .expect("every kind is in ALL")
136    }
137
138    fn from_code(code: u8) -> Result<Self, DecodeError> {
139        Self::ALL
140            .get(usize::from(code))
141            .copied()
142            .ok_or(DecodeError("reference kind"))
143    }
144}
145
146/// A reference as extracted, before resolution: no target is known.
147#[derive(Clone, PartialEq, Eq, Debug)]
148pub struct Reference {
149    pub ordinal: u32,
150    pub kind: RefKind,
151    pub caller_symbol: Option<String>,
152    pub short_name: Option<String>,
153    pub full_ref: Option<String>,
154    pub module_path: Option<String>,
155    pub line: u32,
156    pub byte_start: u64,
157    pub byte_end: u64,
158    pub path_override: Option<String>,
159    pub local_name: Option<String>,
160    pub requested_name: Option<String>,
161    pub namespace_alias: Option<String>,
162    pub wildcard: bool,
163    pub import_kind: Option<String>,
164}
165
166/// An import statement.
167#[derive(Clone, PartialEq, Eq, Debug)]
168pub struct Import {
169    pub ordinal: u32,
170    pub module_path: String,
171    pub names: Vec<String>,
172    pub default_import: Option<String>,
173    pub namespace_import: Option<String>,
174    pub byte_start: u64,
175    pub byte_end: u64,
176    pub raw_text: String,
177    pub type_only: bool,
178    pub side_effect: bool,
179}
180
181/// A Python name binding at one span: the module and symbol it refers to,
182/// or `None` when it is shadowed locally.
183#[derive(Clone, PartialEq, Eq, Debug)]
184pub struct PythonBinding {
185    pub byte_start: u64,
186    pub byte_end: u64,
187    pub target: Option<(String, String)>,
188}
189
190#[derive(Clone, PartialEq, Eq, Debug)]
191pub struct TypeFact {
192    pub name: String,
193    pub bases: Vec<String>,
194    pub interface: bool,
195    pub closed: bool,
196}
197
198#[derive(Clone, PartialEq, Eq, Debug)]
199pub struct MethodFact {
200    pub owner: String,
201    pub trait_name: Option<String>,
202    pub name: String,
203    pub symbol: String,
204    pub has_body: bool,
205    pub shape: String,
206    pub private: bool,
207}
208
209#[derive(Clone, PartialEq, Eq, Debug)]
210pub struct FieldFact {
211    pub owner: String,
212    pub name: String,
213    pub ty: String,
214}
215
216#[derive(Clone, PartialEq, Eq, Debug)]
217pub struct ReturnFact {
218    pub symbol: String,
219    pub ty: String,
220}
221
222/// A method-call site: a call whose target depends on a receiver's type.
223#[derive(Clone, PartialEq, Eq, Debug)]
224pub struct CallSite {
225    pub ordinal: u32,
226    pub caller: Option<String>,
227    pub line: u32,
228    pub member: Option<String>,
229    pub receiver: Option<String>,
230    pub dynamic: bool,
231}
232
233/// What other files may read about a parsed file.
234#[derive(Clone, PartialEq, Eq, Debug, Default)]
235pub struct Surface {
236    pub symbols: Vec<Symbol>,
237    pub default_export_symbol: Option<String>,
238    pub exported_symbols: Vec<String>,
239    pub callable_symbols: Vec<String>,
240    pub entry_point_symbols: Vec<String>,
241    /// Go's package clause, which tells co-located test packages apart.
242    pub go_package: Option<String>,
243    pub types: Vec<TypeFact>,
244    pub methods: Vec<MethodFact>,
245    pub fields: Vec<FieldFact>,
246    pub returns: Vec<ReturnFact>,
247}
248
249/// One symbol as outline lists it. Outline reads the parser's own symbol
250/// table for a file, which differs from [`Surface::symbols`]: the call graph
251/// qualifies, adds and merges symbols for resolution, outline shows them as
252/// written. Lines and columns are zero-based.
253#[derive(Clone, PartialEq, Eq, Debug)]
254pub struct OutlineSymbol {
255    pub name: String,
256    /// The parser's symbol kind, in its snake-case name (`function`,
257    /// `type_alias`).
258    pub kind: String,
259    pub start_line: u32,
260    pub start_col: u32,
261    pub end_line: u32,
262    pub end_col: u32,
263    pub signature: Option<String>,
264    /// The enclosing scopes, outermost first.
265    pub scope_chain: Vec<String>,
266    pub exported: bool,
267    pub parent: Option<String>,
268}
269
270/// What only reads of this one file need: its own resolution, and its
271/// outline.
272#[derive(Clone, PartialEq, Eq, Debug, Default)]
273pub struct Body {
274    pub imports: Vec<Import>,
275    pub python_bindings: Vec<PythonBinding>,
276    pub references: Vec<Reference>,
277    pub call_sites: Vec<CallSite>,
278    /// The file's symbols as outline lists them, in the parser's order.
279    /// `None` in a record from an extractor that did not store them.
280    pub outline: Option<Vec<OutlineSymbol>>,
281    /// What dead-code analysis reads from the file's syntax tree, recorded
282    /// when the file is parsed so an analysis never parses it again. The
283    /// store does not read these bytes: their format belongs to the
284    /// extractor that wrote them, which the record's extractor version
285    /// names. `None` in a record from an extractor that did not store them.
286    pub dead_code: Option<Vec<u8>>,
287    /// Sparse static receiver evidence; its format belongs to the extractor.
288    pub static_dispatch: Option<Vec<u8>>,
289}
290
291/// What a content record holds.
292#[derive(Clone, PartialEq, Eq, Debug)]
293pub enum RecordBody {
294    Parsed {
295        surface: Box<Surface>,
296        body: Box<Body>,
297    },
298    /// A configuration file's raw bytes.
299    Config { source: Vec<u8> },
300    /// Nothing but the record's [`ContentRecord::todos`]: a file the call
301    /// graph does not parse whose comments are still counted.
302    Markers,
303}
304
305/// One TODO marker comment line, as AFT's TODO count reports it.
306#[derive(Clone, PartialEq, Eq, Debug)]
307pub struct TodoMarker {
308    /// The one-based line the marker is on.
309    pub line: u32,
310    /// The marker word, such as `TODO` or `FIXME`.
311    pub marker: String,
312    /// The name in parentheses after the marker (`TODO(name):`), if any.
313    pub author: Option<String>,
314    /// The comment's text after the marker, as the count shows it.
315    pub text: String,
316}
317
318/// The TODO markers of one content.
319#[derive(Clone, PartialEq, Eq, Debug)]
320pub struct TodoMarkers {
321    /// The language the content's comments were read as. The same bytes can
322    /// be read as another language at another path, so a reader checks it
323    /// against the path's.
324    pub language: String,
325    /// The markers in line order; `None` when the content is not text the
326    /// count reads (not UTF-8, or holding a NUL byte).
327    pub items: Option<Vec<TodoMarker>>,
328}
329
330/// Everything parsing one content yields.
331#[derive(Clone, PartialEq, Eq, Debug)]
332pub struct ContentRecord {
333    pub language: String,
334    /// The extractor that produced the record. A record from another
335    /// version is extracted again, never reused.
336    pub extractor_version: String,
337    pub data: RecordBody,
338    /// The content's TODO markers. `None` in a record from an extractor
339    /// that did not look for them, or of a file whose comments are not
340    /// counted.
341    pub todos: Option<TodoMarkers>,
342}
343
344/// A parsed record whose body holds no outline. Records of this kind encode
345/// exactly as they did before records could hold one.
346const PARSED: u8 = 1;
347const CONFIG: u8 = 2;
348/// A parsed record whose body ends with its outline. The kind byte, not the
349/// body's length, says whether an outline follows, so a body cut short
350/// before its outline still fails to decode.
351const PARSED_WITH_OUTLINE: u8 = 3;
352/// [`PARSED`], with each symbol's entry facts ([`Symbol::program_start`],
353/// [`Symbol::entry_attribute`]) after the rest of the surface. Records of
354/// the two kinds above predate those facts and read back without them.
355const PARSED_WITH_ENTRIES: u8 = 4;
356/// [`PARSED_WITH_OUTLINE`], with each symbol's entry facts after the rest
357/// of the surface.
358const PARSED_WITH_ENTRIES_AND_OUTLINE: u8 = 5;
359/// [`PARSED_WITH_ENTRIES_AND_OUTLINE`], whose body ends with its dead-code
360/// facts after the outline.
361const PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE: u8 = 6;
362/// [`PARSED_WITH_ENTRIES`], whose body ends with its dead-code facts.
363const PARSED_WITH_ENTRIES_AND_DEAD_CODE: u8 = 7;
364/// A parsed record with its TODO markers. After the kind come a byte of
365/// [`HAS_OUTLINE`] and [`HAS_DEAD_CODE`] flags, saying what the body ends
366/// with, then the markers, the surface and each symbol's entry facts.
367const PARSED_WITH_TODOS: u8 = 8;
368/// [`CONFIG`] with the TODO markers between the kind and the source.
369const CONFIG_WITH_TODOS: u8 = 9;
370/// A [`RecordBody::Markers`] record: the kind, then whether markers follow
371/// (a byte, 0 or 1), then the markers. Its body part is empty.
372const MARKERS: u8 = 10;
373/// A parsed record whose body ends with static receiver facts, after the
374/// other optional parts. Its flags also say whether TODO markers follow.
375const PARSED_WITH_STATIC_DISPATCH: u8 = 11;
376const STATIC_HAS_TODOS: u8 = 4;
377/// In a [`PARSED_WITH_TODOS`] record's flags: the body ends with an outline.
378const HAS_OUTLINE: u8 = 1;
379/// In a [`PARSED_WITH_TODOS`] record's flags: the body ends with dead-code
380/// facts, after the outline when there is one.
381const HAS_DEAD_CODE: u8 = 2;
382
383impl ContentRecord {
384    /// The surface part's bytes and the body part's bytes. A configuration
385    /// or markers-only record has an empty body part. A record without TODO
386    /// markers encodes exactly as it did before records could hold them.
387    #[must_use]
388    pub fn encode(&self) -> (Vec<u8>, Vec<u8>) {
389        let mut head = Encoder::default();
390        head.str(&self.language);
391        head.str(&self.extractor_version);
392        match &self.data {
393            RecordBody::Config { source } => {
394                match &self.todos {
395                    None => head.byte(CONFIG),
396                    Some(todos) => {
397                        head.byte(CONFIG_WITH_TODOS);
398                        encode_todos(&mut head, todos);
399                    }
400                }
401                head.blob(source);
402                (head.finish(), Vec::new())
403            }
404            RecordBody::Markers => {
405                head.byte(MARKERS);
406                head.bool(self.todos.is_some());
407                if let Some(todos) = &self.todos {
408                    encode_todos(&mut head, todos);
409                }
410                (head.finish(), Vec::new())
411            }
412            RecordBody::Parsed { surface, body } => {
413                match &self.todos {
414                    _ if body.static_dispatch.is_some() => {
415                        head.byte(PARSED_WITH_STATIC_DISPATCH);
416                        let flags = (u8::from(body.outline.is_some()) * HAS_OUTLINE)
417                            | (u8::from(body.dead_code.is_some()) * HAS_DEAD_CODE)
418                            | (u8::from(self.todos.is_some()) * STATIC_HAS_TODOS);
419                        head.byte(flags);
420                        if let Some(todos) = &self.todos {
421                            encode_todos(&mut head, todos);
422                        }
423                    }
424                    None => head.byte(match (body.outline.is_some(), body.dead_code.is_some()) {
425                        (true, true) => PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE,
426                        (true, false) => PARSED_WITH_ENTRIES_AND_OUTLINE,
427                        (false, true) => PARSED_WITH_ENTRIES_AND_DEAD_CODE,
428                        (false, false) => PARSED_WITH_ENTRIES,
429                    }),
430                    Some(todos) => {
431                        head.byte(PARSED_WITH_TODOS);
432                        let mut flags = 0;
433                        if body.outline.is_some() {
434                            flags |= HAS_OUTLINE;
435                        }
436                        if body.dead_code.is_some() {
437                            flags |= HAS_DEAD_CODE;
438                        }
439                        head.byte(flags);
440                        encode_todos(&mut head, todos);
441                    }
442                }
443                encode_surface(&mut head, surface);
444                encode_entries(&mut head, surface);
445                let mut tail = Encoder::default();
446                encode_body(&mut tail, body);
447                (head.finish(), tail.finish())
448            }
449        }
450    }
451
452    /// Reads a record from its two parts.
453    ///
454    /// # Errors
455    ///
456    /// When either part is not well formed.
457    pub fn decode(surface: &[u8], body: &[u8]) -> Result<Self, DecodeError> {
458        let mut head = Decoder::new(surface)?;
459        let language = head.string()?;
460        let extractor_version = head.string()?;
461        let mut todos = None;
462        let data = match head.byte()? {
463            kind @ (CONFIG | CONFIG_WITH_TODOS) => {
464                if kind == CONFIG_WITH_TODOS {
465                    todos = Some(decode_todos(&mut head)?);
466                }
467                let source = head.blob()?.to_vec();
468                head.finish()?;
469                if !body.is_empty() {
470                    return Err(DecodeError("a configuration record has a body"));
471                }
472                RecordBody::Config { source }
473            }
474            MARKERS => {
475                if head.bool()? {
476                    todos = Some(decode_todos(&mut head)?);
477                }
478                head.finish()?;
479                if !body.is_empty() {
480                    return Err(DecodeError("a markers record has a body"));
481                }
482                RecordBody::Markers
483            }
484            kind @ (PARSED
485            | PARSED_WITH_OUTLINE
486            | PARSED_WITH_ENTRIES
487            | PARSED_WITH_ENTRIES_AND_OUTLINE
488            | PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
489            | PARSED_WITH_ENTRIES_AND_DEAD_CODE
490            | PARSED_WITH_TODOS
491            | PARSED_WITH_STATIC_DISPATCH) => {
492                // What the kind says follows: entry facts after the surface,
493                // and an outline and dead-code facts at the body's end.
494                let static_dispatch = kind == PARSED_WITH_STATIC_DISPATCH;
495                let (entries, outline, dead_code) = if kind == PARSED_WITH_TODOS || static_dispatch
496                {
497                    let flags = head.byte()?;
498                    let allowed = HAS_OUTLINE
499                        | HAS_DEAD_CODE
500                        | if static_dispatch { STATIC_HAS_TODOS } else { 0 };
501                    if flags & !allowed != 0 {
502                        return Err(DecodeError("parsed record flags"));
503                    }
504                    if !static_dispatch || flags & STATIC_HAS_TODOS != 0 {
505                        todos = Some(decode_todos(&mut head)?);
506                    }
507                    (true, flags & HAS_OUTLINE != 0, flags & HAS_DEAD_CODE != 0)
508                } else {
509                    (
510                        matches!(
511                            kind,
512                            PARSED_WITH_ENTRIES
513                                | PARSED_WITH_ENTRIES_AND_OUTLINE
514                                | PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
515                                | PARSED_WITH_ENTRIES_AND_DEAD_CODE
516                        ),
517                        matches!(
518                            kind,
519                            PARSED_WITH_OUTLINE
520                                | PARSED_WITH_ENTRIES_AND_OUTLINE
521                                | PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
522                        ),
523                        matches!(
524                            kind,
525                            PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
526                                | PARSED_WITH_ENTRIES_AND_DEAD_CODE
527                        ),
528                    )
529                };
530                let mut surface = decode_surface(&mut head)?;
531                if entries {
532                    decode_entries(&mut head, &mut surface)?;
533                }
534                head.finish()?;
535                let mut tail = Decoder::new(body)?;
536                let mut body = decode_body(&mut tail)?;
537                if outline {
538                    body.outline = Some(decode_outline(&mut tail)?);
539                }
540                if dead_code {
541                    body.dead_code = Some(tail.blob()?.to_vec());
542                }
543                if static_dispatch {
544                    body.static_dispatch = Some(tail.blob()?.to_vec());
545                }
546                tail.finish()?;
547                RecordBody::Parsed {
548                    surface: Box::new(surface),
549                    body: Box::new(body),
550                }
551            }
552            _ => return Err(DecodeError("record kind")),
553        };
554        Ok(Self {
555            language,
556            extractor_version,
557            data,
558            todos,
559        })
560    }
561
562    /// The TODO markers of the record whose surface part is `surface`,
563    /// read without decoding the rest of the record: they come right after
564    /// its kind. `None` when the record holds none.
565    ///
566    /// # Errors
567    ///
568    /// When the bytes before and of the markers are not well formed.
569    pub fn todos_of(surface: &[u8]) -> Result<Option<TodoMarkers>, DecodeError> {
570        let mut head = Decoder::new(surface)?;
571        head.str()?;
572        head.str()?;
573        match head.byte()? {
574            CONFIG_WITH_TODOS => decode_todos(&mut head).map(Some),
575            MARKERS if head.bool()? => decode_todos(&mut head).map(Some),
576            PARSED_WITH_TODOS => {
577                head.byte()?;
578                decode_todos(&mut head).map(Some)
579            }
580            PARSED_WITH_STATIC_DISPATCH => {
581                if head.byte()? & STATIC_HAS_TODOS != 0 {
582                    decode_todos(&mut head).map(Some)
583                } else {
584                    Ok(None)
585                }
586            }
587            CONFIG
588            | MARKERS
589            | PARSED
590            | PARSED_WITH_OUTLINE
591            | PARSED_WITH_ENTRIES
592            | PARSED_WITH_ENTRIES_AND_OUTLINE
593            | PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
594            | PARSED_WITH_ENTRIES_AND_DEAD_CODE => Ok(None),
595            _ => Err(DecodeError("record kind")),
596        }
597    }
598}
599
600/// The markers' language, then a byte saying whether the content was text
601/// (1) or not (0), then for text the count of markers and each marker.
602fn encode_todos(out: &mut Encoder, todos: &TodoMarkers) {
603    out.str(&todos.language);
604    out.bool(todos.items.is_some());
605    if let Some(items) = &todos.items {
606        out.usize(items.len());
607        for item in items {
608            out.u32(item.line);
609            out.str(&item.marker);
610            out.opt_str(item.author.as_deref());
611            out.str(&item.text);
612        }
613    }
614}
615
616fn decode_todos(input: &mut Decoder<'_>) -> Result<TodoMarkers, DecodeError> {
617    let language = input.string()?;
618    let items = if input.bool()? {
619        let count = input.count()?;
620        let mut items = Vec::with_capacity(count);
621        for _ in 0..count {
622            items.push(TodoMarker {
623                line: input.u32()?,
624                marker: input.string()?,
625                author: input.opt_string()?,
626                text: input.string()?,
627            });
628        }
629        Some(items)
630    } else {
631        None
632    };
633    Ok(TodoMarkers { language, items })
634}
635
636fn encode_surface(out: &mut Encoder, surface: &Surface) {
637    out.usize(surface.symbols.len());
638    for symbol in &surface.symbols {
639        out.byte(match symbol.is_test {
640            None => 0,
641            Some(false) => 1,
642            Some(true) => 2,
643        });
644        out.u32(symbol.ordinal);
645        out.str(&symbol.name);
646        out.str(&symbol.scoped_name);
647        out.str(&symbol.kind);
648        out.bool(symbol.exported);
649        out.bool(symbol.is_default_export);
650        out.u32(symbol.start_line);
651        out.u32(symbol.start_col);
652        out.u32(symbol.end_line);
653        out.u32(symbol.end_col);
654        out.opt_str(symbol.signature.as_deref());
655    }
656    out.opt_str(surface.default_export_symbol.as_deref());
657    out.strs(&surface.exported_symbols);
658    out.strs(&surface.callable_symbols);
659    out.strs(&surface.entry_point_symbols);
660    out.opt_str(surface.go_package.as_deref());
661    out.usize(surface.types.len());
662    for fact in &surface.types {
663        out.str(&fact.name);
664        out.strs(&fact.bases);
665        out.bool(fact.interface);
666        out.bool(fact.closed);
667    }
668    out.usize(surface.methods.len());
669    for fact in &surface.methods {
670        out.str(&fact.owner);
671        out.opt_str(fact.trait_name.as_deref());
672        out.str(&fact.name);
673        out.str(&fact.symbol);
674        out.bool(fact.has_body);
675        out.str(&fact.shape);
676        out.bool(fact.private);
677    }
678    out.usize(surface.fields.len());
679    for fact in &surface.fields {
680        out.str(&fact.owner);
681        out.str(&fact.name);
682        out.str(&fact.ty);
683    }
684    out.usize(surface.returns.len());
685    for fact in &surface.returns {
686        out.str(&fact.symbol);
687        out.str(&fact.ty);
688    }
689}
690
691fn decode_surface(input: &mut Decoder<'_>) -> Result<Surface, DecodeError> {
692    let count = input.count()?;
693    let mut symbols = Vec::with_capacity(count);
694    for _ in 0..count {
695        symbols.push(Symbol {
696            is_test: match input.byte()? {
697                0 => None,
698                1 => Some(false),
699                2 => Some(true),
700                _ => return Err(DecodeError("is_test")),
701            },
702            ordinal: input.u32()?,
703            name: input.string()?,
704            scoped_name: input.string()?,
705            kind: input.string()?,
706            exported: input.bool()?,
707            is_default_export: input.bool()?,
708            start_line: input.u32()?,
709            start_col: input.u32()?,
710            end_line: input.u32()?,
711            end_col: input.u32()?,
712            signature: input.opt_string()?,
713            program_start: false,
714            entry_attribute: None,
715        });
716    }
717    let default_export_symbol = input.opt_string()?;
718    let exported_symbols = input.strings()?;
719    let callable_symbols = input.strings()?;
720    let entry_point_symbols = input.strings()?;
721    let go_package = input.opt_string()?;
722    let count = input.count()?;
723    let mut types = Vec::with_capacity(count);
724    for _ in 0..count {
725        types.push(TypeFact {
726            name: input.string()?,
727            bases: input.strings()?,
728            interface: input.bool()?,
729            closed: input.bool()?,
730        });
731    }
732    let count = input.count()?;
733    let mut methods = Vec::with_capacity(count);
734    for _ in 0..count {
735        methods.push(MethodFact {
736            owner: input.string()?,
737            trait_name: input.opt_string()?,
738            name: input.string()?,
739            symbol: input.string()?,
740            has_body: input.bool()?,
741            shape: input.string()?,
742            private: input.bool()?,
743        });
744    }
745    let count = input.count()?;
746    let mut fields = Vec::with_capacity(count);
747    for _ in 0..count {
748        fields.push(FieldFact {
749            owner: input.string()?,
750            name: input.string()?,
751            ty: input.string()?,
752        });
753    }
754    let count = input.count()?;
755    let mut returns = Vec::with_capacity(count);
756    for _ in 0..count {
757        returns.push(ReturnFact {
758            symbol: input.string()?,
759            ty: input.string()?,
760        });
761    }
762    Ok(Surface {
763        symbols,
764        default_export_symbol,
765        exported_symbols,
766        callable_symbols,
767        entry_point_symbols,
768        go_package,
769        types,
770        methods,
771        fields,
772        returns,
773    })
774}
775
776/// Each symbol's entry facts, in symbol order, after the rest of the
777/// surface of a [`PARSED_WITH_ENTRIES`] or
778/// [`PARSED_WITH_ENTRIES_AND_OUTLINE`] record.
779fn encode_entries(out: &mut Encoder, surface: &Surface) {
780    for symbol in &surface.symbols {
781        out.bool(symbol.program_start);
782        out.opt_str(symbol.entry_attribute.as_deref());
783    }
784}
785
786fn decode_entries(input: &mut Decoder<'_>, surface: &mut Surface) -> Result<(), DecodeError> {
787    for symbol in &mut surface.symbols {
788        symbol.program_start = input.bool()?;
789        symbol.entry_attribute = input.opt_string()?;
790    }
791    Ok(())
792}
793
794fn encode_body(out: &mut Encoder, body: &Body) {
795    out.usize(body.imports.len());
796    for import in &body.imports {
797        out.u32(import.ordinal);
798        out.str(&import.module_path);
799        out.strs(&import.names);
800        out.opt_str(import.default_import.as_deref());
801        out.opt_str(import.namespace_import.as_deref());
802        out.u64(import.byte_start);
803        out.u64(import.byte_end);
804        out.str(&import.raw_text);
805        out.bool(import.type_only);
806        out.bool(import.side_effect);
807    }
808    out.usize(body.python_bindings.len());
809    for binding in &body.python_bindings {
810        out.u64(binding.byte_start);
811        out.u64(binding.byte_end);
812        match &binding.target {
813            None => out.bool(false),
814            Some((module, symbol)) => {
815                out.bool(true);
816                out.str(module);
817                out.str(symbol);
818            }
819        }
820    }
821    out.usize(body.references.len());
822    for reference in &body.references {
823        out.u32(reference.ordinal);
824        out.byte(reference.kind.code());
825        out.opt_str(reference.caller_symbol.as_deref());
826        out.opt_str(reference.short_name.as_deref());
827        out.opt_str(reference.full_ref.as_deref());
828        out.opt_str(reference.module_path.as_deref());
829        out.u32(reference.line);
830        out.u64(reference.byte_start);
831        out.u64(reference.byte_end);
832        out.opt_str(reference.path_override.as_deref());
833        out.opt_str(reference.local_name.as_deref());
834        out.opt_str(reference.requested_name.as_deref());
835        out.opt_str(reference.namespace_alias.as_deref());
836        out.bool(reference.wildcard);
837        out.opt_str(reference.import_kind.as_deref());
838    }
839    out.usize(body.call_sites.len());
840    for site in &body.call_sites {
841        out.u32(site.ordinal);
842        out.opt_str(site.caller.as_deref());
843        out.u32(site.line);
844        out.opt_str(site.member.as_deref());
845        out.opt_str(site.receiver.as_deref());
846        out.bool(site.dynamic);
847    }
848    if let Some(outline) = &body.outline {
849        out.usize(outline.len());
850        for symbol in outline {
851            out.str(&symbol.name);
852            out.str(&symbol.kind);
853            out.u32(symbol.start_line);
854            out.u32(symbol.start_col);
855            out.u32(symbol.end_line);
856            out.u32(symbol.end_col);
857            out.opt_str(symbol.signature.as_deref());
858            out.strs(&symbol.scope_chain);
859            out.bool(symbol.exported);
860            out.opt_str(symbol.parent.as_deref());
861        }
862    }
863    if let Some(facts) = &body.dead_code {
864        out.blob(facts);
865    }
866    if let Some(facts) = &body.static_dispatch {
867        out.blob(facts);
868    }
869}
870
871fn decode_body(input: &mut Decoder<'_>) -> Result<Body, DecodeError> {
872    let count = input.count()?;
873    let mut imports = Vec::with_capacity(count);
874    for _ in 0..count {
875        imports.push(Import {
876            ordinal: input.u32()?,
877            module_path: input.string()?,
878            names: input.strings()?,
879            default_import: input.opt_string()?,
880            namespace_import: input.opt_string()?,
881            byte_start: input.u64()?,
882            byte_end: input.u64()?,
883            raw_text: input.string()?,
884            type_only: input.bool()?,
885            side_effect: input.bool()?,
886        });
887    }
888    let count = input.count()?;
889    let mut python_bindings = Vec::with_capacity(count);
890    for _ in 0..count {
891        let byte_start = input.u64()?;
892        let byte_end = input.u64()?;
893        let target = if input.bool()? {
894            Some((input.string()?, input.string()?))
895        } else {
896            None
897        };
898        python_bindings.push(PythonBinding {
899            byte_start,
900            byte_end,
901            target,
902        });
903    }
904    let count = input.count()?;
905    let mut references = Vec::with_capacity(count);
906    for _ in 0..count {
907        references.push(Reference {
908            ordinal: input.u32()?,
909            kind: RefKind::from_code(input.byte()?)?,
910            caller_symbol: input.opt_string()?,
911            short_name: input.opt_string()?,
912            full_ref: input.opt_string()?,
913            module_path: input.opt_string()?,
914            line: input.u32()?,
915            byte_start: input.u64()?,
916            byte_end: input.u64()?,
917            path_override: input.opt_string()?,
918            local_name: input.opt_string()?,
919            requested_name: input.opt_string()?,
920            namespace_alias: input.opt_string()?,
921            wildcard: input.bool()?,
922            import_kind: input.opt_string()?,
923        });
924    }
925    let count = input.count()?;
926    let mut call_sites = Vec::with_capacity(count);
927    for _ in 0..count {
928        call_sites.push(CallSite {
929            ordinal: input.u32()?,
930            caller: input.opt_string()?,
931            line: input.u32()?,
932            member: input.opt_string()?,
933            receiver: input.opt_string()?,
934            dynamic: input.bool()?,
935        });
936    }
937    Ok(Body {
938        imports,
939        python_bindings,
940        references,
941        call_sites,
942        outline: None,
943        dead_code: None,
944        static_dispatch: None,
945    })
946}
947
948/// The outline a body of a [`PARSED_WITH_OUTLINE`] record ends with.
949fn decode_outline(input: &mut Decoder<'_>) -> Result<Vec<OutlineSymbol>, DecodeError> {
950    let count = input.count()?;
951    let mut outline = Vec::with_capacity(count);
952    for _ in 0..count {
953        outline.push(OutlineSymbol {
954            name: input.string()?,
955            kind: input.string()?,
956            start_line: input.u32()?,
957            start_col: input.u32()?,
958            end_line: input.u32()?,
959            end_col: input.u32()?,
960            signature: input.opt_string()?,
961            scope_chain: input.strings()?,
962            exported: input.bool()?,
963            parent: input.opt_string()?,
964        });
965    }
966    Ok(outline)
967}
968
969crate::heap_bytes_none!(RecordKey, RefKind);
970crate::heap_bytes_of_fields!(Symbol {
971    is_test,
972    ordinal,
973    name,
974    scoped_name,
975    kind,
976    exported,
977    is_default_export,
978    start_line,
979    start_col,
980    end_line,
981    end_col,
982    signature,
983    program_start,
984    entry_attribute,
985});
986crate::heap_bytes_of_fields!(Reference {
987    ordinal,
988    kind,
989    caller_symbol,
990    short_name,
991    full_ref,
992    module_path,
993    line,
994    byte_start,
995    byte_end,
996    path_override,
997    local_name,
998    requested_name,
999    namespace_alias,
1000    wildcard,
1001    import_kind,
1002});
1003crate::heap_bytes_of_fields!(Import {
1004    ordinal,
1005    module_path,
1006    names,
1007    default_import,
1008    namespace_import,
1009    byte_start,
1010    byte_end,
1011    raw_text,
1012    type_only,
1013    side_effect,
1014});
1015crate::heap_bytes_of_fields!(PythonBinding {
1016    byte_start,
1017    byte_end,
1018    target,
1019});
1020crate::heap_bytes_of_fields!(TypeFact {
1021    name,
1022    bases,
1023    interface,
1024    closed,
1025});
1026crate::heap_bytes_of_fields!(MethodFact {
1027    owner,
1028    trait_name,
1029    name,
1030    symbol,
1031    has_body,
1032    shape,
1033    private,
1034});
1035crate::heap_bytes_of_fields!(FieldFact { owner, name, ty });
1036crate::heap_bytes_of_fields!(ReturnFact { symbol, ty });
1037crate::heap_bytes_of_fields!(CallSite {
1038    ordinal,
1039    caller,
1040    line,
1041    member,
1042    receiver,
1043    dynamic,
1044});
1045crate::heap_bytes_of_fields!(Surface {
1046    symbols,
1047    default_export_symbol,
1048    exported_symbols,
1049    callable_symbols,
1050    entry_point_symbols,
1051    go_package,
1052    types,
1053    methods,
1054    fields,
1055    returns,
1056});
1057crate::heap_bytes_of_fields!(OutlineSymbol {
1058    name,
1059    kind,
1060    start_line,
1061    start_col,
1062    end_line,
1063    end_col,
1064    signature,
1065    scope_chain,
1066    exported,
1067    parent,
1068});
1069crate::heap_bytes_of_fields!(Body {
1070    imports,
1071    python_bindings,
1072    references,
1073    call_sites,
1074    outline,
1075    dead_code,
1076    static_dispatch,
1077});
1078crate::heap_bytes_of_fields!(TodoMarker {
1079    line,
1080    marker,
1081    author,
1082    text,
1083});
1084crate::heap_bytes_of_fields!(TodoMarkers { language, items });
1085crate::heap_bytes_of_fields!(ContentRecord {
1086    language,
1087    extractor_version,
1088    data,
1089    todos,
1090});
1091
1092impl crate::heap::HeapBytes for RecordBody {
1093    fn heap_bytes(&self, seen: &mut crate::heap::Seen) -> usize {
1094        match self {
1095            Self::Parsed { surface, body } => {
1096                crate::heap::HeapBytes::heap_bytes(surface, seen)
1097                    + crate::heap::HeapBytes::heap_bytes(body, seen)
1098            }
1099            Self::Config { source } => crate::heap::HeapBytes::heap_bytes(source, seen),
1100            Self::Markers => 0,
1101        }
1102    }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108
1109    fn sample() -> ContentRecord {
1110        ContentRecord {
1111            language: "rust".into(),
1112            extractor_version: "v1".into(),
1113            data: RecordBody::Parsed {
1114                surface: Box::new(Surface {
1115                    symbols: vec![Symbol {
1116                        is_test: Some(false),
1117                        ordinal: 7,
1118                        name: "open".into(),
1119                        scoped_name: "Store::open".into(),
1120                        kind: "method".into(),
1121                        exported: true,
1122                        is_default_export: false,
1123                        start_line: 3,
1124                        start_col: 4,
1125                        end_line: 9,
1126                        end_col: 5,
1127                        signature: Some("fn open() -> Self".into()),
1128                        program_start: false,
1129                        entry_attribute: Some("no_mangle".into()),
1130                    }],
1131                    exported_symbols: vec!["Store".into()],
1132                    callable_symbols: vec!["Store::open".into()],
1133                    go_package: None,
1134                    types: vec![TypeFact {
1135                        name: "Store".into(),
1136                        bases: vec!["Base".into()],
1137                        interface: false,
1138                        closed: true,
1139                    }],
1140                    methods: vec![MethodFact {
1141                        owner: "Store".into(),
1142                        trait_name: None,
1143                        name: "open".into(),
1144                        symbol: "Store::open".into(),
1145                        has_body: true,
1146                        shape: "()".into(),
1147                        private: false,
1148                    }],
1149                    fields: vec![FieldFact {
1150                        owner: "Store".into(),
1151                        name: "path".into(),
1152                        ty: "PathBuf".into(),
1153                    }],
1154                    returns: vec![ReturnFact {
1155                        symbol: "Store::open".into(),
1156                        ty: "Store".into(),
1157                    }],
1158                    ..Surface::default()
1159                }),
1160                body: Box::new(Body {
1161                    imports: vec![Import {
1162                        ordinal: 1,
1163                        module_path: "std::path".into(),
1164                        names: vec!["PathBuf".into()],
1165                        default_import: None,
1166                        namespace_import: None,
1167                        byte_start: 0,
1168                        byte_end: 22,
1169                        raw_text: "use std::path::PathBuf;".into(),
1170                        type_only: false,
1171                        side_effect: false,
1172                    }],
1173                    python_bindings: vec![PythonBinding {
1174                        byte_start: 2,
1175                        byte_end: 3,
1176                        target: Some(("m".into(), "f".into())),
1177                    }],
1178                    references: vec![Reference {
1179                        ordinal: 9,
1180                        kind: RefKind::Call,
1181                        caller_symbol: Some("Store::open".into()),
1182                        short_name: Some("new".into()),
1183                        full_ref: Some("PathBuf::new".into()),
1184                        module_path: None,
1185                        line: 5,
1186                        byte_start: 100,
1187                        byte_end: 112,
1188                        path_override: None,
1189                        local_name: None,
1190                        requested_name: None,
1191                        namespace_alias: None,
1192                        wildcard: false,
1193                        import_kind: None,
1194                    }],
1195                    call_sites: vec![CallSite {
1196                        ordinal: 11,
1197                        caller: Some("Store::open".into()),
1198                        line: 6,
1199                        member: Some("join".into()),
1200                        receiver: Some("self.path".into()),
1201                        dynamic: false,
1202                    }],
1203                    outline: None,
1204                    dead_code: None,
1205                    static_dispatch: None,
1206                }),
1207            },
1208            todos: None,
1209        }
1210    }
1211
1212    fn todos(language: &str) -> TodoMarkers {
1213        TodoMarkers {
1214            language: language.into(),
1215            items: Some(vec![
1216                TodoMarker {
1217                    line: 4,
1218                    marker: "TODO".into(),
1219                    author: Some("ana".into()),
1220                    text: "close the store".into(),
1221                },
1222                TodoMarker {
1223                    line: 9,
1224                    marker: "FIXME".into(),
1225                    author: None,
1226                    text: String::new(),
1227                },
1228            ]),
1229        }
1230    }
1231
1232    /// Every kind of record round-trips its TODO markers, which
1233    /// `todos_of` reads from the first part alone; a record without them
1234    /// encodes exactly as before records could hold them, and every cut of
1235    /// the first part is refused.
1236    #[test]
1237    fn todo_markers_round_trip_in_every_kind_and_read_from_the_first_part() {
1238        let mut parsed = sample();
1239        let RecordBody::Parsed { body, .. } = &mut parsed.data else {
1240            unreachable!("the sample is parsed");
1241        };
1242        body.outline = Some(outline());
1243        body.dead_code = Some(b"facts".to_vec());
1244        let without = parsed.clone();
1245        parsed.todos = Some(todos("rust"));
1246        let config = ContentRecord {
1247            language: "config".into(),
1248            extractor_version: "v1".into(),
1249            data: RecordBody::Config {
1250                source: b"# TODO: x\n".to_vec(),
1251            },
1252            todos: Some(todos("toml")),
1253        };
1254        let markers = ContentRecord {
1255            language: "markers-markdown".into(),
1256            extractor_version: "v1".into(),
1257            data: RecordBody::Markers,
1258            todos: Some(todos("markdown")),
1259        };
1260        let not_text = ContentRecord {
1261            todos: Some(TodoMarkers {
1262                language: "markdown".into(),
1263                items: None,
1264            }),
1265            ..markers.clone()
1266        };
1267        let empty_markers = ContentRecord {
1268            todos: None,
1269            ..markers.clone()
1270        };
1271        for record in [&parsed, &config, &markers, &not_text, &empty_markers] {
1272            let (surface, body) = record.encode();
1273            assert_eq!(&ContentRecord::decode(&surface, &body).unwrap(), record);
1274            assert_eq!(ContentRecord::todos_of(&surface).unwrap(), record.todos);
1275            for cut in 0..surface.len() {
1276                assert!(ContentRecord::decode(&surface[..cut], &body).is_err());
1277            }
1278        }
1279        let (surface, body) = without.encode();
1280        assert_eq!(ContentRecord::todos_of(&surface).unwrap(), None);
1281        assert_eq!(ContentRecord::decode(&surface, &body).unwrap(), without);
1282        // Without markers the kind is the one records had before them.
1283        let mut head = Decoder::new(&surface).unwrap();
1284        head.str().unwrap();
1285        head.str().unwrap();
1286        assert_eq!(
1287            head.byte().unwrap(),
1288            PARSED_WITH_ENTRIES_OUTLINE_AND_DEAD_CODE
1289        );
1290    }
1291
1292    fn outline() -> Vec<OutlineSymbol> {
1293        vec![
1294            OutlineSymbol {
1295                name: "Store".into(),
1296                kind: "struct".into(),
1297                start_line: 1,
1298                start_col: 0,
1299                end_line: 1,
1300                end_col: 33,
1301                signature: Some("pub struct Store".into()),
1302                scope_chain: Vec::new(),
1303                exported: true,
1304                parent: None,
1305            },
1306            OutlineSymbol {
1307                name: "open".into(),
1308                kind: "method".into(),
1309                start_line: 3,
1310                start_col: 4,
1311                end_line: 9,
1312                end_col: 5,
1313                signature: Some("fn open() -> Self".into()),
1314                scope_chain: vec!["Store".into()],
1315                exported: true,
1316                parent: Some("Store".into()),
1317            },
1318        ]
1319    }
1320
1321    #[test]
1322    fn an_outline_round_trips_and_its_absence_is_told_by_the_record_kind() {
1323        let without = sample();
1324        let mut with = sample();
1325        let RecordBody::Parsed { body, .. } = &mut with.data else {
1326            unreachable!("the sample is parsed");
1327        };
1328        body.outline = Some(outline());
1329        let (surface, body) = with.encode();
1330        assert_eq!(ContentRecord::decode(&surface, &body).unwrap(), with);
1331        let (plain_surface, plain_body) = without.encode();
1332        let decoded = ContentRecord::decode(&plain_surface, &plain_body).unwrap();
1333        assert_eq!(decoded, without);
1334
1335        // The two surfaces differ only in the record kind.
1336        assert_eq!(surface.len(), plain_surface.len());
1337        let differing = surface
1338            .iter()
1339            .zip(&plain_surface)
1340            .filter(|(a, b)| a != b)
1341            .map(|(a, b)| (*a, *b))
1342            .collect::<Vec<_>>();
1343        assert_eq!(
1344            differing,
1345            vec![(PARSED_WITH_ENTRIES_AND_OUTLINE, PARSED_WITH_ENTRIES)]
1346        );
1347
1348        // A body without its outline, or with one the kind does not
1349        // announce, is refused, as is every cut of a body with one.
1350        assert!(ContentRecord::decode(&surface, &plain_body).is_err());
1351        assert!(ContentRecord::decode(&plain_surface, &body).is_err());
1352        for cut in 0..body.len() {
1353            assert!(ContentRecord::decode(&surface, &body[..cut]).is_err());
1354        }
1355
1356        // An empty outline is still an outline.
1357        let mut empty = sample();
1358        let RecordBody::Parsed { body, .. } = &mut empty.data else {
1359            unreachable!("the sample is parsed");
1360        };
1361        body.outline = Some(Vec::new());
1362        let (surface, body) = empty.encode();
1363        assert_eq!(ContentRecord::decode(&surface, &body).unwrap(), empty);
1364    }
1365
1366    #[test]
1367    fn dead_code_facts_round_trip_with_and_without_an_outline() {
1368        for outline in [None, Some(outline())] {
1369            let without = {
1370                let mut record = sample();
1371                let RecordBody::Parsed { body, .. } = &mut record.data else {
1372                    unreachable!("the sample is parsed");
1373                };
1374                body.outline.clone_from(&outline);
1375                record
1376            };
1377            let mut with = without.clone();
1378            let RecordBody::Parsed { body, .. } = &mut with.data else {
1379                unreachable!("the sample is parsed");
1380            };
1381            body.dead_code = Some(b"{\"facts\":1}".to_vec());
1382            let (surface, body) = with.encode();
1383            assert_eq!(ContentRecord::decode(&surface, &body).unwrap(), with);
1384            let (plain_surface, plain_body) = without.encode();
1385            assert_eq!(
1386                ContentRecord::decode(&plain_surface, &plain_body).unwrap(),
1387                without
1388            );
1389
1390            // The record kind alone says whether facts follow: a body without
1391            // them, or with facts the kind does not announce, is refused, as
1392            // is every cut of a body with them.
1393            assert!(ContentRecord::decode(&surface, &plain_body).is_err());
1394            assert!(ContentRecord::decode(&plain_surface, &body).is_err());
1395            for cut in 0..body.len() {
1396                assert!(ContentRecord::decode(&surface, &body[..cut]).is_err());
1397            }
1398        }
1399    }
1400
1401    #[test]
1402    fn records_round_trip_and_refuse_damage() {
1403        let record = sample();
1404        let (surface, body) = record.encode();
1405        assert_eq!(ContentRecord::decode(&surface, &body).unwrap(), record);
1406        // Strings repeat across fields but are stored once.
1407        let text = String::from_utf8_lossy(&surface);
1408        assert_eq!(text.matches("Store::open").count(), 1);
1409
1410        let config = ContentRecord {
1411            language: "config".into(),
1412            extractor_version: "v1".into(),
1413            data: RecordBody::Config {
1414                source: b"[package]\n".to_vec(),
1415            },
1416            todos: None,
1417        };
1418        let (head, tail) = config.encode();
1419        assert!(tail.is_empty());
1420        assert_eq!(ContentRecord::decode(&head, &tail).unwrap(), config);
1421
1422        for cut in 0..body.len() {
1423            assert!(ContentRecord::decode(&surface, &body[..cut]).is_err());
1424        }
1425        for cut in 0..surface.len() {
1426            assert!(ContentRecord::decode(&surface[..cut], &body).is_err());
1427        }
1428    }
1429
1430    /// A record of a kind written before symbols carried entry facts reads
1431    /// back with none, and the facts round-trip in the kinds that hold them.
1432    #[test]
1433    fn entry_facts_round_trip_and_older_records_read_without_them() {
1434        let mut record = sample();
1435        let RecordBody::Parsed { surface, .. } = &mut record.data else {
1436            unreachable!("the sample is parsed");
1437        };
1438        surface.symbols[0].program_start = true;
1439        let (head, tail) = record.encode();
1440        assert_eq!(ContentRecord::decode(&head, &tail).unwrap(), record);
1441
1442        // The encoding records had before entry facts: the same surface and
1443        // body under the older kind byte, without the facts.
1444        let RecordBody::Parsed { surface, body } = &record.data else {
1445            unreachable!("the sample is parsed");
1446        };
1447        let mut old = Encoder::default();
1448        old.str(&record.language);
1449        old.str(&record.extractor_version);
1450        old.byte(PARSED);
1451        encode_surface(&mut old, surface);
1452        let mut old_tail = Encoder::default();
1453        encode_body(&mut old_tail, body);
1454        let decoded = ContentRecord::decode(&old.finish(), &old_tail.finish()).unwrap();
1455        let RecordBody::Parsed { surface, .. } = decoded.data else {
1456            unreachable!("the record is parsed");
1457        };
1458        assert!(!surface.symbols[0].program_start);
1459        assert_eq!(surface.symbols[0].entry_attribute, None);
1460        assert_eq!(surface.symbols[0].scoped_name, "Store::open");
1461    }
1462}