1use std::ffi::{OsStr, OsString};
8use std::path::Path;
9use std::sync::atomic::{AtomicU32, Ordering};
10
11use cuno_core::Env;
12
13use crate::compiler::Family;
14use crate::flags::{CompileInput, Mode, ToolContext, compile_args, for_clang_tools};
15use crate::select::{LlvmChoice, Selected};
16use crate::{Runner, ToolchainError, Version};
17
18#[derive(Clone, Copy, Debug)]
20pub struct ProbeInputs<'a> {
21 pub scratch: &'a Path,
23 pub input: &'a CompileInput<'a>,
30 pub cwd: &'a Path,
35}
36
37pub fn applies(selected: &Selected) -> bool {
42 match selected.kind.family() {
43 Family::Llvm => selected.msvc.is_some(),
44 Family::Msvc | Family::Gnu => false,
45 }
46}
47
48pub fn check(
54 selected: &Selected,
55 env: &Env,
56 inputs: ProbeInputs<'_>,
57 run: &dyn Runner,
58) -> Result<(), ToolchainError> {
59 if !applies(selected) {
60 return Ok(());
61 }
62 stl_probe(
63 selected.kind.name(),
64 selected.version,
65 inputs.scratch,
66 |probe| {
67 let args = check_command(&inputs, probe);
68 run.run_in(&selected.executable, &as_args(&args), env, inputs.cwd)
69 },
70 )
71}
72
73fn check_command(inputs: &ProbeInputs<'_>, probe: &Path) -> Vec<OsString> {
76 let input = CompileInput {
77 mode: Mode::Check,
78 ..*inputs.input
79 };
80 compile_args(&input, probe, None)
81}
82
83pub fn check_tidy(
93 tidy: &LlvmChoice,
94 env: &Env,
95 context: ToolContext<'_>,
96 inputs: ProbeInputs<'_>,
97 run: &dyn Runner,
98) -> Result<(), ToolchainError> {
99 stl_probe("clang-tidy", tidy.version, inputs.scratch, |probe| {
100 let mut args: Vec<OsString> = vec![
101 "--checks=-*,readability-braces-around-statements".into(),
102 "--config={}".into(),
103 probe.into(),
104 "--".into(),
105 ];
106 let input = CompileInput {
108 mode: Mode::Compile,
109 ..*inputs.input
110 };
111 let command = for_clang_tools(context, &compile_args(&input, probe, None));
112 args.extend(
113 command
114 .after_double_dash()
115 .into_iter()
116 .filter(|arg| arg.as_os_str() != probe.as_os_str()),
117 );
118 run.run_in(&tidy.path, &as_args(&args), env, inputs.cwd)
119 })
120}
121
122fn as_args(args: &[OsString]) -> Vec<&OsStr> {
123 args.iter().map(|a| a.as_os_str()).collect()
124}
125
126fn stl_probe(
130 name: &'static str,
131 version: Version,
132 scratch: &Path,
133 invoke: impl FnOnce(&Path) -> std::io::Result<crate::Output>,
134) -> Result<(), ToolchainError> {
135 let failed = |output: String| ToolchainError::ProbeFailed {
136 compiler: name,
137 output,
138 };
139 static NEXT: AtomicU32 = AtomicU32::new(0);
142 let probe = scratch.join(format!(
143 "cuno-stl-probe-{}-{}.cpp",
144 std::process::id(),
145 NEXT.fetch_add(1, Ordering::Relaxed)
146 ));
147 std::fs::write(&probe, "#include <yvals_core.h>\n")
148 .map_err(|e| failed(format!("could not write {}: {e}", probe.display())))?;
149 let output = invoke(&probe);
150 let _ = std::fs::remove_file(&probe);
151 let output = output.map_err(|e| failed(e.to_string()))?;
152 if output.success {
153 return Ok(());
154 }
155 let text = format!(
156 "{}{}",
157 String::from_utf8_lossy(&output.stdout),
158 String::from_utf8_lossy(&output.stderr)
159 );
160 match text.lines().find(|line| line.contains("STL1000:")) {
161 Some(line) => Err(ToolchainError::RejectedByStl {
162 compiler: name,
163 version,
164 needed: needed_clang(line),
165 message: line.trim().to_owned(),
166 }),
167 None => Err(failed(text.trim().to_owned())),
168 }
169}
170
171fn needed_clang(message: &str) -> Option<String> {
174 let rest = &message[message.find("expected Clang ")? + "expected Clang ".len()..];
175 let version = &rest[..rest.find(" or newer")?];
176 (!version.is_empty()).then(|| version.to_owned())
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use crate::Output;
183 use crate::compiler::CompilerKind;
184 use crate::flags::{
185 BuildSettings, Edition, Lang, OptLevel, ProfileSettings, Runtime, TARGET_SWITCH, Warnings,
186 };
187 use crate::msvc::MsvcToolset;
188 use crate::select::Source;
189 use std::cell::RefCell;
190 use std::path::PathBuf;
191
192 fn v(major: u32, minor: u32, patch: u32) -> Version {
193 Version {
194 major,
195 minor,
196 patch,
197 }
198 }
199
200 fn toolset(path: &str, version: Version) -> MsvcToolset {
202 MsvcToolset {
203 dir: Path::new(path).join(format!("VC/Tools/MSVC/{version}")),
204 cl_version: version,
205 }
206 }
207
208 struct Answers {
210 ok: bool,
211 stdout: &'static str,
212 stderr: &'static str,
213 args: RefCell<Vec<String>>,
214 calls: RefCell<u32>,
215 }
216
217 fn answers(ok: bool, stdout: &'static str, stderr: &'static str) -> Answers {
218 Answers {
219 ok,
220 stdout,
221 stderr,
222 args: Default::default(),
223 calls: Default::default(),
224 }
225 }
226
227 impl Runner for Answers {
228 fn run(&self, _p: &Path, args: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
229 *self.calls.borrow_mut() += 1;
230 *self.args.borrow_mut() = args
231 .iter()
232 .map(|a| a.to_string_lossy().into_owned())
233 .collect();
234 Ok(Output {
235 success: self.ok,
236 stdout: self.stdout.as_bytes().to_vec(),
237 stderr: self.stderr.as_bytes().to_vec(),
238 })
239 }
240 }
241
242 struct CannotStart;
243 impl Runner for CannotStart {
244 fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
245 Err(std::io::Error::other("cannot start"))
246 }
247 }
248
249 struct TimesOut;
251 impl Runner for TimesOut {
252 fn run(&self, _p: &Path, _a: &[&OsStr], _e: &Env) -> std::io::Result<Output> {
253 Err(std::io::Error::new(
254 std::io::ErrorKind::TimedOut,
255 "did not finish within 30 seconds and was stopped",
256 ))
257 }
258 }
259
260 fn selected(kind: CompilerKind) -> Selected {
261 Selected {
262 kind,
263 executable: "clang".into(),
264 version: v(20, 1, 8),
265 msvc: Some(toolset("VS", v(19, 52, 1))),
266 source: Source::CommandLine,
267 }
268 }
269
270 fn no_rtti() -> (BuildSettings, ProfileSettings) {
273 let build = BuildSettings {
274 warnings: Warnings::Default,
275 warnings_as_errors: false,
276 defines: vec!["_HAS_STATIC_RTTI=0".into()],
277 include_dirs: vec![],
278 links: vec![],
279 lib_dirs: vec![],
280 link_flags: vec![],
281 flags: vec![],
282 runtime: Runtime::Dynamic,
283 exceptions: true,
284 rtti: false,
285 };
286 let profile = ProfileSettings {
287 opt_level: OptLevel::O0,
288 debug_info: false,
289 debug_assertions: true,
290 lto: false,
291 };
292 (build, profile)
293 }
294
295 fn no_context(kind: CompilerKind) -> ToolContext<'static> {
297 ToolContext {
298 kind,
299 include: &[],
300 msvc: None,
301 gnuc: None,
302 }
303 }
304
305 fn input(
307 kind: CompilerKind,
308 settings: &(BuildSettings, ProfileSettings),
309 mode: Mode,
310 ) -> CompileInput<'_> {
311 CompileInput {
312 kind,
313 lang: Lang::Cxx,
314 edition: Edition::Cxx20,
315 build: &settings.0,
316 profile: &settings.1,
317 include_dirs: &[],
318 test: false,
319 mode,
320 }
321 }
322
323 fn strings(args: Vec<OsString>) -> Vec<String> {
324 args.into_iter().map(|a| a.into_string().unwrap()).collect()
325 }
326
327 #[test]
332 fn the_probe_verdict_follows_the_standard_library() {
333 let root = tempfile::tempdir().unwrap();
334 let settings = no_rtti();
335 let compile = input(CompilerKind::Clang, &settings, Mode::Check);
336 let inputs = ProbeInputs {
337 scratch: root.path(),
338 input: &compile,
339 cwd: root.path(),
340 };
341 let clang = selected(CompilerKind::Clang);
342 let stl = "x\\yvals_core.h(922,1): error: STL1000: Unexpected compiler version, expected Clang 22 or newer.\n";
343 let err = check(&clang, &Env::default(), inputs, &answers(false, "", stl)).unwrap_err();
344 assert_eq!(
345 err.to_string(),
346 "clang 20.1.8 is not accepted by the MSVC standard library in use (STL1000)"
347 );
348 let ToolchainError::RejectedByStl {
349 needed, message, ..
350 } = &err
351 else {
352 panic!("{err:?}");
353 };
354 assert_eq!(
355 (needed.as_deref(), message.as_str()),
356 (Some("22"), stl.trim())
357 );
358
359 let err = check(
360 &clang,
361 &Env::default(),
362 inputs,
363 &answers(false, "fatal error: 'yvals_core.h' file not found", ""),
364 )
365 .unwrap_err();
366 assert!(
367 matches!(&err, ToolchainError::ProbeFailed { compiler: "clang", output } if output == "fatal error: 'yvals_core.h' file not found"),
368 "{err:?}"
369 );
370 let err = check(&clang, &Env::default(), inputs, &TimesOut).unwrap_err();
371 assert!(
372 matches!(&err, ToolchainError::ProbeFailed { output, .. } if output.contains("within 30 seconds")),
373 "{err:?}"
374 );
375 let err = check(&clang, &Env::default(), inputs, &CannotStart).unwrap_err();
376 assert!(
377 matches!(&err, ToolchainError::ProbeFailed { output, .. } if output == "cannot start"),
378 "{err:?}"
379 );
380 check(&clang, &Env::default(), inputs, &answers(true, "", "")).unwrap();
381 assert_eq!(
382 std::fs::read_dir(root.path()).unwrap().count(),
383 0,
384 "probe file left behind"
385 );
386
387 assert_eq!(
388 needed_clang("expected Clang 17.0.0 or newer."),
389 Some("17.0.0".into())
390 );
391 assert_eq!(needed_clang("expected Clang or newer."), None);
392 assert_eq!(needed_clang("STL1000: Unexpected compiler version"), None);
393 }
394
395 #[test]
406 fn the_probe_runs_the_builds_command_in_check_mode() {
407 let root = tempfile::tempdir().unwrap();
408 let settings = no_rtti();
409 let mut probes = Vec::new();
410 for (kind, switch, cxx, rtti) in [
411 (CompilerKind::Clang, "-fsyntax-only", "c++", "-fno-rtti"),
412 (CompilerKind::ClangCl, "/Zs", "/TP", "/GR-"),
413 ] {
414 let handed = input(kind, &settings, Mode::Compile);
415 let inputs = ProbeInputs {
416 scratch: root.path(),
417 input: &handed,
418 cwd: root.path(),
419 };
420 let run = answers(true, "", "");
421 check(&selected(kind), &Env::default(), inputs, &run).unwrap();
422 let args = run.args.borrow().clone();
423 let probe = args.last().unwrap().clone();
424 assert!(probe.ends_with(".cpp"), "{probe}");
425 let expected = strings(compile_args(
426 &input(kind, &settings, Mode::Check),
427 Path::new(&probe),
428 None,
429 ));
430 assert_eq!(args, expected, "{kind:?}");
431 assert_eq!(args[0], switch, "{kind:?}");
432 for needed in [cxx, rtti, "-D_HAS_STATIC_RTTI=0"] {
433 let needed = match kind {
434 CompilerKind::ClangCl if needed.starts_with("-D") => "/D_HAS_STATIC_RTTI=0",
435 _ => needed,
436 };
437 assert!(args.iter().any(|a| a == needed), "{kind:?}: {args:?}");
438 }
439 assert_eq!(
440 args.iter().filter(|a| a.starts_with("--target")).count(),
441 1,
442 "{kind:?}: {args:?}"
443 );
444 probes.push(probe);
445 }
446 assert_ne!(probes[0], probes[1]);
447
448 let compile = input(CompilerKind::Msvc, &settings, Mode::Check);
449 let inputs = ProbeInputs {
450 scratch: root.path(),
451 input: &compile,
452 cwd: root.path(),
453 };
454 let never = answers(false, "STL1000:", "");
455 check(
456 &selected(CompilerKind::Msvc),
457 &Env::default(),
458 inputs,
459 &never,
460 )
461 .unwrap();
462 let mut elsewhere = selected(CompilerKind::Clang);
463 elsewhere.msvc = None;
464 check(&elsewhere, &Env::default(), inputs, &never).unwrap();
465 assert_eq!(*never.calls.borrow(), 0);
466 }
467
468 #[test]
482 fn clang_tidy_is_asked_the_standard_librarys_verdict() {
483 let root = tempfile::tempdir().unwrap();
484 let settings = no_rtti();
485 let tidy = LlvmChoice {
486 path: "clang-tidy".into(),
487 version: v(20, 1, 8),
488 };
489 let stl = "x\\yvals_core.h(922,1): error: STL1000: Unexpected compiler version, expected Clang 22 or newer. [clang-diagnostic-error]\n";
490 let include = [PathBuf::from("C:/inc")];
491 let version = v(19, 52, 1);
492 let context = |kind| ToolContext {
493 kind,
494 include: &include,
495 msvc: Some(&version),
496 gnuc: None,
497 };
498 let msvc = input(CompilerKind::Msvc, &settings, Mode::Check);
499 let err = check_tidy(
500 &tidy,
501 &Env::default(),
502 context(CompilerKind::Msvc),
503 ProbeInputs {
504 scratch: root.path(),
505 input: &msvc,
506 cwd: root.path(),
507 },
508 &answers(false, stl, ""),
509 )
510 .unwrap_err();
511 assert_eq!(
512 err.to_string(),
513 "clang-tidy 20.1.8 is not accepted by the MSVC standard library in use (STL1000)"
514 );
515 assert_eq!(
516 cuno_core::CunoError::help(&err).unwrap(),
517 "install clang-tidy 22 or newer"
518 );
519
520 for (kind, mode) in [
521 (CompilerKind::Msvc, &["--driver-mode=cl", TARGET_SWITCH][..]),
522 (CompilerKind::ClangCl, &["--driver-mode=cl"][..]),
523 (CompilerKind::Clang, &[][..]),
524 ] {
525 let handed = input(kind, &settings, Mode::Check);
526 let inputs = ProbeInputs {
527 scratch: root.path(),
528 input: &handed,
529 cwd: root.path(),
530 };
531 let run = answers(true, "", "");
532 check_tidy(&tidy, &Env::default(), context(kind), inputs, &run).unwrap();
533 let compile = input(kind, &settings, Mode::Compile);
534 let args = run.args.borrow().clone();
535 assert_eq!(args[0], "--checks=-*,readability-braces-around-statements");
536 let probe = &args[2];
537 assert!(probe.ends_with(".cpp"), "{args:?}");
538 let command: Vec<String> = strings(
539 for_clang_tools(
540 context(kind),
541 &compile_args(&compile, Path::new(probe), None),
542 )
543 .args()
544 .to_vec(),
545 )
546 .into_iter()
547 .filter(|a| a != probe)
548 .collect();
549 for each in ["-fms-compatibility-version=19.52.1", "C:/inc"] {
550 assert!(args.iter().any(|a| a.contains(each)), "{kind:?}: {args:?}");
551 }
552 let expected: Vec<String> = ["--"]
553 .iter()
554 .chain(mode)
555 .map(|s| (*s).to_owned())
556 .chain(command)
557 .collect();
558 assert_eq!(args[3..], expected, "{kind:?}");
559 assert_eq!(
560 args.iter().filter(|a| a.starts_with("--target")).count(),
561 1,
562 "{kind:?}: {args:?}"
563 );
564 }
565 assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 0);
566 }
567
568 #[test]
576 fn clang_tidy_reads_an_msvc_standard_as_clang_cl_does() {
577 let root = tempfile::tempdir().unwrap();
578 let settings = no_rtti();
579 let mut compile = input(CompilerKind::Msvc, &settings, Mode::Check);
580 compile.edition = Edition::Cxx23;
581 let run = answers(true, "", "");
582 let tidy = LlvmChoice {
583 path: "clang-tidy".into(),
584 version: v(22, 1, 8),
585 };
586 let inputs = ProbeInputs {
587 scratch: root.path(),
588 input: &compile,
589 cwd: root.path(),
590 };
591 check_tidy(
592 &tidy,
593 &Env::default(),
594 no_context(CompilerKind::Msvc),
595 inputs,
596 &run,
597 )
598 .unwrap();
599 let args = run.args.borrow().clone();
600 assert!(args.iter().any(|a| a == "/clang:-std=c++23"), "{args:?}");
601 assert!(!args.iter().any(|a| a == "/std:c++23"), "{args:?}");
602 }
603
604 #[test]
609 fn clang_tidy_is_not_given_link_time_optimization() {
610 let root = tempfile::tempdir().unwrap();
611 let mut settings = no_rtti();
612 settings.1.lto = true;
613 let compile = input(CompilerKind::Msvc, &settings, Mode::Check);
614 let built = strings(compile_args(&compile, Path::new("x.cpp"), None));
615 assert!(built.iter().any(|a| a == "/GL"), "{built:?}");
616 let run = answers(true, "", "");
617 let tidy = LlvmChoice {
618 path: "clang-tidy".into(),
619 version: v(22, 1, 8),
620 };
621 let inputs = ProbeInputs {
622 scratch: root.path(),
623 input: &compile,
624 cwd: root.path(),
625 };
626 check_tidy(
627 &tidy,
628 &Env::default(),
629 no_context(CompilerKind::Msvc),
630 inputs,
631 &run,
632 )
633 .unwrap();
634 let args = run.args.borrow().clone();
635 assert!(!args.iter().any(|a| a == "/GL"), "{args:?}");
636 }
637}