1use 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
22pub 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 &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 &[],
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
80pub 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#[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#[derive(Debug, Clone, serde::Serialize)]
138pub struct WireSequenceModel {
139 pub participants: Vec<WireParticipant>,
140 pub messages: Vec<WireMessage>,
141 pub blocks: Vec<WireAltBlock>,
142 pub trigger: WireTrigger,
144}
145
146#[derive(Debug, Clone, serde::Serialize)]
147pub struct WireTrigger {
148 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 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 pub callee: Option<WireCallee>,
175}
176
177#[derive(Debug, Clone, serde::Serialize)]
181pub struct WireCallee {
182 pub unit: Option<String>,
184 pub owner: String,
185 pub method: Option<String>,
187 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 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 pub reply: Option<String>,
213 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
260pub 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
302pub 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 #[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 #[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 #[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}