deps-core 1.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
// #673: fixed test-fixture lengths cast to `u32` never approach truncation range; this
// whole module is `#[cfg(test)]`-gated fixture support, not the request-path cast concern
// the crate-level `warn` targets.
#![allow(clippy::cast_possible_truncation)]

//! Shared test fixtures (mock formatters, dependencies, registries) reused across
//! this module's per-feature test suites.

use super::*;
use crate::{
    ConcreteVersion, Dependency, InvalidPackageName, PackageName, ParseResult, PublishTime,
    RemovalStatus, VersionReq,
};
use std::any::Any;
use tower_lsp_server::ls_types::{CodeAction, CodeActionKind};

pub(crate) fn pkg(s: &str) -> PackageName {
    PackageName::new(s)
}

pub(crate) struct MockFormatter;

impl PackageNaming for MockFormatter {}

impl PackageRendering for MockFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        format!("\"{}\"", version)
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{}", name)
    }
}

impl RequirementResolution for MockFormatter {}

impl DiagnosticMessages for MockFormatter {}

impl DiagnosticPolicy for MockFormatter {}

impl SourcePolicy for MockFormatter {}

impl OsvNaming for MockFormatter {}

/// Formatter stub that always reports `Unresolved`, mirroring `MavenFormatter` /
/// `GradleFormatter`'s override for `${property}` / `$var` requirements.
pub(crate) struct MockUnresolvedFormatter;

impl PackageNaming for MockUnresolvedFormatter {}

impl PackageRendering for MockUnresolvedFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{}", name)
    }
}

impl RequirementResolution for MockUnresolvedFormatter {
    fn requirement_status(
        &self,
        _requirement: &VersionReq,
        _latest: &ConcreteVersion,
    ) -> RequirementStatus {
        RequirementStatus::Unresolved
    }
}

impl DiagnosticMessages for MockUnresolvedFormatter {}

impl DiagnosticPolicy for MockUnresolvedFormatter {}

impl SourcePolicy for MockUnresolvedFormatter {}

impl OsvNaming for MockUnresolvedFormatter {}

/// Formatter stub mirroring `GoFormatter`'s override: reports the manifest
/// version-requirement line (go.mod's `require`) as itself the resolved
/// version, since it is already the exact MVS-selected version (#235).
pub(crate) struct MockGoFormatter;

impl PackageNaming for MockGoFormatter {}

impl PackageRendering for MockGoFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://pkg.go.dev/{}", name)
    }
}

impl RequirementResolution for MockGoFormatter {
    fn manifest_requirement_is_resolved_version(&self, _dep: &dyn Dependency) -> bool {
        true
    }
}

impl DiagnosticMessages for MockGoFormatter {}

impl DiagnosticPolicy for MockGoFormatter {}

impl SourcePolicy for MockGoFormatter {}

impl OsvNaming for MockGoFormatter {}

/// Formatter stub mirroring `deps-cargo`'s `CargoFormatter`: widens
/// `can_resolve_source` to accept `AlternateRegistry` (any private/internal
/// index, not just a crates.io mirror), while leaving
/// `source_is_public_registry_content` at its default (`Registry` only) —
/// exercises the M2/critic-C2 regression class, where a source can be
/// resolvable without its content being safe to treat as a public
/// registry's (e.g. for the deps.dev trust-signal gate, which must use the
/// latter, never the former).
pub(crate) struct MockWidenedResolveFormatter;

impl PackageNaming for MockWidenedResolveFormatter {}

impl PackageRendering for MockWidenedResolveFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for MockWidenedResolveFormatter {}

impl DiagnosticMessages for MockWidenedResolveFormatter {}

impl DiagnosticPolicy for MockWidenedResolveFormatter {}

impl SourcePolicy for MockWidenedResolveFormatter {
    fn can_resolve_source(&self, source: &crate::parser::DependencySource) -> bool {
        matches!(
            source,
            crate::parser::DependencySource::Registry
                | crate::parser::DependencySource::AlternateRegistry { .. }
        )
    }
}

impl OsvNaming for MockWidenedResolveFormatter {}

/// A formatter whose `validate_package_name` always rejects, for exercising
/// the "Invalid package name" diagnostic path independently of "Unknown package".
pub(crate) struct RejectingFormatter;

impl PackageNaming for RejectingFormatter {
    fn validate_package_name(&self, _name: &str) -> Result<(), InvalidPackageName> {
        Err(InvalidPackageName::new("name is rejected for testing"))
    }
}

impl PackageRendering for RejectingFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{}", name)
    }
}

impl RequirementResolution for RejectingFormatter {}

impl DiagnosticMessages for RejectingFormatter {}

impl DiagnosticPolicy for RejectingFormatter {}

impl SourcePolicy for RejectingFormatter {}

impl OsvNaming for RejectingFormatter {}

pub(crate) struct MockParseResult {
    pub(crate) deps: Vec<MockDep>,
    pub(crate) uri: Uri,
}

impl ParseResult for MockParseResult {
    fn dependencies(&self) -> Vec<&dyn Dependency> {
        self.deps.iter().map(|d| d as &dyn Dependency).collect()
    }
    fn workspace_root(&self) -> Option<&std::path::Path> {
        None
    }
    fn uri(&self) -> &Uri {
        &self.uri
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A [`ParseResult`] over heterogeneous [`Dependency`] impls — for tests that mix a
/// [`MockDep`] with a [`MockSyntheticRangeDep`] in one document, which [`MockParseResult`]'s
/// homogeneous `Vec<MockDep>` can't express.
pub(crate) struct MockMixedParseResult {
    pub(crate) deps: Vec<Box<dyn Dependency>>,
    pub(crate) uri: Uri,
}

impl ParseResult for MockMixedParseResult {
    fn dependencies(&self) -> Vec<&dyn Dependency> {
        self.deps.iter().map(AsRef::as_ref).collect()
    }
    fn workspace_root(&self) -> Option<&std::path::Path> {
        None
    }
    fn uri(&self) -> &Uri {
        &self.uri
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) struct MockDep {
    pub(crate) name: PackageName,
    pub(crate) version_req: VersionReq,
    pub(crate) version_range: Range,
    pub(crate) name_range: Range,
}

impl Dependency for MockDep {
    fn name(&self) -> &PackageName {
        &self.name
    }
    fn name_range(&self) -> Range {
        self.name_range
    }
    fn version_requirement(&self) -> Option<&VersionReq> {
        Some(&self.version_req)
    }
    fn version_range(&self) -> Option<Range> {
        Some(self.version_range)
    }
    fn source(&self) -> crate::parser::DependencySource {
        crate::parser::DependencySource::Registry
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A dependency whose `name_range()` is a synthetic placeholder
/// (`Dependency::name_range_is_synthetic() == true`) and `version_range()` is always `None` —
/// mirrors a `deps-dart` container-anchor-alias-resolved dependency (issue #905) for testing
/// that `name_range()`-keyed lookups and position-based hover/diagnostic anchoring correctly
/// skip it rather than treat `name_range()` as real. A separate, additive type rather than a
/// new field on [`MockDep`] (used at many pre-existing call sites across this crate's tests)
/// specifically so adding it touches none of them.
pub(crate) struct MockSyntheticRangeDep {
    pub(crate) name: PackageName,
}

impl Dependency for MockSyntheticRangeDep {
    fn name(&self) -> &PackageName {
        &self.name
    }
    fn name_range(&self) -> Range {
        Range::default()
    }
    fn version_requirement(&self) -> Option<&VersionReq> {
        None
    }
    fn version_range(&self) -> Option<Range> {
        None
    }
    fn source(&self) -> crate::parser::DependencySource {
        crate::parser::DependencySource::Registry
    }
    fn name_range_is_synthetic(&self) -> bool {
        true
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) struct MockMarkedDep {
    pub(crate) name: PackageName,
    pub(crate) name_range: Range,
    pub(crate) markers: Option<String>,
}

impl Dependency for MockMarkedDep {
    fn name(&self) -> &PackageName {
        &self.name
    }
    fn name_range(&self) -> Range {
        self.name_range
    }
    fn version_requirement(&self) -> Option<&VersionReq> {
        None
    }
    fn version_range(&self) -> Option<Range> {
        None
    }
    fn source(&self) -> crate::parser::DependencySource {
        crate::parser::DependencySource::Registry
    }
    fn markers(&self) -> Option<&str> {
        self.markers.as_deref()
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) struct MockMarkedParseResult {
    pub(crate) dep: MockMarkedDep,
    pub(crate) uri: Uri,
}

impl ParseResult for MockMarkedParseResult {
    fn dependencies(&self) -> Vec<&dyn Dependency> {
        vec![&self.dep]
    }
    fn workspace_root(&self) -> Option<&std::path::Path> {
        None
    }
    fn uri(&self) -> &Uri {
        &self.uri
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) struct MockRegistry;

impl crate::Registry for MockRegistry {
    fn get_versions<'a>(
        &'a self,
        _name: &'a PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a PackageName,
        _req: &'a VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry whose `get_versions` always errs, for exercising a fetch-failure code
/// path (e.g. `generate_hover`'s degrade-to-basic-card behavior on a failed fetch).
pub(crate) struct ErrorRegistry;

impl crate::Registry for ErrorRegistry {
    fn get_versions<'a>(
        &'a self,
        _name: &'a PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        Box::pin(async move {
            Err(crate::error::DepsError::CacheError(
                "mock registry error".to_string(),
            ))
        })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a PackageName,
        _req: &'a VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry whose `get_versions` always errs with `PackageNotFound`, for
/// exercising a "package genuinely doesn't exist" code path — distinct from
/// [`ErrorRegistry`], whose `CacheError` stands in for a transient/unanswerable
/// failure instead.
pub(crate) struct NotFoundRegistry;

impl crate::Registry for NotFoundRegistry {
    fn get_versions<'a>(
        &'a self,
        name: &'a PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        Box::pin(async move {
            Err(crate::error::DepsError::PackageNotFound {
                package: name.to_string(),
                registry: "mock",
            })
        })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a PackageName,
        _req: &'a VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A version with a configurable yanked flag and publish time, used for the
/// "Recent versions" hover freshness tests below.
pub(crate) struct MockVersionWithAge {
    pub(crate) version: ConcreteVersion,
    pub(crate) yanked: bool,
    pub(crate) published_at: Option<PublishTime>,
}

impl crate::Version for MockVersionWithAge {
    fn version_string(&self) -> &ConcreteVersion {
        &self.version
    }

    fn removal_status(&self) -> crate::RemovalStatus {
        crate::RemovalStatus::from_yanked(self.yanked)
    }

    fn published_at(&self) -> Option<PublishTime> {
        self.published_at
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

pub(crate) struct TestVersion {
    pub(crate) version: ConcreteVersion,
    pub(crate) yanked: bool,
}

impl crate::Version for TestVersion {
    fn version_string(&self) -> &ConcreteVersion {
        &self.version
    }

    fn removal_status(&self) -> crate::RemovalStatus {
        crate::RemovalStatus::from_yanked(self.yanked)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry whose `get_versions` returns a fixed, caller-supplied version list —
/// used to exercise hover's "Recent versions" rendering, which `MockRegistry`
/// above (always empty) cannot.
pub(crate) struct MockRegistryWithVersions {
    pub(crate) versions: Vec<MockVersionWithAge>,
}

impl crate::Registry for MockRegistryWithVersions {
    fn get_versions<'a>(
        &'a self,
        _name: &'a crate::PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        let versions = self
            .versions
            .iter()
            .map(|v| {
                Box::new(MockVersionWithAge {
                    version: v.version.clone(),
                    yanked: v.yanked,
                    published_at: v.published_at,
                }) as Box<dyn crate::Version>
            })
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a crate::PackageName,
        _req: &'a crate::VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    /// Newest entry that is neither yanked nor a prerelease — same predicate hover used
    /// to derive `live_latest_idx` before it was routed through this trait method
    /// (#347/#348 S1). A deprecated-but-installable entry is a legitimate "latest" here,
    /// matching most ecosystems (Cargo, PyPI, ...) which have no ranking preference for
    /// non-deprecated over deprecated; see `MockRegistryPreferringUnflagged` below for the
    /// npm-shaped ranking preference.
    fn select_latest_matching(
        &self,
        versions: &[Box<dyn crate::Version>],
        _req: &crate::VersionReq,
    ) -> Option<usize> {
        versions.iter().position(|v| v.is_stable())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A version carrying an SPDX `license` list (issue #204), used by hover tests that
/// exercise `push_license_hover_section`'s native-version-list path without touching
/// every existing [`MockVersionWithAge`] call site.
pub(crate) struct MockVersionWithLicense {
    pub(crate) version: ConcreteVersion,
    pub(crate) license: Vec<String>,
}

impl crate::Version for MockVersionWithLicense {
    fn version_string(&self) -> &ConcreteVersion {
        &self.version
    }

    fn license(&self) -> &[String] {
        &self.license
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Registry stub serving [`MockVersionWithLicense`] entries — the license-hover
/// counterpart of [`MockRegistryWithVersions`].
pub(crate) struct MockRegistryWithLicensedVersions {
    pub(crate) versions: Vec<MockVersionWithLicense>,
}

impl crate::Registry for MockRegistryWithLicensedVersions {
    fn get_versions<'a>(
        &'a self,
        _name: &'a crate::PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        let versions = self
            .versions
            .iter()
            .map(|v| {
                Box::new(MockVersionWithLicense {
                    version: v.version.clone(),
                    license: v.license.clone(),
                }) as Box<dyn crate::Version>
            })
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a crate::PackageName,
        _req: &'a crate::VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn select_latest_matching(
        &self,
        versions: &[Box<dyn crate::Version>],
        _req: &crate::VersionReq,
    ) -> Option<usize> {
        versions.iter().position(|v| v.is_stable())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A version carrying an explicit [`RemovalStatus`], used where a test needs
/// `AdvisoryDeprecated` specifically — `MockVersionWithAge`'s `bool` field can only
/// express `Available`/`Yanked` via [`RemovalStatus::from_yanked`].
pub(crate) struct MockVersionWithStatus {
    pub(crate) version: ConcreteVersion,
    pub(crate) status: RemovalStatus,
}

impl crate::Version for MockVersionWithStatus {
    fn version_string(&self) -> &ConcreteVersion {
        &self.version
    }

    fn removal_status(&self) -> RemovalStatus {
        self.status
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry whose `select_latest_matching` mirrors the shared 3-rung existence
/// ladder ([`crate::select_latest_for_existence`]) used by Cargo/PyPI/Dart/npm/Deno under
/// a wildcard requirement, rather than `MockRegistryWithVersions`'s generic `is_stable()`
/// scan. Exists for the hover/cache-agreement regression test (#347/#348 S1, #364): hover
/// must resolve "latest" through this same ranking, not an independent `is_stable()`-based
/// pick that disagrees with it — including rung 3 (newest overall, unconditionally), which
/// is what lets an all-yanked/all-prerelease package still resolve a "latest" instead of
/// `None`.
pub(crate) struct MockRegistryPreferringUnflagged {
    pub(crate) versions: Vec<MockVersionWithStatus>,
}

impl crate::Registry for MockRegistryPreferringUnflagged {
    fn get_versions<'a>(
        &'a self,
        _name: &'a crate::PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        let versions = self
            .versions
            .iter()
            .map(|v| {
                Box::new(MockVersionWithStatus {
                    version: v.version.clone(),
                    status: v.status,
                }) as Box<dyn crate::Version>
            })
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a crate::PackageName,
        _req: &'a crate::VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn select_latest_matching(
        &self,
        versions: &[Box<dyn crate::Version>],
        _req: &crate::VersionReq,
    ) -> Option<usize> {
        crate::select_latest_for_existence(versions, |v| v.as_ref())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry whose `select_latest_matching` always returns `None` — mirroring Go's
/// list-based ladder, which is deliberately excluded from the shared 3-rung existence
/// ladder (#364/#372) since `/@v/list` has no real per-version retraction data — paired
/// with a `get_latest_matching` that DOES resolve, mirroring Go's `/@latest` endpoint
/// answering from a more complete source than the list. Exists for the hover
/// list-based-pick-failed fallback regression test (#373). `get_latest_matching_calls`
/// counts invocations so a test can assert the fallback is NOT reached on the happy
/// path (a list-based pick that already succeeds), guarding against a future regression
/// that would make every hover pay for a second network round trip.
pub(crate) struct MockRegistryListFailsLatestFallbackSucceeds {
    pub(crate) versions: Vec<MockVersionWithAge>,
    pub(crate) fallback_latest: MockVersionWithAge,
    /// `select_latest_matching`'s return value — `None` reproduces the Go
    /// list-based-pick-failure this mock exists for; `Some(idx)` lets a test exercise the
    /// happy path (list pick succeeds) through this same mock, to assert the fallback is
    /// NOT reached.
    pub(crate) list_pick_index: Option<usize>,
    pub(crate) get_latest_matching_calls: std::sync::atomic::AtomicUsize,
}

impl crate::Registry for MockRegistryListFailsLatestFallbackSucceeds {
    fn get_versions<'a>(
        &'a self,
        _name: &'a crate::PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        let versions = self
            .versions
            .iter()
            .map(|v| {
                Box::new(MockVersionWithAge {
                    version: v.version.clone(),
                    yanked: v.yanked,
                    published_at: v.published_at,
                }) as Box<dyn crate::Version>
            })
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a crate::PackageName,
        _req: &'a crate::VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        self.get_latest_matching_calls
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let fallback = MockVersionWithAge {
            version: self.fallback_latest.version.clone(),
            yanked: self.fallback_latest.yanked,
            published_at: self.fallback_latest.published_at,
        };
        Box::pin(async move { Ok(Some(Box::new(fallback) as Box<dyn crate::Version>)) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    fn select_latest_matching(
        &self,
        _versions: &[Box<dyn crate::Version>],
        _req: &crate::VersionReq,
    ) -> Option<usize> {
        self.list_pick_index
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A registry returning a fixed, caller-supplied version list — used to
/// exercise the yank check and display-item dedup in
/// [`generate_code_actions`].
pub(crate) struct FixedVersionRegistry {
    pub(crate) versions: Vec<(&'static str, bool)>,
}

impl crate::Registry for FixedVersionRegistry {
    fn get_versions<'a>(
        &'a self,
        _name: &'a PackageName,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Version>>>> {
        let versions: Vec<Box<dyn crate::Version>> = self
            .versions
            .iter()
            .map(|(version, yanked)| {
                Box::new(TestVersion {
                    version: (*version).into(),
                    yanked: *yanked,
                }) as Box<dyn crate::Version>
            })
            .collect();
        Box::pin(async move { Ok(versions) })
    }

    fn get_latest_matching<'a>(
        &'a self,
        _name: &'a PackageName,
        _req: &'a VersionReq,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Option<Box<dyn crate::Version>>>>
    {
        Box::pin(async move { Ok(None) })
    }

    fn search<'a>(
        &'a self,
        _query: &'a str,
        _limit: usize,
    ) -> crate::ecosystem::BoxFuture<'a, crate::error::Result<Vec<Box<dyn crate::Metadata>>>> {
        Box::pin(async move { Ok(Vec::new()) })
    }

    // Mirrors the real 3-rung existence ladder every ecosystem's own `select_latest_matching`
    // delegates to (`crate::select_latest_for_existence`), rather than the trait default
    // (always `None`) — `generate_code_actions`'s `(latest)`/`is_preferred` REFACTOR-action
    // pick is now sourced from this call (#952), same as hover's `live_latest_idx`.
    fn select_latest_matching(
        &self,
        versions: &[Box<dyn crate::Version>],
        _req: &VersionReq,
    ) -> Option<usize> {
        crate::select_latest_for_existence(versions, |v| v.as_ref())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Builds a single-dependency parse result for the freshness hover tests, cursor
/// positioned on the dependency name.
pub(crate) fn freshness_test_parse_result(name: &str) -> MockParseResult {
    MockParseResult {
        deps: vec![MockDep {
            name: name.into(),
            version_req: "1.0.0".into(),
            version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
            name_range: Range::new(Position::new(0, 0), Position::new(0, name.len() as u32)),
        }],
        uri: crate::test_util::test_uri("/test/Cargo.toml"),
    }
}

/// A formatter whose `format_version_for_text_edit` is the identity —
/// unlike [`MockFormatter`], which wraps the version in quotes and would
/// otherwise confound the N1 no-op-edit guard's own test.
pub(crate) struct IdentityFormatter;

impl PackageNaming for IdentityFormatter {}

impl PackageRendering for IdentityFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for IdentityFormatter {}

impl DiagnosticMessages for IdentityFormatter {}

impl DiagnosticPolicy for IdentityFormatter {}

impl SourcePolicy for IdentityFormatter {}

impl OsvNaming for IdentityFormatter {}

/// A formatter mimicking `deps-dart`'s non-identity
/// `format_version_for_text_edit` (wraps the version in a caret
/// constraint) — used to prove the N1 guard compares the *formatted*
/// text actually written, not the bare version (critic S3).
pub(crate) struct CaretWrappingFormatter;

impl PackageNaming for CaretWrappingFormatter {}

impl PackageRendering for CaretWrappingFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        format!("^{version}")
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for CaretWrappingFormatter {}

impl DiagnosticMessages for CaretWrappingFormatter {}

impl DiagnosticPolicy for CaretWrappingFormatter {}

impl SourcePolicy for CaretWrappingFormatter {}

impl OsvNaming for CaretWrappingFormatter {}

/// A formatter mimicking `deps-pypi`'s non-identity
/// `format_version_replacing` override (preserves an `==` pin instead of
/// falling back to `format_version_for_text_edit`) — used to prove the
/// vulnerability-fix action's `TextEdit` goes through the override, not
/// the default delegation (critic S3).
pub(crate) struct PinPreservingFormatter;

impl PackageNaming for PinPreservingFormatter {}

impl PackageRendering for PinPreservingFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        format!(">={version}")
    }

    fn format_version_replacing(&self, version: &ConcreteVersion, current: &str) -> String {
        if current.starts_with("==") {
            format!("=={version}")
        } else {
            self.format_version_for_text_edit(version)
        }
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for PinPreservingFormatter {}

impl DiagnosticMessages for PinPreservingFormatter {}

impl DiagnosticPolicy for PinPreservingFormatter {}

impl SourcePolicy for PinPreservingFormatter {}

impl OsvNaming for PinPreservingFormatter {}

/// Builds a `pkg = "<version_req>"`-shaped fixture: a dependency whose
/// `version_range` slices `content` to exactly `version_req` (so the
/// literal-span guard in `generate_code_actions` never rejects it).
pub(crate) fn vulnerable_dep(
    version_req: &str,
) -> (MockDep, tower_lsp_server::ls_types::Range, String) {
    use tower_lsp_server::ls_types::{Position, Range};

    let content = format!("pkg = \"{version_req}\"");
    let start = 7u32; // len(`pkg = "`)
    let end = start + version_req.chars().count() as u32;
    let version_range = Range::new(Position::new(0, start), Position::new(0, end));
    (
        MockDep {
            name: pkg("pkg"),
            version_req: VersionReq::new(version_req),
            version_range,
            name_range: Range::new(Position::new(0, 0), Position::new(0, 3)),
        },
        version_range,
        content,
    )
}

pub(crate) fn quickfix_titles(actions: &[CodeAction]) -> Vec<&str> {
    actions
        .iter()
        .filter(|a| a.kind == Some(CodeActionKind::QUICKFIX))
        .map(|a| a.title.as_str())
        .collect()
}

pub(crate) fn refactor_titles(actions: &[CodeAction]) -> Vec<&str> {
    actions
        .iter()
        .filter(|a| a.kind == Some(CodeActionKind::REFACTOR))
        .map(|a| a.title.as_str())
        .collect()
}

/// A formatter whose formatted edit text differs from the bare version only in
/// whitespace (a trailing space) — used to prove the REFACTOR-loop no-op guard
/// compares whitespace-insensitively rather than by raw string equality.
pub(crate) struct TrailingSpaceFormatter;

impl PackageNaming for TrailingSpaceFormatter {}

impl PackageRendering for TrailingSpaceFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        format!("{version} ")
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for TrailingSpaceFormatter {}

impl DiagnosticMessages for TrailingSpaceFormatter {}

impl DiagnosticPolicy for TrailingSpaceFormatter {}

impl SourcePolicy for TrailingSpaceFormatter {}

impl OsvNaming for TrailingSpaceFormatter {}

/// A formatter that truncates every version to `==<major>.<minor>`, mirroring
/// `deps-pypi`'s `truncate_release_to_match` collapsing several distinct
/// registry versions (or a registry version and an OSV fix version) to the
/// same rewritten text — used to prove issue #242's two dedup gaps: an item
/// matching the fix action's text under a different raw version, and two
/// items matching each other's text.
pub(crate) struct TruncatingFormatter;

impl PackageNaming for TruncatingFormatter {}

impl PackageRendering for TruncatingFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn format_version_replacing(&self, version: &ConcreteVersion, _current: &str) -> String {
        let mut parts = version.as_str().split('.');
        let major = parts.next().unwrap_or("0");
        let minor = parts.next().unwrap_or("0");
        format!("=={major}.{minor}")
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{name}")
    }
}

impl RequirementResolution for TruncatingFormatter {}

impl DiagnosticMessages for TruncatingFormatter {}

impl DiagnosticPolicy for TruncatingFormatter {}

impl SourcePolicy for TruncatingFormatter {}

impl OsvNaming for TruncatingFormatter {}

pub(crate) fn sample_advisory(
    id: &str,
    severity: crate::osv::VulnSeverity,
) -> std::sync::Arc<crate::osv::Advisory> {
    std::sync::Arc::new(crate::osv::Advisory {
        id: id.to_string(),
        modified: "2023-01-01T00:00:00Z".to_string(),
        summary: Some("Something went wrong".to_string()),
        aliases: vec!["CVE-2020-0001".to_string()],
        severity,
        cvss_vector: None,
        fixed_versions: vec!["1.2.0".to_string(), "1.5.0".to_string()],
        url: format!("https://osv.dev/vulnerability/{id}"),
    })
}

pub(crate) fn dep_at(name: &str) -> MockDep {
    MockDep {
        name: PackageName::new(name),
        version_req: VersionReq::new("1.0.0"),
        version_range: Range::new(Position::new(0, 10), Position::new(0, 20)),
        name_range: Range::new(Position::new(0, 0), Position::new(0, name.len() as u32)),
    }
}

/// Wraps a [`MockDep`] to report a non-`Registry` [`crate::parser::DependencySource`],
/// without touching every other `MockDep` literal in this test module.
pub(crate) struct NonRegistryDep(
    pub(crate) MockDep,
    pub(crate) crate::parser::DependencySource,
);

impl Dependency for NonRegistryDep {
    fn name(&self) -> &PackageName {
        self.0.name()
    }
    fn name_range(&self) -> Range {
        self.0.name_range()
    }
    fn version_requirement(&self) -> Option<&VersionReq> {
        self.0.version_requirement()
    }
    fn version_range(&self) -> Option<Range> {
        self.0.version_range()
    }
    fn source(&self) -> crate::parser::DependencySource {
        self.1.clone()
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// `ParseResult` holding exactly one dependency of any concrete `Dependency`
/// type, so single-dependency tests aren't forced to use `MockDep`/`MockParseResult`.
pub(crate) struct SingleDepParseResult<D> {
    pub(crate) dep: D,
    pub(crate) uri: Uri,
}

impl<D: Dependency + 'static> ParseResult for SingleDepParseResult<D> {
    fn dependencies(&self) -> Vec<&dyn Dependency> {
        vec![&self.dep]
    }
    fn workspace_root(&self) -> Option<&std::path::Path> {
        None
    }
    fn uri(&self) -> &Uri {
        &self.uri
    }
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Formatter whose `compile_requirement` does exact-string matching, so
/// `requirement_is_unsatisfiable` can actually return `true` in a test
/// (unlike the default `MockFormatter`, whose `compile_requirement`
/// default always returns `None`).
pub(crate) struct ExactMatchFormatter;

pub(crate) struct ExactMatcher(pub(crate) String);
impl RequirementMatcher for ExactMatcher {
    fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
        Some(version.as_str() == self.0)
    }
}

impl PackageNaming for ExactMatchFormatter {}

impl PackageRendering for ExactMatchFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{}", name)
    }
}

impl RequirementResolution for ExactMatchFormatter {
    fn compile_requirement(&self, requirement: &VersionReq) -> Option<Box<dyn RequirementMatcher>> {
        Some(Box::new(ExactMatcher(requirement.as_str().to_string())))
    }
}

impl DiagnosticMessages for ExactMatchFormatter {}

impl DiagnosticPolicy for ExactMatchFormatter {}

impl SourcePolicy for ExactMatchFormatter {}

impl OsvNaming for ExactMatchFormatter {}

pub(crate) struct RealSemverMatcher(pub(crate) semver::VersionReq);
impl RequirementMatcher for RealSemverMatcher {
    fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
        version
            .as_str()
            .parse::<semver::Version>()
            .ok()
            .map(|v| self.0.matches(&v))
    }
}

/// Mirrors `deps-cargo`/`deps-swift`'s real formatter shape (`semver::VersionReq`
/// compilation, opted into `strict_semver_prerelease_exclusion`) without depending on
/// those crates. Shared by `matching_prerelease_would_satisfy_tests` and the
/// `generate_diagnostics_from_cache` end-to-end coverage below (#299).
pub(crate) struct StrictSemverFormatter;
impl PackageNaming for StrictSemverFormatter {}

impl PackageRendering for StrictSemverFormatter {
    fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
        version.to_string()
    }

    fn package_url(&self, name: &PackageName) -> String {
        name.to_string()
    }
}

impl RequirementResolution for StrictSemverFormatter {
    fn compile_requirement(&self, requirement: &VersionReq) -> Option<Box<dyn RequirementMatcher>> {
        requirement
            .as_str()
            .parse::<semver::VersionReq>()
            .ok()
            .map(|req| Box::new(RealSemverMatcher(req)) as Box<dyn RequirementMatcher>)
    }
}

impl DiagnosticMessages for StrictSemverFormatter {}

impl DiagnosticPolicy for StrictSemverFormatter {
    fn strict_semver_prerelease_exclusion(&self) -> bool {
        true
    }
}

impl SourcePolicy for StrictSemverFormatter {}

impl OsvNaming for StrictSemverFormatter {}