perl-lsp-completion 0.12.2

Context-aware LSP completion engine for Perl — variables, functions, methods, packages, and file paths
Documentation
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
//! Workspace symbol completion for Perl
//!
//! Provides completion for symbols from other files in the workspace using the workspace index.
//! Includes module name completion for `use`/`require` statements, workspace-aware method
//! completion for `->` expressions, and general cross-file symbol completion.

use super::{
    auto_import,
    context::CompletionContext,
    items::{CompletionItem, CompletionItemKind},
};
use perl_workspace_index::workspace_index::{SymbolKind as WsSymbolKind, VarKind, WorkspaceIndex};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// Add workspace symbol completions for functions and variables
///
/// Queries the workspace index to provide completions for symbols from other files.
/// Uses the `import_map` to promote imported symbols and downrank explicitly
/// not-imported symbols for import-aware sort ordering.
pub fn add_workspace_symbol_completions(
    completions: &mut Vec<CompletionItem>,
    context: &CompletionContext,
    workspace_index: &Option<Arc<WorkspaceIndex>>,
    import_map: &HashMap<String, HashSet<String>>,
) {
    // Only proceed if we have a workspace index
    let Some(index) = workspace_index else {
        return;
    };

    // Only provide workspace completions if there's a reasonable prefix
    // to avoid overwhelming the user with all workspace symbols
    if context.prefix.is_empty() {
        return;
    }

    // Check if the workspace index has any symbols
    if !index.has_symbols() {
        return;
    }

    // Search for symbols matching the prefix
    let matching_symbols = index.find_symbols(&context.prefix);

    for symbol in matching_symbols {
        // Skip symbols that don't match the prefix
        if !symbol.name.starts_with(&context.prefix)
            && !symbol.qualified_name.as_ref().is_some_and(|qn| qn.contains(&context.prefix))
        {
            continue;
        }

        match symbol.kind {
            WsSymbolKind::Subroutine | WsSymbolKind::Method => {
                // Determine sort priority and detail based on import map
                let label = symbol.qualified_name.as_ref().unwrap_or(&symbol.name).clone();
                let module = symbol.container_name.as_deref().unwrap_or("");

                let (sort_prefix, detail) = match import_map.get(module) {
                    None => {
                        // Module not in import_map: not used or `use Module` (import all).
                        // Rank at tier 4 (after core builtins at tier 3).
                        let det = symbol
                            .container_name
                            .clone()
                            .unwrap_or_else(|| "workspace".to_string());
                        ("4_", det)
                    }
                    Some(imported_set) if imported_set.is_empty() => {
                        // Explicit empty import `use Module qw()` — not in namespace.
                        // Rank at tier 5 (lowest, after all useful completions).
                        ("5_", "not imported".to_string())
                    }
                    Some(imported_set) if imported_set.contains(&symbol.name) => {
                        // Symbol is explicitly imported — boost priority to tier 2
                        // (treated like a file-scope symbol).
                        let det = format!("imported from {module}");
                        ("2_", det)
                    }
                    Some(_) => {
                        // Module used with explicit list, but this symbol wasn't in it.
                        // Rank at tier 4 (workspace, after core builtins).
                        let det = symbol
                            .container_name
                            .clone()
                            .unwrap_or_else(|| "workspace".to_string());
                        ("4_", det)
                    }
                };

                completions.push(CompletionItem {
                    insert_text: Some(symbol.name.clone()),
                    sort_text: Some(format!("{sort_prefix}{label}")),
                    filter_text: Some(label.clone()),
                    label,
                    kind: CompletionItemKind::Function,
                    detail: Some(detail),
                    documentation: symbol.documentation.clone(),
                    additional_edits: vec![],
                    text_edit_range: Some((context.prefix_start, context.position)),
                    commit_characters: None,
                });
            }
            WsSymbolKind::Variable(var_kind) => {
                // Add variable completion with appropriate sigil
                let sigil = match var_kind {
                    VarKind::Scalar => "$",
                    VarKind::Array => "@",
                    VarKind::Hash => "%",
                };

                let label = if let Some(ref qname) = symbol.qualified_name {
                    format!("{}{}", sigil, qname)
                } else {
                    format!("{}{}", sigil, symbol.name)
                };

                // Only suggest if the prefix matches (considering sigil)
                if !label.starts_with(&context.prefix) {
                    continue;
                }

                completions.push(CompletionItem {
                    insert_text: Some(label.clone()),
                    sort_text: Some(format!("4_{}", label)), // Tier 4: after core builtins
                    filter_text: Some(label.clone()),
                    label,
                    kind: CompletionItemKind::Variable,
                    detail: symbol.container_name.clone().or_else(|| Some("workspace".to_string())),
                    documentation: symbol.documentation.clone(),
                    additional_edits: vec![],
                    text_edit_range: Some((context.prefix_start, context.position)),
                    commit_characters: None,
                });
            }
            WsSymbolKind::Package => {
                // Add package completion — tier 4 (workspace, after core builtins)
                let name = &symbol.name;
                completions.push(CompletionItem {
                    label: name.clone(),
                    kind: CompletionItemKind::Module,
                    detail: Some("package".to_string()),
                    documentation: symbol.documentation.clone(),
                    insert_text: Some(name.clone()),
                    sort_text: Some(format!("4_{name}")),
                    filter_text: Some(name.clone()),
                    additional_edits: vec![],
                    text_edit_range: Some((context.prefix_start, context.position)),
                    commit_characters: None,
                });
            }
            WsSymbolKind::Constant => {
                // Add constant completion — tier 4 (workspace, after core builtins)
                let name = &symbol.name;
                completions.push(CompletionItem {
                    label: name.clone(),
                    kind: CompletionItemKind::Constant,
                    detail: symbol.container_name.clone().or_else(|| Some("workspace".to_string())),
                    documentation: symbol.documentation.clone(),
                    insert_text: Some(name.clone()),
                    sort_text: Some(format!("4_{name}")),
                    filter_text: Some(name.clone()),
                    additional_edits: vec![],
                    text_edit_range: Some((context.prefix_start, context.position)),
                    commit_characters: None,
                });
            }
            WsSymbolKind::Export => {
                // Add exported symbol completion
                let name = &symbol.name;
                completions.push(CompletionItem {
                    label: name.clone(),
                    kind: CompletionItemKind::Function,
                    detail: Some("exported".to_string()),
                    documentation: symbol.documentation.clone(),
                    insert_text: Some(name.clone()),
                    sort_text: Some(format!("2_{name}")), // Prioritize exports
                    filter_text: Some(name.clone()),
                    additional_edits: vec![],
                    text_edit_range: Some((context.prefix_start, context.position)),
                    commit_characters: None,
                });
            }
            _ => {
                // Skip other symbol types
            }
        }
    }
}

/// Add module name completions for `use` and `require` statements.
///
/// When the cursor is after `use ` or `require `, suggests package names from the
/// workspace index. This enables discovering available modules as you type.
///
/// For example, typing `use My` will suggest `MyApp`, `MyApp::Config`, etc.
pub fn add_use_module_completions(
    completions: &mut Vec<CompletionItem>,
    context: &CompletionContext,
    workspace_index: &Option<Arc<WorkspaceIndex>>,
) {
    let Some(index) = workspace_index else {
        return;
    };

    if !index.has_symbols() {
        return;
    }

    let mut seen: HashSet<String> = HashSet::new();

    // Search for package symbols matching the prefix
    let all_symbols = if context.prefix.is_empty() {
        index.all_symbols()
    } else {
        index.find_symbols(&context.prefix)
    };

    for symbol in all_symbols {
        if symbol.kind != WsSymbolKind::Package {
            continue;
        }

        // Match against the module name prefix
        if !context.prefix.is_empty() && !symbol.name.starts_with(&context.prefix) {
            continue;
        }

        if !seen.insert(symbol.name.clone()) {
            continue;
        }

        let name = &symbol.name;
        completions.push(CompletionItem {
            label: name.clone(),
            kind: CompletionItemKind::Module,
            detail: Some("module".to_string()),
            documentation: symbol
                .documentation
                .clone()
                .or_else(|| Some(format!("Package `{name}`"))),
            insert_text: Some(name.clone()),
            sort_text: Some(format!("1_{name}")), // High priority in use context
            filter_text: Some(name.clone()),
            additional_edits: vec![],
            text_edit_range: Some((context.prefix_start, context.position)),
            commit_characters: None,
        });
    }
}

/// Add import completions for symbols inside `use Module qw(...)`.
///
/// When the cursor is inside the `qw()` import list of a `use` statement,
/// queries the workspace index for symbols exported by or defined in that
/// module and suggests matching function/variable/constant names.
///
/// For example, typing `use File::Basename qw(bas` will suggest `basename`,
/// `fileparse`, `dirname`, etc.
pub fn add_use_qw_import_completions(
    completions: &mut Vec<CompletionItem>,
    context: &CompletionContext,
    workspace_index: &Option<Arc<WorkspaceIndex>>,
    module_name: &str,
    qw_prefix: &str,
) {
    let Some(index) = workspace_index else {
        return;
    };

    if !index.has_symbols() {
        return;
    }

    let mut seen: HashSet<&str> = HashSet::new();
    let members = index.get_package_members(module_name);

    for symbol in &members {
        match symbol.kind {
            WsSymbolKind::Subroutine
            | WsSymbolKind::Method
            | WsSymbolKind::Export
            | WsSymbolKind::Constant => {}
            _ => continue,
        }

        // Filter by prefix typed inside qw()
        if !qw_prefix.is_empty() && !symbol.name.starts_with(qw_prefix) {
            continue;
        }

        // Deduplicate
        if !seen.insert(&symbol.name) {
            continue;
        }

        let kind_label = match symbol.kind {
            WsSymbolKind::Constant => "constant",
            WsSymbolKind::Export => "exported",
            _ => "function",
        };

        let name = &symbol.name;
        completions.push(CompletionItem {
            label: name.clone(),
            kind: match symbol.kind {
                WsSymbolKind::Constant => CompletionItemKind::Constant,
                _ => CompletionItemKind::Function,
            },
            detail: Some(format!("{module_name} {kind_label}")),
            documentation: symbol
                .documentation
                .clone()
                .or_else(|| Some(format!("`{module_name}::{name}`"))),
            insert_text: Some(name.clone()),
            sort_text: Some(format!("1_{name}")),
            filter_text: Some(name.clone()),
            additional_edits: vec![],
            text_edit_range: Some((context.prefix_start, context.position)),
            commit_characters: None,
        });
    }
}

/// Infer the package type of a `->` receiver from the source context.
///
/// Looks for patterns like `My::Package->method` (static call) or attempts to
/// find the type from variable assignment context like `my $obj = My::Package->new`.
fn infer_receiver_package(context: &CompletionContext, source: &str) -> Option<String> {
    let arrow_prefix = context.prefix.trim_end_matches("->");

    // Case 1: Static method call like `My::Package->meth` or `Package->meth`
    // The prefix already contains the package name (starts with uppercase, no sigil)
    if !arrow_prefix.starts_with('$')
        && !arrow_prefix.starts_with('@')
        && !arrow_prefix.starts_with('%')
        && arrow_prefix.chars().next().is_some_and(|c| c.is_ascii_uppercase())
    {
        return Some(arrow_prefix.to_string());
    }

    // Case 3: Self-call inside a method — `$self->` or `$this->` resolves to the
    // current package. Standard Perl OO convention: the invocant of `bless` is
    // assigned to `$self` (or `$this`) via `my $self = shift`.  The RHS is just
    // `shift`, so Case 2 would not match any constructor pattern.  Instead we
    // fall back to `context.current_package` which the context analyser already
    // sets correctly from the surrounding `package` declaration.
    if matches!(arrow_prefix, "$self" | "$this")
        && !context.current_package.is_empty()
        && context.current_package != "main"
    {
        return Some(context.current_package.clone());
    }

    // Case 2: Variable method call like `$obj->meth`
    // Try to find the type from assignment context
    if arrow_prefix.starts_with('$') {
        let var_name = arrow_prefix;
        // Look for assignment pattern: `my $var = Package->new`
        // Search backwards in source for the variable assignment
        let before = &source[..context.position.min(source.len())];

        // Find the most recent assignment to this variable
        for line in before.lines().rev() {
            let trimmed = line.trim();
            // Match patterns like: `my $var = Package::Name->new(...)`
            // or `$var = Package::Name->new(...)`
            // We need a single `=` that is not part of `==`, `!=`, `<=`, `>=`, `=~`.
            let assign_pos = find_assignment_eq(trimmed);
            if let Some(assign_pos) = assign_pos {
                let lhs = trimmed[..assign_pos].trim();
                if lhs.ends_with(var_name) || lhs.contains(&format!("{var_name} ")) {
                    let rhs = trimmed[assign_pos + 1..].trim();
                    // Extract package name from `Package::Name->new(...)` pattern
                    if let Some(arrow_pos) = rhs.find("->") {
                        let pkg = rhs[..arrow_pos].trim();
                        if pkg.contains("::")
                            || pkg.chars().next().is_some_and(|c| c.is_ascii_uppercase())
                        {
                            return Some(pkg.to_string());
                        }
                    }
                }
            }
        }
    }

    None
}

/// Add method completions from the workspace index for `->` expressions.
///
/// When the user types `$obj->` or `Package->`, queries the workspace index for
/// methods defined in the receiver's package and suggests them.
///
/// Auto-import edits are attached when the receiver package is not yet imported.
pub fn add_workspace_method_completions(
    completions: &mut Vec<CompletionItem>,
    context: &CompletionContext,
    source: &str,
    workspace_index: &Option<Arc<WorkspaceIndex>>,
) {
    let Some(index) = workspace_index else {
        return;
    };

    if !index.has_symbols() {
        return;
    }

    let Some(package_name) = infer_receiver_package(context, source) else {
        return;
    };

    // Collect labels already present to avoid duplicates with local method completions
    let existing_labels: HashSet<String> =
        completions.iter().map(|item| item.label.clone()).collect();

    let method_prefix = context.prefix.rsplit("->").next().unwrap_or("");
    let members = index.get_package_members(&package_name);

    // Build an auto-import edit once for all methods from this package.
    let auto_import_edit = auto_import::build_auto_import_edit(source, &package_name);

    for symbol in members {
        match symbol.kind {
            WsSymbolKind::Subroutine | WsSymbolKind::Method => {}
            _ => continue,
        }

        if !method_prefix.is_empty() && !symbol.name.starts_with(method_prefix) {
            continue;
        }

        // Skip if already provided by local method completion
        if existing_labels.contains(&symbol.name) {
            continue;
        }

        let additional_edits =
            auto_import_edit.as_ref().map(|e| vec![e.clone()]).unwrap_or_default();

        completions.push(CompletionItem {
            label: symbol.name.clone(),
            kind: CompletionItemKind::Function,
            detail: Some(format!("{package_name} method")),
            documentation: symbol.documentation.clone().or_else(|| {
                Some(format!("Method `{}::{}` from workspace index.", package_name, symbol.name))
            }),
            insert_text: Some(format!("{}()", symbol.name)),
            sort_text: Some(format!("2_{}", symbol.name)), // After local, before generic
            filter_text: Some(symbol.name.clone()),
            additional_edits,
            text_edit_range: Some((context.prefix_start, context.position)),
            commit_characters: None,
        });
    }
}

/// Find the position of a single assignment `=` in a line, skipping compound
/// operators like `==`, `!=`, `<=`, `>=`, `=~`, and `=>`.
///
/// Returns `None` if no assignment operator is found.
fn find_assignment_eq(line: &str) -> Option<usize> {
    let bytes = line.as_bytes();
    for (i, &b) in bytes.iter().enumerate() {
        if b != b'=' {
            continue;
        }
        // Skip if preceded by !, <, >, or = (compound operators)
        if i > 0 && matches!(bytes[i - 1], b'!' | b'<' | b'>' | b'=') {
            continue;
        }
        // Skip if followed by = or ~ or > (==, =~, =>)
        if i + 1 < bytes.len() && matches!(bytes[i + 1], b'=' | b'~' | b'>') {
            continue;
        }
        return Some(i);
    }
    None
}