Skip to main content

bynk_check/
locals.rs

1//! v0.31 (ADR 0064): the local-binding sink.
2//!
3//! Records each local binding — `let`/`let <-`, lambda/fn/handler parameters,
4//! and match-arm pattern bindings — with its **lexical scope range**, so the
5//! LSP can offer/navigate locals (the recurring deferral: the v0.25 index, the
6//! v0.27 hints, the v0.28 tokens, and v0.30.2 completion all stop at top-level
7//! symbols for want of a scope-at-offset query).
8//!
9//! Mirrors [`HintSink`](crate::hints::HintSink): a `&mut` sink threaded through
10//! the checker, recording at the binding sites as types are computed — so it
11//! survives a transient error at the sites the checker still reaches, and (like
12//! hints) it is not part of the `Ok(TypedCommons)` payload. Scope ranges are
13//! taken from the enclosing block/body/arm span the checker already has at each
14//! binding site, not re-derived — so nesting and shadowing are the checker's
15//! own (tested) scoping, resolved in [`locals_at`]. Only synthetic files are
16//! muted (locals serve completion/navigation in test files too).
17
18use bynk_syntax::span::Span;
19use std::collections::HashMap;
20use std::path::{Path, PathBuf};
21
22/// What kind of local binding this is — the distinction hover renders as its
23/// `let`/`param` prefix (v0.122, editor-currency slice 1). Every
24/// [`LocalsSink::record`] site knows its kind statically; this is a threaded
25/// argument, not inferred.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum LocalKind {
28    /// A `let =` / `let <-` binding.
29    Let,
30    /// A parameter — fn / handler / op / lambda, or an actor `by`-binder.
31    Param,
32}
33
34/// One local binding: its name, the binding-name span (the def site), its
35/// [`kind`](LocalKind), its rendered type (Bynk surface syntax, as hints
36/// render — no `Ty` on the surface), and the source range over which it is in
37/// scope.
38#[derive(Debug, Clone)]
39pub struct LocalBinding {
40    pub name: String,
41    pub def_span: Span,
42    pub kind: LocalKind,
43    pub ty: String,
44    pub scope: Span,
45}
46
47/// Project-relative source path → that file's local bindings, in source order.
48pub type FileLocals = HashMap<PathBuf, Vec<LocalBinding>>;
49
50/// Records local bindings per file. A fresh sink records nothing until
51/// [`enter_file`](Self::enter_file) attributes it.
52#[derive(Debug, Default, Clone)]
53pub struct LocalsSink {
54    files: FileLocals,
55    file: Option<PathBuf>,
56    /// Set for synthetic (toolchain-injected) files only.
57    muted: bool,
58    /// (file, name, def site) → indices into that file's entries.
59    index: HashMap<(PathBuf, String, Span), Vec<usize>>,
60}
61
62impl LocalsSink {
63    pub fn new() -> Self {
64        Self::default()
65    }
66
67    /// Enter a per-file recording context.
68    pub fn enter_file(&mut self, file: &Path, muted: bool) {
69        self.file = Some(file.to_path_buf());
70        self.muted = muted;
71    }
72
73    /// Record a binding `name` defined at `def_span`, of the given `kind` and
74    /// rendered type `ty`, in scope over `scope`. Dropped when muted or before
75    /// any `enter_file`.
76    pub fn record(
77        &mut self,
78        name: String,
79        def_span: Span,
80        kind: LocalKind,
81        ty: String,
82        scope: Span,
83    ) {
84        if self.muted {
85            return;
86        }
87        let Some(file) = &self.file else {
88            return;
89        };
90        let entries = self.files.entry(file.clone()).or_default();
91        // #2701: an `is` binding is recorded once per region it is in scope in
92        // (a left-nested `&&` chain records it per operand). The same binding
93        // (same file, name and def site) with an overlapping scope is one
94        // entry; a disjoint scope is its own entry, never the hull of the two,
95        // so the gap between them (where an outer same-named binding may be
96        // the one in scope) stays out of scope.
97        let slot = self
98            .index
99            .entry((file.clone(), name.clone(), def_span))
100            .or_default();
101        for &i in slot.iter() {
102            let prev: &mut LocalBinding = &mut entries[i];
103            if prev.scope.start <= scope.end && scope.start <= prev.scope.end {
104                prev.scope = prev.scope.merge(scope);
105                prev.ty = ty;
106                prev.kind = kind;
107                return;
108            }
109        }
110        slot.push(entries.len());
111        entries.push(LocalBinding {
112            name,
113            def_span,
114            kind,
115            ty,
116            scope,
117        });
118    }
119
120    /// Fold in what `other` recorded (#3243 S2.3). A file already present keeps
121    /// its entries; `other`'s are appended and its merge index shifted to match.
122    pub fn absorb(&mut self, other: LocalsSink) {
123        let LocalsSink { files, index, .. } = other;
124        let mut offsets: HashMap<PathBuf, usize> = HashMap::new();
125        for (file, entries) in files {
126            let slot = self.files.entry(file.clone()).or_default();
127            offsets.insert(file, slot.len());
128            slot.extend(entries);
129        }
130        for ((file, name, span), positions) in index {
131            let base = offsets.get(&file).copied().unwrap_or(0);
132            self.index
133                .entry((file, name, span))
134                .or_default()
135                .extend(positions.into_iter().map(|p| p + base));
136        }
137    }
138
139    /// Drain the recorded bindings, each file's entries ordered by def span.
140    pub fn take_files(&mut self) -> FileLocals {
141        self.index.clear();
142        let mut files = std::mem::take(&mut self.files);
143        for locals in files.values_mut() {
144            locals.sort_by_key(|b| (b.def_span.start, b.def_span.end));
145        }
146        files
147    }
148}
149
150/// The local bindings in scope at `offset`, deduplicated by name with the
151/// **innermost/latest** definition winning (shadowing) — the completion and
152/// navigation query.
153pub fn locals_at(entries: &[LocalBinding], offset: usize) -> Vec<&LocalBinding> {
154    let mut by_name: HashMap<&str, &LocalBinding> = HashMap::new();
155    for b in entries {
156        if b.scope.start <= offset && offset <= b.scope.end {
157            // Later def (larger start) shadows an earlier same-name binding.
158            by_name
159                .entry(&b.name)
160                .and_modify(|cur| {
161                    if b.def_span.start >= cur.def_span.start {
162                        *cur = b;
163                    }
164                })
165                .or_insert(b);
166        }
167    }
168    let mut out: Vec<&LocalBinding> = by_name.into_values().collect();
169    out.sort_by_key(|b| (b.def_span.start, b.def_span.end));
170    out
171}
172
173/// The single binding whose **def-name** span covers `offset` — the
174/// definition-site query (for references/rename on a local's declaration).
175pub fn binding_at_def(entries: &[LocalBinding], offset: usize) -> Option<&LocalBinding> {
176    entries
177        .iter()
178        .find(|b| b.def_span.start <= offset && offset <= b.def_span.end)
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    fn b(name: &str, def: usize, scope: (usize, usize)) -> LocalBinding {
186        LocalBinding {
187            name: name.to_string(),
188            def_span: Span::new(def, def + name.len()),
189            kind: LocalKind::Let,
190            ty: "Int".to_string(),
191            scope: Span::new(scope.0, scope.1),
192        }
193    }
194
195    #[test]
196    fn absorb_rebases_the_merge_index_onto_a_file_already_present() {
197        let file = Path::new("a.bynk");
198        let record =
199            |sink: &mut LocalsSink, name: &str, ty: &str, def: usize, scope: (usize, usize)| {
200                sink.enter_file(file, false);
201                sink.record(
202                    name.to_string(),
203                    Span::new(def, def + 1),
204                    LocalKind::Let,
205                    ty.to_string(),
206                    Span::new(scope.0, scope.1),
207                );
208            };
209        let mut kept = LocalsSink::new();
210        record(&mut kept, "x", "Int", 1, (10, 20));
211        let mut other = LocalsSink::new();
212        record(&mut other, "y", "Int", 2, (10, 20));
213        kept.absorb(other);
214        // The same binding as the absorbed `y`, overlapping scope: it must merge
215        // into that entry (now at index 1), not duplicate it or touch `x`.
216        record(&mut kept, "y", "String", 2, (15, 30));
217        let files = kept.take_files();
218        let entries = &files[file];
219        assert_eq!(entries.len(), 2, "no duplicate entry: {entries:?}");
220        let x = entries.iter().find(|e| e.name == "x").unwrap();
221        let y = entries.iter().find(|e| e.name == "y").unwrap();
222        assert_eq!((x.ty.as_str(), x.scope), ("Int", Span::new(10, 20)));
223        assert_eq!((y.ty.as_str(), y.scope), ("String", Span::new(10, 30)));
224    }
225
226    #[test]
227    fn record_merges_overlapping_scopes_keeps_disjoint_ones_apart_and_last_wins() {
228        let mut sink = LocalsSink::new();
229        sink.enter_file(Path::new("a.bynk"), false);
230        let def = Span::new(10, 11);
231        let rec = |sink: &mut LocalsSink, ty: &str, lo: usize, hi: usize| {
232            sink.record(
233                "v".to_string(),
234                def,
235                LocalKind::Let,
236                ty.to_string(),
237                Span::new(lo, hi),
238            );
239        };
240        rec(&mut sink, "Int", 20, 30);
241        rec(&mut sink, "String", 25, 40); // overlaps: merges, last type wins
242        rec(&mut sink, "Bool", 60, 70); // disjoint: its own entry
243        let files = sink.take_files();
244        let got = &files[Path::new("a.bynk")];
245        assert_eq!(got.len(), 2, "{got:?}");
246        assert_eq!((got[0].scope.start, got[0].scope.end), (20, 40));
247        assert_eq!(got[0].ty, "String");
248        assert_eq!((got[1].scope.start, got[1].scope.end), (60, 70));
249        assert_eq!(got[1].ty, "Bool");
250    }
251
252    #[test]
253    fn locals_at_filters_by_scope_and_resolves_shadowing() {
254        let entries = vec![
255            b("x", 0, (3, 50)),   // outer x
256            b("y", 10, (13, 30)), // y, narrower scope
257            b("x", 20, (23, 50)), // inner x shadows the outer
258        ];
259        // Before y's scope: just the outer x.
260        assert_eq!(names(&locals_at(&entries, 5)), vec!["x"]);
261        // Inside y's scope, before the inner x: x (outer) + y.
262        assert_eq!(names(&locals_at(&entries, 15)), vec!["x", "y"]);
263        // After the inner x and past y's scope: one x (the inner shadows).
264        let at = locals_at(&entries, 40);
265        assert_eq!(names(&at), vec!["x"]);
266        assert_eq!(at[0].def_span.start, 20, "latest x wins");
267    }
268
269    #[test]
270    fn binding_at_def_finds_the_declaration_under_the_cursor() {
271        let entries = vec![b("total", 4, (12, 40))];
272        assert!(binding_at_def(&entries, 6).is_some()); // on the name
273        assert!(binding_at_def(&entries, 20).is_none()); // a use site, not the def
274    }
275
276    fn names(bs: &[&LocalBinding]) -> Vec<String> {
277        bs.iter().map(|b| b.name.clone()).collect()
278    }
279}