Skip to main content

bynk_ide/
locals_nav.rs

1//! v0.31 (ADR 0064): locals navigation — resolve the local binding under the
2//! cursor and all its sites (its definition plus every use that resolves to
3//! it), for `references`, go-to-`definition`, and `documentHighlight`.
4//!
5//! Slice 1 records bindings with scope ranges (not use sites); the use sites
6//! are recovered here by lexing the file and keeping the identifier tokens of
7//! the binding's name within its scope that resolve back to it (so a shadowing
8//! inner binding's uses — and every binding's *def* token — are excluded).
9//! Pure over the analysed snapshot, like `index_queries`.
10
11use 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
18/// Whether two spans cover the same byte range. Lexer tokens carry
19/// `FileId::UNKNOWN` while the checker's `def_span`s carry the analysed file's
20/// id, so whole-`Span` equality never holds between them; compare offsets, as
21/// the rest of bynk-ide does for lexer spans.
22fn same_range(a: Span, b: Span) -> bool {
23    a.start == b.start && a.end == b.end
24}
25
26/// The identifier-token name covering `offset`, if any. Interpolation holes are
27/// expanded (issue #473), so a cursor inside `"… \(name) …"` resolves to the
28/// hole's `name` identifier rather than the opaque `InterpStr` token.
29///
30/// Finding #63: a field-access member name (`items` in `p.items`) is lexically
31/// indistinguishable from a bare identifier — excluded via `is_dot_preceded`
32/// (the same guard `symbols.rs` uses for state/store-op token matching, #596)
33/// so the cursor sitting on a field name never resolves to a same-named local.
34fn 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
46/// The binding the cursor refers to — whether it sits on the definition name
47/// or on a use — within `locals` (a file's bindings).
48fn 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
63/// All sites of the local under the cursor — its definition first, then every
64/// use that resolves to it (shadowing-safe). `None` when the cursor is not on
65/// a local.
66pub fn local_sites_at(locals: &[LocalBinding], text: &str, offset: usize) -> Option<Vec<Span>> {
67    let target = target_at(locals, text, offset)?;
68    // Hole-aware (issue #473): use sites inside `\(…)` holes count too.
69    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; // the definition, already added
77        }
78        // A binding's own def token is not a use of anything.
79        if locals.iter().any(|b| same_range(b.def_span, t.span)) {
80            continue;
81        }
82        // Finding #63: a field-access member name (`r.total`) is not a use of
83        // a same-named local, even when one is in scope.
84        if is_dot_preceded(text, t.span.start) {
85            continue;
86        }
87        // (Outside every scope range of the binding: `locals_at` below no
88        // longer resolves the use to it, so it is skipped there.)
89        // Does this use resolve to `target` (not a shadowing inner binding)?
90        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
101/// The definition site of the local under the cursor, if any.
102pub 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
106/// v0.122 (editor-currency slice 1): a hover summary for the local binding /
107/// parameter under the cursor — `let x: <ty>` / `param n: <ty>`, rendered from
108/// the checker's captured `LocalBinding` (its `ty` is already the surface
109/// `type_ref` form, matching inlay hints and signature help). `None` when the
110/// cursor is not on a local. Reuses the same `target_at` resolution as
111/// go-to-definition / references, so hover cannot disagree with them.
112pub 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
121/// Every local-binding occurrence in the file — `(span, is_definition)` — for
122/// semantic-token colouring. A token is a definition if it sits on a binding's
123/// def span, else a use if it resolves to a local in scope at that point.
124pub fn local_token_sites(locals: &[LocalBinding], text: &str) -> Vec<(Span, bool)> {
125    // Hole-aware (issue #473): locals used inside `\(…)` holes colour too.
126    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)); // a binding's def
137        } 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            // Finding #63: a field-access member name is excluded — a def
143            // token is never dot-preceded (it's a fresh binding, not an
144            // access), so that branch above is unaffected by this guard.
145            out.push((t.span, false)); // a use that resolves to a local
146        }
147    }
148    out
149}
150
151/// #2476: one variable the editor should show inline while a debugger is
152/// paused — where it is declared and the name the *emitted* code gives it.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct InlineValueSite {
155    /// The binding-name span, whose line gets the value.
156    pub range: Span,
157    /// The emitted TypeScript variable the debug adapter looks up.
158    pub variable: String,
159}
160
161/// Whether `text` is a `suite` file. A suite's cases run inside a scaffold
162/// that destructures names of its own (the unit under test's types and
163/// functions, assets, bindings, `for all` binders) in the same JS scope as the
164/// case body; deliberately over-approximate (a line merely starting `suite `
165/// counts), since the cost of a false positive is a missing inline value.
166pub fn is_suite_file(text: &str) -> bool {
167    text.lines().any(|l| l.trim_start().starts_with("suite "))
168}
169
170/// The bindings whose value to show at `stopped`: each local declared inside
171/// `visible` and still in scope where the debugger is paused, named as the
172/// emitter names it ([`bynk_check::emitted_names`]). A binding whose emitted
173/// name is not knowable from the source (a re-`let`) is left out rather than
174/// guessed, so a value is never shown against the wrong variable.
175///
176/// `scaffold_names` is `Some` for a suite file: the emitter gives a `let` a
177/// fresh name when the test scaffold already binds its name, and which names
178/// the scaffold binds is not visible here. So a `let` there is also left out
179/// when its name is one the project declares (`scaffold_names`, a superset of
180/// what a scaffold can destructure) or another local in the file reuses it
181/// (a `for all` binder or history run variable).
182pub 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 f(n: Int) -> Int { let x = n  <uses> }` laid out so offsets are easy.
219    fn bindings() -> Vec<LocalBinding> {
220        // text: see `TEXT`; n: param scope over body, x: let scope after its stmt.
221        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    //                   0         1         2         3
241    //                   0123456789012345678901234567890123456789
242
243    #[test]
244    fn sites_for_a_use_collect_def_plus_uses() {
245        let locals = bindings();
246        // Cursor on the first `x` use (offset 36, in `  x + x`).
247        let x_use = TEXT.match_indices('x').nth(1).unwrap().0; // first use of x
248        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(); // the `n` in `let x = n`
260        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()); // on `fn`
270    }
271
272    /// Finding #63: `total` is both a local *and*, unrelated, a record field
273    /// name — the `r.total` field access must never be mistaken for a use of
274    /// the local, in any of the three query surfaces this module exposes.
275    #[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        // Cursor on the field access resolves to nothing — not the local.
291        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        // The local's own use-site list must not include the field access.
297        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        // Semantic-token colouring must not mark the field access as a use.
304        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        // The `x` def is a declaration token.
320        assert!(
321            sites.contains(&(Span::new(26, 27), true)),
322            "x def is a declaration: {sites:?}"
323        );
324    }
325
326    // End-to-end against real checker output — the lexer's token spans must
327    // line up with the checker's recorded def spans.
328    #[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 total = …` then `total` — cursor on the use resolves to def + use.
347        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        // The definition is first and is the `let total` name.
351        let def = text.find("total").expect("total def");
352        assert_eq!(sites[0].start, def, "def first");
353    }
354
355    // v0.122 (slice 1): hover renders a local's `let`/`param` prefix and its
356    // inferred type, from the same real checker output.
357    #[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        // A `let` binding — `let total = xs.fold(…)` → `let total: Int`.
376        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        // A parameter — `fn sum(xs: List[Int])` → `param xs: List[Int]`. Use the
382        // def site so we land on the parameter, not a shadowing local.
383        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        // Not on a local (the `fn` keyword) → nothing.
389        assert!(describe_local_at(&locals, text, text.find("fn").unwrap()).is_none());
390    }
391
392    // Issue #473: a parameter used *inside* an interpolation hole
393    // (`"… \(name) …"`) must resolve the same as anywhere else. Drives the real
394    // hover / go-to-definition / references resolution against live checker
395    // output — the position→symbol step that was previously blind to holes
396    // because the file lexes the string to one opaque `InterpStr` token.
397
398    // `greet`'s param `name` is used only inside a `\(shout(name))` hole.
399    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    /// `(text, locals)` for `demo/text.bynk` after a real project analysis.
412    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    /// `(text, locals)` for `src` written at `rel` (e.g. `demo/text.bynk`) in a
417    /// fresh temp project, after a real `diagnose_project` analysis — so the
418    /// locals carry the checker's real file id, not `FileId::UNKNOWN`.
419    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    /// The byte offset of the `n`th occurrence of `needle` in `text`.
450    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        // 2nd `name`: the use inside `\(shout(name))` (1st is the declaration).
458        let in_hole = nth_offset(&text, "name", 1) + 1; // mid-identifier
459        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); // the parameter declaration
472        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    // A `let` binding and a parameter, each defined once and used once.
488    const STEPS_SRC: &str =
489        "commons demo.steps\n\nfn total(r: Int) -> Int {\n  let plain = r\n  plain\n}\n";
490
491    /// Definition tokens must survive real checker output: the lexer's spans
492    /// carry `FileId::UNKNOWN`, the checker's `def_span`s the file's real id,
493    /// so a whole-`Span` comparison dropped every definition token.
494    #[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        // Uses are still reported, as uses.
518        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        // Every token is reported once — a def is never also a use.
525        assert_eq!(sites.len(), 4, "two defs + two uses: {sites:?}");
526    }
527
528    /// References/rename over real checker output: an inner `let x` that
529    /// shadows an outer one is its own binding's definition, not a use of the
530    /// outer `x` — and the outer definition is listed exactly once.
531    #[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    // #2476: the sites come from real checker output, with the name mapping
551    // taken from the emitter's own rules.
552    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; // the final `total`
559        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        // The first `total` is the one kept, not the re-let.
570        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        // Only the `let total` line is visible.
578        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        // `w` is a `let` the scaffold may bind; the param `z` is never renamed.
610        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        // Paused on the first `let total` line: neither `total` is live yet.
627        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}