tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

218 lignes · 6881 octetsBrut · Historique
1//! Completion. The context is read from the text before the cursor, so it
2//! works while the file does not parse (`list.|`).
3
4use louise_hir::{DefId, DefKind, Hir, ModuleId};
5use louise_span::{FileId, TextSize};
6use louise_types::Printer;
7
8use crate::Analysis;
9
10#[derive(Copy, Clone, PartialEq, Eq, Debug)]
11pub enum CompletionKind {
12 Function,
13 Constructor,
14 Operation,
15 Variable,
16 Module,
17 Type,
18 Keyword,
19}
20
21#[derive(Clone, PartialEq, Debug)]
22pub struct Completion {
23 pub label: String,
24 pub kind: CompletionKind,
25 /// The type, when known.
26 pub detail: Option<String>,
27}
28
29const KEYWORDS: &[&str] = &[
30 "fn", "let", "use", "defer", "match", "if", "else", "handle", "with", "import", "pub",
31 "opaque", "type", "effect", "trait", "impl",
32];
33
34/// Completions for the identifier being typed at `offset` in `text`.
35pub fn complete(
36 analysis: &Analysis,
37 text: &str,
38 file: FileId,
39 offset: TextSize,
40) -> Vec<Completion> {
41 let hir = &analysis.hir;
42 let Some((module, _)) = hir.modules.iter().find(|(_, m)| m.file == file) else {
43 return Vec::new();
44 };
45 let before = &text[..usize::from(offset).min(text.len())];
46 let prefix_start = before
47 .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
48 .map_or(0, |i| i + 1);
49 let prefix = &before[prefix_start..];
50 let mut out = Vec::new();
51
52 // `module.prefix`: the module's public items.
53 if before[..prefix_start].ends_with('.') {
54 let qualifier_text = &before[..prefix_start - 1];
55 let q_start = qualifier_text
56 .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
57 .map_or(0, |i| i + 1);
58 let qualifier = &qualifier_text[q_start..];
59 if let Some(target) = hir.lookup_module(module, qualifier) {
60 let exports = &hir.exports[target.index()];
61 for (name, def) in exports.values.iter().chain(exports.types.iter()) {
62 if name.starts_with(prefix) {
63 out.push(item(analysis, name, *def));
64 }
65 }
66 }
67 out.sort_by(|a, b| a.label.cmp(&b.label));
68 return out;
69 }
70
71 out.extend(locals_before(analysis, file, offset, prefix));
72 let scope = &hir.scopes[module.index()];
73 let prelude = hir.prelude.map(|p| &hir.exports[p.index()].values);
74 let mut items: Vec<Completion> = scope
75 .values
76 .iter()
77 .chain(prelude.into_iter().flatten())
78 .filter(|(name, _)| name.starts_with(prefix))
79 .map(|(name, def)| item(analysis, name, *def))
80 .collect();
81 items.extend(
82 scope
83 .modules
84 .keys()
85 .filter(|m| m.starts_with(prefix))
86 .map(|m| Completion {
87 label: m.clone(),
88 kind: CompletionKind::Module,
89 detail: Some(module_path(hir, scope.modules[m])),
90 }),
91 );
92 items.extend(
93 KEYWORDS
94 .iter()
95 .filter(|k| k.starts_with(prefix))
96 .map(|k| Completion {
97 label: (*k).into(),
98 kind: CompletionKind::Keyword,
99 detail: None,
100 }),
101 );
102 items.sort_by(|a, b| a.label.cmp(&b.label));
103 items.dedup_by(|a, b| a.label == b.label);
104 // Locals first; an item shadowed by a local is not offered twice.
105 items.retain(|i| !out.iter().any(|o| o.label == i.label));
106 out.extend(items);
107 out
108}
109
110fn module_path(hir: &Hir, m: ModuleId) -> String {
111 hir.modules[m].path.clone()
112}
113
114fn item(analysis: &Analysis, name: &str, def: DefId) -> Completion {
115 let hir = &analysis.hir;
116 let kind = match &hir.def(def).kind {
117 DefKind::Fn(_) => CompletionKind::Function,
118 DefKind::Ctor(_) => CompletionKind::Constructor,
119 DefKind::Op(_) => CompletionKind::Operation,
120 _ => CompletionKind::Type,
121 };
122 let detail = analysis.typeck.schemes.get(&def).map(|s| {
123 Printer {
124 hir,
125 ctx: None,
126 gen_names: &[],
127 rigid_names: &[],
128 }
129 .scheme(s)
130 });
131 Completion {
132 label: name.to_owned(),
133 kind,
134 detail,
135 }
136}
137
138/// Locals bound before `offset` in the function around it (an
139/// approximation of lexical scope that suits completion).
140fn locals_before(
141 analysis: &Analysis,
142 file: FileId,
143 offset: TextSize,
144 prefix: &str,
145) -> Vec<Completion> {
146 let hir = &analysis.hir;
147 let mut out: Vec<Completion> = Vec::new();
148 for (id, f) in hir.fn_defs() {
149 if hir.modules[hir.def(id).module].file != file {
150 continue;
151 }
152 let Some(body) = &f.body else { continue };
153 let Some(root) = body.root else { continue };
154 let range = body.expr_span(root);
155 if !range.contains_inclusive(offset) && !hir.def(id).span.range.contains_inclusive(offset) {
156 continue;
157 }
158 let results = analysis.typeck.bodies.get(&id);
159 for (l, local) in body.locals.iter() {
160 if local.synthetic
161 || local.span.start() >= offset
162 || !local.name.starts_with(prefix)
163 || local.name == "resume"
164 {
165 continue;
166 }
167 let detail = results.map(|r| r.show(hir, &r.types.locals[l.index()]));
168 out.retain(|c| c.label != local.name);
169 out.push(Completion {
170 label: local.name.clone(),
171 kind: CompletionKind::Variable,
172 detail,
173 });
174 }
175 }
176 out.reverse();
177 out
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183 use crate::Db;
184
185 fn labels(src: &str) -> Vec<(String, CompletionKind)> {
186 let mut db = Db::new();
187 let offset = src.find('$').unwrap() as u32;
188 let text = src.replace('$', "");
189 let file = db.add_module("main", "main.lse", text.clone());
190 let analysis = db.analyze();
191 complete(&analysis, &text, file, offset.into())
192 .into_iter()
193 .map(|c| (c.label, c.kind))
194 .collect()
195 }
196
197 #[test]
198 fn module_members_after_a_dot() {
199 let got = labels("import std/list\nfn f() { list.re$ }");
200 assert_eq!(got, [("reverse".to_owned(), CompletionKind::Function)]);
201 }
202
203 #[test]
204 fn locals_items_and_keywords() {
205 let got = labels("fn helper() { 1 }\nfn f(value: Int) {\n let velocity = 2\n v$\n}");
206 let names: Vec<_> = got.iter().map(|(l, _)| l.as_str()).collect();
207 assert_eq!(&names[..2], ["velocity", "value"], "{got:?}");
208 let got = labels("fn helper() { 1 }\nfn f() { h$ }");
209 assert!(
210 got.contains(&("helper".into(), CompletionKind::Function)),
211 "{got:?}"
212 );
213 assert!(
214 got.contains(&("handle".into(), CompletionKind::Keyword)),
215 "{got:?}"
216 );
217 }
218}