perl-module 0.16.0

Perl module resolution, import analysis, and refactoring — unified facade
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
//! Integration tests for go-to-definition module resolution scenarios.
//!
//! These tests cover the end-to-end resolution pipeline used when the LSP
//! processes `use` statements for go-to-definition:
//!
//! 1. System-installed modules via @INC (`use File::Basename`)
//! 2. Workspace modules with custom include paths (`use lib 'lib'; use MyApp::Model`)
//! 3. Parent/base module resolution (`use parent 'Base::Class'`)
//! 4. Graceful not-found handling (no crash)

use perl_module::resolution::{ModuleUriResolution, resolve_module_path, resolve_module_uri};
use std::path::PathBuf;
use std::time::Duration;

// ============================================================================
// Scenario 1: System @INC resolution (e.g., `use File::Basename`)
// ============================================================================

mod system_inc_resolution {
    use super::*;

    #[test]
    fn resolves_module_from_simulated_system_inc() -> Result<(), Box<dyn std::error::Error>> {
        // Simulate a system @INC directory containing File/Basename.pm
        let temp = tempfile::tempdir()?;
        let inc_dir = temp.path().join("perl5lib");
        let module_file = inc_dir.join("File").join("Basename.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package File::Basename;\nuse strict;\n1;")?;

        let result = resolve_module_uri(
            "File::Basename",
            &[],
            &[],
            &[],
            true,
            &[inc_dir],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(
                    uri.ends_with("File/Basename.pm"),
                    "expected File/Basename.pm in URI, got: {uri}"
                );
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn system_inc_not_searched_when_disabled() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let inc_dir = temp.path().join("perl5lib");
        let module_file = inc_dir.join("File").join("Basename.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package File::Basename; 1;")?;

        let result = resolve_module_uri(
            "File::Basename",
            &[],
            &[],
            &[],
            false, // system @INC disabled
            &[inc_dir],
            Duration::from_millis(200),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
        Ok(())
    }

    #[test]
    fn multiple_inc_dirs_searched_in_order() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let site_lib = temp.path().join("site_perl");
        let core_lib = temp.path().join("core_perl");

        // Module exists in both dirs -- site_perl should win
        let site_file = site_lib.join("File").join("Basename.pm");
        let core_file = core_lib.join("File").join("Basename.pm");

        std::fs::create_dir_all(site_file.parent().ok_or("no parent")?)?;
        std::fs::create_dir_all(core_file.parent().ok_or("no parent")?)?;
        std::fs::write(&site_file, "# site version")?;
        std::fs::write(&core_file, "# core version")?;

        let result = resolve_module_uri(
            "File::Basename",
            &[],
            &[],
            &[],
            true,
            &[site_lib.clone(), core_lib],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(uri.contains("site_perl"), "first @INC entry should win, got: {uri}");
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }
}

// ============================================================================
// Scenario 2: Workspace modules with custom include paths
// (simulating `use lib 'lib'; use MyApp::Model`)
// ============================================================================

mod workspace_include_path_resolution {
    use super::*;

    #[test]
    fn resolves_module_under_lib_include_path() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        let module_file = workspace.join("lib").join("MyApp").join("Model.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package MyApp::Model;\nuse strict;\n1;")?;

        // This simulates the effect of `use lib 'lib'` -- the 'lib' directory
        // is configured as an include path
        let ws_uri = url::Url::from_file_path(&workspace).map_err(|()| "bad URI")?.to_string();

        let result = resolve_module_uri(
            "MyApp::Model",
            &[],
            &[ws_uri],
            &["lib".to_string()],
            false,
            &[],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(uri.ends_with("MyApp/Model.pm"), "expected MyApp/Model.pm, got: {uri}");
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn resolves_module_from_custom_include_path() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        // Module lives in a custom path, not the standard 'lib'
        let module_file = workspace.join("local_modules").join("MyApp").join("Model.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package MyApp::Model; 1;")?;

        let ws_uri = url::Url::from_file_path(&workspace).map_err(|()| "bad URI")?.to_string();

        let result = resolve_module_uri(
            "MyApp::Model",
            &[],
            &[ws_uri],
            &["local_modules".to_string()],
            false,
            &[],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(
                    uri.contains("local_modules") && uri.ends_with("MyApp/Model.pm"),
                    "expected local_modules/MyApp/Model.pm, got: {uri}"
                );
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn multiple_include_paths_searched_in_priority_order() -> Result<(), Box<dyn std::error::Error>>
    {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");

        // Module in both 'vendor' and 'lib' -- 'vendor' is listed first
        let vendor_file = workspace.join("vendor").join("MyApp").join("Model.pm");
        let lib_file = workspace.join("lib").join("MyApp").join("Model.pm");

        std::fs::create_dir_all(vendor_file.parent().ok_or("no parent")?)?;
        std::fs::create_dir_all(lib_file.parent().ok_or("no parent")?)?;
        std::fs::write(&vendor_file, "# vendor version")?;
        std::fs::write(&lib_file, "# lib version")?;

        let ws_uri = url::Url::from_file_path(&workspace).map_err(|()| "bad URI")?.to_string();

        let result = resolve_module_uri(
            "MyApp::Model",
            &[],
            &[ws_uri],
            &["vendor".to_string(), "lib".to_string()],
            false,
            &[],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(uri.contains("vendor"), "first include path should win, got: {uri}");
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn resolve_module_path_with_lib_include() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        let module_file = workspace.join("lib").join("MyApp").join("Model.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package MyApp::Model; 1;")?;

        let result = resolve_module_path(&workspace, "MyApp::Model", &["lib".to_string()]);

        assert_eq!(result, Some(module_file));
        Ok(())
    }
}

// ============================================================================
// Scenario 3: use parent 'Base::Class' resolution
// (the module reference extraction happens in perl-module-reference,
//  but the resolution pipeline is tested here)
// ============================================================================

mod parent_base_module_resolution {
    use super::*;

    #[test]
    fn resolves_parent_module_from_workspace() -> Result<(), Box<dyn std::error::Error>> {
        // When the LSP extracts "Base::Class" from `use parent 'Base::Class'`,
        // it passes that module name to the resolution pipeline.
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        let module_file = workspace.join("lib").join("Base").join("Class.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package Base::Class;\nsub new { bless {}, shift }\n1;")?;

        let ws_uri = url::Url::from_file_path(&workspace).map_err(|()| "bad URI")?.to_string();

        let result = resolve_module_uri(
            "Base::Class",
            &[],
            &[ws_uri],
            &["lib".to_string()],
            false,
            &[],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(uri.ends_with("Base/Class.pm"), "expected Base/Class.pm, got: {uri}");
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn resolves_parent_module_from_system_inc() -> Result<(), Box<dyn std::error::Error>> {
        // Parent module in system @INC (e.g., `use parent 'Exporter'`)
        let temp = tempfile::tempdir()?;
        let inc_dir = temp.path().join("perl5lib");
        let module_file = inc_dir.join("Exporter.pm");

        std::fs::create_dir_all(&inc_dir)?;
        std::fs::write(&module_file, "package Exporter; 1;")?;

        let result = resolve_module_uri(
            "Exporter",
            &[],
            &[],
            &[],
            true,
            &[inc_dir],
            Duration::from_millis(200),
        );

        match result {
            ModuleUriResolution::Resolved(uri) => {
                assert!(uri.ends_with("Exporter.pm"), "expected Exporter.pm, got: {uri}");
            }
            other => return Err(format!("expected Resolved, got {other:?}").into()),
        }
        Ok(())
    }

    #[test]
    fn resolve_module_path_for_parent_module() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        let module_file = workspace.join("lib").join("Base").join("Class.pm");

        std::fs::create_dir_all(module_file.parent().ok_or("no parent")?)?;
        std::fs::write(&module_file, "package Base::Class; 1;")?;

        let result = resolve_module_path(&workspace, "Base::Class", &["lib".to_string()]);
        assert_eq!(result, Some(module_file));
        Ok(())
    }
}

// ============================================================================
// Scenario 4: Graceful error handling (not found, no crash)
// ============================================================================

mod graceful_error_handling {
    use super::*;

    #[test]
    fn module_not_found_returns_not_found_not_panic() {
        let result = resolve_module_uri(
            "Nonexistent::Module::That::Does::Not::Exist",
            &[],
            &[],
            &[],
            false,
            &[],
            Duration::from_millis(100),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
    }

    #[test]
    fn module_not_found_with_workspace_returns_not_found() -> Result<(), Box<dyn std::error::Error>>
    {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path().join("project");
        std::fs::create_dir_all(workspace.join("lib"))?;

        let ws_uri = url::Url::from_file_path(&workspace).map_err(|()| "bad URI")?.to_string();

        let result = resolve_module_uri(
            "Missing::Module",
            &[],
            &[ws_uri],
            &["lib".to_string()],
            false,
            &[],
            Duration::from_millis(200),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
        Ok(())
    }

    #[test]
    fn module_not_found_with_system_inc_returns_not_found() -> Result<(), Box<dyn std::error::Error>>
    {
        let temp = tempfile::tempdir()?;
        let inc_dir = temp.path().join("perl5lib");
        std::fs::create_dir_all(&inc_dir)?;

        let result = resolve_module_uri(
            "Missing::Module",
            &[],
            &[],
            &[],
            true,
            &[inc_dir],
            Duration::from_millis(200),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
        Ok(())
    }

    #[test]
    fn empty_module_name_does_not_crash() {
        let result = resolve_module_uri(
            "",
            &[],
            &[],
            &[],
            true,
            &[PathBuf::from("/nonexistent")],
            Duration::from_millis(100),
        );

        // Should return gracefully, not crash
        assert!(
            result == ModuleUriResolution::NotFound || result == ModuleUriResolution::TimedOut,
            "unexpected result: {result:?}"
        );
    }

    #[test]
    fn nonexistent_workspace_folder_does_not_crash() {
        let result = resolve_module_uri(
            "Foo::Bar",
            &[],
            &["file:///does/not/exist/at/all".to_string()],
            &["lib".to_string()],
            false,
            &[],
            Duration::from_millis(100),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
    }

    #[test]
    fn nonexistent_system_inc_path_does_not_crash() {
        let result = resolve_module_uri(
            "Foo::Bar",
            &[],
            &[],
            &[],
            true,
            &[PathBuf::from("/absolutely/nonexistent/perl/lib")],
            Duration::from_millis(100),
        );

        assert_eq!(result, ModuleUriResolution::NotFound);
    }

    #[test]
    fn timeout_returns_timed_out_not_panic() {
        // Create a scenario that will definitely time out
        let workspace_folders: Vec<String> =
            (0..10_000).map(|i| format!("file:///workspace-{i}")).collect();

        let result = resolve_module_uri(
            "Never::Found",
            &[],
            &workspace_folders,
            &["lib".to_string()],
            false,
            &[],
            Duration::from_nanos(1),
        );

        assert_eq!(result, ModuleUriResolution::TimedOut);
    }

    #[test]
    fn resolve_module_path_with_nonexistent_root_does_not_crash() {
        let root = PathBuf::from("/nonexistent/workspace/root");
        let result = resolve_module_path(&root, "Some::Module", &["lib".to_string()]);

        // Should return Some (the fallback path), not panic
        assert!(result.is_some());
    }

    #[test]
    fn unicode_module_name_does_not_crash() {
        let result = resolve_module_uri(
            "\u{1F600}::Module",
            &[],
            &[],
            &[],
            false,
            &[],
            Duration::from_millis(100),
        );

        // Should handle gracefully
        assert_eq!(result, ModuleUriResolution::NotFound);
    }
}