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
//! **Unreal Engine** — everything the analysis knows about it, in one module.
//!
//! ```text
//! .cppls.toml                 [unreal] enable = true, engine = "…"
//! Engine/Source/Runtime/…     the engine's own headers (`Core/Public`, `Engine/Public`, `CoreUObject/Public`, …)
//! Source/<Module>/…           the project's modules (named by the project's `*.uproject`)
//! Intermediate/Build/…/UHT    the reflection headers the build tool generated
//! ```
//!
//! # What is here today
//!
//! [`UnrealSection`] — the `[unreal]` section of `.cppls.toml` — and [`UnrealSection::applied_to`], which turns it
//! into the compiler configuration an engine's headers need:
//!
//! ```text
//! engine = "…"    where the engine is installed. Every `Engine/Source/Runtime/<Module>/{Public,Classes}` becomes an
//!                 include directory, so `#include "CoreMinimal.h"` and `#include "GameFramework/Actor.h"` resolve
//!                 the way they do in a build
//! enable          the two engine rules run; the macros below are defined either way, because a project that names the
//!                 engine is engine code whether or not it also switched the rules on
//! ```
//!
//! **The macros an engine build defines are supplied by this layer**, not by the headers: `WITH_EDITOR`,
//! `WITH_EDITORONLY_DATA`, `WITH_ENGINE`, `UE_BUILD_DEVELOPMENT`, `UE_SERVER`, `IS_PROGRAM` and the platform the server
//! runs on. And from the project's `*.uproject`, one `<MODULE>_API` per module, defined as nothing — the engine's build
//! tool is what makes it a visibility attribute, and a reader that saw `class MYGAME_API AActor` without it would report
//! an unknown name. A define the project states itself wins: neither the section nor the engine may overwrite what a
//! compile command said.
//!
//! # Why a project's decision, and not a detection
//!
//! A file that writes `UCLASS()` outside UE is a file with an unknown macro, not a game, and running Epic's naming
//! rules on an engine-agnostic project would report every `class Widget` as a missing `A`/`U`/`F`.
//!
//! # What will be here
//!
//! ```text
//! discovery     the module list from `*.Build.cs` (the `.uproject` names the targets), the generated include
//!               directories under `Intermediate/Build/<Platform>/<Config>/Inc/<Module>/UHT`, and the engine version
//! reading       the reflection annotations — UCLASS/USTRUCT/UENUM/UINTERFACE/UPROPERTY/UFUNCTION and their
//!               specifiers — which are **empty macros** and therefore have to be read from the written text
//! members       what GENERATED_BODY() stands for: StaticClass(), GetPrivateStaticClass(), Super, ThisClass
//! ```
//!
//! **The rules themselves do not live here.** One check per code, in
//! [`crate::sema::check`](crate::sema::check) — `ue_naming`, `ue_generate_body` — like every other rule, because that is
//! where a rule is found by its code and where its tests are. What this module owns is the *answers* those rules read,
//! so that two rules cannot disagree about which class a `UCLASS()` annotates.

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

use serde::Deserialize;

/// **`[unreal]`** — whether this project is Unreal Engine code.
///
/// ```toml
/// [unreal]
/// enable = true
/// engine = "C:/Program Files/Epic Games/UE_5.4"
/// ```
///
/// `enable` alone is enough for a project whose headers already say where the engine is (a compile database with the
/// `-I` entries UBT generates); `engine` is what makes a project without a database — or without the engine installed
/// where the build says — resolve its includes, and it turns the rules on as well.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnrealSection {
    /// Run the Unreal conventions — see `ue-naming` and `ue-generate-body`.
    #[serde(default)]
    pub enable: bool,
    /// **The engine's installation root** — the directory that holds `Engine/Source/Runtime`, or a plain directory of
    /// headers. A relative path is relative to the workspace root, like every other path in `.cppls.toml`.
    #[serde(default)]
    pub engine: Option<PathBuf>,
}

impl UnrealSection {
    /// **Is this project engine code at all?** — the rules run, and the engine's macros are defined.
    ///
    /// `engine` implies it: naming the engine is saying what the project is, and a reader who had to write both keys
    /// would eventually write one.
    pub fn is_on(&self) -> bool {
        self.enable || self.engine.is_some()
    }

    /// **The engine's installation root, as an absolute directory** — the section's own path, or the directory under
    /// the workspace that holds `Engine/Source/Runtime`.
    ///
    /// **Two spellings are accepted for `engine`**: the installation root (`…/UE_5.4`, which contains `Engine/`) and
    /// that `Engine` directory itself (`…/UE_5.4/Engine`), because which one a person calls "the engine" is not
    /// something this layer can know and both are unambiguous on disk. The answer is always the installation root, so
    /// that everything below it has one spelling.
    ///
    /// The workspace's own tree is the fallback — a project checked out inside an engine, or beside one — and it is a
    /// **guess** rather than a fact, which is why it is only taken when it exists.
    pub fn engine_root(&self, root: &Path) -> Option<PathBuf> {
        if let Some(named) = self.engine.as_ref() {
            let named = if named.is_absolute() {
                named.clone()
            } else {
                root.join(named)
            };
            if named.join("Engine/Source/Runtime").is_dir() {
                return Some(named);
            }
            // The `Engine` directory itself: the parent is the installation root.
            if named.join("Source/Runtime").is_dir()
                && let Some(parent) = named.parent()
            {
                return Some(parent.to_path_buf());
            }
            // A directory of headers rather than an installation: used as it is, as an include root.
            return Some(named);
        }
        [root.to_path_buf(), root.parent()?.to_path_buf()]
            .into_iter()
            .find(|candidate| candidate.join("Engine/Source/Runtime").is_dir())
    }

    /// **The configuration this section describes**, applied to what discovery worked out.
    ///
    /// One function rather than a handful of edits in the session, for the same reason [`CudaSection`] has one: the
    /// keys are one statement — naming an engine means "and its headers resolve, and its macros are defined" — and
    /// splitting that across call sites is how one of the three would eventually be forgotten.
    ///
    /// [`CudaSection`]: crate::project::cuda::CudaSection
    pub fn applied_to(
        &self,
        mut config: crate::include::config::CompilerConfig,
        root: &Path,
    ) -> crate::include::config::CompilerConfig {
        if !self.is_on() {
            return config;
        }
        // **The project's own generated code first.** UHT writes each module's generated headers into
        // `Intermediate/Build/<Platform>/<Config>/Inc/<Module>/UHT`, and that directory is what makes
        // `#include "MyActor.generated.h"` resolve — the header a UE source file includes, and the one that declares
        // `Super`, `ThisClass` and `StaticClass()` for the compiler. A project that has been built has them as **real
        // symbols**; one that has not keeps the fallback [`crate::sema::resolve`] documents.
        for include in generated_include_directories(root) {
            config
                .include_paths
                .push(crate::include::config::IncludePath::system(include));
        }
        if let Some(engine) = self.engine_root(root) {
            for include in engine_include_directories(&engine) {
                config
                    .include_paths
                    .push(crate::include::config::IncludePath::system(include));
            }
        }
        // **What an engine build defines.** Nothing here overwrites a define the project stated: a compile database
        // that says `WITH_EDITOR=0` is describing the build that exists, and a guess about the editor must not win.
        for (name, value) in engine_defines() {
            define_if_absent(&mut config, name, value);
        }
        // **One `<MODULE>_API` per module the project names.** `MYGAME_API` is what the build tool turns into a
        // visibility attribute; to a reader it expands to nothing, and a class that writes it must still parse.
        for module in game_modules(root) {
            // **`MyGame` becomes `MYGAME_API`**, which is how the build tool spells the visibility macro of a module.
            define_if_absent(&mut config, &format!("{}_API", module.to_uppercase()), "");
        }
        config
    }
}

/// **The specifiers each reflection macro accepts**, as the engine documents them.
///
/// A mistyped specifier is **silently ignored** by the build tool: `UPROPERTY(BlueprintReadWrit)` compiles, and the
/// property is not readable from Blueprint. That silence is what `ue-specifier` reports, and this table is the answer it
/// compares against.
///
/// # Why a table, and why it is allowed to be incomplete
///
/// Rider runs the real UnrealHeaderTool in the background and shows its diagnostics; this analysis has no engine to run,
/// so the vocabulary has to be written down. It is the **common** set, and the rule is a warning rather than an error for
/// exactly that reason: a specifier this table does not know may be one a newer engine added, and a project that hits a
/// false positive silences the rule by name (`[diagnostics] disable = ["ue-specifier"]`) — the escape hatch every rule in
/// this server has.
///
/// `meta` is in every list because it is accepted everywhere, and its inside is free-form: `meta=(DisplayName="…")` is
/// **one** specifier whose parentheses hold whatever the engine's documentation says.
pub fn known_specifiers(macro_name: &str) -> Option<&'static [&'static str]> {
    const UCLASS: &[&str] = &[
        "Abstract",
        "AdvancedClassDisplay",
        "AutoCollapseCategories",
        "AutoExpandCategories",
        "Blueprintable",
        "BlueprintType",
        "ClassGroup",
        "CollapseCategories",
        "Config",
        "Const",
        "CustomConstructor",
        "DefaultConfig",
        "DefaultToInstanced",
        "Deprecated",
        "DontAutoCollapseCategories",
        "DontCollapseCategories",
        "EarlyAccessPreview",
        "Experimental",
        "HideCategories",
        "Interface",
        "MinimalAPI",
        "NoExport",
        "NonTransient",
        "NotBlueprintable",
        "NotPlaceable",
        "PerObjectConfig",
        "Placeable",
        "ShowCategories",
        "SparseClassDataType",
        "Transient",
        "Within",
        "meta",
    ];
    const USTRUCT: &[&str] = &[
        "Atomic",
        "BlueprintType",
        "Immutable",
        "NoExport",
        "SparseClassDataType",
        "meta",
    ];
    const UENUM: &[&str] = &["BlueprintType", "Experimental", "meta"];
    const UINTERFACE: &[&str] = &[
        "Blueprintable",
        "Experimental",
        "MinimalAPI",
        "NotBlueprintable",
        "meta",
    ];
    const UPROPERTY: &[&str] = &[
        "AdvancedDisplay",
        "AssetRegistrySearchable",
        "BlueprintAssignable",
        "BlueprintCallable",
        "BlueprintGetter",
        "BlueprintHidden",
        "BlueprintReadOnly",
        "BlueprintReadWrite",
        "BlueprintSetter",
        "Category",
        "Config",
        "DuplicateTransient",
        "EditAnywhere",
        "EditDefaultsOnly",
        "EditFixedSize",
        "EditInline",
        "EditInstanceOnly",
        "Export",
        "GlobalConfig",
        "HideAlphaChannel",
        "HidePin",
        "Instanced",
        "Interp",
        "Localized",
        "NoClear",
        "NoExport",
        "NonPIEDuplicateTransient",
        "NonTransactional",
        "PersistentInstance",
        "RepNotify",
        "Replicated",
        "ReplicatedUsing",
        "SaveGame",
        "SerializeText",
        "SimpleDisplay",
        "SkipSerialization",
        "TextExportTransient",
        "Transient",
        "VisibleAnywhere",
        "VisibleDefaultsOnly",
        "VisibleInstanceOnly",
        "ZeroConstructor",
        "meta",
    ];
    const UFUNCTION: &[&str] = &[
        "BlueprintAuthorityOnly",
        "BlueprintCallable",
        "BlueprintCosmetic",
        "BlueprintImplementableEvent",
        "BlueprintNativeEvent",
        "BlueprintPure",
        "CallInEditor",
        "Category",
        "Client",
        "CustomThunk",
        "Exec",
        "NetMulticast",
        "Reliable",
        "SealedEvent",
        "Server",
        "ServiceRequest",
        "ServiceResponse",
        "Unreliable",
        "WithValidation",
        "meta",
    ];
    match macro_name {
        "UCLASS" => Some(UCLASS),
        "USTRUCT" => Some(USTRUCT),
        "UENUM" => Some(UENUM),
        "UINTERFACE" => Some(UINTERFACE),
        "UPROPERTY" => Some(UPROPERTY),
        "UFUNCTION" => Some(UFUNCTION),
        _ => None,
    }
}

/// **What `GENERATED_BODY()` writes into a class that a macro cannot** — the two names that need the class and its base.
///
/// The engine's build tool writes `typedef <Base> Super;` and `typedef <ThisClass> ThisClass;` into the generated code,
/// which is why a macro in the engine's own header can declare `StaticClass()` (no name needed) and not these two. A
/// language server that only reads the macro therefore answers `Super` and `ThisClass` as unknown names — measured on
/// `UE-like`, where `Super::BeginPlay()` resolved to nothing.
///
/// The answer is derived, not invented: `Super` **is** the class's first base as its declaration wrote it, and
/// `ThisClass` **is** the class. Returned as `(name, type)` in the order the generated code writes them.
pub fn generated_members(class_name: &str, bases: &[String]) -> Vec<(&'static str, String)> {
    let mut members = vec![("ThisClass", class_name.to_string())];
    if let Some(base) = bases.first() {
        members.push(("Super", base.clone()));
    }
    members
}

/// **The directories UHT wrote this project's generated headers into.**
///
/// ```text
/// Intermediate/Build/<Platform>/<Config>/Inc/<Module>/UHT/MyActor.generated.h
/// ```
///
/// Both `<Module>/UHT` and `<Module>` are offered, because a module's generated code is reachable under either in a real
/// tree and a duplicate search path costs nothing. Every platform and configuration found is included: a language
/// server analyses a checkout rather than a build, and a file compiled for `Win64/Development` may be read while the
/// editor's `Win64/UnrealEditorDevelopment` directory is the only one regenerated.
///
/// A project that has never been built has no such directory, and the answer is empty — that is the honest state, not a
/// failure: [`crate::sema::resolve`]'s generated-member fallback exists for exactly that case.
fn generated_include_directories(root: &Path) -> Vec<PathBuf> {
    let build = root.join("Intermediate/Build");
    let Ok(platforms) = std::fs::read_dir(&build) else {
        return Vec::new();
    };
    let mut platforms: Vec<PathBuf> = platforms
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .filter(|path| path.is_dir())
        .collect();
    platforms.sort();
    let mut directories = Vec::new();
    for platform in platforms {
        let Ok(configurations) = std::fs::read_dir(&platform) else {
            continue;
        };
        let mut configurations: Vec<PathBuf> = configurations
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .filter(|path| path.is_dir())
            .collect();
        configurations.sort();
        for configuration in configurations {
            let inc = configuration.join("Inc");
            let Ok(modules) = std::fs::read_dir(&inc) else {
                continue;
            };
            let mut modules: Vec<PathBuf> = modules
                .filter_map(|entry| entry.ok().map(|entry| entry.path()))
                .filter(|path| path.is_dir())
                .collect();
            modules.sort();
            for module in modules {
                let uht = module.join("UHT");
                if uht.is_dir() {
                    directories.push(uht);
                }
                directories.push(module);
            }
        }
    }
    directories
}
/// **The include directories an engine root offers**, in the order a build would read them.
///
/// The real layout is `Engine/Source/Runtime/<Module>/Public` (the module's headers) and, for some modules,
/// `<Module>/Classes` (the assets-facing part, which is where `GameFramework/Actor.h` lives in a UE4 tree). Both are
/// added when they exist, sorted by module so that the search order does not depend on the filesystem's.
///
/// A directory that does not have `Engine/Source/Runtime` is used **as an include root itself**: that is what a
/// simulation or a hand-made header set looks like, and refusing it would make `[unreal] engine` mean "the whole
/// installation or nothing" for no reason.
fn engine_include_directories(engine: &Path) -> Vec<PathBuf> {
    let runtime = engine.join("Engine/Source/Runtime");
    if !runtime.is_dir() {
        return vec![engine.to_path_buf()];
    }
    let mut modules: Vec<PathBuf> = std::fs::read_dir(&runtime)
        .map(|entries| {
            entries
                .filter_map(|entry| entry.ok().map(|entry| entry.path()))
                .filter(|path| path.is_dir())
                .collect()
        })
        .unwrap_or_default();
    modules.sort();
    let mut directories = Vec::new();
    for module in modules {
        for relative in ["Public", "Classes"] {
            let directory = module.join(relative);
            if directory.is_dir() {
                directories.push(directory);
            }
        }
    }
    directories
}

/// **The macros an engine build defines**, as (name, value).
///
/// A deliberately short list, and each entry is a statement about the build a language server is describing: the engine's
/// **editor** configuration, on the platform the server runs on. `__CUDA_ARCH__`'s lesson applies here too — a macro
/// that is only defined in a pass a compiler never sees would make the analysis read a different program — so nothing
/// that depends on the *target* is defined beyond the host's own platform.
fn engine_defines() -> Vec<(&'static str, &'static str)> {
    let mut defines = vec![
        ("WITH_EDITOR", "1"),
        ("WITH_EDITORONLY_DATA", "1"),
        ("WITH_ENGINE", "1"),
        ("UE_BUILD_DEVELOPMENT", "1"),
        ("UE_SERVER", "0"),
        ("IS_PROGRAM", "0"),
    ];
    if cfg!(windows) {
        defines.push(("PLATFORM_WINDOWS", "1"));
        defines.push(("PLATFORM_DESKTOP", "1"));
    } else if cfg!(target_os = "macos") {
        defines.push(("PLATFORM_MAC", "1"));
        defines.push(("PLATFORM_DESKTOP", "1"));
    } else {
        defines.push(("PLATFORM_LINUX", "1"));
        defines.push(("PLATFORM_DESKTOP", "1"));
    }
    defines
}

/// **Define a macro unless the project already said what it is.**
fn define_if_absent(config: &mut crate::include::config::CompilerConfig, name: &str, value: &str) {
    let taken = config
        .defines
        .iter()
        .any(|defined| defined.name.as_ref() == name)
        || config
            .undefines
            .iter()
            .any(|undefined| undefined.as_ref() == name);
    if taken {
        return;
    }
    let value = if value.is_empty() { None } else { Some(value) };
    config.defines.push(match value {
        Some(value) => {
            crate::include::config::CommandLineMacro::with_value(name.to_string(), value)
        }
        // `-DFOO` is `1`; an **empty** value is a different macro, and this is the only spelling the type has for it.
        None => crate::include::config::CommandLineMacro::with_value(name.to_string(), ""),
    });
}

/// **The modules the project's `*.uproject` names** — `["MyGame"]` for a game module, and one per plugin's module too.
///
/// Read rather than run: the file is a small JSON object, and the only field this layer needs is `Modules[].Name`. A
/// missing or unreadable file is not an error here — the engine's headers still resolve, and the `*_API` macros are the
/// one thing lost.
fn game_modules(root: &Path) -> Vec<String> {
    let uproject = match std::fs::read_dir(root) {
        Ok(entries) => entries
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .find(|path| {
                path.extension()
                    .is_some_and(|extension| extension == "uproject")
            }),
        Err(_) => None,
    };
    let Some(uproject) = uproject else {
        return Vec::new();
    };
    let Ok(text) = std::fs::read_to_string(&uproject) else {
        return Vec::new();
    };
    module_names_in(&text)
}

/// **The `Modules[].Name` entries of a `.uproject`'s text.**
///
/// A hand-written scan rather than a JSON parser, for the same reason the compile database has one: this crate has no
/// JSON dependency, the shape asked for is one array of one field, and a parser that rejects the file over a comment or
/// a trailing comma would lose the module names for a reason that has nothing to do with them.
fn module_names_in(text: &str) -> Vec<String> {
    let mut names = Vec::new();
    let Some(modules) = text.find("\"Modules\"") else {
        return names;
    };
    // The array that follows, and its end — `Modules` is the only array this reads, so the depth is all the state.
    let Some(open) = text[modules..].find('[').map(|at| modules + at) else {
        return names;
    };
    let mut depth = 0usize;
    let mut index = open;
    let bytes = text.as_bytes();
    while index < bytes.len() {
        match bytes[index] {
            b'[' => depth += 1,
            b']' => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            b'"' => {
                // A string key or value: `"Name"` followed by `:` then the value.
                let start = index + 1;
                let Some(end) = text[start..].find('"').map(|at| start + at) else {
                    break;
                };
                let word = &text[start..end];
                if word == "Name" {
                    let rest = &text[end + 1..];
                    if let Some(value) = quoted_value_after_colon(rest) {
                        names.push(value);
                    }
                }
                index = end;
            }
            _ => {}
        }
        index += 1;
    }
    names
}

/// The string after a `:` in `rest`, when the next non-space characters are `: "…"`.
fn quoted_value_after_colon(rest: &str) -> Option<String> {
    let rest = rest.trim_start();
    let rest = rest.strip_prefix(':')?.trim_start();
    let rest = rest.strip_prefix('"')?;
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

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

    #[test]
    fn a_uprojects_modules_are_read() {
        let text = "{\n  \"FileVersion\": 3,\n  \"Modules\": [\n    { \"Name\": \"MyGame\", \"Type\": \"Runtime\" },\n    \
                    { \"Name\": \"MyGameEditor\", \"Type\": \"Editor\" }\n  ]\n}\n";
        assert_eq!(module_names_in(text), vec!["MyGame", "MyGameEditor"]);
    }

    #[test]
    fn a_file_without_modules_names_none() {
        assert!(module_names_in("{\"FileVersion\": 3}").is_empty());
        assert!(module_names_in("").is_empty());
    }

    #[test]
    fn an_engine_root_with_the_real_layout_offers_its_modules() {
        let root = std::env::temp_dir().join(format!("cppls_ue_engine_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(root.join("Engine/Source/Runtime/Core/Public")).expect("a tree");
        std::fs::create_dir_all(root.join("Engine/Source/Runtime/Engine/Public")).expect("a tree");
        std::fs::create_dir_all(root.join("Engine/Source/Runtime/Engine/Classes")).expect("a tree");
        let directories = engine_include_directories(&root);
        assert_eq!(
            directories,
            vec![
                root.join("Engine/Source/Runtime/Core/Public"),
                root.join("Engine/Source/Runtime/Engine/Public"),
                root.join("Engine/Source/Runtime/Engine/Classes"),
            ]
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_built_projects_generated_directories_are_found() {
        let root = std::env::temp_dir().join(format!("cppls_ue_uht_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let editor = root.join("Intermediate/Build/Win64/UnrealEditor/Inc/Game/UHT");
        let development = root.join("Intermediate/Build/Win64/Development/Inc/Other");
        std::fs::create_dir_all(&editor).expect("the UHT directory");
        std::fs::create_dir_all(&development).expect("a second configuration");
        let directories = generated_include_directories(&root);
        assert!(directories.contains(&editor), "{directories:?}");
        assert!(
            directories.contains(&root.join("Intermediate/Build/Win64/Development/Inc/Other")),
            "a module's own directory is offered too: {directories:?}"
        );
        // **A project that was never built has none**, and that is an answer rather than a failure.
        let empty = std::env::temp_dir().join(format!("cppls_ue_unbuilt_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&empty);
        std::fs::create_dir_all(&empty).expect("an empty project");
        assert!(generated_include_directories(&empty).is_empty());
        let _ = std::fs::remove_dir_all(&root);
        let _ = std::fs::remove_dir_all(&empty);
    }

    #[test]
    fn a_plain_header_directory_is_an_include_root() {
        let root = std::env::temp_dir().join(format!("cppls_ue_stub_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        std::fs::create_dir_all(&root).expect("a tree");
        assert_eq!(engine_include_directories(&root), vec![root.clone()]);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn a_project_that_names_the_engine_is_engine_code() {
        let section = UnrealSection {
            enable: false,
            engine: Some(PathBuf::from("Engine")),
        };
        assert!(section.is_on());
        let off = UnrealSection::default();
        assert!(!off.is_on());
    }
}