perl-workspace 0.13.3

Workspace file discovery, indexing, and observability for Perl
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! Visibility resolution for symbols at a given query point.
//!
//! Resolves which symbols are visible at a `(file_id, byte_offset, scope_id)`
//! query point by consulting:
//!
//! 1. The file's own entities (local lexical/package scope)
//! 2. The file's import specs (from [`ImportExportIndex`])
//! 3. The workspace's export sets (from [`ImportExportIndex`])
//!
//! For each import in the file:
//!
//! - `UseExplicitList` with `Explicit(names)` → make those names visible
//!   with source [`VisibleSymbolSource::ExplicitImport`]
//! - `UseEmpty` → suppress all defaults (no symbols visible from this module)
//! - `Use` (bare) → make the module's `@EXPORT` (default_exports) visible
//!   with source [`VisibleSymbolSource::DefaultExport`]
//! - `UseTag` with `Tags(tags)` → make all symbols in those tags visible
//!   with source [`VisibleSymbolSource::ExportTag`]

use perl_semantic_facts::{
    Confidence, EntityKind, FileId, ImportKind, ImportSymbols, ScopeId, VisibleSymbol,
    VisibleSymbolContext, VisibleSymbolSource,
};

use super::imports::ImportExportIndex;
use crate::workspace::workspace_index::FileFactShard;

/// Compute the list of symbols visible at a given query point.
///
/// Visibility is resolved from multiple sources in priority order:
///
/// 1. **Local lexical scope** — entities whose scope matches `scope_id` and
///    whose byte span encloses `byte_offset`.
/// 2. **Local package scope** — file-level subroutines, constants, and
///    variables visible throughout the file.
/// 3. **Explicit imports** — `use Foo qw(a b)` makes `a` and `b` visible.
/// 4. **Default exports** — bare `use Foo` makes `@EXPORT` symbols visible.
/// 5. **Export tags** — `use Foo ':tag'` makes tag members visible.
/// 6. **Constants** — `use constant` declarations.
/// 7. **Generated members** — framework-synthesized accessors (Moo/Moose).
pub fn visible_symbols_at(
    file_id: FileId,
    byte_offset: u32,
    scope_id: Option<ScopeId>,
    shard: &FileFactShard,
    import_export_index: &ImportExportIndex,
) -> Vec<VisibleSymbol> {
    let mut result: Vec<VisibleSymbol> = Vec::new();

    // ── 1. Local lexical scope ──
    collect_local_lexical(&mut result, shard, byte_offset, scope_id);

    // ── 2. Local package scope ──
    collect_local_package(&mut result, shard);

    // ── 3–5. Import-derived visibility ──
    collect_import_visibility(&mut result, file_id, import_export_index);

    // ── 6. Constants (use constant) ──
    collect_constants(&mut result, shard);

    // ── 7. Generated members ──
    collect_generated_members(&mut result, shard);

    result
}

// ── Private helpers ──

/// Collect entities from the local lexical scope.
///
/// An entity is considered lexically visible when:
/// - It has a matching `scope_id` (if the query provides one), AND
/// - Its anchor span starts at or before `byte_offset`.
///
/// Variables are the primary lexical-scope entities.
fn collect_local_lexical(
    result: &mut Vec<VisibleSymbol>,
    shard: &FileFactShard,
    byte_offset: u32,
    scope_id: Option<ScopeId>,
) {
    for entity in &shard.entities {
        // Only variables are lexically scoped in Perl.
        if entity.kind != EntityKind::Variable {
            continue;
        }

        // If we have a scope_id query, require a matching scope.
        if let Some(query_scope) = scope_id {
            match entity.scope_id {
                Some(entity_scope) if entity_scope == query_scope => {}
                Some(_) => continue,
                // Entities without a scope are file-level; include them.
                None => {}
            }
        }

        // The entity must be declared at or before the query offset.
        let declared_before_offset = entity
            .anchor_id
            .and_then(|aid| shard.anchors.iter().find(|a| a.id == aid))
            .map(|anchor| anchor.span_start_byte <= byte_offset)
            .unwrap_or(false);

        if !declared_before_offset {
            continue;
        }

        result.push(VisibleSymbol {
            name: bare_name(&entity.canonical_name),
            entity_id: Some(entity.id),
            source: VisibleSymbolSource::LocalLexical,
            confidence: entity.confidence,
            context: None,
        });
    }
}

/// Collect file-level subroutines and package-scoped entities.
///
/// Subroutines, methods, and package declarations are visible throughout
/// the file regardless of byte offset.
fn collect_local_package(result: &mut Vec<VisibleSymbol>, shard: &FileFactShard) {
    for entity in &shard.entities {
        match entity.kind {
            EntityKind::Subroutine | EntityKind::Method | EntityKind::Package => {}
            _ => continue,
        }

        // Skip entities that are definition occurrences from other files
        // (they would not be local).

        result.push(VisibleSymbol {
            name: bare_name(&entity.canonical_name),
            entity_id: Some(entity.id),
            source: VisibleSymbolSource::LocalPackage,
            confidence: entity.confidence,
            context: None,
        });
    }
}

/// Collect symbols made visible through import statements.
///
/// Walks the file's import specs and resolves each against the workspace
/// export index:
///
/// - `UseExplicitList` + `Explicit(names)` → ExplicitImport
/// - `UseEmpty` → suppress defaults (skip)
/// - `Use` (bare) → DefaultExport from `@EXPORT`
/// - `UseTag` + `Tags(tags)` → ExportTag from `%EXPORT_TAGS`
/// - `RequireThenImport` + `Explicit(names)` → ExplicitImport
fn collect_import_visibility(
    result: &mut Vec<VisibleSymbol>,
    file_id: FileId,
    import_export_index: &ImportExportIndex,
) {
    let imports = import_export_index.get_imports_for_file(file_id);

    for import in imports {
        let context = VisibleSymbolContext::new(
            Some(import.module.clone()),
            import.anchor_id,
            import_export_index.get_exports_for_module(&import.module).and_then(|es| es.anchor_id),
        );

        match import.kind {
            ImportKind::UseExplicitList => {
                // `use Foo qw(a b)` → make explicit names visible.
                if let ImportSymbols::Explicit(ref names) = import.symbols {
                    for name in names {
                        result.push(VisibleSymbol {
                            name: name.clone(),
                            entity_id: None,
                            source: VisibleSymbolSource::ExplicitImport,
                            confidence: Confidence::High,
                            context: Some(context.clone()),
                        });
                    }
                }
            }

            ImportKind::UseEmpty => {
                // `use Foo ()` → suppress all defaults. No symbols visible.
            }

            ImportKind::Use => {
                // Bare `use Foo` → make @EXPORT (default_exports) visible.
                if let Some(export_set) = import_export_index.get_exports_for_module(&import.module)
                {
                    for name in &export_set.default_exports {
                        result.push(VisibleSymbol {
                            name: name.clone(),
                            entity_id: None,
                            source: VisibleSymbolSource::DefaultExport,
                            confidence: export_set.confidence,
                            context: Some(context.clone()),
                        });
                    }
                }
            }

            ImportKind::UseTag => {
                // `use Foo ':tag'` → make tag members visible.
                if let ImportSymbols::Tags(ref tag_names) = import.symbols {
                    if let Some(export_set) =
                        import_export_index.get_exports_for_module(&import.module)
                    {
                        for tag_name in tag_names {
                            for tag in &export_set.tags {
                                if tag.name == *tag_name {
                                    for member in &tag.members {
                                        result.push(VisibleSymbol {
                                            name: member.clone(),
                                            entity_id: None,
                                            source: VisibleSymbolSource::ExportTag,
                                            confidence: export_set.confidence,
                                            context: Some(context.clone()),
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
            }

            ImportKind::RequireThenImport => {
                // `require Foo; Foo->import(qw(x y))` → explicit names.
                if let ImportSymbols::Explicit(ref names) = import.symbols {
                    for name in names {
                        result.push(VisibleSymbol {
                            name: name.clone(),
                            entity_id: None,
                            source: VisibleSymbolSource::ExplicitImport,
                            confidence: import.confidence,
                            context: Some(context.clone()),
                        });
                    }
                }
            }

            ImportKind::UseConstant | ImportKind::Require | ImportKind::DynamicRequire => {
                // UseConstant is handled separately in collect_constants.
                // Require without import and DynamicRequire do not make
                // symbols visible in the importing file's namespace.
            }
        }
    }
}

/// Collect constants declared via `use constant`.
///
/// Constants are entities with kind `Constant` and occurrence kind
/// `Definition` in the shard.
fn collect_constants(result: &mut Vec<VisibleSymbol>, shard: &FileFactShard) {
    for entity in &shard.entities {
        if entity.kind != EntityKind::Constant {
            continue;
        }

        result.push(VisibleSymbol {
            name: bare_name(&entity.canonical_name),
            entity_id: Some(entity.id),
            source: VisibleSymbolSource::Constant,
            confidence: entity.confidence,
            context: None,
        });
    }
}

/// Collect generated members (Moo/Moose accessors, etc.).
fn collect_generated_members(result: &mut Vec<VisibleSymbol>, shard: &FileFactShard) {
    for entity in &shard.entities {
        if entity.kind != EntityKind::GeneratedMember {
            continue;
        }

        result.push(VisibleSymbol {
            name: bare_name(&entity.canonical_name),
            entity_id: Some(entity.id),
            source: VisibleSymbolSource::Generated,
            confidence: entity.confidence,
            context: None,
        });
    }
}

/// Extract the bare name from a potentially qualified name.
///
/// `"Foo::Bar::baz"` → `"baz"`, `"baz"` → `"baz"`.
fn bare_name(qualified: &str) -> String {
    match qualified.rsplit_once("::") {
        Some((_, bare)) => bare.to_string(),
        None => qualified.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use perl_semantic_facts::{
        AnchorFact, AnchorId, Confidence, EntityFact, EntityId, EntityKind, ExportSet, ExportTag,
        ImportKind, ImportSpec, ImportSymbols, Provenance, ScopeId,
    };

    /// Build a minimal shard with one subroutine entity.
    fn shard_with_sub(file_id: FileId) -> FileFactShard {
        FileFactShard {
            source_uri: "file:///lib/Main.pm".to_string(),
            file_id,
            content_hash: 1,
            anchors_hash: None,
            entities_hash: None,
            occurrences_hash: None,
            edges_hash: None,
            anchors: vec![AnchorFact {
                id: AnchorId(10),
                file_id,
                span_start_byte: 0,
                span_end_byte: 20,
                scope_id: None,
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            entities: vec![EntityFact {
                id: EntityId(100),
                kind: EntityKind::Subroutine,
                canonical_name: "Main::do_stuff".to_string(),
                anchor_id: Some(AnchorId(10)),
                scope_id: None,
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            occurrences: vec![],
            edges: vec![],
        }
    }

    /// Build a shard with a lexical variable.
    fn shard_with_variable(file_id: FileId) -> FileFactShard {
        FileFactShard {
            source_uri: "file:///lib/Main.pm".to_string(),
            file_id,
            content_hash: 2,
            anchors_hash: None,
            entities_hash: None,
            occurrences_hash: None,
            edges_hash: None,
            anchors: vec![AnchorFact {
                id: AnchorId(20),
                file_id,
                span_start_byte: 5,
                span_end_byte: 10,
                scope_id: Some(ScopeId(1)),
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            entities: vec![EntityFact {
                id: EntityId(200),
                kind: EntityKind::Variable,
                canonical_name: "$count".to_string(),
                anchor_id: Some(AnchorId(20)),
                scope_id: Some(ScopeId(1)),
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            occurrences: vec![],
            edges: vec![],
        }
    }

    /// Build a shard with a constant entity.
    fn shard_with_constant(file_id: FileId) -> FileFactShard {
        FileFactShard {
            source_uri: "file:///lib/Main.pm".to_string(),
            file_id,
            content_hash: 3,
            anchors_hash: None,
            entities_hash: None,
            occurrences_hash: None,
            edges_hash: None,
            anchors: vec![AnchorFact {
                id: AnchorId(30),
                file_id,
                span_start_byte: 0,
                span_end_byte: 15,
                scope_id: None,
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            entities: vec![EntityFact {
                id: EntityId(300),
                kind: EntityKind::Constant,
                canonical_name: "MAX_SIZE".to_string(),
                anchor_id: Some(AnchorId(30)),
                scope_id: None,
                provenance: Provenance::ExactAst,
                confidence: Confidence::High,
            }],
            occurrences: vec![],
            edges: vec![],
        }
    }

    /// Build a shard with a generated member entity.
    fn shard_with_generated(file_id: FileId) -> FileFactShard {
        FileFactShard {
            source_uri: "file:///lib/Main.pm".to_string(),
            file_id,
            content_hash: 4,
            anchors_hash: None,
            entities_hash: None,
            occurrences_hash: None,
            edges_hash: None,
            anchors: vec![AnchorFact {
                id: AnchorId(40),
                file_id,
                span_start_byte: 0,
                span_end_byte: 20,
                scope_id: None,
                provenance: Provenance::FrameworkSynthesis,
                confidence: Confidence::Medium,
            }],
            entities: vec![EntityFact {
                id: EntityId(400),
                kind: EntityKind::GeneratedMember,
                canonical_name: "MyClass::name".to_string(),
                anchor_id: Some(AnchorId(40)),
                scope_id: None,
                provenance: Provenance::FrameworkSynthesis,
                confidence: Confidence::Medium,
            }],
            occurrences: vec![],
            edges: vec![],
        }
    }

    fn empty_shard(file_id: FileId) -> FileFactShard {
        FileFactShard {
            source_uri: "file:///lib/Main.pm".to_string(),
            file_id,
            content_hash: 0,
            anchors_hash: None,
            entities_hash: None,
            occurrences_hash: None,
            edges_hash: None,
            anchors: vec![],
            entities: vec![],
            occurrences: vec![],
            edges: vec![],
        }
    }

    fn sample_export_set() -> ExportSet {
        ExportSet {
            default_exports: vec!["foo".to_string(), "bar".to_string()],
            optional_exports: vec!["baz".to_string()],
            tags: vec![ExportTag {
                name: "all".to_string(),
                members: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
            }],
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            module_name: Some("Foo".to_string()),
            anchor_id: Some(AnchorId(500)),
        }
    }

    // ── Local package scope ──

    #[test]
    fn local_subroutine_is_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_sub(file_id);
        let index = ImportExportIndex::new();

        let symbols = visible_symbols_at(file_id, 50, None, &shard, &index);

        let sub_sym = symbols.iter().find(|s| s.name == "do_stuff");
        assert!(sub_sym.is_some(), "subroutine should be visible");
        let sym = sub_sym.ok_or("expected visible symbol")?;
        assert_eq!(sym.source, VisibleSymbolSource::LocalPackage);
        assert!(sym.context.is_none());
        Ok(())
    }

    // ── Local lexical scope ──

    #[test]
    fn lexical_variable_visible_in_same_scope() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_variable(file_id);
        let index = ImportExportIndex::new();

        // Query at offset 15, in scope 1 — variable declared at offset 5.
        let symbols = visible_symbols_at(file_id, 15, Some(ScopeId(1)), &shard, &index);

        let var_sym = symbols.iter().find(|s| s.name == "$count");
        assert!(var_sym.is_some(), "variable should be visible in same scope");
        let sym = var_sym.ok_or("expected visible symbol")?;
        assert_eq!(sym.source, VisibleSymbolSource::LocalLexical);
        Ok(())
    }

    #[test]
    fn lexical_variable_not_visible_in_different_scope() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_variable(file_id);
        let index = ImportExportIndex::new();

        // Query in scope 2 — variable is in scope 1.
        let symbols = visible_symbols_at(file_id, 15, Some(ScopeId(2)), &shard, &index);

        let var_sym = symbols.iter().find(|s| s.name == "$count");
        assert!(var_sym.is_none(), "variable should not be visible in different scope");
        Ok(())
    }

    #[test]
    fn lexical_variable_not_visible_before_declaration() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_variable(file_id);
        let index = ImportExportIndex::new();

        // Query at offset 2, before the variable declared at offset 5.
        let symbols = visible_symbols_at(file_id, 2, Some(ScopeId(1)), &shard, &index);

        let var_sym = symbols.iter().find(|s| s.name == "$count");
        assert!(var_sym.is_none(), "variable should not be visible before declaration");
        Ok(())
    }

    // ── Explicit imports ──

    #[test]
    fn use_explicit_list_makes_names_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::UseExplicitList,
            symbols: ImportSymbols::Explicit(vec!["alpha".to_string(), "beta".to_string()]),
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(100)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        let alpha = symbols.iter().find(|s| s.name == "alpha");
        let beta = symbols.iter().find(|s| s.name == "beta");
        assert!(alpha.is_some(), "alpha should be visible");
        assert!(beta.is_some(), "beta should be visible");

        let a = alpha.ok_or("expected alpha")?;
        assert_eq!(a.source, VisibleSymbolSource::ExplicitImport);
        let ctx = a.context.as_ref().ok_or("expected context")?;
        assert_eq!(ctx.source_module.as_deref(), Some("Foo"));
        Ok(())
    }

    // ── Empty import suppresses defaults ──

    #[test]
    fn use_empty_suppresses_defaults() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        // Register exports for Foo.
        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        // Import with empty list: `use Foo ()`
        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::UseEmpty,
            symbols: ImportSymbols::None,
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(101)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        // No symbols from Foo should be visible.
        let from_foo: Vec<_> = symbols
            .iter()
            .filter(|s| {
                s.context
                    .as_ref()
                    .and_then(|c| c.source_module.as_deref())
                    .map(|m| m == "Foo")
                    .unwrap_or(false)
            })
            .collect();
        assert!(from_foo.is_empty(), "use Foo () should suppress all defaults");
        Ok(())
    }

    // ── Bare use → default exports ──

    #[test]
    fn bare_use_makes_default_exports_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::Use,
            symbols: ImportSymbols::Default,
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(102)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        let foo_sym = symbols.iter().find(|s| s.name == "foo");
        let bar_sym = symbols.iter().find(|s| s.name == "bar");
        assert!(foo_sym.is_some(), "foo should be visible via default export");
        assert!(bar_sym.is_some(), "bar should be visible via default export");

        let f = foo_sym.ok_or("expected foo")?;
        assert_eq!(f.source, VisibleSymbolSource::DefaultExport);
        let ctx = f.context.as_ref().ok_or("expected context")?;
        assert_eq!(ctx.source_module.as_deref(), Some("Foo"));
        assert_eq!(ctx.source_export_anchor_id, Some(AnchorId(500)));

        // baz is in optional_exports only, not default — should NOT be visible.
        let baz_sym = symbols.iter().find(|s| s.name == "baz");
        assert!(baz_sym.is_none(), "baz should not be visible via bare use");
        Ok(())
    }

    // ── Tag import ──

    #[test]
    fn use_tag_makes_tag_members_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::UseTag,
            symbols: ImportSymbols::Tags(vec!["all".to_string()]),
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(103)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        let foo_sym = symbols.iter().find(|s| s.name == "foo");
        let bar_sym = symbols.iter().find(|s| s.name == "bar");
        let baz_sym = symbols.iter().find(|s| s.name == "baz");
        assert!(foo_sym.is_some(), "foo should be visible via :all tag");
        assert!(bar_sym.is_some(), "bar should be visible via :all tag");
        assert!(baz_sym.is_some(), "baz should be visible via :all tag");

        let f = foo_sym.ok_or("expected foo")?;
        assert_eq!(f.source, VisibleSymbolSource::ExportTag);
        let ctx = f.context.as_ref().ok_or("expected context")?;
        assert_eq!(ctx.source_module.as_deref(), Some("Foo"));
        Ok(())
    }

    // ── Constants ──

    #[test]
    fn constants_are_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_constant(file_id);
        let index = ImportExportIndex::new();

        let symbols = visible_symbols_at(file_id, 50, None, &shard, &index);

        let const_sym = symbols.iter().find(|s| s.name == "MAX_SIZE");
        assert!(const_sym.is_some(), "constant should be visible");
        let sym = const_sym.ok_or("expected constant")?;
        assert_eq!(sym.source, VisibleSymbolSource::Constant);
        Ok(())
    }

    // ── Generated members ──

    #[test]
    fn generated_members_are_visible() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_generated(file_id);
        let index = ImportExportIndex::new();

        let symbols = visible_symbols_at(file_id, 50, None, &shard, &index);

        let gen_sym = symbols.iter().find(|s| s.name == "name");
        assert!(gen_sym.is_some(), "generated member should be visible");
        let sym = gen_sym.ok_or("expected generated member")?;
        assert_eq!(sym.source, VisibleSymbolSource::Generated);
        assert_eq!(sym.confidence, Confidence::Medium);
        Ok(())
    }

    // ── RequireThenImport ──

    #[test]
    fn require_then_import_makes_explicit_names_visible() -> Result<(), Box<dyn std::error::Error>>
    {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        let import = ImportSpec {
            module: "Bar".to_string(),
            kind: ImportKind::RequireThenImport,
            symbols: ImportSymbols::Explicit(vec!["x".to_string(), "y".to_string()]),
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(104)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        let x_sym = symbols.iter().find(|s| s.name == "x");
        let y_sym = symbols.iter().find(|s| s.name == "y");
        assert!(x_sym.is_some(), "x should be visible via require+import");
        assert!(y_sym.is_some(), "y should be visible via require+import");

        let x = x_sym.ok_or("expected x")?;
        assert_eq!(x.source, VisibleSymbolSource::ExplicitImport);
        Ok(())
    }

    #[test]
    fn require_then_import_dynamic_symbols_do_not_invent_visibility()
    -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        let import = ImportSpec {
            module: "Bar".to_string(),
            kind: ImportKind::RequireThenImport,
            symbols: ImportSymbols::Dynamic,
            provenance: Provenance::ExactAst,
            confidence: Confidence::Low,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(104)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);

        assert!(symbols.is_empty(), "dynamic import list should not invent exact symbols");
        Ok(())
    }

    // ── No imports, no exports ──

    #[test]
    fn bare_use_with_no_exports_produces_nothing() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        // Bare use of a module with no registered exports.
        let import = ImportSpec {
            module: "Unknown".to_string(),
            kind: ImportKind::Use,
            symbols: ImportSymbols::Default,
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(105)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);
        assert!(symbols.is_empty(), "no symbols should be visible from unknown module");
        Ok(())
    }

    // ── Tag import with non-existent tag ──

    #[test]
    fn use_tag_with_nonexistent_tag_produces_nothing() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::UseTag,
            symbols: ImportSymbols::Tags(vec!["nonexistent".to_string()]),
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(106)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);
        assert!(symbols.is_empty(), "nonexistent tag should produce no symbols");
        Ok(())
    }

    // ── Bare name extraction ──

    #[test]
    fn bare_name_extracts_last_component() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!(bare_name("Foo::Bar::baz"), "baz");
        assert_eq!(bare_name("baz"), "baz");
        assert_eq!(bare_name("A::B"), "B");
        Ok(())
    }

    // ── Combined visibility ──

    #[test]
    fn combined_local_and_import_visibility() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = shard_with_sub(file_id);
        let mut index = ImportExportIndex::new();

        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::UseExplicitList,
            symbols: ImportSymbols::Explicit(vec!["alpha".to_string()]),
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(107)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 50, None, &shard, &index);

        // Local sub should be visible.
        assert!(symbols.iter().any(|s| s.name == "do_stuff"));
        // Imported symbol should be visible.
        assert!(symbols.iter().any(|s| s.name == "alpha"));
        Ok(())
    }

    // ── Context metadata ──

    // ── Property-based tests ──

    mod prop_tests {
        use super::*;
        use proptest::prelude::*;
        use proptest::test_runner::Config as ProptestConfig;

        /// Strategy to generate a valid Perl-like symbol name (1–20 lowercase
        /// ASCII chars).
        fn arb_symbol_name() -> impl Strategy<Value = String> {
            "[a-z_][a-z_0-9]{0,19}".prop_filter("non-empty", |s| !s.is_empty())
        }

        /// Strategy to generate a Perl-like module name (e.g. "Foo", "Bar").
        fn arb_module_name() -> impl Strategy<Value = String> {
            "[A-Z][a-z]{1,9}".prop_filter("non-empty", |s| !s.is_empty())
        }

        /// Strategy to generate a non-empty set of distinct symbol names.
        fn arb_symbol_set(min: usize, max: usize) -> impl Strategy<Value = Vec<String>> {
            prop::collection::hash_set(arb_symbol_name(), min..=max)
                .prop_map(|s| s.into_iter().collect::<Vec<_>>())
        }

        /// Strategy to generate a tag name (e.g. "all", "utils").
        fn arb_tag_name() -> impl Strategy<Value = String> {
            "[a-z]{2,8}"
        }

        // **Validates: Requirements 12.1**
        //
        // Property 9 (explicit import): `use Foo qw(a b)` makes a,b visible
        // with source ExplicitImport.
        proptest! {
            #![proptest_config(ProptestConfig {
                failure_persistence: None,
                ..ProptestConfig::default()
            })]

            #[test]
            fn prop_explicit_import_source_attribution(
                module_name in arb_module_name(),
                symbols in arb_symbol_set(1, 8),
            ) {
                let file_id = FileId(1);
                let shard = empty_shard(file_id);
                let mut index = ImportExportIndex::new();

                let import = ImportSpec {
                    module: module_name.clone(),
                    kind: ImportKind::UseExplicitList,
                    symbols: ImportSymbols::Explicit(symbols.clone()),
                    provenance: Provenance::ExactAst,
                    confidence: Confidence::High,
                    file_id: Some(file_id),
                    anchor_id: Some(AnchorId(100)),
                    scope_id: None,
                };
                index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

                let visible = visible_symbols_at(file_id, 0, None, &shard, &index);

                // Every explicitly imported symbol must appear with ExplicitImport source.
                for sym_name in &symbols {
                    let found = visible.iter().find(|v| v.name == *sym_name);
                    prop_assert!(
                        found.is_some(),
                        "explicit import '{}' should be visible",
                        sym_name
                    );
                    let vs = found.expect("checked above");
                    prop_assert_eq!(
                        &vs.source,
                        &VisibleSymbolSource::ExplicitImport,
                        "explicit import '{}' should have ExplicitImport source",
                        sym_name
                    );
                    // Context should carry the source module.
                    let ctx = vs.context.as_ref();
                    prop_assert!(ctx.is_some(), "explicit import should have context");
                    prop_assert_eq!(
                        ctx.expect("checked above").source_module.as_deref(),
                        Some(module_name.as_str()),
                        "context source_module should match import module"
                    );
                }
            }
        }

        // **Validates: Requirements 12.3**
        //
        // Property 9 (default export): Bare `use Foo` makes @EXPORT symbols
        // visible with source DefaultExport.
        proptest! {
            #![proptest_config(ProptestConfig {
                failure_persistence: None,
                ..ProptestConfig::default()
            })]

            #[test]
            fn prop_default_export_source_attribution(
                module_name in arb_module_name(),
                default_exports in arb_symbol_set(1, 8),
                optional_exports in arb_symbol_set(0, 4),
            ) {
                let file_id = FileId(1);
                let shard = empty_shard(file_id);
                let mut index = ImportExportIndex::new();

                let export_set = ExportSet {
                    default_exports: default_exports.clone(),
                    optional_exports: optional_exports.clone(),
                    tags: vec![],
                    provenance: Provenance::ExactAst,
                    confidence: Confidence::High,
                    module_name: Some(module_name.clone()),
                    anchor_id: Some(AnchorId(500)),
                };
                index.add_module_exports(
                    &format!("file:///lib/{module_name}.pm"),
                    &module_name,
                    export_set,
                );

                let import = ImportSpec {
                    module: module_name.clone(),
                    kind: ImportKind::Use,
                    symbols: ImportSymbols::Default,
                    provenance: Provenance::ExactAst,
                    confidence: Confidence::High,
                    file_id: Some(file_id),
                    anchor_id: Some(AnchorId(100)),
                    scope_id: None,
                };
                index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

                let visible = visible_symbols_at(file_id, 0, None, &shard, &index);

                // Every default export must appear with DefaultExport source.
                for sym_name in &default_exports {
                    let found = visible.iter().find(|v| v.name == *sym_name);
                    prop_assert!(
                        found.is_some(),
                        "default export '{}' should be visible",
                        sym_name
                    );
                    let vs = found.expect("checked above");
                    prop_assert_eq!(
                        &vs.source,
                        &VisibleSymbolSource::DefaultExport,
                        "default export '{}' should have DefaultExport source",
                        sym_name
                    );
                    let ctx = vs.context.as_ref();
                    prop_assert!(ctx.is_some(), "default export should have context");
                    prop_assert_eq!(
                        ctx.expect("checked above").source_module.as_deref(),
                        Some(module_name.as_str()),
                        "context source_module should match export module"
                    );
                }

                // Optional exports that are NOT in default_exports should NOT
                // be visible via bare `use`.
                for sym_name in &optional_exports {
                    if !default_exports.contains(sym_name) {
                        let found = visible.iter().find(|v| v.name == *sym_name);
                        prop_assert!(
                            found.is_none(),
                            "optional-only export '{}' should NOT be visible via bare use",
                            sym_name
                        );
                    }
                }
            }
        }

        // **Validates: Requirements 12.4**
        //
        // Property 9 (tag export): `use Foo ':tag'` makes all symbols in the
        // named tag visible with source ExportTag.
        proptest! {
            #![proptest_config(ProptestConfig {
                failure_persistence: None,
                ..ProptestConfig::default()
            })]

            #[test]
            fn prop_tag_export_source_attribution(
                module_name in arb_module_name(),
                tag_name in arb_tag_name(),
                tag_members in arb_symbol_set(1, 8),
            ) {
                let file_id = FileId(1);
                let shard = empty_shard(file_id);
                let mut index = ImportExportIndex::new();

                let export_set = ExportSet {
                    default_exports: vec![],
                    optional_exports: vec![],
                    tags: vec![ExportTag {
                        name: tag_name.clone(),
                        members: tag_members.clone(),
                    }],
                    provenance: Provenance::ExactAst,
                    confidence: Confidence::High,
                    module_name: Some(module_name.clone()),
                    anchor_id: Some(AnchorId(500)),
                };
                index.add_module_exports(
                    &format!("file:///lib/{module_name}.pm"),
                    &module_name,
                    export_set,
                );

                let import = ImportSpec {
                    module: module_name.clone(),
                    kind: ImportKind::UseTag,
                    symbols: ImportSymbols::Tags(vec![tag_name.clone()]),
                    provenance: Provenance::ExactAst,
                    confidence: Confidence::High,
                    file_id: Some(file_id),
                    anchor_id: Some(AnchorId(100)),
                    scope_id: None,
                };
                index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

                let visible = visible_symbols_at(file_id, 0, None, &shard, &index);

                // Every tag member must appear with ExportTag source.
                for sym_name in &tag_members {
                    let found = visible.iter().find(|v| v.name == *sym_name);
                    prop_assert!(
                        found.is_some(),
                        "tag member '{}' should be visible via :{} tag",
                        sym_name,
                        tag_name
                    );
                    let vs = found.expect("checked above");
                    prop_assert_eq!(
                        &vs.source,
                        &VisibleSymbolSource::ExportTag,
                        "tag member '{}' should have ExportTag source",
                        sym_name
                    );
                    let ctx = vs.context.as_ref();
                    prop_assert!(ctx.is_some(), "tag export should have context");
                    prop_assert_eq!(
                        ctx.expect("checked above").source_module.as_deref(),
                        Some(module_name.as_str()),
                        "context source_module should match export module"
                    );
                }
            }
        }
    }

    #[test]
    fn visible_symbol_context_carries_export_anchor() -> Result<(), Box<dyn std::error::Error>> {
        let file_id = FileId(1);
        let shard = empty_shard(file_id);
        let mut index = ImportExportIndex::new();

        index.add_module_exports("file:///lib/Foo.pm", "Foo", sample_export_set());

        let import = ImportSpec {
            module: "Foo".to_string(),
            kind: ImportKind::Use,
            symbols: ImportSymbols::Default,
            provenance: Provenance::ExactAst,
            confidence: Confidence::High,
            file_id: Some(file_id),
            anchor_id: Some(AnchorId(108)),
            scope_id: None,
        };
        index.add_file_imports("file:///lib/Main.pm", file_id, vec![import]);

        let symbols = visible_symbols_at(file_id, 0, None, &shard, &index);
        let foo_sym = symbols.iter().find(|s| s.name == "foo").ok_or("expected foo")?;

        let ctx = foo_sym.context.as_ref().ok_or("expected context")?;
        assert_eq!(ctx.source_module.as_deref(), Some("Foo"));
        assert_eq!(ctx.source_import_anchor_id, Some(AnchorId(108)));
        assert_eq!(ctx.source_export_anchor_id, Some(AnchorId(500)));
        Ok(())
    }
}