cpp_code_analysis 0.3.0

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
//! The macros a **query** evaluates a file's conditions against.
//!
//! A summary stores each conditional region as the question it asks ([`crate::SummaryGuards`]), and the answer
//! depends on the compilation: `-D`s, the `-std=` that fixes `__cplusplus`, and the five hundred names a compiler
//! predefines. None of that is in a summary, and none of it can be: a summary's key is computed from the text and
//! the paths alone, which is what lets the cache be consulted before anything is parsed. So the environment
//! arrives at the query, is applied to the stored question, and the answer is thrown away with the query.
//!
//! # What this is complete about, and what it is not
//!
//! Three sources of definitions are known here, and they are the three a query can defend:
//!
//! ```text
//! the compiler's predefined names   asked once, with `-dM` (see `Toolchain::macros`)
//! the command line's `-D`/`-U`      read from the compile database's entry
//! this file's own `#define`s        the summary's macro facts, above the point being asked about
//! ```
//!
//! Everything a *header* defines is missing, and that absence is the whole design: a name none of the three
//! mentions is [`Lookup::Unanswered`], which the evaluator turns into `Unknown` rather than into the standard's
//! `0`. The alternative — reading "no file I indexed defines it" as "it is not defined" — is how
//! `#ifdef NT_INCLUDED` comes out false in a header that a real translation unit includes, and a wrong answer
//! there is worse than a missing one: it hides declarations that exist.
//!
//! The next step is recorded: the macros a *closure* defines, threaded in translation order
//! by the same walk that finds the files. That is the half which would decide the conditions naming a header's own
//! feature macros (`_GLIBCXX_USE_CXX11_ABI` and the like), and it needs the complete-input question answered
//! first — an unresolved `#include` or an unindexed header is a hole in exactly the reasoning that would make
//! "not defined" sound.

use std::path::Path;

use crate::ProjectIndex;
use crate::condition::{Lookup, MacroValues};
use crate::guard::Visibility;
use crate::include::config::CompilerConfig;
use crate::include::graph::Marked;
use crate::summary::{FactGuard, FileSummary, MacroFact, MacroKind};

/// The macros in force at one point in one file, as far as a query can know.
///
/// Cheap to build — two references and an offset — because one is built per condition: the question "what does
/// this `#if` mean" is asked where the condition was written, which is a different offset for every region.
pub struct MacrosHere<'a> {
    /// What the compilation starts with, plus — for the walk's own caller — every fact the walk has passed.
    /// Deliberately an **incomplete** [`Marked`], so that a name it does not mention is unanswered rather than
    /// undefined.
    ///
    /// Borrowed when a walk already has one, owned when it was built for this one condition
    /// ([`MacrosHere::from_summary`] asks [`ProjectIndex::macros_at`], which walks): a condition has at most a few
    /// names to look up, and borrowing the walk's state is the difference between one traversal and one per
    /// condition.
    seed: std::borrow::Cow<'a, Marked>,
    /// The file the condition is written in, for what it does to a name above that point — `None` when the state
    /// is already up to date, which is what the walk passes: it has applied the file's own facts, with their
    /// values, and looking them up again here would answer with less than the state knows.
    file: Option<&'a FileSummary>,
    /// The offset the file's own facts are read up to: the condition's own position.
    offset: usize,
}

impl<'a> MacrosHere<'a> {
    /// The macros at a condition a **walk** has reached, whose state already includes the facts above it.
    pub fn from_walk(state: &'a Marked, offset: usize) -> Self {
        MacrosHere {
            seed: std::borrow::Cow::Borrowed(state),
            file: None,
            offset,
        }
    }

    /// The macros at a condition in `file`, given only an environment: the file's own facts above the point are
    /// read from the summary.
    ///
    /// The state a query uses comes from a walk; this is for a caller that has an offset and an index and no walk
    /// — [`visibility_at`], which is how a probe or a test asks the same question.
    pub fn from_summary(state: Marked, file: &'a FileSummary, offset: usize) -> Self {
        MacrosHere {
            seed: std::borrow::Cow::Owned(state),
            file: Some(file),
            offset,
        }
    }
}

impl MacroValues for MacrosHere<'_> {
    fn lookup(&self, name: &str) -> Lookup<'_> {
        // The file's own last word above the point wins, because that is the order a preprocessor reads in: a
        // `#define` here shadows the command line, and `#undef __cplusplus` — which real test suites write —
        // really does remove a compiler's built-in.
        if let Some(fact) = self.last_word_about(name) {
            return match fact.kind {
                MacroKind::Definition => {
                    // **A body that is one integer literal, or one other macro's name, is a value a condition can
                    // read** — and the second is not an optimisation, it is the shape half of MSVC's headers are
                    // built out of. `vcruntime.h` writes
                    //
                    // ```cpp
                    // #if defined(_MSVC_LANG) && _MSVC_LANG > __cplusplus
                    // #define _STL_LANG _MSVC_LANG
                    // #else
                    // #define _STL_LANG __cplusplus
                    // #endif
                    // #if _STL_LANG > 201402L
                    // #define _HAS_CXX17 1
                    // ```
                    //
                    // and answering `DefinedWithoutAValue` for `_STL_LANG` makes `#if _STL_LANG > 201402L`
                    // **undecidable**, so `_HAS_CXX17` is never defined, so every `#if _HAS_CXX17` below it —
                    // including the one around `<atomic>` in `<memory>` — is undecidable too.
                    //
                    // Following one alias is what the expander would do with the body, and it is done here rather
                    // than by handing over a `MacroDef` because a summary stores a fact's body as a `MacroBody`
                    // whose tokens live in the *file* it was written in, not in the summary. The chain is bounded by
                    // [`ALIAS_DEPTH`] so that `#define A B` / `#define B A` answers `DefinedWithoutAValue` instead
                    // of recursing forever, which is the same answer the expander's own depth cap gives.
                    match self.alias_of(fact, ALIAS_DEPTH) {
                        Some(alias) => self.lookup(alias),
                        None => Lookup::DefinedWithoutAValue,
                    }
                }
                MacroKind::Undefinition => Lookup::Undefined,
            };
        }

        // What the compiler and the command line define, and `Unanswered` for anything they do not mention: the
        // headers that could define it have not been walked *for this question*, and pretending otherwise is the
        // one move this layer must not make.
        self.seed.as_ref().lookup(name)
    }
}

const ALIAS_DEPTH: usize = 8;

impl<'a> MacrosHere<'a> {
    /// **The one name a fact's body *is*, when the body is exactly one identifier.**
    ///
    /// `#define _STL_LANG __cplusplus` is an alias: a condition that reads `_STL_LANG` gets whatever
    /// `__cplusplus` is, and a summary cannot say that by holding a body — its `MacroBody`'s tokens point into
    /// the file the `#define` was written in, not into the summary. So the alias is followed by name instead,
    /// which is the same chain the expander walks (`condition::macro_value` → `expand_with_budget`) for a body it
    /// *can* see.
    ///
    /// `depth` counts the aliases already followed, so `#define A B` beside `#define B A` stops rather than
    /// recursing: the answer is then `DefinedWithoutAValue`, the same `Unknown` the expander's own depth cap
    /// produces.
    ///
    /// A body of anything else — two tokens, a literal, a call — is `None`, because reading *that* is the
    /// expander's job and guessing at it here would be a second evaluator.
    fn alias_of(&self, fact: &'a MacroFact, depth: usize) -> Option<&'a str> {
        if depth == 0 {
            return None;
        }

        fact.alias.as_deref()
    }

    /// The file's own last fact about `name` at or above `offset`.
    ///
    /// Only facts **outside every conditional** count. A `#define FOO` written inside an `#if` may not be there
    /// at all, and treating it as in force would decide the very condition that is being asked about — with
    /// evidence that depends on the answer.
    ///
    /// A summary holds tens to hundreds of macro facts, and a condition mentions a handful of names, so this is a
    /// scan rather than an index. The alternative — a name-keyed map built for every condition — allocates once
    /// per region per query to save a walk over a list that fits in a cache line.
    fn last_word_about(&self, name: &str) -> Option<&'a MacroFact> {
        self.file?
            .macros
            .iter()
            .filter(|fact| {
                &*fact.name == name
                    && fact.guard == FactGuard::Unconditional
                    && fact.range.start_offset <= self.offset
            })
            .max_by_key(|fact| fact.range.start_offset)
    }
}

/// The macros a compilation starts with: what the compiler predefines, then what the command line says.
///
/// The order is the compiler's own: a `-D` of a name the compiler also predefines is the one the translation unit
/// sees, so the built-ins go in first and the command line last. A `-U` — which is how a project removes a
/// compiler's built-in — is applied after both.
///
/// # `configured`: whether this environment is the whole of what the compilation defines
///
/// The flag is the difference between `Unknown` and "not defined" for every condition naming something no file
/// defines, and it is passed in rather than assumed because it is a statement about the caller's **inputs**:
/// [`crate::Session::open`] sets it when the compiler it discovered **answered with its predefined macros** — the
/// table `-dM`/`/PD` prints, and the only place `_MSC_VER`, `__cplusplus` and five hundred more exist. A toolchain
/// that could not be asked (or the last-resort one built from conventional header directories, whose
/// `builtin_macros` is empty) leaves the environment [`Marked::incomplete`] and every such condition `Unknown`.
///
/// The project's own build description — `.cppls.toml` and `compile_commands.json`, and the cache — is a source of
/// *flags* (`-D`s, `-std=`, include paths) rather than the licence for the claim: a project that wrote none down
/// has none to miss, and a project built with flags nobody can read (a `Makefile`) is a hole this flag cannot see
/// and the walk usually catches, because such a file names `-I` directories too and an `#include` that does not
/// resolve takes the claim back.
///
/// What the flag is *not* is a promise about the files: a walk that runs into an `#include` that did not resolve, or
/// one nobody indexed, takes the claim back with [`Marked::mark_incomplete`] — see
/// [`crate::index::environment`], which is where the two meet.
///
/// # Why it is one function and not three
///
/// A caller that discovers a toolchain has to make the same three decisions in the same order — the compiler's
/// predefined names, what the configuration decides (`-std=`, the target), the project's own `-D`/`-U` — and the
/// **completeness claim** that goes with them. Three copies would be three worlds: a probe that built its own would
/// be measuring an environment the server never runs with, which is exactly how the difference between "the body of
/// `_STD_BEGIN` is in force" and "nobody can say" went unnoticed. That difference is measured, and it is not small:
/// `_STD_BEGIN`'s `#define` sits under `#if _STL_COMPILER_PREPROCESSOR` in `yvals_core.h`, so with an incomplete
/// seed the whole of MSVC's STL reads as "no replacement lists at all" and not one namespace scope can be opened
/// from a body.
pub fn compilation_environment(
    config: &CompilerConfig,
    toolchain: Option<&crate::include::toolchain::Toolchain>,
    configured: bool,
) -> Marked {
    let mut marked = Marked::default();

    // **What the configuration itself decides** — the standard it was compiled with, the target it was compiled
    // for — applied **under** the compiler's own table, which is the correction of an order that used to be the
    // other way round. The old argument was that a toolchain's `-dM` output answers for the compiler's *default*
    // invocation while `-std=c++11` in the database is what the project asked for, so the configuration's number
    // had to win. That argument is gone: the standard is passed to the compiler now
    // (`toolchain::discover_with`), including the standard the *analysis* assumes when nothing states one, so the
    // table is the compiler's own answer **for that same standard** — and a table cannot know it. Concretely:
    // `-std=c++23` makes this `g++` print `__cplusplus = 202100L` while the derived table says `202302L`, and
    // `c++latest` has no number at all; a condition like `#if __cplusplus >= 202302L` would then answer a
    // confident **true** where the compiler answers false, which is the one failure this layer does not accept.
    //
    // The derived table keeps its job as the **fallback**: a toolchain that could not be asked has no macros, and
    // then the configuration's standard is all anybody knows about `__cplusplus`.
    for definition in crate::predefined_macros_of(config) {
        marked.define_on_the_command_line(&definition.name, definition.value.as_deref());
    }

    if let Some(toolchain) = toolchain {
        for (name, value) in toolchain.macros() {
            marked.define_on_the_command_line(name, value);
        }
    }

    for definition in &config.defines {
        marked.define_on_the_command_line(&definition.name, definition.value.as_deref());
    }

    for name in &config.undefines {
        marked.undefine(name);
    }

    if configured {
        marked
    } else {
        marked.incomplete()
    }
}

/// Was the code the guard names compiled, as far as this index can tell?
///
/// [`Visibility::Active`] — every enclosing condition is decided, and taken (or there is no condition at all,
/// which is decided without evaluating anything). [`Visibility::Inactive`] — one of them is decided and *not*
/// taken, so a compiler would not have read this code at all. [`Visibility::Unknown`] — at least one condition
/// cannot be decided from what this index knows, which is the honest answer for most `#if`s in most projects
/// today.
///
/// Takes the guard rather than a bare offset because every caller has one: a fact records the region it was
/// written in, and the region is where the walk outwards starts. See [`crate::SummaryGuards::visibility_of`].
///
/// # Why this builds a state per condition
///
/// Is this fact **in force** — is the branch of the `#if` that wrote it the branch that was taken?
///
/// The question the evidence layer asks before it hands a conditional `#define` to the parser: the fact knows which
/// region it was written in, [`SummaryGuards`](crate::SummaryGuards) stores that region's **question**, and this is
/// where the question meets the macros the compilation starts with (`-D`s, `-std=`, the compiler's own names — a
/// [`Marked`]).
///
/// [`MacrosHere::from_walk`] rather than [`MacrosHere::from_summary`]: the seed already holds the compilation's
/// macros, and borrowing it costs nothing where owning it would copy the whole table once per condition. What is
/// given up is the defining file's **own** earlier `#define`s — a name one of those defines reads as unanswered,
/// which is `Unknown`, and `Unknown` keeps the fact out. That is the safe direction: this can lose evidence, never
/// invent it.
pub fn fact_in_force(seed: &Marked, file: &FileSummary, fact: &MacroFact) -> bool {
    a_guard_is_in_force(file, fact, |condition_at| {
        MacrosHere::from_walk(seed, condition_at)
    })
}

/// The same question, asked of **any** table of macros — which is what a walk that feeds its own state needs.
///
/// `macros_at` answers for one condition's own offset, because a region's condition is decided where it is
/// written: `#ifndef NAME` whose body then writes `#define NAME` is the shape that makes the difference. A table
/// that answers [`Lookup::Unanswered`](crate::Lookup) for a name makes the whole guard `Unknown`, and `Unknown`
/// keeps the fact out — this can lose evidence, never invent it.
pub fn a_guard_is_in_force<M: crate::MacroValues>(
    file: &FileSummary,
    fact: &MacroFact,
    macros_at: impl Fn(usize) -> M,
) -> bool {
    a_guard_holds(file, fact.guard, fact.range.start_offset, macros_at)
}

/// **A `MacroValues` over what the compilation already knows**, for a question asked *before* a file's own table
/// exists — which is the position `preprocess` is in.
///
/// Only definedness is answered, and only from [`cpp_parser::MacroFacts::kind_of`], which is the positional answer
/// the parser and the scope walk already read: `Some` is "this name is a macro there" and `None` is "it is not",
/// including when an `#undef` took it away. A body would be needed to evaluate an *expression* (`#if __cplusplus >=
/// 201703L`), and it is deliberately not synthesised here: that question is answered where the file has been read.
pub struct KnownMacros<'a> {
    facts: &'a dyn cpp_parser::MacroFacts,
    offset: usize,
}

impl<'a> KnownMacros<'a> {
    pub fn new(facts: &'a dyn cpp_parser::MacroFacts, offset: usize) -> Self {
        KnownMacros { facts, offset }
    }
}

impl crate::condition::MacroValues for KnownMacros<'_> {
    fn lookup(&self, name: &str) -> crate::condition::Lookup<'_> {
        match self.facts.kind_of(name, self.offset) {
            Some(_) => crate::condition::Lookup::DefinedWithoutAValue,
            None => crate::condition::Lookup::Undefined,
        }
    }
}

/// **Is this branch the one that gets compiled?** Asked of the compilation's own knowledge, before a file is read.
///
/// `None` when nobody can say — no environment, or a condition whose expression needs a body — which leaves the
/// branch exactly as the walk treated it before this existed. The direction is deliberate: a branch wrongly called
/// *dead* loses a `#define` that is really there, while one wrongly called *live* keeps a definition that shadows a
/// better one. Only an answer the environment is **sure** of is turned into a decision.
///
/// Written for `vcruntime.h`:
///
/// ```cpp
/// #ifdef __cplusplus
///     #define _STL_LANG _MSVC_LANG
/// #else
///     #define _STL_LANG 0L          // <- recorded as the definition, because it is the last one
/// #endif
/// ```
///
/// `__cplusplus` is the compiler's own name and is in the environment, so this answers `true` for the first branch
/// and `false` for the `#else` — which is what stops `0L` from shadowing the real value.
pub fn a_branch_is_taken(
    is_a_macro: &mut dyn FnMut(&str, usize) -> bool,
    kind: crate::DirectiveKind,
    branch: &crate::preprocess::guard::Branch,
    offset: usize,
) -> Option<bool> {
    match kind {
        // **The two forms that only ask whether a name is a macro**, and therefore the two this can decide.
        crate::DirectiveKind::Ifdef => {
            let name = branch.name.as_deref()?;
            Some(is_a_macro(name, offset))
        }
        crate::DirectiveKind::Ifndef => {
            let name = branch.name.as_deref()?;
            Some(!is_a_macro(name, offset))
        }
        // Everything else is left as it was: an expression needs bodies (`#if X > 2`, `defined X`), and an
        // `#elif`'s verdict depends on the branches before it rather than on itself.
        _ => None,
    }
}

///
/// Written because a `#include` is a guarded fact too, and the walk used to descend into one **without asking**.
/// That is not a small omission on a compiler's own headers: every conditional include in them was entered, so
/// `sal.h`'s `#if _USE_ATTRIBUTES_FOR_SAL` — which our own cooker decides is **0** — still pulled
/// `CodeAnalysis/sourceannotations.h` (1020 tokens) into the program. cl.exe does not read that file.
///
/// `guard` and `offset` rather than a fact because the two kinds of fact carry them in the same shape and nothing
/// else is needed: a guard is a region, and the offset is where the fact stands in its file.
pub fn a_guard_holds<M: crate::MacroValues>(
    file: &FileSummary,
    guard: FactGuard,
    offset: usize,
    macros_at: impl Fn(usize) -> M,
) -> bool {
    // **This was the one function worth counting, and the count is why it is now fast.** A counter
    // here reported nine million calls and 271 s of a 465 s index of a real project — 84% of the
    // walk — which is what sent the search into `visibility_of` and then into the two debug-trace
    // gates that turned out to be the cost. Removing those took this function to 124 s. The counter
    // is gone because it reported a *total*, and a total is not what needs watching any more; the
    // stage timer around the walk still shows whether this path regresses.
    a_guard_holds_measured(file, guard, offset, macros_at)
}

/// **The three-way answer** — `Active`, `Inactive`, or `Unknown` — which [`a_guard_holds`] collapses to a bool.
///
/// The walk needs the third case: a `#define` in a region nobody can decide is **not** a branch to drop. A compiler
/// takes one branch or the other, so the name is defined afterwards either way; dropping both branches`'` definitions —
/// which is what collapsing `Unknown` to `false` does — leaves a name undefined that the compiler has in force. Measured
/// on `import std;`: `<xstddef>` defines `_MEMBER_CALL_CV_REF_NOEXCEPT` in **both** branches of
/// `#ifdef __cpp_noexcept_function_type` and no file `#undef`s it, yet the walk never fed it, and `<xtr1common>` usages
/// were left as text in the rendering.
pub fn a_guard_visibility<M: crate::MacroValues>(
    file: &FileSummary,
    fact: &MacroFact,
    macros_at: impl Fn(usize) -> M,
) -> crate::preprocess::guard::Visibility {
    if matches!(fact.guard, FactGuard::Unconditional) {
        return crate::preprocess::guard::Visibility::Active;
    }
    file.guards
        .visibility_of(fact.guard, fact.range.start_offset, &macros_at)
}

/// [`a_guard_holds`] without a counter — see the note there.
fn a_guard_holds_measured<M: crate::MacroValues>(
    file: &FileSummary,
    guard: FactGuard,
    offset: usize,
    macros_at: impl Fn(usize) -> M,
) -> bool {
    if matches!(guard, FactGuard::Unconditional) {
        return true;
    }

    let visibility = file.guards.visibility_of(guard, offset, &macros_at);

    visibility == Visibility::Active
}

/// Each condition is evaluated against the macros **at its own offset**, which is a walk
/// ([`ProjectIndex::macros_at`]) rather than the environment the index was seeded with. Two reasons, and both are
/// the difference between an answer and a wrong one:
///
/// * a `#define` written above the condition is in force and one written below is not — for every condition in the
///   file, including the ones about a *name the same file defines*;
/// * a condition must be read **before** its own body, or `#ifndef NAME / #define NAME` decides itself backwards.
///
/// A caller already walking the graph — [`ProjectIndex::macro_environment`] — has the state in hand and uses
/// [`crate::index::environment::MacrosHere::from_walk`] instead: one traversal, not one per condition.
pub fn visibility_at(
    index: &ProjectIndex,
    path: &Path,
    guard: FactGuard,
    offset: usize,
) -> Visibility {
    if guard == FactGuard::Unconditional {
        return Visibility::Active;
    }

    let Some(summary) = index.summary(path) else {
        return Visibility::Unknown;
    };

    summary.guards.visibility_of(guard, offset, |condition_at| {
        MacrosHere::from_summary(index.macros_at(path, condition_at), summary, condition_at)
    })
}

#[cfg(test)]
mod tests {
    use super::visibility_at;
    use crate::cache::SummaryKey;
    use crate::guard::Visibility;
    use crate::index::ProjectIndex;
    use crate::summary::{FactGuard, SummaryGuards};
    use std::path::Path;

    /// An index over one file, with whatever environment the test names.
    ///
    /// **Incomplete**, which is what a fixture with no project around it is: nothing has said that these are all
    /// the compilation's definitions, so a name the environment does not mention may still be defined by a header
    /// — and `#ifdef` on it is `Unknown` rather than false. A real session without a compile database is in the
    /// same position (see `compilation_environment` in `session.rs`), and
    /// [`a_name_nothing_defines_is_not_defined_when_the_inputs_are_complete`] is the other side of it.
    fn index_of(source: &str, defines: &[&str]) -> ProjectIndex {
        index_of_with(source, defines, false)
    }

    /// The same, told whether the environment is the whole of what the compilation defines.
    fn index_of_with(source: &str, defines: &[&str], complete: bool) -> ProjectIndex {
        let path = Path::new("/p/widget.h");
        let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));

        let mut macros = crate::Marked::default();
        for name in defines {
            macros.define_on_the_command_line(name, None);
        }

        let mut index = ProjectIndex::new().with_macros(if complete {
            macros
        } else {
            macros.incomplete()
        });
        index.insert(summary);
        index
    }

    /// The guard of the fact naming `needle`, and where it is.
    fn guard_of(source: &str, defines: &[&str], needle: &str) -> (ProjectIndex, FactGuard, usize) {
        let index = index_of(source, defines);
        let (guard, offset) = guard_in(&index, source, needle);

        (index, guard, offset)
    }

    /// The same, for an index a test built itself — so that it can choose the completeness on its own.
    fn guard_in(index: &ProjectIndex, source: &str, needle: &str) -> (FactGuard, usize) {
        let offset = source.find(needle).expect("the needle is in the fixture");
        let guard = index
            .summary(Path::new("/p/widget.h"))
            .expect("the file is indexed")
            .macros
            .iter()
            .find(|fact| fact.range.start_offset == offset)
            .map(|fact| fact.guard)
            .expect("a fact starts at the needle");

        (guard, offset)
    }

    /// [`guard_of`] with an environment the caller declares **complete**.
    fn guard_of_in_complete(
        source: &str,
        defines: &[&str],
        needle: &str,
    ) -> (ProjectIndex, FactGuard, usize) {
        let index = index_of_with(source, defines, true);
        let (guard, offset) = guard_in(&index, source, needle);

        (index, guard, offset)
    }

    #[test]
    fn a_conditional_define_is_in_force_only_when_its_branch_was_taken() {
        // The question the evidence layer asks before it lets a conditional `#define` be read at all. Three
        // answers, and the third is the one nothing may be guessed at: an unanswered condition keeps the fact out,
        // because this layer can lose evidence but must not invent it.
        let source = "#if FOO\n#define X 1\n#endif\n#if BAR\n#define Y 2\n#endif\n";
        let path = Path::new("/p/widget.h");
        let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));

        let fact = |name: &str| {
            summary
                .macros
                .iter()
                .find(|fact| &*fact.name == name)
                .expect("the fixture defines it")
        };

        let mut seed = crate::Marked::default();
        seed.define_on_the_command_line("FOO", Some("1"));

        assert!(
            super::fact_in_force(&seed, &summary, fact("X")),
            "`FOO` is defined, so that branch was taken"
        );
        assert!(
            !super::fact_in_force(&seed, &summary, fact("Y")),
            "nothing defines `BAR`, so that branch was not taken"
        );

        // Outside every `#if` there is nothing to ask — and the fast path is what keeps a closure's tens of
        // thousands of unconditional facts from costing an evaluation each.
        let source = "#define Z 3\n";
        let summary = crate::index::summarize(path, source, SummaryKey::new(0, 0));
        assert!(
            super::fact_in_force(&crate::Marked::default(), &summary, &summary.macros[0]),
            "a `#define` outside every conditional is a fact about the file"
        );
    }

    #[test]
    fn a_name_nothing_defines_is_not_defined_when_the_inputs_are_complete() {
        // The other side of the coin, and the claim [`crate::Session::open`] makes when it read the project's own
        // compile database: these are the compilation's definitions, every `#include` that mattered resolved, and
        // nothing indexed defines `NT_INCLUDED` — so the guard *is* taken.
        //
        // This is the decision the whole macro line was blocked on: `windef.h`
        // has `#ifndef NT_INCLUDED / #include <winnt.h> / #endif`, `NT_INCLUDED` is defined nowhere in the MinGW
        // headers, and every one of `STDMETHODCALLTYPE`'s four thousand references was "maybe" because of it.
        let source = "int early;\n#ifndef NT_INCLUDED\n#include \"winnt.h\"\n#endif\n";
        let path = Path::new("/p/widget.h");
        let (guard, offset) = include_guard(&index_of_with(source, &[], true));

        assert_eq!(
            visibility_at(&index_of_with(source, &[], true), path, guard, offset),
            Visibility::Active,
            "nothing defines it, and the caller said nothing else can: the include is certain"
        );

        // …and the same file with an incomplete environment is `Unknown`, which is the answer that costs an answer
        // rather than giving a wrong one.
        assert_eq!(
            visibility_at(&index_of(source, &[]), path, guard, offset),
            Visibility::Unknown
        );
    }

    /// The include's own guard and offset — the position a condition about an *include* is asked at.
    fn include_guard(index: &ProjectIndex) -> (FactGuard, usize) {
        let summary = index
            .summary(Path::new("/p/widget.h"))
            .expect("the file is indexed");
        let include = summary
            .includes
            .first()
            .expect("the fixture includes a file");

        (include.guard, include.range.start_offset)
    }

    #[test]
    fn the_files_own_guard_is_transparent_to_everything_inside_it() {
        // A header is `#ifndef GUARD / #define GUARD` and then a file full of conditions. The guard is not one of
        // them: entering the file at all is what it means, so a fact nested inside it must be decided by the
        // conditions *it* is written in — not by a guard that has, by that point, defined its own name and would
        // read as "not taken" if it were evaluated like any other `#ifndef`.
        //
        // This is the shape that made `_GLIBCXX_USE_CXX11_ABI` come out `0` in the standard library (round 15):
        // `bits/c++config.h` is guarded, and its `#define _GLIBCXX_USE_CXX11_ABI 1` sits inside `#if __cplusplus`
        // inside that guard.
        let source = "#ifndef WIDGET_H\n#define WIDGET_H\n#if __cplusplus\n#define INNER 1\n#endif\n#endif\n";
        let path = Path::new("/p/widget.h");
        let (index, guard, offset) = guard_of_in_complete(source, &["__cplusplus"], "INNER");

        assert_eq!(
            visibility_at(&index, path, guard, offset),
            Visibility::Active,
            "the condition is `#if __cplusplus`, and the guard around it is not a condition at all"
        );

        // And the guard is still *recorded*: it is the region the file's own guard opens, which is what makes the
        // rule above applicable rather than a blanket "the outermost region does not count".
        let summary = index.summary(path).expect("the file is indexed");
        assert_eq!(summary.guards.own_guard, Some(0));
        assert!(
            summary.guards.conditions_of(0).is_empty(),
            "and asking about the guard itself gets no condition back"
        );
    }

    #[test]
    fn code_outside_every_conditional_is_active_without_being_evaluated() {
        // The fast path, which is also the common case: an unconditional include is one no query has to think
        // about, and an index that has been told nothing must still answer this — the region search would find no
        // condition to evaluate, and "no condition" is not "cannot tell".
        let index = index_of("#define NAME 1\n", &[]);
        let path = Path::new("/p/widget.h");

        assert_eq!(
            visibility_at(&index, path, FactGuard::Unconditional, 0),
            Visibility::Active
        );
        assert!(
            index.macros().is_empty(),
            "and it did not need an environment to say so"
        );
    }

    #[test]
    fn a_condition_the_environment_decides_is_decided() {
        // The three answers, from the same file and the same condition, with three environments. `X` is a fact
        // about the compilation, so the *file* is the same in all three.
        let source = "#ifdef X\n#define INNER 1\n#endif\n";
        let path = Path::new("/p/widget.h");

        let (index, guard, offset) = guard_of(source, &["X"], "INNER");
        assert_eq!(
            visibility_at(&index, path, guard, offset),
            Visibility::Active
        );

        let (index, guard, offset) = guard_of(source, &[], "INNER");
        assert_eq!(
            visibility_at(&index, path, guard, offset),
            Visibility::Unknown,
            "a name nothing the index read mentions is not 'not defined'"
        );

        // The same question with the *other* environment answer, which is the caller's to give: an environment
        // that is the whole of what the compilation defines makes the guard not taken instead of unknown.
        let (index, guard, offset) = guard_of_in_complete(source, &[], "INNER");
        assert_eq!(
            visibility_at(&index, path, guard, offset),
            Visibility::Inactive,
            "nothing defines `X`, and the caller said nothing else can"
        );

        // And the decided *no*: `#if 0` asks nothing, so nothing can be missing.
        let source = "#if 0\n#define INNER 1\n#endif\n";
        let (index, guard, offset) = guard_of(source, &[], "INNER");
        assert_eq!(
            visibility_at(&index, path, guard, offset),
            Visibility::Inactive
        );
    }

    #[test]
    fn a_region_the_summary_does_not_describe_is_unknown_rather_than_taken() {
        // A guard naming a region whose condition is not in the summary: a summary written before the regions
        // carried their conditions, or one whose bytes came from somewhere else. Nothing can be said about it, and
        // the tempting answer — "there is no condition, so it is compiled" — is the one that would silently stop
        // qualifying a fact that may well be behind an `#if`.
        let source = "#ifdef X\n#define INNER 1\n#endif\n";
        let mut index = index_of(source, &["X"]);
        let path = Path::new("/p/widget.h");

        let summary = index.summary(path).expect("the file is indexed");
        let mut stripped = summary.clone();
        stripped.guards = SummaryGuards {
            regions: summary.guards.regions.clone(),
            conditionals: Vec::new(),
            ..SummaryGuards::default()
        };
        index.insert(stripped);

        assert_eq!(
            visibility_at(&index, path, FactGuard::Region(0), 0),
            Visibility::Unknown
        );
    }

    #[test]
    fn a_name_the_file_defines_inside_the_region_is_not_evidence_about_the_region() {
        // A `#define` written *inside* an `#if` may not be there at all, so it is not evidence about the very
        // condition that guards it. The file's **own** include guard is the exception, and it is not an exception
        // made here: the walk de-guards it (reaching the file at all is what a guard means), so no condition is
        // asked about — see `deguard_the_files_own_guard`. The declaration at the top is what keeps this region
        // from being that guard.
        let source = "int early;\n#ifndef WRAPPER\n#define WRAPPER 1\n#define INNER 2\n#endif\n";
        let (index, guard, offset) = guard_of(source, &[], "INNER");

        assert_eq!(
            visibility_at(&index, Path::new("/p/widget.h"), guard, offset),
            Visibility::Unknown,
            "nothing outside the region says whether `WRAPPER` was defined when the `#ifndef` was read"
        );

        let (index, guard, offset) = guard_of(source, &["WRAPPER"], "INNER");
        assert_eq!(
            visibility_at(&index, Path::new("/p/widget.h"), guard, offset),
            Visibility::Inactive,
            "with WRAPPER defined the guard is not taken, and the body is not in the translation unit"
        );
    }
}