zccache 1.12.4

Local-first compiler cache for C/C++/Rust/Emscripten
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! `#include` directive scanner.
//!
//! Scans C/C++ source files for `#include` directives, skipping comments
//! and string literals. Does not evaluate preprocessor conditionals —
//! all `#include` directives are returned unconditionally.

use std::path::Path;

use super::search_paths::IncludeSearchPaths;
use crate::core::NormalizedPath;

/// The kind of `#include` directive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IncludeKind {
    /// `#include "foo.h"` — quoted include.
    Quoted,
    /// `#include <foo.h>` — angle-bracket include.
    AngleBracket,
    /// `#include MACRO` — computed include, cannot resolve by text scanning.
    Computed(String),
}

/// A parsed `#include` directive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeDirective {
    /// The kind of include.
    pub kind: IncludeKind,
    /// The path as written in the source (for Quoted/AngleBracket),
    /// or the macro name (for Computed).
    pub path: String,
    /// 1-based line number in the file.
    pub line: u32,
}

/// Result of a recursive include scan.
#[derive(Debug, Clone)]
pub struct ScanResult {
    /// All resolved include paths (absolute, deduplicated).
    pub resolved: Vec<NormalizedPath>,
    /// Include paths that could not be resolved to an existing file.
    pub unresolved: Vec<String>,
    /// True if any `#include MACRO` (computed include) was found.
    pub has_computed: bool,
}

/// Scan a source string for `#include` directives.
///
/// Skips directives inside `//` line comments, `/* */` block comments,
/// and string/character literals. Handles backslash line continuations.
pub fn scan_includes_str(source: &str) -> Vec<IncludeDirective> {
    let joined = join_continuations(source);
    let mut results = Vec::new();

    // Track original line numbers: each line in `joined` maps to a source line.
    // After joining continuations, we need to track the starting line of each
    // logical line.
    let line_map = build_line_map(source);

    let mut in_block_comment = false;

    for (logical_idx, line) in joined.lines().enumerate() {
        let source_line = if logical_idx < line_map.len() {
            line_map[logical_idx]
        } else {
            (logical_idx + 1) as u32
        };

        if in_block_comment {
            if let Some(end) = line.find("*/") {
                // Block comment ends on this line. Check rest of line.
                let rest = &line[end + 2..];
                if let Some(dir) = parse_include_from_line(rest) {
                    results.push(IncludeDirective {
                        line: source_line,
                        ..dir
                    });
                }
                in_block_comment = false;
                // Could have another block comment start after...
                if rest.contains("/*") {
                    let after_end = rest.find("/*").unwrap();
                    if !rest[..after_end].contains("*/") {
                        in_block_comment = true;
                    }
                }
            }
            continue;
        }

        // Strip line comments first.
        let effective = strip_comments(line, &mut in_block_comment);
        if let Some(dir) = parse_include_from_line(&effective) {
            results.push(IncludeDirective {
                line: source_line,
                ..dir
            });
        }
    }

    results
}

/// Scan a file on disk for `#include` directives.
///
/// # Errors
///
/// Returns an error if the file cannot be read.
pub fn scan_includes(path: &Path) -> std::io::Result<Vec<IncludeDirective>> {
    let source = std::fs::read_to_string(path)?;
    Ok(scan_includes_str(&source))
}

/// Resolve a single `#include` directive to an absolute path.
///
/// For quoted includes, searches the including file's directory first,
/// then `-iquote`, `-I`, `-isystem`, `-idirafter` in order.
///
/// For angle-bracket includes, searches `-I`, `-isystem`, `-idirafter`.
///
/// Returns `None` if the file is not found in any search path.
pub fn resolve_include(
    directive: &IncludeDirective,
    search: &IncludeSearchPaths,
    including_file_dir: &Path,
) -> Option<NormalizedPath> {
    match &directive.kind {
        IncludeKind::Quoted => {
            // 1. Directory of the including file.
            let candidate = including_file_dir.join(&directive.path);
            if candidate.is_file() {
                return Some(normalize(&candidate));
            }
            // 2. Search paths for quoted includes.
            for dir in search.quoted_search_dirs() {
                let candidate = dir.join(&directive.path);
                if candidate.is_file() {
                    return Some(normalize(&candidate));
                }
            }
            None
        }
        IncludeKind::AngleBracket => {
            for dir in search.angle_search_dirs() {
                let candidate = dir.join(&directive.path);
                if candidate.is_file() {
                    return Some(normalize(&candidate));
                }
            }
            None
        }
        IncludeKind::Computed(_) => None,
    }
}

/// Recursively scan a source file for all transitive includes.
///
/// Builds the full include list by scanning the source file, resolving
/// each `#include`, then scanning each resolved header, and so on, using
/// a parallel BFS over per-level frontiers. Headers within a frontier are
/// read and parsed in parallel via rayon; new resolutions feed the next
/// frontier. A `DashSet` deduplicates so each header is scanned exactly
/// once across the DAG, even with circular or diamond includes.
///
/// `resolved` returns in BFS-level order (was DFS-post-order before
/// parallelization). Callers in `graph.rs` only iterate the list to hash
/// all files; no order invariant is broken.
pub fn scan_recursive(source: &Path, search: &IncludeSearchPaths) -> ScanResult {
    use dashmap::DashSet;
    use rayon::prelude::*;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Mutex;

    let visited: DashSet<NormalizedPath> = DashSet::new();
    let resolved: Mutex<Vec<NormalizedPath>> = Mutex::new(Vec::new());
    let unresolved: Mutex<Vec<String>> = Mutex::new(Vec::new());
    let has_computed = AtomicBool::new(false);

    // Mark the source itself as visited so we don't re-scan it via a
    // self-include chain.
    if let Some(abs) = try_normalize(source) {
        visited.insert(abs);
    }

    let mut frontier: Vec<NormalizedPath> = vec![NormalizedPath::from(source)];
    while !frontier.is_empty() {
        let next: Vec<NormalizedPath> = frontier
            .par_iter()
            .flat_map_iter(|file| {
                scan_one_level(
                    file.as_path(),
                    search,
                    &visited,
                    &resolved,
                    &unresolved,
                    &has_computed,
                )
            })
            .collect();
        frontier = next;
    }

    ScanResult {
        resolved: resolved.into_inner().expect("resolved mutex poisoned"),
        unresolved: unresolved.into_inner().expect("unresolved mutex poisoned"),
        has_computed: has_computed.load(Ordering::Relaxed),
    }
}

/// Scan one file: read it, parse `#include`s, resolve each, and return the
/// list of newly-discovered resolved paths for the next frontier level.
///
/// All four shared collections take exactly one lock per scanned file: the
/// per-file results are buffered locally and pushed in a single batch at
/// the end. This keeps Mutex contention proportional to (file count) and
/// not to (include count).
fn scan_one_level(
    file: &Path,
    search: &IncludeSearchPaths,
    visited: &dashmap::DashSet<NormalizedPath>,
    resolved: &std::sync::Mutex<Vec<NormalizedPath>>,
    unresolved: &std::sync::Mutex<Vec<String>>,
    has_computed: &std::sync::atomic::AtomicBool,
) -> Vec<NormalizedPath> {
    let directives = match scan_includes(file) {
        Ok(d) => d,
        Err(_) => return Vec::new(),
    };

    let file_dir = file.parent().unwrap_or(Path::new("."));

    let mut new_for_next: Vec<NormalizedPath> = Vec::new();
    let mut local_resolved: Vec<NormalizedPath> = Vec::new();
    let mut local_unresolved: Vec<String> = Vec::new();
    let mut saw_computed = false;

    for directive in &directives {
        match &directive.kind {
            IncludeKind::Computed(_) => {
                saw_computed = true;
            }
            _ => {
                if let Some(abs_path) = resolve_include(directive, search, file_dir) {
                    if visited.insert(abs_path.clone()) {
                        local_resolved.push(abs_path.clone());
                        new_for_next.push(abs_path);
                    }
                } else {
                    local_unresolved.push(directive.path.clone());
                }
            }
        }
    }

    if !local_resolved.is_empty() {
        resolved
            .lock()
            .expect("resolved mutex poisoned")
            .extend(local_resolved);
    }
    if !local_unresolved.is_empty() {
        unresolved
            .lock()
            .expect("unresolved mutex poisoned")
            .extend(local_unresolved);
    }
    if saw_computed {
        has_computed.store(true, std::sync::atomic::Ordering::Relaxed);
    }

    new_for_next
}

// ── Helpers ──────────────────────────────────────────────────────────

/// Join backslash-continued lines into single logical lines.
fn join_continuations(source: &str) -> String {
    let mut result = String::with_capacity(source.len());
    let mut chars = source.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\\' {
            match chars.peek() {
                Some('\n') => {
                    chars.next(); // consume the newline
                                  // Don't emit either the backslash or the newline.
                }
                Some('\r') => {
                    chars.next(); // consume \r
                    if chars.peek() == Some(&'\n') {
                        chars.next(); // consume \n
                    }
                    // Don't emit.
                }
                _ => result.push(ch),
            }
        } else {
            result.push(ch);
        }
    }

    result
}

/// Build a map from logical line index to 1-based source line number.
/// Accounts for backslash continuations merging multiple source lines.
fn build_line_map(source: &str) -> Vec<u32> {
    let mut map = Vec::new();
    let mut source_line: u32 = 1;
    let mut continued = false;

    for line in source.split('\n') {
        if !continued {
            map.push(source_line);
        }
        let trimmed = line.trim_end_matches('\r');
        continued = trimmed.ends_with('\\');
        source_line += 1;
    }

    map
}

/// Strip line comments and block comments from a line.
/// Updates `in_block_comment` state for multi-line block comments.
///
/// String literals are NOT stripped. This is intentional:
/// `#include "foo.h"` has quotes that look like strings but are part of
/// the directive syntax. False positives like `const char* s = "#include ..."`
/// are handled by `parse_include_from_line` which requires `#` to be the
/// first non-whitespace character on the line.
fn strip_comments(line: &str, in_block_comment: &mut bool) -> String {
    let mut result = String::with_capacity(line.len());
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        if *in_block_comment {
            if i + 1 < len && bytes[i] == b'*' && bytes[i + 1] == b'/' {
                *in_block_comment = false;
                i += 2;
            } else {
                i += 1;
            }
            continue;
        }

        // Line comment — stop processing this line.
        if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'/' {
            break;
        }

        // Block comment start.
        if i + 1 < len && bytes[i] == b'/' && bytes[i + 1] == b'*' {
            *in_block_comment = true;
            i += 2;
            continue;
        }

        result.push(bytes[i] as char);
        i += 1;
    }

    result
}

/// Parse an `#include` directive from a (comment-stripped) line.
fn parse_include_from_line(line: &str) -> Option<IncludeDirective> {
    let trimmed = line.trim();

    // Must start with #
    let after_hash = trimmed.strip_prefix('#')?;
    let after_hash = after_hash.trim();

    // Must be "include"
    let after_include = after_hash.strip_prefix("include")?;

    // "include" must not be part of a longer identifier.
    if let Some(next_ch) = after_include.chars().next() {
        if next_ch.is_alphanumeric() || next_ch == '_' {
            return None;
        }
    }

    let rest = after_include.trim();

    if rest.is_empty() {
        return None;
    }

    // #include "path"
    if let Some(inner) = rest.strip_prefix('"') {
        let end = inner.find('"')?;
        let path = &inner[..end];
        if path.is_empty() {
            return None;
        }
        return Some(IncludeDirective {
            kind: IncludeKind::Quoted,
            path: path.to_string(),
            line: 0, // Filled in by caller.
        });
    }

    // #include <path>
    if let Some(inner) = rest.strip_prefix('<') {
        let end = inner.find('>')?;
        let path = &inner[..end];
        if path.is_empty() {
            return None;
        }
        return Some(IncludeDirective {
            kind: IncludeKind::AngleBracket,
            path: path.to_string(),
            line: 0,
        });
    }

    // #include MACRO — computed include.
    let macro_name: String = rest
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();
    if !macro_name.is_empty() {
        return Some(IncludeDirective {
            kind: IncludeKind::Computed(macro_name.clone()),
            path: macro_name,
            line: 0,
        });
    }

    None
}

/// Normalize a path to an absolute path (best-effort, no symlink resolution).
fn normalize(path: &Path) -> NormalizedPath {
    try_normalize(path).unwrap_or_else(|| path.into())
}

fn try_normalize(path: &Path) -> Option<NormalizedPath> {
    // Use canonicalize which resolves symlinks and produces an absolute path.
    // On Windows, canonicalize produces \\?\ extended-length paths which must
    // be stripped to match the watcher's path format for journal lookups.
    let p = path.canonicalize().ok()?;
    #[cfg(windows)]
    {
        let s = p.to_string_lossy();
        if let Some(stripped) = s.strip_prefix(r"\\?\") {
            return Some(NormalizedPath::from(stripped));
        }
    }
    Some(p.into())
}

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

    // ── scan_includes_str tests ─────────────────────────────────────

    #[test]
    fn basic_quoted_include() {
        let source = r#"#include "foo.h""#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].kind, IncludeKind::Quoted);
        assert_eq!(includes[0].path, "foo.h");
        assert_eq!(includes[0].line, 1);
    }

    #[test]
    fn basic_angle_bracket_include() {
        let source = "#include <stdio.h>";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].kind, IncludeKind::AngleBracket);
        assert_eq!(includes[0].path, "stdio.h");
    }

    #[test]
    fn multiple_includes() {
        let source = r#"
#include <stdio.h>
#include "config.h"
#include <stdlib.h>
"#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 3);
        assert_eq!(includes[0].path, "stdio.h");
        assert_eq!(includes[1].path, "config.h");
        assert_eq!(includes[2].path, "stdlib.h");
    }

    #[test]
    fn include_with_path_separators() {
        let source = r#"#include "path/to/header.h""#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "path/to/header.h");
    }

    #[test]
    fn computed_include() {
        let source = "#include PLATFORM_HEADER";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(
            includes[0].kind,
            IncludeKind::Computed("PLATFORM_HEADER".to_string())
        );
        assert_eq!(includes[0].path, "PLATFORM_HEADER");
    }

    #[test]
    fn skip_line_comment() {
        let source = r#"
// #include "old.h"
#include "real.h"
"#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "real.h");
    }

    #[test]
    fn skip_block_comment() {
        let source = r#"
/* #include "old.h" */
#include "real.h"
"#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "real.h");
    }

    #[test]
    fn skip_multiline_block_comment() {
        let source = r#"
/*
#include "old1.h"
#include "old2.h"
*/
#include "real.h"
"#;
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "real.h");
    }

    #[test]
    fn skip_include_in_string_literal() {
        let source = "const char* s = \"#include \\\"fake.h\\\"\";\n#include \"real.h\"\n";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "real.h");
    }

    #[test]
    fn backslash_continuation() {
        let source = "#in\\\nclude \"continued.h\"";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "continued.h");
    }

    #[test]
    fn indented_include() {
        let source = "    #include <indented.h>";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "indented.h");
    }

    #[test]
    fn hash_space_include() {
        let source = "#  include <spaced.h>";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "spaced.h");
    }

    #[test]
    fn not_include_directive() {
        let source = "#define FOO 1\n#ifdef BAR\n#endif\n";
        let includes = scan_includes_str(source);
        assert!(includes.is_empty());
    }

    #[test]
    fn include_guard_not_confused() {
        let source = "#ifndef FOO_H\n#define FOO_H\n#include \"bar.h\"\n#endif\n";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "bar.h");
    }

    #[test]
    fn line_numbers_are_correct() {
        let source = "// preamble\n\n#include \"a.h\"\n\n#include <b.h>\n";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 2);
        assert_eq!(includes[0].line, 3);
        assert_eq!(includes[1].line, 5);
    }

    #[test]
    fn empty_source() {
        let includes = scan_includes_str("");
        assert!(includes.is_empty());
    }

    #[test]
    fn include_after_code() {
        let source = "int x = 1;\n#include \"late.h\"\n";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "late.h");
    }

    #[test]
    fn block_comment_ending_on_include_line() {
        let source = "/* comment */ #include \"after.h\"";
        let includes = scan_includes_str(source);
        assert_eq!(includes.len(), 1);
        assert_eq!(includes[0].path, "after.h");
    }

    // ── resolve_include tests ────────────────────────────────────────

    #[test]
    fn resolve_quoted_in_file_dir() {
        let dir = TempDir::new().unwrap();
        let header = dir.path().join("local.h");
        std::fs::write(&header, "// header").unwrap();

        let directive = IncludeDirective {
            kind: IncludeKind::Quoted,
            path: "local.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths::default();
        let result = resolve_include(&directive, &search, dir.path());
        assert!(result.is_some());
        assert_eq!(result.unwrap(), normalize(&header));
    }

    #[test]
    fn resolve_quoted_in_iquote_dir() {
        let dir = TempDir::new().unwrap();
        let iquote_dir = dir.path().join("iquote");
        std::fs::create_dir(&iquote_dir).unwrap();
        let header = iquote_dir.join("q.h");
        std::fs::write(&header, "// header").unwrap();

        let directive = IncludeDirective {
            kind: IncludeKind::Quoted,
            path: "q.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths {
            iquote: vec![iquote_dir.into()],
            ..Default::default()
        };
        // Not in the including file's dir — should find via iquote.
        let other_dir = dir.path().join("other");
        std::fs::create_dir(&other_dir).unwrap();
        let result = resolve_include(&directive, &search, &other_dir);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), normalize(&header));
    }

    #[test]
    fn resolve_angle_bracket_in_user_dir() {
        let dir = TempDir::new().unwrap();
        let inc = dir.path().join("inc");
        std::fs::create_dir(&inc).unwrap();
        let header = inc.join("sys.h");
        std::fs::write(&header, "// header").unwrap();

        let directive = IncludeDirective {
            kind: IncludeKind::AngleBracket,
            path: "sys.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths {
            user: vec![inc.into()],
            ..Default::default()
        };
        let result = resolve_include(&directive, &search, dir.path());
        assert!(result.is_some());
    }

    #[test]
    fn resolve_angle_bracket_skips_iquote() {
        let dir = TempDir::new().unwrap();
        let iquote_dir = dir.path().join("iquote");
        std::fs::create_dir(&iquote_dir).unwrap();
        let header = iquote_dir.join("only_iquote.h");
        std::fs::write(&header, "// header").unwrap();

        let directive = IncludeDirective {
            kind: IncludeKind::AngleBracket,
            path: "only_iquote.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths {
            iquote: vec![iquote_dir.into()],
            ..Default::default()
        };
        let result = resolve_include(&directive, &search, dir.path());
        assert!(result.is_none(), "angle bracket should not search iquote");
    }

    #[test]
    fn resolve_unresolved_returns_none() {
        let directive = IncludeDirective {
            kind: IncludeKind::Quoted,
            path: "nonexistent.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths::default();
        let result = resolve_include(&directive, &search, Path::new("/tmp"));
        assert!(result.is_none());
    }

    #[test]
    fn resolve_computed_returns_none() {
        let directive = IncludeDirective {
            kind: IncludeKind::Computed("MACRO".to_string()),
            path: "MACRO".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths::default();
        let result = resolve_include(&directive, &search, Path::new("/tmp"));
        assert!(result.is_none());
    }

    #[test]
    fn resolve_search_order_user_before_system() {
        let dir = TempDir::new().unwrap();
        let user_dir = dir.path().join("user");
        let sys_dir = dir.path().join("sys");
        std::fs::create_dir(&user_dir).unwrap();
        std::fs::create_dir(&sys_dir).unwrap();

        let user_header = user_dir.join("shared.h");
        let sys_header = sys_dir.join("shared.h");
        std::fs::write(&user_header, "// user").unwrap();
        std::fs::write(&sys_header, "// system").unwrap();

        let directive = IncludeDirective {
            kind: IncludeKind::AngleBracket,
            path: "shared.h".to_string(),
            line: 1,
        };
        let search = IncludeSearchPaths {
            user: vec![user_dir.into()],
            system: vec![sys_dir.into()],
            ..Default::default()
        };
        let result = resolve_include(&directive, &search, dir.path()).unwrap();
        assert_eq!(result, normalize(&user_header));
    }

    // ── scan_recursive tests ─────────────────────────────────────────

    #[test]
    fn recursive_scan_finds_transitive_includes() {
        let dir = TempDir::new().unwrap();

        // main.c -> a.h -> b.h
        std::fs::write(dir.path().join("main.c"), "#include \"a.h\"\n").unwrap();
        std::fs::write(dir.path().join("a.h"), "#include \"b.h\"\n").unwrap();
        std::fs::write(dir.path().join("b.h"), "// leaf\n").unwrap();

        let search = IncludeSearchPaths::default();
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        assert_eq!(result.resolved.len(), 2);
        assert!(result
            .resolved
            .contains(&normalize(&dir.path().join("a.h"))));
        assert!(result
            .resolved
            .contains(&normalize(&dir.path().join("b.h"))));
        assert!(result.unresolved.is_empty());
        assert!(!result.has_computed);
    }

    #[test]
    fn recursive_scan_handles_cycles() {
        let dir = TempDir::new().unwrap();

        // a.h -> b.h -> a.h (cycle)
        std::fs::write(dir.path().join("main.c"), "#include \"a.h\"\n").unwrap();
        std::fs::write(dir.path().join("a.h"), "#include \"b.h\"\n").unwrap();
        std::fs::write(dir.path().join("b.h"), "#include \"a.h\"\n").unwrap();

        let search = IncludeSearchPaths::default();
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        // Should find both a.h and b.h without infinite loop.
        assert_eq!(result.resolved.len(), 2);
    }

    #[test]
    fn recursive_scan_records_unresolved() {
        let dir = TempDir::new().unwrap();

        std::fs::write(
            dir.path().join("main.c"),
            "#include \"exists.h\"\n#include <missing.h>\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("exists.h"), "// ok\n").unwrap();

        let search = IncludeSearchPaths::default();
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        assert_eq!(result.resolved.len(), 1);
        assert_eq!(result.unresolved, vec!["missing.h"]);
    }

    #[test]
    fn recursive_scan_detects_computed_includes() {
        let dir = TempDir::new().unwrap();

        std::fs::write(
            dir.path().join("main.c"),
            "#include PLATFORM_HEADER\n#include \"normal.h\"\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("normal.h"), "// ok\n").unwrap();

        let search = IncludeSearchPaths::default();
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        assert!(result.has_computed);
        assert_eq!(result.resolved.len(), 1);
    }

    #[test]
    fn recursive_scan_deduplicates() {
        let dir = TempDir::new().unwrap();

        // main.c includes a.h and b.h, both include common.h
        std::fs::write(
            dir.path().join("main.c"),
            "#include \"a.h\"\n#include \"b.h\"\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("a.h"), "#include \"common.h\"\n").unwrap();
        std::fs::write(dir.path().join("b.h"), "#include \"common.h\"\n").unwrap();
        std::fs::write(dir.path().join("common.h"), "// shared\n").unwrap();

        let search = IncludeSearchPaths::default();
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        // a.h, b.h, common.h — each once.
        assert_eq!(result.resolved.len(), 3);
    }

    #[test]
    fn recursive_scan_with_search_paths() {
        let dir = TempDir::new().unwrap();
        let inc = dir.path().join("inc");
        std::fs::create_dir(&inc).unwrap();

        std::fs::write(dir.path().join("main.c"), "#include <lib.h>\n").unwrap();
        std::fs::write(inc.join("lib.h"), "#include \"detail.h\"\n").unwrap();
        std::fs::write(inc.join("detail.h"), "// impl\n").unwrap();

        let search = IncludeSearchPaths {
            user: vec![inc.clone().into()],
            ..Default::default()
        };
        let result = scan_recursive(&dir.path().join("main.c"), &search);

        assert_eq!(result.resolved.len(), 2);
        assert!(result.resolved.contains(&normalize(&inc.join("lib.h"))));
        assert!(result.resolved.contains(&normalize(&inc.join("detail.h"))));
    }

    // ── Helper function tests ────────────────────────────────────────

    #[test]
    fn join_continuations_merges_lines() {
        assert_eq!(join_continuations("a\\\nb"), "ab");
        assert_eq!(join_continuations("a\\\r\nb"), "ab");
    }

    #[test]
    fn join_continuations_preserves_normal_lines() {
        assert_eq!(join_continuations("a\nb"), "a\nb");
    }

    #[test]
    fn strip_comments_handles_line_comment() {
        let mut in_block = false;
        let result = strip_comments("code // comment", &mut in_block);
        assert_eq!(result, "code ");
        assert!(!in_block);
    }

    #[test]
    fn strip_comments_handles_block_comment() {
        let mut in_block = false;
        let result = strip_comments("before /* inside */ after", &mut in_block);
        assert_eq!(result, "before  after");
        assert!(!in_block);
    }

    #[test]
    fn strip_comments_handles_unterminated_block() {
        let mut in_block = false;
        let result = strip_comments("code /* start", &mut in_block);
        assert_eq!(result, "code ");
        assert!(in_block);
    }

    #[test]
    fn strip_comments_preserves_string_literal() {
        let mut in_block = false;
        let result = strip_comments(r#"x = "hello""#, &mut in_block);
        assert_eq!(result, r#"x = "hello""#);
    }
}