cuno_toolchain/compiler.rs
1//! The compilers cuno can build with, and every fact about one that the rest
2//! of the crate branches on. Each fact is answered here by a match that
3//! names every compiler, so a new one does not compile until each is
4//! answered for it (`docs/en/specs/toolchain.md`, "Compiler abstraction").
5//! Elsewhere, code asks these questions rather than comparing kinds.
6
7use std::path::{Path, PathBuf};
8
9use crate::llvm::Tool;
10use crate::select::Source;
11use crate::{HostOs, ToolchainError, Version};
12
13/// A compiler cuno can build with.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum CompilerKind {
16 /// cl.exe.
17 Msvc,
18 /// clang with GCC-style flags.
19 Clang,
20 /// clang-cl, Clang with MSVC-style flags.
21 ClangCl,
22 /// MinGW-w64's GCC (`docs/en/specs/toolchain.md`, "MinGW (GCC)").
23 Gcc,
24}
25
26/// How a compiler's command line is written.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Syntax {
29 /// cl's: `/c`, `/Fo<obj>`, `/D`, linker options after `/link`.
30 Cl,
31 /// GCC's: `-c`, `-o <obj>`, `-D`, `-l`.
32 Gnu,
33}
34
35/// Whose compiler it is, which decides its linker, its link-time
36/// optimisation and whether it needs a target and the MSVC standard library
37/// check.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum Family {
40 /// Microsoft's cl.exe with link.exe.
41 Msvc,
42 /// An LLVM driver with lld, targeting the MSVC ABI.
43 Llvm,
44 /// GCC with its own linker and runtime, targeting MinGW-w64.
45 Gnu,
46}
47
48/// How a compiler says which headers a compile read
49/// (`docs/en/specs/build.md`, "Incremental and parallel builds").
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum Dependencies {
52 /// cl's `/sourceDependencies` JSON file, whose paths do not depend on
53 /// the language Visual Studio is installed in.
54 SourceDependencies,
55 /// A `-MD` dependency file in make's syntax, from clang and, through
56 /// `/clang:`, clang-cl, whose `/showIncludes` leaves out files read by
57 /// `#embed`.
58 DepFile,
59}
60
61impl CompilerKind {
62 /// Every compiler, in the order cuno lists them. A new variant is added
63 /// here as well as to the matches below.
64 pub const ALL: [CompilerKind; 4] = [
65 CompilerKind::Msvc,
66 CompilerKind::Clang,
67 CompilerKind::ClangCl,
68 CompilerKind::Gcc,
69 ];
70
71 /// The name used in settings (`msvc`, `clang`, `clang-cl`).
72 pub const fn name(self) -> &'static str {
73 match self {
74 CompilerKind::Msvc => "msvc",
75 CompilerKind::Clang => "clang",
76 CompilerKind::ClangCl => "clang-cl",
77 CompilerKind::Gcc => "gcc",
78 }
79 }
80
81 /// How its command line is written.
82 pub fn syntax(self) -> Syntax {
83 match self {
84 CompilerKind::Msvc | CompilerKind::ClangCl => Syntax::Cl,
85 CompilerKind::Clang | CompilerKind::Gcc => Syntax::Gnu,
86 }
87 }
88
89 /// Whose compiler it is.
90 pub fn family(self) -> Family {
91 match self {
92 CompilerKind::Msvc => Family::Msvc,
93 CompilerKind::Clang | CompilerKind::ClangCl => Family::Llvm,
94 CompilerKind::Gcc => Family::Gnu,
95 }
96 }
97
98 /// Whether finding it means running it, so that it is looked for only
99 /// when it is wanted (`docs/en/specs/toolchain.md`, "MinGW (GCC)"):
100 /// each GCC copy on `PATH` is run to learn what it is. The others are
101 /// found by their files. A new compiler must answer here before
102 /// detection can be asked for it.
103 pub fn found_by_running(self) -> bool {
104 match self {
105 CompilerKind::Gcc => true,
106 CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => false,
107 }
108 }
109
110 /// Whether it builds with an MSVC toolset (its standard library, the
111 /// Windows SDK and its environment) on `host`, so selecting it needs
112 /// Visual Studio (`docs/en/specs/toolchain.md`, "Environment resolution
113 /// on Windows"). On Windows cl does, and Clang and clang-cl target the
114 /// MSVC ABI and borrow its toolset; elsewhere none does (cl does not run
115 /// there, and is refused as not found). MinGW's GCC brings its own
116 /// headers, libraries and runtime. A new compiler must answer here
117 /// before it can be selected.
118 pub fn uses_msvc_toolset(self, host: HostOs) -> bool {
119 match self {
120 CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => {
121 host == HostOs::Windows
122 }
123 CompilerKind::Gcc => false,
124 }
125 }
126
127 /// Whether it borrows an MSVC toolset it is not part of: the Clangs do,
128 /// so `cuno doctor` names the toolset they use; cl's own is its
129 /// `Selected` line, and GCC uses none (`docs/en/specs/commands.md`,
130 /// "What `cuno doctor` prints").
131 pub fn borrows_msvc_toolset(self) -> bool {
132 match self {
133 CompilerKind::Clang | CompilerKind::ClangCl => true,
134 CompilerKind::Msvc | CompilerKind::Gcc => false,
135 }
136 }
137
138 /// Whether it builds against the MSVC standard library, whose switches
139 /// (`_HAS_EXCEPTIONS`) cuno sets: cl and the Clangs do, MinGW's GCC uses
140 /// libstdc++ (`docs/en/specs/build.md`, "Settings and flags").
141 pub fn uses_msvc_stl(self) -> bool {
142 match self {
143 CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => true,
144 CompilerKind::Gcc => false,
145 }
146 }
147
148 /// Whether the tools it runs open paths in the ANSI code page, so that
149 /// what they create or read must be named in ASCII: MinGW's assembler
150 /// and linker do (`docs/en/specs/toolchain.md`, "MinGW (GCC)"); cl,
151 /// the Clangs and lld open them as Unicode.
152 pub fn needs_ascii_paths(self) -> bool {
153 match self {
154 CompilerKind::Gcc => true,
155 CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => false,
156 }
157 }
158
159 /// The driver that links objects compiled by `program`, when any is C++
160 /// (`cxx`): GCC's `gcc` adds no C++ standard library, so C++ links with
161 /// the `g++` beside it (`docs/en/specs/build.md`, "Linking"); every other
162 /// driver links both languages.
163 pub fn link_driver(self, program: &Path, cxx: bool) -> PathBuf {
164 match self {
165 CompilerKind::Gcc if cxx => {
166 let mut name = std::ffi::OsString::from("g++");
167 if let Some(ext) = program.extension() {
168 name.push(".");
169 name.push(ext);
170 }
171 program.with_file_name(name)
172 }
173 CompilerKind::Gcc
174 | CompilerKind::Msvc
175 | CompilerKind::Clang
176 | CompilerKind::ClangCl => program.to_owned(),
177 }
178 }
179
180 /// Whether it prints the source's name on stdout for each compile, which
181 /// the build leaves out of what it shows: cl does, the LLVM drivers and
182 /// GCC do not.
183 pub fn echoes_source_name(self) -> bool {
184 match self {
185 CompilerKind::Msvc => true,
186 CompilerKind::Clang | CompilerKind::ClangCl | CompilerKind::Gcc => false,
187 }
188 }
189
190 /// Whether `cuno check` compiles as the build does, without linking,
191 /// rather than checking syntax alone: cl's `/Zs` misses diagnostics
192 /// raised during code generation (C4716, and C4700, C4701 and C4715
193 /// under `warnings-as-errors`), which clang and clang-cl report when
194 /// checking; GCC's `-fsyntax-only` misses those its optimiser raises
195 /// (`-Warray-bounds`, `-Wstringop-overflow`) (`docs/en/specs/build.md`,
196 /// "Always-on flags").
197 pub fn checks_by_compiling(self) -> bool {
198 match self {
199 CompilerKind::Msvc | CompilerKind::Gcc => true,
200 CompilerKind::Clang | CompilerKind::ClangCl => false,
201 }
202 }
203
204 /// How it says which headers a compile read.
205 pub fn dependencies(self) -> Dependencies {
206 match self {
207 CompilerKind::Msvc => Dependencies::SourceDependencies,
208 CompilerKind::Clang | CompilerKind::ClangCl | CompilerKind::Gcc => {
209 Dependencies::DepFile
210 }
211 }
212 }
213
214 /// The LLVM tool it is found as, for the LLVM family.
215 pub fn llvm_tool(self) -> Option<Tool> {
216 match self {
217 CompilerKind::Msvc | CompilerKind::Gcc => None,
218 CompilerKind::Clang => Some(Tool::Clang),
219 CompilerKind::ClangCl => Some(Tool::ClangCl),
220 }
221 }
222
223 /// The oldest version cuno supports (`toolchain.md`, "Minimum compiler
224 /// versions").
225 pub(crate) fn minimum(self) -> Version {
226 match self {
227 CompilerKind::Msvc => Version {
228 major: 19,
229 minor: 29,
230 patch: 0,
231 },
232 CompilerKind::Clang | CompilerKind::ClangCl => Version {
233 major: 17,
234 minor: 0,
235 patch: 0,
236 },
237 CompilerKind::Gcc => Version {
238 major: 10,
239 minor: 0,
240 patch: 0,
241 },
242 }
243 }
244
245 /// The compiler `name` names, or an error naming where it was given.
246 pub(crate) fn parse(name: &str, source: Source) -> Result<CompilerKind, ToolchainError> {
247 if let Some(kind) = CompilerKind::ALL.into_iter().find(|k| k.name() == name) {
248 return Ok(kind);
249 }
250 match name {
251 "safec" => Err(ToolchainError::UnsupportedCompiler {
252 name: name.to_owned(),
253 source: source.to_string(),
254 }),
255 _ => Err(ToolchainError::UnknownCompiler {
256 name: name.to_owned(),
257 source: source.to_string(),
258 }),
259 }
260 }
261
262 /// The names of every compiler, as a sentence: `msvc, clang, clang-cl or
263 /// gcc`.
264 pub(crate) fn names() -> String {
265 let names: Vec<&str> = CompilerKind::ALL.iter().map(|k| k.name()).collect();
266 match names.split_last() {
267 Some((last, [])) => (*last).to_owned(),
268 Some((last, rest)) => format!("{} or {last}", rest.join(", ")),
269 None => String::new(),
270 }
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277
278 /// On Windows every kind but GCC uses an MSVC toolset, and none does
279 /// elsewhere. Every kind is asked, so a new one is too.
280 ///
281 /// Mutation: answer false for clang on Windows, true elsewhere, or true
282 /// for GCC; this test fails.
283 #[test]
284 fn which_kinds_use_an_msvc_toolset() {
285 for kind in CompilerKind::ALL {
286 let windows = kind.uses_msvc_toolset(HostOs::Windows);
287 let other = kind.uses_msvc_toolset(HostOs::Other);
288 let want = match kind {
289 CompilerKind::Msvc | CompilerKind::Clang | CompilerKind::ClangCl => (true, false),
290 CompilerKind::Gcc => (false, false),
291 };
292 assert_eq!((windows, other), want, "{}", kind.name());
293 }
294 }
295
296 /// Mutation: answer true for clang, clang-cl or GCC, or false for MSVC;
297 /// this test fails.
298 #[test]
299 fn only_cl_echoes_the_source_name() {
300 assert!(CompilerKind::Msvc.echoes_source_name());
301 assert!(!CompilerKind::Clang.echoes_source_name());
302 assert!(!CompilerKind::ClangCl.echoes_source_name());
303 assert!(!CompilerKind::Gcc.echoes_source_name());
304 }
305
306 /// cl and GCC check by compiling, as their checks alone miss what code
307 /// generation raises; the LLVM drivers check syntax.
308 ///
309 /// Mutation: change the answer for any compiler; this test fails.
310 #[test]
311 fn cl_and_gcc_check_by_compiling() {
312 let by_compiling: Vec<bool> = CompilerKind::ALL
313 .iter()
314 .map(|k| k.checks_by_compiling())
315 .collect();
316 assert_eq!(by_compiling, [true, false, false, true]);
317 }
318
319 /// Mutation: leave a compiler out of `ALL`, list it twice, or reorder it;
320 /// this test fails. (A new variant does not compile here until this
321 /// match names it, which is the reminder to add it to `ALL`.)
322 #[test]
323 fn all_lists_every_compiler_once_in_order() {
324 let position = |kind: CompilerKind| match kind {
325 CompilerKind::Msvc => 0,
326 CompilerKind::Clang => 1,
327 CompilerKind::ClangCl => 2,
328 CompilerKind::Gcc => 3,
329 };
330 let positions: Vec<usize> = CompilerKind::ALL.iter().map(|k| position(*k)).collect();
331 assert_eq!(positions, (0..positions.len()).collect::<Vec<_>>());
332 assert_eq!(CompilerKind::ALL.len(), position(CompilerKind::Gcc) + 1);
333 }
334
335 /// GCC links C++ with the `g++` beside it, keeping the extension; every
336 /// other driver, and GCC for C, links with itself.
337 ///
338 /// Mutation: link GCC's C++ with `gcc`, its C with `g++`, or another
339 /// driver with `g++`; this test fails.
340 #[test]
341 fn gcc_links_cxx_with_g_plus_plus() {
342 let gcc = Path::new("C:/msys64/ucrt64/bin/gcc.exe");
343 assert_eq!(
344 CompilerKind::Gcc.link_driver(gcc, true),
345 Path::new("C:/msys64/ucrt64/bin/g++.exe")
346 );
347 assert_eq!(CompilerKind::Gcc.link_driver(gcc, false), gcc);
348 assert_eq!(
349 CompilerKind::Gcc.link_driver(Path::new("/usr/bin/gcc"), true),
350 Path::new("/usr/bin/g++")
351 );
352 for kind in [
353 CompilerKind::Msvc,
354 CompilerKind::Clang,
355 CompilerKind::ClangCl,
356 ] {
357 assert_eq!(
358 kind.link_driver(Path::new("x/cc.exe"), true),
359 Path::new("x/cc.exe")
360 );
361 }
362 }
363
364 /// Only GCC's tools open paths in the ANSI code page.
365 ///
366 /// Mutation: change the answer for any compiler; this test fails.
367 #[test]
368 fn only_gcc_needs_ascii_paths() {
369 let ascii: Vec<bool> = CompilerKind::ALL
370 .iter()
371 .map(|k| k.needs_ascii_paths())
372 .collect();
373 assert_eq!(ascii, [false, false, false, true]);
374 }
375
376 /// Mutation: say any compiler but GCC does not use the MSVC standard
377 /// library, or that GCC does; this test fails.
378 #[test]
379 fn only_gcc_brings_its_own_standard_library() {
380 let msvc_stl: Vec<bool> = CompilerKind::ALL
381 .iter()
382 .map(|k| k.uses_msvc_stl())
383 .collect();
384 assert_eq!(msvc_stl, [true, true, true, false]);
385 }
386
387 /// Mutation: say cl or GCC borrows a toolset, or a Clang does not; this
388 /// test fails.
389 #[test]
390 fn only_the_clangs_borrow_an_msvc_toolset() {
391 let borrows: Vec<(CompilerKind, bool)> = CompilerKind::ALL
392 .iter()
393 .map(|k| (*k, k.borrows_msvc_toolset()))
394 .collect();
395 assert_eq!(
396 borrows,
397 [
398 (CompilerKind::Msvc, false),
399 (CompilerKind::Clang, true),
400 (CompilerKind::ClangCl, true),
401 (CompilerKind::Gcc, false),
402 ]
403 );
404 }
405
406 /// Mutation: change any answer for any compiler; this test fails.
407 #[test]
408 fn each_compiler_answers_its_properties() {
409 let answers: Vec<_> = CompilerKind::ALL
410 .iter()
411 .map(|k| {
412 (
413 k.name(),
414 k.syntax(),
415 k.family(),
416 k.llvm_tool(),
417 k.dependencies(),
418 k.minimum().to_string(),
419 )
420 })
421 .collect();
422 let dep = Dependencies::DepFile;
423 let deps = Dependencies::SourceDependencies;
424 assert_eq!(
425 answers,
426 [
427 (
428 "msvc",
429 Syntax::Cl,
430 Family::Msvc,
431 None,
432 deps,
433 "19.29.0".to_owned()
434 ),
435 (
436 "clang",
437 Syntax::Gnu,
438 Family::Llvm,
439 Some(Tool::Clang),
440 dep,
441 "17.0.0".to_owned()
442 ),
443 (
444 "clang-cl",
445 Syntax::Cl,
446 Family::Llvm,
447 Some(Tool::ClangCl),
448 dep,
449 "17.0.0".to_owned()
450 ),
451 (
452 "gcc",
453 Syntax::Gnu,
454 Family::Gnu,
455 None,
456 dep,
457 "10.0.0".to_owned()
458 ),
459 ]
460 );
461 assert_eq!(CompilerKind::names(), "msvc, clang, clang-cl or gcc");
462 }
463}