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
//! Parameter names at the call sites — the inlay hint an editor draws inside the code.
//!
//! The hints are placed **by position**: the first argument gets the first parameter's name, and so on. That is
//! what most of these tests are about, because the interesting cases are the ones where the positions do *not*
//! line up — an unnamed parameter, a variadic tail, a call of a class rather than of a function, a callee nothing
//! can resolve. Each of those has to produce no hint rather than a plausible-looking wrong one: a hint is printed
//! in the middle of the user's code, where nothing tells them it was a guess.

use cpp_code_analysis::{
    CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};

/// A session over the given files, with all of them indexed so that a callee in another file resolves.
fn session_with(files: &[(&str, &str)]) -> Session<MemoryFiles> {
    let mut memory = MemoryFiles::new();
    for (path, source) in files {
        memory = memory.with_file(*path, *source);
    }

    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files(
        files
            .iter()
            .map(|(path, _)| std::path::PathBuf::from(*path)),
    );

    // **The ask, and then the pump** - see `tests/completion.rs`'s `cooked_view`. A view is of the file's *cooked
    // reading*, and a rendering is built because something asked for it.
    for (path, _) in files {
        session.want_cooked_reading(std::path::Path::new(path));
    }
    session.index_everything();

    session
}

/// Every hint in one file, as `(offset, name)` pairs in the order they were produced.
fn hints_in(files: &[(&str, &str)], path: &str) -> Vec<(usize, String)> {
    let session = session_with(files);
    let view = session.view(path).expect("the file is held");
    let whole_file = cpp_parser::SourceRange::new(0, view.source.len());

    session
        .inlay_hints(&view, whole_file)
        .into_iter()
        .map(|hint| (hint.offset, hint.name))
        .collect()
}

/// The hints for the calls in a single file, with the named parameter each offset lands on.
fn hints_of(source: &str) -> Vec<(usize, String)> {
    hints_in(&[("/p/a.cpp", source)], "/p/a.cpp")
}

/// `scale(count: 3, factor: 0.5)` — the case the feature exists for.
#[test]
fn a_call_reports_the_parameters_of_its_callee() {
    let source = "\
double scale(int count, double factor);
double f() { return scale(3, 0.5); }
";
    let call = source.find("scale(3").expect("the fixture") + "scale(".len();

    assert_eq!(
        hints_of(source),
        vec![
            (call, "count".to_string()),
            (call + "3, ".len(), "factor".to_string()),
        ]
    );
}

/// **A call into a header nobody has cooked still gets its hints.**
///
/// The names used to come only from the declaring file's **rendering**, and a query does not build one — so a
/// system header nobody had opened answered nothing, and the hint was silently absent. Measured on a real file:
/// `anotherVec.push_back(_Val: …)` was hinted (a member's names come from `members_of`'s facts) while
/// `printf(…)` on the next line was not, because a free function's names came from `parameter_list_of` and that
/// needs a tree.
///
/// The fixture is the same shape: only the caller is cooked, and the assertion says so, or the test could pass
/// through the tree path and prove nothing.
#[test]
fn a_call_into_an_uncooked_header_is_still_hinted() {
    let declaration = "/p/stdio.h";
    let source = "int printf(const char* __format, ...);\n";
    let caller = "#include \"stdio.h\"\nint main() { printf(\"x = %d\\n\", 123); }\n";

    let mut memory = MemoryFiles::new();
    memory = memory.with_file(declaration, source);
    memory = memory.with_file("/p/a.cpp", caller);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.add_project_files([
        std::path::PathBuf::from(declaration),
        std::path::PathBuf::from("/p/a.cpp"),
    ]);
    session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
    session.index_everything();

    let view = session.view("/p/a.cpp").expect("the caller is held");
    assert!(
        session.view(declaration).is_none(),
        "the fixture is only meaningful while the declaration's file has no rendering"
    );

    // **The argument's offset in the *file***, which is what `inlay_hints` answers in: the handler places the hint
    // in the buffer the client is showing, so the query maps back across the seam.
    let argument = caller
        .find("\"x = %d")
        .expect("the argument is in the file");
    let whole_file = cpp_parser::SourceRange::new(0, view.source.len());
    let hints: Vec<(usize, String)> = session
        .inlay_hints(&view, whole_file)
        .into_iter()
        .map(|hint| (hint.offset, hint.name))
        .collect();

    assert_eq!(
        hints,
        vec![(argument, "__format".to_string())],
        "one hint, for the named parameter; `...` has no name to show.\n\
         rendering: {:?}",
        view.source
    );
}

/// A parameter list is not a call, and a hint goes at the **argument**: the declaration above writes
/// `int value`, and the one hint is the one at `other`, named after the parameter it lands in.
#[test]
fn only_the_arguments_of_a_call_are_hinted() {
    let source = "\
int twice(int value);
int f(int other) { return twice(other); }
";
    let argument = source.find("twice(other").expect("the fixture") + "twice(".len();

    assert_eq!(hints_of(source), vec![(argument, "value".to_string())]);
}

/// An argument that already spells the parameter needs no hint in front of it: the line says `count, factor`, and
/// `count: count, factor: factor` is the editor repeating the code back at the reader.
#[test]
fn an_argument_that_already_spells_the_parameter_is_not_hinted() {
    let source = "\
double scale(int count, double factor);
double f(int count, double factor) { return scale(count, factor); }
";
    assert!(hints_of(source).is_empty());
}

/// **A parameter with no name does not shift the ones after it.**
///
/// `void log(int, const char* message);` declares a second parameter named `message`, and the second *argument* is
/// where it belongs. A reading that dropped the unnamed parameter would put `message` against the first argument —
/// a wrong answer printed into the code, which is why the reading keeps the gap.
#[test]
fn an_unnamed_parameter_does_not_shift_the_others() {
    let source = "\
void log(int, const char* message);
void f() { log(1, \"hi\"); }
";
    let second = source.find("1, ").expect("the fixture") + "1, ".len();

    assert_eq!(
        hints_of(source),
        vec![(second, "message".to_string())],
        "the first parameter has no name, so only the second argument is hinted"
    );
}

/// A variadic tail is not a parameter, so the arguments past the named ones get nothing.
#[test]
fn a_variadic_tail_is_not_hinted() {
    let source = "\
void log(const char* format, ...);
void f() { log(\"%d %d\", 1, 2); }
";
    let format = source.find("\"%d %d\"").expect("the fixture");

    assert_eq!(
        hints_of(source),
        vec![(format, "format".to_string())],
        "the two integers have no parameter to be named after"
    );
}

/// A call through a member is the same question about the member's declaration.
#[test]
fn a_member_call_reports_the_members_parameters() {
    let source = "\
struct Widget {
    int size_of(int scale) const;
};
int f(Widget& w) { return w.size_of(3); }
";
    let argument = source.find("size_of(3").expect("the fixture") + "size_of(".len();

    assert_eq!(hints_of(source), vec![(argument, "scale".to_string())]);
}

/// **A call of a class is not a call of a function.**
///
/// `Widget(1, 2)` names a type, and a type's scope holds its *fields*, not the constructor's parameters — so a
/// hint here would label the arguments with whatever names the class happens to declare. The refusal is the scope
/// kind's: only a function scope has parameters.
#[test]
fn a_call_of_a_class_is_not_hinted() {
    let source = "\
struct Widget {
    int width;
    int height;
    Widget(int w, int h);
};
Widget make() { return Widget(3, 4); }
";
    assert!(hints_of(source).is_empty());
}

/// A callee this analysis cannot place is not guessed at: a function pointer's parameters are its type's, and this
/// layer does not read types that way.
#[test]
fn an_unresolvable_callee_is_not_hinted() {
    let source = "\
double f() { return unknown(1, 2); }
";
    assert!(hints_of(source).is_empty());
}

/// **A callee in another file.** The parameters are read from the header's own scope, which means the header is
/// parsed for the answer — and the index is what says the header declares the function at all.
#[test]
fn a_callee_in_another_file_reports_its_parameters() {
    let header = "double scale(int count, double factor);\n";
    let source = "#include \"b.h\"\ndouble f() { return scale(3, 0.5); }\n";
    let call = source.find("scale(3").expect("the fixture") + "scale(".len();

    assert_eq!(
        hints_in(&[("/p/a.cpp", source), ("/p/b.h", header)], "/p/a.cpp"),
        vec![
            (call, "count".to_string()),
            (call + "3, ".len(), "factor".to_string()),
        ]
    );
}

/// Two calls into the same header are one parse of the header and two sets of hints — a hint is about the call,
/// not about the declaration.
#[test]
fn every_call_is_hinted_separately() {
    let header = "double scale(int count, double factor);\n";
    let source = "\
#include \"b.h\"
double f() { return scale(3, 0.5); }
double g() { return scale(4, 1.5); }
";
    let hints = hints_in(&[("/p/a.cpp", source), ("/p/b.h", header)], "/p/a.cpp");

    assert_eq!(hints.len(), 4, "{hints:?}");
    assert_eq!(hints[0].1, "count");
    assert_eq!(hints[1].1, "factor");
    assert_eq!(hints[2].1, "count");
    assert_eq!(hints[3].1, "factor");
}

/// The range is the client's visible area: a hint outside it is work the client throws away, so an argument below
/// the range is not hinted even though its call starts inside it.
#[test]
fn only_arguments_inside_the_range_are_hinted() {
    let source = "\
double scale(int count, double factor);
double f() { return scale(3, 0.5); }
";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let first = source.find("scale(3").expect("the fixture") + "scale(".len();

    // A range that ends inside the first argument.
    let partial = cpp_parser::SourceRange::new(0, first + 1);
    let hints = session.inlay_hints(&view, partial);

    assert_eq!(hints.len(), 1, "{hints:?}");
    assert_eq!(hints[0].name, "count");
}

/// **A call of a variable is not a call of a function**, even inside a function whose own parameters are right
/// there in the file. `x(1)` where `x` is an `int` is nonsense C++, and it is the shape that matters: the
/// enclosing function's parameter list is the nearest one up the tree, and reading *that* would label the
/// argument `y` — a name from a different declaration, printed into the code.
#[test]
fn a_call_of_a_variable_is_not_hinted() {
    let source = "\
int f(int y) {
    int x = 0;
    return x(1);
}
";
    assert!(hints_of(source).is_empty(), "{:?}", hints_of(source));
}

/// A lambda held in a variable has parameters of its own, and they are not read: `g`'s declaration has no
/// parameter list — the list belongs to the lambda *expression*, which is a different construct — so there is
/// nothing a hint could be named after.
#[test]
fn a_call_of_a_lambda_variable_is_not_hinted() {
    let source = "\
int f() {
    auto g = [](int a) { return a; };
    return g(1);
}
";
    assert!(hints_of(source).is_empty(), "{:?}", hints_of(source));
}

/// **A member declared in a class and called through `this`.** The declaration is in the class body, the call is
/// in a member function, and the parameter names come from the declaration's own declarator — which is also the
/// path a header's member is reached by.
#[test]
fn a_member_called_through_this_is_hinted() {
    let source = "\
struct S {
    int other(int c) const;
    int go() { return this->other(2); }
};
";
    let argument = source.find("other(2").expect("the fixture") + "other(".len();

    assert_eq!(hints_of(source), vec![(argument, "c".to_string())]);
}

/// **A boundary this feature inherits.** `void (*f(int a))(int b);` declares a function, and the scope model does
/// not bind `f`: the declarator is parenthesized, and `declared_name` walks the declarator-to-name path, which
/// this shape leaves. So the call is unresolved, and an unresolved call gets no hint rather than a guess.
///
/// Pinned as a claim about the **resolution** rather than as "no hint", because which layer refuses is the
/// interesting part: the day the binding exists, the reading already takes the declarator the name is a name of —
/// the one whose list says `a`, not the list of the function it returns.
/// **A function that returns a pointer to a function is bound, and its own parameters are the ones read.**
///
/// `void (*f(int a))(int b);` declares `f` — a function of `a` returning a pointer to a function of `b` — and the walk that
/// finds a name used to stop at the parenthesised declarator, so `f` was not bound at all and `f(1)` resolved to nothing. That
/// boundary is gone: the declarator walk continues past a nested declarator that names nothing (measured tree:
/// `InitDeclarator "(*f(int a))(int b)" > Declarator "(*f(int a))" > Declarator "*f(int a)" > …`), and the **name's own**
/// parameter list is the one the hint reads — `a`, not the `b` of the function it returns.
#[test]
fn a_function_returning_a_function_pointer_is_bound() {
    let source = "void (*f(int a))(int b);\nvoid g() { f(1); }\n";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");

    assert!(
        matches!(
            session.definition(
                &view,
                cpp_code_analysis::file::coordinates::ReadingOffset::new(
                    source.rfind("f(1)").expect("the call")
                )
            ),
            cpp_code_analysis::Known::Yes(_)
        ),
        "the declaration is bound, so the call resolves"
    );
    let argument = source.rfind("f(1)").expect("the call") + "f(".len();
    assert_eq!(
        hints_of(source),
        vec![(argument, "a".to_string())],
        "the name's own parameter, not the returned function's"
    );
}

/// **A call through a function pointer is not hinted, and the parameters of its type are not read.**
///
/// `cb` is a parameter whose *type* is a function with a parameter `a`, and `cb(1)` passes `1` to that `a`. The
/// reading refuses anyway, deliberately: the parameter list belongs to the declarator the *name* is a name of, and
/// `cb`'s own declarator has none — the list is one level out, in the type. That is the boundary
/// `type_of_a_call` already has ("a call of a function pointer, of a lambda, of a template parameter" stays
/// `Unknown`), and reading through it here would make this feature the one place that trusts a type's shape.
///
/// It is also the case that tells this reading apart from "the nearest parameter list up the tree", which would
/// find `a` and hint it.
#[test]
fn a_call_through_a_function_pointer_is_not_hinted() {
    let source = "\
void h(int (*cb)(int a)) {
    cb(1);
}
";
    assert!(hints_of(source).is_empty(), "{:?}", hints_of(source));
}

/// A call whose argument list is empty has nothing to place a name at, which is not an error and not a hint.
#[test]
fn a_call_with_no_arguments_has_no_hints() {
    assert!(hints_of("int f();\nint g() { return f(); }\n").is_empty());
}

/// **The types the file does not write** — `auto`, a range-for's element, and a deduced return.
///
/// The module used to refuse these: "the analysis has no type system — nothing deduces `auto`". That stopped being true
/// when `type_at` learned to deduce from the initializer, which is why the hints are asked of the same reader the hover
/// asks. A hint that was *wrong* would be printed into the user's code, so the test asserts both what is hinted and that
/// the unanswerable shapes stay silent.
#[test]
fn the_types_the_file_does_not_write() {
    let source = "\
struct Widget { int size; };
void f() {
    auto n = 1;
    auto& r = n;
    const auto c = 2.5;
    int v[3] = {1, 2, 3};
    for (auto item : v) { }
    auto untyped = Widget{};
}
auto one() { return 1; }
";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let whole_file = cpp_parser::SourceRange::new(0, view.source.len());
    let hints = session.type_hints(&view, whole_file);
    let said: Vec<(String, cpp_code_analysis::TypeHintKind)> = hints
        .iter()
        .map(|hint| (hint.label.clone(), hint.kind))
        .collect();

    // **The whole list, in the order the walk finds the declarations.** A hint printed into the user's code is either
    // right or a lie, so the expected answer is exact rather than "contains".
    assert_eq!(
        said,
        vec![
            ("int".to_string(), cpp_code_analysis::TypeHintKind::Auto),
            ("int&".to_string(), cpp_code_analysis::TypeHintKind::Auto),
            (
                "const double".to_string(),
                cpp_code_analysis::TypeHintKind::Auto
            ),
            ("int".to_string(), cpp_code_analysis::TypeHintKind::Auto),
            ("Widget".to_string(), cpp_code_analysis::TypeHintKind::Auto),
            (
                "int".to_string(),
                cpp_code_analysis::TypeHintKind::DeducedReturn
            ),
        ],
        "`auto n`, `auto& r`, `const auto c`, the range-for's `auto item`, `auto untyped`, and `auto one()`"
    );

    // Every hint is drawn at the end of a name, so the text before it ends with one — and no hint repeats the
    // placeholder the file already writes.
    for hint in &hints {
        assert!(hint.offset <= source.len(), "inside the file");
        assert!(source.is_char_boundary(hint.offset), "a drawable position");
        assert_ne!(hint.label, "auto");
    }
}

/// **A lambda's deduced return is a hint**, and an init-capture's type comes from its initializer.
///
/// `[value = counter + 10] { return value; }` — the capture is neither a parameter nor a local, so the return walk refused
/// it and the lambda had no `-> T` hint. The initializer is an expression the same walk types, with the **enclosing
/// function's** declarations in hand (the capture is written in the function's scope, not in the variable's).
#[test]
fn a_lambdas_deduced_return_is_a_hint() {
    let source = "\
void f() {
    int counter = 0;
    auto initialised = [value = counter + 10] { return value; };
    auto noexcept_lambda = []() noexcept { return 1; };
    auto by_ref = [&counter] { ++counter; };
}
";
    let session = session_with(&[("/p/a.cpp", source)]);
    let view = session.view("/p/a.cpp").expect("the file is held");
    let whole_file = cpp_parser::SourceRange::new(0, view.source.len());
    let hints: Vec<(usize, String)> = session
        .type_hints(&view, whole_file)
        .into_iter()
        .map(|hint| (hint.offset, hint.label))
        .collect();

    // The hint sits at the body's first byte, which is the `{` after the specifiers.
    for needle in ["{ return value; }", "{ return 1; }"] {
        let at = source.find(needle).expect("the fixture");
        assert!(
            hints
                .iter()
                .any(|(offset, label)| *offset == at && label == "int"),
            "`-> int` before `{needle}`: {hints:?}"
        );
    }
    // A body with no return has nothing to deduce.
    assert!(
        !hints
            .iter()
            .any(|(_, label)| label == "void" || label.is_empty()),
        "no hint for `++counter`: {hints:?}"
    );
}