Skip to main content

cuno_toolchain/
prepare.rs

1//! What every command that compiles does before it compiles: find the
2//! compilers and tools, then, for the selected compiler, resolve the
3//! environment it runs in. `cuno doctor` and the build commands both call
4//! these, so they diagnose and build with the same answers.
5
6use std::ffi::OsString;
7use std::path::{Path, PathBuf};
8
9use cuno_core::Env;
10
11use crate::compiler::CompilerKind;
12use crate::gcc::Gcc;
13use crate::llvm::{ExplicitPaths, LlvmTool, find_llvm_tools};
14use crate::msvc::{self, Registry, VsInstallation, WindowsSdk};
15use crate::select::{Found, Selected};
16use crate::{HostOs, Runner, ToolchainError};
17
18/// What detection found. Each part is a result of its own, so a caller that
19/// reports problems (`cuno doctor`) keeps going after one fails.
20#[derive(Debug)]
21pub struct Detected {
22    /// Every Visual Studio installation; empty on a host that has none.
23    pub installs: Result<Vec<VsInstallation>, ToolchainError>,
24    /// Every LLVM tool found, in search order.
25    pub llvm: Result<Vec<LlvmTool>, ToolchainError>,
26    /// Every GCC, or `None` when it was not looked for: GCC is searched
27    /// only when it is wanted, or by `cuno doctor` (`toolchain.md`, "MinGW
28    /// (GCC)"). [`detect`] leaves it `None`.
29    pub gcc: Option<Result<Vec<Gcc>, ToolchainError>>,
30}
31
32impl Detected {
33    /// Why `kind` was not searched for, when its search failed (a
34    /// configured path with no file there). A new compiler does not compile
35    /// until it says where its search's error is kept.
36    pub fn search_error(&self, kind: CompilerKind) -> Option<&ToolchainError> {
37        match kind {
38            CompilerKind::Msvc => self.installs.as_ref().err(),
39            CompilerKind::Clang | CompilerKind::ClangCl => self.llvm.as_ref().err(),
40            CompilerKind::Gcc => self.gcc.as_ref().and_then(|g| g.as_ref().err()),
41        }
42    }
43
44    /// What selection chooses from: each part found, empty where its
45    /// search failed or did not run.
46    pub fn found<'a>(&'a self, explicit_msvc: Option<&'a Path>) -> Found<'a> {
47        Found {
48            installs: self.installs.as_deref().unwrap_or(&[]),
49            llvm: self.llvm.as_deref().unwrap_or(&[]),
50            gcc: match &self.gcc {
51                Some(Ok(gcc)) => gcc,
52                Some(Err(_)) | None => &[],
53            },
54            explicit_msvc,
55        }
56    }
57
58    /// Whether `kind` was searched for, so an empty result means it was
59    /// not found. A search that failed (a configured path with no file,
60    /// already reported) looked for nothing. Visual Studio is always
61    /// searched; whether it was found is selection's answer.
62    pub fn looked_for(&self, kind: CompilerKind) -> bool {
63        match kind {
64            CompilerKind::Msvc => true,
65            CompilerKind::Clang | CompilerKind::ClangCl => self.llvm.is_ok(),
66            CompilerKind::Gcc => matches!(self.gcc, Some(Ok(_))),
67        }
68    }
69}
70
71/// Finds Visual Studio (on Windows) and the LLVM tools, the copies
72/// `explicit` names first. LLVM is searched even when Visual Studio is not
73/// found, since its bundled LLVM is only one of the places looked in.
74pub fn detect(env: &Env, host: HostOs, explicit: &ExplicitPaths, run: &dyn Runner) -> Detected {
75    let installs = match host {
76        HostOs::Windows => msvc::find_installations(env, run),
77        HostOs::Other => Ok(Vec::new()),
78    };
79    let found = installs.as_deref().unwrap_or(&[]);
80    let llvm = find_llvm_tools(env, host, explicit, found, run);
81    Detected {
82        installs,
83        llvm,
84        gcc: None,
85    }
86}
87
88/// Variables compilers and linkers read options or include paths from by
89/// themselves, which would add flags no command line shows
90/// (`toolchain.md`, "How it is resolved").
91pub const TOOL_OPTION_VARIABLES: [&str; 12] = [
92    "CL",
93    "_CL_",
94    "LINK",
95    "_LINK_",
96    "CPATH",
97    "C_INCLUDE_PATH",
98    "CPLUS_INCLUDE_PATH",
99    // GCC's: where its linker finds libraries and it finds its own
100    // programs, and a second dependency file it would write.
101    "LIBRARY_PATH",
102    "GCC_EXEC_PREFIX",
103    "COMPILER_PATH",
104    "DEPENDENCIES_OUTPUT",
105    "SUNPRO_DEPENDENCIES",
106];
107
108/// The environment the selected compiler runs in.
109#[derive(Clone, Debug)]
110pub struct Prepared {
111    /// The process environment with the MSVC toolset's and the Windows SDK's
112    /// paths applied, or as given when no toolset is used.
113    pub env: Env,
114    /// The Windows SDK, when a toolset is used.
115    pub sdk: Option<WindowsSdk>,
116    /// The [`TOOL_OPTION_VARIABLES`] that were set and are left out of
117    /// `env`, for the build to warn about.
118    pub ignored: Vec<&'static str>,
119    /// What GCC builds with besides its command line, when GCC is used.
120    pub gcc: Option<crate::gcc::Install>,
121}
122
123impl Prepared {
124    /// The include directories the compiler searches for the system and
125    /// standard headers: the resolved `INCLUDE`, in order, when the
126    /// environment was prepared for an MSVC toolset; GCC's own, as it told
127    /// them, for GCC; else none, whatever the process's own `INCLUDE` says.
128    /// The one place an MSVC environment's include path is read, so a
129    /// compiler with no toolset never takes it as its include path
130    /// (compile_commands.json, the build records, clang-tidy).
131    pub fn include_dirs(&self) -> Vec<PathBuf> {
132        match (&self.sdk, &self.gcc) {
133            (Some(_), _) => crate::flags::include_dirs(self.env.get("INCLUDE")),
134            (None, Some(gcc)) => gcc.include.clone(),
135            (None, None) => Vec::new(),
136        }
137    }
138
139    /// What besides each compile's arguments identifies its command: the
140    /// compiler's `version`, the variables of the environment that decide
141    /// which headers and libraries it reads, and for GCC the runtime files
142    /// it links into every program (`build.md`, "Deciding what changed").
143    pub fn identity(&self, version: &str) -> Vec<OsString> {
144        let var = |name| self.env.get(name).unwrap_or_default().to_owned();
145        let mut out = vec![
146            OsString::from(version),
147            var("INCLUDE"),
148            var("LIB"),
149            var("LIBPATH"),
150        ];
151        if let Some(gcc) = &self.gcc {
152            out.extend(gcc.runtime.iter().map(OsString::from));
153        }
154        out
155    }
156}
157
158/// `env` with its temporary directory, as Windows finds it (`TMP`, else
159/// `TEMP`, else `USERPROFILE`), set as `TMP` and `TEMP` by its short name
160/// when it is not ASCII and has an ASCII one: GCC's linker and the tools
161/// it runs open it in the ANSI code page (`docs/en/specs/toolchain.md`,
162/// "MinGW (GCC)"). As it is otherwise; the build refuses what is left.
163fn ascii_temp(env: Env) -> Env {
164    let Some(temp) = crate::short_path::temp_dir(&env) else {
165        return env;
166    };
167    if temp.to_str().is_some_and(str::is_ascii) {
168        return env;
169    }
170    match crate::short_path::ascii_short_path(&temp) {
171        Some(short) => env
172            .with("TMP", short.clone().into_os_string())
173            .with("TEMP", short.into_os_string()),
174        None => env,
175    }
176}
177
178/// Resolves the environment for `selected`: with an MSVC toolset (every
179/// compiler on Windows but GCC), the Windows SDK is found and both are
180/// applied to `env` (`docs/en/specs/toolchain.md`, "Environment resolution
181/// on Windows"); GCC gets its own directory first on `PATH`, which its
182/// compiler proper loads DLLs from (`toolchain.md`, "MinGW (GCC)").
183pub fn prepare(
184    selected: &Selected,
185    env: &Env,
186    host: HostOs,
187    registry: &dyn Registry,
188    run: &dyn Runner,
189) -> Result<Prepared, ToolchainError> {
190    let ignored: Vec<&'static str> = TOOL_OPTION_VARIABLES
191        .into_iter()
192        .filter(|name| env.get(name).is_some())
193        .collect();
194    let clean = env.without(&TOOL_OPTION_VARIABLES);
195    let Some(toolset) = &selected.msvc else {
196        let (env, gcc) = match selected.kind {
197            CompilerKind::Gcc => {
198                let env = ascii_temp(crate::gcc::env_for(&selected.executable, &clean));
199                let install = crate::gcc::install(&selected.executable, host, &env, run)?;
200                (env, Some(install))
201            }
202            CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => (clean, None),
203        };
204        return Ok(Prepared {
205            env,
206            sdk: None,
207            ignored,
208            gcc,
209        });
210    };
211    let sdk = msvc::find_windows_sdk(env, registry)?;
212    Ok(Prepared {
213        env: msvc::resolve(toolset, &sdk).apply(&clean),
214        sdk: Some(sdk),
215        ignored,
216        gcc: None,
217    })
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::Version;
224    use crate::msvc::MsvcToolset;
225
226    use crate::select::Source;
227    use cuno_core::NameCase;
228    use std::ffi::{OsStr, OsString};
229    use std::path::{Path, PathBuf};
230
231    /// The include directories are the prepared `INCLUDE`, in order, only
232    /// when the environment was prepared for a toolset; without one, an
233    /// `INCLUDE` the process had is not the compiler's.
234    ///
235    /// Mutation: read `INCLUDE` whether or not a toolset was used, or lose
236    /// the order; this test fails.
237    #[test]
238    fn include_dirs_are_the_toolset_s_only() {
239        let env = Env::from_pairs(
240            [("INCLUDE".into(), "C:/msvc/include;;C:/sdk/ucrt".into())],
241            NameCase::Insensitive,
242        );
243        let with_toolset = Prepared {
244            env: env.clone(),
245            sdk: Some(WindowsSdk {
246                dir: "C:/sdk".into(),
247                version: "10.0.28000.0".to_owned(),
248            }),
249            ignored: Vec::new(),
250            gcc: None,
251        };
252        assert_eq!(
253            with_toolset.include_dirs(),
254            [
255                PathBuf::from("C:/msvc/include"),
256                PathBuf::from("C:/sdk/ucrt")
257            ]
258        );
259        let without = Prepared {
260            env,
261            sdk: None,
262            ignored: Vec::new(),
263            gcc: None,
264        };
265        assert!(without.include_dirs().is_empty());
266    }
267
268    /// A step's command is identified by the compiler's version and the
269    /// `INCLUDE`, `LIB` and `LIBPATH` it runs with, so an updated compiler
270    /// or SDK rebuilds.
271    ///
272    /// Mutation: leave out the version or any of the variables; this test
273    /// fails.
274    #[test]
275    fn the_compiler_and_its_environment_identify_commands() {
276        let prepared = |env| Prepared {
277            env,
278            sdk: None,
279            ignored: Vec::new(),
280            gcc: None,
281        };
282        let env = Env::from_pairs(
283            [
284                ("include".into(), "C:/inc".into()),
285                ("LIB".into(), "C:/lib".into()),
286                ("LIBPATH".into(), "C:/libpath".into()),
287                ("PATH".into(), "C:/bin".into()),
288            ],
289            NameCase::Insensitive,
290        );
291        assert_eq!(
292            prepared(env).identity("19.52.1"),
293            ["19.52.1", "C:/inc", "C:/lib", "C:/libpath"].map(OsStr::new)
294        );
295        assert_eq!(
296            prepared(Env::default()).identity("1"),
297            ["1", "", "", ""].map(OsStr::new)
298        );
299    }
300
301    /// A registry that names `dir` as the Windows Kits root.
302    struct Kits(PathBuf);
303    impl Registry for Kits {
304        fn local_machine_string(&self, _key: &str, _value: &str) -> Option<OsString> {
305            Some(self.0.clone().into())
306        }
307    }
308
309    /// A runner that runs nothing.
310    struct Nothing;
311    impl Runner for Nothing {
312        fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<crate::Output> {
313            Err(std::io::Error::other("not run"))
314        }
315    }
316
317    fn complete_sdk(kits: &Path, version: &str) {
318        let include = kits.join("Include").join(version);
319        let lib = kits.join("Lib").join(version);
320        for (dir, file) in [("um", "windows.h"), ("ucrt", "stdio.h")] {
321            std::fs::create_dir_all(include.join(dir)).unwrap();
322            std::fs::write(include.join(dir).join(file), "").unwrap();
323            std::fs::create_dir_all(lib.join(dir).join("x64")).unwrap();
324        }
325    }
326
327    fn selected(msvc: Option<MsvcToolset>) -> Selected {
328        Selected {
329            kind: CompilerKind::ClangCl,
330            executable: "clang-cl".into(),
331            version: Version {
332                major: 22,
333                minor: 1,
334                patch: 8,
335            },
336            msvc,
337            source: Source::CommandLine,
338        }
339    }
340
341    fn env() -> Env {
342        Env::from_pairs([("KEEP".into(), "1".into())], NameCase::Insensitive)
343    }
344
345    /// With a toolset, the SDK is found and both are applied to the
346    /// environment; without one, the environment is as given and there is
347    /// no SDK; with no SDK, the error says so.
348    ///
349    /// Mutation: skip the SDK, return the environment unresolved, or require
350    /// a toolset; this test fails.
351    #[test]
352    fn a_toolset_gets_the_sdk_and_its_environment() {
353        let root = tempfile::tempdir().unwrap();
354        let kits = root.path().join("Kits");
355        complete_sdk(&kits, "10.0.28000.0");
356        let toolset = MsvcToolset {
357            dir: root.path().join("VS/VC/Tools/MSVC/14.52.1"),
358            cl_version: Version {
359                major: 19,
360                minor: 52,
361                patch: 1,
362            },
363        };
364        let prepared = prepare(
365            &selected(Some(toolset.clone())),
366            &env(),
367            HostOs::Windows,
368            &Kits(kits.clone()),
369            &Nothing,
370        )
371        .unwrap();
372        assert_eq!(prepared.sdk.as_ref().unwrap().version, "10.0.28000.0");
373        let include = prepared
374            .env
375            .get("INCLUDE")
376            .unwrap()
377            .to_string_lossy()
378            .into_owned();
379        assert!(
380            include.contains(&toolset.dir.join("include").display().to_string()),
381            "{include}"
382        );
383        assert!(include.contains("10.0.28000.0"), "{include}");
384        assert_eq!(prepared.env.get("KEEP").unwrap(), "1");
385
386        let bare = prepare(
387            &selected(None),
388            &env(),
389            HostOs::Windows,
390            &Kits(kits),
391            &Nothing,
392        )
393        .unwrap();
394        assert!(bare.sdk.is_none());
395        assert_eq!(bare.env.get("INCLUDE"), None);
396        assert_eq!(bare.env.get("KEEP").unwrap(), "1");
397
398        let nowhere = root.path().join("none");
399        assert!(matches!(
400            prepare(
401                &selected(Some(toolset)),
402                &env(),
403                HostOs::Windows,
404                &Kits(nowhere),
405                &Nothing
406            ),
407            Err(ToolchainError::NoWindowsSdk { .. })
408        ));
409    }
410
411    /// Answers as a GCC whose libraries are in `libs` would, and only when
412    /// run in its own directory with its messages untranslated.
413    struct Answers {
414        libs: PathBuf,
415    }
416
417    impl Runner for Answers {
418        fn run(&self, _: &Path, _: &[&OsStr], _: &Env) -> std::io::Result<crate::Output> {
419            panic!("GCC is asked in its own directory")
420        }
421
422        fn run_in(
423            &self,
424            program: &Path,
425            args: &[&OsStr],
426            env: &Env,
427            cwd: &Path,
428        ) -> std::io::Result<crate::Output> {
429            assert_eq!(Some(cwd), program.parent());
430            assert_eq!(env.get("LC_ALL"), Some(OsStr::new("C")));
431            let ok = |stdout: String, stderr: &str| crate::Output {
432                success: true,
433                stdout: stdout.into_bytes(),
434                stderr: stderr.as_bytes().to_vec(),
435            };
436            Ok(match args[0].to_str().unwrap() {
437                "-E" => ok(
438                    String::new(),
439                    "ignoring nonexistent directory \"x\"\n\
440                     #include \"...\" search starts here:\n\
441                     #include <...> search starts here:\n \
442                     C:/m/lib/gcc/x86_64-w64-mingw32/16.2.0/../../../../include/c++/16.2.0\n \
443                     C:/m/include\n\
444                     End of search list.\n",
445                ),
446                "-print-search-dirs" => ok(
447                    format!(
448                        "install: C:/m/\nlibraries: =C:/nowhere;{}\n",
449                        self.libs.display()
450                    ),
451                    "",
452                ),
453                other => panic!("asked {other}"),
454            })
455        }
456    }
457
458    /// GCC runs with its own directory first on `PATH` and the rest kept,
459    /// and with no MSVC environment; no other compiler's `PATH` changes.
460    /// Its include directories, as it lists them with `..` resolved, are its
461    /// system ones, and its runtime files found in its library directories
462    /// identify its commands.
463    ///
464    /// Mutation: give GCC the environment unchanged, put its directory on
465    /// another compiler's `PATH`, leave its include directories out, keep
466    /// the `..`, or leave a runtime file (`libstdc++exp.a` among them) out
467    /// of the identity; this test fails.
468    #[test]
469    fn gcc_finds_its_own_dlls() {
470        let path = |dirs: &[&str]| std::env::join_paths(dirs).unwrap();
471        let env = Env::from_pairs(
472            [("PATH".into(), path(&["C:/Windows"]))],
473            NameCase::Insensitive,
474        );
475        let gcc = Selected {
476            kind: CompilerKind::Gcc,
477            executable: "C:/msys64/ucrt64/bin/gcc.exe".into(),
478            ..selected(None)
479        };
480        let libs = tempfile::tempdir().unwrap();
481        std::fs::write(libs.path().join("libstdc++.a"), "x").unwrap();
482        std::fs::write(libs.path().join("libstdc++exp.a"), "x").unwrap();
483        let answers = Answers {
484            libs: libs.path().to_owned(),
485        };
486        let prepared = prepare(
487            &gcc,
488            &env,
489            HostOs::Windows,
490            &Kits("C:/nowhere".into()),
491            &answers,
492        )
493        .unwrap();
494        assert_eq!(
495            prepared.include_dirs(),
496            [
497                PathBuf::from("C:/m/include/c++/16.2.0"),
498                PathBuf::from("C:/m/include")
499            ]
500        );
501        let identity = prepared.identity("16.2.0");
502        let runtime: Vec<&OsString> = identity[4..].iter().collect();
503        assert_eq!(runtime.len(), 2, "{identity:?}");
504        for (stamp, file) in runtime.iter().zip(["libstdc++.a", "libstdc++exp.a"]) {
505            let stamp = stamp.to_string_lossy();
506            assert!(
507                stamp.starts_with(&format!("{} 1 ", libs.path().join(file).display())),
508                "{stamp}"
509            );
510        }
511
512        assert_eq!(
513            prepared.env.get("PATH"),
514            Some(path(&["C:/msys64/ucrt64/bin", "C:/Windows"]).as_os_str())
515        );
516        assert!(prepared.sdk.is_none());
517        for kind in [
518            CompilerKind::Msvc,
519            CompilerKind::Clang,
520            CompilerKind::ClangCl,
521        ] {
522            let other = Selected {
523                kind,
524                ..gcc.clone()
525            };
526            let prepared = prepare(
527                &other,
528                &env,
529                HostOs::Windows,
530                &Kits("C:/nowhere".into()),
531                &Nothing,
532            )
533            .unwrap();
534            assert_eq!(prepared.env.get("PATH"), env.get("PATH"), "{kind:?}");
535        }
536    }
537
538    /// A temporary directory that is not ASCII is given to GCC by its
539    /// ASCII short name, as both `TMP` and `TEMP`, whichever named it; an
540    /// ASCII one, or one without a short name, is left as it is.
541    ///
542    /// Mutation: leave it as it is, or set only `TMP`; this test fails.
543    #[cfg(windows)]
544    #[test]
545    fn gcc_gets_the_temporary_directory_s_short_name() {
546        let root = tempfile::tempdir().unwrap();
547        let japanese = root.path().join("一時");
548        std::fs::create_dir(&japanese).unwrap();
549        let ascii = Env::from_pairs([("TMP".into(), "C:/tmp".into())], NameCase::Insensitive);
550        assert_eq!(ascii_temp(ascii.clone()).get("TMP"), ascii.get("TMP"));
551        let Some(short) = crate::short_path::ascii_short_path(&japanese) else {
552            return;
553        };
554        let env = Env::from_pairs(
555            [("TEMP".into(), japanese.clone().into_os_string())],
556            NameCase::Insensitive,
557        );
558        let given = ascii_temp(env);
559        assert_eq!(given.get("TMP"), Some(short.as_os_str()));
560        assert_eq!(given.get("TEMP"), Some(short.as_os_str()));
561    }
562
563    /// Off Windows nothing looks for Visual Studio.
564    ///
565    /// Mutation: look for Visual Studio on every host; this test fails.
566    #[test]
567    fn other_hosts_look_for_no_visual_studio() {
568        let detected = detect(&env(), HostOs::Other, &ExplicitPaths::default(), &Nothing);
569        assert!(
570            matches!(detected.installs, Ok(ref v) if v.is_empty()),
571            "{detected:?}"
572        );
573        assert!(
574            matches!(detected.llvm, Ok(ref v) if v.is_empty()),
575            "{detected:?}"
576        );
577    }
578
579    /// Answers vswhere, cl.exe and clang from canned output.
580    struct Canned(Vec<(&'static str, Vec<u8>)>);
581    impl Runner for Canned {
582        fn run(&self, program: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<crate::Output> {
583            let program = program.to_string_lossy().replace('\\', "/");
584            self.0
585                .iter()
586                .find(|(suffix, _)| program.ends_with(suffix))
587                .map(|(_, stdout)| crate::Output {
588                    success: true,
589                    stdout: stdout.clone(),
590                    stderr: Vec::new(),
591                })
592                .ok_or_else(|| std::io::Error::other("not answered"))
593        }
594    }
595
596    /// On Windows, the Visual Studio found is searched for its bundled LLVM:
597    /// with nothing on `PATH` and no `%ProgramFiles%\LLVM`, the clang
598    /// Visual Studio ships is found.
599    ///
600    /// Mutation: search LLVM without the installations found; this test
601    /// fails.
602    #[test]
603    fn the_llvm_visual_studio_bundles_is_found() {
604        let root = tempfile::tempdir().unwrap();
605        let installer = root.path().join("x86/Microsoft Visual Studio/Installer");
606        std::fs::create_dir_all(&installer).unwrap();
607        std::fs::write(installer.join("vswhere.exe"), "").unwrap();
608        let vs = root.path().join("VS");
609        let cl_dir = vs.join("VC/Tools/MSVC/14.52.1/bin/Hostx64/x64");
610        let llvm_dir = vs.join("VC/Tools/Llvm/x64/bin");
611        for dir in [&cl_dir, &llvm_dir] {
612            std::fs::create_dir_all(dir).unwrap();
613        }
614        std::fs::write(cl_dir.join("cl.exe"), "").unwrap();
615        std::fs::write(llvm_dir.join("clang.exe"), "").unwrap();
616        let vswhere = serde_json::to_vec(&serde_json::json!([{
617            "installationPath": vs,
618            "isPrerelease": false,
619            "isComplete": true,
620            "isLaunchable": true,
621        }]))
622        .unwrap();
623        let run = Canned(vec![
624            ("vswhere.exe", vswhere),
625            (
626                "cl.exe",
627                b"Microsoft (R) C/C++ Optimizing Compiler Version 19.52.1 for x64".to_vec(),
628            ),
629            (
630                "clang.exe",
631                b"clang version 22.1.3\nTarget: x86_64-pc-windows-msvc\n".to_vec(),
632            ),
633        ]);
634        let env = Env::from_pairs(
635            [(
636                "ProgramFiles(x86)".into(),
637                root.path().join("x86").into_os_string(),
638            )],
639            NameCase::Insensitive,
640        );
641        let detected = detect(&env, HostOs::Windows, &ExplicitPaths::default(), &run);
642        assert_eq!(detected.installs.unwrap().len(), 1);
643        let llvm = detected.llvm.unwrap();
644        assert_eq!(llvm.len(), 1, "{llvm:?}");
645        assert_eq!(llvm[0].path, llvm_dir.join("clang.exe"));
646    }
647
648    /// Variables that add compiler or linker options unseen are left out of
649    /// the build's environment, with or without a toolset, and named so the
650    /// build can warn; others are kept.
651    ///
652    /// Mutation: keep any of them (GCC's `LIBRARY_PATH` among them), or
653    /// name one that was not set; this test fails.
654    #[test]
655    fn option_variables_are_left_out_and_named() {
656        let env = Env::from_pairs(
657            [
658                ("cl".into(), "/DX".into()),
659                ("_LINK_".into(), "/STACK:1".into()),
660                ("CPATH".into(), "C:/x".into()),
661                ("LIBRARY_PATH".into(), "C:/lib".into()),
662                ("KEEP".into(), "1".into()),
663            ],
664            NameCase::Insensitive,
665        );
666        let prepared = prepare(
667            &selected(None),
668            &env,
669            HostOs::Windows,
670            &Kits(PathBuf::new()),
671            &Nothing,
672        )
673        .unwrap();
674        assert_eq!(prepared.ignored, ["CL", "_LINK_", "CPATH", "LIBRARY_PATH"]);
675        for name in TOOL_OPTION_VARIABLES {
676            assert_eq!(prepared.env.get(name), None, "{name}");
677        }
678        assert_eq!(prepared.env.get("KEEP").unwrap(), "1");
679    }
680
681    /// A search that did not run, or failed, looked for nothing, so doctor
682    /// prints no line for it; Visual Studio is always looked for.
683    ///
684    /// Mutation: answer true for GCC when it was not searched, or for LLVM
685    /// when its search failed; this test fails.
686    #[test]
687    fn only_a_search_that_ran_and_succeeded_looked_for_anything() {
688        let missing = || ToolchainError::ConfiguredToolMissing {
689            setting: "[toolchain.paths] clang".to_owned(),
690            path: PathBuf::from("C:/nowhere/clang.exe"),
691        };
692        let detected = |llvm_ok: bool, gcc: Option<bool>| Detected {
693            installs: Ok(Vec::new()),
694            llvm: if llvm_ok {
695                Ok(Vec::new())
696            } else {
697                Err(missing())
698            },
699            gcc: gcc.map(|ok| if ok { Ok(Vec::new()) } else { Err(missing()) }),
700        };
701        let looked = |d: &Detected| -> Vec<bool> {
702            CompilerKind::ALL.iter().map(|&k| d.looked_for(k)).collect()
703        };
704        assert_eq!(
705            looked(&detected(true, Some(true))),
706            [true, true, true, true]
707        );
708        assert_eq!(looked(&detected(true, None)), [true, true, true, false]);
709        assert_eq!(
710            looked(&detected(false, Some(false))),
711            [true, false, false, false]
712        );
713    }
714}