Skip to main content

logicaffeine_lsp/
hover.rs

1use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Position, Range};
2
3use logicaffeine_compile::analysis::VarState;
4use logicaffeine_language::token::{BlockType, TokenType};
5
6use crate::document::DocumentState;
7use crate::workspace::WorkspaceView;
8
9/// Handle hover request.
10///
11/// Shows type info, signatures, and keyword documentation depending on
12/// what's under the cursor.
13pub fn hover(doc: &DocumentState, position: Position) -> Option<Hover> {
14    let offset = doc.line_index.offset(position);
15
16    // ★ A NAME INSIDE A TEMPLATE IS NOT A TOKEN. The match below dispatches on the token's KIND,
17    // and a `View:` body is one `RawBlock` — so `{count}` never reached the identifier arm and
18    // hovering it said nothing at all. The reference the parser recorded is the only place that
19    // name exists by now, and it already points at the definition, which is exactly what the
20    // identifier arm goes on to look up.
21    //
22    // ★ ONLY WHERE THERE IS NO NAME TOKEN, which means only inside a raw block. Taking this path
23    // whenever a reference covered the cursor ALSO took it for ordinary code, and skipped the
24    // enrichment below — the ownership state, the diagnostics on the token — so hovering a plain
25    // `x` stopped saying whether it had been given away. A narrower gate keeps the two worlds
26    // apart: outside a template the token path was always right and still is.
27    let inside_raw_block = doc
28        .tokens
29        .iter()
30        .find(|t| offset >= t.span.start && offset < t.span.end)
31        .is_some_and(|t| matches!(t.kind, TokenType::RawBlock { .. }));
32    if let Some(reference) = doc
33        .symbol_index
34        .references
35        .iter()
36        .find(|r| inside_raw_block && offset >= r.span.start && offset < r.span.end)
37    {
38        if let Some(def) = reference
39            .definition_idx
40            .and_then(|i| doc.symbol_index.definitions.get(i))
41        {
42            if let Some(md) = definition_hover(def) {
43                return Some(Hover {
44                    contents: HoverContents::Markup(MarkupContent {
45                        kind: MarkupKind::Markdown,
46                        value: md,
47                    }),
48                    range: Some(Range {
49                        start: doc.line_index.position(reference.span.start),
50                        end: doc.line_index.position(reference.span.end),
51                    }),
52                });
53            }
54        }
55    }
56
57    // Find the token at the cursor position
58    let at = doc
59        .tokens
60        .iter()
61        .position(|t| offset >= t.span.start && offset < t.span.end)?;
62    let token = &doc.tokens[at];
63
64    // A comparison written in English (`is less than`, `at least`, `is equal to`) is several
65    // tokens that mean one thing; the hover covers the phrase and teaches the comparison, the
66    // same lesson `<`, `>=` or `==` would.
67    if let Some((lesson, span)) = logicaffeine_language::teach::doc_for_phrase(&doc.source, &doc.tokens, at) {
68        return Some(Hover {
69            contents: HoverContents::Markup(MarkupContent {
70                kind: MarkupKind::Markdown,
71                value: crate::teach_md::keyword_hover_md(lesson),
72            }),
73            range: Some(Range {
74                start: doc.line_index.position(span.start),
75                end: doc.line_index.position(span.end),
76            }),
77        });
78    }
79
80    let text = doc.source.get(token.span.start..token.span.end)?;
81
82    let content = match &token.kind {
83        // Block headers → the shared lesson table (total over BlockType),
84        // plus the socratic proof-strategy hint on theorems.
85        TokenType::BlockHeader { block_type } => {
86            let lesson = logicaffeine_language::teach::doc_for_block(block_type);
87            let mut result = crate::teach_md::block_hover_md(lesson);
88
89            if *block_type == BlockType::Theorem {
90                let hint = proof_strategy_hint_from_source(&doc.source, token.span.start);
91                result.push_str(&format!("\n\n---\n\n**Proof Strategy**: {}", hint));
92            }
93
94            Some(result)
95        }
96
97        // Taught keywords → the shared lesson table (one brain for hover,
98        // completion docs, and the REPL's :explain).
99        kind if logicaffeine_language::teach::doc_for(kind).is_some() => {
100            logicaffeine_language::teach::doc_for(kind).map(crate::teach_md::keyword_hover_md)
101        }
102
103        // Identifiers, proper names, adjectives, nouns → look up definition
104        // info first (detail + literate doc), then the stdlib registry.
105        TokenType::Identifier
106        | TokenType::ProperName(_)
107        | TokenType::Adjective(_)
108        | TokenType::Noun(_) => {
109            let defs = doc.symbol_index.definitions_of(text);
110            if let Some(def) = defs.first() {
111                definition_hover(def)
112            } else if let Some(binding) = let_binding(doc, text) {
113                Some(binding)
114            } else if let Some(lesson) = logicaffeine_language::teach::doc_for_primitive(text) {
115                // `Int`, `Text`, `Seq`: the type's lesson (DAT-106).
116                Some(crate::teach_md::keyword_hover_md(lesson))
117            } else if let Some(entry) = crate::stdlib_docs::stdlib_doc(text) {
118                Some(crate::stdlib_docs::hover_md(text, entry))
119            } else {
120                // Fall back to token-specific info
121                match &token.kind {
122                    TokenType::Noun(sym) => {
123                        Some(format!("**Noun**: {}", doc.interner.resolve(*sym)))
124                    }
125                    TokenType::Adjective(sym) => {
126                        Some(format!("**Adjective**: {}", doc.interner.resolve(*sym)))
127                    }
128                    _ => None,
129                }
130            }
131        }
132
133        // Verbs → a defined function first (English-word function names lex
134        // as verbs), then the stdlib registry, then the verb-class display.
135        TokenType::Verb {
136            lemma,
137            time,
138            aspect,
139            class,
140        } => {
141            let defs = doc.symbol_index.definitions_of(text);
142            if let Some(def) = defs.first() {
143                definition_hover(def)
144            } else if let Some(binding) = let_binding(doc, text) {
145                Some(binding)
146            } else if let Some(entry) = crate::stdlib_docs::stdlib_doc(text) {
147                Some(crate::stdlib_docs::hover_md(text, entry))
148            } else {
149                let lemma_str = doc.interner.resolve(*lemma);
150                Some(format!(
151                    "**Verb**: {} ({}, {}, {})",
152                    lemma_str,
153                    verb_class_display(class),
154                    time_display(time),
155                    aspect_display(aspect),
156                ))
157            }
158        }
159
160        // Type names → the primitive's lesson, else the registry
161        _ => {
162            if let Some(lesson) = logicaffeine_language::teach::doc_for_primitive(text) {
163                Some(crate::teach_md::keyword_hover_md(lesson))
164            } else if let Some(sym) = doc.interner.lookup(text) {
165                if let Some(typedef) = doc.type_registry.get(sym) {
166                    Some(format_typedef(text, typedef, &doc.interner))
167                } else {
168                    None
169                }
170            } else {
171                None
172            }
173        }
174    };
175
176    let token_range = Range {
177        start: doc.line_index.position(token.span.start),
178        end: doc.line_index.position(token.span.end),
179    };
180
181    // Enrich variable-like tokens with their ownership state. A token's problems are the
182    // editor's to show, in its own section of the hover — repeating them here says each twice.
183    let content = content.map(|mut c| {
184        if matches!(
185            &token.kind,
186            TokenType::Identifier
187                | TokenType::ProperName(_)
188                | TokenType::Adjective(_)
189                | TokenType::Noun(_)
190        ) {
191            // Ownership state
192            if let Some(state) = doc.ownership_states.get(text) {
193                let state_str = match state {
194                    VarState::Owned => "Owned",
195                    VarState::Moved => "Moved",
196                    VarState::MaybeMoved(_) => "Maybe Moved",
197                    VarState::Borrowed => "Borrowed",
198                };
199                c.push_str(&format!("\n\n**Ownership**: {}", state_str));
200                match state {
201                    VarState::Moved => {
202                        c.push_str(
203                            "\n\n*This variable has been given away and can no longer be used.*",
204                        );
205                    }
206                    VarState::MaybeMoved(given_in) => {
207                        c.push_str(&format!(
208                            "\n\n*This variable might have been given away in {given_in}.*"
209                        ));
210                    }
211                    _ => {}
212                }
213            }
214        }
215        c
216    });
217
218    content.map(|c| Hover {
219        contents: HoverContents::Markup(MarkupContent {
220            kind: MarkupKind::Markdown,
221            value: c,
222        }),
223        range: Some(token_range),
224    })
225}
226
227fn verb_class_display(class: &logicaffeine_language::lexicon::VerbClass) -> &'static str {
228    match class {
229        logicaffeine_language::lexicon::VerbClass::State => "state",
230        logicaffeine_language::lexicon::VerbClass::Activity => "activity",
231        logicaffeine_language::lexicon::VerbClass::Accomplishment => "accomplishment",
232        logicaffeine_language::lexicon::VerbClass::Achievement => "achievement",
233        logicaffeine_language::lexicon::VerbClass::Semelfactive => "semelfactive",
234    }
235}
236
237fn time_display(time: &logicaffeine_language::lexicon::Time) -> &'static str {
238    match time {
239        logicaffeine_language::lexicon::Time::Past => "past",
240        logicaffeine_language::lexicon::Time::Present => "present",
241        logicaffeine_language::lexicon::Time::Future => "future",
242        logicaffeine_language::lexicon::Time::None => "none",
243    }
244}
245
246fn aspect_display(aspect: &logicaffeine_language::lexicon::Aspect) -> &'static str {
247    match aspect {
248        logicaffeine_language::lexicon::Aspect::Simple => "simple",
249        logicaffeine_language::lexicon::Aspect::Progressive => "progressive",
250        logicaffeine_language::lexicon::Aspect::Perfect => "perfect",
251    }
252}
253
254/// A definition's hover: its signature detail plus its literate `## Note`
255/// documentation, when either exists.
256/// The `Let` that binds `name`, read from the tokens alone — `Let mut tries` for
257/// `Let mutable tries be 0.` A program that does not parse (an exercise with a `???` hole) has
258/// no symbol index to find its variables in, yet its `Let` lines still say which words they
259/// are, whatever those words would lex as on their own.
260fn let_binding(doc: &DocumentState, name: &str) -> Option<String> {
261    let text = |i: usize| {
262        doc.tokens
263            .get(i)
264            .and_then(|t| doc.source.get(t.span.start..t.span.end))
265            .unwrap_or("")
266    };
267    (0..doc.tokens.len()).find_map(|i| {
268        if !matches!(doc.tokens[i].kind, TokenType::Let) {
269            return None;
270        }
271        let mutable = matches!(doc.tokens.get(i + 1).map(|t| &t.kind), Some(TokenType::Mut))
272            || text(i + 1).eq_ignore_ascii_case("mutable")
273            || text(i + 1).eq_ignore_ascii_case("mut");
274        let bound = if mutable { i + 2 } else { i + 1 };
275        (text(bound) == name).then(|| format!("Let {}{name}", if mutable { "mut " } else { "" }))
276    })
277}
278
279fn definition_hover(def: &crate::index::Definition) -> Option<String> {
280    match (&def.detail, &def.doc) {
281        (Some(detail), Some(doc)) => Some(format!("{detail}\n\n{doc}")),
282        (Some(detail), None) => Some(detail.clone()),
283        (None, Some(doc)) => Some(doc.clone()),
284        (None, None) => None,
285    }
286}
287
288fn format_typedef(
289    name: &str,
290    typedef: &logicaffeine_language::analysis::TypeDef,
291    interner: &logicaffeine_base::Interner,
292) -> String {
293    match typedef {
294        logicaffeine_language::analysis::TypeDef::Struct { fields, .. } => {
295            let mut s = format!("**struct** {}\n\n", name);
296            for field in fields {
297                let field_name = interner.resolve(field.name);
298                let field_type = format_field_type(&field.ty, interner);
299                s.push_str(&format!("- `{}`: {}\n", field_name, field_type));
300            }
301            s
302        }
303        logicaffeine_language::analysis::TypeDef::Enum { variants, .. } => {
304            let mut s = format!("**enum** {}\n\n", name);
305            for variant in variants {
306                let variant_name = interner.resolve(variant.name);
307                if variant.fields.is_empty() {
308                    s.push_str(&format!("- `{}`\n", variant_name));
309                } else {
310                    let fields: Vec<String> = variant
311                        .fields
312                        .iter()
313                        .map(|f| {
314                            format!(
315                                "{}: {}",
316                                interner.resolve(f.name),
317                                format_field_type(&f.ty, interner)
318                            )
319                        })
320                        .collect();
321                    s.push_str(&format!(
322                        "- `{}` with {}\n",
323                        variant_name,
324                        fields.join(", ")
325                    ));
326                }
327            }
328            s
329        }
330        logicaffeine_language::analysis::TypeDef::Primitive => {
331            format!("**primitive** {}", name)
332        }
333        logicaffeine_language::analysis::TypeDef::Generic { param_count } => {
334            format!(
335                "**generic** {} (takes {} type parameter(s))",
336                name, param_count
337            )
338        }
339        logicaffeine_language::analysis::TypeDef::Alias { target } => {
340            format!("**alias** {} = {}", name, interner.resolve(*target))
341        }
342    }
343}
344
345/// "Defined in module `util.lg`" for a cross-file name — a name NOT defined in
346/// this document and NOT a stdlib name, but publicly exported by some project
347/// module. Returns `None` for local/stdlib names (they have their own hover).
348pub fn module_attribution(
349    doc: &DocumentState,
350    position: Position,
351    ws: &dyn WorkspaceView,
352) -> Option<String> {
353    let offset = doc.line_index.offset(position);
354    let token = doc
355        .tokens
356        .iter()
357        .find(|t| offset >= t.span.start && offset < t.span.end)?;
358    let text = doc.source.get(token.span.start..token.span.end)?;
359
360    if !doc.symbol_index.definitions_of(text).is_empty() {
361        return None;
362    }
363    if crate::stdlib_docs::stdlib_doc(text).is_some() {
364        return None;
365    }
366    let files: Vec<String> = ws
367        .module_exporting(text)
368        .iter()
369        .filter_map(|e| crate::workspace::url_path(&e.module_url))
370        .filter_map(|p| {
371            p.file_name()
372                .and_then(|s| s.to_str())
373                .map(|s| format!("`{s}`"))
374        })
375        .collect();
376    if files.is_empty() {
377        return None;
378    }
379    Some(format!("*Defined in module {}*", files.join(", ")))
380}
381
382/// [`hover`] enriched with cross-file module attribution: when the name under the
383/// cursor is defined in another project module, append "Defined in module X".
384pub fn hover_with_workspace(
385    doc: &DocumentState,
386    position: Position,
387    ws: &dyn WorkspaceView,
388) -> Option<Hover> {
389    let base = hover(doc, position);
390    let attribution = module_attribution(doc, position, ws);
391    match (base, attribution) {
392        (Some(mut h), Some(attr)) => {
393            if let HoverContents::Markup(mc) = &mut h.contents {
394                mc.value.push_str("\n\n---\n\n");
395                mc.value.push_str(&attr);
396            }
397            Some(h)
398        }
399        (Some(h), None) => Some(h),
400        (None, Some(attr)) => Some(Hover {
401            contents: HoverContents::Markup(MarkupContent {
402                kind: MarkupKind::Markdown,
403                value: attr,
404            }),
405            range: None,
406        }),
407        (None, None) => None,
408    }
409}
410
411#[cfg(test)]
412#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/hover/tests.rs"]
413mod tests;
414
415/// Analyze the source text of a Theorem block to suggest a proof strategy.
416///
417/// Scans the block's body text for structural keywords (quantifiers, connectives)
418/// and returns a Socratic hint guiding the user toward the right tactic.
419fn proof_strategy_hint_from_source(source: &str, block_start: usize) -> String {
420    let block_text = &source[block_start..];
421    let block_end = block_text.find("\n## ").unwrap_or(block_text.len());
422    let block_body = &block_text[..block_end].to_lowercase();
423
424    if block_body.contains("for all") || block_body.contains("every") || block_body.contains("all ")
425    {
426        return "Your theorem involves a universal claim. To prove it, consider an arbitrary element and show the property holds.".to_string();
427    }
428    if block_body.contains("there exists") || block_body.contains("some ") {
429        return "Your theorem involves an existential claim. You need to find a specific witness that satisfies the property.".to_string();
430    }
431    if block_body.contains(" implies ") || block_body.contains("if ") {
432        return "Your theorem is an implication. Try assuming the antecedent and proving the consequent.".to_string();
433    }
434    if block_body.contains(" and ") {
435        return "Your theorem is a conjunction. You need to prove both parts separately."
436            .to_string();
437    }
438    if block_body.contains(" or ") {
439        return "Your theorem is a disjunction. You only need to prove one of the alternatives."
440            .to_string();
441    }
442    if block_body.contains("not ") || block_body.contains("no ") {
443        return "Your theorem involves negation. Try assuming the positive form and deriving a contradiction.".to_string();
444    }
445    if block_body.contains("equals") || block_body.contains(" = ") {
446        return "Your theorem is an equality. Can you rewrite one side to match the other, or use reflexivity?".to_string();
447    }
448
449    "What logical structure does your theorem have? Try breaking it down into simpler parts."
450        .to_string()
451}
452
453pub fn format_field_type(
454    ty: &logicaffeine_language::analysis::FieldType,
455    interner: &logicaffeine_base::Interner,
456) -> String {
457    match ty {
458        logicaffeine_language::analysis::FieldType::Primitive(sym) => {
459            interner.resolve(*sym).to_string()
460        }
461        logicaffeine_language::analysis::FieldType::Named(sym) => {
462            interner.resolve(*sym).to_string()
463        }
464        logicaffeine_language::analysis::FieldType::Generic { base, params } => {
465            let base_name = interner.resolve(*base);
466            let param_strs: Vec<String> = params
467                .iter()
468                .map(|p| format_field_type(p, interner))
469                .collect();
470            format!("{} of {}", base_name, param_strs.join(", "))
471        }
472        logicaffeine_language::analysis::FieldType::TypeParam(sym) => {
473            interner.resolve(*sym).to_string()
474        }
475        logicaffeine_language::analysis::FieldType::Tuple(items) => {
476            let parts: Vec<String> = items
477                .iter()
478                .map(|t| format_field_type(t, interner))
479                .collect();
480            format!("({})", parts.join(", "))
481        }
482        logicaffeine_language::analysis::FieldType::Record(fields) => {
483            let parts: Vec<String> = fields
484                .iter()
485                .map(|(n, t)| {
486                    format!(
487                        "{}: {}",
488                        interner.resolve(*n),
489                        format_field_type(t, interner)
490                    )
491                })
492                .collect();
493            format!("({})", parts.join(", "))
494        }
495    }
496}