Skip to main content

bynk_check/
oracle.rs

1//! The differential oracle's comparison (#3243, #1523 S2).
2//!
3//! The language server is to reuse per-file analysis work between edits (a memo
4//! table, [`crate::memo`]). The one property that must never break is that a
5//! reused round answers **exactly** what a fresh round answers: a stale
6//! diagnostic is the failure mode of every incremental scheme. This module is
7//! what the CI oracle compares: [`canonical_report`] renders everything a
8//! [`ProjectAnalysis`] says into one deterministic string, so two analyses are
9//! equal exactly when their reports are.
10//!
11//! Deterministic means independent of everything that is not meaning:
12//!
13//! - hash-map iteration order: maps are walked in sorted key order;
14//! - `TyId`s, which are indices into one analysis's own interner and differ
15//!   between two analyses of the same project: types are rendered structurally
16//!   through each analysis's own table (`Types::display`), never by id.
17//!
18//! What it deliberately does not compare is memory identity (`Arc` pointers) or
19//! timing. Fields whose `Debug` output contains a hash map (the sequence and
20//! boundary tables) are compared through their sorted keys and the sorted debug
21//! of each entry, one level deep; the checker's own results (diagnostics, index,
22//! hints, locals, requirements, expression types, capability paths, contract
23//! diff) are compared in full.
24
25use std::collections::{BTreeMap, HashMap};
26use std::fmt::{Debug, Write};
27
28use crate::analysis::{ContextBoundaryInfo, ContextSequenceInfo, ProjectAnalysis};
29use crate::index::ProjectIndex;
30use crate::resolver::CrossContextInfo;
31
32/// One deterministic rendering of everything `analysis` says. See the module doc.
33pub fn canonical_report(analysis: &ProjectAnalysis) -> String {
34    let mut out = String::new();
35    // Destructured exhaustively, with no `..`: a field added to `ProjectAnalysis`
36    // is a compile error here until the report accounts for it, so a memo cannot
37    // serve a stale value for a field the oracle never looked at.
38    let ProjectAnalysis {
39        snapshots,
40        errors,
41        index,
42        hints,
43        expr_types,
44        ty_intern,
45        locals,
46        requirements,
47        capability_paths,
48        unit_sources,
49        sequence_info,
50        architecture_facts,
51        boundary_info,
52        doc_scope,
53        contract_diff,
54    } = analysis;
55    let ProjectIndex {
56        symbols,
57        foreign_refs,
58        calls,
59        impls,
60        refinements,
61    } = index;
62
63    section(&mut out, "snapshots", {
64        let mut v: Vec<String> = snapshots.iter().map(|s| format!("{s:?}")).collect();
65        v.sort();
66        v
67    });
68    // The error list's order is part of the contract: it is what the user reads.
69    section(
70        &mut out,
71        "errors",
72        errors
73            .iter()
74            .map(|e| format!("{:?} | {:?} | {:?}", e.source_path, e.error, e.label_files))
75            .collect(),
76    );
77
78    section(&mut out, "index.symbols", sorted_map(symbols));
79    section(&mut out, "index.foreign_refs", debug_all(foreign_refs));
80    section(&mut out, "index.calls", debug_all(calls));
81    section(&mut out, "index.impls", debug_all(impls));
82    section(&mut out, "index.refinements", debug_all(refinements));
83
84    section(&mut out, "hints", sorted_map(hints));
85    section(&mut out, "locals", sorted_map(locals));
86    section(&mut out, "requirements", sorted_map(requirements));
87    section(&mut out, "capability_paths", sorted_map(capability_paths));
88
89    // Expression types are `(Span, TyId)`; the id means nothing outside this
90    // analysis's own table, so each is rendered through it.
91    let tys = ty_intern;
92    let expr: BTreeMap<String, Vec<String>> = expr_types
93        .iter()
94        .map(|(path, entries)| {
95            (
96                format!("{path:?}"),
97                entries
98                    .iter()
99                    .map(|(span, id)| format!("{span:?} : {}", tys.display(*id)))
100                    .collect(),
101            )
102        })
103        .collect();
104    section(
105        &mut out,
106        "expr_types",
107        expr.into_iter()
108            .map(|(path, entries)| format!("{path} => {entries:?}"))
109            .collect(),
110    );
111
112    section(&mut out, "unit_sources", sorted_map(unit_sources));
113    section(&mut out, "doc_scope", sorted_map(doc_scope));
114    section(
115        &mut out,
116        "contract_diff",
117        vec![format!("{contract_diff:?}")],
118    );
119    section(
120        &mut out,
121        "sequence_info",
122        sorted_lines(sequence_info.iter().map(|(name, info)| {
123            let ContextSequenceInfo {
124                cross_context: cc,
125                agents,
126            } = info;
127            format!(
128                "{name:?} => cross_context[{}] agents[{}]",
129                cross_context(cc),
130                sorted_map(agents).join("; ")
131            )
132        })),
133    );
134    section(
135        &mut out,
136        "architecture_facts",
137        vec![format!("{architecture_facts:?}")],
138    );
139    section(
140        &mut out,
141        "boundary_info",
142        sorted_lines(boundary_info.iter().map(|(name, info)| {
143            let ContextBoundaryInfo {
144                types,
145                services,
146                agents,
147                ..
148            } = info;
149            format!(
150                "{name:?} => types[{}] services[{}] agents[{}]",
151                sorted_map(types).join("; "),
152                sorted_map(services).join("; "),
153                sorted_map(agents).join("; ")
154            )
155        })),
156    );
157    out
158}
159
160/// A [`CrossContextInfo`] with every map and set in sorted order. Its fields are
161/// maps of maps, so `Debug` on the whole would print hash order.
162pub(crate) fn cross_context(c: &CrossContextInfo) -> String {
163    // Exhaustive (no `..`), like `canonical_report`: a field added to
164    // `CrossContextInfo` must be accounted for here.
165    let CrossContextInfo {
166        self_context,
167        consumed_contexts,
168        aliases,
169        consumed_services,
170        consumed_types,
171        consumed_type_renames,
172        consumed_capabilities,
173        flattened_caps,
174        consumed_event_names,
175        consumed_type_owners,
176        consumed_type_aliases,
177        callee_type_aliases,
178        callee_alias_keys,
179        cookie_records,
180        signed_cookie_names,
181    } = c;
182    fn two_level<V: Debug>(map: &HashMap<String, HashMap<String, V>>) -> String {
183        sorted_lines(
184            map.iter()
185                .map(|(k, inner)| format!("{k:?} => {{{}}}", sorted_map(inner).join("; "))),
186        )
187        .join("; ")
188    }
189    let events = sorted_lines(consumed_event_names.iter().map(|(k, set)| {
190        let mut names: Vec<&String> = set.iter().collect();
191        names.sort();
192        format!("{k:?} => {names:?}")
193    }))
194    .join("; ");
195    [
196        format!("self_context={:?}", self_context),
197        format!("consumed_contexts={:?}", consumed_contexts),
198        format!("aliases={{{}}}", sorted_map(aliases).join("; ")),
199        format!("consumed_services={{{}}}", two_level(consumed_services)),
200        format!("consumed_types={{{}}}", two_level(consumed_types)),
201        format!(
202            "consumed_type_renames={{{}}}",
203            two_level(consumed_type_renames)
204        ),
205        format!(
206            "consumed_capabilities={{{}}}",
207            two_level(consumed_capabilities)
208        ),
209        format!(
210            "flattened_caps={{{}}}",
211            sorted_map(flattened_caps).join("; ")
212        ),
213        format!("consumed_event_names={{{events}}}"),
214        format!(
215            "consumed_type_owners={{{}}}",
216            two_level(consumed_type_owners)
217        ),
218        format!(
219            "consumed_type_aliases={{{}}}",
220            two_level(consumed_type_aliases)
221        ),
222        format!("callee_type_aliases={{{}}}", two_level(callee_type_aliases)),
223        format!("callee_alias_keys={{{}}}", two_level(callee_alias_keys)),
224        format!(
225            "cookie_records={:?}",
226            sorted_lines(cookie_records.iter().cloned())
227        ),
228        format!(
229            "signed_cookie_names={:?}",
230            sorted_lines(signed_cookie_names.iter().cloned())
231        ),
232    ]
233    .join(" ")
234}
235
236fn sorted_lines(lines: impl IntoIterator<Item = String>) -> Vec<String> {
237    let mut v: Vec<String> = lines.into_iter().collect();
238    v.sort();
239    v
240}
241
242fn section(out: &mut String, name: &str, lines: Vec<String>) {
243    let _ = writeln!(out, "== {name} ({})", lines.len());
244    for line in lines {
245        let _ = writeln!(out, "{line}");
246    }
247}
248
249fn debug_all<T: Debug>(items: &[T]) -> Vec<String> {
250    items.iter().map(|i| format!("{i:?}")).collect()
251}
252
253/// A map as sorted `key => value` lines, so its hash order cannot show.
254fn sorted_map<'a, K, V>(map: impl IntoIterator<Item = (&'a K, &'a V)>) -> Vec<String>
255where
256    K: Debug + 'a,
257    V: Debug + 'a,
258{
259    let mut v: Vec<String> = map
260        .into_iter()
261        .map(|(k, val)| format!("{k:?} => {val:?}"))
262        .collect();
263    v.sort();
264    v
265}