1use std::collections::{HashMap, HashSet};
13use std::path::Path;
14use std::sync::LazyLock;
15
16use bynk_check::index::ProjectIndex;
17use bynk_check::locals::LocalBinding;
18use bynk_syntax::ast::SourceUnit;
19use bynk_syntax::span::Span;
20use serde_json::json;
21use tower_lsp::lsp_types::{
22 CodeAction, CodeActionKind, CodeActionOrCommand, Diagnostic, DiagnosticSeverity,
23 DocumentChanges, NumberOrString, OneOf, OptionalVersionedTextDocumentIdentifier, Range,
24 TextDocumentEdit, TextEdit, Url, WorkspaceEdit,
25};
26
27use crate::index_queries::{
28 DOC_LINK_BARE_KINDS, DOC_LINK_MEMBER_KINDS, DocLinkContext, own_part_names, resolve_doc_link_in,
29};
30
31pub const CODE: &str = "bynk.doc.unresolved_link";
33
34const MAX_SUGGESTIONS: usize = 3;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
39pub enum Level {
40 Off,
41 #[default]
42 Hint,
43 Warning,
44}
45
46impl Level {
47 pub fn parse(s: &str) -> Option<Level> {
48 match s {
49 "off" => Some(Level::Off),
50 "hint" => Some(Level::Hint),
51 "warning" => Some(Level::Warning),
52 _ => None,
53 }
54 }
55
56 pub fn from_settings(settings: &serde_json::Value) -> Option<Level> {
60 let section = settings.get("bynk").unwrap_or(settings);
61 let value = section.get("docLinks")?.get("reportUnresolved")?.as_str()?;
62 Level::parse(value)
63 }
64
65 fn severity(self) -> Option<DiagnosticSeverity> {
66 match self {
67 Level::Off => None,
68 Level::Hint => Some(DiagnosticSeverity::HINT),
69 Level::Warning => Some(DiagnosticSeverity::WARNING),
70 }
71 }
72}
73
74static UNLINKED_FIRST_PARTY_NAMES: LazyLock<HashSet<String>> = LazyLock::new(|| {
82 let mut names = HashSet::new();
83 for (_, src) in bynk_check::firstparty::FIRSTPARTY_SOURCES {
84 let Ok(tokens) = bynk_syntax::lexer::tokenize(src) else {
85 continue;
86 };
87 let (Some(unit), _) = bynk_syntax::parser::parse_unit_with_recovery(&tokens, src) else {
88 continue;
89 };
90 let items = match &unit {
91 SourceUnit::Commons(c) => &c.items,
92 SourceUnit::Adapter(a) => &a.items,
93 SourceUnit::Context(c) => &c.items,
94 SourceUnit::Suite(_) => continue,
95 };
96 names.extend(
97 items
98 .iter()
99 .filter_map(|i| i.name())
100 .map(|n| n.name.clone())
101 .filter(|n| {
102 !crate::first_party_docs::FIRST_PARTY_DOCS
103 .iter()
104 .any(|(_, cap, ..)| cap == n)
105 }),
106 );
107 }
108 names
109});
110
111fn is_unlinked_first_party(name: &str) -> bool {
114 let owner = name.split_once('.').map_or(name, |(o, _)| o);
115 UNLINKED_FIRST_PARTY_NAMES.contains(owner)
116}
117
118fn is_escaped(text: &str, span: Span) -> bool {
121 if text[..span.start].ends_with('\\') {
122 return true;
123 }
124 let line_start = text[..span.start].rfind('\n').map_or(0, |i| i + 1);
125 text[line_start..span.start].matches('`').count() % 2 == 1
126}
127
128fn distance(a: &str, b: &str) -> usize {
131 let a: Vec<char> = a.to_lowercase().chars().collect();
132 let b: Vec<char> = b.to_lowercase().chars().collect();
133 let mut rows = vec![vec![0usize; b.len() + 1]; a.len() + 1];
134 for (i, row) in rows.iter_mut().enumerate() {
135 row[0] = i;
136 }
137 for (j, cell) in rows[0].iter_mut().enumerate() {
138 *cell = j;
139 }
140 for i in 1..=a.len() {
141 for j in 1..=b.len() {
142 let cost = usize::from(a[i - 1] != b[j - 1]);
143 let mut d = (rows[i - 1][j] + 1)
144 .min(rows[i][j - 1] + 1)
145 .min(rows[i - 1][j - 1] + cost);
146 if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
147 d = d.min(rows[i - 2][j - 2] + 1);
148 }
149 rows[i][j] = d;
150 }
151 }
152 rows[a.len()][b.len()]
153}
154
155fn suggestions(
160 index: &ProjectIndex,
161 doc_scope: &HashMap<String, Vec<String>>,
162 owner_unit: &str,
163 name: &str,
164 own_parts: &[String],
165) -> Vec<String> {
166 let scope = doc_scope.get(owner_unit).map_or(&[][..], Vec::as_slice);
167 let kinds = if name.contains('.') {
168 DOC_LINK_MEMBER_KINDS
169 } else {
170 DOC_LINK_BARE_KINDS
171 };
172 let budget = (name.chars().count() / 3).max(1);
173 let first_party = crate::first_party_docs::in_scope_names(doc_scope, owner_unit);
174 let mut found: Vec<(usize, &str)> = index
175 .symbols
176 .iter()
177 .filter(|(k, e)| e.def.is_some() && kinds.contains(&k.kind) && scope.contains(&k.unit))
178 .map(|(k, _)| k.name.as_str())
179 .chain(
180 own_parts
181 .iter()
182 .map(String::as_str)
183 .filter(|_| !name.contains('.')),
184 )
185 .chain(
186 first_party
187 .iter()
188 .map(String::as_str)
189 .filter(|n| n.contains('.') == name.contains('.')),
190 )
191 .map(|n| (distance(name, n), n))
192 .filter(|&(d, n)| d <= budget && n != name)
193 .collect();
194 found.sort();
195 found.dedup_by_key(|&mut (_, n)| n);
196 found
197 .into_iter()
198 .take(MAX_SUGGESTIONS)
199 .map(|(_, n)| n.to_string())
200 .collect()
201}
202
203pub fn unresolved_link_diagnostics(
209 text: &str,
210 path: &Path,
211 owner_unit: &str,
212 index: &ProjectIndex,
213 doc_scope: &HashMap<String, Vec<String>>,
214 locals: &[LocalBinding],
215 level: Level,
216) -> Vec<Diagnostic> {
217 let Some(severity) = level.severity() else {
218 return Vec::new();
219 };
220 let mut out = Vec::new();
221 for link in crate::symbols::doc_link_spans_attached(text) {
222 let (name, span) = (link.name, link.span);
223 let ctx = link.attached.map(|attached| DocLinkContext {
224 path,
225 text,
226 attached,
227 locals,
228 });
229 if resolve_doc_link_in(index, doc_scope, owner_unit, &name, ctx.as_ref())
230 .resolved()
231 .is_some()
232 || crate::first_party_docs::resolve_first_party_doc_link(doc_scope, owner_unit, &name)
233 .is_some()
234 || is_unlinked_first_party(&name)
235 || is_escaped(text, span)
236 {
237 continue;
238 }
239 let own_parts = ctx
240 .as_ref()
241 .map_or_else(Vec::new, |c| own_part_names(index, c));
242 let suggestions = suggestions(index, doc_scope, owner_unit, &name, &own_parts);
243 if suggestions.is_empty()
247 && !name.contains('.')
248 && name.starts_with(|c: char| c.is_ascii_lowercase())
249 {
250 continue;
251 }
252 let candidate = &text[span.start..span.end];
255 let name_start = span.start + candidate.rfind(name.as_str()).unwrap_or(0);
256 let name_range: Range =
257 crate::position::span_to_range(text, Span::new(name_start, name_start + name.len()));
258 let message = match suggestions.first() {
259 Some(best) => format!("Unresolved doc link `{name}`; did you mean `{best}`?"),
260 None => format!(
261 "Unresolved doc link `{name}`; escape it as `\\[{name}]` if the brackets are intentional"
262 ),
263 };
264 out.push(Diagnostic {
265 range: crate::position::span_to_range(text, span),
266 severity: Some(severity),
267 code: Some(NumberOrString::String(CODE.to_string())),
268 source: Some("bynk".to_string()),
269 message,
270 data: Some(
271 json!({ "name": name, "suggestions": suggestions, "nameRange": name_range }),
272 ),
273 ..Default::default()
274 });
275 }
276 out
277}
278
279pub fn quick_fix_edits(diag: &Diagnostic) -> Vec<(String, Range)> {
282 quick_fix_edits_in(diag, None)
283}
284
285fn quick_fix_edits_in(diag: &Diagnostic, text: Option<&str>) -> Vec<(String, Range)> {
290 if diag.code != Some(NumberOrString::String(CODE.to_string())) {
291 return Vec::new();
292 }
293 let Some(data) = &diag.data else {
294 return Vec::new();
295 };
296 let Some(range) = data
297 .get("nameRange")
298 .and_then(|r| serde_json::from_value::<Range>(r.clone()).ok())
299 else {
300 return Vec::new();
301 };
302 if let Some(text) = text {
303 let at = |p| crate::position::position_to_offset(text, p);
304 let current = at(range.start)
305 .zip(at(range.end))
306 .and_then(|(start, end)| text.get(start..end));
307 if current != data.get("name").and_then(|n| n.as_str()) {
308 return Vec::new();
309 }
310 }
311 data.get("suggestions")
312 .and_then(|s| s.as_array())
313 .map(|names| {
314 names
315 .iter()
316 .filter_map(|n| n.as_str())
317 .map(|n| (n.to_string(), range))
318 .collect()
319 })
320 .unwrap_or_default()
321}
322
323pub fn quick_fix_actions(
327 text: &str,
328 diagnostics: &[Diagnostic],
329 requested: Range,
330 uri: &Url,
331 version: Option<i32>,
332) -> Vec<CodeActionOrCommand> {
333 let touches = |r: &Range| r.start <= requested.end && requested.start <= r.end;
334 diagnostics
335 .iter()
336 .filter(|d| touches(&d.range))
337 .flat_map(|d| {
338 quick_fix_edits_in(d, Some(text))
339 .into_iter()
340 .map(move |(name, range)| {
341 CodeActionOrCommand::CodeAction(CodeAction {
342 title: format!("Change to `{name}`"),
343 kind: Some(CodeActionKind::QUICKFIX),
344 diagnostics: Some(vec![d.clone()]),
345 edit: Some(WorkspaceEdit {
346 changes: None,
347 document_changes: Some(DocumentChanges::Edits(vec![
348 TextDocumentEdit {
349 text_document: OptionalVersionedTextDocumentIdentifier {
350 uri: uri.clone(),
351 version,
352 },
353 edits: vec![OneOf::Left(TextEdit {
354 range,
355 new_text: name,
356 })],
357 },
358 ])),
359 change_annotations: None,
360 }),
361 ..Default::default()
362 })
363 })
364 })
365 .collect()
366}
367
368#[cfg(test)]
369mod tests {
370 use super::*;
371 use bynk_check::index::{SiteRef, SymbolEntry, SymbolKey, SymbolKind};
372 use bynk_check::locals::LocalKind;
373 use std::path::PathBuf;
374
375 fn index() -> ProjectIndex {
376 let mut index = ProjectIndex::default();
377 for (kind, name) in [
378 (SymbolKind::Agent, "Limiter"),
379 (SymbolKind::Type, "Window"),
380 (SymbolKind::Field, "Window.size"),
381 (SymbolKind::Fn, "decide"),
382 ] {
383 index.symbols.insert(
384 SymbolKey {
385 unit: "ratelimit".into(),
386 kind,
387 name: name.into(),
388 },
389 SymbolEntry {
390 def: Some(SiteRef {
391 path: PathBuf::from("ratelimit.bynk"),
392 span: Span::new(0, 1),
393 }),
394 ..Default::default()
395 },
396 );
397 }
398 index
399 }
400
401 fn scope() -> HashMap<String, Vec<String>> {
402 HashMap::from([("ratelimit".to_string(), vec!["ratelimit".to_string()])])
403 }
404
405 fn doc_text(doc: &str) -> String {
406 format!("--| {doc}\nfn f() -> Int {{ 1 }}\n")
407 }
408
409 fn run(doc: &str, level: Level) -> Vec<Diagnostic> {
410 let text = doc_text(doc);
411 unresolved_link_diagnostics(
412 &text,
413 Path::new("ratelimit.bynk"),
414 "ratelimit",
415 &index(),
416 &scope(),
417 &[],
418 level,
419 )
420 }
421
422 fn run_attached(
426 text: &str,
427 owner: (SymbolKind, &str),
428 extra: &[(SymbolKind, &str)],
429 params: &[&str],
430 ) -> Vec<Diagnostic> {
431 let mut index = index();
432 let attached = text.find(owner.1).expect("owner in text");
433 let mut define = |kind, name: &str, at: usize| {
434 index.symbols.insert(
435 SymbolKey {
436 unit: "ratelimit".into(),
437 kind,
438 name: name.into(),
439 },
440 SymbolEntry {
441 def: Some(SiteRef {
442 path: PathBuf::from("ratelimit.bynk"),
443 span: Span::new(at, at + 1),
444 }),
445 ..Default::default()
446 },
447 );
448 };
449 define(owner.0, owner.1, attached);
450 for &(kind, name) in extra {
451 define(kind, name, 0);
452 }
453 let locals: Vec<LocalBinding> = params
454 .iter()
455 .map(|p| {
456 let at = text.find(&format!("{p}:")).expect("param in text");
457 LocalBinding {
458 name: p.to_string(),
459 def_span: Span::new(at, at + p.len()),
460 kind: LocalKind::Param,
461 ty: "Int".into(),
462 scope: Span::new(at, text.len()),
463 }
464 })
465 .collect();
466 unresolved_link_diagnostics(
467 text,
468 Path::new("ratelimit.bynk"),
469 "ratelimit",
470 &index,
471 &scope(),
472 &locals,
473 Level::Hint,
474 )
475 }
476
477 #[test]
478 fn a_field_link_in_its_own_records_doc_is_quiet() {
479 let text = "--| The [size] of the window; see [sizes].\ntype Box { size: Int }\n";
482 let diags = run_attached(
483 text,
484 (SymbolKind::Type, "Box"),
485 &[(SymbolKind::Field, "Box.size"), (SymbolKind::Fn, "sizes")],
486 &[],
487 );
488 assert!(diags.is_empty(), "{diags:?}");
489 let diags = run_attached(
491 text,
492 (SymbolKind::Type, "Box"),
493 &[(SymbolKind::Fn, "sizes")],
494 &[],
495 );
496 assert_eq!(diags.len(), 1);
497 }
498
499 #[test]
500 fn a_parameter_link_in_its_fns_doc_is_quiet() {
501 let text =
502 "--| Decides for [order], not [orders].\nfn place(order: Int) -> Int { order }\n";
503 let diags = run_attached(
504 text,
505 (SymbolKind::Fn, "place"),
506 &[(SymbolKind::Fn, "orders")],
507 &["order"],
508 );
509 assert!(diags.is_empty(), "{diags:?}");
510 }
511
512 #[test]
513 fn an_own_part_does_not_excuse_a_similar_unresolved_sibling() {
514 let text = "--| Takes [order] and [ordre].\nfn place(order: Int) -> Int { order }\n";
515 let diags = run_attached(text, (SymbolKind::Fn, "place"), &[], &["order"]);
516 assert_eq!(diags.len(), 1, "{diags:?}");
517 assert!(diags[0].message.contains("`ordre`"), "{}", diags[0].message);
518 }
519
520 #[test]
521 fn an_ambiguous_own_part_is_not_suggested() {
522 let text = "--| The [Sizw].\ntype Box { Size: Int }\n";
525 let diags = run_attached(
526 text,
527 (SymbolKind::Type, "Box"),
528 &[
529 (SymbolKind::Field, "Box.Size"),
530 (SymbolKind::Method, "Box.Size"),
531 ],
532 &[],
533 );
534 assert_eq!(diags.len(), 1, "{diags:?}");
535 assert!(quick_fix_edits(&diags[0]).is_empty());
536 }
537
538 #[test]
539 fn the_hint_is_wired_to_the_analysed_locals() {
540 let src = "commons pay\n\n--| Pays the [amount] and [amoutn].\nfn pay(amount: Int) -> Int { amount }\n";
543 let root = std::env::temp_dir().join(format!("bynk-lsp-doclink-{}", std::process::id()));
544 let _ = std::fs::remove_dir_all(&root);
545 std::fs::create_dir_all(&root).unwrap();
546 std::fs::write(root.join("pay.bynk"), src).unwrap();
547 let root = root.canonicalize().unwrap();
548 let overlay = HashMap::from([(root.join("pay.bynk"), src.to_string())]);
549 let result = bynk_ide::diagnose_project(&root, &overlay);
550 let _ = std::fs::remove_dir_all(&root);
551 let file = &result.files[0];
552 let diags = unresolved_link_diagnostics(
553 &file.text,
554 &file.source_path,
555 "pay",
556 &result.index,
557 &result.doc_scope,
558 result
559 .locals
560 .get(&file.source_path)
561 .map_or(&[], Vec::as_slice),
562 Level::Hint,
563 );
564 assert_eq!(diags.len(), 1, "{diags:?}");
567 assert_eq!(quick_fix_edits(&diags[0])[0].0, "amount");
568 }
569
570 #[test]
571 fn did_you_mean_offers_own_parts() {
572 let text = "--| Takes [ordr].\nfn place(order: Int) -> Int { order }\n";
573 let diags = run_attached(text, (SymbolKind::Fn, "place"), &[], &["order"]);
574 assert_eq!(diags.len(), 1, "{diags:?}");
575 assert_eq!(quick_fix_edits(&diags[0])[0].0, "order");
576 let text = "--| The [sizw].\ntype Box { size: Int }\n";
577 let diags = run_attached(
578 text,
579 (SymbolKind::Type, "Box"),
580 &[(SymbolKind::Field, "Box.size")],
581 &[],
582 );
583 assert_eq!(quick_fix_edits(&diags[0])[0].0, "size");
584 }
585
586 #[test]
587 fn a_misspelt_link_hints_with_a_did_you_mean() {
588 let diags = run("See [Limtier].", Level::Hint);
589 assert_eq!(diags.len(), 1);
590 let d = &diags[0];
591 assert_eq!(d.severity, Some(DiagnosticSeverity::HINT));
592 assert_eq!(d.code, Some(NumberOrString::String(CODE.into())));
593 assert!(
594 d.message.contains("did you mean `Limiter`?"),
595 "{}",
596 d.message
597 );
598 let fixes = quick_fix_edits(d);
599 assert_eq!(fixes.len(), 1);
600 assert_eq!(fixes[0].0, "Limiter");
601 assert_eq!(fixes[0].1.start.character, 9);
603 assert_eq!(fixes[0].1.end.character, 16);
604 }
605
606 #[test]
607 fn a_resolved_link_is_quiet() {
608 assert!(run("See [Limiter] and [Window.size].", Level::Hint).is_empty());
609 }
610
611 #[test]
612 fn a_name_with_no_near_match_hints_without_a_suggestion() {
613 let diags = run("See [TODO].", Level::Hint);
614 assert_eq!(diags.len(), 1);
615 assert!(quick_fix_edits(&diags[0]).is_empty());
616 assert!(diags[0].message.contains("escape it"));
617 }
618
619 #[test]
620 fn an_escaped_bracket_is_quiet() {
621 assert!(run("Still \\[TODO] here.", Level::Hint).is_empty());
622 }
623
624 #[test]
625 fn a_bracket_inside_a_code_span_is_quiet() {
626 assert!(run("Write `[TODO]` here.", Level::Hint).is_empty());
627 }
628
629 #[test]
630 fn a_full_reference_fixes_its_label_not_its_text() {
631 let diags = run("See [the limiter][Limtier].", Level::Hint);
632 assert_eq!(diags.len(), 1);
633 let (name, range) = &quick_fix_edits(&diags[0])[0];
634 assert_eq!(name, "Limiter");
635 assert_eq!(range.start.character, 22);
637 }
638
639 #[test]
640 fn the_setting_picks_the_severity_and_off_suppresses_all() {
641 assert_eq!(
642 run("[Nope]", Level::Warning)[0].severity,
643 Some(DiagnosticSeverity::WARNING)
644 );
645 assert!(run("[Nope]", Level::Off).is_empty());
646 }
647
648 fn run_first_party(doc: &str) -> Vec<Diagnostic> {
649 let text = doc_text(doc);
650 let scope = HashMap::from([(
651 "ratelimit".to_string(),
652 vec!["ratelimit".to_string(), "bynk".to_string()],
653 )]);
654 unresolved_link_diagnostics(
655 &text,
656 Path::new("ratelimit.bynk"),
657 "ratelimit",
658 &index(),
659 &scope,
660 &[],
661 Level::Hint,
662 )
663 }
664
665 #[test]
666 fn resolving_first_party_links_are_not_hinted() {
667 assert!(run_first_party("See [Clock.now] and [Clock].").is_empty());
668 }
669
670 #[test]
671 fn first_party_types_and_crypto_without_a_doc_entry_are_not_hinted() {
672 assert!(
673 run_first_party("Returns a [FetchError] or a [Uuid]; signs with [Crypto].").is_empty()
674 );
675 }
676
677 #[test]
678 fn a_mistyped_first_party_operation_is_hinted_with_the_real_one() {
679 let diags = run_first_party("See [Clock.nwo].");
680 assert_eq!(diags.len(), 1);
681 assert_eq!(quick_fix_edits(&diags[0])[0].0, "Clock.now");
682 let diags = run_first_party("See [Clok].");
683 assert_eq!(quick_fix_edits(&diags[0])[0].0, "Clock");
684 }
685
686 #[test]
687 fn the_setting_is_read_from_either_payload_shape() {
688 let nested = json!({ "bynk": { "docLinks": { "reportUnresolved": "warning" } } });
689 let section = json!({ "docLinks": { "reportUnresolved": "off" } });
690 assert_eq!(Level::from_settings(&nested), Some(Level::Warning));
691 assert_eq!(Level::from_settings(§ion), Some(Level::Off));
692 assert_eq!(Level::from_settings(&json!({})), None);
693 assert_eq!(
694 Level::from_settings(&json!({ "docLinks": { "reportUnresolved": "loud" } })),
695 None
696 );
697 }
698
699 #[test]
700 fn a_code_action_edits_the_diagnostic_range() {
701 let diags = run("See [Limtier].", Level::Hint);
702 let uri = Url::parse("file:///tmp/a.bynk").unwrap();
703 let actions = quick_fix_actions(
704 &doc_text("See [Limtier]."),
705 &diags,
706 diags[0].range,
707 &uri,
708 Some(3),
709 );
710 assert_eq!(actions.len(), 1);
711 let CodeActionOrCommand::CodeAction(a) = &actions[0] else {
712 panic!("a code action")
713 };
714 assert_eq!(a.title, "Change to `Limiter`");
715 let moved = Range {
717 start: tower_lsp::lsp_types::Position::new(5, 0),
718 end: tower_lsp::lsp_types::Position::new(5, 1),
719 };
720 assert!(
721 quick_fix_actions(&doc_text("See [Limtier]."), &diags, moved, &uri, None).is_empty()
722 );
723 }
724
725 #[test]
726 fn lowercase_prose_brackets_are_quiet_but_a_misspelt_fn_is_not() {
727 assert!(run("Done: [x] and a[i] and [optional].", Level::Hint).is_empty());
728 let diags = run("See [decidee].", Level::Hint);
729 assert_eq!(diags.len(), 1);
730 assert_eq!(quick_fix_edits(&diags[0])[0].0, "decide");
731 assert_eq!(run("See [window.size].", Level::Hint).len(), 1);
733 }
734
735 #[test]
736 fn a_fix_is_withheld_when_the_range_no_longer_holds_the_name() {
737 let diags = run("See [Limtier].", Level::Hint);
738 let uri = Url::parse("file:///tmp/a.bynk").unwrap();
739 let shifted = format!("--| intro text here\n{}", doc_text("See [Limtier]."));
742 assert!(quick_fix_actions(&shifted, &diags, diags[0].range, &uri, None).is_empty());
743 assert_eq!(
744 quick_fix_actions(
745 &doc_text("See [Limtier]."),
746 &diags,
747 diags[0].range,
748 &uri,
749 None
750 )
751 .len(),
752 1
753 );
754 }
755}