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
//! Reading a compiler configuration, and a compile database.
//!
//! The theme of these tests is that a wrong configuration is invisible: nothing in a source file says
//! which `#ifdef` branches are live or which `vector` was included, so a mistake here produces an analysis
//! that is confidently wrong rather than loudly incomplete. Each flag is therefore pinned separately,
//! including the two spellings of every option and the ones that are deliberately ignored.

use cpp_code_analysis::{
    CommandLineMacro, CompilerConfig, IncludePath, parse_compile_commands, split_command_line,
};
use std::path::{Path, PathBuf};

/// A configuration read from a command line, which is how every one of these arrives in practice.
fn from_arguments(arguments: &[&str]) -> CompilerConfig {
    let command = cpp_code_analysis::CompileCommand {
        file: PathBuf::from("src/main.cpp"),
        directory: Some(PathBuf::from("/project")),
        arguments: arguments.iter().map(|it| it.to_string()).collect(),
    };

    command.to_config()
}

// ============================================================================
// Command lines
// ============================================================================

#[test]
fn both_spellings_of_an_include_path_are_read() {
    let joined = from_arguments(&["-Iinc", "main.cpp"]);
    let separate = from_arguments(&["-I", "inc", "main.cpp"]);

    assert_eq!(joined.include_paths, vec![IncludePath::user("inc")]);
    assert_eq!(joined.include_paths, separate.include_paths);
}

#[test]
fn a_system_include_path_is_marked_as_one() {
    let config = from_arguments(&["-isystem", "/usr/include", "-Iinc"]);

    assert_eq!(
        config.include_paths,
        vec![
            IncludePath::system("/usr/include"),
            IncludePath::user("inc"),
        ]
    );
    assert_eq!(
        config.user_include_paths().collect::<Vec<_>>(),
        vec![Path::new("inc")]
    );
    assert_eq!(
        config.system_include_paths().collect::<Vec<_>>(),
        vec![Path::new("/usr/include")]
    );
}

/// Order is load-bearing: the first directory holding a file wins, which is how a project shadows a system
/// header. Reversing the lists would break that silently.
#[test]
fn include_path_order_is_preserved() {
    let config = from_arguments(&["-I", "first", "-I", "second", "-isystem", "third"]);

    assert_eq!(
        config.search_order().collect::<Vec<_>>(),
        vec![
            (Path::new("first"), false),
            (Path::new("second"), false),
            (Path::new("third"), true),
        ]
    );
}

/// **`-DFOO` defines `FOO` as `1`, not as nothing.** The standard says so, and `#if FOO` depends on it —
/// treating it as an empty body would make every `#if FOO` false.
#[test]
fn a_bare_define_is_one_and_a_valued_define_keeps_its_value() {
    let config = from_arguments(&["-DFOO", "-DBAR=2", "-DBAZ="]);

    assert_eq!(
        config.defines,
        vec![
            CommandLineMacro::defined("FOO"),
            CommandLineMacro::with_value("BAR", "2"),
            CommandLineMacro::with_value("BAZ", ""),
        ]
    );

    assert_eq!(
        config.defines[0].value, None,
        "`-DFOO` has no written value"
    );
    assert_eq!(
        config.defines[2].value.as_deref(),
        Some(""),
        "and `-DBAZ=` is an empty one, which is a different thing"
    );
}

#[test]
fn an_undefine_is_read() {
    let config = from_arguments(&["-UFOO", "-U", "BAR"]);

    assert_eq!(config.undefines, vec!["FOO".into(), "BAR".into()]);
}

#[test]
fn the_standard_and_the_target_are_read() {
    let config = from_arguments(&["-std=c++20", "--target=x86_64-linux-gnu", "-m32"]);

    assert_eq!(config.standard.as_deref(), Some("c++20"));
    assert_eq!(
        config.target.as_deref(),
        Some("-m32"),
        "the later flag wins"
    );
}

#[test]
fn a_target_given_as_a_separate_argument_is_read() {
    let config = from_arguments(&["--target", "aarch64-none-elf"]);

    assert_eq!(config.target.as_deref(), Some("aarch64-none-elf"));
}

/// A flag this does not know is ignored rather than guessed at. A wrong `-D` is worse than a missing one,
/// and the flags that matter are all read.
#[test]
fn unknown_flags_are_ignored() {
    let config = from_arguments(&[
        "-O2",
        "-Wall",
        "-fno-exceptions",
        "-c",
        "-o",
        "build/main.o",
        "-Iinc",
    ]);

    assert_eq!(config.include_paths, vec![IncludePath::user("inc")]);
    assert!(config.defines.is_empty());
}

/// A relative `-I` is relative to where the compiler ran. Nothing in the source says where that was, so
/// without the working directory a project's own include paths resolve against nothing in particular.
#[test]
fn paths_resolve_against_the_working_directory() {
    let config = from_arguments(&["-Iinc", "src/main.cpp"]);

    assert_eq!(config.working_directory, Some(PathBuf::from("/project")));
    assert_eq!(
        config.resolve_against_working_directory(Path::new("inc")),
        PathBuf::from("/project/inc")
    );
    assert_eq!(
        config.resolve_against_working_directory(Path::new("/absolute/inc")),
        PathBuf::from("/absolute/inc"),
        "an absolute path is already resolved"
    );
}

#[test]
fn a_configuration_with_nothing_supplied_is_empty() {
    assert!(CompilerConfig::new().is_empty());
    assert!(
        !CompilerConfig::new()
            .with_define(CommandLineMacro::defined("X"))
            .is_empty()
    );
    assert!(!CompilerConfig::new().with_include_path("inc").is_empty());
    assert!(!CompilerConfig::new().with_standard("c++20").is_empty());
    assert!(
        !CompilerConfig::new()
            .with_working_directory("/project")
            .is_empty()
    );
}

// ============================================================================
// Command-line splitting
// ============================================================================

#[test]
fn a_command_line_splits_on_whitespace() {
    assert_eq!(
        split_command_line("c++ -c src/main.cpp -o build/main.o"),
        vec!["c++", "-c", "src/main.cpp", "-o", "build/main.o"]
    );
}

#[test]
fn quoting_keeps_an_argument_together() {
    assert_eq!(
        split_command_line("c++ \"-DFOO=some value\" 'x y'"),
        vec!["c++", "-DFOO=some value", "x y"]
    );
}

#[test]
fn an_empty_quoted_argument_is_an_argument() {
    assert_eq!(split_command_line("a \"\" b"), vec!["a", "", "b"]);
}

#[test]
fn a_backslash_escapes_the_next_character() {
    assert_eq!(split_command_line("c++ -I a\\ b"), vec!["c++", "-I", "a b"]);
}

/// **A Windows path keeps its separators** — the defect that made a CMake+MinGW project be analysed by MSVC.
///
#[test]
fn a_windows_path_keeps_its_separators() {
    assert_eq!(
        split_command_line(
            r#"C:\toolchains\mingw64\bin\c++.exe -std=c++23 -o CMakeFiles\demo.dir\src\main.cpp.obj -c C:\work\demo\src\main.cpp"#
        ),
        vec![
            r#"C:\toolchains\mingw64\bin\c++.exe"#,
            "-std=c++23",
            "-o",
            r#"CMakeFiles\demo.dir\src\main.cpp.obj"#,
            "-c",
            r#"C:\work\demo\src\main.cpp"#,
        ]
    );

    // A quoted path with a space, and a UNC share: the two spellings a naive "strip every backslash" gets wrong.
    assert_eq!(
        split_command_line(r#""C:\Program Files\mingw\c++.exe" -I \\server\share\inc"#),
        vec![
            r#"C:\Program Files\mingw\c++.exe"#,
            "-I",
            r#"\\server\share\inc"#
        ]
    );

    // And the escapes a command line really does use still work: a quote inside a quoted run, and an escaped space.
    assert_eq!(
        split_command_line(r#"-DMSG="say \"hi\"" -I a\ b"#),
        vec![r#"-DMSG=say "hi""#, "-I", "a b"]
    );
}

/// Runs of whitespace collapse, and leading and trailing ones produce nothing.
#[test]
fn extra_whitespace_produces_no_empty_arguments() {
    assert_eq!(split_command_line("  a   b  "), vec!["a", "b"]);
    assert!(split_command_line("   ").is_empty());
    assert!(split_command_line("").is_empty());
}

// ============================================================================
// Compile databases
// ============================================================================

const DATABASE: &str = r#"[
  {
    "directory": "/home/u/project",
    "command": "/usr/bin/c++ -Iinc -DFOO=1 -std=c++20 -c src/main.cpp",
    "file": "/home/u/project/src/main.cpp"
  },
  {
    "directory": "/home/u/project",
    "arguments": ["/usr/bin/c++", "-isystem", "/usr/include", "-c", "src/other.cpp"],
    "file": "/home/u/project/src/other.cpp"
  }
]"#;

#[test]
fn both_shapes_of_entry_are_read() {
    let database = parse_compile_commands(DATABASE);

    assert_eq!(database.len(), 2);
    assert_eq!(database.malformed, 0);

    let first = database.command_for(Path::new("/home/u/project/src/main.cpp"));
    assert!(first.is_some(), "the `command` shape");

    let second = database.command_for(Path::new("/home/u/project/src/other.cpp"));
    assert!(second.is_some(), "the `arguments` shape");
}

#[test]
fn a_command_string_becomes_a_configuration() {
    let database = parse_compile_commands(DATABASE);
    let config = database
        .command_for(Path::new("/home/u/project/src/main.cpp"))
        .expect("an entry")
        .to_config();

    assert_eq!(config.include_paths, vec![IncludePath::user("inc")]);
    assert_eq!(
        config.defines,
        vec![CommandLineMacro::with_value("FOO", "1")]
    );
    assert_eq!(config.standard.as_deref(), Some("c++20"));
    assert_eq!(
        config.working_directory,
        Some(PathBuf::from("/home/u/project"))
    );
}

#[test]
fn an_arguments_entry_becomes_a_configuration() {
    let database = parse_compile_commands(DATABASE);
    let config = database
        .command_for(Path::new("/home/u/project/src/other.cpp"))
        .expect("an entry")
        .to_config();

    assert_eq!(
        config.include_paths,
        vec![IncludePath::system("/usr/include")]
    );
}

/// A database written on one machine and opened on another spells the same file with a different prefix.
/// Matching the tail is what makes a checked-in database usable at all.
#[test]
fn a_file_is_found_whatever_the_path_prefix_is() {
    let database = parse_compile_commands(DATABASE);

    assert!(
        database
            .command_for(Path::new("/somewhere/else/src/main.cpp"))
            .is_some()
    );
    assert!(
        database.command_for(Path::new("src/main.cpp")).is_some(),
        "and with no prefix at all"
    );
    assert!(database.command_for(Path::new("src/nothing.cpp")).is_none());
}

/// Case and separator differences are the same file: a database written on Windows and read on Linux — or
/// the reverse — must still match.
#[test]
fn a_file_matches_across_separators_and_case() {
    let database = parse_compile_commands(DATABASE);

    assert!(
        database
            .command_for(Path::new("/home/u/project/src/Main.cpp"))
            .is_some()
    );
    assert!(
        database
            .command_for(Path::new("\\home\\u\\project\\src\\main.cpp"))
            .is_some()
    );
}

/// **A malformed entry must not be a hard failure.** Projects emit databases with trailing commas, with
/// comments, and with entries for languages this has nothing to say about; the useful behaviour is to take
/// what parses and report how much did not.
///
/// The entry with no `command` and no `arguments` is counted as malformed, while `{ this is not json }` is
/// *not*: it is a well-formed object that happens to lack the fields, and the shallow reader cannot tell
/// the two apart — nor does it need to, because both lead to the same decision.
#[test]
fn a_malformed_database_is_reported_not_fatal() {
    let database = parse_compile_commands(
        r#"[
  { "directory": "/p", "command": "c++ -c a.cpp", "file": "/p/a.cpp" },
  { "directory": "/p", "file": "/p/no-command.cpp" },
  { this is not json at all },
  { "directory": "/p", "arguments": ["c++", "-c", "b.cpp"], "file": "/p/b.cpp" }
]"#,
    );

    assert_eq!(database.len(), 2, "the two readable entries");
    assert_eq!(database.malformed, 2, "and the two that could not be used");
    assert!(
        database.command_for(Path::new("a.cpp")).is_some(),
        "a malformed entry does not lose the good ones"
    );
    assert!(
        database.command_for(Path::new("b.cpp")).is_some(),
        "and the good entry after it is still read"
    );
}

#[test]
fn an_empty_or_absent_database_is_empty() {
    assert!(parse_compile_commands("[]").is_empty());
    assert!(parse_compile_commands("").is_empty());
    assert!(parse_compile_commands("not json").is_empty());
    assert!(
        parse_compile_commands("{}").is_empty(),
        "an object, not an array"
    );
}

/// A brace inside a string does not open an object, which is what a naive splitter would get wrong on a
/// command containing one.
#[test]
fn braces_inside_strings_do_not_confuse_the_reader() {
    let database = parse_compile_commands(
        r#"[{ "directory": "/p", "command": "c++ -DX={a} -c a.cpp", "file": "/p/a.cpp" }]"#,
    );

    assert_eq!(database.len(), 1);
    assert_eq!(database.malformed, 0);

    let config = database
        .command_for(Path::new("a.cpp"))
        .expect("an entry")
        .to_config();
    assert_eq!(
        config.defines,
        vec![CommandLineMacro::with_value("X", "{a}")]
    );
}

/// A Windows path in a database is spelled with doubled separators in JSON, which the reader has to undo
/// or every include in the project fails to resolve.
///
/// **The assertion is on the normalized spelling, not on `Path` equality.** `PathBuf::from("C:\proj")` and
/// `PathBuf::from("C:/proj")` are one path on Windows — a separator is a separator there — and two on a system that
/// has no such rule, which is where this test failed. What the rest of the crate relies on is the normalized
/// spelling: one separator, forward.
#[test]
fn escaped_separators_in_a_path_are_unescaped() {
    let database = parse_compile_commands(
        r#"[{ "directory": "C:\\proj", "command": "cl /c a.cpp", "file": "C:\\proj\\a.cpp" }]"#,
    );

    assert_eq!(database.len(), 1);
    let config = database
        .command_for(Path::new("a.cpp"))
        .expect("an entry")
        .to_config();
    let directory = config.working_directory.expect("the database names one");
    assert_eq!(
        cpp_code_analysis::normalize_path(&directory, false),
        "C:/proj",
        "the doubled separators are folded into the one spelling comparisons are made in"
    );
}