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
12pub fn completions(doc: &DocumentState, position: Position) -> Option<CompletionResponse> {
16 let offset = doc.line_index.offset(position);
17
18 let prev_token = doc.tokens.iter().rev().find(|t| t.span.end <= offset);
22
23 let mut items = Vec::new();
24
25 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 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 Some(TokenType::Be) => {
66 add_expression_completions(doc, &mut items);
67 }
68
69 Some(TokenType::Colon) => {
71 add_type_completions(doc, &mut items);
72 }
73
74 Some(TokenType::Possessive) => {
76 add_field_completions(doc, offset, &mut items);
78 }
79
80 Some(TokenType::Inspect) => {
82 add_variant_completions(doc, &mut items);
83 }
84
85 _ => {
87 add_identifier_completions(doc, &mut items);
88 }
89 }
90
91 if items.is_empty() {
92 add_identifier_completions(doc, &mut items);
94 add_statement_keywords(&mut items);
95 }
96
97 add_stdlib_completions(doc, &mut items);
100
101 Some(CompletionResponse::Array(items))
102}
103
104pub 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 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 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 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 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
198fn 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
209fn 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 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 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
337fn 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 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_identifier_completions(doc, items);
368
369 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 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 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 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 if let Some(type_name) = resolve_possessive_type(doc, offset) {
432 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 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
477fn resolve_possessive_type(doc: &DocumentState, offset: usize) -> Option<String> {
479 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 let defs = doc.symbol_index.definitions_of(var_name);
489 let def = defs.first()?;
490
491 let detail = def.detail.as_ref()?;
493 let after_colon = detail.rsplit_once(": ")?;
495 let type_name = after_colon.1.trim();
496 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 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 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
571fn 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
598fn 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}