Skip to main content

logicaffeine_lsp/
semantic_tokens.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::OnceLock;
3
4use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensLegend};
5
6use logicaffeine_language::token::{BlockType, RawKind, Span, Token, TokenType};
7
8use crate::document::DocumentState;
9use crate::index::DefinitionKind;
10use crate::line_index::LineIndex;
11
12/// Our semantic token types, registered with the client.
13/// The legend is APPEND-ONLY — indices are a wire contract with client themes
14/// (pinned by `tests/locks.rs`).
15pub const TOKEN_TYPES: &[SemanticTokenType] = &[
16    SemanticTokenType::KEYWORD,     // 0
17    SemanticTokenType::TYPE,        // 1
18    SemanticTokenType::FUNCTION,    // 2
19    SemanticTokenType::VARIABLE,    // 3
20    SemanticTokenType::STRING,      // 4
21    SemanticTokenType::NUMBER,      // 5
22    SemanticTokenType::OPERATOR,    // 6
23    SemanticTokenType::NAMESPACE,   // 7
24    SemanticTokenType::MODIFIER,    // 8
25    SemanticTokenType::PROPERTY,    // 9
26    SemanticTokenType::COMMENT,     // 10
27    SemanticTokenType::PARAMETER,   // 11
28    SemanticTokenType::ENUM_MEMBER, // 12
29    // A template's element names and plain attribute names. No standard type exists for either;
30    // the VS Code manifest maps both onto the TextMate scopes an HTML grammar uses, so a theme
31    // paints them as it paints HTML.
32    SemanticTokenType::new("tag"),       // 13
33    SemanticTokenType::new("attribute"), // 14
34];
35
36pub const TOKEN_MODIFIERS: &[SemanticTokenModifier] = &[
37    SemanticTokenModifier::DECLARATION,     // bit 0
38    SemanticTokenModifier::READONLY,        // bit 1
39    SemanticTokenModifier::MODIFICATION,    // bit 2 — write sites (Set/Increase/Push targets)
40    SemanticTokenModifier::DEFAULT_LIBRARY, // bit 3 — stdlib prelude names
41];
42
43pub const TYPE_KEYWORD: u32 = 0;
44pub const TYPE_TYPE: u32 = 1;
45pub const TYPE_FUNCTION: u32 = 2;
46pub const TYPE_VARIABLE: u32 = 3;
47pub const TYPE_STRING: u32 = 4;
48pub const TYPE_NUMBER: u32 = 5;
49pub const TYPE_OPERATOR: u32 = 6;
50pub const TYPE_NAMESPACE: u32 = 7;
51pub const TYPE_MODIFIER: u32 = 8;
52pub const TYPE_PROPERTY: u32 = 9;
53pub const TYPE_COMMENT: u32 = 10;
54pub const TYPE_PARAMETER: u32 = 11;
55pub const TYPE_ENUM_MEMBER: u32 = 12;
56pub const TYPE_TAG: u32 = 13;
57pub const TYPE_ATTRIBUTE: u32 = 14;
58
59pub const MOD_DECLARATION: u32 = 1 << 0;
60pub const MOD_READONLY: u32 = 1 << 1;
61pub const MOD_MODIFICATION: u32 = 1 << 2;
62pub const MOD_DEFAULT_LIBRARY: u32 = 1 << 3;
63
64pub fn legend() -> SemanticTokensLegend {
65    SemanticTokensLegend {
66        token_types: TOKEN_TYPES.to_vec(),
67        token_modifiers: TOKEN_MODIFIERS.to_vec(),
68    }
69}
70
71/// Encode a document's tokens with the full resolution overlay.
72///
73/// The base layer is part-of-speech classification ([`classify_token`]);
74/// the overlay upgrades identifiers through the `SymbolIndex` — a name that
75/// resolves to a parameter IS a parameter, at declaration and at every
76/// reference — and adds the modifier facts: DECLARATION only where
77/// `token.span == definition.span`, READONLY for immutable `Let`s,
78/// MODIFICATION on write sites, DEFAULT_LIBRARY on stdlib prelude names.
79/// Prose inside `## Note`/`## Example` blocks recedes to COMMENT.
80pub fn encode_document_tokens(doc: &DocumentState) -> Vec<SemanticToken> {
81    let overlay = ResolutionOverlay::build(doc);
82    let spans = paint_spans(doc, &overlay, None);
83    encode_spans(&spans, &doc.line_index)
84}
85
86/// The classified paint spans for the document: one per token, EXCEPT
87/// interpolated strings, whose `{expr}` interiors expand into real code
88/// spans — string segments stay strings, braces paint as operators, and the
89/// interior re-lexes and resolves against the document's own index — and a
90/// `View:` / `Head:` body, which is painted by its own grammar
91/// ([`paint_template`]).
92fn paint_spans(
93    doc: &DocumentState,
94    overlay: &ResolutionOverlay,
95    range: Option<(usize, usize)>,
96) -> Vec<(Span, u32, u32)> {
97    let mut spans = Vec::new();
98    for token in &doc.tokens {
99        if let Some((start, end)) = range {
100            if token.span.end <= start || token.span.start >= end {
101                continue;
102            }
103        }
104        if let TokenType::RawBlock { kind, .. } = token.kind {
105            if matches!(kind, RawKind::View | RawKind::Head) {
106                paint_template(doc, overlay, token.span, &mut spans);
107            }
108            continue;
109        }
110        let (token_type, modifiers) = overlay.classify(token, doc);
111        let Some(token_type) = token_type else {
112            continue;
113        };
114        if matches!(token.kind, TokenType::InterpolatedString(_)) && token_type == TYPE_STRING {
115            expand_interpolation(doc, overlay, token, &mut spans);
116        } else {
117            spans.push((token.span, token_type, modifiers));
118        }
119    }
120    spans
121}
122
123/// Paint a `View:` / `Head:` body by the language it is written in.
124///
125/// The body is HTML whose `{…}` groups are template tags and LOGOS holes, so it is painted as
126/// that: an element's name as a `tag` (a component's as the `type` it names), an attribute's name
127/// as an `attribute` (a component's as the `parameter` it binds, a directive as the `keyword` the
128/// framework reads, an event modifier as a `modifier`), a static value as a `string`, a tag's
129/// phrase and clause words as `keyword`s, and every expression through the resolution the rest of
130/// the file gets. Text and markup punctuation carry no token: the editor's HTML grammar paints
131/// them, and a semantic token over them would replace its colouring.
132///
133/// A `Style:` body gets no tokens for the same reason — the CSS grammar paints it and the server
134/// knows nothing about CSS it could add.
135///
136/// The token's span is the body's place in the file with its indentation intact, and indentation
137/// is whitespace to HTML, so tokenizing that slice yields spans that are file offsets once shifted
138/// by its start. A body that does not tokenize (a tag half-typed) gets no tokens.
139fn paint_template(
140    doc: &DocumentState,
141    overlay: &ResolutionOverlay,
142    span: Span,
143    out: &mut Vec<(Span, u32, u32)>,
144) {
145    use logicaffeine_language::lgx::html::{self, HtmlToken};
146    let Some(body) = doc.source.get(span.start..span.end) else {
147        return;
148    };
149    let Ok(tokens) = html::tokenize(body) else {
150        return;
151    };
152    let base = span.start;
153    for token in &tokens {
154        match token {
155            HtmlToken::StartTag {
156                name,
157                attrs,
158                span: at,
159                ..
160            } => {
161                let component = html::is_component_name(name);
162                paint_tag_name(name, base + at.start + 1, out);
163                for attr in attrs {
164                    paint_attribute(doc, overlay, body, base, attr, component, out);
165                }
166            }
167            HtmlToken::EndTag { name, span: at } => paint_tag_name(name, base + at.start + 2, out),
168            HtmlToken::Brace { inner, span: at } => {
169                paint_brace(doc, overlay, inner, base + at.start, out)
170            }
171            HtmlToken::Text { .. } => {}
172        }
173    }
174}
175
176/// An element's name: a component is the type it names, anything else is an HTML tag.
177fn paint_tag_name(name: &str, at: usize, out: &mut Vec<(Span, u32, u32)>) {
178    let kind = if logicaffeine_language::lgx::html::is_component_name(name) {
179        TYPE_TYPE
180    } else {
181        TYPE_TAG
182    };
183    out.push((Span::new(at, at + name.len()), kind, 0));
184}
185
186/// One attribute of a start tag, name and value. `body` is the template text `attr`'s span indexes
187/// and `base` its offset in the file.
188fn paint_attribute(
189    doc: &DocumentState,
190    overlay: &ResolutionOverlay,
191    body: &str,
192    base: usize,
193    attr: &logicaffeine_language::lgx::html::HtmlAttr,
194    on_component: bool,
195    out: &mut Vec<(Span, u32, u32)>,
196) {
197    use logicaffeine_language::lgx::html::{AttrPart, AttrValue};
198    let name = attr.name.as_str();
199    let at = base + attr.span.start;
200    if let Some(directive) = name.strip_prefix("on-") {
201        let mut pieces = directive.split('.');
202        let event = pieces.next().unwrap_or("");
203        let mut cursor = at + "on-".len() + event.len();
204        out.push((Span::new(at, cursor), TYPE_KEYWORD, 0));
205        for modifier in pieces {
206            let end = cursor + 1 + modifier.len();
207            out.push((Span::new(cursor, end), TYPE_MODIFIER, 0));
208            cursor = end;
209        }
210    } else if let Some(class) = name.strip_prefix("class:") {
211        let split = at + "class:".len();
212        out.push((Span::new(at, split), TYPE_KEYWORD, 0));
213        out.push((Span::new(split, split + class.len()), TYPE_ATTRIBUTE, 0));
214    } else if name == "bind" {
215        out.push((Span::new(at, at + name.len()), TYPE_KEYWORD, 0));
216    } else {
217        let kind = if on_component {
218            TYPE_PARAMETER
219        } else {
220            TYPE_ATTRIBUTE
221        };
222        out.push((Span::new(at, at + name.len()), kind, 0));
223    }
224
225    let Some(value) = &attr.value else { return };
226    // The value begins after the name, the `=` and any whitespace around it.
227    let after_name = attr.span.start + name.len();
228    let value_start = body[after_name..attr.span.end]
229        .find(|c: char| !c.is_whitespace() && c != '=')
230        .map_or(attr.span.end, |k| after_name + k);
231    let mut cursor = value_start;
232    if let AttrValue::Parts(parts) = value {
233        for part in parts {
234            let AttrPart::Brace { inner, span } = part else {
235                continue;
236            };
237            if span.start > cursor {
238                out.push((Span::new(base + cursor, base + span.start), TYPE_STRING, 0));
239            }
240            paint_brace(doc, overlay, inner, base + span.start, out);
241            cursor = span.end;
242        }
243    }
244    if attr.span.end > cursor {
245        out.push((
246            Span::new(base + cursor, base + attr.span.end),
247            TYPE_STRING,
248            0,
249        ));
250    }
251}
252
253/// One `{…}` group whose `{` sits at file offset `open`: a comment, a template tag (its phrase a
254/// keyword, the rest code), or a hole (code, then each filter a function applied to it).
255fn paint_brace(
256    doc: &DocumentState,
257    overlay: &ResolutionOverlay,
258    inner: &str,
259    open: usize,
260    out: &mut Vec<(Span, u32, u32)>,
261) {
262    let close = open + 1 + inner.len();
263    if crate::template::is_comment(inner) {
264        out.push((Span::new(open, close + 1), TYPE_COMMENT, 0));
265        return;
266    }
267    out.push((Span::new(open, open + 1), TYPE_OPERATOR, 0));
268    let at = open + 1;
269    match crate::template::tag_phrase(inner) {
270        Some((phrase, len)) => {
271            out.push((
272                Span::new(at + len - phrase.len(), at + len),
273                TYPE_KEYWORD,
274                0,
275            ));
276            let rest = &inner[len..];
277            if phrase == "for each" {
278                paint_with_clause_words(
279                    doc,
280                    overlay,
281                    rest,
282                    at + len,
283                    crate::template::FOR_EACH_CLAUSES,
284                    out,
285                );
286            } else {
287                paint_fragment(doc, overlay, rest, at + len, out);
288            }
289        }
290        None => {
291            let pipes = crate::template::filter_pipes(inner);
292            let mut segment_start = 0;
293            for (k, &pipe) in pipes
294                .iter()
295                .chain(std::iter::once(&inner.len()))
296                .enumerate()
297            {
298                let segment = &inner[segment_start..pipe];
299                if k == 0 {
300                    paint_fragment(doc, overlay, segment, at + segment_start, out);
301                } else {
302                    // `| name args…` — the name is the function the hole's value is passed to.
303                    let trimmed = segment.trim_start();
304                    let name_at = segment_start + (segment.len() - trimmed.len());
305                    let name_len = trimmed
306                        .find(|c: char| !c.is_alphanumeric() && c != '_')
307                        .unwrap_or(trimmed.len());
308                    let modifiers = if prelude_names().contains(&trimmed[..name_len]) {
309                        MOD_DEFAULT_LIBRARY
310                    } else {
311                        0
312                    };
313                    out.push((
314                        Span::new(at + name_at, at + name_at + name_len),
315                        TYPE_FUNCTION,
316                        modifiers,
317                    ));
318                    let args_at = name_at + name_len;
319                    paint_fragment(doc, overlay, &inner[args_at..pipe], at + args_at, out);
320                }
321                if pipe < inner.len() {
322                    out.push((Span::new(at + pipe, at + pipe + 1), TYPE_OPERATOR, 0));
323                }
324                segment_start = pipe + 1;
325            }
326        }
327    }
328    out.push((Span::new(close, close + 1), TYPE_OPERATOR, 0));
329}
330
331/// Paint `text` (at file offset `at`) as code, with every whole-word occurrence of `clauses`
332/// outside a string painted as a keyword — the `in`, `keyed by` and `at index` of a
333/// `{for each …:}` tag, which the expression lexer would read as ordinary words.
334fn paint_with_clause_words(
335    doc: &DocumentState,
336    overlay: &ResolutionOverlay,
337    text: &str,
338    at: usize,
339    clauses: &[&str],
340    out: &mut Vec<(Span, u32, u32)>,
341) {
342    let mut words: Vec<(usize, usize)> = Vec::new();
343    let mut in_string = false;
344    let bytes = text.as_bytes();
345    let mut i = 0;
346    while i < text.len() {
347        if bytes[i] == b'"' {
348            in_string = !in_string;
349        } else if !in_string {
350            let boundary_before =
351                i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
352            if boundary_before {
353                if let Some(word) = clauses.iter().find(|w| {
354                    text[i..].starts_with(**w)
355                        && text[i + w.len()..]
356                            .chars()
357                            .next()
358                            .is_none_or(|c| !c.is_alphanumeric() && c != '_')
359                }) {
360                    words.push((i, i + word.len()));
361                    i += word.len();
362                    continue;
363                }
364            }
365        }
366        i += 1;
367    }
368    let mut cursor = 0;
369    for (start, end) in words {
370        paint_fragment(doc, overlay, &text[cursor..start], at + cursor, out);
371        out.push((Span::new(at + start, at + end), TYPE_KEYWORD, 0));
372        cursor = end;
373    }
374    paint_fragment(doc, overlay, &text[cursor..], at + cursor, out);
375}
376
377/// Split one interpolated-string token into string segments, `{`/`}`
378/// operators, and re-lexed interior code (`{{` escapes stay string).
379fn expand_interpolation(
380    doc: &DocumentState,
381    overlay: &ResolutionOverlay,
382    token: &Token,
383    out: &mut Vec<(Span, u32, u32)>,
384) {
385    let Some(src) = doc.source.get(token.span.start..token.span.end) else {
386        out.push((token.span, TYPE_STRING, 0));
387        return;
388    };
389    let base = token.span.start;
390    let bytes = src.as_bytes();
391    let mut segment_start = 0usize;
392    let mut i = 0usize;
393    while i < bytes.len() {
394        match bytes[i] {
395            b'{' if bytes.get(i + 1) == Some(&b'{') => i += 2,
396            b'{' => {
397                let Some(close_rel) = src[i + 1..].find('}') else {
398                    i += 1;
399                    continue;
400                };
401                let close = i + 1 + close_rel;
402                if i > segment_start {
403                    out.push((Span::new(base + segment_start, base + i), TYPE_STRING, 0));
404                }
405                out.push((Span::new(base + i, base + i + 1), TYPE_OPERATOR, 0));
406                paint_fragment(doc, overlay, &src[i + 1..close], base + i + 1, out);
407                out.push((Span::new(base + close, base + close + 1), TYPE_OPERATOR, 0));
408                segment_start = close + 1;
409                i = close + 1;
410            }
411            _ => i += 1,
412        }
413    }
414    if segment_start < src.len() {
415        out.push((
416            Span::new(base + segment_start, base + src.len()),
417            TYPE_STRING,
418            0,
419        ));
420    }
421}
422
423/// Paint an embedded code fragment — an interpolation interior, a template hole or a tag's
424/// expression — at file offset `offset`: lex it with the REAL lexer, classify by part of speech,
425/// and upgrade identifier-like tokens through resolution — a `{name}` paints exactly like `name`
426/// would outside the string.
427///
428/// A reference the index already resolved at this exact file position (every name a template
429/// mentions is one) is taken as resolved; any other name falls back to its definitions by name.
430fn paint_fragment(
431    doc: &DocumentState,
432    overlay: &ResolutionOverlay,
433    fragment: &str,
434    offset: usize,
435    out: &mut Vec<(Span, u32, u32)>,
436) {
437    let mut interner = logicaffeine_base::Interner::new();
438    let mut lexer = logicaffeine_language::lexer::Lexer::new(fragment, &mut interner);
439    let tokens = lexer.tokenize();
440    for token in tokens {
441        if token.span.end > fragment.len() || token.span.start >= token.span.end {
442            continue;
443        }
444        let (token_type, mut modifiers) = classify_token(&token.kind);
445        let Some(mut token_type) = token_type else {
446            continue;
447        };
448        let resolved = overlay
449            .ref_at
450            .get(&(offset + token.span.start))
451            .map(|&i| &doc.symbol_index.definitions[i])
452            // The same surface-form resolution the overlay applies (verbs and
453            // ambiguous words resolve by what they LOOK like, not their lemma).
454            .or_else(|| {
455                crate::index::resolve_token_name(&token, &interner)
456                    .and_then(|name| doc.symbol_index.definitions_of(name).first().copied())
457            });
458        if let Some(def) = resolved {
459            token_type = semantic_type_for(&def.kind);
460            modifiers = readonly_bit(def);
461        }
462        out.push((
463            Span::new(offset + token.span.start, offset + token.span.end),
464            token_type,
465            modifiers,
466        ));
467    }
468}
469
470/// One protocol-legal (single-line) semantic token in absolute coordinates,
471/// before delta-encoding.
472struct AbsToken {
473    line: u32,
474    character: u32,
475    length: u32,
476    token_type: u32,
477    modifiers: u32,
478}
479
480/// Split a byte span into one `AbsToken` per source line it covers (each a
481/// single line, terminator excluded) and push them into `out`. A single-line
482/// span (the common case) yields exactly one; a multi-line `"""…"""` string
483/// yields one token per line — the protocol forbids a token that crosses a
484/// newline, and an over-long `length` desyncs every token after it.
485fn push_span_pieces(
486    span: &Span,
487    token_type: u32,
488    modifiers: u32,
489    li: &LineIndex,
490    out: &mut Vec<AbsToken>,
491) {
492    let start = li.position(span.start);
493    let end = li.position(span.end);
494    let mut emit = |line: u32, character: u32, length: u32| {
495        if length > 0 {
496            out.push(AbsToken {
497                line,
498                character,
499                length,
500                token_type,
501                modifiers,
502            });
503        }
504    };
505    if start.line == end.line {
506        emit(
507            start.line,
508            start.character,
509            end.character.saturating_sub(start.character),
510        );
511        return;
512    }
513    // First covered line: from the span start to that line's content end.
514    let first_end = li.line_end_offset(start.line as usize);
515    emit(
516        start.line,
517        start.character,
518        li.utf16_length(span.start, first_end),
519    );
520    // Whole intermediate lines.
521    for line in (start.line as usize + 1)..(end.line as usize) {
522        let ls = li.line_start_offset(line);
523        let le = li.line_end_offset(line);
524        emit(line as u32, 0, li.utf16_length(ls, le));
525    }
526    // Last covered line: from its start to the span end.
527    emit(end.line, 0, end.character);
528}
529
530/// Delta-encode absolute tokens (sorted by position) into the LSP wire form.
531/// Sorting + saturating deltas make the encoder total: the wire contract
532/// (monotonic, non-negative deltas) holds even if the input spans are out of
533/// order — one negative delta would otherwise wrap and corrupt the whole stream.
534fn delta_encode(mut abs: Vec<AbsToken>) -> Vec<SemanticToken> {
535    abs.sort_by_key(|t| (t.line, t.character));
536    let mut result = Vec::with_capacity(abs.len());
537    let mut prev_line = 0u32;
538    let mut prev_start = 0u32;
539    for t in abs {
540        let delta_line = t.line.saturating_sub(prev_line);
541        let delta_start = if delta_line == 0 {
542            t.character.saturating_sub(prev_start)
543        } else {
544            t.character
545        };
546        result.push(SemanticToken {
547            delta_line,
548            delta_start,
549            length: t.length,
550            token_type: t.token_type,
551            token_modifiers_bitset: t.modifiers,
552        });
553        prev_line = t.line;
554        prev_start = t.character;
555    }
556    result
557}
558
559/// Delta-encode classified spans into the LSP wire form.
560fn encode_spans(spans: &[(Span, u32, u32)], line_index: &LineIndex) -> Vec<SemanticToken> {
561    let mut abs = Vec::with_capacity(spans.len());
562    for (span, token_type, modifiers) in spans {
563        push_span_pieces(span, *token_type, *modifiers, line_index, &mut abs);
564    }
565    delta_encode(abs)
566}
567
568struct ResolutionOverlay {
569    /// Definition-site span starts → definition index.
570    decl_at: HashMap<usize, usize>,
571    /// Resolved reference span starts → definition index.
572    ref_at: HashMap<usize, usize>,
573    /// Span starts of write targets (Set/Increase/Push-to/…).
574    mutation_at: HashSet<usize>,
575    /// `## Note` / `## Example` block extents.
576    prose: Vec<Span>,
577    /// Every registered type name (primitives included): `Int` in an
578    /// annotation is a TYPE even though no definition site exists for it.
579    type_names: HashSet<String>,
580}
581
582impl ResolutionOverlay {
583    fn build(doc: &DocumentState) -> Self {
584        let index = &doc.symbol_index;
585
586        let mut decl_at = HashMap::new();
587        for (i, def) in index.definitions.iter().enumerate() {
588            if def.span != Span::default() {
589                decl_at.insert(def.span.start, i);
590            }
591        }
592
593        let mut ref_at = HashMap::new();
594        for reference in &index.references {
595            if let Some(def_idx) = reference.definition_idx {
596                ref_at.insert(reference.span.start, def_idx);
597            }
598        }
599
600        let prose = index
601            .block_spans
602            .iter()
603            .filter(|(_, block_type, _)| matches!(block_type, BlockType::Note | BlockType::Example))
604            .map(|(_, _, span)| *span)
605            .collect();
606
607        let type_names = doc
608            .type_registry
609            .iter_types()
610            .map(|(sym, _)| doc.interner.resolve(*sym).to_string())
611            .collect();
612
613        ResolutionOverlay {
614            decl_at,
615            ref_at,
616            mutation_at: find_mutation_targets(&doc.tokens),
617            prose,
618            type_names,
619        }
620    }
621
622    fn classify(&self, token: &Token, doc: &DocumentState) -> (Option<u32>, u32) {
623        // Headers keep their identity even when they open a prose block.
624        if matches!(token.kind, TokenType::BlockHeader { .. }) {
625            return classify_token(&token.kind);
626        }
627
628        // Documentation prose recedes: everything inside Note/Example is comment.
629        let start = token.span.start;
630        if self.prose.iter().any(|p| start > p.start && start < p.end) {
631            return (Some(TYPE_COMMENT), 0);
632        }
633
634        let (mut token_type, mut modifiers) = classify_token(&token.kind);
635
636        if let Some(&def_idx) = self.decl_at.get(&start) {
637            let def = &doc.symbol_index.definitions[def_idx];
638            token_type = Some(semantic_type_for(&def.kind));
639            modifiers = MOD_DECLARATION | readonly_bit(def);
640        } else if let Some(&def_idx) = self.ref_at.get(&start) {
641            let def = &doc.symbol_index.definitions[def_idx];
642            token_type = Some(semantic_type_for(&def.kind));
643            modifiers = readonly_bit(def);
644        } else if is_identifier_like(&token.kind)
645            && self.type_names.contains(doc.interner.resolve(token.lexeme))
646        {
647            // A registered type name with no definition site (primitives:
648            // `Int`, `Text`, …) is a TYPE wherever it appears.
649            token_type = Some(TYPE_TYPE);
650            modifiers &= !MOD_DECLARATION;
651        } else if matches!(doc.interner.resolve(token.lexeme), "mutable" | "mut") {
652            // The mutability marker lexes as an English noun; it IS a
653            // storage modifier (the grammar layer agrees).
654            token_type = Some(TYPE_MODIFIER);
655            modifiers = 0;
656        } else if matches!(token.kind, TokenType::ProperName(_)) {
657            // Base layer marks ProperName as a declaration; without a resolved
658            // definition at this exact span it is a reference, not a declaration.
659            modifiers &= !MOD_DECLARATION;
660        }
661
662        if self.mutation_at.contains(&start) {
663            modifiers |= MOD_MODIFICATION;
664        }
665        if is_identifier_like(&token.kind)
666            && prelude_names().contains(doc.interner.resolve(token.lexeme))
667        {
668            modifiers |= MOD_DEFAULT_LIBRARY;
669        }
670
671        (token_type, modifiers)
672    }
673}
674
675fn readonly_bit(def: &crate::index::Definition) -> u32 {
676    match def.mutable {
677        Some(false) => MOD_READONLY,
678        _ => 0,
679    }
680}
681
682/// The semantic token type an identifier gets once resolution names its kind.
683/// Wildcard-free: a new `DefinitionKind` must decide its color here.
684pub fn semantic_type_for(kind: &DefinitionKind) -> u32 {
685    match kind {
686        DefinitionKind::Variable => TYPE_VARIABLE,
687        DefinitionKind::Function => TYPE_FUNCTION,
688        DefinitionKind::Struct => TYPE_TYPE,
689        DefinitionKind::Enum => TYPE_TYPE,
690        DefinitionKind::Field => TYPE_PROPERTY,
691        DefinitionKind::Parameter => TYPE_PARAMETER,
692        DefinitionKind::Block => TYPE_NAMESPACE,
693        DefinitionKind::Variant => TYPE_ENUM_MEMBER,
694        DefinitionKind::Theorem => TYPE_NAMESPACE,
695        DefinitionKind::Component => TYPE_TYPE,
696        DefinitionKind::Action => TYPE_FUNCTION,
697        DefinitionKind::StateField => TYPE_PROPERTY,
698    }
699}
700
701fn is_identifier_like(kind: &TokenType) -> bool {
702    matches!(
703        kind,
704        TokenType::Identifier
705            | TokenType::ProperName(_)
706            | TokenType::Noun(_)
707            | TokenType::Verb { .. }
708            | TokenType::Adjective(_)
709    )
710}
711
712/// The stdlib prelude vocabulary (`md5`, `uuidV3`, `flush`, …), computed once.
713fn prelude_names() -> &'static HashSet<String> {
714    static NAMES: OnceLock<HashSet<String>> = OnceLock::new();
715    NAMES.get_or_init(|| {
716        logicaffeine_compile::loader::prelude_vocabulary()
717            .into_iter()
718            .collect()
719    })
720}
721
722/// Span starts of tokens that a statement WRITES:
723/// `Set <x> to …` / `Set … at <k> to …`-style targets take the identifier
724/// nearest the write (the last one before `to`, or before `at` when a keyed
725/// write follows), `Increase`/`Decrease <x>`, `Push`/`Add`/`Append … to <x>`,
726/// `Remove`/`Pop … from <x>`.
727pub fn find_mutation_targets(tokens: &[Token]) -> HashSet<usize> {
728    let mut targets = HashSet::new();
729    let mut i = 0;
730    while i < tokens.len() {
731        match &tokens[i].kind {
732            TokenType::Set => {
733                let mut last_ident: Option<usize> = None;
734                let mut before_at: Option<usize> = None;
735                let mut j = i + 1;
736                while j < tokens.len() {
737                    match &tokens[j].kind {
738                        TokenType::To => break,
739                        TokenType::At => before_at = last_ident,
740                        TokenType::Period => break,
741                        kind if is_identifier_like(kind) => last_ident = Some(tokens[j].span.start),
742                        _ => {}
743                    }
744                    j += 1;
745                }
746                if let Some(start) = before_at.or(last_ident) {
747                    targets.insert(start);
748                }
749                i = j;
750            }
751            TokenType::Increase | TokenType::Decrease => {
752                if let Some(next) = tokens[i + 1..].iter().find(|t| is_identifier_like(&t.kind)) {
753                    targets.insert(next.span.start);
754                }
755                i += 1;
756            }
757            TokenType::Push | TokenType::Add | TokenType::Append => {
758                // The collection after `to` is what changes.
759                if let Some(start) = ident_after_keyword(tokens, i, &TokenType::To) {
760                    targets.insert(start);
761                }
762                i += 1;
763            }
764            TokenType::Pop | TokenType::Remove => {
765                if let Some(start) = ident_after_keyword(tokens, i, &TokenType::From) {
766                    targets.insert(start);
767                }
768                i += 1;
769            }
770            _ => i += 1,
771        }
772    }
773    targets
774}
775
776/// The first identifier after `keyword` within the current sentence.
777fn ident_after_keyword(tokens: &[Token], from: usize, keyword: &TokenType) -> Option<usize> {
778    let mut seen_keyword = false;
779    for token in &tokens[from + 1..] {
780        match &token.kind {
781            TokenType::Period => return None,
782            kind if kind == keyword => seen_keyword = true,
783            kind if seen_keyword && is_identifier_like(kind) => return Some(token.span.start),
784            _ => {}
785        }
786    }
787    None
788}
789
790/// Convert a token stream to LSP semantic tokens (delta-encoded) using the
791/// base part-of-speech layer only. [`encode_document_tokens`] is the
792/// resolution-aware entry point.
793pub fn encode_tokens(tokens: &[Token], line_index: &LineIndex) -> Vec<SemanticToken> {
794    encode_with(tokens, line_index, |token| classify_token(&token.kind))
795}
796
797/// Resolution-aware encoding restricted to tokens overlapping a byte range.
798/// The first emitted token stays absolute from the document start, exactly as
799/// the LSP range response requires.
800pub fn encode_document_tokens_in_range(
801    doc: &DocumentState,
802    start_offset: usize,
803    end_offset: usize,
804) -> Vec<SemanticToken> {
805    let overlay = ResolutionOverlay::build(doc);
806    let spans = paint_spans(doc, &overlay, Some((start_offset, end_offset)));
807    encode_spans(&spans, &doc.line_index)
808}
809
810/// The minimal single-splice edit list turning `prev` into `next`.
811///
812/// Deltas are compared raw: a positional shift changes the first token after
813/// the edited region, so prefix/suffix agreement on the encoded stream is
814/// exactly the correct splice boundary. Offsets are in INTEGERS (5 per
815/// token), as the LSP delta contract requires.
816pub fn semantic_token_edits(
817    prev: &[SemanticToken],
818    next: &[SemanticToken],
819) -> Vec<lsp_types::SemanticTokensEdit> {
820    let prefix = prev
821        .iter()
822        .zip(next.iter())
823        .take_while(|(a, b)| a == b)
824        .count();
825    if prefix == prev.len() && prefix == next.len() {
826        return Vec::new();
827    }
828    let max_suffix = prev.len().min(next.len()) - prefix;
829    let suffix = prev
830        .iter()
831        .rev()
832        .zip(next.iter().rev())
833        .take_while(|(a, b)| a == b)
834        .count()
835        .min(max_suffix);
836
837    vec![lsp_types::SemanticTokensEdit {
838        start: (prefix * 5) as u32,
839        delete_count: ((prev.len() - prefix - suffix) * 5) as u32,
840        data: Some(next[prefix..next.len() - suffix].to_vec()),
841    }]
842}
843
844fn encode_with(
845    tokens: &[Token],
846    line_index: &LineIndex,
847    classify: impl Fn(&Token) -> (Option<u32>, u32),
848) -> Vec<SemanticToken> {
849    let mut abs = Vec::with_capacity(tokens.len());
850    for token in tokens {
851        let (token_type, modifiers) = classify(token);
852        let Some(token_type) = token_type else {
853            continue;
854        }; // Skip tokens we don't highlight
855        push_span_pieces(&token.span, token_type, modifiers, line_index, &mut abs);
856    }
857    delta_encode(abs)
858}
859
860/// Map a `TokenType` to a semantic token type index and modifier bitset.
861///
862/// Delegates the CLASS decision to the language crate's
863/// [`logicaffeine_language::token_class`] — the single classification truth
864/// every surface (this server, the terminal REPL) shares — and adds the
865/// legend-level concerns: index mapping and the ProperName declaration bit.
866/// `tests/locks.rs` pins every classification inside the advertised legend.
867pub fn classify_token(kind: &TokenType) -> (Option<u32>, u32) {
868    use logicaffeine_language::token_class::{classify, TokenClass};
869    let class = classify(kind);
870    let index = class.map(|c| match c {
871        TokenClass::Keyword => TYPE_KEYWORD,
872        TokenClass::Type => TYPE_TYPE,
873        TokenClass::Function => TYPE_FUNCTION,
874        TokenClass::Variable => TYPE_VARIABLE,
875        TokenClass::String => TYPE_STRING,
876        TokenClass::Number => TYPE_NUMBER,
877        TokenClass::Operator => TYPE_OPERATOR,
878        TokenClass::Namespace => TYPE_NAMESPACE,
879        TokenClass::Modifier => TYPE_MODIFIER,
880        TokenClass::Property => TYPE_PROPERTY,
881        TokenClass::Comment => TYPE_COMMENT,
882        TokenClass::Parameter => TYPE_PARAMETER,
883        TokenClass::EnumMember => TYPE_ENUM_MEMBER,
884    });
885    let modifiers = if matches!(kind, TokenType::ProperName(_)) {
886        MOD_DECLARATION
887    } else {
888        0
889    };
890    (index, modifiers)
891}
892
893#[cfg(test)]
894#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/semantic_tokens/tests.rs"]
895mod tests;