Skip to main content

bynk_check/
capability_paths.rs

1//! #2469: capability *paths* — the answer to "why does this need `Logger`?".
2//!
3//! The [requirement ledger](crate::requirements) records every capability use
4//! and whether the enclosing declaration's `given` covers it. This module adds
5//! the second half of the explanation: how a declaration *reaches* a use that
6//! lives in another body. The only such edge in the language is an agent-handler
7//! call (`Agent(key).m()`): a service or agent handler's deps are widened to
8//! cover the agent handlers it calls (#527), and a provider must list them in
9//! its `given` (`bynk.provider.agent_call_undeclared_capability`).
10//!
11//! The checker owns the answer. [`CapabilityGraph::build`] runs in the same
12//! pass as that provider check, over the same `Callee::Agent` classification,
13//! and records two things per file:
14//!
15//! - one **witness** — the shortest chain — for each `(given entry, capability)`
16//!   pair, so a hover is a lookup; and
17//! - the compact call/use facts the witnesses were drawn from, so the full set
18//!   of chains is computed *on demand* ([`CapabilityGraph::all_paths`]) rather
19//!   than stored for every pair.
20//!
21//! Nothing here re-reads source text: the editor surfaces ask this module, they
22//! never re-derive a path.
23
24use crate::checker::Callee;
25use crate::requirements::{Requirement, RequirementSource};
26use crate::symbols::UnitTable;
27use bynk_syntax::ast::{Block, CapRef, ExprId, HandlerKind};
28use bynk_syntax::span::{FileId, Span};
29use std::collections::{HashMap, HashSet, VecDeque};
30use std::path::PathBuf;
31
32/// The most chains [`CapabilityGraph::all_paths`] returns for one entry. A
33/// densely connected project can have exponentially many simple paths; the
34/// action lists the shortest `MAX_PATHS` and says it stopped.
35pub const MAX_PATHS: usize = 64;
36
37/// The most nodes one [`CapabilityGraph::all_paths`] walk expands before it
38/// stops with the chains found so far.
39const WALK_BUDGET: usize = 20_000;
40
41/// One hop of a capability path.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum PathStep {
44    /// The declaration being walked calls the agent handler `agent.handler` at
45    /// `site` (the method name in the call).
46    Call {
47        site: Span,
48        agent: String,
49        handler: String,
50    },
51    /// The chain ends: the capability is used at `site`.
52    Use {
53        site: Span,
54        source: RequirementSource,
55    },
56}
57
58impl PathStep {
59    pub fn site(&self) -> Span {
60        match self {
61            PathStep::Call { site, .. } | PathStep::Use { site, .. } => *site,
62        }
63    }
64}
65
66/// A chain from a declaration to a use of a capability: zero or more
67/// [`PathStep::Call`]s then exactly one [`PathStep::Use`]. A *direct* use is the
68/// one-step chain.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct CapabilityPath {
71    pub steps: Vec<PathStep>,
72}
73
74impl CapabilityPath {
75    /// `true` when the declaration uses the capability itself.
76    pub fn is_direct(&self) -> bool {
77        self.steps.len() == 1
78    }
79}
80
81/// The shortest chain recorded for one `given` entry.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct CapabilityWitness {
84    /// The `given` entry the chain explains.
85    pub given_entry: Span,
86    pub capability: String,
87    /// The declaration that carries the entry: `Cart.add`, a provider's name.
88    pub declaration: String,
89    pub path: CapabilityPath,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93struct Use {
94    capability: String,
95    site: Span,
96    source: RequirementSource,
97}
98
99#[derive(Debug, Clone, PartialEq, Eq)]
100struct Node {
101    label: String,
102    uses: Vec<Use>,
103    /// `(call site, callee node)`, in source order.
104    calls: Vec<(Span, usize, String, String)>,
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
108struct Entry {
109    given_entry: Span,
110    capability: String,
111    node: usize,
112}
113
114/// One file's capability call/use facts and the witnesses drawn from them.
115#[derive(Debug, Clone, Default, PartialEq, Eq)]
116pub struct CapabilityGraph {
117    /// The file this graph was recorded for. A unit's table spans all of its
118    /// files, so the steps of a path can lie in a sibling file; the span's own
119    /// file id says which, and this lets the editor map ids back to paths.
120    pub file: FileId,
121    nodes: Vec<Node>,
122    entries: Vec<Entry>,
123    witnesses: Vec<CapabilityWitness>,
124}
125
126/// Project-relative source path → that file's capability graph.
127pub type FileCapabilityPaths = HashMap<PathBuf, CapabilityGraph>;
128
129/// A handler-shaped body the walk treats as one node: its own `given`, body, and
130/// the label it is shown under.
131struct Decl<'t> {
132    label: String,
133    given: &'t [CapRef],
134    bodies: Vec<&'t Block>,
135}
136
137fn handler_label(owner: &str, kind: &HandlerKind, method: Option<&str>) -> String {
138    match (method, kind) {
139        (Some(m), _) => format!("{owner}.{m}"),
140        (None, HandlerKind::Call) => format!("{owner}.call"),
141        (None, _) => owner.to_string(),
142    }
143}
144
145fn within(inner: Span, outer: Span) -> bool {
146    let same_file =
147        inner.file == outer.file || inner.file == FileId::UNKNOWN || outer.file == FileId::UNKNOWN;
148    same_file && outer.start <= inner.start && inner.end <= outer.end
149}
150
151/// A graph is per file, so lookups key on the byte range alone — the editor
152/// holds offsets, not the checker's file ids.
153fn same_range(a: Span, b: Span) -> bool {
154    a.start == b.start && a.end == b.end
155}
156
157impl CapabilityGraph {
158    pub fn is_empty(&self) -> bool {
159        self.entries.is_empty()
160    }
161
162    /// Fold `other` in. A unit-wide table is walked once per file of the unit,
163    /// so a graph whose entries are all already present adds nothing.
164    pub fn merge(&mut self, other: CapabilityGraph) {
165        let known: HashSet<(Span, String)> = self
166            .entries
167            .iter()
168            .map(|e| (e.given_entry, e.capability.clone()))
169            .collect();
170        let fresh = |given_entry: Span, capability: &str| {
171            !known.contains(&(given_entry, capability.to_string()))
172        };
173        if self.file == FileId::UNKNOWN {
174            self.file = other.file;
175        }
176        if !other
177            .entries
178            .iter()
179            .any(|e| fresh(e.given_entry, &e.capability))
180        {
181            return;
182        }
183        let base = self.nodes.len();
184        for n in &other.nodes {
185            let mut n = n.clone();
186            for c in &mut n.calls {
187                c.1 += base;
188            }
189            self.nodes.push(n);
190        }
191        for e in other.entries {
192            if fresh(e.given_entry, &e.capability) {
193                self.entries.push(Entry {
194                    node: e.node + base,
195                    ..e
196                });
197            }
198        }
199        for w in other.witnesses {
200            if fresh(w.given_entry, &w.capability) {
201                self.witnesses.push(w);
202            }
203        }
204    }
205
206    /// Build the graph for a unit table. `requirements` is the ledger recorded
207    /// so far for the file being checked; only **covered** requirements are
208    /// uses (an uncovered one is a missing `given`, not a path).
209    pub fn build(
210        table: &UnitTable,
211        callees: &HashMap<ExprId, Callee>,
212        requirements: &[Requirement],
213        own: FileId,
214    ) -> CapabilityGraph {
215        let mut decls: Vec<Decl<'_>> = Vec::new();
216        let mut agents: Vec<_> = table.agents.values().collect();
217        agents.sort_by_key(|a| a.span.start);
218        for agent in agents {
219            for h in &agent.handlers {
220                decls.push(Decl {
221                    label: handler_label(
222                        &agent.name.name,
223                        &h.kind,
224                        h.method_name.as_ref().map(|m| m.name.as_str()),
225                    ),
226                    given: &h.given,
227                    bodies: vec![&h.body],
228                });
229            }
230        }
231        let mut services: Vec<_> = table.services.values().collect();
232        services.sort_by_key(|s| s.span.start);
233        for svc in services {
234            for h in &svc.handlers {
235                decls.push(Decl {
236                    label: handler_label(
237                        &svc.name.name,
238                        &h.kind,
239                        h.method_name.as_ref().map(|m| m.name.as_str()),
240                    ),
241                    given: &h.given,
242                    bodies: vec![&h.body],
243                });
244            }
245        }
246        let mut providers: Vec<_> = table.providers.values().collect();
247        providers.sort_by_key(|p| p.span.start);
248        for p in providers {
249            decls.push(Decl {
250                label: p.provider_name.name.clone(),
251                given: &p.given,
252                bodies: p.ops.iter().map(|op| &op.body).collect(),
253            });
254        }
255
256        // Agent handler `(agent, handler)` → its node, for call edges.
257        let mut handler_node: HashMap<(String, String), usize> = HashMap::new();
258        for (i, d) in decls.iter().enumerate() {
259            if let Some((a, m)) = d.label.split_once('.')
260                && table.agents.contains_key(a)
261            {
262                handler_node.insert((a.to_string(), m.to_string()), i);
263            }
264        }
265
266        let mut nodes = Vec::with_capacity(decls.len());
267        for d in &decls {
268            let mut uses = Vec::new();
269            let mut calls = Vec::new();
270            for body in &d.bodies {
271                for r in requirements.iter().filter(|r| r.covered) {
272                    if within(r.site, body.span) {
273                        uses.push(Use {
274                            capability: r.capability.clone(),
275                            site: r.site,
276                            source: r.source.clone(),
277                        });
278                    }
279                }
280                for (agent, handler, site) in crate::context_checks::agent_calls_in(body, callees) {
281                    if let Some(&to) = handler_node.get(&(agent.clone(), handler.clone())) {
282                        calls.push((site, to, agent, handler));
283                    }
284                }
285            }
286            uses.sort_by_key(|u| (u.site.start, u.site.end));
287            calls.sort_by_key(|c| (c.0.start, c.0.end));
288            nodes.push(Node {
289                label: d.label.clone(),
290                uses,
291                calls,
292            });
293        }
294
295        let mut graph = CapabilityGraph {
296            file: own,
297            nodes,
298            entries: Vec::new(),
299            witnesses: Vec::new(),
300        };
301        let mut reported: HashSet<(usize, &str)> = HashSet::new();
302        for (i, d) in decls.iter().enumerate() {
303            for cap in d.given {
304                // Each file's pass walks the whole unit; an entry is explained
305                // by the pass of the file it is written in.
306                if cap.span.file != own && cap.span.file != FileId::UNKNOWN {
307                    continue;
308                }
309                // A second `given` of the same capability on one declaration is
310                // already a diagnosed duplicate; only the first is explained.
311                if !reported.insert((i, cap.key())) {
312                    continue;
313                }
314                graph.entries.push(Entry {
315                    given_entry: cap.span,
316                    capability: cap.key().to_string(),
317                    node: i,
318                });
319            }
320        }
321        for e in &graph.entries {
322            if let Some(path) = graph.shortest(e.node, &e.capability) {
323                graph.witnesses.push(CapabilityWitness {
324                    given_entry: e.given_entry,
325                    capability: e.capability.clone(),
326                    declaration: graph.nodes[e.node].label.clone(),
327                    path,
328                });
329            }
330        }
331        graph
332    }
333
334    /// The `given` entry covering byte `offset` (a cursor on either edge counts),
335    /// with the capability it names.
336    pub fn entry_at(&self, offset: usize) -> Option<(Span, &str)> {
337        self.entries
338            .iter()
339            .find(|e| e.given_entry.start <= offset && offset <= e.given_entry.end)
340            .map(|e| (e.given_entry, e.capability.as_str()))
341    }
342
343    /// The shortest recorded chain for the `given` entry at `given_entry`.
344    pub fn witness(&self, given_entry: Span) -> Option<&CapabilityWitness> {
345        self.witnesses
346            .iter()
347            .find(|w| same_range(w.given_entry, given_entry))
348    }
349
350    /// Every chain from the declaration carrying `given_entry` to a use of its
351    /// capability, shortest first, at most [`MAX_PATHS`]. Computed on demand
352    /// from the recorded call/use facts. The `bool` is `true` when the cap cut
353    /// the list short.
354    pub fn all_paths(&self, given_entry: Span) -> Option<(String, Vec<CapabilityPath>, bool)> {
355        let e = self
356            .entries
357            .iter()
358            .find(|e| same_range(e.given_entry, given_entry))?;
359        let mut paths = self.walk(e.node, &e.capability, MAX_PATHS + 1);
360        let truncated = paths.len() > MAX_PATHS;
361        paths.truncate(MAX_PATHS);
362        Some((e.capability.clone(), paths, truncated))
363    }
364
365    /// The nodes from which a use of `capability` is reachable (a use of its
366    /// own counts). Walks that never leave this set cannot dead-end.
367    fn reaches(&self, capability: &str) -> Vec<bool> {
368        let mut callers: Vec<Vec<usize>> = vec![Vec::new(); self.nodes.len()];
369        for (i, n) in self.nodes.iter().enumerate() {
370            for c in &n.calls {
371                callers[c.1].push(i);
372            }
373        }
374        let mut reach = vec![false; self.nodes.len()];
375        let mut stack: Vec<usize> = Vec::new();
376        for (i, n) in self.nodes.iter().enumerate() {
377            if n.uses.iter().any(|u| u.capability == capability) {
378                reach[i] = true;
379                stack.push(i);
380            }
381        }
382        while let Some(i) = stack.pop() {
383            for &c in &callers[i] {
384                if !reach[c] {
385                    reach[c] = true;
386                    stack.push(c);
387                }
388            }
389        }
390        reach
391    }
392
393    /// The shortest chain from `from` to a use of `capability`: a breadth-first
394    /// search over nodes with a parent pointer each, O(nodes + calls).
395    fn shortest(&self, from: usize, capability: &str) -> Option<CapabilityPath> {
396        // node -> (predecessor, the call step that reached it)
397        let mut parent: HashMap<usize, (usize, PathStep)> = HashMap::new();
398        let mut seen: HashSet<usize> = HashSet::from([from]);
399        let mut queue: VecDeque<usize> = VecDeque::from([from]);
400        while let Some(node) = queue.pop_front() {
401            let n = &self.nodes[node];
402            if let Some(u) = n.uses.iter().find(|u| u.capability == capability) {
403                let mut steps = vec![PathStep::Use {
404                    site: u.site,
405                    source: u.source.clone(),
406                }];
407                let mut at = node;
408                while let Some((prev, step)) = parent.get(&at) {
409                    steps.push(step.clone());
410                    at = *prev;
411                }
412                steps.reverse();
413                return Some(CapabilityPath { steps });
414            }
415            for (site, to, agent, handler) in &n.calls {
416                if seen.insert(*to) {
417                    parent.insert(
418                        *to,
419                        (
420                            node,
421                            PathStep::Call {
422                                site: *site,
423                                agent: agent.clone(),
424                                handler: handler.clone(),
425                            },
426                        ),
427                    );
428                    queue.push_back(*to);
429                }
430            }
431        }
432        None
433    }
434
435    /// Simple paths from `from` to a use of `capability`, shortest first, at
436    /// most `limit`. A breadth-first walk that never revisits a node on its own
437    /// path (so a call cycle terminates) and never enters a node that cannot
438    /// reach a use (so an unused or sparse entry costs O(nodes + calls)). A
439    /// total-work budget bounds dense graphs, where simple paths are factorial.
440    fn walk(&self, from: usize, capability: &str, limit: usize) -> Vec<CapabilityPath> {
441        let reach = self.reaches(capability);
442        let mut out = Vec::new();
443        if !reach[from] {
444            return out;
445        }
446        let mut budget = WALK_BUDGET;
447        // (node, steps so far, nodes on the path)
448        let mut queue: VecDeque<(usize, Vec<PathStep>, Vec<usize>)> = VecDeque::new();
449        queue.push_back((from, Vec::new(), vec![from]));
450        while let Some((node, steps, on_path)) = queue.pop_front() {
451            if budget == 0 {
452                break;
453            }
454            budget -= 1;
455            let n = &self.nodes[node];
456            for u in n.uses.iter().filter(|u| u.capability == capability) {
457                let mut s = steps.clone();
458                s.push(PathStep::Use {
459                    site: u.site,
460                    source: u.source.clone(),
461                });
462                out.push(CapabilityPath { steps: s });
463                if out.len() >= limit {
464                    return out;
465                }
466            }
467            for (site, to, agent, handler) in &n.calls {
468                if on_path.contains(to) || !reach[*to] {
469                    continue;
470                }
471                let mut s = steps.clone();
472                s.push(PathStep::Call {
473                    site: *site,
474                    agent: agent.clone(),
475                    handler: handler.clone(),
476                });
477                let mut p = on_path.clone();
478                p.push(*to);
479                queue.push_back((*to, s, p));
480            }
481        }
482        out
483    }
484}