c-shell 0.1.1

An interactive shell for C: type an expression, a statement or a function and see what your real compiler does with it
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Finding a C compiler and speaking its flag dialect.

use anyhow::{Context, Result, bail};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use crate::proc;

/// Deadline for every probe: a compiler that needs longer than this to
/// answer `--version` or build ten lines is effectively hung, and a hung
/// probe would otherwise freeze startup before the prompt even appears.
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);

/// `.output()` with a deadline; `None` covers spawn failure and timeout
/// alike — for a probe those are the same answer.
fn probe_output(cmd: &mut Command) -> Option<proc::Captured> {
    let cap = proc::run_captured(cmd, PROBE_TIMEOUT, false).ok()?;
    cap.status.is_some().then_some(cap)
}

/// Which flag dialect a compiler speaks. Version numbers are deliberately
/// not part of this: capabilities are probed by trial compile, never derived
/// from a version string.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Family {
    Gnu,
    Clang,
    /// `cl.exe`, and `clang-cl` which mimics its command line.
    Msvc,
}

#[derive(Clone, Debug)]
pub struct Toolchain {
    pub path: PathBuf,
    pub family: Family,
    /// First line of the compiler's own version banner.
    pub version: String,
    /// The `-std=` value to pass, or empty to leave the compiler on its own
    /// default. Empty is the normal state: what a plain `gcc foo.c` does on
    /// this machine is exactly what the tool exists to demonstrate.
    pub std: String,
    /// What a flag-less compile actually is (e.g. "gnu23"), reported by the
    /// compiler itself via `__STDC_VERSION__` / `__STRICT_ANSI__`.
    pub default_std: Option<String>,
    /// Set when `std` was forced by us rather than the user, because the
    /// compiler's default mode cannot host the `_Generic` value printer
    /// (MSVC without `/std:` is C89).
    pub auto_std: bool,
}

/// Compiled and *run* once per detection, with no `-std` flag: the compiler
/// reports what its default mode is. A successful run doubles as the
/// self-test that this toolchain can build a working executable at all.
const VERSION_PROBE: &str = r#"#include <stdio.h>
int main(void) {
    long v = 0;
#ifdef __STDC_VERSION__
    v = (long)__STDC_VERSION__;
#endif
    int gnu = 1;
#ifdef __STRICT_ANSI__
    gnu = 0;
#endif
    printf("%ld %d\n", v, gnu);
    return 0;
}
"#;

/// The one hard requirement on the language mode: without `_Generic` the
/// value printer cannot compile and expressions stop printing entirely.
const GENERIC_PROBE: &str =
    "int main(void){int v = _Generic(1, int: 1, default: 0); return v - 1;}";

/// Turn the VERSION_PROBE's output into a human label like "gnu23".
fn parse_std_probe(out: &str, family: Family) -> Option<String> {
    let mut it = out.split_whitespace();
    let v: i64 = it.next()?.parse().ok()?;
    let gnu: i32 = it.next()?.parse().ok()?;
    let n = match v {
        202000.. => "23", // gcc used 202000L for pre-release C2x
        201710.. => "17",
        201112.. => "11",
        199901.. => "99",
        _ => "89",
    };
    // __STRICT_ANSI__ is a GNU-family signal; MSVC has no gnu dialect.
    let prefix = if gnu == 1 && family != Family::Msvc {
        "gnu"
    } else {
        "c"
    };
    Some(format!("{prefix}{n}"))
}

/// Candidate compiler names, most preferred first. On Windows `cc` is rarely
/// present but costs nothing to try; `cl` comes last because it only works
/// from a Developer Command Prompt.
#[cfg(windows)]
const CANDIDATES: &[&str] = &["gcc", "clang", "cc", "clang-cl", "cl"];
#[cfg(not(windows))]
const CANDIDATES: &[&str] = &["cc", "gcc", "clang", "tcc"];

fn family_of(path: &Path, banner: &str) -> Family {
    let stem = path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    // clang-cl must be checked before clang: it is clang, but takes MSVC flags.
    if stem == "cl" || stem.ends_with("clang-cl") {
        return Family::Msvc;
    }
    // Never trust the executable's name for gcc-vs-clang. On macOS both `cc`
    // and `gcc` are usually Apple clang, and the banner is the only honest
    // signal.
    if banner.to_ascii_lowercase().contains("clang") {
        return Family::Clang;
    }
    Family::Gnu
}

fn banner_of(path: &Path) -> Result<String> {
    // MSVC has no --version; invoked bare it prints its banner to stderr and
    // exits nonzero, so accept output from either stream and ignore status.
    let out = probe_output(Command::new(path).arg("--version"))
        .with_context(|| format!("failed to run {}", path.display()))?;
    let pick = |b: &[u8]| {
        String::from_utf8_lossy(b)
            .lines()
            .next()
            .unwrap_or("")
            .trim()
            .to_string()
    };
    let s = pick(&out.stdout);
    if !s.is_empty() && out.status.is_some_and(|st| st.success()) {
        return Ok(s);
    }
    if let Some(bare) = probe_output(&mut Command::new(path)) {
        let e = pick(&bare.stderr);
        if !e.is_empty() {
            return Ok(e);
        }
    }
    let e = pick(&out.stderr);
    if e.is_empty() {
        bail!("{} produced no version output", path.display());
    }
    Ok(e)
}

impl Toolchain {
    /// Resolve a compiler: explicit choice, then `$CC`, then PATH.
    pub fn detect(explicit: Option<&str>, std: Option<&str>) -> Result<Self> {
        let mut tried: Vec<String> = Vec::new();
        let mut names: Vec<String> = Vec::new();
        if let Some(e) = explicit {
            names.push(e.to_string());
        } else {
            if let Some(cc) = std::env::var("CC").ok().filter(|c| !c.trim().is_empty()) {
                names.push(cc);
            }
            names.extend(CANDIDATES.iter().map(|s| s.to_string()));
        }

        for name in names {
            let path = match which::which(&name) {
                Ok(p) => p,
                Err(_) => {
                    tried.push(name);
                    continue;
                }
            };
            let banner = match banner_of(&path) {
                Ok(b) => b,
                Err(_) => {
                    tried.push(name);
                    continue;
                }
            };
            let family = family_of(&path, &banner);
            let mut tc = Toolchain {
                path,
                family,
                version: banner,
                std: String::new(),
                default_std: None,
                auto_std: false,
            };
            // One compile + run answers two questions at once: does this
            // toolchain produce working executables (MSVC outside a Developer
            // Command Prompt fails here), and what its default mode is.
            match tc.probe_run(&[], VERSION_PROBE) {
                Some(out) => tc.default_std = parse_std_probe(&out, family),
                None => {
                    tried.push(format!(
                        "{} (cannot build a working program)",
                        tc.path.display()
                    ));
                    continue;
                }
            }
            if let Some(s) = std {
                // Explicitly requested. If unsupported, fall through with the
                // compiler default; the banner makes the outcome visible.
                if tc.supports_std(s) {
                    tc.std = s.to_string();
                }
            }
            if tc.std.is_empty() && !tc.generic_ok() {
                // The default mode cannot host the value printer. Force the
                // oldest std that can, and own up to it via `auto_std`.
                for cand in ["c17", "c11"] {
                    if tc.supports_std(cand) {
                        tc.std = cand.to_string();
                        tc.auto_std = true;
                        break;
                    }
                }
            }
            // C11 `_Generic` is this tool's hard floor: without it no
            // expression ever prints a value, which reads as "the tool is
            // broken" with no hint why. A compiler that cannot reach it in
            // any mode is disqualified outright, not limped along with.
            if !tc.generic_ok() {
                tried.push(format!(
                    "{} (too old: no C11 _Generic in any mode)",
                    tc.path.display()
                ));
                continue;
            }
            return Ok(tc);
        }

        bail!(
            "no usable C compiler found (tried: {}).\n\
             c-shell requires C11: value printing depends on _Generic.\n\
             Install gcc or clang, or point c-shell at one with --cc <path>.{}",
            tried.join(", "),
            if cfg!(windows) {
                "\nOn Windows, MSVC (cl.exe) only works from a Developer Command Prompt."
            } else {
                ""
            }
        )
    }

    pub fn is_msvc(&self) -> bool {
        self.family == Family::Msvc
    }

    /// Render the argv for compiling `src` to `exe`.
    pub fn compile_args(&self, src: &Path, exe: &Path, obj_dir: &Path) -> Vec<String> {
        let mut a: Vec<String> = Vec::new();
        if self.is_msvc() {
            a.push("/nologo".into());
            if !self.std.is_empty() {
                a.push(format!("/std:{}", self.std));
            }
            a.push("/W3".into());
            // The MSVC spellings of "defined but not used yet", normal at a
            // REPL: C4101 unreferenced local, C4102 unreferenced label,
            // C4552/C4553 expression result not used (a deliberate `expr;`).
            a.push("/wd4101".into());
            a.push("/wd4102".into());
            a.push("/wd4552".into());
            a.push("/wd4553".into());
            // /TC forces C even when the temp file has an odd extension.
            a.push("/TC".into());
            a.push(src.display().to_string());
            a.push(format!("/Fe:{}", exe.display()));
            // Keep the intermediate .obj out of the working directory. The
            // trailing separator is what tells cl this is a directory.
            a.push(format!(
                "/Fo:{}{}",
                obj_dir.display(),
                std::path::MAIN_SEPARATOR
            ));
            a.push("/link".into());
        } else {
            if !self.std.is_empty() {
                a.push(format!("-std={}", self.std));
            }
            // Beginners benefit far more from seeing warnings than from a
            // quiet prompt, so these are on by default.
            a.push("-Wall".into());
            a.push("-Wextra".into());
            // ...except the -Wunused umbrella. At a REPL everything is
            // unused the moment it is defined: a new function has no caller
            // yet, and a deliberate `expr;` is an unused value by design.
            a.push("-Wno-unused".into());
            // Enabled by -Wextra and not part of the umbrella.
            a.push("-Wno-unused-parameter".into());
            a.push("-fno-diagnostics-color".into());
            a.push("-x".into());
            a.push("c".into());
            a.push(src.display().to_string());
            a.push("-o".into());
            a.push(exe.display().to_string());
            // Math lives in libm only on Unix. On Windows it is part of
            // every C runtime, and worse: clang.exe defaults to the MSVC
            // target there, where `-lm` becomes a link against a
            // nonexistent m.lib. The probes never pass -lm, so that
            // failure would surface not at detection but at the user's
            // first evaluation.
            if !cfg!(windows) {
                a.push("-lm".into());
            }
        }
        a
    }

    fn probe(&self, args: &[&str], body: &str) -> bool {
        let dir = match tempfile::tempdir() {
            Ok(d) => d,
            Err(_) => return false,
        };
        let src = dir.path().join("probe.c");
        if std::fs::write(&src, body).is_err() {
            return false;
        }
        let exe = dir
            .path()
            .join(format!("probe{}", std::env::consts::EXE_SUFFIX));
        let mut cmd = Command::new(&self.path);
        if self.is_msvc() {
            cmd.arg("/nologo").arg("/TC");
            cmd.args(args);
            cmd.arg(&src).arg(format!("/Fe:{}", exe.display()));
            cmd.arg(format!(
                "/Fo:{}{}",
                dir.path().display(),
                std::path::MAIN_SEPARATOR
            ));
        } else {
            cmd.args(args);
            cmd.arg("-x").arg("c").arg(&src).arg("-o").arg(&exe);
        }
        probe_output(&mut cmd).is_some_and(|c| c.status.is_some_and(|st| st.success()))
    }

    /// Like `probe`, but also runs the produced executable and returns its
    /// stdout. `None` means compile, link or run failed.
    fn probe_run(&self, args: &[&str], body: &str) -> Option<String> {
        let dir = tempfile::tempdir().ok()?;
        let src = dir.path().join("probe.c");
        std::fs::write(&src, body).ok()?;
        let exe = dir
            .path()
            .join(format!("probe{}", std::env::consts::EXE_SUFFIX));
        let mut cmd = Command::new(&self.path);
        if self.is_msvc() {
            cmd.arg("/nologo").arg("/TC");
            cmd.args(args);
            cmd.arg(&src).arg(format!("/Fe:{}", exe.display()));
            cmd.arg(format!(
                "/Fo:{}{}",
                dir.path().display(),
                std::path::MAIN_SEPARATOR
            ));
        } else {
            cmd.args(args);
            cmd.arg("-x").arg("c").arg(&src).arg("-o").arg(&exe);
        }
        let ok = probe_output(&mut cmd).is_some_and(|c| c.status.is_some_and(|st| st.success()));
        if !ok {
            return None;
        }
        let run = probe_output(&mut Command::new(&exe))?;
        if !run.status.is_some_and(|st| st.success()) {
            return None;
        }
        Some(String::from_utf8_lossy(&run.stdout).into_owned())
    }

    fn supports_std(&self, std: &str) -> bool {
        let flag = if self.is_msvc() {
            format!("/std:{std}")
        } else {
            format!("-std={std}")
        };
        self.probe(&[&flag], "int main(void){return 0;}")
    }

    /// Can the value-printing runtime compile under the currently chosen
    /// mode? Probed with the actual flag that will be used, so a forced
    /// `--std` is judged as-is rather than assumed fine.
    fn generic_ok(&self) -> bool {
        let flag = if self.std.is_empty() {
            None
        } else if self.is_msvc() {
            Some(format!("/std:{}", self.std))
        } else {
            Some(format!("-std={}", self.std))
        };
        match &flag {
            Some(f) => self.probe(&[f], GENERIC_PROBE),
            None => self.probe(&[], GENERIC_PROBE),
        }
    }

    pub fn describe(&self) -> String {
        let std = match (&self.std, &self.default_std) {
            (s, _) if s.is_empty() => match &self.default_std {
                Some(d) => format!("default std {d}"),
                None => "default std".to_string(),
            },
            (s, Some(d)) if self.auto_std => {
                format!("-std={s}, auto-raised: default {d} lacks _Generic")
            }
            (s, _) => format!("-std={s}"),
        };
        format!("{} ({})", self.version, std)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_modern_gcc_default() {
        assert_eq!(
            parse_std_probe("202311 1\n", Family::Gnu).as_deref(),
            Some("gnu23")
        );
        // gcc's pre-release C2x value maps to the same label.
        assert_eq!(
            parse_std_probe("202000 1\n", Family::Gnu).as_deref(),
            Some("gnu23")
        );
    }

    #[test]
    fn distinguishes_strict_from_gnu_dialect() {
        assert_eq!(
            parse_std_probe("201710 0\n", Family::Clang).as_deref(),
            Some("c17")
        );
        assert_eq!(
            parse_std_probe("201710 1\n", Family::Clang).as_deref(),
            Some("gnu17")
        );
    }

    #[test]
    fn msvc_legacy_mode_has_no_gnu_dialect() {
        // MSVC never defines __STRICT_ANSI__; the gnu bit is meaningless there.
        assert_eq!(
            parse_std_probe("0 1\n", Family::Msvc).as_deref(),
            Some("c89")
        );
    }

    #[test]
    fn rejects_garbage() {
        assert_eq!(parse_std_probe("", Family::Gnu), None);
        assert_eq!(parse_std_probe("not numbers\n", Family::Gnu), None);
    }

    #[test]
    fn family_detection_covers_windows_compilers() {
        // clang-cl IS clang, but speaks the MSVC dialect: the name must win
        // over the banner.
        assert_eq!(
            family_of(
                Path::new("C:/LLVM/bin/clang-cl.exe"),
                "clang version 22.1.6"
            ),
            Family::Msvc
        );
        assert_eq!(
            family_of(Path::new("cl.exe"), "Microsoft (R) C/C++"),
            Family::Msvc
        );
        assert_eq!(
            family_of(Path::new("/usr/bin/clang"), "clang version 22.1.6"),
            Family::Clang
        );
        assert_eq!(
            family_of(Path::new("/mingw64/bin/gcc.exe"), "gcc (GCC) 14.2"),
            Family::Gnu
        );
        // The macOS trap: a binary named gcc that is actually clang.
        assert_eq!(
            family_of(Path::new("/usr/bin/gcc"), "Apple clang version 21.0.0"),
            Family::Clang
        );
    }

    #[test]
    fn libm_is_linked_only_on_unix() {
        // On Windows, clang defaults to the MSVC target where `-lm` becomes
        // a link against a nonexistent m.lib; MinGW keeps math in the CRT.
        let tc = Toolchain {
            path: "gcc".into(),
            family: Family::Gnu,
            version: String::new(),
            std: "c17".into(),
            default_std: None,
            auto_std: false,
        };
        let args = tc.compile_args(Path::new("in.c"), Path::new("out"), Path::new("."));
        assert_eq!(args.contains(&"-lm".to_string()), cfg!(unix));
    }
}