c-shell 0.4.0

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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! Finding a C compiler and speaking its flag dialect.

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

use crate::i18n;
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);
/// Successful capability probes remain valid until the compiler, relevant
/// environment, requested standard, c-shell version, or this TTL changes.
const CACHE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
const CACHE_SCHEMA: &str = "toolchain-v4";

/// `.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 driver lineage a compiler belongs to. Both currently share the GNU
/// flag dialect; the distinction is recorded in the capability cache rather
/// than used to choose flags. 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,
}

#[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.
    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;
}
"#;

/// Exercise the C features used by the value-printer runtime rather than
/// `_Generic` alone: some compilers accept `_Generic` as an extension in a
/// mode that still rejects `inline` or `_Bool`.
const VALUE_PRINTER_PROBE: &str = r#"
static inline int cs_probe(_Bool v) { return v ? 1 : 0; }
int main(void) {
    int (*p)(_Bool) = _Generic(1, int: cs_probe, default: cs_probe);
    return p(1) - 1;
}
"#;

/// Turn the VERSION_PROBE's output into a human label like "gnu23".
fn parse_std_probe(out: &str) -> 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__ separates `-std=c17` from `-std=gnu17`.
    let prefix = if gnu == 1 { "gnu" } else { "c" };
    Some(format!("{prefix}{n}"))
}

/// Candidate compiler names, most preferred first. On Windows, WinLibs GCC
/// (or another MinGW-w64 GCC) is the supported toolchain; `cc` is rarely
/// present but costs nothing to try.
#[cfg(windows)]
const CANDIDATES: &[&str] = &["gcc.exe", "gcc", "clang.exe", "clang", "cc.exe", "cc"];
#[cfg(not(windows))]
const CANDIDATES: &[&str] = &["cc", "gcc", "clang"];

fn family_of(banner: &str) -> Family {
    // Never trust the executable's name for gcc-vs-clang. Apple's Command
    // Line Tools may expose /usr/bin/gcc as an Apple Clang driver, while a
    // separately installed GNU GCC is genuine GCC; the banner distinguishes
    // them without making assumptions from the filename.
    if banner.to_ascii_lowercase().contains("clang") {
        return Family::Clang;
    }
    Family::Gnu
}

fn cache_dir() -> Option<PathBuf> {
    let base = if cfg!(windows) {
        std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
    } else {
        std::env::var_os("XDG_CACHE_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))
    }?;
    Some(base.join("c-shell"))
}

/// Fingerprint everything that can reasonably change a probe's answer.
/// Compiler metadata catches upgrades in place; the selected environment
/// variables cover driver lookup, headers, libraries and platform SDKs.
fn cache_key(path: &Path, requested_std: Option<&str>) -> Option<u64> {
    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    let meta = std::fs::metadata(&path).ok()?;
    let modified = meta
        .modified()
        .ok()?
        .duration_since(SystemTime::UNIX_EPOCH)
        .ok()?;
    let mut h = std::collections::hash_map::DefaultHasher::new();
    CACHE_SCHEMA.hash(&mut h);
    env!("CARGO_PKG_VERSION").hash(&mut h);
    path.hash(&mut h);
    meta.len().hash(&mut h);
    modified.as_nanos().hash(&mut h);
    requested_std.hash(&mut h);
    for name in [
        "PATH",
        "INCLUDE",
        "LIB",
        "LIBPATH",
        "CPATH",
        "C_INCLUDE_PATH",
        "LIBRARY_PATH",
        "SDKROOT",
        "DEVELOPER_DIR",
        "GCC_EXEC_PREFIX",
        "COMPILER_PATH",
    ] {
        name.hash(&mut h);
        std::env::var_os(name).hash(&mut h);
    }
    Some(h.finish())
}

fn hex_encode(s: &str) -> String {
    s.as_bytes().iter().map(|b| format!("{b:02x}")).collect()
}

fn hex_decode(s: &str) -> Option<String> {
    if !s.len().is_multiple_of(2) {
        return None;
    }
    let bytes = (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).ok())
        .collect::<Option<Vec<_>>>()?;
    String::from_utf8(bytes).ok()
}

fn load_cached(path: &Path, requested_std: Option<&str>) -> Option<Toolchain> {
    let key = cache_key(path, requested_std)?;
    let file = cache_dir()?.join(format!("{key:016x}.cache"));
    let age = std::fs::metadata(&file)
        .ok()?
        .modified()
        .ok()?
        .elapsed()
        .ok()?;
    if age > CACHE_TTL {
        return None;
    }
    let text = std::fs::read_to_string(file).ok()?;
    let mut lines = text.lines();
    if lines.next()? != CACHE_SCHEMA || lines.next()? != format!("{key:016x}") {
        return None;
    }
    let family = match lines.next()? {
        "gnu" => Family::Gnu,
        "clang" => Family::Clang,
        _ => return None,
    };
    let version = hex_decode(lines.next()?)?;
    let std = hex_decode(lines.next()?)?;
    let default_std = match lines.next()? {
        "-" => None,
        encoded => Some(hex_decode(encoded)?),
    };
    let auto_std = match lines.next()? {
        "0" => false,
        "1" => true,
        _ => return None,
    };
    Some(Toolchain {
        path: path.to_path_buf(),
        family,
        version,
        std,
        default_std,
        auto_std,
    })
}

fn store_cached(tc: &Toolchain, requested_std: Option<&str>) {
    let Some(key) = cache_key(&tc.path, requested_std) else {
        return;
    };
    let Some(dir) = cache_dir() else { return };
    if std::fs::create_dir_all(&dir).is_err() {
        return;
    }
    let family = match tc.family {
        Family::Gnu => "gnu",
        Family::Clang => "clang",
    };
    let default_std = tc
        .default_std
        .as_deref()
        .map(hex_encode)
        .unwrap_or_else(|| "-".to_string());
    let text = format!(
        "{CACHE_SCHEMA}\n{key:016x}\n{family}\n{}\n{}\n{default_std}\n{}\n",
        hex_encode(&tc.version),
        hex_encode(&tc.std),
        u8::from(tc.auto_std)
    );
    // Cache corruption is harmless (the next launch probes again), so cache
    // I/O remains best effort and never prevents the prompt from opening.
    let _ = std::fs::write(dir.join(format!("{key:016x}.cache")), text);
}

fn banner_of(path: &Path) -> Result<String> {
    let mut cmd = Command::new(path);
    cmd.arg("--version");
    if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
        cmd.current_dir(parent);
    }
    let out =
        probe_output(&mut cmd).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);
    }
    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());
            #[cfg(windows)]
            if !e.to_ascii_lowercase().ends_with(".exe") {
                names.push(format!("{e}.exe"));
            }
        } else {
            if let Some(cc) = std::env::var("CC").ok().filter(|c| !c.trim().is_empty()) {
                names.push(cc.clone());
                #[cfg(windows)]
                if !cc.to_ascii_lowercase().ends_with(".exe") {
                    names.push(format!("{cc}.exe"));
                }
            }
            names.extend(CANDIDATES.iter().map(|s| s.to_string()));
        }

        for name in names {
            let path = match which::which(&name) {
                Ok(p) => p,
                Err(e) => {
                    if explicit.is_some() {
                        tried.push(format!("{name} ({e})"));
                    } else {
                        tried.push(name);
                    }
                    continue;
                }
            };
            if let Some(tc) = load_cached(&path, std) {
                return Ok(tc);
            }
            let banner = match banner_of(&path) {
                Ok(b) => b,
                Err(e) => {
                    tried.push(format!("{} ({e:#})", path.display()));
                    continue;
                }
            };
            let family = family_of(&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, and what its default
            // mode is.
            match tc.probe_run(&[], VERSION_PROBE) {
                Some(out) => tc.default_std = parse_std_probe(&out),
                None => {
                    tried.push(i18n::text_with(
                        "compiler-cannot-build",
                        &[("path", tc.path.display().to_string())],
                    ));
                    continue;
                }
            }
            if let Some(s) = std {
                if tc.supports_std(s) {
                    tc.std = s.to_string();
                } else {
                    tried.push(i18n::text_with(
                        "compiler-standard-unsupported",
                        &[
                            ("path", tc.path.display().to_string()),
                            ("standard", s.to_string()),
                        ],
                    ));
                    continue;
                }
            }
            if tc.std.is_empty() && !tc.value_printer_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.value_printer_ok() {
                tried.push(i18n::text_with(
                    "compiler-printer-unsupported",
                    &[("path", tc.path.display().to_string())],
                ));
                continue;
            }
            store_cached(&tc, std);
            return Ok(tc);
        }

        let windows_note = if cfg!(windows) {
            format!("\n{}", i18n::text("compiler-windows-note"))
        } else {
            String::new()
        };
        bail!(i18n::text_with(
            "compiler-not-found",
            &[("tried", tried.join(", ")), ("windows-note", windows_note),],
        ))
    }

    /// Render the argv for compiling `src` to `exe`.
    pub fn compile_args(&self, src: &Path, exe: &Path) -> Vec<String> {
        let mut a: Vec<String> = Vec::new();
        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("-pipe".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. MinGW keeps it in the C runtime,
        // and the probes never pass -lm, so a link failure would otherwise
        // 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);
        cmd.current_dir(dir.path());
        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);
        cmd.current_dir(dir.path());
        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 mut run = Command::new(&exe);
        run.current_dir(dir.path());
        let run_cap = probe_output(&mut run)?;
        if !run_cap.status.is_some_and(|st| st.success()) {
            return None;
        }
        Some(String::from_utf8_lossy(&run_cap.stdout).into_owned())
    }

    fn supports_std(&self, std: &str) -> bool {
        let flag = 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 value_printer_ok(&self) -> bool {
        let flag = if self.std.is_empty() {
            None
        } else {
            Some(format!("-std={}", self.std))
        };
        match &flag {
            Some(f) => self.probe(&[f], VALUE_PRINTER_PROBE),
            None => self.probe(&[], VALUE_PRINTER_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) => {
                    i18n::text_with("compiler-default-std-value", &[("standard", d.clone())])
                }
                None => i18n::text("compiler-default-std"),
            },
            (s, Some(d)) if self.auto_std => i18n::text_with(
                "compiler-auto-std",
                &[("selected", s.clone()), ("default", d.clone())],
            ),
            (s, _) => format!("-std={s}"),
        };
        format!("{} ({})", self.version, std)
    }
}

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

    #[test]
    fn cache_text_round_trips_utf8_and_empty_strings() {
        for value in ["", "gcc (GCC) 16.1.1", "编译器"] {
            assert_eq!(hex_decode(&hex_encode(value)).as_deref(), Some(value));
        }
        assert!(hex_decode("0").is_none());
        assert!(hex_decode("zz").is_none());
    }

    #[test]
    fn requested_standard_is_part_of_cache_identity() {
        let exe = std::env::current_exe().expect("current test executable");
        assert_ne!(cache_key(&exe, None), cache_key(&exe, Some("c17")));
        assert_ne!(cache_key(&exe, Some("c17")), cache_key(&exe, Some("c23")));
    }

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

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

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

    #[test]
    fn family_detection_distinguishes_gcc_from_clang() {
        assert_eq!(family_of("clang version 22.1.6"), Family::Clang);
        assert_eq!(family_of("gcc (GCC) 14.2"), Family::Gnu);
        // Apple Command Line Tools may expose a gcc-named Clang driver.
        assert_eq!(family_of("Apple clang version 21.0.0"), Family::Clang);
    }

    #[test]
    fn libm_is_linked_only_on_unix() {
        // MinGW keeps math in the C runtime.
        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"));
        assert_eq!(args.contains(&"-lm".to_string()), cfg!(unix));
    }
}