unity-solution-generator 0.1.0

Regenerates Unity .csproj/.sln files from asmdef/asmref layout without launching the Unity editor.
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
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
//! `typecheck` subcommand — validate compile via direct `csc.dll` invocation,
//! bypassing MSBuild entirely. See [[architecture.md]] (Typecheck subsystem).
//!
//! Roughly: scan + topo-sort + per-project mtime UTD check + `dotnet exec
//! csc.dll @rsp` per dirty project. The headline win is the UTD short-circuit
//! (warm no-op): MSBuild always re-invokes csc on every project even when
//! nothing changed (CoreCompile uses `$(NonExistentFile)` as a sentinel that
//! defeats stat-based UTD); we don't.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::{self, File, FileTimes};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, UNIX_EPOCH};

use rayon::prelude::*;

use crate::error::{GeneratorError, Result, io_err};
use crate::lockfile::{DllRef, Lockfile, LockfileIO, RefCategory};
use crate::paths::{DEFAULT_GENERATOR_ROOT, resolve_real_path};
use crate::project_scanner::{AsmDefRecord, ProjectCategory, ProjectScanner};
use crate::solution_generator::{BuildConfig, BuildPlatform};

#[derive(Debug, Clone)]
pub struct TypecheckOptions {
    pub project_root: String,
    pub platform: BuildPlatform,
    pub build_config: BuildConfig,
    pub extra_refs: Vec<DllRef>,
}

impl TypecheckOptions {
    pub fn new(project_root: impl Into<String>, platform: BuildPlatform) -> Self {
        Self {
            project_root: project_root.into(),
            platform,
            build_config: BuildConfig::Editor,
            extra_refs: Vec::new(),
        }
    }
    pub fn with_build_config(mut self, c: BuildConfig) -> Self {
        self.build_config = c;
        self
    }
    pub fn with_extra_refs(mut self, refs: Vec<DllRef>) -> Self {
        self.extra_refs = refs;
        self
    }
}

#[derive(Debug)]
pub struct TypecheckResult {
    /// Number of projects that had to recompile (dirty UTD).
    pub recompiled: usize,
    /// Number of projects skipped via UTD.
    pub skipped: usize,
    /// Diagnostic output from failing csc invocations, keyed by project name.
    pub failures: BTreeMap<String, String>,
}

impl TypecheckResult {
    pub fn ok(&self) -> bool {
        self.failures.is_empty()
    }
}

/// Run typecheck. Returns the per-project status; caller decides exit code.
pub fn run(opts: &TypecheckOptions) -> Result<TypecheckResult> {
    let _span = tracing::info_span!("typecheck.run").entered();
    let root = resolve_real_path(&opts.project_root);
    let lockfile = LockfileIO::load_or_scan(&root, DEFAULT_GENERATOR_ROOT)?;
    let scan = ProjectScanner::scan(&root, DEFAULT_GENERATOR_ROOT)?;

    let included = compute_included_projects(&scan.asm_def_by_name, opts);
    let levels = topo_levels(&included, &scan.asm_def_by_name);

    // Output dir: per-variant under generator root, gitignored alongside other caches.
    let variant = format!("{}-{}", opts.platform.raw(), opts.build_config.raw());
    let out_dir = format!("{}/{}/typecheck-{}", root, DEFAULT_GENERATOR_ROOT, variant);
    fs::create_dir_all(&out_dir).map_err(|e| io_err(&out_dir, e))?;

    let csc_dll = find_csc_dll().ok_or_else(|| {
        io_err(
            "csc.dll",
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "csc.dll not found — run `dotnet --list-sdks` to confirm a .NET SDK is installed",
            ),
        )
    })?;

    let common_defines = collect_defines(&lockfile, opts.platform, opts.build_config);
    let common_refs = collect_refs(&lockfile, opts.platform, opts.build_config, &opts.extra_refs);
    // Resolve MSBuild-style properties (`$(UnityPath)`, `$(ProjectRoot)`,
    // `$(UsgCache)`) in lockfile paths now — MSBuild does this at eval time
    // but `csc.dll` doesn't recognize MSBuild property syntax. Applies to
    // refs AND analyzers.
    let usg_cache = crate::paths::usg_cache_dir(&lockfile.unity_version);
    let resolve = |s: &str| -> String {
        s.replace("$(UnityPath)", &lockfile.unity_path)
            .replace("$(ProjectRoot)", &root)
            .replace("$(UsgCache)", &usg_cache)
    };
    let common_refs: Vec<DllRef> = common_refs
        .into_iter()
        .map(|r| DllRef::new(r.name, resolve(&r.path)))
        // Filter out native DLLs (CS0009: PE image doesn't contain managed metadata).
        // Unity's lockfile references some native plugins (e.g.
        // `unity_sprite_author.dll`) that MSBuild's RAR silently filters but raw
        // csc doesn't. Match RAR's behaviour by inspecting the PE header.
        .filter(|r| {
            if is_managed_dll(Path::new(&r.path)) {
                true
            } else {
                tracing::debug!(target: "unity_solution_generator::typecheck", path = %r.path, "filtered: not a managed DLL");
                false
            }
        })
        .collect();
    let analyzers: Vec<String> = lockfile
        .analyzers
        .iter()
        .map(|a| resolve(a))
        .filter(|a| is_managed_dll(Path::new(a)))
        .collect();

    let mut recompiled = 0usize;
    let mut skipped = 0usize;
    let mut failures = BTreeMap::new();
    // Tracks which projects' compiles failed (or were cascade-skipped). When a
    // downstream project references one of these, we skip rather than invoking
    // csc on a doomed compile that produces a wall of CS0006 noise.
    let mut failed_set: BTreeSet<String> = BTreeSet::new();

    // Process the DAG level-by-level. Within a level all projects are
    // independent (no cross-edges), so we fan out via rayon — each worker
    // spawns a `dotnet exec csc.dll /shared` which connects to the shared
    // VBCSCompiler over its named pipe. The server already accepts
    // concurrent requests, and our per-project filesystem writes target
    // disjoint paths (`<name>.rsp`, `<name>.dll`).
    //
    // Sequential processing across levels is required because level N+1
    // reads level N's `.dll` outputs as `/reference:` inputs and depends
    // on the failed-set decision (cascade-skip).
    for level in &levels {
        let outcomes: Vec<(String, ProjectOutcome)> = level
            .par_iter()
            .map(|name| {
                let outcome = compile_project(
                    name,
                    &scan,
                    &included,
                    &failed_set,
                    &root,
                    &out_dir,
                    &csc_dll,
                    &common_defines,
                    &common_refs,
                    &analyzers,
                    &lockfile.lang_version,
                );
                (name.clone(), outcome)
            })
            .collect();

        for (name, outcome) in outcomes {
            match outcome {
                ProjectOutcome::Recompiled => recompiled += 1,
                ProjectOutcome::Skipped => skipped += 1,
                ProjectOutcome::Empty => {}
                ProjectOutcome::CascadeSkipped(dep) => {
                    failures.insert(
                        name.clone(),
                        format!("skipped (cascade): upstream '{}' failed", dep),
                    );
                    failed_set.insert(name);
                }
                ProjectOutcome::Failed(stderr) => {
                    failures.insert(name.clone(), stderr);
                    failed_set.insert(name);
                }
                ProjectOutcome::Io(e) => return Err(e),
            }
        }
    }

    Ok(TypecheckResult {
        recompiled,
        skipped,
        failures,
    })
}

// ── inclusion + topo ──────────────────────────────────────────────────────

fn compute_included_projects(
    asm_def_by_name: &HashMap<String, AsmDefRecord>,
    opts: &TypecheckOptions,
) -> BTreeSet<String> {
    let is_editor = opts.build_config == BuildConfig::Editor;
    let target_platform = opts.platform.unity_platform_name();
    asm_def_by_name
        .iter()
        .filter(|(_, asm)| {
            if is_editor {
                return true;
            }
            if asm.category != ProjectCategory::Runtime {
                return false;
            }
            let platforms: Vec<&str> = asm
                .include_platforms
                .iter()
                .filter(|p| p.as_str() != "Editor")
                .map(String::as_str)
                .collect();
            platforms.is_empty() || platforms.contains(&target_platform)
        })
        .map(|(n, _)| n.clone())
        .collect()
}

/// Group `included` into levels: `levels[0]` has no upstream deps in
/// `included`; `levels[i+1]` has all its deps in `levels[0..=i]`. Within a
/// level all projects are independent and can be compiled in parallel.
/// Lex-sorted within levels for deterministic output.
fn topo_levels(
    included: &BTreeSet<String>,
    asm_def_by_name: &HashMap<String, AsmDefRecord>,
) -> Vec<Vec<String>> {
    let mut indeg: HashMap<String, usize> = HashMap::new();
    let mut adj: HashMap<String, Vec<String>> = HashMap::new();
    for name in included {
        indeg.entry(name.clone()).or_insert(0);
        if let Some(asm) = asm_def_by_name.get(name) {
            for r in &asm.references {
                if included.contains(r) {
                    adj.entry(r.clone()).or_default().push(name.clone());
                    *indeg.entry(name.clone()).or_insert(0) += 1;
                }
            }
        }
    }

    let mut levels: Vec<Vec<String>> = Vec::new();
    let mut current: BTreeSet<String> = indeg
        .iter()
        .filter(|(_, &d)| d == 0)
        .map(|(n, _)| n.clone())
        .collect();
    while !current.is_empty() {
        let mut next: BTreeSet<String> = BTreeSet::new();
        for n in &current {
            if let Some(succs) = adj.get(n) {
                for s in succs {
                    if let Some(d) = indeg.get_mut(s) {
                        *d -= 1;
                        if *d == 0 {
                            next.insert(s.clone());
                        }
                    }
                }
            }
        }
        levels.push(current.into_iter().collect());
        current = next;
    }
    levels
}

/// Per-project compile outcome. Counters + failure-set updates happen on the
/// caller side under the level-sequential lock; the parallel work (csc spawn)
/// is contained inside `compile_project`.
enum ProjectOutcome {
    /// csc ran and exited 0.
    Recompiled,
    /// mtime UTD said inputs weren't newer than the cached output.
    Skipped,
    /// asmdef has no `.cs` files — nothing to compile.
    Empty,
    /// At least one upstream is in `failed_set`; compile would just spew CS0006.
    CascadeSkipped(String),
    /// csc exited non-zero. Stderr captured for reporting.
    Failed(String),
    /// Local I/O error (couldn't write the rsp, etc.) — fatal, surfaced to caller.
    Io(GeneratorError),
}

/// Pure-ish: takes everything it needs by reference, mutates only its own
/// per-project filesystem outputs (`<name>.rsp`, `<name>.dll`). Safe to call
/// in parallel across projects within a topo level.
#[allow(clippy::too_many_arguments)]
fn compile_project(
    name: &str,
    scan: &crate::project_scanner::ScanResult,
    included: &BTreeSet<String>,
    failed_set: &BTreeSet<String>,
    root: &str,
    out_dir: &str,
    csc_dll: &str,
    common_defines: &[String],
    common_refs: &[DllRef],
    analyzers: &[String],
    lang_version: &str,
) -> ProjectOutcome {
    let asm = &scan.asm_def_by_name[name];

    if let Some(dep) = asm.references.iter().find(|r| failed_set.contains(*r)) {
        return ProjectOutcome::CascadeSkipped(dep.clone());
    }

    let sources = collect_sources(root, asm, &scan.dirs_by_project);
    if sources.is_empty() {
        return ProjectOutcome::Empty;
    }

    let proj_refs = collect_project_refs(asm, included, out_dir);
    let out_dll = format!("{}/{}.dll", out_dir, name);

    if is_up_to_date(&sources, common_refs, &proj_refs, &out_dll) {
        return ProjectOutcome::Skipped;
    }

    let mut defines: Vec<String> = common_defines.to_vec();
    for vd in &asm.version_defines {
        defines.push(vd.define.clone());
    }
    defines.extend(asm.include_platforms.iter().cloned());

    let rsp_path = format!("{}/{}.rsp", out_dir, name);
    let rsp_body = build_rsp(
        lang_version,
        &defines,
        common_refs,
        &proj_refs,
        analyzers,
        &sources,
        &out_dll,
        asm.allow_unsafe_code,
    );
    if let Err(e) = fs::write(&rsp_path, rsp_body) {
        return ProjectOutcome::Io(io_err(&rsp_path, e));
    }

    // Snapshot pre-compile bytes + mtime. csc with `/refonly /deterministic`
    // produces byte-identical output for unchanged inputs, but the .dll's
    // mtime advances on every emit — that cascades into spurious downstream
    // rebuilds (downstream's UTD sees `upstream.dll` newer than its own
    // output). Compare bytes after compile; if identical, restore the old
    // mtime so the cascade never starts.
    let prev_bytes = fs::read(&out_dll).ok();
    let prev_mtime = mtime_nsec(&out_dll);

    match invoke_csc(csc_dll, &rsp_path) {
        Ok(()) => {
            if let (Some(prev), Some(prev_t)) = (&prev_bytes, prev_mtime) {
                if let Ok(new) = fs::read(&out_dll) {
                    if prev == &new {
                        let _ = restore_mtime(&out_dll, prev_t);
                    }
                }
            }
            ProjectOutcome::Recompiled
        }
        Err(stderr) => ProjectOutcome::Failed(stderr),
    }
}

// ── data collection ───────────────────────────────────────────────────────

fn collect_sources(
    root: &str,
    asm: &AsmDefRecord,
    dirs_by_project: &HashMap<String, Vec<String>>,
) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let Some(dirs) = dirs_by_project.get(&asm.name) else {
        return out;
    };
    for d in dirs {
        let dir = if d.is_empty() {
            PathBuf::from(root)
        } else {
            Path::new(root).join(d)
        };
        let Ok(rd) = fs::read_dir(&dir) else { continue };
        for entry in rd.filter_map(|e| e.ok()) {
            let p = entry.path();
            if p.extension().and_then(|s| s.to_str()) == Some("cs") {
                out.push(p);
            }
        }
    }
    out.sort();
    out
}

fn collect_project_refs(
    asm: &AsmDefRecord,
    included: &BTreeSet<String>,
    out_dir: &str,
) -> Vec<PathBuf> {
    asm.references
        .iter()
        .filter(|r| included.contains(*r))
        .map(|r| PathBuf::from(format!("{}/{}.dll", out_dir, r)))
        .collect()
}

fn collect_defines(lockfile: &Lockfile, platform: BuildPlatform, config: BuildConfig) -> Vec<String> {
    let mut out: Vec<String> = lockfile.defines.clone();
    out.extend(lockfile.defines_scripting.iter().cloned());
    out.extend(platform.platform_defines().iter().map(|s| s.to_string()));
    if config == BuildConfig::Editor {
        for d in ["UNITY_EDITOR", "UNITY_EDITOR_64", "UNITY_EDITOR_OSX"] {
            out.push(d.to_string());
        }
    }
    if matches!(config, BuildConfig::Editor | BuildConfig::Dev) {
        for d in ["DEBUG", "TRACE", "UNITY_ASSERTIONS"] {
            out.push(d.to_string());
        }
    }
    out
}

fn collect_refs(
    lockfile: &Lockfile,
    platform: BuildPlatform,
    config: BuildConfig,
    extra: &[DllRef],
) -> Vec<DllRef> {
    let is_editor = config == BuildConfig::Editor;
    let mut cats = vec![RefCategory::Engine];
    if is_editor {
        cats.push(RefCategory::Editor);
    }
    cats.push(RefCategory::PlaybackStandalone);
    match platform {
        BuildPlatform::Ios => cats.push(RefCategory::PlaybackIos),
        BuildPlatform::Android => cats.push(RefCategory::PlaybackAndroid),
        BuildPlatform::Osx => {}
    }
    cats.push(RefCategory::Project);
    cats.push(RefCategory::Netstandard);

    let mut seen: BTreeSet<String> = BTreeSet::new();
    let mut out: Vec<DllRef> = Vec::new();
    for c in cats {
        for r in lockfile.refs_for(c) {
            if seen.insert(r.name.clone()) {
                out.push(r.clone());
            }
        }
    }
    for r in extra {
        if seen.insert(r.name.clone()) {
            out.push(r.clone());
        }
    }
    out
}

// ── up-to-date check ──────────────────────────────────────────────────────

fn mtime_nsec(p: impl AsRef<Path>) -> Option<u128> {
    let m = fs::metadata(p.as_ref()).ok()?;
    let secs = m.mtime() as u128;
    let nsecs = m.mtime_nsec() as u128;
    Some(secs * 1_000_000_000 + nsecs)
}

/// Set `path`'s mtime to a previously-recorded `mtime_nsec` value.
/// Used to roll back csc's freshly-emitted mtime when the bytes match the
/// pre-compile bytes — see "content-hash UTD" in `run`.
fn restore_mtime(path: &str, mtime_ns: u128) -> std::io::Result<()> {
    let secs = (mtime_ns / 1_000_000_000) as u64;
    let nanos = (mtime_ns % 1_000_000_000) as u32;
    let t = UNIX_EPOCH + Duration::new(secs, nanos);
    let f = File::options().write(true).open(path)?;
    f.set_times(FileTimes::new().set_modified(t))?;
    Ok(())
}

fn is_up_to_date(
    sources: &[PathBuf],
    refs: &[DllRef],
    proj_refs: &[PathBuf],
    out_dll: &str,
) -> bool {
    let Some(out_mtime) = mtime_nsec(out_dll) else {
        return false;
    };
    for s in sources {
        if mtime_nsec(s).map_or(true, |t| t > out_mtime) {
            return false;
        }
    }
    for r in refs {
        // Refs are pre-resolved (`$(UnityPath)` substituted) by `run`.
        // If a path doesn't exist, treat as dirty.
        if mtime_nsec(&r.path).map_or(true, |t| t > out_mtime) {
            return false;
        }
    }
    for p in proj_refs {
        if mtime_nsec(p).map_or(true, |t| t > out_mtime) {
            return false;
        }
    }
    true
}

// ── csc invocation ────────────────────────────────────────────────────────

fn find_csc_dll() -> Option<String> {
    // Parse `dotnet --list-sdks` output: "8.0.303 [/usr/local/share/dotnet/sdk]"
    // → /usr/local/share/dotnet/sdk/8.0.303/Roslyn/bincore/csc.dll. Pick the
    // highest semver — `dotnet`'s own sort order isn't contractually
    // ascending, and a future 9.0/10.0 should win even if listed first.
    let out = Command::new("dotnet").arg("--list-sdks").output().ok()?;
    if !out.status.success() {
        return None;
    }
    let stdout = String::from_utf8_lossy(&out.stdout);
    let parse_semver = |s: &str| -> (u32, u32, u32) {
        let mut parts = s.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
        (
            parts.next().unwrap_or(0),
            parts.next().unwrap_or(0),
            parts.next().unwrap_or(0),
        )
    };
    let best = stdout
        .lines()
        .filter_map(|l| {
            let l = l.trim();
            if l.is_empty() {
                return None;
            }
            let (version, rest) = l.split_once(' ')?;
            let base = rest.trim().trim_start_matches('[').trim_end_matches(']');
            Some((parse_semver(version), version.to_string(), base.to_string()))
        })
        .max_by_key(|t| t.0)?;
    let path = format!("{}/{}/Roslyn/bincore/csc.dll", best.2, best.1);
    if Path::new(&path).exists() {
        Some(path)
    } else {
        None
    }
}

#[doc(hidden)]
pub fn __test_only_build_rsp(
    lang_version: &str,
    defines: &[String],
    refs: &[DllRef],
    proj_refs: &[PathBuf],
    analyzers: &[String],
    sources: &[PathBuf],
    out_dll: &str,
    allow_unsafe: bool,
) -> String {
    build_rsp(lang_version, defines, refs, proj_refs, analyzers, sources, out_dll, allow_unsafe)
}

fn build_rsp(
    lang_version: &str,
    defines: &[String],
    refs: &[DllRef],
    proj_refs: &[PathBuf],
    analyzers: &[String],
    sources: &[PathBuf],
    out_dll: &str,
    allow_unsafe: bool,
) -> String {
    // `/noconfig` MUST go on the command line (not in the rsp) — otherwise csc
    // emits CS2023 and reads its default csc.rsp anyway. See `invoke_csc`.
    let mut s = String::new();
    s.push_str("/nostdlib+\n");
    s.push_str("/target:library\n");
    // Intentionally NOT `/refonly` — under .NET 8 SDK csc (4.10.x) it silently
    // skips body-binding diagnostics that don't affect the reference-assembly
    // surface, e.g. CS1503 at call sites. Hit on meow-tower `orgel-fix`:
    // USG reported `ok` while Unity Editor flagged a real type mismatch. We
    // emit a full library; `/deterministic` keeps output byte-identical for
    // unchanged inputs so the mtime-restore cascade-skip trick still works.
    s.push_str("/deterministic\n");
    s.push_str(&format!("/langversion:{}\n", lang_version));
    s.push_str(&format!("/out:{}\n", out_dll));
    if allow_unsafe {
        s.push_str("/unsafe+\n");
    }
    if !defines.is_empty() {
        s.push_str(&format!("/define:{}\n", defines.join(";")));
    }
    for r in refs {
        s.push_str(&format!("/reference:{}\n", r.path));
    }
    for p in proj_refs {
        s.push_str(&format!("/reference:{}\n", p.display()));
    }
    for a in analyzers {
        s.push_str(&format!("/analyzer:{}\n", a));
    }
    for src in sources {
        s.push_str(&format!("{}\n", src.display()));
    }
    s
}

fn invoke_csc(csc_dll: &str, rsp_path: &str) -> std::result::Result<(), String> {
    let out = Command::new("dotnet")
        .arg("exec")
        .arg(csc_dll)
        // `/noconfig` and `/shared` are client-only flags and MUST go on the
        // command line (not in the rsp — csc otherwise rejects them with
        // CS2007 / CS2023). `/shared` connects to a long-lived VBCSCompiler
        // over the named-pipe protocol; the server amortizes Roslyn JIT +
        // metadata-loading across calls (~390 ms saved per call after the
        // first). VBCSCompiler self-spawns on first connect, idles 10 min.
        .arg("/shared")
        .arg("/noconfig")
        .arg(format!("@{}", rsp_path))
        .output()
        .map_err(|e| format!("failed to spawn dotnet: {}", e))?;
    if out.status.success() {
        Ok(())
    } else {
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        Err(filter_diagnostics(&format!("{}{}", stdout, stderr)))
    }
}

/// Strip `warning CS####` and `info CS####` / `info USG####` lines from csc
/// output. Typecheck is for errors only; warnings repeat across assemblies
/// that share sources via asmref (e.g. `com.boxcat.libs` pulled into half a
/// dozen projects), and they're not actionable from the typecheck path.
/// Errors and the csc banner pass through untouched.
fn filter_diagnostics(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for line in s.lines() {
        // csc diagnostics: `<path>(L,C): <severity> <CODE>: <text>` or
        // `<severity> <CODE>: <text>` for tool-level info. Drop everything
        // except errors. Includes `info SP####` from DiagnosticSuppressor,
        // `info USG####` (Unity), `warning CS####`, etc.
        if line.contains(": warning ") || line.contains(": info ") {
            continue;
        }
        let t = line.trim_start();
        if t.starts_with("warning ") || t.starts_with("info ") {
            continue;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// True if `path` is a managed-code (CLI) PE binary. Reads enough of the PE
/// header to find the CLR Runtime Header data-directory entry (index 14 of 16);
/// if its RVA is non-zero, the file is a managed assembly.
///
/// Native DLLs (e.g. Unity's `unity_sprite_author.dll`) have an empty CLR
/// header entry; passing them via `/reference:` to csc fires CS0009. MSBuild's
/// `ResolveAssemblyReferences` task does this filter — we replicate it.
///
/// PE format reference:
/// <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format>
fn is_managed_dll(path: &Path) -> bool {
    use std::io::Read;
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(e) => {
            tracing::warn!(
                "is_managed_dll: cannot open {} — dropping ref ({})",
                path.display(),
                e
            );
            return false;
        }
    };
    let mut buf = [0u8; 1024];
    let n = match f.read(&mut buf) {
        Ok(n) => n,
        Err(e) => {
            tracing::warn!(
                "is_managed_dll: read failed for {} — dropping ref ({})",
                path.display(),
                e
            );
            return false;
        }
    };
    if n < 0x40 {
        return false;
    }
    let e_lfanew = u32::from_le_bytes([buf[0x3c], buf[0x3d], buf[0x3e], buf[0x3f]]) as usize;
    // PE signature + COFF header (20) + Optional Header magic (2)
    if e_lfanew + 24 + 2 > n {
        return false;
    }
    if &buf[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
        return false;
    }
    let opt_off = e_lfanew + 24;
    let magic = u16::from_le_bytes([buf[opt_off], buf[opt_off + 1]]);
    let dd_off = match magic {
        0x10b => opt_off + 96,  // PE32
        0x20b => opt_off + 112, // PE32+
        _ => return false,
    };
    // Data directory entry 14 = CLR Runtime Header. Each entry is 8 bytes
    // ({RVA: u32, Size: u32}). Non-zero RVA → managed.
    let clr_off = dd_off + 14 * 8;
    if clr_off + 4 > n {
        return false;
    }
    let clr_va = u32::from_le_bytes([buf[clr_off], buf[clr_off + 1], buf[clr_off + 2], buf[clr_off + 3]]);
    clr_va != 0
}