perl-lsp 0.3.0

A Perl LSP server built on tree-sitter-perl and tower-lsp
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
use super::*;

#[test]
fn test_detect_variable_context() {
    let source = "my $x = $";
    let ctx = detect_cursor_context(source, Point::new(0, 9), None);
    assert_eq!(ctx, CursorContext::Variable { sigil: '$' });
}

#[test]
fn test_detect_method_context() {
    let source = "my $obj = Foo->new; $obj->";
    // Column 26 = after the `>` in `->`
    let ctx = detect_cursor_context(source, Point::new(0, 26), None);
    assert_eq!(
        ctx,
        CursorContext::Method {
            invocant_type: None,
            invocant_text: "$obj".to_string(),
        }
    );
}

#[test]
fn test_detect_method_context_mid_word() {
    // Typing `$p->mag` should still be Method context
    let source = "$p->mag";
    let ctx = detect_cursor_context(source, Point::new(0, 7), None);
    assert_eq!(
        ctx,
        CursorContext::Method {
            invocant_type: None,
            invocant_text: "$p".to_string(),
        }
    );
}

#[test]
fn test_detect_method_context_class_mid_word() {
    let source = "Foo->ne";
    let ctx = detect_cursor_context(source, Point::new(0, 7), None);
    assert_eq!(
        ctx,
        CursorContext::Method {
            invocant_type: Some(InferredType::ClassName("Foo".to_string())),
            invocant_text: "Foo".to_string(),
        }
    );
}

#[test]
fn test_detect_hashkey_arrow() {
    let source = "$self->{";
    let ctx = detect_cursor_context(source, Point::new(0, 8), None);
    assert_eq!(
        ctx,
        CursorContext::HashKey {
            owner_type: None,
            var_text: "$self".to_string(),
            source_sub: None,
        }
    );
}

#[test]
fn test_detect_hashkey_arrow_midword() {
    let source = "$self->{ho";
    let ctx = detect_cursor_context(source, Point::new(0, 10), None);
    assert_eq!(
        ctx,
        CursorContext::HashKey {
            owner_type: None,
            var_text: "$self".to_string(),
            source_sub: None,
        }
    );
}

#[test]
fn test_detect_hashkey_direct_midword() {
    let source = "$hash{ver";
    let ctx = detect_cursor_context(source, Point::new(0, 9), None);
    assert_eq!(
        ctx,
        CursorContext::HashKey {
            owner_type: None,
            var_text: "$hash".to_string(),
            source_sub: None,
        }
    );
}

#[test]
fn test_detect_hashkey_direct() {
    let source = "$hash{";
    let ctx = detect_cursor_context(source, Point::new(0, 6), None);
    assert_eq!(
        ctx,
        CursorContext::HashKey {
            owner_type: None,
            var_text: "$hash".to_string(),
            source_sub: None,
        }
    );
}

#[test]
fn test_detect_general() {
    let source = "my $x = foo";
    let ctx = detect_cursor_context(source, Point::new(0, 11), None);
    assert_eq!(ctx, CursorContext::General);
}

#[test]
fn test_detect_class_method_context() {
    let source = "Calculator->";
    let ctx = detect_cursor_context(source, Point::new(0, 12), None);
    assert_eq!(
        ctx,
        CursorContext::Method {
            invocant_type: Some(InferredType::ClassName("Calculator".to_string())),
            invocant_text: "Calculator".to_string(),
        }
    );
}

fn parse(source: &str) -> Tree {
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    parser.parse(source, None).unwrap()
}

#[test]
fn test_find_call_context_function() {
    let source = "sub greet { }\ngreet(";
    let tree = parse(source);
    let ctx = find_call_context(&tree, source.as_bytes(), Point::new(1, 6)).unwrap();
    assert_eq!(ctx.name, "greet");
    assert!(!ctx.is_method);
    assert_eq!(ctx.active_param, 0);
}

#[test]
fn test_find_call_context_with_args() {
    let source = "sub foo { }\nfoo(1, 2, ";
    let tree = parse(source);
    let ctx = find_call_context(&tree, source.as_bytes(), Point::new(1, 10)).unwrap();
    assert_eq!(ctx.name, "foo");
    assert_eq!(ctx.active_param, 2);
}

/// Regression: cursor inside a single-arg call's string literal
/// (e.g. `url_for('Users#list')` with cursor on the `s` of `Users`)
/// must report `active_param = 0`. Before the fix, `active_slot_in_node`
/// iterated the string_literal's INTERNAL children (the lone
/// `string_content`) and counted it as a slot once the cursor
/// reached its end boundary — making dispatch completion die at
/// exactly the boundary where users expect it to narrow by the
/// typed content. Live symptom: in nvim, typing inside the
/// quotes randomly flipped the completion on/off (vs the stable
/// `active_param = 0` needed to surface handlers).
#[test]
fn test_call_context_cursor_inside_single_string_arg() {
    let source = "$c->url_for('Users#list');";
    let tree = parse(source);
    for col in 12..=23 {
        let ctx = find_call_context(&tree, source.as_bytes(), Point::new(0, col)).unwrap();
        assert_eq!(
            ctx.active_param, 0,
            "cursor at col {} inside `url_for('Users#list')` must be active_param=0; \
                 got {}",
            col, ctx.active_param,
        );
    }
}

#[test]
fn test_call_context_key_position() {
    // Complete call so tree-sitter can parse it
    let source = "sub foo { }\nfoo(host => 'x', port => 8080);";
    let tree = parse(source);
    // Cursor at the `p` of `port` (column 17) — at key position after first `, `
    let ctx = find_call_context(&tree, source.as_bytes(), Point::new(1, 17)).unwrap();
    assert!(ctx.at_key_position);
    assert!(ctx.used_keys.contains("host"));
}

#[test]
fn test_selection_ranges_basic() {
    let source = "my $x = 1;";
    let tree = parse(source);
    let ranges = selection_ranges(&tree, Point::new(0, 3));
    assert!(!ranges.is_empty());
    // Innermost should be the variable node
    assert!(ranges.len() >= 2);
}

fn build_fa(source: &str) -> (Tree, crate::file_analysis::FileAnalysis) {
    let tree = parse(source);
    let fa = crate::builder::build(&tree, source.as_bytes());
    (tree, fa)
}

#[test]
fn test_tree_context_method_on_function_call() {
    // get_config()-> should detect Method with HashRef type
    let source = "sub get_config {\n    return { host => 1 };\n}\nget_config()->";
    let (tree, fa) = build_fa(source);
    // Cursor at end of line 3 (after "->")
    let ctx = detect_cursor_context_tree(&tree, source.as_bytes(), Point::new(3, 14), &fa);
    assert!(
        matches!(ctx, Some(CursorContext::Method { ref invocant_type, .. }) if *invocant_type == Some(InferredType::HashRef)),
        "expected Method with HashRef type, got {:?}",
        ctx,
    );
}

#[test]
fn test_tree_context_method_on_chained_call() {
    // $f->get_bar()-> where get_bar returns Object(Bar)
    let source = "package Foo;\nsub new { bless {}, shift }\nsub get_bar {\n    return Bar->new();\n}\npackage Bar;\nsub new { bless {}, shift }\npackage main;\nmy $f = Foo->new();\n$f->get_bar()->";
    let (tree, fa) = build_fa(source);
    // Line 9: $f->get_bar()->   cursor at end
    let ctx = detect_cursor_context_tree(&tree, source.as_bytes(), Point::new(9, 15), &fa);
    assert!(
        matches!(ctx, Some(CursorContext::Method { ref invocant_type, .. })
                if invocant_type.as_ref().and_then(|t| t.class_name()) == Some("Bar")),
        "expected Method with Object(Bar) type, got {:?}",
        ctx,
    );
}

#[test]
fn test_tree_context_hashkey_on_chained_call() {
    // $calc->get_self->get_config->{ should detect HashKey with resolved type
    let source = "\
package Calculator;
sub new { bless {}, shift }
sub get_self {
    my ($self) = @_;
    return $self;
}
sub get_config {
    return { host => 'localhost', port => 5432 };
}
package main;
my $calc = Calculator->new();
$calc->get_self->get_config->{";
    let (tree, fa) = build_fa(source);
    // Last line: "$calc->get_self->get_config->{"
    let cursor = Point::new(11, 30); // after "{"
    let ctx = detect_cursor_context_tree(&tree, source.as_bytes(), cursor, &fa);
    assert!(
        matches!(ctx, Some(CursorContext::HashKey { ref owner_type, ref source_sub, .. })
                if *owner_type == Some(InferredType::HashRef) && *source_sub == Some("get_config".to_string())),
        "expected HashKey with HashRef type and get_config source, got {:?}",
        ctx,
    );
}

#[test]
fn test_tree_context_simple_var_method() {
    // $obj-> with nothing after: tree-based detection resolves the type
    let source = "my $obj = Foo->new();\n$obj->";
    let (tree, fa) = build_fa(source);
    let ctx = detect_cursor_context_tree(&tree, source.as_bytes(), Point::new(1, 6), &fa);
    assert_eq!(
        ctx,
        Some(CursorContext::Method {
            invocant_type: Some(InferredType::ClassName("Foo".to_string())),
            invocant_text: "$obj".to_string(),
        })
    );

    // Text-based fallback also resolves the type
    let ctx = detect_cursor_context(source, Point::new(1, 6), Some(&fa));
    assert_eq!(
        ctx,
        CursorContext::Method {
            invocant_type: Some(InferredType::ClassName("Foo".to_string())),
            invocant_text: "$obj".to_string(),
        }
    );
}

#[test]
fn test_use_context_module_prefix() {
    let source = "use Mojo::Ba";
    let ctx = detect_cursor_context(source, Point::new(0, 12), None);
    assert_eq!(
        ctx,
        CursorContext::UseStatement {
            module_prefix: "Mojo::Ba".to_string(),
            in_import_list: false,
            module_name: None,
        }
    );
}

#[test]
fn test_use_context_empty_prefix() {
    let source = "use ";
    let ctx = detect_cursor_context(source, Point::new(0, 4), None);
    assert_eq!(
        ctx,
        CursorContext::UseStatement {
            module_prefix: String::new(),
            in_import_list: false,
            module_name: None,
        }
    );
}

#[test]
fn test_use_context_import_list_qw() {
    let source = "use List::Util qw(ma";
    let ctx = detect_cursor_context(source, Point::new(0, 20), None);
    assert_eq!(
        ctx,
        CursorContext::UseStatement {
            module_prefix: String::new(),
            in_import_list: true,
            module_name: Some("List::Util".to_string()),
        }
    );
}

#[test]
fn test_use_context_import_list_bare_string() {
    let source = "use Foo 'ba";
    let ctx = detect_cursor_context(source, Point::new(0, 11), None);
    assert_eq!(
        ctx,
        CursorContext::UseStatement {
            module_prefix: String::new(),
            in_import_list: true,
            module_name: Some("Foo".to_string()),
        }
    );
}

#[test]
fn test_use_context_skips_pragmas() {
    let source = "use strict";
    let ctx = detect_cursor_context(source, Point::new(0, 10), None);
    assert_eq!(ctx, CursorContext::General);
}

#[test]
fn test_require_context_module_prefix() {
    let source = "require DBI";
    let ctx = detect_cursor_context(source, Point::new(0, 11), None);
    assert_eq!(
        ctx,
        CursorContext::UseStatement {
            module_prefix: "DBI".to_string(),
            in_import_list: false,
            module_name: None,
        }
    );
}

#[test]
fn test_detect_qualified_path_basic() {
    let source = "my $x = Math::Util::";
    let ctx = detect_cursor_context(source, Point::new(0, 20), None);
    assert_eq!(
        ctx,
        CursorContext::QualifiedPath { package: "Math::Util".to_string() },
    );
}

#[test]
fn test_detect_qualified_path_midword() {
    // Cursor mid-typed-name: `Math::Util::squ|` — should still
    // detect Math::Util as the package being qualified against.
    let source = "my $x = Math::Util::squ";
    let ctx = detect_cursor_context(source, Point::new(0, 23), None);
    assert_eq!(
        ctx,
        CursorContext::QualifiedPath { package: "Math::Util".to_string() },
    );
}

/// Unicode word characters in package names (Perl identifiers under
/// `use utf8` accept Unicode letters — `Acmé::Util`, `Münch::Helpers`,
/// etc.). Byte-wise walkback would stop at a UTF-8 continuation byte
/// and yield the wrong package text; the character-aware walkback
/// has to consume `é` / `ü` / etc. as single chars.
///
/// Marker for future work: ideally the tree-sitter parser tells us
/// the qualified-name span directly so we don't reimplement Perl's
/// identifier rules in the text walkback. The current case is the
/// common one (text walkback inside detect_cursor_context).
#[test]
fn test_detect_qualified_path_with_unicode_segment() {
    let source = "my $x = Acmé::Util::";
    // Point.column is a byte offset (`é` is 2 bytes), not a char
    // count — using `source.len()` keeps us aligned with the rest
    // of the detection path which slices by byte.
    let ctx = detect_cursor_context(source, Point::new(0, source.len()), None);
    assert_eq!(
        ctx,
        CursorContext::QualifiedPath { package: "Acmé::Util".to_string() },
    );
}