1use std::collections::HashMap;
43use std::path::{Path, PathBuf};
44
45use bynk_check::checker::Types;
46use bynk_check::index::SymbolKind;
47use bynk_syntax::span::Span;
48
49use crate::index_queries::{DocLinkResolution, resolve_doc_link_in};
50
51pub struct HoverAnalysis<'a> {
53 pub index: &'a bynk_check::index::ProjectIndex,
54 pub snapshots: &'a HashMap<PathBuf, String>,
56 pub locals: &'a bynk_check::locals::FileLocals,
57 pub expr_types: &'a bynk_check::expr_types::FileExprTypes,
58 pub tys: &'a Types,
60 pub rel: &'a Path,
62 pub offset: usize,
63 pub capability_paths: &'a bynk_check::capability_paths::FileCapabilityPaths,
65 pub project_root: &'a Path,
68 pub doc_scope: &'a HashMap<String, Vec<String>>,
71 pub boundary_info: &'a HashMap<String, crate::ContextBoundaryInfo>,
74 pub context_count: usize,
82}
83
84pub struct HoverInput<'a> {
86 pub analysis: Option<HoverAnalysis<'a>>,
89 pub doc: Option<(&'a str, usize)>,
92 pub path: Option<&'a Path>,
96 pub files: Option<&'a HashMap<PathBuf, String>>,
102}
103
104pub fn hover_content(input: &HoverInput<'_>) -> Option<String> {
109 if let Some(a) = &input.analysis {
110 let tys = a.tys;
111 if let Some((key, def)) = crate::index_queries::definition_at(a.index, a.rel, a.offset)
122 && let Some(def_text) = a.snapshots.get(&def.path)
123 && let Some(content) = crate::symbols::describe_symbol(def_text, &key.name)
124 {
125 let ctx = crate::index_queries::DocLinkContext {
129 path: &def.path,
130 text: def_text,
131 attached: def.span.start,
132 locals: a.locals.get(&def.path).map_or(&[], |l| l.as_slice()),
133 };
134 let content = crate::doc_link_urls::linkify_doc_links(
135 &content,
136 a.index,
137 a.doc_scope,
138 a.project_root,
139 a.snapshots,
140 &key.unit,
141 Some(&ctx),
142 );
143 let content = if key.kind == SymbolKind::Service {
150 match wire_contract_for_service_key(a, key, &def.path, def_text) {
151 Some(model) => format!("{content}{}", wire_contract_appendix(&model)),
152 None => content,
153 }
154 } else {
155 content
156 };
157 return Some(with_capability_path(content, a));
158 }
159 if let Some(section) = capability_path_section(a) {
162 return Some(section);
163 }
164 if let Some(text) = a.snapshots.get(a.rel)
170 && let Some(content) = crate::symbols::describe_store_op_at(
171 text,
172 a.offset,
173 a.locals.get(a.rel).map_or(&[], |l| l.as_slice()),
174 )
175 {
176 return Some(content);
177 }
178 if let Some(text) = a.snapshots.get(a.rel)
181 && let Some(entries) = a.expr_types.get(a.rel)
182 && let Some(content) =
183 crate::symbols::describe_question_at(text, a.offset, entries, tys)
184 {
185 return Some(content);
186 }
187 if let Some(text) = a.snapshots.get(a.rel) {
192 let local = a
193 .locals
194 .get(a.rel)
195 .and_then(|locals| crate::locals_nav::describe_local_at(locals, text, a.offset))
196 .or_else(|| {
197 let entries = a.expr_types.get(a.rel)?;
198 crate::symbols::describe_self_at(text, a.offset, entries, tys)
199 });
200 if let Some(content) = local {
201 if let Some(section) = query_param_section(a, text) {
204 return Some(format!("{content}\n\n{section}"));
205 }
206 return Some(content);
207 }
208 }
209 if let Some(text) = a.snapshots.get(a.rel)
212 && let Some(entries) = a.expr_types.get(a.rel)
213 && let Some(content) =
214 crate::symbols::describe_effect_method_at(text, a.offset, entries, tys)
215 {
216 return Some(content);
217 }
218 if let Some(text) = a.snapshots.get(a.rel)
230 && let Some((service_name, handler)) = header_handler_at(text, a.offset)
231 && let Some((unit, _)) = crate::symbols::own_declaration_name(text)
232 && let Some(info) = a.boundary_info.get(&unit)
233 {
234 let expr_types = a.expr_types.get(a.rel).map(|v| v.as_slice()).unwrap_or(&[]);
235 if let Some(model) = crate::wire_contract::wire_contract_for_service(
236 &unit,
237 text,
238 &service_name,
239 &handler,
240 info,
241 expr_types,
242 tys,
243 a.context_count,
244 ) {
245 return Some(with_cron_schedule(text, a.offset, &model));
246 }
247 }
248 if let Some(text) = a.snapshots.get(a.rel)
254 && let Some(content) = doc_link_hover(a, text)
255 {
256 return Some(content);
257 }
258 }
259
260 let (text, offset) = input.doc?;
262 let Some((name, span)) = identifier_at(text, offset) else {
263 return crate::symbols::describe_keyword_at(text, offset).map(str::to_string);
270 };
271 let mut others: Vec<(&PathBuf, &str)> = match (input.files, &input.analysis) {
281 (Some(files), _) => files.iter().map(|(p, t)| (p, t.as_str())).collect(),
282 (None, Some(a)) => a
283 .snapshots
284 .iter()
285 .filter(|(p, _)| p.as_path() != a.rel)
286 .map(|(p, t)| (p, t.as_str()))
287 .collect(),
288 (None, None) => Vec::new(),
289 };
290 others.sort_by(|a, b| a.0.cmp(b.0));
291 if let Some(content) = describe_dependency_unit(input, text, span.start, &others) {
295 return Some(content);
296 }
297 let others: Vec<&str> = others.into_iter().map(|(_, t)| t).collect();
298 if let Some(content) =
299 crate::symbols::describe_unit_at(text, span.start, others.iter().copied())
300 {
301 return Some(content);
302 }
303 if let Some(content) = crate::symbols::describe_advance_at(text, span.start) {
305 return Some(content);
306 }
307 if let Some(content) = crate::symbols::describe_by_at(text, span.start) {
310 return Some(content);
311 }
312 if let Some(content) = crate::symbols::describe_derives_at(text, span.start) {
315 return Some(content);
316 }
317 if let Some(content) = crate::symbols::describe_constraint_at(text, span.start) {
318 return Some(content);
319 }
320 if let Some(content) = crate::symbols::describe_par_at(text, span.start) {
322 return Some(content);
323 }
324 if let Some(content) = crate::symbols::describe_private_at(text, span.start) {
326 return Some(content);
327 }
328 if let Some(content) = crate::symbols::describe_fixture_at(text, span.start) {
330 return Some(content);
331 }
332 if let Some(content) =
336 crate::symbols::describe_system_job_address_at(text, span.start, others.iter().copied())
337 {
338 return Some(content);
339 }
340 if let Some(content) = crate::symbols::describe_env_at(text, span.start) {
344 return Some(content);
345 }
346 if let Some(content) = crate::symbols::describe_run_id_at(text, span.start) {
348 return Some(content);
349 }
350 if let Some(content) = crate::symbols::describe_reserved_principal_at(text, span.start) {
353 return Some(content);
354 }
355 if let Some(content) = crate::symbols::describe_symbol(text, &name) {
357 return Some(content);
358 }
359 if let Some(content) = crate::symbols::describe_agent_state_at(text, span.start) {
364 return Some(content);
365 }
366 if let Some(content) = crate::symbols::describe_handler_annotation_at(text, span.start) {
369 return Some(content);
370 }
371 if let Some(content) = crate::symbols::describe_refinement_example_at(text, span.start) {
373 return Some(content);
374 }
375 crate::symbols::qualified_callee_at(text, span)
381 .and_then(|callee| {
382 describe_variant_anywhere(text, input.files, |src| {
383 crate::symbols::describe_variant_key(src, &callee)
384 })
385 .or_else(|| {
386 crate::signature_help::resolve_label(&callee, text, input.files).map(|sig| {
387 let typed = crate::signature_help::is_typed_read_label(&callee, &sig);
390 format!(
391 "```bynk\n{sig}\n```{}",
392 if typed {
393 typed_read_columns(&callee, &text[span.end..], text, input.files)
394 } else {
395 String::new()
396 }
397 )
398 })
399 })
400 })
401 .or_else(|| {
408 input
409 .files
410 .zip(input.path)
411 .and_then(|(content, path)| {
412 crate::symbols::describe_symbol_cross_file(content, path, &name)
413 })
414 .map(|(_other_path, desc)| desc)
415 })
416 .or_else(|| {
421 describe_variant_anywhere(text, input.files, |src| {
422 crate::symbols::describe_variant_named(src, &name)
423 })
424 })
425 .or_else(|| crate::symbols::describe_firstparty_symbol(&name))
426 .or_else(|| describe_fault_builtin(&name, &text[span.end..]))
429 .or_else(|| describe_iso_date_predicate(&name, &text[..span.start]))
431}
432
433fn describe_cron_predicate(name: &str, before: &str) -> Option<String> {
435 if name != "Cron" {
436 return None;
437 }
438 let line = before.rsplit('\n').next().unwrap_or(before);
439 (line.contains("where") || line.trim_end().ends_with("&&")).then(|| {
440 "```bynk\nCron\n```\n\nA `String` refinement predicate: the value is a valid Cloudflare \
441 cron schedule. Five fields (`minute hour day-of-month month day-of-week`) separated by \
442 exactly one space; minute `0-59`, hour `0-23`, day of month `1-31` (also `L`, `W`), \
443 month `1-12` or `JAN`-`DEC`, day of week `1-7` with `1` = Sunday, or `SUN`-`SAT` \
444 (also `L`, `#`). `* , - /` work in every field. No seconds, year, `?` or `@daily`. \
445 Schedules run in UTC. Checked at compile time for a literal, and at runtime by `.of`, \
446 `Json.decode` and the HTTP boundary."
447 .to_string()
448 })
449}
450
451fn with_cron_schedule(
454 text: &str,
455 offset: usize,
456 model: &crate::wire_contract::WireContractModel,
457) -> String {
458 let contract = wire_contract_standalone(model);
459 match describe_cron_schedule_literal(text, offset) {
460 Some(fields) => format!("{fields}\n\n---\n\n{contract}"),
461 None => contract,
462 }
463}
464
465pub(crate) fn describe_cron_schedule_literal(text: &str, offset: usize) -> Option<String> {
469 let line_start = text[..offset].rfind('\n').map_or(0, |i| i + 1);
470 let line_end = text[offset..].find('\n').map_or(text.len(), |i| offset + i);
471 let line = &text[line_start..line_end];
472 let at = offset - line_start;
473 let open = line.find("schedule(\"")? + "schedule(\"".len();
474 let close = open + line[open..].find('"')?;
475 if at < open - 1 || at > close {
476 return None;
477 }
478 let fields = bynk_syntax::cron::describe_fields(&line[open..close])?;
479 let rows: Vec<String> = fields
480 .iter()
481 .map(|(name, text)| format!("- {name}: `{text}`"))
482 .collect();
483 Some(format!(
484 "```bynk\nschedule(\"{}\")\n```\n\nA cron schedule (UTC):\n\n{}",
485 &line[open..close],
486 rows.join("\n")
487 ))
488}
489
490fn describe_iso_date_predicate(name: &str, before: &str) -> Option<String> {
493 if name == "Cron" {
495 return describe_cron_predicate(name, before);
496 }
497 if name != "IsoDate" {
498 return None;
499 }
500 let line = before.rsplit('\n').next().unwrap_or(before);
501 (line.contains("where") || line.trim_end().ends_with("&&")).then(|| {
502 "```bynk\nIsoDate\n```\n\nA `String` refinement predicate: the value is a calendar date, \
503 exactly `YYYY-MM-DD` (years 0000 to 9999) and a date that exists \
504 (`2028-02-29` is valid; `2026-02-29` and `2026-13-01` are not). \
505 Checked at compile time for a literal, and at runtime by `.of`, `Json.decode` \
506 and the HTTP boundary. `Instant.fromIso(\"\\(day)T00:00:00Z\")` is always \
507 `Some` for such a value."
508 .to_string()
509 })
510}
511
512fn typed_read_columns(
517 callee: &str,
518 after: &str,
519 text: &str,
520 files: Option<&HashMap<PathBuf, String>>,
521) -> String {
522 use bynk_syntax::ast::{CommonsItem, SourceUnit, TypeBody};
523 if !(callee.ends_with(".select") || callee.ends_with(".firstAs")) {
524 return String::new();
525 }
526 let Some(row) = after
527 .strip_prefix('[')
528 .and_then(|r| r.split(']').next())
529 .map(str::trim)
530 .filter(|r| !r.is_empty() && r.chars().all(|c| c.is_alphanumeric() || c == '_'))
531 else {
532 return String::new();
533 };
534 let mut cols = None;
535 crate::completion::for_each_unit(text, files, |unit| {
536 let items = match unit {
537 SourceUnit::Commons(c) => &c.items,
538 SourceUnit::Context(c) => &c.items,
539 SourceUnit::Adapter(a) => &a.items,
540 _ => return,
541 };
542 for item in items {
543 if let CommonsItem::Type(t) = item
544 && t.name.name == row
545 && let TypeBody::Record(r) = &t.body
546 && cols.is_none()
547 {
548 cols = Some(
549 r.fields
550 .iter()
551 .map(|f| format!("\"{}\"", f.name.name.replace('"', "\"\"")))
552 .collect::<Vec<_>>()
553 .join(", "),
554 );
555 }
556 }
557 });
558 cols.map_or_else(String::new, |c| {
559 format!("\n\nThe compiler writes `SELECT {c}` ahead of the literal.")
560 })
561}
562
563fn describe_fault_builtin(name: &str, after: &str) -> Option<String> {
566 let info = bynk_syntax::keywords::BUILTIN_FUNCTIONS
567 .iter()
568 .find(|k| k.word == name)?;
569 after.trim_start().starts_with('(').then(|| {
570 format!(
571 "```bynk\n{name}(message: String) -> never returns\n```\n\n{}",
572 info.meaning
573 )
574 })
575}
576
577fn capability_path_section(a: &HoverAnalysis<'_>) -> Option<String> {
580 crate::capability_path::hover_section(
581 &crate::capability_path::PathView {
582 graphs: a.capability_paths,
583 snapshots: a.snapshots,
584 project_root: a.project_root,
585 rel: a.rel,
586 },
587 a.offset,
588 )
589}
590
591fn with_capability_path(content: String, a: &HoverAnalysis<'_>) -> String {
594 match capability_path_section(a) {
595 Some(section) => format!("{content}\n\n---\n\n{section}"),
596 None => content,
597 }
598}
599
600fn describe_dependency_unit(
606 input: &HoverInput<'_>,
607 text: &str,
608 offset: usize,
609 files: &[(&PathBuf, &str)],
610) -> Option<String> {
611 let written = crate::symbols::unit_name_at(text, offset)?;
612 let empty = HashMap::new();
616 let view = match &input.analysis {
617 Some(a) => {
618 crate::packages::DependencyView::for_root(a.project_root, input.files.unwrap_or(&empty))
619 }
620 None => input
621 .files
622 .and_then(crate::packages::DependencyView::from_files),
623 }?;
624 let target = view.resolve(&written)?;
625 let root = input.analysis.as_ref().map(|a| a.project_root);
626 let sources = files.iter().filter(|(p, _)| {
627 let path = match root {
628 Some(r) if p.is_relative() => r.join(p),
629 _ => (*p).clone(),
630 };
631 view.package_of(&path) == Some(&target.package)
632 });
633 let mut out = crate::symbols::describe_unit(sources.map(|(_, t)| *t), &target.unit)?;
634 out.push('\n');
635 out.push_str(&crate::packages::hover_note(&target));
636 out.push('\n');
637 Some(out)
638}
639
640fn describe_variant_anywhere(
643 text: &str,
644 files: Option<&HashMap<PathBuf, String>>,
645 describe: impl Fn(&str) -> Option<String>,
646) -> Option<String> {
647 describe(text).or_else(|| {
648 let files = files?;
649 let mut paths: Vec<&PathBuf> = files.keys().collect();
650 paths.sort();
651 paths
652 .into_iter()
653 .map(|p| &files[p])
654 .filter(|src| src.as_str() != text)
655 .find_map(|src| describe(src))
656 })
657}
658
659pub fn identifier_at(text: &str, offset: usize) -> Option<(String, Span)> {
666 use bynk_syntax::lexer::TokenKind;
667 let tokens = bynk_syntax::lexer::tokenize_expanding_holes(text).ok()?;
668 tokens
669 .iter()
670 .find(|t| {
671 t.span.start <= offset
672 && offset < t.span.end
673 && matches!(
674 t.kind,
675 TokenKind::Ident
676 | TokenKind::Int
677 | TokenKind::String
678 | TokenKind::Bool
679 | TokenKind::Float
680 | TokenKind::Decimal
681 | TokenKind::Result
682 | TokenKind::Option
683 | TokenKind::Effect
684 )
685 })
686 .map(|t| (text[t.span.start..t.span.end].to_string(), t.span))
687}
688
689fn wire_contract_for_service_key(
708 a: &HoverAnalysis<'_>,
709 key: &bynk_check::index::SymbolKey,
710 def_path: &Path,
711 def_text: &str,
712) -> Option<crate::wire_contract::WireContractModel> {
713 let tys = a.tys;
714 let info = a.boundary_info.get(&key.unit)?;
715 let svc = info.services.get(&key.name)?;
716 let [handler] = svc.handlers.as_slice() else {
717 return None;
718 };
719 let expr_types = a
720 .expr_types
721 .get(def_path)
722 .map(|v| v.as_slice())
723 .unwrap_or(&[]);
724 crate::wire_contract::wire_contract_for_service(
725 &key.unit,
726 def_text,
727 &key.name,
728 handler,
729 info,
730 expr_types,
731 tys,
732 a.context_count,
733 )
734}
735
736fn header_handler_at(text: &str, offset: usize) -> Option<(String, bynk_syntax::ast::Handler)> {
745 use bynk_syntax::ast::{CommonsItem, SourceUnit};
746 let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
747 let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
748 let items: &[CommonsItem] = match parsed.as_ref()? {
749 SourceUnit::Context(c) => &c.items,
750 SourceUnit::Adapter(a) => &a.items,
751 SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
752 };
753 for item in items {
754 let CommonsItem::Service(s) = item else {
755 continue;
756 };
757 for h in &s.handlers {
758 let prefix_end = h
764 .params
765 .first()
766 .map(|p| p.span.start)
767 .unwrap_or(h.body.span.start);
768 if h.span.start <= offset && offset < prefix_end {
769 return Some((s.name.name.clone(), h.clone()));
770 }
771 }
772 }
773 None
774}
775
776fn query_param_section(a: &HoverAnalysis<'_>, text: &str) -> Option<String> {
782 use bynk_syntax::ast::{CommonsItem, SourceUnit, TypeBody, TypeRef};
783 let word_start = text[..a.offset]
784 .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
785 .map_or(0, |i| i + 1);
786 let word_end = a.offset
787 + text[a.offset..]
788 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
789 .unwrap_or(text.len() - a.offset);
790 let word = &text[word_start..word_end];
792 let heading = match word {
793 "query" => {
794 "**Query string** — decoded and validated before the handler runs; unknown keys are ignored."
795 }
796 "cookies" => {
797 "**Cookies** — parsed from the `Cookie` header, decoded and validated before the handler runs; unknown cookies are ignored."
798 }
799 _ => return None,
800 };
801 let (unit, _) = crate::symbols::own_declaration_name(text)?;
802 let info = a.boundary_info.get(&unit)?;
803 let tokens = bynk_syntax::lexer::tokenize(text).ok()?;
804 let (parsed, _errs) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, text);
805 let items: &[CommonsItem] = match parsed.as_ref()? {
806 SourceUnit::Context(c) => &c.items,
807 SourceUnit::Adapter(a) => &a.items,
808 SourceUnit::Commons(_) | SourceUnit::Suite(_) => return None,
809 };
810 let handler = items.iter().find_map(|item| {
811 let CommonsItem::Service(s) = item else {
812 return None;
813 };
814 s.handlers.iter().find(|h| {
815 matches!(
816 bynk_model::lower_handler_kind_ir(&h.kind),
817 bynk_model::IrHandlerKind::Http { .. }
818 ) && h.span.start <= a.offset
819 && a.offset < h.span.end
820 })
821 })?;
822 let param = handler.params.iter().find(|p| p.name.name == word)?;
823 let TypeRef::Named(id) = ¶m.type_ref else {
824 return None;
825 };
826 let Some(TypeBody::Record(record)) = info.types.get(&id.name).map(|t| &t.body) else {
827 return None;
828 };
829 let key = if word == "cookies" { "cookie" } else { "key" };
830 let mut out = format!("{heading}\n\n| {key} | type | |\n|---|---|---|\n");
831 for f in &record.fields {
832 let note = match (&f.type_ref, &f.init) {
833 (_, Some(init)) => format!("default `{}`", bynk_fmt::expr_to_string(init)),
834 (TypeRef::Option(..), None) => "optional".to_string(),
835 (TypeRef::List(..), None) => "repeatable, required".to_string(),
836 _ => "required".to_string(),
837 };
838 let note = match (&f.type_ref, &f.init) {
839 (TypeRef::List(..), Some(_)) => format!("repeatable, {note}"),
840 _ => note,
841 };
842 let key_name = match f.wire_name() {
844 Some(w) => format!("{w}` (field `{}", f.name.name),
845 None => f.name.name.clone(),
846 };
847 out.push_str(&format!(
848 "| `{}` | `{}` | {} |\n",
849 key_name,
850 bynk_check::context_checks::ts_type_ref_display(&f.type_ref),
851 note
852 ));
853 }
854 Some(out)
855}
856
857fn wire_contract_body(model: &crate::wire_contract::WireContractModel) -> String {
862 use crate::wire_contract::{BoundaryKind, Envelope};
863
864 let mut out = String::new();
865 if let BoundaryKind::Http { method, path } = &model.kind {
866 out.push_str(&format!("`{} {}`\n\n", method.as_str(), path));
867 }
868
869 out.push_str("**Request:** ");
870 match &model.envelope {
871 Envelope::Empty => out.push_str("no body — the handler never reads it.\n\n"),
872 Envelope::Bare { param, .. } => out.push_str(&format!(
873 "the request body **is** the value of `{param}` — not wrapped in an object.\n\n"
874 )),
875 Envelope::Raw {
876 param,
877 content_type,
878 } => out.push_str(&format!(
879 "the request body is the raw octets of `{param}` — not JSON, not base64 — sent as \
880 `{content_type}`.\n\n"
881 )),
882 Envelope::Keyed { params } => {
883 let names: Vec<&str> = params.iter().map(|(n, _)| n.as_str()).collect();
884 out.push_str(&format!(
885 "an object keyed by `{}`, in declaration order.\n\n",
886 names.join("`, `")
887 ));
888 }
889 }
890
891 if let Some(contract) = &model.contract {
892 out.push_str(&format!(
893 "**Cross-context contract** (hash `{}`) — change any of this and \
894 already-deployed callers get a 409:\n\n```\n{}\n```\n\n",
895 contract.hash,
896 bynk_check::symbols::display_type_names_in(&contract.normal_form)
898 ));
899 }
900
901 if !model.responses.is_empty() {
902 out.push_str("**Responses:**\n\n");
903 for r in &model.responses {
904 out.push_str(&format!("- `{} {}`\n", r.status, r.variant));
905 }
906 out.push('\n');
907 }
908
909 out
910}
911
912fn wire_contract_appendix(model: &crate::wire_contract::WireContractModel) -> String {
916 format!(
917 "\n\n---\n\n**Wire contract**\n\n{}",
918 wire_contract_body(model)
919 )
920}
921
922fn wire_contract_standalone(model: &crate::wire_contract::WireContractModel) -> String {
926 format!(
927 "**Wire contract** — `{}`\n\n{}",
928 model.service,
929 wire_contract_body(model)
930 )
931}
932
933fn doc_link_hover(a: &HoverAnalysis<'_>, text: &str) -> Option<String> {
941 let link = crate::symbols::doc_link_spans_attached(text)
944 .into_iter()
945 .find(|l| l.span.start <= a.offset && a.offset < l.span.end)?;
946 let name = link.name;
947 let owner_unit = crate::symbols::doc_link_unit(text)?;
948 let ctx = link
949 .attached
950 .map(|attached| crate::index_queries::DocLinkContext {
951 path: a.rel,
952 text,
953 attached,
954 locals: a.locals.get(a.rel).map_or(&[], |l| l.as_slice()),
955 });
956 let resolution = resolve_doc_link_in(a.index, a.doc_scope, &owner_unit, &name, ctx.as_ref());
957 let resolved = match resolution {
958 DocLinkResolution::Resolved(resolved) => Some(resolved),
959 DocLinkResolution::Ambiguous { unit, kinds } => {
960 let kinds: Vec<String> = kinds.iter().map(|k| format!("{k:?}")).collect();
961 return Some(format!(
962 "Ambiguous doc link `{name}` in `{unit}` (matches: {})",
963 kinds.join(", ")
964 ));
965 }
966 DocLinkResolution::Unresolved => None,
967 };
968 if let Some(resolved) = &resolved {
969 let def_text = a.snapshots.get(&resolved.def.path);
970 match (&resolved.key, def_text) {
971 (Some(key), Some(def_text)) => {
972 if let Some(content) = crate::symbols::describe_symbol(def_text, &key.name) {
973 let target_ctx = crate::index_queries::DocLinkContext {
975 path: &resolved.def.path,
976 text: def_text,
977 attached: resolved.def.span.start,
978 locals: a
979 .locals
980 .get(&resolved.def.path)
981 .map_or(&[], |l| l.as_slice()),
982 };
983 return Some(crate::doc_link_urls::linkify_doc_links(
984 &content,
985 a.index,
986 a.doc_scope,
987 a.project_root,
988 a.snapshots,
989 &key.unit,
990 Some(&target_ctx),
991 ));
992 }
993 }
994 (None, Some(def_text)) => {
997 let described = a.locals.get(&resolved.def.path).and_then(|locals| {
998 crate::locals_nav::describe_local_at(locals, def_text, resolved.def.span.start)
999 });
1000 return Some(described.unwrap_or_else(|| format!("parameter `{name}`")));
1001 }
1002 _ => {}
1003 }
1004 return Some(match &resolved.key {
1007 Some(key) => format!("`{}` — {:?} in `{}`", key.name, key.kind, key.unit),
1008 None => format!("parameter `{name}`"),
1009 });
1010 }
1011 let searched = a
1013 .doc_scope
1014 .get(&owner_unit)
1015 .map_or_else(|| owner_unit.clone(), |s| s.join(", "));
1016 Some(format!(
1017 "Unresolved doc link `{name}` — searched: {searched}"
1018 ))
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023
1024 #[test]
1027 fn cron_predicate_and_schedule_literal_hover() {
1028 let src = "commons demo.m\n\ntype S = String where Cron\n";
1029 let h = hover_at(src, "Cron", 0).expect("`Cron` hovers");
1030 assert!(h.contains("cron schedule"), "{h}");
1031 let elsewhere = hover_at("commons demo.m\n\nfn Cron() -> Int { 1 }\n", "Cron", 0);
1032 assert!(!elsewhere.is_some_and(|h| h.contains("refinement predicate")));
1033
1034 let line = " on schedule(\"0 2 * * MON-FRI\") () -> Effect[Result[(), String]] {";
1035 let at = line.find("2 *").unwrap();
1036 let h = describe_cron_schedule_literal(line, at).expect("fields named");
1037 assert!(
1038 h.contains("- minute: `0`") && h.contains("- day of week: `MON-FRI`"),
1039 "{h}"
1040 );
1041 assert!(describe_cron_schedule_literal(line, 0).is_none());
1042 let bad = " on schedule(\"61 * * * *\") () -> Effect[Result[(), String]] {";
1043 assert!(describe_cron_schedule_literal(bad, 16).is_none());
1044 }
1045 use super::*;
1046
1047 fn hover_at(src: &str, needle: &str, nth: usize) -> Option<String> {
1048 let offset = src.match_indices(needle).nth(nth).unwrap().0;
1049 hover_content(&HoverInput {
1050 analysis: None,
1051 doc: Some((src, offset)),
1052 path: None,
1053 files: None,
1054 })
1055 }
1056
1057 #[test]
1060 fn a_given_fn_hovers_with_its_capabilities() {
1061 let src = "context demo.m\n\ncapability Logger {\n fn error(m: String) -> Effect[()]\n}\n\nfn warn(what: String) -> Effect[()] given Logger {\n Logger.error(what)\n}\n\nservice s {\n on call() -> Effect[()] by Caller given Logger {\n warn(\"x\")\n }\n}\n";
1062 for nth in [0, 1] {
1063 let h = hover_at(src, "warn", nth).expect("`warn` hovers");
1064 assert!(
1065 h.contains("fn warn(what: String) -> Effect[()] given Logger")
1066 || h.contains("warn(what: String) -> Effect[()] given Logger"),
1067 "{h}"
1068 );
1069 }
1070 }
1071
1072 #[test]
1075 fn fault_builtins_hover_unless_shadowed() {
1076 let src = "commons demo.m\n\nfn f(n: Int) -> Int { if n > 0 { n } else { unreachable(\"never\") } }\n";
1077 let h = hover_at(src, "unreachable", 0).expect("`unreachable` hovers");
1078 assert!(
1079 h.contains("unreachable(message: String) -> never returns"),
1080 "{h}"
1081 );
1082 let shadowed =
1083 "commons demo.m\n\nfn todo(n: Int) -> Int { n }\n\nfn g() -> Int { todo(1) }\n";
1084 let h = hover_at(shadowed, "todo", 1).expect("the user's `todo` hovers");
1085 assert!(!h.contains("never returns"), "{h}");
1086 }
1087
1088 #[test]
1090 fn iso_date_predicate_hovers_in_where() {
1091 let src = "commons demo.m\n\ntype Day = String where IsoDate\n";
1092 let h = hover_at(src, "IsoDate", 0).expect("`IsoDate` hovers");
1093 assert!(h.contains("YYYY-MM-DD") && h.contains("2028-02-29"), "{h}");
1094 let elsewhere = "commons demo.m\n\nfn IsoDate() -> Int { 1 }\n";
1095 let h = hover_at(elsewhere, "IsoDate", 0);
1096 assert!(
1097 h.as_deref().is_none_or(|h| !h.contains("calendar date")),
1098 "{h:?}"
1099 );
1100 }
1101
1102 #[test]
1104 fn json_error_hovers_with_its_fields() {
1105 let src = "commons demo.m\n\nfn f(s: String) -> Result[Int, DecodeError] { Json.decode[Int](s) }\n";
1106 let h = hover_at(src, "DecodeError", 0).expect("`DecodeError` hovers");
1107 assert!(
1108 h.contains("`kind`") && h.contains("`path`") && h.contains("`message`"),
1109 "{h}"
1110 );
1111 }
1112
1113 #[test]
1115 fn d1_peek_hovers_with_its_signature() {
1116 let src = "suite shop.orders as system\n\ncase \"c\" {\n let db = D1.peek(shop.orders.Orders)\n expect true\n}\n";
1117 let h = hover_at(src, "peek", 0).expect("`peek` hovers");
1118 assert!(h.contains("peek(<participant>.<Capability>)"), "{h}");
1119 }
1120
1121 #[test]
1123 fn validation_error_hovers_with_its_fields() {
1124 let src = "commons demo.m\n\ntype Age = Int where self >= 0\n\nfn f(n: Int) -> Result[Age, ValidationError] { Age.of(n) }\n";
1125 let h = hover_at(src, "ValidationError", 0).expect("`ValidationError` hovers");
1126 assert!(h.contains("`field`") && h.contains("`message`"), "{h}");
1127 assert!(!h.contains("`value`"), "{h}");
1128 }
1129
1130 #[test]
1133 fn derives_and_constraint_names_hover() {
1134 let src = "commons demo.m\n\ntype P = Int derives Ord\n\nfn top[T: Ord](xs: List[T]) -> Option[T] { None }\n\nfn same[T: Eq](a: T) -> T { a }\n";
1135 let kw = hover_at(src, "derives", 0).expect("`derives` hovers");
1136 assert!(kw.contains("declaration order"), "{kw}");
1137 for nth in 0..2 {
1139 let ord = hover_at(src, "Ord", nth).expect("`Ord` hovers");
1140 assert!(ord.contains("constraint Ord"), "{ord}");
1141 }
1142 assert!(hover_at(src, "Eq", 0).unwrap().contains("constraint Eq"));
1143 assert!(hover_at(src, "P =", 0).unwrap().contains("derives Ord"));
1145 assert!(
1147 hover_at(src, "top", 0)
1148 .unwrap()
1149 .contains("fn top[T: Ord](xs: List[T])")
1150 );
1151 }
1152}