forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompletion.rs
More file actions
1751 lines (1536 loc) · 59.6 KB
/
Copy pathcompletion.rs
File metadata and controls
1751 lines (1536 loc) · 59.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{backend::Backend, util::to_offset_from_position};
use async_lsp::ResponseError;
use async_lsp::lsp_types::{
CompletionItem, CompletionItemKind, CompletionParams, CompletionResponse, InsertTextFormat,
Position, Range, TextEdit,
};
use common::InputDb;
use driver::DriverDataBase;
use hir::{
analysis::name_resolution::{
NameDomain, NameResKind, available_traits_in_scope, is_scope_visible_from,
},
hir_def::{
Body, Func, HirIngot, ItemKind, Partial, Pat, Stmt, TopLevelMod, scope_graph::ScopeId,
},
lower::map_file_to_mod,
visitor::prelude::*,
};
pub async fn handle_completion(
backend: &Backend,
params: CompletionParams,
) -> Result<Option<CompletionResponse>, ResponseError> {
let url =
backend.map_client_uri_to_internal(params.text_document_position.text_document.uri.clone());
let file = backend
.db
.workspace()
.get(&backend.db, &url)
.ok_or_else(|| {
ResponseError::new(
async_lsp::ErrorCode::INTERNAL_ERROR,
format!("File not found: {url}"),
)
})?;
let file_text = file.text(&backend.db);
let cursor = to_offset_from_position(params.text_document_position.position, file_text);
let top_mod = map_file_to_mod(&backend.db, file);
let mut items = Vec::new();
// Check if this is a member access completion (triggered by '.')
// Method 1: Check trigger character from LSP context
let trigger_is_dot = params
.context
.as_ref()
.and_then(|ctx| ctx.trigger_character.as_ref())
.map(|c| c == ".")
.unwrap_or(false);
// Method 2: Check if character before cursor is a dot (handles manual completion invoke)
let char_before_is_dot = cursor
.checked_sub(1.into())
.and_then(|pos| file_text.get(usize::from(pos)..usize::from(cursor)))
.map(|s| s == ".")
.unwrap_or(false);
let is_member_access = trigger_is_dot || char_before_is_dot;
// Check if this is a path completion (triggered by '::')
let trigger_is_colon = params
.context
.as_ref()
.and_then(|ctx| ctx.trigger_character.as_ref())
.map(|c| c == ":")
.unwrap_or(false);
// Check for "::" before cursor
let is_path_completion = cursor
.checked_sub(2.into())
.and_then(|pos| file_text.get(usize::from(pos)..usize::from(cursor)))
.map(|s| s == "::")
.unwrap_or(false)
|| trigger_is_colon;
if is_member_access {
// Member access completion: show fields and methods for the receiver type
collect_member_completions(&backend.db, top_mod, cursor, &mut items);
} else if is_path_completion {
// Path completion: show items in the module before ::
collect_path_completions(&backend.db, top_mod, cursor, file_text, &mut items);
} else {
// Regular completion: show items visible in scope
let scope = find_scope_at_cursor(&backend.db, top_mod, cursor);
if let Some(scope) = scope {
// Detect whether we're in a type or expression context
let context = detect_completion_context(file_text, cursor);
collect_items_from_scope(&backend.db, scope, context, &mut items);
// Also collect auto-import suggestions for symbols not in scope
collect_auto_import_completions(
&backend.db,
top_mod,
scope,
context,
file_text,
&mut items,
);
}
}
if items.is_empty() {
Ok(None)
} else {
Ok(Some(CompletionResponse::Array(items)))
}
}
/// Completion context - determines what kind of items to suggest.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompletionContext {
/// Expression context: suggest values (variables, functions, constants)
Expression,
/// Type context: suggest types (structs, enums, type aliases, traits)
Type,
/// Mixed context: suggest both types and values (e.g., top-level, unknown)
Mixed,
}
impl CompletionContext {
fn to_name_domain(self) -> NameDomain {
match self {
CompletionContext::Expression => NameDomain::VALUE,
CompletionContext::Type => NameDomain::TYPE,
CompletionContext::Mixed => NameDomain::VALUE | NameDomain::TYPE,
}
}
}
/// Detect the completion context based on surrounding text.
fn detect_completion_context(file_text: &str, cursor: parser::TextSize) -> CompletionContext {
let cursor_pos = usize::from(cursor);
// Look backwards from cursor to find context clues
let before = file_text
.get(..cursor_pos)
.unwrap_or_else(|| &file_text[..floor_char_boundary(file_text, cursor_pos)]);
// Skip whitespace to find the last significant character
let trimmed = before.trim_end();
if trimmed.is_empty() {
return CompletionContext::Mixed;
}
let last_char = trimmed.chars().last().unwrap();
// After ':' (but check it's not '::') → type context
if last_char == ':' && !trimmed.ends_with("::") {
return CompletionContext::Type;
}
// After '<' → likely generic argument, type context
if last_char == '<' {
return CompletionContext::Type;
}
// After ',' inside angle brackets → type context (generic args)
if last_char == ',' {
// Check if we're inside angle brackets by counting < and >
let open_angles = trimmed.chars().filter(|&c| c == '<').count();
let close_angles = trimmed.chars().filter(|&c| c == '>').count();
if open_angles > close_angles {
return CompletionContext::Type;
}
}
// After '->' → return type annotation, type context
if trimmed.ends_with("->") {
return CompletionContext::Type;
}
// After 'impl' or 'impl ' → type context (impl block target type)
let trimmed_lower = trimmed.to_lowercase();
if trimmed_lower.ends_with("impl") || trimmed.ends_with("impl ") {
return CompletionContext::Type;
}
// After '=' in a let or assignment → expression context
if last_char == '=' && !trimmed.ends_with("==") && !trimmed.ends_with("!=") {
return CompletionContext::Expression;
}
// After '(' → expression context (function arguments)
if last_char == '(' {
return CompletionContext::Expression;
}
// After operators → expression context
if matches!(last_char, '+' | '-' | '*' | '/' | '%' | '&' | '|' | '^') {
return CompletionContext::Expression;
}
// Default to mixed for safety
CompletionContext::Mixed
}
fn floor_char_boundary(text: &str, index: usize) -> usize {
if index >= text.len() {
return text.len();
}
let mut boundary = index;
while boundary > 0 && !text.is_char_boundary(boundary) {
boundary -= 1;
}
boundary
}
/// Find the most specific scope containing the cursor position.
fn find_scope_at_cursor<'db>(
db: &'db DriverDataBase,
top_mod: TopLevelMod<'db>,
cursor: parser::TextSize,
) -> Option<ScopeId<'db>> {
use hir::span::LazySpan;
// Find the smallest enclosing item
let items = top_mod.scope_graph(db).items_dfs(db);
let mut best_scope = None;
let mut best_size = None;
for item in items {
let span = match item.span().resolve(db) {
Some(s) => s,
None => continue,
};
if span.range.contains(cursor) {
let size = span.range.len();
match best_size {
None => {
best_scope = Some(ScopeId::from_item(item));
best_size = Some(size);
}
Some(current_best) if size < current_best => {
best_scope = Some(ScopeId::from_item(item));
best_size = Some(size);
}
_ => {}
}
}
}
best_scope.or(Some(top_mod.scope()))
}
/// Collect completion items from a scope.
fn collect_items_from_scope<'db>(
db: &'db DriverDataBase,
scope: ScopeId<'db>,
context: CompletionContext,
items: &mut Vec<CompletionItem>,
) {
let domain = context.to_name_domain();
// First collect local bindings and parameters (shadows module-level items)
// Only collect locals in expression context (types can't be local bindings)
if matches!(
context,
CompletionContext::Expression | CompletionContext::Mixed
) {
collect_locals_in_scope(db, scope, items);
}
// Then collect module-level items based on context
let visible_items = scope.items_in_scope(db, domain);
for (name, name_res) in visible_items {
if let Some(completion) = name_res_to_completion(db, name, name_res, context) {
items.push(completion);
}
}
}
/// Collect auto-import completion suggestions for public symbols not currently in scope.
///
/// This iterates all items in the ingot (including nested inline modules) and suggests
/// auto-imports for public items that aren't already visible in the current scope.
fn collect_auto_import_completions<'db>(
db: &'db DriverDataBase,
current_mod: TopLevelMod<'db>,
current_scope: ScopeId<'db>,
context: CompletionContext,
file_text: &str,
items: &mut Vec<CompletionItem>,
) {
let ingot = current_mod.ingot(db);
let domain = context.to_name_domain();
// Get names already visible in the current scope
let visible_items = current_scope.items_in_scope(db, domain);
let visible_names: std::collections::HashSet<_> = visible_items.keys().collect();
// Find where to insert the import (in the containing module)
let import_position = find_module_import_position(db, current_scope, file_text);
// Iterate all items in the ingot (includes nested inline modules)
for item in ingot.all_items(db).iter().copied() {
// Only include items visible from the current scope
let item_scope = ScopeId::from_item(item);
if !is_scope_visible_from(db, item_scope, current_scope) {
continue;
}
// Skip if already visible in current scope
let Some(name) = item.name(db) else {
continue;
};
let name_str = name.data(db).to_string();
if visible_names.contains(&name_str) {
continue;
}
// Compute the import path for this item
let Some(import_path) = compute_item_import_path(db, item) else {
continue;
};
// Build auto-import completion with proper snippets
if let Some(completion) =
build_auto_import_completion(db, item, &import_path, context, import_position)
{
items.push(completion);
}
}
}
/// Build an auto-import completion item for an item from another module.
fn build_auto_import_completion<'db>(
db: &'db DriverDataBase,
item: ItemKind<'db>,
module_path: &str,
context: CompletionContext,
import_position: Position,
) -> Option<CompletionItem> {
let name = item.name(db)?;
let name_str = name.data(db).to_string();
// Filter and get completion kind based on item type and context
let (kind, snippet, detail) = match item {
ItemKind::Func(func) => {
if matches!(context, CompletionContext::Type) {
return None;
}
// Build callable snippet
let (snippet, detail) = build_func_snippet_and_detail(db, func, &name_str);
(CompletionItemKind::FUNCTION, snippet, detail)
}
ItemKind::Const(_) => {
if matches!(context, CompletionContext::Type) {
return None;
}
(
CompletionItemKind::CONSTANT,
name_str.clone(),
name_str.clone(),
)
}
ItemKind::Struct(_) => {
if matches!(context, CompletionContext::Expression) {
return None;
}
(
CompletionItemKind::STRUCT,
name_str.clone(),
name_str.clone(),
)
}
ItemKind::Enum(_) => {
if matches!(context, CompletionContext::Expression) {
return None;
}
(CompletionItemKind::ENUM, name_str.clone(), name_str.clone())
}
ItemKind::Trait(_) => {
if matches!(context, CompletionContext::Expression) {
return None;
}
(
CompletionItemKind::INTERFACE,
name_str.clone(),
name_str.clone(),
)
}
ItemKind::TypeAlias(_) | ItemKind::Contract(_) => {
if matches!(context, CompletionContext::Expression) {
return None;
}
(
CompletionItemKind::CLASS,
name_str.clone(),
name_str.clone(),
)
}
// Skip modules, impls, etc.
_ => return None,
};
// module_path is already the full import path (e.g., "utils::func_with_args")
// Create the import text edit
let import_text = format!("use {}\n", module_path);
let import_edit = TextEdit {
range: Range {
start: import_position,
end: import_position,
},
new_text: import_text,
};
// Extract just the module portion for display (everything before the last ::)
let module_only = module_path
.rsplit_once("::")
.map(|(m, _)| m)
.unwrap_or(module_path);
Some(CompletionItem {
label: name_str,
kind: Some(kind),
detail: Some(format!("use {} [{}]", module_path, detail)),
label_details: Some(async_lsp::lsp_types::CompletionItemLabelDetails {
detail: Some(format!(" ({})", module_only)),
description: None,
}),
insert_text: Some(snippet),
insert_text_format: Some(InsertTextFormat::SNIPPET),
additional_text_edits: Some(vec![import_edit]),
..Default::default()
})
}
/// Build snippet and detail for a function (shared logic for auto-import).
fn build_func_snippet_and_detail<'db>(
db: &'db DriverDataBase,
func: Func<'db>,
name_str: &str,
) -> (String, String) {
let mut param_names = Vec::new();
let mut param_details = Vec::new();
for param in func.params(db) {
if param.is_self_param(db) {
continue;
}
let param_name = param
.name(db)
.map(|n| n.data(db).to_string())
.unwrap_or_else(|| format!("arg{}", param_names.len()));
let param_ty = param.ty(db);
param_details.push(format!("{}: {}", param_name, param_ty.pretty_print(db)));
param_names.push(param_name);
}
let ret_ty = func.return_ty(db);
let ret_str = {
let ret_pretty = ret_ty.pretty_print(db);
if ret_pretty == "()" {
String::new()
} else {
format!(" -> {}", ret_pretty)
}
};
let detail = format!("fn {}({}){}", name_str, param_details.join(", "), ret_str);
let snippet = if param_names.is_empty() {
format!("{}()$0", name_str)
} else {
let tabstops: Vec<String> = param_names
.iter()
.enumerate()
.map(|(i, p)| format!("${{{}:{}}}", i + 1, p))
.collect();
format!("{}({})$0", name_str, tabstops.join(", "))
};
(snippet, detail)
}
/// Find the position to insert imports in the containing module.
fn find_module_import_position<'db>(
db: &'db DriverDataBase,
scope: ScopeId<'db>,
file_text: &str,
) -> Position {
use hir::span::LazySpan;
// Find the containing module
if let Some(parent_mod) = scope.parent_module(db) {
match parent_mod.item() {
ItemKind::Mod(m) => {
// For inline modules, find position after the opening brace
if let Some(span) = m.span().resolve(db) {
let mod_start = usize::from(span.range.start());
let mod_text = &file_text[mod_start..];
// Find the opening brace
if let Some(brace_offset) = mod_text.find('{') {
let abs_brace_pos = mod_start + brace_offset;
// Find position after the opening brace
return find_import_position_after_brace(file_text, abs_brace_pos);
}
}
}
ItemKind::TopMod(_) => {
// For top-level modules, use the file-level position
return find_import_insertion_position(file_text);
}
_ => {}
}
}
// Fallback to file-level position
find_import_insertion_position(file_text)
}
/// Find import position within a module body (after opening brace).
/// `full_file_text` is the complete file content, `brace_offset` is the byte offset of the `{`.
fn find_import_position_after_brace(full_file_text: &str, brace_offset: usize) -> Position {
// Find the line after the opening brace
// The use statement should go on the next line after '{'
let mut line = 0u32;
let mut last_newline_offset = 0;
for (i, ch) in full_file_text.char_indices() {
if i >= brace_offset {
// Found the brace, now find the next newline
let rest = &full_file_text[brace_offset..];
if rest.find('\n').is_some() {
// Position at start of the line after the brace
return Position {
line: line + 1,
character: 0,
};
} else {
// No newline after brace, insert right after brace
return Position {
line,
character: (brace_offset - last_newline_offset + 1) as u32,
};
}
}
if ch == '\n' {
line += 1;
last_newline_offset = i + 1;
}
}
// Fallback
Position {
line: 0,
character: 0,
}
}
/// Compute the import path for any item, including those in nested inline modules.
///
/// Returns the path like "utils::helper_func" or "outer::inner::SomeStruct".
/// For use in auto-import, this returns only the path needed within the current ingot,
/// excluding the top-level module name (file name) but including the item name.
fn compute_item_import_path<'db>(db: &'db DriverDataBase, item: ItemKind<'db>) -> Option<String> {
let item_name = item.name(db)?.data(db).to_string();
// Build the path by walking up from the item's scope to find containing modules
let scope = ScopeId::from_item(item);
let mut path_parts = vec![item_name];
// Walk up the parent chain looking for Mod items (inline modules)
// Start from parent (not the item's own scope) to avoid duplicating the name
let mut current = scope.parent(db);
while let Some(parent_scope) = current {
match parent_scope.item() {
ItemKind::Mod(m) => {
// This is an inline module - add its name to the path
if let Partial::Present(name) = m.name(db) {
path_parts.push(name.data(db).to_string());
}
}
ItemKind::TopMod(_) => {
// Reached the top-level file module - stop here
// We don't include the file name in the import path for single-file scenarios
break;
}
_ => {
// Other items (functions, impls, structs, etc.) - skip them
// These don't contribute to the import path
}
}
current = parent_scope.parent(db);
}
// Reverse to get the path in correct order (outer to inner)
path_parts.reverse();
// If there's only the item name (no module path), it means the item is at
// the top level - don't suggest auto-import for top-level items in same file
if path_parts.len() <= 1 {
return None;
}
Some(path_parts.join("::"))
}
/// Find the position to insert new import statements at the top level.
/// For top-level modules, we simply insert at the start of the file (line 0).
/// The user can organize imports as they prefer.
fn find_import_insertion_position(_file_text: &str) -> Position {
// Insert at the very start of the file for top-level modules
Position {
line: 0,
character: 0,
}
}
/// Collect completions for path access (items after `::`).
fn collect_path_completions<'db>(
db: &'db DriverDataBase,
top_mod: TopLevelMod<'db>,
cursor: parser::TextSize,
file_text: &str,
items: &mut Vec<CompletionItem>,
) {
use hir::analysis::name_resolution::NameDomain;
// Find the full path before ::
// We need to go back from the cursor (which is after ::) and find the complete path
let cursor_pos = usize::from(cursor);
if cursor_pos < 2 {
return;
}
// Go back past the ::
let before_colons = &file_text[..cursor_pos.saturating_sub(2)];
// Find the start of the full path (including all :: segments)
// Look for whitespace, operators, or other non-path characters
let path_start = before_colons
.rfind(|c: char| !c.is_alphanumeric() && c != '_' && c != ':')
.map(|i| i + 1)
.unwrap_or(0);
let full_path = before_colons[path_start..].trim();
if full_path.is_empty() {
return;
}
// Split the path into segments
let segments: Vec<&str> = full_path.split("::").filter(|s| !s.is_empty()).collect();
if segments.is_empty() {
return;
}
// Resolve the path step by step
let mut current_scope = top_mod.scope();
for segment in &segments {
let visible = current_scope.items_in_scope(db, NameDomain::VALUE | NameDomain::TYPE);
if let Some(name_res) = visible.get(*segment) {
if let hir::analysis::name_resolution::NameResKind::Scope(target_scope) = &name_res.kind
{
current_scope = *target_scope;
} else {
return;
}
} else {
return;
}
}
// Detect context for filtering (look at what's before the path)
let context = detect_completion_context(file_text, cursor);
// Get direct child items of the final resolved scope
// This gives us only items defined directly in this module, not inherited ones
let child_items: Vec<_> = current_scope.child_items(db).collect();
for item in child_items {
let Some(name) = item.name(db) else {
continue;
};
let name_str = name.data(db);
// Filter and determine kind based on item type and context
let (kind, insert_text) = match item {
ItemKind::Func(func) => {
if matches!(context, CompletionContext::Type) {
continue;
}
// Use callable snippet for functions
if let Some(completion) =
build_callable_completion(db, func, CompletionItemKind::FUNCTION)
{
items.push(completion);
}
continue;
}
ItemKind::Const(_) => {
if matches!(context, CompletionContext::Type) {
continue;
}
(CompletionItemKind::CONSTANT, None)
}
ItemKind::Struct(_) => {
if matches!(context, CompletionContext::Expression) {
continue;
}
(CompletionItemKind::STRUCT, None)
}
ItemKind::Enum(_) => {
if matches!(context, CompletionContext::Expression) {
continue;
}
(CompletionItemKind::ENUM, None)
}
ItemKind::Trait(_) => {
if matches!(context, CompletionContext::Expression) {
continue;
}
(CompletionItemKind::INTERFACE, None)
}
ItemKind::TypeAlias(_) => {
if matches!(context, CompletionContext::Expression) {
continue;
}
(CompletionItemKind::CLASS, None)
}
ItemKind::Contract(_) => {
if matches!(context, CompletionContext::Expression) {
continue;
}
(CompletionItemKind::CLASS, None)
}
ItemKind::Mod(_) | ItemKind::TopMod(_) => {
// Modules get :: suffix
(CompletionItemKind::MODULE, Some(format!("{}::", name_str)))
}
_ => continue,
};
items.push(CompletionItem {
label: name_str.to_string(),
kind: Some(kind),
insert_text,
..Default::default()
});
}
}
/// Collect completions for member access (fields and methods after `.`).
fn collect_member_completions<'db>(
db: &'db DriverDataBase,
top_mod: TopLevelMod<'db>,
cursor: parser::TextSize,
items: &mut Vec<CompletionItem>,
) {
use hir::analysis::ty::ty_check::check_func_body;
use hir::hir_def::Expr;
use hir::span::LazySpan;
// Find the enclosing function
let scope_graph = top_mod.scope_graph(db);
let mut enclosing_func = None;
for item in scope_graph.items_dfs(db) {
if let ItemKind::Func(func) = item
&& let Some(span) = func.span().resolve(db)
&& span.range.contains(cursor)
{
enclosing_func = Some(func);
}
}
let Some(func) = enclosing_func else {
return;
};
let Some(body) = func.body(db) else {
return;
};
// Get typed body for type information
let (_, typed_body) = check_func_body(db, func);
// Strategy 1: Find Field expressions (field access like `foo.bar` or incomplete `foo.`)
// that contain the cursor, and use their receiver's type
for (expr_id, expr_data) in body.exprs(db).iter() {
if let Partial::Present(Expr::Field(receiver_id, _field)) = expr_data {
let expr_span = expr_id.span(body);
if let Some(resolved) = expr_span.resolve(db) {
// Check if cursor is within this field expression
if resolved.range.contains(cursor) || resolved.range.end() == cursor {
let mut ty = typed_body.expr_ty(db, *receiver_id);
// If the receiver type is invalid (due to incomplete syntax), try to find
// the type from the expression itself (e.g., if it's a path to a local binding)
if ty.has_invalid(db)
&& let Some(Partial::Present(Expr::Path(Partial::Present(path)))) =
body.exprs(db).get(*receiver_id)
{
// Try to resolve the path to find a local binding's type
if let Some(ident) = path.as_ident(db) {
let ident_str = ident.data(db);
// Special case: if the path is "self", get the self parameter's type
if ident_str == "self" {
for param in func.params(db) {
if param.is_self_param(db) {
let self_ty = param.ty(db);
if !self_ty.has_invalid(db) {
ty = self_ty;
break;
}
}
}
} else {
// Look through patterns to find this binding's type
for (pat_id, pat_data) in body.pats(db).iter() {
if let Partial::Present(Pat::Path(
Partial::Present(pat_path),
_,
)) = pat_data
&& pat_path.as_ident(db) == Some(ident)
{
let pat_ty = typed_body.pat_ty(db, pat_id);
if !pat_ty.has_invalid(db) {
ty = pat_ty;
break;
}
}
}
}
}
}
collect_fields_for_type(db, ty, items);
collect_methods_for_type(db, top_mod, ty, func.scope(), items);
return;
}
}
}
}
// Strategy 2: Fallback - look for any expression ending at cursor-1 (before the dot)
let dot_pos = cursor.checked_sub(1.into()).unwrap_or(cursor);
for (expr_id, _) in body.exprs(db).iter() {
let expr_span = expr_id.span(body);
if let Some(resolved) = expr_span.resolve(db)
&& resolved.range.end() == dot_pos
{
let ty = typed_body.expr_ty(db, expr_id);
collect_fields_for_type(db, ty, items);
collect_methods_for_type(db, top_mod, ty, func.scope(), items);
return;
}
}
}
/// Collect struct fields as completion items.
fn collect_fields_for_type<'db>(
db: &'db DriverDataBase,
ty: hir::analysis::ty::ty_def::TyId<'db>,
items: &mut Vec<CompletionItem>,
) {
// Use the traversal API to get fields for struct/contract types
let Some(field_parent) = ty.field_parent(db) else {
return;
};
for field in field_parent.fields(db) {
let Some(name) = field.name(db) else {
continue;
};
let field_ty = field.ty(db);
let detail = format!("{}: {}", name.data(db), field_ty.pretty_print(db));
items.push(CompletionItem {
label: name.data(db).to_string(),
kind: Some(CompletionItemKind::FIELD),
detail: Some(detail),
..Default::default()
});
}
}
/// Build a completion item for a callable (function or method) with snippet tabstops.
fn build_callable_completion<'db>(
db: &'db DriverDataBase,
func: Func<'db>,
kind: CompletionItemKind,
) -> Option<CompletionItem> {
let name = func.name(db).to_opt()?;
let name_str = name.data(db).to_string();
// Build parameter list for detail and snippet
let mut param_names = Vec::new();
let mut param_details = Vec::new();
for param in func.params(db) {
if param.is_self_param(db) {
continue; // Skip self parameter in completion
}
let param_name = param
.name(db)
.map(|n| n.data(db).to_string())
.unwrap_or_else(|| format!("arg{}", param_names.len()));
let param_ty = param.ty(db);
param_details.push(format!("{}: {}", param_name, param_ty.pretty_print(db)));
param_names.push(param_name);
}
// Build detail string: fn name(param1: Type1, param2: Type2) -> ReturnType
let ret_ty = func.return_ty(db);
let ret_str = {
let ret_pretty = ret_ty.pretty_print(db);
if ret_pretty == "()" {
String::new()
} else {
format!(" -> {}", ret_pretty)
}
};
let detail = format!("fn {}({}){}", name_str, param_details.join(", "), ret_str);
// Build snippet with tabstops: name(${1:param1}, ${2:param2})
let snippet = if param_names.is_empty() {
format!("{}()$0", name_str)
} else {
let tabstops: Vec<String> = param_names
.iter()
.enumerate()
.map(|(i, p)| format!("${{{}:{}}}", i + 1, p))
.collect();
format!("{}({})$0", name_str, tabstops.join(", "))
};
Some(CompletionItem {
label: name_str,
kind: Some(kind),
detail: Some(detail),
insert_text: Some(snippet),
insert_text_format: Some(InsertTextFormat::SNIPPET),
..Default::default()
})
}
/// Collect methods from impls as completion items.
fn collect_methods_for_type<'db>(
db: &'db DriverDataBase,
top_mod: TopLevelMod<'db>,
ty: hir::analysis::ty::ty_def::TyId<'db>,
scope: ScopeId<'db>,
items: &mut Vec<CompletionItem>,
) {
// Get the type name for matching impl blocks
let ty_name = ty.pretty_print(db);
// Track method names to avoid duplicates
let mut seen_methods = std::collections::HashSet::new();
// Look for inherent impl blocks in the module
for item in top_mod.scope_graph(db).items_dfs(db) {
if let ItemKind::Impl(impl_) = item {
// Check if this impl is for our type by comparing target type name
let impl_ty_name = impl_.ty(db).pretty_print(db);
if impl_ty_name == ty_name {
for func in impl_.funcs(db) {
if func.is_method(db)
&& let Some(name) = func.name(db).to_opt()
&& seen_methods.insert(name)
&& let Some(completion) =
build_callable_completion(db, func, CompletionItemKind::METHOD)
{
items.push(completion);
}
}
}
}
}
// Collect trait methods from in-scope traits that are implemented for this type
collect_trait_methods_for_type(db, ty, scope, &mut seen_methods, items);
}
/// Collect methods from trait implementations for the given type.
fn collect_trait_methods_for_type<'db>(
db: &'db DriverDataBase,
ty: hir::analysis::ty::ty_def::TyId<'db>,
scope: ScopeId<'db>,
seen_methods: &mut std::collections::HashSet<hir::hir_def::IdentId<'db>>,
items: &mut Vec<CompletionItem>,
) {
// Get traits available in the current scope
let available_traits = available_traits_in_scope(db, scope);
// Get the type name for matching impl trait blocks