Skip to main content

bynk_lsp/
semantic_tokens.rs

1//! v0.28 (ADR 0057): semantic tokens over the project binding index.
2//!
3//! The one `index_queries` function that builds `lsp_types` values, so it stays
4//! with the transport; the rest of the queries live in
5//! [`bynk_ide::index_queries`] and are re-exported by `crate::index_queries`.
6
7use std::path::Path;
8
9use bynk_check::index::{ProjectIndex, SymbolKind};
10use bynk_syntax::span::Span;
11
12// -- v0.28 (ADR 0057): semantic tokens --
13
14/// The frozen semantic-tokens legend. **Array order is the wire encoding**
15/// (clients index into these arrays): entries are append-only, never
16/// reordered — pinned by the legend-stability test. Token types: standard
17/// where faithful (`type`, `function`), custom for the Bynk-distinctive
18/// kinds (`capability`, `service`, `agent`, `provider`). The names live in
19/// `bynk_syntax::semantic_tokens`, shared with the editor contract.
20pub fn semantic_tokens_legend() -> tower_lsp::lsp_types::SemanticTokensLegend {
21    use bynk_syntax::semantic_tokens::{TOKEN_MODIFIERS, TOKEN_TYPES};
22    use tower_lsp::lsp_types::{SemanticTokenModifier, SemanticTokenType, SemanticTokensLegend};
23    SemanticTokensLegend {
24        token_types: TOKEN_TYPES
25            .iter()
26            .map(|n| SemanticTokenType::new(n))
27            .collect(),
28        token_modifiers: TOKEN_MODIFIERS
29            .iter()
30            .map(|n| SemanticTokenModifier::new(n))
31            .collect(),
32    }
33}
34
35/// Legend indices/bits — must mirror [`semantic_tokens_legend`]'s order.
36fn token_type_index(kind: SymbolKind) -> u32 {
37    match kind {
38        SymbolKind::Type => 0,
39        SymbolKind::Fn => 1,
40        SymbolKind::Capability => 2,
41        SymbolKind::Service => 3,
42        SymbolKind::Agent => 4,
43        SymbolKind::Provider => 5,
44        // 6 is `variable` (locals; TOK_LOCAL); methods append at 7.
45        SymbolKind::Method => 7,
46        // v0.36 slice 2: ops reuse `method` (7); fields append `property` at 8.
47        SymbolKind::CapabilityOp => 7,
48        SymbolKind::Field => 8,
49        // v0.45: actors append `actor` at 9.
50        SymbolKind::Actor => 9,
51        // #304: agent handlers reuse `method` (7), same as capability ops.
52        SymbolKind::Handler => 7,
53        // message-bundles slice 1: `messages` bundles append `messages` at 11.
54        SymbolKind::Messages => 11,
55        // #1883: asset names append `asset` at 13.
56        SymbolKind::Asset => 13,
57        // #2387: embed names append `embed` at 14.
58        SymbolKind::Embed => 14,
59        // #2617: constant names append `constant` at 16.
60        SymbolKind::Const => 16,
61    }
62}
63
64/// Legend index of the `variable` token type (locals; ADR 0064).
65const TOK_LOCAL: u32 = 6;
66
67/// Legend index of the `decorator` token type (handler annotations; ADR 0163;
68/// #2958: a multi-line string literal's language tag).
69pub const TOK_DECORATOR: u32 = 10;
70
71/// Legend index of the `interface` token type (constraint names in a bound).
72pub const TOK_INTERFACE: u32 = 15;
73
74/// Legend index of the `method` token type.
75pub const TOK_METHOD: u32 = 7;
76
77/// Legend index of the `property` token type.
78pub const TOK_PROPERTY: u32 = 8;
79
80/// Legend index of the `keyword` token type (#2618: `private` in modifier
81/// position, a contextual keyword the editor grammars may not know).
82pub const TOK_KEYWORD: u32 = 17;
83
84/// Legend index of the `escape` token type (#2619: an escape sequence in a
85/// string literal).
86pub const TOK_ESCAPE: u32 = 18;
87
88/// Legend index of the `string` token type (#2619: a raw string's delimiters).
89pub const TOK_STRING: u32 = 19;
90
91const MOD_DECLARATION: u32 = 1 << 0;
92const MOD_REFINED: u32 = 1 << 1;
93const MOD_OPAQUE: u32 = 1 << 2;
94const MOD_PLATFORM_NATIVE: u32 = 1 << 3;
95
96fn modifier_bits(m: bynk_check::index::SymbolModifiers) -> u32 {
97    (if m.refined { MOD_REFINED } else { 0 })
98        | (if m.opaque { MOD_OPAQUE } else { 0 })
99        | (if m.platform_native {
100            MOD_PLATFORM_NATIVE
101        } else {
102            0
103        })
104}
105
106/// Semantic tokens for `path`, delta-encoded over the frozen legend —
107/// a pure read of the cached index's two sources: `symbols` (user
108/// defs+refs; a def site carries `declaration`) and `foreign_refs`
109/// (first-party references). `range` (byte offsets into `text`, the
110/// analysed snapshot) filters to overlapping tokens for the `…/range`
111/// request; `None` is the full document.
112pub fn semantic_tokens(
113    index: &ProjectIndex,
114    local_tokens: &[(Span, bool)],
115    syntax_tokens: &[(Span, u32)],
116    path: &Path,
117    text: &str,
118    range: Option<Span>,
119) -> Vec<tower_lsp::lsp_types::SemanticToken> {
120    let in_scope = |span: Span| {
121        span.end <= text.len() && range.is_none_or(|r| span.end > r.start && span.start < r.end)
122    };
123    let mut raw: Vec<(Span, u32, u32)> = Vec::new();
124    for (key, entry) in &index.symbols {
125        // #3582: a service handler is call-hierarchy-only; the call site keeps
126        // the `Service` token and the `on` keyword stays a keyword.
127        if entry.call_only {
128            continue;
129        }
130        let ty = token_type_index(key.kind);
131        let mods = modifier_bits(entry.modifiers);
132        if let Some(def) = &entry.def
133            && def.path == path
134            && in_scope(def.span)
135        {
136            raw.push((def.span, ty, mods | MOD_DECLARATION));
137        }
138        for site in &entry.refs {
139            if site.path == path && in_scope(site.span) {
140                raw.push((site.span, ty, mods));
141            }
142        }
143    }
144    for fr in &index.foreign_refs {
145        if fr.site.path == path && in_scope(fr.site.span) {
146            raw.push((
147                fr.site.span,
148                token_type_index(fr.kind),
149                modifier_bits(fr.modifiers),
150            ));
151        }
152    }
153    // v0.31 (ADR 0064): local bindings + their uses (precomputed by the caller
154    // via `locals_nav`, so this stays free of that dependency for the
155    // `#[path]`-include tests). Disjoint from the index tokens — locals are
156    // never top-level symbols — so they merge into the same sorted stream.
157    for &(span, is_decl) in local_tokens {
158        if in_scope(span) {
159            raw.push((span, TOK_LOCAL, if is_decl { MOD_DECLARATION } else { 0 }));
160        }
161    }
162    // v0.140 (ADR 0163): handler-annotation name + argument-label spans (precomputed
163    // by the caller from the parsed unit, keeping this a parse-free index read).
164    // Disjoint from the index/local tokens — annotations are neither symbols nor
165    // locals — so they merge into the same sorted stream.
166    // Constrained generics slice 0: constraint names ride the same list, as
167    // `interface` (the caller classifies each span). #2618: so does each
168    // `private` modifier, as `keyword`.
169    for &(span, ty) in syntax_tokens {
170        if in_scope(span) {
171            raw.push((span, ty, 0));
172        }
173    }
174    // Name segments never overlap (the index invariant), so a position
175    // sort fully determines the protocol's relative encoding.
176    raw.sort_by_key(|(span, _, _)| (span.start, span.end));
177    // #2837: the lexical keyword-name tokens overlap the index's at a keyword
178    // field or method the index also knows; the sort is stable and the index's
179    // entries come first, so keeping the first of a span keeps the index's.
180    raw.dedup_by_key(|(span, _, _)| (span.start, span.end));
181    let mut data = Vec::with_capacity(raw.len());
182    // One line index for the whole snapshot: a `semanticTokens/full` request
183    // emits a position per token, so scanning from byte 0 each time is O(n²)
184    // (#732). Build it once and binary-search per token instead.
185    let positions = crate::position::PositionMap::new(text);
186    let (mut prev_line, mut prev_start) = (0u32, 0u32);
187    for (span, token_type, token_modifiers_bitset) in raw {
188        let pos = positions.position(span.start);
189        let delta_line = pos.line - prev_line;
190        let delta_start = if delta_line == 0 {
191            pos.character - prev_start
192        } else {
193            pos.character
194        };
195        data.push(tower_lsp::lsp_types::SemanticToken {
196            delta_line,
197            delta_start,
198            // The protocol counts in the negotiated encoding (UTF-16, as
199            // positions are) — not bytes.
200            length: text[span.range()].encode_utf16().count() as u32,
201            token_type,
202            token_modifiers_bitset,
203        });
204        prev_line = pos.line;
205        prev_start = pos.character;
206    }
207    data
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use bynk_check::index::{SiteRef, SymbolEntry, SymbolKey};
214    use std::path::PathBuf;
215
216    fn site(path: &str, start: usize, end: usize) -> SiteRef {
217        SiteRef {
218            path: PathBuf::from(path),
219            span: Span::new(start, end),
220        }
221    }
222
223    fn key(unit: &str, kind: SymbolKind, name: &str) -> SymbolKey {
224        SymbolKey {
225            unit: unit.into(),
226            kind,
227            name: name.into(),
228        }
229    }
230
231    fn index_with(entries: Vec<(SymbolKey, SiteRef, Vec<SiteRef>)>) -> ProjectIndex {
232        let mut index = ProjectIndex::default();
233        for (k, def, refs) in entries {
234            index.symbols.insert(
235                k,
236                SymbolEntry {
237                    def: Some(def),
238                    refs,
239                    ..Default::default()
240                },
241            );
242        }
243        index
244    }
245
246    // -- v0.28 (ADR 0057): semantic tokens --
247
248    /// The legend's array order IS the wire encoding: this test freezes it.
249    /// New entries APPEND — a failure here means a silent recolour of every
250    /// client; never fix it by reordering.
251    #[test]
252    fn legend_is_frozen() {
253        let legend = semantic_tokens_legend();
254        let types: Vec<&str> = legend.token_types.iter().map(|t| t.as_str()).collect();
255        assert_eq!(
256            types,
257            [
258                "type",
259                "function",
260                "capability",
261                "service",
262                "agent",
263                "provider",
264                "variable",  // v0.31 (ADR 0064): locals — appended, never reordered
265                "method",    // v0.36 (ADR 0069): instance methods — appended
266                "property",  // v0.36 (ADR 0069, slice 2): record fields — appended
267                "actor",     // v0.45: actor declarations — appended
268                "decorator", // v0.140 (ADR 0163): handler annotations — appended
269                "messages",  // message-bundles slice 1 (#859): messages bundles — appended
270                "comment",   // #1888: `--|` doc lines — appended
271                "asset",     // #1883: static asset names — appended
272                "embed",     // #2387: embedded-text names — appended
273                "interface", // constrained generics slice 0: constraint names — appended
274                "constant",  // #2617: named constants — appended
275                "keyword",   // #2618: contextual `private` modifier — appended
276                "escape",    // #2619: escape sequences in string literals — appended
277                "string",    // #2619: raw string delimiters — appended
278            ]
279        );
280        let modifiers: Vec<&str> = legend.token_modifiers.iter().map(|m| m.as_str()).collect();
281        assert_eq!(
282            modifiers,
283            [
284                "declaration",
285                "refined",
286                "opaque",
287                "platformNative",
288                "documentation"
289            ]
290        );
291    }
292
293    /// #2203: a one-line doc gets no semantic token, as a `---` block gets
294    /// none, so the editor grammar's Markdown highlighting shows through; the
295    /// legend keeps its `comment` type and `documentation` modifier.
296    #[test]
297    fn doc_lines_get_no_semantic_token() {
298        let text = "commons m\n\n  --- A doc.\n// a comment\ntype T = Int\n";
299        let tokens = semantic_tokens(
300            &ProjectIndex::default(),
301            &[],
302            &[],
303            Path::new("a.bynk"),
304            text,
305            None,
306        );
307        assert!(tokens.is_empty(), "{tokens:?}");
308        let legend = semantic_tokens_legend();
309        assert_eq!(legend.token_types[12].as_str(), "comment");
310        assert_eq!(legend.token_modifiers[4].as_str(), "documentation");
311    }
312
313    /// Constrained generics slice 1: the names of a `derives Ord` clause are
314    /// `interface` tokens, with those of a bound; the contextual `derives`
315    /// itself gets none (keywords are the editor grammar's).
316    #[test]
317    fn derives_and_bound_constraint_names_are_interface_tokens() {
318        let text = "commons m\n\ntype P = Int derives Ord\nfn f[T: Eq + Ord](a: T) -> T { a }\n";
319        let syntax: Vec<(Span, u32)> = crate::symbols::constraint_token_spans(text)
320            .into_iter()
321            .map(|s| (s, TOK_INTERFACE))
322            .collect();
323        let tokens = semantic_tokens(
324            &ProjectIndex::default(),
325            &[],
326            &syntax,
327            Path::new("a.bynk"),
328            text,
329            None,
330        );
331        assert_eq!(tokens.len(), 3, "{tokens:?}");
332        assert!(tokens.iter().all(|t| t.token_type == TOK_INTERFACE));
333        // First token: `Ord` after `derives ` (line 2, char 21), length 3.
334        assert_eq!(
335            (
336                tokens[0].delta_line,
337                tokens[0].delta_start,
338                tokens[0].length
339            ),
340            (2, 21, 3)
341        );
342    }
343
344    #[test]
345    fn tokens_are_delta_encoded_with_modifier_bitsets() {
346        // text:  line 0: "type Age = Int"   (def `Age` at 5..8, refined)
347        //        line 1: "fn f(a: Age) ..." (ref `Age` at 23..26)
348        let text = "type Age = Int\nfn f(a: Age) -> Age {}\n";
349        let mut index = index_with(vec![(
350            key("shop", SymbolKind::Type, "Age"),
351            site("a.bynk", 5, 8),
352            vec![site("a.bynk", 23, 26), site("a.bynk", 31, 34)],
353        )]);
354        index
355            .symbols
356            .get_mut(&key("shop", SymbolKind::Type, "Age"))
357            .unwrap()
358            .modifiers = bynk_check::index::SymbolModifiers {
359            refined: true,
360            ..Default::default()
361        };
362        let tokens = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), text, None);
363        assert_eq!(tokens.len(), 3);
364        // Def: line 0 char 5, length 3, type `type` (0), declaration|refined.
365        assert_eq!(
366            (
367                tokens[0].delta_line,
368                tokens[0].delta_start,
369                tokens[0].length
370            ),
371            (0, 5, 3)
372        );
373        assert_eq!(tokens[0].token_type, 0);
374        assert_eq!(tokens[0].token_modifiers_bitset, 0b0011);
375        // First ref: next line, char 8 (absolute — line changed), refined only.
376        assert_eq!(
377            (
378                tokens[1].delta_line,
379                tokens[1].delta_start,
380                tokens[1].length
381            ),
382            (1, 8, 3)
383        );
384        assert_eq!(tokens[1].token_modifiers_bitset, 0b0010);
385        // Second ref: same line, char delta from the previous token's start.
386        assert_eq!(
387            (
388                tokens[2].delta_line,
389                tokens[2].delta_start,
390                tokens[2].length
391            ),
392            (0, 8, 3)
393        );
394    }
395
396    /// #3582: a call-only service handler adds no token — the call site keeps
397    /// its `service` token and the `on` keyword is not classified.
398    #[test]
399    fn call_only_service_handler_adds_no_tokens() {
400        let mut index = ProjectIndex::default();
401        index.symbols.insert(
402            SymbolKey {
403                unit: "u".into(),
404                kind: SymbolKind::Service,
405                name: "charge".into(),
406            },
407            SymbolEntry {
408                def: Some(site("a.bynk", 0, 6)),
409                refs: vec![site("a.bynk", 20, 26)],
410                ..Default::default()
411            },
412        );
413        index.symbols.insert(
414            SymbolKey {
415                unit: "u".into(),
416                kind: SymbolKind::Handler,
417                name: "charge.call".into(),
418            },
419            SymbolEntry {
420                def: Some(site("a.bynk", 10, 12)),
421                refs: vec![site("a.bynk", 20, 26)],
422                call_only: true,
423                ..Default::default()
424            },
425        );
426        let toks = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), &" ".repeat(40), None);
427        assert_eq!(toks.len(), 2, "service def + service call site only");
428        assert!(toks.iter().all(|t| t.token_type == 3));
429    }
430
431    #[test]
432    fn foreign_refs_emit_tokens_and_range_filters() {
433        let text = "given Kv {\n  Kv.get(k)\n}\n";
434        let mut index = ProjectIndex::default();
435        index.foreign_refs.push(bynk_check::index::ForeignRef {
436            site: site("a.bynk", 6, 8),
437            kind: SymbolKind::Capability,
438            modifiers: bynk_check::index::SymbolModifiers {
439                platform_native: true,
440                ..Default::default()
441            },
442        });
443        index.foreign_refs.push(bynk_check::index::ForeignRef {
444            site: site("a.bynk", 13, 15),
445            kind: SymbolKind::Capability,
446            modifiers: bynk_check::index::SymbolModifiers {
447                platform_native: true,
448                ..Default::default()
449            },
450        });
451        let all = semantic_tokens(&index, &[], &[], Path::new("a.bynk"), text, None);
452        assert_eq!(all.len(), 2);
453        assert_eq!(all[0].token_type, 2); // capability
454        assert_eq!(all[0].token_modifiers_bitset, 0b1000); // platformNative
455        // Range covering only line 0 keeps only the first token.
456        let ranged = semantic_tokens(
457            &index,
458            &[],
459            &[],
460            Path::new("a.bynk"),
461            text,
462            Some(Span::new(0, 10)),
463        );
464        assert_eq!(ranged.len(), 1);
465        // Other files and empty indexes yield nothing.
466        assert!(semantic_tokens(&index, &[], &[], Path::new("b.bynk"), text, None).is_empty());
467        assert!(
468            semantic_tokens(
469                &ProjectIndex::default(),
470                &[],
471                &[],
472                Path::new("a.bynk"),
473                text,
474                None
475            )
476            .is_empty()
477        );
478    }
479}