use std::path::Path;
use cuno_core::{CunoError, Env, Shell};
use cuno_manifest::{ConfigError, Profile, Settings};
use cuno_toolchain::compiler::{CompilerKind, Family};
use cuno_toolchain::flags::check_edition;
use cuno_toolchain::llvm::Tool;
use cuno_toolchain::msvc::SystemRegistry;
use cuno_toolchain::prepare;
use cuno_toolchain::select::{self, Choices, Found};
use cuno_toolchain::{HostOs, SystemRunner, ToolchainError};
use cuno_build::bundled;
use cuno_build::toolchain::{self, TidyCompile};
struct Problems<'a> {
shell: &'a mut Shell,
count: usize,
}
impl Problems<'_> {
fn status(&mut self, verb: &str, message: impl std::fmt::Display) {
self.shell.status(verb, message);
}
fn report(&mut self, error: &dyn CunoError) {
self.shell.error(error);
if let Some(help) = error.help() {
self.shell.help(help);
}
self.count += 1;
}
}
pub fn doctor(
compiler: Option<String>,
resolved: Result<Settings, ConfigError>,
env: &Env,
cwd: &Path,
host: HostOs,
temp: &Path,
shell: &mut Shell,
) -> usize {
let mut problems = Problems { shell, count: 0 };
let runner = SystemRunner::new();
let settings = match resolved {
Ok(settings) => Some(settings),
Err(error) => {
problems.report(&error);
None
}
};
let settings = settings.as_ref();
let detected = toolchain::detect(settings, env, host, &runner);
let no_visual_studio = detected.installs.is_err();
let installs = detected.installs.unwrap_or_else(|error| {
problems.report(&error);
Vec::new()
});
let no_llvm = detected.llvm.is_err();
let llvm = detected.llvm.unwrap_or_else(|error| {
problems.report(&error);
Vec::new()
});
let found = Found {
installs: &installs,
llvm: &llvm,
explicit_msvc: settings.and_then(Settings::msvc_path),
};
let diagnosed = diagnose(
settings,
compiler,
found,
no_visual_studio,
env,
cwd,
host,
temp,
&runner,
&mut problems,
);
if !no_llvm {
tools(
&llvm,
diagnosed.tidy.as_ref(),
host,
temp,
&runner,
&mut problems,
);
}
others(&diagnosed, found, !no_llvm, host, &mut problems);
let count = problems.count;
problems.status("Finished", finished(count));
count
}
fn finished(count: usize) -> String {
match count {
0 => "no problems found".to_owned(),
1 => "1 problem found".to_owned(),
n => format!("{n} problems found"),
}
}
#[derive(Default)]
struct Diagnosed {
attempted: Option<CompilerKind>,
vs_reported: bool,
tidy: Option<TidyCompile>,
}
#[allow(clippy::too_many_arguments)]
fn diagnose(
settings: Option<&Settings>,
compiler: Option<String>,
found: Found<'_>,
no_visual_studio: bool,
env: &Env,
cwd: &Path,
host: HostOs,
temp: &Path,
runner: &SystemRunner,
problems: &mut Problems<'_>,
) -> Diagnosed {
let choices = settings
.map(|s| s.compiler.clone())
.unwrap_or_else(|| Choices {
cli: compiler,
env: env
.set_value("CUNO_COMPILER")
.map(|v| v.to_string_lossy().into_owned()),
project: None,
user: None,
});
let attempted = choices.kind(host).ok().map(|(kind, _)| kind);
let constraints = settings.map(|s| s.constraints.clone()).unwrap_or_default();
let selected = match select::select(&choices, found, &constraints, host) {
Ok(selected) => selected,
Err(error) => {
let vs_error = matches!(
error,
ToolchainError::NoVisualStudio | ToolchainError::VisualStudioNotAt { .. }
);
if !(no_visual_studio && matches!(error, ToolchainError::NoVisualStudio)) {
problems.report(&error);
}
if vs_error
&& let Some(kind) = attempted.filter(|k| match k.family() {
Family::Llvm => true,
Family::Msvc => false,
})
&& let Err(unusable @ ToolchainError::ConfiguredToolUnusable { .. }) =
select::copy_of(kind, found, &constraints, host)
{
problems.report(&unusable);
}
return Diagnosed {
attempted,
vs_reported: matches!(error, ToolchainError::VisualStudioNotAt { .. }),
tidy: None,
};
}
};
let mut diagnosed = Diagnosed {
attempted,
vs_reported: false,
tidy: None,
};
let source = match (selected.source, settings) {
(select::Source::Automatic, None) => {
"automatic selection; the configuration could not be read".to_owned()
}
(source, _) => source.to_string(),
};
problems.status(
"Selected",
format!("{} {} ({source})", selected.kind.name(), selected.version),
);
problems.status("", selected.executable.display());
let project = settings.and_then(|s| s.project.as_ref());
if let Some((_, manifest)) = project
&& let Err(error) = check_edition(selected.kind, selected.version, manifest.package.edition)
{
problems.report(&error);
}
let Some(toolset) = &selected.msvc else {
return diagnosed;
};
let borrows_msvc = match selected.kind.family() {
Family::Llvm => true,
Family::Msvc => false,
};
if borrows_msvc {
problems.status(
"Using",
format!(
"MSVC {} ({})",
toolset.cl_version,
toolset.install_dir().display()
),
);
}
let prepared = match prepare::prepare(&selected, env, &SystemRegistry) {
Ok(prepared) => prepared,
Err(error) => {
problems.report(&error);
return diagnosed;
}
};
if let Some(sdk) = &prepared.sdk {
problems.status("Using", format!("Windows SDK {}", sdk.version));
}
let Ok(home) = cuno_core::cuno_home(env) else {
return diagnosed;
};
let project = project.map(|(p, m)| (p.root.as_path(), m));
let bundled = bundled::include_dir(&home);
let Some(stl) = toolchain::probe_compile(
&selected,
&prepared,
project,
Profile::Dev,
cwd,
host,
&bundled,
) else {
return diagnosed;
};
if borrows_msvc {
match toolchain::probe(&selected, &stl, temp, "doctor", runner) {
Ok(()) => problems.status("Accepted", "by the MSVC standard library"),
Err(error) => problems.report(&*error),
}
}
diagnosed.tidy = toolchain::tidy_compile(&selected, &prepared, project, cwd, host, &bundled);
diagnosed
}
fn tools(
llvm: &[cuno_toolchain::llvm::LlvmTool],
tidy: Option<&TidyCompile>,
host: HostOs,
temp: &Path,
runner: &SystemRunner,
problems: &mut Problems<'_>,
) {
for tool in [Tool::ClangFormat, Tool::ClangTidy] {
let chosen = match select::select_tool(tool, llvm, host) {
Ok(chosen) => chosen,
Err(error) => {
problems.report(&error);
continue;
}
};
problems.status("Found", format!("{} {}", tool.name(), chosen.version));
if tool == Tool::ClangTidy
&& let Some(tidy) = tidy
&& let Err(error) = toolchain::tidy_ready(&chosen, tidy, temp, "doctor", runner)
{
problems.report(&*error);
}
}
}
fn others(
diagnosed: &Diagnosed,
found: Found<'_>,
looked_for_llvm: bool,
host: HostOs,
problems: &mut Problems<'_>,
) {
for kind in CompilerKind::ALL {
let skip = match kind.family() {
Family::Llvm => !looked_for_llvm,
Family::Msvc => diagnosed.vs_reported,
};
if Some(kind) == diagnosed.attempted || skip {
continue;
}
let line = match select::copy_of(kind, found, &Default::default(), host) {
Ok((_, version, _)) => format!("{} {version} (not selected)", kind.name()),
Err(
error @ (ToolchainError::ConfiguredToolUnusable { .. }
| ToolchainError::VisualStudioNotAt { .. }),
) => {
problems.report(&error);
continue;
}
Err(ToolchainError::CompilerNotFound { .. } | ToolchainError::NoVisualStudio) => {
format!("{} not found", kind.name())
}
Err(error) => format!("{} not usable: {error}", kind.name()),
};
problems.status("Info", line);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_last_line_counts_the_problems() {
assert_eq!(finished(0), "no problems found");
assert_eq!(finished(1), "1 problem found");
assert_eq!(finished(2), "2 problems found");
}
}