Skip to main content

cuno_toolchain/
select.rs

1//! Choosing the compiler: which one the user asked for, and which installed
2//! copy satisfies the version requirements. See `docs/en/specs/toolchain.md`,
3//! "Selection" and "Version pinning". Whether the copy chosen can build here
4//! is [`crate::probe`]'s.
5
6use std::fmt;
7use std::path::{Path, PathBuf};
8
9use crate::gcc::{Gcc, Origin as GccOrigin, Probe as GccProbe};
10use crate::llvm::{LlvmTool, Origin, Probe, Tool};
11use crate::msvc::{MsvcToolset, VsInstallation};
12use crate::prepare::Detected;
13use cuno_core::paths;
14
15use crate::{HostOs, ToolchainError, Version};
16
17pub use crate::compiler::CompilerKind;
18
19/// Where the choice of compiler came from, highest precedence first.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21pub enum Source {
22    /// `--compiler`.
23    CommandLine,
24    /// `CUNO_COMPILER`.
25    Environment,
26    /// The project's `.cuno/config.toml`.
27    ProjectConfig,
28    /// `[toolchain] compiler` in `Cuno.toml`.
29    Manifest,
30    /// The user-level `config.toml`.
31    UserConfig,
32    /// Nothing asked: the platform's default.
33    Automatic,
34}
35
36impl fmt::Display for Source {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.write_str(match self {
39            Source::CommandLine => "--compiler",
40            Source::Environment => "CUNO_COMPILER",
41            Source::ProjectConfig => "compiler in .cuno/config.toml",
42            Source::Manifest => "[toolchain] compiler in Cuno.toml",
43            Source::UserConfig => "compiler in the user-level config.toml",
44            Source::Automatic => "automatic selection",
45        })
46    }
47}
48
49/// The compiler names each layer gives, as read by whoever reads them.
50#[derive(Clone, Debug, Default)]
51pub struct Choices {
52    /// `--compiler`.
53    pub cli: Option<String>,
54    /// `CUNO_COMPILER`.
55    pub env: Option<String>,
56    /// The project's layers; `None` outside a project, where they do not
57    /// exist (`toolchain.md`, "Selection").
58    pub project: Option<ProjectChoices>,
59    /// The user-level `config.toml`.
60    pub user: Option<String>,
61}
62
63/// The compiler names a project's own layers give.
64#[derive(Clone, Debug, Default)]
65pub struct ProjectChoices {
66    /// `.cuno/config.toml`.
67    pub config: Option<String>,
68    /// `[toolchain] compiler` in `Cuno.toml`.
69    pub manifest: Option<String>,
70}
71
72impl Choices {
73    /// The compiler asked for and where the request came from: the
74    /// highest-precedence name given, else the platform's default. An
75    /// unknown or unsupported name is an error naming where it was given.
76    pub fn kind(&self, host: HostOs) -> Result<(CompilerKind, Source), ToolchainError> {
77        match self.requested() {
78            Some((name, source)) => Ok((CompilerKind::parse(name, source)?, source)),
79            None => match host {
80                HostOs::Windows => Ok((CompilerKind::Msvc, Source::Automatic)),
81                // GCC on Linux and Apple Clang on macOS come after the MVP.
82                HostOs::Other => Err(ToolchainError::UnsupportedCompiler {
83                    name: "gcc".to_owned(),
84                    source: Source::Automatic.to_string(),
85                }),
86            },
87        }
88    }
89
90    /// The highest-precedence name given, and where it came from.
91    fn requested(&self) -> Option<(&str, Source)> {
92        let project = self.project.as_ref();
93        [
94            (self.cli.as_deref(), Source::CommandLine),
95            (self.env.as_deref(), Source::Environment),
96            (
97                project.and_then(|p| p.config.as_deref()),
98                Source::ProjectConfig,
99            ),
100            (
101                project.and_then(|p| p.manifest.as_deref()),
102                Source::Manifest,
103            ),
104            (self.user.as_deref(), Source::UserConfig),
105        ]
106        .into_iter()
107        .find_map(|(name, source)| Some((name?, source)))
108    }
109}
110
111/// A `[toolchain.version]` value: comma-separated `>=`, `>`, `<=`, `<` or `=`
112/// conditions, each compared only up to the components it writes
113/// (`manifest.md`, "`[toolchain.version]`").
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct VersionReq {
116    text: String,
117    conditions: Vec<(Op, Vec<u32>)>,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121enum Op {
122    Ge,
123    Gt,
124    Le,
125    Lt,
126    Eq,
127}
128
129impl VersionReq {
130    /// Parses a requirement for `compiler`, such as `">=17, <19"`.
131    pub fn parse(compiler: &str, text: &str) -> Result<VersionReq, ToolchainError> {
132        let invalid = || ToolchainError::InvalidVersionRequirement {
133            compiler: compiler.to_owned(),
134            text: text.to_owned(),
135        };
136        let conditions = text
137            .split(',')
138            .map(|condition| {
139                let condition = condition.trim();
140                let (op, rest) = [
141                    (">=", Op::Ge),
142                    ("<=", Op::Le),
143                    (">", Op::Gt),
144                    ("<", Op::Lt),
145                    ("=", Op::Eq),
146                ]
147                .into_iter()
148                .find_map(|(s, op)| Some((op, condition.strip_prefix(s)?)))
149                .ok_or_else(invalid)?;
150                let parts: Vec<u32> = rest
151                    .trim()
152                    .split('.')
153                    .map(|part| part.parse().map_err(|_| invalid()))
154                    .collect::<Result<_, _>>()?;
155                if parts.len() > 3 {
156                    return Err(invalid());
157                }
158                Ok((op, parts))
159            })
160            .collect::<Result<Vec<_>, _>>()?;
161        Ok(VersionReq {
162            text: text.to_owned(),
163            conditions,
164        })
165    }
166
167    /// Whether `version` satisfies every condition.
168    pub fn matches(&self, version: &Version) -> bool {
169        let full = [version.major, version.minor, version.patch];
170        self.conditions.iter().all(|(op, parts)| {
171            let ordering = full[..parts.len()].cmp(parts);
172            match op {
173                Op::Ge => ordering.is_ge(),
174                Op::Gt => ordering.is_gt(),
175                Op::Le => ordering.is_le(),
176                Op::Lt => ordering.is_lt(),
177                Op::Eq => ordering.is_eq(),
178            }
179        })
180    }
181}
182
183impl fmt::Display for VersionReq {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.write_str(&self.text)
186    }
187}
188
189/// `[toolchain.version]`, for the compilers cuno can build with.
190#[derive(Clone, Debug, Default, PartialEq, Eq)]
191pub struct Constraints {
192    /// `msvc`.
193    pub msvc: Option<VersionReq>,
194    /// `clang`.
195    pub clang: Option<VersionReq>,
196    /// `clang-cl`.
197    pub clang_cl: Option<VersionReq>,
198    /// `gcc`.
199    pub gcc: Option<VersionReq>,
200}
201
202impl Constraints {
203    /// The constraint written for `kind`, to set: every kind has one, so a
204    /// new kind must say where its constraint lives.
205    pub fn slot(&mut self, kind: CompilerKind) -> &mut Option<VersionReq> {
206        match kind {
207            CompilerKind::Msvc => &mut self.msvc,
208            CompilerKind::Clang => &mut self.clang,
209            CompilerKind::ClangCl => &mut self.clang_cl,
210            CompilerKind::Gcc => &mut self.gcc,
211        }
212    }
213
214    /// The constraint written for `kind`, if any.
215    pub fn of(&self, kind: CompilerKind) -> Option<&VersionReq> {
216        match kind {
217            CompilerKind::Msvc => self.msvc.as_ref(),
218            CompilerKind::Clang => self.clang.as_ref(),
219            CompilerKind::ClangCl => self.clang_cl.as_ref(),
220            CompilerKind::Gcc => self.gcc.as_ref(),
221        }
222    }
223}
224
225/// What detection found.
226#[derive(Clone, Copy, Debug)]
227pub struct Found<'a> {
228    /// Every Visual Studio installation.
229    pub installs: &'a [VsInstallation],
230    /// Every LLVM tool.
231    pub llvm: &'a [LlvmTool],
232    /// Every GCC, searched only when GCC is wanted (`toolchain.md`, "MinGW
233    /// (GCC)"): empty otherwise.
234    pub gcc: &'a [Gcc],
235    /// `[toolchain.paths] msvc`: the only installation to use, when written.
236    pub explicit_msvc: Option<&'a Path>,
237}
238
239/// The compiler to build with.
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub struct Selected {
242    /// Which compiler.
243    pub kind: CompilerKind,
244    /// Its executable.
245    pub executable: PathBuf,
246    /// Its version.
247    pub version: Version,
248    /// The MSVC toolset whose headers and libraries it uses (Windows).
249    pub msvc: Option<MsvcToolset>,
250    /// Where the choice came from.
251    pub source: Source,
252}
253
254/// Chooses the compiler: the highest-precedence name given, else the
255/// platform's default, then its newest installed copy that satisfies cuno's
256/// minimum and `[toolchain.version]`, never a preview.
257pub fn select(
258    choices: &Choices,
259    found: Found<'_>,
260    constraints: &Constraints,
261    host: HostOs,
262) -> Result<Selected, ToolchainError> {
263    let (kind, source) = choices.kind(host)?;
264    // A compiler that builds with an MSVC toolset needs Visual Studio, even
265    // a Clang, which borrows its toolset; one that does not, needs none
266    // (`CompilerKind::uses_msvc_toolset`).
267    let newest_toolset = if kind.uses_msvc_toolset(host) {
268        let toolsets = usable_toolsets(found, host)?;
269        first_newest(toolsets.iter().map(|t| (t, t.cl_version))).cloned()
270    } else {
271        None
272    };
273    let (executable, version, msvc) = copy_of(kind, found, constraints, host)?;
274    Ok(Selected {
275        kind,
276        executable,
277        version,
278        // A Clang gets the newest toolset; MSVC is its own.
279        msvc: msvc.or(newest_toolset),
280        source,
281    })
282}
283
284/// The copy of `kind` that selecting it would use, and its version (with
285/// its own toolset for MSVC), or why there is none: the one written in
286/// `[toolchain.paths]` when there is one, which must be usable, otherwise
287/// the newest eligible copy; cuno's minimum and `constraints` apply either
288/// way. The one answer `select` and `cuno doctor`'s `Info` lines share. A
289/// Clang is answered without Visual Studio, which `select` requires
290/// separately.
291pub fn copy_of(
292    kind: CompilerKind,
293    found: Found<'_>,
294    constraints: &Constraints,
295    host: HostOs,
296) -> Result<(PathBuf, Version, Option<MsvcToolset>), ToolchainError> {
297    let requirement = constraints.of(kind);
298    let acceptable = |version: &Version| {
299        *version >= kind.minimum() && requirement.is_none_or(|r| r.matches(version))
300    };
301    let mut requirements = vec![format!(">={} (cuno's minimum)", kind.minimum())];
302    if let Some(r) = requirement {
303        requirements.push(format!("{r} ([toolchain.version] {})", kind.name()));
304    }
305
306    let mut candidates: Vec<(PathBuf, Version, Option<MsvcToolset>)> = Vec::new();
307    // Copies found but not eligible, with why, for the error.
308    let mut excluded: Vec<String> = Vec::new();
309    match kind {
310        CompilerKind::Msvc => {
311            if host != HostOs::Windows {
312                return Err(ToolchainError::NoVisualStudio);
313            }
314            candidates.extend(
315                usable_toolsets(found, host)?
316                    .into_iter()
317                    .map(|t| (t.cl(), t.cl_version, Some(t))),
318            );
319        }
320        CompilerKind::Clang | CompilerKind::ClangCl => {
321            let tool = kind
322                .llvm_tool()
323                .expect("the LLVM family is found as an LLVM tool");
324            let configured = found
325                .llvm
326                .iter()
327                .any(|t| t.tool == tool && t.origin == Origin::Configured);
328            if configured {
329                // The configured copy is the only one used (`toolchain.md`,
330                // "LLVM (clang / clang-cl / clang-format / clang-tidy)"): one
331                // that cannot be used is an error, never a reason to take
332                // another.
333                let chosen = select_tool(tool, found.llvm, host)?;
334                if !acceptable(&chosen.version) {
335                    return Err(ToolchainError::ConfiguredToolUnusable {
336                        setting: format!("[toolchain.paths] {}", tool.name()),
337                        path: chosen.path,
338                        why: format!(
339                            "{} does not satisfy {}",
340                            chosen.version,
341                            requirements.join(" and ")
342                        ),
343                    });
344                }
345                return Ok((chosen.path, chosen.version, None));
346            }
347            for t in found.llvm.iter().filter(|t| t.tool == tool) {
348                match release_for(t, host) {
349                    Ok(version) => candidates.push((t.path.clone(), version, None)),
350                    Err(why) => excluded.push(format!("{} ({why})", t.path.display())),
351                }
352            }
353        }
354        CompilerKind::Gcc => {
355            // As for LLVM, a configured copy is the only one used.
356            if let Some(g) = found.gcc.iter().find(|g| g.origin == GccOrigin::Configured) {
357                let why = match gcc_release(g) {
358                    Ok(version) if acceptable(&version) => {
359                        return Ok((g.path.clone(), version, None));
360                    }
361                    Ok(version) => {
362                        format!("{version} does not satisfy {}", requirements.join(" and "))
363                    }
364                    Err(why) => why,
365                };
366                return Err(ToolchainError::ConfiguredToolUnusable {
367                    setting: "[toolchain.paths] gcc".to_owned(),
368                    path: g.path.clone(),
369                    why,
370                });
371            }
372            for g in found.gcc {
373                match gcc_release(g) {
374                    Ok(version) => candidates.push((g.path.clone(), version, None)),
375                    Err(why) => excluded.push(format!("{} ({why})", g.path.display())),
376                }
377            }
378        }
379    }
380    if candidates.is_empty() {
381        return Err(if excluded.is_empty() {
382            ToolchainError::CompilerNotFound {
383                compiler: kind.name(),
384            }
385        } else {
386            ToolchainError::NoUsableCompiler {
387                compiler: kind.name(),
388                excluded,
389            }
390        });
391    }
392    let best = first_newest(
393        candidates
394            .iter()
395            .filter(|c| acceptable(&c.1))
396            .map(|c| (c, c.1)),
397    );
398    match best.cloned() {
399        Some(best) => Ok(best),
400        None => Err(ToolchainError::NoMatchingVersion {
401            compiler: kind.name(),
402            requirements,
403            found: candidates.iter().map(|c| c.1).collect(),
404        }),
405    }
406}
407
408/// The item with the highest version; among equals, the first, so that
409/// search order decides and every compiler picks the same toolset.
410fn first_newest<T>(items: impl Iterator<Item = (T, Version)>) -> Option<T> {
411    let mut best: Option<(T, Version)> = None;
412    for (item, version) in items {
413        if best.as_ref().is_none_or(|(_, b)| version > *b) {
414            best = Some((item, version));
415        }
416    }
417    best.map(|(item, _)| item)
418}
419
420/// The toolsets of the complete, non-preview installations (only the one in
421/// `[toolchain.paths] msvc`, when written).
422fn usable_toolsets(found: Found<'_>, host: HostOs) -> Result<Vec<MsvcToolset>, ToolchainError> {
423    let installs: Vec<&VsInstallation> = found
424        .installs
425        .iter()
426        .filter(|i| i.complete && !i.prerelease)
427        .filter(|i| {
428            found
429                .explicit_msvc
430                .is_none_or(|dir| paths::same(dir, &i.path, host.name_case()))
431        })
432        .collect();
433    if installs.is_empty() {
434        return Err(match found.explicit_msvc {
435            Some(dir) => ToolchainError::VisualStudioNotAt {
436                path: dir.to_owned(),
437            },
438            None => ToolchainError::NoVisualStudio,
439        });
440    }
441    Ok(installs
442        .into_iter()
443        .flat_map(|i| i.toolsets.iter().cloned())
444        .collect())
445}
446
447/// The version of a tool that ran and is a release, or why it is not one.
448fn release(tool: &LlvmTool) -> Result<Version, String> {
449    match &tool.probe {
450        Probe::Failed => Err("it did not run".to_owned()),
451        Probe::NoVersion => Err("it printed no version".to_owned()),
452        Probe::Ran {
453            version,
454            prerelease: true,
455            ..
456        } => Err(format!("{version} is a preview")),
457        Probe::Ran { version, .. } => Ok(*version),
458    }
459}
460
461/// The version of a tool that ran, is a release, and on Windows targets MSVC (a
462/// MinGW Clang cannot be linked with MSVC; `toolchain.md`, "LLVM (clang /
463/// clang-cl / clang-format / clang-tidy)"), or why it is not eligible.
464fn release_for(tool: &LlvmTool, host: HostOs) -> Result<Version, String> {
465    let version = release(tool)?;
466    if host == HostOs::Windows {
467        let target = match &tool.probe {
468            Probe::Ran { target, .. } => target,
469            _ => &None,
470        };
471        match target.as_deref() {
472            Some(t) if t.ends_with("-windows-msvc") => {}
473            Some(t) => return Err(format!("it targets {t}, not MSVC")),
474            None => return Err("it reports no target".to_owned()),
475        }
476    }
477    Ok(version)
478}
479
480/// The version of a GCC that ran, is a release, targets
481/// `x86_64-w64-mingw32` and links UCRT, or why it is not eligible
482/// (`toolchain.md`, "MinGW (GCC)").
483fn gcc_release(gcc: &Gcc) -> Result<Version, String> {
484    match &gcc.probe {
485        GccProbe::Failed => Err("it did not run".to_owned()),
486        GccProbe::NoVersion => Err("it printed no version".to_owned()),
487        GccProbe::Ran {
488            version,
489            prerelease,
490            target,
491            ucrt,
492        } => {
493            if *prerelease {
494                return Err(format!("{version} is a preview"));
495            }
496            match target.as_deref() {
497                Some(GCC_TARGET) => {}
498                Some(t) => return Err(format!("it targets {t}, not {GCC_TARGET}")),
499                None => return Err("it reports no target".to_owned()),
500            }
501            if !ucrt {
502                return Err("its C runtime is MSVCRT, not UCRT".to_owned());
503            }
504            Ok(*version)
505        }
506    }
507}
508
509/// The one target cuno builds for with GCC.
510pub(crate) const GCC_TARGET: &str = "x86_64-w64-mingw32";
511
512/// A clang-format or clang-tidy to use.
513#[derive(Clone, Debug, PartialEq, Eq)]
514pub struct LlvmChoice {
515    /// The executable.
516    pub path: PathBuf,
517    /// Its version.
518    pub version: Version,
519}
520
521/// The oldest clang-format and clang-tidy cuno supports
522/// (`docs/en/specs/dev-tools.md`, "Tool versions").
523pub const TOOL_MINIMUM: Version = Version {
524    major: 17,
525    minor: 0,
526    patch: 0,
527};
528
529/// The copy of `tool` to use among those detected (`toolchain.md`, "LLVM (clang
530/// / clang-cl / clang-format / clang-tidy)"): the one written in
531/// `[toolchain.paths]` when there is one, which must be eligible, or else the
532/// newest eligible copy; among equals, the first in search order. Eligible is a
533/// release that ran, and for clang and clang-cl on Windows one targeting MSVC;
534/// clang-format and clang-tidy have no target to check (clang-tidy prints
535/// none), and must be at least [`TOOL_MINIMUM`]; the compilers' minimum and
536/// `[toolchain.version]` are the compiler selection's.
537pub fn select_tool(
538    tool: Tool,
539    llvm: &[LlvmTool],
540    host: HostOs,
541) -> Result<LlvmChoice, ToolchainError> {
542    let eligible = |t: &LlvmTool| match tool {
543        Tool::Clang | Tool::ClangCl => release_for(t, host),
544        // 17 at least, so formatting and analysis do not change from one
545        // machine to another (`dev-tools.md`, "Tool versions").
546        Tool::ClangFormat | Tool::ClangTidy => release(t).and_then(|version| {
547            if version >= TOOL_MINIMUM {
548                Ok(version)
549            } else {
550                Err(format!(
551                    "{version} does not satisfy >={TOOL_MINIMUM} (cuno's minimum)"
552                ))
553            }
554        }),
555    };
556    let copies = || llvm.iter().filter(|t| t.tool == tool);
557    if let Some(configured) = copies().find(|t| t.origin == Origin::Configured) {
558        return match eligible(configured) {
559            Ok(version) => Ok(LlvmChoice {
560                path: configured.path.clone(),
561                version,
562            }),
563            Err(why) => Err(ToolchainError::ConfiguredToolUnusable {
564                setting: format!("[toolchain.paths] {}", tool.name()),
565                path: configured.path.clone(),
566                why,
567            }),
568        };
569    }
570    let mut excluded = Vec::new();
571    let mut candidates = Vec::new();
572    for t in copies() {
573        match eligible(t) {
574            Ok(version) => candidates.push((
575                LlvmChoice {
576                    path: t.path.clone(),
577                    version,
578                },
579                version,
580            )),
581            Err(why) => excluded.push(format!("{} ({why})", t.path.display())),
582        }
583    }
584    match first_newest(candidates.into_iter()) {
585        Some(best) => Ok(best),
586        None if excluded.is_empty() => Err(ToolchainError::CompilerNotFound {
587            compiler: tool.name(),
588        }),
589        None => Err(ToolchainError::NoUsableCompiler {
590            compiler: tool.name(),
591            excluded,
592        }),
593    }
594}
595
596/// Whether a compiler can be selected here, and if not, why.
597#[derive(Debug)]
598pub enum Availability {
599    /// Selecting it would use this copy, of this version.
600    Selectable {
601        /// The copy's executable.
602        path: PathBuf,
603        /// Its version.
604        version: Version,
605    },
606    /// No copy was found: none installed, or no Visual Studio for cl.
607    NotFound,
608    /// Copies were found and none can be used, for this reason (too old, a
609    /// preview, another target).
610    Unusable(ToolchainError),
611    /// The copy written in `[toolchain.paths]` (or the Visual Studio in
612    /// `[toolchain.paths] msvc`) cannot be used. Unlike [`Self::Unusable`],
613    /// this is the user's own setting that is wrong, which is a problem
614    /// even for a compiler not in use (`docs/en/specs/commands.md`, "`cuno
615    /// doctor`").
616    ConfiguredUnusable(ToolchainError),
617}
618
619/// Each compiler `detected` looked for, except `except`, with whether
620/// selecting it would succeed. Each is judged as [`copy_of`] judges it.
621/// Only cuno's minimum applies, since `[toolchain.version]` constrains the
622/// compiler in use and not the others. When `vs_reported`, selection has
623/// already reported the Visual Studio in `[toolchain.paths] msvc` as
624/// unusable, and cl is left out rather than reported again.
625pub fn survey(
626    detected: &Detected,
627    found: Found<'_>,
628    except: Option<CompilerKind>,
629    vs_reported: bool,
630    host: HostOs,
631) -> Vec<(CompilerKind, Availability)> {
632    CompilerKind::ALL
633        .into_iter()
634        .filter(|&kind| Some(kind) != except && detected.looked_for(kind))
635        .filter_map(|kind| {
636            let availability = match copy_of(kind, found, &Constraints::default(), host) {
637                Ok((path, version, _)) => Availability::Selectable { path, version },
638                Err(ToolchainError::VisualStudioNotAt { .. }) if vs_reported => return None,
639                // Both name a setting the user wrote.
640                Err(
641                    error @ (ToolchainError::ConfiguredToolUnusable { .. }
642                    | ToolchainError::VisualStudioNotAt { .. }),
643                ) => Availability::ConfiguredUnusable(error),
644                // cl is found through Visual Studio: none installed is cl
645                // not found.
646                Err(ToolchainError::CompilerNotFound { .. } | ToolchainError::NoVisualStudio) => {
647                    Availability::NotFound
648                }
649                Err(error) => Availability::Unusable(error),
650            };
651            Some((kind, availability))
652        })
653        .collect()
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use crate::llvm::Origin;
660
661    fn v(major: u32, minor: u32, patch: u32) -> Version {
662        Version {
663            major,
664            minor,
665            patch,
666        }
667    }
668
669    fn install(path: &str, toolsets: &[Version]) -> VsInstallation {
670        VsInstallation {
671            path: path.into(),
672            prerelease: false,
673            complete: true,
674            toolsets: toolsets
675                .iter()
676                .map(|v| MsvcToolset {
677                    dir: Path::new(path).join(format!("VC/Tools/MSVC/{v}")),
678                    cl_version: *v,
679                })
680                .collect(),
681            unusable_toolsets: Vec::new(),
682            default_toolset: None,
683        }
684    }
685
686    fn tool(tool: Tool, path: &str, probe: Probe) -> LlvmTool {
687        LlvmTool {
688            tool,
689            path: path.into(),
690            probe,
691            origin: Origin::Path,
692        }
693    }
694
695    fn ran(version: Version, prerelease: bool, target: Option<&str>) -> Probe {
696        Probe::Ran {
697            version,
698            prerelease,
699            target: target.map(Into::into),
700        }
701    }
702
703    fn clang(kind: Tool, path: &str, version: Version) -> LlvmTool {
704        tool(kind, path, ran(version, false, Some(MSVC_TARGET)))
705    }
706
707    const MSVC_TARGET: &str = "x86_64-pc-windows-msvc";
708
709    fn found<'a>(installs: &'a [VsInstallation], llvm: &'a [LlvmTool]) -> Found<'a> {
710        Found {
711            installs,
712            llvm,
713            gcc: &[],
714            explicit_msvc: None,
715        }
716    }
717
718    fn asking(name: &str) -> Choices {
719        Choices {
720            cli: Some(name.to_owned()),
721            ..Default::default()
722        }
723    }
724
725    fn pick(
726        choices: &Choices,
727        found: Found<'_>,
728        constraints: &Constraints,
729    ) -> Result<Selected, ToolchainError> {
730        select(choices, found, constraints, HostOs::Windows)
731    }
732
733    /// Mutation: swap any two levels of the precedence; this test fails.
734    #[test]
735    fn each_level_beats_every_level_below_it() {
736        let installs = [install("VS", &[v(19, 52, 1)])];
737        let llvm = [
738            clang(Tool::Clang, "clang", v(22, 1, 8)),
739            clang(Tool::ClangCl, "clang-cl", v(22, 1, 8)),
740        ];
741        // Each level names a different compiler than the level below it;
742        // whichever wins tells which level won.
743        let levels = ["clang", "clang-cl", "msvc", "clang", "clang-cl"];
744        let sources = [
745            Source::CommandLine,
746            Source::Environment,
747            Source::ProjectConfig,
748            Source::Manifest,
749            Source::UserConfig,
750        ];
751        for top in 0..=levels.len() {
752            let given = |i: usize| (i >= top).then(|| levels[i].to_owned());
753            let choices = Choices {
754                cli: given(0),
755                env: given(1),
756                project: Some(ProjectChoices {
757                    config: given(2),
758                    manifest: given(3),
759                }),
760                user: given(4),
761            };
762            let selected =
763                pick(&choices, found(&installs, &llvm), &Constraints::default()).unwrap();
764            if top < levels.len() {
765                assert_eq!(selected.source, sources[top]);
766                assert_eq!(selected.kind.name(), levels[top]);
767                assert_eq!(
768                    selected.executable.file_name().unwrap(),
769                    if levels[top] == "msvc" {
770                        "cl.exe"
771                    } else {
772                        levels[top]
773                    }
774                );
775            } else {
776                assert_eq!(selected.source, Source::Automatic);
777                assert_eq!(selected.kind, CompilerKind::Msvc);
778            }
779        }
780    }
781
782    /// Outside a project the project's layers cannot be given (`Choices`
783    /// has no place for them), so the user-level choice comes right after
784    /// `CUNO_COMPILER`.
785    ///
786    /// Mutation: drop the user-level layer; this test fails.
787    #[test]
788    fn outside_a_project_the_user_config_is_next_after_the_environment() {
789        let installs = [install("VS", &[v(19, 52, 1)])];
790        let llvm = [clang(Tool::Clang, "clang", v(22, 1, 8))];
791        let choices = Choices {
792            user: Some("clang".to_owned()),
793            ..Default::default()
794        };
795        let selected = pick(&choices, found(&installs, &llvm), &Constraints::default()).unwrap();
796        assert_eq!(
797            (selected.kind, selected.source),
798            (CompilerKind::Clang, Source::UserConfig)
799        );
800    }
801
802    /// Mutation: change what any source is called, or fall back to
803    /// automatic selection for `gcc`, `safec` or an unknown name, or report
804    /// another source than the one that named it; this test fails.
805    #[test]
806    fn unsupported_and_unknown_names_are_errors_naming_their_source() {
807        let installs = [install("VS", &[v(19, 52, 1)])];
808        let names = [
809            (Source::CommandLine, "--compiler"),
810            (Source::Environment, "CUNO_COMPILER"),
811            (Source::ProjectConfig, "compiler in .cuno/config.toml"),
812            (Source::Manifest, "[toolchain] compiler in Cuno.toml"),
813            (Source::UserConfig, "compiler in the user-level config.toml"),
814            (Source::Automatic, "automatic selection"),
815        ];
816        for (source, text) in names {
817            assert_eq!(source.to_string(), text);
818        }
819        for (choices, text) in [
820            (asking("safec"), "--compiler"),
821            (
822                Choices {
823                    env: Some("safec".into()),
824                    ..Default::default()
825                },
826                "CUNO_COMPILER",
827            ),
828            (
829                Choices {
830                    project: Some(ProjectChoices {
831                        config: None,
832                        manifest: Some("nope".into()),
833                    }),
834                    ..Default::default()
835                },
836                "[toolchain] compiler in Cuno.toml",
837            ),
838        ] {
839            let err = pick(&choices, found(&installs, &[]), &Constraints::default()).unwrap_err();
840            match &err {
841                ToolchainError::UnsupportedCompiler { source, .. }
842                | ToolchainError::UnknownCompiler { source, .. } => assert_eq!(source, text),
843                _ => panic!("{err:?}"),
844            }
845            assert_eq!(
846                matches!(err, ToolchainError::UnknownCompiler { .. }),
847                text.contains("Cuno.toml")
848            );
849        }
850    }
851
852    /// Mutation: include previews or incomplete installations, take the
853    /// oldest, or ignore the upper bound; this test fails.
854    #[test]
855    fn the_newest_satisfying_release_is_chosen() {
856        let mut preview = install("Preview", &[v(19, 44, 1)]);
857        preview.prerelease = true;
858        let mut incomplete = install("Incomplete", &[v(19, 45, 1)]);
859        incomplete.complete = false;
860        let installs = [
861            install("VS", &[v(19, 40, 1), v(19, 52, 1)]),
862            preview,
863            incomplete,
864        ];
865        let constraints = Constraints {
866            msvc: Some(VersionReq::parse("msvc", ">=19.29, <19.50").unwrap()),
867            ..Default::default()
868        };
869        let selected = pick(&Choices::default(), found(&installs, &[]), &constraints).unwrap();
870        assert_eq!(selected.version, v(19, 40, 1));
871        let selected = pick(
872            &Choices::default(),
873            found(&installs[1..], &[]),
874            &Constraints::default(),
875        );
876        assert!(
877            matches!(selected, Err(ToolchainError::NoVisualStudio)),
878            "{selected:?}"
879        );
880    }
881
882    /// Mutation: accept a preview, a MinGW Clang or one that reports no
883    /// target, take the last of equal versions, or give Clang another
884    /// toolset than MSVC would use; this test fails.
885    #[test]
886    fn only_msvc_targeting_clang_releases_are_eligible() {
887        let installs = [install("A", &[v(19, 52, 1)]), install("B", &[v(19, 52, 1)])];
888        let llvm = [
889            clang(Tool::Clang, "old", v(18, 1, 0)),
890            tool(Tool::Clang, "rc", ran(v(23, 0, 0), true, Some(MSVC_TARGET))),
891            tool(
892                Tool::Clang,
893                "mingw",
894                ran(v(22, 5, 0), false, Some("x86_64-w64-windows-gnu")),
895            ),
896            tool(Tool::Clang, "untargeted", ran(v(22, 4, 0), false, None)),
897            clang(Tool::Clang, "new", v(22, 1, 8)),
898            clang(Tool::Clang, "same", v(22, 1, 8)),
899        ];
900        let selected = pick(
901            &asking("clang"),
902            found(&installs, &llvm),
903            &Constraints::default(),
904        )
905        .unwrap();
906        assert_eq!(selected.executable, PathBuf::from("new"));
907        let msvc = pick(
908            &asking("msvc"),
909            found(&installs, &llvm),
910            &Constraints::default(),
911        )
912        .unwrap();
913        assert_eq!(selected.msvc, msvc.msvc);
914        assert!(msvc.msvc.unwrap().dir.starts_with("A"));
915    }
916
917    /// Mutation: report "not found" when copies were found but none is
918    /// eligible, or drop why each was left out; this test fails.
919    #[test]
920    fn ineligible_copies_are_named_with_why() {
921        let installs = [install("VS", &[v(19, 52, 1)])];
922        let llvm = [
923            tool(Tool::Clang, "rc", ran(v(23, 0, 0), true, Some(MSVC_TARGET))),
924            tool(
925                Tool::Clang,
926                "mingw",
927                ran(v(22, 5, 0), false, Some("x86_64-w64-windows-gnu")),
928            ),
929            tool(Tool::Clang, "untargeted", ran(v(22, 4, 0), false, None)),
930            tool(Tool::Clang, "broken", Probe::Failed),
931            tool(Tool::Clang, "silent", Probe::NoVersion),
932        ];
933        let err = pick(
934            &asking("clang"),
935            found(&installs, &llvm),
936            &Constraints::default(),
937        )
938        .unwrap_err();
939        let ToolchainError::NoUsableCompiler { excluded, .. } = &err else {
940            panic!("{err:?}");
941        };
942        assert_eq!(
943            *excluded,
944            [
945                "rc (23.0.0 is a preview)",
946                "mingw (it targets x86_64-w64-windows-gnu, not MSVC)",
947                "untargeted (it reports no target)",
948                "broken (it did not run)",
949                "silent (it printed no version)",
950            ]
951        );
952        let err = pick(
953            &asking("clang"),
954            found(&installs, &[]),
955            &Constraints::default(),
956        )
957        .unwrap_err();
958        assert!(
959            matches!(err, ToolchainError::CompilerNotFound { compiler: "clang" }),
960            "{err:?}"
961        );
962    }
963
964    /// Mutation: change or drop any compiler's minimum, accept below it, or
965    /// reject the minimum itself; this test fails.
966    #[test]
967    fn each_compiler_starts_at_its_minimum() {
968        for (kind, below, at) in [
969            ("msvc", v(19, 28, 99), v(19, 29, 0)),
970            ("clang", v(16, 9, 9), v(17, 0, 0)),
971            ("clang-cl", v(16, 9, 9), v(17, 0, 0)),
972        ] {
973            for (version, ok) in [(below, false), (at, true)] {
974                let installs = [install(
975                    "VS",
976                    &[if kind == "msvc" {
977                        version
978                    } else {
979                        v(19, 52, 1)
980                    }],
981                )];
982                let llvm = [
983                    clang(Tool::Clang, "clang", version),
984                    clang(Tool::ClangCl, "clang-cl", version),
985                ];
986                let result = pick(
987                    &asking(kind),
988                    found(&installs, &llvm),
989                    &Constraints::default(),
990                );
991                match result {
992                    Ok(_) => assert!(ok, "{kind} {version} accepted"),
993                    Err(ToolchainError::NoMatchingVersion { found, .. }) => {
994                        assert!(!ok, "{kind} {version} rejected");
995                        assert_eq!(found, [version]);
996                    }
997                    Err(e) => panic!("{kind} {version}: {e:?}"),
998                }
999            }
1000        }
1001    }
1002
1003    /// Mutation: apply one compiler's `[toolchain.version]` to another, or
1004    /// leave the user's requirement out of the error; this test fails.
1005    #[test]
1006    fn each_requirement_is_its_own_compilers() {
1007        let installs = [install("VS", &[v(19, 52, 1)])];
1008        let llvm = [
1009            clang(Tool::Clang, "clang-old", v(18, 1, 0)),
1010            clang(Tool::Clang, "clang-new", v(22, 1, 8)),
1011            clang(Tool::ClangCl, "cl-old", v(18, 1, 0)),
1012            clang(Tool::ClangCl, "cl-new", v(22, 1, 8)),
1013        ];
1014        let below_22 = || Some(VersionReq::parse("x", "<22").unwrap());
1015        for (kind, constraints) in [
1016            (
1017                "clang",
1018                Constraints {
1019                    clang: below_22(),
1020                    ..Default::default()
1021                },
1022            ),
1023            (
1024                "clang-cl",
1025                Constraints {
1026                    clang_cl: below_22(),
1027                    ..Default::default()
1028                },
1029            ),
1030            (
1031                "msvc",
1032                Constraints {
1033                    msvc: Some(VersionReq::parse("msvc", "<19.50").unwrap()),
1034                    ..Default::default()
1035                },
1036            ),
1037        ] {
1038            let constrained = pick(&asking(kind), found(&installs, &llvm), &constraints);
1039            let others: Vec<_> = ["clang", "clang-cl"]
1040                .into_iter()
1041                .filter(|other| *other != kind)
1042                .map(|other| pick(&asking(other), found(&installs, &llvm), &constraints).unwrap())
1043                .collect();
1044            for other in others {
1045                assert_eq!(other.version, v(22, 1, 8), "{kind} constrained {other:?}");
1046            }
1047            if kind == "msvc" {
1048                let err = constrained.unwrap_err();
1049                assert_eq!(
1050                    err.to_string(),
1051                    "no msvc found satisfies >=19.29.0 (cuno's minimum) and <19.50 ([toolchain.version] msvc); found 19.52.1"
1052                );
1053            } else {
1054                assert_eq!(constrained.unwrap().version, v(18, 1, 0), "{kind}");
1055            }
1056        }
1057    }
1058
1059    /// Mutation: choose Clang without a Visual Studio, ignore
1060    /// `[toolchain.paths] msvc`, or compare it as written rather than as the
1061    /// same directory; this test fails.
1062    #[test]
1063    fn visual_studio_is_required_and_paths_msvc_limits_it() {
1064        let llvm = [clang(Tool::Clang, "clang", v(22, 1, 8))];
1065        let err = pick(&asking("clang"), found(&[], &llvm), &Constraints::default()).unwrap_err();
1066        assert!(matches!(err, ToolchainError::NoVisualStudio), "{err:?}");
1067
1068        let root = tempfile::tempdir().unwrap();
1069        for dir in ["A", "B"] {
1070            std::fs::create_dir(root.path().join(dir)).unwrap();
1071        }
1072        let installs = [
1073            install(root.path().join("A").to_str().unwrap(), &[v(19, 52, 1)]),
1074            install(root.path().join("B").to_str().unwrap(), &[v(19, 40, 1)]),
1075        ];
1076        let with = |dir: &Path| {
1077            pick(
1078                &Choices::default(),
1079                Found {
1080                    installs: &installs,
1081                    llvm: &[],
1082                    gcc: &[],
1083                    explicit_msvc: Some(dir),
1084                },
1085                &Constraints::default(),
1086            )
1087        };
1088        let spelled_otherwise = root.path().join("A").join("..").join("B");
1089        assert_eq!(with(&spelled_otherwise).unwrap().version, v(19, 40, 1));
1090        let err = with(&root.path().join("C")).unwrap_err();
1091        assert!(
1092            matches!(err, ToolchainError::VisualStudioNotAt { .. }),
1093            "{err:?}"
1094        );
1095    }
1096
1097    /// Mutation: elsewhere than on Windows, select a default other than the
1098    /// unsupported GCC, accept MSVC, or require Visual Studio or an MSVC
1099    /// target for Clang; this test fails.
1100    #[test]
1101    fn other_hosts_need_no_visual_studio_and_have_no_msvc() {
1102        let other = |choices: &Choices, llvm: &[LlvmTool]| {
1103            select(
1104                choices,
1105                found(&[], llvm),
1106                &Constraints::default(),
1107                HostOs::Other,
1108            )
1109        };
1110        let err = other(&Choices::default(), &[]).unwrap_err();
1111        assert!(
1112            matches!(&err, ToolchainError::UnsupportedCompiler { name, source } if name == "gcc" && source == "automatic selection"),
1113            "{err:?}"
1114        );
1115        let err = other(&asking("msvc"), &[]).unwrap_err();
1116        assert!(matches!(err, ToolchainError::NoVisualStudio), "{err:?}");
1117        let llvm = [tool(
1118            Tool::Clang,
1119            "clang",
1120            ran(v(22, 1, 8), false, Some("x86_64-pc-linux-gnu")),
1121        )];
1122        let selected = other(&asking("clang"), &llvm).unwrap();
1123        assert_eq!((selected.version, selected.msvc), (v(22, 1, 8), None));
1124    }
1125
1126    /// Mutation: compare every component instead of only those written, or
1127    /// treat `>` as `>=` or `=` as `>=`; this test fails.
1128    #[test]
1129    fn requirements_compare_only_the_components_written() {
1130        let req = |text| VersionReq::parse("msvc", text).unwrap();
1131        assert!(req("=19.40").matches(&v(19, 40, 33811)));
1132        assert!(!req("=19.40").matches(&v(19, 41, 0)));
1133        assert!(!req("=19.40").matches(&v(19, 39, 9)));
1134        assert!(req(">=17").matches(&v(17, 0, 6)));
1135        assert!(!req("<19").matches(&v(19, 1, 0)));
1136        assert!(!req(">19.40").matches(&v(19, 40, 9)));
1137        assert!(req(">19.40").matches(&v(19, 41, 0)));
1138        assert!(req("<= 19.40, >=19.29").matches(&v(19, 40, 99)));
1139        assert_eq!(req(">=17, <19").to_string(), ">=17, <19");
1140        for bad in ["19", "~19", ">=", ">=a.b", ">=1.2.3.4", ">=17,", ""] {
1141            assert!(
1142                matches!(
1143                    VersionReq::parse("msvc", bad),
1144                    Err(ToolchainError::InvalidVersionRequirement { .. })
1145                ),
1146                "{bad}"
1147            );
1148        }
1149    }
1150
1151    /// MSVC keeps the toolset of the cl selected, even when
1152    /// `[toolchain.version]` leaves out a newer one; a Clang gets the newest.
1153    ///
1154    /// Mutation: give MSVC the newest toolset instead of its own, or a Clang
1155    /// none; this test fails.
1156    #[test]
1157    fn msvc_keeps_its_own_toolset_and_clang_gets_the_newest() {
1158        let installs = [install("VS", &[v(19, 44, 1), v(19, 52, 1)])];
1159        let llvm = [clang(Tool::Clang, "clang", v(22, 1, 8))];
1160        let older = Constraints {
1161            msvc: Some(VersionReq::parse("msvc", "<19.50").unwrap()),
1162            ..Default::default()
1163        };
1164        let msvc = pick(&asking("msvc"), found(&installs, &llvm), &older).unwrap();
1165        assert_eq!(msvc.version, v(19, 44, 1));
1166        let toolset = msvc.msvc.unwrap();
1167        assert_eq!(
1168            (toolset.cl_version, toolset.cl()),
1169            (v(19, 44, 1), msvc.executable)
1170        );
1171
1172        let clang = pick(&asking("clang"), found(&installs, &llvm), &older).unwrap();
1173        assert_eq!(clang.msvc.unwrap().cl_version, v(19, 52, 1));
1174    }
1175
1176    /// `copy_of` answers a Clang without Visual Studio (doctor's `Info`
1177    /// lines need it when Visual Studio is missing), holds every copy to
1178    /// cuno's minimum and to the constraints passed, and gives MSVC its own
1179    /// toolset; `Choices::kind` names the kind asked for even when its
1180    /// selection would fail.
1181    ///
1182    /// Mutation: require Visual Studio for a Clang in `copy_of`, drop cuno's
1183    /// minimum or the constraints, or make `kind` fail when selection would;
1184    /// this test fails.
1185    #[test]
1186    fn copy_of_is_the_answer_selection_and_doctor_share() {
1187        let none = Constraints::default();
1188        let llvm = [clang(Tool::Clang, "found", v(22, 1, 8))];
1189        let without_vs = found(&[], &llvm);
1190        assert_eq!(
1191            copy_of(CompilerKind::Clang, without_vs, &none, HostOs::Windows).unwrap(),
1192            (PathBuf::from("found"), v(22, 1, 8), None)
1193        );
1194        assert!(matches!(
1195            copy_of(CompilerKind::Msvc, without_vs, &none, HostOs::Windows),
1196            Err(ToolchainError::NoVisualStudio)
1197        ));
1198
1199        let old = [clang(Tool::Clang, "old", v(16, 0, 6))];
1200        assert!(matches!(
1201            copy_of(
1202                CompilerKind::Clang,
1203                found(&[], &old),
1204                &none,
1205                HostOs::Windows
1206            ),
1207            Err(ToolchainError::NoMatchingVersion { .. })
1208        ));
1209        let required = Constraints {
1210            clang: Some(VersionReq::parse("clang", ">=30").unwrap()),
1211            ..Default::default()
1212        };
1213        assert!(matches!(
1214            copy_of(CompilerKind::Clang, without_vs, &required, HostOs::Windows),
1215            Err(ToolchainError::NoMatchingVersion { .. })
1216        ));
1217
1218        let installs = [install("VS", &[v(19, 44, 1), v(19, 52, 1)])];
1219        let (cl, version, toolset) = copy_of(
1220            CompilerKind::Msvc,
1221            found(&installs, &[]),
1222            &none,
1223            HostOs::Windows,
1224        )
1225        .unwrap();
1226        assert_eq!(version, v(19, 52, 1));
1227        assert_eq!(toolset.unwrap().cl(), cl);
1228
1229        // Asked for clang with no Visual Studio: selection fails, the kind
1230        // asked for is still clang.
1231        assert!(pick(&asking("clang"), without_vs, &none).is_err());
1232        assert_eq!(
1233            asking("clang").kind(HostOs::Windows).unwrap(),
1234            (CompilerKind::Clang, Source::CommandLine)
1235        );
1236        assert_eq!(
1237            Choices::default().kind(HostOs::Windows).unwrap(),
1238            (CompilerKind::Msvc, Source::Automatic)
1239        );
1240    }
1241
1242    /// A configured clang or clang-cl is the only copy selection takes, with
1243    /// the MSVC toolset every Clang gets: an older one wins over a newer copy
1244    /// found, and one that cannot be used, or does not satisfy the version
1245    /// requirements, is an error naming its own setting rather than a reason
1246    /// to take another. A copy configured for the other driver plays no part.
1247    ///
1248    /// Mutation: let a newer copy found win over the configured one, fall
1249    /// back to another copy when the configured one is unusable, select it
1250    /// without a toolset, name another setting, or let a configured copy of
1251    /// the other driver count; this test fails.
1252    #[test]
1253    fn a_configured_compiler_is_the_only_one_selected() {
1254        let installs = [install("VS", &[v(19, 52, 1)])];
1255        let toolset = installs[0].toolsets[0].clone();
1256        let none = Constraints::default();
1257        for (kind, driver, other) in [
1258            (CompilerKind::Clang, Tool::Clang, Tool::ClangCl),
1259            (CompilerKind::ClangCl, Tool::ClangCl, Tool::Clang),
1260        ] {
1261            let name = kind.name();
1262            let mine = |probe| LlvmTool {
1263                origin: Origin::Configured,
1264                ..tool(driver, "mine", probe)
1265            };
1266            let newer = clang(driver, "found", v(22, 1, 8));
1267            let pick_with = |llvm: &[LlvmTool], constraints: &Constraints| {
1268                pick(&asking(name), found(&installs, llvm), constraints)
1269            };
1270
1271            let older = [
1272                mine(ran(v(19, 1, 0), false, Some(MSVC_TARGET))),
1273                newer.clone(),
1274            ];
1275            let selected = pick_with(&older, &none).unwrap();
1276            assert_eq!(
1277                selected,
1278                Selected {
1279                    kind,
1280                    executable: "mine".into(),
1281                    version: v(19, 1, 0),
1282                    msvc: Some(toolset.clone()),
1283                    source: Source::CommandLine,
1284                }
1285            );
1286
1287            // A broken copy configured for the other driver is not this
1288            // one's: the newest found is selected.
1289            let elsewhere = [
1290                LlvmTool {
1291                    origin: Origin::Configured,
1292                    ..tool(other, "theirs", Probe::Failed)
1293                },
1294                newer.clone(),
1295            ];
1296            assert_eq!(
1297                pick_with(&elsewhere, &none).unwrap().executable,
1298                PathBuf::from("found")
1299            );
1300            // ... and when the copy found fails the requirements, the error
1301            // is about it, not about the other driver's setting.
1302            let mut unmet = Constraints::default();
1303            let req = Some(VersionReq::parse(name, ">=30").unwrap());
1304            match kind {
1305                CompilerKind::Clang => unmet.clang = req,
1306                _ => unmet.clang_cl = req,
1307            }
1308            assert!(
1309                matches!(
1310                    pick_with(&elsewhere, &unmet),
1311                    Err(ToolchainError::NoMatchingVersion { .. })
1312                ),
1313                "{kind:?}"
1314            );
1315
1316            let mut required = Constraints::default();
1317            let req = Some(VersionReq::parse(name, ">=20").unwrap());
1318            match kind {
1319                CompilerKind::Clang => required.clang = req,
1320                _ => required.clang_cl = req,
1321            }
1322            let cases: [(LlvmTool, &Constraints, String); 4] = [
1323                (mine(Probe::Failed), &none, "it did not run".into()),
1324                (
1325                    mine(ran(v(22, 1, 0), false, Some("x86_64-w64-windows-gnu"))),
1326                    &none,
1327                    "it targets x86_64-w64-windows-gnu, not MSVC".into(),
1328                ),
1329                (
1330                    mine(ran(v(16, 0, 0), false, Some(MSVC_TARGET))),
1331                    &none,
1332                    "16.0.0 does not satisfy >=17.0.0 (cuno's minimum)".into(),
1333                ),
1334                (
1335                    mine(ran(v(19, 1, 0), false, Some(MSVC_TARGET))),
1336                    &required,
1337                    format!(
1338                        "19.1.0 does not satisfy >=17.0.0 (cuno's minimum) and >=20 ([toolchain.version] {name})"
1339                    ),
1340                ),
1341            ];
1342            for (configured, constraints, why) in cases {
1343                let err = pick_with(&[configured, newer.clone()], constraints).unwrap_err();
1344                assert_eq!(
1345                    err.to_string(),
1346                    format!("[toolchain.paths] {name} is mine, but {why}")
1347                );
1348            }
1349        }
1350    }
1351
1352    /// clang-format and clang-tidy below 17 are not used: a found one is
1353    /// passed over for a newer, and a configured one is an error saying so
1354    /// (`dev-tools.md`, "Tool versions").
1355    ///
1356    /// Mutation: drop the minimum, or apply it to one tool only; this test
1357    /// fails.
1358    #[test]
1359    fn llvm_tools_below_17_are_not_used() {
1360        for kind in [Tool::ClangFormat, Tool::ClangTidy] {
1361            let old = tool(kind, "old", ran(v(16, 0, 6), false, None));
1362            let new = tool(kind, "new", ran(v(17, 0, 1), false, None));
1363            assert_eq!(
1364                select_tool(kind, &[old.clone(), new], HostOs::Windows)
1365                    .unwrap()
1366                    .path,
1367                PathBuf::from("new")
1368            );
1369            assert!(select_tool(kind, std::slice::from_ref(&old), HostOs::Windows).is_err());
1370            let configured = LlvmTool {
1371                origin: Origin::Configured,
1372                ..old
1373            };
1374            let err = select_tool(kind, &[configured], HostOs::Windows).unwrap_err();
1375            assert!(
1376                err.to_string()
1377                    .ends_with("16.0.6 does not satisfy >=17.0.0 (cuno's minimum)"),
1378                "{err}"
1379            );
1380        }
1381    }
1382
1383    /// A configured copy is the only one used, even when older, and is an
1384    /// error naming the setting when it cannot be used; a Clang must target
1385    /// MSVC.
1386    ///
1387    /// Mutation: let a newer found copy win over the configured one, fall
1388    /// back to another copy when the configured one did not run, or drop the
1389    /// MSVC-target rule for clang; this test fails.
1390    #[test]
1391    fn a_configured_tool_is_used_or_is_an_error() {
1392        let configured = |probe| LlvmTool {
1393            origin: Origin::Configured,
1394            ..tool(Tool::ClangTidy, "mine", probe)
1395        };
1396        let newer = tool(Tool::ClangTidy, "found", ran(v(22, 1, 8), false, None));
1397        let llvm = [configured(ran(v(19, 1, 0), false, None)), newer.clone()];
1398        assert_eq!(
1399            select_tool(Tool::ClangTidy, &llvm, HostOs::Windows).unwrap(),
1400            LlvmChoice {
1401                path: "mine".into(),
1402                version: v(19, 1, 0)
1403            }
1404        );
1405        let llvm = [configured(Probe::Failed), newer];
1406        let err = select_tool(Tool::ClangTidy, &llvm, HostOs::Windows).unwrap_err();
1407        assert_eq!(
1408            err.to_string(),
1409            "[toolchain.paths] clang-tidy is mine, but it did not run"
1410        );
1411        assert_eq!(
1412            cuno_core::CunoError::help(&err).unwrap(),
1413            "correct [toolchain.paths] clang-tidy, or remove it to let cuno find the tool"
1414        );
1415
1416        let clangs = [
1417            tool(
1418                Tool::Clang,
1419                "mingw",
1420                ran(v(23, 1, 0), false, Some("x86_64-w64-windows-gnu")),
1421            ),
1422            clang(Tool::Clang, "msvc", v(22, 1, 8)),
1423        ];
1424        assert_eq!(
1425            select_tool(Tool::Clang, &clangs, HostOs::Windows)
1426                .unwrap()
1427                .path,
1428            PathBuf::from("msvc")
1429        );
1430    }
1431
1432    /// Mutation: pick the first copy rather than the newest, accept a preview
1433    /// or a copy that did not run, demand an MSVC target of clang-tidy (it
1434    /// prints none), or say "not found" when copies were left out; this test
1435    /// fails.
1436    #[test]
1437    fn the_newest_release_of_a_tool_is_used() {
1438        let llvm = [
1439            tool(Tool::ClangTidy, "old", ran(v(19, 1, 0), false, None)),
1440            tool(Tool::ClangTidy, "new", ran(v(22, 1, 8), false, None)),
1441            tool(Tool::ClangTidy, "preview", ran(v(23, 0, 0), true, None)),
1442            tool(Tool::ClangTidy, "broken", Probe::Failed),
1443            tool(Tool::ClangFormat, "format", ran(v(18, 1, 0), false, None)),
1444        ];
1445        assert_eq!(
1446            select_tool(Tool::ClangTidy, &llvm, HostOs::Windows).unwrap(),
1447            LlvmChoice {
1448                path: "new".into(),
1449                version: v(22, 1, 8)
1450            }
1451        );
1452        assert!(matches!(
1453            select_tool(Tool::Clang, &llvm, HostOs::Windows),
1454            Err(ToolchainError::CompilerNotFound { compiler: "clang" })
1455        ));
1456        let unusable = [
1457            tool(Tool::ClangFormat, "preview", ran(v(23, 0, 0), true, None)),
1458            tool(Tool::ClangFormat, "silent", Probe::NoVersion),
1459            tool(Tool::ClangFormat, "broken", Probe::Failed),
1460        ];
1461        let err = select_tool(Tool::ClangFormat, &unusable, HostOs::Windows).unwrap_err();
1462        assert_eq!(
1463            err.to_string(),
1464            "no usable clang-format was found; left out: preview (23.0.0 is a preview); \
1465             silent (it printed no version); broken (it did not run)"
1466        );
1467    }
1468
1469    fn gcc(path: &str, probe: GccProbe, origin: GccOrigin) -> Gcc {
1470        Gcc {
1471            path: path.into(),
1472            probe,
1473            origin,
1474        }
1475    }
1476
1477    fn gcc_ran(version: Version, target: &str, ucrt: bool) -> GccProbe {
1478        GccProbe::Ran {
1479            version,
1480            prerelease: false,
1481            target: Some(target.to_owned()),
1482            ucrt,
1483        }
1484    }
1485
1486    fn with_gcc(gcc: &[Gcc]) -> Found<'_> {
1487        Found {
1488            installs: &[],
1489            llvm: &[],
1490            gcc,
1491            explicit_msvc: None,
1492        }
1493    }
1494
1495    const MINGW: &str = "x86_64-w64-mingw32";
1496
1497    /// GCC needs no Visual Studio. Of the copies found, the newest that
1498    /// ran, is a release, targets `x86_64-w64-mingw32`, links UCRT and
1499    /// meets cuno's minimum and `[toolchain.version] gcc` is chosen; each
1500    /// other copy is left out with why, the reasons in the error when none
1501    /// is left.
1502    ///
1503    /// Mutation: take a preview, an MSVCRT, i686 or Linux GCC, one older
1504    /// than 10, the oldest, ignore `[toolchain.version] gcc`, or require
1505    /// Visual Studio; this test fails.
1506    #[test]
1507    fn the_newest_usable_ucrt_gcc_is_chosen() {
1508        let mut preview = gcc_ran(v(17, 0, 0), MINGW, true);
1509        if let GccProbe::Ran { prerelease, .. } = &mut preview {
1510            *prerelease = true;
1511        }
1512        let copies = [
1513            gcc("old", gcc_ran(v(9, 5, 0), MINGW, true), GccOrigin::Path),
1514            gcc("ucrt13", gcc_ran(v(13, 2, 0), MINGW, true), GccOrigin::Path),
1515            gcc(
1516                "ucrt14",
1517                gcc_ran(v(14, 2, 0), MINGW, true),
1518                GccOrigin::Msys2,
1519            ),
1520            gcc(
1521                "msvcrt",
1522                gcc_ran(v(16, 0, 0), MINGW, false),
1523                GccOrigin::Msys2,
1524            ),
1525            gcc(
1526                "i686",
1527                gcc_ran(v(16, 0, 0), "i686-w64-mingw32", true),
1528                GccOrigin::Path,
1529            ),
1530            gcc(
1531                "linux",
1532                gcc_ran(v(16, 0, 0), "x86_64-linux-gnu", true),
1533                GccOrigin::Path,
1534            ),
1535            gcc("preview", preview, GccOrigin::Path),
1536            gcc("broken", GccProbe::Failed, GccOrigin::Path),
1537        ];
1538        let selected = pick(&asking("gcc"), with_gcc(&copies), &Constraints::default()).unwrap();
1539        assert_eq!(
1540            (
1541                selected.kind,
1542                selected.executable,
1543                selected.version,
1544                selected.msvc
1545            ),
1546            (
1547                CompilerKind::Gcc,
1548                PathBuf::from("ucrt14"),
1549                v(14, 2, 0),
1550                None
1551            )
1552        );
1553        let pinned = Constraints {
1554            gcc: Some(VersionReq::parse("gcc", "<14").unwrap()),
1555            ..Constraints::default()
1556        };
1557        let selected = pick(&asking("gcc"), with_gcc(&copies), &pinned).unwrap();
1558        assert_eq!(selected.executable, PathBuf::from("ucrt13"));
1559
1560        let err = pick(
1561            &asking("gcc"),
1562            with_gcc(&copies[3..]),
1563            &Constraints::default(),
1564        )
1565        .unwrap_err();
1566        assert_eq!(
1567            err.to_string(),
1568            "no usable gcc was found; left out: msvcrt (its C runtime is MSVCRT, not UCRT); \
1569             i686 (it targets i686-w64-mingw32, not x86_64-w64-mingw32); \
1570             linux (it targets x86_64-linux-gnu, not x86_64-w64-mingw32); \
1571             preview (17.0.0 is a preview); broken (it did not run)"
1572        );
1573        assert!(matches!(
1574            pick(&asking("gcc"), with_gcc(&[]), &Constraints::default()),
1575            Err(ToolchainError::CompilerNotFound { compiler: "gcc" })
1576        ));
1577        // A GCC older than 10 alone is not enough.
1578        let err = pick(
1579            &asking("gcc"),
1580            with_gcc(&copies[..1]),
1581            &Constraints::default(),
1582        )
1583        .unwrap_err();
1584        assert!(
1585            matches!(
1586                err,
1587                ToolchainError::NoMatchingVersion {
1588                    compiler: "gcc",
1589                    ..
1590                }
1591            ),
1592            "{err:?}"
1593        );
1594    }
1595
1596    /// The GCC written in `[toolchain.paths] gcc` is the only one used: a
1597    /// newer one found elsewhere is not taken, and one that cannot be used
1598    /// is an error naming the setting, never a reason to take another.
1599    ///
1600    /// Mutation: pick the newest copy over the configured one, or fall back
1601    /// to another when it is unusable; this test fails.
1602    #[test]
1603    fn a_configured_gcc_is_the_only_one_used() {
1604        let newer = gcc("newer", gcc_ran(v(15, 1, 0), MINGW, true), GccOrigin::Msys2);
1605        let configured = gcc(
1606            "mine",
1607            gcc_ran(v(13, 2, 0), MINGW, true),
1608            GccOrigin::Configured,
1609        );
1610        let copies = [configured, newer.clone()];
1611        let selected = pick(&asking("gcc"), with_gcc(&copies), &Constraints::default()).unwrap();
1612        assert_eq!(selected.executable, PathBuf::from("mine"));
1613
1614        let msvcrt = gcc(
1615            "mine",
1616            gcc_ran(v(13, 2, 0), MINGW, false),
1617            GccOrigin::Configured,
1618        );
1619        let err = pick(
1620            &asking("gcc"),
1621            with_gcc(&[msvcrt, newer.clone()]),
1622            &Constraints::default(),
1623        )
1624        .unwrap_err();
1625        assert!(
1626            matches!(&err, ToolchainError::ConfiguredToolUnusable { setting, why, .. }
1627                if setting == "[toolchain.paths] gcc" && why == "its C runtime is MSVCRT, not UCRT"),
1628            "{err:?}"
1629        );
1630        let pinned = Constraints {
1631            gcc: Some(VersionReq::parse("gcc", ">=14").unwrap()),
1632            ..Constraints::default()
1633        };
1634        let copies = [
1635            gcc(
1636                "mine",
1637                gcc_ran(v(13, 2, 0), MINGW, true),
1638                GccOrigin::Configured,
1639            ),
1640            newer,
1641        ];
1642        let err = pick(&asking("gcc"), with_gcc(&copies), &pinned).unwrap_err();
1643        assert!(
1644            matches!(&err, ToolchainError::ConfiguredToolUnusable { why, .. } if why.contains("13.2.0 does not satisfy")),
1645            "{err:?}"
1646        );
1647    }
1648
1649    fn detected(llvm: Vec<LlvmTool>, gcc: Option<Vec<Gcc>>) -> Detected {
1650        Detected {
1651            installs: Ok(Vec::new()),
1652            llvm: Ok(llvm),
1653            gcc: gcc.map(Ok),
1654        }
1655    }
1656
1657    /// A configured GCC that cannot be used is the user's setting being
1658    /// wrong, apart from copies that are merely unusable, even when GCC is
1659    /// not the compiler in use.
1660    ///
1661    /// Mutation: map `ConfiguredToolUnusable` to `Unusable`; this test
1662    /// fails.
1663    #[test]
1664    fn a_configured_copy_that_cannot_be_used_is_a_problem() {
1665        let old = gcc(
1666            "C:/old/gcc.exe",
1667            gcc_ran(v(9, 2, 0), GCC_TARGET, true),
1668            GccOrigin::Configured,
1669        );
1670        let detected = detected(Vec::new(), Some(vec![old]));
1671        let others = survey(
1672            &detected,
1673            detected.found(None),
1674            Some(CompilerKind::Msvc),
1675            false,
1676            HostOs::Windows,
1677        );
1678        let gcc = others.iter().find(|(k, _)| *k == CompilerKind::Gcc);
1679        assert!(
1680            matches!(
1681                gcc,
1682                Some((
1683                    _,
1684                    Availability::ConfiguredUnusable(ToolchainError::ConfiguredToolUnusable { .. })
1685                ))
1686            ),
1687            "{others:?}"
1688        );
1689    }
1690
1691    /// The Visual Studio in `[toolchain.paths] msvc` that selection already
1692    /// reported is not reported again; when selection did not report it
1693    /// (another compiler was asked for), it is a problem here.
1694    ///
1695    /// Mutation: drop the `vs_reported` arm; this test fails.
1696    #[test]
1697    fn a_visual_studio_selection_reported_is_left_out() {
1698        let detected = detected(Vec::new(), None);
1699        let nowhere = Path::new("C:/nowhere");
1700        let msvc = |vs_reported| {
1701            survey(
1702                &detected,
1703                detected.found(Some(nowhere)),
1704                Some(CompilerKind::Clang),
1705                vs_reported,
1706                HostOs::Windows,
1707            )
1708            .into_iter()
1709            .find(|(k, _)| *k == CompilerKind::Msvc)
1710        };
1711        assert!(msvc(true).is_none());
1712        assert!(matches!(
1713            msvc(false),
1714            Some((
1715                _,
1716                Availability::ConfiguredUnusable(ToolchainError::VisualStudioNotAt { .. })
1717            ))
1718        ));
1719    }
1720
1721    /// Only what was looked for is surveyed, the compiler excepted is
1722    /// not, and one looked for and not found is `NotFound`.
1723    ///
1724    /// Mutation: keep `except`, or skip the `looked_for` filter; this
1725    /// test fails.
1726    #[test]
1727    fn the_compiler_excepted_and_those_not_searched_have_no_line() {
1728        let llvm = [clang(Tool::Clang, "C:/llvm/clang.exe", v(20, 1, 0))];
1729        let detected = detected(llvm.to_vec(), None);
1730        let others = survey(
1731            &detected,
1732            detected.found(None),
1733            Some(CompilerKind::ClangCl),
1734            false,
1735            HostOs::Windows,
1736        );
1737        let lines: Vec<String> = others
1738            .iter()
1739            .map(|(k, o)| match o {
1740                Availability::Selectable { version, .. } => format!("{} {version}", k.name()),
1741                Availability::NotFound => format!("{} not found", k.name()),
1742                other => format!("{} {other:?}", k.name()),
1743            })
1744            .collect();
1745        assert_eq!(lines, ["msvc not found", "clang 20.1.0"]);
1746    }
1747}