Skip to main content

logicaffeine_lsp/
completion.rs

1use lsp_types::{
2    CompletionItem, CompletionItemKind, CompletionItemTag, CompletionResponse, Position, Url,
3};
4
5use logicaffeine_compile::analysis::VarState;
6use logicaffeine_language::token::{RawKind, TokenType};
7
8use crate::document::DocumentState;
9use crate::index::DefinitionKind;
10use crate::workspace::WorkspaceView;
11
12/// Handle completion request.
13///
14/// Provides context-aware completions based on the preceding tokens.
15pub fn completions(doc: &DocumentState, position: Position) -> Option<CompletionResponse> {
16    let offset = doc.line_index.offset(position);
17
18    // The preceding token sets the context. NONE (empty document, or the cursor
19    // before the first token) is not a dead end — it gets identifiers, keywords, and (below)
20    // stdlib names alike, so a fresh file still completes.
21    let prev_token = doc.tokens.iter().rev().find(|t| t.span.end <= offset);
22
23    let mut items = Vec::new();
24
25    // ★ A TEMPLATE HOLE HAS ITS OWN, SMALL VOCABULARY — and it used to be handed the whole stdlib.
26    //
27    // Completion dispatches on the PREVIOUS TOKEN, and a `View:` body is one `RawBlock`, so a
28    // cursor inside a template fell through to the general fallback: every function the prelude
29    // declares, about a thousand of them. Typing `{co` offered `cConj`, `cCosh`, `commonRunLen`
30    // and never `count`. **Useless suggestions are not a neutral default** — they bury the two
31    // names that were wanted, and an author who is shown a thousand irrelevant entries once stops
32    // reading the list at all.
33    //
34    // What a hole can hold is knowable: this page's state, props and actions, the components it
35    // can place, and the template tags. That is a few dozen entries, all of them plausible.
36    //
37    // A `Style:` body is CSS, and its vocabulary is knowable too: a scoped stylesheet matches
38    // only what its own component renders.
39    match raw_section_at(doc, offset) {
40        Some(RawKind::View | RawKind::Head) => {
41            add_template_completions(doc, &mut items);
42            return Some(CompletionResponse::Array(items));
43        }
44        Some(RawKind::Style) => {
45            add_style_completions(doc, offset, &mut items);
46            return Some(CompletionResponse::Array(items));
47        }
48        None => {}
49    }
50
51    match prev_token.map(|t| &t.kind) {
52        // After period, at start of line, or before the first token → statement keywords. A
53        // token-less cursor must not depend on `add_identifier_completions` coming back empty to
54        // reach this: a compiler-registered built-in type (`HttpError`, `File`) can populate
55        // `items` even for an otherwise-empty document, and a statement start still needs its
56        // keywords regardless of whatever else is offered alongside them.
57        None | Some(TokenType::Period | TokenType::Indent | TokenType::Newline) => {
58            add_statement_keywords(&mut items);
59            if prev_token.is_none() {
60                add_identifier_completions(doc, &mut items);
61            }
62        }
63
64        // After "Let x be" or similar → expression completions
65        Some(TokenType::Be) => {
66            add_expression_completions(doc, &mut items);
67        }
68
69        // After ":" → type completions
70        Some(TokenType::Colon) => {
71            add_type_completions(doc, &mut items);
72        }
73
74        // After possessive ('s) → field completions
75        Some(TokenType::Possessive) => {
76            // Look back to find the object before possessive
77            add_field_completions(doc, offset, &mut items);
78        }
79
80        // After "Inspect x:" → variant completions
81        Some(TokenType::Inspect) => {
82            add_variant_completions(doc, &mut items);
83        }
84
85        // Default → variables and functions in scope
86        _ => {
87            add_identifier_completions(doc, &mut items);
88        }
89    }
90
91    if items.is_empty() {
92        // Fallback: always offer identifiers + keywords
93        add_identifier_completions(doc, &mut items);
94        add_statement_keywords(&mut items);
95    }
96
97    // Stdlib prelude names ride along in every context, after the locals —
98    // additive, so they can never displace the context-specific items above.
99    add_stdlib_completions(doc, &mut items);
100
101    Some(CompletionResponse::Array(items))
102}
103
104/// [`completions`] enriched with cross-module knowledge from the workspace: after
105/// `Import `, the available module NAMES; in code, the public SYMBOLS of the
106/// modules this file imports (each labelled `from <Module>`). Additive — never
107/// displaces the local + stdlib completions.
108pub fn completions_with_workspace(
109    doc: &DocumentState,
110    position: Position,
111    ws: &dyn WorkspaceView,
112    uri: &Url,
113) -> Option<CompletionResponse> {
114    let mut items = match completions(doc, position) {
115        Some(CompletionResponse::Array(v)) => v,
116        Some(CompletionResponse::List(list)) => list.items,
117        None => Vec::new(),
118    };
119
120    let offset = doc.line_index.offset(position);
121    // A stylesheet names selectors, never code, so no module's symbols belong in it.
122    if raw_section_at(doc, offset) == Some(RawKind::Style) {
123        return Some(CompletionResponse::Array(items));
124    }
125    let line_start = doc.source[..offset.min(doc.source.len())]
126        .rfind('\n')
127        .map(|i| i + 1)
128        .unwrap_or(0);
129    let line_prefix = &doc.source[line_start..offset.min(doc.source.len())];
130
131    if line_prefix.trim_start().starts_with("Import") {
132        // Import-statement context → complete module names not already on the line.
133        for (alias, _url) in ws.module_names() {
134            if line_prefix.contains(&alias) {
135                continue;
136            }
137            items.push(CompletionItem {
138                label: alias,
139                kind: Some(CompletionItemKind::MODULE),
140                ..Default::default()
141            });
142        }
143    } else {
144        // Code context → exactly the names this file's imports bring into scope
145        // (a selective import narrows to its selected names, not the whole module).
146        for (label, alias) in ws.imported_symbols(uri) {
147            items.push(CompletionItem {
148                label,
149                kind: Some(CompletionItemKind::FUNCTION),
150                detail: Some(format!("from {alias}")),
151                ..Default::default()
152            });
153        }
154    }
155
156    Some(CompletionResponse::Array(items))
157}
158
159fn add_statement_keywords(items: &mut Vec<CompletionItem>) {
160    // Snippet skeletons are editing mechanics and live here; the teaching
161    // text (detail + documentation) comes from the shared lesson table, so
162    // completion, hover, and the REPL always say the same thing.
163    let keywords = [
164        (TokenType::Let, "Let ${1:name} be ${2:value}."),
165        (TokenType::Set, "Set ${1:name} to ${2:value}."),
166        (TokenType::If, "If ${1:condition}:\n    ${2:body}"),
167        (TokenType::While, "While ${1:condition}:\n    ${2:body}"),
168        (
169            TokenType::Repeat,
170            "Repeat for ${1:item} in ${2:collection}:\n    ${3:body}",
171        ),
172        (TokenType::Return, "Return ${1:value}."),
173        (TokenType::Show, "Show ${1:value}."),
174        (TokenType::Give, "Give ${1:value} to ${2:target}."),
175        (TokenType::Push, "Push ${1:value} to ${2:list}."),
176        (TokenType::Call, "Call ${1:function} with ${2:args}."),
177        (
178            TokenType::Inspect,
179            "Inspect ${1:value}:\n    ${2:pattern}:\n        ${3:body}",
180        ),
181    ];
182
183    for (kind, snippet) in keywords {
184        let lesson = logicaffeine_language::teach::doc_for(&kind)
185            .expect("every statement-keyword completion is taught");
186        items.push(CompletionItem {
187            label: lesson.name.to_string(),
188            kind: Some(CompletionItemKind::KEYWORD),
189            detail: Some(lesson.what.to_string()),
190            documentation: Some(crate::teach_md::completion_docs(lesson)),
191            insert_text: Some(snippet.to_string()),
192            insert_text_format: Some(lsp_types::InsertTextFormat::SNIPPET),
193            ..Default::default()
194        });
195    }
196}
197
198/// The raw section (`View:`, `Style:`, `Head:` body — one `RawBlock` token to the lexer) the
199/// cursor is inside, if any.
200fn raw_section_at(doc: &DocumentState, offset: usize) -> Option<RawKind> {
201    doc.tokens.iter().find_map(|t| match t.kind {
202        TokenType::RawBlock { kind, .. } if offset > t.span.start && offset <= t.span.end => {
203            Some(kind)
204        }
205        _ => None,
206    })
207}
208
209/// What a scoped stylesheet can match: the element names, classes (static `class="…"` words and
210/// `class:name` toggles) and ids the `View:` of the SAME `##` block renders, plus `:global(…)` —
211/// the way out of the scope.
212fn add_style_completions(doc: &DocumentState, offset: usize, items: &mut Vec<CompletionItem>) {
213    use logicaffeine_language::lgx::html::{self, AttrPart, AttrValue, HtmlToken};
214    use std::collections::BTreeSet;
215
216    // The `##` block holding the cursor: from the header before it to the header after it.
217    let block_start = doc
218        .tokens
219        .iter()
220        .filter(|t| matches!(t.kind, TokenType::BlockHeader { .. }) && t.span.start <= offset)
221        .map(|t| t.span.start)
222        .last()
223        .unwrap_or(0);
224    let block_end = doc
225        .tokens
226        .iter()
227        .find(|t| matches!(t.kind, TokenType::BlockHeader { .. }) && t.span.start > offset)
228        .map_or(doc.source.len(), |t| t.span.start);
229
230    let mut tags = BTreeSet::new();
231    let mut classes = BTreeSet::new();
232    let mut ids = BTreeSet::new();
233    let views = doc.tokens.iter().filter(|t| {
234        matches!(
235            t.kind,
236            TokenType::RawBlock {
237                kind: RawKind::View,
238                ..
239            }
240        ) && t.span.start >= block_start
241            && t.span.end <= block_end
242    });
243    for view in views {
244        let Some(body) = doc.source.get(view.span.start..view.span.end) else {
245            continue;
246        };
247        let Ok(tokens) = html::tokenize(body) else {
248            continue;
249        };
250        for token in tokens {
251            let HtmlToken::StartTag { name, attrs, .. } = token else {
252                continue;
253            };
254            if !html::is_component_name(&name) {
255                tags.insert(name.to_ascii_lowercase());
256            }
257            for attr in attrs {
258                if let Some(toggled) = attr.name.strip_prefix("class:") {
259                    classes.insert(toggled.to_string());
260                    continue;
261                }
262                let words = match &attr.value {
263                    Some(AttrValue::Static(v)) => vec![v.clone()],
264                    // A word touching a `{…}` is only part of a class name; the whole words of the
265                    // text between holes are real ones.
266                    Some(AttrValue::Parts(parts)) => parts
267                        .iter()
268                        .enumerate()
269                        .filter_map(|(i, p)| match p {
270                            AttrPart::Text(t) => {
271                                let mut words: Vec<&str> = t.split_whitespace().collect();
272                                if i > 0 && !t.starts_with(char::is_whitespace) && !words.is_empty()
273                                {
274                                    words.remove(0);
275                                }
276                                if i + 1 < parts.len() && !t.ends_with(char::is_whitespace) {
277                                    words.pop();
278                                }
279                                Some(words.join(" "))
280                            }
281                            AttrPart::Brace { .. } => None,
282                        })
283                        .collect(),
284                    None => Vec::new(),
285                };
286                let target = match attr.name.as_str() {
287                    "class" => &mut classes,
288                    "id" => &mut ids,
289                    _ => continue,
290                };
291                for w in words.iter().flat_map(|v| v.split_whitespace()) {
292                    target.insert(w.to_string());
293                }
294            }
295        }
296    }
297
298    let mut push = |label: String, kind: CompletionItemKind, detail: &str| {
299        items.push(CompletionItem {
300            label,
301            kind: Some(kind),
302            detail: Some(detail.to_string()),
303            ..Default::default()
304        });
305    };
306    for c in classes {
307        push(
308            format!(".{c}"),
309            CompletionItemKind::CLASS,
310            "a class this component's view renders",
311        );
312    }
313    for id in ids {
314        push(
315            format!("#{id}"),
316            CompletionItemKind::REFERENCE,
317            "an id this component's view renders",
318        );
319    }
320    for t in tags {
321        push(
322            t,
323            CompletionItemKind::KEYWORD,
324            "an element this component's view renders",
325        );
326    }
327    items.push(CompletionItem {
328        label: ":global(…)".to_string(),
329        kind: Some(CompletionItemKind::SNIPPET),
330        detail: Some("match outside this component — the one way out of the scope".to_string()),
331        insert_text: Some(":global(${1:selector})".to_string()),
332        insert_text_format: Some(lsp_types::InsertTextFormat::SNIPPET),
333        ..Default::default()
334    });
335}
336
337/// What a template hole can name: the page's own vocabulary, and the tags.
338fn add_template_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
339    for def in &doc.symbol_index.definitions {
340        let kind = match def.kind {
341            DefinitionKind::StateField => CompletionItemKind::PROPERTY,
342            DefinitionKind::Action => CompletionItemKind::METHOD,
343            DefinitionKind::Component => CompletionItemKind::CLASS,
344            _ => continue,
345        };
346        items.push(CompletionItem {
347            label: def.name.clone(),
348            kind: Some(kind),
349            detail: def.detail.clone(),
350            ..Default::default()
351        });
352    }
353    // The tags, from the editor's one tag table (`crate::template::TAGS`), which is held against
354    // the template parser's own tag words.
355    for (label, detail) in crate::template::TAGS.iter().copied() {
356        items.push(CompletionItem {
357            label: label.to_string(),
358            kind: Some(CompletionItemKind::KEYWORD),
359            detail: Some(detail.to_string()),
360            ..Default::default()
361        });
362    }
363}
364
365fn add_expression_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
366    // Add variables in scope
367    add_identifier_completions(doc, items);
368
369    // Add "a new Type" constructor
370    for (name, typedef) in doc.type_registry.iter_types() {
371        let type_name = doc.interner.resolve(*name);
372        if matches!(
373            typedef,
374            logicaffeine_language::analysis::TypeDef::Struct { .. }
375        ) {
376            items.push(CompletionItem {
377                label: format!("a new {}", type_name),
378                kind: Some(CompletionItemKind::CONSTRUCTOR),
379                detail: Some(format!("Create a new {} instance", type_name)),
380                ..Default::default()
381            });
382        }
383    }
384}
385
386fn add_type_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
387    // Primitive types — each teaches from the shared lesson table.
388    let primitives = [
389        "Int", "Nat", "Text", "Bool", "Float", "Unit", "Char", "Byte",
390    ];
391    for prim in primitives {
392        let lesson = logicaffeine_language::teach::doc_for_primitive(prim)
393            .expect("every offered primitive is taught");
394        items.push(CompletionItem {
395            label: prim.to_string(),
396            kind: Some(CompletionItemKind::TYPE_PARAMETER),
397            detail: Some(lesson.what.to_string()),
398            documentation: Some(crate::teach_md::completion_docs(lesson)),
399            ..Default::default()
400        });
401    }
402
403    // Generic types — same table.
404    let generics = ["List", "Seq", "Map", "Set", "Option", "Result"];
405    for gen in generics {
406        let lesson = logicaffeine_language::teach::doc_for_primitive(gen)
407            .expect("every offered generic is taught");
408        items.push(CompletionItem {
409            label: gen.to_string(),
410            kind: Some(CompletionItemKind::CLASS),
411            detail: Some(lesson.what.to_string()),
412            documentation: Some(crate::teach_md::completion_docs(lesson)),
413            ..Default::default()
414        });
415    }
416
417    // User-defined types from registry
418    for (name, _typedef) in doc.type_registry.iter_types() {
419        let type_name = doc.interner.resolve(*name);
420        items.push(CompletionItem {
421            label: type_name.to_string(),
422            kind: Some(CompletionItemKind::CLASS),
423            detail: Some("User-defined type".to_string()),
424            ..Default::default()
425        });
426    }
427}
428
429fn add_field_completions(doc: &DocumentState, offset: usize, items: &mut Vec<CompletionItem>) {
430    // Try to resolve the type of the object before the possessive
431    if let Some(type_name) = resolve_possessive_type(doc, offset) {
432        // Only offer fields from the resolved type
433        for (name, typedef) in doc.type_registry.iter_types() {
434            let tname = doc.interner.resolve(*name);
435            if tname != type_name {
436                continue;
437            }
438            if let logicaffeine_language::analysis::TypeDef::Struct { fields, .. } = typedef {
439                for field in fields {
440                    let field_name = doc.interner.resolve(field.name);
441                    items.push(CompletionItem {
442                        label: field_name.to_string(),
443                        kind: Some(CompletionItemKind::FIELD),
444                        detail: Some(format!(
445                            "{}: {}",
446                            field_name,
447                            crate::hover::format_field_type(&field.ty, &doc.interner)
448                        )),
449                        ..Default::default()
450                    });
451                }
452            }
453        }
454    }
455
456    // Fall back: if no fields were added, show all fields from all structs
457    if items
458        .iter()
459        .all(|i| i.kind != Some(CompletionItemKind::FIELD))
460    {
461        for (_name, typedef) in doc.type_registry.iter_types() {
462            if let logicaffeine_language::analysis::TypeDef::Struct { fields, .. } = typedef {
463                for field in fields {
464                    let field_name = doc.interner.resolve(field.name);
465                    items.push(CompletionItem {
466                        label: field_name.to_string(),
467                        kind: Some(CompletionItemKind::FIELD),
468                        detail: Some(format!("{}", field_name)),
469                        ..Default::default()
470                    });
471                }
472            }
473        }
474    }
475}
476
477/// Look back from the possessive token to find the object's type name.
478fn resolve_possessive_type(doc: &DocumentState, offset: usize) -> Option<String> {
479    // Find the token right before the possessive
480    let prev_token = doc
481        .tokens
482        .iter()
483        .rev()
484        .find(|t| t.span.end <= offset && !matches!(t.kind, TokenType::Possessive))?;
485    let var_name = doc.source.get(prev_token.span.start..prev_token.span.end)?;
486
487    // Look up the variable's definition to find its type
488    let defs = doc.symbol_index.definitions_of(var_name);
489    let def = defs.first()?;
490
491    // Extract type from detail string like "Let x: Point" or "Let x: Point: inferred"
492    let detail = def.detail.as_ref()?;
493    // Match pattern "Let name: TypeName" or "name: TypeName"
494    let after_colon = detail.rsplit_once(": ")?;
495    let type_name = after_colon.1.trim();
496    // Strip trailing ": inferred" or other suffixes
497    let type_name = type_name.split(':').next().unwrap_or(type_name).trim();
498    if type_name.is_empty() || type_name == "inferred" {
499        return None;
500    }
501    Some(type_name.to_string())
502}
503
504fn add_variant_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
505    // Fall back to showing all variants from all enums (type-aware filtering
506    // would require resolving the Inspect target, which we can do in the future)
507    for (_name, typedef) in doc.type_registry.iter_types() {
508        if let logicaffeine_language::analysis::TypeDef::Enum { variants, .. } = typedef {
509            for variant in variants {
510                let variant_name = doc.interner.resolve(variant.name);
511                items.push(CompletionItem {
512                    label: variant_name.to_string(),
513                    kind: Some(CompletionItemKind::ENUM_MEMBER),
514                    ..Default::default()
515                });
516            }
517        }
518    }
519}
520
521#[cfg(test)]
522#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/completion/tests.rs"]
523mod tests;
524
525fn add_identifier_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
526    for def in &doc.symbol_index.definitions {
527        let kind = match def.kind {
528            DefinitionKind::Variable => CompletionItemKind::VARIABLE,
529            DefinitionKind::Function => CompletionItemKind::FUNCTION,
530            DefinitionKind::Struct => CompletionItemKind::CLASS,
531            DefinitionKind::Enum => CompletionItemKind::ENUM,
532            DefinitionKind::Field => CompletionItemKind::FIELD,
533            DefinitionKind::Parameter => CompletionItemKind::VARIABLE,
534            DefinitionKind::Block => CompletionItemKind::MODULE,
535            DefinitionKind::Variant => CompletionItemKind::ENUM_MEMBER,
536            DefinitionKind::Theorem => CompletionItemKind::CLASS,
537            DefinitionKind::Component => CompletionItemKind::CLASS,
538            DefinitionKind::Action => CompletionItemKind::METHOD,
539            DefinitionKind::StateField => CompletionItemKind::PROPERTY,
540        };
541
542        // Check ownership state for moved variables
543        let is_moved = doc.ownership_states.get(&def.name).map_or(false, |state| {
544            matches!(state, VarState::Moved | VarState::MaybeMoved(_))
545        });
546
547        let mut detail = def.detail.clone();
548        let mut tags = None;
549        let mut deprecated = None;
550        if is_moved {
551            deprecated = Some(true);
552            tags = Some(vec![CompletionItemTag::DEPRECATED]);
553            detail = Some(format!(
554                "{} (moved)",
555                detail.as_deref().unwrap_or(&def.name)
556            ));
557        }
558
559        items.push(CompletionItem {
560            label: def.name.clone(),
561            kind: Some(kind),
562            detail,
563            documentation: def.doc.clone().map(markdown_docs),
564            deprecated,
565            tags,
566            ..Default::default()
567        });
568    }
569}
570
571/// Stdlib prelude names, documented from their literate `## Note`s.
572/// Declarer wins: a local definition of the same name suppresses the
573/// stdlib entry, mirroring the loader's auto-import rule.
574fn add_stdlib_completions(doc: &DocumentState, items: &mut Vec<CompletionItem>) {
575    for (name, entry) in crate::stdlib_docs::all() {
576        if doc.symbol_index.name_to_defs.contains_key(name) {
577            continue;
578        }
579        items.push(CompletionItem {
580            label: name.to_string(),
581            kind: Some(if entry.is_type {
582                CompletionItemKind::CLASS
583            } else {
584                CompletionItemKind::FUNCTION
585            }),
586            detail: Some(entry.signature.trim_start_matches("## ").to_string()),
587            documentation: Some(lsp_types::Documentation::MarkupContent(
588                lsp_types::MarkupContent {
589                    kind: lsp_types::MarkupKind::Markdown,
590                    value: crate::stdlib_docs::hover_md(name, entry),
591                },
592            )),
593            ..Default::default()
594        });
595    }
596}
597
598/// Plain prose as markdown completion documentation.
599fn markdown_docs(value: String) -> lsp_types::Documentation {
600    lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
601        kind: lsp_types::MarkupKind::Markdown,
602        value,
603    })
604}