1use crate::symbols::is_dot_preceded;
12use bynk_check::emitted_names::emitted_local_name;
13use bynk_check::locals::{LocalBinding, LocalKind, binding_at_def, locals_at};
14use bynk_syntax::lexer::{self, TokenKind};
15use bynk_syntax::span::Span;
16use std::collections::HashSet;
17
18fn same_range(a: Span, b: Span) -> bool {
23 a.start == b.start && a.end == b.end
24}
25
26fn ident_at(text: &str, offset: usize) -> Option<(&str, Span)> {
35 let toks = lexer::tokenize_expanding_holes(text).ok()?;
36 toks.into_iter()
37 .find(|t| {
38 t.kind == TokenKind::Ident
39 && t.span.start <= offset
40 && offset <= t.span.end
41 && !is_dot_preceded(text, t.span.start)
42 })
43 .map(|t| (&text[t.span.start..t.span.end], t.span))
44}
45
46fn target_at<'a>(
49 locals: &'a [LocalBinding],
50 text: &str,
51 offset: usize,
52) -> Option<&'a LocalBinding> {
53 let (name, _) = ident_at(text, offset)?;
54 binding_at_def(locals, offset)
55 .filter(|b| b.name == name)
56 .or_else(|| {
57 locals_at(locals, offset)
58 .into_iter()
59 .find(|b| b.name == name)
60 })
61}
62
63pub fn local_sites_at(locals: &[LocalBinding], text: &str, offset: usize) -> Option<Vec<Span>> {
67 let target = target_at(locals, text, offset)?;
68 let toks = lexer::tokenize_expanding_holes(text).ok()?;
70 let mut sites = vec![target.def_span];
71 for t in &toks {
72 if t.kind != TokenKind::Ident || text[t.span.start..t.span.end] != target.name {
73 continue;
74 }
75 if same_range(t.span, target.def_span) {
76 continue; }
78 if locals.iter().any(|b| same_range(b.def_span, t.span)) {
80 continue;
81 }
82 if is_dot_preceded(text, t.span.start) {
85 continue;
86 }
87 let resolves = locals_at(locals, t.span.start)
91 .into_iter()
92 .find(|b| b.name == target.name)
93 .map(|b| b.def_span);
94 if resolves == Some(target.def_span) {
95 sites.push(t.span);
96 }
97 }
98 Some(sites)
99}
100
101pub fn local_definition_at(locals: &[LocalBinding], text: &str, offset: usize) -> Option<Span> {
103 target_at(locals, text, offset).map(|b| b.def_span)
104}
105
106pub fn describe_local_at(locals: &[LocalBinding], text: &str, offset: usize) -> Option<String> {
113 let b = target_at(locals, text, offset)?;
114 let keyword = match b.kind {
115 LocalKind::Let => "let",
116 LocalKind::Param => "param",
117 };
118 Some(format!("```bynk\n{keyword} {}: {}\n```", b.name, b.ty))
119}
120
121pub fn local_token_sites(locals: &[LocalBinding], text: &str) -> Vec<(Span, bool)> {
125 let Ok(toks) = lexer::tokenize_expanding_holes(text) else {
127 return Vec::new();
128 };
129 let mut out = Vec::new();
130 for t in &toks {
131 if t.kind != TokenKind::Ident {
132 continue;
133 }
134 let name = &text[t.span.start..t.span.end];
135 if locals.iter().any(|b| same_range(b.def_span, t.span)) {
136 out.push((t.span, true)); } else if !is_dot_preceded(text, t.span.start)
138 && locals_at(locals, t.span.start)
139 .into_iter()
140 .any(|b| b.name == name)
141 {
142 out.push((t.span, false)); }
147 }
148 out
149}
150
151#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct InlineValueSite {
155 pub range: Span,
157 pub variable: String,
159}
160
161pub fn is_suite_file(text: &str) -> bool {
167 text.lines().any(|l| l.trim_start().starts_with("suite "))
168}
169
170pub fn inline_value_sites(
183 locals: &[LocalBinding],
184 visible: Span,
185 stopped: Span,
186 scaffold_names: Option<&HashSet<String>>,
187) -> Vec<InlineValueSite> {
188 let scaffold_may_bind = |b: &LocalBinding| {
189 scaffold_names.is_some_and(|names| {
190 b.kind == LocalKind::Let
191 && (names.contains(&b.name)
192 || locals
193 .iter()
194 .any(|o| o.name == b.name && o.def_span != b.def_span))
195 })
196 };
197 let mut out: Vec<InlineValueSite> = locals
198 .iter()
199 .filter(|b| visible.start <= b.def_span.start && b.def_span.end <= visible.end)
200 .filter(|b| b.scope.start <= stopped.start && stopped.start <= b.scope.end)
201 .filter(|b| !scaffold_may_bind(b))
202 .filter_map(|b| {
203 let variable = emitted_local_name(b, locals)?;
204 Some(InlineValueSite {
205 range: b.def_span,
206 variable,
207 })
208 })
209 .collect();
210 out.sort_by_key(|s| s.range.start);
211 out
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 fn bindings() -> Vec<LocalBinding> {
220 vec![
222 LocalBinding {
223 name: "n".into(),
224 def_span: Span::new(5, 6),
225 kind: LocalKind::Param,
226 ty: "Int".into(),
227 scope: Span::new(20, 60),
228 },
229 LocalBinding {
230 name: "x".into(),
231 def_span: Span::new(26, 27),
232 kind: LocalKind::Let,
233 ty: "Int".into(),
234 scope: Span::new(34, 60),
235 },
236 ]
237 }
238
239 const TEXT: &str = "fn f(n: Int) -> Int { let x = n\n x + x\n}";
240 #[test]
244 fn sites_for_a_use_collect_def_plus_uses() {
245 let locals = bindings();
246 let x_use = TEXT.match_indices('x').nth(1).unwrap().0; let sites = local_sites_at(&locals, TEXT, x_use).expect("on a local");
249 assert!(
250 sites.contains(&Span::new(26, 27)),
251 "includes def: {sites:?}"
252 );
253 assert!(sites.len() >= 2, "def + at least one use: {sites:?}");
254 }
255
256 #[test]
257 fn definition_resolves_from_a_use() {
258 let locals = bindings();
259 let n_use = TEXT.rfind('n').unwrap(); assert_eq!(
261 local_definition_at(&locals, TEXT, n_use),
262 Some(Span::new(5, 6))
263 );
264 }
265
266 #[test]
267 fn not_on_a_local_yields_none() {
268 let locals = bindings();
269 assert!(local_sites_at(&locals, TEXT, 0).is_none()); }
271
272 #[test]
276 fn field_access_is_not_mistaken_for_a_local_use() {
277 const TEXT: &str = "fn f(r: Rec) -> Int {\n let total = 1\n r.total\n}";
278 let total_let = TEXT.find("total").unwrap();
279 let field_total = TEXT.rfind("total").unwrap();
280 assert_ne!(field_total, total_let, "def and field access are distinct");
281 let locals = vec![LocalBinding {
282 name: "total".into(),
283 def_span: Span::new(total_let, total_let + "total".len()),
284 kind: LocalKind::Let,
285 ty: "Int".into(),
286 scope: Span::new(total_let, TEXT.len()),
287 }];
288 let field_span = Span::new(field_total, field_total + "total".len());
289
290 assert!(
292 local_definition_at(&locals, TEXT, field_total).is_none(),
293 "a field-access member name must not resolve to the same-named local"
294 );
295
296 let sites = local_sites_at(&locals, TEXT, total_let).expect("on the local's own def");
298 assert!(
299 !sites.contains(&field_span),
300 "field access wrongly counted as a use: {sites:?}"
301 );
302
303 let token_sites = local_token_sites(&locals, TEXT);
305 assert!(
306 !token_sites.contains(&(field_span, false)),
307 "field access wrongly coloured as a local use: {token_sites:?}"
308 );
309 }
310
311 #[test]
312 fn token_sites_mark_definitions_and_uses() {
313 let sites = local_token_sites(&bindings(), TEXT);
314 assert!(
315 sites.iter().any(|(_, decl)| *decl),
316 "has a definition token"
317 );
318 assert!(sites.iter().any(|(_, decl)| !*decl), "has a use token");
319 assert!(
321 sites.contains(&(Span::new(26, 27), true)),
322 "x def is a declaration: {sites:?}"
323 );
324 }
325
326 #[test]
329 fn resolves_a_real_local_from_diagnose_project() {
330 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
331 .join("../bynk-tests/tests/fixtures/inlay/clean/src");
332 let r = crate::testkit::diagnose_project(&root);
333 let file = r
334 .files
335 .iter()
336 .find(|f| f.source_path.to_string_lossy().ends_with("util.bynk"))
337 .expect("util.bynk analysed");
338 let text = &file.text;
339 let locals = r
340 .locals
341 .iter()
342 .find(|(p, _)| p.to_string_lossy().ends_with("util.bynk"))
343 .map(|(_, l)| l.clone())
344 .expect("util.bynk locals");
345
346 let use_off = text.rfind("total").expect("total use");
348 let sites = local_sites_at(&locals, text, use_off).expect("on a local");
349 assert!(sites.len() >= 2, "def + use: {sites:?}");
350 let def = text.find("total").expect("total def");
352 assert_eq!(sites[0].start, def, "def first");
353 }
354
355 #[test]
358 fn describe_local_renders_kind_and_type() {
359 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
360 .join("../bynk-tests/tests/fixtures/inlay/clean/src");
361 let r = crate::testkit::diagnose_project(&root);
362 let file = r
363 .files
364 .iter()
365 .find(|f| f.source_path.to_string_lossy().ends_with("util.bynk"))
366 .expect("util.bynk analysed");
367 let text = &file.text;
368 let locals = r
369 .locals
370 .iter()
371 .find(|(p, _)| p.to_string_lossy().ends_with("util.bynk"))
372 .map(|(_, l)| l.clone())
373 .expect("util.bynk locals");
374
375 let total = text.find("total").expect("total def");
377 assert_eq!(
378 describe_local_at(&locals, text, total).as_deref(),
379 Some("```bynk\nlet total: Int\n```")
380 );
381 let xs_param = text.find("xs: List[Int]").expect("xs param");
384 assert_eq!(
385 describe_local_at(&locals, text, xs_param).as_deref(),
386 Some("```bynk\nparam xs: List[Int]\n```")
387 );
388 assert!(describe_local_at(&locals, text, text.find("fn").unwrap()).is_none());
390 }
391
392 const HOLE_SRC: &str = "\
400commons demo.text
401
402fn shout(s: String) -> String {
403 s
404}
405
406fn greet(name: String) -> String {
407 \"Hi, \\(shout(name))!\"
408}
409";
410
411 fn analyse_hole_fixture(test_name: &str) -> (String, Vec<LocalBinding>) {
413 analyse_source(&format!("hole-{test_name}"), "demo/text.bynk", HOLE_SRC)
414 }
415
416 fn analyse_source(tag: &str, rel: &str, src: &str) -> (String, Vec<LocalBinding>) {
420 let root = std::env::temp_dir().join(format!("bynk-locals-{tag}-{}", std::process::id()));
421 let _ = std::fs::remove_dir_all(&root);
422 let file = root.join(rel);
423 std::fs::create_dir_all(file.parent().unwrap()).expect("create dirs");
424 std::fs::write(&file, src).expect("write fixture");
425 let root = root.canonicalize().unwrap_or(root);
426
427 let name = std::path::Path::new(rel)
428 .file_name()
429 .unwrap()
430 .to_string_lossy()
431 .into_owned();
432 let r = crate::testkit::diagnose_project(&root);
433 let text = r
434 .files
435 .iter()
436 .find(|f| f.source_path.to_string_lossy().ends_with(&name))
437 .expect("fixture analysed")
438 .text
439 .clone();
440 let locals = r
441 .locals
442 .iter()
443 .find(|(p, _)| p.to_string_lossy().ends_with(&name))
444 .map(|(_, l)| l.clone())
445 .expect("fixture locals");
446 (text, locals)
447 }
448
449 fn nth_offset(text: &str, needle: &str, n: usize) -> usize {
451 text.match_indices(needle).nth(n).expect("occurrence").0
452 }
453
454 #[test]
455 fn hover_describes_a_param_inside_a_hole() {
456 let (text, locals) = analyse_hole_fixture("hover");
457 let in_hole = nth_offset(&text, "name", 1) + 1; assert_eq!(
460 describe_local_at(&locals, &text, in_hole).as_deref(),
461 Some("```bynk\nparam name: String\n```"),
462 "hover inside the hole renders the param summary"
463 );
464 }
465
466 #[test]
467 fn definition_of_a_param_resolves_from_inside_a_hole() {
468 let (text, locals) = analyse_hole_fixture("def");
469 let in_hole = nth_offset(&text, "name", 1) + 1;
470 let def = local_definition_at(&locals, &text, in_hole).expect("resolves to a def");
471 let decl = nth_offset(&text, "name", 0); assert_eq!(def.start, decl, "def points at the `name` parameter");
473 }
474
475 #[test]
476 fn references_include_a_param_use_inside_a_hole() {
477 let (text, locals) = analyse_hole_fixture("refs");
478 let decl = nth_offset(&text, "name", 0);
479 let sites = local_sites_at(&locals, &text, decl).expect("on the param");
480 let in_hole = nth_offset(&text, "name", 1);
481 assert!(
482 sites.iter().any(|s| s.start <= in_hole && in_hole < s.end),
483 "references include the in-hole use at {in_hole}; got {sites:?}"
484 );
485 }
486
487 const STEPS_SRC: &str =
489 "commons demo.steps\n\nfn total(r: Int) -> Int {\n let plain = r\n plain\n}\n";
490
491 #[test]
495 fn token_sites_include_real_definitions_from_diagnose_project() {
496 let (text, locals) = analyse_source("tokens", "demo/steps.bynk", STEPS_SRC);
497 let sites = local_token_sites(&locals, &text);
498 let at = |needle: &str, n: usize| {
499 let start = nth_offset(&text, needle, n);
500 Span::new(start, start + needle.len())
501 };
502 let has = |span: Span, decl: bool| {
503 sites
504 .iter()
505 .any(|(s, d)| same_range(*s, span) && *d == decl)
506 };
507
508 let r_param = text.find("r: Int").unwrap();
509 assert!(
510 has(Span::new(r_param, r_param + 1), true),
511 "param `r` def is a declaration token: {sites:?}"
512 );
513 assert!(
514 has(at("plain", 0), true),
515 "`let plain` def is a declaration token: {sites:?}"
516 );
517 assert!(has(at("plain", 1), false), "`plain` use: {sites:?}");
519 let r_use = text.find("= r").unwrap() + 2;
520 assert!(
521 has(Span::new(r_use, r_use + 1), false),
522 "`r` use: {sites:?}"
523 );
524 assert_eq!(sites.len(), 4, "two defs + two uses: {sites:?}");
526 }
527
528 #[test]
532 fn sites_exclude_a_shadowing_definition_from_diagnose_project() {
533 const SRC: &str =
534 "commons demo.shadow\n\nfn f(r: Int) -> Int {\n let x = r\n let x = x + 1\n x\n}\n";
535 let (text, locals) = analyse_source("shadow", "demo/shadow.bynk", SRC);
536 let outer = nth_offset(&text, "x", 0);
537 let inner = nth_offset(&text, "x", 1);
538 let outer_use = nth_offset(&text, "x", 2);
539
540 let sites = local_sites_at(&locals, &text, outer).expect("on the outer x");
541 let starts: Vec<usize> = sites.iter().map(|s| s.start).collect();
542 assert_eq!(
543 starts,
544 vec![outer, outer_use],
545 "outer def once, then its one use; never the inner def: {sites:?}"
546 );
547 assert!(!starts.contains(&inner));
548 }
549
550 const INLINE_SRC: &str = "commons demo.inline\n\nfn calc(class: Int) -> Int {\n let total = class\n let total = total + 1\n total\n}\n\nfn other(z: Int) -> Int {\n let w = z\n w\n}\n";
553
554 #[test]
555 fn inline_sites_map_to_emitted_names_and_skip_re_lets() {
556 let (text, locals) = analyse_source("inline", "demo/inline.bynk", INLINE_SRC);
557 let whole = Span::new(0, text.len());
558 let stop = nth_offset(&text, " total\n", 0) + 2; let sites = inline_value_sites(&locals, whole, Span::new(stop, stop), None);
560 let seen: Vec<(&str, &str)> = sites
561 .iter()
562 .map(|s| (&text[s.range.start..s.range.end], s.variable.as_str()))
563 .collect();
564 assert_eq!(
565 seen,
566 vec![("class", "__id_class"), ("total", "total")],
567 "param renamed (reserved word); the re-let is dropped; `other` is out of scope"
568 );
569 assert_eq!(sites[1].range.start, nth_offset(&text, "total", 0));
571 }
572
573 #[test]
574 fn inline_sites_respect_the_visible_range() {
575 let (text, locals) = analyse_source("inline-vis", "demo/inline.bynk", INLINE_SRC);
576 let stop = nth_offset(&text, " total\n", 0) + 2;
577 let line = nth_offset(&text, "let total = class", 0);
579 let visible = Span::new(line, line + "let total = class".len());
580 let sites = inline_value_sites(&locals, visible, Span::new(stop, stop), None);
581 assert_eq!(sites.len(), 1);
582 assert_eq!(&text[sites[0].range.start..sites[0].range.end], "total");
583 }
584
585 #[test]
586 fn inline_sites_follow_the_stopped_function() {
587 let (text, locals) = analyse_source("inline-fn", "demo/inline.bynk", INLINE_SRC);
588 let whole = Span::new(0, text.len());
589 let stop = nth_offset(&text, " w\n", 0) + 2;
590 let sites = inline_value_sites(&locals, whole, Span::new(stop, stop), None);
591 let seen: Vec<(&str, &str)> = sites
592 .iter()
593 .map(|s| (&text[s.range.start..s.range.end], s.variable.as_str()))
594 .collect();
595 assert_eq!(seen, vec![("z", "z"), ("w", "w")]);
596 }
597
598 #[test]
599 fn a_suite_let_named_like_a_project_item_is_left_out() {
600 let (text, locals) = analyse_source("inline-suite", "demo/inline.bynk", INLINE_SRC);
601 let whole = Span::new(0, text.len());
602 let stop = nth_offset(&text, " w\n", 0) + 2;
603 let scaffold: HashSet<String> = ["w".to_string()].into();
604 let sites = inline_value_sites(&locals, whole, Span::new(stop, stop), Some(&scaffold));
605 let names: Vec<&str> = sites
606 .iter()
607 .map(|s| &text[s.range.start..s.range.end])
608 .collect();
609 assert_eq!(names, vec!["z"]);
611 }
612
613 #[test]
614 fn suite_files_are_recognised() {
615 assert!(is_suite_file("suite shop.maths {\n}\n"));
616 assert!(is_suite_file("---\ndoc\n---\nsuite a.b as system {\n}\n"));
617 assert!(!is_suite_file(
618 "commons shop.maths\n\nfn f() -> Int { 1 }\n"
619 ));
620 }
621
622 #[test]
623 fn a_let_after_the_stop_is_not_yet_in_scope() {
624 let (text, locals) = analyse_source("inline-pre", "demo/inline.bynk", INLINE_SRC);
625 let whole = Span::new(0, text.len());
626 let stop = nth_offset(&text, "let total = class", 0);
628 let sites = inline_value_sites(&locals, whole, Span::new(stop, stop), None);
629 let names: Vec<&str> = sites
630 .iter()
631 .map(|s| &text[s.range.start..s.range.end])
632 .collect();
633 assert_eq!(names, vec!["class"]);
634 }
635}