Skip to main content

cuno_toolchain/llvm/
detect.rs

1//! Finding every copy of the LLVM tools cuno uses, in the order the spec
2//! gives, with each copy's version.
3
4use std::ffi::OsStr;
5use std::path::{Path, PathBuf};
6
7use cuno_core::Env;
8
9use crate::msvc::VsInstallation;
10use crate::{HostOs, Runner, ToolchainError, Version};
11
12/// An LLVM tool cuno uses.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Tool {
15    /// `clang` (GNU-style driver).
16    Clang,
17    /// `clang-cl` (MSVC-style driver).
18    ClangCl,
19    /// `clang-format`.
20    ClangFormat,
21    /// `clang-tidy`.
22    ClangTidy,
23}
24
25impl Tool {
26    /// Every tool, in a fixed order.
27    pub const ALL: [Tool; 4] = [
28        Tool::Clang,
29        Tool::ClangCl,
30        Tool::ClangFormat,
31        Tool::ClangTidy,
32    ];
33
34    /// The executable's name without a suffix, which is also its key in
35    /// `[toolchain.paths]`.
36    pub fn name(self) -> &'static str {
37        match self {
38            Tool::Clang => "clang",
39            Tool::ClangCl => "clang-cl",
40            Tool::ClangFormat => "clang-format",
41            Tool::ClangTidy => "clang-tidy",
42        }
43    }
44}
45
46/// Where a copy of a tool was found.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub enum Origin {
49    /// The path written in `[toolchain.paths]`.
50    Configured,
51    /// A directory on `PATH`.
52    Path,
53    /// `%ProgramFiles%\LLVM\bin`.
54    LlvmInstall,
55    /// The Clang bundled with the Visual Studio installed here.
56    VisualStudio(PathBuf),
57}
58
59/// The paths written in `[toolchain.paths]`, as `cuno-manifest` will give
60/// them.
61#[derive(Clone, Debug, Default)]
62pub struct ExplicitPaths {
63    /// `[toolchain.paths] clang`.
64    pub clang: Option<PathBuf>,
65    /// `[toolchain.paths] clang-cl`.
66    pub clang_cl: Option<PathBuf>,
67    /// `[toolchain.paths] clang-format`.
68    pub clang_format: Option<PathBuf>,
69    /// `[toolchain.paths] clang-tidy`.
70    pub clang_tidy: Option<PathBuf>,
71}
72
73impl ExplicitPaths {
74    fn get(&self, tool: Tool) -> Option<&Path> {
75        match tool {
76            Tool::Clang => self.clang.as_deref(),
77            Tool::ClangCl => self.clang_cl.as_deref(),
78            Tool::ClangFormat => self.clang_format.as_deref(),
79            Tool::ClangTidy => self.clang_tidy.as_deref(),
80        }
81    }
82}
83
84/// One copy of an LLVM tool.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct LlvmTool {
87    /// Which tool.
88    pub tool: Tool,
89    /// The executable.
90    pub path: PathBuf,
91    /// What `--version` told about it.
92    pub probe: Probe,
93    /// Where it was found.
94    pub origin: Origin,
95}
96
97/// What running a tool with `--version` told.
98#[derive(Clone, Debug, PartialEq, Eq)]
99pub enum Probe {
100    /// It ran and printed a version.
101    Ran {
102        /// The version on the line with the word `version`.
103        version: Version,
104        /// Whether the version is a pre-release (`19.1.0-rc1`, `23.0.0git`):
105        /// something follows the number in the same word.
106        prerelease: bool,
107        /// The `Target:` it reports, if any (`x86_64-pc-windows-msvc`).
108        target: Option<String>,
109    },
110    /// It ran but printed no version it could be read from.
111    NoVersion,
112    /// It could not be started, or exited with an error.
113    Failed,
114}
115
116impl LlvmTool {
117    /// The version, when `--version` gave one.
118    pub fn version(&self) -> Option<Version> {
119        match &self.probe {
120            Probe::Ran { version, .. } => Some(*version),
121            _ => None,
122        }
123    }
124}
125
126/// Every copy of every tool, in the spec's search order per tool: the
127/// configured path, `PATH`, the LLVM installer's location, then each Visual
128/// Studio's bundled Clang (the last two on Windows only). The same file found
129/// twice is listed once. Not finding a tool is not an error; a configured path
130/// with no file is.
131pub fn find_llvm_tools(
132    env: &Env,
133    host: HostOs,
134    explicit: &ExplicitPaths,
135    installs: &[VsInstallation],
136    run: &dyn Runner,
137) -> Result<Vec<LlvmTool>, ToolchainError> {
138    let mut dirs: Vec<(PathBuf, Origin)> = Vec::new();
139    dirs.extend(env.search_dirs().into_iter().map(|d| (d, Origin::Path)));
140    if host == HostOs::Windows {
141        if let Some(program_files) = env.get("ProgramFiles") {
142            dirs.push((
143                PathBuf::from(program_files).join("LLVM").join("bin"),
144                Origin::LlvmInstall,
145            ));
146        }
147        for install in installs {
148            dirs.push((
149                install
150                    .path
151                    .join("VC")
152                    .join("Tools")
153                    .join("Llvm")
154                    .join("x64")
155                    .join("bin"),
156                Origin::VisualStudio(install.path.clone()),
157            ));
158        }
159    }
160
161    let mut found = Vec::new();
162    for tool in Tool::ALL {
163        let mut seen: Vec<PathBuf> = Vec::new();
164        let mut candidates: Vec<(PathBuf, Origin)> = Vec::new();
165        let mut configured = None;
166        if let Some(path) = explicit.get(tool) {
167            if !path.is_file() {
168                return Err(ToolchainError::ConfiguredToolMissing {
169                    setting: format!("[toolchain.paths] {}", tool.name()),
170                    path: path.to_owned(),
171                });
172            }
173            // Run once, for what it is and for its version.
174            let version = run.run(path, &[OsStr::new("--version")], env).ok();
175            if let Err(why) = identity(tool, version.as_ref(), path, run, env) {
176                return Err(ToolchainError::ConfiguredToolUnusable {
177                    setting: format!("[toolchain.paths] {}", tool.name()),
178                    path: path.to_owned(),
179                    why,
180                });
181            }
182            configured = Some(probe_of(version.as_ref()));
183            candidates.push((path.to_owned(), Origin::Configured));
184        }
185        let file = host.executable(tool.name());
186        candidates.extend(
187            dirs.iter()
188                .map(|(dir, origin)| (dir.join(&file), origin.clone()))
189                .filter(|(path, _)| path.is_file()),
190        );
191        for (path, origin) in candidates {
192            let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
193            if seen.contains(&identity) {
194                continue;
195            }
196            seen.push(identity);
197            let probe = match (&origin, configured.take()) {
198                (Origin::Configured, Some(probe)) => probe,
199                _ => probe(&path, run, env),
200            };
201            found.push(LlvmTool {
202                tool,
203                probe,
204                path,
205                origin,
206            });
207        }
208    }
209    Ok(found)
210}
211
212/// Whether the configured file `path` is `tool` and not another LLVM tool
213/// (`docs/en/specs/toolchain.md`, "LLVM (clang / clang-cl / clang-format /
214/// clang-tidy)"): its `--version` names the kind, and clang and clang-cl,
215/// one program whose mode follows its file name, are told apart by how
216/// `/?` answers. One that cannot run is left to the probe, which says so.
217fn identity(
218    tool: Tool,
219    version: Option<&crate::Output>,
220    path: &Path,
221    run: &dyn Runner,
222    env: &Env,
223) -> Result<(), String> {
224    let Some(output) = version.filter(|o| o.success) else {
225        return Ok(());
226    };
227    let text = String::from_utf8_lossy(&output.stdout);
228    let is = if text.contains("clang-format version") {
229        Tool::ClangFormat
230    } else if text.contains("clang version") {
231        // clang-cl answers `/?` with its option list; clang takes it for a
232        // file and fails.
233        let cl = run
234            .run(path, &[OsStr::new("/?")], env)
235            .is_ok_and(|o| o.success && o.stdout.starts_with(b"OVERVIEW:"));
236        if cl { Tool::ClangCl } else { Tool::Clang }
237    } else if text.contains("LLVM (http://llvm.org") || text.contains("LLVM version") {
238        // clang-tidy: `LLVM (http://llvm.org/):` then `LLVM version`, or a
239        // vendor's `Ubuntu LLVM version` alone.
240        Tool::ClangTidy
241    } else {
242        return Err("it is not an LLVM tool cuno knows".to_owned());
243    };
244    if is == tool {
245        Ok(())
246    } else {
247        Err(format!("it is {}, not {}", is.name(), tool.name()))
248    }
249}
250
251/// Runs `<tool> --version`. The version is the first `<n>.<n>.<n>` after the
252/// word `version` on the same line (`clang version 22.1.8`, `LLVM version
253/// 22.1.8`), so a number on a later line (an install directory) is never
254/// taken for it.
255fn probe(path: &Path, run: &dyn Runner, env: &Env) -> Probe {
256    probe_of(run.run(path, &[OsStr::new("--version")], env).ok().as_ref())
257}
258
259/// What a `--version` run told, as [`probe`] reads it; `None` for one that
260/// could not be started.
261fn probe_of(output: Option<&crate::Output>) -> Probe {
262    let Some(output) = output.filter(|o| o.success) else {
263        return Probe::Failed;
264    };
265    let text = String::from_utf8_lossy(&output.stdout);
266    let Some(line) = text.lines().find(|l| l.contains("version")) else {
267        return Probe::NoVersion;
268    };
269    let after = &line[line.find("version").unwrap_or(0)..];
270    let Some(version) = Version::find_in(after) else {
271        return Probe::NoVersion;
272    };
273    // The word the version is in: anything after the number (`-rc1`, `git`)
274    // marks a pre-release.
275    let text_version = version.to_string();
276    let prerelease = after
277        .split_whitespace()
278        .find(|word| word.contains(&text_version))
279        .is_some_and(|word| word.len() > text_version.len());
280    let target = text
281        .lines()
282        .find_map(|l| l.trim().strip_prefix("Target:"))
283        .map(|t| t.trim().to_owned());
284    Probe::Ran {
285        version,
286        prerelease,
287        target,
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use crate::Output;
295    use cuno_core::NameCase;
296
297    /// Answers `--version` with the version encoded in the file's parent
298    /// directory name (`.../v22/clang.exe` answers `clang version 22.0.0`).
299    struct ByDir;
300
301    impl Runner for ByDir {
302        fn run(&self, program: &Path, _args: &[&OsStr], _env: &Env) -> std::io::Result<Output> {
303            let dir = program
304                .parent()
305                .unwrap()
306                .file_name()
307                .unwrap()
308                .to_string_lossy();
309            let major = dir.trim_start_matches('v');
310            Ok(Output {
311                success: true,
312                stdout: format!("clang version {major}.0.0 (test)\n").into_bytes(),
313                stderr: Vec::new(),
314            })
315        }
316    }
317
318    /// Creates `root/<rel>/<file>` for each entry.
319    fn files(root: &Path, entries: &[(&str, &str)]) {
320        for (rel, file) in entries {
321            let dir = root.join(rel);
322            std::fs::create_dir_all(&dir).unwrap();
323            std::fs::write(dir.join(file), "").unwrap();
324        }
325    }
326
327    fn env(root: &Path, path_dirs: &[&str]) -> Env {
328        let path = std::env::join_paths(path_dirs.iter().map(|d| root.join(d))).unwrap();
329        Env::from_pairs(
330            [
331                ("Path".into(), path),
332                ("ProgramFiles".into(), root.join("pf").into_os_string()),
333            ],
334            NameCase::Insensitive,
335        )
336    }
337
338    fn vs(root: &Path, name: &str) -> VsInstallation {
339        VsInstallation {
340            path: root.join(name),
341            prerelease: false,
342            complete: true,
343            toolsets: Vec::new(),
344            unusable_toolsets: Vec::new(),
345            default_toolset: None,
346        }
347    }
348
349    fn clangs(found: &[LlvmTool]) -> Vec<(Origin, String)> {
350        found
351            .iter()
352            .filter(|t| t.tool == Tool::Clang)
353            .map(|t| {
354                (
355                    t.origin.clone(),
356                    t.version().map(|v| v.to_string()).unwrap_or_default(),
357                )
358            })
359            .collect()
360    }
361
362    /// Mutation: skip any of the four places, or search them in another
363    /// order; this test fails.
364    #[test]
365    fn every_place_is_searched_in_the_specified_order() {
366        let root = tempfile::tempdir().unwrap();
367        let r = root.path();
368        files(
369            r,
370            &[
371                ("cfg/v23", "clang.exe"),
372                ("onpath/v20", "clang.exe"),
373                ("pf/LLVM/bin", "clang.exe"),
374                ("VS/VC/Tools/Llvm/x64/bin", "clang.exe"),
375            ],
376        );
377        let explicit = ExplicitPaths {
378            clang: Some(r.join("cfg/v23/clang.exe")),
379            ..Default::default()
380        };
381        // The fake answers by directory name; give the installer and VS
382        // copies recognisable versions by their own directory names.
383        let found = find_llvm_tools(
384            &env(r, &["onpath/v20"]),
385            HostOs::Windows,
386            &explicit,
387            &[vs(r, "VS")],
388            &ByDir,
389        )
390        .unwrap();
391        let origins: Vec<_> = clangs(&found).into_iter().map(|(o, _)| o).collect();
392        assert_eq!(
393            origins,
394            [
395                Origin::Configured,
396                Origin::Path,
397                Origin::LlvmInstall,
398                Origin::VisualStudio(r.join("VS")),
399            ]
400        );
401    }
402
403    /// Mutation: drop the de-duplication; this test fails.
404    #[test]
405    fn the_same_file_found_twice_is_listed_once() {
406        let root = tempfile::tempdir().unwrap();
407        let r = root.path();
408        files(r, &[("pf/LLVM/bin", "clang.exe")]);
409        // PATH names the installer's directory itself, twice.
410        let found = find_llvm_tools(
411            &env(r, &["pf/LLVM/bin", "pf/LLVM/bin"]),
412            HostOs::Windows,
413            &ExplicitPaths::default(),
414            &[],
415            &ByDir,
416        )
417        .unwrap();
418        assert_eq!(clangs(&found).len(), 1, "{found:?}");
419        assert_eq!(found[0].origin, Origin::Path);
420    }
421
422    /// Mutation: ignore a configured path that has no file, or fall back to
423    /// the other places; this test fails.
424    #[test]
425    fn a_configured_path_without_a_file_names_the_setting() {
426        let root = tempfile::tempdir().unwrap();
427        let explicit = ExplicitPaths {
428            clang_tidy: Some(root.path().join("nope/clang-tidy.exe")),
429            ..Default::default()
430        };
431        let err = find_llvm_tools(
432            &env(root.path(), &[]),
433            HostOs::Windows,
434            &explicit,
435            &[],
436            &ByDir,
437        )
438        .unwrap_err();
439        assert!(
440            err.to_string().contains("[toolchain.paths] clang-tidy"),
441            "{err}"
442        );
443    }
444
445    /// Mutation: look in `%ProgramFiles%\LLVM` or Visual Studio on a non-
446    /// Windows host, or add `.exe` there; this test fails.
447    #[test]
448    fn other_hosts_look_on_path_only_without_a_suffix() {
449        let root = tempfile::tempdir().unwrap();
450        let r = root.path();
451        files(
452            r,
453            &[
454                ("onpath/v18", "clang"),
455                ("pf/LLVM/bin", "clang"),
456                ("VS/VC/Tools/Llvm/x64/bin", "clang"),
457            ],
458        );
459        let found = find_llvm_tools(
460            &env(r, &["onpath/v18"]),
461            HostOs::Other,
462            &ExplicitPaths::default(),
463            &[vs(r, "VS")],
464            &ByDir,
465        )
466        .unwrap();
467        assert_eq!(clangs(&found), [(Origin::Path, "18.0.0".to_owned())]);
468    }
469
470    /// Mutation: read the first three-part number anywhere (a path or hash
471    /// before the word `version`), or stop finding tools that print no
472    /// version; this test fails.
473    #[test]
474    fn the_version_follows_the_word_version() {
475        struct Banner;
476        impl Runner for Banner {
477            fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
478                Ok(Output {
479                    success: true,
480                    stdout: b"LLVM (http://llvm.org/ 1.2.3):\n  LLVM version 22.1.8\n".to_vec(),
481                    stderr: Vec::new(),
482                })
483            }
484        }
485        let root = tempfile::tempdir().unwrap();
486        files(root.path(), &[("bin", "clang-tidy.exe")]);
487        let found = find_llvm_tools(
488            &env(root.path(), &["bin"]),
489            HostOs::Windows,
490            &ExplicitPaths::default(),
491            &[],
492            &Banner,
493        )
494        .unwrap();
495        assert_eq!(found[0].version().unwrap().to_string(), "22.1.8");
496    }
497
498    /// Mutation: drop a tool from `Tool::ALL`, or misname its executable;
499    /// this test fails.
500    #[test]
501    fn all_four_tools_are_found() {
502        let root = tempfile::tempdir().unwrap();
503        files(
504            root.path(),
505            &[
506                ("v22", "clang.exe"),
507                ("v22", "clang-cl.exe"),
508                ("v22", "clang-format.exe"),
509                ("v22", "clang-tidy.exe"),
510            ],
511        );
512        let found = find_llvm_tools(
513            &env(root.path(), &["v22"]),
514            HostOs::Windows,
515            &ExplicitPaths::default(),
516            &[],
517            &ByDir,
518        )
519        .unwrap();
520        let tools: Vec<_> = found.iter().map(|t| t.tool).collect();
521        assert_eq!(tools, Tool::ALL);
522    }
523
524    /// Answers as each real LLVM tool does, by its file name: what
525    /// `--version` prints, and for clang-cl alone, `/?` succeeding with its
526    /// option list.
527    struct ByName;
528    impl Runner for ByName {
529        fn run(&self, program: &Path, args: &[&OsStr], _env: &Env) -> std::io::Result<Output> {
530            let name = program.file_stem().unwrap().to_string_lossy().into_owned();
531            let help = args.first().is_some_and(|a| *a == OsStr::new("/?"));
532            let (success, stdout) = match (name.as_str(), help) {
533                ("clang-cl", true) => (true, "OVERVIEW: clang LLVM compiler\n"),
534                (_, true) => (false, ""),
535                ("clang" | "clang-cl", false) => (
536                    true,
537                    "clang version 22.1.8 (x)\nTarget: x86_64-pc-windows-msvc\n",
538                ),
539                ("clang-format", false) => (true, "clang-format version 22.1.8 (x)\n"),
540                ("clang-tidy", false) => {
541                    (true, "LLVM (http://llvm.org/):\n  LLVM version 22.1.8\n")
542                }
543                // A vendor's clang-tidy names itself on one line.
544                ("vendor-tidy", false) => (true, "Ubuntu LLVM version 22.1.0\n"),
545                _ => (true, "some tool 1.0.0\n"),
546            };
547            Ok(Output {
548                success,
549                stdout: stdout.as_bytes().to_vec(),
550                stderr: Vec::new(),
551            })
552        }
553    }
554
555    /// A configured file that is another LLVM tool than its key is refused,
556    /// naming what it is; the right tool is taken. clang and clang-cl are
557    /// told apart by `/?`, the rest by `--version`.
558    ///
559    /// Mutation: skip the `/?` check, skip the `--version` kinds, or check
560    /// nothing; this test fails.
561    #[test]
562    fn a_configured_path_must_be_the_tool_its_key_names() {
563        let root = tempfile::tempdir().unwrap();
564        let r = root.path();
565        files(
566            r,
567            &[
568                ("a", "clang.exe"),
569                ("a", "clang-cl.exe"),
570                ("a", "clang-format.exe"),
571                ("a", "clang-tidy.exe"),
572                ("a", "other.exe"),
573                ("a", "vendor-tidy.exe"),
574            ],
575        );
576        let at = |name: &str| Some(r.join("a").join(name));
577        let refused = |explicit: ExplicitPaths| match find_llvm_tools(
578            &env(r, &[]),
579            HostOs::Windows,
580            &explicit,
581            &[],
582            &ByName,
583        ) {
584            Err(ToolchainError::ConfiguredToolUnusable { setting, why, .. }) => {
585                Some(format!("{setting}: {why}"))
586            }
587            Err(other) => panic!("{other:?}"),
588            Ok(_) => None,
589        };
590        let cases = [
591            (
592                ExplicitPaths {
593                    clang: at("clang-cl.exe"),
594                    ..Default::default()
595                },
596                "[toolchain.paths] clang: it is clang-cl, not clang",
597            ),
598            (
599                ExplicitPaths {
600                    clang_cl: at("clang.exe"),
601                    ..Default::default()
602                },
603                "[toolchain.paths] clang-cl: it is clang, not clang-cl",
604            ),
605            (
606                ExplicitPaths {
607                    clang: at("clang-format.exe"),
608                    ..Default::default()
609                },
610                "[toolchain.paths] clang: it is clang-format, not clang",
611            ),
612            (
613                ExplicitPaths {
614                    clang_format: at("clang-tidy.exe"),
615                    ..Default::default()
616                },
617                "[toolchain.paths] clang-format: it is clang-tidy, not clang-format",
618            ),
619            (
620                ExplicitPaths {
621                    clang_tidy: at("other.exe"),
622                    ..Default::default()
623                },
624                "[toolchain.paths] clang-tidy: it is not an LLVM tool cuno knows",
625            ),
626        ];
627        for (explicit, want) in cases {
628            assert_eq!(refused(explicit).as_deref(), Some(want));
629        }
630        let right = ExplicitPaths {
631            clang: at("clang.exe"),
632            clang_cl: at("clang-cl.exe"),
633            clang_format: at("clang-format.exe"),
634            clang_tidy: at("clang-tidy.exe"),
635        };
636        assert_eq!(refused(right), None);
637        // A vendor's clang-tidy names itself `Ubuntu LLVM version` alone.
638        let vendor = ExplicitPaths {
639            clang_tidy: at("vendor-tidy.exe"),
640            ..Default::default()
641        };
642        assert_eq!(refused(vendor), None);
643    }
644
645    /// A configured tool's `--version` is run once, for what it is and for
646    /// its version, so a tool slow to answer is waited for once.
647    ///
648    /// Mutation: run `--version` again for the probe; this test fails.
649    #[test]
650    fn a_configured_tool_is_asked_its_version_once() {
651        struct Counting(std::sync::atomic::AtomicUsize);
652        impl Runner for Counting {
653            fn run(&self, program: &Path, args: &[&OsStr], env: &Env) -> std::io::Result<Output> {
654                if args.first().is_some_and(|a| *a == OsStr::new("--version")) {
655                    self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
656                }
657                ByName.run(program, args, env)
658            }
659        }
660        let root = tempfile::tempdir().unwrap();
661        let r = root.path();
662        files(r, &[("a", "clang.exe")]);
663        let explicit = ExplicitPaths {
664            clang: Some(r.join("a/clang.exe")),
665            ..Default::default()
666        };
667        let counting = Counting(std::sync::atomic::AtomicUsize::new(0));
668        let found =
669            find_llvm_tools(&env(r, &[]), HostOs::Windows, &explicit, &[], &counting).unwrap();
670        assert_eq!(found.len(), 1);
671        assert!(matches!(found[0].probe, Probe::Ran { .. }));
672        assert_eq!(counting.0.load(std::sync::atomic::Ordering::SeqCst), 1);
673    }
674
675    /// A runner that answers every `--version` with the same output.
676    struct Says(bool, &'static str);
677    impl Runner for Says {
678        fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
679            Ok(Output {
680                success: self.0,
681                stdout: self.1.as_bytes().to_vec(),
682                stderr: Vec::new(),
683            })
684        }
685    }
686
687    /// A runner whose programs cannot be started.
688    struct CannotStart;
689    impl Runner for CannotStart {
690        fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
691            Err(std::io::Error::other("cannot start"))
692        }
693    }
694
695    fn one_clang(run: &dyn Runner) -> LlvmTool {
696        let root = tempfile::tempdir().unwrap();
697        files(root.path(), &[("bin", "clang.exe")]);
698        find_llvm_tools(
699            &env(root.path(), &["bin"]),
700            HostOs::Windows,
701            &ExplicitPaths::default(),
702            &[],
703            run,
704        )
705        .unwrap()
706        .remove(0)
707    }
708
709    /// Mutation: keep empty or relative `PATH` entries; this test fails.
710    #[test]
711    fn only_absolute_path_entries_are_searched() {
712        let root = tempfile::tempdir().unwrap();
713        let absolute = root.path().join("bin");
714        let path = std::env::join_paths([
715            std::path::PathBuf::new(),
716            ".".into(),
717            "relative/bin".into(),
718            absolute.clone(),
719        ])
720        .unwrap();
721        let env = Env::from_pairs([("PATH".into(), path)], NameCase::Insensitive);
722        assert_eq!(env.search_dirs(), [absolute]);
723    }
724
725    /// Mutation: read a version from a run that failed, or drop a tool that
726    /// could not be started instead of recording it as failed; this test
727    /// fails.
728    #[test]
729    fn failing_tools_are_recorded_as_failed() {
730        assert_eq!(
731            one_clang(&Says(false, "clang version 22.1.8\n")).probe,
732            Probe::Failed
733        );
734        assert_eq!(one_clang(&CannotStart).probe, Probe::Failed);
735        assert_eq!(one_clang(&Says(true, "garbage\n")).probe, Probe::NoVersion);
736    }
737
738    /// Mutation: search for the version past the line with the word
739    /// `version`; this test fails (the install directory holds `9.9.9`).
740    #[test]
741    fn the_version_is_read_from_its_own_line() {
742        let tool = one_clang(&Says(
743            true,
744            "clang version trunk\nInstalledDir: C:/llvm-9.9.9/bin\n",
745        ));
746        assert_eq!(tool.probe, Probe::NoVersion);
747    }
748
749    /// Mutation: ignore the text after the number, or drop the `Target:`
750    /// line; this test fails.
751    #[test]
752    fn prereleases_and_targets_are_recorded() {
753        let release = one_clang(&Says(
754            true,
755            "clang version 22.1.8 (https://x)\nTarget: x86_64-pc-windows-msvc\n",
756        ));
757        assert_eq!(
758            release.probe,
759            Probe::Ran {
760                version: Version {
761                    major: 22,
762                    minor: 1,
763                    patch: 8
764                },
765                prerelease: false,
766                target: Some("x86_64-pc-windows-msvc".into()),
767            }
768        );
769        for banner in [
770            "clang version 19.1.0-rc1 (x)\n",
771            "clang version 23.0.0git (x)\n",
772        ] {
773            let Probe::Ran {
774                prerelease, target, ..
775            } = one_clang(&Says(true, banner)).probe
776            else {
777                panic!("{banner}");
778            };
779            assert!(prerelease, "{banner}");
780            assert_eq!(target, None);
781        }
782        let mingw = one_clang(&Says(
783            true,
784            "clang version 21.1.0\nTarget: x86_64-w64-windows-gnu\n",
785        ));
786        assert!(
787            matches!(mingw.probe, Probe::Ran { target: Some(t), .. } if t == "x86_64-w64-windows-gnu")
788        );
789    }
790
791    /// Mutation: map any `[toolchain.paths]` field to another tool; this test
792    /// fails.
793    #[test]
794    fn each_configured_path_belongs_to_its_own_tool() {
795        let root = tempfile::tempdir().unwrap();
796        let r = root.path();
797        files(
798            r,
799            &[
800                ("a", "clang.exe"),
801                ("b", "clang-cl.exe"),
802                ("c", "clang-format.exe"),
803                ("d", "clang-tidy.exe"),
804            ],
805        );
806        let explicit = ExplicitPaths {
807            clang: Some(r.join("a/clang.exe")),
808            clang_cl: Some(r.join("b/clang-cl.exe")),
809            clang_format: Some(r.join("c/clang-format.exe")),
810            clang_tidy: Some(r.join("d/clang-tidy.exe")),
811        };
812        let found =
813            find_llvm_tools(&env(r, &[]), HostOs::Windows, &explicit, &[], &ByName).unwrap();
814        let got: Vec<_> = found
815            .iter()
816            .map(|t| {
817                (
818                    t.tool,
819                    t.path
820                        .parent()
821                        .unwrap()
822                        .file_name()
823                        .unwrap()
824                        .to_string_lossy()
825                        .into_owned(),
826                    t.origin.clone(),
827                )
828            })
829            .collect();
830        assert_eq!(
831            got,
832            [
833                (Tool::Clang, "a".to_owned(), Origin::Configured),
834                (Tool::ClangCl, "b".to_owned(), Origin::Configured),
835                (Tool::ClangFormat, "c".to_owned(), Origin::Configured),
836                (Tool::ClangTidy, "d".to_owned(), Origin::Configured),
837            ]
838        );
839    }
840
841    /// Mutation: accept a configured directory (`exists` instead of
842    /// `is_file`); this test fails.
843    #[test]
844    fn a_configured_directory_is_not_a_tool() {
845        let root = tempfile::tempdir().unwrap();
846        let explicit = ExplicitPaths {
847            clang: Some(root.path().to_owned()),
848            ..Default::default()
849        };
850        let err = find_llvm_tools(
851            &env(root.path(), &[]),
852            HostOs::Windows,
853            &explicit,
854            &[],
855            &ByDir,
856        )
857        .unwrap_err();
858        assert!(
859            matches!(err, ToolchainError::ConfiguredToolMissing { .. }),
860            "{err}"
861        );
862    }
863
864    /// Mutation: compare paths as written instead of canonicalized; this test
865    /// fails (`pf/../pf/LLVM/bin` and `pf/LLVM/bin` are one directory).
866    #[test]
867    fn the_same_file_spelled_differently_is_listed_once() {
868        let root = tempfile::tempdir().unwrap();
869        let r = root.path();
870        files(r, &[("pf/LLVM/bin", "clang.exe")]);
871        let found = find_llvm_tools(
872            &env(r, &["pf/../pf/LLVM/bin"]),
873            HostOs::Windows,
874            &ExplicitPaths::default(),
875            &[],
876            &ByDir,
877        )
878        .unwrap();
879        assert_eq!(clangs(&found).len(), 1, "{found:?}");
880    }
881
882    /// Mutation: search only the first Visual Studio, reverse them, or tag
883    /// every bundled Clang with the first installation; this test fails.
884    #[test]
885    fn every_visual_studio_is_searched_in_order() {
886        let root = tempfile::tempdir().unwrap();
887        let r = root.path();
888        files(
889            r,
890            &[
891                ("VS1/VC/Tools/Llvm/x64/bin", "clang.exe"),
892                ("VS2/VC/Tools/Llvm/x64/bin", "clang.exe"),
893            ],
894        );
895        let found = find_llvm_tools(
896            &env(r, &[]),
897            HostOs::Windows,
898            &ExplicitPaths::default(),
899            &[vs(r, "VS1"), vs(r, "VS2")],
900            &ByDir,
901        )
902        .unwrap();
903        let origins: Vec<_> = clangs(&found).into_iter().map(|(o, _)| o).collect();
904        assert_eq!(
905            origins,
906            [
907                Origin::VisualStudio(r.join("VS1")),
908                Origin::VisualStudio(r.join("VS2"))
909            ]
910        );
911    }
912}