Skip to main content

bynk_lsp/
agent_state_request.rs

1//! #2196: `bynk/agentStateModel` — the agent state view's custom LSP request
2//! (agent-state-views track, slice 2).
3//!
4//! Agent-scoped, not handler-scoped: the cursor anywhere inside an `agent`
5//! declaration (its header, a `store` field, a handler body) selects that
6//! agent, and the response is the whole agent's state model
7//! ([`bynk_ide::agent_state`]). Served from the committed round by
8//! re-parsing the snapshot, like `bynk/sequenceModel` (ADR 0301's posture); no
9//! refresh nudge, since the client re-pulls (ADR 0504).
10//!
11//! Also here: the sites of the per-agent `Show State` lens, and the wire
12//! shape — a serde mirror of the model with `Span`s lowered to LSP `Range`s,
13//! plus each handler's name and range (the table's rows, and what the client
14//! highlights for the handler under the cursor).
15
16use std::collections::{HashMap, HashSet};
17use std::sync::Arc;
18
19use bynk_ide::agent_effects::{self, HandlerEffects};
20use bynk_ide::agent_state::{
21    self, AgentInvariant, AgentStateModel, Certainty, InvariantKind, Target,
22};
23use bynk_syntax::ast::{AgentDecl, CommonsItem, SourceUnit, TypeDecl};
24use bynk_syntax::span::Span;
25use tower_lsp::lsp_types::Range;
26
27/// The `bynk/agentStateModel` request payload. `rename_all = "camelCase"` is
28/// load-bearing — the client sends `textDocument`/`position` (see
29/// `sequence_request::SequenceModelParams`).
30#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub struct AgentStateModelParams {
33    pub text_document: tower_lsp::lsp_types::TextDocumentIdentifier,
34    pub position: tower_lsp::lsp_types::Position,
35}
36
37/// The agents of `text`, re-parsed. Empty for a commons, a suite, or a file
38/// that doesn't tokenize.
39fn agents(text: &str) -> Vec<AgentDecl> {
40    let Ok(tokens) = bynk_syntax::lexer::tokenize(text) else {
41        return Vec::new();
42    };
43    let (unit, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
44    let items = match unit {
45        Some(SourceUnit::Context(c)) => c.items,
46        Some(SourceUnit::Adapter(a)) => a.items,
47        _ => return Vec::new(),
48    };
49    items
50        .into_iter()
51        .filter_map(|i| match i {
52            CommonsItem::Agent(a) => Some(a),
53            _ => None,
54        })
55        .collect()
56}
57
58/// The agent enclosing `offset`, with its model built against `types` (the
59/// unit's combined type table). `None` outside every agent.
60pub fn agent_state_at(
61    text: &str,
62    offset: usize,
63    types: &HashMap<String, Arc<TypeDecl>>,
64) -> Option<(AgentDecl, AgentStateModel)> {
65    let agent = agents(text)
66        .into_iter()
67        .find(|a| a.span.start <= offset && offset < a.span.end)?;
68    let model = agent_state::agent_state_model(&agent, types);
69    Some((agent, model))
70}
71
72/// Every agent's name, for the per-agent `Show State` lens.
73pub fn agent_lens_sites(text: &str) -> Vec<Span> {
74    agents(text).iter().map(|a| a.name.span).collect()
75}
76
77#[derive(Debug, Clone, serde::Serialize)]
78pub struct WireAgentStateModel {
79    pub agent: String,
80    pub range: Range,
81    pub handlers: Vec<WireHandler>,
82    pub machines: Vec<WireStateMachine>,
83    /// #2198: what each handler writes, reads and calls, path by path.
84    pub effects: Vec<WireHandlerEffects>,
85    /// #3608: the agent's `invariant`s and `transition`s; omitted when it
86    /// declares neither.
87    #[serde(skip_serializing_if = "Vec::is_empty")]
88    pub invariants: Vec<WireInvariant>,
89}
90
91/// #3608: one declared `invariant` or `transition`.
92#[derive(Debug, Clone, serde::Serialize)]
93pub struct WireInvariant {
94    /// `"invariant"` or `"transition"`.
95    pub kind: &'static str,
96    pub name: String,
97    /// The predicate's source text, printed by the expression printer.
98    pub predicate: String,
99    pub range: Range,
100    /// The declaration's documentation text; omitted when it has none.
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub doc: Option<String>,
103}
104
105fn wire_invariants(invariants: &[AgentInvariant], text: &str) -> Vec<WireInvariant> {
106    invariants
107        .iter()
108        .map(|i| WireInvariant {
109            kind: match i.kind {
110                InvariantKind::Invariant => "invariant",
111                InvariantKind::Transition => "transition",
112            },
113            name: i.name.clone(),
114            predicate: i.predicate.clone(),
115            range: crate::position::span_to_range(text, i.span),
116            doc: i.doc.clone(),
117        })
118        .collect()
119}
120
121#[derive(Debug, Clone, serde::Serialize)]
122pub struct WireHandlerEffects {
123    pub handler: String,
124    pub rows: Vec<WireEffectRow>,
125    pub truncated: bool,
126}
127
128#[derive(Debug, Clone, serde::Serialize)]
129pub struct WireEffectRow {
130    pub guards: Vec<String>,
131    pub writes: Vec<WireEffectWrite>,
132    pub reads: Vec<String>,
133    pub calls: Vec<String>,
134    pub outcomes: Vec<String>,
135}
136
137#[derive(Debug, Clone, serde::Serialize)]
138pub struct WireEffectWrite {
139    pub field: String,
140    pub op: String,
141    pub key: Option<String>,
142    pub range: Range,
143}
144
145/// #2198: the effects of `agent`'s handlers, with `agents` naming the
146/// agents a handler can call (the context's agent table).
147pub fn effects_of(agent: &AgentDecl, agents: &HashSet<String>) -> Vec<HandlerEffects> {
148    agent_effects::agent_effects(agent, agents)
149}
150
151#[derive(Debug, Clone, serde::Serialize)]
152pub struct WireHandler {
153    pub name: String,
154    pub range: Range,
155}
156
157#[derive(Debug, Clone, serde::Serialize)]
158#[serde(rename_all = "camelCase")]
159pub struct WireStateMachine {
160    pub field: String,
161    pub field_range: Range,
162    pub states: Vec<String>,
163    pub initial: Option<String>,
164    pub edges: Vec<WireEdge>,
165    pub reachable: Vec<String>,
166    /// #2219: the states the agent can be in after a commit — the only start
167    /// states the overlay checks, since the genesis commit runs no
168    /// `transition`.
169    pub reachable_after_commit: Vec<String>,
170    pub truncated: Vec<String>,
171    /// #2197: `transition`s on the field the overlay could not evaluate.
172    pub not_evaluated: Vec<WireNamed>,
173}
174
175#[derive(Debug, Clone, serde::Serialize)]
176pub struct WireNamed {
177    pub name: String,
178    pub range: Range,
179}
180
181/// #2197: a `transition` this edge can violate at commit.
182#[derive(Debug, Clone, serde::Serialize)]
183pub struct WireViolation {
184    pub transition: String,
185    pub range: Range,
186    /// `"Known"` or `"Possible"`.
187    pub certainty: &'static str,
188    pub from: Vec<String>,
189    pub targets: Vec<String>,
190}
191
192#[derive(Debug, Clone, serde::Serialize)]
193pub struct WireEdge {
194    pub handler: String,
195    pub from: Vec<String>,
196    pub guards: Vec<String>,
197    /// `{ "kind": "State", "state": "Placed" }`, `{ "kind": "Unknown" }` or
198    /// `{ "kind": "Unchanged" }`.
199    pub to: WireTarget,
200    pub outcome: Option<String>,
201    pub range: Range,
202    pub violations: Vec<WireViolation>,
203}
204
205#[derive(Debug, Clone, serde::Serialize)]
206#[serde(tag = "kind")]
207pub enum WireTarget {
208    State { state: String },
209    Unknown,
210    Unchanged,
211}
212
213pub fn to_wire(
214    agent: &AgentDecl,
215    model: &AgentStateModel,
216    effects: &[HandlerEffects],
217    text: &str,
218) -> WireAgentStateModel {
219    let range = |s: Span| crate::position::span_to_range(text, s);
220    WireAgentStateModel {
221        invariants: wire_invariants(&model.invariants, text),
222        effects: effects
223            .iter()
224            .map(|h| WireHandlerEffects {
225                handler: h.handler.clone(),
226                truncated: h.truncated,
227                rows: h
228                    .rows
229                    .iter()
230                    .map(|r| WireEffectRow {
231                        guards: r.guards.clone(),
232                        writes: r
233                            .writes
234                            .iter()
235                            .map(|w| WireEffectWrite {
236                                field: w.field.clone(),
237                                op: w.op.clone(),
238                                key: w.key.clone(),
239                                range: range(w.span),
240                            })
241                            .collect(),
242                        reads: r.reads.clone(),
243                        calls: r.calls.clone(),
244                        outcomes: r.outcomes.clone(),
245                    })
246                    .collect(),
247            })
248            .collect(),
249        agent: model.agent.clone(),
250        range: range(agent.name.span),
251        handlers: agent
252            .handlers
253            .iter()
254            .map(|h| WireHandler {
255                name: h
256                    .method_name
257                    .as_ref()
258                    .map_or_else(|| "call".to_string(), |m| m.name.clone()),
259                range: range(h.method_name.as_ref().map_or(h.span, |m| m.span)),
260            })
261            .collect(),
262        machines: model
263            .machines
264            .iter()
265            .map(|m| WireStateMachine {
266                field: m.field.clone(),
267                field_range: range(m.field_span),
268                states: m.states.clone(),
269                initial: m.initial.clone(),
270                edges: m
271                    .edges
272                    .iter()
273                    .map(|e| WireEdge {
274                        handler: e.handler.clone(),
275                        from: e.from.clone(),
276                        guards: e.guards.clone(),
277                        to: match &e.to {
278                            Target::State(s) => WireTarget::State { state: s.clone() },
279                            Target::Unknown => WireTarget::Unknown,
280                            Target::Unchanged => WireTarget::Unchanged,
281                        },
282                        outcome: e.outcome.clone(),
283                        range: range(e.span),
284                        violations: e
285                            .violations
286                            .iter()
287                            .map(|v| WireViolation {
288                                transition: v.transition.clone(),
289                                range: range(v.span),
290                                certainty: match v.certainty {
291                                    Certainty::Known => "Known",
292                                    Certainty::Possible => "Possible",
293                                },
294                                from: v.from.clone(),
295                                targets: v.targets.clone(),
296                            })
297                            .collect(),
298                    })
299                    .collect(),
300                reachable: m.reachable.clone(),
301                reachable_after_commit: m.reachable_after_commit.clone(),
302                truncated: m.truncated.clone(),
303                not_evaluated: m
304                    .not_evaluated
305                    .iter()
306                    .map(|n| WireNamed {
307                        name: n.transition.clone(),
308                        range: range(n.span),
309                    })
310                    .collect(),
311            })
312            .collect(),
313    }
314}