//! Completion. The context is read from the text before the cursor, so it //! works while the file does not parse (`list.|`). use louise_hir::{DefId, DefKind, Hir, ModuleId}; use louise_span::{FileId, TextSize}; use louise_types::Printer; use crate::Analysis; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum CompletionKind { Function, Constructor, Operation, Variable, Module, Type, Keyword, } #[derive(Clone, PartialEq, Debug)] pub struct Completion { pub label: String, pub kind: CompletionKind, /// The type, when known. pub detail: Option, } const KEYWORDS: &[&str] = &[ "fn", "let", "use", "defer", "match", "if", "else", "handle", "with", "import", "pub", "opaque", "type", "effect", "trait", "impl", ]; /// Completions for the identifier being typed at `offset` in `text`. pub fn complete( analysis: &Analysis, text: &str, file: FileId, offset: TextSize, ) -> Vec { let hir = &analysis.hir; let Some((module, _)) = hir.modules.iter().find(|(_, m)| m.file == file) else { return Vec::new(); }; let before = &text[..usize::from(offset).min(text.len())]; let prefix_start = before .rfind(|c: char| !(c.is_alphanumeric() || c == '_')) .map_or(0, |i| i + 1); let prefix = &before[prefix_start..]; let mut out = Vec::new(); // `module.prefix`: the module's public items. if before[..prefix_start].ends_with('.') { let qualifier_text = &before[..prefix_start - 1]; let q_start = qualifier_text .rfind(|c: char| !(c.is_alphanumeric() || c == '_')) .map_or(0, |i| i + 1); let qualifier = &qualifier_text[q_start..]; if let Some(target) = hir.lookup_module(module, qualifier) { let exports = &hir.exports[target.index()]; for (name, def) in exports.values.iter().chain(exports.types.iter()) { if name.starts_with(prefix) { out.push(item(analysis, name, *def)); } } } out.sort_by(|a, b| a.label.cmp(&b.label)); return out; } out.extend(locals_before(analysis, file, offset, prefix)); let scope = &hir.scopes[module.index()]; let prelude = hir.prelude.map(|p| &hir.exports[p.index()].values); let mut items: Vec = scope .values .iter() .chain(prelude.into_iter().flatten()) .filter(|(name, _)| name.starts_with(prefix)) .map(|(name, def)| item(analysis, name, *def)) .collect(); items.extend( scope .modules .keys() .filter(|m| m.starts_with(prefix)) .map(|m| Completion { label: m.clone(), kind: CompletionKind::Module, detail: Some(module_path(hir, scope.modules[m])), }), ); items.extend( KEYWORDS .iter() .filter(|k| k.starts_with(prefix)) .map(|k| Completion { label: (*k).into(), kind: CompletionKind::Keyword, detail: None, }), ); items.sort_by(|a, b| a.label.cmp(&b.label)); items.dedup_by(|a, b| a.label == b.label); // Locals first; an item shadowed by a local is not offered twice. items.retain(|i| !out.iter().any(|o| o.label == i.label)); out.extend(items); out } fn module_path(hir: &Hir, m: ModuleId) -> String { hir.modules[m].path.clone() } fn item(analysis: &Analysis, name: &str, def: DefId) -> Completion { let hir = &analysis.hir; let kind = match &hir.def(def).kind { DefKind::Fn(_) => CompletionKind::Function, DefKind::Ctor(_) => CompletionKind::Constructor, DefKind::Op(_) => CompletionKind::Operation, _ => CompletionKind::Type, }; let detail = analysis.typeck.schemes.get(&def).map(|s| { Printer { hir, ctx: None, gen_names: &[], rigid_names: &[], } .scheme(s) }); Completion { label: name.to_owned(), kind, detail, } } /// Locals bound before `offset` in the function around it (an /// approximation of lexical scope that suits completion). fn locals_before( analysis: &Analysis, file: FileId, offset: TextSize, prefix: &str, ) -> Vec { let hir = &analysis.hir; let mut out: Vec = Vec::new(); for (id, f) in hir.fn_defs() { if hir.modules[hir.def(id).module].file != file { continue; } let Some(body) = &f.body else { continue }; let Some(root) = body.root else { continue }; let range = body.expr_span(root); if !range.contains_inclusive(offset) && !hir.def(id).span.range.contains_inclusive(offset) { continue; } let results = analysis.typeck.bodies.get(&id); for (l, local) in body.locals.iter() { if local.synthetic || local.span.start() >= offset || !local.name.starts_with(prefix) || local.name == "resume" { continue; } let detail = results.map(|r| r.show(hir, &r.types.locals[l.index()])); out.retain(|c| c.label != local.name); out.push(Completion { label: local.name.clone(), kind: CompletionKind::Variable, detail, }); } } out.reverse(); out } #[cfg(test)] mod tests { use super::*; use crate::Db; fn labels(src: &str) -> Vec<(String, CompletionKind)> { let mut db = Db::new(); let offset = src.find('$').unwrap() as u32; let text = src.replace('$', ""); let file = db.add_module("main", "main.lse", text.clone()); let analysis = db.analyze(); complete(&analysis, &text, file, offset.into()) .into_iter() .map(|c| (c.label, c.kind)) .collect() } #[test] fn module_members_after_a_dot() { let got = labels("import std/list\nfn f() { list.re$ }"); assert_eq!(got, [("reverse".to_owned(), CompletionKind::Function)]); } #[test] fn locals_items_and_keywords() { let got = labels("fn helper() { 1 }\nfn f(value: Int) {\n let velocity = 2\n v$\n}"); let names: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect(); assert_eq!(&names[..2], ["velocity", "value"], "{got:?}"); let got = labels("fn helper() { 1 }\nfn f() { h$ }"); assert!( got.contains(&("helper".into(), CompletionKind::Function)), "{got:?}" ); assert!( got.contains(&("handle".into(), CompletionKind::Keyword)), "{got:?}" ); } }