corgi-build 0.1.48

PoC: deterministic, content-addressed, lock-free cargo-compatible build tool
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
//! Workspace `.cargo/config.toml` resolution.
//!
//! corgi honors the narrow slice of cargo configuration that changes what
//! gets compiled: `build.rustflags`, `target.<spec>.rustflags`, and `[env]`.
//! Everything else that would alter build semantics is a hard error, so a
//! config the tool cannot faithfully reproduce never builds silently wrong.
//! Only the workspace's own `.cargo/config.toml` is read: configs in parent
//! directories or CARGO_HOME are machine-local state and stay invisible.

use anyhow::{bail, Context, Result};
use std::path::Path;

pub struct CargoConfig {
    build_rustflags: Vec<String>,
    /// Raw `target.<spec>` rustflags entries, spec as written.
    target_rustflags: Vec<(String, Vec<String>)>,
    /// `[env]` entries, sorted by name.
    pub env: Vec<(String, String)>,
}

impl CargoConfig {
    /// Rustflags for a compilation target triple, with cargo's precedence:
    /// all matching `target.<triple>` and `target.'cfg(...)'` entries are
    /// concatenated; `build.rustflags` applies only when no target entry
    /// matched. Cargo's join order for multiple matches is incidental, so
    /// corgi pins one: literal triple entries first, then cfg entries in
    /// lexicographic spec order.
    pub fn rustflags_for(&self, triple: &str) -> Result<Vec<String>> {
        let mut flags = Vec::new();
        let mut any_match = false;
        for (spec, entry) in &self.target_rustflags {
            if spec == triple {
                any_match = true;
                flags.extend(entry.iter().cloned());
            }
        }
        let mut cfg_entries: Vec<&(String, Vec<String>)> = self
            .target_rustflags
            .iter()
            .filter(|(s, _)| s.starts_with("cfg("))
            .collect();
        cfg_entries.sort_by(|a, b| a.0.cmp(&b.0));
        if !cfg_entries.is_empty() {
            let info = TripleInfo::of(triple)?;
            for (spec, entry) in cfg_entries {
                if eval_cfg(&parse_cfg(spec)?, &info)? {
                    any_match = true;
                    flags.extend(entry.iter().cloned());
                }
            }
        }
        if !any_match {
            flags = self.build_rustflags.clone();
        }
        Ok(flags)
    }
}

/// Walk up from the invocation directory, like cargo, to the nearest
/// `.cargo/config.toml` (or legacy `.cargo/config`). Returns the parsed
/// config and the directory it was found in; the caller verifies that hit
/// is the workspace root once cargo metadata reveals it, so member-level
/// or machine-local configs are hard errors instead of silent inputs.
pub fn discover(start: &Path) -> Result<(CargoConfig, Option<std::path::PathBuf>)> {
    let mut dir = Some(start);
    while let Some(d) = dir {
        for name in [".cargo/config.toml", ".cargo/config"] {
            let p = d.join(name);
            if p.is_file() {
                let text = std::fs::read_to_string(&p)
                    .with_context(|| format!("reading {}", p.display()))?;
                let config = parse(&text).with_context(|| format!("parsing {}", p.display()))?;
                return Ok((config, Some(d.to_path_buf())));
            }
        }
        dir = d.parent();
    }
    Ok((
        CargoConfig {
            build_rustflags: Vec::new(),
            target_rustflags: Vec::new(),
            env: Vec::new(),
        },
        None,
    ))
}

fn parse(text: &str) -> Result<CargoConfig> {
    let root: toml::Value = toml::from_str(text).context("invalid TOML")?;
    let table = root.as_table().context("config root is not a table")?;
    let mut build_rustflags = Vec::new();
    let mut target_rustflags = Vec::new();
    let mut env = Vec::new();
    for (section, value) in table {
        match section.as_str() {
            "build" => {
                let entries = value.as_table().context("[build] is not a table")?;
                for (key, v) in entries {
                    match key.as_str() {
                        "rustflags" => {
                            build_rustflags = flag_list(v).context("build.rustflags")?;
                        }
                        // Parallelism and layout preferences: corgi owns
                        // both, and rustdoc is not run.
                        "jobs" | "target-dir" | "incremental" | "rustdocflags" => {}
                        other => bail!("unsupported .cargo/config key build.{other}"),
                    }
                }
            }
            "target" => {
                let entries = value.as_table().context("[target] is not a table")?;
                for (spec, sub) in entries {
                    if spec.starts_with("cfg(") {
                        // Validate now so a broken config fails on load,
                        // not on first use of an unusual triple.
                        validate_cfg(&parse_cfg(spec)?)?;
                    }
                    let sub_entries = sub
                        .as_table()
                        .with_context(|| format!("[target.{spec}] is not a table"))?;
                    for (key, v) in sub_entries {
                        match key.as_str() {
                            "rustflags" => target_rustflags.push((
                                spec.clone(),
                                flag_list(v).with_context(|| format!("target.{spec}.rustflags"))?,
                            )),
                            "rustdocflags" => {}
                            other => bail!("unsupported .cargo/config key target.{spec}.{other}"),
                        }
                    }
                }
            }
            "env" => {
                let entries = value.as_table().context("[env] is not a table")?;
                for (name, v) in entries {
                    let val = v.as_str().with_context(|| {
                        format!("env.{name}: only plain string values are supported")
                    })?;
                    let managed = matches!(
                        name.as_str(),
                        "TMPDIR" | "PATH" | "HOME" | "OUT_DIR" | "SDKROOT" | "RUSTFLAGS"
                    ) || name.starts_with("CARGO_")
                        || name.starts_with("CORGI_");
                    if managed {
                        bail!("env.{name} collides with a tool-managed variable");
                    }
                    env.push((name.clone(), val.to_string()));
                }
            }
            // Command aliases and network/UI preferences never change what
            // gets compiled.
            "alias"
            | "net"
            | "http"
            | "term"
            | "registries"
            | "registry"
            | "cargo-new"
            | "future-incompat-report"
            | "cache"
            | "install"
            | "doc" => {}
            other => bail!("unsupported .cargo/config section [{other}]"),
        }
    }
    env.sort();
    Ok(CargoConfig {
        build_rustflags,
        target_rustflags,
        env,
    })
}

/// Cargo accepts rustflags as an array of strings or one space-separated
/// string.
fn flag_list(value: &toml::Value) -> Result<Vec<String>> {
    match value {
        toml::Value::String(s) => Ok(s.split_whitespace().map(str::to_string).collect()),
        toml::Value::Array(items) => items
            .iter()
            .map(|i| {
                i.as_str()
                    .map(str::to_string)
                    .context("rustflags entries must be strings")
            })
            .collect(),
        _ => bail!("rustflags must be a string or an array of strings"),
    }
}

/// The target-triple facts simple `cfg()` predicates can ask about.
struct TripleInfo {
    arch: String,
    vendor: String,
    os: String,
    env: String,
    family: &'static str,
}

impl TripleInfo {
    fn of(triple: &str) -> Result<TripleInfo> {
        let parts: Vec<&str> = triple.split('-').collect();
        let arch = parts[0].to_string();
        let (vendor, os, env, family): (&str, &str, &str, &str) = match &parts[1..] {
            ["apple", "darwin"] => ("apple", "macos", "", "unix"),
            ["unknown", "linux", environment] => ("unknown", "linux", *environment, "unix"),
            ["unknown", "linux"] => ("unknown", "linux", "", "unix"),
            ["pc", "windows", environment] => ("pc", "windows", *environment, "windows"),
            ["unknown", "unknown"] => ("unknown", "unknown", "", ""),
            ["wasip1"] => ("unknown", "wasi", "p1", "wasm"),
            ["wasip2"] => ("unknown", "wasi", "p2", "wasm"),
            ["wasi"] => ("unknown", "wasi", "", "wasm"),
            _ => bail!("unrecognized target triple {triple}"),
        };
        Ok(TripleInfo {
            arch,
            vendor: vendor.to_string(),
            os: os.to_string(),
            env: env.to_string(),
            family,
        })
    }
}

enum CfgExpr {
    All(Vec<CfgExpr>),
    Any(Vec<CfgExpr>),
    Not(Box<CfgExpr>),
    Name(String),
    KeyValue(String, String),
}

fn parse_cfg(spec: &str) -> Result<CfgExpr> {
    let inner = spec
        .strip_prefix("cfg(")
        .and_then(|s| s.strip_suffix(')'))
        .with_context(|| format!("malformed cfg spec {spec}"))?;
    let tokens = tokenize(inner).with_context(|| format!("in {spec}"))?;
    let mut pos = 0;
    let expr = parse_expr(&tokens, &mut pos).with_context(|| format!("in {spec}"))?;
    if pos != tokens.len() {
        bail!("trailing tokens in {spec}");
    }
    Ok(expr)
}

#[derive(PartialEq, Debug)]
enum Token {
    Ident(String),
    Str(String),
    LParen,
    RParen,
    Comma,
    Eq,
}

fn tokenize(text: &str) -> Result<Vec<Token>> {
    let mut tokens = Vec::new();
    let mut chars = text.chars().peekable();
    while let Some(&c) = chars.peek() {
        match c {
            ' ' | '\t' => {
                chars.next();
            }
            '(' => {
                chars.next();
                tokens.push(Token::LParen);
            }
            ')' => {
                chars.next();
                tokens.push(Token::RParen);
            }
            ',' => {
                chars.next();
                tokens.push(Token::Comma);
            }
            '=' => {
                chars.next();
                tokens.push(Token::Eq);
            }
            '"' => {
                chars.next();
                let mut value = String::new();
                loop {
                    match chars.next() {
                        Some('"') => break,
                        Some('\\') => bail!("escape sequences in cfg strings are not supported"),
                        Some(ch) => value.push(ch),
                        None => bail!("unterminated string"),
                    }
                }
                tokens.push(Token::Str(value));
            }
            ch if ch.is_ascii_alphanumeric() || ch == '_' => {
                let mut ident = String::new();
                while let Some(&ch) = chars.peek() {
                    if ch.is_ascii_alphanumeric() || ch == '_' {
                        ident.push(ch);
                        chars.next();
                    } else {
                        break;
                    }
                }
                tokens.push(Token::Ident(ident));
            }
            other => bail!("unexpected character {other:?} in cfg expression"),
        }
    }
    Ok(tokens)
}

fn parse_expr(tokens: &[Token], pos: &mut usize) -> Result<CfgExpr> {
    let Some(Token::Ident(name)) = tokens.get(*pos) else {
        bail!("expected identifier");
    };
    *pos += 1;
    match tokens.get(*pos) {
        Some(Token::LParen) => {
            *pos += 1;
            let mut items = Vec::new();
            if tokens.get(*pos) != Some(&Token::RParen) {
                loop {
                    items.push(parse_expr(tokens, pos)?);
                    match tokens.get(*pos) {
                        Some(Token::Comma) => *pos += 1,
                        _ => break,
                    }
                }
            }
            if tokens.get(*pos) != Some(&Token::RParen) {
                bail!("expected closing parenthesis");
            }
            *pos += 1;
            match name.as_str() {
                "all" => Ok(CfgExpr::All(items)),
                "any" => Ok(CfgExpr::Any(items)),
                "not" => {
                    if items.len() != 1 {
                        bail!("not() takes exactly one predicate");
                    }
                    Ok(CfgExpr::Not(Box::new(items.into_iter().next().unwrap())))
                }
                other => bail!("unsupported cfg operator {other}"),
            }
        }
        Some(Token::Eq) => {
            *pos += 1;
            let Some(Token::Str(value)) = tokens.get(*pos) else {
                bail!("expected string after =");
            };
            *pos += 1;
            Ok(CfgExpr::KeyValue(name.clone(), value.clone()))
        }
        _ => Ok(CfgExpr::Name(name.clone())),
    }
}

/// Reject predicates corgi cannot evaluate, up front and regardless of
/// short-circuiting, so unsupported configs fail on load.
fn validate_cfg(expr: &CfgExpr) -> Result<()> {
    match expr {
        CfgExpr::All(items) | CfgExpr::Any(items) => items.iter().try_for_each(validate_cfg),
        CfgExpr::Not(inner) => validate_cfg(inner),
        CfgExpr::Name(name) => match name.as_str() {
            "unix" | "windows" => Ok(()),
            other => bail!("unsupported cfg predicate {other}"),
        },
        CfgExpr::KeyValue(key, _) => match key.as_str() {
            "target_os" | "target_arch" | "target_env" | "target_vendor" | "target_family" => {
                Ok(())
            }
            other => bail!("unsupported cfg predicate {other}"),
        },
    }
}

fn eval_cfg(expr: &CfgExpr, info: &TripleInfo) -> Result<bool> {
    Ok(match expr {
        CfgExpr::All(items) => {
            for item in items {
                if !eval_cfg(item, info)? {
                    return Ok(false);
                }
            }
            true
        }
        CfgExpr::Any(items) => {
            for item in items {
                if eval_cfg(item, info)? {
                    return Ok(true);
                }
            }
            false
        }
        CfgExpr::Not(inner) => !eval_cfg(inner, info)?,
        CfgExpr::Name(name) => match name.as_str() {
            "unix" => info.family == "unix",
            "windows" => info.family == "windows",
            other => bail!("unsupported cfg predicate {other}"),
        },
        CfgExpr::KeyValue(key, value) => match key.as_str() {
            "target_os" => info.os == *value,
            "target_arch" => info.arch == *value,
            "target_env" => info.env == *value,
            "target_vendor" => info.vendor == *value,
            "target_family" => info.family == *value,
            other => bail!("unsupported cfg predicate {other}"),
        },
    })
}

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

    #[test]
    fn build_rustflags_used_when_no_target_entry_matches() {
        let config = parse(
            r#"
            [build]
            rustflags = ["-C", "symbol-mangling-version=v0", "--cfg", "tokio_unstable"]
            "#,
        )
        .unwrap();
        assert_eq!(
            config.rustflags_for("aarch64-apple-darwin").unwrap(),
            vec![
                "-C",
                "symbol-mangling-version=v0",
                "--cfg",
                "tokio_unstable"
            ]
        );
    }

    #[test]
    fn matching_target_entries_replace_build_rustflags() {
        // Zed's real config shape: a global mangling/cfg pair, a windows
        // cfg section, and a literal linux triple section.
        let config = parse(
            r#"
            [build]
            rustflags = ["-C", "symbol-mangling-version=v0", "--cfg", "tokio_unstable"]

            [target.'cfg(target_os = "windows")']
            rustflags = ["--cfg", "windows_slim_errors", "-C", "target-feature=+crt-static"]

            [target.aarch64-unknown-linux-gnu]
            rustflags = ["-C", "link-arg=-fuse-ld=lld"]
            "#,
        )
        .unwrap();
        // No target entry matches on macOS: the build flags apply.
        assert_eq!(
            config.rustflags_for("aarch64-apple-darwin").unwrap(),
            vec![
                "-C",
                "symbol-mangling-version=v0",
                "--cfg",
                "tokio_unstable"
            ]
        );
        // A matching cfg entry replaces the build flags entirely.
        assert_eq!(
            config.rustflags_for("x86_64-pc-windows-msvc").unwrap(),
            vec![
                "--cfg",
                "windows_slim_errors",
                "-C",
                "target-feature=+crt-static"
            ]
        );
        // A matching literal triple does the same.
        assert_eq!(
            config.rustflags_for("aarch64-unknown-linux-gnu").unwrap(),
            vec!["-C", "link-arg=-fuse-ld=lld"]
        );
    }

    #[test]
    fn triple_and_cfg_matches_concatenate_in_pinned_order() {
        let config = parse(
            r#"
            [build]
            rustflags = ["--cfg", "never_applies"]

            [target.'cfg(unix)']
            rustflags = ["--cfg", "from_cfg"]

            [target.aarch64-apple-darwin]
            rustflags = ["--cfg", "from_triple"]
            "#,
        )
        .unwrap();
        assert_eq!(
            config.rustflags_for("aarch64-apple-darwin").unwrap(),
            vec!["--cfg", "from_triple", "--cfg", "from_cfg"]
        );
    }

    #[test]
    fn cfg_operators_and_string_form_flags() {
        let config = parse(
            r#"
            [target.'cfg(all(unix, not(target_os = "macos")))']
            rustflags = "-C link-arg=-fuse-ld=lld"
            "#,
        )
        .unwrap();
        assert_eq!(
            config.rustflags_for("x86_64-unknown-linux-gnu").unwrap(),
            vec!["-C", "link-arg=-fuse-ld=lld"]
        );
        assert!(config
            .rustflags_for("aarch64-apple-darwin")
            .unwrap()
            .is_empty());
    }

    #[test]
    fn env_entries_are_parsed_and_sorted() {
        let config = parse(
            r#"
            [env]
            ZED_B = "two"
            MACOSX_DEPLOYMENT_TARGET = "10.15.7"
            "#,
        )
        .unwrap();
        assert_eq!(
            config.env,
            vec![
                (
                    "MACOSX_DEPLOYMENT_TARGET".to_string(),
                    "10.15.7".to_string()
                ),
                ("ZED_B".to_string(), "two".to_string()),
            ]
        );
    }

    #[test]
    fn semantics_bearing_config_is_a_hard_error() {
        // Alternate compilers, linkers, profiles, forced env shapes, and
        // predicates corgi cannot evaluate must refuse to build rather
        // than silently diverge from cargo.
        for bad in [
            "[build]\nrustc = \"my-rustc\"",
            "[target.aarch64-apple-darwin]\nlinker = \"lld\"",
            "[profile.dev]\nopt-level = 3",
            "[env]\nFOO = { value = \"x\", force = true }",
            "[env]\nCARGO_TERM_COLOR = \"always\"",
            "[target.'cfg(feature = \"x\")']\nrustflags = [\"--cfg\", \"y\"]",
        ] {
            assert!(parse(bad).is_err(), "expected hard error for: {bad}");
        }
        // Aliases and network settings never change a build: ignored.
        parse("[alias]\nxtask = \"run --package xtask --\"\n[net]\ngit-fetch-with-cli = true")
            .unwrap();
    }
}