Skip to main content

logicaffeine_lsp/
document.rs

1use std::collections::HashMap;
2
3use lsp_types::{Diagnostic, Range, Url};
4
5use logicaffeine_base::Interner;
6use logicaffeine_compile::analysis::VarState;
7use logicaffeine_language::{
8    analysis::{PolicyRegistry, TypeRegistry},
9    token::Token,
10};
11
12use crate::index::SymbolIndex;
13use crate::line_index::LineIndex;
14use crate::pipeline;
15
16/// Per-document state: source text, analysis results, and cached diagnostics.
17/// The NAME under the cursor, and where it is written.
18///
19/// ★ ONE RULE, FOUR ASKERS. Go-to-definition, hover, rename and find-references each asked this
20/// question for themselves, and each answered it the same wrong way: find the token at the offset,
21/// read its text. Inside a `View:` that token is the whole `RawBlock`, so all four read the ENTIRE
22/// TEMPLATE as the name and matched nothing — the same bug four times, discoverable four separate
23/// times. An author hovering `{count}` got nothing; renaming it was not even offered.
24///
25/// A recorded REFERENCE wins over the token, and inside a template it is the only thing there is:
26/// the parser noted every name a template mentions with its file span, precisely because that
27/// information exists nowhere else by the time the tokens are all that is left. It is the better
28/// answer outside a template too — a reference is a name the index has already placed, where a
29/// token is only a string that happens to sit under the cursor.
30pub fn name_at(
31    doc: &DocumentState,
32    offset: usize,
33) -> Option<(String, logicaffeine_language::token::Span)> {
34    if let Some(reference) = doc
35        .symbol_index
36        .references
37        .iter()
38        .find(|r| offset >= r.span.start && offset < r.span.end)
39    {
40        return Some((reference.name.clone(), reference.span));
41    }
42    let token = doc
43        .tokens
44        .iter()
45        .find(|t| offset >= t.span.start && offset < t.span.end)?;
46    let text = doc.source.get(token.span.start..token.span.end)?;
47    Some((text.to_string(), token.span))
48}
49
50pub struct DocumentState {
51    pub source: String,
52    pub version: i32,
53    pub line_index: LineIndex,
54
55    // Analysis results (rebuilt on each change)
56    pub tokens: Vec<Token>,
57    pub interner: Interner,
58    pub diagnostics: Vec<Diagnostic>,
59    pub symbol_index: SymbolIndex,
60    pub type_registry: TypeRegistry,
61    pub policy_registry: PolicyRegistry,
62    pub ownership_states: HashMap<String, VarState>,
63}
64
65impl DocumentState {
66    /// Create a new document state from source text.
67    ///
68    /// Pass a `uri` to enable `DiagnosticRelatedInformation` on analysis errors.
69    pub fn new(source: String, version: i32) -> Self {
70        Self::with_uri(source, version, None)
71    }
72
73    /// Create a new document state with a document URI for richer diagnostics.
74    pub fn with_uri(source: String, version: i32, uri: Option<&Url>) -> Self {
75        let line_index = LineIndex::new(&source);
76
77        let analysis = pipeline::analyze(&source);
78        let diagnostics = build_diagnostics(&analysis, &line_index, uri);
79
80        DocumentState {
81            source,
82            version,
83            line_index,
84            tokens: analysis.tokens,
85            interner: analysis.interner,
86            diagnostics,
87            symbol_index: analysis.symbol_index,
88            type_registry: analysis.type_registry,
89            policy_registry: analysis.policy_registry,
90            ownership_states: analysis.ownership_states,
91        }
92    }
93}
94
95/// Apply one LSP content change to a document's text.
96///
97/// A `None` range is a whole-document replacement; a `Some` range is an
98/// incremental edit whose positions are in UTF-16 code units, converted to
99/// byte offsets through a fresh [`LineIndex`] over the current text.
100pub fn apply_content_change(text: &mut String, range: Option<Range>, new_text: &str) {
101    match range {
102        None => {
103            text.clear();
104            text.push_str(new_text);
105        }
106        Some(range) => {
107            let line_index = LineIndex::new(text);
108            let start = line_index.offset(range.start);
109            let end = line_index.offset(range.end);
110            text.replace_range(start..end, new_text);
111        }
112    }
113}
114
115/// Convert every error class one analysis pass produced into LSP diagnostics.
116fn build_diagnostics(
117    analysis: &pipeline::AnalysisResult,
118    line_index: &LineIndex,
119    uri: Option<&Url>,
120) -> Vec<Diagnostic> {
121    let mut diagnostics = crate::diagnostics::convert_errors(
122        &analysis.errors,
123        &analysis.tokens,
124        &analysis.interner,
125        line_index,
126        uri,
127    );
128    diagnostics.extend(crate::diagnostics::convert_analysis_errors(
129        &analysis.escape_errors,
130        &analysis.tokens,
131        &analysis.interner,
132        line_index,
133        uri,
134    ));
135    diagnostics.extend(crate::diagnostics::convert_analysis_errors(
136        &analysis.ownership_errors,
137        &analysis.tokens,
138        &analysis.interner,
139        line_index,
140        uri,
141    ));
142    diagnostics.extend(crate::diagnostics::unused_variable_hints(
143        &analysis.symbol_index,
144        line_index,
145    ));
146    diagnostics.extend(crate::diagnostics::shadowing_warnings(
147        &analysis.symbol_index,
148        line_index,
149        uri,
150    ));
151    diagnostics.extend(crate::diagnostics::unused_function_hints(
152        &analysis.symbol_index,
153        line_index,
154    ));
155    diagnostics.extend(crate::diagnostics::lgx_finding_diagnostics(
156        &analysis.lgx_findings,
157        line_index,
158    ));
159    diagnostics.extend(crate::diagnostics::copy_finding_diagnostics(
160        &analysis.copy_findings,
161        line_index,
162    ));
163    diagnostics.extend(crate::diagnostics::refusal_diagnostics(
164        &analysis.refusals,
165        line_index,
166    ));
167    diagnostics
168}
169
170#[cfg(test)]
171#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/document/tests.rs"]
172mod tests;