cpp_code_analysis 0.1.1

The analysis layer of cpp_ls: the preprocessor, symbol scopes, type inference and the semantic checks.
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
//! Finding the file an `#include` names.
//!
//! # The rules, and why each one exists
//!
//! * **`#include "x.h"` searches the including file's own directory first.** That is the whole difference
//!   between the two spellings, and it is what lets a header include its own neighbours without the build
//!   system listing every directory.
//! * **`#include <x.h>` does not.** A system header that accidentally picks up a project file of the same
//!   name is a bug that is very hard to see; the standard forbids the search precisely so that it cannot
//!   happen.
//! * **User paths (`-I`) before system paths (`-isystem`).** A project overriding a system header with its
//!   own copy of the same name is a real technique, and it only works if the order is respected.
//! * **`#include_next` continues from where the current file was found**, not from the start. It exists so
//!   that a wrapper header can forward to the header it shadows, and searching from the start would find
//!   the wrapper again.
//!
//! # What a failure is
//!
//! Not an error. An unresolved include is the normal state of a file being written, of a project without a
//! compile database, and of a codebase whose dependencies are not checked out. The analysis continues
//! without the included declarations, which is worse than having them and much better than refusing to
//! analyse the file at all. [`Unresolved`] carries what was searched so that a "cannot find header" message
//! can say where it looked.

use std::path::{Path, PathBuf};

use crate::{
    config::CompilerConfig,
    directive::{Include, IncludeForm},
    paths::{FileId, FileProvider, PathInterner, join_normalized, normalize_path},
};

/// A resolved include.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
    pub file: FileId,
    /// The path as it was found: the candidate that existed.
    pub path: PathBuf,
    /// Which directory it was found in — the entry of the search list that matched.
    ///
    /// Needed for `#include_next`, and worth keeping for a consumer that wants to distinguish a project
    /// header from a system one without re-running the search.
    pub found_in: FoundIn,
}

/// Where in the search order a file was found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FoundIn {
    /// The including file's own directory.
    LocalDirectory,
    /// Index into [`CompilerConfig::include_paths`].
    SearchPath(usize),
}

/// An include that could not be resolved, and what was tried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unresolved {
    /// The name as written, with its delimiters removed.
    pub name: Box<str>,
    /// Every candidate path that was tried, in order.
    ///
    /// Kept because "cannot find vector" is not actionable and "looked in these four directories" is.
    pub searched: Vec<PathBuf>,
}

/// The outcome of resolving an include.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
    Resolved(Resolved),
    Unresolved(Unresolved),
}

impl Resolution {
    pub fn resolved(&self) -> Option<&Resolved> {
        match self {
            Resolution::Resolved(resolved) => Some(resolved),
            Resolution::Unresolved(_) => None,
        }
    }

    pub fn is_resolved(&self) -> bool {
        matches!(self, Resolution::Resolved(_))
    }
}

/// **The `include` directories above a file, nearest first** — the `-I` a compilation database would have named, for
/// a checkout that has none.
///
/// Climbs from `directory` to its ancestors and takes every one that has an `include` child. A file at
/// `CodeFormatServer/src/main.cpp` gets `CodeFormatServer/include`; a file at
/// `CodeFormatCore/src/Format/Analyzer/SpaceAnalyzer.cpp` gets `CodeFormatCore/include`.
///
/// **It does not stop at the first ancestor without one**, and the first attempt at this did — which found nothing
/// at all for this project, because the file is in `src/` and `src/include` does not exist while the answer is one
/// level up. There is no level at which the climb is "done", so the bound is what ends it.
///
/// Bounded, because the climb's length is a fact about where a checkout sits on disk — `E:\a\b\c\…` has no natural
/// end — and a session may not spend an unbounded number of probes deciding what to look at.
///
/// The **provider** is asked, not `std::fs`, so that a session over a virtual filesystem — `MemoryFiles` in every
/// test — behaves the same way, and so that a provider that caches its answers caches these too.
fn include_roots_above<F: FileProvider>(directory: &Path, files: &F) -> Vec<PathBuf> {
    /// How far up to look. Six covers `repo/<target>/src/<module>/<sub>`, which is as deep as this layout goes in
    /// practice, and it is small enough that a checkout at the root of a drive cannot collect unrelated trees.
    const LEVELS: usize = 6;

    let mut roots = Vec::new();
    let mut at = Some(directory);
    for _ in 0..LEVELS {
        let Some(current) = at else { break };
        let candidate = current.join("include");
        if files.exists(&candidate) {
            roots.push(candidate);
        }
        at = current.parent();
    }
    roots
}

/// Resolves includes against a provider and a configuration.
///
/// Holds a `&mut PathInterner` because resolving is the moment a file's identity is decided: the id has to
/// be minted by whoever keeps the table, and there is no useful resolution that does not produce one.
pub struct IncludeResolver<'a, F: FileProvider> {
    files: &'a F,
    config: &'a CompilerConfig,
}

impl<'a, F: FileProvider> IncludeResolver<'a, F> {
    pub fn new(files: &'a F, config: &'a CompilerConfig) -> Self {
        IncludeResolver { files, config }
    }

    /// The provider this resolver reads through.
    ///
    /// Exposed for the one caller that has to resolve something an include search cannot: a **module partition**,
    /// whose file is found by the module naming convention rather than by a search path. It needs the same provider
    /// and the same configuration, and taking them from here is what keeps one resolver per file rather than two.
    pub fn files(&self) -> &'a F {
        self.files
    }

    /// The compilation this resolver resolves against.
    pub fn config(&self) -> &'a CompilerConfig {
        self.config
    }

    /// Resolve an include written in the file at `including`.
    ///
    /// `including` is the *directory* of the file doing the including, which the caller has because only it
    /// knows how that file was itself found.
    pub fn resolve(
        &self,
        include: &Include,
        including: &Path,
        origin: Option<&FoundIn>,
        interner: &mut PathInterner,
    ) -> Resolution {
        let name = Path::new(&*include.target);
        let mut searched = Vec::new();

        // A macro target (`#include HEADER`) cannot be resolved here: its value comes from expansion, and
        // guessing is not available. Reported as unresolved with nothing searched, which is the honest
        // description — no directory could have helped.
        if include.form == IncludeForm::Macro {
            return Resolution::Unresolved(Unresolved {
                name: include.target.clone(),
                searched,
            });
        }

        // A target that is absolute skips the search entirely. Rare and legal.
        if name.is_absolute() {
            if let Some(path) = self.existing(name) {
                return Resolution::Resolved(self.resolved(
                    path,
                    FoundIn::LocalDirectory,
                    interner,
                ));
            }
            searched.push(name.to_path_buf());
            return Resolution::Unresolved(Unresolved {
                name: include.target.clone(),
                searched,
            });
        }

        // `#include_next` starts *after* the place the current file was found, so that a wrapper header
        // forwards to the header it shadows instead of finding itself.
        let mut candidates: Vec<(PathBuf, FoundIn)> = Vec::new();
        let skip_through = if include.is_next {
            origin.map(|origin| match origin {
                FoundIn::LocalDirectory => 0usize,
                FoundIn::SearchPath(index) => index + 1,
            })
        } else {
            None
        };

        if include.form == IncludeForm::Quote && skip_through.is_none() {
            candidates.push((
                join_normalized(including, name, self.case_insensitive()),
                FoundIn::LocalDirectory,
            ));
        }

        // **The `include` directories between this file and the top of its tree.**
        //
        // A compilation database names them (`-I CodeFormatServer/include`) and this project has none, which is the
        // ordinary state of a checkout nobody has configured: measured on `E:\EmmyLuaCodeStyle`, a real CMake project
        // laid out as `src/` + `include/` per target, **the closure of its `main.cpp` was 14 files instead of the
        // whole program** — `#include "Session/StandardIOSession.h"` was searched for beside `main.cpp` and in
        // MSVC's own directories, and the file is at `CodeFormatServer/include/Session/StandardIOSession.h`.
        //
        // `-I` is what the compile command would have said, and the layout that produces it is a convention rather
        // than a guess: `include/` beside `src/` is what CMake projects have, and the climb stops at the first
        // ancestor without one. A **quoted** include only, deliberately — an inferred directory must not be able to
        // shadow `<vector>`, and an angle include in this project is a system header.
        //
        // A search that finds something is a file that exists at the spelling asked for, and the summary records
        // which path won, so a wrong hit is a wrong file rather than a wrong answer about a right one — the same
        // standing every `-I` has.
        for root in include_roots_above(including, self.files) {
            candidates.push((
                join_normalized(&root, name, self.case_insensitive()),
                FoundIn::LocalDirectory,
            ));
        }

        for (index, include_path) in self.config.include_paths.iter().enumerate() {
            if skip_through.is_some_and(|skip| index < skip) {
                continue;
            }
            // The directory is resolved against the working directory, because a relative `-I` is relative
            // to where the compiler ran and not to any file.
            let directory = self
                .config
                .resolve_against_working_directory(&include_path.directory);
            candidates.push((
                join_normalized(&directory, name, self.case_insensitive()),
                FoundIn::SearchPath(index),
            ));
        }

        for (candidate, found_in) in candidates {
            if let Some(path) = self.existing(&candidate) {
                return Resolution::Resolved(self.resolved(path, found_in, interner));
            }
            searched.push(candidate);
        }

        // **The guess, and only after every exact candidate has failed.**
        //
        // There is no `-I` that could have found the file — a Visual Studio solution cannot export a database, and a
        // checkout nobody has configured has none — so the last thing to try is the tail of what was written against
        // the files that are under the project root. It cannot shadow a real include directory, because reaching here
        // means every one of them was already tried and answered `None`.
        //
        // Refused outright for a bare file name (`vector`, `stdio.h`): a name spelled without a directory is spelled
        // that way *because* the search path is meant to find it, and matching it against whatever same-named file is
        // under the root is the confident wrong answer this fallback must not produce. See [`fuzzy`].
        if self.config.fuzzy_includes
            && let Some(root) = &self.config.root
            && let Some(index) = fuzzy::index_for(root)
        {
            let matches = index.matching(&include.target);
            if let Some(chosen) = matches.first() {
                // Recorded under `LocalDirectory` because that is what it is in effect: the answer came from where
                // the file is, not from a directory anything named. A consumer that shows `searched` shows every
                // exact place that failed, and the resolved path is the answer, so nothing is hidden by this.
                return Resolution::Resolved(self.resolved(
                    chosen.clone(),
                    FoundIn::LocalDirectory,
                    interner,
                ));
            }
        }

        Resolution::Unresolved(Unresolved {
            name: include.target.clone(),
            searched,
        })
    }

    /// The file at this path, as it should be stored, if it is there.
    ///
    /// Returns the *normalized* path so that the id's stored spelling is the same one comparison uses: a
    /// consumer displaying a file's name should not be shown `inc/../inc/a.h`.
    fn existing(&self, candidate: &Path) -> Option<PathBuf> {
        if self.files.exists(candidate) {
            return Some(candidate.to_path_buf());
        }

        // A case-insensitive filesystem was asked for a path with the wrong case. Probing every case
        // combination is not possible, so the practical fallback is to try the other common spelling of the
        // whole path — which is what happens when a project is checked out on Linux and analysed on
        // Windows, the case this exists for.
        if self.case_insensitive() {
            let lowered = normalize_path(candidate, true);
            let lowered = Path::new(&lowered);
            if self.files.exists(lowered) {
                return Some(lowered.to_path_buf());
            }
        }

        None
    }

    fn resolved(&self, path: PathBuf, found_in: FoundIn, interner: &mut PathInterner) -> Resolved {
        let file = interner.intern(&path);
        Resolved {
            file,
            path,
            found_in,
        }
    }

    fn case_insensitive(&self) -> bool {
        self.files.is_case_insensitive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{config::IncludePath, paths::MemoryFiles};

    /// A project tree: a local header, and two search directories holding the same name.
    fn project() -> MemoryFiles {
        MemoryFiles::new()
            .with_case_insensitive(false)
            .with_file("src/main.cpp", "")
            .with_file("src/local.h", "local")
            .with_file("user/vector", "user's vector")
            .with_file("system/vector", "system's vector")
            .with_file("system/stdio.h", "stdio")
    }

    fn config() -> CompilerConfig {
        CompilerConfig::new()
            .with_include_path("user")
            .with_system_include_path("system")
    }

    fn resolve(
        name: &str,
        form: IncludeForm,
        including: &str,
        case_insensitive: bool,
    ) -> Resolution {
        let files = project().with_case_insensitive(case_insensitive);
        let config = config();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(case_insensitive);

        let include = Include {
            form,
            target: name.into(),
            is_next: false,
        };

        // `including` is given as a path so the test reads like the file it is describing.
        let mut resolution = resolver.resolve(&include, Path::new(including), None, &mut interner);

        // The config is a local; the resolver borrows it, so the resolution is detached before returning.
        if let Resolution::Resolved(resolved) = &mut resolution {
            resolved.path = PathBuf::from(normalize_path(&resolved.path, case_insensitive));
        }

        resolution
    }

    /// **The fuzzy fallback, which reads the disk rather than the provider.**
    ///
    /// See [`crate::include::fuzzy`]: a match is a statement about what is *there*, so the root has to be a real
    /// directory. Each test gets its own, and the process-wide index cache is cleared first because a name reused
    /// across tests would otherwise be answered from another test's tree.
    mod fuzzy_fallback {
        use crate::include::fuzzy;
        use crate::{CompilerConfig, DiskFiles, IncludeResolver};

        use super::{Include, IncludeForm, PathInterner, Resolution};

        /// A root on disk with `files` in it, and a config that points at it.
        fn project(name: &str, files: &[&str]) -> (std::path::PathBuf, CompilerConfig) {
            let root = std::env::temp_dir().join("cppls-include-fuzzy").join(name);
            let _ = std::fs::remove_dir_all(&root);
            for file in files {
                let path = root.join(file);
                std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory");
                std::fs::write(&path, "// a header\n").expect("a file");
            }
            fuzzy::forget_everything();

            let config = CompilerConfig {
                root: Some(root.clone()),
                fuzzy_includes: true,
                ..CompilerConfig::new()
            };
            (root, config)
        }

        fn resolve(name: &str, config: &CompilerConfig) -> Option<std::path::PathBuf> {
            let resolver = IncludeResolver::new(&DiskFiles, config);
            let mut interner = PathInterner::new(false);
            let include = Include {
                form: IncludeForm::Quote,
                target: name.into(),
                is_next: false,
            };
            match resolver.resolve(
                &include,
                std::path::Path::new("/nowhere"),
                None,
                &mut interner,
            ) {
                Resolution::Resolved(resolved) => Some(resolved.path),
                Resolution::Unresolved(_) => None,
            }
        }

        #[test]
        fn a_header_nothing_could_place_is_found_by_its_tail() {
            // **The case this exists for.** No `-I` names `CodeFormatServer/include`, so
            // `#include "Session/StandardIOSession.h"` was searched for beside the including file and in the
            // compiler's own directories — and the closure of a real project's `main.cpp` was 14 files instead of
            // the whole program.
            let (root, config) = project(
                "tail",
                &["CodeFormatServer/include/Session/StandardIOSession.h"],
            );

            let found = resolve("Session/StandardIOSession.h", &config).expect("found by its tail");
            assert_eq!(
                found,
                root.join("CodeFormatServer/include/Session/StandardIOSession.h")
            );
        }

        #[test]
        fn an_exact_include_directory_is_never_shadowed() {
            // **The rule that makes the fallback safe.** A file that a search path *can* place must be placed by it:
            // reaching the fallback means every exact candidate was tried and answered `None`, so a guess can never
            // take a resolution away from a directory the project named.
            let (root, mut config) =
                project("shadow", &["named/Widget.h", "elsewhere/named/Widget.h"]);
            config
                .include_paths
                .push(crate::config::IncludePath::user(root.join("named")));

            let found = resolve("Widget.h", &config).expect("the search path found it");

            // **The same file, not the same spelling.** A resolution comes back in the resolver's own normalised
            // form — separators unified and, where the filesystem is case-insensitive, case folded — and comparing
            // that to `root.join(..)` compares how two spellings are written rather than which file they name. The
            // test that did so passed on nothing: it failed the moment the spelling changed for a reason that had
            // nothing to do with the rule under test.
            assert!(
                found.to_string_lossy().to_lowercase().replace('\\', "/")
                    == root
                        .join("named/Widget.h")
                        .to_string_lossy()
                        .to_lowercase()
                        .replace('\\', "/"),
                "the search path placed it: {found:?}"
            );

            // …and the same tree with the flag **off** resolves the tail-only spelling to nothing, which is what
            // every project without a database got before this existed.
            let strict = CompilerConfig {
                include_paths: config.include_paths.clone(),
                ..CompilerConfig::new()
            };
            assert_eq!(resolve("Session/Absent.h", &strict), None);
        }

        #[test]
        fn a_bare_name_is_left_to_the_search_path() {
            // `#include <vector>` spelled without a directory is spelled that way *because* the search path is meant
            // to find it, so a miss means the path is wrong rather than that the file is elsewhere. Matching it
            // against whatever same-named file is under the root is the confident wrong answer this refuses.
            let (_, config) = project("bare", &["a/vector", "b/vector", "c/stdio.h"]);

            assert_eq!(resolve("vector", &config), None);
            assert_eq!(resolve("stdio.h", &config), None);
        }

        #[test]
        fn the_flag_off_means_no_fallback_at_all() {
            // **The default, stated as a test.** A project that has stated how it is built must not have a guess
            // run underneath it, and a project that has said nothing gets the guess only when it asks for one.
            let (_root, config) = project("off", &["include/Session/IOSession.h"]);
            let strict = CompilerConfig {
                root: config.root.clone(),
                fuzzy_includes: false,
                ..CompilerConfig::new()
            };

            assert_eq!(resolve("Session/IOSession.h", &strict), None);
            assert!(resolve("Session/IOSession.h", &config).is_some());
        }
    }

    #[test]
    fn a_quoted_include_prefers_the_files_own_directory() {
        let resolution = resolve("local.h", IncludeForm::Quote, "src", false);

        assert_eq!(
            resolution.resolved().map(|it| it.path.as_path()),
            Some(Path::new("src/local.h"))
        );
        assert_eq!(
            resolution.resolved().map(|it| &it.found_in),
            Some(&FoundIn::LocalDirectory)
        );
    }

    #[test]
    fn a_quoted_include_falls_back_to_the_search_paths() {
        let resolution = resolve("stdio.h", IncludeForm::Quote, "src", false);

        assert_eq!(
            resolution.resolved().map(|it| it.path.as_path()),
            Some(Path::new("system/stdio.h"))
        );
        assert_eq!(
            resolution.resolved().map(|it| &it.found_in),
            Some(&FoundIn::SearchPath(1))
        );
    }

    /// **The one thing the two spellings disagree about.** An angled include must not find a file next to
    /// the including file: a system header picking up a project file of the same name is a bug the standard
    /// exists to prevent.
    #[test]
    fn an_angled_include_does_not_search_the_files_own_directory() {
        let resolution = resolve("local.h", IncludeForm::Angle, "src", false);

        assert!(
            !resolution.is_resolved(),
            "`src/local.h` exists but must not be found: {resolution:?}"
        );
        assert_eq!(
            resolution,
            Resolution::Unresolved(Unresolved {
                name: "local.h".into(),
                searched: vec![
                    PathBuf::from("user/local.h"),
                    PathBuf::from("system/local.h")
                ],
            })
        );
    }

    /// A project directory shadows a system one, which is why the order of the two lists matters.
    #[test]
    fn a_user_path_shadows_a_system_path() {
        let resolution = resolve("vector", IncludeForm::Angle, "src", false);

        assert_eq!(
            resolution.resolved().map(|it| it.path.as_path()),
            Some(Path::new("user/vector"))
        );
        assert_eq!(
            resolution.resolved().map(|it| &it.found_in),
            Some(&FoundIn::SearchPath(0))
        );
    }

    /// A failure reports where it looked, because "cannot find vector" is not actionable.
    #[test]
    fn an_unresolved_include_lists_what_was_searched() {
        let resolution = resolve("missing.h", IncludeForm::Quote, "src", false);

        match resolution {
            Resolution::Unresolved(unresolved) => {
                assert_eq!(&*unresolved.name, "missing.h");
                assert_eq!(
                    unresolved.searched,
                    vec![
                        PathBuf::from("src/missing.h"),
                        PathBuf::from("user/missing.h"),
                        PathBuf::from("system/missing.h"),
                    ]
                );
            }
            Resolution::Resolved(resolved) => panic!("expected a failure, got {resolved:?}"),
        }
    }

    /// A macro target cannot be resolved here — its value comes from expansion — and saying so is better
    /// than searching for a file named `BOOST_VERSION_HEADER`.
    #[test]
    fn a_macro_include_is_unresolved_and_searches_nothing() {
        let resolution = resolve("BOOST_HEADER", IncludeForm::Macro, "src", false);

        assert_eq!(
            resolution,
            Resolution::Unresolved(Unresolved {
                name: "BOOST_HEADER".into(),
                searched: Vec::new(),
            })
        );
    }

    /// `#include_next` continues after the directory the current file was found in, so a wrapper header
    /// forwards to the header it shadows instead of finding itself.
    #[test]
    fn include_next_continues_past_the_current_file() {
        // A wrapper in the user path that wants the system header of the same name.
        let files = MemoryFiles::new()
            .with_file("user/vector", "the wrapper")
            .with_file("system/vector", "the real one");
        let config = config();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let include = Include {
            form: IncludeForm::Angle,
            target: "vector".into(),
            is_next: true,
        };

        // Found in the user path, so the search resumes at the *next* path.
        let resolution = resolver.resolve(
            &include,
            Path::new("src"),
            Some(&FoundIn::SearchPath(0)),
            &mut interner,
        );

        assert_eq!(
            resolution
                .resolved()
                .map(|it| normalize_path(&it.path, false)),
            Some("system/vector".to_string())
        );
    }

    /// Without `#include_next`, the same file resolves to the wrapper — which is the difference the
    /// directive makes and the reason it exists.
    #[test]
    fn an_ordinary_include_finds_the_wrapper() {
        let files = MemoryFiles::new()
            .with_file("user/vector", "the wrapper")
            .with_file("system/vector", "the real one");
        let config = config();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let include = Include {
            form: IncludeForm::Angle,
            target: "vector".into(),
            is_next: false,
        };

        let resolution = resolver.resolve(
            &include,
            Path::new("src"),
            Some(&FoundIn::SearchPath(0)),
            &mut interner,
        );

        assert_eq!(
            resolution
                .resolved()
                .map(|it| normalize_path(&it.path, false)),
            Some("user/vector".to_string())
        );
    }

    /// Two includes of one file produce one id, so the graph has one node for it however it was reached.
    #[test]
    fn two_routes_to_one_file_produce_one_id() {
        let files = project();
        let config = config();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let quoted = Include {
            form: IncludeForm::Quote,
            target: "stdio.h".into(),
            is_next: false,
        };
        let angled = Include {
            form: IncludeForm::Angle,
            target: "stdio.h".into(),
            is_next: false,
        };

        let first = resolver.resolve(&quoted, Path::new("src"), None, &mut interner);
        let second = resolver.resolve(&angled, Path::new("src"), None, &mut interner);

        assert_eq!(
            first.resolved().map(|it| it.file),
            second.resolved().map(|it| it.file)
        );
        assert_eq!(interner.len(), 1);
    }

    /// A relative `-I` is relative to where the compiler ran, not to any file.
    #[test]
    fn a_relative_search_path_resolves_against_the_working_directory() {
        let files = MemoryFiles::new().with_file("build/inc/a.h", "found");
        let config = CompilerConfig::new()
            .with_include_path("inc")
            .with_working_directory("build");
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let include = Include {
            form: IncludeForm::Angle,
            target: "a.h".into(),
            is_next: false,
        };

        let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);

        assert_eq!(
            resolution
                .resolved()
                .map(|it| normalize_path(&it.path, false)),
            Some("build/inc/a.h".to_string())
        );
    }

    /// An absolute target is used as written rather than searched for.
    ///
    /// Asserted through the *searched* list, because "absolute" and the spelling of a root are
    /// platform-specific — `/opt/inc/a.h` is not a rooted path on Windows — so a test that finds a file by
    /// absolute path is a test of the platform. What distinguishes the two cases is the list: an absolute
    /// target is tried exactly as written, so a failure names one path, while a relative one is tried
    /// against every search directory in turn.
    #[test]
    fn an_absolute_target_is_tried_only_as_written() {
        let files = project();
        let config = config();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        // Built from the real root so the test is about absoluteness and not about separators.
        let absolute = std::env::temp_dir().join("definitely-not-here-a1b2c3.h");
        let name: Box<str> = absolute.to_string_lossy().into_owned().into();
        let include = Include {
            form: IncludeForm::Angle,
            target: name.clone(),
            is_next: false,
        };

        let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);

        assert_eq!(
            resolution,
            Resolution::Unresolved(Unresolved {
                name,
                searched: vec![absolute],
            }),
            "the target was tried as written and nothing else was"
        );
    }

    /// A relative target *is* searched for, which is the other half of the property above.
    #[test]
    fn a_relative_target_is_searched_for() {
        let resolution = resolve("nope.h", IncludeForm::Angle, "src", false);

        match resolution {
            Resolution::Unresolved(unresolved) => assert_eq!(
                unresolved.searched,
                vec![PathBuf::from("user/nope.h"), PathBuf::from("system/nope.h")],
                "every search directory was tried"
            ),
            Resolution::Resolved(resolved) => panic!("expected a failure, got {resolved:?}"),
        }
    }

    /// A configuration with no search paths still resolves a quoted include next to the file, which is
    /// what makes a project without a compile database partly usable rather than useless.
    #[test]
    fn an_empty_configuration_still_finds_neighbours() {
        let files = MemoryFiles::new().with_file("src/a.h", "found");
        let config = CompilerConfig::new();
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let include = Include {
            form: IncludeForm::Quote,
            target: "a.h".into(),
            is_next: false,
        };

        let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
        assert!(resolution.is_resolved(), "{resolution:?}");
    }

    #[test]
    fn an_include_path_with_a_trailing_separator_still_matches() {
        let files = MemoryFiles::new().with_file("user/a.h", "found");
        let config = CompilerConfig {
            include_paths: vec![IncludePath::user("user/")],
            ..CompilerConfig::default()
        };
        let resolver = IncludeResolver::new(&files, &config);
        let mut interner = PathInterner::new(false);

        let include = Include {
            form: IncludeForm::Angle,
            target: "a.h".into(),
            is_next: false,
        };

        let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
        assert!(resolution.is_resolved(), "{resolution:?}");
    }
}

// Where files come from, and who includes whom: compiler settings (`config`), the resolver (this module), the graph
// those resolutions form (`graph`), and the one place that asks the toolchain where its own headers are
// (`toolchain`) — which is what makes `#include <vector>` resolve at all, and therefore what makes a project's own
// files cacheable. `msvc` and `system_headers` are the two halves of the answer on a machine where no compiler can
// be asked: Microsoft's layout (measured), and the conventional directories of an operating
// system.
//
// **`paths` is not here any more**: reading a file is the *file* layer's business (`crate::file::paths`), and this
// module keeps a re-export so that every path written before the move still resolves. The distinction is the one
// that matters for a language server: an include search *asks* for a file, and the file layer is what *holds* one.
pub mod config;
pub mod fuzzy;
pub mod graph;
pub mod msvc;
pub mod system_headers;
pub mod toolchain;

pub use crate::file::paths;