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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! **The element a range yields** — what a `for` binds, through C++20's views and algorithms.
//!
//! A view's own type is unnamed (a class template over a closure type), so nothing here tries to spell it: the question is
//! the *element*, which is what a reader writes next (`value.member`, `it->name`) and what completion needs. The shapes are
//! `ranges.cpp`'s: a pipe chain, `views::iota`, `views::keys`/`values`, `views::join`, and the `std::ranges` algorithms
//! whose answers the standard fixes.

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

/// A session over one file, cooked and indexed, so a type question reads the same tree the server would.
fn session_with(source: &str) -> (Session<MemoryFiles>, cpp_code_analysis::FileView) {
    let memory = MemoryFiles::new().with_file("/p/a.cpp", source);
    let providers = SessionFiles::new(OpenDocuments::new(), memory);
    let mut session = Session::with_config(
        "/p",
        providers,
        WatchFilter::new("/p"),
        CompilerConfig::default(),
    );
    session.load("/p/a.cpp");
    let view = session
        .view_of_the_file(std::path::Path::new("/p/a.cpp"))
        .expect("the file is held");
    (session, view)
}

/// The type of the variable whose name follows `needle`, as the engine spells it.
fn type_after(source: &str, needle: &str) -> Option<String> {
    let (session, view) = session_with(source);
    let at = source.find(needle).expect("the fixture writes it");
    session
        .type_at(
            &view,
            cpp_code_analysis::file::coordinates::ReadingOffset::new(at),
        )
        .value()
        .map(|found| found.type_of.clone())
}

/// **A pipe chain keeps the element of the range it starts from.**
#[test]
fn a_pipe_chain_keeps_the_element_of_its_left_operand() {
    let source = "
#include <ranges>
#include <vector>
int main() {
    std::vector<int> numbers{5, 3, 1};
    for (auto value : numbers | std::views::filter([](int v) { return v > 2; }) | std::views::take(2)) {
        value = 0;
    }
}
";
    assert_eq!(
        type_after(source, "value :"),
        Some("int".to_string()),
        "`numbers` yields `int`, and filter/take do not change it"
    );
}

/// **A pipeline names the view the standard fixes** — `numbers | std::views::take(2)` is a `take_view`.
///
/// The closure's own type is internal to the library (`__adaptor::_Partial<_Filter, …>`) and its second argument is an
/// unnamed closure type, so `std::views::filter(pred)` alone still has no type. A *pipe* does: the standard says which
/// view class each adaptor produces and that the range is passed through `views::all_t`.
///
/// ```text
/// numbers | std::views::take(2)      std::ranges::take_view<std::ranges::ref_view<std::vector<int>>>
/// numbers | std::views::filter(pred) std::ranges::filter_view<std::ranges::ref_view<std::vector<int>>, (lambda)>
/// ```
///
/// The position is asked of the **operator**, which is the byte whose innermost expression is the whole pipe.
#[test]
fn a_pipeline_names_the_view_the_standard_fixes() {
    let source = "
#include <ranges>
#include <vector>
int main() {
    std::vector<int> numbers{5, 3, 1};
    auto first2 = numbers | std::views::take(2);
    auto odds = numbers | std::views::filter([](int v) { return v > 2; });
    auto both = numbers | std::views::filter([](int v) { return v > 2; }) | std::views::reverse;
}
";
    assert_eq!(
        type_after(source, "| std::views::take"),
        Some("std::ranges::take_view<std::ranges::ref_view<std::vector<int>>>".to_string()),
        "an adaptor with no callable is one template argument: the range, borrowed"
    );
    assert_eq!(
        type_after(source, "| std::views::filter"),
        Some(
            "std::ranges::filter_view<std::ranges::ref_view<std::vector<int>>, (lambda)>"
                .to_string()
        ),
        "a predicate adaptor carries the callable, which a lambda describes without naming"
    );
    assert_eq!(
        type_after(source, "| std::views::reverse"),
        Some(
            "std::ranges::reverse_view<std::ranges::filter_view<std::ranges::ref_view<std::vector<int>>, (lambda)>>"
                .to_string()
        ),
        "a second adaptor takes the first view whole — `all_t` of a view is the view"
    );
}

/// **A range that is a temporary is owned, not borrowed** — `views::all_t` says `owning_view` for a prvalue.
#[test]
fn a_pipeline_over_a_temporary_owns_the_range() {
    let source = "
#include <ranges>
#include <vector>
std::vector<int> make_numbers();
int main() {
    auto first2 = make_numbers() | std::views::take(2);
}
";
    assert_eq!(
        type_after(source, "| std::views::take"),
        Some("std::ranges::take_view<std::ranges::owning_view<std::vector<int>>>".to_string()),
        "`make_numbers()` is a prvalue, so `all_t` moves it into an `owning_view`"
    );
}

/// **A pipe of a project's own is not a view.** The adaptor table is keyed on a spelling that must contain `views::`,
/// because `items | filter(x)` is a function call the project wrote and answering `filter_view` would be a type from
/// another library.
#[test]
fn a_project_own_pipe_is_not_named_as_a_view() {
    let source = "
#include <vector>
std::vector<int> filter(std::vector<int> const& values);
int main() {
    std::vector<int> numbers{1, 2};
    auto mine = numbers | filter(numbers);
}
";
    assert_eq!(
        type_after(source, "| filter"),
        None,
        "nothing in the standard says what this pipe is"
    );
}

/// **A pipeline a reader names keeps the element the pipe yields.**
///
/// `element_of_a_range_expression` answers a pipe written in place, and `for (auto v : items | …)` has always worked.
/// The ordinary style binds the view first — `auto ids = items | …` — and every later use of `ids` asked its *type*,
/// which a view has no spelling for. Measured before this: the in-place loop was `Item` and the named one `auto`.
#[test]
fn a_named_pipeline_keeps_the_element_of_its_range() {
    let source = "
#include <ranges>
#include <vector>
struct Item { int id; };
int main() {
    std::vector<Item> items;
    auto ids = items | std::views::filter([](const Item& item) { return item.id > 0; });
    for (auto value : ids) {
        value.id = 0;
    }
}
";
    assert_eq!(
        type_after(source, "value :"),
        Some("Item".to_string()),
        "`ids` is the view the in-place pipe makes, so its element is `Item`"
    );
}

/// **A pipeline of two adaptors a reader names also keeps it** — the look-through is one variable, not one adaptor.
#[test]
fn a_named_pipeline_of_two_adaptors_keeps_it_too() {
    let source = "
#include <ranges>
#include <vector>
struct Item { int id; };
int main() {
    std::vector<Item> items;
    auto ids = items | std::views::filter([](const Item& item) { return item.id > 0; }) | std::views::take(2);
    for (auto value : ids) {
        value.id = 0;
    }
}
";
    assert_eq!(type_after(source, "value :"), Some("Item".to_string()));
}

/// **A generic lambda's parameter takes the element of the range it is handed.**
///
/// `[](auto value)` has no declaration that says what `value` is: the lambda's parameter is the placeholder, and the
/// adaptor call is the only thing that knows. Measured before this: `value` was `auto`/unknown, so `value.id` resolved
/// nothing and completion inside the lambda offered nothing.
#[test]
fn a_generic_lambdas_parameter_takes_the_ranges_element() {
    let source = "
#include <ranges>
#include <vector>
struct Item { int id; };
int main() {
    std::vector<Item> items;
    auto ids = items | std::views::filter([](auto value) { return value.id > 0; });
    for (auto item : ids) {
        item.id = 0;
    }
}
";
    assert_eq!(
        type_after(source, "value.id"),
        Some("Item".to_string()),
        "`value` receives what `items` yields"
    );
}

/// **And the parameter's type is what makes a transform's element answerable** — `[](auto n)` is `int` over
/// `iota(1, 6)`, so `n * n` is an `int` and the loop variable is one too.
#[test]
fn a_generic_lambdas_parameter_feeds_the_transform_element() {
    let source = "
#include <ranges>
int main() {
    for (auto value : std::views::iota(1, 6) | std::views::transform([](auto n) { return n * n; })) {
        value = 0;
    }
}
";
    assert_eq!(type_after(source, "value :"), Some("int".to_string()));
}

/// **The parameter's reference shape is the declaration's, not the element's** — `auto&` over a container's element
/// is a `T&`, which is what the lambda body writes through.
#[test]
fn a_generic_lambdas_parameter_keeps_the_reference_it_wrote() {
    let source = "
#include <ranges>
#include <vector>
struct Item { int id; };
int main() {
    std::vector<Item> items;
    auto ids = items | std::views::filter([](auto& value) { return value.id > 0; });
    for (auto item : ids) {
        item.id = 0;
    }
}
";
    assert_eq!(type_after(source, "value.id"), Some("Item&".to_string()));
}

/// **A lambda handed to something else keeps the placeholder.** The table is the standard adaptors and algorithms
/// only: a project's own `apply(f)` says nothing about what `f` receives, and a guess there would type the body
/// against the wrong class. Measured before the table existed, and re-pinned here so a later widening has to say so.
#[test]
fn a_lambda_outside_the_standard_adaptors_keeps_its_placeholder() {
    let source = "
#include <vector>
struct Item { int id; };
struct applier { template <class F> void operator()(F f) const; };
void use(std::vector<Item> items) {
    applier{}([](auto value) { value.id = 0; });
}
";
    assert_eq!(type_after(source, "value.id"), None);
}

/// **The algorithm form writes the range first** — `std::ranges::find_if(items, f)` — and the element is the
/// first argument's, not a pipe's.
#[test]
fn a_generic_lambdas_parameter_in_an_algorithm_takes_the_first_arguments_element() {
    let source = "
namespace std {
template <class T> struct vector { };
namespace ranges { void find_if(); }
}
struct Item { int id; };
void use(std::vector<Item> items) {
    std::ranges::find_if(items, [](auto value) { value.id = 0; });
}
";
    assert_eq!(type_after(source, "value.id"), Some("Item".to_string()));
}

/// **A transform that projects a member answers that member's type** — `[](auto item) { return item.name; }`.
///
/// The parameter is `Item` now (3b), so the missing half was the *return*: a member access needs the class's member
/// list, which the syntax-only deduction does not have. Measured before this: the loop over `names` answered `auto`.
#[test]
fn a_transform_of_a_generic_lambdas_member_answers_the_members_type() {
    let source = "
#include <ranges>
#include <string>
#include <vector>
struct Item { int id; std::string name; };
int main() {
    std::vector<Item> items;
    auto names = items | std::views::transform([](auto item) { return item.name; });
    for (auto name : names) {
        name.size();
    }
}
";
    assert_eq!(
        type_after(source, "name :"),
        Some("std::string".to_string()),
        "`names` yields what `item.name` is"
    );
}

/// **The parameter does not have to be generic** — `[](const Item& item)` names its own type, and the member lookup is
/// the same question.
#[test]
fn a_transform_of_a_written_parameters_member_answers_the_members_type() {
    let source = "
#include <ranges>
#include <string>
#include <vector>
struct Item { int id; std::string name; };
int main() {
    std::vector<Item> items;
    auto names = items | std::views::transform([](const Item& item) { return item.name; });
    for (auto name : names) {
        name.size();
    }
}
";
    assert_eq!(
        type_after(source, "name :"),
        Some("std::string".to_string())
    );
}

/// **A member the class does not have stays refused** — the answer is the class's own list, not a guess from a name.
#[test]
fn a_transform_of_a_member_that_is_not_declared_stays_unknown() {
    let source = "
#include <ranges>
#include <vector>
struct Item { int id; };
int main() {
    std::vector<Item> items;
    auto names = items | std::views::transform([](auto item) { return item.missing; });
    for (auto name : names) {
        name = 0;
    }
}
";
    assert_eq!(type_after(source, "name :"), None);
}

/// **`views::iota` yields the type of its first argument.**
#[test]
fn a_counted_range_yields_its_bound() {
    let source = "
#include <ranges>
int main() {
    for (auto value : std::views::iota(1, 6)) {
        value = 0;
    }
}
";
    assert_eq!(type_after(source, "value :"), Some("int".to_string()));
}

/// **`keys` and `values` are the two halves of a map's element.**
#[test]
fn the_key_of_a_map_is_a_view_of_the_key() {
    let source = "
#include <map>
#include <ranges>
#include <string>
int main() {
    std::map<std::string, int> map;
    for (auto key : map | std::views::keys) {
        key = 0;
    }
    for (auto value : map | std::views::values) {
        value = 0;
    }
}
";
    assert_eq!(
        type_after(source, "key :"),
        Some("std::string".to_string()),
        "the key, not `std::pair<const std::string, int>`"
    );
    assert_eq!(type_after(source, "value :"), Some("int".to_string()));
}

/// **`join` flattens one level.**
#[test]
fn a_joined_range_yields_the_inner_element() {
    let source = "
#include <ranges>
#include <vector>
int main() {
    std::vector<std::vector<int>> rows;
    for (auto value : rows | std::views::join) {
        value = 0;
    }
}
";
    assert_eq!(type_after(source, "value :"), Some("int".to_string()));
}

/// **`std::ranges::find` answers the element it found** — what a reader dereferences.
#[test]
fn a_ranges_algorithm_answers_the_element() {
    let source = "
#include <ranges>
#include <vector>
struct Person { int age; };
int main() {
    std::vector<Person> people;
    auto found = std::ranges::find(people, Person{}, &Person::age);
}
";
    assert_eq!(
        type_after(source, "found ="),
        Some("Person".to_string()),
        "an iterator to the element is, to a reader, the element"
    );
}

/// **`std::ranges::size` and `distance` are counts.**
#[test]
fn the_counting_algorithms_are_ptrdiff_t() {
    let source = "
#include <ranges>
#include <vector>
int main() {
    std::vector<int> numbers;
    auto count = std::ranges::size(numbers);
    auto from = std::ranges::distance(numbers);
}
";
    assert_eq!(
        type_after(source, "count ="),
        Some("std::size_t".to_string())
    );
    assert_eq!(
        type_after(source, "from ="),
        Some("std::ptrdiff_t".to_string())
    );
}

/// **`views::transform`'s element is the lambda's return type** — the deduction `a_lambdas_return_type` already had, so
/// this is one answer rather than a guess.
#[test]
fn a_transform_answers_the_lambdas_return() {
    let source = "
#include <ranges>
#include <vector>
int main() {
    std::vector<int> numbers;
    for (auto value : numbers | std::views::transform([](int v) { return v * 10; })) {
        value = 0;
    }
}
";
    assert_eq!(
        type_after(source, "value :"),
        Some("int".to_string()),
        "`v * 10` is an `int`, and that is what the transform yields"
    );
}

/// **And a body this layer cannot type is still refused** — a transform that answers a wrong element would offer the loop
/// wrong members, which is the failure the refusal exists for.
#[test]
fn a_transform_of_an_unclearable_body_is_refused() {
    let source = "
#include <ranges>
#include <vector>
struct S { int field; };
void f(S other) {
    std::vector<int> numbers;
    for (auto value : numbers | std::views::transform([&](int v) { return other; })) {
        value = 0;
    }
}
";
    // The body returns a parameter of a **captured** object — a name this syntax walk cannot type — so the element is
    // unknown rather than `S`.
    assert_eq!(type_after(source, "value :"), None);
}