Skip to main content

bynk_lsp/
sequence_request.rs

1//! #846: `bynk/sequenceModel` — the sequence-diagram custom LSP request.
2//!
3//! The first custom (non-standard) request in this server: no `workspace/*/
4//! refresh` nudge exists for it (there is no generic "refresh a custom
5//! method" in the LSP spec or in `tower_lsp::Client`), and none is needed —
6//! Tier 1 is on-demand: the client re-issues the request each time the
7//! command/lens fires, rather than the server pushing updates.
8//!
9//! Two responsibilities live here, out of `lib.rs`: locating the `Handler`
10//! AST node enclosing a cursor position (by re-parsing the committed
11//! snapshot, the same convention `identifier_at` uses in `lib.rs`), and the
12//! wire shape sent to the client (a plain serde mirror of
13//! [`bynk_ide::sequence::SequenceModel`], `Span` lowered to LSP `Range` —
14//! same convention as `SerKey` in `lib.rs`).
15
16use bynk_ide::sequence::{
17    self, AltKind, Callee, HandlerOwner, MessageKind, ParticipantKind, SequenceModel, TriggerKind,
18};
19use bynk_syntax::ast::{CommonsItem, Handler, SourceUnit};
20use tower_lsp::lsp_types::{Location, Url};
21
22/// Locate the `Handler` enclosing `offset` in `text` and build its sequence
23/// model. `info` is the owning unit's cross-context/agent table — `None`
24/// degrades classification to capabilities only (still correct; just unable
25/// to recognise agent/cross-context lifelines), which happens for a unit
26/// `sequence_info` has no entry for (a commons file, or one this round never
27/// reached because the pipeline bailed before it).
28pub fn sequence_model_at(
29    text: &str,
30    offset: usize,
31    info: Option<&bynk_ide::ContextSequenceInfo>,
32) -> Option<SequenceModel> {
33    let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
34    let (unit, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
35    let items: &[CommonsItem] = match unit.as_ref()? {
36        SourceUnit::Context(c) => &c.items,
37        SourceUnit::Adapter(a) => &a.items,
38        SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
39    };
40    for item in items {
41        match item {
42            CommonsItem::Service(s) => {
43                if let Some(h) = handler_at(&s.handlers, offset) {
44                    return Some(sequence::sequence_model(
45                        h,
46                        HandlerOwner::Service(&s.name.name),
47                        // v0.155: a handler with no `given`/`by` of its own
48                        // inherits the service-level default. See `sequence_model`.
49                        &s.default_given,
50                        s.default_by.as_ref(),
51                        info,
52                    ));
53                }
54            }
55            CommonsItem::Agent(a) => {
56                if let Some(h) = handler_at(&a.handlers, offset) {
57                    return Some(sequence::sequence_model(
58                        h,
59                        HandlerOwner::Agent(&a.name.name),
60                        // Agents have no service-level `given` default and no
61                        // principal (`by`).
62                        &[],
63                        None,
64                        info,
65                    ));
66                }
67            }
68            _ => {}
69        }
70    }
71    None
72}
73
74fn handler_at(handlers: &[Handler], offset: usize) -> Option<&Handler> {
75    handlers
76        .iter()
77        .find(|h| h.span.start <= offset && offset < h.span.end)
78}
79
80/// Every `on <kind>` handler declaration in `text`, for the per-handler
81/// "Show Sequence" CodeLens. **Not** `index_queries::code_lenses` — that
82/// walks `SymbolKind::Handler` sites, which only agent handlers get
83/// (`bynk-check/src/index.rs`: "Service handlers have no per-handler name...
84/// so only agent dispatch is covered"); reusing it as-is would silently drop
85/// the lens for every service (non-agent) handler, which is most of them.
86/// A direct AST walk covers both uniformly.
87pub fn handler_lens_sites(text: &str) -> Vec<bynk_syntax::span::Span> {
88    let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
89        return Vec::new();
90    };
91    let (unit, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
92    let Some(unit) = unit else {
93        return Vec::new();
94    };
95    let items: &[CommonsItem] = match &unit {
96        SourceUnit::Context(c) => &c.items,
97        SourceUnit::Adapter(a) => &a.items,
98        SourceUnit::Commons(_) | SourceUnit::Suite(_) => return Vec::new(),
99    };
100    let mut sites = Vec::new();
101    for item in items {
102        match item {
103            CommonsItem::Service(s) => sites.extend(s.handlers.iter().map(|h| h.span)),
104            CommonsItem::Agent(a) => sites.extend(a.handlers.iter().map(|h| h.span)),
105            _ => {}
106        }
107    }
108    sites
109}
110
111/// The `bynk/sequenceModel` request payload — the same two-field
112/// text-document + cursor-position shape every other cursor-anchored request
113/// in this server uses (`HoverParams`, `SignatureHelpParams`, …).
114///
115/// #847: `rename_all = "camelCase"` added — the client sends the LSP wire names
116/// `textDocument`/`position`, so the params must deserialize from camelCase.
117/// Without it the request failed with a missing-field error the moment a real
118/// client called it (the #846 in-crate tests drive `sequence_model_at` directly
119/// and never deserialize these params, and the live VS Code path was not run —
120/// so the mismatch shipped latent).
121#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub struct SequenceModelParams {
124    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
125    pub position: tower_lsp::lsp_types::Position,
126}
127
128// -- Wire shape: a plain serde mirror of `bynk_ide::sequence::SequenceModel`,
129// -- `Span` lowered to `Range` (converted against the committed snapshot text
130// -- the caller already has — this module stays position-map-agnostic).
131
132// Model-diagrams slice 3 adds `trigger`, `WireParticipant::key`,
133// `WireMessage::callee` and `WireAltBlock::depth`, and the `"Break"` block
134// kind. All additive: an older client ignores the fields, and draws a `Break`
135// as it draws any block it does not know.
136
137#[derive(Debug, Clone, serde::Serialize)]
138pub struct WireSequenceModel {
139    pub participants: Vec<WireParticipant>,
140    pub messages: Vec<WireMessage>,
141    pub blocks: Vec<WireAltBlock>,
142    /// What starts the handler — see [`bynk_ide::sequence::Trigger`].
143    pub trigger: WireTrigger,
144}
145
146#[derive(Debug, Clone, serde::Serialize)]
147pub struct WireTrigger {
148    /// `Request`, `Call`, `Schedule`, `Event`, `Message`, `Connection` or
149    /// `Rejected`.
150    pub kind: &'static str,
151    pub label: String,
152}
153
154#[derive(Debug, Clone, serde::Serialize)]
155pub struct WireParticipant {
156    pub id: u32,
157    pub kind: &'static str,
158    pub name: String,
159    pub range: Option<tower_lsp::lsp_types::Range>,
160    /// An agent's key expression as called (`client`), or `…` when calls
161    /// disagree; `null` otherwise. See [`bynk_ide::sequence::Participant::key`].
162    pub key: Option<String>,
163}
164
165#[derive(Debug, Clone, serde::Serialize)]
166pub struct WireMessage {
167    pub from: u32,
168    pub to: u32,
169    pub kind: &'static str,
170    pub label: String,
171    pub range: tower_lsp::lsp_types::Range,
172    pub block: Option<u32>,
173    /// The handler a boundary call reaches; `null` for every other message.
174    pub callee: Option<WireCallee>,
175}
176
177/// The handler a boundary call reaches: by name, and where it is when the
178/// server can find it in the committed round (a client opens the callee's own
179/// sequence diagram there).
180#[derive(Debug, Clone, serde::Serialize)]
181pub struct WireCallee {
182    /// The consumed context; `null` for an agent of the caller's own context.
183    pub unit: Option<String>,
184    pub owner: String,
185    /// The handler's method name; `null` for a service's unnamed `on call`.
186    pub method: Option<String>,
187    /// The handler's declaration; `null` when not found (a consumed context
188    /// from a package, say, whose source is not in this project).
189    pub location: Option<Location>,
190}
191
192#[derive(Debug, Clone, serde::Serialize)]
193pub struct WireAltBlock {
194    pub id: u32,
195    pub kind: &'static str,
196    pub branches: Vec<WireBranch>,
197    pub range: tower_lsp::lsp_types::Range,
198    pub parent: Option<u32>,
199    #[serde(rename = "parentBranch")]
200    pub parent_branch: Option<u32>,
201    /// The block's nesting depth, 0 at the top level (ADR 0858).
202    pub depth: u32,
203}
204
205#[derive(Debug, Clone, serde::Serialize)]
206pub struct WireBranch {
207    pub label: String,
208    #[serde(rename = "messageIds")]
209    pub message_ids: Vec<usize>,
210    /// The branch's rendered outcome (`Ok(view)`) — see
211    /// [`bynk_ide::sequence::Branch::reply`]. `null` on the wire when absent.
212    pub reply: Option<String>,
213    /// The source range of the branch's arm — see
214    /// [`bynk_ide::sequence::Branch::span`]. For the `else` of an `else if`,
215    /// the range starts at the inner `if` keyword and covers the rest of the
216    /// chain (#3599); the inner `if` is a nested block with its own ranges.
217    pub range: tower_lsp::lsp_types::Range,
218}
219
220fn participant_kind_str(k: ParticipantKind) -> &'static str {
221    match k {
222        ParticipantKind::Entry => "Entry",
223        ParticipantKind::Capability => "Capability",
224        ParticipantKind::Context => "Context",
225        ParticipantKind::Agent => "Agent",
226        ParticipantKind::Actor => "Actor",
227    }
228}
229
230fn message_kind_str(k: MessageKind) -> &'static str {
231    match k {
232        MessageKind::Call => "Call",
233        MessageKind::Return => "Return",
234        MessageKind::Send => "Send",
235        MessageKind::StateWrite => "StateWrite",
236    }
237}
238
239fn alt_kind_str(k: AltKind) -> &'static str {
240    match k {
241        AltKind::If => "If",
242        AltKind::Match => "Match",
243        AltKind::Collapsed => "Collapsed",
244        AltKind::Break => "Break",
245    }
246}
247
248fn trigger_kind_str(k: TriggerKind) -> &'static str {
249    match k {
250        TriggerKind::Request => "Request",
251        TriggerKind::Call => "Call",
252        TriggerKind::Schedule => "Schedule",
253        TriggerKind::Event => "Event",
254        TriggerKind::Message => "Message",
255        TriggerKind::Connection => "Connection",
256        TriggerKind::Rejected => "Rejected",
257    }
258}
259
260/// Find the handler `callee` names among `files` (the callee unit's files:
261/// URI and analysed text), and return its declaration. A service's handler is
262/// its `on call` (named `method`, or unnamed when `method` is `None`); an
263/// agent's is its `on call method`.
264pub fn locate_callee<'a>(
265    callee: &Callee,
266    files: impl IntoIterator<Item = (Url, &'a str)>,
267) -> Option<Location> {
268    for (uri, text) in files {
269        let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
270            continue;
271        };
272        let (unit, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
273        let items: &[CommonsItem] = match unit.as_ref() {
274            Some(SourceUnit::Context(c)) => &c.items,
275            Some(SourceUnit::Adapter(a)) => &a.items,
276            _ => continue,
277        };
278        for item in items {
279            let (name, handlers) = match item {
280                CommonsItem::Service(s) => (&s.name.name, &s.handlers),
281                CommonsItem::Agent(a) => (&a.name.name, &a.handlers),
282                _ => continue,
283            };
284            if *name != callee.owner {
285                continue;
286            }
287            let found = handlers.iter().find(|h| {
288                matches!(h.kind, bynk_syntax::ast::HandlerKind::Call)
289                    && h.method_name.as_ref().map(|m| m.name.as_str()) == callee.method.as_deref()
290            });
291            if let Some(h) = found {
292                return Some(Location {
293                    uri,
294                    range: crate::position::span_to_range(text, h.span),
295                });
296            }
297        }
298    }
299    None
300}
301
302/// The wire shape of `model`, with each callee located by `locate` (the
303/// server passes a lookup over the committed round's files).
304pub fn to_wire(
305    model: &SequenceModel,
306    text: &str,
307    locate: impl Fn(&Callee) -> Option<Location>,
308) -> WireSequenceModel {
309    WireSequenceModel {
310        trigger: WireTrigger {
311            kind: trigger_kind_str(model.trigger.kind),
312            label: model.trigger.label.clone(),
313        },
314        participants: model
315            .participants
316            .iter()
317            .map(|p| WireParticipant {
318                id: p.id,
319                kind: participant_kind_str(p.kind),
320                name: p.name.clone(),
321                range: p.span.map(|s| crate::position::span_to_range(text, s)),
322                key: p.key.clone(),
323            })
324            .collect(),
325        messages: model
326            .messages
327            .iter()
328            .map(|m| WireMessage {
329                from: m.from,
330                to: m.to,
331                kind: message_kind_str(m.kind),
332                label: m.label.clone(),
333                range: crate::position::span_to_range(text, m.span),
334                block: m.block,
335                callee: m.callee.as_ref().map(|c| WireCallee {
336                    unit: c.unit.clone(),
337                    owner: c.owner.clone(),
338                    method: c.method.clone(),
339                    location: locate(c),
340                }),
341            })
342            .collect(),
343        blocks: model
344            .blocks
345            .iter()
346            .map(|b| WireAltBlock {
347                id: b.id,
348                kind: alt_kind_str(b.kind),
349                branches: b
350                    .branches
351                    .iter()
352                    .map(|br| WireBranch {
353                        label: br.label.clone(),
354                        message_ids: br.message_ids.clone(),
355                        reply: br.reply.clone(),
356                        range: crate::position::span_to_range(text, br.span),
357                    })
358                    .collect(),
359                range: crate::position::span_to_range(text, b.span),
360                parent: b.parent,
361                parent_branch: b.parent_branch,
362                depth: b.depth,
363            })
364            .collect(),
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use bynk_ide::sequence::{AltBlock, Branch};
372    use bynk_syntax::span::Span;
373
374    /// #3584: a branch's span is lowered to a `range` on the wire.
375    #[test]
376    fn wire_branch_carries_a_range() {
377        let text = "ab\ncd\n";
378        let model = SequenceModel {
379            blocks: vec![AltBlock {
380                id: 0,
381                kind: AltKind::If,
382                branches: vec![Branch {
383                    label: "x".into(),
384                    message_ids: vec![],
385                    reply: None,
386                    span: Span::from(3..5),
387                }],
388                span: Span::from(0..5),
389                parent: None,
390                parent_branch: None,
391                depth: 0,
392            }],
393            ..SequenceModel::default()
394        };
395        let json = serde_json::to_value(to_wire(&model, text, |_| None)).unwrap();
396        let range = &json["blocks"][0]["branches"][0]["range"];
397        assert_eq!(range["start"]["line"], 1);
398        assert_eq!(range["start"]["character"], 0);
399        assert_eq!(range["end"]["character"], 2);
400    }
401
402    const PLATFORM: &str = "context platform\n\nservice Pinger {\n  on call(n: Int) -> Effect[Int] by Caller {\n    n\n  }\n}\n";
403    const LIMITS: &str = "context ratelimit\n\nagent Limiter {\n  key client: String\n\n  store count: Cell[Int]\n\n  on call reset() -> Effect[()] {\n    count := 0\n  }\n\n  on call hit(now: Int) -> Effect[Int] {\n    now\n  }\n}\n";
404
405    fn uri(name: &str) -> Url {
406        Url::parse(&format!("file:///p/{name}")).unwrap()
407    }
408
409    /// Model-diagrams slice 3: a callee is found by owner and method among
410    /// its unit's files.
411    #[test]
412    fn locates_a_service_call_and_a_named_agent_handler() {
413        let pinger = Callee {
414            unit: Some("platform".into()),
415            owner: "Pinger".into(),
416            method: None,
417        };
418        let found = locate_callee(
419            &pinger,
420            [
421                (uri("other.bynk"), LIMITS),
422                (uri("platform.bynk"), PLATFORM),
423            ],
424        )
425        .expect("the service's on call");
426        assert_eq!(found.uri, uri("platform.bynk"));
427        assert_eq!(found.range.start.line, 3, "the `on call` line");
428
429        let hit = Callee {
430            unit: None,
431            owner: "Limiter".into(),
432            method: Some("hit".into()),
433        };
434        let found = locate_callee(&hit, [(uri("limits.bynk"), LIMITS)]).expect("on call hit");
435        assert_eq!(found.range.start.line, 11, "not `reset`, the first handler");
436    }
437
438    #[test]
439    fn a_callee_that_is_not_there_has_no_location() {
440        let missing = Callee {
441            unit: None,
442            owner: "Limiter".into(),
443            method: Some("nope".into()),
444        };
445        assert_eq!(
446            locate_callee(&missing, [(uri("limits.bynk"), LIMITS)]),
447            None
448        );
449        let other = Callee {
450            unit: None,
451            owner: "Nobody".into(),
452            method: None,
453        };
454        assert_eq!(
455            locate_callee(
456                &other,
457                [
458                    (uri("limits.bynk"), LIMITS),
459                    (uri("bad.bynk"), "context {{{")
460                ]
461            ),
462            None
463        );
464    }
465
466    /// Model-diagrams slice 3: the additive wire fields.
467    #[test]
468    fn wire_carries_trigger_depth_key_and_located_callee() {
469        let text = "x\n";
470        let callee = Callee {
471            unit: None,
472            owner: "Limiter".into(),
473            method: Some("hit".into()),
474        };
475        let model = SequenceModel {
476            participants: vec![bynk_ide::sequence::Participant {
477                id: 1,
478                kind: ParticipantKind::Agent,
479                name: "Limiter".into(),
480                span: None,
481                key: Some("client".into()),
482            }],
483            messages: vec![bynk_ide::sequence::Message {
484                from: 0,
485                to: 1,
486                kind: MessageKind::Call,
487                label: "hit(now)".into(),
488                span: Span::from(0..1),
489                block: Some(0),
490                callee: Some(callee),
491            }],
492            blocks: vec![AltBlock {
493                id: 0,
494                kind: AltKind::Break,
495                branches: vec![],
496                span: Span::from(0..1),
497                parent: None,
498                parent_branch: None,
499                depth: 3,
500            }],
501            trigger: bynk_ide::sequence::Trigger {
502                kind: TriggerKind::Schedule,
503                label: "cron \"0 * * * *\"".into(),
504            },
505        };
506        let located = |_: &Callee| {
507            Some(Location {
508                uri: uri("limits.bynk"),
509                range: Default::default(),
510            })
511        };
512        let json = serde_json::to_value(to_wire(&model, text, located)).unwrap();
513        assert_eq!(json["trigger"]["kind"], "Schedule");
514        assert_eq!(json["trigger"]["label"], "cron \"0 * * * *\"");
515        assert_eq!(json["participants"][0]["key"], "client");
516        assert_eq!(json["blocks"][0]["kind"], "Break");
517        assert_eq!(json["blocks"][0]["depth"], 3);
518        let c = &json["messages"][0]["callee"];
519        assert_eq!(c["owner"], "Limiter");
520        assert_eq!(c["method"], "hit");
521        assert!(c["unit"].is_null());
522        assert_eq!(c["location"]["uri"], "file:///p/limits.bynk");
523    }
524}