zccache-compiler 1.2.15

Compiler detection and argument parsing for zccache
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
//! Archiver/static-linker detection and argument parsing for zccache.
//!
//! Handles parsing command-line arguments for `ar`, `llvm-ar`, and MSVC `lib.exe`
//! to determine cacheability and extract cache-relevant information.

use zccache_core::NormalizedPath;

/// Supported archiver tool families.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiverFamily {
    /// GNU ar (ar, x86_64-linux-gnu-ar, etc.)
    Ar,
    /// LLVM ar (llvm-ar, llvm-ar-15, etc.)
    LlvmAr,
    /// MSVC lib.exe
    MsvcLib,
}

/// The result of parsing an archiver invocation.
#[derive(Debug, Clone)]
pub enum ParsedArchiveInvocation {
    /// A cacheable archive creation.
    Cacheable(CacheableArchive),
    /// A non-cacheable invocation.
    NonCacheable {
        /// Reason why this invocation is not cacheable.
        reason: String,
    },
}

/// A cacheable archive creation invocation.
#[derive(Debug, Clone)]
pub struct CacheableArchive {
    /// The archiver executable path.
    pub tool: NormalizedPath,
    /// The detected archiver family.
    pub family: ArchiverFamily,
    /// Input object files (order preserved — matters for ar).
    pub input_files: Vec<NormalizedPath>,
    /// The output archive file path.
    pub output_file: NormalizedPath,
    /// Flags relevant to cache keying (e.g., "rcs", "rcsD").
    pub cache_relevant_flags: Vec<String>,
    /// The full original argument list (for fallback execution).
    pub original_args: Vec<String>,
    /// Whether non-deterministic output is detected (missing D flag / /BREPRO).
    pub non_deterministic: bool,
}

/// Check if a tool name is a known archiver.
#[must_use]
pub fn is_archiver(tool: &str) -> bool {
    detect_family(tool).is_some()
}

/// Detect the archiver family from the tool path/name.
fn detect_family(tool: &str) -> Option<ArchiverFamily> {
    let name = std::path::Path::new(tool)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(tool);

    // MSVC lib.exe (case-insensitive on Windows)
    if name.eq_ignore_ascii_case("lib") {
        return Some(ArchiverFamily::MsvcLib);
    }

    // llvm-ar, llvm-ar-15, etc. — check before plain "ar" to avoid false match
    if name.starts_with("llvm-ar") || name.starts_with("llvm_ar") {
        return Some(ArchiverFamily::LlvmAr);
    }

    // GNU ar: ar, x86_64-linux-gnu-ar, aarch64-linux-gnu-ar, etc.
    // Must end with "ar" (not just contain it — "lzma-archiver" is not ar)
    if name == "ar" || name.ends_with("-ar") {
        return Some(ArchiverFamily::Ar);
    }

    None
}

/// Parse an archiver invocation's arguments to determine cacheability.
///
/// Returns a `ParsedArchiveInvocation` indicating whether the invocation is
/// cacheable, and if so, extracts the relevant information.
#[must_use]
pub fn parse_archive_invocation(tool: &str, args: &[String]) -> ParsedArchiveInvocation {
    let family = match detect_family(tool) {
        Some(f) => f,
        None => {
            return ParsedArchiveInvocation::NonCacheable {
                reason: format!("not a recognized archiver: {tool}"),
            };
        }
    };

    match family {
        ArchiverFamily::MsvcLib => parse_msvc_lib(tool, args),
        ArchiverFamily::Ar | ArchiverFamily::LlvmAr => parse_gnu_ar(tool, family, args),
    }
}

/// Parse GNU ar / llvm-ar arguments.
///
/// GNU ar syntax:
///   ar [--plugin name] [-X32_64] [-]operation [relpos] [count] archive [member...]
///
/// We only cache archive creation: operations containing 'r' (replace/insert).
/// Operations containing 'x' (extract), 't' (list), 'd' (delete), 'p' (print)
/// are not cacheable (they read from an archive, not create one).
fn parse_gnu_ar(tool: &str, family: ArchiverFamily, args: &[String]) -> ParsedArchiveInvocation {
    if args.is_empty() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no arguments".to_string(),
        };
    }

    // Find the operation string. It's the first arg that doesn't start with '--'.
    // (GNU ar allows `-rcs` or `rcs` — the dash prefix is optional.)
    let mut op_idx = 0;
    let mut long_flags = Vec::new();

    // Skip leading long options (--plugin, --target, etc.)
    while op_idx < args.len() && args[op_idx].starts_with("--") {
        long_flags.push(args[op_idx].clone());
        op_idx += 1;
        // Some long options take a value
        if op_idx < args.len()
            && !args[op_idx].starts_with('-')
            && matches!(
                long_flags.last().map(|s| s.as_str()),
                Some("--plugin" | "--target")
            )
        {
            long_flags.push(args[op_idx].clone());
            op_idx += 1;
        }
    }

    if op_idx >= args.len() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no operation specified".to_string(),
        };
    }

    let op_str = args[op_idx].strip_prefix('-').unwrap_or(&args[op_idx]);

    // Check for non-cacheable operations
    if op_str.contains('x') {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "extract operation (x) not cacheable".to_string(),
        };
    }
    if op_str.contains('t') {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "list operation (t) not cacheable".to_string(),
        };
    }
    if op_str.contains('d') {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "delete operation (d) not cacheable".to_string(),
        };
    }
    if op_str.contains('p') {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "print operation (p) not cacheable".to_string(),
        };
    }

    // We only cache 'r' (replace/insert) or 'q' (quick append, for fresh archives)
    if !op_str.contains('r') && !op_str.contains('q') {
        return ParsedArchiveInvocation::NonCacheable {
            reason: format!("unsupported operation: {op_str}"),
        };
    }

    // Non-determinism check: 'D' flag enables deterministic mode (zero UIDs, timestamps)
    let non_deterministic = !op_str.contains('D');

    // After the operation, next arg is the archive name, then member files.
    // But some modifiers consume extra positional args:
    //   'a', 'b', 'i' → next arg is relpos (a member name for positioning)
    let has_relpos = op_str.contains('a') || op_str.contains('b') || op_str.contains('i');
    // 'N' → next arg is count
    let has_count = op_str.contains('N');

    let mut pos = op_idx + 1;

    // Skip relpos if present
    if has_relpos {
        pos += 1;
    }
    // Skip count if present
    if has_count {
        pos += 1;
    }

    if pos >= args.len() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no archive file specified".to_string(),
        };
    }

    let output_file = NormalizedPath::new(&args[pos]);
    pos += 1;

    // Remaining args are input member files
    let input_files: Vec<NormalizedPath> = args[pos..].iter().map(NormalizedPath::from).collect();

    if input_files.is_empty() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no input files specified".to_string(),
        };
    }

    let mut cache_relevant_flags = vec![op_str.to_string()];
    cache_relevant_flags.extend(long_flags);

    ParsedArchiveInvocation::Cacheable(CacheableArchive {
        tool: NormalizedPath::new(tool),
        family,
        input_files,
        output_file,
        cache_relevant_flags,
        original_args: args.to_vec(),
        non_deterministic,
    })
}

/// Parse MSVC lib.exe arguments.
///
/// lib.exe syntax:
///   lib [options] [/OUT:filename] [objfiles...] [libraries...]
///
/// Options start with `/` or `-`. Input files are positional.
fn parse_msvc_lib(tool: &str, args: &[String]) -> ParsedArchiveInvocation {
    if args.is_empty() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no arguments".to_string(),
        };
    }

    let mut output_file: Option<NormalizedPath> = None;
    let mut input_files: Vec<NormalizedPath> = Vec::new();
    let mut cache_relevant_flags: Vec<String> = Vec::new();
    let mut is_extract = false;
    let mut has_brepro = false;
    let mut has_list = false;

    for arg in args {
        let upper = arg.to_uppercase();

        // /EXTRACT:member — extraction mode
        if upper.starts_with("/EXTRACT:") || upper.starts_with("-EXTRACT:") {
            is_extract = true;
            break;
        }

        // /LIST — list mode
        if upper == "/LIST" || upper == "-LIST" {
            has_list = true;
        }

        // /OUT:filename
        if upper.starts_with("/OUT:") || upper.starts_with("-OUT:") {
            output_file = Some(NormalizedPath::new(&arg[5..]));
            continue;
        }

        // /BREPRO — binary reproducibility
        if upper == "/BREPRO" || upper == "-BREPRO" {
            has_brepro = true;
            cache_relevant_flags.push(arg.clone());
            continue;
        }

        // Other flags
        if arg.starts_with('/') || arg.starts_with('-') {
            cache_relevant_flags.push(arg.clone());
            continue;
        }

        // Positional — input file
        input_files.push(NormalizedPath::new(arg));
    }

    if is_extract {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "extract operation (/EXTRACT) not cacheable".to_string(),
        };
    }

    if has_list {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "list operation (/LIST) not cacheable".to_string(),
        };
    }

    if input_files.is_empty() {
        return ParsedArchiveInvocation::NonCacheable {
            reason: "no input files specified".to_string(),
        };
    }

    // If no /OUT:, lib.exe defaults to first input file with .lib extension
    let output_file = output_file.unwrap_or_else(|| {
        let first = &input_files[0];
        NormalizedPath::new(first.with_extension("lib"))
    });

    ParsedArchiveInvocation::Cacheable(CacheableArchive {
        tool: NormalizedPath::new(tool),
        family: ArchiverFamily::MsvcLib,
        input_files,
        output_file,
        cache_relevant_flags,
        original_args: args.to_vec(),
        non_deterministic: !has_brepro,
    })
}

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

    fn args(s: &[&str]) -> Vec<String> {
        s.iter().map(|x| x.to_string()).collect()
    }

    // ─── Detection ─────────────────────────────────────────────────────

    #[test]
    fn detect_gnu_ar() {
        assert_eq!(detect_family("ar"), Some(ArchiverFamily::Ar));
        assert_eq!(detect_family("/usr/bin/ar"), Some(ArchiverFamily::Ar));
        assert_eq!(
            detect_family("x86_64-linux-gnu-ar"),
            Some(ArchiverFamily::Ar)
        );
        assert_eq!(
            detect_family("aarch64-linux-gnu-ar"),
            Some(ArchiverFamily::Ar)
        );
    }

    #[test]
    fn detect_llvm_ar() {
        assert_eq!(detect_family("llvm-ar"), Some(ArchiverFamily::LlvmAr));
        assert_eq!(detect_family("llvm-ar-15"), Some(ArchiverFamily::LlvmAr));
        assert_eq!(
            detect_family("/usr/bin/llvm-ar"),
            Some(ArchiverFamily::LlvmAr)
        );
    }

    #[test]
    fn detect_msvc_lib() {
        assert_eq!(detect_family("lib"), Some(ArchiverFamily::MsvcLib));
        assert_eq!(detect_family("lib.exe"), Some(ArchiverFamily::MsvcLib));
        assert_eq!(detect_family("LIB"), Some(ArchiverFamily::MsvcLib));
        assert_eq!(detect_family("LIB.EXE"), Some(ArchiverFamily::MsvcLib));
    }

    #[test]
    fn detect_unknown_tool() {
        assert_eq!(detect_family("gcc"), None);
        assert_eq!(detect_family("clang"), None);
        assert_eq!(detect_family("ld"), None);
        assert_eq!(detect_family("lzma"), None);
    }

    #[test]
    fn is_archiver_works() {
        assert!(is_archiver("ar"));
        assert!(is_archiver("llvm-ar"));
        assert!(is_archiver("lib.exe"));
        assert!(!is_archiver("gcc"));
        assert!(!is_archiver("ld"));
    }

    // ─── GNU ar parsing ────────────────────────────────────────────────

    #[test]
    fn basic_ar_rcs() {
        let result = parse_archive_invocation("ar", &args(&["rcs", "libfoo.a", "a.o", "b.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.family, ArchiverFamily::Ar);
                assert_eq!(c.output_file, NormalizedPath::new("libfoo.a"));
                assert_eq!(c.input_files.len(), 2);
                assert_eq!(c.input_files[0], NormalizedPath::new("a.o"));
                assert_eq!(c.input_files[1], NormalizedPath::new("b.o"));
                assert!(c.non_deterministic); // no D flag
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_with_dash_prefix() {
        let result = parse_archive_invocation("ar", &args(&["-rcs", "libfoo.a", "a.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.output_file, NormalizedPath::new("libfoo.a"));
                assert_eq!(c.input_files, vec![NormalizedPath::new("a.o")]);
                assert_eq!(c.cache_relevant_flags, vec!["rcs"]);
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_deterministic_flag() {
        let result = parse_archive_invocation("ar", &args(&["rcsD", "libfoo.a", "a.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert!(!c.non_deterministic); // D flag present
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_extract_non_cacheable() {
        let result = parse_archive_invocation("ar", &args(&["x", "libfoo.a"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_list_non_cacheable() {
        let result = parse_archive_invocation("ar", &args(&["t", "libfoo.a"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_delete_non_cacheable() {
        let result = parse_archive_invocation("ar", &args(&["d", "libfoo.a", "old.o"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_print_non_cacheable() {
        let result = parse_archive_invocation("ar", &args(&["p", "libfoo.a"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_no_args() {
        let result = parse_archive_invocation("ar", &args(&[]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_no_inputs() {
        let result = parse_archive_invocation("ar", &args(&["rcs", "libfoo.a"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn ar_quick_append() {
        let result =
            parse_archive_invocation("ar", &args(&["qcs", "libfoo.a", "a.o", "b.o", "c.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.input_files.len(), 3);
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_preserves_input_order() {
        let result =
            parse_archive_invocation("ar", &args(&["rcs", "libfoo.a", "z.o", "a.o", "m.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.input_files[0], NormalizedPath::new("z.o"));
                assert_eq!(c.input_files[1], NormalizedPath::new("a.o"));
                assert_eq!(c.input_files[2], NormalizedPath::new("m.o"));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_with_relpos_modifier() {
        // ar rcsb existing.o libfoo.a new.o
        // 'b' modifier: insert before existing.o (relpos arg consumed)
        let result =
            parse_archive_invocation("ar", &args(&["rcsb", "existing.o", "libfoo.a", "new.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.output_file, NormalizedPath::new("libfoo.a"));
                assert_eq!(c.input_files, vec![NormalizedPath::new("new.o")]);
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn ar_with_long_options() {
        let result = parse_archive_invocation(
            "ar",
            &args(&["--plugin", "liblto_plugin.so", "rcs", "libfoo.a", "a.o"]),
        );
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.output_file, NormalizedPath::new("libfoo.a"));
                assert_eq!(c.input_files, vec![NormalizedPath::new("a.o")]);
                assert!(c.cache_relevant_flags.contains(&"--plugin".to_string()));
                assert!(c
                    .cache_relevant_flags
                    .contains(&"liblto_plugin.so".to_string()));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn llvm_ar_basic() {
        let result = parse_archive_invocation("llvm-ar", &args(&["rcs", "libfoo.a", "a.o", "b.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.family, ArchiverFamily::LlvmAr);
                assert_eq!(c.output_file, NormalizedPath::new("libfoo.a"));
                assert_eq!(c.input_files.len(), 2);
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn cross_compile_ar() {
        let result =
            parse_archive_invocation("x86_64-linux-gnu-ar", &args(&["rcs", "libfoo.a", "a.o"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.family, ArchiverFamily::Ar);
                assert_eq!(c.tool, NormalizedPath::new("x86_64-linux-gnu-ar"));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    // ─── MSVC lib.exe parsing ──────────────────────────────────────────

    #[test]
    fn basic_msvc_lib() {
        let result =
            parse_archive_invocation("lib.exe", &args(&["/OUT:foo.lib", "a.obj", "b.obj"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.family, ArchiverFamily::MsvcLib);
                assert_eq!(c.output_file, NormalizedPath::new("foo.lib"));
                assert_eq!(c.input_files.len(), 2);
                assert_eq!(c.input_files[0], NormalizedPath::new("a.obj"));
                assert_eq!(c.input_files[1], NormalizedPath::new("b.obj"));
                assert!(c.non_deterministic); // no /BREPRO
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn msvc_lib_with_brepro() {
        let result =
            parse_archive_invocation("lib.exe", &args(&["/BREPRO", "/OUT:foo.lib", "a.obj"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert!(!c.non_deterministic); // /BREPRO present
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn msvc_lib_extract_non_cacheable() {
        let result =
            parse_archive_invocation("lib.exe", &args(&["/EXTRACT:member.obj", "foo.lib"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn msvc_lib_list_non_cacheable() {
        let result = parse_archive_invocation("lib.exe", &args(&["/LIST", "foo.lib"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn msvc_lib_default_output_name() {
        // Without /OUT:, output defaults to first input with .lib extension
        let result = parse_archive_invocation("lib.exe", &args(&["a.obj", "b.obj"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.output_file, NormalizedPath::new("a.lib"));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn msvc_lib_no_inputs() {
        let result = parse_archive_invocation("lib.exe", &args(&["/OUT:foo.lib"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }

    #[test]
    fn msvc_lib_with_flags() {
        let result = parse_archive_invocation(
            "lib.exe",
            &args(&["/NOLOGO", "/MACHINE:X64", "/OUT:foo.lib", "a.obj"]),
        );
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert!(c.cache_relevant_flags.contains(&"/NOLOGO".to_string()));
                assert!(c.cache_relevant_flags.contains(&"/MACHINE:X64".to_string()));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn msvc_lib_preserves_input_order() {
        let result = parse_archive_invocation(
            "lib.exe",
            &args(&["/OUT:foo.lib", "z.obj", "a.obj", "m.obj"]),
        );
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.input_files[0], NormalizedPath::new("z.obj"));
                assert_eq!(c.input_files[1], NormalizedPath::new("a.obj"));
                assert_eq!(c.input_files[2], NormalizedPath::new("m.obj"));
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    #[test]
    fn msvc_lib_dash_syntax() {
        // lib.exe also accepts - prefix for flags
        let result =
            parse_archive_invocation("lib.exe", &args(&["-OUT:foo.lib", "-BREPRO", "a.obj"]));
        match result {
            ParsedArchiveInvocation::Cacheable(c) => {
                assert_eq!(c.output_file, NormalizedPath::new("foo.lib"));
                assert!(!c.non_deterministic);
            }
            other => panic!("expected cacheable, got: {other:?}"),
        }
    }

    // ─── Unknown tool ──────────────────────────────────────────────────

    #[test]
    fn unknown_tool_non_cacheable() {
        let result = parse_archive_invocation("gcc", &args(&["-c", "foo.c"]));
        assert!(matches!(
            result,
            ParsedArchiveInvocation::NonCacheable { .. }
        ));
    }
}