deps-core 0.11.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
//! Shared test fixtures (mock formatters, dependencies, registries) reused across
//! this module's per-feature test suites.

use super::*;
use crate::{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 EcosystemFormatter for MockFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        format!("\"{}\"", version)
    }

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

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

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

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

    fn requirement_status(&self, _requirement: &VersionReq, _latest: &str) -> RequirementStatus {
        RequirementStatus::Unresolved
    }
}

/// 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 EcosystemFormatter for MockGoFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }

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

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

/// 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 EcosystemFormatter for RejectingFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }

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

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

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
    }
}

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
    }
}

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
/// `generate_diagnostics`'s `Err` arm.
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 `generate_diagnostics`'s "Unknown package" branch (#267 C1) —
/// distinct from [`ErrorRegistry`], whose `CacheError` must instead produce
/// the "Registry lookup failed" message.
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 registry whose `get_versions` succeeds with a newer stable version and
/// whose `get_latest_matching` returns a non-yanked current version, for
/// exercising `generate_diagnostics`'s outdated-severity wiring.
pub(crate) struct OutdatedRegistry;

impl crate::Registry for OutdatedRegistry {
    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![Box::new(MockVersionWithAge {
                version: "2.0.0".to_string(),
                yanked: false,
                published_at: None,
            }) as Box<dyn crate::Version>])
        })
    }

    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(Some(Box::new(MockVersionWithAge {
                version: "1.0.0".to_string(),
                yanked: false,
                published_at: None,
            }) 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 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: String,
    pub(crate) yanked: bool,
    pub(crate) published_at: Option<PublishTime>,
}

impl crate::Version for MockVersionWithAge {
    fn version_string(&self) -> &str {
        &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: String,
    pub(crate) yanked: bool,
}

impl crate::Version for TestVersion {
    fn version_string(&self) -> &str {
        &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 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: String,
    pub(crate) status: RemovalStatus,
}

impl crate::Version for MockVersionWithStatus {
    fn version_string(&self) -> &str {
        &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).to_string(),
                    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()) })
    }

    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 EcosystemFormatter for IdentityFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }

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

/// 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 EcosystemFormatter for CaretWrappingFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        format!("^{version}")
    }

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

/// 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 EcosystemFormatter for PinPreservingFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        format!(">={version}")
    }

    fn format_version_replacing(&self, version: &str, 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}")
    }
}

/// 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 EcosystemFormatter for TrailingSpaceFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        format!("{version} ")
    }

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

/// 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 EcosystemFormatter for TruncatingFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }

    fn format_version_replacing(&self, version: &str, _current: &str) -> String {
        let mut parts = version.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}")
    }
}

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: &str) -> Option<bool> {
        Some(version == self.0)
    }
}

impl EcosystemFormatter for ExactMatchFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }
    fn package_url(&self, name: &PackageName) -> String {
        format!("https://example.com/{}", name)
    }
    fn compile_requirement(&self, requirement: &VersionReq) -> Option<Box<dyn RequirementMatcher>> {
        Some(Box::new(ExactMatcher(requirement.as_str().to_string())))
    }
}

pub(crate) struct RealSemverMatcher(pub(crate) semver::VersionReq);
impl RequirementMatcher for RealSemverMatcher {
    fn matches(&self, version: &str) -> Option<bool> {
        version
            .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 EcosystemFormatter for StrictSemverFormatter {
    fn format_version_for_text_edit(&self, version: &str) -> String {
        version.to_string()
    }
    fn package_url(&self, name: &PackageName) -> String {
        name.to_string()
    }
    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>)
    }
    fn strict_semver_prerelease_exclusion(&self) -> bool {
        true
    }
}