bynk_check/requirements.rs
1//! v0.99 (ADR — agent capability provenance): the capability-requirement ledger.
2//!
3//! A requirement is *where a capability is needed and why*. The checker already
4//! decides, at every capability-consuming site, whether the enclosing handler's
5//! `given` covers it (and errors when it does not). This sink records **every**
6//! such decision — covered or not — so the editor surfaces can answer two
7//! questions the bare diagnostic cannot:
8//!
9//! - *"What `given` does this handler still need?"* — the uncovered requirements
10//! drive the materializable ghost `given` inlay hint (DECISION E).
11//! - *"Why does this handler declare `given Clock`?"* — the covered requirements
12//! explain, on hover, what a declared capability is *for*.
13//!
14//! The sink mirrors [`HintSink`](crate::hints::HintSink): a `&mut` parameter
15//! threaded through the checker entry points, NOT part of the `Ok(TypedCommons)`
16//! payload — so requirements persist through a transient type error at every
17//! site the checker still reaches. Spans are bare byte offsets into the file the
18//! sink was attributed to via [`RequirementSink::enter_file`].
19//!
20//! **Decisive property (DECISION C):** the human *reason* is a total function of
21//! the [`RequirementSource`] — a small closed enum — with **no per-capability
22//! text**. Adding a new capability needs zero new reason text; a fragment is
23//! authored only when a new capability-*consuming feature* is added (a store
24//! kind, a builtin) — a closed, compiler-internal set.
25
26use crate::capability_paths::{CapabilityGraph, FileCapabilityPaths};
27use bynk_syntax::span::{FileId, Span};
28use std::collections::HashMap;
29use std::path::{Path, PathBuf};
30
31/// Why a capability requirement arises. The reason renders from this alone.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum RequirementSource {
34 /// The body calls `Cap.op(...)` directly — the call site *is* the
35 /// explanation. Correct for **any** capability, including user-defined ones
36 /// (`Payments.authorise` → *"calls `Payments.authorise`"*) with no bespoke
37 /// text.
38 DirectCall { op: String },
39 /// A storage op consumes a capability. `(kind, op)` keys a reason fragment
40 /// owned by the storage feature — the only code that knows *why* a store
41 /// needs a capability (e.g. `Cache` eviction reads the clock).
42 StoreOp { kind: StoreKind, op: String },
43 /// A language builtin draws on a capability (e.g. `Uuid` → `Random`). The
44 /// fragment is owned by the builtin's surface.
45 Builtin { feature: String },
46}
47
48/// The storage kinds that consume a capability. A closed set: a new kind is a
49/// deliberate language addition, and adding one is the only time a new store
50/// reason fragment is authored.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum StoreKind {
53 Cache,
54 Log,
55}
56
57impl StoreKind {
58 pub fn as_str(self) -> &'static str {
59 match self {
60 StoreKind::Cache => "Cache",
61 StoreKind::Log => "Log",
62 }
63 }
64}
65
66impl RequirementSource {
67 /// The human reason for a requirement, derived purely from the source — no
68 /// per-capability text. `capability` names the required capability so a
69 /// `DirectCall` can render `calls \`Cap.op\``.
70 pub fn reason(&self, capability: &str) -> String {
71 match self {
72 RequirementSource::DirectCall { op } => format!("calls `{capability}.{op}`"),
73 RequirementSource::StoreOp { kind, op } => store_reason(*kind, op).to_string(),
74 RequirementSource::Builtin { feature } => {
75 format!("the `{feature}` builtin draws on `{capability}`")
76 }
77 }
78 }
79}
80
81/// The storage feature's `(kind, op) -> reason` table — the one place that knows
82/// *why* a store consumes a capability. Total over the clock-consuming store ops
83/// (`requirements::tests::store_reason_table_is_total` pins this); a `(kind, op)`
84/// outside the table falls back to a generic phrasing rather than panicking, so
85/// a new store op can never crash a render before its fragment is authored.
86pub fn store_reason(kind: StoreKind, op: &str) -> &'static str {
87 match (kind, op) {
88 // Every `Cache` op but `remove` applies TTL expiry, which reads the clock.
89 (StoreKind::Cache, "put" | "get" | "update" | "upsert" | "contains" | "size") => {
90 "a `Cache` operation applies TTL expiry, which reads the clock"
91 }
92 // `Log.append` stamps the current time.
93 (StoreKind::Log, "append") => "`Log.append` stamps the current time, which reads the clock",
94 _ => "a storage operation consumes this capability",
95 }
96}
97
98/// One capability requirement: which capability, at what site, why, and whether
99/// the enclosing handler already covers it.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct Requirement {
102 /// The required capability's simple name (the deps key) — e.g. `Clock`.
103 pub capability: String,
104 /// The consuming site (the op or direct-call span).
105 pub site: Span,
106 pub source: RequirementSource,
107 /// `true` when the enclosing handler's `given` already lists the capability.
108 /// An uncovered requirement drives the ghost `given` inlay hint; a covered
109 /// one explains, on hover, what a declared capability is for.
110 pub covered: bool,
111 /// For an **uncovered** requirement, where the ghost `given` would render
112 /// (the handler's return-type span) — and the edit that materializes the
113 /// clause. `None` for covered requirements and where no anchor applies
114 /// (e.g. a provider body, which has no return-type-anchored `given`).
115 pub materialize: Option<Materialize>,
116}
117
118/// The data the ghost `given` inlay hint needs to render and one-click apply.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct Materialize {
121 /// Where the ghost clause renders — the end of the handler's return type.
122 pub anchor: Span,
123 /// The text edit that writes the real `given Cap` (or `, Cap`) clause.
124 pub edit_span: Span,
125 pub edit_text: String,
126}
127
128/// Project-relative source path → that file's requirements, span-ordered.
129pub type FileRequirements = HashMap<PathBuf, Vec<Requirement>>;
130
131/// Records capability requirements per file. A fresh sink records nothing until
132/// [`enter_file`](Self::enter_file) attributes it.
133#[derive(Debug, Default, Clone)]
134pub struct RequirementSink {
135 files: FileRequirements,
136 /// #2469: per-file capability paths, built after a unit's bodies are checked.
137 paths: FileCapabilityPaths,
138 file: Option<PathBuf>,
139 /// The checker's id for `file`, when the pipeline supplies one.
140 file_id: FileId,
141 /// Set for synthetic (toolchain-injected) and test/integration files:
142 /// requirements are discarded — they never surface in an editor.
143 muted: bool,
144}
145
146impl RequirementSink {
147 pub fn new() -> Self {
148 Self::default()
149 }
150
151 /// Enter a per-file recording context.
152 pub fn enter_file(&mut self, file: &Path, muted: bool) {
153 self.file = Some(file.to_path_buf());
154 self.muted = muted;
155 }
156
157 /// #2469: the checker's id for the file being checked, so its capability
158 /// graph can name it even when the unit's table says nothing of this file.
159 pub fn set_file_id(&mut self, id: FileId) {
160 self.file_id = id;
161 }
162
163 /// Record a requirement. Dropped when muted or before any `enter_file`.
164 pub fn record(&mut self, req: Requirement) {
165 if self.muted {
166 return;
167 }
168 let Some(file) = &self.file else {
169 return;
170 };
171 self.files.entry(file.clone()).or_default().push(req);
172 }
173
174 /// The requirements recorded so far for the file being checked.
175 pub fn current(&self) -> &[Requirement] {
176 self.file
177 .as_ref()
178 .and_then(|f| self.files.get(f))
179 .map_or(&[], Vec::as_slice)
180 }
181
182 /// #2469: attach the capability graph built over the file being checked.
183 /// Dropped when muted or before any `enter_file`, like [`record`](Self::record).
184 /// An empty graph is kept: it still names the file's id, which the editor
185 /// needs to link a step that lies in a file with no `given` of its own.
186 pub fn record_paths(&mut self, mut graph: CapabilityGraph) {
187 if self.muted {
188 return;
189 }
190 let Some(file) = &self.file else {
191 return;
192 };
193 if self.file_id != FileId::UNKNOWN {
194 graph.file = self.file_id;
195 }
196 self.paths.entry(file.clone()).or_default().merge(graph);
197 }
198
199 /// Fold in what `other` recorded (#3243 S2.3), per file, in order.
200 pub fn absorb(&mut self, other: RequirementSink) {
201 for (file, entries) in other.files {
202 self.files.entry(file).or_default().extend(entries);
203 }
204 for (file, graph) in other.paths {
205 self.paths.entry(file).or_default().merge(graph);
206 }
207 }
208
209 /// Drain the capability paths recorded per file.
210 pub fn take_paths(&mut self) -> FileCapabilityPaths {
211 std::mem::take(&mut self.paths)
212 }
213
214 /// Drain the recorded requirements, each file's entries ordered by span.
215 pub fn take_files(&mut self) -> FileRequirements {
216 let mut files = std::mem::take(&mut self.files);
217 for reqs in files.values_mut() {
218 reqs.sort_by_key(|r| (r.site.start, r.site.end));
219 }
220 files
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 /// DECISION C: the store-reason table is total over the clock-consuming
229 /// store ops — every op that records a `StoreOp` requirement has a concrete
230 /// (non-fallback) fragment, so the reason is never the generic placeholder
231 /// for a real requirement.
232 #[test]
233 fn store_reason_table_is_total() {
234 let cache_ops = ["put", "get", "update", "upsert", "contains", "size"];
235 for op in cache_ops {
236 let r = store_reason(StoreKind::Cache, op);
237 assert_ne!(
238 r, "a storage operation consumes this capability",
239 "Cache.{op} has no concrete reason fragment"
240 );
241 }
242 assert_ne!(
243 store_reason(StoreKind::Log, "append"),
244 "a storage operation consumes this capability",
245 "Log.append has no concrete reason fragment"
246 );
247 }
248
249 /// DECISION C: a user-defined capability's `DirectCall` reason renders with
250 /// no bespoke entry — the call site is the whole explanation.
251 #[test]
252 fn direct_call_reason_needs_no_bespoke_entry() {
253 let src = RequirementSource::DirectCall {
254 op: "authorise".to_string(),
255 };
256 assert_eq!(src.reason("Payments"), "calls `Payments.authorise`");
257 }
258}