1use std::fmt;
5use std::path::PathBuf;
6
7use cuno_core::{CunoError, ExitClass};
8
9use crate::Version;
10
11const BUILD_TOOLS_HELP: &str = "install Build Tools for Visual Studio with the \"Desktop development with C++\" workload: https://visualstudio.microsoft.com/visual-cpp-build-tools/";
12
13#[derive(Clone, Debug)]
15pub enum ToolchainError {
16 VswhereMissing {
18 path: PathBuf,
20 },
21 VswhereFailed {
23 detail: String,
25 },
26 NoVisualStudio,
28 ClVersionUnknown {
30 path: PathBuf,
32 },
33 NoWindowsSdk {
35 looked_in: Vec<PathBuf>,
37 },
38 UnknownCompiler {
40 name: String,
42 source: String,
44 },
45 UnsupportedCompiler {
47 name: String,
49 source: String,
51 },
52 CompilerNotFound {
54 compiler: &'static str,
56 },
57 NoUsableCompiler {
60 compiler: &'static str,
62 excluded: Vec<String>,
64 },
65 NoMatchingVersion {
67 compiler: &'static str,
69 requirements: Vec<String>,
71 found: Vec<Version>,
73 },
74 InvalidVersionRequirement {
76 compiler: String,
78 text: String,
80 },
81 VisualStudioNotAt {
83 path: PathBuf,
85 },
86 RejectedByStl {
88 compiler: &'static str,
90 version: Version,
92 needed: Option<String>,
94 message: String,
96 },
97 GccUnreadable {
100 path: PathBuf,
102 asked: &'static str,
104 output: String,
106 },
107 ProbeFailed {
109 compiler: &'static str,
111 output: String,
113 },
114 EditionNotSupported {
116 compiler: &'static str,
118 version: Version,
120 edition: &'static str,
122 needed: Version,
124 },
125 ConfiguredToolMissing {
127 setting: String,
129 path: PathBuf,
131 },
132 ConfiguredToolUnusable {
135 setting: String,
137 path: PathBuf,
139 why: String,
141 },
142}
143
144impl fmt::Display for ToolchainError {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 match self {
147 ToolchainError::VswhereMissing { path } => {
148 write!(f, "vswhere.exe was not found at {}", path.display())
149 }
150 ToolchainError::VswhereFailed { detail } => {
151 f.write_str(&with_output("vswhere.exe failed".to_owned(), detail))
152 }
153 ToolchainError::NoVisualStudio => {
154 f.write_str("no Visual Studio or Build Tools with the C++ x64 tools was found")
155 }
156 ToolchainError::ClVersionUnknown { path } => {
157 write!(f, "could not read the version of {}", path.display())
158 }
159 ToolchainError::NoWindowsSdk { looked_in } => {
160 let places: Vec<String> =
161 looked_in.iter().map(|p| p.display().to_string()).collect();
162 write!(
163 f,
164 "no Windows SDK with the x64 headers and libraries was found in {}",
165 places.join(" or ")
166 )
167 }
168 ToolchainError::UnknownCompiler { name, source } => {
169 write!(
170 f,
171 "{source} names `{name}`, which is not a compiler cuno knows"
172 )
173 }
174 ToolchainError::UnsupportedCompiler { name, source } => {
175 write!(f, "{name} is not supported yet (chosen by {source})")
176 }
177 ToolchainError::CompilerNotFound { compiler } => write!(f, "no {compiler} was found"),
178 ToolchainError::NoUsableCompiler { compiler, excluded } => write!(
179 f,
180 "no usable {compiler} was found; left out: {}",
181 excluded.join("; ")
182 ),
183 ToolchainError::NoMatchingVersion {
184 compiler,
185 requirements,
186 found,
187 } => {
188 let found: Vec<String> = found.iter().map(Version::to_string).collect();
189 write!(
190 f,
191 "no {compiler} found satisfies {}; found {}",
192 requirements.join(" and "),
193 found.join(", ")
194 )
195 }
196 ToolchainError::InvalidVersionRequirement { compiler, text } => write!(
197 f,
198 "[toolchain.version] {compiler} = \"{text}\" is not a version requirement"
199 ),
200 ToolchainError::VisualStudioNotAt { path } => write!(
201 f,
202 "[toolchain.paths] msvc is {}, but no Visual Studio with the C++ x64 tools is installed there",
203 path.display()
204 ),
205 ToolchainError::RejectedByStl {
206 compiler, version, ..
207 } => write!(
208 f,
209 "{compiler} {version} is not accepted by the MSVC standard library in use (STL1000)"
210 ),
211 ToolchainError::ProbeFailed { compiler, output } => f.write_str(&with_output(
212 format!("could not tell whether {compiler} works with the MSVC standard library"),
213 output,
214 )),
215 ToolchainError::GccUnreadable {
216 path,
217 asked,
218 output,
219 } => f.write_str(&with_output(
220 format!("{} did not say {asked}", path.display()),
221 output,
222 )),
223 ToolchainError::EditionNotSupported {
224 compiler,
225 version,
226 edition,
227 ..
228 } => write!(
229 f,
230 "{compiler} {version} does not support edition = \"{edition}\""
231 ),
232 ToolchainError::ConfiguredToolUnusable { setting, path, why } => {
233 write!(f, "{setting} is {}, but {why}", path.display())
234 }
235 ToolchainError::ConfiguredToolMissing { setting, path } => {
236 write!(
237 f,
238 "{setting} is {}, but there is no file there",
239 path.display()
240 )
241 }
242 }
243 }
244}
245
246impl std::error::Error for ToolchainError {}
247
248const GCC: &str = crate::compiler::CompilerKind::Gcc.name();
250
251const MSYS2_GCC: &str = "https://www.msys2.org/, then `pacman -S mingw-w64-ucrt-x86_64-gcc`";
253
254impl CunoError for ToolchainError {
255 fn exit_class(&self) -> ExitClass {
256 ExitClass::Setup
257 }
258
259 fn help(&self) -> Option<String> {
260 match self {
261 ToolchainError::UnknownCompiler { .. } | ToolchainError::UnsupportedCompiler { .. } => {
262 Some(format!("choose {}", crate::compiler::CompilerKind::names()))
263 }
264 ToolchainError::CompilerNotFound { compiler } if *compiler == GCC => Some(format!(
266 "install MSYS2's UCRT64 GCC ({MSYS2_GCC}), or write where gcc is in [toolchain.paths] gcc"
267 )),
268 ToolchainError::NoUsableCompiler { compiler, .. } if *compiler == GCC => Some(format!(
269 "install MSYS2's UCRT64 GCC ({MSYS2_GCC}), or write where a usable gcc is in [toolchain.paths] gcc"
270 )),
271 ToolchainError::CompilerNotFound { compiler } => Some(format!(
272 "install LLVM (https://github.com/llvm/llvm-project/releases), or write where {compiler} is in [toolchain.paths] {compiler}"
273 )),
274 ToolchainError::NoUsableCompiler { compiler, .. } => Some(format!(
275 "install a release of LLVM for Windows (https://github.com/llvm/llvm-project/releases), or write where a usable {compiler} is in [toolchain.paths] {compiler}"
276 )),
277 ToolchainError::NoMatchingVersion { compiler, .. } => Some(format!(
278 "install a {compiler} that satisfies it, or change [toolchain.version] {compiler}"
279 )),
280 ToolchainError::InvalidVersionRequirement { .. } => Some(
281 "write conditions such as \">=17\" or \">=19.29, <19.50\"".to_owned(),
282 ),
283 ToolchainError::VisualStudioNotAt { .. } => Some(
284 "correct [toolchain.paths] msvc, or remove it to let cuno find Visual Studio"
285 .to_owned(),
286 ),
287 ToolchainError::RejectedByStl {
288 compiler: "clang-tidy",
289 needed: Some(needed),
290 ..
291 } => Some(format!("install clang-tidy {needed} or newer")),
292 ToolchainError::RejectedByStl {
293 needed, message, ..
294 } => Some(match needed {
295 Some(needed) => {
296 format!("install Clang {needed} or newer, or select another compiler")
297 }
298 None => format!("the standard library says: {message}"),
299 }),
300 ToolchainError::ProbeFailed { .. } => Some(
301 "check `[build.<compiler>] flags` in Cuno.toml, and the Visual Studio and LLVM installations".to_owned(),
302 ),
303 ToolchainError::GccUnreadable { .. } => Some(format!(
304 "reinstall MSYS2's UCRT64 GCC ({MSYS2_GCC}), or write where a working gcc is in [toolchain.paths] gcc"
305 )),
306
307 ToolchainError::EditionNotSupported {
308 compiler, needed, ..
309 } => Some(format!(
310 "use {compiler} {needed} or newer, or choose another edition or compiler"
311 )),
312 ToolchainError::ConfiguredToolMissing { setting, .. }
313 | ToolchainError::ConfiguredToolUnusable { setting, .. } => Some(format!(
314 "correct {setting}, or remove it to let cuno find the tool"
315 )),
316 ToolchainError::VswhereMissing { .. } | ToolchainError::NoVisualStudio => {
317 Some(BUILD_TOOLS_HELP.to_owned())
318 }
319 ToolchainError::NoWindowsSdk { .. } => Some(
320 "add a Windows SDK in the Visual Studio Installer (a \"Windows 11 SDK\" component of the \"Desktop development with C++\" workload)".to_owned(),
321 ),
322 ToolchainError::VswhereFailed { .. } | ToolchainError::ClVersionUnknown { .. } => Some(
323 "repair the Visual Studio installation with the Visual Studio Installer".to_owned(),
324 ),
325 }
326 }
327}
328
329const MAX_QUOTED_LINES: usize = 20;
332
333fn with_output(line: String, output: &str) -> String {
338 let output = output.trim_end();
339 if output.is_empty() {
340 return line;
341 }
342 let lines: Vec<&str> = output.lines().collect();
343 let shown = lines.len().min(MAX_QUOTED_LINES);
344 let mut out = format!("{line}:\n{}", lines[..shown].join("\n"));
345 match lines.len() - shown {
346 0 => {}
347 1 => out.push_str("\n(and 1 more line)"),
348 rest => out.push_str(&format!("\n(and {rest} more lines)")),
349 }
350 out
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
359 fn every_toolchain_error_is_a_setup_problem() {
360 for e in [
361 ToolchainError::VswhereMissing { path: "x".into() },
362 ToolchainError::VswhereFailed { detail: "x".into() },
363 ToolchainError::NoVisualStudio,
364 ToolchainError::ClVersionUnknown { path: "x".into() },
365 ToolchainError::ConfiguredToolMissing {
366 setting: "x".into(),
367 path: "x".into(),
368 },
369 ToolchainError::NoWindowsSdk {
370 looked_in: vec!["x".into()],
371 },
372 ToolchainError::UnknownCompiler {
373 name: "x".into(),
374 source: "x".into(),
375 },
376 ToolchainError::UnsupportedCompiler {
377 name: "x".into(),
378 source: "x".into(),
379 },
380 ToolchainError::CompilerNotFound { compiler: "x" },
381 ToolchainError::NoUsableCompiler {
382 compiler: "x",
383 excluded: vec![],
384 },
385 ToolchainError::NoMatchingVersion {
386 compiler: "x",
387 requirements: vec![],
388 found: vec![],
389 },
390 ToolchainError::InvalidVersionRequirement {
391 compiler: "x".into(),
392 text: "x".into(),
393 },
394 ToolchainError::VisualStudioNotAt { path: "x".into() },
395 ToolchainError::RejectedByStl {
396 compiler: "x",
397 version: Version {
398 major: 0,
399 minor: 0,
400 patch: 0,
401 },
402 needed: None,
403 message: "x".into(),
404 },
405 ToolchainError::ProbeFailed {
406 compiler: "x",
407 output: "x".into(),
408 },
409 ToolchainError::EditionNotSupported {
410 compiler: "x",
411 version: Version {
412 major: 0,
413 minor: 0,
414 patch: 0,
415 },
416 edition: "x",
417 needed: Version {
418 major: 0,
419 minor: 0,
420 patch: 0,
421 },
422 },
423 ] {
424 assert_eq!(e.exit_class(), ExitClass::Setup, "{e}");
425 assert!(e.help().is_some(), "{e}");
426 }
427 }
428
429 #[test]
433 fn messages_name_what_was_looked_for_and_how_to_fix_it() {
434 let cases = [
435 (
436 ToolchainError::VswhereMissing {
437 path: "Z:/x/vswhere.exe".into(),
438 },
439 "Z:/x/vswhere.exe",
440 "Desktop development with C++",
441 ),
442 (
443 ToolchainError::VswhereFailed {
444 detail: "access denied".into(),
445 },
446 "access denied",
447 "Visual Studio Installer",
448 ),
449 (
450 ToolchainError::NoVisualStudio,
451 "C++ x64 tools",
452 "Desktop development with C++",
453 ),
454 (
455 ToolchainError::ClVersionUnknown {
456 path: "Z:/t/cl.exe".into(),
457 },
458 "Z:/t/cl.exe",
459 "Visual Studio Installer",
460 ),
461 (
462 ToolchainError::ConfiguredToolMissing {
463 setting: "[toolchain.paths] clang".into(),
464 path: "Z:/c/clang.exe".into(),
465 },
466 "Z:/c/clang.exe",
467 "[toolchain.paths] clang",
468 ),
469 (
470 ToolchainError::NoWindowsSdk {
471 looked_in: vec!["Y:/Kits".into(), "Z:/Windows Kits/10".into()],
472 },
473 "Y:/Kits or Z:/Windows Kits/10",
474 "Windows 11 SDK",
475 ),
476 (
477 ToolchainError::UnsupportedCompiler {
478 name: "safec".into(),
479 source: "CUNO_COMPILER".into(),
480 },
481 "safec is not supported yet (chosen by CUNO_COMPILER)",
482 "msvc, clang, clang-cl or gcc",
483 ),
484 (
485 ToolchainError::NoMatchingVersion {
486 compiler: "msvc",
487 requirements: vec![">=19.29 (cuno's minimum)".into()],
488 found: vec![Version {
489 major: 19,
490 minor: 28,
491 patch: 1,
492 }],
493 },
494 "satisfies >=19.29 (cuno's minimum); found 19.28.1",
495 "[toolchain.version] msvc",
496 ),
497 (
498 ToolchainError::RejectedByStl {
499 compiler: "clang",
500 version: Version {
501 major: 20,
502 minor: 1,
503 patch: 8,
504 },
505 needed: Some("22".into()),
506 message: "STL1000: ...".into(),
507 },
508 "clang 20.1.8 is not accepted by the MSVC standard library in use (STL1000)",
509 "install Clang 22 or newer, or select another compiler",
510 ),
511 (
512 ToolchainError::RejectedByStl {
513 compiler: "clang",
514 version: Version {
515 major: 20,
516 minor: 1,
517 patch: 8,
518 },
519 needed: None,
520 message: "STL1000: odd wording".into(),
521 },
522 "(STL1000)",
523 "STL1000: odd wording",
524 ),
525 (
526 ToolchainError::UnknownCompiler {
527 name: "nope".into(),
528 source: "--compiler".into(),
529 },
530 "--compiler names `nope`, which is not a compiler cuno knows",
531 "msvc, clang, clang-cl or gcc",
532 ),
533 (
534 ToolchainError::CompilerNotFound { compiler: "clang" },
535 "no clang was found",
536 "[toolchain.paths] clang",
537 ),
538 (
539 ToolchainError::NoUsableCompiler {
540 compiler: "clang",
541 excluded: vec!["a (x)".into(), "b (y)".into()],
542 },
543 "no usable clang was found; left out: a (x); b (y)",
544 "release of LLVM",
545 ),
546 (
547 ToolchainError::CompilerNotFound { compiler: "gcc" },
548 "no gcc was found",
549 "pacman -S mingw-w64-ucrt-x86_64-gcc`), or write where gcc is in [toolchain.paths] gcc",
550 ),
551 (
552 ToolchainError::NoUsableCompiler {
553 compiler: "gcc",
554 excluded: vec![
555 "C:/mingw64/bin/gcc.exe (its C runtime is MSVCRT, not UCRT)".into(),
556 ],
557 },
558 "left out: C:/mingw64/bin/gcc.exe (its C runtime is MSVCRT, not UCRT)",
559 "install MSYS2's UCRT64 GCC",
560 ),
561 (
562 ToolchainError::InvalidVersionRequirement {
563 compiler: "clang".into(),
564 text: "~17".into(),
565 },
566 "[toolchain.version] clang = \"~17\" is not a version requirement",
567 "\">=19.29, <19.50\"",
568 ),
569 (
570 ToolchainError::VisualStudioNotAt {
571 path: "Z:/VS".into(),
572 },
573 "[toolchain.paths] msvc is Z:/VS, but no Visual Studio",
574 "correct [toolchain.paths] msvc",
575 ),
576 (
577 ToolchainError::ProbeFailed {
578 compiler: "clang-cl",
579 output: "fatal error: x".into(),
580 },
581 "whether clang-cl works with the MSVC standard library:\nfatal error: x",
582 "[build.<compiler>] flags",
583 ),
584 ];
585 for (error, in_message, in_help) in cases {
586 let message = error.to_string();
587 let help = error.help().unwrap();
588 assert!(message.contains(in_message), "{message}");
589 assert!(help.contains(in_help), "{help}");
590 }
591 }
592
593 fn unreadable(output: &str) -> String {
594 ToolchainError::GccUnreadable {
595 path: PathBuf::from("gcc.exe"),
596 asked: "where its headers are",
597 output: output.to_owned(),
598 }
599 .to_string()
600 }
601
602 fn numbered(n: usize) -> String {
603 (1..=n).map(|i| format!("line {i}\n")).collect()
604 }
605
606 #[test]
612 fn an_empty_output_quotes_nothing() {
613 for output in ["", "\n \n", "\r\n"] {
614 assert_eq!(
615 unreadable(output),
616 "gcc.exe did not say where its headers are"
617 );
618 }
619 }
620
621 #[test]
629 fn a_long_output_is_quoted_as_its_first_20_lines() {
630 assert_eq!(
631 unreadable("cc1: fatal\nsecond\n\n"),
632 "gcc.exe did not say where its headers are:\ncc1: fatal\nsecond"
633 );
634 let twenty = numbered(20);
635 assert_eq!(
636 unreadable(&twenty),
637 format!(
638 "gcc.exe did not say where its headers are:\n{}",
639 twenty.trim_end()
640 )
641 );
642 assert_eq!(
643 unreadable(&numbered(21)),
644 format!(
645 "gcc.exe did not say where its headers are:\n{}\n(and 1 more line)",
646 twenty.trim_end()
647 )
648 );
649 assert_eq!(
650 unreadable(&numbered(3000)),
651 format!(
652 "gcc.exe did not say where its headers are:\n{}\n(and 2980 more lines)",
653 twenty.trim_end()
654 )
655 );
656 }
657
658 #[test]
663 fn the_probe_failure_quotes_by_the_same_rule() {
664 let failed = |output: &str| {
665 ToolchainError::ProbeFailed {
666 compiler: "clang",
667 output: output.to_owned(),
668 }
669 .to_string()
670 };
671 let line = "could not tell whether clang works with the MSVC standard library";
672 assert_eq!(failed(""), line);
673 assert_eq!(
674 failed(&numbered(25)),
675 format!("{line}:\n{}\n(and 5 more lines)", numbered(20).trim_end())
676 );
677 }
678
679 #[test]
685 fn the_vswhere_failure_quotes_by_the_same_rule() {
686 let failed = |detail: &str| {
687 ToolchainError::VswhereFailed {
688 detail: detail.to_owned(),
689 }
690 .to_string()
691 };
692 assert_eq!(failed(""), "vswhere.exe failed");
693 assert_eq!(
694 failed(&numbered(22)),
695 format!(
696 "vswhere.exe failed:\n{}\n(and 2 more lines)",
697 numbered(20).trim_end()
698 )
699 );
700 }
701}