deps_core/lsp_helpers/mod.rs
1//! Shared LSP response builders.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::Duration;
6
7#[cfg(doc)]
8use crate::EcosystemId;
9use crate::error::DepsError;
10use crate::native_cooldown::{NativeCooldown, NativeGate};
11use crate::osv::{
12 CandidateStatusMap, CandidateStatuses, LatestStatusMap, ScanOutcome, UpgradeStatus, VulnKey,
13 VulnSeverity, VulnerabilityMap,
14};
15use crate::package::NormalizedName;
16use crate::position::{Position, Range};
17use crate::{
18 ConcreteVersion, CooldownWindow, Dependency, Deprecation, FetchFailure, GossipFindings,
19 PackageKey, PublishTime, RemovalStatus, VersionReq,
20};
21
22mod candidate_tags;
23#[cfg(feature = "lsp-responses")]
24mod code_actions;
25#[cfg(feature = "lsp-responses")]
26mod code_lenses;
27mod diagnostics;
28pub mod exemption;
29mod formatted_dependency;
30mod formatter;
31mod git_pin;
32mod git_probe;
33#[cfg(test)]
34mod git_probe_lineage_tests;
35mod git_ref;
36mod git_tags;
37#[cfg(feature = "lsp-responses")]
38mod hover;
39#[cfg(feature = "lsp-responses")]
40mod hover_markdown;
41mod in_use_version;
42#[cfg(feature = "lsp-responses")]
43mod inlay_hints;
44mod interactive_fetch;
45mod mutable_ref_pin;
46mod probe_pass;
47mod sha_comment;
48mod suppression;
49#[cfg(test)]
50pub(crate) mod test_support;
51#[cfg(test)]
52#[cfg(feature = "lsp-responses")]
53pub(crate) mod test_support_lsp;
54mod unknown_ref;
55mod version_data;
56mod version_grammar;
57
58/// Generic replacement for this module's former `TextEdit`-only `dedup_overlapping_edits`
59/// (#1329) — re-exported here so every existing `lsp_helpers::dedup_overlapping_edits(edits,
60/// caller)` call site (e.g. `deps_github_actions::collect_pin_all_to_sha_edits`) keeps
61/// compiling unchanged, with `E = ls_types::TextEdit` inferred from the call's own argument
62/// type.
63#[cfg(feature = "lsp-responses")]
64pub use crate::edit::dedup_overlapping_edits;
65pub use candidate_tags::{
66 CandidateSiblings, CandidateSiblingsUnknown, CandidateTagSource, TaggedVersions,
67};
68#[cfg(feature = "lsp-responses")]
69pub use code_actions::generate_code_actions;
70#[cfg(feature = "lsp-responses")]
71pub use code_lenses::{
72 PIN_ALL_TO_SHA_COMMAND_ID, PinNoun, build_pin_all_to_sha_lens, collect_update_all_edits,
73 generate_code_lenses,
74};
75pub use diagnostics::{
76 BoundedVersionReq, DEPRECATED_DIAGNOSTIC_CODE, DiagnosticSeverities,
77 LICENSE_POLICY_VIOLATION_DIAGNOSTIC_CODE, MAX_DIAGNOSTIC_VALUE_CHARS, MAX_REQUIREMENT_LEN,
78 SiblingMatchNote, TYPOSQUAT_DIAGNOSTIC_CODE, TyposquatFetchOutcome,
79 UNSATISFIABLE_DIAGNOSTIC_CODE, advisory_text, fetch_gossip_findings_batch,
80 fetch_typosquat_signals, force_refresh_gossip_findings, generate_diagnostics_from_cache,
81 redact_name_for_diagnostic, redact_requirement_for_diagnostic, requirement_is_unsatisfiable,
82 requirement_len_exceeds_cap, sanitize_advisory_text_for_diagnostic,
83 sanitize_and_truncate_for_diagnostic, truncate_for_diagnostic,
84};
85pub use mutable_ref_pin::{
86 FixAvailability, GitlabInclude, MutablePinPolicy, MutableRefPin, PinSubject,
87};
88// `pub` (#1578): `edit.rs`/`in_use_version.rs` share this in-crate, and it is also reused by
89// callers outside `deps-core` that need this same size gate before compiling a requirement
90// (mirroring `requirement_len_exceeds_cap`'s own `pub` rationale) rather than duplicating the
91// length check at their own `compile_bounded_requirement` call site (#1472).
92pub use diagnostics::requirement_is_oversized;
93// `pub(crate)` (not `pub`, matching the constant's own visibility) so `completion.rs` can
94// share this bound with `inlay_hints`/`hover` rather than declaring a duplicate cap.
95// `completion` is itself `#[cfg(feature = "lsp-responses")]` (see `lib.rs`) and is this
96// re-export's only consumer outside `lsp_helpers`, so without this gate a default-features
97// build (e.g. `fuzz`'s workspace check) sees it as unused.
98#[cfg(feature = "lsp-responses")]
99pub(crate) use diagnostics::MAX_VERSION_DIAGNOSTIC_CHARS;
100pub use formatted_dependency::{BoundDependency, FormattedDependency};
101pub use formatter::{
102 BareMeaning, BuildMetadataPolicy, DependencyFormatter, DependencyGate, DiagnosticMessages,
103 DiagnosticPolicy, EcosystemFormatter, LowercaseNaming, NormalizeName, OperatorGrammar,
104 OsvNameAvailability, OsvNaming, PackageNaming, PackageRendering, ProbeDependency,
105 PublicContent, RequirementGate, RequirementResolution, RequirementRewriteShape, RewriteTarget,
106 SourcePolicy, bare_meaning, classify_requirement_rewrite_shape, fit_segments,
107 format_version_replacing_by_shape, requirement_is_compound,
108 up_to_date_for_comparators_via_compiled_matcher, up_to_date_via_compiled_matcher,
109};
110pub use git_pin::{
111 GitPinView, git_candidate_tag_source, git_commit_rewrite, git_tag_replacement, resolve_git_pin,
112};
113pub use git_probe::{
114 AheadProof, BranchEvidence, BranchEvidenceStore, COMPARE_BODY_LIMIT, CommitEvidence,
115 CommitEvidenceStore, CommitLineage, CompareStatus, CompareSummary, DefaultBranchMembership,
116 EVIDENCE_STORE_CAPACITY, EvidenceStore, HoverProvenance, PercentEncoded, ProbeEffect,
117 ProbePhase, ProbeRef, ProbeReport,
118};
119pub use git_ref::{
120 CommitRewrite, CommitSha, CoreSchemaType, MAX_FALLBACK_SCAN_BYTES, MarkedScalar,
121 PartialTagPolicy, PinResolution, ResolvedPin, ShaPinLookup, SiblingScope, SiblingTags,
122 TagIndex, TagName, TagPosition, UnpublishedRef, byte_span_to_range, extends_tag,
123 is_core_schema_tag, is_full_sha, is_null_tag, is_partial_semver_shaped, is_plain_null,
124 is_tag_shaped, locate_value_span, marker_byte_offset, match_v_prefix_style, short_sha,
125 tag_has_precedence, tag_pin_is_up_to_date,
126};
127#[cfg(feature = "lsp-responses")]
128pub use git_ref::{
129 ResolvedShaPin, ShaPinning, build_sha_pin_action, sha_pin_text_edit, splice_hover_line,
130 splice_resolved_line, splice_sha_pin_hover_lines,
131};
132pub use git_tags::{GitTagsPinning, git_tags_diagnostics, sha_comment_mismatch_diagnostics};
133#[cfg(feature = "lsp-responses")]
134pub use git_tags::{git_tags_sha_comment_fix_action, git_tags_unknown_ref_fix_action};
135#[cfg(feature = "lsp-responses")]
136pub(crate) use hover::find_hovered_dependency;
137#[cfg(feature = "lsp-responses")]
138pub use hover::{CMD_DOT_FOOTER, generate_hover};
139#[cfg(feature = "lsp-responses")]
140pub use hover_markdown::{FieldKind, HoverMarkdown, SafeNumber};
141pub use in_use_version::{
142 InUseVersions, LockSelectionMemo, concrete_pin_version, has_unqueryable_resolved_pin,
143 is_full_semver_shape, resolve_in_use_version, resolve_in_use_versions,
144 resolve_in_use_versions_memoized,
145};
146#[cfg(feature = "lsp-responses")]
147pub use inlay_hints::generate_inlay_hints;
148pub use interactive_fetch::{
149 AuxiliaryLookup, FetchContext, InteractiveFetch, InteractiveFetchError, InteractiveFetchGate,
150 InteractiveFetchRequest, NoLiveList, SharedVersions, await_interactive_fetch,
151 await_interactive_versions,
152};
153pub use probe_pass::{
154 BranchProbe, CommitProbe, EVIDENCE_TTL, GitTagVersion, LatestRelease, PROBE_CONCURRENCY,
155 ProbeAnswer, ProbeBackend, ProbeKind, ProbeOutcome, ProbePlan, ProbeQuestion, ProbeStores,
156 branch_answer, parsed_answer, run_probe_pass,
157};
158#[cfg(feature = "lsp-responses")]
159pub use sha_comment::build_sha_comment_fix_action;
160pub use sha_comment::{
161 ClosingDelimiters, CommentCheck, CommentMismatch, CommentRemainder, CommentSlot, CommentStyle,
162 CommentTag, SHA_COMMENT_MISMATCH_DIAGNOSTIC_CODE, ShaPinComment, ShaPinTail, ShaPinTailRead,
163 comment_slot_after, position_past_sha, read_sha_pin_tail, ref_is_last_on_line,
164 sha_comment_mismatch_diagnostic, sha_comment_mismatch_hover_line, sha_pin_rewrite,
165 sha_pin_rewrite_with_default_style,
166};
167pub use suppression::{
168 PackagePattern, PackageSuppression, PatternError, ResolvedSuppression, RuleError,
169 SuppressedKinds, SuppressionKind, SuppressionRule, SuppressionSet,
170};
171#[cfg(feature = "lsp-responses")]
172pub use unknown_ref::build_unknown_ref_fix_action;
173pub use unknown_ref::{
174 UNKNOWN_REF_DIAGNOSTIC_CODE, UnknownRefTarget, dependency_at_position, unknown_ref_diagnostic,
175 unknown_ref_diagnostic_for, unknown_ref_diagnostics,
176};
177pub(crate) use version_data::OwnerPreference;
178pub use version_data::{
179 CachedVersionsMap, LockCandidates, ResolvedCandidatesMap, ResolvedVersionsMap, VersionData,
180};
181use version_grammar::matcher_of;
182pub use version_grammar::{
183 CandidateSet, SemverGrammar, VersionGrammar, grammar_candidates, grammar_matcher,
184};
185
186/// Maximum number of recent versions hover's "Recent versions" section renders.
187///
188/// Also the walk target for registries (NuGet, npm) that must fetch publish times for
189/// only the versions actually rendered, rather than the entire version history.
190pub const HOVER_RECENT_VERSIONS: usize = 8;
191
192/// A cooldown-cleared, ecosystem-safe, floor-protected fallback candidate (spec 075
193/// `deps-cli update` fallback, FR-001/FR-002).
194///
195/// Computed once, at fetch time, by `deps-engine::classify::fetch::fetch_and_classify_package`
196/// — never at read time (see [`cooldown_disposition`] for the read-time side). [`Self::published_at`]
197/// is never `None`: a candidate without a known publish time is never stored (OQ2's fail-closed
198/// rule for a non-`latest` candidate).
199#[non_exhaustive]
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct CooldownFallback {
202 /// The fallback candidate's version.
203 pub version: ConcreteVersion,
204 /// When the fallback candidate was published. Never `None` — see the type's own doc.
205 pub published_at: PublishTime,
206}
207
208impl CooldownFallback {
209 /// Constructs a `CooldownFallback`.
210 ///
211 /// Needed because [`Self`] is `#[non_exhaustive]`: a struct literal only works inside
212 /// this crate, so every other crate must go through this constructor instead.
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use deps_core::PublishTime;
218 /// use deps_core::lsp_helpers::CooldownFallback;
219 ///
220 /// let fallback = CooldownFallback::new("1.1.0".into(), PublishTime::from_unix_secs(1_000));
221 /// assert_eq!(fallback.version, "1.1.0");
222 /// ```
223 #[must_use]
224 pub const fn new(version: ConcreteVersion, published_at: PublishTime) -> Self {
225 Self {
226 version,
227 published_at,
228 }
229 }
230}
231
232/// What blocked [`PackageVersions::latest`] from being usable as-is — drives
233/// check/hover/diagnostics wording. Carried by [`CooldownDisposition::Blocked`].
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub enum CooldownBlocker {
236 /// GOSSIP reported an active cooldown for this exact version (spec 072 FR-005).
237 Gossip,
238 /// The local [`CooldownWindow`] heuristic reports this version as
239 /// recently published, with no authoritative GOSSIP answer available for it.
240 Local {
241 /// When `latest` was published, per the registry.
242 published_at: PublishTime,
243 },
244}
245
246/// Read-time-only outcome of [`cooldown_disposition`] — never stored on [`PackageVersions`].
247///
248/// Spec 075 NFR-002: a stored disposition would be a fetch-time snapshot, violating spec 072
249/// FR-011's read-time evaluation requirement.
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub enum CooldownDisposition<'a> {
252 /// The freshness feature is disabled — cooldown has no effect at all.
253 NotEvaluated,
254 /// `latest` is not blocked by cooldown (no GOSSIP verdict, or a past one; no active local
255 /// heuristic result).
256 Cleared,
257 /// `latest` is currently blocked. `fallback`, when present, is the newest
258 /// cooldown-cleared, ecosystem-safe, floor-protected alternative a caller may offer
259 /// instead (spec 075) — `None` when no such candidate was found at fetch time.
260 Blocked {
261 /// What blocked `latest`.
262 by: CooldownBlocker,
263 /// The fallback candidate, if one was computed and stored for this dependency.
264 fallback: Option<&'a CooldownFallback>,
265 },
266 /// `latest` is held back by the package manager's own publish-age window (spec 099).
267 /// Independent of the freshness feature: it is reported even when freshness is disabled.
268 /// `fallback` is the stored cooldown-fallback candidate, kept only when the freshness
269 /// cooldown would also have blocked `latest` and the candidate itself clears the native
270 /// window; surfaces that only explain the hold ignore it.
271 NativeHeld {
272 /// The configured window that holds `latest` back.
273 cooldown: &'a NativeCooldown,
274 /// The fallback candidate that survives both windows, if any.
275 fallback: Option<&'a CooldownFallback>,
276 },
277}
278
279/// Outcome of [`cooldown_precedence`]: whether a single version is currently blocked by the
280/// freshness cooldown, and by what.
281#[derive(Debug, Clone, Copy, PartialEq, Eq)]
282pub enum CooldownPrecedence {
283 /// Not blocked (no active GOSSIP verdict, or a past one; no active local heuristic result).
284 Cleared,
285 /// Currently blocked, and by what.
286 Blocked(CooldownBlocker),
287}
288
289/// The GOSSIP-vs-local cooldown precedence rule for a single `(name, version)` pair.
290///
291/// An authoritative GOSSIP verdict wins outright, and only when GOSSIP has none does the local
292/// heuristic ([`local_cooldown_precedence`]) apply.
293///
294/// Extracted from [`cooldown_disposition`] (spec 075 FR-004) so `deps-engine`'s fetch-time
295/// fallback-candidate search (`compute_cooldown_fallback`) can share the exact same rule
296/// without first needing a full [`PackageVersions`] — that type doesn't exist yet at fetch
297/// time for any version other than the one being classified (issue #1551).
298///
299/// Takes a [`CooldownWindow`] rather than the [`FreshnessSettings`
300/// enum](crate::FreshnessSettings) so callers naturally go through
301/// [`FreshnessSettings::Enabled`](crate::FreshnessSettings::Enabled) — the only place a window
302/// value is produced — though `CooldownWindow::from_secs` being `pub` means this is a
303/// convention, not a hard type-level guarantee.
304///
305/// # Examples
306///
307/// ```
308/// use deps_core::lsp_helpers::{CooldownPrecedence, cooldown_precedence};
309/// use deps_core::{CooldownWindow, NormalizedName, PublishTime};
310///
311/// let cleared = cooldown_precedence(
312/// None,
313/// &NormalizedName::for_test("left-pad"),
314/// "2.0.0",
315/// Some(PublishTime::from_unix_secs(1_000)),
316/// CooldownWindow::from_secs(500),
317/// PublishTime::from_unix_secs(2_000),
318/// );
319/// assert_eq!(cleared, CooldownPrecedence::Cleared);
320///
321/// let blocked = cooldown_precedence(
322/// None,
323/// &NormalizedName::for_test("left-pad"),
324/// "2.0.0",
325/// Some(PublishTime::from_unix_secs(1_000)),
326/// CooldownWindow::from_secs(5_000),
327/// PublishTime::from_unix_secs(2_000),
328/// );
329/// assert!(matches!(blocked, CooldownPrecedence::Blocked(_)));
330/// ```
331#[must_use]
332pub fn cooldown_precedence(
333 gossip_prefetch: Option<&HashMap<NormalizedName, GossipFindings>>,
334 name: &NormalizedName,
335 version: &str,
336 published_at: Option<PublishTime>,
337 cooldown: CooldownWindow,
338 now: PublishTime,
339) -> CooldownPrecedence {
340 match gossip_cooldown_for(gossip_prefetch, name, version, now) {
341 GossipCooldownLookup::Active => CooldownPrecedence::Blocked(CooldownBlocker::Gossip),
342 GossipCooldownLookup::NotActive => CooldownPrecedence::Cleared,
343 GossipCooldownLookup::Unavailable => local_cooldown_precedence(published_at, cooldown, now),
344 }
345}
346
347/// The local freshness heuristic alone (`published_at` age against `cooldown`), without GOSSIP.
348///
349/// Extracted from [`cooldown_precedence`]'s `Unavailable` arm so every site that evaluates the
350/// local rule by itself — that arm, and [`cooldown_disposition`]'s read-time fallback
351/// re-evaluation — shares one implementation rather than reimplementing the age comparison.
352///
353/// # Examples
354///
355/// ```
356/// use deps_core::lsp_helpers::{CooldownPrecedence, local_cooldown_precedence};
357/// use deps_core::{CooldownWindow, PublishTime};
358///
359/// let now = PublishTime::from_unix_secs(2_000);
360/// let cooldown = CooldownWindow::from_secs(500);
361///
362/// // No known publish time: never blocked.
363/// assert_eq!(
364/// local_cooldown_precedence(None, cooldown, now),
365/// CooldownPrecedence::Cleared
366/// );
367///
368/// // Published recently: blocked.
369/// let recent = PublishTime::from_unix_secs(1_900);
370/// assert!(matches!(
371/// local_cooldown_precedence(Some(recent), cooldown, now),
372/// CooldownPrecedence::Blocked(_)
373/// ));
374///
375/// // Age exactly equal to the window: cleared (the bound is exclusive).
376/// let at_boundary = PublishTime::from_unix_secs(1_500);
377/// assert_eq!(
378/// local_cooldown_precedence(Some(at_boundary), cooldown, now),
379/// CooldownPrecedence::Cleared
380/// );
381/// ```
382#[must_use]
383pub fn local_cooldown_precedence(
384 published_at: Option<PublishTime>,
385 cooldown: CooldownWindow,
386 now: PublishTime,
387) -> CooldownPrecedence {
388 match published_at {
389 Some(published_at) if cooldown.contains(published_at.age_secs_from(now)) => {
390 CooldownPrecedence::Blocked(CooldownBlocker::Local { published_at })
391 }
392 _ => CooldownPrecedence::Cleared,
393 }
394}
395
396/// Evaluates, at read time, whether [`PackageVersions::latest`] is blocked by the freshness
397/// cooldown and whether a stored [`PackageVersions::cooldown_fallback`] candidate is available.
398///
399/// Spec 075 FR-004's single precedence function, shared by `apply_outdated_rule`
400/// (check/diagnostics wording) and `deps-cli update`'s planner so the two commands can no
401/// longer disagree (spec 075 NFR-001 steps 0-4; OSV verification is deliberately NOT this
402/// function's job — see spec 075 FR-010/FR-011). The GOSSIP-vs-local precedence itself is
403/// [`cooldown_precedence`]; this function adds the read-time fallback re-evaluation on top.
404///
405/// # Examples
406///
407/// ```
408/// use deps_core::lsp_helpers::{CooldownDisposition, PackageVersions, cooldown_disposition};
409/// use deps_core::{FreshnessSettings, NormalizedName, PublishTime};
410/// use std::sync::Arc;
411///
412/// let versions = PackageVersions::new(
413/// "2.0.0".into(),
414/// Arc::from(vec!["2.0.0".into(), "1.0.0".into()]),
415/// )
416/// .with_published_at(PublishTime::from_unix_secs(1_000));
417///
418/// let disposition = cooldown_disposition(
419/// &versions,
420/// &NormalizedName::for_test("left-pad"),
421/// FreshnessSettings::Enabled {
422/// cooldown: deps_core::CooldownWindow::from_secs(500),
423/// },
424/// None,
425/// None,
426/// PublishTime::from_unix_secs(2_000),
427/// );
428/// assert_eq!(disposition, CooldownDisposition::Cleared);
429///
430/// let blocked = cooldown_disposition(
431/// &versions,
432/// &NormalizedName::for_test("left-pad"),
433/// FreshnessSettings::Enabled {
434/// cooldown: deps_core::CooldownWindow::from_secs(5_000),
435/// },
436/// None,
437/// None,
438/// PublishTime::from_unix_secs(2_000),
439/// );
440/// assert!(matches!(blocked, CooldownDisposition::Blocked { .. }));
441/// ```
442#[must_use]
443pub fn cooldown_disposition<'a>(
444 versions: &'a PackageVersions,
445 name: &NormalizedName,
446 freshness: crate::freshness::FreshnessSettings,
447 gossip_prefetch: Option<&HashMap<NormalizedName, GossipFindings>>,
448 native: Option<&NativeGate<'a>>,
449 now: PublishTime,
450) -> CooldownDisposition<'a> {
451 let freshness_disposition =
452 freshness_disposition(versions, name, freshness, gossip_prefetch, now);
453 let Some(gate) = native else {
454 return freshness_disposition;
455 };
456 if !gate.excludes(
457 versions.published_at_of(&versions.latest),
458 &versions.latest,
459 gate.now(),
460 ) {
461 return freshness_disposition;
462 }
463 let fallback = match freshness_disposition {
464 CooldownDisposition::Blocked { fallback, .. } => fallback.filter(|fallback| {
465 !gate.excludes(Some(fallback.published_at), &fallback.version, gate.now())
466 }),
467 CooldownDisposition::NotEvaluated
468 | CooldownDisposition::Cleared
469 | CooldownDisposition::NativeHeld { .. } => None,
470 };
471 CooldownDisposition::NativeHeld {
472 cooldown: gate.cooldown(),
473 fallback,
474 }
475}
476
477/// The freshness-cooldown half of [`cooldown_disposition`]: GOSSIP-vs-local precedence plus the
478/// read-time fallback re-evaluation, with no native window involved.
479fn freshness_disposition<'a>(
480 versions: &'a PackageVersions,
481 name: &NormalizedName,
482 freshness: crate::freshness::FreshnessSettings,
483 gossip_prefetch: Option<&HashMap<NormalizedName, GossipFindings>>,
484 now: PublishTime,
485) -> CooldownDisposition<'a> {
486 let crate::freshness::FreshnessSettings::Enabled { cooldown } = freshness else {
487 return CooldownDisposition::NotEvaluated;
488 };
489
490 // NFR-002 (M3): the stored fallback candidate is itself re-evaluated at read time — a
491 // cooldown window narrowed between fetch and read (or, for a long-lived LSP cache, simply
492 // enough wall-clock time passing that the fetch-time computation has gone stale in the
493 // *other* direction the caller didn't ask about) must never let a candidate that no
494 // longer clears the window keep reading as usable. This can only make the outcome
495 // stricter, never less safe — a `None` fallback stays `None`.
496 let fallback = versions.cooldown_fallback.as_ref().filter(|fallback| {
497 matches!(
498 local_cooldown_precedence(Some(fallback.published_at), cooldown, now),
499 CooldownPrecedence::Cleared
500 )
501 });
502
503 match cooldown_precedence(
504 gossip_prefetch,
505 name,
506 versions.latest.as_str(),
507 versions.published_at,
508 cooldown,
509 now,
510 ) {
511 CooldownPrecedence::Cleared => CooldownDisposition::Cleared,
512 CooldownPrecedence::Blocked(by) => CooldownDisposition::Blocked { by, fallback },
513 }
514}
515
516/// Result of [`fallback_edit_excludes_newer`] (spec 076 FR-023): whether the ecosystem's
517/// default-rendered fallback edit is safe to write.
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub enum FallbackEditVerdict {
520 /// The edit is safe: applying and re-parsing it still excludes every known `available`
521 /// version newer than the fallback candidate.
522 Writable,
523 /// The edit was rejected — see [`FallbackEditRejection`] for which check failed.
524 Rejected(FallbackEditRejection),
525}
526
527/// Which [`fallback_edit_excludes_newer`] check rejected the fallback edit, in evaluation
528/// order (first failure wins; phase 2 is only reached once every phase-1 check passes).
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum FallbackEditRejection {
531 /// Precondition (round-4 critic D5, fix-cycle M2): `candidate`'s span does not equal this
532 /// occurrence's own `Dependency::version_range()` — the edit was built for a different
533 /// occurrence (or a stale one), so nothing below is meaningful for THIS dependency.
534 /// Production always passes equality (the edit is always built from the same dependency's
535 /// own `version_range()`); this guards the public API against a caller passing a
536 /// mismatched edit.
537 CandidateSpanMismatch,
538 /// Fix-cycle (issue #1561/CWE-1284 class): `fallback` itself is absent from `available` —
539 /// a stale or inconsistent candidate computed against a version list that has since
540 /// changed. Checked once, shared by both d0 and d1, before either can read `fallback`'s
541 /// position: never infer "not a downgrade" from the absence of evidence.
542 FallbackUnlisted,
543 /// Phase 1, a0 pre-check (issue #1580, CWE-400 defense-in-depth mirroring #1472/#1578):
544 /// R0's raw string exceeds [`crate::lsp_helpers::MAX_REQUIREMENT_LEN`] —
545 /// `compile_bounded_requirement` is never called for it. A size-based fail-closed guard, distinct
546 /// from [`Self::OriginalUncompilable`] (a confirmed parse failure on an attempted compile).
547 OriginalOversized,
548 /// Phase 1, a0: the ORIGINAL declared requirement has no compiled matcher (e.g. GitHub
549 /// Actions/GitLab CI tag pins) — unchanged from spec 075.
550 OriginalUncompilable,
551 /// Phase 1, c0: the original requirement already reads the fallback as current (a
552 /// below-floor fallback, e.g. NuGet's bare-floor shape).
553 OriginalAlreadyUpToDate,
554 /// Phase 1, d0: the original requirement's own floor (the OLDEST `available` entry it
555 /// still matches) is newer than `fallback` — writing it would be a downgrade below what R0
556 /// already resolves to, or no listed entry evidences the floor at all (issues #1564/#1561:
557 /// fixed from an earlier "reject if anything newer also matches" reading, which rejected
558 /// nearly every permissive/auto-following requirement, and from a "no evidence means safe"
559 /// vacuous accept on an unlisted declared pin).
560 OriginalResolvesPastFallback,
561 /// Fix-cycle (#1571): the original declared requirement admits some entry strictly newer
562 /// than `fallback`, or a matcher-reported `!=`-style term explicitly bans `fallback`
563 /// (`RequirementMatcher::explicitly_excludes`), yet `fallback` itself fails
564 /// `r0_matcher.matches` — `fallback` sits inside R0's nominal span (or one of its `||`
565 /// branches, for an ecosystem with alternation) but is punched out of it (a `!=` term, or a
566 /// `||`-alternation gap), which a bare floor-position comparison (d0 above) cannot see since
567 /// neither hole shape moves the floor. Distinct from the legitimate case where `fallback`
568 /// fails `r0_matcher.matches` only because it exceeds every branch's ceiling entirely
569 /// (FR-025's out-of-range acceptance).
570 OriginalExcludesFallback,
571 /// The edited manifest could not be re-parsed (FR-024) — [`crate::edit::ManifestReparse`]
572 /// returned `None`, e.g. an `Ecosystem::parse_manifest_sync` override or default that itself
573 /// fails to parse the edited scratch copy.
574 ReparseFailed,
575 /// The re-parsed manifest did not contain exactly one dependency matching this occurrence's
576 /// `(normalized name, version_range.start)`.
577 OccurrenceNotUnique,
578 /// Phase 2, a1 pre-check: same guard as [`Self::OriginalOversized`], applied to R1 (the
579 /// re-parsed EDITED requirement) before its own `compile_bounded_requirement` attempt.
580 EditedOversized,
581 /// Phase 2, a1: the re-parsed, EDITED requirement has no compiled matcher.
582 EditedUncompilable,
583 /// Phase 2, b1: the edited requirement's matcher does not accept the fallback itself — the
584 /// written edit does not actually express the fallback version.
585 EditedExcludesFallback,
586 /// Phase 2, d1: the edited (WRITTEN) requirement admits some `available` entry strictly
587 /// newer than the fallback — the edit auto-follows back into an in-cooldown version. Unlike
588 /// d0, this is NOT a floor comparison: an auto-following range (Cargo's caret, Dart's caret,
589 /// PyPI's default `>=X,<next`) has its floor AT the fallback itself by construction (the
590 /// edit was rendered FROM `fallback`), so a floor check alone would never catch a range that
591 /// also admits something newer above it — exactly the case round-1 critic S1 exists to
592 /// reject (spec 076 §1's documented, intentional fail-closed outcome for these ecosystems).
593 EditedAdmitsNewer,
594}
595
596/// Spec 076 FR-023/FR-024: THE uniform guard deciding whether a cooldown-fallback candidate's
597/// default-rendered edit is safe to write.
598///
599/// Applied identically to spec 075's lockfile-resolved path and spec 076's no-lockfile path —
600/// no per-ecosystem override or retry (FR-025).
601///
602/// Two phases, evaluated in this exact order, first failure wins:
603///
604/// - **Phase 1**, on `R0 = dep.version_requirement()` (the ORIGINAL declared requirement, no
605/// parse needed): a0-pre (issue #1580, CWE-400 defense-in-depth) R0 must not be
606/// [`BoundedVersionReq::new`] (i.e. not [`requirement_is_oversized`]) — `compile_bounded_requirement`
607/// is never called for an oversized requirement; a0 `compile_bounded_requirement(R0)` must be
608/// `Some`; c0 `is_bounded_requirement_up_to_date(R0, fallback)` must be `false` (closes a NuGet bare-floor gap,
609/// spec 076 round-1 critic S2); d0 no `available` entry STRICTLY newer than `fallback` may
610/// satisfy `bounded_requirement_already_resolves_to(R0, entry)` (anti-downgrade — writing `fallback`
611/// must not move resolution backward relative to what R0 already resolves to); fix-cycle #1571:
612/// when `fallback` itself does not match R0's compiled matcher, R0 must not directly report
613/// `fallback` as `!=`-excluded ([`RequirementMatcher::explicitly_excludes`]) and it must not
614/// be the case that some entry strictly newer than `fallback` still matches R0 — otherwise
615/// `fallback` sits inside R0's nominal span (or a `||` branch's) but not R0 itself (a `!=`
616/// term or a `||`-alternation gap), which the floor comparison alone cannot see
617/// ([`FallbackEditRejection::OriginalExcludesFallback`]).
618/// - **Re-parse** (only if phase 1 passes, FR-024): `candidate` is applied to a scratch copy of
619/// `content`, the copy is re-parsed via `reparse`, and the edited occurrence is located by
620/// `(formatter.normalize_package_name(dep.name()), version_range().start)` — NOT `name_range`,
621/// since some grammars (NuGet's `Version`-before-`Include` attribute order, Maven's XML
622/// element order, Gradle's map notation) put the version before the name, so `name_range`
623/// would shift under the edit and silently fail closed. Exactly one match is required; zero
624/// or more than one is [`FallbackEditRejection::OccurrenceNotUnique`].
625/// - **Phase 2**, on `R1` = the located occurrence's re-parsed requirement: a1-pre, the same
626/// [`BoundedVersionReq::new`] guard as a0-pre, applied to R1 before its own
627/// `compile_bounded_requirement` attempt; a1 `compile_bounded_requirement(R1)` must be `Some`; b1 R1's
628/// matcher must accept `fallback` itself
629/// (`Some(true)`) — proving the written edit actually expresses `fallback`, failing closed for
630/// an unmodellable/unsatisfiable written requirement; d1 no `available` entry STRICTLY newer
631/// than `fallback` may satisfy `bounded_requirement_already_resolves_to(R1, entry)` (the edit must not
632/// auto-follow back into a known newer, still-in-cooldown version).
633///
634/// Yanked entries in `available` are NOT excluded from the d0/d1 scans — conservative,
635/// fail-closed: a yanked newer version admitted by the requirement still rejects the fallback.
636///
637/// # Examples
638///
639/// ```
640/// use deps_core::edit::ManifestEdit;
641/// use deps_core::lsp_helpers::{
642/// BoundedVersionReq, DiagnosticMessages, DiagnosticPolicy, FallbackEditRejection, FallbackEditVerdict,
643/// OsvNaming, PackageNaming, PackageRendering, RequirementMatcher, RequirementResolution,
644/// SourcePolicy, fallback_edit_excludes_newer,
645/// };
646/// use deps_core::position::{Position, Range};
647/// use deps_core::{ConcreteVersion, Dependency, PackageName, ParseResult, VersionReq};
648///
649/// struct ExactMatcher(String);
650/// impl RequirementMatcher for ExactMatcher {
651/// fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
652/// Some(version.as_str() == self.0)
653/// }
654/// fn strict_prerelease_exclusion(&self) -> bool {
655/// false
656/// }
657/// }
658///
659/// struct ExactFormatter;
660/// impl PackageNaming for ExactFormatter {}
661/// impl PackageRendering for ExactFormatter {
662/// fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
663/// version.to_string()
664/// }
665/// fn package_url(&self, name: &PackageName) -> String {
666/// name.as_str().to_string()
667/// }
668/// }
669/// impl RequirementResolution for ExactFormatter {
670/// fn compile_bounded_requirement(
671/// &self,
672/// requirement: BoundedVersionReq<'_>,
673/// ) -> Option<Box<dyn RequirementMatcher>> {
674/// Some(Box::new(ExactMatcher(requirement.as_str().to_string())))
675/// }
676/// }
677/// impl DiagnosticMessages for ExactFormatter {}
678/// impl DiagnosticPolicy for ExactFormatter {}
679/// impl SourcePolicy for ExactFormatter {}
680/// impl OsvNaming for ExactFormatter {}
681///
682/// struct ExactDependency;
683/// impl Dependency for ExactDependency {
684/// fn name(&self) -> &PackageName {
685/// static NAME: std::sync::LazyLock<PackageName> =
686/// std::sync::LazyLock::new(|| PackageName::new("pkg"));
687/// &NAME
688/// }
689/// fn name_range(&self) -> Range {
690/// Range::default()
691/// }
692/// fn version_requirement(&self) -> Option<&VersionReq> {
693/// static REQ: std::sync::LazyLock<VersionReq> =
694/// std::sync::LazyLock::new(|| VersionReq::new("1.0.0"));
695/// Some(&REQ)
696/// }
697/// fn version_range(&self) -> Option<Range> {
698/// Some(Range::new(Position::new(0, 0), Position::new(0, 6)))
699/// }
700/// fn source(&self) -> deps_core::parser::DependencySource {
701/// deps_core::parser::DependencySource::Registry
702/// }
703/// }
704///
705/// let formatter = ExactFormatter;
706/// let dep = ExactDependency;
707/// let candidate = ManifestEdit {
708/// range: Range::new(Position::new(0, 0), Position::new(0, 6)),
709/// new_text: "1.1.0".to_string(),
710/// };
711/// let fallback = ConcreteVersion::new("1.1.0");
712/// let available = [ConcreteVersion::new("1.1.0"), ConcreteVersion::new("1.0.0")];
713/// // A stub `ManifestReparse` that always fails — demonstrates the fail-closed re-parse gate.
714/// let reparse = |_content: &str| -> Option<Box<dyn ParseResult>> { None };
715///
716/// let verdict = fallback_edit_excludes_newer(
717/// &formatter,
718/// &reparse,
719/// "1.0.0",
720/// &dep,
721/// &candidate,
722/// &fallback,
723/// &available,
724/// );
725/// assert_eq!(
726/// verdict,
727/// FallbackEditVerdict::Rejected(FallbackEditRejection::ReparseFailed)
728/// );
729/// ```
730#[must_use]
731pub fn fallback_edit_excludes_newer(
732 formatter: &dyn crate::lsp_helpers::EcosystemFormatter,
733 reparse: &dyn crate::edit::ManifestReparse,
734 content: &str,
735 dep: &dyn Dependency,
736 candidate: &crate::edit::ManifestEdit,
737 fallback: &ConcreteVersion,
738 available: &[ConcreteVersion],
739) -> FallbackEditVerdict {
740 use FallbackEditRejection::{
741 CandidateSpanMismatch, EditedAdmitsNewer, EditedExcludesFallback, EditedOversized,
742 EditedUncompilable, FallbackUnlisted, OccurrenceNotUnique, OriginalAlreadyUpToDate,
743 OriginalExcludesFallback, OriginalOversized, OriginalResolvesPastFallback,
744 OriginalUncompilable, ReparseFailed,
745 };
746
747 // Precondition (D5, fix-cycle M2): `candidate` must target THIS occurrence's own span.
748 if Some(candidate.range) != dep.version_range() {
749 return FallbackEditVerdict::Rejected(CandidateSpanMismatch);
750 }
751
752 // Phase 1: R0, the ORIGINAL declared requirement — no parse needed.
753 let Some(r0) = dep.version_requirement() else {
754 return FallbackEditVerdict::Rejected(OriginalUncompilable);
755 };
756 // a0-pre (issue #1580, CWE-400 defense-in-depth mirroring #1472/#1578): fail closed before
757 // `compile_bounded_requirement` ever sees an oversized requirement string.
758 let Some(r0) = BoundedVersionReq::new(r0) else {
759 return FallbackEditVerdict::Rejected(OriginalOversized);
760 };
761 let Some(r0_matcher) = formatter.compile_bounded_requirement(r0) else {
762 return FallbackEditVerdict::Rejected(OriginalUncompilable);
763 };
764
765 // Fix-cycle (issues #1564/#1561, CWE-1284 class): `fallback`'s own position is looked up
766 // ONCE here and shared by d0/d1 below — fails closed instead of letting a "no evidence"
767 // absence read as "safe" the way `available.iter().take_while(|v| *v != fallback)` did when
768 // `fallback` was never found at all (it would scan to the end without ever short-circuiting,
769 // silently changing what the scan even means). Ordered after a0 so an ecosystem with no
770 // compiled requirement model (GitHub Actions, GitLab CI) logs the more informative
771 // `OriginalUncompilable` instead of `FallbackUnlisted` — same final `Rejected` outcome either
772 // way, this only affects the `tracing::debug!` reason.
773 let Some(fallback_pos) = available.iter().position(|v| v == fallback) else {
774 return FallbackEditVerdict::Rejected(FallbackUnlisted);
775 };
776
777 if formatter.is_bounded_requirement_up_to_date(r0, fallback) {
778 return FallbackEditVerdict::Rejected(OriginalAlreadyUpToDate);
779 }
780 // d0 (issues #1564/#1561 fix, matching #1565's shipped floor-comparison exactly): a FLOOR
781 // comparison over R0's raw admitted-set membership (`compile_bounded_requirement(..).matches`), not
782 // "does anything newer also match" and NOT `bounded_requirement_already_resolves_to` — that stricter
783 // predicate is deliberately always `false` for a floor-shaped requirement (NuGet's bare
784 // `Version="1.0.0"`, see its `bounded_requirement_already_resolves_to` doc), which would make this
785 // scan find no floor at all and fail closed on every floor-type ecosystem. `available` is
786 // newest-first, so the requirement's own floor — the OLDEST entry it still admits — sits at
787 // the LARGEST matching index. Accept iff that floor is at or after `fallback`'s own index
788 // (`fallback` is not older than what R0, left unedited, already resolves to); `None`
789 // (nothing evidences the floor at all, e.g. an unlisted declared pin) fails closed the same
790 // as a floor strictly newer than `fallback`.
791 let r0_floor = available
792 .iter()
793 .rposition(|v| r0_matcher.matches(v) == Some(true));
794 if r0_floor.is_none_or(|floor| floor < fallback_pos) {
795 return FallbackEditVerdict::Rejected(OriginalResolvesPastFallback);
796 }
797 // Fix-cycle (#1571): R0 admitting `fallback` inside its nominal span yet not `fallback`
798 // itself — a `!=`-style exclusion (PyPI/Composer/Bundler) or a `||`-alternation gap
799 // (Composer) punches a hole rather than shifting the floor, so the floor comparison above
800 // alone cannot see it. Two independent signals, either one rejects. `r0_floor ==
801 // Some(fallback_pos)` (code-review perf finding) means the floor scan above already proved
802 // `fallback` matches R0 — the floor is BY DEFINITION a matching index, so no need to call
803 // `matches` on `fallback` again for that common case.
804 let fallback_matches_r0 =
805 r0_floor == Some(fallback_pos) || r0_matcher.matches(fallback) == Some(true);
806 if !fallback_matches_r0 {
807 // (i) Intensional: the matcher itself names `fallback` as explicitly banned (critic
808 // fix-cycle S1 — `r0_matcher.explicitly_excludes` is the only way to tell a `!=` hole
809 // apart from a legitimate ceiling-exceeding fallback when NO listed `available` entry
810 // happens to evidence the hole either, e.g. `>=1.0,!=1.5.0,<2.0` with `fallback` ==
811 // 1.5.0 and `available` = [2.0.0, 1.5.0, 1.0.0] — 2.0.0 fails `matches` too (it's past
812 // the `<2.0` ceiling), so (ii) below is vacuous and only this direct check catches it).
813 if r0_matcher.explicitly_excludes(fallback) {
814 return FallbackEditVerdict::Rejected(OriginalExcludesFallback);
815 }
816 // (ii) Extensional, structural fallback net: some LISTED entry strictly newer than
817 // `fallback` still matches R0 (e.g. `r0_floor` (4) >= `fallback_pos` (2) passed above
818 // even though R0 explicitly excludes `fallback`, or a `||`-alternation gap like
819 // `^1.0 || ^3.0` with `fallback` = 2.5.0). A legitimate out-of-range fallback (e.g.
820 // Cargo's `^1.0` with fallback 2.5.0) has no R0-matching entry newer than it at all —
821 // FR-025's intentional ceiling-exceeding acceptance — so this never misfires on that
822 // case.
823 #[allow(clippy::indexing_slicing)]
824 let newer_than_fallback = &available[..fallback_pos];
825 if newer_than_fallback
826 .iter()
827 .any(|v| r0_matcher.matches(v) == Some(true))
828 {
829 return FallbackEditVerdict::Rejected(OriginalExcludesFallback);
830 }
831 }
832
833 // Re-parse (FR-024): apply the candidate edit to a scratch copy and re-parse it.
834 let edited_content = crate::edit::apply_edits(content, std::slice::from_ref(candidate));
835 let Some(parsed) = reparse.reparse(&edited_content) else {
836 return FallbackEditVerdict::Rejected(ReparseFailed);
837 };
838
839 // Locate the edited occurrence by (normalized name, version_range().start) — invariant
840 // under an edit that only changes text at or after it, unlike `name_range` (round-4 critic
841 // M3: NuGet/Maven/Gradle grammars can put the version before the name).
842 let key = formatter.normalize_package_name(dep.name());
843 let orig_start = dep.version_range().map(|r| r.start);
844 let mut candidates = parsed.dependencies().into_iter().filter(|edited_dep| {
845 formatter.normalize_package_name(edited_dep.name()) == key
846 && edited_dep.version_range().map(|r| r.start) == orig_start
847 });
848 let Some(edited_dep) = candidates.next() else {
849 return FallbackEditVerdict::Rejected(OccurrenceNotUnique);
850 };
851 if candidates.next().is_some() {
852 return FallbackEditVerdict::Rejected(OccurrenceNotUnique);
853 }
854
855 // Phase 2: R1, the re-parsed EDITED requirement.
856 let Some(r1) = edited_dep.version_requirement() else {
857 return FallbackEditVerdict::Rejected(EditedUncompilable);
858 };
859 // a1-pre: same guard as a0-pre, applied to R1.
860 let Some(r1) = BoundedVersionReq::new(r1) else {
861 return FallbackEditVerdict::Rejected(EditedOversized);
862 };
863 let Some(matcher) = formatter.compile_bounded_requirement(r1) else {
864 return FallbackEditVerdict::Rejected(EditedUncompilable);
865 };
866 if matcher.matches(fallback) != Some(true) {
867 return FallbackEditVerdict::Rejected(EditedExcludesFallback);
868 }
869 // d1 (round-1 critic S1) is deliberately NOT the d0 floor comparison: an auto-following
870 // range's floor sits at `fallback` itself by construction (the edit was rendered FROM
871 // `fallback`), so a floor check alone would never see that the SAME range also admits an
872 // entry strictly newer — the auto-follow case this check exists to catch. `fallback_pos` is
873 // `available.iter().position(..)`'s own result, so it is always `<= available.len()` and the
874 // slice below (every entry strictly newer than `fallback`, since `available` is newest-first)
875 // never panics — exact, not the fragile `take_while(|v| *v != fallback)` this replaced.
876 #[allow(clippy::indexing_slicing)]
877 let strictly_newer = &available[..fallback_pos];
878 if strictly_newer
879 .iter()
880 .any(|v| formatter.bounded_requirement_already_resolves_to(r1, v))
881 {
882 return FallbackEditVerdict::Rejected(EditedAdmitsNewer);
883 }
884
885 FallbackEditVerdict::Writable
886}
887
888/// Registry version data for one package, fetched together in a single round trip.
889///
890/// `latest` and `available` are deliberately asymmetric — this is load-bearing, not an
891/// oversight:
892/// - `latest` comes from this ecosystem's own `Registry::select_latest_matching(.., "*")`
893/// pick, which excludes yanked (and, for semver/node-semver `*`, prerelease) versions —
894/// the same value `get_latest_matching` returned before this type existed.
895/// - `available` is the **unfiltered** `get_versions` output: every published version,
896/// newest-first, yanked and prerelease entries included.
897///
898/// The unsatisfiable-requirement check (see `crate::lsp_helpers::requirement_is_unsatisfiable`)
899/// scans `available` and deliberately does not filter it: a requirement that only matches a
900/// yanked or prerelease version is still satisfied, so filtering `available` the same way
901/// `latest` is filtered would produce false "no published version satisfies" warnings.
902///
903/// `yanked` is the subset of `available` (same version-string encoding) that the registry
904/// reported as yanked/deprecated, paired with each entry's [`RemovalStatus`]. It exists
905/// because `Registry::get_latest_matching` — the call that used to populate this cache —
906/// filters yanked entries out by contract on every current registry implementation, so a
907/// per-version yanked flag threaded through *that* call would always read `false` (see
908/// #233). `available` now comes from the unfiltered `get_versions` instead, which does
909/// observe yanked entries, so `yanked` is derived from that same fetch rather than
910/// discarded.
911///
912/// The status rides alongside each version (rather than a bare membership list) so
913/// [`crate::lsp_helpers::generate_diagnostics_from_cache`]'s #247 "requirement satisfiable
914/// only by a yanked version" check can gate its own package-level-deprecation suppression
915/// on `AdvisoryDeprecated` specifically, never on a genuine `Yanked` finding — mirroring
916/// [`VersionData::outcomes`]'s D5 gate for the #263 in-use-version check (see #437).
917#[non_exhaustive]
918#[derive(Debug, Clone, PartialEq, Eq)]
919pub struct PackageVersions {
920 /// Latest usable version for this package.
921 pub latest: ConcreteVersion,
922 /// Every published version, newest-first, unfiltered.
923 pub available: Arc<[ConcreteVersion]>,
924 /// Subset of `available` reported as yanked/deprecated by the registry, each paired
925 /// with its [`RemovalStatus`].
926 pub yanked: Arc<[(ConcreteVersion, RemovalStatus)]>,
927 /// When `latest` was published, if the registry exposes it. `None` when
928 /// the ecosystem doesn't wire [`crate::Version::published_at`] or the fetch
929 /// never ran.
930 ///
931 /// Deliberately a field on this single per-package struct rather than a
932 /// second parallel map keyed alongside `latest` — the earlier two-map
933 /// design (issue #227 critique C3) let `latest` and its age drift apart
934 /// silently whenever one map was updated (e.g. lockfile-resolved
935 /// overwrite) without the other. Bundling them here makes that
936 /// desync impossible: whoever sets `latest` sets `published_at` too.
937 pub published_at: Option<crate::freshness::PublishTime>,
938 /// Set when a version was excluded from being [`Self::latest`] solely because of an
939 /// active GOSSIP cooldown finding whose version was strictly newer than the dependency's
940 /// already-in-use version (`deps-cli` spec 074, FR-003/FR-005's floor-protected filter —
941 /// round 1 correction: there is no local [`CooldownWindow`]-based
942 /// exclusion this unions with, the freshness cooldown window only ever rewords a
943 /// downstream diagnostic message).
944 /// `None` in the common case (GOSSIP disabled, no matching finding, or no active
945 /// cooldown), and in four further no-op cases where nothing was actually held back: the
946 /// protect floor fully neutralized the exclusion because the flagged version was itself
947 /// already in use and still the best available (C1a); no in-use version could be
948 /// resolved at all, so no floor could be constructed and GOSSIP deliberately excludes
949 /// nothing this fetch (C1b — the common case for a range requirement with no lockfile);
950 /// a floor exists but the ecosystem's own selection rules reject every remaining
951 /// candidate above it (S1); or a floor exists and a filtered pick is found, but that
952 /// pick's original (pre-filter) position is older than the floor itself — the floor
953 /// version survived filtering yet was rejected by the ecosystem's own selection rules
954 /// (e.g. an in-use prerelease/yanked version), leaving only an even-older release to be
955 /// picked, which would be a downgrade below the floor (S4). In all four cases the
956 /// unfiltered pick is reused instead. Purely an in-process outcome-reporting field: no
957 /// wire/schema format carries it.
958 pub gossip_excluded_version: Option<ConcreteVersion>,
959 /// The newest cooldown-cleared, ecosystem-safe, floor-protected candidate found for this
960 /// dependency when `latest` may be cooldown-blocked (`deps-cli update`'s fallback, spec
961 /// 075 FR-001/FR-002). Computed unconditionally whenever freshness is enabled, regardless
962 /// of whether `latest` itself is currently blocked — see [`cooldown_disposition`] for the
963 /// read-time decision of whether it is actually needed (spec 075 NFR-002). `None` when
964 /// freshness is disabled, no lockfile-resolved in-use version exists to floor the search
965 /// (spec 075 OQ1), or no candidate passed every guard.
966 pub cooldown_fallback: Option<CooldownFallback>,
967 /// Publish time of each entry of [`Self::available`], same order and length; empty when
968 /// unknown. Window-independent data read by the native publish-age gate.
969 pub publish_times: Arc<[Option<crate::freshness::PublishTime>]>,
970}
971
972impl PackageVersions {
973 /// Constructs a `PackageVersions` from its two required fields, with [`Self::yanked`] and
974 /// [`Self::published_at`] left empty/`None` — chain [`Self::with_yanked`] and/or
975 /// [`Self::with_published_at`] to attach them.
976 ///
977 /// Needed because [`Self`] is `#[non_exhaustive]`: a struct literal only works inside
978 /// this crate, so every other crate (including test code) must go through this
979 /// constructor instead.
980 ///
981 /// # Examples
982 ///
983 /// ```
984 /// use deps_core::{ConcreteVersion, PackageVersions};
985 /// use std::sync::Arc;
986 ///
987 /// let versions = PackageVersions::new(
988 /// ConcreteVersion::new("2.0.0"),
989 /// Arc::from(vec![ConcreteVersion::new("2.0.0"), ConcreteVersion::new("1.0.0")]),
990 /// );
991 /// assert_eq!(versions.latest, "2.0.0");
992 /// assert_eq!(versions.available.len(), 2);
993 /// assert!(versions.yanked.is_empty());
994 /// ```
995 #[must_use]
996 pub fn new(latest: ConcreteVersion, available: Arc<[ConcreteVersion]>) -> Self {
997 Self {
998 latest,
999 available,
1000 yanked: Arc::from(Vec::new()),
1001 published_at: None,
1002 gossip_excluded_version: None,
1003 cooldown_fallback: None,
1004 publish_times: Arc::from(Vec::new()),
1005 }
1006 }
1007
1008 /// Attaches the registry's yanked/deprecated-version findings. See [`Self::yanked`].
1009 #[must_use]
1010 pub fn with_yanked(mut self, yanked: Arc<[(ConcreteVersion, RemovalStatus)]>) -> Self {
1011 self.yanked = yanked;
1012 self
1013 }
1014
1015 /// Attaches when `latest` was published. See [`Self::published_at`].
1016 #[must_use]
1017 pub const fn with_published_at(mut self, published_at: crate::freshness::PublishTime) -> Self {
1018 self.published_at = Some(published_at);
1019 self
1020 }
1021
1022 /// Attaches the version a GOSSIP cooldown finding excluded from being [`Self::latest`].
1023 /// See [`Self::gossip_excluded_version`].
1024 #[must_use]
1025 pub fn with_gossip_excluded_version(mut self, excluded: ConcreteVersion) -> Self {
1026 self.gossip_excluded_version = Some(excluded);
1027 self
1028 }
1029
1030 /// Attaches per-version publish times. See [`Self::publish_times`].
1031 #[must_use]
1032 pub fn with_publish_times(
1033 mut self,
1034 publish_times: Arc<[Option<crate::freshness::PublishTime>]>,
1035 ) -> Self {
1036 self.publish_times = publish_times;
1037 self
1038 }
1039
1040 /// Publish time of `version`.
1041 ///
1042 /// Looked up by the version's position in [`Self::available`] when [`Self::publish_times`]
1043 /// is aligned with it. Otherwise (empty, or a length mismatch) only [`Self::latest`] is
1044 /// known, through [`Self::published_at`]. A version with no known time is `None`, which the
1045 /// native gate reads as eligible.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```
1050 /// use deps_core::{ConcreteVersion, PackageVersions, PublishTime};
1051 /// use std::sync::Arc;
1052 ///
1053 /// let versions = PackageVersions::new(
1054 /// ConcreteVersion::new("2.0.0"),
1055 /// Arc::from(vec![ConcreteVersion::new("2.0.0"), ConcreteVersion::new("1.0.0")]),
1056 /// )
1057 /// .with_publish_times(Arc::from(vec![None, Some(PublishTime::from_unix_secs(7))]));
1058 /// assert_eq!(
1059 /// versions.published_at_of(&ConcreteVersion::new("1.0.0")),
1060 /// Some(PublishTime::from_unix_secs(7))
1061 /// );
1062 /// assert_eq!(versions.published_at_of(&ConcreteVersion::new("2.0.0")), None);
1063 /// ```
1064 #[must_use]
1065 pub fn published_at_of(
1066 &self,
1067 version: &ConcreteVersion,
1068 ) -> Option<crate::freshness::PublishTime> {
1069 if self.publish_times.len() == self.available.len()
1070 && let Some(index) = self.available.iter().position(|v| v == version)
1071 {
1072 return self.publish_times.get(index).copied().flatten();
1073 }
1074 (*version == self.latest)
1075 .then_some(self.published_at)
1076 .flatten()
1077 }
1078
1079 /// Attaches the computed cooldown-fallback candidate. See [`Self::cooldown_fallback`].
1080 #[must_use]
1081 pub fn with_cooldown_fallback(mut self, fallback: CooldownFallback) -> Self {
1082 self.cooldown_fallback = Some(fallback);
1083 self
1084 }
1085
1086 /// Builds a `PackageVersions` from only the "latest" version string, with `available`
1087 /// populated as the single-element list `[latest]`.
1088 ///
1089 /// **Test-only in intent.** The one-element `available` this produces is a real, if
1090 /// small, version list — it is not "empty/unknown", so `requirement_is_unsatisfiable`
1091 /// will evaluate a requirement against it. Do **not** use this for a lock-file-only
1092 /// population path that has no real version list to offer (use
1093 /// [`latest_without_list`](Self::latest_without_list) there instead, which leaves
1094 /// `available` genuinely empty) — that exact substitution is the false-positive N5 was
1095 /// written to prevent: it would let the unsatisfiable-requirement check produce a
1096 /// verdict against a fabricated one-entry list before any registry fetch has run. Real
1097 /// registry fetches always populate `available` from the full `get_versions` result
1098 /// instead of using either constructor.
1099 ///
1100 /// # Examples
1101 ///
1102 /// ```
1103 /// use deps_core::{ConcreteVersion, PackageVersions};
1104 ///
1105 /// let versions = PackageVersions::latest_only("1.0.214");
1106 /// assert_eq!(versions.latest, "1.0.214");
1107 /// assert_eq!(&*versions.available, &[ConcreteVersion::new("1.0.214")]);
1108 /// ```
1109 pub fn latest_only(latest: impl Into<ConcreteVersion>) -> Self {
1110 let latest = latest.into();
1111 let available = Arc::from(vec![latest.clone()]);
1112 Self {
1113 latest,
1114 available,
1115 yanked: Arc::from(Vec::new()),
1116 published_at: None,
1117 gossip_excluded_version: None,
1118 cooldown_fallback: None,
1119 publish_times: Arc::from(Vec::new()),
1120 }
1121 }
1122
1123 /// Builds a `PackageVersions` with no version list — used where only the "latest" value
1124 /// is known and probing further would be misleading, notably the lock-file population
1125 /// path (`crates/deps-lsp/src/document/lifecycle.rs`), which must not populate a
1126 /// plausible-looking one-element `available` list before any registry fetch has run: the
1127 /// unsatisfiable-requirement check treats an empty `available` as "still loading, skip".
1128 ///
1129 /// # Examples
1130 ///
1131 /// ```
1132 /// use deps_core::PackageVersions;
1133 ///
1134 /// let versions = PackageVersions::latest_without_list("1.0.195");
1135 /// assert_eq!(versions.latest, "1.0.195");
1136 /// assert!(versions.available.is_empty());
1137 /// ```
1138 pub fn latest_without_list(latest: impl Into<ConcreteVersion>) -> Self {
1139 Self {
1140 latest: latest.into(),
1141 available: Arc::from(Vec::new()),
1142 yanked: Arc::from(Vec::new()),
1143 published_at: None,
1144 gossip_excluded_version: None,
1145 cooldown_fallback: None,
1146 publish_times: Arc::from(Vec::new()),
1147 }
1148 }
1149}
1150
1151/// Looks up `dep` in the registry cache under its normalized name.
1152///
1153/// The lookup for a caller that holds a raw cache map plus the dependency and its formatter
1154/// (the fix-target snapshot, `deps-engine`'s OSV classification). A case-folding ecosystem such
1155/// as Composer therefore resolves a dependency the same way on every path (#1832).
1156///
1157/// # Examples
1158///
1159/// ```
1160/// use deps_core::lsp_helpers::{PackageNaming, PackageVersions, cached_package_versions};
1161/// use deps_core::position::Range;
1162/// use deps_core::{CachedVersionsMap, Dependency, PackageKey, PackageName, VersionReq};
1163///
1164/// struct Lowercase;
1165/// impl PackageNaming for Lowercase {
1166/// fn normalized_spelling(&self, name: &PackageName) -> String {
1167/// name.as_str().to_lowercase()
1168/// }
1169/// }
1170///
1171/// # struct Dep(PackageName);
1172/// # impl Dependency for Dep {
1173/// # fn name(&self) -> &PackageName { &self.0 }
1174/// # fn name_range(&self) -> Range { Range::default() }
1175/// # fn version_requirement(&self) -> Option<&VersionReq> { None }
1176/// # fn version_range(&self) -> Option<Range> { None }
1177/// # fn source(&self) -> deps_core::parser::DependencySource {
1178/// # deps_core::parser::DependencySource::Registry
1179/// # }
1180/// # }
1181/// let dep = Dep(PackageName::new("Monolog/Monolog"));
1182/// let mut cached = CachedVersionsMap::new();
1183/// cached.insert(
1184/// PackageKey::new(dep.name(), &Lowercase).normalized().clone(),
1185/// PackageVersions::latest_only("3.0.0"),
1186/// );
1187///
1188/// let hit = cached_package_versions(&cached, &dep, &Lowercase);
1189/// assert_eq!(hit.map(|v| v.latest.as_str()), Some("3.0.0"));
1190/// ```
1191#[must_use]
1192pub fn cached_package_versions<'m>(
1193 cached: &'m CachedVersionsMap,
1194 dep: &dyn Dependency,
1195 naming: &(impl PackageNaming + ?Sized),
1196) -> Option<&'m PackageVersions> {
1197 cached.get(PackageKey::new(dep.name(), naming).normalized())
1198}
1199
1200/// Everything the lifecycle fetch learned about one package, keyed by its normalized name.
1201///
1202/// All three channels can hold simultaneously for the same package — this is load-bearing,
1203/// not an incidental shape. The D5 status gate in
1204/// [`generate_diagnostics_from_cache`] reads the [`Self::deprecation`] and [`Self::yanked`]
1205/// entries for the same normalized name together and compares their [`RemovalStatus`], and on
1206/// the didChange path a surviving deprecation can coexist with a later fetch failure. A single
1207/// enum variant per package could not express that overlap.
1208#[non_exhaustive]
1209#[derive(Debug, Clone, Default, PartialEq)]
1210pub struct DependencyOutcome {
1211 /// The version found yanked (the in-use version, or `latest` when only `latest` itself is
1212 /// yanked), paired with its [`RemovalStatus`]. See [`VersionData::outcomes`]'s prior
1213 /// semantics (#233/#263).
1214 pub yanked: Option<(ConcreteVersion, RemovalStatus)>,
1215 /// Package-level deprecation finding (#205). See [`Deprecation`].
1216 pub deprecation: Option<Deprecation>,
1217 /// Registry fetch errored, timed out, or was never attempted (#267). See [`FetchFailure`].
1218 pub fetch_failure: Option<FetchFailure>,
1219 /// The registry answered, but the lookup produced nothing usable: see [`LookupMiss`].
1220 /// Distinct from both an absent [`DependencyOutcome`] entry ("never fetched") and
1221 /// [`Self::fetch_failure`] ("couldn't be asked"). The two [`LookupMiss`] variants are
1222 /// mutually exclusive by construction.
1223 pub lookup_miss: Option<LookupMiss>,
1224}
1225
1226/// Why a successfully answered registry lookup yielded no usable "latest" version.
1227///
1228/// No variant is a [`FetchFailure`]: the registry was reachable and replied, or never asked.
1229/// Exhaustive on purpose so every consumer must handle a new variant.
1230///
1231/// # Examples
1232///
1233/// ```
1234/// use deps_core::lsp_helpers::LookupMiss;
1235///
1236/// assert_ne!(LookupMiss::NotFound, LookupMiss::NoComparableVersions);
1237/// ```
1238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1239pub enum LookupMiss {
1240 /// The registry endpoint itself answered "no such package" (e.g. HTTP 404).
1241 NotFound,
1242 /// The fetch succeeded but no published version is comparable with the requirement,
1243 /// e.g. a GitHub repository whose only tag `v1` is not full semver (#550).
1244 NoComparableVersions,
1245 /// The miss was decided locally (policy, configuration, an unexpanded template), so no
1246 /// registry was asked and nothing is known about the package's existence (#1901). Never
1247 /// surfaced to the user; recorded so "no cache entry" is not misread as "unknown package".
1248 NotLookedUp,
1249}
1250
1251impl DependencyOutcome {
1252 /// True when none of the channels are set.
1253 #[must_use]
1254 pub const fn is_empty(&self) -> bool {
1255 self.yanked.is_none()
1256 && self.deprecation.is_none()
1257 && self.fetch_failure.is_none()
1258 && self.lookup_miss.is_none()
1259 }
1260}
1261
1262/// Normalized-package-name -> [`DependencyOutcome`] map.
1263///
1264/// A newtype rather than a bare `HashMap` so the empty-entry pruning invariant (an entry is
1265/// removed once all of its channels are cleared) lives in one place, and so test
1266/// fixtures get chainable `with_*` constructors instead of building three ad-hoc `HashMap`s.
1267/// Keyed by plain normalized name — unlike [`crate::osv::VulnerabilityMap`], which is keyed by
1268/// [`crate::osv::VulnKey`] to disambiguate multiple occurrences of one name.
1269#[derive(Debug, Clone, Default, PartialEq)]
1270pub struct DependencyOutcomes(HashMap<NormalizedName, DependencyOutcome>);
1271
1272impl DependencyOutcomes {
1273 /// Creates an empty map.
1274 #[must_use]
1275 pub fn new() -> Self {
1276 Self::default()
1277 }
1278
1279 /// Looks up the full outcome recorded for `name`.
1280 #[must_use]
1281 pub fn get(&self, name: &NormalizedName) -> Option<&DependencyOutcome> {
1282 self.0.get(name)
1283 }
1284
1285 /// Looks up the yanked-version finding for `name`.
1286 #[must_use]
1287 pub fn yanked(&self, name: &NormalizedName) -> Option<&(ConcreteVersion, RemovalStatus)> {
1288 self.0.get(name)?.yanked.as_ref()
1289 }
1290
1291 /// Looks up the package-level deprecation finding for `name`.
1292 #[must_use]
1293 pub fn deprecation(&self, name: &NormalizedName) -> Option<&Deprecation> {
1294 self.0.get(name)?.deprecation.as_ref()
1295 }
1296
1297 /// Looks up the fetch-failure finding for `name`.
1298 #[must_use]
1299 pub fn fetch_failure(&self, name: &NormalizedName) -> Option<&FetchFailure> {
1300 self.0.get(name)?.fetch_failure.as_ref()
1301 }
1302
1303 /// Looks up why the registry lookup for `name` yielded no usable version (#550, #1891).
1304 #[must_use]
1305 pub fn lookup_miss(&self, name: &NormalizedName) -> Option<LookupMiss> {
1306 self.0.get(name)?.lookup_miss
1307 }
1308
1309 /// Records a yanked-version finding for `name`, creating the entry if absent.
1310 pub fn set_yanked(&mut self, name: NormalizedName, yanked: (ConcreteVersion, RemovalStatus)) {
1311 self.0.entry(name).or_default().yanked = Some(yanked);
1312 }
1313
1314 /// Records a package-level deprecation finding for `name`, creating the entry if absent.
1315 pub fn set_deprecation(&mut self, name: NormalizedName, deprecation: Deprecation) {
1316 self.0.entry(name).or_default().deprecation = Some(deprecation);
1317 }
1318
1319 /// Records a fetch-failure finding for `name`, creating the entry if absent.
1320 pub fn set_fetch_failure(&mut self, name: NormalizedName, failure: FetchFailure) {
1321 self.0.entry(name).or_default().fetch_failure = Some(failure);
1322 }
1323
1324 /// Records a fetch-failure finding for `name` only if one is not already recorded,
1325 /// creating the entry if absent.
1326 pub fn set_fetch_failure_if_absent(&mut self, name: NormalizedName, failure: FetchFailure) {
1327 self.0
1328 .entry(name)
1329 .or_default()
1330 .fetch_failure
1331 .get_or_insert(failure);
1332 }
1333
1334 /// Records why `name`'s registry lookup yielded no usable version, creating the entry
1335 /// if absent and replacing any previous [`LookupMiss`].
1336 pub fn set_lookup_miss(&mut self, name: NormalizedName, miss: LookupMiss) {
1337 self.0.entry(name).or_default().lookup_miss = Some(miss);
1338 }
1339
1340 /// Clears the lookup-miss channel for `name`, pruning the entry if it becomes empty.
1341 pub fn clear_lookup_miss(&mut self, name: &NormalizedName) {
1342 if let Some(entry) = self.0.get_mut(name) {
1343 entry.lookup_miss = None;
1344 self.prune(name);
1345 }
1346 }
1347
1348 /// Clears the yanked-version channel for `name`, pruning the entry if it becomes empty.
1349 pub fn clear_yanked(&mut self, name: &NormalizedName) {
1350 if let Some(entry) = self.0.get_mut(name) {
1351 entry.yanked = None;
1352 self.prune(name);
1353 }
1354 }
1355
1356 /// Clears the deprecation channel for `name`, pruning the entry if it becomes empty.
1357 pub fn clear_deprecation(&mut self, name: &NormalizedName) {
1358 if let Some(entry) = self.0.get_mut(name) {
1359 entry.deprecation = None;
1360 self.prune(name);
1361 }
1362 }
1363
1364 /// Clears the fetch-failure channel for `name`, pruning the entry if it becomes empty.
1365 pub fn clear_fetch_failure(&mut self, name: &NormalizedName) {
1366 if let Some(entry) = self.0.get_mut(name) {
1367 entry.fetch_failure = None;
1368 self.prune(name);
1369 }
1370 }
1371
1372 /// Removes the whole entry for `name`, regardless of which channels are set.
1373 pub fn remove(&mut self, name: &NormalizedName) {
1374 self.0.remove(name);
1375 }
1376
1377 /// Clears the fetch-failure channel for every entry, pruning any that become empty.
1378 ///
1379 /// Used when a forced re-fetch (e.g. a live-reloaded registry-routing setting, deps-lsp
1380 /// issue #592) makes every previously recorded fetch-failure finding untrustworthy: the
1381 /// routing itself changed, so a failure recorded under the old routing must not survive
1382 /// to be merged with results fetched under the new one.
1383 pub fn clear_all_fetch_failures(&mut self) {
1384 let names: Vec<NormalizedName> = self.0.keys().cloned().collect();
1385 for name in names {
1386 self.clear_fetch_failure(&name);
1387 }
1388 }
1389
1390 fn prune(&mut self, name: &NormalizedName) {
1391 if self.0.get(name).is_some_and(DependencyOutcome::is_empty) {
1392 self.0.remove(name);
1393 }
1394 }
1395
1396 /// Number of entries currently stored.
1397 #[must_use]
1398 pub fn len(&self) -> usize {
1399 self.0.len()
1400 }
1401
1402 /// True when no entries are stored.
1403 #[must_use]
1404 pub fn is_empty(&self) -> bool {
1405 self.0.is_empty()
1406 }
1407
1408 /// Number of entries with a yanked-version finding, for logging/`Debug`.
1409 #[must_use]
1410 pub fn yanked_count(&self) -> usize {
1411 self.0.values().filter(|o| o.yanked.is_some()).count()
1412 }
1413
1414 /// Number of entries with a deprecation finding, for logging/`Debug`.
1415 #[must_use]
1416 pub fn deprecation_count(&self) -> usize {
1417 self.0.values().filter(|o| o.deprecation.is_some()).count()
1418 }
1419
1420 /// Number of entries with a fetch-failure finding, for logging/`Debug`.
1421 #[must_use]
1422 pub fn fetch_failure_count(&self) -> usize {
1423 self.0
1424 .values()
1425 .filter(|o| o.fetch_failure.is_some())
1426 .count()
1427 }
1428
1429 /// Chainable builder recording a yanked-version finding. Test/fixture ergonomics.
1430 #[must_use]
1431 pub fn with_yanked(
1432 mut self,
1433 name: NormalizedName,
1434 yanked: (ConcreteVersion, RemovalStatus),
1435 ) -> Self {
1436 self.set_yanked(name, yanked);
1437 self
1438 }
1439
1440 /// Chainable builder recording a package-level deprecation finding. Test/fixture
1441 /// ergonomics.
1442 #[must_use]
1443 pub fn with_deprecation(mut self, name: NormalizedName, deprecation: Deprecation) -> Self {
1444 self.set_deprecation(name, deprecation);
1445 self
1446 }
1447
1448 /// Chainable builder recording a fetch-failure finding. Test/fixture ergonomics.
1449 #[must_use]
1450 pub fn with_fetch_failure(mut self, name: NormalizedName, failure: FetchFailure) -> Self {
1451 self.set_fetch_failure(name, failure);
1452 self
1453 }
1454
1455 /// Chainable builder recording a lookup-miss finding (#550, #1891). Test/fixture
1456 /// ergonomics.
1457 #[must_use]
1458 pub fn with_lookup_miss(mut self, name: NormalizedName, miss: LookupMiss) -> Self {
1459 self.set_lookup_miss(name, miss);
1460 self
1461 }
1462}
1463
1464/// The three states [`gossip_cooldown_for`] can resolve to — deliberately distinct from a
1465/// plain `Option<&GossipCooldown>` (issue #1456 security/impl-critic review, S2).
1466///
1467/// A bare `Option` conflates "no GOSSIP data available for this version at all" with "GOSSIP
1468/// has data and it authoritatively says this version is not in cooldown", and both used to
1469/// fall through to the unattributed local heuristic — which can then show a cooldown callout
1470/// that directly contradicts what GOSSIP already knows, violating FR-002's "authoritative when
1471/// available" requirement.
1472///
1473/// Spec 075 FR-005 (R-S3) redefined [`Self::NotActive`] to require a parsed, past `end` —
1474/// a missing COOLDOWN finding is [`Self::Unavailable`], not [`Self::NotActive`]. The earlier
1475/// definition conflated "no data" with "confirmed clear", which was fail-open for a write
1476/// path (`deps-cli update`'s cooldown-fallback candidate, spec 075).
1477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1478pub enum GossipCooldownLookup {
1479 /// No GOSSIP data for this exact version — an absent entry, an FR-008 version mismatch,
1480 /// or a COOLDOWN finding with no cooldown at all (`findings.cooldown == None`, including
1481 /// a missing/unparseable `end`, spec 075 FR-005) — the caller falls back to
1482 /// [`local_cooldown_precedence`], unattributed.
1483 Unavailable,
1484 /// GOSSIP data is present for this exact version and confirms an active cooldown as of
1485 /// `now` (spec 072 FR-011's read-time `end > now` check) — the caller renders a
1486 /// GOSSIP-attributed callout. Carries no payload: no caller renders the cooldown's own
1487 /// `end`/`risk` today, only whether one is active — see [`gossip_cooldown_for`] for
1488 /// where that data is still available (`GossipFindings.cooldown`) if a future caller
1489 /// needs it.
1490 Active,
1491 /// GOSSIP data is present for this exact version and authoritatively reports a cooldown
1492 /// that has already ended (a parsed, past `end`) — the caller must render nothing here,
1493 /// never falling back to the local heuristic, which could contradict this answer.
1494 NotActive,
1495}
1496
1497/// Looks up the GOSSIP cooldown state for `name` in `gossip_prefetch`, applying spec 072
1498/// FR-008's version-equality gate against `comparand` and FR-011's read-time `end > now` check.
1499///
1500/// `comparand` is the version actually being displayed at this call site — hover's
1501/// `latest_line`, diagnostics' `package_versions.latest` — shared by
1502/// `hover::push_latest_hover_section`, `diagnostics::apply_outdated_rule`,
1503/// [`crate::lsp_helpers::cooldown_disposition`], and `deps-engine`'s fallback-candidate
1504/// computation (spec 075) so no call site can diverge on this gate.
1505///
1506/// See [`GossipCooldownLookup`]'s doc for why this returns a three-state enum rather than
1507/// `Option<&GossipCooldown>`.
1508///
1509/// # Examples
1510///
1511/// ```
1512/// use deps_core::NormalizedName;
1513/// use deps_core::deps_dev::{GossipCooldown, GossipRiskLevel};
1514/// use deps_core::lsp_helpers::{GossipCooldownLookup, gossip_cooldown_for};
1515/// use deps_core::test_util::stub_gossip_findings;
1516/// use deps_core::PublishTime;
1517/// use std::collections::HashMap;
1518///
1519/// let name = NormalizedName::for_test("left-pad");
1520/// let mut prefetch = HashMap::new();
1521/// prefetch.insert(
1522/// name.clone(),
1523/// stub_gossip_findings(
1524/// "1.3.0",
1525/// Some(GossipCooldown::new(
1526/// PublishTime::from_unix_secs(2_000),
1527/// GossipRiskLevel::High,
1528/// )),
1529/// ),
1530/// );
1531///
1532/// assert_eq!(
1533/// gossip_cooldown_for(Some(&prefetch), &name, "1.3.0", PublishTime::from_unix_secs(1_000)),
1534/// GossipCooldownLookup::Active
1535/// );
1536/// assert_eq!(
1537/// gossip_cooldown_for(Some(&prefetch), &name, "1.3.0", PublishTime::from_unix_secs(3_000)),
1538/// GossipCooldownLookup::NotActive
1539/// );
1540/// assert_eq!(
1541/// gossip_cooldown_for(None, &name, "1.3.0", PublishTime::now()),
1542/// GossipCooldownLookup::Unavailable
1543/// );
1544/// ```
1545#[must_use]
1546pub fn gossip_cooldown_for(
1547 gossip_prefetch: Option<&HashMap<NormalizedName, GossipFindings>>,
1548 name: &NormalizedName,
1549 comparand: &str,
1550 now: PublishTime,
1551) -> GossipCooldownLookup {
1552 let Some(findings) = gossip_prefetch.and_then(|m| m.get(name)) else {
1553 return GossipCooldownLookup::Unavailable;
1554 };
1555 if findings.version != comparand {
1556 return GossipCooldownLookup::Unavailable;
1557 }
1558 match findings.cooldown.as_ref() {
1559 Some(cooldown) if cooldown.is_active(now) => GossipCooldownLookup::Active,
1560 Some(_) => GossipCooldownLookup::NotActive,
1561 None => GossipCooldownLookup::Unavailable,
1562 }
1563}
1564
1565/// Wall-clock budget `deps-lsp`'s completion handler gives an ecosystem's
1566/// `generate_completions` before treating it as a timeout.
1567///
1568/// Past this, the handler skips the fallback search rather than treating a
1569/// fast-but-empty result as "genuinely no results"
1570/// (`crates/deps-lsp/src/handlers/completion.rs`).
1571///
1572/// A registry-backed completion path that retries internally on failure (e.g.
1573/// `deps-maven`'s `search`, #274) must size its own total retry budget to
1574/// exceed this constant: finishing sooner with an empty/error result is
1575/// indistinguishable, at the call site, from a query that legitimately has no
1576/// matches, and triggers a wasted (and, for a struggling registry, likely to also
1577/// fail) fallback search rather than the handler's existing skip-on-timeout path.
1578///
1579/// Lives here (ungated), not in [`crate::completion`] (`#[cfg(feature =
1580/// "lsp-responses")]`), and is re-exported from there for that feature's consumers:
1581/// a registry-backed completion path's own retry-budget constant (e.g. `deps-maven`'s
1582/// `RECENT_FAILURE_TTL`) is genuine `Registry::search` behavior, not LSP-response-shaped,
1583/// and must stay available under `--no-default-features` too (issue #1083 critic M1) —
1584/// one definition, not a hand-copied duplicate per feature state.
1585pub const COMPLETION_SEARCH_TIMEOUT: Duration = Duration::from_secs(2);
1586
1587/// Wall-clock budget hover and code-action generation give the primary
1588/// `Registry::get_versions_from` fetch for the dependency under the cursor.
1589///
1590/// Unlike completion, code lens, inlay hints, and the background fetch task, hover
1591/// and code actions previously awaited this call with no deadline at all — an
1592/// ecosystem whose registry client retries across several candidate URLs
1593/// sequentially (e.g. `deps-maven`'s Gradle Plugin Portal fallback) could multiply
1594/// `HttpCache`'s own per-request timeout into tens of seconds of blocked, user-facing
1595/// latency on a single hover or lightbulb request (issue #1204). This is the *only*
1596/// deadline needed to fix that: it wraps the whole `get_versions_from` future,
1597/// cancelling it — candidate-URL loop included — at the ecosystem-registry level, so
1598/// no per-ecosystem inner budget is required on top of it. On elapse, hover falls back
1599/// to its existing `.ok()`-based basic-card degradation (the same path a genuine fetch
1600/// error takes); code actions instead drop the speculative fix/unsat actions outright
1601/// (see [`NoLiveList::Unverified`]) rather than reusing that same fail-open path, since an
1602/// unverified yank check must not be treated as "not yanked". [`await_interactive_fetch`]
1603/// applies this budget and, with an [`InteractiveFetchGate`] attached, remembers the elapse so
1604/// the next request does not pay it again (#1830).
1605pub const REGISTRY_FETCH_BUDGET: Duration = Duration::from_secs(10);
1606
1607/// Converts UTF-16 offset to byte offset in a string.
1608///
1609/// LSP uses UTF-16 code units for character positions (for compatibility with
1610/// JavaScript and other languages). This function converts from UTF-16 offset
1611/// to byte offset for Rust string indexing.
1612///
1613/// # Arguments
1614///
1615/// * `s` - The string to index into
1616/// * `utf16_offset` - UTF-16 code unit offset (from LSP Position.character)
1617///
1618/// # Returns
1619///
1620/// Byte offset if valid, `None` if the UTF-16 offset is out of bounds.
1621///
1622/// # Examples
1623///
1624/// ```
1625/// # use deps_core::lsp_helpers::utf16_to_byte_offset;
1626/// // ASCII: UTF-16 offset equals byte offset
1627/// assert_eq!(utf16_to_byte_offset("hello", 2), Some(2));
1628///
1629/// // Unicode: "日本語" - each char is 3 bytes but 1 UTF-16 code unit
1630/// assert_eq!(utf16_to_byte_offset("日本語", 0), Some(0));
1631/// assert_eq!(utf16_to_byte_offset("日本語", 1), Some(3));
1632/// assert_eq!(utf16_to_byte_offset("日本語", 2), Some(6));
1633///
1634/// // Emoji: "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
1635/// assert_eq!(utf16_to_byte_offset("😀test", 2), Some(4));
1636/// ```
1637pub fn utf16_to_byte_offset(s: &str, utf16_offset: u32) -> Option<usize> {
1638 let mut utf16_count = 0u32;
1639 for (byte_idx, ch) in s.char_indices() {
1640 if utf16_count >= utf16_offset {
1641 return Some(byte_idx);
1642 }
1643 #[expect(
1644 clippy::cast_possible_truncation,
1645 reason = "char::len_utf16 always returns 1 or 2, so this cast never truncates"
1646 )]
1647 {
1648 utf16_count += ch.len_utf16() as u32;
1649 }
1650 }
1651 if utf16_count == utf16_offset {
1652 return Some(s.len());
1653 }
1654 None
1655}
1656
1657/// Converts a byte offset within `s` to a UTF-16 code unit offset (LSP `Position.character`).
1658///
1659/// `byte_offset` may be an arbitrary caller-supplied value: it is clamped to `s.len()` and
1660/// floored down to the nearest UTF-8 char boundary before use, so this never panics.
1661///
1662/// # Examples
1663///
1664/// ```
1665/// # use deps_core::lsp_helpers::byte_to_utf16_offset;
1666/// // ASCII: byte offset equals UTF-16 offset
1667/// assert_eq!(byte_to_utf16_offset("hello", 2), 2);
1668///
1669/// // Unicode: "日本語" - each char is 3 bytes but 1 UTF-16 code unit
1670/// assert_eq!(byte_to_utf16_offset("日本語", 0), 0);
1671/// assert_eq!(byte_to_utf16_offset("日本語", 3), 1);
1672/// assert_eq!(byte_to_utf16_offset("日本語", 6), 2);
1673///
1674/// // Emoji: "😀" is 4 bytes but 2 UTF-16 code units (surrogate pair)
1675/// assert_eq!(byte_to_utf16_offset("😀test", 4), 2);
1676///
1677/// // Never panics: an offset landing mid-character floors down to the start of that
1678/// // character, and an offset past the end saturates to the string's length.
1679/// assert_eq!(byte_to_utf16_offset("日本語", 1), 0); // inside the first character
1680/// assert_eq!(byte_to_utf16_offset("日本語", 999), 3); // past the end
1681/// ```
1682#[expect(
1683 clippy::string_slice,
1684 reason = "end is floor_char_boundary-clamped just above, mirroring the already-hardened \
1685 LineOffsetTable::byte_offset_to_position (lsp_helpers/mod.rs)"
1686)]
1687pub fn byte_to_utf16_offset(s: &str, byte_offset: usize) -> u32 {
1688 // Saturate rather than silently wrap: an LSP `Position.character` past `u32::MAX` UTF-16
1689 // units is already meaningless, but a wrapped value would be a wrong-but-plausible one
1690 // (#673 — the exact offset-math bug class #244 shipped).
1691 //
1692 // `byte_offset` is not guaranteed to be in bounds or on a char boundary (a caller-supplied
1693 // offset can be past `s.len()` or land mid-character); `floor_char_boundary` clamps both
1694 // — past-the-end saturates to `s.len()` and any other in-bounds index floors to the
1695 // nearest char boundary — mirroring `LineOffsetTable::byte_offset_to_position`
1696 // (lsp_helpers/mod.rs).
1697 let end = s.floor_char_boundary(byte_offset);
1698 u32::try_from(s[..end].encode_utf16().count()).unwrap_or(u32::MAX)
1699}
1700
1701/// Checks whether a cursor position falls within an LSP range (inclusive on both ends).
1702pub fn position_in_range(pos: Position, range: Range) -> bool {
1703 if pos.line < range.start.line || pos.line > range.end.line {
1704 return false;
1705 }
1706 if pos.line == range.start.line && pos.character < range.start.character {
1707 return false;
1708 }
1709 if pos.line == range.end.line && pos.character > range.end.character {
1710 return false;
1711 }
1712 true
1713}
1714
1715/// Whether `dep`'s `version_range()` is a degenerate, completion-only position with no
1716/// requirement behind it (e.g. Maven's `<version></version>`/self-closing `<version/>`) rather
1717/// than a real, non-empty range that happens to have no requirement (e.g. Gradle's
1718/// `version.ref` pointing at a dangling or rich-version alias, which spans the real
1719/// alias-reference text). Zero-width (`start == end`) is the discriminating signal —
1720/// `version_requirement().is_none()` alone is not, since both shapes share it.
1721pub(crate) fn version_range_is_synthetic_empty(dep: &dyn Dependency) -> bool {
1722 dep.version_requirement().is_none() && dep.version_range().is_some_and(|r| r.start == r.end)
1723}
1724
1725/// Resolves the [`ScanOutcome`] for one dependency occurrence.
1726///
1727/// Tries `keys`' version-qualified lookup key for `dep` first (from
1728/// `crate::osv::vulnerability_keys`, #394 S2 — distinguishes two occurrences of one name
1729/// pinned to different versions), then the ecosystem-normalized name, then `dep`'s declared
1730/// name.
1731///
1732/// The single shared fallback chain for every OSV-outcome consumer
1733/// (`diagnostics::apply_vulnerability_rule`, `diagnostics::skip_reason_notice`,
1734/// `hover::generate_hover`'s vulnerability section) — previously written out four times
1735/// independently (issue #1400), risking a future change to the fallback priority landing in
1736/// only some of them. `keys` is `Option` because a caller with no [`EcosystemId`] to give
1737/// `crate::osv::vulnerability_keys` (most test
1738/// fixtures) has none to pass. `key` stays a caller-supplied parameter rather than being
1739/// derived here: `diagnostics` precomputes it once per name range and shares it across both
1740/// this lookup and its own per-dependency loop, so `normalize_package_name` (an allocating
1741/// call) never runs twice for the same dependency.
1742///
1743/// # Examples
1744///
1745/// ```
1746/// use deps_core::lsp_helpers::{
1747/// DiagnosticMessages, DiagnosticPolicy, OsvNaming, PackageNaming, PackageRendering,
1748/// RequirementResolution, SourcePolicy, resolve_scan_outcome,
1749/// };
1750/// use deps_core::osv::{ScanOutcome, VulnerabilityMap};
1751/// use deps_core::position::{Position, Range};
1752/// use deps_core::{ConcreteVersion, Dependency, PackageName, VersionReq};
1753/// use std::any::Any;
1754///
1755/// struct SimpleDep {
1756/// name: PackageName,
1757/// name_range: Range,
1758/// }
1759///
1760/// impl Dependency for SimpleDep {
1761/// fn name(&self) -> &PackageName {
1762/// &self.name
1763/// }
1764/// fn name_range(&self) -> Range {
1765/// self.name_range
1766/// }
1767/// fn version_requirement(&self) -> Option<&VersionReq> {
1768/// None
1769/// }
1770/// fn version_range(&self) -> Option<Range> {
1771/// None
1772/// }
1773/// fn source(&self) -> deps_core::parser::DependencySource {
1774/// deps_core::parser::DependencySource::Registry
1775/// }
1776/// }
1777///
1778/// let dep = SimpleDep {
1779/// name: PackageName::new("time"),
1780/// name_range: Range::new(Position::new(0, 0), Position::new(0, 4)).into(),
1781/// };
1782/// let key = deps_core::PackageKey::new(dep.name(), &deps_core::test_util::StubFormatter::new());
1783///
1784/// let mut vulnerabilities = VulnerabilityMap::new();
1785/// vulnerabilities.insert(deps_core::test_util::vuln_key("time"), ScanOutcome::Clean);
1786///
1787/// // No `VulnKeys` map: falls back straight to the normalized name.
1788/// let outcome = resolve_scan_outcome(&vulnerabilities, &dep, None, &key);
1789/// assert!(matches!(outcome, Some(ScanOutcome::Clean)));
1790/// ```
1791pub fn resolve_scan_outcome<'a>(
1792 vulnerabilities: &'a VulnerabilityMap,
1793 dep: &dyn Dependency,
1794 keys: Option<&crate::osv::VulnKeys>,
1795 key: &PackageKey,
1796) -> Option<&'a ScanOutcome> {
1797 resolve_by_vuln_key(vulnerabilities, dep, keys, key)
1798}
1799
1800/// Shared per-occurrence [`VulnKey`] lookup chain (version-qualified key, then normalized name)
1801/// underlying both [`resolve_scan_outcome`] and [`resolve_latest_status`] —
1802/// the two maps [`VulnerabilityMap`] and [`crate::osv::LatestStatusMap`] share this exact key
1803/// space (#1517), so the fallback chain only needs writing once.
1804fn resolve_by_vuln_key<'a, V>(
1805 map: &'a HashMap<VulnKey, V>,
1806 dep: &dyn Dependency,
1807 keys: Option<&crate::osv::VulnKeys>,
1808 key: &PackageKey,
1809) -> Option<&'a V> {
1810 keys.and_then(|k| k.get(&dep.name_range()))
1811 .and_then(|vuln_key| map.get(vuln_key))
1812 .or_else(|| map.get(&VulnKey::from_name(key.normalized())))
1813}
1814
1815/// Looks up `dep`'s entry in phase B's per-key "latest" status map, using the same
1816/// version-qualified-key-then-normalized-name fallback chain as
1817/// [`resolve_scan_outcome`] (#1517).
1818///
1819/// # Examples
1820///
1821/// ```
1822/// use deps_core::lsp_helpers::resolve_latest_status;
1823/// use deps_core::osv::{LatestStatusMap, UpgradeStatus};
1824/// use deps_core::position::{Position, Range};
1825/// use deps_core::{Dependency, PackageName, VersionReq};
1826/// use std::any::Any;
1827///
1828/// struct SimpleDep {
1829/// name: PackageName,
1830/// name_range: Range,
1831/// }
1832///
1833/// impl Dependency for SimpleDep {
1834/// fn name(&self) -> &PackageName {
1835/// &self.name
1836/// }
1837/// fn name_range(&self) -> Range {
1838/// self.name_range
1839/// }
1840/// fn version_requirement(&self) -> Option<&VersionReq> {
1841/// None
1842/// }
1843/// fn version_range(&self) -> Option<Range> {
1844/// None
1845/// }
1846/// fn source(&self) -> deps_core::parser::DependencySource {
1847/// deps_core::parser::DependencySource::Registry
1848/// }
1849/// }
1850///
1851/// let dep = SimpleDep {
1852/// name: PackageName::new("time"),
1853/// name_range: Range::new(Position::new(0, 0), Position::new(0, 4)).into(),
1854/// };
1855/// let key = deps_core::PackageKey::new(dep.name(), &deps_core::test_util::StubFormatter::new());
1856///
1857/// let mut latest_status = LatestStatusMap::new();
1858/// latest_status.insert(
1859/// deps_core::test_util::vuln_key("time"),
1860/// UpgradeStatus::CandidateClean {
1861/// version: deps_core::ConcreteVersion::new("1.0.0"),
1862/// },
1863/// );
1864///
1865/// let status = resolve_latest_status(&latest_status, &dep, None, &key);
1866/// assert!(matches!(status, Some(UpgradeStatus::CandidateClean { .. })));
1867/// ```
1868pub fn resolve_latest_status<'a>(
1869 latest_status: &'a LatestStatusMap,
1870 dep: &dyn Dependency,
1871 keys: Option<&crate::osv::VulnKeys>,
1872 key: &PackageKey,
1873) -> Option<&'a UpgradeStatus> {
1874 resolve_by_vuln_key(latest_status, dep, keys, key)
1875}
1876
1877/// Whether a dependency's currently-displayed "latest" upgrade recommendation is safe to
1878/// surface as such (issue #1517).
1879///
1880/// The single gate every renderer (hover, diagnostics, code actions, code lens, inlay hints,
1881/// completion) and `deps-cli update`/`check` must consult before treating `latest` as an
1882/// endorsed upgrade target.
1883// Exhaustive: a new "verdict" is a deliberate design decision about how a fifth case should
1884// render everywhere at once, never a silent default — mirrors `EcosystemId`'s exhaustive-match
1885// convention (project rule, see #118).
1886#[derive(Debug, Clone, PartialEq, Eq)]
1887pub enum LatestVerdict {
1888 /// OSV's latest-check does not apply here: OSV is disabled/offline for this scan entirely
1889 /// (no [`crate::osv::LatestStatusMap`] was ever attached), or this dependency's skip reason
1890 /// is structural ([`crate::osv::SkipReason::is_structural`] — its source/ecosystem is never
1891 /// checked against OSV, e.g. a git dependency or an OSV-unsupported ecosystem).
1892 NotApplicable,
1893 /// The exact version currently displayed as "latest" was checked and found clean (or
1894 /// affected only by [`VulnSeverity::Informational`]-only advisories, e.g. an "unmaintained"
1895 /// notice with no genuine security content).
1896 Verified,
1897 /// The exact version currently displayed as "latest" was checked and found affected by at
1898 /// least one non-informational advisory (or a record whose severity could not be
1899 /// determined, which is treated as blocking rather than silently passed through).
1900 Flagged {
1901 /// Advisory ids affecting the checked version, for display.
1902 advisory_ids: Vec<crate::osv::OsvId>,
1903 /// Whether the worst affecting advisory is a confirmed-malicious-package record
1904 /// ([`VulnSeverity::Malicious`]) — renderers use this to escalate wording/severity.
1905 malicious: bool,
1906 /// The sibling release tags through which the checked version is affected, when every
1907 /// advisory matched through siblings alone; `None` makes no claim about how.
1908 via_sibling_tags: Option<crate::osv::MatchedTags>,
1909 },
1910 /// The version was never definitively checked against OSV: no entry for this dependency
1911 /// (including the pre-phase-B window, where an empty map is attached deliberately so this
1912 /// case fires instead of [`Self::NotApplicable`]), a transient skip (timeout, query
1913 /// failure, truncation), or the checked version has since diverged from what's now
1914 /// displayed as `latest`. Renderers must treat this the same as [`Self::Flagged`] for the
1915 /// purpose of *not* recommending the upgrade — the two are kept distinct only so wording can
1916 /// differ ("not yet verified" vs. "flagged unsafe").
1917 Unverified,
1918}
1919
1920/// Computes `dep`'s [`LatestVerdict`] against `displayed_latest` (the exact version string a
1921/// renderer is about to show as "latest") from `latest_status` (typically
1922/// [`VersionData::latest_status`]).
1923///
1924/// # Examples
1925///
1926/// ```
1927/// use deps_core::lsp_helpers::{LatestVerdict, latest_verdict};
1928/// use deps_core::osv::{LatestStatusMap, UpgradeStatus};
1929/// use deps_core::position::{Position, Range};
1930/// use deps_core::{Dependency, PackageName, VersionReq};
1931/// use std::any::Any;
1932///
1933/// struct SimpleDep {
1934/// name: PackageName,
1935/// name_range: Range,
1936/// }
1937///
1938/// # deps_core::impl_unprobed_dependency!(SimpleDep);
1939/// impl Dependency for SimpleDep {
1940/// fn name(&self) -> &PackageName {
1941/// &self.name
1942/// }
1943/// fn name_range(&self) -> Range {
1944/// self.name_range
1945/// }
1946/// fn version_requirement(&self) -> Option<&VersionReq> {
1947/// None
1948/// }
1949/// fn version_range(&self) -> Option<Range> {
1950/// None
1951/// }
1952/// fn source(&self) -> deps_core::parser::DependencySource {
1953/// deps_core::parser::DependencySource::Registry
1954/// }
1955/// }
1956///
1957/// let dep = SimpleDep {
1958/// name: PackageName::new("left-pad"),
1959/// name_range: Range::new(Position::new(0, 0), Position::new(0, 8)).into(),
1960/// };
1961/// let formatter = deps_core::test_util::StubFormatter::new().for_dependency::<SimpleDep>();
1962/// let key = deps_core::PackageKey::new(dep.name(), &formatter);
1963///
1964/// // No map attached at all (OSV disabled/offline) — not applicable, today's behavior.
1965/// assert_eq!(
1966/// latest_verdict(None, &dep, None, &key, "1.0.8", &formatter),
1967/// LatestVerdict::NotApplicable
1968/// );
1969///
1970/// // A map with no entry for this dependency (e.g. before phase B first completes) must fail
1971/// // closed, never pass through as safe.
1972/// let empty = LatestStatusMap::new();
1973/// assert_eq!(
1974/// latest_verdict(Some(&empty), &dep, None, &key, "1.0.8", &formatter),
1975/// LatestVerdict::Unverified
1976/// );
1977/// ```
1978#[must_use]
1979pub fn latest_verdict<F: DependencyFormatter>(
1980 latest_status: Option<&LatestStatusMap>,
1981 dep: &F::Dep,
1982 keys: Option<&crate::osv::VulnKeys>,
1983 key: &PackageKey,
1984 displayed_latest: &str,
1985 formatter: &F,
1986) -> LatestVerdict {
1987 let Some(map) = latest_status else {
1988 return LatestVerdict::NotApplicable;
1989 };
1990 upgrade_status_to_verdict(
1991 resolve_latest_status(map, dep, keys, key),
1992 displayed_latest,
1993 dep,
1994 formatter,
1995 )
1996}
1997
1998/// Shared `UpgradeStatus -> LatestVerdict` mapping behind both [`latest_verdict`] and
1999/// [`candidate_verdict`] (#1524) — factored out so the two never drift on what "clean" vs.
2000/// "vulnerable" vs. "unverified"/"not applicable" means for a checked candidate.
2001///
2002/// A source-dependent structural entry (`NonRegistrySource`, `UnverifiedRegistrySource`) is
2003/// cached under `dep`'s plain [`crate::osv::VulnKey`] (name, not source), so it survives
2004/// untouched if `dep`'s source later changes from e.g. path/git to registry — until the next
2005/// phase B run overwrites it. Since that window would otherwise read as the fail-open
2006/// [`LatestVerdict::NotApplicable`] for a dependency that is now registry-resolvable and simply
2007/// hasn't been checked yet, this re-checks `dep`'s *current* source before trusting a cached
2008/// source-dependent skip (issue #1531). The check goes through `formatter.public_content` — the
2009/// same predicate phase B itself uses to classify the skip in the first place (`deps-engine`'s
2010/// `classify::osv`) — rather than a bare `DependencySource::Registry` match, so an ecosystem
2011/// that widens what counts as registry content (e.g. `deps-cargo`'s
2012/// `AlternateRegistry { mirrors_public_registry: true }` for a configured crates.io mirror) is
2013/// not itself misread as still-non-registry and wrongly kept stale. A mismatch means the entry
2014/// is stale, so it fails closed to [`LatestVerdict::Unverified`] instead.
2015fn upgrade_status_to_verdict<F: DependencyFormatter>(
2016 status: Option<&UpgradeStatus>,
2017 expected_version: &str,
2018 dep: &F::Dep,
2019 formatter: &F,
2020) -> LatestVerdict {
2021 match status {
2022 None | Some(UpgradeStatus::NotChecked) => LatestVerdict::Unverified,
2023 Some(UpgradeStatus::StructurallyUnchecked(reason)) => {
2024 let stale_non_registry_skip =
2025 reason.depends_on_source() && formatter.public_content(dep).is_some();
2026 if stale_non_registry_skip {
2027 LatestVerdict::Unverified
2028 } else {
2029 LatestVerdict::NotApplicable
2030 }
2031 }
2032 Some(UpgradeStatus::CandidateUnverified { reason, .. }) => {
2033 if reason.is_structural() {
2034 LatestVerdict::NotApplicable
2035 } else {
2036 LatestVerdict::Unverified
2037 }
2038 }
2039 Some(UpgradeStatus::CandidateClean { version }) => {
2040 if version == expected_version {
2041 LatestVerdict::Verified
2042 } else {
2043 LatestVerdict::Unverified
2044 }
2045 }
2046 Some(UpgradeStatus::CandidateVulnerable {
2047 version,
2048 advisory_ids,
2049 worst_severity,
2050 via_sibling_tags,
2051 }) => {
2052 if version != expected_version {
2053 return LatestVerdict::Unverified;
2054 }
2055 if *worst_severity == Some(VulnSeverity::Informational) {
2056 LatestVerdict::Verified
2057 } else {
2058 LatestVerdict::Flagged {
2059 advisory_ids: advisory_ids.items().to_vec(),
2060 malicious: *worst_severity == Some(VulnSeverity::Malicious),
2061 via_sibling_tags: via_sibling_tags.clone(),
2062 }
2063 }
2064 }
2065 }
2066}
2067
2068/// Resolves `dep`'s per-version candidate status from `candidate_status` (typically
2069/// [`VersionData::candidate_status`]), using the same three-tier `VulnKey` resolution
2070/// [`resolve_latest_status`] uses.
2071///
2072/// # Examples
2073///
2074/// ```
2075/// use deps_core::lsp_helpers::resolve_candidate_status;
2076/// use deps_core::osv::{CandidateStatusMap, UpgradeStatus};
2077/// use deps_core::position::{Position, Range};
2078/// use deps_core::{Dependency, PackageName, VersionReq};
2079/// use std::any::Any;
2080///
2081/// struct SimpleDep {
2082/// name: PackageName,
2083/// name_range: Range,
2084/// }
2085///
2086/// impl Dependency for SimpleDep {
2087/// fn name(&self) -> &PackageName {
2088/// &self.name
2089/// }
2090/// fn name_range(&self) -> Range {
2091/// self.name_range
2092/// }
2093/// fn version_requirement(&self) -> Option<&VersionReq> {
2094/// None
2095/// }
2096/// fn version_range(&self) -> Option<Range> {
2097/// None
2098/// }
2099/// fn source(&self) -> deps_core::parser::DependencySource {
2100/// deps_core::parser::DependencySource::Registry
2101/// }
2102/// }
2103///
2104/// let dep = SimpleDep {
2105/// name: PackageName::new("time"),
2106/// name_range: Range::new(Position::new(0, 0), Position::new(0, 4)).into(),
2107/// };
2108/// let key = deps_core::PackageKey::new(dep.name(), &deps_core::test_util::StubFormatter::new());
2109///
2110/// let mut candidate_status = CandidateStatusMap::new();
2111/// candidate_status.insert(
2112/// deps_core::test_util::vuln_key("time"),
2113/// deps_core::osv::CandidateStatuses::PerVersion(
2114/// std::iter::once((
2115/// deps_core::ConcreteVersion::new("0.1.43"),
2116/// UpgradeStatus::CandidateClean {
2117/// version: deps_core::ConcreteVersion::new("0.1.43"),
2118/// },
2119/// ))
2120/// .collect(),
2121/// ),
2122/// );
2123///
2124/// let statuses = resolve_candidate_status(&candidate_status, &dep, None, &key).unwrap();
2125/// let deps_core::osv::CandidateStatuses::PerVersion(per_version) = statuses else {
2126/// unreachable!()
2127/// };
2128/// assert!(matches!(
2129/// per_version.get(&deps_core::ConcreteVersion::new("0.1.43")),
2130/// Some(UpgradeStatus::CandidateClean { .. })
2131/// ));
2132/// ```
2133#[must_use]
2134pub fn resolve_candidate_status<'a>(
2135 candidate_status: &'a CandidateStatusMap,
2136 dep: &dyn Dependency,
2137 keys: Option<&crate::osv::VulnKeys>,
2138 key: &PackageKey,
2139) -> Option<&'a CandidateStatuses> {
2140 resolve_by_vuln_key(candidate_status, dep, keys, key)
2141}
2142
2143/// Computes `dep`'s [`LatestVerdict`] for one specific candidate version (#1524).
2144///
2145/// The sibling of [`latest_verdict`] for a candidate-offering surface (code actions' "update
2146/// to X" list, completion's version items) that needs a verdict for more than just the
2147/// registry's single "latest" pick.
2148///
2149/// A dependency with no entry at all in `candidate_status` (phase B's candidate-check round
2150/// never covered it) resolves to [`LatestVerdict::Unverified`], matching [`latest_verdict`]'s
2151/// identical fail-closed default. A structural skip is recorded once per dependency as
2152/// [`crate::osv::CandidateStatuses::Structural`] (see that type's doc) and applies uniformly to
2153/// every candidate version, never mixed with real per-version data for the same dependency.
2154///
2155/// # Examples
2156///
2157/// ```
2158/// use deps_core::lsp_helpers::{LatestVerdict, candidate_verdict};
2159/// use deps_core::osv::{CandidateStatusMap, UpgradeStatus};
2160/// use deps_core::position::{Position, Range};
2161/// use deps_core::{Dependency, PackageName, VersionReq};
2162/// use std::any::Any;
2163///
2164/// struct SimpleDep {
2165/// name: PackageName,
2166/// name_range: Range,
2167/// }
2168///
2169/// # deps_core::impl_unprobed_dependency!(SimpleDep);
2170/// impl Dependency for SimpleDep {
2171/// fn name(&self) -> &PackageName {
2172/// &self.name
2173/// }
2174/// fn name_range(&self) -> Range {
2175/// self.name_range
2176/// }
2177/// fn version_requirement(&self) -> Option<&VersionReq> {
2178/// None
2179/// }
2180/// fn version_range(&self) -> Option<Range> {
2181/// None
2182/// }
2183/// fn source(&self) -> deps_core::parser::DependencySource {
2184/// deps_core::parser::DependencySource::Registry
2185/// }
2186/// }
2187///
2188/// let dep = SimpleDep {
2189/// name: PackageName::new("left-pad"),
2190/// name_range: Range::new(Position::new(0, 0), Position::new(0, 8)).into(),
2191/// };
2192/// let formatter = deps_core::test_util::StubFormatter::new().for_dependency::<SimpleDep>();
2193/// let key = deps_core::PackageKey::new(dep.name(), &formatter);
2194///
2195/// // No map attached at all (OSV disabled/offline) — not applicable, mirrors `latest_verdict`.
2196/// assert_eq!(
2197/// candidate_verdict(None, &dep, None, &key, "1.0.6", &formatter),
2198/// LatestVerdict::NotApplicable
2199/// );
2200///
2201/// // A map with an entry for this dependency, but not for this exact version — fails closed
2202/// // to `Unverified`, never silently treated as safe.
2203/// let mut candidate_status = CandidateStatusMap::new();
2204/// candidate_status.insert(
2205/// deps_core::test_util::vuln_key("left-pad"),
2206/// deps_core::osv::CandidateStatuses::PerVersion(std::collections::HashMap::new()),
2207/// );
2208/// assert_eq!(
2209/// candidate_verdict(Some(&candidate_status), &dep, None, &key, "1.0.6", &formatter),
2210/// LatestVerdict::Unverified
2211/// );
2212/// ```
2213#[must_use]
2214pub fn candidate_verdict<F: DependencyFormatter>(
2215 candidate_status: Option<&CandidateStatusMap>,
2216 dep: &F::Dep,
2217 keys: Option<&crate::osv::VulnKeys>,
2218 key: &PackageKey,
2219 version: &str,
2220 formatter: &F,
2221) -> LatestVerdict {
2222 let Some(map) = candidate_status else {
2223 return LatestVerdict::NotApplicable;
2224 };
2225 match resolve_candidate_status(map, dep, keys, key) {
2226 None => LatestVerdict::Unverified,
2227 Some(CandidateStatuses::Structural(reason)) => upgrade_status_to_verdict(
2228 Some(&UpgradeStatus::StructurallyUnchecked(*reason)),
2229 version,
2230 dep,
2231 formatter,
2232 ),
2233 Some(CandidateStatuses::PerVersion(per_version)) => {
2234 let status = per_version.get(&ConcreteVersion::from(version));
2235 upgrade_status_to_verdict(status, version, dep, formatter)
2236 }
2237 }
2238}
2239
2240/// Converts byte offsets in source text to LSP `Position` values.
2241///
2242/// Precomputes line-start byte offsets once, then maps any byte offset to a
2243/// `(line, character)` position. Characters are counted as UTF-16 code units
2244/// as required by the LSP specification.
2245///
2246/// Also precomputes, per line, whether that line is pure ASCII (`line_is_ascii`): for an
2247/// ASCII-only line, byte offset and UTF-16 code-unit
2248/// offset are always equal, so [`byte_offset_to_position`](Self::byte_offset_to_position)
2249/// can skip the `chars().map(char::len_utf16).sum()` scan entirely and compute the
2250/// character offset in O(1). This matters because a single minified manifest line (e.g. a
2251/// `package.json` with hundreds of dependencies on one line) turns per-offset lookups into
2252/// an O(n) scan each, and O(n) lookups across the line's length make the whole document
2253/// O(n^2) (#742) — the common case of an ASCII-only line now stays O(1) per lookup; a
2254/// non-ASCII line still takes an O(1) lookup too, via a lazily-built per-line index (#882) —
2255/// see `with_non_ascii_line_index`.
2256///
2257/// Interior mutability: this type is `Send` but not `Sync` (the non-ASCII line index cache
2258/// uses a `RefCell`). Build one per document parse and never share it across threads.
2259pub struct LineOffsetTable {
2260 line_starts: Vec<usize>,
2261 line_is_ascii: Vec<bool>,
2262 // Lazily populated, keyed by line number. A `HashMap` rather than a `Vec` sized to the
2263 // line count so cost is proportional to lines actually queried non-ASCII (#882).
2264 non_ascii_line_index_cache:
2265 std::cell::RefCell<std::collections::HashMap<usize, NonAsciiLineIndex>>,
2266}
2267
2268/// A non-ASCII line's char-boundary index, lazily built and cached by
2269/// `LineOffsetTable::with_non_ascii_line_index`.
2270///
2271/// `entries[i]` is `(byte_offset, utf16_units_before)` for the line's `i`-th char boundary
2272/// (`byte_offset` relative to the line's own start, `utf16_units_before` the cumulative UTF-16
2273/// code-unit count of every char *before* it). A final sentinel entry for the end of the line
2274/// (`byte_offset == line.len()`, `utf16_units_before` = the line's total UTF-16 length) makes
2275/// end-of-line byte offsets resolvable the same way as any other char boundary.
2276///
2277/// Serves both directions #882 needs on a non-ASCII line, from one build pass: char index ->
2278/// byte offset (`entries.get(col)`, what [`marker_byte_offset`] needs) and byte offset ->
2279/// UTF-16 units (`entries.binary_search_by_key`, what
2280/// [`byte_offset_to_position`](LineOffsetTable::byte_offset_to_position) needs) — a second,
2281/// independent cache would duplicate the exact `char_indices()` walk this one pass already
2282/// performs.
2283struct NonAsciiLineIndex {
2284 entries: Vec<(u32, u32)>,
2285}
2286
2287impl NonAsciiLineIndex {
2288 /// Builds the index for one line's text via a single `char_indices()` walk.
2289 fn build(line_text: &str) -> Self {
2290 let mut entries = Vec::with_capacity(line_text.len() + 1);
2291 let mut utf16_units = 0u32;
2292 for (byte_offset, c) in line_text.char_indices() {
2293 entries.push((u32::try_from(byte_offset).unwrap_or(u32::MAX), utf16_units));
2294 utf16_units = utf16_units.saturating_add(u32::try_from(c.len_utf16()).unwrap_or(2));
2295 }
2296 entries.push((
2297 u32::try_from(line_text.len()).unwrap_or(u32::MAX),
2298 utf16_units,
2299 ));
2300 // The initial `line_text.len() + 1` capacity over-reserves 3-4x on a multi-byte-heavy
2301 // line (CJK, Devanagari, ...): it reserves per byte but pushes one entry per char.
2302 entries.shrink_to_fit();
2303 Self { entries }
2304 }
2305}
2306
2307impl LineOffsetTable {
2308 /// Builds the table for `content`.
2309 pub fn new(content: &str) -> Self {
2310 let mut line_starts = vec![0];
2311 let mut line_is_ascii = Vec::new();
2312 let mut current_ascii = true;
2313 for (i, c) in content.char_indices() {
2314 if !c.is_ascii() {
2315 current_ascii = false;
2316 }
2317 if c == '\n' {
2318 line_starts.push(i + 1);
2319 line_is_ascii.push(current_ascii);
2320 current_ascii = true;
2321 }
2322 }
2323 line_is_ascii.push(current_ascii);
2324 debug_assert_eq!(
2325 line_starts.len(),
2326 line_is_ascii.len(),
2327 "line_starts and line_is_ascii must stay in lockstep — one entry per line"
2328 );
2329 Self {
2330 line_starts,
2331 line_is_ascii,
2332 non_ascii_line_index_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
2333 }
2334 }
2335
2336 /// Runs `f` against the cached (building it on first call) [`NonAsciiLineIndex`] for the
2337 /// non-ASCII line starting at `line0` (0-indexed), given that line's own text.
2338 ///
2339 /// Callers must pass the exact text of line `line0` as sliced from the same `content` this
2340 /// table was built from — the cache trusts its first-seen `line_text` for every later
2341 /// lookup of the same `line0` and never re-validates it. Building a line's index the first
2342 /// time it is looked up is still O(line length) (one `char_indices()` walk); only repeat
2343 /// lookups on an already-cached line become O(1) — a huge non-ASCII line's *first* lookup
2344 /// is not free, it is the same one-time cost `LineOffsetTable::new` always paid.
2345 ///
2346 /// Takes a closure rather than returning a `Ref` so the `RefCell` borrow never outlives one
2347 /// call — a caller cannot accidentally hold it open across an unrelated later borrow.
2348 #[expect(
2349 clippy::expect_used,
2350 reason = "borrow_mut() is dropped before borrow() runs, and the inserted entry is \
2351 never removed, so the lookup below always succeeds"
2352 )]
2353 fn with_non_ascii_line_index<R>(
2354 &self,
2355 line0: usize,
2356 line_text: &str,
2357 f: impl FnOnce(&NonAsciiLineIndex) -> R,
2358 ) -> R {
2359 self.non_ascii_line_index_cache
2360 .borrow_mut()
2361 .entry(line0)
2362 .or_insert_with(|| NonAsciiLineIndex::build(line_text));
2363 let cache = self.non_ascii_line_index_cache.borrow();
2364 let index = cache
2365 .get(&line0)
2366 .expect("just inserted above if it was missing");
2367 f(index)
2368 }
2369
2370 /// Byte offset (relative to the line's own start) of the `col`-th char boundary within the
2371 /// non-ASCII line starting at `line0`, given that line's text. Clamps to `line_text.len()`
2372 /// if `col` is past the line's char count, matching a plain `char_indices().nth(col)` walk.
2373 fn non_ascii_char_byte_offset(&self, line0: usize, line_text: &str, col: usize) -> usize {
2374 self.with_non_ascii_line_index(line0, line_text, |index| {
2375 index
2376 .entries
2377 .get(col)
2378 .map_or(line_text.len(), |&(byte_offset, _)| byte_offset as usize)
2379 })
2380 }
2381
2382 /// UTF-16 code-unit count preceding `byte_offset` (relative to the line's own start) within
2383 /// the non-ASCII line starting at `line0`, given that line's text.
2384 ///
2385 /// `byte_offset` must be a char boundary within the line (guaranteed by
2386 /// [`byte_offset_to_position`](Self::byte_offset_to_position)'s `floor_char_boundary` clamp
2387 /// before calling this) — every char boundary, including end-of-line, has an exact entry in
2388 /// the index, so this never needs to interpolate between two boundaries.
2389 fn non_ascii_utf16_units_before(
2390 &self,
2391 line0: usize,
2392 line_text: &str,
2393 byte_offset: usize,
2394 ) -> u32 {
2395 self.with_non_ascii_line_index(line0, line_text, |index| {
2396 let byte_offset = u32::try_from(byte_offset).unwrap_or(u32::MAX);
2397 let found = index
2398 .entries
2399 .binary_search_by_key(&byte_offset, |&(b, _)| b);
2400 // `Err` shouldn't happen given the caller's `floor_char_boundary` guarantee, but
2401 // falls back to the nearest preceding entry rather than panicking.
2402 let i = found.unwrap_or_else(|i| i.saturating_sub(1));
2403 index.entries.get(i).map_or(0, |&(_, units)| units)
2404 })
2405 }
2406
2407 /// Absolute byte offset where `line` (0-indexed) starts, or `None` if
2408 /// `line` is out of range.
2409 ///
2410 /// Prefer this over re-deriving a line's start via cursor arithmetic
2411 /// (`cursor += line.len() + 1`): `str::lines()` strips a trailing `\r`,
2412 /// so that approach under-counts by one byte per CRLF line and corrupts
2413 /// every subsequent offset in the file. This table is built by scanning
2414 /// `char_indices()` for `\n` (see [`new`](Self::new)), which counts the
2415 /// `\r`, so it stays correct for LF, CRLF and mixed line endings alike.
2416 ///
2417 /// # Examples
2418 ///
2419 /// ```
2420 /// use deps_core::lsp_helpers::LineOffsetTable;
2421 ///
2422 /// let table = LineOffsetTable::new("a\r\nb\r\nc");
2423 /// assert_eq!(table.line_start(0), Some(0));
2424 /// assert_eq!(table.line_start(1), Some(3));
2425 /// assert_eq!(table.line_start(2), Some(6));
2426 /// assert_eq!(table.line_start(3), None);
2427 /// ```
2428 pub fn line_start(&self, line: usize) -> Option<usize> {
2429 self.line_starts.get(line).copied()
2430 }
2431
2432 /// Converts a byte offset into an LSP `Position`.
2433 pub fn byte_offset_to_position(&self, content: &str, offset: usize) -> Position {
2434 let offset = offset.min(content.len());
2435 // The requirements.txt line parser derives offsets via hand-rolled byte arithmetic,
2436 // which can land inside a multi-byte character — clamp to the nearest char boundary
2437 // rather than panicking on the slice below.
2438 let offset = content.floor_char_boundary(offset);
2439 let line = self
2440 .line_starts
2441 .partition_point(|&start| start <= offset)
2442 .saturating_sub(1);
2443 #[expect(
2444 clippy::indexing_slicing,
2445 reason = "line_starts always has at least one element (vec![0] at construction), \
2446 so partition_point().saturating_sub(1) is always a valid index into it"
2447 )]
2448 let line_start = self.line_starts[line];
2449 // #673 M1: `line`/`character` aren't bounded by any size cap for editor-sent
2450 // full-document-sync text, so this saturates rather than assuming an upstream cap
2451 // (mirrors `completion::byte_to_utf16_offset`'s identical fix).
2452 //
2453 // #742: an ASCII-only line has 1 UTF-16 unit per byte, so no need to walk `chars()`.
2454 let character = if self.line_is_ascii.get(line).copied().unwrap_or(false) {
2455 u32::try_from(offset - line_start).unwrap_or(u32::MAX)
2456 } else {
2457 // #882: a naive `chars().map(len_utf16).sum()` per call is O(line length); N
2458 // lookups on the same wide line made this O(N x line length). The cached
2459 // per-line index (`with_non_ascii_line_index`) makes repeat lookups O(1).
2460 let line_end = self
2461 .line_starts
2462 .get(line + 1)
2463 .copied()
2464 .unwrap_or(content.len());
2465 let line_text = content.get(line_start..line_end).unwrap_or_default();
2466 self.non_ascii_utf16_units_before(line, line_text, offset - line_start)
2467 };
2468 Position::new(u32::try_from(line).unwrap_or(u32::MAX), character)
2469 }
2470
2471 /// Converts an LSP `Position` back into a byte offset — the inverse of
2472 /// [`byte_offset_to_position`](Self::byte_offset_to_position). Out-of-range lines or
2473 /// UTF-16 characters clamp to `content.len()` rather than panicking, matching the
2474 /// forward conversion's `.min(content.len())` guard.
2475 ///
2476 /// A `character` landing inside a surrogate pair rounds up to the next char boundary, and
2477 /// one past the line's end (including its `\n`) resolves to the line's end — the same
2478 /// results as [`utf16_to_byte_offset`] on the line, but O(1) on an ASCII line and
2479 /// O(log line length) on a non-ASCII one via the cached per-line index (#1711).
2480 #[expect(
2481 clippy::string_slice,
2482 reason = "line_start/line_end come from line_starts (post-newline offsets, always \
2483 char boundaries) or content.len()"
2484 )]
2485 pub fn position_to_byte_offset(&self, content: &str, position: Position) -> usize {
2486 let line0 = position.line as usize;
2487 let Some(&line_start) = self.line_starts.get(line0) else {
2488 return content.len();
2489 };
2490 let line_end = self
2491 .line_starts
2492 .get(line0 + 1)
2493 .copied()
2494 .unwrap_or(content.len());
2495 let line_len = line_end - line_start;
2496 let relative = if self.line_is_ascii.get(line0).copied().unwrap_or(false) {
2497 let character = position.character as usize;
2498 if character <= line_len {
2499 character
2500 } else {
2501 line_len
2502 }
2503 } else {
2504 let line_text = &content[line_start..line_end];
2505 self.with_non_ascii_line_index(line0, line_text, |index| {
2506 let i = index
2507 .entries
2508 .partition_point(|&(_, units)| units < position.character);
2509 index
2510 .entries
2511 .get(i)
2512 .map_or(line_len, |&(byte_offset, _)| byte_offset as usize)
2513 })
2514 };
2515 (line_start + relative).min(content.len())
2516 }
2517}
2518
2519/// Escapes Markdown syntax characters so untrusted text cannot break out of the
2520/// Markdown structure it is embedded in.
2521///
2522/// Applied to manifest-controlled text (dependency names) before it is written into
2523/// hover markdown link labels, and to registry-controlled completion metadata
2524/// (package name/version, description, repository/documentation URLs) before it is
2525/// written into completion-item link labels and link destinations. Every ASCII
2526/// punctuation character is backslash-escaped (CommonMark's full escapable set — not
2527/// just brackets/parens, which would still leave e.g. `<https://evil.example>`
2528/// autolinks live), and control characters (including newlines) plus a narrow set of
2529/// invisible/bidi-override characters (see `is_markdown_unsafe`, #1248) are replaced
2530/// with a space so the text cannot terminate the single-line block it is embedded in,
2531/// splice in new content, or visually spoof the rendered name via a Trojan Source
2532/// (CVE-2021-42574) bidi override.
2533///
2534/// Backslash-escaping is valid in link destinations as well as regular text, so this
2535/// also neutralizes `)`/`]` breakout attempts in a `[label](destination)` URL. It does
2536/// *not* block dangerous URI schemes (e.g. `javascript:`) in a destination — that is a
2537/// separate concern from breaking out of the surrounding Markdown structure.
2538///
2539/// Backslash-escaping does *not* work inside inline code spans (CommonMark §6.1) —
2540/// use [`markdown_code_span`] for text embedded in `` `...` `` instead.
2541///
2542/// # Examples
2543///
2544/// ```
2545/// use deps_core::lsp_helpers::escape_markdown;
2546///
2547/// assert_eq!(escape_markdown("pkg](evil)[pkg"), r"pkg\]\(evil\)\[pkg");
2548/// assert_eq!(escape_markdown("a\nb"), "a b");
2549/// ```
2550pub fn escape_markdown(s: &str) -> String {
2551 let mut escaped = String::with_capacity(s.len());
2552 for c in s.chars() {
2553 if is_markdown_unsafe(c) {
2554 escaped.push(' ');
2555 continue;
2556 }
2557 if c.is_ascii_punctuation() {
2558 escaped.push('\\');
2559 }
2560 escaped.push(c);
2561 }
2562 escaped
2563}
2564
2565/// Predicate for a character that must not survive [`escape_markdown`]/
2566/// [`markdown_code_span`] unescaped (#1248, widened #1323): every Unicode `Cc`/`Cf`/`Zl`/`Zp`
2567/// character except a small, named exempt set with genuine mid-string use in real-world free
2568/// text — RTL/ZWNJ/ZWJ marks and Arabic/Syriac/Kaithi prefixed-format signs (see individual
2569/// `matches!` arms below, and `EXEMPT_CHARS` in
2570/// `test_is_markdown_unsafe_exempt_set_matches_sanitize_invisible_drift_guard` for the exact
2571/// list). Deliberately narrower than [`crate::redact::sanitize_invisible`]'s full sweep for
2572/// that reason; a name/version-shaped caller with no such legitimate-mark concern should
2573/// layer `sanitize_invisible` on top for full parity, as
2574/// `deps_npm::catalog::CatalogOrigin::hover_detail` does (#1266) — this crate's own
2575/// `deprecation.replacement` hover field does not yet (#1311).
2576///
2577/// The drift-guard test above scans the full Unicode code space and enforces that the
2578/// exempt set is exact. Do not widen or narrow this function without updating that test's
2579/// `EXEMPT_CHARS`, and do not fold in `sanitize_invisible`'s RTL/ZWNJ/ZWJ exemption without
2580/// also revisiting #1248.
2581fn is_markdown_unsafe(c: char) -> bool {
2582 c.is_control()
2583 || matches!(c,
2584 '\u{202A}'..='\u{202E}' // LRE RLE PDF LRO RLO
2585 | '\u{2060}'..='\u{206F}' // WORD JOINER, invisible math ops, bidi isolates,
2586 // deprecated format-control block (U+2065 unassigned,
2587 // deliberately included)
2588 | '\u{200B}' // ZWSP
2589 | '\u{2028}' | '\u{2029}' // LS, PS
2590 | '\u{FEFF}' // ZWNBSP / BOM
2591 | '\u{FFF9}'..='\u{FFFB}' // interlinear annotation anchor/separator/terminator
2592 | '\u{E0000}'..='\u{E007F}' // Unicode tag characters
2593 | '\u{00AD}' // SOFT HYPHEN
2594 | '\u{180E}' // MONGOLIAN VOWEL SEPARATOR
2595 | '\u{13430}'..='\u{1343F}' // Egyptian Hieroglyph format controls
2596 | '\u{1BCA0}'..='\u{1BCA3}' // Shorthand format controls
2597 | '\u{1D173}'..='\u{1D17A}' // Musical symbol format controls
2598 )
2599}
2600
2601/// Replaces every [`is_markdown_unsafe`] character in `s` with a single space.
2602///
2603/// Shared by [`markdown_code_span`] and `diagnostics::sanitize_advisory_text_for_diagnostic`
2604/// (#1262 code-review follow-up) so the narrow bidi/invisible-character filter has exactly
2605/// one loop to keep in sync with [`is_markdown_unsafe`]'s policy, instead of two copies that
2606/// could silently drift. Also called from `crate::diagnostic::Diagnostic::new` and
2607/// `crate::diagnostic::RelatedInformation::new` as a defense-in-depth backstop on their
2608/// constructor path (#1276) — `pub(crate)` rather than private for that, but still not
2609/// reachable from outside `deps-core`.
2610///
2611/// Idempotent: `' '` is not itself [`is_markdown_unsafe`], so re-applying this to
2612/// already-sanitized input is a no-op — safe to double-apply through both a producer-side
2613/// call and the constructor-path backstop.
2614///
2615/// Only correct for a text/label sink or an inline code span, where a stray space is
2616/// harmless — **not** for a Markdown link *destination*: per CommonMark, an unbracketed
2617/// `[label](destination)` destination cannot contain a literal space at all, so
2618/// substituting one would turn a fired hazard into a broken (non-)link instead of a
2619/// sanitized one. [`strip_markdown_unsafe_chars`] is the destination-safe sibling.
2620pub(crate) fn replace_markdown_unsafe_chars(s: &str) -> String {
2621 s.chars()
2622 .map(|c| if is_markdown_unsafe(c) { ' ' } else { c })
2623 .collect()
2624}
2625
2626/// Same filter as [`replace_markdown_unsafe_chars`], except `\n` is never replaced.
2627///
2628/// [`is_markdown_unsafe`] starts with `c.is_control()`, which classifies `\n` as unsafe —
2629/// correct for a single-line diagnostic message, but wrong for hover content: a hover card
2630/// is a multi-section Markdown document that relies on structural newlines between
2631/// sections, so running it through [`replace_markdown_unsafe_chars`] verbatim would
2632/// collapse the whole card onto one line. Used as `crate::hover::Hover`'s constructor-path
2633/// sanitization backstop (#1277), the hover equivalent of `Diagnostic::new`'s use of
2634/// [`replace_markdown_unsafe_chars`] (#1276).
2635///
2636/// Idempotent for the same reason [`replace_markdown_unsafe_chars`] is: neither `' '` nor
2637/// `'\n'` is itself [`is_markdown_unsafe`], so re-applying this to already-sanitized input
2638/// (or to input already sanitized by [`replace_markdown_unsafe_chars`], which is strictly
2639/// more aggressive) is a no-op.
2640///
2641/// Same **not destination-safe** caveat as [`replace_markdown_unsafe_chars`], but more load-
2642/// bearing here: this filter runs over the *entire* hover document on every construction and
2643/// mutation, so unlike the sibling's narrow, hand-picked call sites, it always spans any
2644/// Markdown link destination the document happens to contain — a substituted space there
2645/// would break the link (CommonMark forbids a literal space in an unbracketed destination)
2646/// rather than neutralize a hazard. This is not a gap in practice: every hover-rendered URL
2647/// is already stripped (not space-substituted) per-site via
2648/// [`crate::lsp_helpers::strip_markdown_unsafe_chars`] before it reaches this filter (see
2649/// `push_header_hover_section` in `lsp_helpers/hover.rs`), so this document-wide pass finds
2650/// nothing left to fire on a correctly-sanitized destination — but a future call site that
2651/// skips the per-site strip would silently break instead of just risking a hazard.
2652#[cfg(feature = "lsp-responses")]
2653pub(crate) fn replace_markdown_unsafe_chars_keep_newlines(s: &str) -> String {
2654 s.chars()
2655 .map(|c| {
2656 if c != '\n' && is_markdown_unsafe(c) {
2657 ' '
2658 } else {
2659 c
2660 }
2661 })
2662 .collect()
2663}
2664
2665/// Removes every `is_markdown_unsafe` character from `s` outright, rather than
2666/// substituting a space (`replace_markdown_unsafe_chars`'s behavior).
2667///
2668/// Used for a Markdown link *destination* (#1259 critic S3): CommonMark forbids a
2669/// literal, unescaped space inside an unbracketed `[label](destination)` destination,
2670/// so replacing a stripped character with a space there would break the link (render it
2671/// as non-link literal text) instead of sanitizing it in place. Dropping the character
2672/// keeps the surrounding URL syntactically intact — the removed character carried no
2673/// meaningful display information to begin with (it is invisible/bidi-control by
2674/// definition), so there is nothing worth preserving a placeholder for.
2675///
2676/// # Examples
2677///
2678/// ```
2679/// use deps_core::lsp_helpers::strip_markdown_unsafe_chars;
2680///
2681/// assert_eq!(strip_markdown_unsafe_chars("https://example.com/pkg"), "https://example.com/pkg");
2682/// assert_eq!(
2683/// strip_markdown_unsafe_chars("https://example.com/real\u{202E}gnp.sj"),
2684/// "https://example.com/realgnp.sj"
2685/// );
2686/// ```
2687pub fn strip_markdown_unsafe_chars(s: &str) -> String {
2688 s.chars().filter(|c| !is_markdown_unsafe(*c)).collect()
2689}
2690
2691/// Wraps `content` in a Markdown inline code span (backticks included) that safely
2692/// contains arbitrary untrusted text, regardless of embedded backticks.
2693///
2694/// Backslash-escaping does not work inside code spans (CommonMark §6.1), so instead
2695/// this fences with one more backtick than the longest run found in `content`, and
2696/// pads with a single space on each side when `content` starts or ends with a
2697/// backtick or space (required by CommonMark to keep the fence unambiguous). Control
2698/// characters (including newlines) plus the same narrow invisible/bidi-override subset
2699/// `escape_markdown` neutralizes (see `is_markdown_unsafe`, #1248) are replaced with a
2700/// space first, since the raw hover string is otherwise free to merge into an adjacent
2701/// Markdown block or carry a Trojan Source bidi override into the rendered code span.
2702///
2703/// # Examples
2704///
2705/// ```
2706/// use deps_core::lsp_helpers::markdown_code_span;
2707///
2708/// assert_eq!(markdown_code_span("1.0.0"), "`1.0.0`");
2709/// assert_eq!(markdown_code_span("a`b"), "``a`b``");
2710/// ```
2711pub fn markdown_code_span(content: &str) -> String {
2712 let sanitized = replace_markdown_unsafe_chars(content);
2713
2714 let max_backtick_run = sanitized
2715 .split(|c| c != '`')
2716 .map(str::len)
2717 .max()
2718 .unwrap_or(0);
2719 let fence = "`".repeat(max_backtick_run + 1);
2720
2721 if sanitized.is_empty() {
2722 format!("{fence} {fence}")
2723 } else if sanitized.starts_with(['`', ' ']) || sanitized.ends_with(['`', ' ']) {
2724 format!("{fence} {sanitized} {fence}")
2725 } else {
2726 format!("{fence}{sanitized}{fence}")
2727 }
2728}
2729
2730/// Checks if two version strings have the same major and minor version.
2731pub fn is_same_major_minor(v1: &str, v2: &str) -> bool {
2732 if v1.is_empty() || v2.is_empty() {
2733 return false;
2734 }
2735
2736 let mut parts1 = v1.split('.');
2737 let mut parts2 = v2.split('.');
2738
2739 if parts1.next() != parts2.next() {
2740 return false;
2741 }
2742
2743 match (parts1.next(), parts2.next()) {
2744 (Some(m1), Some(m2)) => m1 == m2,
2745 _ => true,
2746 }
2747}
2748
2749/// The length of the maximal `[a-zA-Z_][a-zA-Z0-9_]*`-shaped identifier starting at `start` in
2750/// `bytes`, or `None` if `bytes[start]` does not start one — the identifier grammar shared by
2751/// shell/envsubst-style variable expansion (`$VAR`, `${VAR}`) and the `@VAR@`/`%VAR%` forms
2752/// below.
2753fn template_placeholder_identifier_end(bytes: &[u8], start: usize) -> Option<usize> {
2754 let first = *bytes.get(start)?;
2755 if !(first.is_ascii_alphabetic() || first == b'_') {
2756 return None;
2757 }
2758 let mut end = start + 1;
2759 while bytes
2760 .get(end)
2761 .is_some_and(|&c| c.is_ascii_alphanumeric() || c == b'_')
2762 {
2763 end += 1;
2764 }
2765 Some(end)
2766}
2767
2768/// Like [`template_placeholder_identifier_end`], but also allows `-` (never `.`) in the
2769/// identifier's tail — the `$(...)` Makefile/MSBuild form's own grammar (spec 070, issue
2770/// #1421): MSBuild property names may contain a hyphen in subsequent positions
2771/// (`$(MOD-VERSION)`) but never a period, unlike the `@VAR@` form's
2772/// [`dotted_identifier_end`], which permits both. Deliberately not reused verbatim for
2773/// `$(...)` — doing so would silently admit the dotted `$(A.VERSION)` form this project's
2774/// prevalence research rejected as unsupported by real tooling.
2775fn hyphenated_identifier_end(bytes: &[u8], start: usize) -> Option<usize> {
2776 let first = *bytes.get(start)?;
2777 if !(first.is_ascii_alphabetic() || first == b'_') {
2778 return None;
2779 }
2780 let mut end = start + 1;
2781 while bytes
2782 .get(end)
2783 .is_some_and(|&c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-'))
2784 {
2785 end += 1;
2786 }
2787 Some(end)
2788}
2789
2790/// Like [`template_placeholder_identifier_end`], but also allows `.`/`-` in the identifier's
2791/// tail (never as the leading character) — the shape a CMake/Autotools `configure_file`
2792/// placeholder needs (`@project.version@`, `@some-flag@`), which is the actual common
2793/// real-world `@..@` form (impl-critic M1, #1379 follow-up): the stricter
2794/// `[a-zA-Z_][a-zA-Z0-9_]*` grammar the `$VAR`/`%VAR%` forms use never matches it, since those
2795/// forms' own real-world identifiers (shell/environment variable names, Windows env vars)
2796/// never contain `.`/`-` to begin with.
2797fn dotted_identifier_end(bytes: &[u8], start: usize) -> Option<usize> {
2798 let first = *bytes.get(start)?;
2799 if !(first.is_ascii_alphabetic() || first == b'_') {
2800 return None;
2801 }
2802 let mut end = start + 1;
2803 while bytes
2804 .get(end)
2805 .is_some_and(|&c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'.' | b'-'))
2806 {
2807 end += 1;
2808 }
2809 Some(end)
2810}
2811
2812/// Whether `text` contains a `delim IDENT delim`-shaped placeholder (`@VAR@`/`@project.version@`
2813/// autoconf/CMake `configure_file`, `%VAR%` Windows batch/NSIS), anywhere in `text`. Unlike the
2814/// `$`-prefixed forms, both delimiters are required — `@`/`%` are common enough in ordinary text
2815/// (email addresses, percentages) that a bare opening delimiter alone would be too permissive.
2816fn contains_delimited_identifier_placeholder(
2817 text: &str,
2818 delim: u8,
2819 identifier_end: impl Fn(&[u8], usize) -> Option<usize>,
2820) -> bool {
2821 let bytes = text.as_bytes();
2822 bytes.iter().enumerate().any(|(i, &b)| {
2823 b == delim && identifier_end(bytes, i + 1).is_some_and(|end| bytes.get(end) == Some(&delim))
2824 })
2825}
2826
2827/// Whether `text` contains an `open ... close`-shaped placeholder with non-blank content
2828/// between the delimiters (`{{ VAR }}` Liquid/Jinja2/Mustache/Go `text/template`, `<%= VAR %>`
2829/// ERB/lodash/Yeoman) — content is not restricted to a single identifier, since these grammars
2830/// commonly carry dotted field access (`{{ .NetVersion }}`), filters, or an `=`/`-` modifier
2831/// right after `open`.
2832///
2833/// The closing delimiter is not required (failing safe on an unclosed `{{VAR` — still treating
2834/// it as a placeholder — mirrors the `${VAR` precedent below): only `open` followed by
2835/// whitespace-then-non-blank content is checked, so a stray, immediately-closed `open` (`{{}}`,
2836/// `{{ }}`) is deliberately NOT flagged, matching `${}`'s empty-placeholder carve-out.
2837fn contains_bracketed_placeholder(text: &str, open: &str, close_or_skip: &[u8]) -> bool {
2838 let bytes = text.as_bytes();
2839 text.match_indices(open).any(|(pos, _)| {
2840 let mut i = pos + open.len();
2841 if close_or_skip.contains(bytes.get(i).unwrap_or(&0)) {
2842 i += 1;
2843 }
2844 while bytes.get(i).is_some_and(|b| b.is_ascii_whitespace()) {
2845 i += 1;
2846 }
2847 bytes.get(i).is_some_and(|&b| b != b'}' && b != b'%')
2848 })
2849}
2850
2851/// Whether `requirement` contains an unresolved external-templating placeholder.
2852///
2853/// Recognizes several common generator syntaxes: `$VAR`/`${VAR}` (shell/envsubst), `$(VAR)`
2854/// (Makefile/MSBuild variable reference), `{{ VAR }}` (Liquid/Jinja2/Mustache/Go `text/template`
2855/// expression tags), `{% ... %}` (Jinja2/Liquid statement tags), `@VAR@`/`@project.version@`
2856/// (autoconf/CMake `configure_file`), `%VAR%` (Windows batch/NSIS), or `<%= VAR %>`
2857/// (ERB/lodash/Yeoman templates).
2858///
2859/// Detected anywhere in the text, not just as the whole value: `"${REACT_VERSION}"`, `"$VUE"`,
2860/// `"$(LODASH_VERSION)"`, `"{{ .NetVersion }}"`, `"{% if x %}"`, `"@PACKAGE_VERSION@"`,
2861/// `"%VERSION%"`, `"<%= version %>"`, and an embedded form like `"1.0.0-$BUILD"` are all
2862/// detected.
2863///
2864/// Issues #1374/#1379/#1417: manifests pre-processed by external templating (`envsubst`, CI
2865/// templating, cookiecutter/Yeoman-style generators, `configure_file`, `Makefile`-orchestrated
2866/// codegen) commonly carry one of these shapes in a version-requirement slot. npm, Cargo, Dart,
2867/// Poetry (`[tool.poetry.dependencies]`), Deno and Go have no expansion syntax of their own for
2868/// any of them — unlike Maven's `${property}` or Gradle's `$var`/`${var}`, which their own build
2869/// tools resolve — so this crate can never expand one either, and a requirement containing it
2870/// must never be classified as outdated/unsatisfiable or rewritten to a literal version.
2871///
2872/// The `$`/`{{`/`{%`/`<%` forms do not require a closing delimiter (failing safe on an unclosed
2873/// `${VAR`/`{{VAR`/`{%VAR`/`<%VAR` — still treating it as a placeholder — mirrors the GitLab
2874/// precedent this predicate was originally extracted alongside); `@VAR@`/`%VAR%` require both
2875/// delimiters, since a bare `@`/`%` is too common in ordinary text to treat as an opening
2876/// delimiter alone. `$(VAR)` also requires both delimiters (unlike `${VAR`'s fail-open
2877/// precedent): an unclosed `$(` is far more likely to be a real, unrelated `$` immediately
2878/// followed by literal `(text...` (parenthetical prose, a pasted shell command-substitution
2879/// snippet) than an unterminated Makefile reference (#1417).
2880///
2881/// NuGet's `.csproj`/`.fsproj`/`.vbproj`/`Directory.Packages.props` MSBuild Central Package
2882/// Management references (also `$(VAR)`-shaped, plus `%(VAR)`/`@(VAR)`) are natively recognized
2883/// by that crate's own, independent `is_msbuild_reference` guard — `NuGetFormatter`'s
2884/// `requirement_is_placeholder` ORs this function with that guard (`shared || native`), so this
2885/// function is still reachable and consulted for NuGet, but its own `$(VAR)` extension is not
2886/// load-bearing there: `is_msbuild_reference` already covered NuGet's `$(VAR)` case before this
2887/// function did.
2888///
2889/// The `$(VAR)` identifier grammar additionally accepts `-` in subsequent (never leading)
2890/// positions (`$(MOD-VERSION)`), matching real MSBuild property-name syntax (spec 070, issue
2891/// #1421). A `.` anywhere before the closing `)` (`$(A.VERSION)`) is a deliberate, researched
2892/// exclusion — not valid MSBuild syntax and not a documented real-world convention — and is
2893/// never matched, even in combination with a hyphen (`$(MOD.SUB-VERSION)`).
2894///
2895/// # Examples
2896///
2897/// ```
2898/// use deps_core::lsp_helpers::requirement_contains_template_placeholder;
2899///
2900/// assert!(requirement_contains_template_placeholder("${REACT_VERSION}"));
2901/// assert!(requirement_contains_template_placeholder("$VUE"));
2902/// assert!(requirement_contains_template_placeholder("1.0.0-$BUILD"));
2903/// assert!(requirement_contains_template_placeholder("$(LODASH_VERSION)"));
2904/// assert!(requirement_contains_template_placeholder("1.0.0-$(BUILD_SUFFIX)"));
2905/// assert!(requirement_contains_template_placeholder("$(MOD-VERSION)"));
2906/// assert!(requirement_contains_template_placeholder("1.0.0-$(BUILD-SUFFIX)"));
2907/// assert!(requirement_contains_template_placeholder("{{ .NetVersion }}"));
2908/// assert!(requirement_contains_template_placeholder("{% if x %}"));
2909/// assert!(requirement_contains_template_placeholder("@PACKAGE_VERSION@"));
2910/// assert!(requirement_contains_template_placeholder("@project.version@"));
2911/// assert!(requirement_contains_template_placeholder("%VERSION%"));
2912/// assert!(requirement_contains_template_placeholder("<%= version %>"));
2913/// assert!(!requirement_contains_template_placeholder("1.2.3"));
2914/// assert!(!requirement_contains_template_placeholder("price-is-$5"));
2915/// assert!(!requirement_contains_template_placeholder("price-is-$(five"));
2916/// assert!(!requirement_contains_template_placeholder("me@example.com"));
2917/// assert!(!requirement_contains_template_placeholder("100%"));
2918/// assert!(!requirement_contains_template_placeholder("$(A.VERSION)"));
2919/// assert!(!requirement_contains_template_placeholder("$(MOD.SUB-VERSION)"));
2920/// assert!(!requirement_contains_template_placeholder("$(-VERSION)"));
2921/// ```
2922pub fn requirement_contains_template_placeholder(requirement: &str) -> bool {
2923 let bytes = requirement.as_bytes();
2924 let has_dollar_form = bytes.iter().enumerate().any(|(i, &b)| {
2925 b == b'$'
2926 && match bytes.get(i + 1) {
2927 Some(b'{') => template_placeholder_identifier_end(bytes, i + 2).is_some(),
2928 // #1421: `[a-zA-Z_][a-zA-Z0-9_-]*` — a hyphen is accepted in subsequent
2929 // positions (real MSBuild property-name syntax, `$(MOD-VERSION)`); a dot
2930 // (`$(A.VERSION)`) remains a deliberate, researched exclusion (spec 070).
2931 Some(b'(') => hyphenated_identifier_end(bytes, i + 2)
2932 .is_some_and(|end| bytes.get(end) == Some(&b')')),
2933 _ => template_placeholder_identifier_end(bytes, i + 1).is_some(),
2934 }
2935 });
2936 has_dollar_form
2937 || contains_delimited_identifier_placeholder(requirement, b'@', dotted_identifier_end)
2938 || contains_delimited_identifier_placeholder(
2939 requirement,
2940 b'%',
2941 template_placeholder_identifier_end,
2942 )
2943 || contains_bracketed_placeholder(requirement, "{{", b"")
2944 || contains_bracketed_placeholder(requirement, "{%", b"-")
2945 || contains_bracketed_placeholder(requirement, "<%", b"=-")
2946}
2947
2948/// Result of checking whether a dependency's declared requirement is already satisfied by
2949/// the latest known version.
2950///
2951/// Diagnostics and inlay hints read this result differently: diagnostics only need to know
2952/// whether it is safe to skip the "Newer version available" warning, so both `UpToDate` and
2953/// `Unresolved` suppress it. Inlay hints additionally need to distinguish `Unresolved` from
2954/// `UpToDate`, since an unresolved requirement (e.g. a dangling Gradle version-catalog
2955/// `version.ref` alias, or an unexpanded Maven `${property}`) must not render an "up to
2956/// date" badge that was never actually verified.
2957// Exhaustive: a wildcard arm at any consuming match site would silently render the wrong
2958// label for a new variant instead of failing to compile (#769).
2959#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2960pub enum RequirementStatus {
2961 /// The latest version satisfies the declared requirement.
2962 UpToDate,
2963 /// The latest version does not satisfy the declared requirement — a newer version is
2964 /// available.
2965 Outdated,
2966 /// The requirement could not be resolved to a concrete constraint, so no comparison
2967 /// could be made.
2968 Unresolved,
2969}
2970
2971impl RequirementStatus {
2972 /// Maps [`Self::UpToDate`] to [`Self::Unresolved`], leaving every other status.
2973 ///
2974 /// The one definition of the cap applied to a status read from text that a truncated tag
2975 /// list cannot confirm (#1769): such a pin may be older than the text claims, but an
2976 /// outdated text status stays outdated.
2977 ///
2978 /// # Examples
2979 ///
2980 /// ```
2981 /// use deps_core::lsp_helpers::RequirementStatus::{Outdated, UpToDate, Unresolved};
2982 ///
2983 /// assert_eq!(UpToDate.never_up_to_date(), Unresolved);
2984 /// assert_eq!(Outdated.never_up_to_date(), Outdated);
2985 /// assert_eq!(Unresolved.never_up_to_date(), Unresolved);
2986 /// ```
2987 #[must_use]
2988 pub const fn never_up_to_date(self) -> Self {
2989 match self {
2990 Self::UpToDate => Self::Unresolved,
2991 Self::Outdated | Self::Unresolved => self,
2992 }
2993 }
2994}
2995
2996/// A `requirement` compiled by one ecosystem, ready to test candidate versions against.
2997///
2998/// Produced by [`formatter::RequirementResolution::compile_bounded_requirement`]. Kept as a separate object
2999/// (rather than a single "does any version match" function) so the requirement is parsed
3000/// once per dependency, and so the scanning loop — including the empty-list guard, the
3001/// early-exit on first match, and the "skip an unparseable candidate" rule — lives once in
3002/// [`requirement_is_unsatisfiable`] instead of being reimplemented by all eleven ecosystems.
3003///
3004/// # Examples
3005///
3006/// ```
3007/// use deps_core::lsp_helpers::RequirementMatcher;
3008/// use deps_core::ConcreteVersion;
3009///
3010/// struct ExactMatch(String);
3011///
3012/// impl RequirementMatcher for ExactMatch {
3013/// fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
3014/// Some(version.as_str() == self.0)
3015/// }
3016///
3017/// fn strict_prerelease_exclusion(&self) -> bool {
3018/// false
3019/// }
3020/// }
3021///
3022/// let matcher = ExactMatch("1.0.0".to_string());
3023/// assert_eq!(matcher.matches(&ConcreteVersion::new("1.0.0")), Some(true));
3024/// assert_eq!(matcher.matches(&ConcreteVersion::new("2.0.0")), Some(false));
3025/// ```
3026pub trait RequirementMatcher: Send + Sync {
3027 /// Tests one candidate version string against the compiled requirement.
3028 ///
3029 /// `Some(true)` / `Some(false)`: this candidate provably does / does not satisfy the
3030 /// requirement. `None`: this candidate *string* could not be parsed by this ecosystem's
3031 /// version format (e.g. a PyPI legacy release identifier, a Maven timestamped snapshot
3032 /// qualifier) — the caller skips it and keeps scanning the rest of the list. Never
3033 /// return `None` to mean "the requirement itself is unusable"; that is
3034 /// [`formatter::RequirementResolution::compile_bounded_requirement`]'s job, via returning `None` from that
3035 /// method instead of constructing a matcher at all.
3036 fn matches(&self, version: &ConcreteVersion) -> Option<bool>;
3037
3038 /// Whether this compiled matcher follows strict SemVer 2.0.0 pre-release semantics: a
3039 /// pre-release version (`X.Y.Z-pre`) is excluded from matching unless the compiled
3040 /// requirement itself pins to the same `X.Y.Z` tuple with a pre-release tag — the rule
3041 /// `semver::VersionReq` and `node_semver::Range` both implement.
3042 ///
3043 /// `matching_prerelease_would_satisfy`'s "requirement is unsatisfiable only because of
3044 /// default pre-release exclusion" enrichment (#299) is gated on this, read from the
3045 /// already-compiled matcher instance rather than from a separate per-formatter flag
3046 /// (#1478) — so a formatter that reuses an existing matcher implementation (e.g.
3047 /// `deps-npm`'s shared `NodeSemverGrammar`, also used by `deps-deno`) inherits the
3048 /// correct answer for free; only a formatter introducing a genuinely new matcher type
3049 /// needs to decide this at all, and only in the one place that type is defined.
3050 ///
3051 /// No default: a new matcher type must decide this explicitly rather than silently
3052 /// inheriting `false` by omission (#1478) — the whole point of moving this property off a
3053 /// per-formatter flag and onto the matcher type is that the answer can no longer go
3054 /// unconsidered. Return `true` only for a matcher whose underlying comparator itself
3055 /// implements this exclusion ([`compile_semver_requirement`]'s shared `semver::VersionReq`
3056 /// wrapper, used by `deps-cargo` and `deps-swift`; `deps-npm`'s shared
3057 /// `NodeSemverGrammar`/`node_semver::Range` wrapper, used by `deps-npm` and
3058 /// `deps-deno`). Maven/NuGet/Composer/Gradle/PyPI/Go/Bundler/Dart's own matchers use
3059 /// non-strict, ecosystem-specific range models where this premise does not hold — they must
3060 /// return `false`.
3061 ///
3062 /// # Examples
3063 ///
3064 /// ```
3065 /// use deps_core::ConcreteVersion;
3066 /// use deps_core::lsp_helpers::RequirementMatcher;
3067 ///
3068 /// struct NonStrictMatcher;
3069 /// impl RequirementMatcher for NonStrictMatcher {
3070 /// fn matches(&self, _version: &ConcreteVersion) -> Option<bool> {
3071 /// Some(true)
3072 /// }
3073 ///
3074 /// fn strict_prerelease_exclusion(&self) -> bool {
3075 /// false
3076 /// }
3077 /// }
3078 ///
3079 /// assert!(!NonStrictMatcher.strict_prerelease_exclusion());
3080 /// ```
3081 fn strict_prerelease_exclusion(&self) -> bool;
3082
3083 /// Whether this requirement's own grammar punches a hole that individually bans exactly
3084 /// `version`, independent of whether `version` would otherwise fall inside the
3085 /// requirement's nominal range — whether via a literal exclusion term (PyPI's `!=`/`!=X.*`,
3086 /// Composer's `!=`, Bundler's `!=`) or, for a grammar with no such operator, a gap between
3087 /// two segments of a disjoint range union (Maven's `[1.0,1.5),(1.5,2.0)`, which bans exactly
3088 /// `1.5.0`).
3089 ///
3090 /// Fix-cycle (#1571, generalized by #1590): [`crate::lsp_helpers::fallback_edit_excludes_newer`]'s
3091 /// `OriginalExcludesFallback` check needs this as an intensional signal — scanning
3092 /// `available` for "does some newer entry also match" cannot distinguish a punched-out
3093 /// hole from a fallback that legitimately exceeds the requirement's ceiling, since both
3094 /// produce the same `matches(fallback) == Some(false)` result and, when no newer entry
3095 /// happens to be listed in `available` either, the identical "nothing newer matches" scan
3096 /// outcome (critic-reproduced: `>=1.0,!=1.5.0,<2.0` and `>=1.0,<1.5` give the same verdict
3097 /// over `available = [2.0.0, 1.5.0, 1.0.0]` unless the matcher is asked directly).
3098 ///
3099 /// Default `false` — most ecosystems have no such shape (range/caret/tilde bounds only ever
3100 /// exclude by falling outside an interval, never by naming or gapping out one banned value
3101 /// inside it). A matcher overrides this exactly when its grammar CAN express such a hole —
3102 /// via a literal `!=`-style term, or, lacking one, via a gap between disjoint range/union
3103 /// segments — something `matches()` alone cannot surface as "explicitly banned" rather than
3104 /// "merely out of range".
3105 ///
3106 /// # Examples
3107 ///
3108 /// ```
3109 /// use deps_core::ConcreteVersion;
3110 /// use deps_core::lsp_helpers::RequirementMatcher;
3111 ///
3112 /// struct RangeOnlyMatcher;
3113 /// impl RequirementMatcher for RangeOnlyMatcher {
3114 /// fn matches(&self, _version: &ConcreteVersion) -> Option<bool> {
3115 /// Some(true)
3116 /// }
3117 /// fn strict_prerelease_exclusion(&self) -> bool {
3118 /// false
3119 /// }
3120 /// }
3121 ///
3122 /// assert!(!RangeOnlyMatcher.explicitly_excludes(&ConcreteVersion::new("1.5.0")));
3123 /// ```
3124 fn explicitly_excludes(&self, _version: &ConcreteVersion) -> bool {
3125 false
3126 }
3127}
3128
3129/// Parses `version` as [`semver::Version`] and tests it against `req`, `None` on parse failure.
3130/// Used by the test-only `NonStrictSemverMatcher` in `diagnostics.rs`, which mirrors
3131/// [`SemverGrammar`]'s matching and differs only in `strict_prerelease_exclusion()`.
3132#[cfg(test)]
3133pub(crate) fn semver_req_matches(
3134 req: &semver::VersionReq,
3135 version: &ConcreteVersion,
3136) -> Option<bool> {
3137 version
3138 .as_str()
3139 .parse::<semver::Version>()
3140 .ok()
3141 .map(|v| req.matches(&v))
3142}
3143
3144/// Compiles `requirement` as a plain [`semver::VersionReq`], the range grammar Cargo's registry
3145/// and Swift Package Manager's `from:`/closed-range/`upToNextMajor` translations both use for
3146/// matching.
3147///
3148/// For callers that compile a plain `semver::VersionReq` without a [`BoundedVersionReq`]; it
3149/// matches through [`SemverGrammar`], the grammar `deps-cargo`'s and `deps-swift`'s formatters
3150/// wrap with their own placeholder guards (#1495).
3151///
3152/// This function has no built-in unresolved-placeholder guard: Cargo and Swift's
3153/// [`formatter::RequirementResolution::bounded_requirement_is_unresolved`] overrides diverge
3154/// (Swift additionally rejects its own native `\(...)` string-interpolation syntax), so a
3155/// formatter must run its own guard first.
3156///
3157/// # Examples
3158///
3159/// ```
3160/// use deps_core::lsp_helpers::{RequirementMatcher, compile_semver_requirement};
3161/// use deps_core::{ConcreteVersion, VersionReq};
3162///
3163/// let matcher = compile_semver_requirement(&VersionReq::new("^1.0.0")).unwrap();
3164/// assert_eq!(matcher.matches(&ConcreteVersion::new("1.5.0")), Some(true));
3165/// assert_eq!(matcher.matches(&ConcreteVersion::new("2.0.0")), Some(false));
3166/// assert!(matcher.strict_prerelease_exclusion());
3167///
3168/// assert!(compile_semver_requirement(&VersionReq::new("not a semver req")).is_none());
3169/// ```
3170pub fn compile_semver_requirement(requirement: &VersionReq) -> Option<Box<dyn RequirementMatcher>> {
3171 requirement
3172 .as_str()
3173 .parse::<semver::VersionReq>()
3174 .ok()
3175 .map(|compiled| matcher_of(SemverGrammar, compiled))
3176}
3177
3178#[cfg(test)]
3179mod semver_req_matcher_tests {
3180 use super::compile_semver_requirement;
3181 use crate::{ConcreteVersion, VersionReq};
3182
3183 /// #299/#1495: `semver::VersionReq::matches` itself excludes a pre-release candidate unless
3184 /// the requirement pins to that exact `X.Y.Z` tuple with a pre-release tag — this is the
3185 /// actual behavior `strict_prerelease_exclusion() == true` promises callers, not just a flag
3186 /// value. `1.5.0-alpha.1` falls inside `>=1.0.0, <2.0.0`'s stable range but must still be
3187 /// rejected, since the requirement never pins to `1.5.0` specifically.
3188 #[test]
3189 fn matches_rejects_prerelease_candidate_not_pinned_by_requirement() {
3190 let matcher = compile_semver_requirement(&VersionReq::new(">=1.0.0, <2.0.0"))
3191 .expect("valid semver requirement must compile");
3192 assert_eq!(
3193 matcher.matches(&ConcreteVersion::new("1.5.0")),
3194 Some(true),
3195 "a stable candidate in range must match"
3196 );
3197 assert_eq!(
3198 matcher.matches(&ConcreteVersion::new("1.5.0-alpha.1")),
3199 Some(false),
3200 "a pre-release candidate must be rejected unless the requirement pins to its exact \
3201 X.Y.Z tuple with a pre-release tag"
3202 );
3203 }
3204
3205 /// The one documented exception: a requirement that itself pins to the same `X.Y.Z` tuple
3206 /// with a pre-release tag does admit that exact pre-release.
3207 #[test]
3208 fn matches_accepts_prerelease_candidate_pinned_by_requirement() {
3209 let matcher = compile_semver_requirement(&VersionReq::new("=1.5.0-alpha.1"))
3210 .expect("valid semver requirement must compile");
3211 assert_eq!(
3212 matcher.matches(&ConcreteVersion::new("1.5.0-alpha.1")),
3213 Some(true)
3214 );
3215 }
3216}
3217
3218/// Whether `segment` is exactly `.` or `..`.
3219///
3220/// Unlike ordinary path characters, a literal `.`/`..` segment is not neutralized by
3221/// percent-encoding: `.` is an unreserved character (RFC 3986), so `urlencoding::encode`
3222/// leaves it untouched, and the URL parser's dot-segment removal (RFC 3986 §5.2.4) still
3223/// collapses it after encoding — `%2E` decodes back to `.` before that normalization runs.
3224/// A registry-fetch URL built as `{base}/{prefix}/{name}` (no fixed suffix after `name`)
3225/// must reject a `name`/path segment satisfying this predicate rather than encode it,
3226/// since encoding alone does not stop the collapse (#341, #349).
3227///
3228/// Shared by `deps-npm`'s scope/package segment guard and `deps-dart`'s package-name
3229/// guard — both ecosystems' registry APIs key a fetch on a bare, suffix-less path segment.
3230///
3231/// **Scope**: this predicate (and the `#365` regression sweep built around it) guards
3232/// registry-*fetch* URL builders — the sink is a request this process actually
3233/// dereferences, so a retargeted URL can make it fetch attacker-chosen data. It
3234/// deliberately does *not* extend to a "docs link"/`package_url`-style builder (the
3235/// per-ecosystem hover/display link, e.g. `deps_cargo::crate_url`, `deps_go::package_url`):
3236/// those interpolate the name into a link rendered in hover text and never fetched by
3237/// this process, so an unrejected `.`/`..` name there produces at worst a misleading
3238/// same-host link (the registry's package-listing root), not a traversal off-host (#379).
3239///
3240/// # Examples
3241///
3242/// ```
3243/// use deps_core::lsp_helpers::is_dot_segment;
3244///
3245/// assert!(is_dot_segment(".."));
3246/// assert!(is_dot_segment("."));
3247/// assert!(!is_dot_segment("left-pad"));
3248/// ```
3249pub fn is_dot_segment(segment: &str) -> bool {
3250 segment == "." || segment == ".."
3251}
3252
3253/// Whether `version` is safe to embed in a manifest `TextEdit` or completion item.
3254///
3255/// Guards every call into
3256/// [`formatter::PackageRendering::format_version_replacing`]/[`formatter::PackageRendering::format_version_for_text_edit`]
3257/// and every completion item's `insert_text`/`text_edit`.
3258///
3259/// Must be applied to the raw version string *before* formatting, never to a
3260/// formatter's output: some formatters legitimately produce structural
3261/// characters in their output from an already-validated version plus fixed,
3262/// trusted operators (e.g. PyPI's `>=1.2.3,<2`), so validating the output
3263/// would wrongly reject those.
3264///
3265/// An allowlist, not a denylist: `version` must be non-empty, at most 64
3266/// bytes, and contain only `[A-Za-z0-9.+_~:*^!-]` — the character set real
3267/// version strings use across every ecosystem this workspace supports
3268/// (SemVer, PEP 440 including epochs like `1!2.0`, Maven qualifiers, npm's
3269/// `^`/`~`/`*` range tokens, Go's `+incompatible` suffix). A denylist here
3270/// would need to anticipate every dangerous token a target manifest format
3271/// (or a build tool evaluating it, e.g. Gradle's Kotlin/Groovy DSL
3272/// interpolating `${...}` inside a version literal) could ever act on;
3273/// failing closed on an unrecognized character is cheaper and safer.
3274///
3275/// This is the single validation chokepoint shared by every producer of a
3276/// version-derived `TextEdit`/completion item in this workspace, including
3277/// OSV advisory data (an `Advisory.fixed_versions` entry is exactly as
3278/// untrusted as a registry-reported version).
3279///
3280/// # Examples
3281///
3282/// ```
3283/// use deps_core::is_safe_version_string;
3284///
3285/// assert!(is_safe_version_string("1.2.3-alpha.1+build"));
3286/// assert!(!is_safe_version_string("1.2.3\", git = \"https://evil"));
3287/// ```
3288pub fn is_safe_version_string(version: &str) -> bool {
3289 !version.is_empty()
3290 && version.len() <= 64
3291 && version.chars().all(|c| {
3292 c.is_ascii_alphanumeric()
3293 || matches!(c, '.' | '+' | '_' | '~' | ':' | '*' | '^' | '!' | '-')
3294 })
3295}
3296
3297/// Whether `segment` is safe to embed as a Maven `groupId`/`artifactId` value in a
3298/// pom.xml `TextEdit` or completion item.
3299///
3300/// Guards Maven's group/artifact completion producer, which builds a completion item's
3301/// `insert_text`/`text_edit` from one field of a Maven Central search result — a value
3302/// type distinct from a version string (see [`is_safe_version_string`]'s doc comment for
3303/// why version-derived and non-version-derived sinks each get their own allowlist).
3304///
3305/// An allowlist, not a denylist: `segment` must be non-empty, at most 128 bytes, not
3306/// exactly `.`/`..` (see [`is_dot_segment`]), and contain only `[A-Za-z0-9._-]` — the
3307/// character set real Maven Central group ids (reverse-DNS style, e.g.
3308/// `org.apache.commons`) and artifact ids (hyphen/underscore separated, e.g.
3309/// `commons-lang3`) use. Deliberately excludes `:` — the `groupId:artifactId` separator —
3310/// because this validates one already-split coordinate field at a time, never the joined
3311/// pair. Failing closed on an unrecognized character (e.g. `<`, `"`, a newline) keeps a
3312/// malicious/compromised search result from restructuring the pom.xml it's inserted into;
3313/// the dedicated `.`/`..` rejection closes the same dot-segment URL-normalization gap
3314/// [`is_dot_segment`] guards elsewhere (`artifactId` reaches a registry-fetch URL as a bare
3315/// path segment in `deps-maven::registry::metadata_urls`, unlike `groupId`, whose `.`→`/`
3316/// expansion can never itself produce a literal `..` component).
3317///
3318/// # Examples
3319///
3320/// ```
3321/// use deps_core::is_safe_maven_coordinate_segment;
3322///
3323/// assert!(is_safe_maven_coordinate_segment("org.apache.commons"));
3324/// assert!(is_safe_maven_coordinate_segment("commons-lang3"));
3325/// assert!(!is_safe_maven_coordinate_segment("commons</artifactId><parent>"));
3326/// assert!(!is_safe_maven_coordinate_segment(".."));
3327/// ```
3328pub fn is_safe_maven_coordinate_segment(segment: &str) -> bool {
3329 !segment.is_empty()
3330 && segment.len() <= 128
3331 && !is_dot_segment(segment)
3332 && segment
3333 .chars()
3334 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
3335}
3336
3337/// Builds the Maven repository URL path (`"group/path/segments/artifact"`) for a
3338/// `groupId`/`artifactId` coordinate pair, or `None` if either fails validation.
3339///
3340/// The single shared home for `groupId:artifactId` -> URL-path construction (#702):
3341/// validates `group_id` and `artifact_id` as whole strings via
3342/// [`is_safe_maven_coordinate_segment`] (preserving its 128-byte total-length cap per
3343/// segment) *and* validates every `.`-separated component of `group_id` individually,
3344/// rejecting an empty component outright. The whole-string check alone is not enough —
3345/// it permits internal `.` characters, so a naive `group_id.replace('.', "/")` on a
3346/// coordinate like `"com..evil"` would produce the empty path segment `"com//evil"`; the
3347/// per-component check closes that gap without dropping the whole-string length bound a
3348/// pure per-segment `split('.')` validation would lose (a 10-segment, 128-byte-each group
3349/// would otherwise pass at 1280 bytes total).
3350///
3351/// # Examples
3352///
3353/// ```
3354/// use deps_core::maven_coordinate_path;
3355///
3356/// assert_eq!(
3357/// maven_coordinate_path("com.example", "artifact").as_deref(),
3358/// Some("com/example/artifact")
3359/// );
3360/// assert_eq!(
3361/// maven_coordinate_path("junit", "junit").as_deref(),
3362/// Some("junit/junit")
3363/// );
3364/// assert_eq!(maven_coordinate_path("com..evil", "artifact"), None);
3365/// ```
3366pub fn maven_coordinate_path(group_id: &str, artifact_id: &str) -> Option<String> {
3367 if !is_safe_maven_coordinate_segment(group_id) || !is_safe_maven_coordinate_segment(artifact_id)
3368 {
3369 return None;
3370 }
3371 let group_segments: Vec<&str> = group_id.split('.').collect();
3372 if group_segments
3373 .iter()
3374 .any(|segment| !is_safe_maven_coordinate_segment(segment))
3375 {
3376 return None;
3377 }
3378 Some(format!("{}/{artifact_id}", group_segments.join("/")))
3379}
3380
3381/// Whether `url` is safe to embed as a Swift Package Manager repository URL in a
3382/// Package.swift `TextEdit` or completion item.
3383///
3384/// Guards Swift's URL-completion producer, which builds a `.package(url: "...")`
3385/// string-literal replacement from a package registry search result's URL — a value
3386/// type distinct from a version string (see [`is_safe_version_string`]'s doc comment for
3387/// why version-derived and non-version-derived sinks each get their own allowlist).
3388///
3389/// An allowlist, not a denylist: `url` must be non-empty, at most 2048 bytes, start with
3390/// `https://` — every real Swift package registry response is HTTPS (GitHub's `html_url`
3391/// never downgrades), so accepting plain `http://` would only hand a
3392/// compromised/malicious registry a transport-downgrade lever for zero legitimate
3393/// benefit — and otherwise contain only RFC 3986 URL characters (`A-Za-z0-9` plus
3394/// `` -._~:/?#[]@!$&'()*+,;=% ``). Deliberately excludes `"`, `\`, control characters,
3395/// and whitespace — none of those are valid unencoded URL characters, and any of them
3396/// could close the surrounding Swift string literal or otherwise corrupt the manifest.
3397/// Failing closed on an unrecognized character keeps a malicious/compromised search
3398/// result from breaking out of the string it's inserted into.
3399///
3400/// # Examples
3401///
3402/// ```
3403/// use deps_core::is_safe_registry_url;
3404///
3405/// assert!(is_safe_registry_url("https://github.com/apple/swift-nio"));
3406/// assert!(!is_safe_registry_url("https://evil.example\", .exact(\"1\")) // "));
3407/// ```
3408pub fn is_safe_registry_url(url: &str) -> bool {
3409 !url.is_empty()
3410 && url.len() <= 2048
3411 && url.starts_with("https://")
3412 && url.chars().all(|c| {
3413 c.is_ascii_alphanumeric()
3414 || matches!(
3415 c,
3416 '-' | '.'
3417 | '_'
3418 | '~'
3419 | ':'
3420 | '/'
3421 | '?'
3422 | '#'
3423 | '['
3424 | ']'
3425 | '@'
3426 | '!'
3427 | '$'
3428 | '&'
3429 | '\''
3430 | '('
3431 | ')'
3432 | '*'
3433 | '+'
3434 | ','
3435 | ';'
3436 | '='
3437 | '%'
3438 )
3439 })
3440}
3441
3442/// Whether `name` is safe to embed as a package name in a manifest `TextEdit` or
3443/// completion item.
3444///
3445/// Guards every arm of `create_package_completion_item`
3446/// (`crates/deps-lsp/src/handlers/completion.rs`) as a single upfront check, applied
3447/// before the raw `name` reaches any ecosystem-specific snippet — including Maven and
3448/// Swift, which additionally validate a *derived* value on top of this gate
3449/// ([`is_safe_maven_coordinate_segment`] on each split coordinate segment,
3450/// [`is_safe_registry_url`] on the constructed URL) because a value type distinct from
3451/// the raw name needs its own allowlist — see [`is_safe_version_string`]'s doc comment
3452/// for why version-derived and non-version-derived sinks each get their own allowlist.
3453/// [`PackageName::new`](crate::PackageName::new) is documented as never validating or
3454/// modifying its input, so this predicate is the first gate a registry-reported name
3455/// passes through before reaching a manifest. Two sinks that key a bare TOML/YAML
3456/// entry by `name` (Cargo/PyPI, Dart) additionally quote that key in the snippet, since
3457/// `.` and `@` are legal here but would otherwise be read as TOML's dotted-key
3458/// separator or break a YAML plain scalar.
3459///
3460/// An allowlist, not a denylist: `name` must be non-empty, at most 256 bytes, and
3461/// contain only `[A-Za-z0-9._@:/~-]` — the character set real package names use across
3462/// every ecosystem this predicate guards: Cargo/PyPI/Dart/NuGet/Bundler
3463/// (alphanumeric, `-`, `_`, `.`), npm/Deno scoped names (`@scope/name`, adding `@` and
3464/// `/`), Composer (`vendor/package`, `/`), Go module paths (domain-qualified paths like
3465/// `github.com/org/repo`, `/`, `.`, and `~` — legal in a Go path element and already
3466/// allowed by [`is_safe_version_string`]/[`is_safe_registry_url`]), and Gradle's
3467/// colon-delimited `group:artifact` short form (`:`). A denylist here would need to
3468/// anticipate every dangerous token a target manifest format (TOML/JSON/YAML/XML
3469/// string literals, a live Kotlin/Groovy build-script DSL) could ever act on; failing
3470/// closed on an unrecognized character — notably `"`, `'`, `<`, `>`, `` ` ``, and all
3471/// control characters/newlines — is cheaper and safer.
3472///
3473/// # Examples
3474///
3475/// ```
3476/// use deps_core::is_safe_package_name;
3477///
3478/// assert!(is_safe_package_name("serde"));
3479/// assert!(is_safe_package_name("@scope/name"));
3480/// assert!(is_safe_package_name("org.apache.commons:commons-lang3"));
3481/// assert!(!is_safe_package_name("evil\"\nbackdoor = \"9.9.9"));
3482/// ```
3483pub fn is_safe_package_name(name: &str) -> bool {
3484 !name.is_empty()
3485 && name.len() <= 256
3486 && name.chars().all(|c| {
3487 c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '@' | ':' | '/' | '-' | '~')
3488 })
3489}
3490
3491/// Whether `name` is safe to embed as a Cargo feature name in a manifest `TextEdit` or
3492/// completion item.
3493///
3494/// Guards [`crate::completion::build_feature_completion`] the same way
3495/// [`is_safe_package_name`] guards [`crate::completion::build_package_completion`]:
3496/// `feature_name` there is registry-supplied (a key of `Version::features()`, read from
3497/// the index JSON's `features`/`features2` maps), not user-typed, so it must pass this
3498/// allowlist before reaching `label`/`insert_text`/`text_edit`/`sort_text`.
3499///
3500/// An allowlist, narrower than [`is_safe_package_name`]: Cargo's own feature-name grammar
3501/// (<https://doc.rust-lang.org/cargo/reference/features.html#the-features-section>) permits
3502/// Unicode `XID_Start`/`XID_Continue` characters, but crates.io's publish-time check — the
3503/// registry `deps-cargo` actually talks to — is stricter and only accepts ASCII
3504/// alphanumerics, `_`, `-`, and `+`; this predicate matches that stricter, ASCII-only set
3505/// (plus `.`, this predicate's own addition, not part of crates.io's check, allowed because
3506/// it's already permitted in [`is_safe_package_name`] and carries the same low risk here).
3507/// `dep:`, `?`, and `/` are never part of a feature *name* (an index JSON map key) either
3508/// way — they only ever appear inside a feature's *value* list (e.g.
3509/// `"avif" = ["dep:ravif", "rgb?/serde"]`), which this predicate never sees. A
3510/// registry-supplied string containing any of those characters is therefore not a
3511/// plausible feature name regardless of intent, so it is rejected the same as any other
3512/// out-of-allowlist character.
3513///
3514/// Tradeoff, accepted rather than incidental: a legitimate feature name published with a
3515/// Unicode `XID` character to an *alternate* (non-crates.io) registry — which Cargo's own
3516/// grammar permits but crates.io's check does not — would fail this allowlist and be
3517/// silently dropped rather than rendered. Failing closed on a character class this
3518/// predicate cannot cheaply distinguish from a homograph/bidi-spoofing attempt is judged
3519/// safer than accepting the full Cargo grammar, consistent with [`is_safe_package_name`]'s
3520/// own ASCII-only rationale.
3521///
3522/// # Examples
3523///
3524/// ```
3525/// use deps_core::is_safe_feature_name;
3526///
3527/// assert!(is_safe_feature_name("derive"));
3528/// assert!(is_safe_feature_name("std_alloc-v2+extra"));
3529/// assert!(!is_safe_feature_name("dep:ravif"));
3530/// assert!(!is_safe_feature_name("rgb?/serde"));
3531/// assert!(!is_safe_feature_name("evil\"\nbackdoor = \"9.9.9"));
3532/// ```
3533pub fn is_safe_feature_name(name: &str) -> bool {
3534 !name.is_empty()
3535 && name.len() <= 256
3536 && name
3537 .chars()
3538 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '+' | '.'))
3539}
3540
3541/// Logs a `tracing::warn!` for a value rejected by an `is_safe_*` predicate (or an
3542/// equivalent value-rejecting gate) before it reaches a manifest edit or registry URL.
3543///
3544/// Deliberately logs only `value`'s byte length, never its content: `value` is
3545/// registry-controlled and, by construction, already failed an allowlist — logging it
3546/// verbatim at `warn` would let a malicious/compromised registry response inject arbitrary
3547/// content into this project's own log stream (a second-order log-injection concern),
3548/// mirroring why `deps-pypi`'s `truncate_for_log` bounds a logged excerpt instead of
3549/// logging a value verbatim. This is this helper's own contract, not a claim that every
3550/// `tracing` call site in the workspace avoids logging a raw value — e.g. an OSV
3551/// malformed-`fixed`-version warning predates this helper and logs its rejected value
3552/// directly; that is an unrelated call site, not a place this helper is used.
3553///
3554/// `gate` names the predicate/guard that rejected `value` (e.g.
3555/// `"is_safe_maven_coordinate_segment"`); `context` is a short description of the call site
3556/// (e.g. `"maven groupId completion"`).
3557///
3558/// # Examples
3559///
3560/// ```
3561/// use deps_core::lsp_helpers::warn_rejected_value;
3562///
3563/// warn_rejected_value("is_safe_version_string", "code lens latest version", "1.0.0\"; evil");
3564/// ```
3565pub fn warn_rejected_value(gate: &str, context: &str, value: &str) {
3566 tracing::warn!(
3567 gate,
3568 context,
3569 len = value.len(),
3570 "rejected unsafe value before manifest/registry sink"
3571 );
3572}
3573
3574/// Logs a [`warn_rejected_value`] warning and builds the [`DepsError::PackageNotFound`] a
3575/// caller returns after its own `is_dot_segment`/`has_dot_segment` predicate rejects `name`.
3576///
3577/// Extracted from four equivalent `warn_rejected_value` + `PackageNotFound`
3578/// constructions in `deps-dart`, `deps-composer`, `deps-nuget`, and `deps-npm`
3579/// (deps-lsp#929 item 2) — `deps-npm`'s `gate` label was `"npm_dot_segment_guard"` rather
3580/// than the other three's `"is_dot_segment"` before this extraction normalized it. Each
3581/// crate keeps its own dot-segment *predicate* and the call to it exactly where it is
3582/// today; only this trailing boilerplate is shared. Deliberately does **not** fold in
3583/// `deps-go`'s guard, which returns `DepsError::InvalidPackageName`, not `PackageNotFound`.
3584///
3585/// # Examples
3586///
3587/// ```
3588/// use deps_core::lsp_helpers::dot_segment_rejection_error;
3589/// use deps_core::DepsError;
3590///
3591/// let err = dot_segment_rejection_error(
3592/// "is_dot_segment",
3593/// "example package metadata request URL",
3594/// "..",
3595/// "example",
3596/// );
3597/// assert!(matches!(err, DepsError::PackageNotFound { .. }));
3598/// ```
3599#[must_use]
3600pub fn dot_segment_rejection_error(
3601 gate: &str,
3602 context: &str,
3603 name: &str,
3604 registry: &'static str,
3605) -> DepsError {
3606 warn_rejected_value(gate, context, name);
3607 DepsError::not_found_locally(name, registry)
3608}
3609
3610/// Converts a domain [`url::Url`] back into a `tower_lsp_server::ls_types::Uri` for
3611/// embedding into an actual LSP response object (`WorkspaceEdit`, `Location`, a code-lens
3612/// command argument, ...).
3613///
3614/// This is the one blessed conversion path from `deps-core`'s internal `url::Url` domain
3615/// type to `tower_lsp_server`'s `Uri` — ecosystem crates and `deps-core` itself must route
3616/// through it rather than re-deriving the conversion (e.g. `uri.as_str().parse()`) locally,
3617/// so a future change to how URLs round-trip through the LSP wire format only needs fixing
3618/// in one place. It mirrors `deps-lsp`'s own `lsp_types_interop::to_lsp_uri` (issue #1071):
3619/// `deps-core` cannot reuse that function (the dependency direction points the other way)
3620/// or express this as a `From` impl (neither `url::Url` nor `ls_types::Uri` is local to
3621/// `deps-core` — the same orphan-rule constraint that makes the `deps-lsp` boundary a pair
3622/// of free functions instead of a trait impl), so this is `deps-core`'s independent
3623/// counterpart, needed because `lsp_helpers` still builds real `ls_types` response objects
3624/// directly even though `Dependency`/`ParseResult` no longer carry an `ls_types::Uri` (see
3625/// `lib.rs`'s "LSP type stability" doc section).
3626///
3627/// # Panics
3628///
3629/// Panics if `url`'s string form does not round-trip into an `Uri`. In practice this
3630/// never happens: every `url::Url` reaching `lsp_helpers` originates from a real
3631/// editor-opened document (an `ls_types::Uri` converted to `Url` at the `deps-lsp`
3632/// boundary), so failing to convert it back indicates upstream corruption, not
3633/// attacker-controlled manifest content.
3634///
3635/// # Examples
3636///
3637/// ```
3638/// use deps_core::to_ls_uri;
3639/// use url::Url;
3640///
3641/// let url = Url::parse("file:///tmp/Cargo.toml").unwrap();
3642/// let uri = to_ls_uri(&url);
3643/// assert_eq!(uri.as_str(), "file:///tmp/Cargo.toml");
3644/// ```
3645#[cfg(feature = "lsp-responses")]
3646#[must_use]
3647pub fn to_ls_uri(url: &url::Url) -> tower_lsp_server::ls_types::Uri {
3648 url.as_str()
3649 .parse()
3650 .unwrap_or_else(|e| panic!("document URL {url} did not round-trip to an LSP Uri: {e}"))
3651}
3652
3653/// Builds a single-entry [`tower_lsp_server::ls_types::WorkspaceEdit::changes`] map replacing `range` in `uri`
3654/// with `new_text`.
3655///
3656/// Shared by every quickfix/refactor code action in `code_actions` that edits exactly
3657/// one span in the current document (`build_vulnerability_fix_action`,
3658/// `build_unsatisfiable_fix_action`, and the plain "update to `<version>`" loop in
3659/// [`generate_code_actions`]) — and by any ecosystem crate hand-building a
3660/// `WorkspaceEdit` for a single-span fix instead of reimplementing this map shape
3661/// locally.
3662///
3663/// # Panics
3664///
3665/// Panics if `uri` does not round-trip through [`to_ls_uri`] — see that function's own
3666/// `# Panics` section.
3667///
3668/// # Examples
3669///
3670/// ```
3671/// use deps_core::single_file_edit;
3672/// use deps_core::position::{Position, Range};
3673/// use url::Url;
3674///
3675/// let url = Url::parse("file:///tmp/Cargo.toml").unwrap();
3676/// let range = Range::new(Position::new(0, 0), Position::new(0, 5));
3677/// let edits = single_file_edit(&url, range, "1.2.3".to_string());
3678///
3679/// assert_eq!(edits.len(), 1);
3680/// ```
3681#[cfg(feature = "lsp-responses")]
3682#[must_use]
3683pub fn single_file_edit(
3684 uri: &url::Url,
3685 range: Range,
3686 new_text: String,
3687) -> HashMap<tower_lsp_server::ls_types::Uri, Vec<tower_lsp_server::ls_types::TextEdit>> {
3688 let mut edits = HashMap::new();
3689 edits.insert(
3690 to_ls_uri(uri),
3691 vec![tower_lsp_server::ls_types::TextEdit {
3692 range: range.into(),
3693 new_text,
3694 }],
3695 );
3696 edits
3697}
3698
3699/// Strips every whitespace character from `s`, so two textually-equivalent strings that
3700/// differ only in spacing compare equal.
3701///
3702/// Shared by every no-op/literal-match guard across `code_actions` and `code_lenses`
3703/// (`build_vulnerability_fix_action`'s N1 guard, `generate_code_actions`'s REFACTOR-loop
3704/// guard, `literal_span_matches`, and `collect_update_all_edits`'s no-op guard), all of
3705/// which compare a declared requirement
3706/// string against a differently-normalized counterpart — e.g. pep508's `>=1.7, <2.0` vs. a
3707/// formatter's `>=1.7,<2.0`.
3708pub(crate) fn strip_whitespace(s: &str) -> String {
3709 s.chars().filter(|c| !c.is_whitespace()).collect()
3710}
3711
3712/// Slices `content` over an LSP `Range` using a pre-built `LineOffsetTable`, returning
3713/// `""` for an inverted or out-of-bounds range instead of panicking.
3714///
3715/// `table` is document-invariant — callers iterating over multiple dependencies in the
3716/// same document must build it once and reuse it, rather than rebuilding it (an O(n)
3717/// scan of `content`) per dependency.
3718pub(crate) fn slice_for_range<'a>(
3719 content: &'a str,
3720 table: &LineOffsetTable,
3721 range: Range,
3722) -> &'a str {
3723 let start = table.position_to_byte_offset(content, range.start);
3724 let end = table.position_to_byte_offset(content, range.end);
3725 if start > end {
3726 return "";
3727 }
3728 content.get(start..end).unwrap_or("")
3729}
3730
3731/// Checks whether `slice` — `content` sliced over a dependency's `version_range` — still
3732/// holds the literal version text declared by `requirement`.
3733///
3734/// Whitespace is stripped from both sides before comparison, since pep508's normalized
3735/// requirement string can diverge from the original source spacing (PyPI's `>=1.7,<2.0`
3736/// renders as `>=1.7, <2.0`) while `version_range` still spans the un-normalized source.
3737///
3738/// The second branch accepts `slice` wrapped in brackets matching `requirement` — the
3739/// exact inverse of NuGet's parser wrapping a bare source version as `format!("[{v}]")`
3740/// (`crates/deps-nuget/src/parser.rs`). This is deliberately **not** a symmetric bracket
3741/// strip: NuGet's `Version="1.0.0"` produces requirement `[1.0.0]` over a bare-literal
3742/// span, so a *symmetric* strip (stripping one bracket pair from both operands) would
3743/// compare `1.0.0` against `1.0.0` — coincidentally correct there, but the same strip
3744/// applied to `Version="[1.0.0]"` (requirement `[[1.0.0]]`, a spelling
3745/// `crates/deps-nuget/src/formatter.rs` explicitly supports) leaves `[1.0.0]` vs
3746/// `1.0.0` and **falsely rejects** an editable dependency. Wrapping only the slice side
3747/// handles both spellings without that false reject.
3748pub(crate) fn literal_span_matches(slice: &str, requirement: &str) -> bool {
3749 let norm_slice = strip_whitespace(slice);
3750 let norm_req = strip_whitespace(requirement);
3751 norm_slice == norm_req || format!("[{norm_slice}]") == norm_req
3752}
3753
3754/// Whether `version_range`'s slice of `content` still holds `dep`'s own declared literal
3755/// version text.
3756///
3757/// The same literal-span discipline [`generate_code_actions`] and
3758/// `collect_update_all_edits` already apply before writing a `TextEdit` there, generalized
3759/// (issue #919) for any caller about to treat `version_range` as an editable literal: a
3760/// completion context, or a raw-text-scanning ecosystem's own completion dispatch (Maven,
3761/// Gradle) that never goes through [`crate::completion::detect_completion_context`] at all.
3762///
3763/// Returns `false` — not editable — when the slice is syntactically reference-shaped (see
3764/// below), or the slice doesn't textually match the declared literal. When `dep` has no
3765/// [`Dependency::version_requirement`] at all, an empty (or whitespace-only) slice is admitted
3766/// — e.g. Maven's `<version></version>`, which has no text for its parser to capture and thus
3767/// nothing that could be misread as a reference/wildcard (#1161) — but a *non-empty* slice is
3768/// still rejected, since there is then no requirement to validate it against.
3769///
3770/// The reference-shape check runs **independently** of the text comparison (#919 C1): an
3771/// *unresolved* Maven `${property}` or Gradle `$var`/`${var}` interpolation is left by its
3772/// parser exactly as-is in both `version_range`'s slice and `version_requirement` (there is
3773/// nothing else to put there), so the two would otherwise textually agree and wrongly pass —
3774/// this is precisely the corruption #919 was filed over, and the dominant real-world Maven
3775/// case (a version inherited from a parent/BOM POM this crate cannot resolve) always lands
3776/// here. A slice containing `$` anywhere is rejected up front, before ever comparing text —
3777/// this single check subsumes both a whole-value `$var`/`${var}` interpolation and a Gradle
3778/// GString with the reference embedded mid-string (`1.0.$patch`), which `resolve_variable_ref`
3779/// only ever resolves in its whole-value form, leaving the mid-string case byte-identical
3780/// between slice and requirement and otherwise invisible to a `starts_with`-only check. A
3781/// slice that starts with `*` is rejected the same way *unless* [`crate::is_existence_wildcard_str`]
3782/// recognizes it as the project-wide existence-wildcard spelling (synthesized by `deps-npm`,
3783/// `deps-composer`, ...) — that case must keep offering a full version list at the exact
3784/// moment a user wants to replace the wildcard with a pin, while a `*anchor` YAML alias (any
3785/// other leading-`*` shape) still gets rejected.
3786///
3787/// An empty `version_requirement` is deliberately **not** special-cased here (unlike
3788/// `generate_code_actions`'s "nothing to update" early return, which does not apply to
3789/// completion): `serde = ""` / `"lodash": ""` — what an editor's auto-closing quotes produce
3790/// the instant the opening quote is typed — must still offer the full version list.
3791/// `literal_span_matches` alone already handles this correctly: `("", "")` matches (empty
3792/// slice, empty requirement — admitted), while a non-empty non-literal slice against an empty
3793/// requirement still fails to match (rejected).
3794///
3795/// Compares against [`Dependency::version_literal`] when the ecosystem provides one, falling
3796/// back to `version_requirement` otherwise (see that method's doc for why).
3797///
3798/// Builds its own [`LineOffsetTable`] for `content` on every call rather than accepting a
3799/// caller-built one — unlike `slice_for_range`'s multi-dependency callers (`generate_code_actions`,
3800/// `code_lenses`), every current call site invokes this at most once per request (a single
3801/// matched dependency), so a table-accepting overload would add API surface with no caller to
3802/// exercise it.
3803///
3804/// # Examples
3805///
3806/// ```
3807/// use deps_core::lsp_helpers::dependency_version_range_is_literal;
3808/// use deps_core::{Dependency, PackageName, VersionReq};
3809/// use std::any::Any;
3810/// use tower_lsp_server::ls_types::{Position, Range};
3811///
3812/// struct MockDep {
3813/// name: PackageName,
3814/// version_req: VersionReq,
3815/// version_range: deps_core::position::Range,
3816/// }
3817/// impl Dependency for MockDep {
3818/// fn name(&self) -> &PackageName {
3819/// &self.name
3820/// }
3821/// fn name_range(&self) -> deps_core::position::Range {
3822/// deps_core::position::Range::default()
3823/// }
3824/// fn version_requirement(&self) -> Option<&VersionReq> {
3825/// Some(&self.version_req)
3826/// }
3827/// fn version_range(&self) -> Option<deps_core::position::Range> {
3828/// Some(self.version_range)
3829/// }
3830/// fn source(&self) -> deps_core::parser::DependencySource {
3831/// deps_core::parser::DependencySource::Registry
3832/// }
3833/// }
3834///
3835/// // A plain literal version is admitted.
3836/// let content = r#"serde = "1.0.0""#;
3837/// let dep = MockDep {
3838/// name: PackageName::new("serde"),
3839/// version_req: VersionReq::new("1.0.0"),
3840/// version_range: Range::new(Position::new(0, 9), Position::new(0, 14)).into(),
3841/// };
3842/// assert!(dependency_version_range_is_literal(&dep, content, dep.version_range.into()));
3843///
3844/// // A Maven `${property}` interpolation is rejected even when unresolved — slice and
3845/// // requirement are byte-identical raw reference text, which the shape check catches
3846/// // independently of the (otherwise-matching) text comparison.
3847/// let content = r"<version>${slf4j.version}</version>";
3848/// let dep = MockDep {
3849/// name: PackageName::new("slf4j-api"),
3850/// version_req: VersionReq::new("${slf4j.version}"),
3851/// version_range: Range::new(Position::new(0, 9), Position::new(0, 25)).into(),
3852/// };
3853/// assert!(!dependency_version_range_is_literal(&dep, content, dep.version_range.into()));
3854/// ```
3855#[must_use]
3856pub fn dependency_version_range_is_literal(
3857 dep: &dyn Dependency,
3858 content: &str,
3859 version_range: Range,
3860) -> bool {
3861 if version_range == Range::default() {
3862 // `Range::default()` ((0,0)-(0,0)) is a purely syntactic "not a real position"
3863 // sentinel, never a genuine in-document location — `deps-gradle`'s catalog context
3864 // deliberately returns it for a `version.ref = "alias"` reference (#931), including a
3865 // dangling or still-being-typed one, so this function must always reject it
3866 // unconditionally, before the `version_requirement()` check below ever runs.
3867 return false;
3868 }
3869
3870 let table = LineOffsetTable::new(content);
3871 let slice = slice_for_range(content, &table, version_range);
3872 let trimmed = slice.trim();
3873
3874 let Some(version_req) = dep.version_requirement() else {
3875 // No parsed requirement at all — e.g. Maven's `<version></version>`, which has no
3876 // text for its parser to capture. An empty span here has no existing text that could
3877 // be misread as a reference/wildcard, so it is always safe to offer completion
3878 // (#1161) — now that the `Range::default()` sentinel above is rejected first, this can
3879 // only be a genuine in-document position.
3880 return trimmed.is_empty();
3881 };
3882 if trimmed.contains('$')
3883 || (trimmed.starts_with('*') && !crate::is_existence_wildcard_str(trimmed))
3884 {
3885 return false;
3886 }
3887 let literal_target = dep
3888 .version_literal()
3889 .unwrap_or_else(|| version_req.as_str());
3890 literal_span_matches(slice, literal_target)
3891}
3892
3893#[cfg(test)]
3894#[expect(
3895 clippy::string_slice,
3896 reason = "fixtures are single-line ASCII literals with hand-computed byte offsets"
3897)]
3898mod tests {
3899 use super::*;
3900 use crate::lsp_helpers::test_support::*;
3901 use crate::osv::{SkipReason, StructuralSkipReason};
3902 use crate::{DependencySource, PackageName, VersionReq};
3903 use std::assert_matches;
3904
3905 // --- gossip_cooldown_for (issue #1456, spec 072 FR-008/FR-011, S2 tri-state) ---
3906
3907 fn gossip_findings_fixture(version: &str, end_unix_secs: i64) -> GossipFindings {
3908 GossipFindings {
3909 version: version.to_string(),
3910 cooldown: Some(crate::GossipCooldown {
3911 end: PublishTime::from_unix_secs(end_unix_secs),
3912 risk: crate::GossipRiskLevel::High,
3913 }),
3914 low_usage: None,
3915 }
3916 }
3917
3918 fn gossip_findings_fixture_not_in_cooldown(version: &str) -> GossipFindings {
3919 GossipFindings {
3920 version: version.to_string(),
3921 cooldown: None,
3922 low_usage: None,
3923 }
3924 }
3925
3926 #[test]
3927 fn gossip_cooldown_for_none_prefetch_is_unavailable() {
3928 let name = NormalizedName::for_test("vite");
3929 assert_matches!(
3930 gossip_cooldown_for(None, &name, "8.3.1", PublishTime::now()),
3931 GossipCooldownLookup::Unavailable
3932 );
3933 }
3934
3935 #[test]
3936 fn gossip_cooldown_for_matching_active_version_is_active() {
3937 let name = NormalizedName::for_test("vite");
3938 let mut prefetch = HashMap::new();
3939 prefetch.insert(name.clone(), gossip_findings_fixture("8.3.1", 2_000));
3940
3941 let lookup = gossip_cooldown_for(
3942 Some(&prefetch),
3943 &name,
3944 "8.3.1",
3945 PublishTime::from_unix_secs(1_000),
3946 );
3947 assert_eq!(lookup, GossipCooldownLookup::Active);
3948 }
3949
3950 #[test]
3951 fn gossip_cooldown_for_version_mismatch_is_unavailable() {
3952 let name = NormalizedName::for_test("vite");
3953 let mut prefetch = HashMap::new();
3954 prefetch.insert(name.clone(), gossip_findings_fixture("8.3.1", 2_000));
3955
3956 // FR-008: the prefetch entry is for 8.3.1, but the caller is displaying 8.4.0 (a
3957 // newer release the prefetch hasn't caught up with yet) — must be `Unavailable`,
3958 // not the stale 8.3.1 answer.
3959 let lookup = gossip_cooldown_for(
3960 Some(&prefetch),
3961 &name,
3962 "8.4.0",
3963 PublishTime::from_unix_secs(1_000),
3964 );
3965 assert_matches!(lookup, GossipCooldownLookup::Unavailable);
3966 }
3967
3968 #[test]
3969 fn gossip_cooldown_for_ended_cooldown_self_clears_to_not_active_at_read_time() {
3970 let name = NormalizedName::for_test("vite");
3971 let mut prefetch = HashMap::new();
3972 prefetch.insert(name.clone(), gossip_findings_fixture("8.3.1", 1_000));
3973
3974 // FR-011: `end` compared against `now` at read time, never a stored bool — a `now`
3975 // past `end` must self-clear to `NotActive` (GOSSIP data is present and version-
3976 // matched, it just no longer reports an active cooldown), never `Unavailable`
3977 // (which would wrongly let the caller fall back to the local heuristic).
3978 let lookup = gossip_cooldown_for(
3979 Some(&prefetch),
3980 &name,
3981 "8.3.1",
3982 PublishTime::from_unix_secs(2_000),
3983 );
3984 assert_matches!(lookup, GossipCooldownLookup::NotActive);
3985 }
3986
3987 /// Spec 075 FR-005 (R-S3), inverting the earlier `..._is_not_active` expectation: GOSSIP
3988 /// data present, version-matched, but explicitly reporting no cooldown at all
3989 /// (`cooldown: None` — no `COOLDOWN` finding and no `cooldownEnd` fallback) must be
3990 /// `Unavailable`, not `NotActive` — `NotActive` now means only "a parsed, past `end` was
3991 /// found", so the caller falls back to the local heuristic instead of reading this as an
3992 /// authoritative "not in cooldown" answer (the old mapping was fail-open for a write path).
3993 #[test]
3994 fn gossip_cooldown_for_present_but_no_cooldown_data_is_unavailable() {
3995 let name = NormalizedName::for_test("vite");
3996 let mut prefetch = HashMap::new();
3997 prefetch.insert(
3998 name.clone(),
3999 gossip_findings_fixture_not_in_cooldown("8.3.1"),
4000 );
4001
4002 let lookup = gossip_cooldown_for(Some(&prefetch), &name, "8.3.1", PublishTime::now());
4003 assert_matches!(lookup, GossipCooldownLookup::Unavailable);
4004 }
4005
4006 #[test]
4007 fn gossip_cooldown_for_absent_name_is_unavailable() {
4008 let name = NormalizedName::for_test("vite");
4009 let other = NormalizedName::for_test("left-pad");
4010 let mut prefetch = HashMap::new();
4011 prefetch.insert(other, gossip_findings_fixture("1.3.0", 2_000));
4012
4013 assert_matches!(
4014 gossip_cooldown_for(Some(&prefetch), &name, "8.3.1", PublishTime::now()),
4015 GossipCooldownLookup::Unavailable
4016 );
4017 }
4018
4019 // --- cooldown_disposition (spec 075 FR-004/NFR-002) ---
4020
4021 /// Spec 099: a native publish-age hold is reported even with freshness disabled, and keeps a
4022 /// stored fallback only when that fallback itself clears the native window.
4023 #[test]
4024 fn cooldown_disposition_native_hold_is_independent_of_freshness_and_vets_the_fallback() {
4025 use crate::native_cooldown::{
4026 NativeCooldown, NativeCooldownSource, NativeGate, NativeLimit, TimeSpanValue,
4027 parse_time_span,
4028 };
4029 let TimeSpanValue::Span(span) = parse_time_span("1 hour").expect("span") else {
4030 panic!("a span");
4031 };
4032 let cooldown =
4033 NativeCooldown::new(NativeLimit::MinAge(span), NativeCooldownSource::CargoGlobal);
4034 let now = PublishTime::from_unix_secs(100_000);
4035 let name = NormalizedName::for_test("pkg");
4036 let cached = HashMap::new();
4037 let resolved = HashMap::new();
4038 let version_data = VersionData::new(&cached, &resolved).with_now(now);
4039 let gate = NativeGate::for_name(&cooldown, &name, &version_data);
4040
4041 let held = |fallback_published: i64| {
4042 PackageVersions::new(
4043 "2.0.0".into(),
4044 Arc::from(vec!["2.0.0".into(), "1.9.0".into()]),
4045 )
4046 .with_published_at(PublishTime::from_unix_secs(99_000))
4047 .with_publish_times(Arc::from(vec![
4048 Some(PublishTime::from_unix_secs(99_000)),
4049 Some(PublishTime::from_unix_secs(fallback_published)),
4050 ]))
4051 .with_cooldown_fallback(CooldownFallback::new(
4052 "1.9.0".into(),
4053 PublishTime::from_unix_secs(fallback_published),
4054 ))
4055 };
4056
4057 let old_fallback = held(1_000);
4058 let disposition = cooldown_disposition(
4059 &old_fallback,
4060 &name,
4061 crate::freshness::FreshnessSettings::Disabled,
4062 None,
4063 Some(&gate),
4064 now,
4065 );
4066 assert_matches!(
4067 disposition,
4068 CooldownDisposition::NativeHeld { fallback: None, .. },
4069 "freshness disabled never yields a fallback, but the native hold is still reported"
4070 );
4071
4072 let enabled = crate::freshness::FreshnessSettings::Enabled {
4073 cooldown: CooldownWindow::from_secs(5_000),
4074 };
4075 assert_matches!(
4076 cooldown_disposition(&old_fallback, &name, enabled, None, Some(&gate), now),
4077 CooldownDisposition::NativeHeld {
4078 fallback: Some(_),
4079 ..
4080 }
4081 );
4082
4083 let young_fallback = held(99_500);
4084 assert_matches!(
4085 cooldown_disposition(&young_fallback, &name, enabled, None, Some(&gate), now),
4086 CooldownDisposition::NativeHeld { fallback: None, .. },
4087 "a fallback inside the native window is dropped"
4088 );
4089
4090 assert_matches!(
4091 cooldown_disposition(&old_fallback, &name, enabled, None, None, now),
4092 CooldownDisposition::Blocked { .. },
4093 "without a gate the disposition is the freshness one"
4094 );
4095 }
4096
4097 /// Fix-cycle item 8 (M3/NFR-002): a stored fallback candidate is re-evaluated against
4098 /// read-time `now`/cooldown window, not trusted as a fetch-time snapshot. A
4099 /// fallback whose own `published_at` no longer clears a (narrower, read-time)
4100 /// cooldown window must read as absent, not as a stale "still usable" answer.
4101 #[test]
4102 fn cooldown_disposition_read_time_reevaluates_the_stored_fallback() {
4103 let now = PublishTime::from_unix_secs(10_000);
4104 let versions = PackageVersions::new("2.0.0".into(), Arc::from(vec!["2.0.0".into()]))
4105 .with_published_at(PublishTime::from_unix_secs(9_900)) // 100s old
4106 .with_cooldown_fallback(CooldownFallback::new(
4107 "1.9.0".into(),
4108 PublishTime::from_unix_secs(9_800), // 200s old at read time
4109 ));
4110 let name = NormalizedName::for_test("pkg");
4111
4112 // At fetch time, a 150s cooldown window: latest (100s old) is blocked, the fallback
4113 // (200s old) already clears it.
4114 let disposition = cooldown_disposition(
4115 &versions,
4116 &name,
4117 crate::freshness::FreshnessSettings::Enabled {
4118 cooldown: CooldownWindow::from_secs(150),
4119 },
4120 None,
4121 None,
4122 now,
4123 );
4124 assert_matches!(
4125 disposition,
4126 CooldownDisposition::Blocked {
4127 fallback: Some(_),
4128 ..
4129 },
4130 "got: {disposition:?}"
4131 );
4132
4133 // Read time later widens the configured cooldown to 10_000s (e.g. a stricter
4134 // `--cooldown` override) — the SAME stored fallback (still only 200s old) no longer
4135 // clears it and must read as absent, never as the earlier fetch-time answer.
4136 let disposition = cooldown_disposition(
4137 &versions,
4138 &name,
4139 crate::freshness::FreshnessSettings::Enabled {
4140 cooldown: CooldownWindow::from_secs(10_000),
4141 },
4142 None,
4143 None,
4144 now,
4145 );
4146 assert_matches!(
4147 disposition,
4148 CooldownDisposition::Blocked { fallback: None, .. },
4149 "a fallback that no longer clears cooldown at read time must not be surfaced: {disposition:?}"
4150 );
4151 }
4152
4153 /// #919: a plain literal version — `version_range`'s slice equals the declared
4154 /// requirement exactly — must be admitted as editable.
4155 #[test]
4156 fn test_dependency_version_range_is_literal_plain_literal_admitted() {
4157 let content = r#"serde = "1.0.0""#;
4158 let dep = MockDep {
4159 name: PackageName::new("serde"),
4160 version_req: VersionReq::new("1.0.0"),
4161 version_range: Range::new(Position::new(0, 9), Position::new(0, 14)),
4162 name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
4163 };
4164
4165 assert!(dependency_version_range_is_literal(
4166 &dep,
4167 content,
4168 dep.version_range,
4169 ));
4170 }
4171
4172 /// #919: a Maven-style `${property}` interpolation — `version_range` slices to the raw
4173 /// placeholder text while the parser resolves `version_requirement` to the property's
4174 /// value (a different string) — must be rejected, since a completion/edit there would
4175 /// splice text into the interpolation instead of updating a version.
4176 #[test]
4177 fn test_dependency_version_range_is_literal_rejects_property_interpolation() {
4178 let content = r"<version>${slf4j.version}</version>";
4179 let dep = MockDep {
4180 name: PackageName::new("slf4j-api"),
4181 version_req: VersionReq::new("2.0.16"), // resolved property value
4182 version_range: Range::new(Position::new(0, 9), Position::new(0, 25)), // "${slf4j.version}"
4183 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4184 };
4185
4186 assert!(!dependency_version_range_is_literal(
4187 &dep,
4188 content,
4189 dep.version_range,
4190 ));
4191 }
4192
4193 /// #919: a YAML alias-shaped value (`*anchor`, e.g. GitLab CI/GitHub Actions `ref: *pin`
4194 /// job reuse) never textually equals a declared literal requirement — rejected the same
4195 /// way as the property-interpolation case.
4196 #[test]
4197 fn test_dependency_version_range_is_literal_rejects_yaml_alias() {
4198 let content = "ref: *pin";
4199 let dep = MockDep {
4200 name: PackageName::new("job"),
4201 version_req: VersionReq::new("1.0.0"),
4202 version_range: Range::new(Position::new(0, 5), Position::new(0, 9)), // "*pin"
4203 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4204 };
4205
4206 assert!(!dependency_version_range_is_literal(
4207 &dep,
4208 content,
4209 dep.version_range,
4210 ));
4211 }
4212
4213 /// S1 (critic follow-up): an empty `version_requirement` over an equally-empty slice —
4214 /// exactly what an editor's auto-closing quotes produce the instant `serde = "` is typed
4215 /// — must be **admitted**, not rejected. `generate_code_actions`'s "nothing to update"
4216 /// semantics for an empty requirement do not apply to completion, where an empty value is
4217 /// the single most common moment to offer the full version list.
4218 #[test]
4219 fn test_dependency_version_range_is_literal_admits_empty_requirement_with_empty_slice() {
4220 let content = r#"serde = """#;
4221 let dep = MockDep {
4222 name: PackageName::new("serde"),
4223 version_req: VersionReq::new(""),
4224 version_range: Range::new(Position::new(0, 9), Position::new(0, 9)),
4225 name_range: Range::new(Position::new(0, 0), Position::new(0, 5)),
4226 };
4227
4228 assert!(dependency_version_range_is_literal(
4229 &dep,
4230 content,
4231 dep.version_range,
4232 ));
4233 }
4234
4235 /// S1 (critic follow-up): an empty `version_requirement` paired with a *non-empty*
4236 /// non-literal slice must still be rejected — dropping the old `is_empty()` early return
4237 /// must not also drop this case, which the plain text comparison already handles on its
4238 /// own (`"1.0" != ""`).
4239 #[test]
4240 fn test_dependency_version_range_is_literal_rejects_empty_requirement_with_mismatched_slice() {
4241 let content = r#"x = "1.0""#;
4242 let dep = MockDep {
4243 name: PackageName::new("x"),
4244 version_req: VersionReq::new(""),
4245 version_range: Range::new(Position::new(0, 5), Position::new(0, 8)), // "1.0"
4246 name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
4247 };
4248
4249 assert!(!dependency_version_range_is_literal(
4250 &dep,
4251 content,
4252 dep.version_range,
4253 ));
4254 }
4255
4256 /// C1 (critic finding): the headline #919 case — an *unresolved* Maven `${property}`
4257 /// reference. The parser leaves an unresolved property as-is in both `version_range`'s
4258 /// slice and `version_requirement` (there is nothing else to put there), so the two
4259 /// textually agree — `literal_span_matches` alone would wrongly admit this. The
4260 /// reference-shape check must reject it independently of that text comparison.
4261 #[test]
4262 fn test_dependency_version_range_is_literal_rejects_unresolved_maven_property() {
4263 let content = r"<version>${slf4j.version}</version>";
4264 let dep = MockDep {
4265 name: PackageName::new("slf4j-api"),
4266 version_req: VersionReq::new("${slf4j.version}"), // left unresolved by the parser
4267 version_range: Range::new(Position::new(0, 9), Position::new(0, 25)), // "${slf4j.version}"
4268 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4269 };
4270
4271 assert!(!dependency_version_range_is_literal(
4272 &dep,
4273 content,
4274 dep.version_range,
4275 ));
4276 }
4277
4278 /// C1 (critic finding): the Gradle sibling of the unresolved-property case — a `$var`
4279 /// reference `resolve_variable_ref` could not resolve, left as raw text in both the slice
4280 /// and `version_requirement`.
4281 #[test]
4282 fn test_dependency_version_range_is_literal_rejects_unresolved_gradle_variable() {
4283 let content = "implementation 'com.example:lib:$libVersion'";
4284 let dep = MockDep {
4285 name: PackageName::new("com.example:lib"),
4286 version_req: VersionReq::new("$libVersion"), // left unresolved by the parser
4287 version_range: Range::new(Position::new(0, 32), Position::new(0, 43)), // "$libVersion"
4288 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4289 };
4290
4291 assert!(!dependency_version_range_is_literal(
4292 &dep,
4293 content,
4294 dep.version_range,
4295 ));
4296 }
4297
4298 /// C1 (critic finding): a partial interpolation embedded mid-string (`1.0-${suffix}`)
4299 /// does not start with `$`, but must still be rejected — the `contains("${")` arm of the
4300 /// reference-shape check, not just the `starts_with` arms.
4301 #[test]
4302 fn test_dependency_version_range_is_literal_rejects_embedded_interpolation() {
4303 let content = r#"x = "1.0-${suffix}""#;
4304 let dep = MockDep {
4305 name: PackageName::new("x"),
4306 version_req: VersionReq::new("1.0-${suffix}"),
4307 version_range: Range::new(Position::new(0, 5), Position::new(0, 18)), // "1.0-${suffix}"
4308 name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
4309 };
4310
4311 assert!(!dependency_version_range_is_literal(
4312 &dep,
4313 content,
4314 dep.version_range,
4315 ));
4316 }
4317
4318 /// M2 (critic follow-up): `"*"` — the project-wide existence-wildcard spelling
4319 /// (`deps_core::registry::is_existence_wildcard`, synthesized by `deps-npm`,
4320 /// `deps-composer`, ...) — must be **admitted**, not caught by the `*`-prefix arm meant
4321 /// for a `*anchor` YAML alias. Rejecting it would silently disable version completion at
4322 /// the exact moment a user wants to replace `"lodash": "*"` with a pinned version.
4323 #[test]
4324 fn test_dependency_version_range_is_literal_admits_existence_wildcard() {
4325 let content = r#"x = "*""#;
4326 let dep = MockDep {
4327 name: PackageName::new("x"),
4328 version_req: VersionReq::new("*"),
4329 version_range: Range::new(Position::new(0, 5), Position::new(0, 6)), // "*"
4330 name_range: Range::new(Position::new(0, 0), Position::new(0, 1)),
4331 };
4332
4333 assert!(dependency_version_range_is_literal(
4334 &dep,
4335 content,
4336 dep.version_range,
4337 ));
4338 }
4339
4340 /// M3 (critic follow-up): a `*anchor`-shaped slice that is *not exactly* `"*"` — e.g. a
4341 /// multi-char alias name — must still be rejected. Distinguishes the wildcard exemption
4342 /// above from a genuine leading-`*` reference.
4343 #[test]
4344 fn test_dependency_version_range_is_literal_rejects_multi_char_alias_despite_wildcard_exemption()
4345 {
4346 let content = "ref: *pinned-anchor";
4347 let dep = MockDep {
4348 name: PackageName::new("job"),
4349 version_req: VersionReq::new("1.0.0"),
4350 version_range: Range::new(Position::new(0, 5), Position::new(0, 19)), // "*pinned-anchor"
4351 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4352 };
4353
4354 assert!(!dependency_version_range_is_literal(
4355 &dep,
4356 content,
4357 dep.version_range,
4358 ));
4359 }
4360
4361 /// M3 (critic follow-up): a Gradle GString with a `$var` reference embedded mid-string
4362 /// (`1.0.$patch`, no braces, not at the start) is not resolved by
4363 /// `resolve_variable_ref` (whole-value only) — the slice stays byte-identical to the raw
4364 /// `version_requirement`, so only the shape check (not the text comparison) can reject
4365 /// it. This is #919 C1 in a narrower spelling than the whole-value `$var`/`${var}` case.
4366 #[test]
4367 fn test_dependency_version_range_is_literal_rejects_gradle_mid_string_variable() {
4368 let content = r#"implementation "com.example:lib:1.0.$patch""#;
4369 let dep = MockDep {
4370 name: PackageName::new("com.example:lib"),
4371 version_req: VersionReq::new("1.0.$patch"), // left unresolved by the parser
4372 version_range: Range::new(Position::new(0, 32), Position::new(0, 42)), // "1.0.$patch"
4373 name_range: Range::new(Position::new(0, 0), Position::new(0, 0)),
4374 };
4375
4376 assert!(!dependency_version_range_is_literal(
4377 &dep,
4378 content,
4379 dep.version_range,
4380 ));
4381 }
4382
4383 /// #1161: a dependency with no `version_requirement()` at all — Maven's parser never
4384 /// sets one for a genuinely empty `<version></version>` tag, since there is no text to
4385 /// capture — must still be admitted when `version_range`'s slice is empty. There is no
4386 /// existing text at that position that could be misread as a reference/wildcard, so
4387 /// offering completion is always safe regardless of whether a requirement was parsed.
4388 #[test]
4389 fn test_dependency_version_range_is_literal_admits_empty_slice_with_no_requirement_at_all() {
4390 let content = "<version></version>";
4391 let dep = MockSyntheticRangeDep {
4392 name: PackageName::new("com.example:foo"),
4393 };
4394 let empty_range = Range::new(Position::new(0, 9), Position::new(0, 9));
4395
4396 assert!(dep.version_requirement().is_none());
4397 assert!(dependency_version_range_is_literal(
4398 &dep,
4399 content,
4400 empty_range
4401 ));
4402 }
4403
4404 /// Critic follow-up (C1, second round) to #1161: a DANGLING or still-being-typed
4405 /// `version.ref` alias (e.g. `version.ref = "gu"` while typing "guava") has
4406 /// `version_requirement() == None` — the exact same shape as Maven's genuinely empty
4407 /// `<version></version>` tag — but its range is `deps-gradle`'s `Range::default()`
4408 /// sentinel, not a real in-document position. This is the *normal* interactive state on
4409 /// every keystroke while typing an alias, not an edge case: admitting it here would offer
4410 /// the full unfiltered version list and splice a version literal into the alias name.
4411 /// Must be rejected regardless of `version_requirement()` being absent.
4412 #[test]
4413 fn test_dependency_version_range_is_literal_rejects_default_range_with_no_requirement_at_all() {
4414 let content = r#"version.ref = "gu""#;
4415 let dep = MockSyntheticRangeDep {
4416 name: PackageName::new("com.example:guava"),
4417 };
4418
4419 assert!(dep.version_requirement().is_none());
4420 assert!(!dependency_version_range_is_literal(
4421 &dep,
4422 content,
4423 Range::default(),
4424 ));
4425 }
4426
4427 /// Critic follow-up (C1) to #1161: an empty slice must NOT be admitted merely because it
4428 /// is empty — only when `version_requirement()` is also absent. `deps-gradle`'s catalog
4429 /// context deliberately returns `Range::default()` (which slices to `""`) for a
4430 /// `version.ref = "alias"` reference while `version_requirement()` still holds the
4431 /// alias's real, non-empty resolved value (#931) — the "always reject" guarantee that
4432 /// sentinel relies on comes from comparing that non-empty value against the empty slice,
4433 /// not from any special-casing of the empty slice itself. A version that checks
4434 /// `trimmed.is_empty()` before/independent of `version_requirement()` would invert this
4435 /// into an always-accept and let a full completion list splice a version literal into
4436 /// the alias name.
4437 #[test]
4438 fn test_dependency_version_range_is_literal_rejects_default_range_with_nonempty_requirement() {
4439 let content = r#"version.ref = "guavaVersion""#;
4440 let dep = MockDep {
4441 name: PackageName::new("com.example:guava"),
4442 version_req: VersionReq::new("32.0.1"), // the alias's resolved value
4443 version_range: Range::default(), // deps-gradle's deliberate always-reject sentinel
4444 name_range: Range::default(),
4445 };
4446
4447 assert!(!dependency_version_range_is_literal(
4448 &dep,
4449 content,
4450 dep.version_range,
4451 ));
4452 }
4453
4454 /// The empty-entry pruning invariant: an entry is removed once its last set channel
4455 /// is cleared, one channel at a time, in every order — never left behind as a
4456 /// vacuous `Some(DependencyOutcome::default())` that would inflate `len()`.
4457 #[test]
4458 fn test_dependency_outcomes_prunes_entry_once_all_channels_cleared() {
4459 let mut outcomes = DependencyOutcomes::new()
4460 .with_yanked(
4461 crate::NormalizedName::for_test("pkg"),
4462 ("1.0.0".into(), RemovalStatus::Yanked),
4463 )
4464 .with_deprecation(
4465 crate::NormalizedName::for_test("pkg"),
4466 Deprecation {
4467 reason: None,
4468 replacement: None,
4469 },
4470 )
4471 .with_fetch_failure(
4472 crate::NormalizedName::for_test("pkg"),
4473 FetchFailure::Transient,
4474 );
4475 assert_eq!(outcomes.len(), 1);
4476
4477 outcomes.clear_yanked(&crate::NormalizedName::for_test("pkg"));
4478 assert!(
4479 outcomes
4480 .get(&crate::NormalizedName::for_test("pkg"))
4481 .is_some(),
4482 "entry must survive while other channels are still set"
4483 );
4484
4485 outcomes.clear_deprecation(&crate::NormalizedName::for_test("pkg"));
4486 assert!(
4487 outcomes
4488 .get(&crate::NormalizedName::for_test("pkg"))
4489 .is_some(),
4490 "entry must survive while the fetch-failure channel is still set"
4491 );
4492
4493 outcomes.clear_fetch_failure(&crate::NormalizedName::for_test("pkg"));
4494 assert!(
4495 outcomes.is_empty(),
4496 "entry must be pruned once its last channel is cleared, not left as a vacuous Some"
4497 );
4498 assert_eq!(outcomes.len(), 0);
4499 }
4500
4501 /// Clearing a channel that was never set on an existing entry must not spuriously
4502 /// prune channels that ARE still set (each `clear_*` only nulls its own field).
4503 #[test]
4504 fn test_dependency_outcomes_clear_on_unset_channel_is_a_no_op_for_others() {
4505 let mut outcomes = DependencyOutcomes::new().with_yanked(
4506 crate::NormalizedName::for_test("pkg"),
4507 ("1.0.0".into(), RemovalStatus::AdvisoryDeprecated),
4508 );
4509
4510 outcomes.clear_deprecation(&crate::NormalizedName::for_test("pkg"));
4511 outcomes.clear_fetch_failure(&crate::NormalizedName::for_test("pkg"));
4512
4513 assert!(
4514 outcomes
4515 .yanked(&crate::NormalizedName::for_test("pkg"))
4516 .is_some(),
4517 "clearing unset channels must not touch the still-set yanked channel"
4518 );
4519 assert_eq!(outcomes.len(), 1);
4520 }
4521
4522 /// `remove` drops the whole entry regardless of which channels are set, unlike the
4523 /// per-channel `clear_*` methods.
4524 #[test]
4525 fn test_dependency_outcomes_remove_drops_entry_with_multiple_channels_set() {
4526 let mut outcomes = DependencyOutcomes::new()
4527 .with_yanked(
4528 crate::NormalizedName::for_test("pkg"),
4529 ("1.0.0".into(), RemovalStatus::Yanked),
4530 )
4531 .with_fetch_failure(
4532 crate::NormalizedName::for_test("pkg"),
4533 FetchFailure::Transient,
4534 );
4535
4536 outcomes.remove(&crate::NormalizedName::for_test("pkg"));
4537
4538 assert!(
4539 outcomes
4540 .get(&crate::NormalizedName::for_test("pkg"))
4541 .is_none()
4542 );
4543 assert!(outcomes.is_empty());
4544 }
4545
4546 /// `clear_all_fetch_failures` (deps-lsp issue #592) drops the fetch-failure channel for
4547 /// every entry, pruning an entry that becomes empty, while leaving other channels
4548 /// (yanked/deprecation/no-comparable-versions) on a still-mixed entry untouched.
4549 #[test]
4550 fn test_dependency_outcomes_clear_all_fetch_failures() {
4551 let mut outcomes = DependencyOutcomes::new()
4552 .with_fetch_failure(
4553 crate::NormalizedName::for_test("only-failure"),
4554 FetchFailure::Transient,
4555 )
4556 .with_yanked(
4557 crate::NormalizedName::for_test("mixed"),
4558 ("1.0.0".into(), RemovalStatus::Yanked),
4559 )
4560 .with_fetch_failure(
4561 crate::NormalizedName::for_test("mixed"),
4562 FetchFailure::Transient,
4563 );
4564
4565 outcomes.clear_all_fetch_failures();
4566
4567 assert!(
4568 outcomes
4569 .get(&crate::NormalizedName::for_test("only-failure"))
4570 .is_none(),
4571 "an entry whose only channel was fetch-failure must be pruned"
4572 );
4573 assert!(
4574 outcomes
4575 .fetch_failure(&crate::NormalizedName::for_test("mixed"))
4576 .is_none()
4577 );
4578 assert!(
4579 outcomes
4580 .yanked(&crate::NormalizedName::for_test("mixed"))
4581 .is_some(),
4582 "clearing fetch-failure must not touch a mixed entry's other channels"
4583 );
4584 }
4585
4586 /// `clear_all_fetch_failures` on an empty map is a no-op, not a panic.
4587 #[test]
4588 fn test_dependency_outcomes_clear_all_fetch_failures_on_empty_map() {
4589 let mut outcomes = DependencyOutcomes::new();
4590 outcomes.clear_all_fetch_failures();
4591 assert!(outcomes.is_empty());
4592 }
4593
4594 /// `set_fetch_failure_if_absent` (impl-critic M2) must never clobber a genuine
4595 /// `Actionable`/`Transient` failure already recorded for the name — only `set_fetch_failure`
4596 /// unconditionally overwrites.
4597 #[test]
4598 fn test_dependency_outcomes_set_fetch_failure_if_absent_does_not_clobber_existing() {
4599 let mut outcomes = DependencyOutcomes::new().with_fetch_failure(
4600 crate::NormalizedName::for_test("pkg"),
4601 FetchFailure::Actionable("set GITHUB_TOKEN".to_string()),
4602 );
4603
4604 outcomes.set_fetch_failure_if_absent(
4605 crate::NormalizedName::for_test("pkg".to_string()),
4606 FetchFailure::NotAttempted,
4607 );
4608
4609 assert_eq!(
4610 outcomes.fetch_failure(&crate::NormalizedName::for_test("pkg")),
4611 Some(&FetchFailure::Actionable("set GITHUB_TOKEN".to_string())),
4612 "an existing genuine failure must survive a collided-name NotAttempted marker"
4613 );
4614 }
4615
4616 /// The mirror case: when no failure is recorded yet, `set_fetch_failure_if_absent` does
4617 /// populate the entry.
4618 #[test]
4619 fn test_dependency_outcomes_set_fetch_failure_if_absent_populates_when_unset() {
4620 let mut outcomes = DependencyOutcomes::new();
4621
4622 outcomes.set_fetch_failure_if_absent(
4623 crate::NormalizedName::for_test("pkg".to_string()),
4624 FetchFailure::NotAttempted,
4625 );
4626
4627 assert_eq!(
4628 outcomes.fetch_failure(&crate::NormalizedName::for_test("pkg")),
4629 Some(&FetchFailure::NotAttempted)
4630 );
4631 }
4632
4633 #[test]
4634 fn test_line_offset_table_line_start_crlf() {
4635 let table = LineOffsetTable::new("a\r\nbb\r\nc");
4636 assert_eq!(table.line_start(0), Some(0));
4637 assert_eq!(table.line_start(1), Some(3));
4638 assert_eq!(table.line_start(2), Some(7));
4639 assert_eq!(table.line_start(3), None);
4640 }
4641
4642 #[test]
4643 fn test_byte_offset_to_position_clamps_to_char_boundary_instead_of_panicking() {
4644 // "é" is a 2-byte UTF-8 sequence; offset 1 lands inside it.
4645 let content = "é";
4646 let table = LineOffsetTable::new(content);
4647 // Must not panic; clamps down to the nearest boundary (offset 0).
4648 let pos = table.byte_offset_to_position(content, 1);
4649 assert_eq!(pos, Position::new(0, 0));
4650 }
4651
4652 #[test]
4653 fn test_byte_offset_to_position_multi_byte_boundary_in_longer_line() {
4654 let content = "ab é cd";
4655 let table = LineOffsetTable::new(content);
4656 // Byte 3 is 'é's leading byte (boundary); byte 4 is its continuation
4657 // byte (not a boundary) and must clamp back to 3 rather than panic.
4658 assert!(content.is_char_boundary(3));
4659 assert!(!content.is_char_boundary(4));
4660 let pos = table.byte_offset_to_position(content, 4);
4661 assert_eq!(pos, table.byte_offset_to_position(content, 3));
4662 }
4663
4664 /// Covers the ASCII/non-ASCII fast-path split introduced for #742: an ASCII-only line
4665 /// (line 0), a non-ASCII line mixing a BMP accented character with a surrogate-pair
4666 /// emoji (line 1), and a mixed line (line 2) must all still resolve to the same
4667 /// `Position`s as the original `chars().map(char::len_utf16).sum()` scan would produce.
4668 #[test]
4669 fn test_byte_offset_to_position_ascii_and_non_ascii_lines_agree() {
4670 let content = "abcde\nhéllo 😀\nab café end";
4671 let table = LineOffsetTable::new(content);
4672
4673 // Line 0 ("abcde"): ASCII fast path, byte offset == UTF-16 character offset.
4674 assert_eq!(
4675 table.byte_offset_to_position(content, 3),
4676 Position::new(0, 3)
4677 );
4678 assert_eq!(
4679 table.byte_offset_to_position(content, 5),
4680 Position::new(0, 5)
4681 );
4682
4683 // Line 1 ("héllo 😀"): non-ASCII scan path.
4684 // Offset after "h\u{e9}" (1 + 2 bytes into the line): 'h' + 'é' = 2 UTF-16 units.
4685 assert_eq!(
4686 table.byte_offset_to_position(content, 6 + 3),
4687 Position::new(1, 2)
4688 );
4689 // Offset at the end of the line: "héllo 😀" = 8 UTF-16 units (emoji is a surrogate pair).
4690 assert_eq!(
4691 table.byte_offset_to_position(content, 6 + 11),
4692 Position::new(1, 8)
4693 );
4694
4695 // Line 2 ("ab café end"): mixed line, still takes the non-ASCII scan path.
4696 // Offset after "ab café" (8 bytes into the line): 7 UTF-16 units ('é' is 1 BMP unit).
4697 assert_eq!(
4698 table.byte_offset_to_position(content, 18 + 8),
4699 Position::new(2, 7)
4700 );
4701 }
4702
4703 fn reference_position_to_byte_offset(
4704 table: &LineOffsetTable,
4705 content: &str,
4706 position: Position,
4707 ) -> usize {
4708 let Some(line_start) = table.line_start(position.line as usize) else {
4709 return content.len();
4710 };
4711 let line_end = table
4712 .line_start(position.line as usize + 1)
4713 .unwrap_or(content.len());
4714 utf16_to_byte_offset(&content[line_start..line_end], position.character)
4715 .map_or(line_end, |offset| line_start + offset)
4716 .min(content.len())
4717 }
4718
4719 /// #1711: the indexed inverse conversion must match the old per-call line scan for every
4720 /// position, including out-of-range lines/characters and ones splitting a surrogate pair.
4721 #[test]
4722 fn test_position_to_byte_offset_matches_line_scan_reference() {
4723 for content in [
4724 "",
4725 "abc",
4726 "abc\n",
4727 "a\r\nbb\r\nc",
4728 "h\u{e9}llo \u{1f600}\nascii\n\u{65e5}\u{672c}\u{8a9e}x\n",
4729 "\u{1f600}\u{1f600}",
4730 "\n\n\u{e9}",
4731 ] {
4732 let table = LineOffsetTable::new(content);
4733 for line in 0..6 {
4734 for character in 0..24 {
4735 let position = Position::new(line, character);
4736 assert_eq!(
4737 table.position_to_byte_offset(content, position),
4738 reference_position_to_byte_offset(&table, content, position),
4739 "content {content:?} position {position:?}"
4740 );
4741 }
4742 }
4743 }
4744 }
4745
4746 #[test]
4747 fn test_position_to_byte_offset_surrogate_split_rounds_up_and_overshoot_clamps() {
4748 let content = "a\u{1f600}b\nzz";
4749 let table = LineOffsetTable::new(content);
4750 assert_eq!(
4751 table.position_to_byte_offset(content, Position::new(0, 2)),
4752 5
4753 );
4754 assert_eq!(
4755 table.position_to_byte_offset(content, Position::new(0, 4)),
4756 6
4757 );
4758 assert_eq!(
4759 table.position_to_byte_offset(content, Position::new(0, 99)),
4760 7
4761 );
4762 assert_eq!(
4763 table.position_to_byte_offset(content, Position::new(1, 99)),
4764 content.len()
4765 );
4766 assert_eq!(
4767 table.position_to_byte_offset(content, Position::new(9, 0)),
4768 content.len()
4769 );
4770 }
4771
4772 /// #1711: many edits on one long non-ASCII line must round-trip through the cached index.
4773 #[test]
4774 fn test_position_to_byte_offset_long_non_ascii_line_round_trips() {
4775 let content = "\u{e9}\u{1f600}dep = \"1.0.0\", ".repeat(5000);
4776 let table = LineOffsetTable::new(&content);
4777 for (offset, _) in content.char_indices().step_by(7) {
4778 let position = table.byte_offset_to_position(&content, offset);
4779 assert_eq!(table.position_to_byte_offset(&content, position), offset);
4780 }
4781 }
4782
4783 #[test]
4784 fn test_position_to_byte_offset_round_trips_across_mixed_ascii_and_non_ascii_lines() {
4785 let content = "plain = 1\r\nh\u{e9}llo \u{1f600}\nascii again\n\u{65e5}\u{672c}\n\nend";
4786 let table = LineOffsetTable::new(content);
4787 let offsets: Vec<usize> = content
4788 .char_indices()
4789 .map(|(i, _)| i)
4790 .chain([content.len()])
4791 .collect();
4792 for &offset in offsets.iter().rev().chain(offsets.iter()) {
4793 let position = table.byte_offset_to_position(content, offset);
4794 assert_eq!(
4795 table.position_to_byte_offset(content, position),
4796 offset,
4797 "offset {offset}"
4798 );
4799 }
4800 }
4801
4802 /// Regression guard for #742: `byte_offset_to_position` on a large single-line
4803 /// (minified) manifest must stay near-instant. The pre-fix implementation rescanned
4804 /// the line from its start on every call, making repeated lookups over such a line
4805 /// O(n^2) in the line's length (~350ms for 8000 calls on an ~180KB line on the
4806 /// reporter's machine); the ASCII fast path makes each call O(1), so the run time stays
4807 /// proportional to the number of lookups.
4808 #[test]
4809 fn test_byte_offset_to_position_minified_line_stays_fast() {
4810 crate::test_util::scaling::assert_scaling(
4811 "byte_offset_to_position on a minified line",
4812 crate::test_util::scaling::ExpectedGrowth::Linear,
4813 8000,
4814 |deps| {
4815 let mut content = String::from("{\"dependencies\":{");
4816 for i in 0..deps {
4817 content.push_str(&format!("\"dep{i}\":\"1.0.{i}\","));
4818 }
4819 content.push_str("}}");
4820 let table = LineOffsetTable::new(&content);
4821 let step = (content.len() / deps).max(1);
4822 (content, table, step)
4823 },
4824 |(content, table, step)| {
4825 for offset in (0..content.len()).step_by(*step) {
4826 std::hint::black_box(table.byte_offset_to_position(content, offset));
4827 }
4828 },
4829 );
4830 }
4831
4832 /// Regression guard for #882 (widened scope): `byte_offset_to_position`'s non-ASCII branch
4833 /// used to walk `chars().map(len_utf16).sum()` from the line's start on every call, so N
4834 /// lookups on the same wide non-ASCII line cost O(N x line length) — the same shape #882
4835 /// reported for `marker_byte_offset`, and, per the #882 review, ~300x its cost since
4836 /// `make_range` calls this twice per dependency. The shared per-line index makes every
4837 /// lookup after the first on a given line O(1).
4838 #[test]
4839 fn test_byte_offset_to_position_non_ascii_line_cache_stays_fast_on_a_huge_single_line() {
4840 // Lookups scale with the line length, so a per-lookup walk from the line start shows
4841 // up as quadratic growth rather than a constant factor.
4842 crate::test_util::scaling::assert_scaling(
4843 "byte_offset_to_position on a huge non-ASCII line",
4844 crate::test_util::scaling::ExpectedGrowth::Linear,
4845 200 * 1024,
4846 |half_len| {
4847 let filler = "x".repeat(half_len);
4848 let content = format!("{filler}\u{2014}{filler}");
4849 let table = LineOffsetTable::new(&content);
4850 (content, table)
4851 },
4852 |(content, table)| {
4853 for offset in (0..content.len()).step_by(80) {
4854 std::hint::black_box(table.byte_offset_to_position(content, offset));
4855 }
4856 },
4857 );
4858 }
4859
4860 /// Differential test: the cached non-ASCII path must agree with a plain reimplemented
4861 /// `chars().map(len_utf16).sum()` walk for every char-boundary offset on a non-ASCII line,
4862 /// including offsets on more than one non-ASCII line in the same document (cache isolation
4863 /// across lines, sharing the same underlying index `marker_byte_offset` populates).
4864 #[test]
4865 fn test_byte_offset_to_position_non_ascii_cache_matches_char_sum_result_across_lines() {
4866 fn slow_path(content: &str, line_start: usize, offset: usize) -> u32 {
4867 u32::try_from(
4868 content[line_start..offset]
4869 .chars()
4870 .map(char::len_utf16)
4871 .sum::<usize>(),
4872 )
4873 .unwrap_or(u32::MAX)
4874 }
4875
4876 let content = "\u{1f680}rocket \u{2014} dash\nascii line\n\u{3000}ideographic \u{e9}nd";
4877 let table = LineOffsetTable::new(content);
4878 let line_starts = [
4879 table.line_start(0).unwrap(),
4880 table.line_start(1).unwrap(),
4881 table.line_start(2).unwrap(),
4882 ];
4883 let line_ends = [line_starts[1] - 1, line_starts[2] - 1, content.len()];
4884
4885 for (line, (&line_start, &line_end)) in line_starts.iter().zip(&line_ends).enumerate() {
4886 let line_text = &content[line_start..line_end];
4887 for (byte_offset, _) in line_text
4888 .char_indices()
4889 .chain(std::iter::once((line_text.len(), '\0')))
4890 {
4891 let offset = line_start + byte_offset;
4892 assert_eq!(
4893 table.byte_offset_to_position(content, offset).character,
4894 slow_path(content, line_start, offset),
4895 "line {line} byte offset {byte_offset} desynced from the char-sum walk"
4896 );
4897 }
4898 }
4899 }
4900
4901 #[test]
4902 fn test_position_in_range_inside() {
4903 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4904 let position = Position::new(5, 15);
4905 assert!(position_in_range(position, range));
4906 }
4907
4908 #[test]
4909 fn test_position_in_range_at_start() {
4910 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4911 let position = Position::new(5, 10);
4912 assert!(position_in_range(position, range));
4913 }
4914
4915 #[test]
4916 fn test_position_in_range_at_end() {
4917 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4918 let position = Position::new(5, 20);
4919 assert!(position_in_range(position, range));
4920 }
4921
4922 #[test]
4923 fn test_position_in_range_before() {
4924 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4925 let position = Position::new(5, 5);
4926 assert!(!position_in_range(position, range));
4927 }
4928
4929 #[test]
4930 fn test_position_in_range_after() {
4931 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4932 let position = Position::new(5, 25);
4933 assert!(!position_in_range(position, range));
4934 }
4935
4936 #[test]
4937 fn test_position_in_range_different_line_before() {
4938 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4939 let position = Position::new(4, 15);
4940 assert!(!position_in_range(position, range));
4941 }
4942
4943 #[test]
4944 fn test_position_in_range_different_line_after() {
4945 let range = Range::new(Position::new(5, 10), Position::new(5, 20));
4946 let position = Position::new(6, 15);
4947 assert!(!position_in_range(position, range));
4948 }
4949
4950 #[test]
4951 fn test_position_in_range_multiline() {
4952 let range = Range::new(Position::new(5, 10), Position::new(7, 5));
4953 let position = Position::new(6, 0);
4954 assert!(position_in_range(position, range));
4955 }
4956
4957 #[test]
4958 fn test_escape_markdown_link_breakout_payload() {
4959 let payload = "real-pkg](https://legit-looking-typosquat.example/download)[real-pkg";
4960 let escaped = escape_markdown(payload);
4961 assert_eq!(
4962 escaped,
4963 r"real\-pkg\]\(https\:\/\/legit\-looking\-typosquat\.example\/download\)\[real\-pkg"
4964 );
4965 assert!(!escaped.contains("]("));
4966 }
4967
4968 #[test]
4969 fn test_escape_markdown_backslash_and_backtick() {
4970 assert_eq!(escape_markdown(r"a\b`c"), r"a\\b\`c");
4971 }
4972
4973 #[test]
4974 fn test_escape_markdown_autolink_angle_brackets() {
4975 // `<...>` around a bare URL is a CommonMark autolink; `<`/`>` must be escaped
4976 // so it cannot render as a live link independent of the `[]`/`()` escaping.
4977 let escaped = escape_markdown("pkg <https://evil.example>");
4978 assert_eq!(escaped, r"pkg \<https\:\/\/evil\.example\>");
4979 assert!(!escaped.contains('<') || escaped.contains(r"\<"));
4980 }
4981
4982 #[test]
4983 fn test_escape_markdown_control_chars_become_spaces() {
4984 assert_eq!(escape_markdown("a\nb"), "a b");
4985 assert_eq!(escape_markdown("a\r\nb"), "a b");
4986 assert_eq!(escape_markdown("a\tb"), "a b");
4987 assert_eq!(escape_markdown("a\0b"), "a b");
4988 }
4989
4990 #[test]
4991 fn test_escape_markdown_newline_cannot_break_out_of_heading() {
4992 // A raw newline used to terminate the ATX heading line early, letting the
4993 // rest of the name (potentially another "# [...](...)" sequence) render as
4994 // separate, unescaped Markdown blocks.
4995 let escaped = escape_markdown("react\n# [fake](https://evil.example)");
4996 assert!(!escaped.contains('\n'));
4997 }
4998
4999 #[test]
5000 fn test_escape_markdown_hyphenated_name_round_trips_visually() {
5001 // Escaping a hyphen (ASCII punctuation) is visually inert on render — CommonMark
5002 // renders `\-` as a literal `-` — so common package names are unaffected in
5003 // practice even though the raw Markdown source now escapes them.
5004 assert_eq!(escape_markdown("tokio-util"), r"tokio\-util");
5005 }
5006
5007 #[test]
5008 fn test_markdown_code_span_plain_content() {
5009 assert_eq!(markdown_code_span("1.0.0"), "`1.0.0`");
5010 }
5011
5012 #[test]
5013 fn test_markdown_code_span_widens_fence_for_embedded_backticks() {
5014 assert_eq!(markdown_code_span("a`b"), "``a`b``");
5015 assert_eq!(markdown_code_span("``double``"), "``` ``double`` ```");
5016 }
5017
5018 #[test]
5019 fn test_markdown_code_span_pads_when_content_starts_or_ends_with_backtick() {
5020 let span = markdown_code_span("`leading");
5021 assert!(span.starts_with("`` `"));
5022 }
5023
5024 #[test]
5025 fn test_markdown_code_span_replaces_control_chars() {
5026 let span = markdown_code_span("1.0\n[evil](https://evil.example)");
5027 assert!(!span.contains('\n'));
5028 }
5029
5030 #[test]
5031 fn test_markdown_code_span_empty_content() {
5032 assert_eq!(markdown_code_span(""), "` `");
5033 }
5034
5035 #[test]
5036 fn test_markdown_code_span_backtick_payload_cannot_break_span() {
5037 // A payload closing the code span early to splice in a live link must not succeed.
5038 let payload = "1.0` <https://evil.example>` more";
5039 let span = markdown_code_span(payload);
5040 // The fence must be strictly longer than any backtick run in the content, so no
5041 // substring after the opening fence can act as a closing fence before the real one.
5042 let opening_fence_len = span.chars().take_while(|&c| c == '`').count();
5043 let inner = &span[opening_fence_len..span.len() - opening_fence_len];
5044 assert!(
5045 !inner.contains(&"`".repeat(opening_fence_len)),
5046 "content contains a run of backticks as long as the fence: {span}"
5047 );
5048 }
5049
5050 #[test]
5051 fn test_escape_markdown_replaces_bidi_and_invisible_characters() {
5052 for c in [
5053 '\u{202E}', // RLO — the Trojan Source vector
5054 '\u{2066}', // LRI
5055 '\u{200B}', // ZWSP
5056 '\u{2060}', // WORD JOINER
5057 '\u{2028}', // LS
5058 '\u{FEFF}', // BOM
5059 '\u{FFFA}', // interlinear annotation separator
5060 '\u{E0041}', // Unicode tag character ("A")
5061 ] {
5062 let escaped = escape_markdown(&format!("a{c}b"));
5063 assert_eq!(escaped, "a b", "{c:?} must be replaced with a space");
5064 }
5065 }
5066
5067 /// #1323: `sanitize_invisible` already stripped these `Cf` characters while
5068 /// `is_markdown_unsafe`'s hand-picked list let them through.
5069 #[test]
5070 fn test_escape_markdown_replaces_1323_gap_characters() {
5071 for c in [
5072 '\u{00AD}', // SOFT HYPHEN
5073 '\u{180E}', // MONGOLIAN VOWEL SEPARATOR
5074 '\u{2061}', // FUNCTION APPLICATION
5075 '\u{2062}', // INVISIBLE TIMES
5076 '\u{2063}', // INVISIBLE SEPARATOR
5077 '\u{2064}', // INVISIBLE PLUS
5078 '\u{206A}', // INHIBIT SYMMETRIC SWAPPING
5079 '\u{206B}', // ACTIVATE SYMMETRIC SWAPPING
5080 '\u{206C}', // INHIBIT ARABIC FORM SHAPING
5081 '\u{206D}', // ACTIVATE ARABIC FORM SHAPING
5082 '\u{206E}', // NATIONAL DIGIT SHAPES
5083 '\u{206F}', // NOMINAL DIGIT SHAPES
5084 '\u{13430}', // Egyptian Hieroglyph format control (first)
5085 '\u{1343F}', // Egyptian Hieroglyph format control (last)
5086 '\u{1BCA0}', // Shorthand format control (first)
5087 '\u{1BCA3}', // Shorthand format control (last)
5088 '\u{1D173}', // Musical symbol format control (first)
5089 '\u{1D17A}', // Musical symbol format control (last)
5090 ] {
5091 let escaped = escape_markdown(&format!("a{c}b"));
5092 assert_eq!(escaped, "a b", "{c:?} must be replaced with a space");
5093 }
5094 }
5095
5096 /// #1323 M1: U+2065 (unassigned, sitting inside the consolidated U+2060-U+206F range)
5097 /// is now deliberately swept in by the range rather than carved out, so a future
5098 /// Unicode assignment of it can't silently open a hole.
5099 #[test]
5100 fn test_escape_markdown_now_blocks_unassigned_u2065() {
5101 assert_eq!(escape_markdown("a\u{2065}b"), "a b");
5102 }
5103
5104 /// #1323 must not regress #1248: legitimate directional marks and ZWNJ/ZWJ survive.
5105 #[test]
5106 fn test_escape_markdown_still_preserves_legitimate_bidi_marks_after_1323() {
5107 for c in ['\u{200F}', '\u{061C}', '\u{200E}', '\u{200C}', '\u{200D}'] {
5108 let escaped = escape_markdown(&format!("a{c}b"));
5109 assert_eq!(
5110 escaped,
5111 format!("a{c}b"),
5112 "{c:?} must survive verbatim (legitimate RTL/emoji use, #1248)"
5113 );
5114 }
5115 }
5116
5117 /// #1323 M2/critic S2: prefixed-format signs with genuine Arabic/Syriac/Kaithi
5118 /// mid-string use must also survive — they were exempt before #1323 and remain so.
5119 #[test]
5120 fn test_escape_markdown_preserves_prefixed_format_signs() {
5121 for c in [
5122 '\u{0600}',
5123 '\u{0601}',
5124 '\u{0602}',
5125 '\u{0603}',
5126 '\u{0604}',
5127 '\u{0605}',
5128 '\u{06DD}',
5129 '\u{070F}',
5130 '\u{0890}',
5131 '\u{0891}',
5132 '\u{08E2}',
5133 '\u{110BD}',
5134 '\u{110CD}',
5135 ] {
5136 let escaped = escape_markdown(&format!("a{c}b"));
5137 assert_eq!(
5138 escaped,
5139 format!("a{c}b"),
5140 "{c:?} must survive verbatim (legitimate Arabic/Syriac/Kaithi use, #1248)"
5141 );
5142 }
5143 }
5144
5145 /// #1323 critic S3: exhaustive drift guard. Scans the full Unicode code space and
5146 /// asserts that every character `sanitize_invisible` strips but `is_markdown_unsafe`
5147 /// does not is exactly the documented, named exempt set (#1248's RTL/ZWNJ/ZWJ marks
5148 /// plus the prefixed-format signs) — not a superset (an undocumented, silently
5149 /// widened exemption) and not a subset (a stale exempt-set constant hiding a real
5150 /// gap). Fails CI if `unicode-general-category` changes classification for any code
5151 /// point, or if either function's character list is hand-edited without updating the
5152 /// other.
5153 #[test]
5154 fn test_is_markdown_unsafe_exempt_set_matches_sanitize_invisible_drift_guard() {
5155 const EXEMPT_CHARS: &[char] = &[
5156 // #1248: RTL/ZWNJ/ZWJ marks, load-bearing in Persian/Arabic/Indic text shaping
5157 // and emoji ZWJ sequences.
5158 '\u{200E}',
5159 '\u{200F}',
5160 '\u{061C}',
5161 '\u{200C}',
5162 '\u{200D}',
5163 // #1248/critic S2: prefixed-format signs with genuine Arabic/Syriac/Kaithi
5164 // mid-string annotation use.
5165 '\u{0600}',
5166 '\u{0601}',
5167 '\u{0602}',
5168 '\u{0603}',
5169 '\u{0604}',
5170 '\u{0605}',
5171 '\u{06DD}',
5172 '\u{070F}',
5173 '\u{0890}',
5174 '\u{0891}',
5175 '\u{08E2}',
5176 '\u{110BD}',
5177 '\u{110CD}',
5178 ];
5179
5180 let mut undocumented_exemptions = Vec::new();
5181 for cp in 0..=0x0010_FFFFu32 {
5182 let Some(c) = char::from_u32(cp) else {
5183 continue;
5184 };
5185 if crate::redact::is_invisible(c)
5186 && !is_markdown_unsafe(c)
5187 && !EXEMPT_CHARS.contains(&c)
5188 {
5189 undocumented_exemptions.push(c);
5190 }
5191 }
5192 assert!(
5193 undocumented_exemptions.is_empty(),
5194 "is_markdown_unsafe silently exempts characters sanitize_invisible strips, \
5195 outside the documented #1248/#1323 exempt set: {undocumented_exemptions:?}"
5196 );
5197
5198 for &c in EXEMPT_CHARS {
5199 assert!(
5200 crate::redact::is_invisible(c) && !is_markdown_unsafe(c),
5201 "{c:?} is listed in the exempt set but is either not stripped by \
5202 sanitize_invisible or is already blocked by is_markdown_unsafe — the \
5203 exempt-set constant is stale"
5204 );
5205 }
5206 }
5207
5208 /// #1276: `Diagnostic::new`/`RelatedInformation::new` apply `replace_markdown_unsafe_chars`
5209 /// on top of producer-side sanitization that may have already called it —
5210 /// double-application must be a no-op, since `' '` (the substitution) is not itself
5211 /// `is_markdown_unsafe`.
5212 #[test]
5213 fn test_replace_markdown_unsafe_chars_is_idempotent() {
5214 for c in [
5215 '\u{202E}',
5216 '\u{2066}',
5217 '\u{200B}',
5218 '\u{2060}',
5219 '\u{2028}',
5220 '\u{2029}',
5221 '\u{FEFF}',
5222 '\u{FFFA}',
5223 '\u{E0041}',
5224 '\n',
5225 '\t',
5226 ] {
5227 let input = format!("a{c}b");
5228 let once = replace_markdown_unsafe_chars(&input);
5229 assert_eq!(once, "a b", "{c:?} must be replaced with a single space");
5230 let twice = replace_markdown_unsafe_chars(&once);
5231 assert_eq!(twice, once, "{c:?} must not change on re-application");
5232 }
5233 assert!(
5234 !is_markdown_unsafe(' '),
5235 "substituted space must be stable under re-application"
5236 );
5237 }
5238
5239 #[test]
5240 fn test_escape_markdown_preserves_legitimate_bidi_marks() {
5241 for c in [
5242 '\u{200F}', // RLM
5243 '\u{061C}', // ALM
5244 '\u{200E}', // LRM
5245 '\u{200D}', // ZWJ
5246 ] {
5247 let escaped = escape_markdown(&format!("a{c}b"));
5248 assert_eq!(
5249 escaped,
5250 format!("a{c}b"),
5251 "{c:?} must survive verbatim (legitimate RTL/emoji use)"
5252 );
5253 }
5254 }
5255
5256 #[test]
5257 fn test_markdown_code_span_replaces_bidi_and_invisible_characters() {
5258 for c in [
5259 '\u{202E}',
5260 '\u{2066}',
5261 '\u{200B}',
5262 '\u{2060}',
5263 '\u{2029}',
5264 '\u{FEFF}',
5265 '\u{FFFA}',
5266 '\u{E0041}',
5267 ] {
5268 let span = markdown_code_span(&format!("a{c}b"));
5269 assert_eq!(span, "`a b`", "{c:?} must be replaced with a space");
5270 }
5271 }
5272
5273 #[test]
5274 fn test_markdown_code_span_preserves_legitimate_bidi_marks() {
5275 for c in ['\u{200F}', '\u{061C}', '\u{200E}', '\u{200D}'] {
5276 let span = markdown_code_span(&format!("a{c}b"));
5277 assert_eq!(
5278 span,
5279 format!("`a{c}b`"),
5280 "{c:?} must survive verbatim (legitimate RTL/emoji use)"
5281 );
5282 }
5283 }
5284
5285 #[test]
5286 fn test_is_same_major_minor_full_match() {
5287 assert!(is_same_major_minor("1.2.3", "1.2.9"));
5288 }
5289
5290 #[test]
5291 fn test_is_same_major_minor_exact_match() {
5292 assert!(is_same_major_minor("1.2.3", "1.2.3"));
5293 }
5294
5295 #[test]
5296 fn test_is_same_major_minor_major_only_match() {
5297 assert!(is_same_major_minor("1", "1.2.3"));
5298 assert!(is_same_major_minor("1.2.3", "1"));
5299 }
5300
5301 #[test]
5302 fn test_is_same_major_minor_no_match_different_minor() {
5303 assert!(!is_same_major_minor("1.2.3", "1.3.0"));
5304 }
5305
5306 #[test]
5307 fn test_is_same_major_minor_no_match_different_major() {
5308 assert!(!is_same_major_minor("1.2.3", "2.2.3"));
5309 }
5310
5311 #[test]
5312 fn test_is_same_major_minor_empty_strings() {
5313 assert!(!is_same_major_minor("", ""));
5314 assert!(!is_same_major_minor("1.2.3", ""));
5315 assert!(!is_same_major_minor("", "1.2.3"));
5316 }
5317
5318 #[test]
5319 fn test_requirement_contains_template_placeholder_bare_and_braced() {
5320 assert!(requirement_contains_template_placeholder("$REACT_VERSION"));
5321 assert!(requirement_contains_template_placeholder(
5322 "${REACT_VERSION}"
5323 ));
5324 assert!(requirement_contains_template_placeholder("1.0.0-$BUILD"));
5325 assert!(requirement_contains_template_placeholder(
5326 "v${MAJOR}.${MINOR}"
5327 ));
5328 }
5329
5330 #[test]
5331 fn test_requirement_contains_template_placeholder_lowercase_and_mixed_case() {
5332 assert!(requirement_contains_template_placeholder("$react_version"));
5333 assert!(requirement_contains_template_placeholder(
5334 "${React_Version}"
5335 ));
5336 }
5337
5338 #[test]
5339 fn test_requirement_contains_template_placeholder_ordinary_requirements_not_flagged() {
5340 assert!(!requirement_contains_template_placeholder("1.2.3"));
5341 assert!(!requirement_contains_template_placeholder("^1.2.3"));
5342 assert!(!requirement_contains_template_placeholder("~1.2.3"));
5343 assert!(!requirement_contains_template_placeholder(">=1.0.0 <2.0.0"));
5344 assert!(!requirement_contains_template_placeholder(""));
5345 assert!(!requirement_contains_template_placeholder("price-is-$5"));
5346 assert!(!requirement_contains_template_placeholder("trailing-$"));
5347 assert!(!requirement_contains_template_placeholder("empty-${}"));
5348 assert!(!requirement_contains_template_placeholder("${123}"));
5349 }
5350
5351 #[test]
5352 fn test_requirement_contains_template_placeholder_unclosed_brace_fails_safe() {
5353 assert!(requirement_contains_template_placeholder("${VAR"));
5354 }
5355
5356 #[test]
5357 fn test_requirement_contains_template_placeholder_dollar_paren_form() {
5358 assert!(requirement_contains_template_placeholder(
5359 "$(LODASH_VERSION)"
5360 ));
5361 assert!(requirement_contains_template_placeholder(
5362 "require golang.org/x/net $(NET_VERSION)"
5363 ));
5364 }
5365
5366 /// #1417: unlike `${VAR`'s fail-open precedent, `$(` requires the closing `)` — an
5367 /// unclosed `$(VAR` must NOT be classified as a placeholder on that basis alone.
5368 #[test]
5369 fn test_requirement_contains_template_placeholder_dollar_paren_unclosed_not_matched() {
5370 assert!(!requirement_contains_template_placeholder("$(VAR"));
5371 assert!(!requirement_contains_template_placeholder(
5372 "price-is-$(five"
5373 ));
5374 }
5375
5376 #[test]
5377 fn test_requirement_contains_template_placeholder_dollar_paren_no_identifier_not_matched() {
5378 assert!(!requirement_contains_template_placeholder("$()"));
5379 assert!(!requirement_contains_template_placeholder("$(123)"));
5380 assert!(!requirement_contains_template_placeholder(
5381 "$(SERDE VERSION)"
5382 ));
5383 }
5384
5385 /// Spec 070 / issue #1421: `-` is accepted in subsequent positions inside `$(...)`, real
5386 /// MSBuild property-name syntax (`$(MOD-VERSION)`).
5387 #[test]
5388 fn test_requirement_contains_template_placeholder_dollar_paren_hyphen_form() {
5389 assert!(requirement_contains_template_placeholder("$(MOD-VERSION)"));
5390 assert!(requirement_contains_template_placeholder(
5391 "$(SERDE-VERSION)"
5392 ));
5393 assert!(requirement_contains_template_placeholder(
5394 "1.0.0-$(BUILD-SUFFIX)"
5395 ));
5396 assert!(!requirement_contains_template_placeholder("$(-VERSION)"));
5397 }
5398
5399 /// Spec 070 / issue #1421 impl-critic M2: a trailing hyphen, consecutive hyphens, and a
5400 /// leading underscore followed by a hyphen are all still valid subsequent-position
5401 /// characters and must match; a bracketed content consisting of only a hyphen fails the
5402 /// first-character constraint (never a valid leading character) and must NOT match.
5403 #[test]
5404 fn test_requirement_contains_template_placeholder_dollar_paren_hyphen_edge_cases() {
5405 assert!(requirement_contains_template_placeholder("$(VERSION-)"));
5406 assert!(requirement_contains_template_placeholder("$(MOD--VERSION)"));
5407 assert!(requirement_contains_template_placeholder("$(_-X)"));
5408 assert!(!requirement_contains_template_placeholder("$(-)"));
5409 }
5410
5411 /// Spec 070 / issue #1421: `.` anywhere before the closing `)` remains a deliberate,
5412 /// researched exclusion (not valid MSBuild syntax) — never matched, even combined with a
5413 /// hyphen.
5414 #[test]
5415 fn test_requirement_contains_template_placeholder_dollar_paren_dotted_form_not_matched() {
5416 assert!(!requirement_contains_template_placeholder("$(A.VERSION)"));
5417 assert!(!requirement_contains_template_placeholder(
5418 "$(MOD.SUB-VERSION)"
5419 ));
5420 }
5421
5422 /// #1391 fixture/detector drift guard: every entry in
5423 /// [`crate::conformance::GENERIC_TEMPLATE_PLACEHOLDERS`] (the mandatory conformance
5424 /// fixture every ecosystem's `formatter_conformance!` invocation is checked against) must
5425 /// actually be recognized by the shared detector itself — otherwise a fixture entry that
5426 /// silently stopped matching would make every crate's conformance test pass vacuously
5427 /// instead of proving anything about that form.
5428 #[test]
5429 fn test_generic_template_placeholders_fixture_matches_detector() {
5430 for &placeholder in crate::conformance::GENERIC_TEMPLATE_PLACEHOLDERS {
5431 assert!(
5432 requirement_contains_template_placeholder(placeholder),
5433 "{placeholder:?} (from GENERIC_TEMPLATE_PLACEHOLDERS) must be recognized by \
5434 requirement_contains_template_placeholder"
5435 );
5436 }
5437 }
5438
5439 #[test]
5440 fn test_requirement_contains_template_placeholder_mustache_form() {
5441 assert!(requirement_contains_template_placeholder(
5442 "{{ STD_VERSION }}"
5443 ));
5444 assert!(requirement_contains_template_placeholder("{{STD_VERSION}}"));
5445 assert!(requirement_contains_template_placeholder(
5446 "{{ .NetVersion }}"
5447 ));
5448 assert!(requirement_contains_template_placeholder(
5449 "v1.2-{{ BUILD | default }}"
5450 ));
5451 // Unclosed still fails safe, mirroring the `${VAR` precedent.
5452 assert!(requirement_contains_template_placeholder("{{ VAR"));
5453 }
5454
5455 #[test]
5456 fn test_requirement_contains_template_placeholder_mustache_empty_not_flagged() {
5457 assert!(!requirement_contains_template_placeholder("{{}}"));
5458 assert!(!requirement_contains_template_placeholder("{{ }}"));
5459 }
5460
5461 /// Security M1 follow-up (impl-critic M1): `{% ... %}` Jinja2/Liquid statement tags
5462 /// alongside `{{ ... }}` expression tags.
5463 #[test]
5464 fn test_requirement_contains_template_placeholder_jinja_statement_tag() {
5465 assert!(requirement_contains_template_placeholder("{% if x %}"));
5466 assert!(requirement_contains_template_placeholder("{%if x%}"));
5467 assert!(requirement_contains_template_placeholder("{%- if x -%}"));
5468 assert!(requirement_contains_template_placeholder(
5469 "v1.2-{% BUILD %}"
5470 ));
5471 assert!(requirement_contains_template_placeholder("{% VAR"));
5472 assert!(!requirement_contains_template_placeholder("{%}"));
5473 assert!(!requirement_contains_template_placeholder("{% %}"));
5474 }
5475
5476 #[test]
5477 fn test_requirement_contains_template_placeholder_autoconf_form() {
5478 assert!(requirement_contains_template_placeholder(
5479 "@PACKAGE_VERSION@"
5480 ));
5481 assert!(requirement_contains_template_placeholder("v1.2-@BUILD@"));
5482 // No closing '@' — not flagged (unlike the '$'/'{{' forms, both delimiters required).
5483 assert!(!requirement_contains_template_placeholder(
5484 "@PACKAGE_VERSION"
5485 ));
5486 assert!(!requirement_contains_template_placeholder("me@example.com"));
5487 }
5488
5489 /// impl-critic M1: the dotted/hyphenated CMake/Autotools `configure_file` form — the
5490 /// actual common real-world `@..@` shape, unlike the bare-identifier form above.
5491 #[test]
5492 fn test_requirement_contains_template_placeholder_autoconf_dotted_form() {
5493 assert!(requirement_contains_template_placeholder(
5494 "@project.version@"
5495 ));
5496 assert!(requirement_contains_template_placeholder(
5497 "@PACKAGE_VERSION_MAJOR@"
5498 ));
5499 assert!(requirement_contains_template_placeholder("@some-flag@"));
5500 assert!(requirement_contains_template_placeholder(
5501 "v@project.version@"
5502 ));
5503 // No closing '@' — still not flagged, even with dots in the tail.
5504 assert!(!requirement_contains_template_placeholder(
5505 "@project.version"
5506 ));
5507 }
5508
5509 #[test]
5510 fn test_requirement_contains_template_placeholder_percent_form() {
5511 assert!(requirement_contains_template_placeholder("%VERSION%"));
5512 assert!(requirement_contains_template_placeholder("v1.2-%BUILD%"));
5513 assert!(!requirement_contains_template_placeholder("%VERSION"));
5514 assert!(!requirement_contains_template_placeholder("100%"));
5515 }
5516
5517 #[test]
5518 fn test_requirement_contains_template_placeholder_erb_form() {
5519 assert!(requirement_contains_template_placeholder("<%= version %>"));
5520 assert!(requirement_contains_template_placeholder("<%version%>"));
5521 assert!(requirement_contains_template_placeholder("<%- version %>"));
5522 assert!(!requirement_contains_template_placeholder("<%%>"));
5523 assert!(!requirement_contains_template_placeholder("<% %>"));
5524 }
5525
5526 #[test]
5527 fn test_is_safe_version_string_accepts_ordinary_versions() {
5528 assert!(is_safe_version_string("1.2.3"));
5529 assert!(is_safe_version_string("1.2.3-beta.1+build"));
5530 assert!(is_safe_version_string("v1.2.3"));
5531 }
5532
5533 #[test]
5534 fn test_is_safe_version_string_rejects_empty_or_whitespace() {
5535 assert!(!is_safe_version_string(""));
5536 assert!(!is_safe_version_string(" "));
5537 assert!(!is_safe_version_string("\t\n"));
5538 }
5539
5540 #[test]
5541 fn test_is_safe_version_string_rejects_control_and_structural_characters() {
5542 for bad in [
5543 "1.2.3\n",
5544 "1.2.3\t",
5545 "1.2.3\"",
5546 "1.2.3'",
5547 "1.2.3<",
5548 "1.2.3>",
5549 "1.2.3&",
5550 "1.2.3\\",
5551 "1.0.0\", \"malicious\": \"true",
5552 ] {
5553 assert!(
5554 !is_safe_version_string(bad),
5555 "expected {bad:?} to be rejected"
5556 );
5557 }
5558 }
5559
5560 #[test]
5561 fn test_is_safe_version_string_rejects_gradle_interpolation_payload() {
5562 // Regression (critic S2): `$`/`{`/`}` are outside the allowlist, so a Gradle
5563 // `${...}` interpolation payload can never reach a version literal via this gate.
5564 for bad in ["1.0${System.getenv(\"X\")}", "1.0$var", "${evil}"] {
5565 assert!(
5566 !is_safe_version_string(bad),
5567 "expected {bad:?} to be rejected"
5568 );
5569 }
5570 }
5571
5572 #[test]
5573 fn test_is_safe_version_string_rejects_invisible_unicode() {
5574 // Regression (critic M1): `char::is_control()` alone only covers category Cc — the
5575 // bidi override U+202E, zero-width space U+200B, and JS/JSON5 line terminators
5576 // U+2028/U+2029 must also be rejected.
5577 for bad in ["1.2.3\u{202E}", "1.2.3\u{200B}", "1.2.3\u{2028}"] {
5578 assert!(
5579 !is_safe_version_string(bad),
5580 "expected {bad:?} to be rejected"
5581 );
5582 }
5583 }
5584
5585 #[test]
5586 fn test_is_safe_version_string_accepts_pep440_epoch() {
5587 // PEP 440 epochs (`1!2.0`) are legitimate PyPI versions.
5588 assert!(is_safe_version_string("1!2.0"));
5589 }
5590
5591 #[test]
5592 fn test_is_safe_version_string_length_cap() {
5593 assert!(is_safe_version_string(&"1".repeat(64)));
5594 assert!(!is_safe_version_string(&"1".repeat(65)));
5595 }
5596
5597 #[test]
5598 fn test_is_safe_maven_coordinate_segment_accepts_real_ids() {
5599 assert!(is_safe_maven_coordinate_segment("org.apache.commons"));
5600 assert!(is_safe_maven_coordinate_segment("commons-lang3"));
5601 assert!(is_safe_maven_coordinate_segment("jackson-core_2.13"));
5602 }
5603
5604 #[test]
5605 fn test_is_safe_maven_coordinate_segment_rejects_empty() {
5606 assert!(!is_safe_maven_coordinate_segment(""));
5607 }
5608
5609 #[test]
5610 fn test_is_safe_maven_coordinate_segment_rejects_xml_structural_characters() {
5611 for bad in [
5612 "commons</artifactId><parent>",
5613 "commons\"",
5614 "commons'",
5615 "commons&",
5616 "commons\nlang3",
5617 "commons\tlang3",
5618 ] {
5619 assert!(
5620 !is_safe_maven_coordinate_segment(bad),
5621 "expected {bad:?} to be rejected"
5622 );
5623 }
5624 }
5625
5626 #[test]
5627 fn test_is_safe_maven_coordinate_segment_rejects_group_artifact_colon() {
5628 assert!(!is_safe_maven_coordinate_segment(
5629 "org.apache.commons:commons-lang3"
5630 ));
5631 }
5632
5633 #[test]
5634 fn test_is_safe_maven_coordinate_segment_length_cap() {
5635 assert!(is_safe_maven_coordinate_segment(&"a".repeat(128)));
5636 assert!(!is_safe_maven_coordinate_segment(&"a".repeat(129)));
5637 }
5638
5639 #[test]
5640 fn test_is_safe_registry_url_accepts_real_urls() {
5641 assert!(is_safe_registry_url("https://github.com/apple/swift-nio"));
5642 assert!(is_safe_registry_url(
5643 "https://github.com/apple/swift-nio.git"
5644 ));
5645 assert!(is_safe_registry_url("https://github.com/apple/swift%2Dnio"));
5646 }
5647
5648 #[test]
5649 fn test_is_safe_registry_url_rejects_non_https_scheme() {
5650 // Every real Swift package registry response is HTTPS; accepting `http://` would
5651 // only hand a compromised registry a transport-downgrade lever.
5652 assert!(!is_safe_registry_url("http://example.com/repo"));
5653 assert!(!is_safe_registry_url("file:///etc/passwd"));
5654 assert!(!is_safe_registry_url("javascript:alert(1)"));
5655 assert!(!is_safe_registry_url("ftp://example.com/repo"));
5656 assert!(!is_safe_registry_url(""));
5657 }
5658
5659 #[test]
5660 fn test_is_safe_registry_url_rejects_swift_string_literal_breakout() {
5661 for bad in [
5662 "https://evil.example\", .exact(\"1.0.0\")), .package(url: \"https://real",
5663 "https://evil.example\\",
5664 "https://evil.example\nlet x = 1",
5665 "https://evil.example`echo`",
5666 "https://evil.example<script>",
5667 ] {
5668 assert!(
5669 !is_safe_registry_url(bad),
5670 "expected {bad:?} to be rejected"
5671 );
5672 }
5673 }
5674
5675 #[test]
5676 fn test_is_safe_registry_url_length_cap() {
5677 let prefix = "https://example.com/";
5678 let at_cap = format!("{prefix}{}", "a".repeat(2048 - prefix.len()));
5679 assert_eq!(at_cap.len(), 2048);
5680 assert!(is_safe_registry_url(&at_cap));
5681
5682 let over_cap = format!("{at_cap}a");
5683 assert_eq!(over_cap.len(), 2049);
5684 assert!(!is_safe_registry_url(&over_cap));
5685 }
5686
5687 #[test]
5688 fn test_is_safe_package_name_accepts_real_names_across_ecosystems() {
5689 for good in [
5690 "serde", // Cargo
5691 "requests", // PyPI
5692 "@scope/name", // npm/Deno scoped
5693 "monolog/monolog", // Composer vendor/package
5694 "github.com/org/repo", // Go module path
5695 "path", // Dart
5696 "org.apache.commons:commons-lang3", // Gradle group:artifact
5697 "Newtonsoft.Json", // NuGet
5698 "rails", // Bundler
5699 "npm:react", // Deno npm-scheme specifier
5700 "jsr:@std/fs", // Deno jsr-scheme specifier
5701 "github.com/foo/bar~compat", // Go path element with `~`
5702 ] {
5703 assert!(
5704 is_safe_package_name(good),
5705 "expected {good:?} to be accepted"
5706 );
5707 }
5708 }
5709
5710 #[test]
5711 fn test_is_safe_package_name_rejects_empty() {
5712 assert!(!is_safe_package_name(""));
5713 }
5714
5715 #[test]
5716 fn test_is_safe_package_name_rejects_non_ascii() {
5717 // Deliberately excluded: the allowlist is ASCII-only, so a legacy non-ASCII
5718 // npm package name (a handful exist, e.g. Unicode-normalized scopes) is
5719 // rejected rather than risking homograph/normalization tricks in a manifest.
5720 assert!(!is_safe_package_name("café"));
5721 assert!(!is_safe_package_name("пакет"));
5722 }
5723
5724 #[test]
5725 fn test_is_safe_package_name_accepts_dot_dot_shapes() {
5726 // `.`/`/` are individually legal (PyPI dotted names, npm/Composer scopes), so
5727 // `..`/`../..` pass the charset too. This is not a path-traversal risk: every
5728 // sink treats `name` as manifest text (a TOML/JSON/YAML/XML value or a
5729 // string-literal argument), never as a filesystem path.
5730 assert!(is_safe_package_name(".."));
5731 assert!(is_safe_package_name("../.."));
5732 }
5733
5734 #[test]
5735 fn test_is_safe_package_name_rejects_structural_breakout_characters() {
5736 for bad in [
5737 "evil\"\nbackdoor = \"9.9.9",
5738 "evil\", git = \"https://evil",
5739 "evil\\",
5740 "evil'",
5741 "evil<script>",
5742 "evil`echo`",
5743 "evil\ninjected = true",
5744 "evil\tname",
5745 ] {
5746 assert!(
5747 !is_safe_package_name(bad),
5748 "expected {bad:?} to be rejected"
5749 );
5750 }
5751 }
5752
5753 #[test]
5754 fn test_is_safe_package_name_length_cap() {
5755 assert!(is_safe_package_name(&"a".repeat(256)));
5756 assert!(!is_safe_package_name(&"a".repeat(257)));
5757 }
5758
5759 #[test]
5760 fn test_is_safe_feature_name_accepts_real_names() {
5761 for good in ["derive", "std_alloc-v2+extra"] {
5762 assert!(
5763 is_safe_feature_name(good),
5764 "expected {good:?} to be accepted"
5765 );
5766 }
5767 }
5768
5769 #[test]
5770 fn test_is_safe_feature_name_rejects_empty() {
5771 assert!(!is_safe_feature_name(""));
5772 }
5773
5774 #[test]
5775 fn test_is_safe_feature_name_rejects_non_ascii() {
5776 // ASCII-only, so homograph/bidi-spoofing characters are rejected outright.
5777 assert!(!is_safe_feature_name("café"));
5778 // U+202E RIGHT-TO-LEFT OVERRIDE.
5779 assert!(!is_safe_feature_name("evil\u{202E}reversed"));
5780 }
5781
5782 #[test]
5783 fn test_is_safe_feature_name_rejects_enable_syntax() {
5784 // `dep:`/`?`/`/` are enable-syntax, only in a feature's value list, never in its name key.
5785 for bad in ["dep:ravif", "rgb?/serde"] {
5786 assert!(
5787 !is_safe_feature_name(bad),
5788 "expected {bad:?} to be rejected"
5789 );
5790 }
5791 }
5792
5793 #[test]
5794 fn test_is_safe_feature_name_length_cap() {
5795 assert!(is_safe_feature_name(&"a".repeat(256)));
5796 assert!(!is_safe_feature_name(&"a".repeat(257)));
5797 }
5798
5799 #[test]
5800 fn test_is_same_major_minor_partial_versions() {
5801 assert!(is_same_major_minor("1.2", "1.2.3"));
5802 assert!(is_same_major_minor("1.2.3", "1.2"));
5803 }
5804
5805 #[test]
5806 fn test_ecosystem_formatter_defaults() {
5807 let formatter = MOCK_FORMATTER;
5808 assert_eq!(
5809 formatter.normalize_package_name(&pkg("test-pkg")),
5810 crate::NormalizedName::for_test("test-pkg")
5811 );
5812 assert_eq!(formatter.yanked_message(), "This version has been yanked");
5813 assert_eq!(formatter.yanked_label(), "*(yanked)*");
5814 }
5815
5816 #[test]
5817 fn test_format_version_replacing_for_default_delegates_to_format_version_replacing() {
5818 let formatter = MOCK_FORMATTER;
5819 let dep = MockDep {
5820 name: pkg("test-pkg"),
5821 version_req: VersionReq::new("1.0.0"),
5822 version_range: Range::default(),
5823 name_range: Range::default(),
5824 };
5825 assert_eq!(
5826 formatter.format_version_replacing_for(&dep, &ConcreteVersion::new("1.2.3"), "1.0.0"),
5827 formatter.format_version_replacing(&ConcreteVersion::new("1.2.3"), "1.0.0")
5828 );
5829 }
5830
5831 #[test]
5832 fn test_ecosystem_formatter_version_satisfies() {
5833 let formatter = MOCK_FORMATTER;
5834
5835 assert!(formatter.version_satisfies_requirement(
5836 &ConcreteVersion::new("1.2.3"),
5837 &VersionReq::new("1.2.3")
5838 ));
5839
5840 assert!(formatter.version_satisfies_requirement(
5841 &ConcreteVersion::new("1.2.3"),
5842 &VersionReq::new("^1.2")
5843 ));
5844 assert!(formatter.version_satisfies_requirement(
5845 &ConcreteVersion::new("1.2.3"),
5846 &VersionReq::new("~1.2")
5847 ));
5848
5849 assert!(
5850 formatter.version_satisfies_requirement(
5851 &ConcreteVersion::new("1.2.3"),
5852 &VersionReq::new("1")
5853 )
5854 );
5855 assert!(formatter.version_satisfies_requirement(
5856 &ConcreteVersion::new("1.2.3"),
5857 &VersionReq::new("1.2")
5858 ));
5859
5860 assert!(!formatter.version_satisfies_requirement(
5861 &ConcreteVersion::new("1.2.3"),
5862 &VersionReq::new("2.0.0")
5863 ));
5864 assert!(!formatter.version_satisfies_requirement(
5865 &ConcreteVersion::new("1.2.3"),
5866 &VersionReq::new("1.3")
5867 ));
5868 }
5869
5870 #[test]
5871 fn test_ecosystem_formatter_custom_normalize() {
5872 struct PyPIFormatter;
5873
5874 impl PackageNaming for PyPIFormatter {
5875 fn normalized_spelling(&self, name: &PackageName) -> String {
5876 name.as_str().to_lowercase().replace('-', "_")
5877 }
5878 }
5879
5880 impl PackageRendering for PyPIFormatter {
5881 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
5882 format!(
5883 ">={},<{}",
5884 version,
5885 version.as_str().split('.').next().unwrap_or("0")
5886 )
5887 }
5888
5889 fn package_url(&self, name: &PackageName) -> String {
5890 format!("https://pypi.org/project/{}", name.as_str())
5891 }
5892 }
5893
5894 impl RequirementResolution for PyPIFormatter {}
5895
5896 impl DiagnosticMessages for PyPIFormatter {}
5897
5898 impl DiagnosticPolicy for PyPIFormatter {}
5899
5900 impl SourcePolicy for PyPIFormatter {}
5901
5902 impl OsvNaming for PyPIFormatter {}
5903
5904 let formatter = PyPIFormatter;
5905 assert_eq!(
5906 formatter.normalize_package_name(&pkg("Test-Package")),
5907 crate::NormalizedName::for_test("test_package")
5908 );
5909 assert_eq!(
5910 formatter.format_version_for_text_edit(&ConcreteVersion::new("1.2.3")),
5911 ">=1.2.3,<1"
5912 );
5913 assert_eq!(
5914 formatter.package_url(&pkg("requests")),
5915 "https://pypi.org/project/requests"
5916 );
5917 }
5918
5919 // --- upgrade_status_to_verdict structural staleness (issue #1531) ---
5920
5921 /// A [`Dependency`] whose `source()` is configurable, for exercising the
5922 /// `NonRegistrySource` structural-skip staleness gate — [`MockDep`] always reports
5923 /// [`DependencySource::Registry`], which can't represent "started non-registry, source
5924 /// changed to registry".
5925 struct DepWithSource {
5926 name: PackageName,
5927 name_range: crate::position::Range,
5928 source: DependencySource,
5929 }
5930
5931 crate::impl_unprobed_dependency!(DepWithSource);
5932 impl Dependency for DepWithSource {
5933 fn name(&self) -> &PackageName {
5934 &self.name
5935 }
5936 fn name_range(&self) -> crate::position::Range {
5937 self.name_range
5938 }
5939 fn version_requirement(&self) -> Option<&VersionReq> {
5940 None
5941 }
5942 fn version_range(&self) -> Option<crate::position::Range> {
5943 None
5944 }
5945 fn source(&self) -> DependencySource {
5946 self.source.clone()
5947 }
5948 }
5949
5950 fn structural_skip_entry() -> UpgradeStatus {
5951 UpgradeStatus::StructurallyUnchecked(StructuralSkipReason::NonRegistrySource)
5952 }
5953
5954 /// Mirrors `deps-cargo`'s `CargoFormatter::source_is_public_registry_content` override
5955 /// (impl-critic S1, #1531): a verified crates.io mirror (`AlternateRegistry {
5956 /// mirrors_public_registry: true, .. }`, reached via a `[source.crates-io] replace-with` chain)
5957 /// counts as public-registry content alongside plain `Registry`. A local double rather than
5958 /// depending on `deps-cargo` from `deps-core` (wrong dependency direction).
5959 struct MockMirrorFormatter;
5960 impl PackageNaming for MockMirrorFormatter {}
5961 impl PackageRendering for MockMirrorFormatter {
5962 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
5963 version.to_string()
5964 }
5965 fn package_url(&self, name: &PackageName) -> String {
5966 name.as_str().to_string()
5967 }
5968 }
5969 impl RequirementResolution for MockMirrorFormatter {}
5970 impl DiagnosticMessages for MockMirrorFormatter {}
5971 impl DiagnosticPolicy for MockMirrorFormatter {}
5972 impl SourcePolicy for MockMirrorFormatter {
5973 fn source_is_public_registry_content(&self, source: &DependencySource) -> bool {
5974 matches!(
5975 source,
5976 DependencySource::Registry
5977 | DependencySource::AlternateRegistry {
5978 mirrors_public_registry: true,
5979 ..
5980 }
5981 )
5982 }
5983 }
5984 impl OsvNaming for MockMirrorFormatter {}
5985 impl DependencyFormatter for MockMirrorFormatter {
5986 type Dep = DepWithSource;
5987 }
5988
5989 /// #1531 regression: a dependency whose source is *still* non-registry keeps the existing
5990 /// structural-fallback behavior — the cached `NonRegistrySource` skip is not stale, so it
5991 /// resolves to `NotApplicable` for both the "latest" and per-candidate verdicts.
5992 #[test]
5993 fn structural_skip_same_source_stays_not_applicable() {
5994 let dep = DepWithSource {
5995 name: pkg("vendored-lib"),
5996 name_range: crate::position::Range::default(),
5997 source: DependencySource::Path {
5998 path: "../vendored-lib".to_string(),
5999 },
6000 };
6001 let formatter = crate::test_util::StubFormatter::new().for_dependency::<DepWithSource>();
6002
6003 let mut latest_status = LatestStatusMap::new();
6004 latest_status.insert(
6005 crate::test_util::vuln_key("vendored-lib"),
6006 structural_skip_entry(),
6007 );
6008 assert_eq!(
6009 latest_verdict(
6010 Some(&latest_status),
6011 &dep,
6012 None,
6013 &crate::test_util::package_key("vendored-lib"),
6014 "1.0.0",
6015 &formatter
6016 ),
6017 LatestVerdict::NotApplicable
6018 );
6019
6020 let mut candidate_status = CandidateStatusMap::new();
6021 candidate_status.insert(
6022 crate::test_util::vuln_key("vendored-lib"),
6023 CandidateStatuses::Structural(StructuralSkipReason::NonRegistrySource),
6024 );
6025 assert_eq!(
6026 candidate_verdict(
6027 Some(&candidate_status),
6028 &dep,
6029 None,
6030 &crate::test_util::package_key("vendored-lib"),
6031 "1.0.0",
6032 &formatter
6033 ),
6034 LatestVerdict::NotApplicable
6035 );
6036 }
6037
6038 /// #1531: a dependency that *started* with a non-registry source (git/path) picks up a
6039 /// `CandidateUnverified{NonRegistrySource}` structural entry under its plain name key. If
6040 /// the manifest is then edited so the same dependency now resolves to a registry source,
6041 /// that cached entry is stale until the next phase B run overwrites it — the verdict must
6042 /// fail closed to `Unverified` for the new registry version, never silently pass through
6043 /// as `NotApplicable` ("safe to offer").
6044 #[test]
6045 fn structural_skip_source_changed_to_registry_is_not_stale_safe() {
6046 let dep = DepWithSource {
6047 name: pkg("vendored-lib"),
6048 name_range: crate::position::Range::default(),
6049 source: DependencySource::Registry,
6050 };
6051 let formatter = crate::test_util::StubFormatter::new().for_dependency::<DepWithSource>();
6052
6053 let mut latest_status = LatestStatusMap::new();
6054 latest_status.insert(
6055 crate::test_util::vuln_key("vendored-lib"),
6056 structural_skip_entry(),
6057 );
6058 assert_eq!(
6059 latest_verdict(
6060 Some(&latest_status),
6061 &dep,
6062 None,
6063 &crate::test_util::package_key("vendored-lib"),
6064 "2.0.0",
6065 &formatter
6066 ),
6067 LatestVerdict::Unverified
6068 );
6069
6070 let mut candidate_status = CandidateStatusMap::new();
6071 candidate_status.insert(
6072 crate::test_util::vuln_key("vendored-lib"),
6073 CandidateStatuses::Structural(StructuralSkipReason::NonRegistrySource),
6074 );
6075 assert_eq!(
6076 candidate_verdict(
6077 Some(&candidate_status),
6078 &dep,
6079 None,
6080 &crate::test_util::package_key("vendored-lib"),
6081 "2.0.0",
6082 &formatter
6083 ),
6084 LatestVerdict::Unverified
6085 );
6086 }
6087
6088 /// #1531 impl-critic S1: phase B classifies `NonRegistrySource` via
6089 /// `formatter.source_is_public_registry_content`, not a bare `DependencySource::Registry`
6090 /// match — an ecosystem like `deps-cargo` widens that predicate to also accept a verified
6091 /// crates.io mirror (`AlternateRegistry { mirrors_public_registry: true, .. }`). A path dependency
6092 /// edited to such a mirrored registry dependency must be recognized as a source change too,
6093 /// not stay wrongly `NotApplicable` just because it isn't the literal `Registry` variant.
6094 #[test]
6095 fn structural_skip_source_changed_to_mirrored_alternate_registry_is_not_stale_safe() {
6096 let dep = DepWithSource {
6097 name: pkg("vendored-lib"),
6098 name_range: crate::position::Range::default(),
6099 source: DependencySource::AlternateRegistry {
6100 index: "https://crates-mirror.example.com/index".to_string(),
6101 mirrors_public_registry: true,
6102 },
6103 };
6104 let formatter = MockMirrorFormatter;
6105
6106 let mut latest_status = LatestStatusMap::new();
6107 latest_status.insert(
6108 crate::test_util::vuln_key("vendored-lib"),
6109 structural_skip_entry(),
6110 );
6111 assert_eq!(
6112 latest_verdict(
6113 Some(&latest_status),
6114 &dep,
6115 None,
6116 &crate::test_util::package_key("vendored-lib"),
6117 "2.0.0",
6118 &formatter
6119 ),
6120 LatestVerdict::Unverified
6121 );
6122
6123 let mut candidate_status = CandidateStatusMap::new();
6124 candidate_status.insert(
6125 crate::test_util::vuln_key("vendored-lib"),
6126 CandidateStatuses::Structural(StructuralSkipReason::NonRegistrySource),
6127 );
6128 assert_eq!(
6129 candidate_verdict(
6130 Some(&candidate_status),
6131 &dep,
6132 None,
6133 &crate::test_util::package_key("vendored-lib"),
6134 "2.0.0",
6135 &formatter
6136 ),
6137 LatestVerdict::Unverified
6138 );
6139 }
6140
6141 /// #1624 critique M3: `UnmappableName` is structural but — unlike `NonRegistrySource` —
6142 /// [`LatestStatusMap`] still records a real candidate version for it (see
6143 /// `deps_engine::classify::osv::build_latest_check_targets`), so it stays a
6144 /// `CandidateUnverified{version, reason}` entry there while [`CandidateStatusMap`] (which
6145 /// has no single-version slot for the whole dependency) represents the identical skip as
6146 /// `CandidateStatuses::Structural`. Both must resolve to `NotApplicable`.
6147 #[test]
6148 fn unmappable_name_resolves_to_not_applicable_for_latest_and_candidate() {
6149 let dep = DepWithSource {
6150 name: pkg("jsr-pinned"),
6151 name_range: crate::position::Range::default(),
6152 source: DependencySource::Registry,
6153 };
6154 let formatter = crate::test_util::StubFormatter::new().for_dependency::<DepWithSource>();
6155
6156 let mut latest_status = LatestStatusMap::new();
6157 latest_status.insert(
6158 crate::test_util::vuln_key("jsr-pinned"),
6159 UpgradeStatus::CandidateUnverified {
6160 version: ConcreteVersion::new("1.0.0"),
6161 reason: SkipReason::UnmappableName,
6162 },
6163 );
6164 assert_eq!(
6165 latest_verdict(
6166 Some(&latest_status),
6167 &dep,
6168 None,
6169 &crate::test_util::package_key("jsr-pinned"),
6170 "1.0.0",
6171 &formatter
6172 ),
6173 LatestVerdict::NotApplicable
6174 );
6175
6176 let mut candidate_status = CandidateStatusMap::new();
6177 candidate_status.insert(
6178 crate::test_util::vuln_key("jsr-pinned"),
6179 CandidateStatuses::Structural(StructuralSkipReason::UnmappableName),
6180 );
6181 assert_eq!(
6182 candidate_verdict(
6183 Some(&candidate_status),
6184 &dep,
6185 None,
6186 &crate::test_util::package_key("jsr-pinned"),
6187 "1.0.0",
6188 &formatter
6189 ),
6190 LatestVerdict::NotApplicable
6191 );
6192 }
6193
6194 /// Spec 076 SC-014: `fallback_edit_excludes_newer`, one test per [`FallbackEditRejection`]
6195 /// variant plus `Writable`. `deps-core` cannot depend on the ecosystem crates, so this
6196 /// module uses two stub formatters (a semver-backed stub mirroring Cargo's real semantics,
6197 /// and a NuGet-floor stub) — the same probe values are pinned against REAL formatters in
6198 /// `deps-cargo`/`deps-nuget` as part of T005/SC-018.
6199 mod fallback_edit_excludes_newer_tests {
6200 use super::*;
6201 use crate::ParseResult;
6202 use crate::edit::{ManifestEdit, ManifestReparse};
6203 use crate::position::Position;
6204
6205 /// Real-semver-backed matcher, mirroring Cargo's actual resolution semantics.
6206 struct SemverMatcher(semver::VersionReq);
6207 impl RequirementMatcher for SemverMatcher {
6208 fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
6209 semver::Version::parse(version.as_str())
6210 .ok()
6211 .map(|v| self.0.matches(&v))
6212 }
6213 fn strict_prerelease_exclusion(&self) -> bool {
6214 true
6215 }
6216 }
6217
6218 /// SC-014's "semver-backed stub": real `semver::VersionReq` compilation, default
6219 /// `is_bounded_requirement_up_to_date`/`bounded_requirement_already_resolves_to` (Cargo-like).
6220 struct SemverFormatter;
6221 impl PackageNaming for SemverFormatter {}
6222 impl PackageRendering for SemverFormatter {
6223 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6224 version.to_string()
6225 }
6226 fn package_url(&self, name: &PackageName) -> String {
6227 name.as_str().to_string()
6228 }
6229 }
6230 impl RequirementResolution for SemverFormatter {
6231 fn compile_bounded_requirement(
6232 &self,
6233 requirement: BoundedVersionReq<'_>,
6234 ) -> Option<Box<dyn RequirementMatcher>> {
6235 semver::VersionReq::parse(requirement.as_str())
6236 .ok()
6237 .map(|req| Box::new(SemverMatcher(req)) as Box<dyn RequirementMatcher>)
6238 }
6239 }
6240 impl DiagnosticMessages for SemverFormatter {}
6241 impl DiagnosticPolicy for SemverFormatter {}
6242 impl SourcePolicy for SemverFormatter {}
6243 impl OsvNaming for SemverFormatter {}
6244
6245 /// Same as [`SemverFormatter`], but `compile_bounded_requirement` fails for the literal text
6246 /// `"uncompilable"` — isolates the a1 `EditedUncompilable` check from a0, which a
6247 /// formatter that always fails to compile could not do (phase 1 would reject first).
6248 struct SelectivelyUncompilableFormatter;
6249 impl PackageNaming for SelectivelyUncompilableFormatter {}
6250 impl PackageRendering for SelectivelyUncompilableFormatter {
6251 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6252 version.to_string()
6253 }
6254 fn package_url(&self, name: &PackageName) -> String {
6255 name.as_str().to_string()
6256 }
6257 }
6258 impl RequirementResolution for SelectivelyUncompilableFormatter {
6259 fn compile_bounded_requirement(
6260 &self,
6261 requirement: BoundedVersionReq<'_>,
6262 ) -> Option<Box<dyn RequirementMatcher>> {
6263 if requirement.as_str() == "uncompilable" {
6264 return None;
6265 }
6266 semver::VersionReq::parse(requirement.as_str())
6267 .ok()
6268 .map(|req| Box::new(SemverMatcher(req)) as Box<dyn RequirementMatcher>)
6269 }
6270 }
6271 impl DiagnosticMessages for SelectivelyUncompilableFormatter {}
6272 impl DiagnosticPolicy for SelectivelyUncompilableFormatter {}
6273 impl SourcePolicy for SelectivelyUncompilableFormatter {}
6274 impl OsvNaming for SelectivelyUncompilableFormatter {}
6275
6276 /// A formatter with no `compile_bounded_requirement` override at all (trait default `None`) —
6277 /// for the a0 `OriginalUncompilable` check.
6278 struct NoCompileFormatter;
6279 impl PackageNaming for NoCompileFormatter {}
6280 impl PackageRendering for NoCompileFormatter {
6281 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6282 version.to_string()
6283 }
6284 fn package_url(&self, name: &PackageName) -> String {
6285 name.as_str().to_string()
6286 }
6287 }
6288 impl RequirementResolution for NoCompileFormatter {}
6289 impl DiagnosticMessages for NoCompileFormatter {}
6290 impl DiagnosticPolicy for NoCompileFormatter {}
6291 impl SourcePolicy for NoCompileFormatter {}
6292 impl OsvNaming for NoCompileFormatter {}
6293
6294 /// Issue #1580 (CWE-400 defense-in-depth mirroring #1472/#1578): otherwise
6295 /// semver-backed like [`SemverFormatter`] — a real compiling matcher, so the a0-pre/a1-pre
6296 /// gates in `fallback_edit_excludes_newer` are the only thing rejecting an oversized
6297 /// requirement (`compile_bounded_requirement` cannot even receive one).
6298 struct SemverBackedFormatter;
6299 impl PackageNaming for SemverBackedFormatter {}
6300 impl PackageRendering for SemverBackedFormatter {
6301 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6302 version.to_string()
6303 }
6304 fn package_url(&self, name: &PackageName) -> String {
6305 name.as_str().to_string()
6306 }
6307 }
6308 impl RequirementResolution for SemverBackedFormatter {
6309 fn compile_bounded_requirement(
6310 &self,
6311 requirement: BoundedVersionReq<'_>,
6312 ) -> Option<Box<dyn RequirementMatcher>> {
6313 semver::VersionReq::parse(requirement.as_str())
6314 .ok()
6315 .map(|req| Box::new(SemverMatcher(req)) as Box<dyn RequirementMatcher>)
6316 }
6317 }
6318 impl DiagnosticMessages for SemverBackedFormatter {}
6319 impl DiagnosticPolicy for SemverBackedFormatter {}
6320 impl SourcePolicy for SemverBackedFormatter {}
6321 impl OsvNaming for SemverBackedFormatter {}
6322
6323 /// A floor matcher: `matches` is membership at-or-above the floor (mirrors NuGet's
6324 /// bare `Version="X"` shape), but resolution never goes below OR above the floor
6325 /// itself — a floor always resolves to its own lowest member.
6326 struct NugetFloorMatcher(semver::Version);
6327 impl RequirementMatcher for NugetFloorMatcher {
6328 fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
6329 semver::Version::parse(version.as_str())
6330 .ok()
6331 .map(|v| v >= self.0)
6332 }
6333 fn strict_prerelease_exclusion(&self) -> bool {
6334 false
6335 }
6336 }
6337
6338 /// SC-014's "NuGet-floor stub" (spec 076 M2): `is_bounded_requirement_up_to_date` and
6339 /// `bounded_requirement_already_resolves_to` overridden with the floor rule — floor at or
6340 /// above target is up to date; a floor resolves ONLY to itself, never forward.
6341 struct NugetFloorFormatter;
6342 impl PackageNaming for NugetFloorFormatter {}
6343 impl PackageRendering for NugetFloorFormatter {
6344 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6345 version.to_string()
6346 }
6347 fn package_url(&self, name: &PackageName) -> String {
6348 name.as_str().to_string()
6349 }
6350 }
6351 impl RequirementResolution for NugetFloorFormatter {
6352 fn compile_bounded_requirement(
6353 &self,
6354 requirement: BoundedVersionReq<'_>,
6355 ) -> Option<Box<dyn RequirementMatcher>> {
6356 semver::Version::parse(requirement.as_str())
6357 .ok()
6358 .map(|floor| Box::new(NugetFloorMatcher(floor)) as Box<dyn RequirementMatcher>)
6359 }
6360 fn is_bounded_requirement_up_to_date(
6361 &self,
6362 requirement: BoundedVersionReq<'_>,
6363 latest: &ConcreteVersion,
6364 ) -> bool {
6365 semver::Version::parse(requirement.as_str())
6366 .ok()
6367 .zip(semver::Version::parse(latest.as_str()).ok())
6368 .is_some_and(|(floor, latest)| floor >= latest)
6369 }
6370 fn bounded_requirement_already_resolves_to(
6371 &self,
6372 requirement: BoundedVersionReq<'_>,
6373 target: &ConcreteVersion,
6374 ) -> bool {
6375 semver::Version::parse(requirement.as_str())
6376 .ok()
6377 .zip(semver::Version::parse(target.as_str()).ok())
6378 .is_some_and(|(floor, target)| floor == target)
6379 }
6380 }
6381 impl DiagnosticMessages for NugetFloorFormatter {}
6382 impl DiagnosticPolicy for NugetFloorFormatter {}
6383 impl SourcePolicy for NugetFloorFormatter {}
6384 impl OsvNaming for NugetFloorFormatter {}
6385
6386 /// Fix-cycle (#1571) stub matcher for a `!=`-exclusion requirement grammar
6387 /// (PyPI/Composer/Bundler all support one): `requirement` is `"<range>,!=<excluded>"`,
6388 /// `<range>` compiled with real `semver::VersionReq` and `<excluded>` an exact,
6389 /// string-compared exclusion — mirrors the shape enough to prove the guard's floor
6390 /// comparison alone cannot see a hole punched inside an otherwise-matching span.
6391 struct ExclusionMatcher {
6392 range: semver::VersionReq,
6393 excluded: String,
6394 }
6395 impl RequirementMatcher for ExclusionMatcher {
6396 fn matches(&self, version: &ConcreteVersion) -> Option<bool> {
6397 if version.as_str() == self.excluded {
6398 return Some(false);
6399 }
6400 semver::Version::parse(version.as_str())
6401 .ok()
6402 .map(|v| self.range.matches(&v))
6403 }
6404 fn strict_prerelease_exclusion(&self) -> bool {
6405 true
6406 }
6407 // Fix-cycle (#1571 critic S1): the intensional signal a real `!=` matcher
6408 // (PyPI/Composer/Bundler) provides — mirrors this stub's own `excluded` field
6409 // directly, the same way `Pep440Grammar`/`ComposerGrammar`/`RubygemsGrammar` read
6410 // their own parsed `!=` term instead of inferring it from `available`.
6411 fn explicitly_excludes(&self, version: &ConcreteVersion) -> bool {
6412 version.as_str() == self.excluded
6413 }
6414 }
6415
6416 struct ExclusionFormatter;
6417 impl PackageNaming for ExclusionFormatter {}
6418 impl PackageRendering for ExclusionFormatter {
6419 fn format_version_for_text_edit(&self, version: &ConcreteVersion) -> String {
6420 version.to_string()
6421 }
6422 fn package_url(&self, name: &PackageName) -> String {
6423 name.as_str().to_string()
6424 }
6425 }
6426 impl RequirementResolution for ExclusionFormatter {
6427 fn compile_bounded_requirement(
6428 &self,
6429 requirement: BoundedVersionReq<'_>,
6430 ) -> Option<Box<dyn RequirementMatcher>> {
6431 let (range, excluded) = requirement.as_str().split_once(",!=")?;
6432 let range = semver::VersionReq::parse(range).ok()?;
6433 Some(Box::new(ExclusionMatcher {
6434 range,
6435 excluded: excluded.to_string(),
6436 }) as Box<dyn RequirementMatcher>)
6437 }
6438 // Never "already up to date" — isolates the new check from c0, mirroring how
6439 // `SemverFormatter`'s own default already keeps c0/d0 independent for its tests.
6440 fn is_bounded_requirement_up_to_date(
6441 &self,
6442 _requirement: BoundedVersionReq<'_>,
6443 _latest: &ConcreteVersion,
6444 ) -> bool {
6445 false
6446 }
6447 }
6448 impl DiagnosticMessages for ExclusionFormatter {}
6449 impl DiagnosticPolicy for ExclusionFormatter {}
6450 impl SourcePolicy for ExclusionFormatter {}
6451 impl OsvNaming for ExclusionFormatter {}
6452
6453 struct StubDep {
6454 name: PackageName,
6455 requirement: Option<VersionReq>,
6456 version_start: Position,
6457 }
6458 impl Dependency for StubDep {
6459 fn name(&self) -> &PackageName {
6460 &self.name
6461 }
6462 fn name_range(&self) -> Range {
6463 Range::default()
6464 }
6465 fn version_requirement(&self) -> Option<&VersionReq> {
6466 self.requirement.as_ref()
6467 }
6468 fn version_range(&self) -> Option<Range> {
6469 Some(Range::new(self.version_start, self.version_start))
6470 }
6471 fn source(&self) -> crate::parser::DependencySource {
6472 crate::parser::DependencySource::Registry
6473 }
6474 }
6475
6476 struct StubParseResult {
6477 deps: Vec<StubDep>,
6478 uri: url::Url,
6479 }
6480 impl ParseResult for StubParseResult {
6481 fn dependencies(&self) -> Vec<&dyn Dependency> {
6482 self.deps.iter().map(|d| d as &dyn Dependency).collect()
6483 }
6484 fn workspace_root(&self) -> Option<&std::path::Path> {
6485 None
6486 }
6487 fn uri(&self) -> &url::Url {
6488 &self.uri
6489 }
6490 }
6491
6492 fn dep(requirement: &str) -> StubDep {
6493 StubDep {
6494 name: pkg("pkg"),
6495 requirement: Some(VersionReq::new(requirement)),
6496 version_start: Position::new(0, 0),
6497 }
6498 }
6499
6500 /// Matches `dep()`'s own `version_range()` (a zero-width span at `version_start`) so
6501 /// the D5 `CandidateSpanMismatch` precondition passes for every test that isn't
6502 /// specifically exercising it.
6503 fn edit() -> ManifestEdit {
6504 ManifestEdit {
6505 range: Range::new(Position::new(0, 0), Position::new(0, 0)),
6506 new_text: "x".to_string(),
6507 }
6508 }
6509
6510 fn versions(strs: &[&str]) -> Vec<ConcreteVersion> {
6511 strs.iter().map(|s| ConcreteVersion::new(*s)).collect()
6512 }
6513
6514 fn reparsed_to(requirement: &str) -> impl ManifestReparse {
6515 let requirement = requirement.to_string();
6516 move |_content: &str| -> Option<Box<dyn ParseResult>> {
6517 Some(Box::new(StubParseResult {
6518 deps: vec![StubDep {
6519 name: pkg("pkg"),
6520 requirement: Some(VersionReq::new(requirement.as_str())),
6521 version_start: Position::new(0, 0),
6522 }],
6523 uri: crate::test_util::test_uri("/test/manifest.toml"),
6524 }))
6525 }
6526 }
6527
6528 /// Issue #1580: R0 exceeds `MAX_REQUIREMENT_LEN` — the a0-pre gate must reject before
6529 /// `compile_bounded_requirement` is ever called; `SemverBackedFormatter`
6530 /// compiles normally, so only the gate can produce `Rejected`.
6531 #[test]
6532 fn original_oversized_a0_pre() {
6533 let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);
6534 let verdict = fallback_edit_excludes_newer(
6535 &SemverBackedFormatter,
6536 &reparsed_to("1.1.0"),
6537 "content",
6538 &dep(&oversized),
6539 &edit(),
6540 &ConcreteVersion::new("1.1.0"),
6541 &versions(&["1.1.0"]),
6542 );
6543 assert_eq!(
6544 verdict,
6545 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalOversized)
6546 );
6547 }
6548
6549 #[test]
6550 fn original_uncompilable_a0() {
6551 let verdict = fallback_edit_excludes_newer(
6552 &NoCompileFormatter,
6553 &reparsed_to("1.1.0"),
6554 "content",
6555 &dep("^1.0"),
6556 &edit(),
6557 &ConcreteVersion::new("1.1.0"),
6558 &versions(&["1.1.0"]),
6559 );
6560 assert_eq!(
6561 verdict,
6562 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalUncompilable)
6563 );
6564 }
6565
6566 #[test]
6567 fn original_already_up_to_date_c0() {
6568 // NuGet-shaped floor `2.0.0`; a fallback below the floor is already "up to date".
6569 let verdict = fallback_edit_excludes_newer(
6570 &NugetFloorFormatter,
6571 &reparsed_to("1.9.0"),
6572 "content",
6573 &dep("2.0.0"),
6574 &edit(),
6575 &ConcreteVersion::new("1.9.0"),
6576 &versions(&["1.9.0"]),
6577 );
6578 assert_eq!(
6579 verdict,
6580 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalAlreadyUpToDate)
6581 );
6582 }
6583
6584 #[test]
6585 fn original_resolves_past_fallback_d0() {
6586 // Absent-path downgrade: unedited `^2.0` already resolves to 2.0.0, strictly newer
6587 // than the 1.9.0 fallback.
6588 let verdict = fallback_edit_excludes_newer(
6589 &SemverFormatter,
6590 &reparsed_to("1.9.0"),
6591 "content",
6592 &dep("^2.0"),
6593 &edit(),
6594 &ConcreteVersion::new("1.9.0"),
6595 &versions(&["2.0.0", "1.9.0"]),
6596 );
6597 assert_eq!(
6598 verdict,
6599 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalResolvesPastFallback)
6600 );
6601 }
6602
6603 #[test]
6604 fn original_excludes_fallback_via_not_equal() {
6605 // R0 ">=1.0.0,<2.0.0,!=1.5.0" (PyPI/Composer/Bundler `!=` shape): 1.5.0 sits inside
6606 // the nominal `[1.0.0,2.0.0)` span but is punched out by the exclusion, while 1.6.0
6607 // still matches and is strictly newer — the floor comparison alone (d0) would pass
6608 // this (the floor, 1.0.0, is not newer than 1.5.0), so only the #1571 check catches
6609 // it.
6610 let verdict = fallback_edit_excludes_newer(
6611 &ExclusionFormatter,
6612 &reparsed_to("1.5.0"),
6613 "content",
6614 &dep(">=1.0.0,<2.0.0,!=1.5.0"),
6615 &edit(),
6616 &ConcreteVersion::new("1.5.0"),
6617 &versions(&["1.6.0", "1.5.0", "1.0.0"]),
6618 );
6619 assert_eq!(
6620 verdict,
6621 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalExcludesFallback)
6622 );
6623 }
6624
6625 #[test]
6626 fn original_excludes_fallback_via_not_equal_is_caught_even_when_vacuous() {
6627 // Critic fix-cycle S1: NO listed `available` entry strictly newer than `fallback`
6628 // matches R0 here (2.0.0 fails the `<2.0.0` ceiling too), so the purely structural
6629 // "some newer entry still matches" heuristic alone is vacuous — it cannot tell this
6630 // apart from `>=1.0.0,<1.5.0` (a legitimate ceiling) over the identical `available`
6631 // list. Only `RequirementMatcher::explicitly_excludes` catches it.
6632 let verdict = fallback_edit_excludes_newer(
6633 &ExclusionFormatter,
6634 &reparsed_to("1.5.0"),
6635 "content",
6636 &dep(">=1.0.0,<2.0.0,!=1.5.0"),
6637 &edit(),
6638 &ConcreteVersion::new("1.5.0"),
6639 &versions(&["2.0.0", "1.5.0", "1.0.0"]),
6640 );
6641 assert_eq!(
6642 verdict,
6643 FallbackEditVerdict::Rejected(FallbackEditRejection::OriginalExcludesFallback)
6644 );
6645 }
6646
6647 #[test]
6648 fn ceiling_exceeding_fallback_is_not_excluded_via_not_equal_check() {
6649 // Cargo-shaped out-of-range acceptance (FR-025): `^1.0` fails `matches` for a
6650 // fallback of 2.5.0 too, but no R0-matching entry is newer than it — the #1571
6651 // check must not fire here, or it would reject spec 076's intentional
6652 // ceiling-exceeding case.
6653 let verdict = fallback_edit_excludes_newer(
6654 &SemverFormatter,
6655 &reparsed_to("^2.5.0"),
6656 "content",
6657 &dep("^1.0"),
6658 &edit(),
6659 &ConcreteVersion::new("2.5.0"),
6660 &versions(&["3.0.0", "2.5.0", "1.0.0"]),
6661 );
6662 assert_eq!(verdict, FallbackEditVerdict::Writable);
6663 }
6664
6665 #[test]
6666 fn reparse_failed() {
6667 // R0 "1.0" is a caret [1.0.0,2.0.0) — fallback 1.5.0 sits at its own floor (the
6668 // only listed entry, matching), so phase 1 passes and re-parse is actually reached.
6669 let reparse = |_content: &str| -> Option<Box<dyn ParseResult>> { None };
6670 let verdict = fallback_edit_excludes_newer(
6671 &SemverFormatter,
6672 &reparse,
6673 "content",
6674 &dep("1.0"),
6675 &edit(),
6676 &ConcreteVersion::new("1.5.0"),
6677 &versions(&["1.5.0"]),
6678 );
6679 assert_eq!(
6680 verdict,
6681 FallbackEditVerdict::Rejected(FallbackEditRejection::ReparseFailed)
6682 );
6683 }
6684
6685 #[test]
6686 fn occurrence_not_unique() {
6687 let reparse = |_content: &str| -> Option<Box<dyn ParseResult>> {
6688 Some(Box::new(StubParseResult {
6689 deps: vec![
6690 StubDep {
6691 name: pkg("pkg"),
6692 requirement: Some(VersionReq::new("1.5.0")),
6693 version_start: Position::new(0, 0),
6694 },
6695 StubDep {
6696 name: pkg("pkg"),
6697 requirement: Some(VersionReq::new("1.5.0")),
6698 version_start: Position::new(0, 0),
6699 },
6700 ],
6701 uri: crate::test_util::test_uri("/test/manifest.toml"),
6702 }) as Box<dyn ParseResult>)
6703 };
6704 let verdict = fallback_edit_excludes_newer(
6705 &SemverFormatter,
6706 &reparse,
6707 "content",
6708 &dep("1.0"),
6709 &edit(),
6710 &ConcreteVersion::new("1.5.0"),
6711 &versions(&["1.5.0"]),
6712 );
6713 assert_eq!(
6714 verdict,
6715 FallbackEditVerdict::Rejected(FallbackEditRejection::OccurrenceNotUnique)
6716 );
6717 }
6718
6719 /// Issue #1580: R1 (the re-parsed EDITED requirement) exceeds `MAX_REQUIREMENT_LEN` —
6720 /// R0 ("1.0") is small and compiles fine, so phase 1 passes and phase 2 is reached; the
6721 /// a1-pre gate must then reject before `compile_bounded_requirement(R1)` is ever called.
6722 #[test]
6723 fn edited_oversized_a1_pre() {
6724 let oversized = "1".repeat(MAX_REQUIREMENT_LEN + 1);
6725 let verdict = fallback_edit_excludes_newer(
6726 &SemverBackedFormatter,
6727 &reparsed_to(&oversized),
6728 "content",
6729 &dep("1.0"),
6730 &edit(),
6731 &ConcreteVersion::new("1.5.0"),
6732 &versions(&["1.5.0"]),
6733 );
6734 assert_eq!(
6735 verdict,
6736 FallbackEditVerdict::Rejected(FallbackEditRejection::EditedOversized)
6737 );
6738 }
6739
6740 #[test]
6741 fn edited_uncompilable_a1() {
6742 let verdict = fallback_edit_excludes_newer(
6743 &SelectivelyUncompilableFormatter,
6744 &reparsed_to("uncompilable"),
6745 "content",
6746 &dep("1.0"),
6747 &edit(),
6748 &ConcreteVersion::new("1.5.0"),
6749 &versions(&["1.5.0"]),
6750 );
6751 assert_eq!(
6752 verdict,
6753 FallbackEditVerdict::Rejected(FallbackEditRejection::EditedUncompilable)
6754 );
6755 }
6756
6757 #[test]
6758 fn edited_excludes_fallback_b1() {
6759 // The re-parse stub yields an unsatisfiable-for-the-fallback `^5` — round-1 critic
6760 // M5: the written edit must actually express the fallback, not merely compile.
6761 let verdict = fallback_edit_excludes_newer(
6762 &SemverFormatter,
6763 &reparsed_to("^5"),
6764 "content",
6765 &dep("1.0"),
6766 &edit(),
6767 &ConcreteVersion::new("1.5.0"),
6768 &versions(&["1.5.0"]),
6769 );
6770 assert_eq!(
6771 verdict,
6772 FallbackEditVerdict::Rejected(FallbackEditRejection::EditedExcludesFallback)
6773 );
6774 }
6775
6776 #[test]
6777 fn edited_admits_newer_d1() {
6778 // R0 "2.0.0" is a caret [2.0.0,3.0.0), whose floor (2.0.1, the only listed match
6779 // at or above the fallback's own position) is at the fallback — phase 1 passes.
6780 // The re-parsed edit "2.0.1" is ALSO a caret ([2.0.1,3.0.0)), which still admits
6781 // the fresh 2.1.0 — d1 must reject that auto-follow regardless of d0's own verdict.
6782 let verdict = fallback_edit_excludes_newer(
6783 &SemverFormatter,
6784 &reparsed_to("2.0.1"),
6785 "content",
6786 &dep("2.0.0"),
6787 &edit(),
6788 &ConcreteVersion::new("2.0.1"),
6789 &versions(&["2.1.0", "2.0.1"]),
6790 );
6791 assert_eq!(
6792 verdict,
6793 FallbackEditVerdict::Rejected(FallbackEditRejection::EditedAdmitsNewer)
6794 );
6795 }
6796
6797 #[test]
6798 fn writable() {
6799 let verdict = fallback_edit_excludes_newer(
6800 &SemverFormatter,
6801 &reparsed_to("^2.5.0"),
6802 "content",
6803 &dep("2.0"),
6804 &edit(),
6805 &ConcreteVersion::new("2.5.0"),
6806 &versions(&["3.0.0", "2.5.0"]),
6807 );
6808 assert_eq!(verdict, FallbackEditVerdict::Writable);
6809 }
6810
6811 /// Spec 076 M2: the d0 `resolves_to` loosening for a NuGet `Located` floor. Spec 075
6812 /// rejected this (raw `matches` sees the floor as admitting the fresh version); this
6813 /// guard writes it, since a floor resolves only to its own lowest member.
6814 #[test]
6815 fn nuget_located_floor_loosening_is_writable() {
6816 // The floor's own value ("1.0.0") must be listed for the fix-cycle floor-comparison
6817 // scan to find it — realistic for production `available` (every published version,
6818 // unfiltered), since the floor is the user's own already-published declared pin.
6819 let verdict = fallback_edit_excludes_newer(
6820 &NugetFloorFormatter,
6821 &reparsed_to("1.1.0"),
6822 "content",
6823 &dep("1.0.0"),
6824 &edit(),
6825 &ConcreteVersion::new("1.1.0"),
6826 &versions(&["1.2.0", "1.1.0", "1.0.0"]),
6827 );
6828 assert_eq!(verdict, FallbackEditVerdict::Writable);
6829 }
6830
6831 /// Fix-cycle (impl-critic M2, D5 precondition): a `candidate` whose range does not
6832 /// equal this occurrence's own `version_range()` (e.g. an edit built for a different
6833 /// line) must be rejected before any check reads it — not silently treated as
6834 /// `Writable` just because R0/R1 happen to agree (a NuGet-floor R0 that already equals
6835 /// its own fallback resolves to `Writable` under every other check here).
6836 #[test]
6837 fn candidate_span_mismatch_is_rejected() {
6838 let mismatched_candidate = ManifestEdit {
6839 range: Range::new(Position::new(1, 0), Position::new(1, 0)),
6840 new_text: "1.1.0".to_string(),
6841 };
6842 let verdict = fallback_edit_excludes_newer(
6843 &NugetFloorFormatter,
6844 &reparsed_to("1.1.0"),
6845 "content",
6846 &dep("1.0.0"),
6847 &mismatched_candidate,
6848 &ConcreteVersion::new("1.1.0"),
6849 &versions(&["1.2.0", "1.1.0"]),
6850 );
6851 assert_eq!(
6852 verdict,
6853 FallbackEditVerdict::Rejected(FallbackEditRejection::CandidateSpanMismatch)
6854 );
6855 }
6856 }
6857}