1use 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#[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
37fn 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
58pub 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
72pub 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 pub effects: Vec<WireHandlerEffects>,
85 #[serde(skip_serializing_if = "Vec::is_empty")]
88 pub invariants: Vec<WireInvariant>,
89}
90
91#[derive(Debug, Clone, serde::Serialize)]
93pub struct WireInvariant {
94 pub kind: &'static str,
96 pub name: String,
97 pub predicate: String,
99 pub range: Range,
100 #[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
145pub 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 pub reachable_after_commit: Vec<String>,
170 pub truncated: Vec<String>,
171 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#[derive(Debug, Clone, serde::Serialize)]
183pub struct WireViolation {
184 pub transition: String,
185 pub range: Range,
186 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 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}