cpp_code_analysis 0.4.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
//! **Unreal Engine support against a simulated engine** — the section, the engine's include tree, and the module macros.
//!
//! There is no engine installation on this machine, so the fixture writes a **simulated** one: the include layout the
//! engine really has (`Engine/Source/Runtime/<Module>/Public/<Header>.h`), its reflection macros expanded to nothing,
//! and the handful of core types a game module derives from. A project beside it names the engine in `.cppls.toml` and
//! its module in a `*.uproject`, which is everything the analysis needs to read UE code:
//!
//! ```text
//!   Engine/Source/Runtime/Core/Public/CoreMinimal.h       UCLASS/UPROPERTY/GENERATED_BODY, int32, TArray, FString
//!   Engine/Source/Runtime/CoreUObject/Public/UObject/Object.h    UObject, TObjectPtr
//!   Engine/Source/Runtime/Engine/Public/GameFramework/Actor.h    AActor
//!   MyGame.uproject                                      Modules[].Name = MyGame  → MYGAME_API
//! ```
//!
//! The questions are the ones a reader of UE code has: do the engine's includes resolve, is `MYGAME_API` a name, do the
//! two engine rules still run, and does the class keep its own members.

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

use cpp_code_analysis::{
    DiagnosticCode, DiskFiles, Known, OpenDocuments, Session, SessionFiles, WatchFilter,
};

const CORE_MINIMAL: &str = r#"
#pragma once

#define UCLASS(...)
#define USTRUCT(...)
#define UENUM(...)
#define UINTERFACE(...)
#define UPROPERTY(...)
#define UFUNCTION(...)
#define GENERATED_BODY() \
public: \
    static UClass* StaticClass(); \
    static UClass* GetPrivateStaticClass();
#define GENERATED_UCLASS_BODY()
#define GENERATED_USTRUCT_BODY()
#define UE_LOG(CategoryName, Verbosity, Format, ...)
#define check(expr) ((void)0)
#define ensure(expr) (!!(expr))
#define TEXT(x) x
#define FORCEINLINE inline

using int32 = int;
using uint8 = unsigned char;

template <typename T>
class TArray
{
public:
    int32 Num() const { return 0; }
    void Add(const T& Value) {}
};

class FString
{
public:
    FString() {}
    FString(const char* Text) {}
};
"#;

const OBJECT: &str = r#"
#pragma once

#include "CoreMinimal.h"

class UClass;

class UObject
{
public:
    virtual ~UObject() {}
    FString GetName() const { return FString(); }
};

template <typename T>
class TObjectPtr
{
public:
    T* Get() const { return nullptr; }
    T* operator->() const { return nullptr; }
};
"#;

const ACTOR: &str = r#"
#pragma once

#include "CoreMinimal.h"
#include "UObject/Object.h"

class AActor : public UObject
{
public:
    virtual void BeginPlay();
    FString GetActorName() const { return FString(); }
};
"#;

/// A simulated engine tree and a game project beside it.
struct World {
    root: PathBuf,
}

impl World {
    fn new(name: &str) -> Self {
        let root = std::env::temp_dir().join(format!(
            "cppls_ue_engine_{name}_{}_{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        let engine = root.join("Engine");
        for (relative, text) in [
            ("Source/Runtime/Core/Public/CoreMinimal.h", CORE_MINIMAL),
            ("Source/Runtime/CoreUObject/Public/UObject/Object.h", OBJECT),
            ("Source/Runtime/Engine/Public/GameFramework/Actor.h", ACTOR),
        ] {
            let path = engine.join(relative);
            std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory");
            std::fs::write(&path, text).expect("the header");
        }
        let project = root.join("Game");
        std::fs::create_dir_all(project.join("Source/Game")).expect("a project");
        std::fs::write(
            project.join(".cppls.toml"),
            "[unreal]\nengine = \"../Engine\"\n\n[compile]\nstandard = \"c++20\"\n",
        )
        .expect("the configuration");
        std::fs::write(
            project.join("Game.uproject"),
            "{\n  \"FileVersion\": 3,\n  \"Modules\": [ { \"Name\": \"Game\", \"Type\": \"Runtime\" } ]\n}\n",
        )
        .expect("the uproject");
        // **The generated header where UHT writes it** — `Intermediate/Build/<Platform>/<Config>/Inc/<Module>/UHT` — so
        // that `#include "Game.generated.h"` resolves through the generated include directory and not beside the source.
        let generated =
            project.join("Intermediate/Build/Win64/UnrealEditor/Inc/Game/UHT/Game.generated.h");
        std::fs::create_dir_all(generated.parent().expect("a parent")).expect("the UHT directory");
        std::fs::write(
            &generated,
            "#pragma once\n\nstruct FFromGenerated\n{\n    int32 Value = 0;\n};\n",
        )
        .expect("the generated header");
        World { root: project }
    }

    fn write(&self, relative: &str, text: &str) -> PathBuf {
        let path = self.root.join(relative);
        std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory");
        std::fs::write(&path, text).expect("the source");
        path
    }

    fn session(&self) -> Session<DiskFiles> {
        let mut session = Session::open(
            self.root.clone(),
            SessionFiles::new(OpenDocuments::new(), DiskFiles),
            WatchFilter::new(&self.root),
        );
        let files: Vec<PathBuf> = session
            .project_files()
            .iter()
            .filter(|path| {
                path.extension()
                    .and_then(|extension| extension.to_str())
                    .is_some_and(|extension| matches!(extension, "h" | "cpp"))
            })
            .cloned()
            .collect();
        session.add_project_files(files);
        session.index_everything();
        let mut steps = 0;
        while session.pending_work() > 0 && steps < 20_000 {
            session.advance(64);
            steps += 1;
        }
        session
    }
}

impl Drop for World {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(self.root.parent().unwrap_or(&self.root));
    }
}

fn findings(session: &Session<DiskFiles>, path: &Path) -> Vec<(DiagnosticCode, String)> {
    session
        .diagnostics(path)
        .map(|found| {
            found
                .checks
                .iter()
                .map(|finding| (finding.code, finding.name.clone()))
                .collect()
        })
        .unwrap_or_default()
}

/// **The engine's includes resolve, the module's API macro is a name, and the class keeps its members.**
#[test]
fn a_game_module_over_a_simulated_engine_reads_and_lints() {
    let world = World::new("clean");
    let header = world.write(
        "Source/Game/MyActor.h",
        r#"
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Game.generated.h"

UCLASS()
class GAME_API AMyActor : public AActor
{
    GENERATED_BODY()

public:
    UPROPERTY(EditAnywhere)
    bool bIsReady = false;

    UPROPERTY()
    TObjectPtr<UObject> Target;

    TArray<FString> Names;

    // A type the generated header declares: it exists only under `Intermediate/…/UHT`, which is the include directory
    // the section adds.
    FFromGenerated Generated;

    void BeginPlay() override
    {
        Super::BeginPlay();
        ThisClass* Self = this;
        (void)Self;
    }
};
"#,
    );
    let mut session = world.session();
    session.cook(&header);

    // **The generated tree is not analysed as source**, though its headers resolve: `Intermediate` is UHT's output.
    assert!(
        session.project_files().iter().all(|path| !path
            .to_string_lossy()
            .to_ascii_lowercase()
            .contains("intermediate")),
        "the generated tree is excluded from the analysis: {:?}",
        session.project_files()
    );

    // **The generated include directory is part of the file's configuration.**
    let config = session.config_for(&header);
    assert!(
        config
            .include_paths
            .iter()
            .any(|path| path.directory.ends_with("UHT")),
        "{:?}",
        config
            .include_paths
            .iter()
            .map(|path| &path.directory)
            .collect::<Vec<_>>()
    );

    let errors = session
        .diagnostics(&header)
        .map(|found| found.errors.len())
        .unwrap_or(usize::MAX);
    assert_eq!(errors, 0, "the engine's headers and the macros parse");
    assert_eq!(
        findings(&session, &header),
        vec![],
        "a clean module is quiet"
    );

    // The class is a class: its own members are recorded, under the name the macro prefixes.
    let view = session.view(&header).expect("the header is held");
    let Known::Yes(list) = session.members_of(&view, "AMyActor") else {
        panic!("`AMyActor` has members");
    };
    let names: Vec<&str> = list
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    for expected in ["bIsReady", "Target", "Names", "StaticClass", "Generated"] {
        assert!(names.contains(&expected), "{expected} of {names:?}");
    }
    // The type came from the generated header, so its own member resolves too.
    let Known::Yes(generated) = session.members_of(&view, "FFromGenerated") else {
        panic!("the generated header's type is indexed");
    };
    let generated_names: Vec<&str> = generated
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert!(generated_names.contains(&"Value"), "{generated_names:?}");

    // **The two members the generated code writes that a macro cannot.** `Super` is the class's first base as its
    // declaration spelled it, `ThisClass` is the class itself — derived from the declaration, not invented.
    let super_member = list
        .members
        .iter()
        .find(|member| member.fact.name == "Super")
        .expect("the generated `Super`");
    assert_eq!(super_member.fact.type_of.as_deref(), Some("AActor"));
    let this_class = list
        .members
        .iter()
        .find(|member| member.fact.name == "ThisClass")
        .expect("the generated `ThisClass`");
    assert_eq!(this_class.fact.type_of.as_deref(), Some("AMyActor"));

    // **And they resolve inside a body**, which is the half the generated code does for a compiler: `Super::BeginPlay()`
    // reaches the engine's `AActor::BeginPlay`, and `ThisClass` is the class the body is written in.
    let source = view.source.to_string();
    // **The cursor goes on the member**, not the qualifier: on `Super` the answer is the base class itself, which is the
    // right answer to a different question.
    let super_at = source.find("Super::BeginPlay").expect("the base call") + "Super::".len();
    let Known::Yes(base) = session.definition(
        &view,
        cpp_code_analysis::file::coordinates::ReadingOffset::new(super_at),
    ) else {
        panic!("`Super::BeginPlay` resolves");
    };
    assert_eq!(base.fact.name, "BeginPlay", "{:?}", base.fact);
    // The index spells a path in its own (lowercased) form on Windows.
    assert!(
        base.file
            .to_string_lossy()
            .to_ascii_lowercase()
            .ends_with("gameframework/actor.h"),
        "the base's own declaration: {:?}",
        base.file
    );

    let this_at = source.find("ThisClass* Self").expect("the class itself");
    let Known::Yes(own) = session.definition(
        &view,
        cpp_code_analysis::file::coordinates::ReadingOffset::new(this_at),
    ) else {
        panic!("`ThisClass` resolves");
    };
    assert_eq!(own.fact.name, "AMyActor", "{:?}", own.fact);
    assert!(
        own.file
            .to_string_lossy()
            .to_ascii_lowercase()
            .ends_with("myactor.h"),
        "{:?}",
        own.file
    );
}

/// **A class with no base gets no `Super`**, and a project that is not engine code gets neither: the synthesis follows
/// the generated code's own rule (`Super` names a base), not the presence of the macro alone.
#[test]
fn a_class_without_a_base_has_no_super() {
    let world = World::new("no_base");
    let header = world.write(
        "Source/Game/MyData.h",
        r#"
#pragma once

#include "CoreMinimal.h"
#include "Game.generated.h"

USTRUCT()
struct FMyData
{
    GENERATED_BODY()

    int32 Value = 0;
};
"#,
    );
    let mut session = world.session();
    session.cook(&header);
    let view = session.view(&header).expect("the header is held");
    let Known::Yes(list) = session.members_of(&view, "FMyData") else {
        panic!("`FMyData` has members");
    };
    let names: Vec<&str> = list
        .members
        .iter()
        .map(|member| member.fact.name.as_str())
        .collect();
    assert!(names.contains(&"ThisClass"), "{names:?}");
    assert!(!names.contains(&"Super"), "a struct has no base: {names:?}");
}

/// **The two engine rules run on a project that names an engine**, and the engine's own headers are quiet: the
/// `Engine/` tree is outside the workspace, so nothing reports the engine's own spelling of `UCLASS` as a violation.
#[test]
fn the_engine_rules_run_and_the_engine_itself_is_not_judged() {
    let world = World::new("bad");
    let header = world.write(
        "Source/Game/MyActor.h",
        r#"
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Game.generated.h"

UCLASS()
class MyActor : public AActor
{
public:
    UPROPERTY()
    bool isReady = false;
};
"#,
    );
    let mut session = world.session();
    session.cook(&header);
    let found = findings(&session, &header);
    assert_eq!(
        found,
        vec![
            (DiagnosticCode::UeNaming, "MyActor".to_string()),
            (DiagnosticCode::UeGenerateBody, "MyActor".to_string()),
            (DiagnosticCode::UeNaming, "isReady".to_string()),
        ],
        "{found:?}"
    );
}

/// **`engine` alone turns the rules on** — naming the engine is saying what the project is, and a project that forgot
/// `enable` would otherwise get the headers but not the rules.
#[test]
fn naming_the_engine_turns_the_conventions_on() {
    let world = World::new("implied");
    let header = world.write(
        "Source/Game/MyActor.h",
        r#"
#include "CoreMinimal.h"
#include "Game.generated.h"

UCLASS()
class MyActor
{
public:
    bool isReady = false;
};
"#,
    );
    let mut session = world.session();
    session.cook(&header);
    let found = findings(&session, &header);
    assert!(
        found
            .iter()
            .any(|(code, _)| *code == DiagnosticCode::UeNaming),
        "the conventions ran: {found:?}"
    );
}