gen-cargo 0.1.8

gen — Cargo adapter. Parses Cargo.toml + Cargo.lock + workspace shape into gen_types::Manifest. The cargo half of the universal package-manager engine; one of N adapters (gen-npm, gen-bundler, gen-pip, gen-gomod, gen-helm, …) that share the typed core. See theory/GEN.md for the full design.
Documentation
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
//! Typed gen-cargo **diagnostics** — non-fatal observations about a
//! spec that the operator should address even though the spec is
//! still well-formed cargo-wise.
//!
//! Diagnostics differ from [`crate::invariants::Violation`] in
//! semantic level:
//!
//! - **Violation** = the spec is provably wrong; substrate cannot
//!   consume it correctly. `assert_well_formed` panics / errors.
//! - **Diagnostic** = the spec is cargo-correct but carries a known
//!   leak/risk class that substrate has a safety net for. The
//!   operator gets a typed warning naming the upstream fix
//!   (consumer Cargo.toml change) so the fleet can shed the safety
//!   net's dependency over time.
//!
//! The first variant (`PlatformFeatureLeakAcrossTargets`) captures
//! the cargo-feature-unification class — discovered fleet-wide when
//! the notify v8 default-feature `macos_fsevent` leaked onto
//! linux/musl builds. Substrate's `pleme-crate-overrides.notify`
//! (triple-aware) corrects the build; this diagnostic surfaces the
//! consumer-side fix so the operator can land it.
//!
//! Run `diagnose(&spec)` after `generate_multi_target` — returns
//! `Vec<Diagnostic>` (empty when no leaks). Pure walk, no I/O,
//! deterministic output. `gen confirm` includes the diagnostics in
//! its output without elevating them to errors.

use crate::build_spec::BuildSpec;
use crate::platform_features::{lookup, PlatformTag};
use serde::{Deserialize, Serialize};

/// Typed diagnostic emitted by `diagnose`. Variants are tagged
/// (`#[serde(tag = "rule")]`) so consumers (gen confirm, cse-lint,
/// IDE tooling) can dispatch on the variant string without
/// re-implementing the matcher.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "rule", rename_all = "kebab-case")]
pub enum Diagnostic {
    /// Cargo's global feature unification activated a
    /// platform-specific feature on a target whose platform tag
    /// doesn't match. Symptom: the cross-target build fails unless
    /// the substrate safety net (triple-aware override) strips the
    /// feature for that target.
    ///
    /// Operator-side fix: in the consumer's `Cargo.toml`, set
    /// `default-features = false` on the leaking crate dependency
    /// and re-add only the cross-platform features it actually
    /// needs, or move the platform-feature into a
    /// `[target.'cfg(target_vendor = "X")'.dependencies]` block.
    ///
    /// Example: `notify`'s `default = ["macos_fsevent"]` leaks the
    /// apple-only fsevent backend onto every linux/musl build of
    /// notify in the workspace's resolve graph. The substrate
    /// strips it; this diagnostic surfaces the leak.
    PlatformFeatureLeakAcrossTargets {
        crate_key: String,
        name: String,
        feature: String,
        feature_platform: PlatformTag,
        triples: Vec<String>,
        upstream_fix_hint: String,
    },
}

/// Run every diagnostic against the spec. Empty `Vec` when no
/// diagnostics fire. Pure function — same inputs always produce the
/// same output, no logging, no I/O.
///
/// O(target_resolves × crates × features × registry) — registry is
/// tiny (~10s of entries indefinitely), target_resolves is bounded
/// by the FLEET_TARGETS list (currently 6), so the cost is
/// dominated by spec.crates × spec.crates.features which is what
/// every other invariant already walks.
#[must_use]
pub fn diagnose(spec: &BuildSpec) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    diagnose_platform_feature_leaks(spec, &mut out);
    out
}

/// Walk `target_resolves[triple].crates[key].features` and flag any
/// (crate, feature, triple) triple where the registered platform tag
/// doesn't match the triple. Returns one diagnostic per (crate,
/// feature) leak — `triples` collects every offending target so the
/// operator sees the full leak footprint, not one diagnostic per
/// (crate, feature, triple) row.
fn diagnose_platform_feature_leaks(spec: &BuildSpec, out: &mut Vec<Diagnostic>) {
    let Some(compact) = spec.target_resolves.as_ref() else {
        // Old-shape spec without per-target resolves — no
        // diagnostic surface to inspect.
        return;
    };
    // Expand the compact (base + overrides) form back to the full
    // per-target crates map so the leak walk sees each triple's
    // complete effective edge set (`base // overrides[triple]`).
    let target_resolves = compact.expand();

    // Group leaks: (crate_key, feature) -> Vec<triple>.
    // Use indexmap to keep deterministic order (registry-then-triple).
    let mut grouped: indexmap::IndexMap<(String, String, String, PlatformTag), Vec<String>> =
        indexmap::IndexMap::new();

    for (triple, resolve) in &target_resolves {
        for (key, edges) in &resolve.crates {
            let Some(crate_spec) = spec.crates.get(key) else {
                // Spec consistency error — would be caught by
                // invariants::check_unresolved_deps. Skip silently
                // here; not a diagnostic concern.
                continue;
            };
            for feature in &edges.features {
                let Some(entry) = lookup(&crate_spec.name, feature) else {
                    continue;
                };
                if entry.tag.matches_triple(triple) {
                    continue;
                }
                grouped
                    .entry((
                        key.clone(),
                        crate_spec.name.clone(),
                        feature.clone(),
                        entry.tag,
                    ))
                    .or_default()
                    .push(triple.clone());
            }
        }
    }

    for ((crate_key, name, feature, feature_platform), mut triples) in grouped {
        triples.sort();
        triples.dedup();
        let upstream_fix_hint = upstream_fix_hint_for(&name, &feature);
        out.push(Diagnostic::PlatformFeatureLeakAcrossTargets {
            crate_key,
            name,
            feature,
            feature_platform,
            triples,
            upstream_fix_hint,
        });
    }
}

/// Per-leak operator hint. Crate-specific where we know the exact
/// drop-in replacement; falls back to a generic
/// `default-features = false` + target-gate message otherwise.
///
/// Cargo features unify globally per-target — there is NO portable
/// macOS backend feature for a crate like notify; the only
/// kqueue-sys-free Linux build is one where the macos_* feature is
/// gated behind `[target.'cfg(target_os = "macos")']`. The hint
/// previously recommended `features = ["macos_kqueue"]` claiming it
/// was portable; that advice produced shikumi 5139dd2's Linux-breaking
/// lockfile and was corrected to the target-gated form in 3913d35.
fn upstream_fix_hint_for(crate_name: &str, _feature: &str) -> String {
    match crate_name {
        "notify" => "In the consumer's Cargo.toml, set the bare notify dep with no \
                     macOS feature flags, then opt macOS into a backend via a \
                     target-conditional block:\n  \
                     [dependencies]\n  \
                     notify = { version = \"<v>\", default-features = false }\n\n  \
                     [target.'cfg(target_os = \"macos\")'.dependencies]\n  \
                     notify = { version = \"<v>\", default-features = false, \
                     features = [\"macos_kqueue\"] }\n\n  \
                     Linux falls back to inotify (notify's only Linux backend) \
                     with no macOS-side dep activation. The target-gate is required \
                     because Cargo features unify globally per-target — putting \
                     `features = [\"macos_kqueue\"]` in [dependencies] would still \
                     activate kqueue → kqueue-sys on every Linux build."
            .to_string(),
        _ => format!(
            "In the consumer's Cargo.toml, set `default-features = false` on \
             {crate_name}, then re-add only the cross-platform features the \
             consumer actually uses. Platform-specific features (apple-only / \
             linux-only / windows-only) must live in a \
             `[target.'cfg(target_os = \"X\")'.dependencies]` block — putting \
             them in plain [dependencies] activates them globally per-target \
             due to Cargo's feature unification, which is the leak this \
             diagnostic detected."
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::build_spec::{
        BuildRustCrateArgs, CompactTargetResolves, CrateSource, CrateSpec, CrateTargetEdges,
        TargetResolve, WorkspaceSpec,
    };
    use indexmap::IndexMap;

    fn empty_spec() -> BuildSpec {
        BuildSpec {
            version: crate::build_spec::SCHEMA_VERSION,
            workspace: WorkspaceSpec {
                root: "/x".into(),
                members: vec![],
            },
            crates: IndexMap::new(),
            root_crate: String::new(),
            workspace_members: vec![],
            flake_metadata: IndexMap::new(),
            target_resolves: None,
            cargo_lock_sha256: None,
        }
    }

    fn registry_crate(name: &str, version: &str, features: Vec<String>) -> (String, CrateSpec) {
        let key = format!("{name}-{version}");
        let args = BuildRustCrateArgs {
            crate_name: Some(name.into()),
            version: Some(version.into()),
            edition: Some("2024".into()),
            features: features.clone(),
            crate_renames: IndexMap::new(),
            release: Some(true),
            proc_macro: None,
            build: None,
            links: None,
            lib_name: None,
            lib_path: None,
            pre_build: Some(format!("export CARGO_CRATE_NAME={};", name.replace('-', "_"))),
        };
        (
            key,
            CrateSpec {
                name: name.into(),
                version: version.into(),
                edition: "2024".into(),
                source: CrateSource::Registry {
                    url: "https://crates.io/x".into(),
                    sha256: "deadbeef".into(),
                    name_with_ext: format!("{name}.tar.gz"),
                },
                features,
                proc_macro: false,
                build_script: None,
                links: None,
                quirks: vec![],
                build_rust_crate_args: args,
                binaries: vec![],
                lib_target: None,
                dependencies: vec![],
                runtime_dependencies: vec![],
                build_dependencies: vec![],
                crate_renames: IndexMap::new(),
            },
        )
    }

    fn target_resolve_for(key: &str, features: Vec<String>) -> TargetResolve {
        let mut crates = IndexMap::new();
        crates.insert(
            key.to_string(),
            CrateTargetEdges {
                dependencies: vec![],
                runtime_dependencies: vec![],
                build_dependencies: vec![],
                features,
            },
        );
        TargetResolve { crates }
    }

    #[test]
    fn empty_spec_yields_no_diagnostics() {
        let s = empty_spec();
        assert!(diagnose(&s).is_empty());
    }

    #[test]
    fn old_shape_spec_without_target_resolves_is_skipped() {
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["macos_fsevent".into()]);
        s.crates.insert(k, c);
        // target_resolves is None — no leak surface to inspect.
        assert!(diagnose(&s).is_empty());
    }

    #[test]
    fn notify_macos_fsevent_on_linux_musl_triggers_diagnostic() {
        let mut s = empty_spec();
        let (k, c) = registry_crate(
            "notify",
            "8.2.0",
            vec!["default".into(), "macos_fsevent".into()],
        );
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "x86_64-unknown-linux-musl".to_string(),
            target_resolve_for(&k, vec!["default".into(), "macos_fsevent".into()]),
        );
        tr.insert(
            "aarch64-apple-darwin".to_string(),
            target_resolve_for(&k, vec!["default".into(), "macos_fsevent".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        let d = diagnose(&s);
        assert_eq!(d.len(), 1, "expected exactly one leak diagnostic");
        match &d[0] {
            Diagnostic::PlatformFeatureLeakAcrossTargets {
                name,
                feature,
                feature_platform,
                triples,
                ..
            } => {
                assert_eq!(name, "notify");
                assert_eq!(feature, "macos_fsevent");
                assert_eq!(*feature_platform, PlatformTag::Apple);
                assert_eq!(triples, &vec!["x86_64-unknown-linux-musl".to_string()]);
            }
        }
    }

    #[test]
    fn apple_targets_alone_yield_no_diagnostic() {
        // The feature is apple-tagged; if it only appears on apple
        // triples, that's the correct case and no diagnostic fires.
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["macos_fsevent".into()]);
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "aarch64-apple-darwin".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        tr.insert(
            "x86_64-apple-darwin".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        assert!(diagnose(&s).is_empty());
    }

    #[test]
    fn linux_only_with_macos_kqueue_fires_leak_diagnostic() {
        // Even with NO apple target in the resolve graph, activating
        // macos_kqueue on linux is itself the leak — the feature pulls
        // kqueue → kqueue-sys, and kqueue-sys's BSD bindings won't
        // compile on linux. Registered as Apple-tagged so the
        // diagnostic fires regardless of whether apple appears.
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["macos_kqueue".into()]);
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "x86_64-unknown-linux-musl".to_string(),
            target_resolve_for(&k, vec!["macos_kqueue".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        let d = diagnose(&s);
        assert_eq!(d.len(), 1, "macos_kqueue on linux must flag");
        match &d[0] {
            Diagnostic::PlatformFeatureLeakAcrossTargets {
                name,
                feature,
                feature_platform,
                triples,
                ..
            } => {
                assert_eq!(name, "notify");
                assert_eq!(feature, "macos_kqueue");
                assert_eq!(*feature_platform, PlatformTag::Apple);
                assert_eq!(triples, &vec!["x86_64-unknown-linux-musl".to_string()]);
            }
        }
    }

    #[test]
    fn linux_only_with_unregistered_feature_yields_no_diagnostic() {
        // Unregistered features (no platform_features.rs entry) skip the
        // check — `lookup` returns None and the diagnostic walker
        // continues. Preserves the "don't flag features the fleet
        // hasn't classified yet" invariant.
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["unregistered-feature".into()]);
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "x86_64-unknown-linux-musl".to_string(),
            target_resolve_for(&k, vec!["unregistered-feature".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        assert!(diagnose(&s).is_empty());
    }

    #[test]
    fn leak_collects_every_offending_triple() {
        // Same feature leaks onto multiple non-apple triples — one
        // diagnostic should aggregate them all.
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["macos_fsevent".into()]);
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "x86_64-unknown-linux-musl".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        tr.insert(
            "aarch64-unknown-linux-gnu".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        tr.insert(
            "aarch64-apple-darwin".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        let d = diagnose(&s);
        assert_eq!(d.len(), 1);
        match &d[0] {
            Diagnostic::PlatformFeatureLeakAcrossTargets { triples, .. } => {
                assert_eq!(
                    triples,
                    &vec![
                        "aarch64-unknown-linux-gnu".to_string(),
                        "x86_64-unknown-linux-musl".to_string(),
                    ]
                );
            }
        }
    }

    #[test]
    fn fix_hint_for_notify_recommends_target_gated_macos_kqueue() {
        // The hint must steer the operator to the cfg-gated form —
        // putting `features = ["macos_kqueue"]` in plain [dependencies]
        // is the trap that produced shikumi 5139dd2's Linux-breaking
        // lockfile. The hint must call out both halves: bare notify in
        // [dependencies] AND the target-gated opt-in block.
        let mut s = empty_spec();
        let (k, c) = registry_crate("notify", "8.2.0", vec!["macos_fsevent".into()]);
        s.crates.insert(k.clone(), c);
        let mut tr = IndexMap::new();
        tr.insert(
            "x86_64-unknown-linux-musl".to_string(),
            target_resolve_for(&k, vec!["macos_fsevent".into()]),
        );
        s.target_resolves = Some(CompactTargetResolves::from_full(tr));
        let d = diagnose(&s);
        match &d[0] {
            Diagnostic::PlatformFeatureLeakAcrossTargets {
                upstream_fix_hint, ..
            } => {
                assert!(
                    upstream_fix_hint.contains("default-features = false"),
                    "hint must name `default-features = false`, got: {upstream_fix_hint}"
                );
                assert!(
                    upstream_fix_hint.contains("target_os = \"macos\""),
                    "hint must steer to the cfg(target_os = \"macos\") target-gate, got: {upstream_fix_hint}"
                );
                assert!(
                    upstream_fix_hint.contains("macos_kqueue"),
                    "hint must name a concrete macOS backend (macos_kqueue), got: {upstream_fix_hint}"
                );
                assert!(
                    upstream_fix_hint.contains("inotify"),
                    "hint must explain Linux falls back to inotify, got: {upstream_fix_hint}"
                );
            }
        }
    }
}