1use std::collections::HashMap;
11use std::path::{Path, PathBuf};
12
13use bynk_syntax::ast::*;
14use bynk_syntax::lexer::tokenize;
15use bynk_syntax::parser::parse_unit_with_recovery;
16use bynk_syntax::span::Span;
17
18fn suite_fn_items(unit: &SourceUnit) -> Vec<CommonsItem> {
22 match unit {
23 SourceUnit::Suite(s) => s
24 .fns
25 .iter()
26 .cloned()
27 .map(CommonsItem::Fn)
28 .chain(s.types.iter().cloned().map(CommonsItem::Type))
29 .chain(s.consts.iter().cloned().map(CommonsItem::Const))
30 .collect(),
31 _ => Vec::new(),
32 }
33}
34
35pub fn find_declaration_span(source: &str, name: &str) -> Option<Span> {
52 let tokens = tokenize(source).ok()?;
53 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
54 let unit = unit?;
55 let suite_fns = suite_fn_items(&unit);
56 let items: &[CommonsItem] = match &unit {
57 SourceUnit::Commons(c) => &c.items,
58 SourceUnit::Context(c) => &c.items,
59 SourceUnit::Adapter(a) => &a.items,
60 SourceUnit::Suite(_) => &suite_fns,
61 };
62 if let SourceUnit::Suite(suite) = &unit
64 && let Some(f) = suite.fixtures.iter().find(|f| f.name.name == name)
65 {
66 return Some(f.name.span);
67 }
68 items
69 .iter()
70 .filter_map(CommonsItem::name)
71 .find(|ident| ident.name == name)
72 .map(|ident| ident.span)
73}
74
75pub fn describe_symbol(source: &str, name: &str) -> Option<String> {
78 let tokens = tokenize(source).ok()?;
79 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
80 let unit = unit?;
81 let suite_fns = suite_fn_items(&unit);
82 let items: &[CommonsItem] = match &unit {
83 SourceUnit::Commons(c) => &c.items,
84 SourceUnit::Context(c) => &c.items,
85 SourceUnit::Adapter(a) => &a.items,
86 SourceUnit::Suite(_) => &suite_fns,
87 };
88 if let SourceUnit::Context(ctx) = &unit
91 && let Some(c) = items.iter().find_map(|item| match item {
92 CommonsItem::Capability(c) if c.name.name == name && c.derived.is_some() => Some(c),
93 _ => None,
94 })
95 && let Some(d) = &c.derived
96 {
97 let base_unit = ctx.consumes.iter().find_map(|cd| {
98 cd.selected
99 .as_ref()?
100 .iter()
101 .any(|s| s.name.name == d.base.name)
102 .then(|| cd.target.joined())
103 });
104 let base = base_unit
105 .as_deref()
106 .and_then(|u| crate::completion::embedded_capability(u, &d.base.name));
107 return Some(describe_derived_capability(
108 c,
109 base_unit.as_deref(),
110 base.as_ref(),
111 ));
112 }
113 if let SourceUnit::Suite(suite) = &unit
115 && let Some(f) = suite.fixtures.iter().find(|f| f.name.name == name)
116 {
117 return Some(describe_fixture(f));
118 }
119 for item in items {
120 if let Some(summary) = describe_item(item, name) {
121 return Some(summary);
122 }
123 }
124 None
125}
126
127pub fn describe_keyword_at(source: &str, offset: usize) -> Option<&'static str> {
135 let tokens = tokenize(source).ok()?;
136 let word = tokens
137 .iter()
138 .find(|t| t.span.start <= offset && offset < t.span.end)
139 .map(|t| &source[t.span.start..t.span.end])?;
140 bynk_syntax::keywords::KEYWORDS
141 .iter()
142 .find(|k| k.word == word)
143 .map(|k| k.meaning)
144}
145
146pub fn describe_agent_state_at(source: &str, offset: usize) -> Option<String> {
167 let tokens = tokenize(source).ok()?;
168 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
169 let unit = unit?;
170 let items: &[CommonsItem] = match &unit {
171 SourceUnit::Commons(c) => &c.items,
172 SourceUnit::Context(c) => &c.items,
173 SourceUnit::Adapter(a) => &a.items,
174 SourceUnit::Suite(_) => &[],
175 };
176 if let SourceUnit::Context(c) = &unit {
179 for r in &c.removed_agents {
180 if span_covers(r.keyword, offset) || span_covers(r.name.span, offset) {
181 return Some(format!(
182 "```bynk\nremoved agent {}\n```\n\nThe agent class `{}` is gone: its stored \
183 data is deleted at the next deploy, which needs `--confirm-delete \
184 <context>.{}`.",
185 r.name.name, r.name.name, r.name.name
186 ));
187 }
188 }
189 }
190 for item in items {
191 let CommonsItem::Agent(a) = item else {
192 continue;
193 };
194 if let Some(old) = &a.replaces {
197 let on_kw = preceding_ident_span(&tokens, source, old.span, "replaces")
198 .is_some_and(|s| span_covers(s, offset));
199 if on_kw || span_covers(old.span, offset) {
200 return Some(format!(
201 "```bynk\nagent {} replaces {}\n```\n\nRenames the agent class `{}` to `{}`: \
202 its stored data and schema history move to `{}`.",
203 a.name.name, old.name, old.name, a.name.name, a.name.name
204 ));
205 }
206 }
207 let on_key_kw = preceding_ident_span(&tokens, source, a.key_name.span, "key")
210 .is_some_and(|s| span_covers(s, offset));
211 if on_key_kw || span_covers(a.key_name.span, offset) {
212 return Some(key_hover(a));
213 }
214 for f in &a.store_fields {
218 let store_kw = Span {
219 file: f.span.file,
220 start: f.span.start,
221 end: f.span.start + "store".len(),
222 };
223 let on_store_kw = source.get(store_kw.start..store_kw.end) == Some("store")
224 && span_covers(store_kw, offset);
225 if on_store_kw || span_covers(f.name.span, offset) {
226 return Some(store_field_hover(f));
227 }
228 }
229 for m in &a.migrations {
232 if span_covers(m.keyword, offset)
233 && source.get(m.keyword.start..m.keyword.end) == Some("migrate")
234 {
235 return Some(migrate_hover(m));
236 }
237 for item in &m.items {
238 if let MigrateItem::Drop(d) = item
239 && span_covers(d.keyword, offset)
240 {
241 return Some(format!(
242 "```bynk\ndrop {}\n```\n\nDiscards the stored value of `{}` on purpose: \
243 a removed field the step doesn't read, or a changed `Set`, `Log` or \
244 `Cache` field, which starts afresh.",
245 d.field.name, d.field.name
246 ));
247 }
248 }
249 }
250 if !in_state_scope(a, offset) {
252 continue;
253 }
254 let Some((name, name_span)) = ident_at(&tokens, source, offset) else {
255 continue;
256 };
257 if is_dot_preceded(source, name_span.start) {
260 continue;
261 }
262 if name == a.key_name.name {
263 return Some(key_hover(a));
264 }
265 if let Some(f) = a.store_fields.iter().find(|f| f.name.name == name) {
266 return Some(store_field_hover(f));
267 }
268 }
269 None
270}
271
272pub const RESERVED_PRINCIPALS: &[(&str, &str)] = &[
276 (
277 "Nobody",
278 "Sends no credential — no `Authorization` header on a Bearer or `Oidc` route, no session cookie on a `SignedCookie` route, no signature headers on a `Signature` route — so the real seam refuses it (`Rejected(Unauthorized)`). `system` tier only.",
279 ),
280 (
281 "Forged",
282 "Signs a `Signature` route's request, or a Bearer route's token (a valid `sub`, a future `exp`), with a secret the seam does not hold, sends a `SignedCookie` route a well-formed cookie signed with a key the seam does not hold, or sends an `Oidc` route a token signed by a key its JWKS does not publish, so the real seam refuses it (`Rejected(Unauthorized)`). `system` tier only.",
283 ),
284 (
285 "Stale",
286 "Signs a `Signature` route's request correctly, timestamped `tolerance + 60` seconds in the past, so the real seam refuses it as a replay (`Rejected(Unauthorized)`). Needs an actor with `timestamp` and `tolerance`. `system` tier only.",
287 ),
288 (
289 "Expired",
290 "Sends a Bearer or `Oidc` route's token, or a `SignedCookie` route's cookie, correctly signed, with a valid `sub` and an expiry one hour in the past, so the real seam refuses it (`Rejected(Unauthorized)`). Needs a `Bearer`, `SignedCookie` or `Oidc` actor. `system` tier only.",
291 ),
292 (
293 "WrongIssuer",
294 "Sends an `Oidc` route a token correctly signed by the test issuer and unexpired, whose `iss` is not the actor's issuer, so the real seam refuses it (`Rejected(Unauthorized)`). Needs an `Oidc` actor. `system` tier only.",
295 ),
296 (
297 "WrongAudience",
298 "Sends an `Oidc` route a token correctly signed by the test issuer and unexpired, whose `aud` is not the actor's audience, so the real seam refuses it (`Rejected(Unauthorized)`). Needs an `Oidc` actor. `system` tier only.",
299 ),
300 (
301 "WrongAlgorithm",
302 "Sends an `Oidc` route two tokens that are otherwise valid, one with `alg: none` and one `HS256`-signed with the JWKS public key as the HMAC secret, so the real seam refuses both (`Rejected(Unauthorized)`); the case reads the first one it admits, if any. Needs an `Oidc` actor. `system` tier only.",
303 ),
304 (
305 "NoSubject",
306 "Sends an `Oidc` route two tokens that are correctly signed by the test issuer and unexpired, one with an empty `sub` and one with no `sub` claim, so the real seam refuses both before the handler runs (`Rejected(Unauthorized)`), whatever the identity's refinement. Needs an `Oidc` actor. `system` tier only.",
307 ),
308];
309
310pub fn describe_reserved_principal_at(source: &str, offset: usize) -> Option<String> {
315 let tokens = tokenize(source).ok()?;
316 let (name, span) = ident_at(&tokens, source, offset)?;
317 let (_, doc) = RESERVED_PRINCIPALS.iter().find(|(n, _)| *n == name)?;
318 preceding_ident_span(&tokens, source, span, "by")
319 .map(|_| format!("```bynk\nby {name}\n```\n\n{doc}"))
320}
321
322pub const ENV_KEYWORD_DOC: &str = "The variables and secrets a suite's participants see (`env { NAME = \"value\" … }`): on each Worker's `env` at `system`, and what the `Secrets` double answers at `unit`/`integration`. A case's `env` layers over its suite's, name by name.";
324
325pub fn describe_env_at(source: &str, offset: usize) -> Option<String> {
332 let tokens = tokenize(source).ok()?;
333 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
334 let SourceUnit::Suite(suite) = unit? else {
335 return None;
336 };
337 let on_kw = |e: &EnvClause| {
338 span_covers(
339 Span {
340 file: e.span.file,
341 start: e.span.start,
342 end: e.span.start + "env".len(),
343 },
344 offset,
345 )
346 };
347 let suite_gives = |name: &str| {
348 suite
349 .envs
350 .iter()
351 .flat_map(|e| e.entries.iter())
352 .any(|x| x.name.name == name)
353 };
354 let render = |entry: &EnvEntry, scope: &str| {
355 let value = match &entry.value.kind {
356 ExprKind::StrLit(v) => format!("{v:?}"),
357 ExprKind::Ident(id) => id.name.clone(),
359 _ => "…".to_string(),
360 };
361 format!(
362 "```bynk\n{} = {value}\n```\n\nvariable given to every participant ({scope})",
363 entry.name.name
364 )
365 };
366 for e in &suite.envs {
367 if on_kw(e) {
368 return Some(ENV_KEYWORD_DOC.to_string());
369 }
370 if let Some(entry) = e.entries.iter().find(|x| span_covers(x.name.span, offset)) {
371 return Some(render(entry, "suite"));
372 }
373 }
374 for case in &suite.cases {
375 for e in &case.envs {
376 if on_kw(e) {
377 return Some(ENV_KEYWORD_DOC.to_string());
378 }
379 if let Some(entry) = e.entries.iter().find(|x| span_covers(x.name.span, offset)) {
380 let scope = if suite_gives(&entry.name.name) {
381 "case, overrides suite"
382 } else {
383 "case"
384 };
385 return Some(render(entry, scope));
386 }
387 }
388 }
389 None
390}
391
392fn in_state_scope(a: &AgentDecl, offset: usize) -> bool {
399 a.handlers.iter().any(|h| span_covers(h.body.span, offset))
400 || a.invariants
401 .iter()
402 .any(|i| span_covers(i.predicate.span, offset))
403 || a.transitions
404 .iter()
405 .any(|t| span_covers(t.predicate.span, offset))
406}
407
408fn migrate_hover(m: &MigrateDecl) -> String {
410 let old = m
411 .old
412 .as_ref()
413 .map(|o| format!(" ({}: {})", o.name.name, type_ref_str(&o.type_ref)))
414 .unwrap_or_default();
415 format!(
416 "```bynk\nmigrate from {}{old}\n```\n\nA migration step: carries a stored record from \
417 schema version {} to the agent's current shape when it next loads.",
418 m.from, m.from
419 )
420}
421
422fn key_hover(a: &AgentDecl) -> String {
424 let sig = format!("key {}: {}", a.key_name.name, type_ref_str(&a.key_type));
425 render_state_hover(&sig, "key")
426}
427
428fn store_field_hover(f: &StoreField) -> String {
430 let mut sig = format!("store {}: {}", f.name.name, store_kind_str(&f.kind));
431 for ann in &f.annotations {
432 sig.push(' ');
433 sig.push_str(&bynk_fmt::annotation_to_string(ann));
434 }
435 render_state_hover(&sig, "store")
436}
437
438pub fn describe_store_op_at(
451 source: &str,
452 offset: usize,
453 locals: &[bynk_check::locals::LocalBinding],
454) -> Option<String> {
455 let tokens = tokenize(source).ok()?;
456 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
457 let unit = unit?;
458 let items: &[CommonsItem] = match &unit {
459 SourceUnit::Commons(c) => &c.items,
460 SourceUnit::Context(c) => &c.items,
461 SourceUnit::Adapter(a) => &a.items,
462 SourceUnit::Suite(_) => &[],
463 };
464 let (op, op_span) = ident_at(&tokens, source, offset)?;
466 let (recv, recv_start) = receiver_segment_at(source, op_span)?;
467 if is_dot_preceded(source, recv_start) {
471 return None;
472 }
473 if bynk_check::locals::locals_at(locals, recv_start)
476 .iter()
477 .any(|b| b.name == recv)
478 {
479 return None;
480 }
481 for item in items {
482 let CommonsItem::Agent(a) = item else {
483 continue;
484 };
485 if !in_state_scope(a, offset) {
486 continue;
487 }
488 let f = a.store_fields.iter().find(|f| f.name.name == recv)?;
489 let sig = bynk_check::store_ops::ops_for(&f.kind.head.name)
490 .iter()
491 .find(|o| o.name == op)?
492 .signature;
493 return Some(format!(
494 "```bynk\n{sig}\n```\n\nA `{}` store operation on `store {}: {}` — the field's \
495 declared kind grounds the operation's type parameters.",
496 f.kind.head.name,
497 f.name.name,
498 store_kind_str(&f.kind),
499 ));
500 }
501 None
502}
503
504fn ident_at<'a>(
507 tokens: &[bynk_syntax::lexer::Token],
508 source: &'a str,
509 offset: usize,
510) -> Option<(&'a str, Span)> {
511 tokens
512 .iter()
513 .find(|t| t.kind == bynk_syntax::lexer::TokenKind::Ident && span_covers(t.span, offset))
514 .and_then(|t| Some((source.get(t.span.start..t.span.end)?, t.span)))
515}
516
517fn receiver_segment_at(text: &str, member_span: Span) -> Option<(&str, usize)> {
524 let before = text.get(..member_span.start)?.strip_suffix('.')?;
525 crate::completion::ident_ending_at(before, before.len())
526}
527
528pub(crate) fn is_dot_preceded(text: &str, start: usize) -> bool {
531 text[..start].ends_with('.') && !text[..start].ends_with("..")
534}
535
536pub fn store_field_kind_at(
554 source: &str,
555 recv_end: usize,
556 locals: &[bynk_check::locals::LocalBinding],
557) -> Option<(String, bool)> {
558 let (recv, recv_start) = crate::completion::ident_ending_at(source, recv_end)?;
559 if bynk_check::locals::locals_at(locals, recv_start)
560 .iter()
561 .any(|b| b.name == recv)
562 {
563 return None;
564 }
565 let tokens = tokenize(source).ok()?;
566 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
567 let unit = unit?;
568 let items: &[CommonsItem] = match &unit {
569 SourceUnit::Commons(c) => &c.items,
570 SourceUnit::Context(c) => &c.items,
571 SourceUnit::Adapter(a) => &a.items,
572 SourceUnit::Suite(_) => &[],
573 };
574 for item in items {
575 let CommonsItem::Agent(a) = item else {
576 continue;
577 };
578 if !in_state_scope(a, recv_end) {
579 continue;
580 }
581 if let Some(f) = a.store_fields.iter().find(|f| f.name.name == recv) {
582 let held = f.kind.head.name == "Map"
583 && f.kind.args.len() == 2
584 && matches!(f.kind.args[1], TypeRef::Connection(..));
585 return Some((f.kind.head.name.clone(), held));
586 }
587 }
588 None
589}
590
591pub fn describe_handler_annotation_at(source: &str, offset: usize) -> Option<String> {
598 let tokens = tokenize(source).ok()?;
599 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
600 let unit = unit?;
601 let items: &[CommonsItem] = match &unit {
602 SourceUnit::Commons(c) => &c.items,
603 SourceUnit::Context(c) => &c.items,
604 SourceUnit::Adapter(a) => &a.items,
605 SourceUnit::Suite(_) => &[],
606 };
607 for item in items {
608 let (handlers, service_cap): (&[Handler], Option<i64>) = match item {
609 CommonsItem::Service(s) => (&s.handlers, s.limits.as_ref().and_then(|l| l.max_body())),
610 CommonsItem::Agent(a) => (&a.handlers, None),
611 _ => continue,
612 };
613 for h in handlers {
614 for ann in &h.annotations {
615 if span_covers(ann.span, offset) {
616 return Some(render_handler_annotation_hover(ann, h, service_cap));
617 }
618 }
619 }
620 }
621 None
622}
623
624pub fn describe_refinement_example_at(source: &str, offset: usize) -> Option<String> {
628 let tokens = tokenize(source).ok()?;
629 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
630 let items: &[CommonsItem] = match unit.as_ref()? {
631 SourceUnit::Commons(c) => &c.items,
632 SourceUnit::Context(c) => &c.items,
633 SourceUnit::Adapter(a) => &a.items,
634 SourceUnit::Suite(_) => &[],
635 };
636 let render = |r: &bynk_syntax::ast::Refinement| -> Option<String> {
637 let ann = r
638 .annotations
639 .iter()
640 .find(|a| a.name.name == "example" && span_covers(a.span, offset))?;
641 let value = ann
642 .args
643 .first()
644 .map(|a| bynk_fmt::expr_to_string(&a.value))
645 .unwrap_or_default();
646 Some(format!(
647 "**`@example({value})`** — the value `Val` uses where it cannot generate one; checked against `{}`. Test-only: it changes neither the type nor its wire format.",
648 bynk_syntax::print::refinement_to_string(r)
649 ))
650 };
651 for item in items {
652 let CommonsItem::Type(t) = item else { continue };
653 match &t.body {
654 bynk_syntax::ast::TypeBody::Refined { refinement, .. }
655 | bynk_syntax::ast::TypeBody::Opaque { refinement, .. } => {
656 if let Some(h) = refinement.as_ref().and_then(render) {
657 return Some(h);
658 }
659 }
660 bynk_syntax::ast::TypeBody::Record(rec) => {
661 for f in &rec.fields {
662 if let Some(h) = f.refinement.as_ref().and_then(render) {
663 return Some(h);
664 }
665 }
666 }
667 bynk_syntax::ast::TypeBody::Sum(_) => {}
668 }
669 }
670 None
671}
672
673pub fn describe_advance_at(source: &str, offset: usize) -> Option<String> {
677 let tokens = tokenize(source).ok()?;
678 let idx = tokens
679 .iter()
680 .position(|t| t.span.start <= offset && offset < t.span.end)?;
681 let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
682 if text(idx)? != "advance"
683 || tokens.get(idx + 1)?.kind != bynk_syntax::lexer::TokenKind::Ident
684 || text(idx + 2)? != "by"
685 {
686 return None;
687 }
688 Some(
689 "```bynk\nadvance Clock by <Duration>\n```\n\nMoves the test harness's clock forward. Each case's clock starts at the epoch; at `unit` and `integration` the `Clock` double reads it, and at `system` every participant's first-party `Clock` does. It governs `Clock` only: JWT expiry, the `Signature` tolerance and Durable Object alarms keep wall-clock time."
690 .to_string(),
691 )
692}
693
694pub fn describe_by_at(source: &str, offset: usize) -> Option<String> {
699 let tokens = tokenize(source).ok()?;
700 let idx = tokens
701 .iter()
702 .position(|t| t.span.start <= offset && offset < t.span.end)?;
703 let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
704 if text(idx)? != "by" || tokens.get(idx)?.kind != bynk_syntax::lexer::TokenKind::Ident {
705 return None;
706 }
707 let advance = idx >= 2
708 && text(idx - 2) == Some("advance")
709 && tokens.get(idx - 1)?.kind == bynk_syntax::lexer::TokenKind::Ident;
710 let start = tokens[idx].span.start;
711 let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
712 let prefix = format!("{}by ", &source[line_start..start]);
713 let named = tokens.get(idx + 1).map(|t| t.kind) == Some(bynk_syntax::lexer::TokenKind::Ident);
716 if !(advance || named && crate::completion::is_by_clause_position(&prefix)) {
717 return None;
718 }
719 let (shape, doc) = if advance {
720 (
721 "advance Clock by <Duration>",
722 "The amount to move the test harness's clock forward by.",
723 )
724 } else {
725 (
726 "by <name>: <Actor>",
727 "Names the actor a handler consumes, after the return type or on a service header — or, at a call, the principal it is made as (`let r <- f() by User(\"bob\")`). Outside these positions `by` is an ordinary name.",
728 )
729 };
730 Some(format!("```bynk\n{shape}\n```\n\n{doc}"))
731}
732
733pub fn describe_derives_at(source: &str, offset: usize) -> Option<String> {
737 let tokens = tokenize(source).ok()?;
738 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
739 let items: &[CommonsItem] = match unit.as_ref()? {
740 SourceUnit::Commons(c) => &c.items,
741 SourceUnit::Context(c) => &c.items,
742 SourceUnit::Adapter(a) => &a.items,
743 SourceUnit::Suite(_) => return None,
744 };
745 items.iter().find_map(|item| match item {
746 CommonsItem::Type(t) if t.derives_kw.is_some_and(|k| k.start <= offset && offset < k.end) => {
747 Some(
748 "```bynk\ntype Priority = enum { Low, High } derives Ord\n```\n\nOpts the type into a constraint. `derives Ord` orders the type by declaration order: a record compares field by field, then a sum by variant, so reordering the declaration changes the order. Every field must itself be orderable. `Eq`, `Key` and `Codable` are automatic and are not derived."
749 .to_string(),
750 )
751 }
752 _ => None,
753 })
754}
755
756fn constraint_doc(name: &str) -> Option<&'static str> {
759 match name {
760 "Eq" => Some(
761 "```bynk\nconstraint Eq\n```\n\nValues of the type compare with `==` and `!=`. Declare it on a type parameter (`T: Eq`) to compare its values inside the function. Every type that can be compared is `Eq` automatically.",
762 ),
763 "Ord" => Some(
764 "```bynk\nconstraint Ord\n```\n\nValues of the type are ordered: they compare with `<`, `<=`, `>` and `>=`, and can be sorted. Declare it on a type parameter (`T: Ord`) to order its values inside the function; `Ord` implies `Eq`. A type opts in with `derives Ord`, which orders it by declaration order.",
765 ),
766 "Key" => Some(
767 "```bynk\nconstraint Key\n```\n\nValues of the type can key a `Map` or be a `Set` member, and group under `distinct` and `groupBy`. Declare it on a type parameter (`K: Key`) to use it that way inside the function; `Key` implies `Eq`. Strings, ints, bytes, `Option` and `List` of a key, and records, sums and enums made of keys are `Key` automatically; a `Float` never is.",
768 ),
769 "Codable" => Some(
770 "```bynk\nconstraint Codable\n```\n\nValues of the type encode and decode with `Json`. Declare it on a type parameter (`T: Codable`) to call `Json.encode` and `Json.decode[T]` inside the function, or to pass the value to a `Codable` parameter of a capability operation, which encodes it at the call site so the provider receives plain JSON. Every type `Json.decode` accepts is `Codable` automatically; `()`, functions, `Effect`, streams and the HTTP result types are not.",
771 ),
772 _ => None,
773 }
774}
775
776pub fn describe_constraint_at(source: &str, offset: usize) -> Option<String> {
780 let span = constraint_token_spans(source)
781 .into_iter()
782 .find(|s| s.start <= offset && offset < s.end)?;
783 constraint_doc(&source[span.start..span.end]).map(str::to_string)
784}
785
786pub fn describe_par_at(source: &str, offset: usize) -> Option<String> {
790 let tokens = tokenize(source).ok()?;
791 let idx = tokens
792 .iter()
793 .position(|t| t.span.start <= offset && offset < t.span.end)?;
794 let text = |i: usize| tokens.get(i).map(|t| &source[t.span.start..t.span.end]);
795 if text(idx)? != "par" || tokens.get(idx + 1)?.kind != bynk_syntax::lexer::TokenKind::LBrace {
796 return None;
797 }
798 Some(
799 "```bynk\npar {\n let a <- first()\n let b <- second()\n}\n```\n\nIssues every effect in the block, in source order, before awaiting any of them, and completes when all have settled. The names bound inside are in scope after the closing brace; no binding may mention a name a sibling binds. If any effect faults, the block waits for the rest, then raises the first fault in source order. Holds only `let x <- e` and `do e`."
800 .to_string(),
801 )
802}
803
804pub fn describe_fixture_at(source: &str, offset: usize) -> Option<String> {
808 use bynk_syntax::lexer::TokenKind;
809 let tokens = tokenize(source).ok()?;
810 let idx = tokens
811 .iter()
812 .position(|t| t.span.start <= offset && offset < t.span.end)?;
813 let t = tokens.get(idx)?;
814 if t.kind != TokenKind::Ident
815 || &source[t.span.start..t.span.end] != "fixture"
816 || tokens.get(idx + 1)?.kind != TokenKind::Ident
817 || tokens.get(idx + 2)?.kind != TokenKind::Eq
818 {
819 return None;
820 }
821 let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
822 .iter()
823 .find(|k| k.word == "fixture")
824 .map(|k| k.meaning)
825 .unwrap_or_default();
826 Some(format!("```bynk\nfixture\n```\n\n{doc}"))
827}
828
829pub fn describe_private_at(source: &str, offset: usize) -> Option<String> {
835 use bynk_syntax::lexer::TokenKind;
836 let tokens = tokenize(source).ok()?;
837 let idx = tokens
838 .iter()
839 .position(|t| t.span.start <= offset && offset < t.span.end)?;
840 let t = tokens.get(idx)?;
841 if t.kind != TokenKind::Ident || &source[t.span.start..t.span.end] != "private" {
842 return None;
843 }
844 let next = tokens.get(idx + 1)?.kind;
845 if !matches!(
846 next,
847 TokenKind::Fn
848 | TokenKind::Type
849 | TokenKind::Messages
850 | TokenKind::Asset
851 | TokenKind::Embed
852 | TokenKind::Const
853 ) {
854 return None;
855 }
856 let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
857 .iter()
858 .find(|k| k.word == "private")
859 .map(|k| k.meaning)
860 .unwrap_or_default();
861 Some(format!("```bynk\nprivate\n```\n\n{doc}"))
862}
863
864pub const RUN_ID_DOC: &str = "**`run.id`** — this test run's identity, a `String`. In process it is always `\"local\"`; each `bynk test --against` run gets a fresh one, so a key built from it (`\"order-\\(run.id)\"`) doesn't collide with an earlier run's data on a shared deployment.";
866
867pub fn is_test_run_receiver(source: &str, run_start: usize) -> bool {
877 let Ok(tokens) = tokenize(source) else {
878 return false;
879 };
880 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
881 let Some(SourceUnit::Suite(suite)) = unit else {
882 return false;
883 };
884 let Some(case) = suite.cases.iter().find(|c| span_covers(c.span, run_start)) else {
885 return false;
886 };
887 run_bound_in_block(&case.body, run_start, &mut Vec::new()) != Some(true)
888}
889
890fn run_bound_in_block(block: &Block, at: usize, bound: &mut Vec<String>) -> Option<bool> {
893 let mark = bound.len();
894 let mut found = None;
895 for stmt in &block.statements {
896 let mut exprs = Vec::new();
897 statement_exprs(stmt, &mut exprs);
898 found = exprs
899 .into_iter()
900 .find_map(|e| run_bound_in_expr(e, at, bound));
901 if found.is_some() {
902 break;
903 }
904 if let Statement::Let(l) | Statement::EffectLet(l) = stmt {
906 bound.push(l.name.name.clone());
907 }
908 if let Statement::Par(p) = stmt {
910 bound.extend(p.statements.iter().filter_map(|s| match s {
911 Statement::EffectLet(l) => Some(l.name.name.clone()),
912 _ => None,
913 }));
914 }
915 }
916 let found = found.or_else(|| run_bound_in_expr(&block.tail, at, bound));
917 bound.truncate(mark);
918 found
919}
920
921fn run_bound_in_expr(e: &Expr, at: usize, bound: &mut Vec<String>) -> Option<bool> {
922 if !span_covers(e.span, at) {
923 return None;
924 }
925 let mark = bound.len();
926 let found = match &e.kind {
927 ExprKind::Ident(id) if id.span.start == at && id.name == "run" => {
928 Some(bound.iter().any(|n| n == "run"))
929 }
930 ExprKind::Block(b) => run_bound_in_block(b, at, bound),
931 ExprKind::Lambda(l) => {
932 bound.extend(l.params.iter().map(|p| p.name.name.clone()));
933 run_bound_in_expr(&l.body, at, bound)
934 }
935 ExprKind::If {
936 cond,
937 then_block,
938 else_block,
939 } => run_bound_in_expr(cond, at, bound)
940 .or_else(|| {
941 let inner = bound.len();
942 bound.extend(is_bound_names(cond, true));
943 let r = run_bound_in_block(then_block, at, bound);
944 bound.truncate(inner);
945 r
946 })
947 .or_else(|| {
948 let inner = bound.len();
949 bound.extend(is_bound_names(cond, false));
950 let r = run_bound_in_block(else_block, at, bound);
951 bound.truncate(inner);
952 r
953 }),
954 ExprKind::BinOp(BinOp::And | BinOp::Implies, lhs, rhs) => run_bound_in_expr(lhs, at, bound)
956 .or_else(|| {
957 bound.extend(is_bound_names(lhs, true));
958 run_bound_in_expr(rhs, at, bound)
959 }),
960 ExprKind::Match { discriminant, arms } => run_bound_in_expr(discriminant, at, bound)
961 .or_else(|| {
962 arms.iter()
963 .find(|a| span_covers(a.span, at))
964 .and_then(|arm| {
965 bound.extend(
966 arm.pattern
967 .bound_names()
968 .into_iter()
969 .map(|id| id.name.clone()),
970 );
971 arm.guard
972 .as_ref()
973 .and_then(|g| run_bound_in_expr(g, at, bound))
974 .or_else(|| match &arm.body {
975 MatchBody::Expr(body) => run_bound_in_expr(body, at, bound),
976 MatchBody::Block(b) => run_bound_in_block(b, at, bound),
977 })
978 })
979 }),
980 _ => expr_children(e)
981 .into_iter()
982 .find_map(|c| run_bound_in_expr(c, at, bound)),
983 };
984 bound.truncate(mark);
985 found
986}
987
988fn is_bound_names(cond: &Expr, when_true: bool) -> Vec<String> {
991 bynk_check::narrowing::matched_is_tests(cond, when_true)
992 .into_iter()
993 .filter_map(|test| match &test.kind {
994 ExprKind::Is { pattern, .. } => Some(pattern.bound_names()),
995 _ => None,
996 })
997 .flatten()
998 .map(|id| id.name.clone())
999 .collect()
1000}
1001
1002pub fn describe_run_id_at(source: &str, offset: usize) -> Option<String> {
1006 let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1009 let offset = offset.min(source.len());
1010 let start = source[..offset]
1011 .char_indices()
1012 .rev()
1013 .take_while(|(_, c)| is_ident(*c))
1014 .last()
1015 .map_or(offset, |(i, _)| i);
1016 let end = source[start..]
1017 .char_indices()
1018 .find(|(_, c)| !is_ident(*c))
1019 .map_or(source.len(), |(i, _)| start + i);
1020 let ends_ident = |rest: &str| !rest.starts_with(is_ident);
1021 let run = match &source[start..end] {
1022 "run" if source[end..].strip_prefix(".id").is_some_and(ends_ident) => start,
1023 "id" if source[..start].ends_with("run.") => start - "run.".len(),
1024 _ => return None,
1025 };
1026 if source[..run].ends_with(|c: char| is_ident(c) || c == '.') {
1027 return None; }
1029 is_test_run_receiver(source, run).then(|| RUN_ID_DOC.to_string())
1030}
1031
1032pub fn describe_system_job_address_at<'s>(
1041 source: &'s str,
1042 offset: usize,
1043 others: impl IntoIterator<Item = &'s str>,
1044) -> Option<String> {
1045 let is_ident = |c: char| c.is_ascii_alphanumeric() || c == '_';
1046 let start = source[..offset.min(source.len())]
1047 .char_indices()
1048 .rev()
1049 .take_while(|(_, c)| is_ident(*c))
1050 .last()
1051 .map_or(offset, |(i, _)| i);
1052 let end = source[start..]
1053 .char_indices()
1054 .find(|(_, c)| !is_ident(*c))
1055 .map_or(source.len(), |(i, _)| start + i);
1056 let name = &source[start..end];
1057 if !source[..start].ends_with('.') || !matches!(name, "schedule" | "message") {
1058 return None;
1059 }
1060 let tokens = tokenize(source).ok()?;
1061 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1062 let SourceUnit::Suite(suite) = unit? else {
1063 return None;
1064 };
1065 let case = suite.cases.iter().find(|c| span_covers(c.span, start))?;
1066 if case.tier.or(suite.tier) != Some(TestTier::System) {
1067 return None;
1068 }
1069 let before = &source[..start - 1];
1071 let receiver = &before[before
1072 .char_indices()
1073 .rev()
1074 .take_while(|(_, c)| is_ident(*c))
1075 .last()
1076 .map_or(before.len(), |(i, _)| i)..];
1077 let target = suite.target.joined();
1078 let is_job_service = std::iter::once(source).chain(others).any(|src| {
1083 let Ok(tokens) = tokenize(src) else {
1084 return false;
1085 };
1086 let (unit, _errs) = parse_unit_with_recovery(&tokens, src);
1087 let Some(SourceUnit::Context(ctx)) = unit else {
1088 return false;
1089 };
1090 ctx.name.joined() == target
1091 && ctx.items.iter().any(|item| {
1092 matches!(item, CommonsItem::Service(svc)
1093 if svc.name.name == receiver
1094 && match name {
1095 "schedule" => matches!(svc.protocol, ServiceProtocol::Cron),
1096 _ => matches!(svc.protocol, ServiceProtocol::Queue { .. }),
1097 })
1098 })
1099 });
1100 if !is_job_service {
1101 return None;
1102 }
1103 Some(if name == "schedule" {
1104 "**`svc.schedule(\"<expr>\", at: Instant)`** at `system` — runs the cron handler through the Worker's `scheduled` entry, with `{ cron, scheduledTime: at }`, and yields the handler's own `Result`.".to_string()
1105 } else {
1106 "**`q.message(m)`** at `system` — delivers `m` through the Worker's `queue` entry, after a JSON round trip, and yields `Ack` or `Retry(reason)` as the consumer acknowledged or retried it.".to_string()
1107 })
1108}
1109
1110pub fn handler_annotation_token_spans(source: &str) -> Vec<Span> {
1116 let Ok(tokens) = tokenize(source) else {
1117 return Vec::new();
1118 };
1119 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1120 let Some(unit) = unit else {
1121 return Vec::new();
1122 };
1123 let items: &[CommonsItem] = match &unit {
1124 SourceUnit::Commons(c) => &c.items,
1125 SourceUnit::Context(c) => &c.items,
1126 SourceUnit::Adapter(a) => &a.items,
1127 SourceUnit::Suite(_) => &[],
1128 };
1129 let mut spans = Vec::new();
1130 fn push_refinement(spans: &mut Vec<Span>, r: &Option<bynk_syntax::ast::Refinement>) {
1132 for ann in r.iter().flat_map(|r| &r.annotations) {
1133 spans.push(Span {
1134 file: ann.span.file,
1135 start: ann.span.start,
1136 end: ann.name.span.end,
1137 });
1138 }
1139 }
1140 for item in items {
1141 if let CommonsItem::Type(t) = item {
1142 match &t.body {
1143 bynk_syntax::ast::TypeBody::Refined { refinement, .. }
1144 | bynk_syntax::ast::TypeBody::Opaque { refinement, .. } => {
1145 push_refinement(&mut spans, refinement)
1146 }
1147 bynk_syntax::ast::TypeBody::Record(r) => {
1148 for f in &r.fields {
1149 push_refinement(&mut spans, &f.refinement);
1150 }
1151 }
1152 bynk_syntax::ast::TypeBody::Sum(_) => {}
1153 }
1154 continue;
1155 }
1156 let handlers: &[Handler] = match item {
1157 CommonsItem::Service(s) => &s.handlers,
1158 CommonsItem::Agent(a) => &a.handlers,
1159 _ => continue,
1160 };
1161 for h in handlers {
1162 for ann in &h.annotations {
1163 spans.push(Span {
1165 file: ann.span.file,
1166 start: ann.span.start,
1167 end: ann.name.span.end,
1168 });
1169 for arg in &ann.args {
1171 if let Some(label) = &arg.label {
1172 spans.push(label.span);
1173 }
1174 }
1175 }
1176 }
1177 }
1178 spans
1179}
1180
1181pub struct SnapshotSite {
1185 pub case: String,
1186 pub name: String,
1187 pub clause: Span,
1188 pub words: [Span; 2],
1189}
1190
1191pub fn snapshot_sites(source: &str) -> Vec<SnapshotSite> {
1194 let Ok(tokens) = tokenize(source) else {
1195 return Vec::new();
1196 };
1197 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1198 let Some(SourceUnit::Suite(suite)) = unit else {
1199 return Vec::new();
1200 };
1201 let mut out = Vec::new();
1202 for case in &suite.cases {
1203 for e in bynk_check::test_suites::snapshot_expects(&case.body) {
1204 let Some(clause) = &e.snapshot else { continue };
1205 let words: Vec<Span> = tokens
1207 .iter()
1208 .filter(|t| {
1209 t.kind == bynk_syntax::lexer::TokenKind::Ident
1210 && t.span.start >= clause.span.start
1211 && t.span.end <= clause.span.end
1212 })
1213 .take(2)
1214 .map(|t| t.span)
1215 .collect();
1216 let [matches, snapshot] = words[..] else {
1217 continue;
1218 };
1219 out.push(SnapshotSite {
1220 case: case.name.clone(),
1221 name: clause.name.clone(),
1222 clause: clause.span,
1223 words: [matches, snapshot],
1224 });
1225 }
1226 }
1227 out
1228}
1229
1230pub fn snapshot_keyword_spans(source: &str) -> Vec<Span> {
1234 snapshot_sites(source)
1235 .into_iter()
1236 .flat_map(|s| s.words)
1237 .collect()
1238}
1239
1240pub fn snapshot_file_for(rel: &Path) -> String {
1243 bynk_project::snapshots::snapshot_path(rel)
1244}
1245
1246pub fn describe_snapshot_at(source: &str, offset: usize, stored: Option<&str>) -> Option<String> {
1250 let site = snapshot_sites(source)
1251 .into_iter()
1252 .find(|s| s.clause.start <= offset && offset < s.clause.end)?;
1253 let recorded = stored
1254 .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())
1255 .and_then(|v| v.get(&site.case)?.get(&site.name).cloned());
1256 let head = format!(
1257 "```bynk\nexpect <value> matches snapshot \"{}\"\n```\n\nCompares the value's canonical JSON (`Json.encode`, keys sorted) with the snapshot stored for case `\"{}\"`.",
1258 site.name, site.case
1259 );
1260 Some(match recorded {
1261 Some(value) => {
1262 let pretty = serde_json::to_string_pretty(&value).unwrap_or_default();
1263 format!("{head}\n\nStored:\n\n```json\n{pretty}\n```")
1264 }
1265 None => format!(
1266 "{head}\n\nNot yet recorded: `bynk test --update-snapshots` writes it, and a run without the flag fails until it does."
1267 ),
1268 })
1269}
1270
1271pub fn private_modifier_token_spans(source: &str) -> Vec<Span> {
1277 let Ok(tokens) = tokenize(source) else {
1278 return Vec::new();
1279 };
1280 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1281 let Some(unit) = unit else {
1282 return Vec::new();
1283 };
1284 let items: &[CommonsItem] = match &unit {
1285 SourceUnit::Commons(c) => &c.items,
1286 SourceUnit::Context(c) => &c.items,
1287 SourceUnit::Adapter(a) => &a.items,
1288 SourceUnit::Suite(_) => &[],
1289 };
1290 let mut spans: Vec<Span> = items.iter().filter_map(CommonsItem::private_span).collect();
1291 if let SourceUnit::Suite(s) = &unit {
1293 spans.extend(
1294 s.fixtures
1295 .iter()
1296 .map(|f| Span::new(f.span.start, f.span.start + "fixture".len())),
1297 );
1298 }
1299 spans
1300}
1301
1302pub fn keyword_name_token_spans(source: &str) -> Vec<(Span, bool)> {
1318 use bynk_syntax::lexer::TokenKind;
1319 use bynk_syntax::parser::is_reserved_keyword;
1320 let Ok(tokens) = tokenize(source) else {
1321 return Vec::new();
1322 };
1323 let mut out = Vec::new();
1324 for (i, t) in tokens.iter().enumerate() {
1325 if !is_reserved_keyword(t.kind) {
1326 continue;
1327 }
1328 let prev = i.checked_sub(1).map(|j| &tokens[j]);
1329 let next = tokens.get(i + 1).map(|n| n.kind);
1330 match prev {
1331 Some(p)
1332 if p.kind == TokenKind::Dot && !source[p.span.end..t.span.start].contains('\n') =>
1333 {
1334 out.push((t.span, next == Some(TokenKind::LParen)));
1335 }
1336 Some(p)
1337 if matches!(
1338 p.kind,
1339 TokenKind::LBrace | TokenKind::Comma | TokenKind::LParen
1340 ) && next == Some(TokenKind::Colon) =>
1341 {
1342 out.push((t.span, false));
1343 }
1344 _ => {}
1345 }
1346 }
1347 out
1348}
1349
1350pub fn constraint_token_spans(source: &str) -> Vec<Span> {
1355 let Ok(tokens) = tokenize(source) else {
1356 return Vec::new();
1357 };
1358 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
1359 let Some(unit) = unit else {
1360 return Vec::new();
1361 };
1362 let items: &[CommonsItem] = match &unit {
1363 SourceUnit::Commons(c) => &c.items,
1364 SourceUnit::Context(c) => &c.items,
1365 SourceUnit::Adapter(a) => &a.items,
1366 SourceUnit::Suite(_) => &[],
1367 };
1368 let mut spans = Vec::new();
1369 fn params(tps: &[TypeParam], spans: &mut Vec<Span>) {
1370 for tp in tps {
1371 spans.extend(tp.bounds.iter().map(|b| b.span));
1372 }
1373 }
1374 for item in items {
1375 match item {
1376 CommonsItem::Fn(f) => params(&f.type_params, &mut spans),
1377 CommonsItem::Type(t) => {
1378 params(&t.type_params, &mut spans);
1379 spans.extend(t.derives.iter().map(|d| d.span));
1381 }
1382 CommonsItem::Capability(c) => {
1383 for op in &c.ops {
1384 params(&op.type_params, &mut spans);
1385 }
1386 }
1387 _ => {}
1388 }
1389 if let CommonsItem::Fn(f) = item {
1390 for wb in &f.where_bounds {
1391 spans.extend(wb.bounds.iter().map(|b| b.span));
1392 }
1393 }
1394 }
1395 spans
1396}
1397
1398fn cache_control_of(ann: &Annotation) -> Option<String> {
1413 let mut max_age_secs = None;
1414 let mut scope = "private";
1415 let mut immutable = false;
1416 for arg in &ann.args {
1417 match (arg.label.as_ref().map(|l| l.name.as_str()), &arg.value.kind) {
1418 (Some("maxAge"), ExprKind::DurationLit { millis, .. })
1419 if *millis > 0 && millis % 1000 == 0 =>
1420 {
1421 max_age_secs = Some(millis / 1000);
1422 }
1423 (Some("scope"), ExprKind::Ident(id)) if id.name == "public" => scope = "public",
1424 (Some("immutable"), ExprKind::BoolLit(b)) => immutable = *b,
1425 _ => {}
1426 }
1427 }
1428 let secs = max_age_secs?;
1429 let suffix = if immutable { ", immutable" } else { "" };
1430 Some(format!("{scope}, max-age={secs}{suffix}"))
1431}
1432
1433fn render_handler_annotation_hover(
1438 ann: &Annotation,
1439 handler: &Handler,
1440 service_cap: Option<i64>,
1441) -> String {
1442 let sig = bynk_fmt::annotation_to_string(ann);
1443 if ann.name.name == "cache" {
1444 let emitted = match cache_control_of(ann) {
1445 Some(header) => format!("\n\nEmits `Cache-Control: {header}`."),
1446 None => String::new(),
1447 };
1448 return format!(
1449 "```bynk\n{sig}\n```\n\n\
1450 **`@cache`** — cache this `GET` read. A `GET` returning `Ok` (or a `Raw` body \
1451 of at most 1 MiB) already carries a synthesised weak `ETag`, and `RawTagged` \
1452 carries the handler's own; a matching `If-None-Match` is answered \
1453 `304 Not Modified`. `@cache` adds a `Cache-Control` freshness window on top.\n\n\
1454 - **`maxAge`** — the freshness window, a `Duration` (e.g. `5.minutes`), lowered to \
1455 `Cache-Control: max-age`.\n\
1456 - **`scope`** — `public` or `private` (default `private`; a shared cache stores the \
1457 response only when `public`).\n\
1458 - **`immutable`** — `true` promises the response at this URL never changes, so \
1459 caches do not revalidate it within `maxAge` (default `false`).{emitted}"
1460 );
1461 }
1462 if ann.name.name == "limit" {
1464 return format!(
1465 "```bynk\n{sig}\n```\n\n\
1466 **`@limit`** — cap the request body size on this `POST`/`PUT`/`PATCH` route. A \
1467 request whose body exceeds the `maxBody` byte ceiling is answered `413 Payload Too \
1468 Large`, synthesised before the body is read.\n\n\
1469 - **`maxBody`** — the maximum request body size in bytes, a positive `Int`."
1470 );
1471 }
1472 if ann.name.name == "json" {
1474 let mode = match handler.json_options() {
1475 Some(JsonOptions::Plain) => "`plain` — `Some(v)` is written `v`, `None` is `null`",
1476 Some(JsonOptions::Tagged) => {
1477 "`tagged` — `{\"kind\": \"Some\", \"value\": v}` / `{\"kind\": \"None\"}`"
1478 }
1479 None => "not a valid mode (`bynk.http.json_invalid_arg`)",
1480 };
1481 return format!(
1482 "```bynk\n{sig}\n```\n\n\
1483 **`@json`** — choose how this route's response body writes `Option`, overriding the \
1484 service's `json {{ }}` section. A Bynk client reads either form; plain JSON is what \
1485 `curl | jq` and other non-Bynk clients expect. `Option[Option[T]]` is refused in a \
1486 plain route (`bynk.json.nested_option_plain`).\n\n\
1487 - **`options`** — `tagged` (the default) or `plain`. This route: {mode}."
1488 );
1489 }
1490 if ann.name.name == "raw" {
1492 let cap = match handler.limit_max_body().or(service_cap) {
1493 Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1494 None => "none — a `@raw` route needs one (`bynk.http.raw_body_unbounded`)".to_string(),
1495 };
1496 let content_type = match handler.raw_content_type() {
1497 Some("*/*") => "any".to_string(),
1498 Some(ct) => format!("`{ct}`"),
1499 None => "—".to_string(),
1500 };
1501 return format!(
1502 "```bynk\n{sig}\n```\n\n\
1503 **`@raw`** — take this route's `body: Bytes` as the raw request body: the octets as \
1504 sent, with no JSON and no base64. Type it `Stream[Bytes]` instead to receive it as \
1505 it arrives, read once and counted against the cap as it is read. Any other \
1506 `Content-Type` is answered `415 Unsupported Media Type`.\n\n\
1507 - **`contentType`** — the media type accepted: {content_type}.\n\
1508 - **Effective body cap** — {cap}."
1509 );
1510 }
1511 if ann.name.name == "form" {
1513 let cap = match handler.limit_max_body().or(service_cap) {
1514 Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1515 None => "none (add `@limit` or `limits { maxBody }` to bound it)".to_string(),
1516 };
1517 return format!(
1518 "```bynk\n{sig}\n```\n\n\
1519 **`@form`** — decode this route's `body` record from an \
1520 `application/x-www-form-urlencoded` form, with the same refinements, defaults and \
1521 `Option`s as a JSON body. Any other `Content-Type` is answered `415 Unsupported \
1522 Media Type`; a bad field is a `400` naming `body.<field>`.\n\n\
1523 - **Fields** — a `String`, `Int`, `Bool`, `Decimal`, an enum or a refined or opaque \
1524 type over one, optionally in an `Option` or a `List` (a repeated key). An unchecked \
1525 checkbox sends nothing, so give a `Bool` a default.\n\
1526 - **Empty values** — `name=` is absent for an `Option` or a non-`String` field, and `\"\"` \
1527 for a `String`.\n\
1528 - **Effective body cap** — {cap}."
1529 );
1530 }
1531 if ann.name.name == "multipart" {
1533 let cap = match handler.limit_max_body().or(service_cap) {
1534 Some(bytes) => format!("{bytes} bytes (from `@limit` or the service `limits`)"),
1535 None => "none — a `@multipart` route needs one (`bynk.http.multipart_body_unbounded`)"
1536 .to_string(),
1537 };
1538 return format!(
1539 "```bynk\n{sig}\n```\n\n\
1540 **`@multipart`** — decode this route's `body` record from a `multipart/form-data` \
1541 body, buffered whole under the body cap. Text parts follow the same rules as a \
1542 [`@form`] body; a part with a filename is a `File` (`filename`, `contentType`, \
1543 `bytes`), both client-controlled. Any other `Content-Type` is a `415`, a body \
1544 that is not multipart a `400` `MalformedForm`, and a part over `maxFile` (or more \
1545 than `maxParts`) a `413`.\n\n\
1546 - **Effective body cap** — {cap}."
1547 );
1548 }
1549 format!("```bynk\n{sig}\n```")
1550}
1551
1552fn span_covers(span: Span, offset: usize) -> bool {
1554 span.start <= offset && offset < span.end
1555}
1556
1557fn preceding_ident_span(
1562 tokens: &[bynk_syntax::lexer::Token],
1563 source: &str,
1564 name_span: Span,
1565 kw: &str,
1566) -> Option<Span> {
1567 let idx = tokens
1568 .iter()
1569 .position(|t| t.span.start == name_span.start)?;
1570 let prev = tokens.get(idx.checked_sub(1)?)?;
1571 (source.get(prev.span.start..prev.span.end) == Some(kw)).then_some(prev.span)
1572}
1573
1574fn render_state_hover(sig: &str, contextual_kw: &str) -> String {
1577 let doc = bynk_syntax::keywords::CONTEXTUAL_KEYWORDS
1578 .iter()
1579 .find(|k| k.word == contextual_kw)
1580 .map(|k| k.meaning)
1581 .unwrap_or_default();
1582 format!("```bynk\n{sig}\n```\n\n{doc}")
1583}
1584
1585pub fn describe_self_at(
1596 text: &str,
1597 offset: usize,
1598 expr_types: &[(Span, bynk_check::checker::TyId)],
1599 tys: &bynk_check::checker::Types,
1600) -> Option<String> {
1601 let tokens = tokenize(text).ok()?;
1602 let on_self = tokens.iter().any(|t| {
1603 t.span.start <= offset && offset < t.span.end && &text[t.span.start..t.span.end] == "self"
1604 });
1605 if !on_self {
1606 return None;
1607 }
1608 let ty = bynk_check::expr_types::type_at_offset(expr_types, offset, tys)?;
1609 let display = ty.display(tys);
1610 let name = display
1611 .strip_prefix("__")
1612 .and_then(|s| s.strip_suffix("Self"))
1613 .unwrap_or(&display);
1614 Some(format!("```bynk\nself: {name}\n```"))
1615}
1616
1617pub fn describe_effect_method_at(
1623 text: &str,
1624 offset: usize,
1625 expr_types: &[(Span, bynk_check::checker::TyId)],
1626 tys: &bynk_check::checker::Types,
1627) -> Option<String> {
1628 let tokens = tokenize(text).ok()?;
1629 let tok = tokens.iter().find(|t| {
1630 t.span.start <= offset
1631 && offset < t.span.end
1632 && matches!(
1633 &text[t.span.start..t.span.end],
1634 "within" | "race" | "detach"
1635 )
1636 })?;
1637 let word = &text[tok.span.start..tok.span.end];
1638 let before = text[..tok.span.start].trim_end();
1639 let after = text[tok.span.end..].trim_start();
1640 if !before.ends_with('.') || !after.starts_with('(') {
1641 return None;
1642 }
1643 let dot = before.len() - 1;
1644 let recv = bynk_check::expr_types::type_at_offset(expr_types, dot.checked_sub(1)?, tys)?;
1645 if !matches!(&*tys.get(recv), bynk_check::checker::Ty::Effect(_)) {
1646 return None;
1647 }
1648 if word == "detach" {
1649 return Some(
1650 "```bynk\ndetach() -> Effect[()]\n```\n\n\
1651 Stops waiting for the effect: returns once the effect has been handed to the \
1652 runtime, not once it has finished. The effect is already running (an effect starts \
1653 where its expression is evaluated), so `detach` never starts or delays it.\n\n\
1654 **A failure is reported, never lost.** A fault goes to the platform's exception \
1655 path; an `Err` (when `T` is a `Result`) is logged as one structured record naming \
1656 the site and the error's type and variant, but not its payload. Detaching is \
1657 best-effort: it is not retried, and the platform may cut it short after the \
1658 response.\n\n\
1659 Only where an execution context exists, as `within`: not in an agent handler."
1660 .to_string(),
1661 );
1662 }
1663 if word == "race" {
1664 return Some(
1665 "```bynk\nrace(other: Effect[T]) -> Effect[T]\n```\n\n\
1666 Takes whichever of the two effects succeeds first. A side that faults does not \
1667 win while the other may still succeed; if both fault, the first fault in source \
1668 order is raised, with the other attached as `suppressed`. A same-instant tie goes \
1669 to the receiver.\n\n\
1670 **The loser is not cancelled.** It is handed to the platform's `waitUntil` and \
1671 runs to completion, so its side effects still happen: use `race` for idempotent \
1672 work such as a read, not a write. Use `FetchOptions.timeout` when work must \
1673 actually stop.\n\n\
1674 Only in a service handler's body (lambdas included): an agent handler or a \
1675 function has no execution context to hand the loser to."
1676 .to_string(),
1677 );
1678 }
1679 Some(
1680 "```bynk\nwithin(d: Duration) -> Effect[Result[T, TimedOut]]\n```\n\n\
1681 Bounds how long the effect may take. If it settles within `d` the result is `Ok`; \
1682 if `d` passes first it is `Err(TimedOut { after: d })` and the handler moves on.\n\n\
1683 **The effect is not cancelled.** It is handed to the platform's `waitUntil` and may \
1684 still complete after the handler has returned, so its side effects can still happen. \
1685 Use `FetchOptions.timeout` when the work must actually stop.\n\n\
1686 Only in a service handler's body (lambdas included): an agent handler or a function \
1687 has no execution context to hand the effect to."
1688 .to_string(),
1689 )
1690}
1691
1692pub fn describe_question_at(
1697 text: &str,
1698 offset: usize,
1699 expr_types: &[(Span, bynk_check::checker::TyId)],
1700 tys: &bynk_check::checker::Types,
1701) -> Option<String> {
1702 let tokens = tokenize(text).ok()?;
1703 let tok = tokens.iter().find(|t| {
1704 t.span.start <= offset && offset < t.span.end && &text[t.span.start..t.span.end] == "?"
1705 })?;
1706 let before = text[..tok.span.start].trim_end();
1707 let operand =
1708 bynk_check::expr_types::type_at_offset(expr_types, before.len().checked_sub(1)?, tys)?;
1709 if !matches!(&*tys.get(operand), bynk_check::checker::Ty::Option(_)) {
1710 return None;
1711 }
1712 Some(
1713 "```bynk\n? : None → 404 NotFound\n```\n\n\
1714 On an `Option` in an `HttpResult` handler, `?` yields the value for `Some` and \
1715 answers `404 NotFound` for `None`. That is right for \"the thing you asked for is not \
1716 there\", but a missing or malformed request input is a `400`: write \
1717 `let Some(x) = e else { BadRequest(\"…\") }` to answer another status."
1718 .to_string(),
1719 )
1720}
1721
1722pub fn qualified_callee_at(text: &str, ident_span: Span) -> Option<String> {
1730 let (recv, _) = receiver_segment_at(text, ident_span)?;
1731 if !recv.chars().next()?.is_uppercase() {
1732 return None;
1733 }
1734 let member = text.get(ident_span.start..ident_span.end)?;
1735 Some(format!("{recv}.{member}"))
1736}
1737
1738pub fn describe_firstparty_symbol(name: &str) -> Option<String> {
1746 bynk_check::firstparty::FIRSTPARTY_SOURCES
1749 .iter()
1750 .find_map(|(unit, src)| {
1751 describe_symbol(src, name).map(|d| d + &firstparty_notes(unit, name))
1752 })
1753}
1754
1755pub fn firstparty_notes(unit: &str, name: &str) -> String {
1760 let mut out = String::new();
1761 let path = format!("{unit}.{name}");
1762 if bynk_check::firstparty::stability_of(&path)
1763 == Some(bynk_check::firstparty::Stability::Experimental)
1764 {
1765 out.push_str(&format!(
1766 "\n\n**Experimental**: it may change or disappear in any release. To use it, add `\"{path}\"` to `[unstable] allow` in `bynk.toml`."
1767 ));
1768 }
1769 if bynk_check::firstparty::is_extensible(unit, name) {
1770 out.push_str(
1771 "\n\n**Extensible**: it may gain variants in a minor release, so a `match` on it needs a wildcard arm.",
1772 );
1773 }
1774 out
1775}
1776
1777pub fn unit_reference_spans(source: &str) -> Vec<(String, Span)> {
1782 let Ok(tokens) = tokenize(source) else {
1783 return Vec::new();
1784 };
1785 let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
1786 return Vec::new();
1787 };
1788 let mut out: Vec<(String, Span)> = Vec::new();
1789 let (uses, consumes): (&[UsesDecl], &[ConsumesDecl]) = match &unit {
1792 SourceUnit::Commons(c) => (&c.uses, &[]),
1793 SourceUnit::Context(c) => (&c.uses, &c.consumes),
1794 SourceUnit::Adapter(a) => (&a.uses, &a.consumes),
1795 SourceUnit::Suite(s) => {
1796 out.push((s.target.joined(), s.target.span));
1797 (&s.uses, &[])
1798 }
1799 };
1800 for u in uses {
1801 out.push((u.target.joined(), u.target.span));
1802 }
1803 for c in consumes {
1804 out.push((c.target.joined(), c.target.span));
1805 }
1806 out
1807}
1808
1809pub fn unit_name_at(source: &str, offset: usize) -> Option<String> {
1818 let own = own_declaration_name(source);
1819 own.into_iter()
1820 .chain(unit_reference_spans(source))
1821 .find(|(_, span)| span.start <= offset && offset <= span.end)
1822 .map(|(name, _)| name)
1823}
1824
1825pub fn describe_unit<'s>(sources: impl IntoIterator<Item = &'s str>, name: &str) -> Option<String> {
1837 let mut kind: Option<&'static str> = None;
1838 let mut doc: Option<String> = None;
1839 for source in sources {
1840 let Ok(tokens) = tokenize(source) else {
1841 continue;
1842 };
1843 let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
1844 continue;
1845 };
1846 if matches!(unit, SourceUnit::Suite(_)) || unit.name().joined() != name {
1847 continue;
1848 }
1849 kind.get_or_insert(unit.kind_name());
1850 if doc.is_none() {
1851 doc = unit.module_doc().map(str::to_string);
1852 }
1853 if doc.is_some() {
1854 break;
1855 }
1856 }
1857 let kind = kind?;
1858 let mut out = format!("```bynk\n{kind} {name}\n```\n");
1859 if let Some(doc) = doc {
1860 out.push('\n');
1861 out.push_str(&doc);
1862 out.push('\n');
1863 }
1864 Some(out)
1865}
1866
1867pub fn describe_unit_at<'s>(
1873 text: &'s str,
1874 offset: usize,
1875 others: impl IntoIterator<Item = &'s str>,
1876) -> Option<String> {
1877 let name = unit_name_at(text, offset)?;
1878 let firstparty = bynk_check::firstparty::FIRSTPARTY_SOURCES
1879 .iter()
1880 .map(|(_, src)| *src);
1881 describe_unit(std::iter::once(text).chain(others).chain(firstparty), &name)
1882}
1883
1884#[derive(Debug, Clone, PartialEq, Eq)]
1891pub struct DocLinkCandidate {
1892 pub name: String,
1893 pub span: std::ops::Range<usize>,
1894 pub display: String,
1895}
1896
1897fn is_doc_link_name(s: &str) -> bool {
1902 fn is_ident(part: &str) -> bool {
1903 let mut chars = part.chars();
1904 matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_')
1905 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1906 }
1907 s.split('.').all(is_ident)
1908}
1909
1910fn doc_link_prepass(text: &str) -> (Vec<(usize, usize)>, std::collections::HashSet<String>) {
1919 let mut fenced = Vec::new();
1920 let mut defined = std::collections::HashSet::new();
1921 let mut in_fence = false;
1922 let mut fence_start = 0usize;
1923 let mut pos = 0usize;
1924 loop {
1925 let line_end = text[pos..]
1926 .find('\n')
1927 .map(|i| pos + i + 1)
1928 .unwrap_or(text.len());
1929 let line = &text[pos..line_end];
1930 let trimmed = line.trim_start();
1931 if trimmed.starts_with("```") {
1932 if in_fence {
1933 fenced.push((fence_start, line_end));
1934 in_fence = false;
1935 } else {
1936 fence_start = pos;
1937 in_fence = true;
1938 }
1939 } else if !in_fence {
1940 let indent = line.len() - trimmed.len();
1943 if indent <= 3
1944 && let Some(rest) = trimmed.strip_prefix('[')
1945 && let Some(close) = rest.find(']')
1946 {
1947 let label = &rest[..close];
1948 if let Some(after_colon) = rest[close + 1..].strip_prefix(':')
1949 && !label.is_empty()
1950 && !after_colon.trim().is_empty()
1951 {
1952 defined.insert(label.to_string());
1953 }
1954 }
1955 }
1956 if line_end >= text.len() {
1957 break;
1958 }
1959 pos = line_end;
1960 }
1961 if in_fence {
1962 fenced.push((fence_start, text.len()));
1963 }
1964 (fenced, defined)
1965}
1966
1967fn scan_bracket_candidate(
1973 text: &str,
1974 start: usize,
1975 defined: &std::collections::HashSet<String>,
1976) -> Option<DocLinkCandidate> {
1977 let bytes = text.as_bytes();
1978 debug_assert_eq!(bytes[start], b'[');
1979 if bytes.get(start + 1) == Some(&b'`') {
1981 let inner_start = start + 2;
1982 let close_tick = text[inner_start..].find('`')? + inner_start;
1983 if bytes.get(close_tick + 1) != Some(&b']') {
1984 return None;
1985 }
1986 let name = &text[inner_start..close_tick];
1987 if !is_doc_link_name(name) || defined.contains(name) {
1988 return None;
1989 }
1990 return Some(DocLinkCandidate {
1991 name: name.to_string(),
1992 span: start..close_tick + 2,
1993 display: text[start + 1..close_tick + 1].to_string(),
1994 });
1995 }
1996 let inner_start = start + 1;
1997 let close = text[inner_start..].find(']')? + inner_start;
1998 let inner = &text[inner_start..close];
1999 let after = close + 1;
2000 match bytes.get(after) {
2001 Some(b'(') => None,
2003 Some(b':') => None,
2006 Some(b'[') => {
2008 let label_start = after + 1;
2009 let label_close = text[label_start..].find(']')? + label_start;
2010 let label = &text[label_start..label_close];
2011 if label.is_empty() || !is_doc_link_name(label) || defined.contains(label) {
2013 return None;
2014 }
2015 Some(DocLinkCandidate {
2016 name: label.to_string(),
2017 span: start..label_close + 1,
2018 display: inner.to_string(),
2019 })
2020 }
2021 _ => {
2023 if !is_doc_link_name(inner) || defined.contains(inner) {
2024 return None;
2025 }
2026 Some(DocLinkCandidate {
2027 name: inner.to_string(),
2028 span: start..after,
2029 display: inner.to_string(),
2030 })
2031 }
2032 }
2033}
2034
2035pub fn scan_doc_link_candidates(text: &str) -> Vec<DocLinkCandidate> {
2040 let (fenced, defined) = doc_link_prepass(text);
2041 let in_fenced = |i: usize| fenced.iter().any(|&(s, e)| i >= s && i < e);
2042 let bytes = text.as_bytes();
2043 let mut out = Vec::new();
2044 let mut i = 0usize;
2045 while i < bytes.len() {
2046 if bytes[i] != b'[' || in_fenced(i) {
2047 i += 1;
2048 continue;
2049 }
2050 match scan_bracket_candidate(text, i, &defined) {
2051 Some(cand) => {
2052 i = cand.span.end;
2053 out.push(cand);
2054 }
2055 None => i += 1,
2056 }
2057 }
2058 out
2059}
2060
2061pub fn doc_link_spans(source: &str) -> Vec<(String, Span)> {
2071 doc_link_spans_attached(source)
2072 .into_iter()
2073 .map(|l| (l.name, l.span))
2074 .collect()
2075}
2076
2077#[derive(Debug, Clone, PartialEq, Eq)]
2082pub struct DocLinkSpan {
2083 pub name: String,
2084 pub span: Span,
2085 pub attached: Option<usize>,
2086}
2087
2088pub fn doc_link_spans_attached(source: &str) -> Vec<DocLinkSpan> {
2090 let Ok(tokens) = tokenize(source) else {
2091 return Vec::new();
2092 };
2093 let mut out = Vec::new();
2094 for (i, t) in tokens.iter().enumerate() {
2095 let range = match t.kind {
2097 bynk_syntax::lexer::TokenKind::DocBlock => {
2098 bynk_syntax::lexer::doc_block_body_range(source, t.span)
2099 }
2100 bynk_syntax::lexer::TokenKind::DocLine => {
2101 Some(bynk_syntax::lexer::doc_line_text_range(source, t.span))
2102 }
2103 _ => None,
2104 };
2105 let Some(range) = range else {
2106 continue;
2107 };
2108 let attached = tokens[i + 1..]
2112 .iter()
2113 .position(|n| n.kind == bynk_syntax::lexer::TokenKind::Ident)
2114 .map(|p| {
2115 let rest = &tokens[i + 1 + p..];
2116 match rest {
2117 [_, dot, name, ..]
2118 if dot.kind == bynk_syntax::lexer::TokenKind::Dot
2119 && name.kind == bynk_syntax::lexer::TokenKind::Ident
2120 && p > 0
2121 && tokens[i + p].kind == bynk_syntax::lexer::TokenKind::Fn =>
2122 {
2123 name.span.start
2124 }
2125 _ => rest[0].span.start,
2126 }
2127 });
2128 for cand in scan_doc_link_candidates(&source[range.clone()]) {
2129 out.push(DocLinkSpan {
2130 name: cand.name,
2131 span: Span::new(range.start + cand.span.start, range.start + cand.span.end),
2132 attached,
2133 });
2134 }
2135 }
2136 out
2137}
2138
2139pub fn doc_link_unit(source: &str) -> Option<String> {
2143 let tokens = tokenize(source).ok()?;
2144 let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
2145 return None;
2146 };
2147 Some(unit.name().joined())
2148}
2149
2150#[derive(Debug, Clone, PartialEq, Eq)]
2152pub struct DocLinkCompletionContext {
2153 pub owner: Option<String>,
2155 pub partial: String,
2157 pub replace_start: usize,
2159 pub replace_end: usize,
2163 pub closed: bool,
2165 pub attached: Option<usize>,
2168}
2169
2170pub fn doc_link_context(source: &str, offset: usize) -> Option<DocLinkCompletionContext> {
2177 let tokens = tokenize(source).ok()?;
2178 let (range, attached) = tokens.iter().enumerate().find_map(|(i, t)| {
2179 let range = match t.kind {
2180 bynk_syntax::lexer::TokenKind::DocBlock => {
2181 bynk_syntax::lexer::doc_block_body_range(source, t.span)
2182 }
2183 bynk_syntax::lexer::TokenKind::DocLine => {
2184 Some(bynk_syntax::lexer::doc_line_text_range(source, t.span))
2185 }
2186 _ => None,
2187 }?;
2188 (range.start <= offset && offset <= range.end).then(|| {
2189 let attached = tokens[i + 1..]
2190 .iter()
2191 .find(|n| n.kind == bynk_syntax::lexer::TokenKind::Ident)
2192 .map(|n| n.span.start);
2193 (range, attached)
2194 })
2195 })?;
2196 let body = &source[range.start..range.end];
2197 let (fenced, _) = doc_link_prepass(body);
2198 let rel = offset - range.start;
2199 if fenced.iter().any(|&(s, e)| rel >= s && rel < e) {
2200 return None;
2201 }
2202 let before = &body[..rel];
2203 let line_start = before.rfind('\n').map_or(0, |i| i + 1);
2204 let open = before[line_start..].rfind('[')? + line_start;
2205 let typed = &before[open + 1..];
2206 if !typed
2207 .chars()
2208 .all(|c| c.is_alphanumeric() || c == '_' || c == '.')
2209 {
2210 return None;
2211 }
2212 let (owner, partial) = match typed.rfind('.') {
2213 Some(i) if i > 0 => (Some(typed[..i].to_string()), &typed[i + 1..]),
2214 Some(_) => return None,
2215 None => (None, typed),
2216 };
2217 let tail = source[offset..range.end]
2218 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
2219 .unwrap_or(range.end - offset);
2220 let replace_end = offset + tail;
2221 Some(DocLinkCompletionContext {
2222 owner,
2223 partial: partial.to_string(),
2224 replace_start: offset - partial.len(),
2225 replace_end,
2226 closed: source[replace_end..].starts_with(']'),
2227 attached,
2228 })
2229}
2230
2231pub fn own_declaration_name(source: &str) -> Option<(String, Span)> {
2236 let tokens = tokenize(source).ok()?;
2237 let (Some(unit), _) = parse_unit_with_recovery(&tokens, source) else {
2238 return None;
2239 };
2240 if matches!(unit, SourceUnit::Suite(_)) {
2241 return None;
2242 }
2243 let name = unit.name();
2244 Some((name.joined(), name.span))
2245}
2246
2247fn describe_item(item: &CommonsItem, name: &str) -> Option<String> {
2248 match item {
2249 CommonsItem::Type(t) if t.name.name == name => Some(describe_type(t)),
2250 CommonsItem::Fn(f) if matches!(f.name, FnName::Free(_)) && f.name.ident().name == name => {
2257 Some(describe_fn(f))
2258 }
2259 CommonsItem::Capability(c) if c.name.name == name => Some(describe_capability(c)),
2260 CommonsItem::Service(s) if s.name.name == name => Some(describe_service(s)),
2261 CommonsItem::Agent(a) if a.name.name == name => Some(describe_agent(a)),
2262 CommonsItem::Provider(p) if p.provider_name.name == name => Some(describe_provider(p)),
2263 CommonsItem::Actor(a) if a.name.name == name => Some(describe_actor(a)),
2268 CommonsItem::Messages(m) if m.tag == name => Some(describe_messages(m)),
2272 CommonsItem::Asset(a) if a.name.name == name => Some(describe_asset(a)),
2274 CommonsItem::Embed(e) if e.name.name == name => Some(describe_embed(e)),
2276 CommonsItem::Const(c) if c.name.name == name => Some(describe_const(c)),
2278 CommonsItem::Event(e) if e.name.name == name => Some(describe_event(e)),
2283 CommonsItem::Type(t) => {
2290 let (owner, field) = name.rsplit_once('.')?;
2291 if t.name.name != owner {
2292 return None;
2293 }
2294 let TypeBody::Record(r) = &t.body else {
2295 return None;
2296 };
2297 r.fields
2298 .iter()
2299 .find(|f| f.name.name == field)
2300 .map(|f| describe_record_field(t, f))
2301 }
2302 CommonsItem::Event(e) => {
2307 let (owner, field) = name.rsplit_once('.')?;
2308 if e.name.name != owner {
2309 return None;
2310 }
2311 let synthetic = e.as_type_decl();
2312 e.body
2313 .fields
2314 .iter()
2315 .find(|f| f.name.name == field)
2316 .map(|f| describe_record_field(&synthetic, f))
2317 }
2318 CommonsItem::Fn(f) => (f.name.display() == name).then(|| describe_fn(f)),
2323 CommonsItem::Capability(c) => {
2325 let (owner, op) = name.rsplit_once('.')?;
2326 if c.name.name != owner {
2327 return None;
2328 }
2329 c.ops
2330 .iter()
2331 .find(|o| o.name.name == op)
2332 .map(|o| describe_capability_op(c, o))
2333 }
2334 CommonsItem::Agent(a) => {
2338 let (owner, handler) = name.rsplit_once('.')?;
2339 if a.name.name != owner {
2340 return None;
2341 }
2342 a.handlers
2343 .iter()
2344 .find(|h| h.method_name.as_ref().is_some_and(|n| n.name == handler))
2345 .map(|h| describe_agent_handler(a, h, handler))
2346 }
2347 _ => None,
2348 }
2349}
2350
2351pub(crate) fn describe_actor(a: &ActorDecl) -> String {
2359 let mut out = String::from("```bynk\n");
2360 match &a.refinement {
2361 Some(r) => out.push_str(&format!(
2363 "actor {} = {} where {}",
2364 a.name.name,
2365 r.base.name,
2366 bynk_fmt::expr_to_string(&r.predicate)
2367 )),
2368 None => {
2369 let auth = a.auth.as_ref().map_or("None", |i| i.name.as_str());
2371 out.push_str(&format!("actor {} {{ auth = {auth}", a.name.name));
2372 if !a.auth_config.is_empty() {
2373 let args: Vec<String> = a
2374 .auth_config
2375 .iter()
2376 .map(|arg| match &arg.value {
2377 SchemeArgValue::Str(s) => {
2382 format!("{} = \"{}\"", arg.key.name, bynk_fmt::escape_string(s))
2383 }
2384 SchemeArgValue::Int(n) => format!("{} = {n}", arg.key.name),
2385 SchemeArgValue::Duration { value, unit, .. } => {
2386 format!("{} = {value}.{}", arg.key.name, unit.name())
2387 }
2388 SchemeArgValue::Ident(id) => format!("{} = {id}", arg.key.name),
2389 })
2390 .collect();
2391 out.push_str(&format!("({})", args.join(", ")));
2392 }
2393 if let Some(id) = &a.identity {
2394 out.push_str(&format!(", identity = {}", type_ref_str(id)));
2395 }
2396 out.push_str(" }");
2397 }
2398 }
2399 out.push_str("\n```\n");
2400 if let Some(doc) = &a.documentation {
2401 out.push('\n');
2402 out.push_str(doc);
2403 out.push('\n');
2404 }
2405 out
2406}
2407
2408fn capability_op_type_params_str(op: &CapabilityOp) -> String {
2412 if op.type_params.is_empty() {
2413 return String::new();
2414 }
2415 let names: Vec<&str> = op
2416 .type_params
2417 .iter()
2418 .map(|tp| tp.name.name.as_str())
2419 .collect();
2420 format!("[{}]", names.join(", "))
2421}
2422
2423pub(crate) fn describe_capability_op(c: &CapabilityDecl, op: &CapabilityOp) -> String {
2427 let params: Vec<String> = op
2428 .params
2429 .iter()
2430 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2431 .collect();
2432 let mut out = format!(
2433 "```bynk\nfn {}{}({}) -> {}\n```\n\nAn operation of capability `{}`.\n",
2434 op.name.name,
2435 capability_op_type_params_str(op),
2436 params.join(", "),
2437 type_ref_str(&op.return_type),
2438 c.name.name
2439 );
2440 if let Some(policy) = bynk_check::checker::codable::typed_read_policy(op) {
2443 out.push_str(match policy {
2444 bynk_check::checker::codable::ReplyPolicy::Miss => {
2445 "\nA typed read: the type argument is explicit, and a reply that does not decode is a miss (the call returns `None` and a warning is logged).\n"
2446 }
2447 bynk_check::checker::codable::ReplyPolicy::Fault => {
2448 "\nA typed read: the type argument is explicit, and a reply that does not decode faults.\n"
2449 }
2450 });
2451 }
2452 if let Some(doc) = &op.documentation {
2453 out.push('\n');
2454 out.push_str(doc);
2455 out.push('\n');
2456 }
2457 out
2458}
2459
2460pub(crate) fn describe_agent_handler(a: &AgentDecl, h: &Handler, handler_name: &str) -> String {
2463 let params: Vec<String> = h
2464 .params
2465 .iter()
2466 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2467 .collect();
2468 let mut out = format!(
2469 "```bynk\nfn {}({}) -> {}\n```\n\nA handler of agent `{}`.\n",
2470 handler_name,
2471 params.join(", "),
2472 type_ref_str(&h.return_type),
2473 a.name.name
2474 );
2475 if let Some(doc) = &h.documentation {
2476 out.push('\n');
2477 out.push_str(doc);
2478 out.push('\n');
2479 }
2480 out
2481}
2482
2483pub(crate) fn describe_service_handler(s: &ServiceDecl, h: &Handler) -> String {
2492 let params: Vec<String> = h
2493 .params
2494 .iter()
2495 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2496 .collect();
2497 let mut out = format!(
2498 "```bynk\n{}({}) -> {}\n```\n\nA handler of service `{}`.\n",
2499 handler_line(h),
2500 params.join(", "),
2501 type_ref_str(&h.return_type),
2502 s.name.name
2503 );
2504 if let Some(doc) = &h.documentation {
2505 out.push('\n');
2506 out.push_str(doc);
2507 out.push('\n');
2508 }
2509 out
2510}
2511
2512pub(crate) fn describe_record_field(t: &TypeDecl, f: &RecordField) -> String {
2519 let mut sig = format!("{}: {}", f.name.name, type_ref_str(&f.type_ref));
2520 if let Some(r) = &f.refinement {
2521 sig.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2522 }
2523 if let Some(init) = &f.init {
2527 sig.push_str(&format!(" = {}", bynk_fmt::expr_to_string(init)));
2528 }
2529 format!(
2530 "```bynk\n{sig}\n```\n\n{}",
2531 member_prose(&f.documentation, || format!(
2532 "A field of `{}`.",
2533 t.name.name
2534 ))
2535 )
2536}
2537
2538fn member_prose(doc: &Option<Doc>, fallback: impl FnOnce() -> String) -> String {
2541 match doc {
2542 Some(d) => d.trim_end().to_string(),
2543 None => fallback(),
2544 }
2545}
2546
2547pub(crate) fn describe_variant(t: &TypeDecl, v: &Variant) -> String {
2551 let mut sig = format!("| {}", v.name.name);
2552 if !v.payload.is_empty() {
2553 let parts: Vec<String> = v
2554 .payload
2555 .iter()
2556 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2557 .collect();
2558 sig.push_str(&format!("({})", parts.join(", ")));
2559 }
2560 let mut out = format!(
2561 "```bynk\n{sig}\n```\n\n{}",
2562 member_prose(&v.documentation, || format!(
2563 "A variant of `{}`.",
2564 t.name.name
2565 ))
2566 );
2567 for p in &v.payload {
2568 if let Some(doc) = &p.documentation {
2569 out.push_str(&format!("\n\n`{}`: {}", p.name.name, doc.trim_end()));
2570 }
2571 }
2572 out
2573}
2574
2575pub(crate) fn describe_variant_field(t: &TypeDecl, v: &Variant, p: &VariantField) -> String {
2578 format!(
2579 "```bynk\n{}: {}\n```\n\n{}",
2580 p.name.name,
2581 type_ref_str(&p.type_ref),
2582 member_prose(&p.documentation, || format!(
2583 "A field of `{}.{}`.",
2584 t.name.name, v.name.name
2585 ))
2586 )
2587}
2588
2589fn with_sum_variants<R>(
2591 source: &str,
2592 mut f: impl FnMut(&TypeDecl, &Variant) -> Option<R>,
2593) -> Option<R> {
2594 let tokens = tokenize(source).ok()?;
2595 let (unit, _errs) = parse_unit_with_recovery(&tokens, source);
2596 let items: &[CommonsItem] = match unit.as_ref()? {
2597 SourceUnit::Commons(c) => &c.items,
2598 SourceUnit::Context(c) => &c.items,
2599 SourceUnit::Adapter(a) => &a.items,
2600 SourceUnit::Suite(_) => &[],
2601 };
2602 for item in items {
2603 if let CommonsItem::Type(t) = item
2604 && let TypeBody::Sum(s) = &t.body
2605 {
2606 for v in &s.variants {
2607 if let Some(r) = f(t, v) {
2608 return Some(r);
2609 }
2610 }
2611 }
2612 }
2613 None
2614}
2615
2616pub fn describe_variant_key(source: &str, key: &str) -> Option<String> {
2619 let (owner, name) = key.rsplit_once('.')?;
2620 with_sum_variants(source, |t, v| {
2621 (t.name.name == owner && v.name.name == name).then(|| describe_variant(t, v))
2622 })
2623}
2624
2625pub fn describe_variant_named(source: &str, name: &str) -> Option<String> {
2630 let mut found: Vec<String> = Vec::new();
2631 with_sum_variants::<()>(source, |t, v| {
2632 if v.name.name == name {
2633 found.push(describe_variant(t, v));
2634 }
2635 None
2636 });
2637 (found.len() == 1).then(|| found.remove(0))
2638}
2639
2640pub(crate) fn describe_type(t: &TypeDecl) -> String {
2641 let mut out = String::new();
2642 out.push_str("```bynk\n");
2643 let params = if t.type_params.is_empty() {
2645 String::new()
2646 } else {
2647 let names: Vec<String> = t
2648 .type_params
2649 .iter()
2650 .map(|tp| bound_str(&tp.name.name, &tp.bounds))
2651 .collect();
2652 format!("[{}]", names.join(", "))
2653 };
2654 if t.private.is_some() {
2656 out.push_str("private ");
2657 }
2658 out.push_str(&format!("type {}{} = ", t.name.name, params));
2659 match &t.body {
2660 TypeBody::Refined {
2663 base, refinement, ..
2664 } => {
2665 out.push_str(base.name());
2666 if let Some(r) = refinement {
2667 out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2668 }
2669 }
2670 TypeBody::Opaque {
2671 base, refinement, ..
2672 } => {
2673 out.push_str(&format!("opaque {}", base.name()));
2674 if let Some(r) = refinement {
2675 out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2676 }
2677 }
2678 TypeBody::Record(r) => {
2680 if r.fields.is_empty() {
2681 out.push_str("{}");
2682 } else {
2683 out.push_str("{\n");
2684 for f in &r.fields {
2685 out.push_str(&format!("\t{}: {}", f.name.name, type_ref_str(&f.type_ref)));
2686 if let Some(r) = &f.refinement {
2687 out.push_str(&format!(" where {}", bynk_fmt::refinement_to_string(r)));
2688 }
2689 if let Some(init) = &f.init {
2693 out.push_str(&format!(" = {}", bynk_fmt::expr_to_string(init)));
2694 }
2695 out.push_str(",\n");
2696 }
2697 out.push('}');
2698 }
2699 }
2700 TypeBody::Sum(s) => {
2702 out.push_str("enum {\n");
2703 for v in &s.variants {
2704 out.push_str(&format!("\t{}", v.name.name));
2705 if !v.payload.is_empty() {
2706 let parts: Vec<String> = v
2707 .payload
2708 .iter()
2709 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2710 .collect();
2711 out.push_str(&format!("({})", parts.join(", ")));
2712 }
2713 out.push_str(",\n");
2714 }
2715 out.push('}');
2716 }
2717 }
2718 if !t.derives.is_empty() {
2720 let names: Vec<&str> = t.derives.iter().map(|d| d.name.as_str()).collect();
2721 out.push_str(&format!(" derives {}", names.join(" + ")));
2722 }
2723 out.push_str("\n```\n");
2724 if let Some(doc) = &t.documentation {
2725 out.push('\n');
2726 out.push_str(doc);
2727 out.push('\n');
2728 }
2729 out
2730}
2731
2732fn describe_event(e: &EventDecl) -> String {
2740 let base = describe_type(&e.as_type_decl());
2741 if e.annotations.is_empty() {
2742 return base;
2743 }
2744 let annotations: String = e
2745 .annotations
2746 .iter()
2747 .map(|a| format!(" {}", bynk_fmt::annotation_to_string(a)))
2748 .collect();
2749 let from = format!("type {} = ", e.name.name);
2750 let to = format!("type {}{annotations} = ", e.name.name);
2751 base.replacen(&from, &to, 1)
2752}
2753
2754pub(crate) fn fn_type_params_str(f: &FnDecl) -> String {
2757 if f.type_params.is_empty() {
2758 return String::new();
2759 }
2760 let ps: Vec<String> = f
2761 .type_params
2762 .iter()
2763 .map(|tp| bound_str(&tp.name.name, &tp.bounds))
2764 .collect();
2765 format!("[{}]", ps.join(", "))
2766}
2767
2768pub(crate) fn fn_given_str(f: &FnDecl) -> String {
2771 if f.given.is_empty() {
2772 return String::new();
2773 }
2774 let names: Vec<String> = f.given.iter().map(|g| g.display_name()).collect();
2775 format!(" given {}", names.join(", "))
2776}
2777
2778pub(crate) fn fn_where_str(f: &FnDecl) -> String {
2780 if f.where_bounds.is_empty() {
2781 return String::new();
2782 }
2783 let ps: Vec<String> = f
2784 .where_bounds
2785 .iter()
2786 .map(|wb| bound_str(&wb.param.name, &wb.bounds))
2787 .collect();
2788 format!(" where {}", ps.join(", "))
2789}
2790
2791fn bound_str(name: &str, bounds: &[Ident]) -> String {
2792 if bounds.is_empty() {
2793 return name.to_string();
2794 }
2795 let names: Vec<&str> = bounds.iter().map(|b| b.name.as_str()).collect();
2796 format!("{name}: {}", names.join(" + "))
2797}
2798
2799pub(crate) fn describe_fn(f: &FnDecl) -> String {
2800 let mut out = String::new();
2801 out.push_str("```bynk\n");
2802 if f.private.is_some() {
2804 out.push_str("private ");
2805 }
2806 out.push_str("fn ");
2807 out.push_str(&f.name.display());
2808 out.push_str(&fn_type_params_str(f));
2809 out.push('(');
2810 let mut parts: Vec<String> = Vec::new();
2811 if f.has_self {
2812 parts.push("self".into());
2813 }
2814 for p in &f.params {
2815 parts.push(format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)));
2816 }
2817 out.push_str(&parts.join(", "));
2818 out.push_str(") -> ");
2819 out.push_str(&type_ref_str(&f.return_type));
2820 out.push_str(&fn_given_str(f));
2821 out.push_str(&fn_where_str(f));
2822 for c in &f.requires {
2825 out.push_str(&format!(
2826 "\n\trequires {}: {}",
2827 c.name.name,
2828 bynk_fmt::expr_to_string(&c.predicate)
2829 ));
2830 }
2831 for c in &f.ensures {
2832 out.push_str(&format!(
2833 "\n\tensures {}: {}",
2834 c.name.name,
2835 bynk_fmt::expr_to_string(&c.predicate)
2836 ));
2837 }
2838 out.push_str("\n```\n");
2839 if let Some(doc) = &f.documentation {
2840 out.push('\n');
2841 out.push_str(doc);
2842 out.push('\n');
2843 }
2844 out
2845}
2846
2847pub(crate) fn describe_capability(c: &CapabilityDecl) -> String {
2848 let mut out = String::new();
2849 if c.derived.is_some() {
2851 return describe_derived_capability(c, None, None);
2852 }
2853 out.push_str("```bynk\ncapability ");
2854 out.push_str(&c.name.name);
2855 out.push_str(" {\n");
2856 for op in &c.ops {
2857 out.push_str("\tfn ");
2858 out.push_str(&op.name.name);
2859 out.push_str(&capability_op_type_params_str(op));
2860 out.push('(');
2861 let parts: Vec<String> = op
2862 .params
2863 .iter()
2864 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2865 .collect();
2866 out.push_str(&parts.join(", "));
2867 out.push_str(") -> ");
2868 out.push_str(&type_ref_str(&op.return_type));
2869 out.push('\n');
2870 }
2871 out.push_str("}\n```\n");
2872 if let Some(doc) = &c.documentation {
2873 out.push('\n');
2874 out.push_str(doc);
2875 out.push('\n');
2876 }
2877 out
2878}
2879
2880pub(crate) fn describe_derived_capability(
2884 c: &CapabilityDecl,
2885 base_unit: Option<&str>,
2886 base: Option<&CapabilityDecl>,
2887) -> String {
2888 let Some(d) = &c.derived else {
2889 return describe_capability(c);
2890 };
2891 let mut out = format!("```bynk\ncapability {} = {}", c.name.name, d.base.name);
2892 for a in &d.annotations {
2893 out.push_str(" @");
2894 out.push_str(&a.name.name);
2895 }
2896 let from = base_unit.map_or(String::new(), |u| format!(" (`{u}`)"));
2897 let what = if d.base.name == "EdgeCache" {
2900 "this context's Worker's edge cache"
2901 } else {
2902 "its own storage"
2903 };
2904 out.push_str(&format!(
2905 "\n```\n\nA distinct instance of `{}`{from}: {what}, with `{}`'s operations",
2906 d.base.name, d.base.name
2907 ));
2908 match base {
2909 Some(b) if !b.ops.is_empty() => {
2910 out.push_str(":\n\n```bynk\n");
2911 for op in &b.ops {
2912 let params: Vec<String> = op
2913 .params
2914 .iter()
2915 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2916 .collect();
2917 out.push_str(&format!(
2918 "fn {}{}({}) -> {}\n",
2919 op.name.name,
2920 capability_op_type_params_str(op),
2921 params.join(", "),
2922 type_ref_str(&op.return_type)
2923 ));
2924 }
2925 out.push_str("```\n");
2926 }
2927 _ => out.push_str(".\n"),
2928 }
2929 if d.base.name == "RateLimit" {
2931 let number = |name: &str| {
2932 d.annotations
2933 .iter()
2934 .find(|a| a.name.name == name)
2935 .and_then(|a| a.args.first())
2936 .and_then(|arg| match &arg.value.kind {
2937 ExprKind::IntLit { value, .. } => Some(*value),
2938 ExprKind::DurationLit { millis, .. } => Some(millis / 1000),
2939 _ => None,
2940 })
2941 };
2942 if let (Some(limit), Some(period)) = (number("limit"), number("period")) {
2943 out.push_str(&format!(
2944 "\nEmits `[[ratelimits]]` with `simple = {{ limit = {limit}, period = {period} }}`: {limit} calls per key every {period} seconds. Counting is approximate (per Cloudflare location, eventually consistent).\n"
2945 ));
2946 }
2947 }
2948 if d.base.name == "Queue"
2950 && let Some(queue) = d
2951 .annotations
2952 .iter()
2953 .find(|a| a.name.name == "name")
2954 .and_then(|a| a.args.first())
2955 .and_then(|arg| match &arg.value.kind {
2956 ExprKind::StrLit(s) => Some(s.clone()),
2957 _ => None,
2958 })
2959 {
2960 out.push_str(&format!(
2961 "\nEmits `[[queues.producers]]` sending to queue `{queue}` (environment-qualified by `bynk deploy`). Bodies are JSON text, normally `Json.encode(value)`.\n"
2962 ));
2963 }
2964 if d.base.name == "Analytics" {
2966 out.push_str("\nEmits `[[analytics_engine_datasets]]`: the dataset is named for the context and the capability in snake case (`shop.cart`'s `Signups` writes to `shop_cart_signups`), environment-qualified by `bynk deploy`, and created on the first write.\n");
2967 }
2968 if d.base.name == "D1" {
2970 out.push_str("\nEmits `[[d1_databases]]`: the database is named for the context and the capability (`shop.cart`'s `Orders` is `shop-cart-orders`), environment-qualified, created by `bynk deploy`, which records its id.\n");
2971 }
2972 if d.base.name == "StoredSecret" {
2974 out.push_str("\nEmits `[[secrets_store_secrets]]`: a distinct instance of `StoredSecret`, reading the secret in the Secrets Store the declaration names. `bynk deploy` links it (it resolves the store's id and checks the secret exists, and creates neither) and fails when either is missing.\n");
2975 }
2976 if d.base.name == "AiSearch" {
2978 out.push_str("\nEmits `[[ai_search]]`: a distinct instance of `AiSearch`, querying the AI Search instance `@instance` names, in every environment. `bynk deploy` links it (it looks the instance up and records it, and creates nothing) and fails when it is missing; `bynk dev` proxies it to the deployed instance.\n");
2979 }
2980 if d.base.name == "MtlsCertificate" {
2982 out.push_str("\nEmits `[[mtls_certificates]]`: a distinct instance of `MtlsCertificate`, whose `send` presents the account's client certificate `@certificate` names to the origin the URL names, in every environment. `bynk deploy` links it by name and never uploads it: the private key never reaches Bynk. `bynk dev` runs it on Cloudflare, once you allow it with `[dev] mtls`.\n");
2983 }
2984 if d.base.name == "Email" {
2986 out.push_str("\nEmits `[[send_email]]`, keyed by `name`, with the instance's `@to`, `@allowedRecipients` and `@allowedSenders` as `destination_address`, `allowed_destination_addresses` and `allowed_sender_addresses`. `bynk deploy` checks each `@allowedSenders` domain has Email Sending enabled on the account, and never configures one. A call that breaks a platform limit or sets a reserved header faults before it is sent.\n");
2987 }
2988 if d.base.name == "Postgres" {
2990 out.push_str("\nEmits `[[hyperdrive]]` with a placeholder `id`: a distinct instance of `Postgres`, reading the database behind the Hyperdrive configuration at `env.<binding>.connectionString`. `bynk deploy` makes the configuration from the connection string in the environment variable `[deploy.hyperdrive.<Capability>] connection_env` names in `bynk.toml` (or adopts one named by `config_id`) and fills in the `id`; `bynk dev` reads the local string from `[dev.hyperdrive.<Capability>] connection_env`. Each statement opens and closes its own connection.\n");
2991 }
2992 if d.base.name == "MySql" {
2994 out.push_str("\nEmits `[[hyperdrive]]` with a placeholder `id` (as `Postgres` does), reading the MySQL database behind the Hyperdrive configuration through mysql2. `@tls(\"required\" | \"verify-ca\" | \"verify-identity\")` is how Hyperdrive secures its connection to the database (default `required`); `bynk deploy` sends it with the config it makes. Statements take `?` placeholders bound from `MySqlValue`s. Each statement opens and closes its own connection.\n");
2995 }
2996 if d.base.name == "EdgeCache" {
2997 out.push_str("\nEmits `[cache] enabled = true`: a `@cache` route's `2xx` is cached at Cloudflare's edge, and every other `GET` or `HEAD` answer is `no-store`.\n");
2998 }
2999 if let Some(doc) = &c.documentation {
3000 out.push('\n');
3001 out.push_str(doc);
3002 out.push('\n');
3003 }
3004 out
3005}
3006
3007pub(crate) fn describe_messages(m: &MessagesDecl) -> String {
3011 let mut out = String::new();
3012 out.push_str("```bynk\n");
3013 if m.private.is_some() {
3015 out.push_str("private ");
3016 }
3017 out.push_str("messages ");
3018 out.push('"');
3019 out.push_str(&m.tag);
3020 out.push('"');
3021 for ann in &m.annotations {
3022 out.push(' ');
3023 out.push_str(&bynk_fmt::annotation_to_string(ann));
3024 }
3025 out.push_str(" {\n");
3026 for entry in &m.entries {
3027 let icu_kinds: Vec<String> = bynk_check::icu::template_format_kinds(&entry.template)
3032 .into_iter()
3033 .map(|(name, kind)| (name.to_string(), kind.as_str()))
3034 .filter(|(_, kind)| *kind != "plain")
3035 .map(|(name, kind)| format!("{name}: {kind}"))
3036 .collect();
3037 if icu_kinds.is_empty() {
3038 out.push_str(&format!("\t\"{}\" => …\n", entry.code));
3039 } else {
3040 out.push_str(&format!(
3041 "\t\"{}\" => … // {}\n",
3042 entry.code,
3043 icu_kinds.join(", ")
3044 ));
3045 }
3046 }
3047 out.push_str("}\n```\n");
3048 if let Some(doc) = &m.documentation {
3049 out.push('\n');
3050 out.push_str(doc);
3051 out.push('\n');
3052 }
3053 out
3054}
3055
3056pub(crate) fn describe_embed(e: &EmbedDecl) -> String {
3061 let mut out = format!(
3062 "```bynk\n{}embed {} = \"{}\"\n```\n\nPrivate: the file's text, compiled into the code as a `String`; never served.\n",
3063 if e.private.is_some() { "private " } else { "" },
3064 e.name.name,
3065 bynk_fmt::escape_string(&e.path)
3066 );
3067 if let Some(doc) = &e.documentation {
3068 out.push('\n');
3069 out.push_str(doc);
3070 out.push('\n');
3071 }
3072 out
3073}
3074
3075pub(crate) fn describe_fixture(f: &FixtureDecl) -> String {
3078 let mut out = format!(
3079 "```bynk\nfixture {} = \"{}\"\n```\n\nTest-only: the file's text as a `String` for this suite's cases; never deployed.\n",
3080 f.name.name,
3081 bynk_fmt::escape_string(&f.path)
3082 );
3083 if let Some(doc) = &f.documentation {
3084 out.push('\n');
3085 out.push_str(doc);
3086 out.push('\n');
3087 }
3088 out
3089}
3090
3091pub(crate) fn describe_const(c: &ConstDecl) -> String {
3094 let mut out = format!(
3095 "```bynk\n{}const {}: {} = {}\n```\n",
3096 if c.private.is_some() { "private " } else { "" },
3098 c.name.name,
3099 type_ref_str(&c.ty),
3100 bynk_fmt::expr_to_string(&c.init)
3101 );
3102 if let Some(doc) = &c.documentation {
3103 out.push('\n');
3104 out.push_str(doc);
3105 out.push('\n');
3106 }
3107 out
3108}
3109
3110pub(crate) fn describe_asset(a: &AssetDecl) -> String {
3111 let at =
3112 a.at.as_ref()
3113 .map(|(p, _)| format!(" at \"{}\"", bynk_fmt::escape_string(p)))
3114 .unwrap_or_default();
3115 let served = match &a.at {
3120 Some((p, _)) => format!("Served at `{p}`."),
3121 None => format!(
3122 "Served at `{}` (content-hashed, cached as immutable).",
3123 bynk_check::assets::served_path_with_hash(
3124 &bynk_project::assets::normalise_asset_path(&a.path),
3125 "<hash>"
3126 )
3127 ),
3128 };
3129 let mut out = format!(
3130 "```bynk\n{}asset {} = \"{}\"{at}\n```\n\n{served} Public: served by the platform, never by the Worker.\n",
3131 if a.private.is_some() { "private " } else { "" },
3132 a.name.name,
3133 bynk_fmt::escape_string(&a.path)
3134 );
3135 if let Some(doc) = &a.documentation {
3136 out.push('\n');
3137 out.push_str(doc);
3138 out.push('\n');
3139 }
3140 out
3141}
3142
3143fn service_protocol_suffix(p: &ServiceProtocol) -> String {
3155 match p {
3156 ServiceProtocol::Call => String::new(),
3157 ServiceProtocol::Http => " from http".to_string(),
3158 ServiceProtocol::Cron => " from cron".to_string(),
3159 ServiceProtocol::Queue { name } => format!(" from queue(\"{name}\")"),
3160 ServiceProtocol::Email { address } => format!(" from email(\"{address}\")"),
3161 ServiceProtocol::WebSocket { .. } => " from websocket".to_string(),
3162 ServiceProtocol::Events { event_type, .. } => {
3167 format!(" from Events({})", type_ref_str(event_type))
3168 }
3169 }
3170}
3171
3172fn cors_summary(cors: &CorsPolicy) -> String {
3175 let mut parts = vec![format!("origins: {:?}", cors.origins())];
3176 if cors.credentials() {
3177 parts.push("credentials: true".to_string());
3178 }
3179 if let Some(secs) = cors.max_age_secs() {
3180 parts.push(format!("maxAge: {secs}s"));
3181 }
3182 parts.join(", ")
3183}
3184
3185fn security_summary(security: &SecurityPolicy) -> String {
3188 let mut parts = Vec::new();
3189 if !security.nosniff() {
3190 parts.push("nosniff: false".to_string());
3191 }
3192 if let Some(secs) = security.hsts_max_age_secs() {
3193 parts.push(format!("hsts: {secs}s"));
3194 }
3195 if parts.is_empty() {
3196 "nosniff".to_string()
3198 } else {
3199 parts.join(", ")
3200 }
3201}
3202
3203fn limits_summary(limits: &LimitsPolicy) -> String {
3206 match limits.max_body() {
3207 Some(bytes) => format!("maxBody: {bytes} bytes"),
3208 None => "maxBody".to_string(),
3209 }
3210}
3211
3212pub(crate) fn handler_line(h: &Handler) -> String {
3216 use bynk_model::IrHandlerKind;
3217 match bynk_model::lower_handler_kind_ir(&h.kind) {
3218 IrHandlerKind::Call => "on call".to_string(),
3219 IrHandlerKind::Http { method, path } => format!("on {}(\"{}\")", method.as_str(), path),
3220 IrHandlerKind::Cron { expr } => format!("on schedule(\"{expr}\")"),
3221 IrHandlerKind::Message => "on message".to_string(),
3222 IrHandlerKind::Open => "on open".to_string(),
3223 IrHandlerKind::Close => "on close".to_string(),
3224 IrHandlerKind::Event => "on event".to_string(),
3225 IrHandlerKind::Rejected => "on rejected".to_string(),
3226 }
3227}
3228
3229pub(crate) fn describe_service(s: &ServiceDecl) -> String {
3230 let mut out = format!(
3233 "```bynk\nservice {}{} {{\n",
3234 s.name.name,
3235 service_protocol_suffix(&s.protocol)
3236 );
3237 if let Some(cors) = &s.cors {
3240 out.push_str(&format!("\tcors {{ {} }}\n", cors_summary(cors)));
3241 }
3242 if let Some(security) = &s.security {
3244 out.push_str(&format!(
3245 "\tsecurity {{ {} }}\n",
3246 security_summary(security)
3247 ));
3248 }
3249 if let Some(limits) = &s.limits {
3251 out.push_str(&format!("\tlimits {{ {} }}\n", limits_summary(limits)));
3252 }
3253 if let Some(json) = &s.json {
3255 let mode = match json.options() {
3256 JsonOptions::Plain => "plain",
3257 JsonOptions::Tagged => "tagged",
3258 };
3259 out.push_str(&format!("\tjson {{ options: {mode} }}\n"));
3260 }
3261 for h in &s.handlers {
3262 let plain = if effective_json_options(s.json.as_ref(), h) == JsonOptions::Plain {
3264 " // plain JSON"
3265 } else {
3266 ""
3267 };
3268 out.push_str(&format!("\t{}{plain}\n", handler_line(h)));
3269 }
3270 out.push_str("}\n```\n");
3271 if let Some(doc) = &s.documentation {
3272 out.push('\n');
3273 out.push_str(doc);
3274 out.push('\n');
3275 }
3276 out
3277}
3278
3279fn store_kind_str(k: &StoreKind) -> String {
3282 if k.args.is_empty() {
3283 k.head.name.clone()
3284 } else {
3285 let args: Vec<String> = k.args.iter().map(type_ref_str).collect();
3286 format!("{}[{}]", k.head.name, args.join(", "))
3287 }
3288}
3289
3290pub(crate) fn describe_agent(a: &AgentDecl) -> String {
3291 let mut out = format!(
3294 "```bynk\nagent {} {{\n\tkey {}: {}\n",
3295 a.name.name,
3296 a.key_name.name,
3297 type_ref_str(&a.key_type),
3298 );
3299 for f in &a.store_fields {
3300 out.push_str(&format!(
3301 "\tstore {}: {}\n",
3302 f.name.name,
3303 store_kind_str(&f.kind)
3304 ));
3305 }
3306 for inv in &a.invariants {
3307 out.push_str(&format!(
3308 "\tinvariant {}: {}\n",
3309 inv.name.name,
3310 bynk_fmt::expr_to_string(&inv.predicate)
3311 ));
3312 }
3313 for tr in &a.transitions {
3314 out.push_str(&format!(
3315 "\ttransition {}: {}\n",
3316 tr.name.name,
3317 bynk_fmt::expr_to_string(&tr.predicate)
3318 ));
3319 }
3320 out.push_str("}\n```\n");
3321 if let Some(doc) = &a.documentation {
3322 out.push('\n');
3323 out.push_str(doc);
3324 out.push('\n');
3325 }
3326 out
3327}
3328
3329pub(crate) fn describe_provider(p: &ProviderDecl) -> String {
3330 let mut out = format!(
3331 "```bynk\nprovides {} = {}\n```\n",
3332 p.capability.name, p.provider_name.name
3333 );
3334 if let Some(doc) = &p.documentation {
3335 out.push('\n');
3336 out.push_str(doc);
3337 out.push('\n');
3338 }
3339 out
3340}
3341
3342pub struct CrossFileSymbol {
3347 pub path: PathBuf,
3348 pub span: Span,
3349 pub source: String,
3350}
3351
3352fn sorted_paths(files: &HashMap<PathBuf, String>) -> Vec<&PathBuf> {
3357 let mut paths: Vec<&PathBuf> = files.keys().collect();
3358 paths.sort();
3359 paths
3360}
3361
3362pub fn find_declaration_cross_file(
3373 files: &HashMap<PathBuf, String>,
3374 current_path: &Path,
3375 name: &str,
3376) -> Option<CrossFileSymbol> {
3377 for path in sorted_paths(files) {
3378 if path.as_path() == current_path {
3379 continue;
3380 }
3381 let source = &files[path];
3382 if let Some(span) = find_declaration_span(source, name) {
3383 return Some(CrossFileSymbol {
3384 path: path.clone(),
3385 span,
3386 source: source.clone(),
3387 });
3388 }
3389 }
3390 None
3391}
3392
3393pub fn describe_symbol_cross_file(
3399 files: &HashMap<PathBuf, String>,
3400 current_path: &Path,
3401 name: &str,
3402) -> Option<(PathBuf, String)> {
3403 for path in sorted_paths(files) {
3404 if path.as_path() == current_path {
3405 continue;
3406 }
3407 let source = &files[path];
3408 if let Some(desc) = describe_symbol(source, name) {
3409 return Some((path.clone(), desc));
3410 }
3411 }
3412 None
3413}
3414
3415pub fn type_ref_str(t: &TypeRef) -> String {
3416 match t {
3417 TypeRef::Fn(params, ret, _) => {
3419 let lhs = match params.len() {
3420 0 => "()".to_string(),
3421 1 if !matches!(params[0], TypeRef::Fn(..)) => type_ref_str(¶ms[0]),
3422 _ => format!(
3423 "({})",
3424 params
3425 .iter()
3426 .map(type_ref_str)
3427 .collect::<Vec<_>>()
3428 .join(", ")
3429 ),
3430 };
3431 format!("{lhs} -> {}", type_ref_str(ret))
3432 }
3433 TypeRef::Base(b, _) => b.name().to_string(),
3434 TypeRef::Named(id) => id.name.clone(),
3435 TypeRef::Result(a, b, _) => format!("Result[{}, {}]", type_ref_str(a), type_ref_str(b)),
3436 TypeRef::Option(t, _) => format!("Option[{}]", type_ref_str(t)),
3437 TypeRef::Effect(t, _) => format!("Effect[{}]", type_ref_str(t)),
3438 TypeRef::HttpResult(t, _) => format!("HttpResult[{}]", type_ref_str(t)),
3439 TypeRef::QueueResult(_) => "QueueResult".to_string(),
3440 TypeRef::Asset(_) => "Asset".to_string(),
3441 TypeRef::RequestHeaders(_) => "RequestHeaders".to_string(),
3442 TypeRef::RequestQuery(_) => "RequestQuery".to_string(),
3443 TypeRef::RequestCookies(_) => "RequestCookies".to_string(),
3444 TypeRef::TokenClaims(_) => "TokenClaims".to_string(),
3445 TypeRef::BoundaryRejection(_) => "BoundaryRejection".to_string(),
3446 TypeRef::List(t, _) => format!("List[{}]", type_ref_str(t)),
3448 TypeRef::Set(t, _) => format!("Set[{}]", type_ref_str(t)),
3449 TypeRef::Query(t, _) => format!("Query[{}]", type_ref_str(t)),
3450 TypeRef::Stream(t, _) => format!("Stream[{}]", type_ref_str(t)),
3451 TypeRef::Connection(t, _) => format!("Connection[{}]", type_ref_str(t)),
3452 TypeRef::History(t, _) => format!("History[{}]", type_ref_str(t)),
3453 TypeRef::Map(k, v, _) => format!("Map[{}, {}]", type_ref_str(k), type_ref_str(v)),
3454 TypeRef::ValidationError(_) => "ValidationError".to_string(),
3455 TypeRef::DecodeError(_) => "DecodeError".to_string(),
3456 TypeRef::Unit(_) => "()".to_string(),
3457 TypeRef::App { name, args, .. } => format!(
3459 "{}[{}]",
3460 name.name,
3461 args.iter().map(type_ref_str).collect::<Vec<_>>().join(", ")
3462 ),
3463 }
3464}
3465
3466#[cfg(test)]
3467mod tests {
3468 #[test]
3471 fn hover_on_a_typed_read_names_its_failure_policy() {
3472 use bynk_syntax::ast::{CommonsItem, SourceUnit};
3473 let src = "context bynk.t\n\ncapability Store {\n fn find[T: Codable](k: String) -> Effect[Option[T]] @onUndecodable(miss)\n fn need[T: Codable](k: String) -> Effect[T]\n fn size() -> Effect[Int]\n}\n";
3474 let toks = bynk_syntax::lexer::tokenize(src).expect("lexes");
3475 let SourceUnit::Context(ctx) = bynk_syntax::parser::parse_unit(&toks, src).expect("parses")
3476 else {
3477 panic!("a context");
3478 };
3479 let Some(CommonsItem::Capability(cap)) = ctx.items.first() else {
3480 panic!("a capability");
3481 };
3482 let hover = |op: &str| {
3483 let op = cap.ops.iter().find(|o| o.name.name == op).expect("op");
3484 describe_capability_op(cap, op)
3485 };
3486 assert!(hover("find").contains("is a miss"), "{}", hover("find"));
3487 assert!(hover("need").contains("faults"), "{}", hover("need"));
3488 assert!(!hover("size").contains("typed read"), "{}", hover("size"));
3489 }
3490
3491 #[test]
3492 fn hover_on_an_example_names_the_refinement() {
3493 let src = "commons c\n\ntype Code = String where Matches(\"[A-Z]{3}\") @example(\"ABC\")\n";
3494 let at = src.find("example").unwrap();
3495 let h = describe_refinement_example_at(src, at).expect("hover");
3496 assert!(
3497 h.contains("@example(\"ABC\")") && h.contains("Matches"),
3498 "{h}"
3499 );
3500 assert!(describe_refinement_example_at(src, 3).is_none());
3501 }
3502
3503 #[test]
3506 fn within_hovers_on_an_effect_receiver_only() {
3507 use bynk_check::checker::{Ty, Types};
3508 use bynk_syntax::ast::BaseType;
3509 let tys = Types::new();
3510 let int = tys.intern(Ty::Base(BaseType::Int));
3511 let effect = tys.intern(Ty::Effect(int));
3512 let src = "let r <- p.quote(1).within(2.seconds)\n";
3513 let dot = src.find(".within").unwrap();
3514 let at = src.find("within").unwrap() + 1;
3515 let on_effect = [(Span::new(8, dot), effect)];
3516 let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("within hovers");
3517 assert!(
3518 hover.contains("within(d: Duration) -> Effect[Result[T, TimedOut]]"),
3519 "{hover}"
3520 );
3521 assert!(hover.contains("not cancelled"), "{hover}");
3522 assert!(hover.contains("waitUntil"), "{hover}");
3523 let on_int = [(Span::new(8, dot), int)];
3525 assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3526 assert!(describe_effect_method_at(src, 0, &on_effect, &tys).is_none());
3528
3529 let src = "let r <- p.get(1).race(p.get(2))\n";
3531 let dot = src.find(".race").unwrap();
3532 let at = src.find("race").unwrap() + 1;
3533 let on_effect = [(Span::new(8, dot), effect)];
3534 let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("race hovers");
3535 assert!(
3536 hover.contains("race(other: Effect[T]) -> Effect[T]"),
3537 "{hover}"
3538 );
3539 assert!(hover.contains("loser is not cancelled"), "{hover}");
3540 assert!(hover.contains("idempotent"), "{hover}");
3541 let on_int = [(Span::new(8, dot), int)];
3542 assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3543
3544 let src = "do p.get(1).detach()\n";
3546 let dot = src.find(".detach").unwrap();
3547 let at = src.find("detach").unwrap() + 1;
3548 let on_effect = [(Span::new(3, dot), effect)];
3549 let hover = describe_effect_method_at(src, at, &on_effect, &tys).expect("detach hovers");
3550 assert!(hover.contains("detach() -> Effect[()]"), "{hover}");
3551 assert!(hover.contains("not once it has finished"), "{hover}");
3552 assert!(hover.contains("reported, never lost"), "{hover}");
3553 let on_int = [(Span::new(3, dot), int)];
3554 assert!(describe_effect_method_at(src, at, &on_int, &tys).is_none());
3555 }
3556
3557 #[test]
3560 fn private_const_hover_shows_the_modifier() {
3561 let src = "commons m\n\nprivate const MaxRetries: Int = 3\n\nconst Shown: Int = 1\n";
3562 let tokens = tokenize(src).unwrap();
3563 let (Some(SourceUnit::Commons(c)), _) = parse_unit_with_recovery(&tokens, src) else {
3564 panic!("a commons");
3565 };
3566 let hidden = describe_item(&c.items[0], "MaxRetries").unwrap();
3567 assert!(
3568 hidden.starts_with("```bynk\nprivate const MaxRetries: Int = 3\n"),
3569 "{hidden}"
3570 );
3571 let shown = describe_item(&c.items[1], "Shown").unwrap();
3572 assert!(shown.starts_with("```bynk\nconst Shown"), "{shown}");
3573 assert!(describe_private_at(src, src.find("private").unwrap()).is_some());
3574 }
3575
3576 #[test]
3578 fn par_hover_is_for_the_block_keyword_only() {
3579 let block =
3580 "fn f() -> Effect[Int] {\n par {\n let a <- g()\n }\n Effect.pure(a)\n}\n";
3581 let at = block.find("par").unwrap();
3582 assert!(describe_par_at(block, at).unwrap().contains("par {"));
3583 let ident = "fn f(par: Int) -> Int {\n par\n}\n";
3584 assert!(describe_par_at(ident, ident.find("par").unwrap()).is_none());
3585 assert!(describe_par_at(ident, ident.rfind("par").unwrap()).is_none());
3586 }
3587
3588 use super::*;
3589
3590 #[test]
3593 fn email_service_header_renders_its_address() {
3594 let p = ServiceProtocol::Email {
3595 address: "*@shop.example".to_string(),
3596 };
3597 assert_eq!(
3598 service_protocol_suffix(&p),
3599 " from email(\"*@shop.example\")"
3600 );
3601 }
3602
3603 #[test]
3607 fn system_job_hover_needs_a_job_service_receiver() {
3608 const CTX: &str = "context cr.jobs\n\ntype Envelope = { message: String }\n\nservice sweeper from cron {\n on schedule(\"*/5 * * * *\") () -> Effect[Result[(), String]] {\n Ok(())\n }\n}\n\nservice deliveries from queue(\"d\") {\n on message(e: Envelope) -> Effect[QueueResult] {\n Ack\n }\n}\n";
3609 let suite = |tier: &str| {
3610 format!(
3611 "suite cr.jobs{tier} {{\n case \"c\" {{\n let e = Envelope {{ message: \"hi\" }}\n let m = e.message\n let r <- deliveries.message(e)\n let s <- sweeper.schedule(\"*/5 * * * *\")\n expect m == \"hi\"\n }}\n}}\n"
3612 )
3613 };
3614 let at = |src: &str, needle: &str| {
3615 src.find(needle).expect("needle is in the suite") + needle.len() - "message".len()
3616 };
3617 let system = suite(" as system");
3618 let field = at(&system, "e.message");
3619 assert!(describe_system_job_address_at(&system, field, [CTX]).is_none());
3620 let queue = at(&system, "deliveries.message");
3621 let hover =
3622 describe_system_job_address_at(&system, queue, [CTX]).expect("queue address hovers");
3623 assert!(hover.contains("`queue` entry"), "{hover}");
3624 let cron = system.find("sweeper.schedule").expect("cron address") + "sweeper.".len();
3625 let hover =
3626 describe_system_job_address_at(&system, cron, [CTX]).expect("cron address hovers");
3627 assert!(hover.contains("`scheduled` entry"), "{hover}");
3628 let unit = suite("");
3629 let queue = at(&unit, "deliveries.message");
3630 assert!(describe_system_job_address_at(&unit, queue, [CTX]).is_none());
3631 }
3632
3633 #[test]
3636 fn run_id_hovers_only_as_the_test_run() {
3637 let src = "suite rid.orders {\n case \"a\" {\n expect run.id == \"local\"\n }\n case \"b\" {\n let run = Wrapper { id: \"x\" }\n expect run.id == \"x\"\n }\n}\n";
3638 let first = src.find("run.id").expect("first run.id");
3639 assert!(describe_run_id_at(src, first).is_some());
3640 assert!(describe_run_id_at(src, first + "run.".len()).is_some());
3641 let shadowed = src.rfind("run.id").expect("second run.id");
3642 assert!(describe_run_id_at(src, shadowed).is_none());
3643 let interp = "suite rid.orders as system {\n case \"a\" {\n let r <- api.POST(\"/o/:id\", \"o-\\(run.id)\") by Visitor\n expect r is Ok(true)\n }\n}\n";
3644 assert!(describe_run_id_at(interp, interp.find("run.id").expect("run.id")).is_some());
3645 let ctx = "context rid.orders\n\nfn f(run: Wrapper) -> String {\n run.id\n}\n";
3646 assert!(describe_run_id_at(ctx, ctx.find("run.id").expect("run.id")).is_none());
3647 }
3648
3649 #[test]
3654 fn run_id_hover_respects_nested_binders() {
3655 let src = "suite rid.orders {\n case \"a\" {\n let w = Wrapper { id: \"x\" }\n let a = if true {\n let run = w\n run.id\n } else { \"\" }\n let f = (run: Wrapper) => run.id\n let m = match Some(w) { Some(run) => run.id, None => \"\" }\n let i = if Some(w) is Some(run) { run.id } else { \"\" }\n let j = Some(w) is Some(run) && run.id == \"x\"\n let k = if !(Some(w) is Some(run)) { \"\" } else { run.id }\n expect run.id == \"local\"\n }\n}\n";
3656 let starts: Vec<usize> = src.match_indices("run.id").map(|(i, _)| i).collect();
3657 assert_eq!(starts.len(), 7, "{src}");
3658 for &shadowed in &starts[..6] {
3659 assert!(
3660 describe_run_id_at(src, shadowed).is_none(),
3661 "shadowed at {shadowed}: {}",
3662 &src[shadowed.saturating_sub(30)..shadowed + 6]
3663 );
3664 }
3665 assert!(describe_run_id_at(src, starts[6]).is_some(), "the test run");
3666 }
3667
3668 #[test]
3671 fn hover_describes_reserved_principals() {
3672 let src = "suite pay.hooks as system {\n\tcase \"c\" {\n\t\tlet r <- webhooks.POST(\"/h\", \"x\") by Forged\n\t\tlet Stale = 1\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3673 let forged = describe_reserved_principal_at(src, src.find("Forged").unwrap()).unwrap();
3674 assert!(
3675 forged.contains("by Forged") && forged.contains("does not hold"),
3676 "{forged}"
3677 );
3678 assert!(describe_reserved_principal_at(src, src.find("Stale").unwrap()).is_none());
3679 let src = "suite pay.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by Expired\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3680 let expired = describe_reserved_principal_at(src, src.find("Expired").unwrap()).unwrap();
3681 assert!(
3682 expired.contains("by Expired") && expired.contains("one hour in the past"),
3683 "{expired}"
3684 );
3685 let src = "suite ci.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by WrongIssuer\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3686 let wrong = describe_reserved_principal_at(src, src.find("WrongIssuer").unwrap()).unwrap();
3687 assert!(
3688 wrong.contains("by WrongIssuer") && wrong.contains("`iss` is not the actor's"),
3689 "{wrong}"
3690 );
3691 let src = "suite ci.api as system {\n\tcase \"c\" {\n\t\tlet r <- api.GET(\"/a\") by WrongAlgorithm\n\t\tlet s <- api.GET(\"/a\") by NoSubject\n\t\texpect r is Rejected(Unauthorized)\n\t}\n}\n";
3693 let alg = describe_reserved_principal_at(src, src.find("WrongAlgorithm").unwrap()).unwrap();
3694 assert!(
3695 alg.contains("by WrongAlgorithm")
3696 && alg.contains("`alg: none`")
3697 && alg.contains("`HS256`"),
3698 "{alg}"
3699 );
3700 let sub = describe_reserved_principal_at(src, src.find("NoSubject").unwrap()).unwrap();
3701 assert!(
3702 sub.contains("by NoSubject")
3703 && sub.contains("empty `sub`")
3704 && sub.contains("no `sub` claim"),
3705 "{sub}"
3706 );
3707 }
3708
3709 #[test]
3712 fn hover_describes_env_entries() {
3713 let src = "suite shop.pay {\n\tenv {\n\t\tA = \"x\"\n\t}\n\n\tcase \"c\" {\n\t\tenv { A = \"y\"\n\t\t\tB = \"z\" }\n\t\texpect true\n\t}\n}\n";
3714 let at = |needle: &str| src.find(needle).unwrap();
3715 assert_eq!(
3716 describe_env_at(src, at("env")).as_deref(),
3717 Some(ENV_KEYWORD_DOC)
3718 );
3719 let suite_a = describe_env_at(src, at("A = \"x\"")).unwrap();
3720 assert!(suite_a.contains("A = \"x\""), "{suite_a}");
3721 assert!(suite_a.ends_with("(suite)"), "{suite_a}");
3722 let case_a = describe_env_at(src, at("A = \"y\"")).unwrap();
3723 assert!(case_a.ends_with("(case, overrides suite)"), "{case_a}");
3724 let case_b = describe_env_at(src, at("B = ")).unwrap();
3725 assert!(case_b.ends_with("(case)"), "{case_b}");
3726 assert!(describe_env_at(src, at("expect")).is_none());
3727 }
3728
3729 #[test]
3732 fn hover_marks_an_extensible_first_party_enum() {
3733 let fetch_error = describe_firstparty_symbol("FetchError").expect("FetchError hovers");
3734 assert!(fetch_error.contains("**Extensible**"), "{fetch_error}");
3735 assert!(
3736 !fetch_error.contains("**Experimental**"),
3737 "nothing ships experimental"
3738 );
3739 assert!(
3740 describe_firstparty_symbol("Method")
3741 .unwrap()
3742 .contains("**Extensible**")
3743 );
3744 let closed = describe_firstparty_symbol("Request").expect("Request hovers");
3745 assert!(
3746 !closed.contains("**Extensible**"),
3747 "a closed first-party type is not marked extensible"
3748 );
3749 assert_eq!(
3750 firstparty_notes("app.user", "FetchError"),
3751 "",
3752 "a user's own enum"
3753 );
3754 }
3755
3756 fn project_files(root: &Path, files: &[(&str, &str)]) -> HashMap<PathBuf, String> {
3762 files
3763 .iter()
3764 .map(|(rel, contents)| (root.join(rel), (*contents).to_string()))
3765 .collect()
3766 }
3767
3768 #[test]
3769 fn receiver_segment_survives_a_multibyte_char_before_the_receiver() {
3770 let text = "\"€p.items"; let member_start = text.rfind("items").unwrap();
3775 let (recv, start) =
3776 receiver_segment_at(text, Span::new(member_start, text.len())).expect("receiver");
3777 assert_eq!(recv, "p");
3778 assert_eq!(&text[start..start + recv.len()], "p");
3779 }
3780
3781 #[test]
3782 fn cross_file_definition_resolves_into_sibling_file() {
3783 let root = PathBuf::from("/synthetic/cross_file_definition");
3784 let files = project_files(
3785 &root,
3786 &[
3787 (
3788 "a.bynk",
3789 "commons demo.a\n\ntype Foo = Int where Positive\n",
3790 ),
3791 (
3792 "b.bynk",
3793 "commons demo.b\n\nuses demo.a\n\ntype Bar = Int where NonNegative\n",
3794 ),
3795 ],
3796 );
3797 let current = root.join("b.bynk");
3798 let found = find_declaration_cross_file(&files, ¤t, "Foo")
3799 .expect("Foo should resolve into a.bynk");
3800 let expected = root.join("a.bynk");
3801 assert_eq!(found.path, expected);
3802 assert!(
3803 found.source.contains("type Foo = Int where Positive"),
3804 "source returned does not contain Foo declaration"
3805 );
3806 }
3807
3808 #[test]
3809 fn cross_file_definition_skips_current_file() {
3810 let root = PathBuf::from("/synthetic/cross_file_skip_current");
3811 let files = project_files(
3812 &root,
3813 &[(
3814 "only.bynk",
3815 "commons demo.only\n\ntype Foo = Int where Positive\n",
3816 )],
3817 );
3818 let current = root.join("only.bynk");
3819 assert!(find_declaration_cross_file(&files, ¤t, "Foo").is_none());
3821 }
3822
3823 #[test]
3824 fn cross_file_hover_returns_markdown_summary() {
3825 let root = PathBuf::from("/synthetic/cross_file_hover");
3826 let files = project_files(
3827 &root,
3828 &[
3829 (
3830 "money.bynk",
3831 "commons demo.money\n\n\
3832 ---\n\
3833 Amount in minor units of currency.\n\
3834 ---\n\
3835 type Money = Int where NonNegative\n",
3836 ),
3837 (
3838 "orders.bynk",
3839 "commons demo.orders\n\nuses demo.money\n\ntype OrderId = Int where Positive\n",
3840 ),
3841 ],
3842 );
3843 let current = root.join("orders.bynk");
3844 let (other_path, desc) = describe_symbol_cross_file(&files, ¤t, "Money")
3845 .expect("Money should produce hover content");
3846 assert_eq!(other_path, root.join("money.bynk"));
3847 assert!(desc.contains("type Money"));
3848 assert!(
3849 desc.contains("Amount in minor units"),
3850 "hover should include the doc block"
3851 );
3852 }
3853
3854 #[test]
3855 fn cross_file_returns_none_for_unknown_name() {
3856 let root = PathBuf::from("/synthetic/cross_file_none");
3857 let files = project_files(
3858 &root,
3859 &[(
3860 "a.bynk",
3861 "commons demo.a\n\ntype Foo = Int where Positive\n",
3862 )],
3863 );
3864 let current = root.join("a.bynk");
3865 assert!(find_declaration_cross_file(&files, ¤t, "DoesNotExist").is_none());
3866 assert!(describe_symbol_cross_file(&files, ¤t, "DoesNotExist").is_none());
3867 }
3868
3869 #[test]
3870 fn first_party_symbols_describe_their_signature_and_doc() {
3871 let reverse = describe_firstparty_symbol("reverse").expect("`bynk.list.reverse` described");
3875 assert!(
3876 reverse.contains("reverse") && reverse.contains("List"),
3877 "{reverse}"
3878 );
3879 assert!(
3880 reverse.contains("reverse order"),
3881 "doc block surfaced: {reverse}"
3882 );
3883 let clock = describe_firstparty_symbol("Clock").expect("`bynk`-surface `Clock`");
3885 assert!(
3886 clock.contains("wall-clock"),
3887 "capability doc surfaced: {clock}"
3888 );
3889 let locale_tag = describe_firstparty_symbol("LocaleTag")
3893 .expect("`bynk.locale.types.LocaleTag` described");
3894 assert!(
3895 locale_tag.contains("LocaleTag") && locale_tag.contains("Matches"),
3896 "{locale_tag}"
3897 );
3898 let render = describe_firstparty_symbol("render").expect("`bynk.locale.render` described");
3899 assert!(
3900 render.contains("render") && render.contains("LocaleTag"),
3901 "{render}"
3902 );
3903 let with_text =
3904 describe_firstparty_symbol("withText").expect("`bynk.locale.withText` described");
3905 assert!(with_text.contains("withText"), "{with_text}");
3906 assert!(describe_firstparty_symbol("DoesNotExist").is_none());
3908 }
3909
3910 #[test]
3914 fn idempotency_hover_names_the_provider_for_each_platform() {
3915 let capability = describe_firstparty_symbol("Idempotency").expect("`Idempotency` hovers");
3916 assert!(capability.contains("D1-backed"), "{capability}");
3917 assert!(capability.contains("Cloudflare"), "{capability}");
3918 assert!(
3919 capability.contains("`<worker>-idempotency`"),
3920 "{capability}"
3921 );
3922 assert!(
3923 capability.contains("in-memory") && capability.contains("Node and in the browser"),
3924 "{capability}"
3925 );
3926 for op in ["dedup", "remember", "claim"] {
3927 let hover =
3928 describe_firstparty_symbol(&format!("Idempotency.{op}")).unwrap_or_default();
3929 assert!(
3930 hover.contains("D1-backed on Cloudflare")
3931 && hover.contains("in-memory on Node and in the browser"),
3932 "`{op}`: {hover}"
3933 );
3934 }
3935 }
3936
3937 #[test]
3938 fn unit_reference_spans_finds_uses_and_consumes_targets() {
3939 let src = "context app.main\n uses billing.charge\n consumes platform.time\n";
3942 let spans = unit_reference_spans(src);
3943 let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
3944 assert!(names.contains(&"billing.charge"), "{names:?}");
3945 assert!(names.contains(&"platform.time"), "{names:?}");
3946 let (_, span) = spans.iter().find(|(n, _)| n == "billing.charge").unwrap();
3948 assert_eq!(&src[span.start..span.end], "billing.charge");
3949 }
3950
3951 #[test]
3952 fn unit_reference_spans_links_the_suite_target() {
3953 let src = "suite todos\n uses billing.charge\n";
3956 let spans = unit_reference_spans(src);
3957 let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
3958 assert!(names.contains(&"todos"), "{names:?}");
3959 assert!(names.contains(&"billing.charge"), "{names:?}");
3960 let (_, span) = spans.iter().find(|(n, _)| n == "todos").unwrap();
3962 assert_eq!(&src[span.start..span.end], "todos");
3963 }
3964
3965 #[test]
3966 fn doc_link_context_is_some_only_inside_a_doc_range() {
3967 let src = "---\nSee [Rat\n---\nfn f() -> Int { [1, 2] }\n";
3968 let at = src.find("Rat").unwrap() + 3;
3969 let ctx = doc_link_context(src, at).expect("in doc");
3970 assert_eq!(ctx.partial, "Rat");
3971 assert_eq!(ctx.owner, None);
3972 assert_eq!(ctx.replace_start, at - 3);
3973 assert!(!ctx.closed);
3974 assert_eq!(ctx.attached, Some(src.find("f()").unwrap()));
3975 let code = src.find("[1").unwrap() + 1;
3976 assert_eq!(doc_link_context(src, code), None);
3977 }
3978
3979 #[test]
3980 fn doc_link_context_splits_an_owner_prefix_and_sees_a_closer() {
3981 let src = "---\nSee [RateView.re]\n---\nfn f() -> Int { 1 }\n";
3982 let at = src.find(".re").unwrap() + 3;
3983 let ctx = doc_link_context(src, at).unwrap();
3984 assert_eq!(ctx.owner.as_deref(), Some("RateView"));
3985 assert_eq!(ctx.partial, "re");
3986 assert!(ctx.closed);
3987 }
3988
3989 #[test]
3990 fn doc_link_context_replaces_the_rest_of_a_word_under_the_cursor() {
3991 let src = "---\nSee [RateView] here\n---\nfn f() -> Int { 1 }\n";
3992 let at = src.find("Rat").unwrap() + 3;
3993 let ctx = doc_link_context(src, at).unwrap();
3994 assert_eq!(ctx.partial, "Rat");
3995 assert_eq!(&src[ctx.replace_start..ctx.replace_end], "RateView");
3996 assert!(ctx.closed);
3997 }
3998
3999 #[test]
4000 fn doc_link_context_is_none_in_a_fenced_block_and_after_a_bare_dot() {
4001 let fenced = "---\n```\nlet v = xs[\n```\n---\nfn f() -> Int { 1 }\n";
4002 let at = fenced.find("xs[").unwrap() + 3;
4003 assert_eq!(doc_link_context(fenced, at), None);
4004 let dot = "---\nSee [.foo\n---\nfn f() -> Int { 1 }\n";
4005 let at = dot.find(".foo").unwrap() + 4;
4006 assert_eq!(doc_link_context(dot, at), None);
4007 }
4008
4009 #[test]
4010 fn doc_link_context_is_none_after_a_closed_or_broken_bracket() {
4011 let src = "---\nSee [Done] and x\n---\nfn f() -> Int { 1 }\n";
4012 let at = src.find(" and").unwrap() + 4;
4013 assert_eq!(doc_link_context(src, at), None);
4014 }
4015
4016 #[test]
4017 fn doc_link_context_works_on_a_doc_line() {
4018 let src = "--| See [Li\nfn f() -> Int { 1 }\n";
4019 let at = src.find("Li").unwrap() + 2;
4020 assert_eq!(doc_link_context(src, at).unwrap().partial, "Li");
4021 }
4022
4023 #[test]
4024 fn scan_doc_link_candidates_finds_a_bare_shortcut() {
4025 let cands = scan_doc_link_candidates("See [Limiter] for details.");
4026 assert_eq!(cands.len(), 1);
4027 assert_eq!(cands[0].name, "Limiter");
4028 assert_eq!(cands[0].display, "Limiter");
4029 assert_eq!(
4030 &"See [Limiter] for details."[cands[0].span.clone()],
4031 "[Limiter]"
4032 );
4033 }
4034
4035 #[test]
4036 fn scan_doc_link_candidates_finds_a_dotted_shortcut() {
4037 let cands = scan_doc_link_candidates("See [RateView.remaining].");
4038 assert_eq!(cands.len(), 1);
4039 assert_eq!(cands[0].name, "RateView.remaining");
4040 }
4041
4042 #[test]
4043 fn scan_doc_link_candidates_finds_a_code_span_shortcut() {
4044 let text = "The [`RateView.remaining`] field is never negative.";
4045 let cands = scan_doc_link_candidates(text);
4046 assert_eq!(cands.len(), 1);
4047 assert_eq!(cands[0].name, "RateView.remaining");
4048 assert_eq!(cands[0].display, "`RateView.remaining`");
4049 assert_eq!(&text[cands[0].span.clone()], "[`RateView.remaining`]");
4050 }
4051
4052 #[test]
4053 fn scan_doc_link_candidates_finds_a_full_reference() {
4054 let cands = scan_doc_link_candidates("See [the limiter][Limiter] for details.");
4055 assert_eq!(cands.len(), 1);
4056 assert_eq!(cands[0].name, "Limiter");
4057 assert_eq!(cands[0].display, "the limiter");
4058 }
4059
4060 #[test]
4061 fn scan_doc_link_candidates_leaves_an_explicit_url_untouched() {
4062 let cands = scan_doc_link_candidates("See [Limiter](https://example.com).");
4063 assert!(cands.is_empty(), "{cands:?}");
4064 }
4065
4066 #[test]
4067 fn scan_doc_link_candidates_leaves_an_author_defined_reference_untouched() {
4068 let text = "See [foo] for details.\n\n[foo]: https://example.com\n";
4069 let cands = scan_doc_link_candidates(text);
4070 assert!(cands.is_empty(), "{cands:?}");
4071 }
4072
4073 #[test]
4074 fn scan_doc_link_candidates_ignores_non_identifier_bracket_content() {
4075 let cands = scan_doc_link_candidates("See [see note] and [1] below.");
4076 assert!(cands.is_empty(), "{cands:?}");
4077 }
4078
4079 #[test]
4080 fn scan_doc_link_candidates_ignores_fenced_code_block_content() {
4081 let text = "Example:\n```\n[Bracket, Syntax]\n[label]: not-a-real-def\n```\nSee [Limiter].";
4082 let cands = scan_doc_link_candidates(text);
4083 assert_eq!(cands.len(), 1);
4084 assert_eq!(cands[0].name, "Limiter");
4085 }
4086
4087 #[test]
4088 fn scan_doc_link_candidates_does_not_recognise_the_collapsed_reference_form() {
4089 let cands = scan_doc_link_candidates("See [Limiter][].");
4092 assert!(cands.is_empty(), "{cands:?}");
4093 }
4094
4095 #[test]
4096 fn doc_link_spans_reports_absolute_offsets_in_an_indented_doc_block() {
4097 let src = "context app.main\n ---\n See [Limiter] here.\n ---\n service api {}\n";
4098 let spans = doc_link_spans(src);
4099 assert_eq!(spans.len(), 1);
4100 let (name, span) = &spans[0];
4101 assert_eq!(name, "Limiter");
4102 assert_eq!(&src[span.start..span.end], "[Limiter]");
4103 }
4104
4105 #[test]
4107 fn doc_link_spans_finds_links_in_doc_lines() {
4108 let src = "--- Wraps a [Foo].\n--- And a [Bar].\ntype Baz = Int\n";
4109 let spans = doc_link_spans(src);
4110 let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
4111 assert_eq!(names, vec!["Foo", "Bar"]);
4112 assert_eq!(&src[spans[1].1.start..spans[1].1.end], "[Bar]");
4113 }
4114
4115 #[test]
4116 fn doc_link_spans_finds_links_across_multiple_doc_blocks() {
4117 let src = "---\nSee [Foo].\n---\ntype Foo = Int\n\n---\nSee [Bar].\n---\ntype Bar = Int\n";
4118 let spans = doc_link_spans(src);
4119 let names: Vec<&str> = spans.iter().map(|(n, _)| n.as_str()).collect();
4120 assert_eq!(names, vec!["Foo", "Bar"]);
4121 }
4122
4123 #[test]
4124 fn own_declaration_name_finds_context_and_commons_names() {
4125 let src = "context app.main\n uses billing.charge\n";
4127 let (name, span) = own_declaration_name(src).expect("context has its own name");
4128 assert_eq!(name, "app.main");
4129 assert_eq!(&src[span.start..span.end], "app.main");
4130
4131 let src = "commons app.util\n\ntype Foo = Int where Positive\n";
4132 let (name, _) = own_declaration_name(src).expect("commons has its own name");
4133 assert_eq!(name, "app.util");
4134 }
4135
4136 #[test]
4137 fn own_declaration_name_none_for_suites() {
4138 let src = "suite todos\n";
4142 assert!(own_declaration_name(src).is_none());
4143 }
4144
4145 #[test]
4148 fn describe_type_renders_fields_variants_and_refinements() {
4149 let record = describe_symbol(
4150 "commons demo.m\n\ntype Order = {\n id: OrderId,\n total: Money,\n}\n",
4151 "Order",
4152 )
4153 .unwrap();
4154 assert!(record.contains("type Order = {"), "{record}");
4155 assert!(record.contains("id: OrderId"), "{record}");
4156 assert!(record.contains("total: Money"), "{record}");
4157
4158 let sum = describe_symbol(
4159 "commons demo.m\n\ntype Status = enum { Pending, Shipped }\n",
4160 "Status",
4161 )
4162 .unwrap();
4163 assert!(sum.contains("enum {"), "{sum}");
4164 assert!(sum.contains("Pending") && sum.contains("Shipped"), "{sum}");
4165
4166 let refined = describe_symbol(
4167 "commons demo.m\n\ntype Email = String where NonEmpty\n",
4168 "Email",
4169 )
4170 .unwrap();
4171 assert!(
4172 refined.contains("type Email = String where NonEmpty"),
4173 "{refined}"
4174 );
4175
4176 let opaque =
4177 describe_symbol("commons demo.m\n\ntype Token = opaque String\n", "Token").unwrap();
4178 assert!(opaque.contains("type Token = opaque String"), "{opaque}");
4179 }
4180
4181 #[test]
4184 fn describe_fn_renders_contracts() {
4185 let src = "commons demo.m\n\nfn discount(p: Int, pct: Int) -> Int\n requires p_nonneg: p >= 0\n ensures never_negative: result >= 0\n{\n p\n}\n";
4186 let out = describe_symbol(src, "discount").unwrap();
4187 assert!(
4188 out.contains("fn discount(p: Int, pct: Int) -> Int"),
4189 "{out}"
4190 );
4191 assert!(out.contains("requires p_nonneg: p >= 0"), "{out}");
4192 assert!(out.contains("ensures never_negative: result >= 0"), "{out}");
4193 }
4194
4195 #[test]
4198 fn describe_fn_renders_bounds_and_where() {
4199 let src = "commons demo.m\n\ntype Box[A] = { value: A }\n\nfn same[T: Eq, U](a: T, b: T, u: U) -> Bool { a == b }\n\nfn Box.has(self, x: A) -> Bool where A: Eq { self.value == x }\n";
4200 let out = describe_symbol(src, "same").unwrap();
4201 assert!(
4202 out.contains("fn same[T: Eq, U](a: T, b: T, u: U) -> Bool"),
4203 "{out}"
4204 );
4205 let method = describe_symbol(src, "Box.has").unwrap();
4206 assert!(
4207 method.contains("fn Box.has(self, x: A) -> Bool where A: Eq"),
4208 "{method}"
4209 );
4210 let ty =
4211 describe_symbol("commons demo.m\n\ntype Pair[T: Eq] = { a: T }\n", "Pair").unwrap();
4212 assert!(ty.contains("type Pair[T: Eq] = "), "{ty}");
4213 }
4214
4215 #[test]
4219 fn constraint_token_spans_cover_every_bound() {
4220 let src = "commons demo.m\n\ntype P[T: Eq] = { a: T }\n\nfn f[T: Eq + Eq, U](a: T, u: U) -> T { a }\n\nfn P.g(self) -> Int where T: Eq { 0 }\n";
4221 let names: Vec<&str> = constraint_token_spans(src)
4222 .into_iter()
4223 .map(|s| &src[s.start..s.end])
4224 .collect();
4225 assert_eq!(names, ["Eq", "Eq", "Eq", "Eq"]);
4226 assert!(constraint_token_spans("commons m\n\nfn f[T](a: T) -> T { a }\n").is_empty());
4227 }
4228
4229 #[test]
4232 fn describe_renders_derives_and_ord_bounds() {
4233 let src = "commons demo.m\n\ntype Priority = enum { Low, High } derives Ord\n\ntype Row = { a: Int } derives Ord\n\nfn top[T: Ord](xs: List[T]) -> Option[T] { None }\n\nfn both[T: Eq + Ord](a: T) -> T { a }\n\nfn Box.big(self, x: A) -> Bool where A: Ord { true }\n";
4234 let p = describe_symbol(src, "Priority").unwrap();
4235 assert!(p.contains("} derives Ord\n```"), "{p}");
4236 assert!(
4237 describe_symbol(src, "Row")
4238 .unwrap()
4239 .contains("} derives Ord")
4240 );
4241 assert!(
4242 describe_symbol(src, "top")
4243 .unwrap()
4244 .contains("fn top[T: Ord](xs: List[T]) -> Option[T]")
4245 );
4246 assert!(
4247 describe_symbol(src, "both")
4248 .unwrap()
4249 .contains("fn both[T: Eq + Ord](a: T)")
4250 );
4251 assert!(
4252 describe_symbol(src, "Box.big")
4253 .unwrap()
4254 .contains("-> Bool where A: Ord")
4255 );
4256 let plain = describe_symbol("commons demo.m\n\ntype R = { a: Int }\n", "R").unwrap();
4258 assert!(!plain.contains("derives"), "{plain}");
4259 }
4260
4261 #[test]
4264 fn describe_derives_at_is_the_clause_only() {
4265 let src =
4266 "commons demo.m\n\ntype P = Int derives Ord\n\nfn f(derives: Int) -> Int { derives }\n";
4267 let at = src.find("derives").unwrap();
4268 let doc = describe_derives_at(src, at).expect("hover on `derives`");
4269 assert!(
4270 doc.contains("derives Ord") && doc.contains("declaration order"),
4271 "{doc}"
4272 );
4273 assert!(describe_derives_at(src, at + 2).is_some());
4274 assert!(describe_derives_at(src, src.find("Ord").unwrap()).is_none());
4275 assert!(describe_derives_at(src, src.rfind("derives").unwrap()).is_none());
4276 assert!(describe_derives_at(src, src.find("(derives").unwrap() + 1).is_none());
4277 }
4278
4279 #[test]
4282 fn describe_constraint_at_explains_bounds_and_derives() {
4283 let src = "commons demo.m\n\ntype P = Int derives Ord\n\nfn f[T: Eq + Ord](a: T) -> T { a }\n\nfn Box.g(self, x: A) -> Bool where A: Ord { true }\n";
4284 let eq = describe_constraint_at(src, src.find("Eq").unwrap()).unwrap();
4285 assert!(eq.contains("constraint Eq") && eq.contains("=="), "{eq}");
4286 for (i, _) in src.match_indices("Ord") {
4287 let ord = describe_constraint_at(src, i + 1).expect("Ord hover");
4288 assert!(
4289 ord.contains("constraint Ord") && ord.contains("implies `Eq`"),
4290 "{ord}"
4291 );
4292 }
4293 assert!(describe_constraint_at(src, src.find("Int").unwrap()).is_none());
4294 assert!(describe_constraint_at(src, src.find("fn f").unwrap()).is_none());
4295 }
4296
4297 #[test]
4299 fn constraint_token_spans_cover_derives() {
4300 let src =
4301 "commons demo.m\n\ntype P = Int derives Ord\n\ntype Q[T: Ord] = { a: T } derives Ord\n";
4302 let names: Vec<&str> = constraint_token_spans(src)
4303 .into_iter()
4304 .map(|s| &src[s.start..s.end])
4305 .collect();
4306 assert_eq!(names, ["Ord", "Ord", "Ord"]);
4307 let first = constraint_token_spans(src)[0];
4308 assert!(
4309 src[..first.start].ends_with("derives "),
4310 "derives clause is the first span"
4311 );
4312 }
4313
4314 #[test]
4316 fn describe_service_renders_routes() {
4317 let src = "context demo.app\n\nservice greeter {\n on call(name: String) -> Effect[String] by Caller {\n Effect.pure(name)\n }\n}\n";
4318 let out = describe_symbol(src, "greeter").unwrap();
4319 assert!(out.contains("service greeter {"), "{out}");
4320 assert!(out.contains("on call"), "{out}");
4321 }
4322
4323 #[test]
4326 fn describe_agent_renders_store_and_invariants() {
4327 let src = "context demo.app\n\nagent Counter {\n key id: String\n store count: Cell[Int] = 0\n invariant non_negative: count >= 0\n transition monotonic: new.count >= old.count\n on call bump() -> Effect[Result[(), String]] {\n Ok(())\n }\n}\n";
4328 let out = describe_symbol(src, "Counter").unwrap();
4329 assert!(out.contains("agent Counter {"), "{out}");
4330 assert!(out.contains("key id: String"), "{out}");
4331 assert!(out.contains("store count: Cell[Int]"), "{out}");
4332 assert!(out.contains("invariant non_negative: count >= 0"), "{out}");
4333 assert!(
4334 out.contains("transition monotonic: new.count >= old.count"),
4335 "{out}"
4336 );
4337 }
4338
4339 #[test]
4342 fn qualified_callee_detects_upper_receiver_only() {
4343 let text = " let t = Clock.now()";
4344 let now = text.find("now").unwrap();
4345 assert_eq!(
4346 qualified_callee_at(text, Span::new(now, now + 3)).as_deref(),
4347 Some("Clock.now")
4348 );
4349 let text2 = " xs.fold(0)";
4352 let fold = text2.find("fold").unwrap();
4353 assert!(qualified_callee_at(text2, Span::new(fold, fold + 4)).is_none());
4354 let text3 = " total";
4356 assert!(qualified_callee_at(text3, Span::new(2, 7)).is_none());
4357 }
4358
4359 #[test]
4363 fn describe_agent_state_covers_key_store_keywords_and_fields() {
4364 let src = "context demo.app\n\nagent Sessions {\n key id: String\n store items: Map[String, Int] @indexed( by: id ) @bounded( 10000 )\n on call read() -> Effect[Int] {\n Effect.pure(0)\n }\n}\n";
4365
4366 let at_key_kw = src.find("key id").unwrap();
4369 let key_kw = describe_agent_state_at(src, at_key_kw).expect("hover on `key`");
4370 assert!(key_kw.contains("key id: String"), "{key_kw}");
4371 assert!(key_kw.contains("identity field"), "doc line: {key_kw}");
4372 let at_key_name = src.find("id: String").unwrap();
4373 let key_name = describe_agent_state_at(src, at_key_name).expect("hover on the key field");
4374 assert_eq!(key_kw, key_name, "keyword and name hover match");
4375
4376 let at_store_kw = src.find("store items").unwrap();
4379 let store_kw = describe_agent_state_at(src, at_store_kw).expect("hover on `store`");
4380 assert!(
4381 store_kw.contains("store items: Map[String, Int]"),
4382 "{store_kw}"
4383 );
4384 assert!(
4385 store_kw.contains("@indexed(by: id)"),
4386 "annotation: {store_kw}"
4387 );
4388 assert!(
4389 store_kw.contains("@bounded(10000)"),
4390 "annotation: {store_kw}"
4391 );
4392 assert!(
4393 store_kw.contains("persisted agent-state"),
4394 "doc line: {store_kw}"
4395 );
4396 let at_store_name = src.find("items:").unwrap();
4397 let store_name =
4398 describe_agent_state_at(src, at_store_name).expect("hover on the store field");
4399 assert_eq!(store_kw, store_name, "keyword and name hover match");
4400
4401 assert!(describe_agent_state_at(src, src.find("Sessions").unwrap()).is_none());
4404 assert!(describe_agent_state_at(src, src.find("Map").unwrap()).is_none());
4405 assert!(describe_agent_state_at(src, src.find("by: id").unwrap() + 4).is_none());
4408 }
4409
4410 const TODOS: &str = "context demo.todos\n\
4415 \n\
4416 agent Todos {\n\
4417 \x20 key owner: String\n\
4418 \n\
4419 \x20 store items: Map[String, Int]\n\
4420 \x20 store lastSeq: Cell[Int]\n\
4421 \n\
4422 \x20 invariant nonneg: lastSeq >= 0\n\
4423 \n\
4424 \x20 on call add(n: Int) -> Effect[()] {\n\
4425 \x20 let next = lastSeq + 1\n\
4426 \x20 let _ <- items.put(owner, next)\n\
4427 \x20 lastSeq := next\n\
4428 \x20 Effect.pure(())\n\
4429 \x20 }\n\
4430 }\n";
4431
4432 #[test]
4433 fn describe_agent_state_covers_references_in_handler_bodies() {
4434 let src = TODOS;
4435 let at = |needle: &str| src.find(needle).expect("needle is in the fixture");
4436
4437 let store_decl = describe_agent_state_at(src, at("store lastSeq")).unwrap();
4439 assert!(
4440 store_decl.contains("store lastSeq: Cell[Int]"),
4441 "{store_decl}"
4442 );
4443 for (what, needle) in [
4444 ("a bare read", "lastSeq + 1"),
4445 ("a `:=` write target", "lastSeq := next"),
4446 ("an invariant subject", "lastSeq >= 0"),
4447 ] {
4448 let hover = describe_agent_state_at(src, at(needle))
4449 .unwrap_or_else(|| panic!("no hover on {what}"));
4450 assert_eq!(hover, store_decl, "{what} hovers as its declaration");
4451 }
4452 let recv = describe_agent_state_at(src, at("items.put")).expect("hover on the receiver");
4454 assert_eq!(
4455 recv,
4456 describe_agent_state_at(src, at("store items")).unwrap()
4457 );
4458
4459 let key_decl = describe_agent_state_at(src, at("key owner")).unwrap();
4461 let key_ref = describe_agent_state_at(src, at("owner, next")).expect("hover on `owner`");
4462 assert_eq!(key_ref, key_decl);
4463 assert!(key_ref.contains("key owner: String"), "{key_ref}");
4464
4465 assert!(describe_agent_state_at(src, at("next = lastSeq")).is_none());
4468 assert!(describe_agent_state_at(src, at("Effect.pure")).is_none());
4469 }
4470
4471 #[test]
4474 fn describe_store_op_renders_the_operation_signature() {
4475 let src = TODOS;
4476 let at_put = src
4477 .find("put(owner")
4478 .expect("the store op is in the fixture");
4479 let put = describe_store_op_at(src, at_put, &[]).expect("hover on `items.put`");
4480 assert!(put.contains("put(key: K, value: V) -> Effect[()]"), "{put}");
4481 assert!(put.contains("store items: Map[String, Int]"), "{put}");
4483
4484 let shadow = [bynk_check::locals::LocalBinding {
4487 name: "items".into(),
4488 def_span: Span::new(0, 5),
4489 kind: bynk_check::locals::LocalKind::Let,
4490 ty: "Map[String, Int]".into(),
4491 scope: Span::new(0, src.len()),
4492 }];
4493 assert!(describe_store_op_at(src, at_put, &shadow).is_none());
4494
4495 let cell_put = src.replace("items.put(owner, next)", "lastSeq.put(owner, next)");
4498 assert!(
4499 describe_store_op_at(&cell_put, cell_put.find("put(owner").unwrap(), &[]).is_none(),
4500 "a `Cell` has no `put`"
4501 );
4502 assert!(describe_store_op_at(src, src.find("pure(()").unwrap(), &[]).is_none());
4503 assert!(describe_store_op_at(src, src.find("next = lastSeq").unwrap(), &[]).is_none());
4504 }
4505
4506 #[test]
4512 fn a_qualified_receiver_is_not_a_store_op_or_a_state_reference() {
4513 let src = "context demo.todos\n\
4514 \n\
4515 type Inner = { put: Int }\n\
4516 type Payload = { items: Inner, lastSeq: Int }\n\
4517 \n\
4518 agent Todos {\n\
4519 \x20 key owner: String\n\
4520 \x20 store items: Map[String, Int]\n\
4521 \x20 store lastSeq: Cell[Int]\n\
4522 \n\
4523 \x20 on call add(p: Payload) -> Effect[()] {\n\
4524 \x20 let a = p.items.put\n\
4525 \x20 let b = p.lastSeq\n\
4526 \x20 Effect.pure(())\n\
4527 \x20 }\n\
4528 }\n";
4529 let at_put = src.find("put\n").expect("the qualified member");
4531 assert!(describe_store_op_at(src, at_put, &[]).is_none());
4532 let at_items = src.find("p.items").unwrap() + "p.".len();
4535 assert!(describe_agent_state_at(src, at_items).is_none());
4536 let at_seq = src.find("p.lastSeq").unwrap() + "p.".len();
4537 assert!(describe_agent_state_at(src, at_seq).is_none());
4538
4539 let bare = src.find("store items").unwrap();
4541 assert!(describe_agent_state_at(src, bare).is_some());
4542 }
4543
4544 #[test]
4549 fn describe_symbol_renders_a_resolved_record_field() {
4550 let src = "context demo.todos\n\n\
4551 type Title = String where NonEmpty\n\n\
4552 type Stored = {\n\
4553 \x20 seq: Int where NonNegative,\n\
4554 \x20 title: Title,\n\
4555 }\n";
4556 let title = describe_symbol(src, "Stored.title").expect("hover on `Stored.title`");
4557 assert!(title.contains("title: Title"), "{title}");
4558 assert!(title.contains("A field of `Stored`"), "{title}");
4559 let seq = describe_symbol(src, "Stored.seq").expect("hover on `Stored.seq`");
4561 assert!(seq.contains("seq: Int where NonNegative"), "{seq}");
4562
4563 assert!(
4565 describe_symbol(src, "Stored")
4566 .unwrap()
4567 .contains("type Stored")
4568 );
4569 assert!(describe_symbol(src, "Stored.nope").is_none());
4571 assert!(describe_symbol(src, "Nope.title").is_none());
4572 assert!(describe_symbol(src, "Title.title").is_none());
4573 }
4574
4575 #[test]
4580 fn describe_symbol_renders_an_event_and_its_defaulted_field() {
4581 let src = "context demo.orders\n\n\
4582 type Region = enum { Domestic, International }\n\n\
4583 event PaymentConfirmed = {\n\
4584 \x20 orderId: String,\n\
4585 \x20 region: Region = Region.Domestic,\n\
4586 }\n";
4587 let whole = describe_symbol(src, "PaymentConfirmed").expect("hover on the event itself");
4588 assert!(whole.contains("type PaymentConfirmed = {"), "{whole}");
4589 assert!(whole.contains("orderId: String"), "{whole}");
4590 assert!(
4591 whole.contains("region: Region = Region.Domestic"),
4592 "{whole}"
4593 );
4594
4595 let field = describe_symbol(src, "PaymentConfirmed.region")
4596 .expect("hover on `PaymentConfirmed.region`");
4597 assert!(
4598 field.contains("region: Region = Region.Domestic"),
4599 "{field}"
4600 );
4601 assert!(field.contains("A field of `PaymentConfirmed`"), "{field}");
4602
4603 let order_id = describe_symbol(src, "PaymentConfirmed.orderId")
4605 .expect("hover on `PaymentConfirmed.orderId`");
4606 assert!(order_id.contains("orderId: String"), "{order_id}");
4607 assert!(!order_id.contains('='), "{order_id}");
4608
4609 assert!(describe_symbol(src, "PaymentConfirmed.nope").is_none());
4610 assert!(describe_symbol(src, "Nope.region").is_none());
4611 }
4612
4613 #[test]
4617 fn describe_symbol_renders_an_events_schema_annotation() {
4618 let src = "context demo.orders\n\n\
4619 event PaymentConfirmed @schema(2) = {\n\
4620 \x20 orderId: String,\n\
4621 }\n";
4622 let whole = describe_symbol(src, "PaymentConfirmed").expect("hover on the event itself");
4623 assert!(
4624 whole.contains("type PaymentConfirmed @schema(2) = {"),
4625 "{whole}"
4626 );
4627 assert!(whole.contains("orderId: String"), "{whole}");
4628 }
4629
4630 #[test]
4635 fn describe_symbol_renders_an_actor_in_both_forms() {
4636 let src = "context demo.auth\n\n\
4637 type UserId = String where NonEmpty\n\n\
4638 ---\n\
4639 A signed-in user.\n\
4640 ---\n\
4641 actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = UserId }\n\n\
4642 actor Public { auth = None }\n\n\
4643 actor Worker { auth = Internal }\n\n\
4644 actor Admin = User where hasClaim(\"admin\")\n";
4645
4646 let user = describe_symbol(src, "User").expect("hover on `User`");
4647 assert!(
4648 user.contains(
4649 "actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = UserId }"
4650 ),
4651 "{user}"
4652 );
4653 assert!(user.contains("A signed-in user."), "{user}");
4655
4656 let public = describe_symbol(src, "Public").expect("hover on `Public`");
4658 assert!(
4659 public.contains("actor Public { auth = None }") && !public.contains("identity"),
4660 "{public}"
4661 );
4662 assert!(
4663 describe_symbol(src, "Worker")
4664 .unwrap()
4665 .contains("actor Worker { auth = Internal }")
4666 );
4667
4668 let admin = describe_symbol(src, "Admin").expect("hover on `Admin`");
4670 assert!(
4671 admin.contains("actor Admin = User where hasClaim(\"admin\")"),
4672 "{admin}"
4673 );
4674
4675 assert!(describe_symbol(src, "Nobody").is_none());
4676 }
4677
4678 #[test]
4685 fn describe_symbol_escapes_an_actors_scheme_config() {
4686 let src = "context demo.auth\n\n\
4687 actor User { auth = Bearer(secret = \"a\\\"b\\\\c\") }\n";
4688 let hover = describe_symbol(src, "User").expect("hover on `User`");
4689 assert!(
4690 hover.contains("actor User { auth = Bearer(secret = \"a\\\"b\\\\c\") }"),
4691 "the config value must round-trip escaped:\n{hover}"
4692 );
4693
4694 let formatted = bynk_fmt::format_source(src, &bynk_fmt::FormatOptions::default())
4696 .expect("the fixture formats");
4697 let actor_line = formatted
4698 .lines()
4699 .find(|l| l.starts_with("actor User"))
4700 .expect("the actor line");
4701 assert!(
4702 hover.contains(actor_line),
4703 "hover:\n{hover}\nfmt: {actor_line}"
4704 );
4705 }
4706
4707 #[test]
4710 fn describe_symbol_renders_a_capability_operation() {
4711 let src = "context demo.svc\n\n\
4712 capability Logger {\n\
4713 \x20 ---\n\
4714 \x20 Record a line.\n\
4715 \x20 ---\n\
4716 \x20 fn info(message: String) -> Effect[()]\n\
4717 }\n\n\
4718 capability Clock {\n\
4719 \x20 fn now() -> Effect[Int]\n\
4720 }\n";
4721
4722 let info = describe_symbol(src, "Logger.info").expect("hover on `Logger.info`");
4723 assert!(
4724 info.contains("fn info(message: String) -> Effect[()]"),
4725 "{info}"
4726 );
4727 assert!(
4728 info.contains("An operation of capability `Logger`"),
4729 "{info}"
4730 );
4731 assert!(info.contains("Record a line."), "{info}");
4732
4733 let now = describe_symbol(src, "Clock.now").expect("hover on `Clock.now`");
4735 assert!(now.contains("fn now() -> Effect[Int]"), "{now}");
4736
4737 assert!(
4739 describe_symbol(src, "Logger")
4740 .unwrap()
4741 .contains("capability Logger")
4742 );
4743 assert!(describe_symbol(src, "Logger.nope").is_none());
4745 assert!(describe_symbol(src, "Clock.info").is_none());
4746 }
4747
4748 #[test]
4749 fn describe_symbol_renders_a_messages_bundle() {
4750 let src = "commons app.bundle\n\n\
4754 ---\n\
4755 The English reference bundle.\n\
4756 ---\n\
4757 messages \"en\" @reference {\n\
4758 \x20 \"greeting\" => \"Hello, {name}!\"\n\
4759 \x20 \"farewell\" => \"Bye\"\n\
4760 }\n";
4761
4762 let info = describe_symbol(src, "en").expect("hover on the `en` messages tag");
4763 assert!(info.contains("messages \"en\" @reference {"), "{info}");
4764 assert!(info.contains("\"greeting\" => …"), "{info}");
4765 assert!(info.contains("\"farewell\" => …"), "{info}");
4766 assert!(info.contains("The English reference bundle."), "{info}");
4767 }
4768
4769 #[test]
4774 fn describe_symbol_keys_methods_by_their_compound_name_only() {
4775 let src = "context demo.shop\n\n\
4776 type Counter = { count: Int }\n\
4777 type Gauge = { level: Int }\n\n\
4778 fn Counter.bump(self) -> Counter { Counter { count: self.count + 1 } }\n\n\
4779 fn Gauge.bump(self) -> Gauge { Gauge { level: self.level + 1 } }\n\n\
4780 fn free(n: Int) -> Int { n }\n";
4781
4782 let counter = describe_symbol(src, "Counter.bump").expect("hover on `Counter.bump`");
4784 assert!(
4785 counter.contains("fn Counter.bump(self) -> Counter") && !counter.contains("Gauge"),
4786 "{counter}"
4787 );
4788 let gauge = describe_symbol(src, "Gauge.bump").expect("hover on `Gauge.bump`");
4789 assert!(
4790 gauge.contains("fn Gauge.bump(self) -> Gauge") && !gauge.contains("Counter"),
4791 "{gauge}"
4792 );
4793
4794 assert!(describe_symbol(src, "bump").is_none());
4797 assert!(
4799 describe_symbol(src, "free")
4800 .unwrap()
4801 .contains("fn free(n: Int) -> Int")
4802 );
4803 assert!(describe_symbol(src, "Counter.nope").is_none());
4804 }
4805
4806 #[test]
4809 fn describe_self_renders_receiver_and_unwraps_agent() {
4810 use bynk_check::checker::{NamedKind, Ty, Types};
4811 let text = "self";
4812 let tys = &Types::new();
4813 let span = Span::new(0, 4);
4814 let account = vec![(
4816 span,
4817 tys.intern(Ty::Named {
4818 name: "Account".into(),
4819 kind: NamedKind::Record,
4820 args: Vec::new(),
4821 }),
4822 )];
4823 assert_eq!(
4824 describe_self_at(text, 0, &account, tys).as_deref(),
4825 Some("```bynk\nself: Account\n```")
4826 );
4827 let agent = vec![(
4830 span,
4831 tys.intern(Ty::Named {
4832 name: "__CounterSelf".into(),
4833 kind: NamedKind::Record,
4834 args: Vec::new(),
4835 }),
4836 )];
4837 assert_eq!(
4838 describe_self_at(text, 0, &agent, tys).as_deref(),
4839 Some("```bynk\nself: Counter\n```")
4840 );
4841 let other = "total";
4844 assert!(
4845 describe_self_at(
4846 other,
4847 0,
4848 &[(
4849 Span::new(0, 5),
4850 tys.intern(Ty::Named {
4851 name: "Int".into(),
4852 kind: NamedKind::Record,
4853 args: Vec::new(),
4854 }),
4855 )],
4856 tys
4857 )
4858 .is_none()
4859 );
4860 }
4861
4862 const CACHE_SVC: &str = "context api\nservice api from http {\n @cache(maxAge: 5.minutes, scope: public)\n on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"y\")\n }\n}\n";
4863
4864 #[test]
4865 fn an_edge_cache_hovers_with_its_stanza() {
4866 let src =
4868 "context a\nconsumes bynk.cloudflare { EdgeCache }\ncapability Edge = EdgeCache\n";
4869 let tokens = tokenize(src).unwrap();
4870 let (unit, _) = parse_unit_with_recovery(&tokens, src);
4871 let Some(SourceUnit::Context(ctx)) = unit else {
4872 panic!("a context")
4873 };
4874 let decl = ctx
4875 .items
4876 .iter()
4877 .find_map(|i| match i {
4878 CommonsItem::Capability(c) => Some(c),
4879 _ => None,
4880 })
4881 .unwrap();
4882 let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4883 assert!(hover.contains("Emits `[cache] enabled = true`"), "{hover}");
4884 assert!(!hover.contains("its own storage"), "{hover}");
4885 }
4886
4887 #[test]
4888 fn a_queue_producer_hovers_with_its_stanza() {
4889 let src = "context a\nconsumes bynk.cloudflare { Queue }\ncapability OrderEvents = Queue @name(\"order-events\")\n";
4891 let tokens = tokenize(src).unwrap();
4892 let (unit, _) = parse_unit_with_recovery(&tokens, src);
4893 let Some(SourceUnit::Context(ctx)) = unit else {
4894 panic!("a context")
4895 };
4896 let decl = ctx
4897 .items
4898 .iter()
4899 .find_map(|i| match i {
4900 CommonsItem::Capability(c) => Some(c),
4901 _ => None,
4902 })
4903 .unwrap();
4904 let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4905 assert!(
4906 hover.contains("Emits `[[queues.producers]]` sending to queue `order-events`"),
4907 "{hover}"
4908 );
4909 }
4910
4911 #[test]
4912 fn an_analytics_dataset_hovers_with_its_stanza() {
4913 let src =
4915 "context a\nconsumes bynk.cloudflare { Analytics }\ncapability Signups = Analytics\n";
4916 let tokens = tokenize(src).unwrap();
4917 let (unit, _) = parse_unit_with_recovery(&tokens, src);
4918 let Some(SourceUnit::Context(ctx)) = unit else {
4919 panic!("a context")
4920 };
4921 let decl = ctx
4922 .items
4923 .iter()
4924 .find_map(|i| match i {
4925 CommonsItem::Capability(c) => Some(c),
4926 _ => None,
4927 })
4928 .unwrap();
4929 let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4930 assert!(
4931 hover.contains("Emits `[[analytics_engine_datasets]]`")
4932 && hover.contains("shop_cart_signups"),
4933 "{hover}"
4934 );
4935 }
4936
4937 #[test]
4938 fn a_rate_limiter_hovers_with_its_stanza() {
4939 let src = "context a\nconsumes bynk.cloudflare { RateLimit }\ncapability LoginLimit = RateLimit @limit(20) @period(1.minute)\n";
4941 let tokens = tokenize(src).unwrap();
4942 let (unit, _) = parse_unit_with_recovery(&tokens, src);
4943 let Some(SourceUnit::Context(ctx)) = unit else {
4944 panic!("a context")
4945 };
4946 let decl = ctx
4947 .items
4948 .iter()
4949 .find_map(|i| match i {
4950 CommonsItem::Capability(c) => Some(c),
4951 _ => None,
4952 })
4953 .unwrap();
4954 let hover = describe_derived_capability(decl, Some("bynk.cloudflare"), None);
4955 assert!(
4956 hover.contains(
4957 "`simple = { limit = 20, period = 60 }`: 20 calls per key every 60 seconds"
4958 ),
4959 "{hover}"
4960 );
4961 assert!(hover.contains("approximate"), "{hover}");
4962 }
4963
4964 #[test]
4965 fn hover_on_cache_annotation_describes_it() {
4966 let offset = CACHE_SVC.find("cache").unwrap() + 1;
4968 let hover = describe_handler_annotation_at(CACHE_SVC, offset).expect("hovers @cache");
4969 assert!(hover.contains("`@cache`"), "names the annotation: {hover}");
4970 assert!(hover.contains("maxAge"), "documents maxAge: {hover}");
4971 assert!(hover.contains("scope"), "documents scope: {hover}");
4972 assert!(hover.contains("immutable"), "documents immutable: {hover}");
4973 assert!(
4974 hover.contains("Emits `Cache-Control: public, max-age=300`."),
4975 "shows the emitted header: {hover}"
4976 );
4977 let ok_offset = CACHE_SVC.find("Ok(").unwrap() + 1;
4979 assert!(describe_handler_annotation_at(CACHE_SVC, ok_offset).is_none());
4980 }
4981
4982 #[test]
4983 fn hover_on_immutable_cache_shows_the_directive() {
4984 let svc = "context api\nservice api from http {\n @cache(maxAge: 365.days, scope: public, immutable: true)\n on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"y\")\n }\n}\n";
4985 let hover = describe_handler_annotation_at(svc, svc.find("cache").unwrap() + 1)
4986 .expect("hovers @cache");
4987 assert!(
4988 hover.contains("Emits `Cache-Control: public, max-age=31536000, immutable`."),
4989 "{hover}"
4990 );
4991 }
4992
4993 #[test]
4994 fn hover_on_form_annotation_shows_the_decoding_rule_and_effective_cap() {
4995 let svc = "context api\ntype Q = { q: String }\nservice api from http {\n limits { maxBody: 4096 }\n @form\n on POST(\"/s\") (body: Q) -> Effect[HttpResult[String]] by v: Visitor {\n Ok(body.q)\n }\n}\n";
4996 let hover = describe_handler_annotation_at(svc, svc.find("form").unwrap() + 1)
4997 .expect("hovers @form");
4998 assert!(hover.contains("`@form`"), "names the annotation: {hover}");
4999 assert!(
5000 hover.contains("application/x-www-form-urlencoded"),
5001 "{hover}"
5002 );
5003 assert!(
5004 hover.contains("`415"),
5005 "says the other-type answer: {hover}"
5006 );
5007 assert!(
5008 hover.contains("4096 bytes"),
5009 "shows the service cap: {hover}"
5010 );
5011 }
5012
5013 #[test]
5014 fn hover_on_multipart_annotation_shows_the_rules_and_effective_cap() {
5015 let svc = "context api\nconsumes bynk { File }\ntype Q = { f: File }\nservice api from http {\n limits { maxBody: 4096 }\n @multipart\n on POST(\"/s\") (body: Q) -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"x\")\n }\n}\n";
5016 let hover = describe_handler_annotation_at(svc, svc.find("multipart").unwrap() + 1)
5017 .expect("hovers @multipart");
5018 assert!(
5019 hover.contains("`@multipart`"),
5020 "names the annotation: {hover}"
5021 );
5022 assert!(hover.contains("multipart/form-data"), "{hover}");
5023 assert!(hover.contains("MalformedForm"), "{hover}");
5024 assert!(
5025 hover.contains("4096 bytes"),
5026 "shows the service cap: {hover}"
5027 );
5028 }
5029
5030 #[test]
5031 fn hover_on_raw_annotation_shows_content_type_and_effective_cap() {
5032 let svc = "context api\nservice api from http {\n limits { maxBody: 1000 }\n @raw(contentType: \"image/png\")\n on POST(\"/a\") (body: Bytes) -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"y\")\n }\n @raw(contentType: \"*/*\")\n @limit(maxBody: 50)\n on POST(\"/b\") (body: Bytes) -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"y\")\n }\n}\n";
5033 let first =
5034 describe_handler_annotation_at(svc, svc.find("raw").unwrap() + 1).expect("hovers @raw");
5035 assert!(first.contains("`image/png`"), "names the type: {first}");
5036 assert!(first.contains("1000 bytes"), "service cap: {first}");
5037 let second = describe_handler_annotation_at(svc, svc.rfind("raw").unwrap() + 1)
5038 .expect("hovers @raw");
5039 assert!(second.contains("any"), "wildcard: {second}");
5040 assert!(second.contains("50 bytes"), "the route's own cap: {second}");
5041 }
5042
5043 #[test]
5044 fn annotation_token_spans_cover_name_and_labels() {
5045 let spans = handler_annotation_token_spans(CACHE_SVC);
5046 assert_eq!(spans.len(), 3, "{spans:?}");
5048 let texts: Vec<&str> = spans.iter().map(|s| &CACHE_SVC[s.start..s.end]).collect();
5049 assert_eq!(texts, ["@cache", "maxAge", "scope"]);
5050 let plain = "context api\nservice api from http {\n on GET(\"/x\") () -> Effect[HttpResult[String]] by v: Visitor { Ok(\"y\") }\n}\n";
5052 assert!(handler_annotation_token_spans(plain).is_empty());
5053 }
5054
5055 #[test]
5056 fn scan_doc_link_candidates_accepts_a_multi_segment_unit_path() {
5057 let cands = scan_doc_link_candidates("See [a.b.Name] and [e.g.] and [x. y].");
5058 let names: Vec<_> = cands.iter().map(|c| c.name.as_str()).collect();
5059 assert_eq!(names, ["a.b.Name"]);
5060 }
5061
5062 #[test]
5063 fn doc_link_spans_attached_reports_the_next_identifier() {
5064 let src = "--- the [x] param\nfn f(x: Int) -> Int { x }\n";
5065 let links = doc_link_spans_attached(src);
5066 assert_eq!(links.len(), 1);
5067 assert_eq!(links[0].attached, Some(src.find("f(").unwrap()));
5068 }
5069
5070 #[test]
5071 fn doc_link_spans_attached_puts_a_method_at_its_name() {
5072 let src = "--- the [x] param\nfn Box.plus(self, x: Int) -> Int { x }\n";
5073 let links = doc_link_spans_attached(src);
5074 assert_eq!(links[0].attached, Some(src.find("plus").unwrap()));
5075 }
5076
5077 #[test]
5078 fn doc_link_unit_names_a_suites_target() {
5079 let src = "suite window\n";
5080 assert_eq!(own_declaration_name(src), None);
5081 assert_eq!(doc_link_unit(src).as_deref(), Some("window"));
5082 }
5083}
5084
5085#[cfg(test)]
5086mod snapshot_tests {
5087 use super::*;
5088
5089 const SUITE: &str = "suite shape\n\ncase \"reads\" {\n expect read(1) matches snapshot \"first\"\n let matches = 1\n}\n";
5090
5091 #[test]
5093 fn the_words_of_a_claim_are_keyword_spans() {
5094 let words: Vec<&str> = snapshot_keyword_spans(SUITE)
5095 .into_iter()
5096 .map(|s| &SUITE[s.start..s.end])
5097 .collect();
5098 assert_eq!(words, ["matches", "snapshot"]);
5099 }
5100
5101 #[test]
5102 fn hover_shows_the_stored_snapshot_or_says_it_is_missing() {
5103 let at = SUITE.find("snapshot \"first\"").unwrap();
5104 let stored = r#"{"reads":{"first":{"id":"a"}}}"#;
5105 let with = describe_snapshot_at(SUITE, at, Some(stored)).expect("hovers");
5106 assert!(
5107 with.contains("Stored:") && with.contains("\"id\": \"a\""),
5108 "{with}"
5109 );
5110 let without = describe_snapshot_at(SUITE, at, None).expect("hovers");
5111 assert!(without.contains("Not yet recorded"), "{without}");
5112 let other = SUITE.rfind("matches").unwrap();
5114 assert!(describe_snapshot_at(SUITE, other, None).is_none());
5115 }
5116}