Skip to main content

bynk_check/
memo.rs

1//! The language server's reusable analysis state (#3243, #1523 S2).
2//!
3//! [`analyse_project_memoised`] is the entry point the language server calls
4//! once per round, passing the same [`AnalysisMemo`] each time. The memo keeps
5//! each file's checked output (a `FileRecord`) keyed by a digest of everything
6//! the check read ([`crate::check_pipeline::file_check_digest`]); a file whose
7//! digest is unchanged is replayed instead of re-checked. The answer must be
8//! exactly `analyse_project`'s; the differential oracle
9//! (`xtask/tests/analysis_oracle.rs`) holds it to that.
10//!
11//! `bynk check` and `bynk build` never call this: they stay on the plain,
12//! table-free path (`analyse_project` / the driver's own checks), which is the
13//! cold-compile cost R3.15 asks us not to raise. A test pins it.
14//!
15//! # The type table's growth policy
16//!
17//! A cached record holds `TyId`s, so every round of one memo shares **one**
18//! append-only [`Types`] table (a `TyId` stays valid as long as its table does).
19//! Interning deduplicates, so an unchanged project adds nothing; but an edit
20//! that mints new types leaves the old ones behind. The policy
21//! (`AnalysisMemo::begin_round`): after a round the table's size is the
22//! baseline; once it has grown past [`GROWTH_FACTOR`] times that baseline (and
23//! past [`MIN_RESET_LEN`], so a tiny project never churns), the memo is dropped
24//! and the next round starts cold with a fresh table. That bounds the table to a
25//! constant multiple of one round's, by construction; the oracle's long edit
26//! sequence tests it.
27
28use std::collections::{HashMap, HashSet};
29use std::path::PathBuf;
30use std::sync::Arc;
31
32use crate::analysis::{ProjectAnalysis, analyse_project_cached};
33use crate::check_pipeline::DeclDigests;
34use crate::checker::{TypedCommons, Types};
35use crate::expr_types::ExprTypeSink;
36use crate::hints::HintSink;
37use crate::index::RefSink;
38use crate::locals::LocalsSink;
39use crate::project_model::ErrorSink;
40use crate::requirements::RequirementSink;
41use bynk_project::{Roots, SchemaLock};
42
43/// The type table may grow to this many times its size after the last cold round
44/// before the memo starts over.
45pub const GROWTH_FACTOR: usize = 4;
46/// ...but never resets while smaller than this many entries.
47pub const MIN_RESET_LEN: usize = 50_000;
48
49/// Everything one file's check produced, enough to replay it into the project's
50/// sinks without checking the file again.
51#[derive(Clone)]
52pub(crate) struct FileRecord {
53    pub errors: ErrorSink,
54    pub refs: RefSink,
55    pub hints: HintSink,
56    pub locals: LocalsSink,
57    pub exprs: ExprTypeSink,
58    pub requirements: RequirementSink,
59    /// The typed unit, `None` when the file did not check clean. Needed by
60    /// `ExecPlan::extend`, which runs every round over every file.
61    pub typed: Option<Arc<TypedCommons>>,
62}
63
64struct Entry {
65    digest: u64,
66    record: FileRecord,
67}
68
69/// How a round used the memo, for tests and for the bench's reporting.
70#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
71pub struct MemoStats {
72    /// Files replayed from the memo this round.
73    pub hits: usize,
74    /// Files checked this round.
75    pub misses: usize,
76    /// Entries held after the round.
77    pub entries: usize,
78    /// Size of the shared type table after the round.
79    pub type_table_len: usize,
80    /// Rounds in which the growth policy dropped the memo.
81    pub resets: usize,
82    /// Distinct shared declarations hashed in the round (their digests are
83    /// dropped when it ends).
84    pub decls_hashed: usize,
85}
86
87/// State reused between rounds. One per project, owned by the language server.
88pub struct AnalysisMemo {
89    types: Arc<Types>,
90    entries: HashMap<PathBuf, Entry>,
91    /// Paths looked up this round; the rest are dropped when it ends.
92    seen: HashSet<PathBuf>,
93    baseline: usize,
94    /// Each shared declaration's digest, for the round in progress only (see
95    /// [`crate::check_pipeline::DeclDigests`]); emptied when a round begins.
96    decls: DeclDigests,
97    growth_factor: usize,
98    min_reset_len: usize,
99    stats: MemoStats,
100}
101
102impl std::fmt::Debug for AnalysisMemo {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.debug_struct("AnalysisMemo")
105            .field("entries", &self.entries.len())
106            .field("baseline", &self.baseline)
107            .field("stats", &self.stats)
108            .finish_non_exhaustive()
109    }
110}
111
112impl Default for AnalysisMemo {
113    fn default() -> Self {
114        Self {
115            types: Arc::new(Types::new()),
116            entries: HashMap::new(),
117            seen: HashSet::new(),
118            baseline: 0,
119            decls: DeclDigests::default(),
120            growth_factor: GROWTH_FACTOR,
121            min_reset_len: MIN_RESET_LEN,
122            stats: MemoStats::default(),
123        }
124    }
125}
126
127impl AnalysisMemo {
128    /// A memo that has seen no round.
129    pub fn new() -> Self {
130        Self::default()
131    }
132
133    /// A memo with its own growth limits, so a test can exercise the reset.
134    pub fn with_limits(growth_factor: usize, min_reset_len: usize) -> Self {
135        Self {
136            growth_factor,
137            min_reset_len,
138            ..Self::default()
139        }
140    }
141
142    /// What the last round did.
143    pub fn stats(&self) -> MemoStats {
144        self.stats
145    }
146
147    /// The table every round of this memo interns into.
148    pub(crate) fn types(&self) -> &Arc<Types> {
149        &self.types
150    }
151
152    /// Start a round: apply the growth policy, and reset the per-round counters.
153    pub(crate) fn begin_round(&mut self) {
154        let resets = self.stats.resets;
155        self.stats = MemoStats {
156            resets,
157            ..MemoStats::default()
158        };
159        self.seen.clear();
160        // `end_round` already emptied it; a round that did not end would leave
161        // addresses that a new allocation could reuse.
162        debug_assert_eq!(
163            self.decls.len(),
164            0,
165            "the previous round's digests were kept"
166        );
167        self.decls = DeclDigests::default();
168        if self.types.len() > self.min_reset_len
169            && self.types.len() > self.growth_factor * self.baseline
170        {
171            self.types = Arc::new(Types::new());
172            self.entries.clear();
173            self.baseline = 0;
174            self.stats.resets += 1;
175        }
176    }
177
178    /// The round's declaration digests.
179    pub(crate) fn decls_mut(&mut self) -> &mut DeclDigests {
180        &mut self.decls
181    }
182
183    /// The record for `path` if its digest is unchanged.
184    pub(crate) fn lookup(&mut self, path: &PathBuf, digest: u64) -> Option<FileRecord> {
185        self.seen.insert(path.clone());
186        let hit = self
187            .entries
188            .get(path)
189            .filter(|e| e.digest == digest)
190            .map(|e| e.record.clone());
191        if hit.is_some() {
192            self.stats.hits += 1;
193        } else {
194            self.stats.misses += 1;
195        }
196        hit
197    }
198
199    pub(crate) fn store(&mut self, path: PathBuf, digest: u64, record: FileRecord) {
200        self.entries.insert(path, Entry { digest, record });
201    }
202
203    /// End a round: forget files that are gone, and record the table's size as
204    /// the baseline if this round started cold.
205    pub(crate) fn end_round(&mut self) {
206        let seen = &self.seen;
207        self.entries.retain(|p, _| seen.contains(p));
208        if self.baseline == 0 {
209            self.baseline = self.types.len();
210        }
211        self.stats.entries = self.entries.len();
212        self.stats.type_table_len = self.types.len();
213        // The declaration digests are keyed by address and valid only while the
214        // round's tables pin the `Arc`s: drop them with the round, so no later
215        // allocation at a reused address can be handed a stale hash.
216        self.stats.decls_hashed = self.decls.len();
217        self.decls = DeclDigests::default();
218    }
219}
220
221/// One analysis round over `roots`, free to reuse what `memo` learned from the
222/// previous round. Must answer exactly what `analyse_project` answers; the
223/// oracle holds it to that.
224pub fn analyse_project_memoised(
225    roots: &Roots,
226    overlay: &HashMap<PathBuf, String>,
227    schema_lock: &SchemaLock,
228    memo: &mut AnalysisMemo,
229) -> ProjectAnalysis {
230    analyse_project_cached(roots, overlay, schema_lock, memo)
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236    use crate::analysis::analyse_project;
237
238    /// #3243 S2.4a: the per-round declaration digests are keyed by address, so they
239    /// must not outlive the round that pins the `Arc`s: a later allocation at a
240    /// reused address would be handed a stale hash.
241    #[test]
242    fn a_round_leaves_no_declaration_digests_behind() {
243        let root = std::env::temp_dir().join(format!("bynk-memo-decls-{}", std::process::id()));
244        let _ = std::fs::remove_dir_all(&root);
245        std::fs::create_dir_all(&root).unwrap();
246        let src = |name: &str| {
247            format!(
248                "context {name}\n\ntype Row = {{\n  id: String,\n  qty: Int,\n}}\n\nservice probe {{\n  on call(n: Int) -> Effect[Int] by Caller {{\n    Effect.pure(n)\n  }}\n}}\n"
249            )
250        };
251        let mut overlay = HashMap::new();
252        for name in ["alpha", "beta"] {
253            let path = root.join(format!("{name}.bynk"));
254            std::fs::write(&path, src(name)).unwrap();
255            overlay.insert(path, src(name));
256        }
257        let roots = Roots::Single(root.clone());
258        let mut memo = AnalysisMemo::new();
259        for round in 0..3 {
260            analyse_project_memoised(&roots, &overlay, &SchemaLock::Off, &mut memo);
261            assert!(
262                memo.stats().decls_hashed > 0,
263                "round {round} hashed the declarations it shares"
264            );
265            assert_eq!(memo.decls.len(), 0, "round {round} ended with digests held");
266        }
267        let _ = std::fs::remove_dir_all(&root);
268    }
269
270    #[test]
271    fn plain_analysis_does_not_touch_a_memo() {
272        // `analyse_project` has no memo parameter at all: the cold path stays
273        // table-free by its signature. This pins that it is still the function
274        // the memoised one is compared to.
275        let f: fn(&Roots, &HashMap<PathBuf, String>, &SchemaLock) -> ProjectAnalysis =
276            analyse_project;
277        let _ = f;
278    }
279}