Skip to main content

cuno_toolchain/flags/
clang_tools.rs

1//! A compile as the Clang-based tools read it: compile_commands.json, which
2//! clangd and `cuno lint` read, and `cuno doctor`'s clang-tidy check, which
3//! is to judge what `cuno lint` will run. Both build the command here: only
4//! [`for_clang_tools`] makes a [`ToolCommand`], so the two cannot come to
5//! give a tool different arguments, as they did before (`docs/en/specs/
6//! build.md`, "Output"; `docs/en/specs/toolchain.md`, "Minimum compiler
7//! versions").
8
9use std::ffi::{OsStr, OsString};
10use std::path::PathBuf;
11
12use super::Edition;
13use super::compile::{TARGET_SWITCH, standard};
14use crate::Version;
15use crate::compiler::{CompilerKind, Family, Syntax};
16use crate::select::Selected;
17
18/// What a Clang-based tool is told about the compiler a build ran with,
19/// besides its arguments.
20#[derive(Clone, Copy, Debug)]
21pub struct ToolContext<'a> {
22    /// The compiler.
23    pub kind: CompilerKind,
24    /// The resolved `INCLUDE`, in order (`Prepared::include_dirs`).
25    pub include: &'a [PathBuf],
26    /// The cl version of the MSVC toolset, whose `_MSC_VER` the build sees;
27    /// `None` without a toolset, when no version is written.
28    pub msvc: Option<&'a Version>,
29    /// GCC's version, whose `__GNUC__` the build sees, for GCC; `None`
30    /// otherwise.
31    pub gnuc: Option<&'a Version>,
32}
33
34impl<'a> ToolContext<'a> {
35    /// What a tool is told about `selected`, whose environment gives
36    /// `include` (`Prepared::include_dirs`). Which versions the build sees,
37    /// and through which macro, are read from `selected` here, once for
38    /// every caller: a tool told the wrong one analyses other code than the
39    /// build compiles.
40    pub fn of(selected: &'a Selected, include: &'a [PathBuf]) -> ToolContext<'a> {
41        ToolContext {
42            kind: selected.kind,
43            include,
44            msvc: selected.msvc.as_ref().map(|toolset| &toolset.cl_version),
45            gnuc: match selected.kind.family() {
46                Family::Gnu => Some(&selected.version),
47                Family::Msvc | Family::Llvm => None,
48            },
49        }
50    }
51}
52
53/// One compile as a Clang-based tool reads it. Only [`for_clang_tools`]
54/// makes one, so compile_commands.json and doctor's check cannot come to
55/// build it differently.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct ToolCommand {
58    args: Vec<OsString>,
59    kind: CompilerKind,
60}
61
62impl ToolCommand {
63    /// The arguments after the compiler's program, as compile_commands.json
64    /// writes them: a tool there learns from the program which driver and
65    /// target to read them as. Given after `--` instead, they need
66    /// [`ToolCommand::after_double_dash`].
67    pub fn args(&self) -> &[OsString] {
68        &self.args
69    }
70
71    /// The arguments as given after `--`, where there is no program: a
72    /// cl-style command is read as clang-cl's only with `--driver-mode=cl`,
73    /// and cl's own flags name no target, so MSVC's gets the one it builds
74    /// for. An LLVM driver's flags already name it. The source is among
75    /// them; a tool given its file before `--` is given it once only if the
76    /// caller leaves it out here.
77    pub fn after_double_dash(&self) -> Vec<OsString> {
78        let mut out = Vec::new();
79        match self.kind.syntax() {
80            Syntax::Cl => out.push("--driver-mode=cl".into()),
81            Syntax::Gnu => {}
82        }
83        match self.kind.family() {
84            Family::Msvc => out.push(TARGET_SWITCH.into()),
85            // GCC's is in the command itself (`for_clang_tools`).
86            Family::Llvm | Family::Gnu => {}
87        }
88        out.extend(self.args.iter().cloned());
89        out
90    }
91}
92
93/// `args`, a compile's arguments for `context.kind` from
94/// [`compile_args`](super::compile_args), as the Clang-based tools must see
95/// them to analyse what the compiler builds: `/c` written `-c`, and for cl
96/// a standard switch clang-cl does not know written as its own and `/GL`
97/// left out, as clang-cl reads a cl command; `INCLUDE` after the tool's own
98/// headers (`/imsvc`, or for clang `-nostdlibinc` and then `-idirafter`, as
99/// clang would otherwise search the environment's headers first), written
100/// before the compile's arguments so a user's own `-idirafter` is searched
101/// after it, as in the build; and the MSVC version, so a tool run anywhere
102/// sees what the build saw. Why each is written so is in
103/// `docs/en/specs/build.md`, "Output".
104pub fn for_clang_tools(context: ToolContext<'_>, args: &[OsString]) -> ToolCommand {
105    let kind = context.kind;
106    let mut include: Vec<OsString> = Vec::new();
107    match kind.syntax() {
108        Syntax::Gnu if !context.include.is_empty() => include.push("-nostdlibinc".into()),
109        Syntax::Gnu | Syntax::Cl => {}
110    }
111    for dir in context.include {
112        match kind.syntax() {
113            Syntax::Cl => {
114                let mut arg = OsString::from("/imsvc");
115                arg.push(dir);
116                include.push(arg);
117            }
118            Syntax::Gnu => {
119                include.push("-idirafter".into());
120                include.push(dir.into());
121            }
122        }
123    }
124    let mut out = args.to_vec();
125    match kind.syntax() {
126        Syntax::Cl => {
127            for arg in &mut out {
128                if arg == "/c" {
129                    *arg = "-c".into();
130                }
131            }
132        }
133        Syntax::Gnu => {}
134    }
135    match kind {
136        CompilerKind::Msvc => {
137            out.retain(|arg| arg != "/GL");
138            for arg in &mut out {
139                let same = Edition::ALL
140                    .iter()
141                    .find(|(edition, _)| *arg == standard(CompilerKind::Msvc, *edition));
142                if let Some((edition, _)) = same {
143                    *arg = standard(CompilerKind::ClangCl, *edition).into();
144                }
145            }
146        }
147        CompilerKind::ClangCl | CompilerKind::Clang | CompilerKind::Gcc => {}
148    }
149    // A tool reading `gcc`'s command learns no target from its name, and
150    // reads MinGW's headers as the MSVC ABI's otherwise (build.md, "Output").
151    match kind.family() {
152        Family::Gnu => include.insert(0, format!("--target={}", crate::select::GCC_TARGET).into()),
153        Family::Msvc | Family::Llvm => {}
154    }
155    out.splice(0..0, include);
156    if let Some(version) = context.msvc {
157        out.push(format!("-fms-compatibility-version={version}").into());
158    }
159    // Clang otherwise claims GCC 4.2.1, and `#if __GNUC__ >= 10` would read
160    // otherwise than the build.
161    if let Some(version) = context.gnuc {
162        out.push(format!("-fgnuc-version={version}").into());
163    }
164    ToolCommand { args: out, kind }
165}
166
167/// The directories of an `INCLUDE` value, in order. An empty entry (`a;;b`,
168/// or a trailing `;`) names no directory and is left out, rather than
169/// written as an empty include directory.
170pub(crate) fn include_dirs(include: Option<&OsStr>) -> Vec<PathBuf> {
171    include
172        .map(|dirs| {
173            std::env::split_paths(dirs)
174                .filter(|dir| !dir.as_os_str().is_empty())
175                .collect()
176        })
177        .unwrap_or_default()
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    /// Each compiler's tools are told the version macros its builds see,
185    /// read from the selection: GCC's version as `__GNUC__`, and the cl
186    /// version of the toolset a compiler builds with as `_MSC_VER`. Every
187    /// kind is asked, with and without a toolset.
188    ///
189    /// Mutation: give GCC no version, or give a compiler other than GCC
190    /// one, or drop or misread the toolset's version; this test fails.
191    #[test]
192    fn each_compiler_s_tools_are_told_the_versions_its_builds_see() {
193        use crate::msvc::MsvcToolset;
194        use crate::select::Source;
195        let version = Version::find_in("16.2.0").unwrap();
196        let cl = Version::find_in("19.44.35207").unwrap();
197        for kind in CompilerKind::ALL {
198            for with_toolset in [false, true] {
199                let selected = Selected {
200                    kind,
201                    executable: PathBuf::from("C:/bin/cc.exe"),
202                    version,
203                    msvc: with_toolset.then(|| MsvcToolset {
204                        dir: PathBuf::from("C:/VS/VC/Tools/MSVC/14.44.35207"),
205                        cl_version: cl,
206                    }),
207                    source: Source::CommandLine,
208                };
209                let context = ToolContext::of(&selected, &[]);
210                let what = format!("{} with_toolset={with_toolset}", kind.name());
211                assert_eq!(context.kind, kind, "{what}");
212                assert_eq!(
213                    context.gnuc.map(ToString::to_string),
214                    (kind == CompilerKind::Gcc).then(|| "16.2.0".to_owned()),
215                    "{what}"
216                );
217                assert_eq!(
218                    context.msvc.map(ToString::to_string),
219                    with_toolset.then(|| "19.44.35207".to_owned()),
220                    "{what}"
221                );
222            }
223        }
224    }
225
226    fn strings(args: &[OsString]) -> Vec<String> {
227        args.iter()
228            .map(|a| a.to_string_lossy().into_owned())
229            .collect()
230    }
231
232    fn os(args: &[&str]) -> Vec<OsString> {
233        args.iter().map(OsString::from).collect()
234    }
235
236    /// The include directories come after the tool's own headers, in the
237    /// form each driver reads, clang's alone with `-nostdlibinc` so the
238    /// environment's are not searched first, then the MSVC version when
239    /// there is a toolset (`docs/en/specs/build.md`, "Output").
240    ///
241    /// Mutation: give clang `/imsvc` or `-isystem`, give a cl-style driver
242    /// `-idirafter` or `-nostdlibinc`, leave `-nostdlibinc` out for clang or
243    /// give it without include directories, drop a directory, change their
244    /// order, write them after the compile's arguments (a user's
245    /// `-idirafter` is then searched first), or leave out the version or
246    /// add one without a toolset; this test fails.
247    #[test]
248    fn include_and_version_follow_the_driver() {
249        let include = [
250            PathBuf::from("C:/sdk/ucrt"),
251            PathBuf::from("C:/msvc/include"),
252        ];
253        let version = Version::find_in("19.52.37029").unwrap();
254        let context = |kind, msvc| ToolContext {
255            kind,
256            include: &include,
257            msvc,
258            gnuc: None,
259        };
260        let args = os(&["-c", "a.cpp"]);
261        for kind in [CompilerKind::Msvc, CompilerKind::ClangCl] {
262            assert_eq!(
263                strings(for_clang_tools(context(kind, Some(&version)), &args).args()),
264                [
265                    "/imsvcC:/sdk/ucrt",
266                    "/imsvcC:/msvc/include",
267                    "-c",
268                    "a.cpp",
269                    "-fms-compatibility-version=19.52.37029"
270                ],
271                "{kind:?}"
272            );
273        }
274        assert_eq!(
275            strings(for_clang_tools(context(CompilerKind::Clang, None), &args).args()),
276            [
277                "-nostdlibinc",
278                "-idirafter",
279                "C:/sdk/ucrt",
280                "-idirafter",
281                "C:/msvc/include",
282                "-c",
283                "a.cpp"
284            ]
285        );
286        // A user's own `-idirafter` in the compile's arguments stays after
287        // the toolset's, as the build searches it.
288        let user = os(&["-idirafter", "extra", "-c", "a.cpp"]);
289        assert_eq!(
290            strings(for_clang_tools(context(CompilerKind::Clang, None), &user).args()),
291            [
292                "-nostdlibinc",
293                "-idirafter",
294                "C:/sdk/ucrt",
295                "-idirafter",
296                "C:/msvc/include",
297                "-idirafter",
298                "extra",
299                "-c",
300                "a.cpp"
301            ]
302        );
303        let none = ToolContext {
304            kind: CompilerKind::Clang,
305            include: &[],
306            msvc: None,
307            gnuc: None,
308        };
309        assert_eq!(
310            strings(for_clang_tools(none, &args).args()),
311            ["-c", "a.cpp"]
312        );
313    }
314
315    /// Mutation: keep cl's `/c`, `/std:c++23`, `/std:clatest` or `/GL`, or
316    /// rewrite them for clang-cl, which takes its own; this test fails.
317    #[test]
318    fn a_cl_command_is_rewritten_as_clang_cl_reads_it() {
319        let context = |kind| ToolContext {
320            kind,
321            include: &[],
322            msvc: None,
323            gnuc: None,
324        };
325        for (switch, as_clang_cl) in [
326            ("/std:c++23", "/clang:-std=c++23"),
327            ("/std:clatest", "/clang:-std=c2x"),
328            ("/std:c++20", "/std:c++20"),
329        ] {
330            let args = os(&["/c", switch, "/GL", "a.cpp"]);
331            assert_eq!(
332                strings(for_clang_tools(context(CompilerKind::Msvc), &args).args()),
333                ["-c", as_clang_cl, "a.cpp"],
334                "{switch}"
335            );
336        }
337        let args = os(&["/c", "/clang:-std=c++23", "a.cpp"]);
338        assert_eq!(
339            strings(for_clang_tools(context(CompilerKind::ClangCl), &args).args()),
340            ["-c", "/clang:-std=c++23", "a.cpp"]
341        );
342    }
343
344    /// After `--`, a cl-style command is read as clang-cl's and MSVC's
345    /// names its target; clang's names its own (`docs/en/specs/
346    /// toolchain.md`, "Minimum compiler versions").
347    ///
348    /// Mutation: leave out `--driver-mode=cl` for MSVC or clang-cl, give it
349    /// to clang, leave out the target for MSVC or add it for an LLVM
350    /// driver, or put them after the arguments; this test fails.
351    #[test]
352    fn after_double_dash_names_the_driver_and_target_a_program_would() {
353        let expected: [(CompilerKind, &[&str]); 4] = [
354            (
355                CompilerKind::Msvc,
356                &["--driver-mode=cl", TARGET_SWITCH, "-c"],
357            ),
358            (CompilerKind::ClangCl, &["--driver-mode=cl", "-c"]),
359            (CompilerKind::Clang, &["-c"]),
360            // GCC's target is in its command, once.
361            (CompilerKind::Gcc, &["--target=x86_64-w64-mingw32", "-c"]),
362        ];
363        for (kind, want) in expected {
364            let context = ToolContext {
365                kind,
366                include: &[],
367                msvc: None,
368                gnuc: None,
369            };
370            let command = for_clang_tools(context, &os(&["-c"]));
371            assert_eq!(strings(&command.after_double_dash()), want, "{kind:?}");
372        }
373    }
374
375    /// GCC's command names its target, MinGW-w64, before its include
376    /// directories, which are written as clang's are, and GCC's version
377    /// after: a tool reading `gcc` learns no target from the name and would
378    /// read MinGW's headers as the MSVC ABI's, and would claim GCC 4.2.1
379    /// (`docs/en/specs/build.md`, "Output").
380    ///
381    /// Mutation: leave the target or the version out, write the target for
382    /// another driver, or write GCC's directories otherwise than clang's;
383    /// this test fails.
384    #[test]
385    fn gcc_s_command_names_its_target() {
386        let include = [PathBuf::from("C:/m/include")];
387        let gcc = Version::find_in("16.2.0").unwrap();
388        let context = |kind| ToolContext {
389            kind,
390            include: &include,
391            msvc: None,
392            gnuc: (kind == CompilerKind::Gcc).then_some(&gcc),
393        };
394        let args = os(&["-c", "a.c"]);
395        assert_eq!(
396            strings(for_clang_tools(context(CompilerKind::Gcc), &args).args()),
397            [
398                "--target=x86_64-w64-mingw32",
399                "-nostdlibinc",
400                "-idirafter",
401                "C:/m/include",
402                "-c",
403                "a.c",
404                "-fgnuc-version=16.2.0"
405            ]
406        );
407        for kind in [
408            CompilerKind::Msvc,
409            CompilerKind::ClangCl,
410            CompilerKind::Clang,
411        ] {
412            let args = strings(for_clang_tools(context(kind), &args).args());
413            assert!(
414                !args.iter().any(|a| a.contains("mingw32")),
415                "{kind:?} {args:?}"
416            );
417        }
418    }
419
420    /// Mutation: keep an empty entry, or change the order; this test fails.
421    #[test]
422    fn include_dirs_keep_the_order_and_drop_empty_entries() {
423        let value = OsString::from("C:\\a;;C:\\b;");
424        assert_eq!(
425            include_dirs(Some(&value)),
426            [PathBuf::from("C:\\a"), PathBuf::from("C:\\b")]
427        );
428        assert!(include_dirs(None).is_empty());
429    }
430}