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
//! **`concept-not-satisfied`** — an argument whose type does not satisfy the concept its parameter is constrained by.
//!
//! ```cpp
//! template <std::integral T>
//! T twice(T value);
//!
//! twice("text");      // `const char*` is not `std::integral`
//! ```
//!
//! # What this decides, and what it deliberately leaves alone
//!
//! Concept satisfaction in general is the language's most expensive question: a `requires`-expression can name any
//! expression, and deciding it means instantiating templates. What this check does is the part that is **decidable
//! from the type alone** and that a reader meets constantly — the standard library's *type* concepts, whose meaning
//! is a property of the type and nothing else:
//!
//! ```text
//!   std::integral, std::signed_integral, std::unsigned_integral    an integer builtin (not a pointer, not a class)
//!   std::floating_point                                            float, double, long double
//!   std::same_as<A, B>                                             the same type
//!   std::convertible_to<From, To>                                  convertible, through the crate's one answer
//! ```
//!
//! Everything else is **silence**: a user-written concept, a `requires` clause, a constraint this file cannot read, a
//! type the analysis cannot work out. That is not a gap to be apologised for but the rule every check here follows —
//! a finding is a claim, and a claim about a concept nobody evaluated would be a guess dressed as an error.
//!
//! # Where the constraint is read from
//!
//! From the declaration's **`template <…>` head**, in one of two places: this file's tree when the declaration is
//! here, and the **summary** when it is not — `DeclFact::constraints` is the head's other half, stored beside the
//! parameter names for exactly this question. The constrained index is then found by matching the type parameter's
//! name against the parameter list's spellings, so `T value` and `const T& value` are both "the parameter `T`
//! constrains".
//!
//! Two declarations of a name are an **overload set** and are skipped: which overload's constraint applies is
//! overload resolution, and a check that guessed would be reporting on a declaration the call may not use.

use cpp_parser::{CppAstNode, CppCallExpr};

use super::{Check, CheckContext, DiagnosticCode};

/// **`concept-not-satisfied`** — see the module documentation.
pub struct ConceptNotSatisfied;

impl Check for ConceptNotSatisfied {
    const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::ConceptNotSatisfied];

    fn check(context: &mut CheckContext<'_>) {
        // **The declarations, as facts.** This file's are in its summary, and everything else is in the index — one
        // question, one shape, and no walk of two trees that could disagree.
        //
        // `DeclFact::constraints` is aligned with the *parameters*, so the answer is `constraints[at]` and nothing
        // has to be re-derived here: the pairing of a template parameter with the function parameter it constrains
        // was decided where the tree was (see `declared_constraints_with`).
        //
        // One declaration per name: a name declared twice is an overload set, and which overload's constraint
        // applies is overload resolution — not a question a check answers by position.
        for call in context.own::<CppCallExpr>().collect::<Vec<_>>() {
            let Some(callee) = call.get_callee() else {
                continue;
            };
            let Some(name) = super::callee_name_of(&callee) else {
                continue;
            };
            // Cloned because the finding below needs `&mut context`: the list is one short string per
            // parameter, and only a constrained declaration ever has a non-empty one.
            let Some(constraints) =
                constraints_of_a_declaration(context, &name).map(<[String]>::to_vec)
            else {
                continue;
            };

            for (at, argument) in call.get_args().iter().enumerate() {
                let Some(concept) = constraints
                    .get(at)
                    .filter(|written| !written.is_empty())
                    .and_then(|written| Concept::from_constraint(written))
                else {
                    continue;
                };
                let crate::Known::Yes((passed, _)) = context.type_of(argument.syntax()) else {
                    continue;
                };
                // **A template parameter is not a type this can judge.** `_Tp&&` is whatever the caller instantiates,
                // so every concept answers "not known" rather than "not satisfied": measured on libstdc++'s
                // `<compare>`, `_Tp&&` was reported as not satisfying `std::floating_point`.
                if crate::sema::convert::names_a_template_parameter_for_a_check(&passed.to_string())
                {
                    continue;
                }
                if concept.is_satisfied_by(&passed, context) != Some(false) {
                    continue;
                }

                context.add(
                    DiagnosticCode::ConceptNotSatisfied,
                    cpp_parser::source_range(argument.syntax().text_range()),
                    name.clone(),
                    t!(
                        "`%{passed}` does not satisfy `%{concept}`, which constrains the parameter this argument is \
                         passed for",
                        passed = passed.to_string(),
                        concept = concept.spelling()
                    ),
                );
            }
        }
    }
}

/// **The constraints of the one declaration of `name`**, from this file's summary or from the index.
///
/// `None` for a name this file declares twice, for one the index holds twice, and for one with no constrained
/// parameter — the three cases where the honest answer is that no constraint applies to a call.
fn constraints_of_a_declaration<'a>(
    context: &'a CheckContext<'_>,
    name: &str,
) -> Option<&'a [String]> {
    let mut own: Option<&[String]> = None;
    let mut own_declarations = 0;
    for fact in &context.summary.declarations {
        if fact.name != name || fact.parameter_list.is_none() {
            continue;
        }
        own_declarations += 1;
        own = Some(&fact.constraints);
    }
    match own_declarations {
        0 => {}
        1 => return own,
        _ => return None,
    }

    let index = context.model.index();
    let declared = index.files_declaring(name, context.path);
    let mut elsewhere: Option<&[String]> = None;
    let mut elsewhere_declarations = 0;
    for found in &declared {
        if found.fact.parameter_list.is_none() {
            continue;
        }
        elsewhere_declarations += 1;
        elsewhere = Some(&found.fact.constraints);
    }
    match elsewhere_declarations {
        1 => elsewhere,
        _ => None,
    }
}
/// **The concepts this check can decide** — a closed set, and that is the point: a name outside it is a concept this
/// layer knows nothing about, and answering `None` is what keeps the check silent about it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Concept {
    /// `std::integral`, `std::signed_integral`, `std::unsigned_integral`.
    Integral,
    /// `std::floating_point`.
    FloatingPoint,
    /// `std::same_as<A, B>`.
    SameAs(String),
    /// `std::convertible_to<From, To>`.
    ConvertibleTo(String),
    /// `std::derived_from<B>` — decided through the index, which is where a class's bases are.
    DerivedFrom(String),
    /// **The object family**: `std::default_initializable`, `move_constructible`, `copy_constructible`,
    /// `movable`, `copyable`, `semiregular`, `regular`.
    ///
    /// A class's answer needs its constructors and its assignment operators, which this layer does not read — so the
    /// only type it can answer *definitely* about is a **reference**, which satisfies none of them (`copyable<int&>`
    /// is false for the same reason `std::copyable` asks for an object type). A value type answers `None`.
    NeedsAnObjectType(&'static str),
}

impl Concept {
    /// **Which concept a constraint names**, from the head's own spelling — with or without `std::`.
    ///
    /// The split order matters and was wrong: taking the last `::` **before** cutting the template arguments finds the scope
    /// *inside* them — `std::derived_from<std::vector<int>>` answered a concept called `vector<int>>` — so the arguments are
    /// cut first, and the scope is then the head's own.
    fn from_constraint(constraint: &str) -> Option<Concept> {
        let (head, arguments) = match constraint.trim().split_once('<') {
            Some((head, rest)) => (head.trim(), Some(rest.trim_end_matches('>'))),
            None => (constraint.trim(), None),
        };
        let name = head.rsplit("::").next().unwrap_or(head).trim();

        match name {
            "integral" | "signed_integral" | "unsigned_integral" => Some(Concept::Integral),
            "floating_point" => Some(Concept::FloatingPoint),
            "same_as" => {
                let arguments = split_at_top_level_commas(arguments?);
                Some(Concept::SameAs(arguments.first()?.trim().to_string()))
            }
            "convertible_to" => {
                let arguments = split_at_top_level_commas(arguments?);
                Some(Concept::ConvertibleTo(
                    arguments.first()?.trim().to_string(),
                ))
            }
            "derived_from" => {
                let arguments = split_at_top_level_commas(arguments?);
                Some(Concept::DerivedFrom(arguments.first()?.trim().to_string()))
            }
            "default_initializable"
            | "move_constructible"
            | "copy_constructible"
            | "movable"
            | "copyable"
            | "semiregular"
            | "regular" => Some(Concept::NeedsAnObjectType(match name {
                "default_initializable" => "std::default_initializable",
                "move_constructible" => "std::move_constructible",
                "copy_constructible" => "std::copy_constructible",
                "movable" => "std::movable",
                "copyable" => "std::copyable",
                "semiregular" => "std::semiregular",
                _ => "std::regular",
            })),
            _ => None,
        }
    }

    fn spelling(&self) -> String {
        match self {
            Concept::Integral => "std::integral".to_string(),
            Concept::FloatingPoint => "std::floating_point".to_string(),
            Concept::SameAs(other) => format!("std::same_as<{other}>"),
            Concept::ConvertibleTo(other) => format!("std::convertible_to<{other}>"),
            Concept::DerivedFrom(other) => format!("std::derived_from<{other}>"),
            Concept::NeedsAnObjectType(spelling) => spelling.to_string(),
        }
    }

    /// `Some(false)` only when the type **definitely** does not satisfy it; `Some(true)` and `None` both keep the
    /// check quiet, and `None` is what every type the analysis cannot work out answers.
    fn is_satisfied_by(
        &self,
        passed: &crate::sema::types::Type,
        context: &CheckContext<'_>,
    ) -> Option<bool> {
        match self {
            Concept::Integral => Some(is_an_integer(passed)),
            Concept::FloatingPoint => Some(is_a_floating_point(passed)),
            Concept::SameAs(declared) => {
                let declared = crate::sema::types::parse_type_spelling(declared);
                match passed.convertible_to(&declared) {
                    crate::Known::No => Some(false),
                    crate::Known::Yes(()) => Some(passed.to_string() == declared.to_string()),
                    crate::Known::Unknown(_) => None,
                }
            }
            Concept::DerivedFrom(base) => derives_from(context, passed, base),
            Concept::NeedsAnObjectType(_) => {
                // **A reference satisfies none of them**, and that is the whole of what this answers: a value type needs
                // its constructors, which this layer does not read. Asked of the type's **variant** — a reference is
                // `Type::Reference`, and `passed.to_string().contains('&')` was a second reader of that fact, one that
                // answered "not an object" for any spelling that happened to carry an `&` (a `decltype(x) &`, a template
                // argument named one) and "an object" for an array, which is not copyable either way.
                match passed {
                    crate::sema::types::Type::Reference { .. } => Some(false),
                    // An array and a function are not object types either, and this layer cannot decide them: saying
                    // nothing is the direction every arm here takes when it would be guessing.
                    crate::sema::types::Type::Array { .. } => None,
                    _ => Some(true),
                }
            }
            Concept::ConvertibleTo(target) => {
                let target = crate::sema::types::parse_type_spelling(target);
                match passed.convertible_to(&target) {
                    // The class case goes through the shared facility, exactly as `param-type-check` asks it — a
                    // class nobody has read answers `Unknown` there and stays quiet here.
                    crate::Known::No => Some(false),
                    crate::Known::Yes(()) => Some(true),
                    crate::Known::Unknown(_) => Some(!matches!(
                        crate::sema::convert::conversion(passed, &target.to_string(), |_| None),
                        crate::sema::convert::Conversion::Refused
                    )),
                }
            }
        }
    }
}

/// **The spelling of a type that is a plain name** — `Some("int")` for `Type::Builtin`, `Some("size_t")` for a
/// `Type::Named` with no arguments; `None` for a pointer, a reference, an array, a function or a pack.
///
/// The **tree's own reading**, not a scan for `*` and `&`: `Type` has a variant for each of those, and asking the
/// string whether it contains an asterisk is a second reader of the same fact — one that disagrees with the first
/// the day a type is spelled `decltype(p)` or `int (*)(int)`.
fn plain_type_spelling(passed: &crate::sema::types::Type) -> Option<String> {
    match passed {
        crate::sema::types::Type::Builtin { spelling } => Some(spelling.clone()),
        crate::sema::types::Type::Named { name, arguments } if arguments.is_empty() => {
            Some(name.clone())
        }
        _ => None,
    }
}

/// **Is this type one of the language's integer types?**
///
/// `std::integral` is true for the builtin integer types and their standard spellings, and false for a pointer, a
/// reference, an enumeration and a class — which is what this answers, from the type's own shape and then from the
/// names the standard gives the same types (`size_t`, `int64_t`).
fn is_an_integer(passed: &crate::sema::types::Type) -> bool {
    let Some(spelling) = plain_type_spelling(passed) else {
        return false;
    };

    matches!(
        spelling.as_str(),
        "bool"
            | "char"
            | "signed char"
            | "unsigned char"
            | "wchar_t"
            | "char8_t"
            | "char16_t"
            | "char32_t"
            | "short"
            | "short int"
            | "signed short"
            | "signed short int"
            | "unsigned short"
            | "unsigned short int"
            | "int"
            | "signed"
            | "signed int"
            | "unsigned"
            | "unsigned int"
            | "long"
            | "long int"
            | "signed long"
            | "signed long int"
            | "unsigned long"
            | "unsigned long int"
            | "long long"
            | "long long int"
            | "signed long long"
            | "signed long long int"
            | "unsigned long long"
            | "unsigned long long int"
            | "size_t"
            | "ptrdiff_t"
            | "intptr_t"
            | "uintptr_t"
            | "int8_t"
            | "int16_t"
            | "int32_t"
            | "int64_t"
            | "uint8_t"
            | "uint16_t"
            | "uint32_t"
            | "uint64_t"
    )
}

fn is_a_floating_point(passed: &crate::sema::types::Type) -> bool {
    let Some(spelling) = plain_type_spelling(passed) else {
        return false;
    };
    matches!(spelling.as_str(), "float" | "double" | "long double")
}
/// Splits `a, b` into its parts, ignoring the commas inside `<>`, `()` and `[]`.
fn split_at_top_level_commas(text: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut depth = 0isize;
    let mut start = 0usize;
    for (at, character) in text.char_indices() {
        match character {
            '<' | '(' | '[' => depth += 1,
            '>' | ')' | ']' => depth -= 1,
            ',' if depth == 0 => {
                parts.push(text[start..at].to_string());
                start = at + 1;
            }
            _ => {}
        }
    }
    parts.push(text[start..].to_string());
    parts
}

/// **Is `derived` a class derived from `base`?** — through the index, which is where a class's bases are recorded.
///
/// `None` when the walk cannot answer: a class nobody has described, a chain deeper than the bound. `Some(false)`
/// only when every class on the way was read and none of them is the base — which is what makes a builtin or a
/// pointer a definite `false` without asking anything.
fn derives_from(
    context: &CheckContext<'_>,
    derived: &crate::sema::types::Type,
    base: &str,
) -> Option<bool> {
    use crate::sema::types::Type;

    let Type::Named { name, arguments } = derived else {
        // A builtin, a pointer, a reference, an array: none of them is a class, and `derived_from` needs one.
        return Some(false);
    };
    if !arguments.is_empty() {
        // `derived_from<B> vector<int>` asks whether the *instantiation* derives from `B`; the index is keyed by the
        // template's own name, and guessing here would be a claim about a type nobody instantiated.
        return None;
    }

    let index = context.model.index();
    let base = the_class_name(base);

    let mut waiting = vec![name.clone()];
    let mut seen = std::collections::HashSet::new();
    let mut answered = true;

    while let Some(class) = waiting.pop() {
        if !seen.insert(class.clone()) {
            continue;
        }
        if the_class_name(&class) == base {
            return Some(true);
        }

        let declared = index.files_declaring(&class, context.path);
        let mut found = None;
        let mut declarations = 0;
        for visible in &declared {
            if visible.fact.kind != crate::DeclKind::Type {
                continue;
            }
            declarations += 1;
            found = Some(&visible.fact);
        }
        let (true, 1) = (answered, declarations) else {
            answered = false;
            continue;
        };
        let Some(fact) = found else {
            answered = false;
            continue;
        };

        for written in &fact.bases {
            // **A base clause is the base's *name***: the fact stores it as one (`shape.bases` is the `CppBaseSpecifier`'s
            // name node, written as the reader spelled it), so there is no access keyword to strip. What it may carry is
            // template arguments and a scope — `std::vector<int>` — and this question is about the class's own name, which
            // is what [`the_class_name`] leaves. Splitting on whitespace, which this did, took `Base>` from
            // `conditional_t<true, X, Base>` and then looked up a class with that name.
            waiting.push(the_class_name(written).to_string());
        }
    }

    answered.then_some(false)
}

/// **A class's own name** — `ns::B<int>` → `B`.
///
/// The template arguments and the scope are not part of the identity this question asks about: a base clause writes
/// `std::vector<int>` and the constraint writes `std::derived_from<vector<int>>`, and both name the class `vector`.
fn the_class_name(written: &str) -> &str {
    let name = written.trim();
    let name = name.split('<').next().unwrap_or(name).trim();
    name.rsplit("::").next().unwrap_or(name).trim()
}