Skip to main content

uv_resolver/
prioritized_distribution.rs

1use std::fmt::{Display, Formatter};
2
3use arcstr::ArcStr;
4use owo_colors::OwoColorize;
5use tracing::debug;
6
7use uv_distribution_filename::{BuildTag, WheelFilename};
8use uv_distribution_types::{
9    File, IndexUrl, InstalledDist, MinimumLibcVersion, Name, RegistryBuiltDist, RegistryBuiltWheel,
10    RegistrySourceDist, RequiresPython, SupportedVariantProperties, VariantScore,
11    VariantsJsonContent, VariantsJsonFilename, VerbatimFile,
12};
13use uv_normalize::PackageName;
14use uv_pep440::{Version, VersionSpecifier, VersionSpecifiers};
15use uv_pep508::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValueString};
16use uv_platform_tags::{
17    AbiTag, BinaryFormat, IncompatibleTag, LanguageTag, PlatformTag, TagPriority, Tags,
18};
19use uv_pypi_types::{HashDigest, Yanked};
20
21use crate::known_platform::KnownPlatform;
22use crate::resolved::ResolvedDistRef;
23
24/// A collection of distributions that have been filtered by relevance.
25#[derive(Debug, Default, Clone)]
26pub struct PrioritizedDist(Box<PrioritizedDistInner>);
27
28/// The preference for a compatible wheel variant, with higher scores preferred.
29#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
30pub(crate) struct WheelVariantScore<'a> {
31    hash: HashComparison,
32    score: VariantScore,
33    tag_priority: Option<TagPriority>,
34    build_tag: Option<&'a BuildTag>,
35}
36
37/// Variant metadata for a package version on an index.
38#[derive(Debug, Clone, PartialEq, Eq, Hash)]
39pub(crate) struct RegistryVariantsJson {
40    pub(crate) filename: VariantsJsonFilename,
41    pub(crate) file: VerbatimFile,
42    pub(crate) index: IndexUrl,
43}
44
45/// The contents of a [`PrioritizedDist`], boxed to keep the outer type small.
46#[derive(Debug, Clone)]
47struct PrioritizedDistInner {
48    /// The highest-priority source distribution. Between compatible source distributions this priority is arbitrary.
49    source: Option<(RegistrySourceDist, SourceDistCompatibility)>,
50    /// The highest-priority wheel index. When present, it is
51    /// guaranteed to be a valid index into `wheels`.
52    best_wheel_index: Option<usize>,
53    /// The set of all wheels associated with this distribution.
54    wheels: Vec<(RegistryBuiltWheel, WheelCompatibility)>,
55    /// Variant metadata files from the indexes contributing files for this version.
56    variants_json: Vec<RegistryVariantsJson>,
57    /// The hashes for each distribution.
58    hashes: Vec<HashDigest>,
59    /// Python coverage, unioned over compatible wheels independently of their platforms.
60    python_markers: MarkerTree,
61    /// Coverage for the glibc and musl baselines, unioned over compatible wheels separately.
62    /// Unconfigured baselines use ordinary platform coverage. Intersect only after unioning, so
63    /// separate glibc and musl wheels can jointly satisfy both baselines.
64    markers: [MarkerTree; 2],
65}
66
67impl Default for PrioritizedDistInner {
68    fn default() -> Self {
69        Self {
70            source: None,
71            best_wheel_index: None,
72            wheels: Vec::new(),
73            variants_json: Vec::new(),
74            hashes: Vec::new(),
75            python_markers: MarkerTree::FALSE,
76            markers: [MarkerTree::FALSE; 2],
77        }
78    }
79}
80
81/// A distribution that can be used for both resolution and installation.
82#[derive(Debug, Copy, Clone)]
83pub(crate) enum CompatibleDist<'a> {
84    /// The distribution is already installed and can be used.
85    InstalledDist(&'a InstalledDist),
86    /// The distribution should be resolved and installed using a source distribution.
87    SourceDist {
88        /// The source distribution that should be used.
89        sdist: &'a RegistrySourceDist,
90        /// The prioritized distribution that the sdist came from.
91        prioritized: &'a PrioritizedDist,
92    },
93    /// The distribution should be resolved and installed using a wheel distribution.
94    CompatibleWheel {
95        /// The wheel that should be used.
96        wheel: &'a RegistryBuiltWheel,
97        /// The prioritized distribution that the wheel came from.
98        prioritized: &'a PrioritizedDist,
99    },
100    /// The distribution should be resolved using an incompatible wheel distribution, but
101    /// installed using a source distribution.
102    IncompatibleWheel {
103        /// The sdist to be used during installation.
104        sdist: &'a RegistrySourceDist,
105        /// The wheel to be used during resolution.
106        wheel: &'a RegistryBuiltWheel,
107        /// The prioritized distribution that the wheel and sdist came from.
108        prioritized: &'a PrioritizedDist,
109    },
110}
111
112impl Name for CompatibleDist<'_> {
113    fn name(&self) -> &PackageName {
114        match self {
115            Self::InstalledDist(dist) => dist.name(),
116            Self::SourceDist {
117                sdist,
118                prioritized: _,
119            } => sdist.name(),
120            Self::CompatibleWheel {
121                wheel,
122                prioritized: _,
123            } => wheel.name(),
124            Self::IncompatibleWheel {
125                sdist,
126                wheel: _,
127                prioritized: _,
128            } => sdist.name(),
129        }
130    }
131}
132
133impl<'a> CompatibleDist<'a> {
134    /// Return whether a usable source distribution or a wheel matching [`RequiresPython`] exists.
135    ///
136    /// Wheel compatibility must be checked against the current Python range when a resolver fork
137    /// narrows the range used to construct the [`PrioritizedDist`].
138    pub(crate) fn matches_python_requirement(&self, requires_python: &RequiresPython) -> bool {
139        self.prioritized().is_none_or(|prioritized| {
140            !prioritized
141                .0
142                .python_markers
143                .is_disjoint(requires_python.to_marker_tree())
144        })
145    }
146
147    /// Return the `requires-python` specifier for the distribution, if any.
148    pub(crate) fn requires_python(&self) -> Option<&VersionSpecifiers> {
149        match self {
150            Self::InstalledDist(_) => None,
151            Self::SourceDist { sdist, .. } => sdist.file.requires_python.as_deref(),
152            Self::CompatibleWheel { wheel, .. } => wheel.file.requires_python.as_deref(),
153            Self::IncompatibleWheel { sdist, .. } => sdist.file.requires_python.as_deref(),
154        }
155    }
156
157    // For installable distributions, return the prioritized distribution it was derived from.
158    pub(crate) fn prioritized(&self) -> Option<&'a PrioritizedDist> {
159        match self {
160            Self::InstalledDist(_) => None,
161            Self::SourceDist { prioritized, .. }
162            | Self::CompatibleWheel { prioritized, .. }
163            | Self::IncompatibleWheel { prioritized, .. } => Some(prioritized),
164        }
165    }
166
167    /// Return the set of supported platforms for the distribution, in terms of their markers.
168    pub(crate) fn implied_markers(&self) -> MarkerTree {
169        match self.prioritized() {
170            Some(prioritized) => {
171                let [glibc, musl] = prioritized.0.markers;
172                glibc.and(musl)
173            }
174            None => MarkerTree::TRUE,
175        }
176    }
177}
178
179#[derive(Debug, PartialEq, Eq, Clone)]
180pub enum IncompatibleDist {
181    /// An incompatible wheel is available.
182    Wheel(IncompatibleWheel),
183    /// An incompatible source distribution is available.
184    Source(IncompatibleSource),
185    /// No distributions are available
186    Unavailable,
187}
188
189impl IncompatibleDist {
190    pub(crate) fn singular_message(&self) -> String {
191        match self {
192            Self::Wheel(incompatibility) => match incompatibility {
193                IncompatibleWheel::NoBinary => format!("has {self}"),
194                IncompatibleWheel::Tag(_) => format!("has {self}"),
195                IncompatibleWheel::Yanked(_) => format!("was {self}"),
196                IncompatibleWheel::ExcludeNewer(ts) => match ts {
197                    Some(_) => format!("was {self}"),
198                    None => format!("has {self}"),
199                },
200                IncompatibleWheel::RequiresPython(..) => format!("requires {self}"),
201                IncompatibleWheel::MissingPlatform(_) => format!("has {self}"),
202            },
203            Self::Source(incompatibility) => match incompatibility {
204                IncompatibleSource::NoBuild => format!("has {self}"),
205                IncompatibleSource::Yanked(_) => format!("was {self}"),
206                IncompatibleSource::ExcludeNewer(ts) => match ts {
207                    Some(_) => format!("was {self}"),
208                    None => format!("has {self}"),
209                },
210                IncompatibleSource::RequiresPython(..) => {
211                    format!("requires {self}")
212                }
213                IncompatibleSource::NotPep625Filename => format!("has {self}"),
214            },
215            Self::Unavailable => format!("has {self}"),
216        }
217    }
218
219    pub(crate) fn plural_message(&self) -> String {
220        match self {
221            Self::Wheel(incompatibility) => match incompatibility {
222                IncompatibleWheel::NoBinary => format!("have {self}"),
223                IncompatibleWheel::Tag(_) => format!("have {self}"),
224                IncompatibleWheel::Yanked(_) => format!("were {self}"),
225                IncompatibleWheel::ExcludeNewer(ts) => match ts {
226                    Some(_) => format!("were {self}"),
227                    None => format!("have {self}"),
228                },
229                IncompatibleWheel::RequiresPython(..) => format!("require {self}"),
230                IncompatibleWheel::MissingPlatform(_) => format!("have {self}"),
231            },
232            Self::Source(incompatibility) => match incompatibility {
233                IncompatibleSource::NoBuild => format!("have {self}"),
234                IncompatibleSource::Yanked(_) => format!("were {self}"),
235                IncompatibleSource::ExcludeNewer(ts) => match ts {
236                    Some(_) => format!("were {self}"),
237                    None => format!("have {self}"),
238                },
239                IncompatibleSource::RequiresPython(..) => {
240                    format!("require {self}")
241                }
242                IncompatibleSource::NotPep625Filename => format!("have {self}"),
243            },
244            Self::Unavailable => format!("have {self}"),
245        }
246    }
247
248    pub(crate) fn context_message(
249        &self,
250        tags: Option<&Tags>,
251        requires_python: Option<AbiTag>,
252    ) -> Option<String> {
253        match self {
254            Self::Wheel(incompatibility) => match incompatibility {
255                IncompatibleWheel::Tag(IncompatibleTag::Python) => {
256                    let tag = tags?.python_tag().as_ref().map(ToString::to_string)?;
257                    Some(format!("(e.g., `{tag}`)", tag = tag.cyan()))
258                }
259                IncompatibleWheel::Tag(IncompatibleTag::Abi) => {
260                    let tag = tags?.abi_tag().as_ref().map(ToString::to_string)?;
261                    Some(format!("(e.g., `{tag}`)", tag = tag.cyan()))
262                }
263                IncompatibleWheel::Tag(IncompatibleTag::FreethreadedAbi) => None,
264                IncompatibleWheel::Tag(IncompatibleTag::AbiPythonVersion) => {
265                    let tag = requires_python?;
266                    Some(format!("(e.g., `{tag}`)", tag = tag.cyan()))
267                }
268                IncompatibleWheel::Tag(IncompatibleTag::Platform) => {
269                    let tag = tags?.platform_tag().map(ToString::to_string)?;
270                    Some(format!("(e.g., `{tag}`)", tag = tag.cyan()))
271                }
272                IncompatibleWheel::Tag(IncompatibleTag::Invalid) => None,
273                IncompatibleWheel::Tag(IncompatibleTag::Variant) => None,
274                IncompatibleWheel::NoBinary => None,
275                IncompatibleWheel::Yanked(..) => None,
276                IncompatibleWheel::ExcludeNewer(..) => None,
277                IncompatibleWheel::RequiresPython(..) => None,
278                IncompatibleWheel::MissingPlatform(..) => None,
279            },
280            Self::Source(..) => None,
281            Self::Unavailable => None,
282        }
283    }
284}
285
286impl Display for IncompatibleDist {
287    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
288        match self {
289            Self::Wheel(incompatibility) => match incompatibility {
290                IncompatibleWheel::NoBinary => f.write_str("no source distribution"),
291                IncompatibleWheel::Tag(tag) => match tag {
292                    IncompatibleTag::Variant => f.write_str("only unsupported wheel variants"),
293                    IncompatibleTag::Invalid => f.write_str("no wheels with valid tags"),
294                    IncompatibleTag::Python => {
295                        f.write_str("no wheels with a matching Python implementation tag")
296                    }
297                    IncompatibleTag::Abi => f.write_str("no wheels with a matching Python ABI tag"),
298                    IncompatibleTag::FreethreadedAbi => {
299                        f.write_str("no wheels with a free-threading compatible ABI tag")
300                    }
301                    IncompatibleTag::AbiPythonVersion => {
302                        f.write_str("no wheels with a matching Python version tag")
303                    }
304                    IncompatibleTag::Platform => {
305                        f.write_str("no wheels with a matching platform tag")
306                    }
307                },
308                IncompatibleWheel::Yanked(yanked) => match yanked {
309                    Yanked::Bool(_) => f.write_str("yanked"),
310                    Yanked::Reason(reason) => write!(
311                        f,
312                        "yanked (reason: {})",
313                        reason.trim().trim_end_matches('.')
314                    ),
315                },
316                IncompatibleWheel::ExcludeNewer(ts) => match ts {
317                    Some(_) => f.write_str("published after the exclude newer time"),
318                    None => f.write_str("no publish time"),
319                },
320                IncompatibleWheel::RequiresPython(python, _) => {
321                    write!(f, "Python {python}")
322                }
323                IncompatibleWheel::MissingPlatform(marker) => {
324                    if let Some(platform) = KnownPlatform::from_marker(*marker) {
325                        write!(f, "no {platform}-compatible wheels")
326                    } else if let Some(marker) = marker.try_to_string() {
327                        write!(f, "no `{marker}`-compatible wheels")
328                    } else {
329                        write!(f, "no compatible wheels")
330                    }
331                }
332            },
333            Self::Source(incompatibility) => match incompatibility {
334                IncompatibleSource::NoBuild => f.write_str("no usable wheels"),
335                IncompatibleSource::Yanked(yanked) => match yanked {
336                    Yanked::Bool(_) => f.write_str("yanked"),
337                    Yanked::Reason(reason) => write!(
338                        f,
339                        "yanked (reason: {})",
340                        reason.trim().trim_end_matches('.')
341                    ),
342                },
343                IncompatibleSource::ExcludeNewer(ts) => match ts {
344                    Some(_) => f.write_str("published after the exclude newer time"),
345                    None => f.write_str("no publish time"),
346                },
347                IncompatibleSource::RequiresPython(python, _) => {
348                    write!(f, "Python {python}")
349                }
350                IncompatibleSource::NotPep625Filename => {
351                    f.write_str("a non-PEP 625-compliant source distribution filename")
352                }
353            },
354            Self::Unavailable => f.write_str("no available distributions"),
355        }
356    }
357}
358
359#[derive(Debug, PartialEq, Eq, Copy, Clone)]
360pub enum PythonRequirementKind {
361    /// The installed version of Python.
362    Installed,
363    /// The target version of Python; that is, the version of Python for which we are resolving
364    /// dependencies. This is typically the same as the installed version, but may be different
365    /// when specifying an alternate Python version for the resolution.
366    Target,
367}
368
369#[derive(Debug, Clone, PartialEq, Eq)]
370pub(crate) enum WheelCompatibility {
371    Incompatible(IncompatibleWheel),
372    /// The wheel matches the platform tags, but its variant properties have not been checked.
373    Variant(HashComparison, Option<TagPriority>, Option<BuildTag>),
374    Compatible(HashComparison, Option<TagPriority>, Option<BuildTag>),
375}
376
377#[derive(Debug, PartialEq, Eq, Clone)]
378pub enum IncompatibleWheel {
379    /// The wheel was published after the exclude newer time.
380    ExcludeNewer(Option<i64>),
381    /// The wheel tags do not match those of the target Python platform.
382    Tag(IncompatibleTag),
383    /// The required Python version is not a superset of the target Python version range.
384    RequiresPython(VersionSpecifiers, PythonRequirementKind),
385    /// The wheel was yanked.
386    Yanked(Yanked),
387    /// The use of binary wheels is disabled.
388    NoBinary,
389    /// Wheels are not available for the current platform.
390    MissingPlatform(MarkerTree),
391}
392
393#[derive(Debug, Clone, PartialEq, Eq)]
394pub enum SourceDistCompatibility {
395    Incompatible(IncompatibleSource),
396    Compatible(HashComparison),
397}
398
399#[derive(Debug, PartialEq, Eq, Clone)]
400pub enum IncompatibleSource {
401    ExcludeNewer(Option<i64>),
402    RequiresPython(VersionSpecifiers, PythonRequirementKind),
403    Yanked(Yanked),
404    NoBuild,
405    /// The source distribution's filename does not confirm to PEP 625.
406    NotPep625Filename,
407}
408
409#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
410pub enum HashComparison {
411    /// The hash is present, but does not match the expected value.
412    Mismatched,
413    /// The hash is missing.
414    Missing,
415    /// The hash matches the expected value.
416    Matched,
417}
418
419impl PrioritizedDist {
420    pub(crate) fn insert_variants_json(&mut self, variants_json: RegistryVariantsJson) {
421        // A flat index can list the same metadata link more than once.
422        if !self.0.variants_json.contains(&variants_json) {
423            self.0.variants_json.push(variants_json);
424        }
425    }
426
427    pub(crate) fn variants_json(&self) -> &[RegistryVariantsJson] {
428        &self.0.variants_json
429    }
430
431    /// Return the `variants.json` files we need to check the candidate wheels.
432    ///
433    /// Match on the index as well as the release: a flat index can include wheels from
434    /// several sources, and each source describes only its own variants.
435    pub(crate) fn variants_json_for_selection(
436        &self,
437    ) -> impl Iterator<Item = &RegistryVariantsJson> {
438        self.0.variants_json.iter().filter(|metadata| {
439            self.0.wheels.iter().any(|(wheel, compatibility)| {
440                wheel.index == metadata.index
441                    && matches!(compatibility, WheelCompatibility::Variant(..))
442            })
443        })
444    }
445
446    /// Score each compatible variant from the index that supplied its wheel.
447    pub(crate) fn scored_variants(
448        &self,
449        metadata: &[(&IndexUrl, &VariantsJsonContent, SupportedVariantProperties)],
450    ) -> impl Iterator<Item = (WheelVariantScore<'_>, usize)> {
451        // Prefer wheels whose advertised hash matches a required hash, followed by wheels with
452        // no advertised hash, then mismatches. If no hashes are required, all wheels match.
453        // The installer verifies required hashes against the downloaded wheel.
454        // Break ties by variant rank, platform tags, then build tag.
455        self.0
456            .wheels
457            .iter()
458            .enumerate()
459            .filter_map(move |(index, (wheel, compatibility))| {
460                let WheelCompatibility::Variant(hash, priority, build_tag) = compatibility else {
461                    return None;
462                };
463                let label = wheel.filename.variant()?;
464                let score = metadata
465                    .iter()
466                    .filter(|(source, _, _)| *source == &wheel.index)
467                    .filter_map(|(_, metadata, supported)| metadata.score_variant(label, supported))
468                    .max()?;
469                let score = WheelVariantScore {
470                    hash: *hash,
471                    score,
472                    tag_priority: *priority,
473                    build_tag: build_tag.as_ref(),
474                };
475                Some((score, index))
476            })
477    }
478
479    /// Select a scored variant if its hash ranks at least as high as the ordinary wheel's.
480    pub(crate) fn select_variant(&self, index: usize) -> Option<Self> {
481        let (_, WheelCompatibility::Variant(hash, priority, build_tag)) =
482            self.0.wheels.get(index)?
483        else {
484            return None;
485        };
486        if let Some((_, WheelCompatibility::Compatible(ordinary_hash, ..))) = self.best_wheel()
487            && ordinary_hash > hash
488        {
489            return None;
490        }
491        let mut selected = self.clone();
492        selected.0.wheels[index].1 =
493            WheelCompatibility::Compatible(*hash, *priority, build_tag.clone());
494        selected.0.best_wheel_index = Some(index);
495        Some(selected)
496    }
497
498    /// Insert the given built distribution into the [`PrioritizedDist`].
499    pub(crate) fn insert_built(
500        &mut self,
501        dist: RegistryBuiltWheel,
502        hashes: impl IntoIterator<Item = HashDigest>,
503        compatibility: WheelCompatibility,
504        minimum_libc_version: Option<MinimumLibcVersion>,
505    ) {
506        if compatibility.is_compatible()
507            && (!self.0.python_markers.is_true()
508                || !self.0.markers.iter().all(|markers| markers.is_true()))
509        {
510            let python = implied_python_markers(&dist.filename);
511            self.0.python_markers = self.0.python_markers.or(python);
512            for (coverage, markers) in self.0.markers.iter_mut().zip(implied_libc_markers(
513                &dist.filename,
514                python,
515                minimum_libc_version,
516            )) {
517                *coverage = coverage.or(markers);
518            }
519        }
520        // Track the hashes.
521        if !compatibility.is_excluded() {
522            self.0.hashes.extend(hashes);
523        }
524        // Before checking variant properties, prefer ordinary wheels as metadata sources even
525        // when they cannot be installed (e.g., with `--no-binary`).
526        if let Some((existing_wheel, existing_compatibility)) = self.best_wheel() {
527            let is_more_compatible =
528                match (dist.filename.variant(), existing_wheel.filename.variant()) {
529                    (None, Some(_)) => true,
530                    (Some(_), None) => false,
531                    (None, None) | (Some(_), Some(_)) => {
532                        compatibility.is_more_compatible(existing_compatibility)
533                    }
534                };
535            if is_more_compatible {
536                self.0.best_wheel_index = Some(self.0.wheels.len());
537            }
538        } else {
539            self.0.best_wheel_index = Some(self.0.wheels.len());
540        }
541        self.0.wheels.push((dist, compatibility));
542    }
543
544    /// Insert the given source distribution into the [`PrioritizedDist`].
545    pub fn insert_source(
546        &mut self,
547        dist: RegistrySourceDist,
548        hashes: impl IntoIterator<Item = HashDigest>,
549        compatibility: SourceDistCompatibility,
550    ) {
551        // A usable source distribution provides coverage for all environments.
552        if compatibility.is_compatible() {
553            self.0.python_markers = MarkerTree::TRUE;
554            self.0.markers = [MarkerTree::TRUE; 2];
555        }
556        // Track the hashes.
557        if !compatibility.is_excluded() {
558            self.0.hashes.extend(hashes);
559        }
560        // Track the highest-priority source.
561        if let Some((.., existing_compatibility)) = &self.0.source {
562            if compatibility.is_more_compatible(existing_compatibility) {
563                self.0.source = Some((dist, compatibility));
564            }
565        } else {
566            self.0.source = Some((dist, compatibility));
567        }
568    }
569
570    /// Return the highest-priority distribution for the package version, if any.
571    pub(crate) fn get(&self) -> Option<CompatibleDist<'_>> {
572        let best_wheel = self.0.best_wheel_index.map(|i| &self.0.wheels[i]);
573        match (&best_wheel, &self.0.source) {
574            // If both are compatible, break ties based on the hash outcome. For example, prefer a
575            // source distribution with a matching hash over a wheel with a mismatched hash. When
576            // the outcomes are equivalent (e.g., both have a matching hash), prefer the wheel.
577            (
578                Some((wheel, WheelCompatibility::Compatible(wheel_hash, ..))),
579                Some((sdist, SourceDistCompatibility::Compatible(sdist_hash))),
580            ) => {
581                if sdist_hash > wheel_hash {
582                    Some(CompatibleDist::SourceDist {
583                        sdist,
584                        prioritized: self,
585                    })
586                } else {
587                    Some(CompatibleDist::CompatibleWheel {
588                        wheel,
589                        prioritized: self,
590                    })
591                }
592            }
593            // Prefer the highest-priority, platform-compatible wheel.
594            (Some((wheel, WheelCompatibility::Compatible(..))), _) => {
595                Some(CompatibleDist::CompatibleWheel {
596                    wheel,
597                    prioritized: self,
598                })
599            }
600            // If we have a compatible source distribution and an incompatible wheel, return the
601            // wheel. We assume that all distributions have the same metadata for a given package
602            // version. If a compatible source distribution exists, we assume we can build it, but
603            // using the wheel is faster.
604            //
605            // (If the incompatible wheel should actually be ignored entirely, fall through to
606            // using the source distribution. Variant wheels need their properties checked before
607            // they can provide metadata.)
608            (
609                Some((wheel, compatibility @ WheelCompatibility::Incompatible(_))),
610                Some((sdist, SourceDistCompatibility::Compatible(_))),
611            ) if !compatibility.is_excluded() && wheel.filename.variant().is_none() => {
612                Some(CompatibleDist::IncompatibleWheel {
613                    sdist,
614                    wheel,
615                    prioritized: self,
616                })
617            }
618            // Otherwise, if we have a source distribution, return it.
619            (.., Some((sdist, SourceDistCompatibility::Compatible(_)))) => {
620                Some(CompatibleDist::SourceDist {
621                    sdist,
622                    prioritized: self,
623                })
624            }
625            _ => None,
626        }
627    }
628
629    /// Return the incompatibility for the best source distribution, if any.
630    pub(crate) fn incompatible_source(&self) -> Option<&IncompatibleSource> {
631        self.0
632            .source
633            .as_ref()
634            .and_then(|(_, compatibility)| match compatibility {
635                SourceDistCompatibility::Compatible(_) => None,
636                SourceDistCompatibility::Incompatible(incompatibility) => Some(incompatibility),
637            })
638    }
639
640    /// Return the incompatibility for the best wheel, if any.
641    pub(crate) fn incompatible_wheel(&self) -> Option<&IncompatibleWheel> {
642        self.0
643            .best_wheel_index
644            .map(|i| &self.0.wheels[i])
645            .and_then(|(_, compatibility)| match compatibility {
646                WheelCompatibility::Compatible(_, _, _) => None,
647                WheelCompatibility::Incompatible(incompatibility) => Some(incompatibility),
648                WheelCompatibility::Variant(..) => {
649                    Some(&IncompatibleWheel::Tag(IncompatibleTag::Variant))
650                }
651            })
652    }
653
654    /// Return the hashes for each distribution.
655    pub(crate) fn hashes(&self) -> &[HashDigest] {
656        &self.0.hashes
657    }
658
659    /// Returns true if and only if this distribution does not contain any
660    /// source distributions or wheels.
661    pub(crate) fn is_empty(&self) -> bool {
662        self.0.source.is_none() && self.0.wheels.is_empty()
663    }
664
665    /// If this prioritized dist has at least one wheel, then this creates
666    /// a built distribution with the best wheel in this prioritized dist.
667    pub(crate) fn built_dist(&self) -> Option<RegistryBuiltDist> {
668        let best_wheel_index = self.0.best_wheel_index?;
669
670        // Remove any excluded wheels from the list of wheels, and adjust the wheel index to be
671        // relative to the filtered list.
672        let mut adjusted_wheels = Vec::with_capacity(self.0.wheels.len());
673        let mut adjusted_best_index = 0;
674        for (i, (wheel, compatibility)) in self.0.wheels.iter().enumerate() {
675            if compatibility.is_excluded() {
676                continue;
677            }
678            if i == best_wheel_index {
679                adjusted_best_index = adjusted_wheels.len();
680            }
681            adjusted_wheels.push(wheel.clone());
682        }
683
684        let sdist = self
685            .0
686            .source
687            .as_ref()
688            .filter(|(_, compatibility)| !compatibility.is_excluded())
689            .map(|(sdist, _)| sdist.clone());
690        Some(RegistryBuiltDist {
691            wheels: adjusted_wheels,
692            best_wheel_index: adjusted_best_index,
693            sdist,
694        })
695    }
696
697    /// If this prioritized dist has an sdist, then this creates a source
698    /// distribution.
699    pub(crate) fn source_dist(&self) -> Option<RegistrySourceDist> {
700        let mut sdist = self
701            .0
702            .source
703            .as_ref()
704            .filter(|(_, compatibility)| !compatibility.is_excluded())
705            .map(|(sdist, _)| sdist.clone())?;
706        assert!(
707            sdist.wheels.is_empty(),
708            "source distribution should not have any wheels yet"
709        );
710        sdist.wheels = self
711            .0
712            .wheels
713            .iter()
714            .filter(|(_, compatibility)| !compatibility.is_excluded())
715            .map(|(wheel, _)| wheel.clone())
716            .collect();
717        Some(sdist)
718    }
719
720    /// Returns the "best" wheel in this prioritized distribution, if one
721    /// exists.
722    pub(crate) fn best_wheel(&self) -> Option<&(RegistryBuiltWheel, WheelCompatibility)> {
723        self.0.best_wheel_index.map(|i| &self.0.wheels[i])
724    }
725
726    /// Returns an iterator of all wheels and the source distribution, if any.
727    pub(crate) fn files(&self) -> impl Iterator<Item = &File> {
728        self.0
729            .wheels
730            .iter()
731            .map(|(wheel, _)| wheel.file.as_ref())
732            .chain(
733                self.0
734                    .source
735                    .as_ref()
736                    .map(|(source_dist, _)| source_dist.file.as_ref()),
737            )
738    }
739
740    /// Returns an iterator over all Python tags for the distribution.
741    pub(crate) fn python_tags(&self) -> impl Iterator<Item = LanguageTag> + '_ {
742        self.0
743            .wheels
744            .iter()
745            .flat_map(|(wheel, _)| wheel.filename.python_tags().iter().copied())
746    }
747
748    /// Returns an iterator over all ABI tags for the distribution.
749    pub(crate) fn abi_tags(&self) -> impl Iterator<Item = AbiTag> + '_ {
750        self.0
751            .wheels
752            .iter()
753            .flat_map(|(wheel, _)| wheel.filename.abi_tags().iter().copied())
754    }
755
756    /// Returns the set of platform tags for the distribution that are ABI-compatible with the given
757    /// tags.
758    pub(crate) fn platform_tags<'a>(
759        &'a self,
760        tags: &'a Tags,
761    ) -> impl Iterator<Item = &'a PlatformTag> + 'a {
762        self.0.wheels.iter().flat_map(move |(wheel, _)| {
763            if wheel.filename.python_tags().iter().any(|wheel_py| {
764                wheel
765                    .filename
766                    .abi_tags()
767                    .iter()
768                    .any(|wheel_abi| tags.is_compatible_abi(*wheel_py, *wheel_abi))
769            }) {
770                wheel.filename.platform_tags().iter()
771            } else {
772                [].iter()
773            }
774        })
775    }
776}
777
778impl<'a> CompatibleDist<'a> {
779    /// Return the [`ResolvedDistRef`] to use during resolution.
780    pub(crate) fn for_resolution(&self) -> ResolvedDistRef<'a> {
781        match self {
782            Self::InstalledDist(dist) => ResolvedDistRef::Installed { dist },
783            Self::SourceDist { sdist, prioritized } => {
784                ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized }
785            }
786            Self::CompatibleWheel {
787                wheel, prioritized, ..
788            } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized },
789            Self::IncompatibleWheel {
790                wheel, prioritized, ..
791            } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized },
792        }
793    }
794
795    /// Return the [`ResolvedDistRef`] to use during installation.
796    pub(crate) fn for_installation(&self) -> ResolvedDistRef<'a> {
797        match self {
798            Self::InstalledDist(dist) => ResolvedDistRef::Installed { dist },
799            Self::SourceDist { sdist, prioritized } => {
800                ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized }
801            }
802            Self::CompatibleWheel {
803                wheel, prioritized, ..
804            } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized },
805            Self::IncompatibleWheel {
806                sdist, prioritized, ..
807            } => ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized },
808        }
809    }
810
811    /// Returns a [`RegistryBuiltWheel`] if the distribution includes a compatible or incompatible
812    /// wheel.
813    pub(crate) fn wheel(&self) -> Option<&RegistryBuiltWheel> {
814        match self {
815            Self::InstalledDist(_) => None,
816            Self::SourceDist { .. } => None,
817            Self::CompatibleWheel { wheel, .. } => Some(wheel),
818            Self::IncompatibleWheel { wheel, .. } => Some(wheel),
819        }
820    }
821}
822
823impl WheelCompatibility {
824    /// Record platform compatibility, deferring the property check for a variant wheel.
825    pub(crate) fn from_tag_priority(
826        filename: &WheelFilename,
827        hash: HashComparison,
828        priority: Option<TagPriority>,
829    ) -> Self {
830        let build_tag = filename.build_tag().cloned();
831        if filename.variant().is_some() {
832            Self::Variant(hash, priority, build_tag)
833        } else {
834            Self::Compatible(hash, priority, build_tag)
835        }
836    }
837
838    /// Return `true` if the distribution is compatible.
839    pub(crate) fn is_compatible(&self) -> bool {
840        matches!(self, Self::Compatible(_, _, _))
841    }
842
843    /// Return `true` if the distribution is excluded.
844    fn is_excluded(&self) -> bool {
845        matches!(self, Self::Incompatible(IncompatibleWheel::ExcludeNewer(_)))
846    }
847
848    /// Return `true` if the current compatibility is more compatible than another.
849    ///
850    /// Compatible wheels are always higher more compatible than incompatible wheels.
851    /// Compatible wheel ordering is determined by tag priority.
852    fn is_more_compatible(&self, other: &Self) -> bool {
853        match (self, other) {
854            (Self::Compatible(_, _, _), Self::Incompatible(_) | Self::Variant(..)) => true,
855            (
856                Self::Compatible(hash, tag_priority, build_tag),
857                Self::Compatible(other_hash, other_tag_priority, other_build_tag),
858            ) => {
859                (hash, tag_priority, build_tag) > (other_hash, other_tag_priority, other_build_tag)
860            }
861            (Self::Incompatible(_) | Self::Variant(..), Self::Compatible(_, _, _)) => false,
862            (Self::Incompatible(incompatibility), Self::Incompatible(other_incompatibility)) => {
863                incompatibility.is_more_compatible(other_incompatibility)
864            }
865            (Self::Variant(..), Self::Incompatible(other)) => {
866                IncompatibleWheel::Tag(IncompatibleTag::Variant).is_more_compatible(other)
867            }
868            (Self::Incompatible(incompatibility), Self::Variant(..)) => incompatibility
869                .is_more_compatible(&IncompatibleWheel::Tag(IncompatibleTag::Variant)),
870            (Self::Variant(..), Self::Variant(..)) => false,
871        }
872    }
873}
874
875impl SourceDistCompatibility {
876    /// Return `true` if the distribution is compatible.
877    pub(crate) fn is_compatible(&self) -> bool {
878        matches!(self, Self::Compatible(_))
879    }
880
881    /// Return `true` if the distribution is excluded.
882    fn is_excluded(&self) -> bool {
883        matches!(
884            self,
885            Self::Incompatible(IncompatibleSource::ExcludeNewer(_))
886        )
887    }
888
889    /// Return the higher priority compatibility.
890    ///
891    /// Compatible source distributions are always higher priority than incompatible source distributions.
892    /// Compatible source distribution priority is arbitrary.
893    /// Incompatible source distribution priority selects a source distribution that was "closest" to being usable.
894    fn is_more_compatible(&self, other: &Self) -> bool {
895        match (self, other) {
896            (Self::Compatible(_), Self::Incompatible(_)) => true,
897            (Self::Compatible(compatibility), Self::Compatible(other_compatibility)) => {
898                compatibility > other_compatibility
899            }
900            (Self::Incompatible(_), Self::Compatible(_)) => false,
901            (Self::Incompatible(incompatibility), Self::Incompatible(other_incompatibility)) => {
902                incompatibility.is_more_compatible(other_incompatibility)
903            }
904        }
905    }
906}
907
908impl IncompatibleSource {
909    fn is_more_compatible(&self, other: &Self) -> bool {
910        match self {
911            Self::ExcludeNewer(timestamp_self) => match other {
912                // Smaller timestamps are closer to the cut-off time
913                Self::ExcludeNewer(timestamp_other) => timestamp_other < timestamp_self,
914                Self::NoBuild
915                | Self::RequiresPython(_, _)
916                | Self::Yanked(_)
917                | Self::NotPep625Filename => true,
918            },
919            Self::RequiresPython(_, _) => match other {
920                Self::ExcludeNewer(_) => false,
921                // Version specifiers cannot be reasonably compared
922                Self::RequiresPython(_, _) => false,
923                Self::NoBuild | Self::Yanked(_) | Self::NotPep625Filename => true,
924            },
925            Self::Yanked(_) => match other {
926                Self::ExcludeNewer(_) | Self::RequiresPython(_, _) | Self::NotPep625Filename => {
927                    false
928                }
929                // Yanks with a reason are more helpful for errors
930                Self::Yanked(yanked_other) => matches!(yanked_other, Yanked::Reason(_)),
931                Self::NoBuild => true,
932            },
933            Self::NoBuild | Self::NotPep625Filename => false,
934        }
935    }
936}
937
938impl IncompatibleWheel {
939    fn is_more_compatible(&self, other: &Self) -> bool {
940        match self {
941            Self::ExcludeNewer(timestamp_self) => match other {
942                // Smaller timestamps are closer to the cut-off time
943                Self::ExcludeNewer(timestamp_other) => match (timestamp_self, timestamp_other) {
944                    (None, _) => true,
945                    (_, None) => false,
946                    (Some(timestamp_self), Some(timestamp_other)) => {
947                        timestamp_other < timestamp_self
948                    }
949                },
950                Self::MissingPlatform(_)
951                | Self::NoBinary
952                | Self::RequiresPython(_, _)
953                | Self::Tag(_)
954                | Self::Yanked(_) => true,
955            },
956            Self::Tag(tag_self) => match other {
957                Self::ExcludeNewer(_) => false,
958                Self::Tag(tag_other) => tag_self > tag_other,
959                Self::MissingPlatform(_)
960                | Self::NoBinary
961                | Self::RequiresPython(_, _)
962                | Self::Yanked(_) => true,
963            },
964            Self::RequiresPython(_, _) => match other {
965                Self::ExcludeNewer(_) | Self::Tag(_) => false,
966                // Version specifiers cannot be reasonably compared
967                Self::RequiresPython(_, _) => false,
968                Self::MissingPlatform(_) | Self::NoBinary | Self::Yanked(_) => true,
969            },
970            Self::Yanked(_) => match other {
971                Self::ExcludeNewer(_) | Self::Tag(_) | Self::RequiresPython(_, _) => false,
972                // Yanks with a reason are more helpful for errors
973                Self::Yanked(yanked_other) => matches!(yanked_other, Yanked::Reason(_)),
974                Self::MissingPlatform(_) | Self::NoBinary => true,
975            },
976            Self::NoBinary => match other {
977                Self::ExcludeNewer(_)
978                | Self::Tag(_)
979                | Self::RequiresPython(_, _)
980                | Self::Yanked(_) => false,
981                Self::NoBinary => false,
982                Self::MissingPlatform(_) => true,
983            },
984            Self::MissingPlatform(_) => false,
985        }
986    }
987}
988
989/// Given a wheel filename, determine the markers covered by every configured libc baseline.
990///
991/// A wheel with multiple platform tags can remain eligible without covering every tagged platform.
992pub(crate) fn implied_markers(
993    filename: &WheelFilename,
994    minimum_libc_version: Option<MinimumLibcVersion>,
995) -> MarkerTree {
996    let python = implied_python_markers(filename);
997    let [glibc, musl] = implied_libc_markers(filename, python, minimum_libc_version);
998    glibc.and(musl)
999}
1000
1001/// Infer coverage for each libc independently so separate wheels can satisfy each baseline.
1002fn implied_libc_markers(
1003    filename: &WheelFilename,
1004    python: MarkerTree,
1005    minimum_libc_version: Option<MinimumLibcVersion>,
1006) -> [MarkerTree; 2] {
1007    let Some(minimum_libc_version) = minimum_libc_version else {
1008        return [implied_platform_markers(filename.platform_tags()).and(python); 2];
1009    };
1010    let mut markers = [MarkerTree::FALSE; 2];
1011    for tag in filename.platform_tags() {
1012        let platform = implied_platform_markers([tag]).and(python);
1013        for (markers, supported) in markers
1014            .iter_mut()
1015            .zip(minimum_libc_version.platform_coverage(tag))
1016        {
1017            if supported {
1018                *markers = markers.or(platform);
1019            }
1020        }
1021    }
1022    markers
1023}
1024
1025/// Infer the environments described by a set of platform tags.
1026fn implied_platform_markers<'a>(
1027    platform_tags: impl IntoIterator<Item = &'a PlatformTag>,
1028) -> MarkerTree {
1029    let mut marker = MarkerTree::FALSE;
1030    for platform_tag in platform_tags {
1031        match platform_tag {
1032            PlatformTag::Any => {
1033                return MarkerTree::TRUE;
1034            }
1035
1036            // Windows
1037            PlatformTag::Win32 => {
1038                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1039                    key: MarkerValueString::SysPlatform,
1040                    operator: MarkerOperator::Equal,
1041                    value: arcstr::literal!("win32"),
1042                });
1043                tag_marker = tag_marker.and(MarkerTree::expression(MarkerExpression::String {
1044                    key: MarkerValueString::PlatformMachine,
1045                    operator: MarkerOperator::Equal,
1046                    value: arcstr::literal!("x86"),
1047                }));
1048                marker = marker.or(tag_marker);
1049            }
1050            PlatformTag::WinAmd64 => {
1051                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1052                    key: MarkerValueString::SysPlatform,
1053                    operator: MarkerOperator::Equal,
1054                    value: arcstr::literal!("win32"),
1055                });
1056                tag_marker = tag_marker.and(MarkerTree::expression(MarkerExpression::String {
1057                    key: MarkerValueString::PlatformMachine,
1058                    operator: MarkerOperator::Equal,
1059                    value: arcstr::literal!("AMD64"),
1060                }));
1061                marker = marker.or(tag_marker);
1062            }
1063            PlatformTag::WinArm64 => {
1064                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1065                    key: MarkerValueString::SysPlatform,
1066                    operator: MarkerOperator::Equal,
1067                    value: arcstr::literal!("win32"),
1068                });
1069                tag_marker = tag_marker.and(MarkerTree::expression(MarkerExpression::String {
1070                    key: MarkerValueString::PlatformMachine,
1071                    operator: MarkerOperator::Equal,
1072                    value: arcstr::literal!("ARM64"),
1073                }));
1074                marker = marker.or(tag_marker);
1075            }
1076
1077            // macOS
1078            PlatformTag::Macos {
1079                major,
1080                minor,
1081                binary_format,
1082            } => {
1083                let Some(release) = macos_darwin_release(*major, *minor) else {
1084                    continue;
1085                };
1086                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1087                    key: MarkerValueString::SysPlatform,
1088                    operator: MarkerOperator::Equal,
1089                    value: arcstr::literal!("darwin"),
1090                });
1091
1092                // Extract the architecture from the end of the tag.
1093                let mut arch_marker = MarkerTree::FALSE;
1094                for arch in binary_format.platform_machine() {
1095                    // A universal2 wheel can target an older macOS on Intel, but its ARM
1096                    // slice requires macOS 11 (Darwin 20) or later.
1097                    let release = if *arch == BinaryFormat::Arm64 {
1098                        release.clone().max(Version::new([20, 0, 0]))
1099                    } else {
1100                        release.clone()
1101                    };
1102                    let architecture = MarkerTree::expression(MarkerExpression::String {
1103                        key: MarkerValueString::PlatformMachine,
1104                        operator: MarkerOperator::Equal,
1105                        value: ArcStr::from(arch.name()),
1106                    });
1107                    let release = MarkerTree::expression(MarkerExpression::String {
1108                        key: MarkerValueString::PlatformRelease,
1109                        operator: MarkerOperator::GreaterEqual,
1110                        value: ArcStr::from(release.to_string()),
1111                    });
1112                    arch_marker = arch_marker.or(architecture.and(release));
1113                }
1114                tag_marker = tag_marker.and(arch_marker);
1115
1116                marker = marker.or(tag_marker);
1117            }
1118
1119            // Linux
1120            PlatformTag::Manylinux { arch, .. }
1121            | PlatformTag::Manylinux1 { arch, .. }
1122            | PlatformTag::Manylinux2010 { arch, .. }
1123            | PlatformTag::Manylinux2014 { arch, .. }
1124            | PlatformTag::Musllinux { arch, .. }
1125            | PlatformTag::Linux { arch } => {
1126                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1127                    key: MarkerValueString::SysPlatform,
1128                    operator: MarkerOperator::Equal,
1129                    value: arcstr::literal!("linux"),
1130                });
1131                tag_marker = tag_marker.and(MarkerTree::expression(MarkerExpression::String {
1132                    key: MarkerValueString::PlatformMachine,
1133                    operator: MarkerOperator::Equal,
1134                    value: ArcStr::from(arch.name()),
1135                }));
1136                marker = marker.or(tag_marker);
1137            }
1138
1139            // Android
1140            //
1141            // The tag's API level is not encoded, since no marker exposes it: `platform_release`
1142            // reports the Android version.
1143            PlatformTag::Android { abi, .. } => {
1144                let mut tag_marker = MarkerTree::expression(MarkerExpression::String {
1145                    key: MarkerValueString::SysPlatform,
1146                    operator: MarkerOperator::Equal,
1147                    value: arcstr::literal!("android"),
1148                });
1149                tag_marker = tag_marker.and(MarkerTree::expression(MarkerExpression::String {
1150                    key: MarkerValueString::PlatformMachine,
1151                    operator: MarkerOperator::Equal,
1152                    value: ArcStr::from(abi.arch().name()),
1153                }));
1154                marker = marker.or(tag_marker);
1155            }
1156
1157            tag => {
1158                debug!("Unknown platform tag in wheel tag: {tag}");
1159            }
1160        }
1161    }
1162
1163    marker
1164}
1165
1166/// Translate a macOS deployment target into the corresponding
1167/// [Darwin kernel release](<https://en.wikipedia.org/wiki/Darwin_(operating_system)#Darwin_20_onwards>).
1168///
1169/// macOS 10.16 is the compatibility spelling of macOS 11. macOS 26 uses Darwin 25;
1170/// starting with macOS 27, the major versions match.
1171fn macos_darwin_release(major: u16, minor: u16) -> Option<Version> {
1172    let release = match (major, minor) {
1173        (10, 0) => [1, 3, 0],
1174        (10, 1) => [1, 4, 1],
1175        (10, 2..=16) => [u64::from(minor) + 4, 0, 0],
1176        (11..=15, 0) => [u64::from(major) + 9, 0, 0],
1177        (26, 0) => [25, 0, 0],
1178        (27.., 0) => [u64::from(major), 0, 0],
1179        _ => return None,
1180    };
1181    Some(Version::new(release))
1182}
1183
1184/// Given a wheel filename, determine the set of supported Python versions, in terms of their markers.
1185///
1186/// This is roughly the inverse of Python tag generation: given a tag, we want to infer the
1187/// supported Python version (rather than generating the supported tags from a given Python version).
1188fn implied_python_markers(filename: &WheelFilename) -> MarkerTree {
1189    let mut marker = MarkerTree::FALSE;
1190
1191    // If any ABI tag is a stable ABI (`abi3` or `abi3t`), the python tag represents a minimum
1192    // version rather than an exact version. For example, `cp39-abi3` means "compatible with
1193    // CPython 3.9+".
1194    let is_abi3 = filename.abi_tags().iter().any(|tag| tag.is_stable_abi());
1195
1196    for python_tag in filename.python_tags() {
1197        // First, construct the version marker based on the tag
1198        let mut tree = match python_tag {
1199            LanguageTag::None => {
1200                // No Python tag means no Python version requirement.
1201                return MarkerTree::TRUE;
1202            }
1203            LanguageTag::Python { major, minor: None } | LanguageTag::CPythonMajor { major } => {
1204                if is_abi3 {
1205                    MarkerTree::expression(MarkerExpression::Version {
1206                        key: uv_pep508::MarkerValueVersion::PythonVersion,
1207                        specifier: VersionSpecifier::greater_than_equal_version(Version::new([
1208                            u64::from(*major),
1209                        ])),
1210                    })
1211                } else {
1212                    MarkerTree::expression(MarkerExpression::Version {
1213                        key: uv_pep508::MarkerValueVersion::PythonVersion,
1214                        specifier: VersionSpecifier::equals_star_version(Version::new([
1215                            u64::from(*major),
1216                        ])),
1217                    })
1218                }
1219            }
1220            LanguageTag::Python {
1221                major,
1222                minor: Some(minor),
1223            } => {
1224                // Generic Python tags support later minor versions within the same major version.
1225                MarkerTree::expression(MarkerExpression::Version {
1226                    key: uv_pep508::MarkerValueVersion::PythonVersion,
1227                    specifier: VersionSpecifier::greater_than_equal_version(Version::new([
1228                        u64::from(*major),
1229                        u64::from(*minor),
1230                    ])),
1231                })
1232                .and(MarkerTree::expression(MarkerExpression::Version {
1233                    key: uv_pep508::MarkerValueVersion::PythonVersion,
1234                    specifier: VersionSpecifier::equals_star_version(Version::new([u64::from(
1235                        *major,
1236                    )])),
1237                }))
1238            }
1239            LanguageTag::CPython {
1240                python_version: (major, minor),
1241            }
1242            | LanguageTag::PyPy {
1243                python_version: (major, minor),
1244            }
1245            | LanguageTag::GraalPy {
1246                python_version: (major, minor),
1247            }
1248            | LanguageTag::Pyston {
1249                python_version: (major, minor),
1250            } => {
1251                if is_abi3 {
1252                    MarkerTree::expression(MarkerExpression::Version {
1253                        key: uv_pep508::MarkerValueVersion::PythonVersion,
1254                        specifier: VersionSpecifier::greater_than_equal_version(Version::new([
1255                            u64::from(*major),
1256                            u64::from(*minor),
1257                        ])),
1258                    })
1259                } else {
1260                    MarkerTree::expression(MarkerExpression::Version {
1261                        key: uv_pep508::MarkerValueVersion::PythonVersion,
1262                        specifier: VersionSpecifier::equals_star_version(Version::new([
1263                            u64::from(*major),
1264                            u64::from(*minor),
1265                        ])),
1266                    })
1267                }
1268            }
1269        };
1270
1271        // Then, add implementation markers for implementation-specific tags
1272        match python_tag {
1273            LanguageTag::None | LanguageTag::Python { .. } => {
1274                // No implementation marker needed
1275            }
1276            LanguageTag::CPython { .. } | LanguageTag::CPythonMajor { .. } => {
1277                tree = tree.and(MarkerTree::expression(MarkerExpression::String {
1278                    key: MarkerValueString::PlatformPythonImplementation,
1279                    operator: MarkerOperator::Equal,
1280                    value: arcstr::literal!("CPython"),
1281                }));
1282            }
1283            LanguageTag::PyPy { .. } => {
1284                tree = tree.and(MarkerTree::expression(MarkerExpression::String {
1285                    key: MarkerValueString::PlatformPythonImplementation,
1286                    operator: MarkerOperator::Equal,
1287                    value: arcstr::literal!("PyPy"),
1288                }));
1289            }
1290            LanguageTag::GraalPy { .. } => {
1291                tree = tree.and(MarkerTree::expression(MarkerExpression::String {
1292                    key: MarkerValueString::PlatformPythonImplementation,
1293                    operator: MarkerOperator::Equal,
1294                    value: arcstr::literal!("GraalPy"),
1295                }));
1296            }
1297            LanguageTag::Pyston { .. } => {
1298                tree = tree.and(MarkerTree::expression(MarkerExpression::String {
1299                    key: MarkerValueString::PlatformPythonImplementation,
1300                    operator: MarkerOperator::Equal,
1301                    value: arcstr::literal!("Pyston"),
1302                }));
1303            }
1304        }
1305
1306        marker = marker.or(tree);
1307    }
1308
1309    marker
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314    use std::str::FromStr;
1315
1316    use super::*;
1317
1318    #[track_caller]
1319    fn assert_platform_markers(filename: &str, expected: &str) {
1320        let filename = WheelFilename::from_str(filename).unwrap();
1321        assert_eq!(
1322            implied_platform_markers(filename.platform_tags()),
1323            expected.parse::<MarkerTree>().unwrap()
1324        );
1325    }
1326
1327    #[track_caller]
1328    fn assert_python_markers(filename: &str, expected: &str) {
1329        let filename = WheelFilename::from_str(filename).unwrap();
1330        assert_eq!(
1331            implied_python_markers(&filename),
1332            expected.parse::<MarkerTree>().unwrap()
1333        );
1334    }
1335
1336    #[track_caller]
1337    fn assert_implied_markers(filename: &str, expected: &str) {
1338        let filename = WheelFilename::from_str(filename).unwrap();
1339        assert_eq!(
1340            implied_markers(&filename, None),
1341            expected.parse::<MarkerTree>().unwrap()
1342        );
1343    }
1344
1345    #[test]
1346    fn test_implied_platform_markers() {
1347        let filename = WheelFilename::from_str("example-1.0-py3-none-any.whl").unwrap();
1348        assert_eq!(
1349            implied_platform_markers(filename.platform_tags()),
1350            MarkerTree::TRUE
1351        );
1352
1353        assert_platform_markers(
1354            "example-1.0-cp310-cp310-win32.whl",
1355            "sys_platform == 'win32' and platform_machine == 'x86'",
1356        );
1357        assert_platform_markers(
1358            "numpy-2.2.1-cp313-cp313t-win_amd64.whl",
1359            "sys_platform == 'win32' and platform_machine == 'AMD64'",
1360        );
1361        assert_platform_markers(
1362            "numpy-2.2.1-cp313-cp313t-win_arm64.whl",
1363            "sys_platform == 'win32' and platform_machine == 'ARM64'",
1364        );
1365        assert_platform_markers(
1366            "numpy-2.2.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl",
1367            "sys_platform == 'linux' and platform_machine == 'aarch64'",
1368        );
1369        assert_platform_markers(
1370            "numpy-2.2.1-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl",
1371            "sys_platform == 'linux' and platform_machine == 'x86_64'",
1372        );
1373        assert_platform_markers(
1374            "numpy-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl",
1375            "sys_platform == 'linux' and platform_machine == 'aarch64'",
1376        );
1377        assert_platform_markers(
1378            "numpy-2.2.1-cp310-cp310-macosx_14_0_x86_64.whl",
1379            "sys_platform == 'darwin' and platform_machine == 'x86_64' and platform_release >= '23.0.0'",
1380        );
1381        assert_platform_markers(
1382            "numpy-2.2.1-cp310-cp310-macosx_10_9_x86_64.whl",
1383            "sys_platform == 'darwin' and platform_machine == 'x86_64' and platform_release >= '13.0.0'",
1384        );
1385        assert_platform_markers(
1386            "numpy-2.2.1-cp310-cp310-macosx_11_0_arm64.whl",
1387            "sys_platform == 'darwin' and platform_machine == 'arm64' and platform_release >= '20.0.0'",
1388        );
1389        assert_platform_markers(
1390            "example-1.0-py3-none-android_24_arm64_v8a.whl",
1391            "sys_platform == 'android' and platform_machine == 'aarch64'",
1392        );
1393        assert_platform_markers(
1394            "example-1.0-py3-none-android_24_armeabi_v7a.whl",
1395            "sys_platform == 'android' and platform_machine == 'armv7l'",
1396        );
1397        assert_platform_markers(
1398            "example-1.0-py3-none-android_24_x86.whl",
1399            "sys_platform == 'android' and platform_machine == 'i686'",
1400        );
1401        assert_platform_markers(
1402            "example-1.0-py3-none-android_24_x86_64.whl",
1403            "sys_platform == 'android' and platform_machine == 'x86_64'",
1404        );
1405    }
1406
1407    #[test]
1408    fn test_implied_python_markers() {
1409        let filename = WheelFilename::from_str("example-1.0-none-none-any.whl").unwrap();
1410        assert_eq!(implied_python_markers(&filename), MarkerTree::TRUE);
1411
1412        assert_python_markers(
1413            "example-1.0-cp310-cp310-any.whl",
1414            "python_full_version == '3.10.*' and platform_python_implementation == 'CPython'",
1415        );
1416        assert_python_markers(
1417            "example-1.0-cp311-cp311-any.whl",
1418            "python_full_version == '3.11.*' and platform_python_implementation == 'CPython'",
1419        );
1420        assert_python_markers(
1421            "example-1.0-cp312-cp312-any.whl",
1422            "python_full_version == '3.12.*' and platform_python_implementation == 'CPython'",
1423        );
1424        assert_python_markers(
1425            "example-1.0-cp313-cp313-any.whl",
1426            "python_full_version == '3.13.*' and platform_python_implementation == 'CPython'",
1427        );
1428        assert_python_markers(
1429            "example-1.0-cp313-cp313t-any.whl",
1430            "python_full_version == '3.13.*' and platform_python_implementation == 'CPython'",
1431        );
1432        assert_python_markers(
1433            "example-1.0-pp310-pypy310_pp73-any.whl",
1434            "python_full_version == '3.10.*' and platform_python_implementation == 'PyPy'",
1435        );
1436        assert_python_markers(
1437            "example-1.0-py310-none-any.whl",
1438            "python_full_version >= '3.10' and python_full_version < '4'",
1439        );
1440        assert_python_markers(
1441            "example-1.0-py3-none-any.whl",
1442            "python_full_version >= '3' and python_full_version < '4'",
1443        );
1444        assert_python_markers(
1445            "example-1.0-py311.py312-none-any.whl",
1446            "python_full_version >= '3.11' and python_full_version < '4'",
1447        );
1448
1449        // abi3 wheels: the python tag represents a minimum version, not an exact version.
1450        assert_python_markers(
1451            "example-1.0-cp39-abi3-any.whl",
1452            "python_full_version >= '3.9' and platform_python_implementation == 'CPython'",
1453        );
1454        assert_python_markers(
1455            "example-1.0-cp312-abi3-any.whl",
1456            "python_full_version >= '3.12' and platform_python_implementation == 'CPython'",
1457        );
1458        assert_python_markers(
1459            "example-1.0-cp315-abi3t-any.whl",
1460            "python_full_version >= '3.15' and platform_python_implementation == 'CPython'",
1461        );
1462        assert_python_markers(
1463            "example-1.0-cp3-abi3-any.whl",
1464            "python_full_version >= '3' and platform_python_implementation == 'CPython'",
1465        );
1466    }
1467
1468    #[test]
1469    fn test_macos_platform_markers() {
1470        for (tag, expected) in [
1471            (
1472                "macosx_10_5_x86_64",
1473                "sys_platform == 'darwin' and platform_machine == 'x86_64' and platform_release >= '9.0.0'",
1474            ),
1475            (
1476                "macosx_10_9_universal2",
1477                "sys_platform == 'darwin' and ((platform_machine == 'x86_64' and platform_release >= '13.0.0') or (platform_machine == 'arm64' and platform_release >= '20.0.0'))",
1478            ),
1479            (
1480                "macosx_10_16_universal2",
1481                "sys_platform == 'darwin' and (platform_machine == 'arm64' or platform_machine == 'x86_64') and platform_release >= '20.0.0'",
1482            ),
1483            (
1484                "macosx_15_0_arm64",
1485                "sys_platform == 'darwin' and platform_machine == 'arm64' and platform_release >= '24.0.0'",
1486            ),
1487            (
1488                "macosx_26_0_arm64",
1489                "sys_platform == 'darwin' and platform_machine == 'arm64' and platform_release >= '25.0.0'",
1490            ),
1491            (
1492                "macosx_27_0_arm64",
1493                "sys_platform == 'darwin' and platform_machine == 'arm64' and platform_release >= '27.0.0'",
1494            ),
1495            (
1496                "macosx_26_0_arm64.macosx_15_0_x86_64",
1497                "sys_platform == 'darwin' and ((platform_machine == 'arm64' and platform_release >= '25.0.0') or (platform_machine == 'x86_64' and platform_release >= '24.0.0'))",
1498            ),
1499        ] {
1500            let filename =
1501                WheelFilename::from_str(&format!("example-1.0-py3-none-{tag}.whl")).unwrap();
1502            assert_eq!(
1503                implied_platform_markers(filename.platform_tags()),
1504                MarkerTree::from_str(expected).unwrap()
1505            );
1506        }
1507    }
1508
1509    #[test]
1510    fn test_implied_markers() {
1511        assert_implied_markers(
1512            "numpy-1.0-cp310-cp310-win32.whl",
1513            "python_full_version == '3.10.*' and platform_python_implementation == 'CPython' and sys_platform == 'win32' and platform_machine == 'x86'",
1514        );
1515        assert_implied_markers(
1516            "pywin32-311-cp314-cp314-win_arm64.whl",
1517            "python_full_version == '3.14.*' and platform_python_implementation == 'CPython' and sys_platform == 'win32' and platform_machine == 'ARM64'",
1518        );
1519        assert_implied_markers(
1520            "numpy-1.0-cp311-cp311-macosx_10_9_x86_64.whl",
1521            "python_full_version == '3.11.*' and platform_python_implementation == 'CPython' and sys_platform == 'darwin' and platform_machine == 'x86_64' and platform_release >= '13.0.0'",
1522        );
1523        assert_implied_markers(
1524            "numpy-1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl",
1525            "python_full_version == '3.12.*' and platform_python_implementation == 'CPython' and sys_platform == 'linux' and platform_machine == 'aarch64'",
1526        );
1527        assert_implied_markers(
1528            "example-1.0-py3-none-any.whl",
1529            "python_full_version >= '3' and python_full_version < '4'",
1530        );
1531
1532        // abi3 wheel: cp39-abi3 means CPython >= 3.9, combined with platform markers.
1533        assert_implied_markers(
1534            "example-1.0-cp39-abi3-manylinux_2_28_x86_64.whl",
1535            "python_full_version >= '3.9' and platform_python_implementation == 'CPython' and sys_platform == 'linux' and platform_machine == 'x86_64'",
1536        );
1537        assert_implied_markers(
1538            "example-1.0-cp315-abi3t-manylinux_2_28_x86_64.whl",
1539            "python_full_version >= '3.15' and platform_python_implementation == 'CPython' and sys_platform == 'linux' and platform_machine == 'x86_64'",
1540        );
1541    }
1542}