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
//! **What a class costs in memory**, as the hover card shows it: the size, the alignment, and the offset of every data
//! member — the question rust-analyzer answers on a struct and C++ readers ask constantly.

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

/// The layout of `name` in a one-file fixture.
fn layout(source: &str, name: &str) -> cpp_code_analysis::sema::layout::ClassLayout {
    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.add_project_files([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 file is read");
    match session.the_layout_of(&view, name) {
        Known::Yes(layout) => {
            eprintln!("[layout] {name}: {layout:?}");
            layout
        }
        other => panic!("`{name}` has no layout: {other:?}"),
    }
}

/// **The rule a struct is laid out by**: each member at the next multiple of its own alignment, and the class rounded
/// up to the largest one.
#[test]
fn a_struct_lays_its_members_out_by_alignment() {
    let layout = layout(
        "\
struct Widget {
    int x;
    double y;
    char c;
    int *p;
    short arr[3];
};
",
        "Widget",
    );
    assert_eq!(layout.size, 40, "38 rounded up to the alignment of 8");
    assert_eq!(layout.alignment, 8);
    let placed: Vec<(&str, usize, usize)> = layout
        .fields
        .iter()
        .map(|field| (field.name.as_str(), field.offset, field.size))
        .collect();
    assert_eq!(
        placed,
        [
            ("x", 0, 4),
            ("y", 8, 8),
            ("c", 16, 1),
            ("p", 24, 8),
            ("arr", 32, 6),
        ]
    );
}

/// **A union** puts everything at 0 and is as large as its largest member.
#[test]
fn a_union_is_as_large_as_its_largest_member() {
    let layout = layout(
        "\
union Value {
    int i;
    double d;
    char raw[3];
};
",
        "Value",
    );
    assert_eq!(layout.size, 8);
    assert_eq!(layout.alignment, 8);
    assert!(layout.union);
    assert!(layout.fields.iter().all(|field| field.offset == 0));
}

/// **A nested class is sized by its own layout**, so a member of a member's type is placed correctly.
#[test]
fn a_member_whose_type_is_a_class_is_sized_by_that_class() {
    let layout = layout(
        "\
struct Point { int x; int y; };
struct Line { Point from; Point to; char tag; };
",
        "Line",
    );
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| (field.name.as_str(), field.offset, field.size))
            .collect::<Vec<_>>(),
        [("from", 0, 8), ("to", 8, 8), ("tag", 16, 1)]
    );
    assert_eq!(layout.size, 20);
}

/// **A member nothing can size withholds the layout**: the unknown member is named and no size is invented.
#[test]
fn a_member_that_cannot_be_sized_is_named_rather_than_guessed() {
    let layout = layout(
        "\
struct Holder {
    int x;
    Unknown w;
};
",
        "Holder",
    );
    assert_eq!(layout.unknown, ["w"]);
    // The known member is still placed, which is what the card shows beside the note.
    assert_eq!(layout.fields.len(), 1);
}

/// **A bitfield withholds it too**, because a fact carries no width and every offset after one would be wrong.
#[test]
fn a_bitfield_member_is_named_rather_than_placed_wrongly() {
    let layout = layout(
        "\
struct Flags {
    unsigned int a : 3;
    unsigned int b : 5;
    int tail;
};
",
        "Flags",
    );
    assert_eq!(layout.unknown, ["a", "b"]);
}

/// **An empty class is one byte**, which is the language's rule rather than arithmetic.
#[test]
fn an_empty_class_is_one_byte() {
    let layout = layout("struct Empty {};\n", "Empty");
    assert_eq!(layout.size, 1);
    assert_eq!(layout.alignment, 1);
}
/// **A typedef is the type it names**, which is how most real C writes its members: `pos_T b_op_start` is a struct.
#[test]
fn a_member_whose_type_is_a_typedef_is_sized_through_it() {
    let layout = layout(
        "\
struct Inner { int x; int y; };
typedef Inner Alias;
struct Outer { Alias a; char c; };
",
        "Outer",
    );
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| (field.name.as_str(), field.offset, field.size))
            .collect::<Vec<_>>(),
        [("a", 0, 8), ("c", 8, 1)]
    );
    assert_eq!(layout.size, 12);
}

/// **A member written in one of the class's own template parameters is not sized**, and the layout says so instead of
/// printing a number beside a guess.
///
/// The lookup that sized it used to resolve the parameter's spelling by *bare name against the asking file*, where
/// some other class may well be called _Ty2 — measured on std::vector<widget::Widget>, whose card said
/// "size 9 byte(s), alignment 1" built from _Mypair's 9. See [ClassLayout::unknown].
#[test]
fn a_member_written_in_a_template_parameter_is_unknown() {
    let layout = layout(
        "\
template <class _Ty1, class _Ty2>
struct _Compressed_pair {
    _Ty2 _Mysecond;
};
template <class _Ty>
struct Box {
    _Compressed_pair<int, _Ty> pair;
    _Ty value;
    int tail;
};
",
        "Box",
    );
    assert_eq!(
        layout.unknown,
        ["pair", "value"],
        "the two dependent members are not sized"
    );
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| field.name.as_str())
            .collect::<Vec<_>>(),
        ["tail"],
        "the members that *can* be sized are still placed"
    );
}

/// **A template-id whose member cannot be sized is unknown** — the instantiation is attempted, and a member written
/// in a parameter whose argument names nothing is where it stops. (`Holder<int>` itself is sized: see
/// `a_member_whose_type_is_an_instantiation_is_sized`.)
#[test]
fn a_member_whose_type_is_a_template_id_is_unknown() {
    let layout = layout(
        "\
template <class T> struct Holder { T value; };
struct Outer {
    Holder<NoSuchType> first;
    int second;
};
",
        "Outer",
    );
    assert_eq!(layout.unknown, ["first"]);
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| field.name.as_str())
            .collect::<Vec<_>>(),
        ["second"]
    );
}

/// **A class template instance is sized from its members with the arguments substituted** — `Holder<double>` is
/// whatever `T value` is for `double`, plus its own `count`.
#[test]
fn a_member_whose_type_is_an_instantiation_is_sized() {
    let layout = layout(
        "\
template <class T>
struct Holder {
    T value;
    int count;
};
struct Outer {
    Holder<double> holder;
    int tail;
};
",
        "Outer",
    );
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| (field.name.as_str(), field.offset, field.size))
            .collect::<Vec<_>>(),
        [("holder", 0, 16), ("tail", 16, 4)]
    );
    assert_eq!(layout.size, 24);
}

/// **A member alias of the instantiation is followed** — `using I = Inner<T>` inside `Outer2<T>` is `Inner<double>` at
/// the use, not the alias's own unsized spelling.
#[test]
fn a_member_whose_type_is_an_alias_of_an_instantiation_is_sized() {
    let layout = layout(
        "\
template <class T>
struct Inner {
    T a;
    T b;
};
template <class T>
struct Outer2 {
    using I = Inner<T>;
    I inner;
    int tail;
};
struct Use {
    Outer2<double> o;
};
",
        "Use",
    );
    assert_eq!(
        layout.size, 24,
        "inner is 16 bytes and the tail lands at 16"
    );
    assert_eq!(layout.alignment, 8);
}

/// **A pointer member of a template is eight bytes whatever the parameter is** — the substitution makes `T*` a
/// pointer, and a pointer's size does not depend on the pointee.
#[test]
fn a_pointer_member_of_a_template_is_a_word() {
    let layout = layout(
        "\
template <class T>
struct Vec {
    T* first;
    T* last;
};
struct Use2 {
    Vec<int> v;
};
",
        "Use2",
    );
    assert_eq!(layout.size, 16);
    assert_eq!(layout.alignment, 8);
}

/// **An empty base costs nothing** — the empty-base optimization, which is why `_Compressed_pair`'s `_Ty1` does not
/// make `std::vector` nine bytes.
#[test]
fn an_empty_base_of_a_template_costs_nothing() {
    let layout = layout(
        "\
struct Empty {};
template <class T>
struct WithBase : Empty {
    T value;
};
struct Use3 {
    WithBase<double> w;
};
",
        "Use3",
    );
    assert_eq!(layout.size, 8);
    assert_eq!(layout.alignment, 8);
}

/// **An alias template is what it names** — `template <class T> using Slot = Blob;` makes `Slot<int>` a `Blob`, and a
/// class template's *instance* is not the only spelling a member's type takes.
#[test]
fn a_member_whose_type_is_an_alias_template_is_sized() {
    let layout = layout(
        "\
struct Blob {
    int first;
    int second;
};
template <class T>
using Slot = Blob;
struct Use6 {
    Slot<double> slot;
    int tail;
};
",
        "Use6",
    );
    assert_eq!(layout.size, 12);
    assert_eq!(
        layout
            .fields
            .iter()
            .map(|field| (field.name.as_str(), field.offset))
            .collect::<Vec<_>>(),
        [("slot", 0), ("tail", 8)]
    );
}

/// **A base that is a template *parameter* costs nothing when the argument is empty** — the `_Compressed_pair<_Ty1,
/// _Ty2>` shape, which is what a standard container is built on.
#[test]
fn a_parameter_base_bound_to_an_empty_class_costs_nothing() {
    let layout = layout(
        "\
struct Empty {};
template <class B, class T>
struct Pair : private B {
    T second;
};
struct Use5 {
    Pair<Empty, double> p;
};
",
        "Use5",
    );
    assert_eq!(layout.size, 8);
    assert_eq!(layout.alignment, 8);
}

/// **A base with data is withheld, not guessed** — it would have to be laid at offset zero ahead of the members, and a
/// layout that ignored it would be too small.
#[test]
fn a_base_with_data_withholds_the_layout() {
    let layout = layout(
        "\
struct HasData {
    int x;
};
template <class T>
struct WithDataBase : HasData {
    T value;
};
",
        "WithDataBase<double>",
    );
    assert!(
        layout.unknown.iter().any(|name| name.contains("base")),
        "the base is named as unsized: {:?}",
        layout.unknown
    );
}