Skip to main content

bynk_check/
architecture_facts.rs

1//! #3583: the project-wide facts behind `bynk/architectureModel`'s `events`
2//! and `uses` sections — who emits and who subscribes to each event, which
3//! capabilities each handler requires through `given`, and which suites
4//! `stub` a capability.
5//!
6//! Until this module, event subscriptions were computed only to be validated
7//! ([`crate::project_model::phase_event_subscriptions`]) and a handler's
8//! resolved `given` was read only for the sequence diagram. A client could
9//! approximate either by text search, which breaks on aliases and `consumes`
10//! qualification. These facts are resolved the way the checker resolves them:
11//!
12//! - an event's *owner* is the context whose `event` table declares it, found
13//!   locally first and then through the consuming context's `consumes`, as
14//!   [`crate::symbols::discover_event_subscribers`] does;
15//! - an *emitter* is a call the checker resolved to `Events.emit` (its own
16//!   [`crate::checker::Callee`], not the receiver's spelling), with the event
17//!   type the checker recorded on the call's `Callee` (its type argument, written or inferred);
18//! - a handler's `given` set is read after [`crate::project_model::normalize_service_defaults`],
19//!   so a service's `default_given` is already part of each handler that
20//!   declares none of its own; a use is marked `inherited` when its span lies
21//!   outside the handler (it is written on the service header);
22//! - a capability reference resolves to its providing unit through the unit's
23//!   `consumes` aliases and flattened selections, as
24//!   [`crate::project_model::handler_cross_caps`] does.
25//!
26//! Spans are bare byte offsets against the project-relative `file` they are
27//! paired with. Nothing here carries source text.
28
29use std::collections::{BTreeMap, HashMap};
30use std::path::PathBuf;
31
32use bynk_project::{ParsedFile, UnitKind};
33use bynk_syntax::ast::{
34    CapRef, CommonsItem, Handler, HandlerKind, ServiceDecl, ServiceProtocol, SourceUnit, TypeRef,
35    expr_children, statement_exprs,
36};
37use bynk_syntax::span::Span;
38
39use crate::project_model::{UnitCallees, is_events_emit, resolve_consume_prefix};
40use crate::symbols::UnitTable;
41
42/// A project-relative file and a span within it.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct FactSite {
45    pub file: PathBuf,
46    pub span: Span,
47}
48
49/// What declares the member that emits, subscribes or uses.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
51pub enum MemberKind {
52    Service,
53    Agent,
54    /// A `provides Cap = Name { op … }` operation body (it can emit, and
55    /// carries its provider's `given`).
56    Provider,
57}
58
59/// One handler (or provider operation) of one unit.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct MemberFact {
62    /// The declaring unit's qualified name.
63    pub unit: String,
64    pub kind: MemberKind,
65    /// The service, agent or provider name (`provider_name` for a provider).
66    pub container: String,
67    /// The handler's request descriptor (`call`, `call addItem`,
68    /// `http GET /x`, `event`, …), or a provider operation's name.
69    pub handler: String,
70    /// The handler's own span.
71    pub site: FactSite,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct EmitterFact {
76    pub member: MemberFact,
77    /// The `Events.emit[E](…)` call.
78    pub site: FactSite,
79}
80
81/// How a subscription selects what it is delivered.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum DeliveryKind {
84    /// `from Events(E)`: every emission.
85    All,
86    /// `from Events(E { f: v, .. })`: emissions whose payload matches.
87    Pattern,
88    /// `from Events(E) via schema(N)`: emissions of that schema version.
89    Schema,
90    /// Both a payload pattern and a `via schema(…)` clause.
91    PatternSchema,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct SubscriberFact {
96    /// The subscribing service's `on event` handler.
97    pub member: MemberFact,
98    pub delivery: DeliveryKind,
99    /// The `from Events(…)` header.
100    pub site: FactSite,
101}
102
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct EventFact {
105    /// The context that declares the event.
106    pub owner: String,
107    pub name: String,
108    /// The `event` declaration.
109    pub site: FactSite,
110    pub emitters: Vec<EmitterFact>,
111    pub subscribers: Vec<SubscriberFact>,
112}
113
114/// One capability a handler requires through `given`.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct UseFact {
117    /// The capability's simple name.
118    pub capability: String,
119    /// The unit that declares it: this unit, a consumed one, or `bynk`.
120    pub provider_unit: Option<String>,
121    /// Written on the service header (`default_given`), not on the handler.
122    /// Always `false` for a provider operation, whose `given` is its provider's.
123    pub inherited: bool,
124    /// The `given` entry.
125    pub site: FactSite,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct HandlerUsesFact {
130    pub member: MemberFact,
131    pub uses: Vec<UseFact>,
132    /// Model-diagrams slice 5: the services and agents the handler calls, as
133    /// the checker resolved them. One entry per target, at its first call.
134    pub calls: Vec<CallFact>,
135}
136
137/// What a handler calls (model-diagrams slice 5).
138#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
139pub enum CallTarget {
140    /// A consumed context's service (`B.service(…)`, `Alias.service(…)`).
141    Service { unit: String, service: String },
142    /// One of this unit's own agents, and the handler dispatched to.
143    Agent { agent: String, handler: String },
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct CallFact {
148    pub target: CallTarget,
149    /// The first call to `target` in the handler.
150    pub site: FactSite,
151}
152
153/// A `stub` of one capability in one suite (suite-level or in a case).
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct StubFact {
156    /// The unit the suite tests.
157    pub target: String,
158    pub capability: String,
159    /// The `stub` clause.
160    pub site: FactSite,
161}
162
163/// Everything `bynk/architectureModel` needs beyond a unit's own declarations.
164#[derive(Debug, Clone, Default, PartialEq, Eq)]
165pub struct ArchitectureFacts {
166    pub events: Vec<EventFact>,
167    pub uses: Vec<HandlerUsesFact>,
168    pub stubs: Vec<StubFact>,
169}
170
171/// The per-unit resolution tables the facts read.
172pub struct FactInputs<'a> {
173    pub parsed: &'a [ParsedFile],
174    pub groups: &'a BTreeMap<String, Vec<usize>>,
175    pub test_groups: &'a BTreeMap<String, Vec<usize>>,
176    pub kinds: &'a BTreeMap<String, UnitKind>,
177    pub unit_tables: &'a HashMap<String, UnitTable>,
178    pub unit_consumes: &'a HashMap<String, Vec<String>>,
179    pub unit_consumes_aliases: &'a HashMap<String, HashMap<String, String>>,
180    pub unit_flattened: &'a HashMap<String, HashMap<String, String>>,
181    pub callees: &'a UnitCallees,
182}
183
184/// Compute the facts. Deterministic: units, events, members and uses are
185/// sorted, so the wire form does not churn between rounds.
186pub fn architecture_facts(inp: &FactInputs<'_>) -> ArchitectureFacts {
187    let mut events: BTreeMap<(String, String), EventFact> = BTreeMap::new();
188    let mut uses = Vec::new();
189
190    // Declared events first: an emitter or subscriber in one unit attaches to
191    // an event another unit declares, whichever is visited first.
192    for (unit, indices) in inp.groups {
193        if !matches!(
194            inp.kinds.get(unit),
195            Some(UnitKind::Context | UnitKind::Adapter)
196        ) {
197            continue;
198        }
199        for &i in indices {
200            let pf = &inp.parsed[i];
201            for item in pf.items() {
202                if let CommonsItem::Event(e) = item {
203                    events.insert(
204                        (unit.clone(), e.name.name.clone()),
205                        EventFact {
206                            owner: unit.clone(),
207                            name: e.name.name.clone(),
208                            site: FactSite {
209                                file: pf.identity_path(),
210                                span: e.name.span,
211                            },
212                            emitters: Vec::new(),
213                            subscribers: Vec::new(),
214                        },
215                    );
216                }
217            }
218        }
219    }
220
221    for (unit, indices) in inp.groups {
222        if !matches!(
223            inp.kinds.get(unit),
224            Some(UnitKind::Context | UnitKind::Adapter)
225        ) {
226            continue;
227        }
228        let mut cx = UnitCx::new(inp, unit);
229        for &i in indices {
230            cx.walk_file(&inp.parsed[i], &mut events, &mut uses);
231        }
232    }
233
234    let mut events: Vec<EventFact> = events.into_values().collect();
235    for e in &mut events {
236        let key = |m: &MemberFact| (m.unit.clone(), m.container.clone(), m.handler.clone());
237        e.emitters.sort_by(|a, b| {
238            (key(&a.member), &a.site.file, a.site.span.start).cmp(&(
239                key(&b.member),
240                &b.site.file,
241                b.site.span.start,
242            ))
243        });
244        e.subscribers.sort_by_key(|a| key(&a.member));
245    }
246    uses.sort_by_key(|a: &HandlerUsesFact| {
247        (
248            a.member.unit.clone(),
249            a.member.container.clone(),
250            a.member.handler.clone(),
251        )
252    });
253    ArchitectureFacts {
254        events,
255        uses,
256        stubs: stub_facts(inp),
257    }
258}
259
260struct UnitCx<'a> {
261    inp: &'a FactInputs<'a>,
262    unit: &'a str,
263    consumed: &'a [String],
264    aliases: Option<&'a HashMap<String, String>>,
265    flattened: Option<&'a HashMap<String, String>>,
266    callees: Option<&'a HashMap<bynk_syntax::ast::ExprId, crate::checker::Callee>>,
267}
268
269impl<'a> UnitCx<'a> {
270    fn new(inp: &'a FactInputs<'a>, unit: &'a str) -> Self {
271        UnitCx {
272            inp,
273            unit,
274            consumed: inp.unit_consumes.get(unit).map_or(&[], Vec::as_slice),
275            aliases: inp.unit_consumes_aliases.get(unit),
276            flattened: inp.unit_flattened.get(unit),
277            callees: inp.callees.get(unit),
278        }
279    }
280
281    /// The context that declares event `name`, as seen from this unit.
282    fn event_owner(&self, name: &str) -> Option<String> {
283        let declares = |u: &str| {
284            self.inp
285                .unit_tables
286                .get(u)
287                .is_some_and(|t| t.events.contains_key(name))
288        };
289        if declares(self.unit) {
290            return Some(self.unit.to_string());
291        }
292        self.consumed.iter().find(|c| declares(c)).cloned()
293    }
294
295    fn resolve_cap(&self, cap: &CapRef) -> Option<String> {
296        match cap.prefix() {
297            Some(p) => {
298                resolve_consume_prefix(&p, self.consumed, self.aliases.unwrap_or(&HashMap::new()))
299            }
300            None => match self.flattened.and_then(|f| f.get(cap.key())) {
301                Some(u) => Some(u.clone()),
302                None => Some(self.unit.to_string()),
303            },
304        }
305    }
306
307    fn walk_file(
308        &mut self,
309        pf: &ParsedFile,
310        events: &mut BTreeMap<(String, String), EventFact>,
311        uses: &mut Vec<HandlerUsesFact>,
312    ) {
313        let file = pf.identity_path();
314        let site = |span: Span| FactSite {
315            file: file.clone(),
316            span,
317        };
318        for item in pf.items() {
319            match item {
320                CommonsItem::Service(s) => {
321                    for h in &s.handlers {
322                        let member = self.member(MemberKind::Service, &s.name.name, h, &site);
323                        self.handler(member, h, Some(s), &site, events, uses);
324                    }
325                }
326                CommonsItem::Agent(a) => {
327                    for h in &a.handlers {
328                        let member = self.member(MemberKind::Agent, &a.name.name, h, &site);
329                        self.handler(member, h, None, &site, events, uses);
330                    }
331                }
332                CommonsItem::Provider(p) => {
333                    for op in &p.ops {
334                        let member = MemberFact {
335                            unit: self.unit.to_string(),
336                            kind: MemberKind::Provider,
337                            container: p.provider_name.name.clone(),
338                            handler: op.name.name.clone(),
339                            site: site(op.span),
340                        };
341                        self.emits(&member, &op.body, &site, events);
342                        uses.push(HandlerUsesFact {
343                            uses: self.use_facts(&p.given, None, &site),
344                            calls: self.calls(&op.body, &site),
345                            member,
346                        });
347                    }
348                }
349                _ => {}
350            }
351        }
352    }
353
354    fn member(
355        &self,
356        kind: MemberKind,
357        container: &str,
358        h: &Handler,
359        site: &dyn Fn(Span) -> FactSite,
360    ) -> MemberFact {
361        MemberFact {
362            unit: self.unit.to_string(),
363            kind,
364            container: container.to_string(),
365            handler: handler_label(h),
366            site: site(h.span),
367        }
368    }
369
370    fn handler(
371        &self,
372        member: MemberFact,
373        h: &Handler,
374        service: Option<&ServiceDecl>,
375        site: &dyn Fn(Span) -> FactSite,
376        events: &mut BTreeMap<(String, String), EventFact>,
377        uses: &mut Vec<HandlerUsesFact>,
378    ) {
379        if let Some(ServiceProtocol::Events {
380            event_type: TypeRef::Named(id),
381            pattern,
382            schema_dispatch,
383        }) = service.map(|s| &s.protocol)
384            && h.kind == HandlerKind::Event
385            && let Some(owner) = self.event_owner(&id.name)
386            && let Some(fact) = events.get_mut(&(owner, id.name.clone()))
387        {
388            let delivery = match (pattern.is_some(), schema_dispatch.is_some()) {
389                (false, false) => DeliveryKind::All,
390                (true, false) => DeliveryKind::Pattern,
391                (false, true) => DeliveryKind::Schema,
392                (true, true) => DeliveryKind::PatternSchema,
393            };
394            fact.subscribers.push(SubscriberFact {
395                member: member.clone(),
396                delivery,
397                site: site(id.span),
398            });
399        }
400        self.emits(&member, &h.body, site, events);
401        uses.push(HandlerUsesFact {
402            uses: self.use_facts(&h.given, Some(h.span), site),
403            calls: self.calls(&h.body, site),
404            member,
405        });
406    }
407
408    fn use_facts(
409        &self,
410        given: &[CapRef],
411        handler_span: Option<Span>,
412        site: &dyn Fn(Span) -> FactSite,
413    ) -> Vec<UseFact> {
414        given
415            .iter()
416            .map(|c| UseFact {
417                capability: c.key().to_string(),
418                provider_unit: self.resolve_cap(c),
419                inherited: handler_span
420                    .is_some_and(|h| c.span.start < h.start || c.span.end > h.end),
421                site: site(c.span),
422            })
423            .collect()
424    }
425
426    /// The services and agents a body calls, in source order, one entry per
427    /// target (its first call).
428    fn calls(
429        &self,
430        body: &bynk_syntax::ast::Block,
431        site: &dyn Fn(Span) -> FactSite,
432    ) -> Vec<CallFact> {
433        let Some(callees) = self.callees else {
434            return Vec::new();
435        };
436        let mut found: Vec<(CallTarget, Span)> = Vec::new();
437        let mut stack = Vec::new();
438        for s in &body.statements {
439            statement_exprs(s, &mut stack);
440        }
441        stack.push(&body.tail);
442        while let Some(e) = stack.pop() {
443            let target = match callees.get(&e.id) {
444                Some(crate::checker::Callee::Cross { unit, service }) => {
445                    Some(CallTarget::Service {
446                        unit: unit.clone(),
447                        service: service.clone(),
448                    })
449                }
450                Some(crate::checker::Callee::Agent { agent, handler }) => Some(CallTarget::Agent {
451                    agent: agent.clone(),
452                    handler: handler.clone(),
453                }),
454                _ => None,
455            };
456            if let Some(target) = target {
457                match found.iter_mut().find(|(t, _)| *t == target) {
458                    Some((_, at)) if e.span.start < at.start => *at = e.span,
459                    Some(_) => {}
460                    None => found.push((target, e.span)),
461                }
462            }
463            stack.extend(expr_children(e));
464        }
465        found.sort_by_key(|(_, span)| span.start);
466        found
467            .into_iter()
468            .map(|(target, span)| CallFact {
469                target,
470                site: site(span),
471            })
472            .collect()
473    }
474
475    fn emits(
476        &self,
477        member: &MemberFact,
478        body: &bynk_syntax::ast::Block,
479        site: &dyn Fn(Span) -> FactSite,
480        events: &mut BTreeMap<(String, String), EventFact>,
481    ) {
482        let Some(callees) = self.callees else { return };
483        let mut stack = Vec::new();
484        for s in &body.statements {
485            statement_exprs(s, &mut stack);
486        }
487        stack.push(&body.tail);
488        while let Some(e) = stack.pop() {
489            if let Some(crate::checker::Callee::Capability {
490                event: Some(name), ..
491            }) = callees.get(&e.id)
492                && callees.get(&e.id).is_some_and(is_events_emit)
493                && let Some(owner) = self.event_owner(name)
494                && let Some(fact) = events.get_mut(&(owner, name.clone()))
495            {
496                fact.emitters.push(EmitterFact {
497                    member: member.clone(),
498                    site: site(e.span),
499                });
500            }
501            stack.extend(expr_children(e));
502        }
503    }
504}
505
506/// The request descriptor of a handler, as the sequence diagram labels it.
507fn handler_label(h: &Handler) -> String {
508    match &h.kind {
509        HandlerKind::Call => h
510            .method_name
511            .as_ref()
512            .map_or_else(|| "call".to_string(), |m| m.name.clone()),
513        HandlerKind::Http { method, path } => format!("{} {}", method.as_str(), path),
514        HandlerKind::Cron { expr } => format!("cron \"{expr}\""),
515        HandlerKind::Message => "message".to_string(),
516        HandlerKind::Open => "open".to_string(),
517        HandlerKind::Close => "close".to_string(),
518        HandlerKind::Event => "event".to_string(),
519        HandlerKind::Rejected => "rejected".to_string(),
520    }
521}
522
523fn stub_facts(inp: &FactInputs<'_>) -> Vec<StubFact> {
524    let mut out = Vec::new();
525    for (target, indices) in inp.test_groups {
526        for &i in indices {
527            let pf = &inp.parsed[i];
528            let SourceUnit::Suite(suite) = pf.unit() else {
529                continue;
530            };
531            let file = pf.identity_path();
532            let stubs = suite
533                .stubs
534                .iter()
535                .chain(suite.cases.iter().flat_map(|c| c.stubs.iter()));
536            for s in stubs {
537                out.push(StubFact {
538                    target: target.clone(),
539                    capability: s.capability.name.clone(),
540                    site: FactSite {
541                        file: file.clone(),
542                        span: s.span,
543                    },
544                });
545            }
546        }
547    }
548    out.sort_by(|a, b| {
549        (&a.target, &a.capability, &a.site.file, a.site.span.start).cmp(&(
550            &b.target,
551            &b.capability,
552            &b.site.file,
553            b.site.span.start,
554        ))
555    });
556    out
557}