1use 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
32pub const MAX_PATHS: usize = 64;
36
37const WALK_BUDGET: usize = 20_000;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum PathStep {
44 Call {
47 site: Span,
48 agent: String,
49 handler: String,
50 },
51 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#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct CapabilityPath {
71 pub steps: Vec<PathStep>,
72}
73
74impl CapabilityPath {
75 pub fn is_direct(&self) -> bool {
77 self.steps.len() == 1
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct CapabilityWitness {
84 pub given_entry: Span,
86 pub capability: String,
87 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 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
116pub struct CapabilityGraph {
117 pub file: FileId,
121 nodes: Vec<Node>,
122 entries: Vec<Entry>,
123 witnesses: Vec<CapabilityWitness>,
124}
125
126pub type FileCapabilityPaths = HashMap<PathBuf, CapabilityGraph>;
128
129struct 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
151fn 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 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 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 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 if cap.span.file != own && cap.span.file != FileId::UNKNOWN {
307 continue;
308 }
309 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 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 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 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 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 fn shortest(&self, from: usize, capability: &str) -> Option<CapabilityPath> {
396 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 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 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}