diff --git a/Cargo.toml b/Cargo.toml index 17ec1fa3..12943fbc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,7 +31,7 @@ lsp-server = "0.10.0" lsp_types = { version = "0.1.0", package = "emmy_lsp_types" } tokio = { version = "1.54", features = ["full"] } tokio-util = "0.7.20" -serde = { version = "1.0.229", features = ["derive"] } +serde = { version = "1.0.229", features = ["derive", "rc"] } serde_json = "1.0.154" rowan = { version = "0.17.0" } glob = "0.3" diff --git a/crates/cpp_code_analysis/src/cache/mod.rs b/crates/cpp_code_analysis/src/cache/mod.rs index e63b5311..a641b83e 100644 --- a/crates/cpp_code_analysis/src/cache/mod.rs +++ b/crates/cpp_code_analysis/src/cache/mod.rs @@ -477,7 +477,7 @@ use std::path::{Path, PathBuf}; /// /// # Why this moved to 65 /// -/// **A stored parameter list dropped its comments.** `tidy_list_text` collapses a declaration`s layout into one line, +/// **A stored parameter list dropped its comments.** The display renderer collapses a declaration's layout into one line, /// and a comment written between two parameters stayed in it: `parameters_in` then split at the comma *inside* the /// comment, and a parameter`s spelling became "`if not null */ sqlite3_value *`" — measured on sqlite, six /// `param-type-check` findings about a type no file writes. A summary is keyed by content and context, neither of diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 30eec791..5a871c2b 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -32,6 +32,8 @@ use crate::Token; use crate::cache; use crate::condition; use crate::index; +use crate::index::params::{ParameterFact, ParamsId, ParamsStore}; +use crate::index::types::ComputedType; use crate::macros; use crate::paths; use crate::preprocess; @@ -53,6 +55,7 @@ use cpp_parser::lex; use cpp_toolchain::FeatureProbe; use smol_str::SmolStr; use std::path::Path; +use std::sync::Arc; use crate::Marked; use crate::cache::SummaryKey; @@ -92,8 +95,11 @@ impl DeclModifiers { pub const MAYBE_UNUSED: Self = Self(1 << 9); /// `[[nodiscard]]`. pub const NODISCARD: Self = Self(1 << 10); - /// A function with a variadic parameter list — `void log(const char*, ...)` or a parameter pack. - pub const VARIADIC: Self = Self(1 << 11); + // **Bit 11 was `VARIADIC`, and it is retired rather than reused.** It marked a declaration with a variadic + // parameter list, which is a property of the **list** and not of the declaration's written modifiers: a list may + // be variadic with no parameter writing a pack marker (`void f(...)`), and a pack parameter writes the marker + // inside the parameter rather than after the list. The answer lives on `DeclFact::variadic_parameters` now, and + // the bit stays unused so a persisted `u32` cannot change meaning under an old name. pub const DELETED: Self = Self(1 << 12); pub const DEFAULTED: Self = Self(1 << 13); /// **A member function declared `const`** — `T sum() const`. Written after the parameter list, which is why it was @@ -131,6 +137,61 @@ impl DeclModifiers { self.0 == 0 } } + +/// **The type a declaration carries** — the value itself, or the honest absence of one. +/// +/// This is deliberately **not** a handle into a type arena. A [`DeclFact`] moves between a summary, a cooked +/// reading, the index's synthetic arena, a query's display copy and the on-disk codec, and a handle is only +/// meaningful beside the table that issued it. An immutable [`ComputedType`] is a value: it can be cloned into +/// any of those containers, shared through `Arc`, encoded beside the fact, and read by a consumer with no +/// `ProjectIndex` in hand at all. There is no second representation and no id space, so no two arenas can alias. +/// +/// The enum keeps the two states named: [`DeclaredType::None`] is "the declaration states no type, or none this +/// reading could reach", and [`DeclaredType::Computed`] is the type the builder lowered from the declaration's own +/// syntax. Both are eight bytes, because `Arc`'s non-null niche fills the `Option`-shaped hole. +/// +/// The same representation is used by [`DeclFact::type_of`]/[`DeclFact::returns`] and by +/// [`crate::index::params::ParameterFact::type_of`]. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] +pub enum DeclaredType { + /// The declaration states no type, or none this reading could reach. + #[default] + None, + /// The type itself, lowered from the declaration's syntax once at the construction edge. + Computed(Arc), +} + +impl DeclaredType { + /// Is there no type at all? + pub fn is_none(&self) -> bool { + matches!(self, Self::None) + } + + /// The value this type holds, when there is one. + pub fn computed(&self) -> Option<&Arc> { + match self { + Self::Computed(computed) => Some(computed), + Self::None => None, + } + } + + /// Does this value carry a type at all? + pub fn has_value(&self) -> bool { + !self.is_none() + } + + /// **The type as the computation layer works on it**, cloned out of the fact. Nothing is parsed and no + /// table is consulted: the value is already the immutable [`ComputedType`] the builder lowered. + pub fn as_computed(&self) -> Option { + self.computed().map(|computed| (**computed).clone()) + } + + /// A lowered type, or [`DeclaredType::None`] when the declaration stated none. + pub fn from_computed(computed: Option) -> Self { + computed.map_or(Self::None, |computed| Self::Computed(Arc::new(computed))) + } +} + /// A declaration the file writes: enough to find it, name it, and say what kind of thing it is. /// /// Deliberately not a syntax tree and not a type: the fields are the ones a *query* needs — where to jump, what to @@ -219,7 +280,7 @@ pub struct DeclFact { /// so the fact of a callee in another file may not exist yet. A second pass could close it, and until then this /// answers the case that matters — the helper whose whole job is to free. pub frees: u16, - /// The type a variable-like declaration was written with, as the file spells it. + /// **The type a variable-like declaration was written with** — see [`DeclaredType`]. /// /// The first field in a fact that is not simply "what the file says about this name" but "what the file says /// about the *type* of it", and it exists for one query: `widget.size` is answered by finding `Widget` and @@ -227,41 +288,65 @@ pub struct DeclFact { /// /// Three limits, all deliberate: /// - /// * **As written, not resolved.** `Widget`, `ns::Widget` and `std::vector` are stored as spelled, so a - /// consumer resolves them with the qualified-name machinery that already exists — and gets `Unknown` where - /// that machinery cannot go, rather than a guess. + /// * **A value, not a spelling.** The fact carries the immutable [`ComputedType`] the builder lowered from + /// the declaration's syntax once at the construction edge — no handle, no arena, and no source-spelling side + /// table. The same value travels to every container the fact does: a summary, a cooked reading, a query's + /// display copy, and the on-disk cache. Display is [`ComputedType`]'s canonical `Display`. /// * **Only for variables, fields and parameters.** A class or a function declares no type in this sense: a /// class *is* one and a function *returns* one, and those spellings live in a different part of the syntax. - /// `None` is the honest answer for them. + /// [`DeclaredType::None`] is the honest answer for them. /// * **Declaration specifiers are stripped.** `static const Widget` records `Widget`, because a specifier is /// not part of the type's name and a lookup by name is what this is for. `unsigned long` survives, because /// there the words *are* the type. - pub type_of: Option, - /// The type a **function** returns, as the file spells it. /// - /// The other half of [`DeclFact::type_of`], and separate from it for the reason that field's documentation - /// gives: a class *is* a type and a function *returns* one, so `Widget make();` has no `type_of` — `make` is - /// not a `Widget` and has no members — while its `returns` is what the *call* `make()` has. Collapsing the two - /// would make `make.size` resolve as if the function were the object. + pub type_of: DeclaredType, + /// The type a **function** returns, by the same rule as [`DeclFact::type_of`] — see [`DeclaredType`]. /// - /// It exists for one query: `make().size` is answered by finding what `make` returns and then `size` inside - /// that, and nothing else in a fact says how to get from a call to a type. - /// - /// Same limits as `type_of`: **as written**, so a consumer resolves it with the qualified-name machinery and - /// gets `Unknown` where that cannot go; declaration specifiers stripped (`static inline Widget make()` records - /// `Widget`); `None` for everything that is not a function. + /// Separate from `type_of` for the reason that field's documentation gives: a class *is* a type and a + /// function *returns* one, so `Widget make();` has no `type_of` — `make` is not a `Widget` and has no + /// members — while its `returns` is what the *call* `make()` has. Collapsing the two would make `make.size` + /// resolve as if the function were the object. /// /// A **trailing return type wins**, and it is the reason this cannot be read out of the specifier sequence /// alone: `auto make() -> Widget` spells the type after the parameter list, so the specifiers say `auto`. - /// `None` for a return type the file does not state — `auto make() { … }` is deduced, and `auto` is not a - /// class anything can be looked up in. - pub returns: Option, + /// [`DeclaredType::None`] for a return type the file does not state — `auto make() { … }` is deduced, and + /// `auto` is not a class anything can be looked up in. + pub returns: DeclaredType, + /// The parameter-list handle in the arena that owns this fact — a summary's or a cooked reading's `ParamsStore`; + /// `NONE` when there is no list. A synthesized fact has no store, and its list is carried by the index's + /// synthetic arena instead (see [`crate::ProjectIndex::parameter_facts_of`]). + pub parameters: ParamsId, + /// **Does the declaration's list write the C-style `...`** — `void f(int, ...)` and `void f(...)` alike? + /// + /// # Why it is on the fact rather than in the parameter arena + /// + /// The ellipsis is a **token of the parameter list**, not a parameter: `void f(int, ...)` has one `CppParam` and a + /// `...` beside it, and `void f(...)` has no parameter at all. It is therefore not a + /// [`crate::index::params::ParameterFact`], and the list's [`ParamsId`] cannot answer for it alone: a fact does + /// not always have an arena that travels with it. A view-made fact carries its list in the index's synthetic + /// arena, and a copy a query builds ([`crate::sema::declarations::facts_with_their_types`]) deliberately clears + /// its `ParamsId` because the store that issued it is dropped. A bit on the fact is the one representation every + /// one of those paths keeps, and it is independent of the handle — `(...)` is a variadic list with **no** + /// parameter, so `variadic_parameters: true` beside [`ParamsId::NONE`] is the honest shape. + /// + /// # It is not the parameter pack + /// + /// [`crate::index::params::ParameterFact::pack`] is a property of **one parameter**: `T... rest` and + /// `Args&&... args` write the marker inside the parameter, and their list is not variadic + /// ([`cpp_parser::CppParamList::is_variadic`] asks the list's own direct token). Both syntaxes make a callee + /// accept a variable number of arguments, so a ranking ORs the two + /// ([`crate::sema::overload::DeclaredParameters::variadic`]); the facts keep them apart because one is a list's + /// marker and the other is a parameter's. + /// + /// Set once, from the declaration's own `CppParamList`, by both fact builders — the summary's + /// (`crate::sema::declarations`) and the view synthesizer's (`crate::index::project`). + pub variadic_parameters: bool, /// **Does the file's own text state this declaration's type across a directive?** /// /// `bits/stl_bvector.h` writes `emplace_back`'s return type as `#if __cplusplus > 201402L … reference … #else /// void … #endif`, and the written reading — which cannot know which branch is live, because that needs the /// compiler configuration a summary is deliberately not keyed by — has no single type to report: [`DeclFact::returns`] - /// and [`DeclFact::type_of`] are `None` for such a declaration instead of one branch's answer. + /// and [`DeclFact::type_of`] are [`DeclaredType::None`] for such a declaration instead of one branch's answer. /// /// This flag is how a consumer tells that apart from `auto` (also `None`, and nothing to ask) and from a /// declaration that simply states no type. A consumer holding a **rendering** — the reading where the directive is @@ -378,8 +463,12 @@ pub struct DeclFact { /// **The fields of a [`DeclFact`] that most declarations do not have** — boxed as a group, see [`DeclFact::detail`]. /// **Spellings in a detail are `SmolStr` because a detail is storage.** A declaration's detail is kept in a /// summary, cloned by queries and written to the cache; a short spelling lives inline, and a long one is an -/// `Arc` whose clone is a refcount. The fields that remain `Vec` are the substitution inputs whose -/// consumers still take `&[String]` — they are the next API to move, not a different storage decision. +/// `Arc` whose clone is a refcount. The vector fields are `Vec` too, and the substitution APIs take +/// `impl AsRef`, so a query no longer copies a short parameter or base into a heap `String`. +/// [`DeclDetail::constraint_facts`] is the exception a type answer has to be: its arguments are +/// [`ConstraintArgument`] values, so a type argument is a [`ComputedType`] and a value argument stays the text the +/// file wrote — the alternative was storing a spelling a consumer would have to parse back into a type, or worse, +/// calling a value a type. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct DeclDetail { /// The **qualified** name of the namespace this declaration is written in, when that is not its scope. @@ -387,17 +476,29 @@ pub struct DeclDetail { /// The class of a function declared out of line — `Widget` in `int Widget::size() const`. pub returns_in_the_class: Option, /// The **named** bases of a class-like definition, in the order the file wrote them. - pub bases: Vec, + pub bases: Vec, /// A reflection annotation — `UCLASS(Blueprintable)` — when the declaration carries one. pub reflection: Option, /// The template parameter names of a template declaration, and of a member of a class template. - pub parameters: Vec, - /// The constraints a `template <…>` head writes after its parameters. - pub constraints: Vec, + pub parameters: Vec, + /// The constraints a `template <…>` head writes after its parameters — the **display** strings. + /// + /// Aligned with the declaration's **parameters**, position for position, with `""` where a parameter is + /// unconstrained: `["std::integral", ""]` for `template T twice(T a, int n)`. The structured + /// form a check reads is [`DeclDetail::constraint_facts`]; this is the spelling a message or a test may show. + pub constraints: Vec, + /// **The same constraints, structurally** — see [`ConstraintFact`]. + /// + /// Aligned with [`DeclDetail::constraints`] position for position, so `constraint_facts[at]` is what the + /// parameter at `at` was constrained by. `None` for an unconstrained parameter, and for a constraint this layer + /// could not lower from its syntax. A consumer must read this rather than splitting [`DeclDetail::constraints`]: + /// the strings are display, and parsing one back is exactly the round trip this field removes — it cannot tell a + /// type argument from a value one, which [`ConstraintArgument`] can. + pub constraint_facts: Vec>, /// The `requires`-clause written after a function's parameter list, or in a template head. pub requires_clause: Option, /// The default arguments of [`DeclDetail::parameters`], position for position. - pub parameter_defaults: Vec, + pub parameter_defaults: Vec, /// A class template's written pattern with its arguments — `map<_Kty, _Ty>`. pub pattern: Option, /// The parameter list as the file spells it, parentheses included. @@ -424,6 +525,7 @@ impl DeclDetail { && self.reflection.is_none() && self.parameters.is_empty() && self.constraints.is_empty() + && self.constraint_facts.is_empty() && self.requires_clause.is_none() && self.parameter_defaults.is_empty() && self.pattern.is_none() @@ -431,6 +533,74 @@ impl DeclDetail { } } +/// **One concept constraint, as the declaration's syntax wrote it** — the structured half of +/// [`DeclDetail::constraints`]. +/// +/// A `template ` head writes a **concept** in front of the parameter's name, and the concept may +/// carry arguments: `std::same_as`, `std::convertible_to`, `SomeConcept<42>`. The names and arguments come +/// from the [`CppTemplateParam`]'s own type nodes when the fact is built — see +/// `sema::types::template_parameters_with_defaults` — so a check at a call site reads a [`ConstraintArgument`], +/// exactly the way every other type answer in this crate reads a [`ComputedType`], instead of splitting a spelling. +/// +/// [`CppTemplateParam`]: cpp_parser::CppTemplateParam +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ConstraintFact { + /// The concept's **last** name segment: `integral` for `std::integral`, `same_as` for + /// `std::ranges::same_as`. A consumer that decides concept satisfaction matches this, and a name outside its + /// set is a concept it knows nothing about. + pub concept: SmolStr, + /// **Every argument the concept wrote**, in the order it wrote them, as an argument and not as a type. + /// + /// A multi-argument constraint keeps all of its arguments: `std::same_as` records both `int` and + /// `long` even though the concept check reads the first (the argument the abbreviated syntax does not + /// implicitly supply). Dropping the rest here would lose the declaration's own answer for a consumer that asks + /// for it. `SomeConcept<42>` keeps `42` as a [`ConstraintArgument::Value`] — it is not the type `42`. + pub arguments: Box<[ConstraintArgument]>, +} + +/// **One argument a concept constraint wrote** — a type the type model can lower, or a value it cannot. +/// +/// The distinction is the whole reason this enum exists. `std::same_as` writes a **type** argument, and a +/// consumer deciding the concept needs the [`ComputedType`]. `SomeConcept<42>` writes a **non-type** argument, and +/// the type model has no representation of a value: `ComputedType::Named("42")` would claim `42` is a type *name*, +/// which every consumer that resolves names or compares types would believe. So a value keeps the text the file +/// wrote and nothing else. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ConstraintArgument { + /// A type argument, lowered structurally from its syntax — `int` in `same_as`. + Type(ComputedType), + /// **A non-type template argument, as the file wrote it** — `"42"` in `SomeConcept<42>`, `"sizeof(T)"`, + /// `"\"text\""`, `"1 + 2"`. + /// + /// It is **text because the type model has no value representation**. The text is enough for a consumer to know + /// that the argument is not a type and which argument was written; nothing here tries to evaluate it, and no + /// consumer may hand it to a type query. + Value(SmolStr), +} + +impl ConstraintArgument { + /// **What this argument costs outside the slot that holds it**, for [`DeclDetail::heap_bytes`] — the payload of + /// a type or the text of a value. The estimate follows [`ComputedType::heap_bytes`]'s convention. + fn heap_bytes(&self) -> usize { + size_of::() + + match self { + ConstraintArgument::Type(computed) => computed.heap_bytes(), + ConstraintArgument::Value(text) => on_the_heap(text), + } + } +} + +impl std::fmt::Display for ConstraintArgument { + /// The argument **as the file wrote it** — the lowered type's own display, or the value's text. A display + /// string is derived here from the structured value so a spelling cannot disagree with the argument it names. + fn fmt(&self, out: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConstraintArgument::Type(computed) => write!(out, "{computed}"), + ConstraintArgument::Value(text) => write!(out, "{text}"), + } + } +} + impl DeclDetail { /// **What the boxed fields cost outside the struct itself** — a lower bound with the same method as the rest of /// [`crate::MemoryReport`]: the detail struct, every `SmolStr` that fell out of line, and the element arrays of @@ -441,14 +611,15 @@ impl DeclDetail { /// the live bytes rather than of the allocator's high-water mark. pub fn heap_bytes(&self) -> usize { size_of::() - + on_the_heap_option(&self.in_namespace) - + on_the_heap_option(&self.returns_in_the_class) - + on_the_heap_option(&self.requires_clause) - + on_the_heap_option(&self.pattern) - + on_the_heap_option(&self.parameter_list) + + on_the_heap_smol_option(&self.in_namespace) + + on_the_heap_smol_option(&self.returns_in_the_class) + + on_the_heap_smol_option(&self.requires_clause) + + on_the_heap_smol_option(&self.pattern) + + on_the_heap_smol_option(&self.parameter_list) + strings_bytes(&self.bases) + strings_bytes(&self.parameters) + strings_bytes(&self.constraints) + + constraint_facts_bytes(&self.constraint_facts) + strings_bytes(&self.parameter_defaults) + self.reflection.as_ref().map_or(0, |reflection| { on_the_heap(&reflection.macro_name) @@ -458,13 +629,33 @@ impl DeclDetail { } } -/// The bytes a `Vec` owns: its element array and each string's payload. -fn strings_bytes(values: &[String]) -> usize { - size_of_val(values) + values.iter().map(String::len).sum::() +/// The bytes a string vector owns: its element array and the payloads that fell out of line. +fn strings_bytes(values: &[SmolStr]) -> usize { + size_of_val(values) + values.iter().map(on_the_heap).sum::() +} + +/// **The bytes the structured constraints own** — their optional slots, each concept's payload, and the argument +/// slots with the type trees or value texts they hold. Each [`ConstraintArgument::heap_bytes`] counts its own slot, +/// the same convention [`ComputedType::heap_bytes`] uses, so the slot array itself is covered by the arguments +/// rather than by the detail's `size_of`, which sees only the `Vec` header. +fn constraint_facts_bytes(values: &[Option]) -> usize { + size_of_val(values) + + values + .iter() + .flatten() + .map(|constraint| { + on_the_heap(&constraint.concept) + + constraint + .arguments + .iter() + .map(ConstraintArgument::heap_bytes) + .sum::() + }) + .sum::() } -/// The bytes an optional `SmolStr` owns outside the `Option` that holds it. -fn on_the_heap_option(text: &Option) -> usize { +/// The bytes an optional inline string owns outside the `Option` that holds it. +fn on_the_heap_smol_option(text: &Option) -> usize { text.as_ref().map_or(0, on_the_heap) } @@ -489,6 +680,28 @@ impl DeclarationAccounting { } impl DeclFact { + /// **Does this fact carry a type at all?** A consumer deciding "is this a typedef" + /// asks this; one that wants the type itself asks [`ProjectIndex::computed_type_of`]. + /// + /// [`ProjectIndex::computed_type_of`]: crate::ProjectIndex::computed_type_of + pub fn has_type_of(&self) -> bool { + self.type_of.has_value() + } + + /// Does this fact carry a return type, by the same rule as [`DeclFact::has_type_of`]? + pub fn has_returns(&self) -> bool { + self.returns.has_value() + } + + /// **Take another fact's types**, for a display copy that was rebuilt from a second reading. + /// + /// The values are immutable and own their names and children, so the copy keeps them directly; no handle + /// names an arena that does not travel with it. + pub fn use_the_types_of(&mut self, other: &DeclFact) { + self.type_of = other.type_of.clone(); + self.returns = other.returns.clone(); + } + /// The boxed half's cost, or zero for the common fact that has no box. pub fn detail_bytes(&self) -> usize { self.detail.as_deref().map_or(0, DeclDetail::heap_bytes) @@ -514,7 +727,7 @@ impl DeclFact { .and_then(|detail| detail.returns_in_the_class.as_deref()) } - pub fn bases(&self) -> &[String] { + pub fn bases(&self) -> &[SmolStr] { self.detail().map_or(&[], |detail| &detail.bases) } @@ -522,20 +735,28 @@ impl DeclFact { self.detail().and_then(|detail| detail.reflection.as_ref()) } - pub fn parameters(&self) -> &[String] { + pub fn parameters(&self) -> &[SmolStr] { self.detail().map_or(&[], |detail| &detail.parameters) } - pub fn constraints(&self) -> &[String] { + /// The constraints a template head wrote, **as display spellings**, aligned with the declaration's parameter + /// list — see [`DeclDetail::constraints`]. A consumer that decides something reads [`DeclFact::constraint_facts`]. + pub fn constraints(&self) -> &[SmolStr] { self.detail().map_or(&[], |detail| &detail.constraints) } + /// **The constraints structurally**, position for position with the declaration's **parameter list** — see + /// [`ConstraintFact`] and [`DeclDetail::constraint_facts`]. + pub fn constraint_facts(&self) -> &[Option] { + self.detail().map_or(&[], |detail| &detail.constraint_facts) + } + pub fn requires_clause(&self) -> Option<&str> { self.detail() .and_then(|detail| detail.requires_clause.as_deref()) } - pub fn parameter_defaults(&self) -> &[String] { + pub fn parameter_defaults(&self) -> &[SmolStr] { self.detail() .map_or(&[], |detail| &detail.parameter_defaults) } @@ -695,6 +916,12 @@ pub struct OutlineSymbol { } impl FileSummary { + /// **The CST parameter facts a declaration names in this summary.** A fact's `ParamsId` is local to the summary; + /// this is the only correct resolver for it, and it never falls back to text. + pub fn parameter_facts(&self, fact: &DeclFact) -> &[ParameterFact] { + self.parameters.parameters(fact.parameters) + } + /// **The file's declarations as a tree**, in source order — what an outline, a breadcrumb bar or a folding /// range is drawn from. /// @@ -1312,7 +1539,7 @@ struct UnitState { /// One definition the unit has in force: what it says, and where it was said. struct Binding { - definition: std::sync::Arc, + definition: Arc, /// The file that wrote it — a position means nothing without it, and only the file being walked can have /// written something *below* the condition being answered. defined_in: Box, @@ -1320,7 +1547,7 @@ struct Binding { } impl UnitState { - fn define(&mut self, name: &str, definition: std::sync::Arc, file: &Path, at: usize) { + fn define(&mut self, name: &str, definition: Arc, file: &Path, at: usize) { self.definitions.insert( name.into(), Binding { @@ -1355,8 +1582,7 @@ pub struct MacroDefinitions { /// **The path is shared**, not owned per key: the same header defines hundreds of macros, and a `PathBuf` per /// entry was hundreds of copies of the same path — measured at 34 000 entries on a cold start, most of them /// pointing into about 400 files. - parsed: - std::collections::HashMap<(std::sync::Arc, usize), Option>>, + parsed: std::collections::HashMap<(Arc, usize), Option>>, /// What the map holds, in the estimate [`MacroDefinitions::accounting`] makes — the number the budget below is /// deducted from. bytes: usize, @@ -1381,9 +1607,15 @@ impl DeclFact { pub fn heap_bytes(&self) -> usize { size_of::() + on_the_heap(&self.name) - + on_the_heap_option(&self.scope) - + on_the_heap_option(&self.type_of) - + on_the_heap_option(&self.returns) + + on_the_heap_smol_option(&self.scope) + + self + .type_of + .computed() + .map_or(0, |computed| computed.heap_bytes()) + + self + .returns + .computed() + .map_or(0, |computed| computed.heap_bytes()) + self.detail_bytes() } } @@ -1419,6 +1651,64 @@ impl IncludeFact { } } +#[cfg(test)] +mod fact_size_tests { + use super::DeclFact; + use std::mem::size_of; + + #[test] + fn a_declaration_fact_stays_within_its_transition_budget() { + // **Two declared-type values are the current shape.** One enum answers stored, synthesized and absent in the + // same width: a stored fact's handle and a synthesized fact's shared `ComputedType` are the same slot. Both + // are far below two hundred bytes, and the boxed detail is what keeps the common fact narrow. + assert!( + size_of::() <= 176, + "DeclFact is {} bytes", + size_of::() + ); + } +} + +#[cfg(test)] +mod declared_type_tests { + use super::{ComputedType, DeclaredType}; + use crate::index::types::PrimaryType; + use std::sync::Arc; + + /// **Two states, one cheap value** — a lowered type and its absence, with `as_computed` as the single edge a + /// consumer uses to get the value out. + #[test] + fn the_two_states_are_distinguishable() { + let computed = + DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::UnsignedLong))); + assert!(!computed.is_none()); + assert!(computed.has_value()); + assert!(computed.computed().is_some()); + assert_eq!( + computed.as_computed().map(|computed| computed.to_string()), + Some("unsigned long".to_string()), + "a computed value is already materialized and is cloned, not interned" + ); + + let absent = DeclaredType::None; + assert!(absent.is_none()); + assert!(!absent.has_value()); + assert!(absent.computed().is_none()); + assert!(absent.as_computed().is_none()); + assert_eq!(DeclaredType::default(), DeclaredType::None); + + assert_eq!( + DeclaredType::from_computed(None), + DeclaredType::None, + "no lowered type is an absence, never a wrapper around one" + ); + assert_eq!( + DeclaredType::from_computed(Some(ComputedType::Primary(PrimaryType::Int))), + DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Int))) + ); + } +} + impl FileSummary { /// **The declaration population and its boxed shares** — the data a decision about `DeclFact::detail` needs. pub fn declaration_accounting(&self) -> DeclarationAccounting { @@ -1483,10 +1773,7 @@ impl MacroDefinitions { pub fn accounting(&self) -> (usize, usize) { let mut bytes = 0usize; for (key, definition) in &self.parsed { - bytes += size_of::<( - (std::path::PathBuf, usize), - Option>, - )>(); + bytes += size_of::<((std::path::PathBuf, usize), Option>)>(); bytes += key.0.as_os_str().len(); if let Some(definition) = definition { bytes += size_of::() + definition.name.len(); @@ -1511,8 +1798,8 @@ impl MacroDefinitions { path: &Path, source: &str, fact: &MacroFact, - ) -> Option> { - let key = (std::sync::Arc::from(path), fact.range.start_offset); + ) -> Option> { + let key = (Arc::from(path), fact.range.start_offset); // **The key allocates, and it stays that way because the measurement said the allocation is // 1 s of a 250 s index.** A counter was put here to answer "what fraction of lookups are // hits" — five million lookups per index at 98.7%, so the waste is real and the fix is not @@ -1522,7 +1809,7 @@ impl MacroDefinitions { return known.clone(); } - let definition = read_back_a_define(source, fact).map(std::sync::Arc::new); + let definition = read_back_a_define(source, fact).map(Arc::new); // **The budget, checked on the way in.** A definition is one `#define` line re-read from a file already in // memory, so dropping the whole table costs less than tracking a weight per entry on this path — which is @@ -1531,10 +1818,7 @@ impl MacroDefinitions { self.parsed.clear(); self.bytes = 0; } - self.bytes += size_of::<( - (std::sync::Arc, usize), - Option>, - )>(); + self.bytes += size_of::<((Arc, usize), Option>)>(); self.bytes += size_of::(); if let Some(definition) = &definition { self.bytes += definition.name.len(); @@ -1574,7 +1858,7 @@ impl MacroDefinitions { path: &Path, source: &str, fact: &MacroFact, - ) -> Option> { + ) -> Option> { self.definition_of(path, source, fact) } } @@ -1917,7 +2201,7 @@ pub struct TranslationUnit { /// /// Derived state, like [`TranslationUnit::paths`]: it is a function of `events`, so it is built by the /// constructors rather than stored in the cache format. - pub(crate) by_name: std::collections::HashMap, Vec>, + pub(crate) by_name: std::collections::HashMap, Vec>, /// **The unit's [UnitDefinitions], built at most once** — the second pass asks for them again for every slice /// that reuses this timeline, and building them is a walk of every event with an Arc per definition. /// @@ -1969,14 +2253,14 @@ pub struct TranslationUnit { /// alternative — a second struct in the codec that mirrors it — is a second place for a field to be forgotten. #[derive(Clone, Debug)] pub(crate) struct TuEvent { - pub(crate) name: std::sync::Arc, + pub(crate) name: Arc, /// `None` for an `#undef`. pub(crate) function_like: Option, /// The shape of the replacement list, as the parser reads it. pub(crate) body: Option, /// The replacement list as text — **shared**, see [`cpp_parser::IncludedMacro::body_text`]. - pub(crate) body_text: Option>, - pub(crate) parameters: Option>, + pub(crate) body_text: Option>, + pub(crate) parameters: Option>, /// Where the **replacement list** is, in the file that wrote it. /// /// Kept so that a definition this unit hands to the cooker can carry **real positions**: the body's text is @@ -2061,14 +2345,14 @@ impl TimelineBuilder { let body_text = fact .body_range .and_then(|range| source.get(range.start_offset..range.start_offset + range.length)) - .map(std::sync::Arc::from); + .map(Arc::from); let parameters = fact .body_range .and_then(|range| parameters_before(source, range.start_offset)) - .map(std::sync::Arc::from); + .map(Arc::from); self.events.push(TuEvent { - name: std::sync::Arc::from(&*fact.name), + name: Arc::from(&*fact.name), function_like: fact.kind.is_definition().then_some(fact.function_like), body: fact.kind.is_definition().then_some(fact.body), body_text, @@ -2193,13 +2477,13 @@ impl TranslationUnit { .or_insert(index as u32); } - let mut by_name: std::collections::HashMap, Vec> = + let mut by_name: std::collections::HashMap, Vec> = std::collections::HashMap::new(); for (index, event) in events.iter().enumerate() { // Walk order, which is the order the queries rely on: the last entry of a name's list is the last fact // the walk put in force for it. by_name - .entry(std::sync::Arc::clone(&event.name)) + .entry(Arc::clone(&event.name)) .or_default() .push(index as u32); } @@ -2276,7 +2560,7 @@ impl TranslationUnit { // **A slot per event, nothing lexed.** A body is read the first time the cook asks for it, which is what makes // this table cheap to build and is why the cache that used to sit in front of it is gone — see // [`UnitDefinitions::of`] for the measurement. - let mut by_event: Vec>>>> = + let mut by_event: Vec>>>> = (0..self.events.len()).map(|_| None).collect(); let mut function_like_without_parameters = 0usize; let mut without_a_body = 0usize; @@ -2757,7 +3041,7 @@ pub struct UnitDefinitions<'unit> { unit: &'unit TranslationUnit, /// Parallel to `TranslationUnit::events`: the definition a fact becomes as a `#define` line, or `None` when that /// fact is not one this reader can put back together. - by_event: Vec>>>>, + by_event: Vec>>>>, /// Definitions whose parameter list the evidence does not carry — a function-like macro that cannot be /// substituted into, so it is not in the table. Counted for the unit; see [`TranslationUnit::definitions`]. pub function_like_without_parameters: usize, @@ -2775,7 +3059,7 @@ impl UnitDefinitions<'_> { pub fn heap_bytes(&self) -> usize { let mut bytes = size_of::>() + self.by_event.capacity() - * size_of::>>>>(); + * size_of::>>>>(); for definition in self.by_event.iter().flatten().filter_map(|cell| cell.get()) { let Some(definition) = definition else { continue; @@ -2793,12 +3077,12 @@ impl UnitDefinitions<'_> { /// The body is lexed here rather than when the unit was prepared: on `import std;` the table holds tens of thousands /// of definitions and the cook meets a fraction of them, so the eager version lexed replacement lists nothing would /// ever expand. A slot remembers its answer — including "this one does not read" — so a second ask costs nothing. - pub(crate) fn of(&self, index: u32) -> Option<&std::sync::Arc> { + pub(crate) fn of(&self, index: u32) -> Option<&Arc> { let cell = self.by_event.get(index as usize)?.as_ref()?; cell.get_or_init(|| { let event = self.unit.events.get(index as usize)?; let body = event.body_text.as_deref()?; - let built = definition_written_at(event, body).map(std::sync::Arc::new); + let built = definition_written_at(event, body).map(Arc::new); if built.is_none() { self.unreadable .fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -3325,7 +3609,7 @@ impl MacroFacts for MacroView<'_> { } } - fn parameters_of(&self, name: &str, offset: usize) -> Option<&std::sync::Arc> { + fn parameters_of(&self, name: &str, offset: usize) -> Option<&Arc> { let (at, event) = self.the_binding(name)?; match (at <= offset, event.function_like, event.body) { (true, Some(_), Some(_)) => event.parameters.as_ref(), @@ -5302,6 +5586,8 @@ pub struct FileSummary { /// against the file it claims to describe rather than trusted because it was found. pub key: SummaryKey, pub declarations: Vec, + /// The summary's local parameter arena, indexed by `DeclFact::parameters`. + pub parameters: ParamsStore, pub macros: Vec, pub includes: Vec, pub guards: SummaryGuards, @@ -5487,6 +5773,7 @@ impl FileSummary { path: path.into(), key, declarations: Vec::new(), + parameters: ParamsStore::default(), macros: Vec::new(), includes: Vec::new(), guards: SummaryGuards::default(), @@ -5824,7 +6111,7 @@ pub struct IndexedRendering { /// /// Keeping it costs one `Arc` clone: the renderer already holds the text in an `Arc`, so this is a pointer and /// not a copy of a header. It is what makes "the reading exists" and "the reading is available" the same state. - pub rendered: std::sync::Arc, + pub rendered: Arc, /// How the mapping went: ranges placed, ranges that landed nowhere. pub mapped: MapReport, /// The parse errors of the rendering, placed in the file. @@ -5892,7 +6179,7 @@ impl preprocess::cooked::MacroEnvironment for MacroView<'_> { /// Lazy on both sides: the table lexes a replacement list the first time a rendering meets it, and a slot nobody asks /// for is never read. `of` is the reader; this trait is the door the renderer is allowed to knock on. impl preprocess::cooked::UnitDefinitionsView for UnitDefinitions<'_> { - fn definition_of(&self, index: u32) -> Option<&std::sync::Arc> { + fn definition_of(&self, index: u32) -> Option<&Arc> { self.of(index) } } diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index ed17eea8..a4bf5c8e 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -23,14 +23,20 @@ //! saying anything about whether it is *correct*. use crate::DeclModifiers; +use crate::DeclaredType; use crate::DirectiveKind; use crate::FORMAT_VERSION; use crate::READING_FINGERPRINT; +use crate::index; +use crate::index::types::{ArrayExtent, ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::macros; use crate::preprocess; +use crate::sema::types::RecordTag; use crate::summary; +use cpp_parser::CppSyntaxId; use smol_str::SmolStr; use std::path::PathBuf; +use std::sync::Arc; use cpp_parser::SymbolKind; use cpp_parser::{MacroBody, SourceRange}; @@ -40,9 +46,9 @@ use crate::index::CookedFile; use crate::preprocess::directive::IncludeForm; use crate::summary::CookedDiagnostic; use crate::summary::{ - Access, ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, - IncludeFact, MacroFact, MacroKind, MacroScopeReading, ModuleReading, SummaryGuards, - TranslationUnit, TuEvent, TuFrame, + Access, ConditionalRegion, ConstraintArgument, DeclFact, DeclKind, FactGuard, FileSummary, + GuardBranch, IncludeFact, MacroFact, MacroKind, MacroScopeReading, ModuleReading, + SummaryGuards, TranslationUnit, TuEvent, TuFrame, }; /// The eight bytes a summary file starts with. @@ -282,7 +288,105 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// A declaration fact gained its **enumerator** byte, written last — see [`DeclFact::enumerator`]. A fact /// decoded from an older summary is not wrong about its other fields; it simply answers `false`, which is the /// answer that made an anonymous enum's members look like variables. -pub const CODEC_VERSION: u32 = 40; +/// +/// # Version 44 +/// +/// **A declaration fact's type is one handle per field, with no spelling beside it.** The record used to write +/// `type_of`/`returns` as optional strings *and* their handles; the strings are gone from [`DeclFact`], and the +/// spelling lives only in the summary's type table (or, for a cooked reading, in that record's own table). An entry +/// written before this has two string fields where this decoder expects the second handle, so the whole record is +/// unreachable — which is what a version bump is for. +/// +/// # The `DeclaredType` enum, and why the number did not move again +/// +/// The two handles became one enum-valued field per type ([`DeclaredType`]), because a synthesized fact carries a +/// `ComputedType` where an ordinary one carries a `TypeId`. **The bytes did not move**: the writer still emits the +/// same two `u32`s in the same places — a stored handle as itself, a computed or absent type as `NONE` — and the +/// reader maps `NONE` back to `DeclaredType::None`. An entry written before the enum therefore decodes into the same +/// facts it always did, so [`CODEC_VERSION`] stays where it is. +/// +/// # Removing `DeclDetail::parameter_facts`, and why the number still did not move +/// +/// That field was a **build-time** duplicate of the summary's parameter table: [`put_declaration`] never wrote it and +/// the decoder never read it, so deleting it changes the in-memory shape of a fact and not one byte of the record. +/// Parameter facts travel exactly where they always travelled — in the summary's `ParamsStore`, written by +/// [`put_params_store`] — and a decoded detail has no build-time copy (it never did). A **cooked reading** is a +/// different record with its own table, which is new, so [`COOKED_VERSION`] moved to 8. +/// +/// # Version 45 +/// +/// **A declaration fact carries the parameter list's own `...`** — see [`DeclFact::variadic_parameters`]. It is the +/// list's token rather than a parameter's flag (`void f(int, ...)` has one parameter and the marker beside it, and +/// `void f(...)` has none), so the parameter table cannot answer it and a view/synthetic fact has no table at all. The +/// byte is appended after the definition/enumerator flags. An entry written before this would decode the byte from +/// whatever follows, so the record is refused rather than misread — the ordinary case for a new field, which is what +/// moving the number is for. A cooked reading and a unit's filed facts carry the same declaration record, so their +/// numbers move with it ([`COOKED_VERSION`] 9, [`crate::cache::unit_codec::UNIT_CODEC_VERSION`] 8). +/// +/// # Version 46 +/// +/// **The type table can hold a C record's tag** — see `EncodedTypeKind::ElaboratedRecord`. The tag was previously +/// dropped at the declaration reader, so this is the first record that can write it; the new kind is the explicit +/// discriminant `11`, with the tag as its own byte. An older build refuses the record on its version rather than +/// reading the kind as a node of a different shape. A cooked reading and a unit's filed facts carry the same type +/// table, so their numbers move with it ([`COOKED_VERSION`] 10). +/// +/// # Version 47 +/// +/// **A fact carries its types as values, not as handles into a table.** The `TypeStore`/`TypeTable` pair is gone: +/// each declaration record writes its `type_of` and `returns` as an [`ENCODED_COMPUTED_TYPE`] value (or a zero byte +/// for "no type"), and each parameter record writes its type the same way. A record written before this holds two +/// `u32` handles where this decoder expects type values, so it is refused rather than misread. A cooked reading and +/// a unit's filed facts carry the same declaration and parameter records, so their numbers move with it +/// ([`COOKED_VERSION`] 11, [`crate::cache::unit_codec::UNIT_CODEC_VERSION`] 9). +/// +/// # Version 48 +/// +/// **A declaration fact carries its template-head constraints structurally** — see [`crate::ConstraintFact`]. After +/// the display spellings, the record writes one optional fact per parameter: its concept name and its type arguments +/// as [`ENCODED_COMPUTED_TYPE`] values. That is the form the `concept-not-satisfied` check reads, so a call site no +/// longer splits the spelling and parses the arguments back into types. A record written before this has the +/// `requires_clause` field where this decoder expects the first structured slot (or a count of zero followed by the +/// clause's presence byte), so it is refused rather than misread — the ordinary case for a field inserted after the +/// constraint strings. A cooked reading and a unit's filed facts carry the same declaration record, so their numbers +/// move with it ([`COOKED_VERSION`] 12, [`crate::cache::unit_codec::UNIT_CODEC_VERSION`] 10). +/// # Version 49 +/// +/// **An array type carries its bound structurally** — see [`crate::index::types::ArrayExtent`]. Where version 48 +/// wrote a presence byte for `Option` (`0` for `[]` and for a dimension the reader could not evaluate, `1` and a +/// `u64` for a literal), the array record now writes `0` for `[]`, `1` and a `u64` for a literal, and `2` and a +/// string for a **named or expression dimension** — `COUNT`, `('z' - 'a' + 1)`. Tags `0` and `1` keep their old +/// meaning, so the extension is readable in one direction; a record written before it holds `0` where a name would +/// be, which is exactly the answer this version stops accepting as equivalent. A cooked reading and a unit's filed +/// facts carry the same declaration and parameter records, so their numbers move with it +/// ([`COOKED_VERSION`] 13, [`crate::cache::unit_codec::UNIT_CODEC_VERSION`] 11). +/// +/// # Version 50 +/// +/// **A constraint's arguments are typed as arguments, not as types** — see [`crate::ConstraintArgument`]. Version 48 +/// wrote every concept argument as an [`ENCODED_COMPUTED_TYPE`] value, so `template T>` recorded +/// `42` as a type *named* `42`; the record now writes a tag per argument, `1` for a type (the bytes version 49 +/// wrote) and `2` for a value followed by its text. An old record that holds a value argument decodes as a type, +/// which is a wrong answer rather than a missing one, so the whole record is refused on the number. A cooked +/// reading and a unit's filed facts carry the same declaration record, so their numbers move with it +/// ([`COOKED_VERSION`] 14, [`crate::cache::unit_codec::UNIT_CODEC_VERSION`] 12). +pub const CODEC_VERSION: u32 = 50; + +/// **The version of the `ComputedType` grammar written inside a fact or parameter record.** +/// +/// Every encoded type is introduced by this byte (and `0` alone means [`crate::DeclaredType::None`]), so a future +/// change to the tag table can be read as a different grammar instead of as a node of the old one. The value is +/// written beside each type rather than once per file: a record is decoded independently, and a type is the unit +/// that changed. +pub(crate) const ENCODED_COMPUTED_TYPE: u8 = 1; + +/// **The tag that introduces one [`crate::ConstraintArgument`]** — a type or a value. +/// +/// A type keeps the byte version 49 already wrote ([`ENCODED_COMPUTED_TYPE`]), so a type argument's bytes are +/// unchanged; a value is the new tag `2` followed by the argument's text. The distinction is on the record because +/// a decoder cannot tell `42`-as-a-type from `42`-as-a-value in the type grammar — that was the defect. +const CONSTRAINT_ARGUMENT_IS_A_TYPE: u8 = ENCODED_COMPUTED_TYPE; +const CONSTRAINT_ARGUMENT_IS_A_VALUE: u8 = 2; /// Write a summary as bytes. /// @@ -398,6 +502,8 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.use_filter.len() as u32); out.extend_from_slice(&summary.use_filter); + put_params_store(&mut out, &summary.parameters); + out } @@ -542,7 +648,7 @@ pub fn decode_translation_unit( let event_count = reader.count()?; let mut events = Vec::with_capacity(event_count); for _ in 0..event_count { - let name: std::sync::Arc = std::sync::Arc::from(reader.string()?); + let name: Arc = Arc::from(reader.string()?); let function_like = match reader.u8()? { 0 => None, 1 => Some(false), @@ -554,8 +660,8 @@ pub fn decode_translation_unit( 1 => Some(macro_body_from(reader.u8()?)?), _ => return Err(DecodeError::BadDiscriminant), }; - let body_text = reader.optional_string()?.map(std::sync::Arc::from); - let parameters = reader.optional_string()?.map(std::sync::Arc::from); + let body_text = reader.optional_string()?.map(Arc::from); + let parameters = reader.optional_string()?.map(Arc::from); let body_range = match reader.u8()? { 0 => None, 1 => Some(SourceRange::new( @@ -786,6 +892,8 @@ pub fn decode(bytes: &[u8]) -> Result { bytes }; + let parameters = get_params_store(&mut reader)?; + // Trailing bytes mean the file was written by something this decoder does not agree with — a newer producer, // or two records where one was expected. Ignoring them would be accepting a file whose *content* is not what // its own encoding says, which is the one thing a cache must not do. @@ -797,6 +905,7 @@ pub fn decode(bytes: &[u8]) -> Result { path, key, declarations, + parameters, macros, includes, guards, @@ -971,6 +1080,329 @@ fn put_str(out: &mut Vec, value: &str) { out.extend_from_slice(value.as_bytes()); } +/// **The byte a C record tag is written as** — an explicit number, like every other discriminant in this codec, so +/// that a reordered enum cannot silently change the record's meaning. +fn encoded_record_tag(tag: RecordTag) -> u8 { + match tag { + RecordTag::Struct => 0, + RecordTag::Union => 1, + } +} + +/// The tag a byte names, or `None` for a value this build never wrote. +fn decoded_record_tag(byte: u8) -> Option { + match byte { + 0 => Some(RecordTag::Struct), + 1 => Some(RecordTag::Union), + _ => None, + } +} + +/// **The byte a primary type is written as** — explicit, like every other discriminant here, so a reordered enum +/// cannot silently change a record's meaning. +fn encoded_primary(primary: PrimaryType) -> u8 { + match primary { + PrimaryType::Void => 0, + PrimaryType::Bool => 1, + PrimaryType::Char => 2, + PrimaryType::SignedChar => 3, + PrimaryType::UnsignedChar => 4, + PrimaryType::Short => 5, + PrimaryType::UnsignedShort => 6, + PrimaryType::Int => 7, + PrimaryType::UnsignedInt => 8, + PrimaryType::Long => 9, + PrimaryType::UnsignedLong => 10, + PrimaryType::LongLong => 11, + PrimaryType::UnsignedLongLong => 12, + PrimaryType::Float => 13, + PrimaryType::Double => 14, + PrimaryType::LongDouble => 15, + PrimaryType::WChar => 16, + PrimaryType::Char8 => 17, + PrimaryType::Char16 => 18, + PrimaryType::Char32 => 19, + PrimaryType::Auto => 20, + PrimaryType::DecltypeAuto => 21, + } +} + +/// The primary a byte names, or `None` for a value this build never wrote. +fn decoded_primary(byte: u8) -> Option { + Some(match byte { + 0 => PrimaryType::Void, + 1 => PrimaryType::Bool, + 2 => PrimaryType::Char, + 3 => PrimaryType::SignedChar, + 4 => PrimaryType::UnsignedChar, + 5 => PrimaryType::Short, + 6 => PrimaryType::UnsignedShort, + 7 => PrimaryType::Int, + 8 => PrimaryType::UnsignedInt, + 9 => PrimaryType::Long, + 10 => PrimaryType::UnsignedLong, + 11 => PrimaryType::LongLong, + 12 => PrimaryType::UnsignedLongLong, + 13 => PrimaryType::Float, + 14 => PrimaryType::Double, + 15 => PrimaryType::LongDouble, + 16 => PrimaryType::WChar, + 17 => PrimaryType::Char8, + 18 => PrimaryType::Char16, + 19 => PrimaryType::Char32, + 20 => PrimaryType::Auto, + 21 => PrimaryType::DecltypeAuto, + _ => return None, + }) +} + +/// **A `DeclaredType` as bytes.** `0` alone is "no type"; every other record begins with +/// [`ENCODED_COMPUTED_TYPE`] and then the type itself. +fn put_declared_type(out: &mut Vec, value: &DeclaredType) { + match value.computed() { + None => put_u8(out, 0), + Some(computed) => { + put_u8(out, ENCODED_COMPUTED_TYPE); + put_computed_type(out, computed); + } + } +} + +/// Read one [`DeclaredType`], the reader half of [`put_declared_type`]. +fn get_declared_type(reader: &mut Reader<'_>) -> Result { + match reader.u8()? { + 0 => Ok(DeclaredType::None), + ENCODED_COMPUTED_TYPE => Ok(DeclaredType::Computed(Arc::new(get_computed_type( + reader, 0, + )?))), + _ => Err(DecodeError::BadDiscriminant), + } +} + +/// **One `ComputedType`, written as a tagged tree.** The value is self-contained: names travel as strings and +/// children follow their parent, so no table, id or source spelling accompanies it. +/// +/// Tags are explicit numbers for the same reason the other discriminants are, and the grammar is versioned by +/// [`ENCODED_COMPUTED_TYPE`] at the enclosing record. +fn put_computed_type(out: &mut Vec, value: &ComputedType) { + match value { + ComputedType::Primary(primary) => { + put_u8(out, 0); + put_u8(out, encoded_primary(*primary)); + } + ComputedType::Named(name) => { + put_u8(out, 1); + put_str(out, name); + } + ComputedType::Generic(generic) => { + put_u8(out, 2); + put_str(out, &generic.name); + put_u32(out, generic.arguments.len() as u32); + for argument in &generic.arguments { + put_computed_type(out, argument); + } + } + ComputedType::TemplateParameter(name) => { + put_u8(out, 3); + put_str(out, name); + } + ComputedType::ElaboratedRecord { tag, of } => { + put_u8(out, 4); + put_u8(out, encoded_record_tag(*tag)); + put_computed_type(out, of); + } + ComputedType::Pointer(to) => { + put_u8(out, 5); + put_computed_type(out, to); + } + ComputedType::Reference { to, rvalue } => { + put_u8(out, 6); + put_computed_type(out, to); + put_u8(out, u8::from(*rvalue)); + } + ComputedType::Array { of, extent } => { + put_u8(out, 7); + put_computed_type(out, of); + // **The dimension is part of the grammar** — a name is a value the record carries, not a spelling a + // consumer has to find again. `0`/`1` were the pre-name tags and keep their meaning. + match extent { + ArrayExtent::Unspecified => put_u8(out, 0), + ArrayExtent::Literal(extent) => { + put_u8(out, 1); + put_u64(out, *extent); + } + ArrayExtent::Written(written) => { + put_u8(out, 2); + put_str(out, written); + } + } + } + ComputedType::Function(function) => { + put_u8(out, 8); + put_computed_type(out, &function.returns); + put_u32(out, function.parameters.len() as u32); + for parameter in &function.parameters { + put_computed_type(out, parameter); + } + } + ComputedType::Pack(of) => { + put_u8(out, 9); + put_computed_type(out, of); + } + ComputedType::Qualified(qualified) => { + put_u8(out, 10); + put_computed_type(out, &qualified.of); + put_u8(out, u8::from(qualified.is_const)); + put_u8(out, u8::from(qualified.is_volatile)); + } + } +} + +/// The deepest a decoded type may nest. A type is a tree read from one source declaration, so this is bounded by +/// the program that produced it; the limit keeps corrupt bytes from recursing the decoder into a stack overflow. +const MAX_ENCODED_TYPE_DEPTH: u32 = 64; + +/// Read one `ComputedType` written by [`put_computed_type`]. +fn get_computed_type(reader: &mut Reader<'_>, depth: u32) -> Result { + if depth >= MAX_ENCODED_TYPE_DEPTH { + return Err(DecodeError::Implausible); + } + Ok(match reader.u8()? { + 0 => ComputedType::Primary( + decoded_primary(reader.u8()?).ok_or(DecodeError::BadDiscriminant)?, + ), + 1 => ComputedType::Named(SmolStr::from(reader.string()?)), + 2 => { + let name = SmolStr::from(reader.string()?); + let count = reader.count()?; + let mut arguments = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + arguments.push(get_computed_type(reader, depth + 1)?); + } + ComputedType::named(name, arguments) + } + 3 => ComputedType::TemplateParameter(SmolStr::from(reader.string()?)), + 4 => ComputedType::ElaboratedRecord { + tag: decoded_record_tag(reader.u8()?).ok_or(DecodeError::BadDiscriminant)?, + of: Arc::new(get_computed_type(reader, depth + 1)?), + }, + 5 => ComputedType::Pointer(Arc::new(get_computed_type(reader, depth + 1)?)), + 6 => ComputedType::Reference { + to: Arc::new(get_computed_type(reader, depth + 1)?), + rvalue: reader.u8()? != 0, + }, + 7 => { + let of = Arc::new(get_computed_type(reader, depth + 1)?); + let extent = match reader.u8()? { + 0 => ArrayExtent::Unspecified, + 1 => ArrayExtent::Literal(reader.u64()?), + 2 => ArrayExtent::written(reader.string()?), + _ => return Err(DecodeError::BadDiscriminant), + }; + ComputedType::Array { of, extent } + } + 8 => { + let returns = Arc::new(get_computed_type(reader, depth + 1)?); + let count = reader.count()?; + let mut parameters = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + parameters.push(get_computed_type(reader, depth + 1)?); + } + ComputedType::Function(Arc::new(FunctionType { + returns, + parameters: parameters.into_boxed_slice(), + })) + } + 9 => ComputedType::Pack(Arc::new(get_computed_type(reader, depth + 1)?)), + 10 => ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(get_computed_type(reader, depth + 1)?), + is_const: reader.u8()? != 0, + is_volatile: reader.u8()? != 0, + })), + _ => return Err(DecodeError::BadDiscriminant), + }) +} + +fn put_parameter_facts(out: &mut Vec, facts: &[index::params::ParameterFact]) { + put_u32(out, facts.len() as u32); + for fact in facts { + put_opt_str(out, fact.name.as_deref()); + let (kind, start, end) = fact.declaration.to_raw_parts(); + put_u32(out, u32::from(kind)); + put_u32(out, start); + put_u32(out, end); + match fact.default_value { + Some(default) => { + let (kind, start, end) = default.to_raw_parts(); + put_u8(out, 1); + put_u32(out, u32::from(kind)); + put_u32(out, start); + put_u32(out, end); + } + None => put_u8(out, 0), + } + put_u8(out, u8::from(fact.pack)); + // **The type itself**, encoded in the record — a parameter carries the same `DeclaredType` a declaration + // does, and there is no table beside the record for a handle to name. + put_declared_type(out, &fact.type_of); + } +} + +fn get_parameter_facts( + reader: &mut Reader<'_>, +) -> Result, DecodeError> { + let count = reader.count()?; + let mut facts = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + let name = reader.optional_string()?.map(SmolStr::from); + let kind = u16::try_from(reader.u32()?).map_err(|_| DecodeError::BadDiscriminant)?; + let start = reader.u32()?; + let end = reader.u32()?; + let declaration = + CppSyntaxId::from_raw_parts(kind, start, end).ok_or(DecodeError::BadDiscriminant)?; + let default_value = match reader.u8()? { + 0 => None, + 1 => { + let kind = + u16::try_from(reader.u32()?).map_err(|_| DecodeError::BadDiscriminant)?; + let start = reader.u32()?; + let end = reader.u32()?; + Some( + CppSyntaxId::from_raw_parts(kind, start, end) + .ok_or(DecodeError::BadDiscriminant)?, + ) + } + _ => return Err(DecodeError::BadDiscriminant), + }; + let pack = reader.u8()? != 0; + let type_of = get_declared_type(reader)?; + facts.push(index::params::ParameterFact { + name, + declaration, + default_value, + pack, + type_of, + }); + } + Ok(facts) +} + +fn put_params_store(out: &mut Vec, store: &index::params::ParamsStore) { + put_u32(out, store.entries().len() as u32); + for facts in store.entries() { + put_parameter_facts(out, facts); + } +} + +fn get_params_store(reader: &mut Reader<'_>) -> Result { + let count = reader.count()?; + let mut entries = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + entries.push(get_parameter_facts(reader)?.into_boxed_slice()); + } + Ok(index::params::ParamsStore::from_entries(entries)) +} + fn put_opt_str(out: &mut Vec, value: Option<&str>) { match value { Some(text) => { @@ -1175,14 +1607,21 @@ fn symbol_kind_code(kind: SymbolKind) -> u8 { #[cfg(test)] mod tests { + use crate::index; + use crate::sema; + use std::sync::Arc; + use super::Access; use super::ModuleReading; use super::{CODEC_VERSION, DecodeError, MAGIC, decl_kind_code, decode, encode}; + use crate::ConstraintArgument; use crate::DeclModifiers; use crate::DirectiveKind; use crate::cache::SummaryKey; + use crate::index::types::{ArrayExtent, ComputedType, PrimaryType}; use crate::preprocess::directive::IncludeForm; use crate::summary; + use crate::summary::DeclaredType; use crate::summary::MacroKind; use crate::summary::{ ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, IncludeFact, @@ -1195,6 +1634,11 @@ mod tests { SourceRange::new(start, length) } + /// One lowered type, as the value a fact carries. + fn computed(value: ComputedType) -> DeclaredType { + DeclaredType::Computed(Arc::new(value)) + } + /// A summary that uses every field, so that a round trip covers the whole format rather than a sample of it. fn every_field() -> FileSummary { FileSummary { @@ -1204,6 +1648,7 @@ mod tests { // file") and a populated one (which is allowed to say no). A field tested at one size is a field whose // other size is untested, and the empty case is the one every summary written before this field has. use_filter: vec![0x00, 0xff, 0x55, 0xaa, 0x01, 0x80], + parameters: index::params::ParamsStore::default(), declarations: vec![ DeclFact { // **The flag at `true`**, on this of the three declarations, so the byte is covered at both ends — the @@ -1215,9 +1660,14 @@ mod tests { kind: DeclKind::Type, modifiers: DeclModifiers::default(), // A class declares no type in `type_of`'s sense, so the `None` branch is covered here. - type_of: None, + type_of: DeclaredType::None, // A class returns nothing either, so `None` — and the second fact below covers the other value. - returns: None, + returns: DeclaredType::None, + parameters: index::params::ParamsId::NONE, + // **The list-level `...` at `true`**, so the byte is covered at both ends — the two facts below + // say `false`. Like `enumerator`, what this fixture's fact *is* is not a claim: it exists to + // exercise the format. + variadic_parameters: true, // A member of a class, with the level its class body gave it — the one field a completion // filters on, so the round trip has to carry a *some* as well as the `None`s below. access: Some(Access::Protected), @@ -1248,12 +1698,30 @@ mod tests { }), returns_in_the_class: None, // A base list, so that branch of the format is covered too: two bases, one qualified. - bases: vec!["Base".to_string(), "ns::Other".to_string()], + bases: vec!["Base".into(), "ns::Other".into()], // And a parameter list, which is the other list-shaped field: a class template's parameter // names, in the order the declaration wrote them. - parameters: vec!["_Ty".to_string(), "_Alloc".to_string()], + parameters: vec!["_Ty".into(), "_Alloc".into()], // The constraint in front of each parameter — empty here, and carried by the round trip. - constraints: vec![String::new(), "Integral".to_string()], + constraints: vec![SmolStr::default(), "Integral".into()], + // **The same constraints structurally**, in the same slots: the second parameter's concept + // carries **one argument of each kind**, so the round trip exercises a nested type value, a + // value's text, and the tag that tells them apart. The first slot is `None`, the shape an + // unconstrained parameter has. + constraint_facts: vec![ + None, + Some(summary::ConstraintFact { + concept: "same_as".into(), + arguments: vec![ + ConstraintArgument::Type(ComputedType::named( + "std::vector", + vec![ComputedType::Primary(PrimaryType::Int)], + )), + ConstraintArgument::Value("42".into()), + ] + .into_boxed_slice(), + }), + ], // A clause is the declaration's text, and this literal is a fixture with no text to read. requires_clause: None, parameter_defaults: Vec::new(), @@ -1275,8 +1743,18 @@ mod tests { modifiers: DeclModifiers::default(), // A function declares no `type_of` — the name has no type — and its `returns` is what a *call* // has. Both halves of that distinction are in this fixture on purpose. - type_of: None, - returns: Some("ns::Container".into()), + type_of: DeclaredType::None, + // A value that is not a primary, so the round trip covers a tree rather than one tag. + returns: computed(ComputedType::named( + "std::pair", + vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Int), + ], + )), + parameters: index::params::ParamsId::NONE, + // The `false` side of the list-level `...`, which the class above covers the other way round. + variadic_parameters: false, // No access level — a free function is not a member — and not exported: the `false` side of // both fields, which the class above covers the other way round. access: None, @@ -1303,8 +1781,31 @@ mod tests { scope: None, kind: DeclKind::Other, modifiers: DeclModifiers::default(), - type_of: None, - returns: None, + type_of: computed(ComputedType::Qualified(Arc::new( + index::types::QualifiedType { + of: Arc::new(ComputedType::Pointer(Arc::new(ComputedType::named( + "std::vector", + vec![ + ComputedType::ElaboratedRecord { + tag: sema::types::RecordTag::Union, + of: Arc::new(ComputedType::Named(SmolStr::new("value"))), + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Literal(4), + }, + ComputedType::TemplateParameter(SmolStr::new("T")), + ], + )))), + is_const: true, + is_volatile: false, + }, + ))), + returns: DeclaredType::None, + parameters: index::params::ParamsId::NONE, + // The third fact has no list at all, so the flag is `false` — the value a decoded fact from an + // older record would have had, which is why the version is what refuses one. + variadic_parameters: false, access: None, exported: false, // A round trip that always wrote one value would not notice a decoder that dropped the byte. @@ -1443,6 +1944,86 @@ mod tests { ); } + #[test] + fn a_computed_type_is_persisted_as_a_value() { + // Every `DeclaredType` the fact carries is written into the record, so a decoded fact answers the same + // type — there is no table to import and no handle to rebind. + let original = every_field(); + let decoded = + decode(&encode(&original)).expect("the bytes this module wrote must be readable by it"); + + assert_eq!( + decoded.declarations[1].returns, + original.declarations[1].returns + ); + assert_eq!( + decoded.declarations[2].type_of, + original.declarations[2].type_of + ); + } + + /// **Every variant of the type grammar, through the codec.** The fixture above exercises the common shapes; this + /// one walks the operator forms so that a tag the encoder writes and the decoder drops cannot hide. + #[test] + fn every_computed_type_variant_round_trips() { + let mut original = FileSummary::empty("/p/types.h", SummaryKey::new(0, 0)); + let mut fact = original.declarations.first().cloned().unwrap_or_else(|| { + // `empty` has no declarations, so build one from the fixture and swap its types. + let mut fact = every_field().declarations.remove(0); + fact.type_of = DeclaredType::None; + fact.returns = DeclaredType::None; + fact + }); + let values = [ + ComputedType::Primary(PrimaryType::UnsignedLongLong), + ComputedType::Named(SmolStr::new("Widget")), + ComputedType::named("std::vector", vec![ComputedType::Primary(PrimaryType::Int)]), + ComputedType::TemplateParameter(SmolStr::new("T")), + ComputedType::ElaboratedRecord { + tag: sema::types::RecordTag::Struct, + of: Arc::new(ComputedType::Named(SmolStr::new("point"))), + }, + ComputedType::Pointer(Arc::new(ComputedType::Primary(PrimaryType::Int))), + ComputedType::Reference { + to: Arc::new(ComputedType::Primary(PrimaryType::Double)), + rvalue: true, + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Char)), + extent: ArrayExtent::Unspecified, + }, + // **The named dimension is its own tag**, so a bound that is not a number and one that is absent cannot + // decode into each other — the defect this version exists to stop. + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Char)), + extent: ArrayExtent::written("COUNT"), + }, + ComputedType::Function(Arc::new(index::types::FunctionType { + returns: Arc::new(ComputedType::Primary(PrimaryType::Void)), + parameters: vec![ComputedType::Primary(PrimaryType::Int)].into_boxed_slice(), + })), + ComputedType::Pack(Arc::new(ComputedType::TemplateParameter(SmolStr::new( + "Args", + )))), + ComputedType::Qualified(Arc::new(index::types::QualifiedType { + of: Arc::new(ComputedType::Named(SmolStr::new("Widget"))), + is_const: true, + is_volatile: true, + })), + ]; + for value in values { + fact.type_of = computed(value.clone()); + fact.returns = DeclaredType::None; + original.declarations = vec![fact.clone()]; + let decoded = decode(&encode(&original)).expect("a type value round-trips"); + assert_eq!( + decoded.declarations[0].type_of, + DeclaredType::Computed(Arc::new(value.clone())), + "every variant survives: {value:?}" + ); + } + } + #[test] fn an_empty_summary_round_trips() { let original = FileSummary::empty("/p/empty.h", SummaryKey::new(0, 0)); @@ -1563,8 +2144,11 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { put_str(out, &fact.name); put_opt_str(out, fact.scope.as_deref()); put_u8(out, decl_kind_code(fact.kind)); - put_opt_str(out, fact.type_of.as_deref()); - put_opt_str(out, fact.returns.as_deref()); + // **The two types as values.** Each is a `DeclaredType`: a presence/version byte, then the type itself, or `0` + // for "no type". There is no type table beside the record and no local handle to rewrite after a decode. + put_declared_type(out, &fact.type_of); + put_declared_type(out, &fact.returns); + put_u32(out, fact.parameters.raw()); // **The spelling `returns` refused** — see [`DeclFact::returns_in_the_class`]. Written beside it because the two // are one answer with two audiences, and a reader that wants the class-aware half must not have to guess. put_opt_str(out, fact.returns_in_the_class()); @@ -1580,6 +2164,33 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { for constraint in fact.constraints() { put_str(out, constraint); } + // **The structured half of those constraints**, in the same parameter order. Each argument is tagged as a + // [`crate::ConstraintArgument`]: a type is written with the same [`ENCODED_COMPUTED_TYPE`] grammar the + // declaration's own types use, and a value keeps the text the file wrote — no value is written as a type name, + // and no spelling is parsed on the way back in. + put_u32(out, fact.constraint_facts().len() as u32); + for constraint in fact.constraint_facts() { + match constraint { + Some(constraint) => { + put_u8(out, 1); + put_str(out, &constraint.concept); + put_u32(out, constraint.arguments.len() as u32); + for argument in &constraint.arguments { + match argument { + ConstraintArgument::Type(argument) => { + put_u8(out, CONSTRAINT_ARGUMENT_IS_A_TYPE); + put_computed_type(out, argument); + } + ConstraintArgument::Value(text) => { + put_u8(out, CONSTRAINT_ARGUMENT_IS_A_VALUE); + put_str(out, text); + } + } + } + } + None => put_u8(out, 0), + } + } put_opt_str(out, fact.requires_clause()); put_u32(out, fact.parameter_defaults().len() as u32); for default in fact.parameter_defaults() { @@ -1620,6 +2231,9 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { // **And whether this declaration is an enumerator** — the flag whose absence made an anonymous enum's members // indistinguishable from variables; see [`DeclFact::enumerator`]. Last for the same reason. put_u8(out, u8::from(fact.enumerator)); + // **And whether the parameter list writes `...`** — the list's own token rather than a parameter's pack bit; see + // [`DeclFact::variadic_parameters`]. Last for the same reason as the two above. + put_u8(out, u8::from(fact.variadic_parameters)); } /// Write one macro fact — see [`put_declaration`] for why this is shared. @@ -1649,12 +2263,41 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let name = SmolStr::from(reader.string()?); let scope = reader.optional_string()?.map(SmolStr::from); let kind = decl_kind_from(reader.u8()?)?; - let type_of = reader.optional_string()?.map(SmolStr::from); - let returns = reader.optional_string()?; + let type_of = get_declared_type(reader)?; + let returns = get_declared_type(reader)?; + let parameters_id = index::params::ParamsId::from_raw(reader.u32()?); let returns_in_the_class = reader.optional_string()?; let bases = get_strings(reader)?; let parameters = get_strings(reader)?; let constraints = get_strings(reader)?; + let constraint_count = reader.count()?; + let mut constraint_facts = Vec::with_capacity(constraint_count.min(1024)); + for _ in 0..constraint_count { + match reader.u8()? { + 0 => constraint_facts.push(None), + 1 => { + let concept = SmolStr::from(reader.string()?); + let count = reader.count()?; + let mut arguments = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + arguments.push(match reader.u8()? { + CONSTRAINT_ARGUMENT_IS_A_TYPE => { + ConstraintArgument::Type(get_computed_type(reader, 0)?) + } + CONSTRAINT_ARGUMENT_IS_A_VALUE => { + ConstraintArgument::Value(SmolStr::from(reader.string()?)) + } + _ => return Err(DecodeError::BadDiscriminant), + }); + } + constraint_facts.push(Some(summary::ConstraintFact { + concept, + arguments: arguments.into_boxed_slice(), + })); + } + _ => return Err(DecodeError::BadDiscriminant), + } + } let requires_clause = reader.optional_string()?; let parameter_defaults = get_strings(reader)?; let parameter_list = reader.optional_string()?; @@ -1687,6 +2330,9 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { }; let definition = reader.u8()? != 0; let enumerator = reader.u8()? != 0; + // **The parameter list's own `...`** — see [`DeclFact::variadic_parameters`]. Read after the two flags it was + // written after; an entry from before this version is refused by the header rather than read here. + let variadic_parameters = reader.u8()? != 0; Ok(DeclFact { enumerator, @@ -1697,7 +2343,9 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { modifiers, frees, type_of, - returns: returns.map(SmolStr::from), + returns, + parameters: parameters_id, + variadic_parameters, split_by_a_directive, range, name_range, @@ -1713,6 +2361,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { reflection, parameters, constraints, + constraint_facts, requires_clause: requires_clause.map(Into::into), parameter_defaults, pattern: pattern.map(Into::into), @@ -1722,11 +2371,11 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { } /// A count-prefixed list of strings — the shape four fields of a declaration share. -fn get_strings(reader: &mut Reader<'_>) -> Result, DecodeError> { +fn get_strings(reader: &mut Reader<'_>) -> Result, DecodeError> { let count = reader.count()?; let mut found = Vec::with_capacity(count.min(1024)); for _ in 0..count { - found.push(reader.string()?); + found.push(SmolStr::from(reader.string()?)); } Ok(found) } @@ -1778,7 +2427,48 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// /// 5: the **exact subset** of those spans. A file can have nine branches decided by definitions and one decided by an /// assumption; the count alone can only suppress all ten, while the subset is what a client may paint. -const COOKED_VERSION: u32 = 5; +/// +/// 6: the reading carries its **local type table**, because a declaration fact's type is now a handle with no +/// spelling beside it (see [`CODEC_VERSION`] 44). A record written before this has strings where this decoder reads +/// the table, so it is refused rather than misread. +/// +/// 7: a reading's handles are **store handles** once it has been filed, and the table is rewritten with them (see +/// [`crate::ProjectIndex::insert_cooked`]). A record from the first version of this layout could hold a filed +/// reading's handles beside its pre-filing table — two ID spaces in one record — so it is refused rather than resolved +/// through the wrong nodes. The layout is unchanged; only records this decoder cannot trust are made unreachable. +/// +/// 8: the reading carries its **local parameter table**, because `DeclFact::parameters` is now the only stored +/// parameter representation (the build-time copy on `DeclDetail` was deleted). A record written before this has facts +/// whose parameter handles name a table it never wrote, so it is refused rather than resolved through an unrelated +/// arena — the same rule version 6 introduced for types. +/// +/// 9: the reading's declaration records gained the parameter list's own `...` byte ([`DeclFact::variadic_parameters`], +/// [`CODEC_VERSION`] 45). A record written before this has no such byte, so it is refused rather than decoded from the +/// bytes that follow it. +/// +/// 10: the reading's type table can hold a **C record's tag** (`EncodedTypeKind::ElaboratedRecord`, `CODEC_VERSION` +/// 46). The kind is a new discriminant, so a record written by this build is refused by an older one and an older +/// record — which can only hold the earlier kinds — would still decode; the number moves so that the two record +/// versions stay in step, which is the rule version 6 set for the shared type table. +/// +/// 11: the reading's declaration and parameter records carry **`ComputedType` values** rather than type-table +/// handles (`CODEC_VERSION` 47). A record written before this has two `u32` handles where this decoder expects the +/// first type byte, so it is refused rather than misread. +/// +/// 12: the reading's declaration records carry their **template-head constraints structurally** (`CODEC_VERSION` 48) +/// — one optional concept name and its type arguments per constrained parameter. A record written before this has +/// the `requires_clause` field where this decoder expects the structured slots, so it is refused rather than +/// misread. +/// +/// 13: the reading's declaration records carry an array's **bound structurally** (`CODEC_VERSION` 49, the +/// `ArrayExtent` name tag) — a record written before it has the old presence byte where a named dimension is now a +/// string, so it is refused rather than misread. +/// +/// 14: the reading's declaration records carry each template-head constraint argument **as an argument** +/// (`CODEC_VERSION` 50): a tag and the type, or the value's text. A record written before it writes the type grammar +/// tag where this decoder expects the argument tag, and a value argument of that record is a type named `42`, so it +/// is refused rather than decoded into that wrong answer. +const COOKED_VERSION: u32 = 14; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -1847,6 +2537,11 @@ fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { put_str(out, &diagnostic.message); } put_u32(out, reading.unplaced as u32); + // **And its parameter table**, for exactly the same reason: a `DeclFact::parameters` handle is local to the + // reading that issued it, so the table has to travel with the declarations or a warm start would resolve the + // handles through an unrelated arena. Written after the type table because the decoder reads it there; both are + // imported at [`ProjectIndex::insert_cooked`]. + put_params_store(out, &reading.parameters); } /// **One token of a rendering, with where it came from.** The origin is the half a `view` needs for navigation: @@ -1929,8 +2624,11 @@ pub fn decode_the_cooked_record( }); } let unplaced = reader.u32()? as usize; + // The reading's parameter table, written by [`put_cooked_body`] before the optional rendering. + let parameters = get_params_store(&mut reader)?; let reading = CookedFile { declarations, + parameters, macros, diagnostics, unplaced, @@ -2025,14 +2723,31 @@ fn get_origin(reader: &mut Reader<'_>) -> Result 0".into()), parameter_defaults: Vec::new(), parameter_list: None, @@ -2066,8 +2782,12 @@ fn a_cooked_reading_round_trips() { name: "f".into(), scope: None, kind: DeclKind::Function, - type_of: Some("int".into()), - returns: Some("void".into()), + type_of: DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Int))), + returns: DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Void))), + parameters: index::params::ParamsId::from_raw(0), + // **The parameter list's own `...`, at `true`** — a function whose list has a parameter and the + // marker beside it, which is the shape the byte exists for. + variadic_parameters: true, range: SourceRange::new(40, 30), name_range: SourceRange::new(44, 1), local: true, @@ -2084,9 +2804,16 @@ fn a_cooked_reading_round_trips() { returns_in_the_class: None, bases: Vec::new(), parameters: Vec::new(), - constraints: vec!["Copyable".to_string()], + constraints: vec!["SomeConcept<42>".into()], + // **A value argument travels through the cooked record too**, because a program read's facts + // are the same declaration records a summary holds — a decoder that dropped the tag here would + // answer `42` as a type on a warm start only. + constraint_facts: vec![Some(summary::ConstraintFact { + concept: "SomeConcept".into(), + arguments: vec![ConstraintArgument::Value("42".into())].into_boxed_slice(), + })], requires_clause: None, - parameter_defaults: vec!["0".to_string()], + parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), pattern: None, in_namespace: None, @@ -2125,6 +2852,15 @@ fn a_cooked_reading_round_trips() { Some("sizeof(T) > 0") ); assert_eq!(back.declarations[0].pattern(), Some("Widget")); + // **A constraint's value argument comes back as a value**, not as a type named `42`: the record carries the + // argument tag, and the cooked path is the one a warm start reads. + assert_eq!( + back.declarations[1].constraint_facts()[0] + .as_ref() + .map(|constraint| constraint.arguments.as_ref()), + Some([ConstraintArgument::Value("42".into())].as_slice()), + "the value argument survives the cooked record" + ); assert_eq!(back.declarations[0].range, SourceRange::new(10, 20)); assert_eq!(back.declarations[0].access, Some(Access::Public)); assert_eq!( @@ -2136,6 +2872,10 @@ fn a_cooked_reading_round_trips() { assert_eq!(back.declarations[1].frees, 3); assert!(back.declarations[1].local); assert!(back.declarations[1].split_by_a_directive); + // **The list-level `...` survives the record**, at both values — the class above says `false`, the function + // here says `true`, and a decoder that dropped the byte would answer `false` for both. + assert!(!back.declarations[0].variadic_parameters); + assert!(back.declarations[1].variadic_parameters); assert_eq!(back.macros.len(), 1); assert_eq!(back.macros[0].name, "_STD_BEGIN"); assert_eq!(back.macros[0].body_range, Some(SourceRange::new(20, 14))); @@ -2143,6 +2883,29 @@ fn a_cooked_reading_round_trips() { assert_eq!(back.diagnostics.len(), 1); assert_eq!(back.diagnostics[0].message, "expected `;`"); assert_eq!(back.unplaced, 2); + // **The parameter table travels with the facts that name it**, and the types travel as values on the facts. + assert_eq!( + back.parameters, reading.parameters, + "the parameter table travels with the facts that name it" + ); + assert_eq!( + back.parameters + .parameters(back.declarations[1].parameters) + .first() + .and_then(|parameter| parameter.name.as_deref()), + Some("value"), + "and the decoded fact's handle still names its entry" + ); + assert_eq!( + back.declarations[1].type_of, + DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Int))), + "the decoded fact carries its type value" + ); + assert_eq!( + back.declarations[1].returns, + DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Void))), + "and its return value" + ); // **The format's own guards**, which is what the magic and the version are for: a record from another // producer, or from a different layout, must be refused rather than decoded into facts nobody wrote. diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 0448985e..925c6c1c 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -47,7 +47,39 @@ use crate::summary::{RenderedUnit, UnitMessage, UnitSpan}; const MAGIC: [u8; 4] = *b"UNIT"; /// Bumped when the layout changes; an older record is then unreachable rather than misread. -pub const UNIT_CODEC_VERSION: u32 = 4; +/// +/// 5: each file's facts are encoded through the summary codec's declaration record, which no longer carries a type +/// spelling — the reading's types are values inside the summary-shaped body instead. +/// +/// 6: the per-file records a program read writes come from [`crate::ProjectIndex::insert_cooked`]'s rewritten table. +/// A unit record from the first version of this layout could pair filed handles with a pre-filing table, so it is +/// refused rather than resolved through the wrong nodes. +/// +/// 7: each file's record now carries its **parameter table** through the summary-shaped body — the field the +/// cooked-reading codec gained in its version 8. A record written before it has facts whose `ParamsId`s name a table +/// it never wrote, so it is refused rather than resolved through an unrelated arena. +/// +/// 8: the summary-shaped body's declaration records gained the parameter list's own `...` byte — the field +/// [`crate::summary_codec::CODEC_VERSION`] 45 added. A record written before it has a fact record the summary decoder +/// would read from the wrong offsets, so it is refused rather than misread. +/// +/// 9: the summary-shaped body's declaration records carry `ComputedType` values rather than type-table handles — the +/// field [`crate::summary_codec::CODEC_VERSION`] 47 changed. A record written before it has handles where the decoder +/// expects type values, so it is refused rather than misread. +/// +/// 10: those declaration records now carry their **template-head constraints structurally** — the field +/// [`crate::summary_codec::CODEC_VERSION`] 48 added. A record written before it has the `requires_clause` field where +/// the decoder expects the structured slots, so it is refused rather than misread. +/// +/// 11: those declaration records now carry an array's **bound structurally** — the field +/// [`crate::summary_codec::CODEC_VERSION`] 49 added. A record written before it has the old presence byte where the +/// decoder expects a named dimension's string, so it is refused rather than misread. +/// +/// 12: those declaration records now carry each template-head constraint argument **as an argument** — the field +/// [`crate::summary_codec::CODEC_VERSION`] 50 added. A record written before it writes the type grammar tag where +/// the decoder expects the argument tag, and a value argument of that record is a type named `42`, so it is refused +/// rather than decoded into that wrong answer. +pub const UNIT_CODEC_VERSION: u32 = 12; #[derive(Debug)] pub enum DecodeError { @@ -450,6 +482,7 @@ pub fn decode_indexed_unit(bytes: &[u8]) -> Result { path, CookedFile { declarations: summary.declarations, + parameters: summary.parameters, macros: summary.macros, diagnostics, unplaced, @@ -488,6 +521,7 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { path: path.to_path_buf(), key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), + parameters: cooked.parameters.clone(), macros: cooked.macros.clone(), includes: Vec::new(), guards: SummaryGuards::default(), @@ -503,6 +537,7 @@ mod index_tests { use crate::CookedDiagnostic; use crate::CookedFile; use crate::IndexedUnit; + use crate::index; #[test] fn an_indexed_unit_survives_a_round_trip() { @@ -511,6 +546,7 @@ mod index_tests { PathBuf::from("/p/a.h"), CookedFile { declarations: Vec::new(), + parameters: index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: vec![CookedDiagnostic { range: SourceRange::new(3, 4), diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index e060c3f6..fc3957e0 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -44,6 +44,7 @@ use crate::ModuleUnit; use crate::RenderedUnit; use crate::directive; use crate::guards; +use crate::index::params::ParamsStore; use crate::preprocess; use crate::sema; use crate::summary; @@ -69,10 +70,12 @@ use cpp_parser::{CppParser, CppSyntaxTree, ParserConfig}; pub mod effect; pub mod environment; mod names; +pub mod params; pub mod project; pub mod references; pub mod store; pub mod surface; +pub mod syntax; pub mod types; pub mod walk_census; pub mod watch; @@ -826,9 +829,10 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { .map(|error| source_range(error.range)) .collect(); - let (mut declarations, mut guards) = - { build_facts(&scopes, &preprocessing, &root, &errors, keep_locals) }; - + let built = build_facts(&scopes, &preprocessing, &root, &errors, keep_locals); + let mut declarations = built.facts; + let mut guards = built.guards; + let parameters = built.parameters; let mut interner = PathInterner::new(cfg!(windows)); // **This file's compilation, not the project's** — see `CompilerConfig::for_file`. let per_file = self.config.for_file(path); @@ -959,6 +963,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { path: path.to_path_buf(), key, declarations, + parameters, macros, includes, guards, @@ -1093,6 +1098,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { // like a real one would invite exactly that. The walk does not read it. key: SummaryKey::new(0, 0), declarations: Vec::new(), + parameters: ParamsStore::default(), macros, includes, guards, @@ -1687,7 +1693,7 @@ fn file_what_was_found( // The count is not lost: [`crate::IndexedUnit::errors`] is the stream's own count, and a consumer that wants to // say "this program did not parse" has it. What is *not* published is a place for it, because the place the // stream gives does not name one. - let _ = (tree, files, unplaced); + let _ = tree; } /// Give `#include "local.h"` the token the parser gives it: a header name — **the shared implementation lives in diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs new file mode 100644 index 00000000..94302533 --- /dev/null +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -0,0 +1,312 @@ +//! **Parameters as facts, built from the CST once.** +//! +//! A declaration's parameters are not text. The tree already has a `CppParam` for each one, the parameter's name, its +//! declarator, its default-value initializer and whether it is a pack. This module turns those nodes into storage +//! facts; no query may parse a parameter list again. +//! +//! **The list-level `...` is not one of these facts.** `void f(int, ...)` writes one `CppParam` and a `...` beside it, +//! and `void f(...)` writes no parameter at all — the marker is a token of the `CppParamList`, so no +//! [`ParameterFact`] describes it. It is read from the same list node by the builder that reads these facts +//! ([`parameter_facts_of`]'s callers) and stored on the declaration as +//! [`crate::DeclFact::variadic_parameters`], because a fact does not always have a `ParamsStore` that travels with it. +//! [`ParameterFact::pack`] is the other spelling and stays right here: `T... rest` writes its marker **inside** the +//! parameter node, and that one *is* a property of a parameter. +//! +//! **The type is a [`DeclaredType`], the same representation a [`DeclFact`](crate::summary::DeclFact)'s own types +//! use.** A parameter's type is the immutable [`ComputedType`](crate::index::types::ComputedType) the builder lowered +//! from the parameter's own `CppParam` node at construction — no handle, no arena, and no spelling field. +//! [`crate::ProjectIndex::parameter_type`] answers that value, and nothing re-parses a type on the way. +use cpp_parser::CppAstNode; +use cpp_parser::CppInitializer; +use cpp_parser::CppParam; +use cpp_parser::CppParamList; +use cpp_parser::CppSyntaxId; +use cpp_parser::CppTokenKind; +use smol_str::SmolStr; + +use crate::cache::summary::DeclaredType; +use rustc_hash::FxHashMap; +use std::mem::size_of; + +/// **One parameter, as the CST declares it.** The declaration/default are `SyntaxId`s, not text; a default value can +/// be any expression (`std::map{…}`, a lambda call, `sizeof(T) * 2`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct ParameterFact { + pub name: Option, + /// The `Parameter` node itself. Resolving it gives the source spelling and the declaration's own ranges. + pub declaration: CppSyntaxId, + /// The initializer expression after `=`, when one is written. + pub default_value: Option, + /// **A parameter pack** — `T... rest`, `Args&&... args`, `double... rest`. Its marker is written inside the + /// `Parameter` node, which is why it is a property of *this* fact; the C-style list-level `...` of + /// `void f(int, ...)` is not a parameter and is stored on [`crate::DeclFact::variadic_parameters`] instead. + pub pack: bool, + /// **The type this parameter is declared with** — see [`DeclaredType`]. A summary's fact holds a handle into the + /// one global store; a view fact holds the computed value, because a view has no store to intern into. + pub type_of: DeclaredType, +} + +/// **Read every parameter from a real `CppParamList`.** This is the only reader a fact builder calls. +pub fn parameter_facts_of(list: &CppParamList) -> Vec { + list.get_params().map(fact_of).collect() +} + +/// A handle to one parameter list in a [`ParamsStore`]; `u32::MAX` is `NONE`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ParamsId(u32); + +impl ParamsId { + pub const NONE: ParamsId = ParamsId(u32::MAX); + + pub fn index(self) -> usize { + self.0 as usize + } + + pub fn raw(self) -> u32 { + self.0 + } + + pub fn from_raw(raw: u32) -> ParamsId { + ParamsId(raw) + } + + pub fn is_none(self) -> bool { + self == ParamsId::NONE + } +} + +/// **Parameter lists, hash-consed.** A declaration points at one entry; two declarations with the same parameter list +/// share it. Nothing here parses: the entries are built from CST facts and are immutable after indexing. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct ParamsStore { + entries: Vec>, + ids: FxHashMap, ParamsId>, +} + +impl ParamsStore { + pub fn new() -> ParamsStore { + ParamsStore::default() + } + + pub fn len(&self) -> usize { + self.entries.len() + } + + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + pub fn intern(&mut self, facts: Vec) -> ParamsId { + if facts.is_empty() { + return ParamsId::NONE; + } + let facts: Box<[ParameterFact]> = facts.into_boxed_slice(); + if let Some(id) = self.ids.get(&facts) { + return *id; + } + let id = ParamsId(self.entries.len() as u32); + self.entries.push(facts.clone()); + self.ids.insert(facts, id); + id + } + + pub fn parameters(&self, id: ParamsId) -> &[ParameterFact] { + self.get(id).unwrap_or(&[]) + } + + /// **The entry an id names, or `None`** — what a resolver that must tell "this store has no such list" from + /// "this list is empty" asks. A store only ever interns a non-empty list (`NONE` is the empty answer), so the + /// two are genuinely different questions: an id outside the table belongs to another arena. + pub fn get(&self, id: ParamsId) -> Option<&[ParameterFact]> { + self.entries.get(id.index()).map(|facts| facts.as_ref()) + } + + pub fn entries(&self) -> &[Box<[ParameterFact]>] { + &self.entries + } + + /// Rebuild a local table from a decoded record. Entry order is the local ID. + pub fn from_entries(entries: Vec>) -> ParamsStore { + let mut store = ParamsStore::new(); + for facts in entries { + store.intern(facts.into_vec()); + } + store + } + + /// **Import another store's local handles**, deduplicating against this one. + pub fn import(&mut self, from: &ParamsStore) -> FxHashMap { + let mut mapping = FxHashMap::default(); + for (at, facts) in from.entries.iter().enumerate() { + mapping.insert(ParamsId(at as u32), self.intern(facts.to_vec())); + } + mapping + } + + /// Lower-bound heap accounting, in the same style as the type store. + pub fn accounting(&self) -> usize { + self.entries.len() * size_of::>() + + self + .entries + .iter() + .map(|facts| facts.len() * size_of::()) + .sum::() + + self.ids.len() * size_of::<(Box<[ParameterFact]>, ParamsId)>() + } +} + +fn fact_of(parameter: CppParam) -> ParameterFact { + let default_value = parameter + .get_default_value() + .map(|initializer: CppInitializer| CppSyntaxId::from_node(initializer.syntax())); + + ParameterFact { + name: parameter.get_name_text().map(SmolStr::from), + declaration: CppSyntaxId::from_node(parameter.syntax()), + default_value, + pack: parameter + .syntax() + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Ellipsis), + // **No type yet.** Lowering it is the fact builder's step — the summary's + // (`crate::sema::declarations::fact_for`) and the view synthesizer's (`crate::index::project`), both of + // which apply the declaration's template parameters and store a `ComputedType`. This reader is the CST half + // only. + type_of: DeclaredType::None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cpp_parser::{CppParser, ParserConfig}; + + fn parameter_list(source: &str) -> CppParamList { + let tree = CppParser::parse(source, ParserConfig::default()); + tree.get_red_root() + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list") + } + + fn parameters(source: &str) -> Vec { + parameter_facts_of(¶meter_list(source)) + } + + /// **The list-level `...` is a token of the list, and a pack is a token of a parameter.** + /// + /// The two spellings are one token kind in the lexer and different facts here: `void f(int, ...)` writes one + /// `CppParam` and the marker beside it, `void f(...)` writes no parameter at all, and `T... rest` / + /// `Args&&... args` write the marker **inside** the `Parameter` node. The first two are + /// [`crate::DeclFact::variadic_parameters`] (read from `CppParamList::is_variadic` by the fact builders); the last + /// two are [`ParameterFact::pack`]. Mixing them would make `(...)` unrepresentable as a list with no parameters and + /// would call every pack a variadic list. + #[test] + fn a_trailing_ellipsis_is_the_lists_own_token() { + let list = parameter_list("void f(int a, ...);\n"); + assert!(list.is_variadic(), "the trailing `...` belongs to the list"); + let facts = parameter_facts_of(&list); + assert_eq!(facts.len(), 1, "and it is not a parameter of its own"); + assert!(!facts[0].pack, "`int a` is not a pack"); + + let list = parameter_list("void f(...);\n"); + assert!(list.is_variadic(), "`(...)` is variadic"); + assert_eq!( + parameter_facts_of(&list).len(), + 0, + "and writes no parameter — the empty list is `NONE`, which is why the list's bit is on the fact" + ); + + for source in ["void f(T... rest);\n", "void f(Args&&... args);\n"] { + let list = parameter_list(source); + assert!( + !list.is_variadic(), + "a pack is the parameter's marker, not the list's: {source:?}" + ); + let facts = parameter_facts_of(&list); + assert_eq!(facts.len(), 1, "one parameter in {source:?}"); + assert!(facts[0].pack, "and it is the pack: {source:?}"); + } + + let list = parameter_list("void f(int a, double b);\n"); + assert!(!list.is_variadic(), "an ordinary list has no `...`"); + assert!( + parameter_facts_of(&list).iter().all(|fact| !fact.pack), + "and no pack" + ); + + // **A `...` written inside a default's literal is not the list's token**, which is the false positive a scan + // of the display spelling produced: `void log(const char* dots = "...")` is not variadic. + let list = parameter_list("void f(const char* text = \"...\");\n"); + assert!(!list.is_variadic()); + assert!( + parameter_facts_of(&list)[0].default_value.is_some(), + "the default is an initializer node, not part of the list's tokens" + ); + } + + #[test] + fn names_defaults_and_packs_come_from_the_tree() { + let facts = + parameters("void f(int a, std::map m = {{1, 2}}, auto... rest, ...);\n"); + assert_eq!( + facts.len(), + 3, + "the trailing ellipsis is a token, not a CppParam" + ); + assert_eq!(facts[0].name.as_deref(), Some("a")); + assert!(facts[0].default_value.is_none()); + assert_eq!(facts[1].name.as_deref(), Some("m")); + assert!( + facts[1].default_value.is_some(), + "a braced default is an initializer node, not a string" + ); + assert_eq!(facts[2].name.as_deref(), Some("rest")); + assert!(facts[2].pack); + // **The CST reader states no type** — lowering is the fact builder's step, and both builders fill it in. + // See `sema::declarations::fact_for` and `fact_from_binding_with`; the structural lowering itself is pinned + // by `tests/params.rs` and by `sema::overload`'s own tests. + assert_eq!(facts[2].type_of, DeclaredType::None); + } + + #[test] + fn equal_parameter_lists_share_one_entry() { + let facts = parameters("void f(int a, double b);\n"); + let mut store = ParamsStore::new(); + let first = store.intern(facts.clone()); + let second = store.intern(facts); + assert_eq!(first, second); + assert_eq!(store.len(), 1); + assert_eq!(store.parameters(first).len(), 2); + assert!(store.accounting() > 0); + assert_eq!(store.intern(Vec::new()), ParamsId::NONE); + } + + #[test] + fn importing_a_local_table_rebases_its_handles() { + let mut source = ParamsStore::new(); + let first = source.intern(parameters("void f(int a);\n")); + let second = source.intern(parameters("void f(int a);\n")); + // Two entries here are possible only if the facts differ; make one differ explicitly. + let _ = second; + let different = source.intern(parameters("void g(double b);\n")); + + let mut destination = ParamsStore::new(); + let mapping = destination.import(&source); + assert_eq!(mapping.len(), source.len()); + assert_eq!( + destination.parameters(mapping[&first]).len(), + source.parameters(first).len() + ); + assert!(mapping.contains_key(&different)); + } + + #[test] + fn an_unnamed_parameter_keeps_its_node() { + let facts = parameters("void f(int);\n"); + assert_eq!(facts.len(), 1); + assert!(facts[0].name.is_none()); + assert!(!facts[0].declaration.get_range().is_empty()); + } +} diff --git a/crates/cpp_code_analysis/src/index/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index cba62f15..9eacdadd 100644 --- a/crates/cpp_code_analysis/src/index/project/aliases.rs +++ b/crates/cpp_code_analysis/src/index/project/aliases.rs @@ -88,8 +88,8 @@ pub(crate) fn a_spelling_through_the_aliases( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class: &Type, - visited: &[Type], + class: &ComputedType, + visited: &[ComputedType], written: &str, depth: usize, ) -> String { @@ -108,7 +108,7 @@ pub(crate) fn a_spelling_through_the_aliases( impl ProjectIndex { /// **Resolve a qualified spelling through the aliases declared by its class** — the public entry point of the - /// walk in this module, for a caller that has a class spelling and a member expression rather than a `Type`. + /// walk in this module, for a caller that has a class spelling and a member expression rather than a `ComputedType`. /// /// `class` is the qualifier (`Text`, `Source::Viewer<>`) and `written` is what follows it (`StrV`, `Type`). /// The answer is the spelling the aliases make of it, or `written` itself when the walk cannot improve it. A @@ -170,8 +170,8 @@ pub(crate) fn a_spelling_through_the_aliases_in( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class: &Type, - visited: &[Type], + class: &ComputedType, + visited: &[ComputedType], environment: &[(String, String)], written: &str, depth: usize, @@ -226,7 +226,7 @@ pub(crate) fn a_spelling_through_the_aliases_in( // (`using typename _Base::value_type;`), and stopping at it would answer nothing where the class it // came from had the type: measured, `vector`'s own `tp_alloc_type` is `typename base::tp_alloc_type` // with no type recorded, and taking it ended the chain at `Alloc>::template rebind::other`. - && fact.type_of.is_some() + && index.type_spelling_of(&fact).is_some() { found = Some((candidate.clone(), fact)); break; @@ -259,13 +259,13 @@ pub(crate) fn a_spelling_through_the_aliases_in( let Some((declared_in, fact)) = found else { return written.to_string(); }; - let Some(target) = fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(&fact) else { return written.to_string(); }; // **The substitution is everything in scope**, which is what makes a name three classes back meaningful: // `vector`'s `_Tp_alloc_type` is `_Base::_Tp_alloc_type`, and `_Base` is its parameter — while the `Alloc` a // nested class writes was paired two levels up. See [`substituted_through`]. - let target = substituted_through(target, ¶meters, &defaults, &arguments, environment); + let target = substituted_through(&target, ¶meters, &defaults, &arguments, environment); if target == core { return written.to_string(); } @@ -411,7 +411,7 @@ pub(crate) fn a_spelling_through_the_aliases_in( // Measured on `Mark.cpp`: without this, the walk stopped at `__gnu_cxx::__alloc_traits<…>::template // rebind::other` — the spelling the report calls "极其夸张" — because `rebind` was never a // name any lookup was asked about. - if fact.kind == DeclKind::Type && fact.type_of.is_none() && !member_arguments.is_empty() { + if fact.kind == DeclKind::Type && !fact.has_type_of() && !member_arguments.is_empty() { let resolved_arguments: Vec = member_arguments .iter() .map(|argument| { @@ -427,7 +427,7 @@ pub(crate) fn a_spelling_through_the_aliases_in( return format!("{leading}{nested}{trailing}"); } - let Some(target) = fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(&fact) else { return written.to_string(); }; // The pattern's slots are what say which written argument each parameter takes. @@ -444,7 +444,7 @@ pub(crate) fn a_spelling_through_the_aliases_in( // chain ended at `Alloc>::template rebind::other`. The environment covers a third: a name the *enclosing* // class of a nested one wrote. let target = substituted_through( - target, + &target, &pattern_parameters, &inner_defaults, &pattern_arguments, @@ -521,12 +521,11 @@ pub(crate) fn a_member_the_class_declares( members .members .iter() - .filter(|member| member.fact.name == name) - .filter(|member| { - a_pattern_matches(member.fact.pattern(), ¶meters, Some(&arguments)) - }) - .map(|member| member.fact.clone()) - .find(|fact| fact.type_of.is_some()) + .filter(|member| index.member_name(member) == name) + .filter_map(|member| index.member_fact(member)) + .filter(|fact| a_pattern_matches(fact.pattern(), ¶meters, Some(&arguments))) + .find(|fact| index.type_spelling_of(fact).is_some()) + .cloned() }) { return Some(found); } @@ -757,7 +756,7 @@ pub(crate) fn the_class_an_arrow_points_at( )?; // **Before `arrow` is partially moved below** — its parameters say whether an answer is one of them. let arrows_parameters = arrow.parameters().to_vec(); - let returns = arrow.returns?; + let returns = index.returns_spelling_of(&arrow)?.to_string(); if arguments.is_empty() { return None; @@ -825,7 +824,7 @@ pub(crate) fn the_class_an_arrow_points_at( || index .files_declaring(bare, path) .iter() - .any(|found| found.fact.kind == DeclKind::Type && found.fact.type_of.is_none()) + .any(|found| found.fact.kind == DeclKind::Type && !found.fact.has_type_of()) }; let walked = the_element_type_of(index, scopes, root, path, class, &bare, &arguments); target = match walked { @@ -933,15 +932,15 @@ pub(crate) fn the_element_type_of( let Some(fact) = members .members .iter() - .find(|member| member.fact.name == name) - .map(|member| &member.fact) + .find(|member| index.member_name(member) == name) + .and_then(|member| index.member_fact(member)) else { continue; }; - let Some(written) = fact.type_of.as_deref() else { + let Some(written) = index.type_spelling_of(fact) else { continue; }; - let substituted = sema::types::substituted_spelling(written, ¶meters, arguments); + let substituted = sema::types::substituted_spelling(&written, ¶meters, arguments); let target = base_type_name(&substituted).to_string(); // A parameter name is not an answer: it means the declaration named something this call cannot substitute. diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 73e2a86a..56878261 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -9,10 +9,16 @@ use crate::BindingKind; use crate::DeclKind; use crate::ScopeKind; use crate::ScopeTree; +use crate::index; +use crate::index::types::ComputedType; use crate::sema; use crate::summary; +use crate::summary::DeclaredType; +use cpp_parser::CppAstNode; +use cpp_parser::CppParam; use cpp_parser::CppSyntaxNode; use smol_str::SmolStr; +use std::sync::Arc; pub(crate) fn direct_member( shapes: &sema::declarations::ShapeTable, @@ -45,7 +51,8 @@ pub(crate) fn direct_member( root, class, binding, - ), + ) + .fact, path.to_path_buf(), )); } @@ -129,7 +136,9 @@ pub(crate) fn direct_member( // out of line can have been filed under a spelling the class's own scope is not (`C::f` for a definition // written outside `C`), and that is exactly what this lookup is for. match index.definition(&format!("{class}::{member}"), path) { - Known::Yes(found) => Some((found.fact, found.file)), + Known::Yes(found) => index + .definition_parts(&found) + .map(|(fact, file)| (fact.clone(), file.to_path_buf())), Known::Unknown(_) | Known::No => None, } } @@ -140,10 +149,10 @@ pub(crate) fn direct_member( /// `true`: a class with no pattern is an ordinary class and matches any use of its name, and a use whose arguments /// could not be read is not evidence against the declaration. That direction is deliberate — this rule removes a /// **wrong** answer, and a spelling it could not read must not remove a right one. -pub(crate) fn a_pattern_matches( +pub(crate) fn a_pattern_matches, W: AsRef>( pattern: Option<&str>, - parameters: &[String], - written: Option<&[String]>, + parameters: &[N], + written: Option<&[W]>, ) -> bool { let (Some(pattern), Some(written)) = (pattern, written) else { return true; @@ -165,7 +174,7 @@ pub(crate) fn a_pattern_matches( slots.iter().zip(written).all(|(slot, argument)| { // A **slot** is one of the class's own parameters, and takes whatever the use put there; anything else has // to **match** it. `_Ty` against `int` matches; `shared_ptr<_Ty>` against `int` does not. - a_slot_matches(slot, argument, parameters) + a_slot_matches(slot, argument.as_ref(), parameters) }) } @@ -181,9 +190,9 @@ pub(crate) fn a_pattern_matches( /// same rule [`rank_of`] and the bare-name lookups elsewhere in this file use. A head that is not a template id is /// compared as text: a bare name in a pattern is a name written in the pattern's own scope, and there is no second /// spelling of it to reconcile. -pub(crate) fn a_slot_matches(slot: &str, argument: &str, parameters: &[String]) -> bool { +pub(crate) fn a_slot_matches>(slot: &str, argument: &str, parameters: &[N]) -> bool { let slot = slot.trim(); - if parameters.iter().any(|name| name == slot) { + if parameters.iter().any(|name| name.as_ref() == slot) { return true; } let argument = folded_for_matching(argument); @@ -241,6 +250,25 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { (!out.is_empty()).then_some(out) } +/// **A fact a query synthesized from a view, with the parameter list no summary table owns.** +/// +/// A view fact is built from a buffer's own tree, and there is no [`crate::FileSummary`] behind it — so its +/// parameters have nowhere to be interned. The index's synthetic arena carries them beside the fact, keyed by the +/// [`FactRef`] the interning call returns; [`ProjectIndex::parameter_facts_of`] resolves them from there. This is +/// the view-side counterpart of `FileSummary::parameters`, **not** a second `ParamsStore`: there is no id space and no +/// interning. Each parameter's type is [`crate::cache::summary::DeclaredType::Computed`] — the value the builder +/// lowered from its own `CppParam`, so it travels with the fact like any other type value; no store or `TypeId` is +/// second store would alias the one global store. The two halves travel together for the same reason the summary's +/// facts and its table do — a fact whose list was dropped must not keep a handle that names nothing. +/// +/// **The list's own `...` is not in this pair.** It is [`DeclFact::variadic_parameters`], read from the same +/// `CppParamList` and stored on the fact, so the synthetic arena carries the parameters and nothing else — a +/// variadic list with no parameter (`void f(...)`) needs no entry in this list to be representable. +pub(crate) struct SynthesizedFact { + pub fact: DeclFact, + pub parameters: Box<[index::params::ParameterFact]>, +} + /// One binding as a [`DeclFact`], under the qualified name of the scope it was written in. /// /// The single reader of a binding's fact-shaped fields, shared by the single-member query and the member-list @@ -263,7 +291,11 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { /// and a consumer showing a member list has nothing to gain from either, which is why neither was worth /// threading the tree through every query for. The same applies to the facts [`member_across_files`] returns /// from this path. -pub(crate) fn fact_from_binding(root: &CppSyntaxNode, class: &str, binding: &Binding) -> DeclFact { +pub(crate) fn fact_from_binding( + root: &CppSyntaxNode, + class: &str, + binding: &Binding, +) -> SynthesizedFact { fact_from_binding_with( &sema::declarations::DeclarationShapes::of(root), root, @@ -281,14 +313,82 @@ pub(crate) fn fact_from_binding(root: &CppSyntaxNode, class: &str, binding: &Bin /// and the answers are a lookup each. Passing the table in makes the whole list cost one pass — the same defect, and /// the same fix, that [`DeclarationShapes`](crate::sema::declarations::DeclarationShapes) records for the index /// builder. +/// +/// # Why the parameters are returned beside the fact +/// +/// The fact's `parameters` field is a [`crate::index::params::ParamsId`], which is only meaningful with the +/// [`crate::index::params::ParamsStore`] that issued it. A view has no summary, so there is no such store — the list +/// is returned here and the index puts it in its synthetic arena when the fact is interned +/// ([`ProjectIndex::intern_a_view_fact`]). A caller that only reads the fact (a type query, a member lookup) drops +/// the list; it is the member list and the completion that intern the fact, and they are the callers that keep it. pub(crate) fn fact_from_binding_with( shapes: &sema::declarations::DeclarationShapes, root: &CppSyntaxNode, class: &str, binding: &Binding, -) -> DeclFact { +) -> SynthesizedFact { let _ = root; - DeclFact { + // **The two types this path can state, lowered structurally once.** The readers below answer a + // [`ComputedType`] from the buffer's own syntax; the fact then carries the immutable + // [`ComputedType`] that value denotes. No store, no id, and no second parse: the declaration's template parameters + // are applied to the structure before it is lowered. + let written_type_of = + sema::declarations::declared_type_of_with(shapes, binding).or_else(|| { + // **A member whose type is an unnamed class body**, named the way the index names it — see + // [crate::sema::declarations::an_unnamed_class_body_named]. The two paths that build a fact must + // agree, and this one is what a member query against the open file uses. + sema::declarations::an_unnamed_class_body_named( + Some(class), + &binding.name.text(), + shapes, + binding, + ) + }); + let written_returns = sema::declarations::declared_returns_of_in(shapes, root, binding) + .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)); + // **The class's and the member's template parameters**, so a type written `T&` is a parameter rather than a + // class named `T`, and a member list that instantiates the class substitutes it. Read once: it is both this + // path's substitution key (through the computed types) and the fact's `parameters` field. + let template_parameters = + sema::declarations::declared_template_parameters_with(shapes, binding); + let lower = |written: Option| { + written.map_or(DeclaredType::None, |written| { + let written = sema::types::with_template_parameters(written, &template_parameters); + DeclaredType::Computed(Arc::new(written)) + }) + }; + let returns_written = written_returns.is_some(); + if binding.name.text() == "pointer" { + eprintln!("[view fact] {:?}", written_type_of); + } + let type_of = lower(written_type_of); + let returns = lower(written_returns); + // **The parameter list, read once and kept beside the fact.** A view has no `ParamsStore`, so the list cannot be + // interned here; the index's synthetic arena owns it once the fact is interned (see [`SynthesizedFact`]). Each + // parameter's type is lowered **from its own `CppParam` node** into the computation layer — the same structural + // read the summary's builder makes, with the declaration's template parameters applied — and stored as + // [`DeclaredType::Computed`]: no spelling is parsed. + // + // **The list-level `...` is a fact field, not part of the list here.** It is read from the same `CppParamList` and + // stored on the fact as [`DeclFact::variadic_parameters`], which is why the synthetic arena needs no third piece: + // a view fact answers whether its callee is variadic the same way a summary's does, and `(...)` (variadic with no + // parameter) is representable without a list entry. + let declared_parameters = sema::declarations::declared_parameter_facts_with(shapes, binding); + let variadic_parameters = declared_parameters.variadic; + let parameters = { + let mut parameters = declared_parameters.facts; + for parameter in &mut parameters { + if let Some(node) = parameter.declaration.to_node_from_root(root) + && let Some(cpp) = CppParam::cast(node) + && let Some(written) = sema::types::type_of_a_parameter(&cpp) + { + let written = sema::types::with_template_parameters(written, &template_parameters); + parameter.type_of = DeclaredType::Computed(Arc::new(written)); + } + } + parameters.into_boxed_slice() + }; + let fact = DeclFact { enumerator: binding.kind == BindingKind::Enumerator, split_by_a_directive: sema::declarations::split_by_a_directive_with(shapes, binding), // **The spelling, the same one the index stores** — `operator[]`, `~Widget`, `operator int`. @@ -329,32 +429,25 @@ pub(crate) fn fact_from_binding_with( as u16, // **Read by the index path too**, when a member query leaves the file: the annotation is a fact like any other, // and a hover on a `UPROPERTY` member should find its specifiers wherever the member is declared. - type_of: sema::declarations::declared_type_of_with(shapes, binding) - .or_else(|| { - // **A member whose type is an unnamed class body**, named the way the index names it — see - // [crate::sema::declarations::an_unnamed_class_body_named]. The two paths that build a fact must - // agree, and this one is what a member query against the open file uses. - sema::declarations::an_unnamed_class_body_named( - Some(class), - &binding.name.text(), - shapes, - binding, - ) - }) - .map(SmolStr::from), + // + // The type is a computation-side value: this fact is synthesized from a buffer, so it has no arena to intern + // into. See the prelude above for the one parse. + type_of, // Answered here as well, because **members** are exactly where a call happens: `fac.build().size` needs the - // return type of a member function that the file being edited declares. See [`DeclFact::returns`]. + // return type of a member function that the file being edited declares. // **The deduction, when the file wrote no return type.** `declared_returns_of_in` answers only what is written, and // `auto` is not — the index's fact deduces through `declared_returns_of`, so this one must too, or the same function // has a return type in one answer and none in the other. Measured: `make_sized` printed `std::array` from // `facts` and "a function" from the hover. - // **No table is built for the fallback.** declared_returns_of_in already answers the deduction - // (deduced_returns_of); what it refuses is the unusable operator spelling, which the _with form still - // returns — the wrapper declared_returns_of would build a whole declaration table to say the same thing, - // and that fallback was measured at 1 000 builds for one 901-line diagnostic pass. - returns: sema::declarations::declared_returns_of_in(shapes, root, binding) - .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)) - .map(SmolStr::from), + returns, + // **`NONE` because no store here issued an id for the list.** The list travels with the fact and the index + // files it in the synthetic arena; `ProjectIndex::parameter_facts_of` resolves it from there. See + // [`SynthesizedFact`]. + parameters: index::params::ParamsId::NONE, + // **The list's own `...`** — read from the same `CppParamList` the parameter facts came from, and stored on the + // fact so neither the synthetic arena nor a copy of the fact has to carry a second list to answer it. See + // [`DeclFact::variadic_parameters`]. + variadic_parameters, // **The same residue the index records**, because a member query is exactly the reader that has the class: // `parameters` and the class's file are both in hand here. See [`crate::DeclFact::returns_in_the_class`]. // @@ -365,16 +458,17 @@ pub(crate) fn fact_from_binding_with( // for members and a member is never a local. See [`DeclFact::in_namespace`]. in_namespace: None, returns_in_the_class: { - let returns = sema::declarations::declared_returns_of_in(shapes, root, binding) - .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)); - if returns.is_some() { + if returns_written { None } else { sema::declarations::the_returns_the_class_has_to_resolve(shapes, root, binding) .map(Into::into) } }, - bases: sema::declarations::declared_bases_of_with(shapes, binding), + bases: sema::declarations::declared_bases_of_with(shapes, binding) + .into_iter() + .map(SmolStr::from) + .collect(), reflection: None, // **Read by the index path too**, when a member query leaves the file: the annotation is a fact like any // other, and a hover on a `UPROPERTY` member should find its specifiers wherever it is declared. @@ -382,15 +476,25 @@ pub(crate) fn fact_from_binding_with( // produced it. These were empty here, with the argument that substitution is the caller's step. // Substitution still is — what these carry is the *names* to substitute and the class's written // **pattern**, and a caller that has the use's arguments cannot pair them without them. - parameters: sema::declarations::declared_template_parameters_with(shapes, binding), + parameters: template_parameters + .iter() + .cloned() + .map(SmolStr::from) + .collect(), constraints: Vec::new(), + // This path reads a *member*, and a member has no constraint of its own: the head that constrains a + // template is the class's, and the class's own fact is the one that carries it. + constraint_facts: Vec::new(), // **The clause the declaration writes**, from the same shape table the modifiers come from — the two // paths that build a fact must say the same thing. requires_clause: sema::declarations::the_requires_clause_with(shapes, binding) .map(Into::into), parameter_defaults: sema::declarations::declared_parameter_defaults_with( shapes, binding, - ), + ) + .into_iter() + .map(SmolStr::from) + .collect(), pattern: sema::declarations::pattern_of(shapes, binding).map(Into::into), // …but the **parameter list as written** is here, because this is the path a member list's detail line is // built from: `size()` and `size_type size() const` are two rows a reader tells apart by exactly this. @@ -420,7 +524,8 @@ pub(crate) fn fact_from_binding_with( name_range: binding.name_range, clean: true, guard: FactGuard::Unconditional, - } + }; + SynthesizedFact { fact, parameters } } /// **Is this base spelling one of the class's own template parameters?** — the filter [`members_of`] applies. @@ -543,7 +648,10 @@ pub(crate) fn bases_of_inner( Known::Yes(found) => { let mut bases: Vec = Vec::new(); for declaration in &found.found { - for base in lookup_names(declaration.fact.bases()) { + let Some(fact) = index.definition_fact(declaration) else { + continue; + }; + for base in lookup_names(fact.bases()) { if !bases.contains(&base) { bases.push(base); } @@ -591,11 +699,11 @@ pub(crate) fn bases_of_inner( /// only find a member one of the candidates really has, and the direction to err in is "found" rather than /// "missing". A language server that reports a name as undeclared because it could not evaluate a /// `conditional_t` is one that reports the standard library as broken. -pub(crate) fn lookup_names(bases: &[String]) -> Vec { +pub(crate) fn lookup_names>(bases: &[B]) -> Vec { let mut names: Vec = Vec::new(); for base in bases { - let parsed = parse_type_spelling(base); + let parsed = parse_type_spelling(base.as_ref()); collect_class_names(&parsed, &mut names); } @@ -607,7 +715,7 @@ pub(crate) fn lookup_names(bases: &[String]) -> Vec { /// The walk is over the **parsed type** rather than its text, so `_Normal_allocator_traits<_Alloc>` /// contributes `_Normal_allocator_traits` and not `_Alloc`, and a class named inside a nested template /// argument is found at whatever depth it was written. -pub(crate) fn collect_class_names(ty: &Type, into: &mut Vec) { +pub(crate) fn collect_class_names(ty: &ComputedType, into: &mut Vec) { if let Some(name) = ty.class_name() && !name.is_empty() && !into.iter().any(|kept| kept == name) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 157bd9a0..9cb0b38c 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -12,6 +12,7 @@ use crate::DeclModifiers; use crate::FileView; use crate::ScopeTree; use crate::completion; +use crate::index; use crate::sema; use cpp_parser::CppSyntaxNode; @@ -44,11 +45,18 @@ pub(crate) fn declaration_of_expression( // A finished type only: a member of a template base whose arguments the member list could not read is // refused rather than answered with the parameter's spelling. if let Some(member) = - a_member_of_the_enclosing_class(index, scopes, root, path, expression, true) + a_member_row_of_the_enclosing_class(index, scopes, root, path, expression, true) + && let (Some(fact), Some(file)) = ( + // **The row as a reader of this class sees it** — a base's `T *` is `Node *` here, and the + // `NamedDeclaration` below reads a spelling. The declaration itself is never rewritten; this is + // the display edge's copy of it. + index.member_display_fact(&member), + index.member_path(&member).map(Path::to_path_buf), + ) { return Known::Yes(NamedDeclaration::Indexed( - member.fact, - member.file, + fact, + file, TypeBindings::default(), )); } @@ -103,7 +111,9 @@ pub(crate) fn declaration_of_expression( let mut was_ambiguous = false; for candidate in candidates { let found: Option<(DeclFact, PathBuf)> = match index.definition(candidate, path) { - Known::Yes(found) => Some((found.fact, found.file)), + Known::Yes(found) => index + .definition_parts(&found) + .map(|(fact, file)| (fact.clone(), file.to_path_buf())), // **Several declarations of one name, and one type between them.** A name query answers // `Ambiguous` when more than one declaration is visible, and that is right for "where is this // declared" — but the question here is *what type it has*, and a type is not ambiguous when @@ -174,12 +184,12 @@ pub(crate) fn declaration_of_expression( /// /// `int (*fp)(int)` is a `Pointer` to a `Function`, and calling `fp(3)` has what that function returns. `None` for every other /// type, which is the ordinary case: a name whose type is not a function pointer is not called through one. -pub(crate) fn a_function_pointer_returns(a_type: &Type) -> Option { - let Type::Pointer { to } = a_type else { +pub(crate) fn a_function_pointer_returns(a_type: &ComputedType) -> Option { + let ComputedType::Pointer(to) = a_type else { return None; }; match to.as_ref() { - Type::Function { returns, .. } => Some(returns.as_ref().clone()), + ComputedType::Function(function) => Some((*function.returns).clone()), // A pointer to a *pointer* to a function is not this: C++ would need the intermediate dereference, and answering // the deep return type would make `(**fpp)(1)` and `fpp(1)` the same call. _ => None, @@ -198,7 +208,7 @@ pub(crate) fn a_lambdas_body_the_callee_names( root: &CppSyntaxNode, scopes: &ScopeTree, callee: &CppSyntaxNode, - argument_types: &[Type], + argument_types: &[ComputedType], ) -> Option { let inside = callee.text_range(); let Known::Yes(binding) = sema::resolve::definition_at(scopes, root, inside.start().into()) @@ -233,7 +243,7 @@ pub(crate) fn type_of_a_call( // is typed by typing that call (see [`the_return_the_body_gives_back`]), which is one more question of the same // kind. Without the bound, `auto f() { return g(); } auto g() { return f(); }` is an infinite walk. depth: usize, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { let written = call.text().to_string(); let written = written.trim(); @@ -292,7 +302,7 @@ pub(crate) fn type_of_a_call( // parameters stand for — and the way the standard library uses almost everywhere: `_Get_unwrapped(_First)` // never writes ``, it passes one. Computed only when nothing was written, which is the only case it is // used in, because typing every argument of every call is not free. - let argument_types: Vec = if written_arguments.is_empty() { + let argument_types: Vec = if written_arguments.is_empty() { sema::call_syntax::arguments_of(call) .unwrap_or_default() .iter() @@ -365,7 +375,10 @@ pub(crate) fn type_of_a_call( && let Known::Yes((callee_type, file)) = type_of_expression_memoed( memo, shapes, index, declaring, scopes, root, path, &callee, 0, ) - && matches!(callee_type, Type::Named { .. }) + && matches!( + callee_type, + ComputedType::Named(_) | ComputedType::Generic(_) + ) && let Some(returns) = operator_returns_of_with_arguments( index, declaring, @@ -378,7 +391,7 @@ pub(crate) fn type_of_a_call( sema::call_syntax::arguments_of(call).map(|arguments| arguments.len()), ) { - return Known::Yes((parse_type_spelling(&returns), file)); + return Known::Yes((returns, file)); } // **The standard library's factories, whose return type the standard fixes.** `make_shared(args…)` is a @@ -391,7 +404,7 @@ pub(crate) fn type_of_a_call( && let Some(argument) = written_arguments.first() { return Known::Yes(( - parse_type_spelling(&format!("{pointer}<{argument}>")), + ComputedType::named(pointer, vec![argument.clone()]), path.to_path_buf(), )); } @@ -418,17 +431,19 @@ pub(crate) fn type_of_a_call( ) && let Some(element) = range_element_of(as_a_range(&argument)) { - let element = parse_type_spelling(&element); - let element = Arc::new(Type::Qualified { - of: Arc::new(element), - qualifiers: sema::types::Qualifiers::CONST, - }); - let array = Arc::new(Type::Array { + let element = Arc::new(ComputedType::Qualified(Arc::new( + index::types::QualifiedType { + of: Arc::new(element), + is_const: true, + is_volatile: false, + }, + ))); + let array = Arc::new(ComputedType::Array { of: element, - extent: None, + extent: index::types::ArrayExtent::Unspecified, }); return Known::Yes(( - Type::Reference { + ComputedType::Reference { to: array, rvalue: false, }, @@ -453,10 +468,16 @@ pub(crate) fn type_of_a_call( } } "count" | "count_if" | "distance" | "ssize" => { - return Known::Yes((parse_type_spelling("std::ptrdiff_t"), path.to_path_buf())); + return Known::Yes(( + ComputedType::named("std::ptrdiff_t", Vec::new()), + path.to_path_buf(), + )); } "size" => { - return Known::Yes((parse_type_spelling("std::size_t"), path.to_path_buf())); + return Known::Yes(( + ComputedType::named("std::size_t", Vec::new()), + path.to_path_buf(), + )); } "subrange" => { if let Some(first) = arguments.first() @@ -647,14 +668,17 @@ pub(crate) fn a_callee_that_names_a_type( None => spelled, }; let names_a_type = match index.definition(bare, path) { - Known::Yes(found) => found.fact.kind == DeclKind::Type, + Known::Yes(found) => index + .definition_fact(&found) + .is_some_and(|fact| fact.kind == DeclKind::Type), Known::Unknown(UnknownReason::Ambiguous(_)) => { index.definitions(bare, path).value().is_some_and(|found| { !found.found.is_empty() - && found - .found - .iter() - .all(|declaration| declaration.fact.kind == DeclKind::Type) + && found.found.iter().all(|declaration| { + index + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Type) + }) }) } Known::Unknown(_) | Known::No => false, @@ -687,7 +711,7 @@ pub(crate) fn the_names_the_call_may_use(callee: &CppSyntaxNode) -> Vec /// guess: /// /// * **can this candidate be called this way** — the arity fits and every parameter takes the argument in its position. Only -/// a *definite* refusal drops a candidate (`sema::convert::conversion`'s `Refused`); one this layer cannot compare keeps +/// a *definite* refusal drops a candidate (`sema::convert::conversion_to`'s `Refused`); one this layer cannot compare keeps /// its place, because dropping it would be the same guess in the other direction; /// * **do the survivors say the same type** — their return spellings, with the call's **written** template arguments /// substituted in, read as `auto` would read them (no top-level reference, no `const`). @@ -702,8 +726,8 @@ pub(crate) fn the_return_the_overloads_agree_on( index: &ProjectIndex, path: &Path, names: &[String], - written_arguments: &[Type], - argument_types: &[Type], + written_arguments: &[ComputedType], + argument_types: &[ComputedType], how_many_arguments: usize, memo: &TypeMemo, declaring: &mut dyn FnMut(&Path) -> Option, @@ -717,16 +741,19 @@ pub(crate) fn the_return_the_overloads_agree_on( }; let mut agreed: Option = None; let mut any = false; - for candidate in found - .found - .iter() - .filter(|declaration| declaration.fact.kind == DeclKind::Function) - { + for candidate in found.found.iter().filter(|declaration| { + index + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Function) + }) { + let Some(candidate_fact) = index.definition_fact(candidate) else { + continue; + }; // **A deleted function is not a candidate** — [dcl.fct.def.delete]: it participates in overload resolution // only to make the call ill-formed. `std::make_unique` declares // `template void make_unique(Args&&...) = delete;` to stop `make_unique(…)`, // and keeping it made the set disagree with the two real overloads around it. - if candidate.fact.modifiers.contains(DeclModifiers::DELETED) { + if candidate_fact.modifiers.contains(DeclModifiers::DELETED) { continue; } // **A function the summary has no return type for may still have one in its body.** The summary types a @@ -734,7 +761,7 @@ pub(crate) fn the_return_the_overloads_agree_on( // make_thing(); }` and `auto field(W w) { return w.member; }` have no `returns` at all, and every call to // them was untyped. Here the declaring file's own view and scopes are in reach, so the expression is // typed with the machinery a use in that file gets. See [`the_return_the_body_gives_back`]. - let written: String = match candidate.fact.returns.as_deref() { + let written: String = match index.returns_spelling_of(candidate_fact) { Some(written) => written.to_string(), None => match the_return_the_body_gives_back( memo, index, declaring, scopes, root, path, depth, candidate, @@ -743,15 +770,30 @@ pub(crate) fn the_return_the_overloads_agree_on( None => continue, }, }; + // **The declaration's parameters, structurally** — or `None` when this reading recorded no list at all + // (a declaration the fact layer could not reach), which is the one answer that has no vote. The *presence* + // of the list is the display field's job; its **content** is resolved as types. + let file = index.definition_path(candidate).unwrap_or(path); + let parameters = candidate_fact + .parameter_list() + .is_some() + .then(|| index.parameter_types_of(file, candidate_fact)); + // **The list-level `...` is the fact's bit, and a pack is a parameter's.** A candidate accepts a variable + // number of arguments for either reason, so the two are combined here rather than at the ranking, which + // takes one flag: `void f(int, ...)` writes the first, `void f(T... rest)` the second. + let list = index.parameter_facts_of(file, candidate_fact); + let variadic = + candidate_fact.variadic_parameters || list.iter().any(|parameter| parameter.pack); if !a_candidate_that_can_be_called_this_way( - candidate.fact.parameter_list(), + parameters.as_deref(), + variadic, argument_types, how_many_arguments, ) { continue; } let substituted = if written_arguments.is_empty() - || candidate.fact.parameters().is_empty() + || candidate_fact.parameters().is_empty() { written.clone() } else { @@ -759,15 +801,15 @@ pub(crate) fn the_return_the_overloads_agree_on( .iter() .map(|one| one.to_string()) .collect(); - sema::types::substituted_spelling(&written, candidate.fact.parameters(), &arguments) + sema::types::substituted_spelling(&written, candidate_fact.parameters(), &arguments) }; // **A spelling that still names one of the candidate's own parameters could not be substituted** — // `variant_alternative_t>` keeps `_Types` — and comparing it with a concrete // answer would make every set holding such an overload disagree for a reason that is not about the type. - let still_unsubstituted = - candidate.fact.parameters().iter().any(|parameter| { - !parameter.is_empty() && substituted.contains(parameter.as_str()) - }); + let still_unsubstituted = candidate_fact + .parameters() + .iter() + .any(|parameter| !parameter.is_empty() && substituted.contains(parameter.as_str())); if still_unsubstituted { continue; } @@ -789,27 +831,31 @@ pub(crate) fn the_return_the_overloads_agree_on( None } -/// **Can a call with this many arguments, of these types, reach this parameter list?** +/// **Can a call with this many arguments, of these types, reach this candidate?** /// /// Arity first — a **parameter pack** accepts any count from its position on — and then each parameter in turn, when the /// arguments could be typed at all. A call that wrote its template arguments (`std::get(either)`) has no /// `argument_types` to compare, and its arity is still known: the counts are checked, the conversions are not. +/// +/// `parameters` are the declaration's **structured** types and `variadic` is the list-level `...`; a declaration with +/// no recorded list has no vote. The conversion question takes the parameter structurally (no spelling, no parse) and +/// answers the C record rule only from the type's own tag; the caller passes no language, so that rule does not apply +/// here. pub(crate) fn a_candidate_that_can_be_called_this_way( - parameter_list: Option<&str>, - argument_types: &[Type], + parameters: Option<&[ComputedType]>, + variadic: bool, + argument_types: &[ComputedType], how_many_arguments: usize, ) -> bool { - let Some(parameter_list) = parameter_list else { - // **A declaration with no recorded list has no vote.** It cannot be refused either, so it is skipped rather - // than kept: `std::make_unique` has a `void`-returning declaration with no parameter list recorded, and keeping - // it made every set holding such a declaration disagree with the concrete answers around it. + // **A declaration with nothing recorded has no vote.** It cannot be refused either, so it is skipped rather + // than kept: `std::make_unique` has a `void`-returning declaration with no parameter list recorded, and keeping + // it made every set holding such a declaration disagree with the concrete answers around it. + let Some(parameters) = parameters else { return false; }; - let parameters = sema::overload::parameters_in(parameter_list).0; - // **A pack is recognised from the written list**, because `parameters_in` strips the `...`: `(_Types&&... _Args)` - // comes back as one parameter, `_Types&&`, and reading that as an exact arity dropped every variadic candidate - // — measured, `std::make_unique()` answered nothing while two of its three overloads agree on the type. - let a_pack = parameter_list.contains("..."); + // **A pack is recognised from the declaration's own flag**, because the element type is what the list holds: a + // pack accepts any count from its position on. + let a_pack = variadic; if a_pack { let fixed = parameters.len().saturating_sub(1); if how_many_arguments < fixed { @@ -827,7 +873,10 @@ pub(crate) fn a_candidate_that_can_be_called_this_way( .iter() .zip(argument_types) .all(|(parameter, argument)| { - !sema::convert::conversion(argument, parameter, None, |_| None).is_refused() + // **The parameter is a `ComputedType` already** — the declaration layer lowered it from its parameter node + // and the fact resolved it structurally. Nothing here parses, and the conversion question takes the value. + let target = parameter; + !sema::convert::conversion_to(argument, target, None, |_| None).is_refused() }) } @@ -859,7 +908,7 @@ pub(crate) fn iterator_element_type( root: &CppSyntaxNode, path: &Path, callee: &CppSyntaxNode, -) -> Option> { +) -> Option> { let member = sema::resolve::member_access_at(root, end_of_the_written_name(callee))?; if !matches!( member.member.as_str(), @@ -891,10 +940,10 @@ pub(crate) fn iterator_element_type( }; let element = range_element_of(&object)?; - Some(Known::Yes((parse_type_spelling(&element), file))) + Some(Known::Yes((element, file))) } -pub(crate) fn written_template_arguments(callee: &CppSyntaxNode) -> Vec { +pub(crate) fn written_template_arguments(callee: &CppSyntaxNode) -> Vec { let Some(list) = callee .descendants() .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TemplateArgumentList) @@ -1028,20 +1077,24 @@ pub(crate) fn declaration_of_a_callee( Some(&written_arguments), ); // **A `const` object can only call a `const` member**: a candidate it could not call is not a candidate. - let callable: Vec<(DeclFact, PathBuf)> = declared + // Each survivor arrived with its parameters resolved — from the arena that issued its fact, or from the view + // that synthesized it — so the ranking is handed structures rather than the declaration's spelling. + let callable: Vec = declared .into_iter() - .filter(|(fact, _)| !object.is_const() || fact.modifiers.contains(DeclModifiers::CONST)) + .filter(|candidate| { + !object.is_const() || candidate.fact.modifiers.contains(DeclModifiers::CONST) + }) .collect(); if callable.len() > 1 && let Some(call) = the_call_around(callee) && let Some(types) = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, &call) && let Some(chosen) = the_one_the_arguments_select(&types, &callable, &[]) - && let Some((fact, file)) = callable.get(chosen) + && let Some(candidate) = callable.get(chosen) { return Known::Yes(NamedDeclaration::Indexed( - fact.clone(), - file.clone(), + candidate.fact.clone(), + candidate.file.clone(), bindings, )); } @@ -1073,28 +1126,32 @@ pub(crate) fn declaration_of_a_callee( && let Some(types) = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, &call) { - let candidates: Vec<(DeclFact, PathBuf)> = bindings + // **The candidates are this buffer's own binding facts**, so their parameter lists are the ones the synthesizer + // returned beside the fact — no summary owns them and no store was written for them. They are handed to the + // ranking directly, `ComputedType`s from the same structural lowering every other fact gets. + let candidates: Vec = bindings .iter() .map(|binding| { - ( - fact_from_binding_with( - sema::declarations::shapes_from(shapes, root), - root, - "", - binding, - ), - path.to_path_buf(), + let synthesized = fact_from_binding_with( + sema::declarations::shapes_from(shapes, root), + root, + "", + binding, + ); + CandidateDeclaration::with_parameters( + path, + synthesized.fact, + &synthesized.parameters, + index, ) }) .collect(); - let explicit_arguments: Vec = call + let explicit_arguments: Vec = call .children() .next() .map(|callee| written_template_arguments(&callee)) .unwrap_or_default() - .iter() - .map(Type::to_string) - .collect(); + .to_vec(); if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments) && let Some(binding) = bindings.get(chosen) { @@ -1117,11 +1174,15 @@ pub(crate) fn declaration_of_a_callee( sema::resolve::definition_at(scopes, root, end_of_the_written_name(callee)), Known::No | Known::Unknown(UnknownReason::NotDeclaredHere(_)) ) && let Some(member) = - a_member_of_the_enclosing_class(index, scopes, root, path, callee, true) + a_member_row_of_the_enclosing_class(index, scopes, root, path, callee, true) + && let (Some(fact), Some(file)) = ( + index.member_display_fact(&member), + index.member_path(&member).map(Path::to_path_buf), + ) { return Known::Yes(NamedDeclaration::Indexed( - member.fact, - member.file, + fact, + file, TypeBindings::new(Vec::new(), Vec::new()), )); } @@ -1145,11 +1206,18 @@ pub(crate) fn declaration_of_a_callee( match sema::resolve::definition_at(scopes, root, start + bare.len()) { Known::Yes(binding) => Known::Yes(NamedDeclaration::Here(binding)), _ => match index.definition(&bare, path) { - Known::Yes(found) => Known::Yes(NamedDeclaration::Indexed( - found.fact, - found.file, - TypeBindings::new(Vec::new(), Vec::new()), - )), + Known::Yes(found) => Known::Yes(match index.definition_parts(&found) { + Some((fact, file)) => NamedDeclaration::Indexed( + fact.clone(), + file.to_path_buf(), + TypeBindings::new(Vec::new(), Vec::new()), + ), + None => { + return Known::Unknown(UnknownReason::NotDeclaredHere( + Box::from(bare), + )); + } + }), Known::Unknown(reason) => Known::Unknown(reason), Known::No => Known::No, }, @@ -1304,10 +1372,13 @@ pub(crate) fn callees_of_a_call( found .found .iter() - .map(|declaration| Callee { - file: declaration.file.clone(), - name_offset: declaration.fact.name_range.start_offset, - parameters: declaration.fact.parameter_list().map(str::to_string), + .filter_map(|declaration| { + let (fact, file) = index.definition_parts(declaration)?; + Some(Callee { + file: file.to_path_buf(), + name_offset: fact.name_range.start_offset, + parameters: fact.parameter_list().map(str::to_string), + }) }) .collect(), ), @@ -1362,22 +1433,24 @@ pub(crate) fn the_declaration_the_arguments_pick( if definitions.found.len() < 2 { return None; } - let candidates: Vec<(DeclFact, PathBuf)> = definitions + let candidates: Vec = definitions .found .iter() - .map(|definition| (definition.fact.clone(), definition.file.clone())) + .filter_map(|definition| { + let (fact, file) = index.definition_parts(definition)?; + Some(CandidateDeclaration::resolved(index, file, fact)) + }) .collect(); let types = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, call)?; - let explicit_arguments: Vec = call + let explicit_arguments: Vec = call .children() .next() .map(|callee| written_template_arguments(&callee)) .unwrap_or_default() - .iter() - .map(Type::to_string) - .collect(); + .to_vec(); let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?; - candidates.get(chosen).cloned() + let candidate = candidates.get(chosen)?; + Some((candidate.fact.clone(), candidate.file.clone())) } /// **A call's callee without the template arguments the call wrote** — the spelling the index keys a name on. @@ -1410,7 +1483,8 @@ pub(crate) fn the_name_without_its_arguments(written: &str) -> &str { } written } -/// **The types of a call's arguments**, as spellings — `Unknown` for an argument whose type the engine cannot read. +/// **The types of a call's arguments**, as the computation layer works on them — `Unknown` for an argument whose type +/// the engine cannot read. The engine's answer is a `ComputedType`; this converts the representation and parses nothing. pub(crate) fn the_types_of_the_arguments( memo: &TypeMemo, index: &ProjectIndex, @@ -1419,7 +1493,7 @@ pub(crate) fn the_types_of_the_arguments( root: &CppSyntaxNode, path: &Path, call: &CppSyntaxNode, -) -> Option>> { +) -> Option>> { let arguments = sema::call_syntax::arguments_of(call)?; Some( arguments @@ -1436,7 +1510,7 @@ pub(crate) fn the_types_of_the_arguments( argument, 0, ) { - Known::Yes((type_of, _)) => Known::Yes(type_of.to_string()), + Known::Yes((type_of, _)) => Known::Yes(type_of), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), } @@ -1445,6 +1519,60 @@ pub(crate) fn the_types_of_the_arguments( ) } +/// **A declaration an overload ranking compares**, with its parameters already resolved. +/// +/// A resolver that took only `(DeclFact, PathBuf)` had to resolve each candidate's parameters itself, through the +/// index — which cannot answer for a fact built from a buffer's own scopes (its list is in the synthetic arena, not in +/// a summary). The caller that holds that fact has the parameter list in hand +/// ([`crate::index::project::SynthesizedFact`]), so it hands the resolved value over with the rest. +#[derive(Clone)] +pub(crate) struct CandidateDeclaration { + pub(crate) fact: DeclFact, + pub(crate) file: PathBuf, + pub(crate) parameters: sema::overload::DeclaredParameters, +} + +impl CandidateDeclaration { + /// **A candidate whose parameters the index can resolve** — the ordinary case: a declaration a summary or a + /// cooked reading filed. + pub(crate) fn resolved(index: &ProjectIndex, file: &Path, fact: &DeclFact) -> Self { + // **The list-level `...` comes from the fact, and a pack from its parameters** — the two syntaxes that make a + // callee accept a variable number of arguments, combined into the one flag the ranking takes. See + // [`DeclFact::variadic_parameters`]. + let facts = index.parameter_facts_of(file, fact); + let variadic = fact.variadic_parameters || facts.iter().any(|parameter| parameter.pack); + let types = facts + .iter() + .filter_map(|parameter| index.parameter_type(parameter)) + .collect(); + CandidateDeclaration { + fact: fact.clone(), + file: file.to_path_buf(), + parameters: sema::overload::DeclaredParameters::new(types, variadic), + } + } + + /// **A candidate whose parameters the caller already has** — a fact built from a view, whose list no store owns. + pub(crate) fn with_parameters( + file: &Path, + fact: DeclFact, + parameters: &[index::params::ParameterFact], + index: &ProjectIndex, + ) -> Self { + let types = parameters + .iter() + .filter_map(|parameter| index.parameter_type(parameter)) + .collect(); + let variadic = + fact.variadic_parameters || parameters.iter().any(|parameter| parameter.pack); + CandidateDeclaration { + fact, + file: file.to_path_buf(), + parameters: sema::overload::DeclaredParameters::new(types, variadic), + } + } +} + /// **Which of these declarations the arguments select**, as an index into `candidates`. /// /// # The tie the ranker leaves, and the one it is allowed to break @@ -1458,16 +1586,21 @@ pub(crate) fn the_types_of_the_arguments( /// are (or none is definite), the tie stands and the caller keeps its `Ambiguous`: a tie between two candidates of the /// same width is a real one. pub(crate) fn the_one_the_arguments_select( - types: &[Known], - candidates: &[(DeclFact, PathBuf)], - explicit_arguments: &[String], + types: &[Known], + candidates: &[CandidateDeclaration], + explicit_arguments: &[ComputedType], ) -> Option { // **A deleted declaration cannot be the meaning of a call this layer reports.** `std::make_unique` has a third // overload `= delete`d so that arrays are rejected ([memory.syn]); it ties with the real one on every argument, and // keeping it in the running is what made `auto unique = std::make_unique(1);` ambiguous and left the // variable with no type. `usable` holds the original indices, in the order the ranking sees them. let usable: Vec = (0..candidates.len()) - .filter(|at| !candidates[*at].0.modifiers.contains(DeclModifiers::DELETED)) + .filter(|at| { + !candidates[*at] + .fact + .modifiers + .contains(DeclModifiers::DELETED) + }) .collect(); if usable.is_empty() { // Every candidate is deleted: the call is ill-formed whichever one it means, and "no answer" is the honest @@ -1477,13 +1610,18 @@ pub(crate) fn the_one_the_arguments_select( let built: Vec = usable .iter() .enumerate() - .map(|(at, &index)| { - let (fact, _) = &candidates[index]; - let (declared, variadic) = fact - .parameter_list() - .map(sema::overload::parameters_in) - .unwrap_or_default(); - let names = fact.parameters().to_vec(); + .map(|(at, &candidate_at)| { + let candidate = &candidates[candidate_at]; + // **The declaration's parameters as structures**, handed over by the caller: a summary's fact resolved + // them through the one store, a view fact carries its own. Nothing here parses a parameter list. + let declared = candidate.parameters.types.clone(); + let variadic = candidate.parameters.variadic; + let names: Vec = candidate + .fact + .parameters() + .iter() + .map(ToString::to_string) + .collect(); let declared_for_ordering = declared.clone(); // **The deduction starts from what the call wrote.** `std::make_unique(1)` states `_Tp` as // `Resource`; without that seed the candidate's every parameter stayed unbound and it ranked `Unranked`. @@ -1496,10 +1634,8 @@ pub(crate) fn the_one_the_arguments_select( Some(deduced) => ( declared .iter() - .map(|spelling| { - sema::types::substituted_spelling(spelling, &names, &deduced) - }) - .collect::>(), + .map(|type_of| sema::deduction::substituted(type_of, &names, &deduced)) + .collect::>(), true, ), None => (declared, !names.is_empty()), @@ -1510,7 +1646,7 @@ pub(crate) fn the_one_the_arguments_select( format!("declaration {at}"), ); if substituted.1 { - candidate.with_declaration(declared_for_ordering, names.to_vec()) + candidate.with_declaration(declared_for_ordering, names) } else { candidate } @@ -1524,16 +1660,19 @@ pub(crate) fn the_one_the_arguments_select( sema::overload::Choice::One(at) => usable.get(at).copied(), sema::overload::Choice::Ambiguous => { let written = types.iter().find_map(|argument| match argument { - Known::Yes(spelling) => the_character_width(spelling), + Known::Yes(argument) => the_character_width(argument), _ => None, })?; let definite: Vec = usable .iter() .filter(|at| { - let (fact, _) = &candidates[**at]; - fact.parameter_list() - .and_then(|list| sema::overload::parameters_in(list).0.into_iter().next()) - .and_then(|first| the_character_width(&first)) + // **The candidate's first parameter, structurally** — the tie-break asks which character family + // its *types* name, not how the declaration spell them. + candidates[**at] + .parameters + .types + .first() + .and_then(the_character_width) == Some(written) }) .copied() @@ -1546,23 +1685,64 @@ pub(crate) fn the_one_the_arguments_select( sema::overload::Choice::None => None, } } -/// **Is this spelling written for wide characters, narrow ones, or neither?** — the tie-break +/// **Is this type written for wide characters, narrow ones, or neither?** — the tie-break /// [`the_declaration_the_arguments_pick`] uses, and nothing else does. /// -/// `wchar_t` contains `char` and `wstring` contains `string`, so the wide spellings are asked first. `None` for a -/// spelling that says neither (`int`, `pair`), which keeps such a candidate in the running. -pub(crate) fn the_character_width(spelling: &str) -> Option { - if spelling.contains("wchar_t") - || spelling.contains("wstring") - || spelling.contains("wformat") - || spelling.contains("wint_t") - { - return Some(true); +/// `wchar_t` contains `char` and `wstring` contains `string`, so the wide names are asked first. The question is asked +/// of the **type's names**, structurally: `std::wstring` answers wide because its class name says so, and `int` answers +/// nothing, which keeps such a candidate in the running. +pub(crate) fn the_character_width(type_of: &ComputedType) -> Option { + let mut wide = false; + let mut narrow = false; + let mut pending = vec![type_of]; + while let Some(current) = pending.pop() { + match current { + ComputedType::Primary(primary) => { + width_of_a_name(primary.spelling(), &mut wide, &mut narrow); + } + ComputedType::TemplateParameter(name) => { + width_of_a_name(name, &mut wide, &mut narrow); + } + ComputedType::Named(name) => { + width_of_a_name(name, &mut wide, &mut narrow); + } + ComputedType::Generic(generic) => { + width_of_a_name(&generic.name, &mut wide, &mut narrow); + pending.extend(generic.arguments.iter()); + } + ComputedType::Pointer(to) + | ComputedType::Pack(to) + | ComputedType::ElaboratedRecord { of: to, .. } => pending.push(to), + ComputedType::Reference { to, .. } | ComputedType::Array { of: to, .. } => { + pending.push(to) + } + ComputedType::Function(function) => { + pending.push(&function.returns); + pending.extend(function.parameters.iter()); + } + ComputedType::Qualified(qualified) => pending.push(&qualified.of), + } } - if spelling.contains("char") || spelling.contains("string") { - return Some(false); + if wide { + Some(true) + } else if narrow { + Some(false) + } else { + None + } +} + +/// Record the character family one name mentions — the wide spellings first, because `wchar_t` contains `char`. +fn width_of_a_name(name: &str, wide: &mut bool, narrow: &mut bool) { + if name.contains("wchar_t") + || name.contains("wstring") + || name.contains("wformat") + || name.contains("wint_t") + { + *wide = true; + } else if name.contains("char") || name.contains("string") { + *narrow = true; } - None } /// **Every declaration of one member name in the object's class** — the member-call half of [`callees_of_a_call`]. /// @@ -1619,11 +1799,13 @@ pub(crate) fn member_callees( let candidates: Vec = found .members .iter() - .filter(|member| member.fact.name == wanted) - .map(|member| Callee { - file: member.file.clone(), - name_offset: member.fact.name_range.start_offset, - parameters: member.fact.parameter_list().map(str::to_string), + .filter(|member| index.member_name(member) == wanted) + .filter_map(|member| { + Some(Callee { + file: index.member_path(member)?.to_path_buf(), + name_offset: index.member_fact(member)?.name_range.start_offset, + parameters: index.member_parameter_list(member), + }) }) .collect(); @@ -1687,7 +1869,7 @@ pub(crate) fn callee_of_a_call( /// /// One level, like the pointer rule: an object whose `operator->` returns another handle is a shape this layer does /// not follow twice, and a second level would be a guess about which `operator->` the language picked. -/// **A member's written answer, read as a type in the class the member belongs to.** +/// **A member's written answer, read as a type in the class the member belongs to** — structurally. /// /// `std::vector::operator[]` is declared `reference operator[](size_type)`, and `reference` is `T&` — an alias /// *inside the class*. Two things have to happen before that is a type a member lookup can ask about: @@ -1700,214 +1882,768 @@ pub(crate) fn callee_of_a_call( /// the one whose member was asked. Measured on EmmyLuaCodeStyle's `Mark.cpp`, where `events[Pos].U` on a /// `std::vector` answered `Unknown(NotDeclaredHere("_Ty"))`: the alias was followed to a *different* class's /// `reference`, whose `_Ty` nothing substitutes. +/// +/// # The walk is structural +/// +/// Every step is a [`ComputedType`]'s own shape: the member is found in the class's member list (which already carries +/// the class's substitution — see [`ProjectIndex::member_computed_type`]), the answer replaces the *named core* the +/// member was asked about while keeping the declarator's operators around it, and the walk continues on the result. +/// No `ComputedType` is printed and parsed on this path: the alias chain of `std::vector::reference` is followed +/// as values. The one remaining spelling-level piece is a **dependent qualified name** — `ComputedType` has no node +/// for `A::template name`, so such a name arrives as one `Named` string; the walk reads its last `::` +/// segment and resolves the qualifier as a type, and stops when the qualifier is itself a member *template* of an +/// instantiation (see [`names_a_member_of_an_instantiation`]). pub(crate) fn a_members_answer_as_a_type( index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, - returns: &str, -) -> String { - // **An alias has no parameters of its own; its target has them.** `std::string` is - // `using string = basic_string, allocator>`, so `template_parameters_for("std::string")` - // answers `[]` — and the members whose spellings this resolves are `basic_string`'s (`reference` is `value_type&`, - // `value_type` is `_Elem`). Measured on the server: `s[0]` on a `std::string&` answered **`_Elem&`**, and the trace - // showed the two alias steps with `(class "std::string", parameters [], arguments [])`. One step to the target is - // enough — the recursion ends at a class, whose declaration carries no `type_of` — and it is the same step - // [`operator_returns_of_with_arguments`] takes for an alias's operators. - let mut class_type = class_type.clone(); - for _ in 0..4 { - let Some(name) = class_type.class_name().map(str::to_string) else { - return returns.to_string(); + class_type: &ComputedType, + returns: &ComputedType, +) -> ComputedType { + // **A type with no class name asks no member question.** A fundamental, a function and an array are already the + // answer — the walk below splits a name and the declarator operators around it, and none of the three is a name + // it could resolve — so the common case never crosses this boundary at all. + if matches!( + returns, + ComputedType::Primary(_) | ComputedType::Function(_) | ComputedType::Array { .. } + ) { + return returns.clone(); + } + let Some(name) = returns.bare_name() else { + return returns.clone(); + }; + if index::types::PrimaryType::from_spelling(name).is_some() { + return returns.clone(); + } + // **A concrete class is already the answer.** When the name is declared as a class (not as an alias carrying its + // own type), the structural return already names it; only a dependent member (`reference` in a class body) or an + // alias target needs the member walk. This keeps the common subscript answer — `operator[]` returning a class — + // from paying for a member list. The check is on the declaration the index files for the *name*: a class member + // alias that shadows a like-named class in another class would be missed, and that is the trade this fast path + // has always made. + if !returns.depends_on_a_parameter() { + let declared: Vec<_> = index.files_declaring(name, path); + if declared + .iter() + .any(|declaration| declaration.fact.kind == DeclKind::Type) + && !declared + .iter() + .any(|declaration| declaration.fact.has_type_of()) + { + return returns.clone(); + } + } + // **The class the member belongs to, with a class alias followed through its own declaration** — `std::string` + // is `basic_string, allocator>`, and the members whose types are resolved here are + // `basic_string`'s. The qualifier is written on the *use*, so it is put back on the target: a `const std::string` + // must stay const, or the member choice treats the object as mutable. + let class = a_class_through_its_aliases(index, path, class_type); + let resolved = + a_type_through_the_members(index, scopes, root, path, &class, returns, &[], &[], 0); + + // **`reference` is `value_type&`** — the standard's own definition for every container, and the one an + // implementation's allocator alias chain can hide. When the walk still ends on the name `value_type`, the class's + // own `value_type` is the answer: libstdc++'s chain goes through `_Tp_alloc_type::value_type`, which names the + // very alias the member list has already substituted for this instantiation. Nothing is printed or parsed: the + // unresolved core is replaced by the member's computed type, and the reference wrapper the alias wrote around it + // is kept. + if let Some(kind) = a_reference_alias(returns) + && names_a_value_type(&resolved) + && let Some(value_type) = a_member_of_the_class( + index, + scopes, + root, + path, + &class, + "value_type", + &[], + &[], + &[], + 0, + ) + { + let value_type = match kind { + ReferenceAlias::Const => a_qualified(value_type, true, false), + ReferenceAlias::Mutable => value_type, }; - let Some(target) = index - .files_declaring(&name, path) - .into_iter() - .find(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.type_of.is_some() - }) - .and_then(|declared| declared.fact.type_of.clone()) - else { + return replace_bare_core(&resolved, &a_name_ends_in_value_type, &value_type); + } + resolved +} + +/// **Which `reference` alias a return type names**, when it names one — the standard's two, and nothing else. +#[derive(Clone, Copy, PartialEq, Eq)] +enum ReferenceAlias { + Mutable, + Const, +} + +fn a_reference_alias(type_of: &ComputedType) -> Option { + match type_of.bare_name() { + Some("reference") => Some(ReferenceAlias::Mutable), + Some("const_reference") => Some(ReferenceAlias::Const), + _ => None, + } +} + +/// **The class a use names, with its class alias followed** — `std::string` → `basic_string`. +/// +/// One step per declaration, bounded by [`MAX_ALIAS_HOPS`] because a corpus can write `using A = A;`. The target's +/// own class name is qualified through the index (`basic_string` in `` is `std::basic_string`), and the +/// use's `const`/`volatile` is re-applied to it — the qualifier is a property of the *use*, not of the alias. +fn a_class_through_its_aliases( + index: &ProjectIndex, + path: &Path, + class_type: &ComputedType, +) -> ComputedType { + let mut current = class_type.clone(); + for _ in 0..MAX_ALIAS_HOPS { + let Some(name) = current.class_name().map(str::to_string) else { break; }; - let resolved = parse_type_spelling(&target); - let Some(resolved_name) = resolved.class_name() else { + let Some(target) = a_class_alias_target(index, path, &name, current.arguments()) else { break; }; - // **The target is written unqualified**, and the class it names is looked up by the index's own spelling: - // `basic_string` in `` is `std::basic_string`, and asking a member question about the bare name found - // no class at all — the substitution then answered `reference`, the alias's *name*, which is no type either. - let qualified = qualified_from_the_index(index, path, resolved_name) - .unwrap_or_else(|| resolved_name.to_string()); - if qualified == name { + let target = a_class_named_with_the_index(index, path, target); + let qualifiers = current.qualifiers(); + let needs_a_qualifier = (qualifiers.is_const() && !target.is_const()) + || (qualifiers.is_volatile() && !target.is_volatile()); + let target = match needs_a_qualifier { + true => a_qualified(target, qualifiers.is_const(), qualifiers.is_volatile()), + false => target, + }; + // **An alias that names itself ends the walk**, the same rule the spelling walk applies to `using A = A;`. + if target.class_name() == Some(name.as_str()) { break; } - let arguments: Vec = resolved - .arguments() - .iter() - .map(|argument| argument.to_string()) - .collect(); - // **The qualifier is written on the use, so it is put back on the target** — see the same step in - // [`operator_returns_of_with_arguments`]: a `const std::string&` resolved to `basic_string` - // unqualified and the member choice then treated the object as non-const. - let resolved = parse_type_spelling(&match arguments.is_empty() { - true => qualified, - false => format!("{qualified}<{}>", arguments.join(", ")), - }); - class_type = match class_type.is_const() && !resolved.is_const() { - true => Type::Qualified { - of: Arc::new(resolved), - qualifiers: sema::types::Qualifiers::CONST, - }, - false => resolved, - }; + current = target; } - let Some(class) = class_type.class_name() else { - return returns.to_string(); - }; - let arguments: Vec = class_type - .arguments() + current +} + +/// **A class alias's target as the computation layer holds it**, or `None` when the name is not a class alias. +/// +/// The target is the alias declaration's own `type_of` (an alias's target *is* its type, see `declared_alias_target`), +/// with the alias's parameters paired with the arguments the use wrote. No spelling is parsed. +fn a_class_alias_target( + index: &ProjectIndex, + path: &Path, + name: &str, + arguments: &[ComputedType], +) -> Option { + let declared = index.files_declaring(name, path); + let alias = declared + .iter() + .find(|declared| declared.fact.kind == DeclKind::Type && declared.fact.has_type_of())?; + let target = index.computed_type_of(alias.fact)?; + let pairing: Vec<(smol_str::SmolStr, ComputedType)> = alias + .fact + .parameters() .iter() - .map(|argument| argument.to_string()) + .cloned() + .zip(arguments.iter().cloned()) .collect(); - let parameters = index.template_parameters_for(class, path, &arguments); - // **A use that writes fewer arguments than the declaration has parameters**, which is the ordinary case: - // `std::vector` names one of two. The defaults are what the rest stand for — see - // [`crate::substituted_spelling_with_defaults`], and `lineStartOffset` for the chain that needed it. - let defaults = index.template_parameter_defaults_for(class, path, &arguments); - let substituted = sema::types::substituted_spelling_with_defaults( - returns, - ¶meters, - &defaults, - &arguments, - ); + Some(match pairing.is_empty() { + true => target, + false => target.substituted_by_bindings(&pairing), + }) +} - // **The operators and qualifiers the spelling around the name carries**: `const reference&` is `const T&`, and - // replacing only the name must keep both ends. - let (leading, core, trailing) = split_the_operators_of(&substituted); - if core.is_empty() - || !core - .chars() - .all(|character| character.is_alphanumeric() || character == '_') +/// **A class name the index files qualified** — `basic_string` → `std::basic_string`. +/// +/// An alias's target is written where the alias is declared, often unqualified, while a member question is asked with +/// the name the index keys. Only a `Named`/`Generic` class is qualified; a fundamental or an unnamed shape is kept. +fn a_class_named_with_the_index( + index: &ProjectIndex, + path: &Path, + type_of: ComputedType, +) -> ComputedType { + match &type_of { + ComputedType::Named(name) if !name.contains("::") => { + match qualified_from_the_index(index, path, name) { + Some(qualified) if qualified != name.as_str() => { + ComputedType::named(qualified, Vec::new()) + } + _ => type_of, + } + } + ComputedType::Generic(generic) if !generic.name.contains("::") => { + match qualified_from_the_index(index, path, &generic.name) { + Some(qualified) if qualified != generic.name.as_str() => { + ComputedType::named(qualified, generic.arguments.to_vec()) + } + _ => type_of, + } + } + _ => type_of, + } +} + +/// **One type with every bare *name* resolved as a member of `class`** — the structural heart of the walk. +/// +/// The declarator's operators are transparent: a `Reference`, `Pointer`, `Array`, `Pack`, `Qualified` or +/// `ElaboratedRecord` around a name is copied with its inside resolved, so `Reference { Named("value_type") }` becomes +/// `Reference { Primary(int) }` — the reference the alias wrote is kept, and only the name inside it changes. +/// +/// `visited` is the classes the walk has already left (outermost first) and `bindings` the names already paired in the +/// scope (a class's template parameters, a member's own): both are what resolve a name that the current class does not +/// declare, the same two pieces the spelling walk carries. `depth` bounds the recursion at [`MAX_ALIAS_HOPS`]. +fn a_type_through_the_members( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + class: &ComputedType, + type_of: &ComputedType, + visited: &[ComputedType], + bindings: &[(smol_str::SmolStr, ComputedType)], + depth: usize, +) -> ComputedType { + if depth > MAX_ALIAS_HOPS { + return type_of.clone(); + } + match type_of { + ComputedType::Primary(_) | ComputedType::TemplateParameter(_) => type_of.clone(), + ComputedType::Named(name) => match a_name_through_the_members( + index, + scopes, + root, + path, + class, + name, + &[], + visited, + bindings, + depth, + ) { + Some(resolved) => resolved, + None => type_of.clone(), + }, + ComputedType::Generic(generic) => { + // **The arguments are written in this class's scope too** — `alloc_traits`'s argument is + // an alias of the class whose member is being resolved, and it has to be concrete before the class can be + // asked about. + let arguments: Vec = generic + .arguments + .iter() + .map(|argument| { + a_type_through_the_members( + index, + scopes, + root, + path, + class, + argument, + visited, + bindings, + depth + 1, + ) + }) + .collect(); + match a_name_through_the_members( + index, + scopes, + root, + path, + class, + &generic.name, + &arguments, + visited, + bindings, + depth, + ) { + Some(resolved) => resolved, + None => ComputedType::Generic(Arc::new(index::types::GenericType { + name: generic.name.clone(), + arguments: arguments.into_boxed_slice(), + })), + } + } + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(a_type_through_the_members( + index, scopes, root, path, class, of, visited, bindings, depth, + )), + }, + ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(a_type_through_the_members( + index, scopes, root, path, class, to, visited, bindings, depth, + ))), + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(a_type_through_the_members( + index, scopes, root, path, class, to, visited, bindings, depth, + )), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(a_type_through_the_members( + index, scopes, root, path, class, of, visited, bindings, depth, + )), + extent: extent.clone(), + }, + ComputedType::Function(function) => { + ComputedType::Function(Arc::new(index::types::FunctionType { + returns: Arc::new(a_type_through_the_members( + index, + scopes, + root, + path, + class, + &function.returns, + visited, + bindings, + depth, + )), + parameters: function + .parameters + .iter() + .map(|parameter| { + a_type_through_the_members( + index, scopes, root, path, class, parameter, visited, bindings, depth, + ) + }) + .collect(), + })) + } + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(a_type_through_the_members( + index, scopes, root, path, class, of, visited, bindings, depth, + ))), + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(index::types::QualifiedType { + of: Arc::new(a_type_through_the_members( + index, + scopes, + root, + path, + class, + &qualified.of, + visited, + bindings, + depth, + )), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + } +} + +/// **One name read as a member of `class`**, or `None` when this layer cannot place it. +/// +/// The shapes, in the order C++ looks at them: +/// +/// ```text +/// A a member of this class (or of a class the walk came through) +/// A the same, with an alias template's own parameters paired with `args` +/// X::A a member of the class `X` names — including a namespace-qualified `std::A` +/// A::value_type the standard's `reference` chain, when `X` cannot be resolved (see below) +/// ``` +/// +/// The last shape is the one the model cannot hold structurally: a **dependent qualified name** arrives as one +/// [`ComputedType::Named`] string, so this is where its last `::` segment is read. That is a *name* split, not a type +/// parse: the qualifier is resolved as a type through the same walk, and the answer is the member's computed type. +/// When the qualifier is itself a member template of an instantiation (`A::template rebind::other`), the walk +/// stops and reports the gap rather than guessing. +fn a_name_through_the_members( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + class: &ComputedType, + written: &str, + arguments: &[ComputedType], + visited: &[ComputedType], + bindings: &[(smol_str::SmolStr, ComputedType)], + depth: usize, +) -> Option { + if depth > MAX_ALIAS_HOPS { + return None; + } + // **The keywords a qualified name may carry are not its name** — `typename _Ty`, `template rebind`, `class A`. + let name = the_member_name(written.trim()); + if name.is_empty() { + return None; + } + // **A name already paired in this scope is the type it stands for** — a class template's parameter, or a name a + // member's own declaration bound (`A` in `typename A::value_type` after `alloc_traits>`). + if arguments.is_empty() + && let Some((_, bound)) = bindings.iter().find(|(bound, _)| bound == name) + { + return Some(bound.clone()); + } + // **A qualified name is a member of whatever the qualifier names** — and the qualifier is resolved first, because + // it is often a member alias of the class in hand (`tp_alloc`, `_Alloc_traits`) or a template parameter. + if let Some((qualifier, member)) = split_at_the_last_scope(name) { + if let Some(owner) = a_qualifier_through_the_members( + index, scopes, root, path, class, &qualifier, visited, bindings, depth, + ) { + let owner = a_class_through_its_aliases(index, path, &owner); + if let Some(found) = a_member_of_the_class( + index, + scopes, + root, + path, + &owner, + the_member_name(&member), + arguments, + visited, + bindings, + depth, + ) { + return Some(found); + } + } + // **`reference` is `value_type&`** — when the qualifier is a dependent name this layer cannot instantiate + // (`some_allocator`), the member the standard defines everything in terms of is the class's own + // `value_type`, and it *is* substituted in the member list. + if the_member_name(&member) == "value_type" { + return a_member_of_the_class( + index, + scopes, + root, + path, + class, + "value_type", + &[], + visited, + bindings, + depth, + ); + } + return None; + } + // **An unqualified name is a member of this class first, then of the classes the walk came through** — the same + // order the spelling walk uses, and the reason a library's `_Tp_alloc_type` written three classes back is still + // found by the class that wrote it. + for scope in std::iter::once(class).chain(visited.iter().rev()) { + if let Some(found) = a_member_of_the_class( + index, scopes, root, path, scope, name, arguments, visited, bindings, depth, + ) { + return Some(found); + } + } + // **A concrete class name is already the type it names.** It is kept as written, so a return type that is a + // class — the common subscript answer — never reaches an alias lookup at all. + if index + .files_declaring(name, path) + .iter() + .any(|declared| declared.fact.kind == DeclKind::Type && !declared.fact.has_type_of()) { - return substituted; + return Some(ComputedType::named(name, arguments.to_vec())); } + None +} - // **The class's own declaration of that name**, which is the only one whose parameters are the ones in hand. - let Known::Yes((fact, _)) = member_fact( - &sema::declarations::ShapeTable::new(), - index, - scopes, - root, - path, - &the_class_spelling(&class_type), - &core, - None, - ) else { - return substituted; - }; - let Some(target) = fact.type_of.as_deref() else { - return substituted; - }; - let target = - sema::types::substituted_spelling_with_defaults(target, ¶meters, &defaults, &arguments); - // **And the target is a *name* too**, so it is followed before it is answered: `pointer` is `_Val*` in the class - // that declares it, and `_Alloc_traits::reference` is whatever that alias names. Answering the spelling instead - // is what made `map::find(text)->second` look `second` up in `_Rb_tree_iterator` rather than in its `pair`. - let target = a_spelling_through_the_aliases( +/// **The class a qualifier names**, resolved the way a name in the class's scope is: a template parameter already +/// paired, a member alias, a class alias, or a class the index knows (`std::allocator`). +#[allow(clippy::too_many_arguments)] +fn a_qualifier_through_the_members( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + class: &ComputedType, + qualifier: &str, + visited: &[ComputedType], + bindings: &[(smol_str::SmolStr, ComputedType)], + depth: usize, +) -> Option { + let qualifier = the_member_name(qualifier.trim()); + if qualifier.is_empty() { + return None; + } + if let Some((_, bound)) = bindings.iter().find(|(bound, _)| bound == qualifier) { + return Some(bound.clone()); + } + // **`A::template name` is the one shape the model cannot hold**: the qualifier is a member *template* + // of an instantiation, and the index's member list answers the nested class by a spelling it does not store + // structurally (`A::name`). Reported rather than reconstructed. + if names_a_member_of_an_instantiation(qualifier) { + return None; + } + let (head, written_arguments) = the_name_and_its_arguments(qualifier); + let arguments: Vec = written_arguments + .iter() + .map(|argument| { + an_argument_through_the_members( + index, scopes, root, path, class, argument, visited, bindings, depth, + ) + }) + .collect::>>()?; + // **A member alias of this class, or of a class the walk came through** — `tp_alloc` is a member of `vector` + // even when the use is written three classes deeper. + for scope in std::iter::once(class).chain(visited.iter().rev()) { + if let Some(found) = a_member_of_the_class( + index, scopes, root, path, scope, head, &arguments, visited, bindings, depth, + ) && found.class_name().is_some() + { + return Some(found); + } + } + // **A class alias used as a qualifier** — `std::string::reference`. + if let Some(target) = a_class_alias_target(index, path, head, &arguments) { + return Some(a_class_named_with_the_index(index, path, target)); + } + // **A class the index knows** — `std::allocator`, a nested `Outer::Inner`, or a plain `Widget`. + let named = ComputedType::named(head, arguments); + let known = index + .files_declaring(head, path) + .iter() + .any(|declared| declared.fact.kind == DeclKind::Type) + || matches!( + members_of_computed(index, scopes, root, path, &named), + Known::Yes(_) + ); + known.then_some(named) +} + +/// **One template argument written in `class`'s scope**, as the type it names. +/// +/// The arguments the walk meets are names (`_Tp_alloc_type`, `Alloc`, `value_type`) — a member alias, a template +/// parameter, or a class. Anything with an operator or a space in it is a *type* this name-level reader does not +/// lower, and the caller then leaves the qualifier unresolved rather than guessing: `None`. +#[allow(clippy::too_many_arguments)] +fn an_argument_through_the_members( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + class: &ComputedType, + written: &str, + visited: &[ComputedType], + bindings: &[(smol_str::SmolStr, ComputedType)], + depth: usize, +) -> Option { + let written = written.trim(); + if written.is_empty() { + return None; + } + if let Some(primary) = index::types::PrimaryType::from_spelling(written) { + return Some(ComputedType::Primary(primary)); + } + // **A plain name only.** `unsigned long` is handled above; `const char*` is not a name, and its qualifiers and + // operators are a type's shape this reader does not reconstruct. + if !written + .chars() + .all(|character| character.is_alphanumeric() || matches!(character, '_' | ':')) + { + return None; + } + match a_name_through_the_members( index, scopes, root, path, - &class_type, + class, + written, &[], - &target, - MAX_ALIAS_HOPS, - ); - // **The substitution runs again, because the aliases put parameter names back.** `std::string`'s `operator[]` - // returns `reference`, which is `value_type&`, and `value_type` is `_Elem` — so the first substitution cannot - // reach it (no parameter is written in `reference`) and the alias walk hands back `_Elem&`: a spelling no reader - // can use. Measured through the server, `s[0]` on a `std::string&` answered **`_Elem&`** where a compiler answers - // `char&`; the second pass is one call and turns it into `char&`. - let target = sema::types::substituted_spelling_with_defaults( - &target, - ¶meters, - &defaults, - &arguments, - ); - // **`reference` is `value_type&`** — the standard's definition for every container, and the one an allocator's - // alias chain can hide. See [`a_reference_resolved_through_its_value_type`]. - let target = a_reference_resolved_through_its_value_type( - index, - scopes, - root, - path, - &class_type, - &core, - &target, - ¶meters, - &defaults, - &arguments, - ) - .unwrap_or(target); - format!("{leading}{target}{trailing}") + visited, + bindings, + depth + 1, + ) { + Some(resolved) => Some(resolved), + None => Some(ComputedType::Named(written.into())), + } } -/// **`reference` is `value_type&`** — the standard's own definition for every container, and the one an -/// implementation's allocator alias chain can hide. -/// -/// libstdc++ writes `vector::reference` as `_Alloc_traits::reference` → -/// `__alloc_traits<_Tp_alloc_type>::reference` → `value_type&` → `_Tp_alloc_type::value_type`, and `_Tp_alloc_type` -/// is `__alloc_traits<…>::rebind_alloc<_Tp>` — a `rebind` through a partial specialization, which this layer does not -/// instantiate. The walk therefore hands back `_Tp_alloc_type::value_type&`: a spelling no reader can use, and one -/// that names **`value_type`**, the very name the standard defines `reference` in terms of — and which the member -/// list has already substituted for the instantiation the reader wrote. +/// **One member of `class`, with the class's substitution already applied** — the step both the name and qualifier +/// readers are made of. /// -/// So when a `reference`/`const_reference` alias still names `value_type` after the walk, the class's own -/// `value_type` is the answer: `std::vector`'s is `std::vector`, `std::map`'s is `pair`, and both -/// are what the standard says. A container whose `reference` is written out — `basic_string`'s `_CharT&` — resolves -/// in the walk and never reaches this, because the trigger is the **unresolved** spelling. +/// `arguments` pair with the member's *own* parameters when it is an alias template (`rebind_alloc`), and the +/// target is resolved in the class's scope, with the member's own bindings added to the names already paired: a +/// member of `alloc_traits>` writes `value_type` as `typename A::value_type`, and `A` is only known +/// from the row's substitution. #[allow(clippy::too_many_arguments)] -fn a_reference_resolved_through_its_value_type( +fn a_member_of_the_class( index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, - member: &str, - target: &str, - parameters: &[String], - defaults: &[String], - arguments: &[String], -) -> Option { - let is_const = match member { - "reference" => false, - "const_reference" => true, - _ => return None, - }; - if !target.contains("::value_type") { + class: &ComputedType, + name: &str, + arguments: &[ComputedType], + visited: &[ComputedType], + bindings: &[(smol_str::SmolStr, ComputedType)], + depth: usize, +) -> Option { + let Known::Yes(list) = members_of_computed(index, scopes, root, path, class) else { return None; + }; + let found = list.members.iter().find(|member| { + index.member_name(member) == name && index.member_computed_type(member).is_some() + })?; + let mut target = index.member_computed_type(found)?; + // **An alias template's own parameters pair with the arguments written on it** — `rebind_alloc<_Other>` is + // `allocator<_Other>`, and the use wrote the `<…>`. + if !arguments.is_empty() + && let Some(fact) = index.member_fact(found) + && !fact.parameters().is_empty() + { + let pairing: Vec<(smol_str::SmolStr, ComputedType)> = fact + .parameters() + .iter() + .cloned() + .zip(arguments.iter().cloned()) + .collect(); + target = target.substituted_by_bindings(&pairing); } - let Known::Yes((fact, _)) = member_fact( - &sema::declarations::ShapeTable::new(), + // **The names the row's substitution paired are in scope for its target** — a member inherited from a base + // carries both instantiations' bindings, and its target was written where *that* class's parameters are names. + let mut here = bindings.to_vec(); + if let Some(substitution) = &found.substitution { + here.extend(substitution.bindings.iter().cloned()); + } + // **The class the member was declared in stays on the visited list** when it is not the class asked about, so a + // name the leaving class wrote can still be resolved by the walk below. + let mut deeper = visited.to_vec(); + if found.declared_in != class.class_name().unwrap_or_default() { + deeper.push(class.clone()); + } + Some(a_type_through_the_members( index, scopes, root, path, - &the_class_spelling(class_type), - "value_type", - None, - ) else { - return None; + class, + &target, + &deeper, + &here, + depth + 1, + )) +} + +/// **A class type with a `const`/`volatile` qualifier around it**, unless it already carries it. +fn a_qualified(type_of: ComputedType, is_const: bool, is_volatile: bool) -> ComputedType { + let is_const = is_const && !type_of.is_const(); + let is_volatile = is_volatile && !type_of.is_volatile(); + if !is_const && !is_volatile { + return type_of; + } + ComputedType::Qualified(Arc::new(index::types::QualifiedType { + of: Arc::new(type_of), + is_const, + is_volatile, + })) +} + +/// **Does this type still name the standard's `value_type` anywhere?** — the trigger for the `reference` fallback. +/// +/// A name that reached here was not resolved by the member walk (a concrete alias would have been replaced), so it is +/// the dependent `_Tp_alloc_type::value_type`-shaped tail the fallback exists for. `value_type` as a *whole* name is +/// included: a class whose member list could not be read still answers the standard's definition. +fn names_a_value_type(type_of: &ComputedType) -> bool { + match type_of { + ComputedType::Named(name) | ComputedType::TemplateParameter(name) => { + a_name_ends_in_value_type(name) + } + ComputedType::Generic(generic) => { + a_name_ends_in_value_type(&generic.name) + || generic.arguments.iter().any(names_a_value_type) + } + ComputedType::ElaboratedRecord { of, .. } + | ComputedType::Pointer(of) + | ComputedType::Reference { to: of, .. } + | ComputedType::Array { of, .. } + | ComputedType::Pack(of) => names_a_value_type(of), + ComputedType::Qualified(qualified) => names_a_value_type(&qualified.of), + ComputedType::Primary(_) | ComputedType::Function(_) => false, + } +} + +/// **This type with the bare core its name satisfies replaced** — `Reference { Named("_Alloc::value_type") }` becomes +/// `Reference { Primary(int) }` when `matches` accepts `_Alloc::value_type`: the declarator's operators stay where the +/// alias wrote them, and only the named core changes. This is the small structural replace the fallback at the end of +/// [`a_members_answer_as_a_type`] is made of; the walk itself resolves a core in place +/// ([`a_type_through_the_members`]). +fn replace_bare_core( + type_of: &ComputedType, + matches: &dyn Fn(&str) -> bool, + with: &ComputedType, +) -> ComputedType { + match type_of { + ComputedType::Named(name) if matches(name) => with.clone(), + ComputedType::Generic(generic) if matches(&generic.name) => with.clone(), + ComputedType::Generic(generic) => { + ComputedType::Generic(Arc::new(index::types::GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(|argument| replace_bare_core(argument, matches, with)) + .collect(), + })) + } + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(replace_bare_core(of, matches, with)), + }, + ComputedType::Pointer(to) => { + ComputedType::Pointer(Arc::new(replace_bare_core(to, matches, with))) + } + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(replace_bare_core(to, matches, with)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(replace_bare_core(of, matches, with)), + extent: extent.clone(), + }, + ComputedType::Function(function) => { + ComputedType::Function(Arc::new(index::types::FunctionType { + returns: Arc::new(replace_bare_core(&function.returns, matches, with)), + parameters: function + .parameters + .iter() + .map(|parameter| replace_bare_core(parameter, matches, with)) + .collect(), + })) + } + ComputedType::Pack(of) => { + ComputedType::Pack(Arc::new(replace_bare_core(of, matches, with))) + } + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(index::types::QualifiedType { + of: Arc::new(replace_bare_core(&qualified.of, matches, with)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + type_of.clone() + } + } +} + +/// **Does a (possibly qualified) name end in `value_type`?** — `typename A::value_type` and `value_type` both do. +fn a_name_ends_in_value_type(name: &str) -> bool { + match split_at_the_last_scope(name) { + Some((_, last)) => the_member_name(&last) == "value_type", + None => the_member_name(name) == "value_type", + } +} + +/// **Is this name a member of an instantiation** — `A::member`, `A::template member`? +/// +/// The one shape the computed type cannot hold: `ComputedType` has no *qualified name* node, so a dependent name is +/// flattened to a `Named` string, and a member of `A` would have to be looked up in a class the model cannot +/// describe without the enclosing instantiation's bindings. The walk reports the gap by stopping here rather than +/// reconstructing the spelling. +fn names_a_member_of_an_instantiation(name: &str) -> bool { + let Some(open) = name.find('<') else { + return false; }; - let written = fact.type_of.as_deref()?; - let value_type = - sema::types::substituted_spelling_with_defaults(written, parameters, defaults, arguments); - if value_type.trim().is_empty() || value_type.contains("::value_type") { - return None; + let mut depth = 0usize; + for (at, character) in name[open..].char_indices() { + match character { + '<' => depth += 1, + '>' => { + depth -= 1; + if depth == 0 { + return name[open + at + 1..].trim_start().starts_with("::"); + } + } + _ => {} + } } - Some(match is_const { - true => format!("const {value_type}&"), - false => format!("{value_type}&"), - }) + false } diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index 0375ba86..34d55830 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -6,6 +6,7 @@ use super::*; use crate::Binding; use crate::DeclKind; +use crate::FileId; use crate::FileView; use crate::ScopeKind; use crate::ScopeTree; @@ -153,7 +154,7 @@ pub fn member_completions_at( index .files_declaring(bare, path) .iter() - .any(|found| found.fact.kind == DeclKind::Type && found.fact.type_of.is_none()) + .any(|found| found.fact.kind == DeclKind::Type && !found.fact.has_type_of()) }; let class = match access.arrow { true => completion::the_class_after_the_operator(index, scopes, root, path, &written, true) @@ -213,10 +214,18 @@ pub(crate) fn written_before_the_cursor( } /// One name a completion can offer: where it is declared, and how far out it was found. +/// +/// A **reference row**, like [`ProjectMember`] and [`ProjectDefinition`]: the declaration belongs to some arena the +/// index owns, and this names it with the index's own [`FactRef`]. A consumer resolves it through +/// [`ProjectIndex::offered_fact`] and spells its file with [`ProjectIndex::offered_path`]; nothing here is a +/// `PathBuf` or an owned [`DeclFact`], so the list can be built, sorted and moved without copying declarations. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OfferedName { - pub file: PathBuf, - pub fact: DeclFact, + /// The file the declaration was written in — the other half of the identity a client echoes back to + /// `completionItem/resolve`. [`ProjectIndex::offered_path`] spells it. + pub file: FileId, + /// The immutable declaration this row names. Resolve it through [`ProjectIndex::offered_fact`]. + pub fact: FactRef, /// How many scopes out from the cursor the declaration was found: `0` is a name declared in the scope the /// cursor is in — a local, or the scope the `::` named — and larger numbers are enclosing scopes, which C++ /// only considers once the inner ones have been searched. The order of [`NameCompletions::names`]. @@ -254,6 +263,24 @@ pub enum NameProvenance { IndirectInclude, } +impl OfferedName { + /// **One offer for a declaration a visibility walk found.** The walk already carries the exact arena entry + /// (`VisibleDeclaration::reference`), so this mints nothing and materializes nothing: a row built here always + /// names a fact [`ProjectIndex::offered_fact`] can resolve. + pub(crate) fn of_a_visible_declaration( + declaration: &VisibleDeclaration<'_>, + depth: usize, + from: NameProvenance, + ) -> OfferedName { + OfferedName { + file: declaration.reference.file, + fact: declaration.reference, + depth, + from, + } + } +} + /// What a completion **in a name** should offer: the scope that was listed, and its names. /// /// The sibling of [`MemberCompletions`], and the other half of "what can be typed here": that one answers after a @@ -489,8 +516,9 @@ pub fn name_completions_at( declaration.kind = DeclKind::MacroLike; // Nothing of the template's *declaration* survives: a macro has no type, no return type, no // parameters of its own and no bases, and a `#define` is never local. - declaration.type_of = None; - declaration.returns = None; + declaration.type_of = DeclaredType::None; + declaration.returns = DeclaredType::None; + declaration.variadic_parameters = false; declaration.detail_mut().bases.clear(); declaration.detail_mut().parameters.clear(); declaration.local = false; @@ -508,10 +536,20 @@ pub fn name_completions_at( // **A function-like macro is offered with its parenthesis**, which is the only hint a completion item can carry // about how it is used: `MAX(` tells the reader the name takes arguments, and `MAX` alone does not. declaration.detail_mut().parameter_list = function_like.then(|| "(".into()); + // **A macro is a fact no arena holds**, so there is no pointer to point at: the index interns the + // synthesized declaration and answers with the reference. A file the index has read gets an ordinary + // [`crate::FileId`] in the synthetic arena, so [`ProjectIndex::path_of`] still spells the file the macro + // was written in; a file it has never read (a test fixture) goes through the view table. + let reference = match index.file_id_of(written_in) { + // A macro has no parameter facts: its `(…)` is the function-like hint above, not a CST parameter + // list. The synthetic arena therefore carries an empty list beside it. + Some(file) => index.intern_synthetic_fact(file, declaration, Box::default()), + None => index.intern_a_view_fact(written_in, declaration, Box::default()), + }; let ours = written_in == summary.path.as_path(); names.push(OfferedName { - file: written_in.to_path_buf(), - fact: declaration, + file: reference.file, + fact: reference, depth: 0, from: match ours { true => NameProvenance::ThisFile, @@ -575,13 +613,9 @@ pub(crate) fn visible_names( if let Some(class) = the_class_a_definition_belongs_to(root, offset) && let Known::Yes(members) = names_of_a_class(index, scopes, root, path, &class) { - names.extend(offered(members, 0)); + names.extend(offered(index, members, 0)); } - // The file the cursor is in, as the store spells paths, so that the declaration-order filter can tell this - // file's offsets from another file's. - let in_this_file = normalize(path); - for (depth, scope) in chain.iter().copied().enumerate() { let Some(data) = scopes.scope(scope) else { continue; @@ -603,7 +637,7 @@ pub(crate) fn visible_names( Known::Unknown(reason) => return Known::Unknown(reason), Known::No => Vec::new(), }; - names.extend(offered(members, depth)); + names.extend(offered(index, members, depth)); continue; } @@ -616,20 +650,25 @@ pub(crate) fn visible_names( ScopeKind::Block | ScopeKind::Function | ScopeKind::Lambda ); names.extend(offered( - // **In a body, only what is declared above the cursor is in scope.** A *scope* holds every binding - // written in its braces, so a list built from the scope contains `int c = a + b;` at a cursor three - // lines above it — a name that cannot be written there, because the language has not declared it yet. - // It is the same rule a reader applies without thinking, and the one a user reported: "在我下面声明的 - // 变量不应该补全出来". + index, + // **In a body, only what is declared above the cursor is in scope.** The filter is applied where the + // fact is built, in the tree's own coordinates — see [`bindings_of`] and [`declared_above`]. It is the + // same rule a reader applies without thinking, and the one a user reported: "在我下面声明的变量不应该补全 + // 出来". // // Only bodies: a class's members and a namespace's names are visible in **declaration order // independent** fashion (`class C { void f() { x = 1; } int x; };` is legal), so the filter would be // wrong there. Nothing is lost by the narrower rule — a body is exactly where the *textual* order is // the language's rule. - bindings_of(root, path, &data.bindings, None, body) - .into_iter() - .filter(|candidate| !body || declared_above(candidate, offset, &in_this_file)) - .collect(), + bindings_of( + index, + root, + path, + &data.bindings, + None, + body, + body.then_some(offset), + ), depth, )); @@ -637,6 +676,7 @@ pub(crate) fn visible_names( // that mentions it, so the buffer's list is never the whole answer. if let Some(prefix) = scopes.qualification_prefix_of(scope) { names.extend(offered( + index, declarations_in(&prefix, index, path, written), depth, )); @@ -657,7 +697,7 @@ pub(crate) fn visible_names( in_completion, )); - sort_and_hide(&mut names); + sort_and_hide(index, &mut names); Known::Yes(names) } @@ -677,10 +717,11 @@ pub(crate) fn global_offers( in_completion: bool, ) -> Vec { let mut names = offered( + index, global_names(index, scopes, root, path, written, in_completion), depth, ); - sort_and_hide(&mut names); + sort_and_hide(index, &mut names); names } @@ -710,13 +751,16 @@ pub(crate) fn a_spelling_names_a_type(index: &ProjectIndex, spelling: &str, path }; let mut any_type = false; for declaration in &found.found { - if declaration.fact.kind == DeclKind::Type { + let Some(fact) = index.definition_fact(declaration) else { + return false; + }; + if fact.kind == DeclKind::Type { any_type = true; continue; } // Everything else has to be *inside* the type: a constructor, a destructor, or a nested name of the same // spelling. A namespace's own facts fail this, which is what keeps `ns::` on the namespace route. - if declaration.fact.scope.as_deref() != Some(spelling) { + if fact.scope.as_deref() != Some(spelling) { return false; } } @@ -773,7 +817,7 @@ pub(crate) fn names_in_a_scope_at( Known::Unknown(reason) => return Known::Unknown(reason), Known::No => Vec::new(), }; - names.extend(offered(members, 0)); + names.extend(offered(index, members, 0)); } // A namespace can be reopened, so the buffer's names and the project's are both part of the answer. Some(_) => { @@ -782,11 +826,24 @@ pub(crate) fn names_in_a_scope_at( // applies to a name beginning with an underscore is the *global* name space's, and the spelling // here is the namespace's own. names.extend(offered( - bindings_of(root, path, &data.bindings, Some(spelling), false), + index, + bindings_of( + index, + root, + path, + &data.bindings, + Some(spelling), + false, + None, + ), 0, )); } - names.extend(offered(declarations_in(spelling, index, path, written), 0)); + names.extend(offered( + index, + declarations_in(spelling, index, path, written), + 0, + )); // **A namespace alias is a scope with no members of its own**, and its target is where the names are. // `namespace views = ranges::views;` gives `std::views` an empty namespace scope — the walker needs one @@ -854,7 +911,7 @@ pub(crate) fn names_in_a_scope_at( let named = named.as_ref(); match names_of_a_class(index, scopes, root, path, named) { - Known::Yes(members) => names.extend(offered(members, 0)), + Known::Yes(members) => names.extend(offered(index, members, 0)), Known::Unknown(reason) => return Known::Unknown(reason), Known::No => {} } @@ -871,11 +928,12 @@ pub(crate) fn names_in_a_scope_at( // `std`) and then as written, because which of the two is right depends on the alias's scope. if depth < 4 && let Known::Yes(alias) = index.definition(spelling, path) - && alias.fact.kind == DeclKind::Namespace - && let Some(target) = alias.fact.type_of.as_deref() + && let Some(alias_fact) = index.definition_fact(&alias) + && alias_fact.kind == DeclKind::Namespace + && let Some(target) = index.type_spelling_of(alias_fact) { let mut candidates: Vec = Vec::new(); - if let Some(scope) = alias.fact.scope.as_deref() { + if let Some(scope) = alias_fact.scope.as_deref() { candidates.push(format!("{scope}::{target}")); } candidates.push(target.trim_start_matches("::").to_string()); @@ -892,19 +950,23 @@ pub(crate) fn names_in_a_scope_at( // Empty is either "declared and empty" or "no such scope", and the difference is the *name* — // the same distinction `direct_members` makes, for the same reason. return match index.definition(spelling, path) { - Known::Yes(found) if found.fact.qualified_name() == spelling => { + Known::Yes(found) + if index + .definition_fact(&found) + .is_some_and(|fact| fact.qualified_name() == spelling) => + { Known::Yes(Vec::new()) } Known::Unknown(reason) => Known::Unknown(reason), _ => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(spelling))), }; } - names.extend(offered(found, 0)); + names.extend(offered(index, found, 0)); } } } - sort_and_hide(&mut names); + sort_and_hide(index, &mut names); Known::Yes(names) } @@ -970,35 +1032,34 @@ pub(crate) fn the_target_in_its_own_scope(scopes: &ScopeTree, alias: &str, targe /// `class C { void f() { x = 1; } int x; };` is perfectly legal — so filtering those by position would remove names /// a reader can legitimately write. /// -/// # The one thing it will not judge +/// # Why it takes a fact rather than a row /// -/// A binding from **another file**: its range is an offset into that file, so comparing it with this file's cursor -/// compares two different rulers. Those are kept — the conservative direction, and the same one the rest of this -/// module takes: a name that is in scope and not offered is a missing answer, while a name that is not in scope yet -/// and *is* offered is one the reader sees as a mistake. -/// -/// In practice every binding here is the buffer's own — `build_scopes` walks one file's tree, and a name reached -/// through an include is a [`NameProvenance::DirectInclude`] fact from the index rather than a binding — so this is -/// the guard that keeps the rule from being wrong if that ever changes. -pub(crate) fn declared_above(candidate: &Candidate, offset: usize, in_this_file: &str) -> bool { - if candidate.file != Path::new(in_this_file) { - return true; - } - - let at = candidate.fact.name_range.start_offset; +/// The two offsets have to be in **one coordinate system**. A completion is asked at a **rendering** offset (the +/// tree the query walks is the compiler's reading, where a macro is expanded), and the fact this compares is built +/// from that same tree — so the filter runs before the row mints its reference, while the shape is still in the +/// rendering's coordinates. An arena fact's offsets are the *file's*, and comparing those with the cursor's would +/// compare two different rulers. Every binding passed here comes from the buffer's own tree, so there is no +/// other-file case to guard against: a name reached through an include is a [`NameProvenance::DirectInclude`] fact +/// from the index rather than a binding. +pub(crate) fn declared_above(fact: &DeclFact, offset: usize) -> bool { + let at = fact.name_range.start_offset; // A zero-length range at the start of the file is what a recovery produces, and it is not a position. at == 0 || at < offset } -/// One name on its way to being offered: where it was declared, how far inside one answer it was, and how near the +/// One name on its way to being offered: the declaration it names, how far inside one answer it was, and how near the /// cursor that is. /// /// Named rather than a tuple because there are four of them now and two of the four are `usize`; a call site that /// had to remember which was which is how a ranking ends up ordered by the wrong number. +/// +/// Like [`OfferedName`], a reference row: constructing one mints the [`FactRef`] through the index, never beside it. pub(crate) struct Candidate { - pub(crate) file: PathBuf, - pub(crate) fact: DeclFact, + /// The file the declaration is in; always [`FactRef::file`] of the reference, and carried beside it so a + /// consumer never has to know the shape of a fact reference to ask "which file". + pub(crate) file: FileId, + pub(crate) fact: FactRef, /// How far *inside* one answer the name was found — a base class's member is one step further than the class's /// own — which is added to the depth of the scope the answer came from. pub(crate) steps: usize, @@ -1006,9 +1067,11 @@ pub(crate) struct Candidate { } impl Candidate { - pub(crate) fn new(file: PathBuf, fact: DeclFact, from: NameProvenance) -> Candidate { + /// A candidate for an arena entry the caller minted **through the index** — the file is taken from the + /// reference itself, so the two halves cannot disagree. + pub(crate) fn new(fact: FactRef, from: NameProvenance) -> Candidate { Candidate { - file, + file: fact.file, fact, steps: 0, from, @@ -1069,20 +1132,44 @@ pub(crate) const POPULAR_NAME: usize = 4096; /// and is offered. Filling this in wrong is not visible anywhere else: the fact's `local` field is only read by /// [`is_reserved_to_the_implementation`] on this path, and a local marked global silently disappears from the list. pub(crate) fn bindings_of( + index: &ProjectIndex, root: &CppSyntaxNode, path: &Path, bindings: &[Binding], scope: Option<&str>, local: bool, + // **In a body, only what is declared above the cursor is in scope** — see [`declared_above`], which is applied + // here rather than by the caller because the comparison has to happen while the fact is still in the tree's + // coordinates. `None` for a class, a namespace and the file scope, where textual order is not the language's + // rule. + above: Option, ) -> Vec { let spelling = scope.unwrap_or_default(); bindings .iter() - .map(|binding| { - let mut fact = fact_from_binding(root, spelling, binding); + .filter_map(|binding| { + let synthesized = fact_from_binding(root, spelling, binding); + let mut fact = synthesized.fact; fact.local = local; - Candidate::new(path.to_path_buf(), fact, NameProvenance::Scope) + // **In a body, only what is declared above the cursor is in scope.** A *scope* holds every binding + // written in its braces, so a list built from the scope contains `int c = a + b;` at a cursor three + // lines above it — a name that cannot be written there, because the language has not declared it yet. + // It is the same rule a reader applies without thinking, and the one a user reported: "在我下面声明的 + // 变量不应该补全出来". See [`declared_above`] for why the comparison happens here. + if above.is_some_and(|offset| !declared_above(&fact, offset)) { + return None; + } + // **The arena entry, never a guessed id.** A binding is a place in the scope tree, and the fact it + // describes already exists in the file's reading whenever the buffer has been read; the match is what + // turns the shape into the reference. A file between an edit and the pump's read — or a fixture no + // index has ever seen — has no arena entry, so the index interns the fact (with its parameters) in its + // view table instead of dropping the name. See [`ProjectIndex::intern_a_view_fact`]. + let reference = match index.fact_ref_matching(path, &fact) { + Some(reference) => reference, + None => index.intern_a_view_fact(path, fact, synthesized.parameters), + }; + Some(Candidate::new(reference, NameProvenance::Scope)) }) .collect() } @@ -1101,7 +1188,7 @@ pub(crate) fn global_names( .and_then(|root_scope| scopes.scope(root_scope)) // `false`: this **is** the global name space — the one scope where a name beginning with an underscore is // reserved to the implementation, which is why `Session::name_completions` does not offer `_Arg` or `_cprintf`. - .map(|data| bindings_of(root, path, &data.bindings, None, false)) + .map(|data| bindings_of(index, root, path, &data.bindings, None, false, None)) .unwrap_or_default(); // **The buffer's own file-scope names are the file's**, even though they live in the global name space: the @@ -1146,9 +1233,10 @@ pub(crate) fn declarations_in_scope( .declarations_in_where(spelling, visible_from, accepts) .into_iter() .map(|declaration| { + // The walk hands back the arena entry it borrowed the fact from, so the row points at a real + // declaration rather than a copy — see [`VisibleDeclaration::reference`]. Candidate::new( - declaration.file.clone(), - declaration.fact.clone(), + declaration.reference, provenance_of( index, visible_from, @@ -1181,8 +1269,7 @@ pub(crate) fn declarations_in_scope( continue; } found.push(Candidate::new( - declaration.file.clone(), - declaration.fact.clone(), + declaration.reference, provenance_of( index, visible_from, @@ -1192,13 +1279,16 @@ pub(crate) fn declarations_in_scope( )); } if let Some(summary) = index.summary(visible_from) { - for fact in &summary.declarations { - if fact.scope.is_none() && !fact.local && accepts(fact) { - found.push(Candidate::new( - summary.path.clone(), - fact.clone(), - NameProvenance::ThisFile, - )); + // **The root's own names are in its summary's arena, reading `0`.** The position is what names the + // entry, and the index is what confirms the summary is still the one it was read from — see + // [`ProjectIndex::summary_fact_ref`]. + for (at, fact) in summary.declarations.iter().enumerate() { + if fact.scope.is_none() + && !fact.local + && accepts(fact) + && let Some(reference) = index.summary_fact_ref(&summary.path, at) + { + found.push(Candidate::new(reference, NameProvenance::ThisFile)); } } } @@ -1218,8 +1308,7 @@ pub(crate) fn declarations_in_scope( .into_iter() .map(|declaration| { Candidate::new( - declaration.file.clone(), - declaration.fact.clone(), + declaration.reference, provenance_of( index, visible_from, @@ -1320,8 +1409,10 @@ pub(crate) fn names_of_a_class( // A class's own members are reachable from a cursor inside the class without a qualifier, and // they are ranked as what they are — the nearest thing there is, beside a local. Which is why // the provenance is `Scope` and the *depth* carries the inheritance: see `Score::LOCAL`. - let mut candidate = - Candidate::new(member.file, member.fact, NameProvenance::Scope); + // + // **A member row is already a reference row**, so the candidate is its `FactRef` — the two + // layers agree on the same declaration without materializing it. + let mut candidate = Candidate::new(member.fact, NameProvenance::Scope); candidate.steps = member.depth; candidate }) @@ -1338,16 +1429,27 @@ pub(crate) fn names_of_a_class( /// [`Candidate::steps`] is how far *inside* one answer the name was — a base class's members are one step further /// than the class's own — and the two are added because they mean the same thing to a consumer: how far the lookup /// had to walk before it found this name, which is the order C++ walks in too. -pub(crate) fn offered(found: Vec, depth: usize) -> Vec { +/// +/// The facts are resolved through `index` here, at the one edge every candidate passes through, so a row that +/// reaches a consumer always names an arena entry the index can answer for. +pub(crate) fn offered( + index: &ProjectIndex, + found: Vec, + depth: usize, +) -> Vec { found .into_iter() - .filter(|candidate| !candidate.fact.name.is_empty()) - .filter(|candidate| !is_reserved_to_the_implementation(&candidate.fact)) - .map(|candidate| OfferedName { - file: candidate.file, - fact: candidate.fact, - depth: depth.saturating_add(candidate.steps), - from: candidate.from, + .filter_map(|candidate| { + let fact = index.fact(candidate.fact)?; + if fact.name.is_empty() || is_reserved_to_the_implementation(fact) { + return None; + } + Some(OfferedName { + file: candidate.file, + fact: candidate.fact, + depth: depth.saturating_add(candidate.steps), + from: candidate.from, + }) }) .collect() } @@ -1402,15 +1504,20 @@ pub(crate) fn is_reserved_to_the_implementation(fact: &DeclFact) -> bool { /// The hiding is what makes a *list* an answer rather than a pile: a local `count` and a header's `count` are two /// declarations of one name, and C++ reaches only the first. Both would be wrong to show — one of them is not what /// the user gets if they pick it — and the inner one is the one they get. -pub(crate) fn sort_and_hide(names: &mut Vec) { +pub(crate) fn sort_and_hide(index: &ProjectIndex, names: &mut Vec) { // Stable, so that two declarations of one name at one depth keep the order they were found in: that is an // overload, and reordering it would be inventing a preference. - names.sort_by(|one, other| { - one.depth - .cmp(&other.depth) - .then_with(|| one.fact.name.cmp(&other.fact.name)) - }); + // + // The key is taken **once per row** rather than once per comparison: resolving a `FactRef` walks a map and + // normalizes a path, and a named scope can hold thousands of rows. A keyed vector rather than + // `sort_by_cached_key` because that one is not documented as stable, and stability is part of the answer. + let mut keyed: Vec<((usize, &str), OfferedName)> = names + .drain(..) + .map(|name| ((name.depth, index.offered_name(&name)), name)) + .collect(); + keyed.sort_by(|left, right| left.0.cmp(&right.0)); + names.extend(keyed.into_iter().map(|(_, name)| name)); let mut seen: HashSet = HashSet::new(); - names.retain(|name| seen.insert(name.fact.name.to_string())); + names.retain(|name| seen.insert(index.offered_name(name).to_string())); } diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index f3502a5d..289bda80 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -10,6 +10,7 @@ use crate::BindingKind; use crate::DeclKind; use crate::FileView; use crate::ScopeTree; +use crate::index; use crate::sema; use cpp_parser::CppNameExpr; use cpp_parser::CppParam; @@ -34,7 +35,7 @@ pub(crate) fn range_for_element_type( path: &Path, named: &NamedDeclaration, depth: usize, -) -> Option> { +) -> Option> { let NamedDeclaration::Here(binding) = named else { return None; }; @@ -92,7 +93,7 @@ pub(crate) fn range_for_element_type( }; Some(match range_element_of(as_a_range(&container)) { - Some(element) => Known::Yes(parse_type_spelling(&element)), + Some(element) => Known::Yes(element), None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))), }) } @@ -111,7 +112,7 @@ pub(crate) fn range_for_element_type( /// ``` /// /// A view has no name this layer can spell — its type is a class template over a closure type — so the question is asked of -/// the **expression** and never of a `Type`: the left operand says the element, and each adaptor is a function on it. An +/// the **expression** and never of a `ComputedType`: the left operand says the element, and each adaptor is a function on it. An /// adaptor that changes the element through a body (`transform`'s lambda) is refused: reading a `return` there needs the /// same deduction a function body does, and a guess would offer the wrong members in the loop. /// @@ -125,7 +126,7 @@ pub(crate) fn element_of_a_range_expression( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Option> { +) -> Option> { use cpp_parser::CppAstNode; // **A pipe chain**: the element of the left, adapted by the right. @@ -169,7 +170,7 @@ pub(crate) fn element_of_a_range_expression( ) && let Some(element) = range_element_of(as_a_range(&container)) { - return Some(Known::Yes((parse_type_spelling(&element), file))); + return Some(Known::Yes((element, file))); } // **A pipeline a reader gave a name.** `auto ids = items | std::views::filter(pred);` binds the view, and a @@ -284,7 +285,7 @@ fn the_initializer_a_name_binds( /// The reference a range yields is treated as an **lvalue** ([`auto_substituted`]'s last argument): a container's /// element is one, which is what makes `auto&` a `T&`. A view that yields **prvalues** (`iota | transform(…)`) is the /// case where that is not known to hold — `auto&&` there would be `T&&` — and the value category is not part of -/// [`Type`]; `auto` and `const auto&` are unaffected, because copying and binding to const are the same either way. +/// [`ComputedType`]; `auto` and `const auto&` are unaffected, because copying and binding to const are the same either way. #[allow(clippy::too_many_arguments)] pub(crate) fn the_element_a_lambda_parameter_receives( memo: &TypeMemo, @@ -422,7 +423,7 @@ pub(crate) fn a_narrowed_generic_parameter( path: &Path, object: &CppSyntaxNode, depth: usize, -) -> Option<(Type, PathBuf)> { +) -> Option<(ComputedType, PathBuf)> { use cpp_parser::{CppAstNode, CppIfStat, CppLambdaExpr}; if depth > MAX_TYPE_DEPTH { @@ -600,40 +601,36 @@ fn the_alternatives_a_visit_hands( else { return None; }; - let written = type_of.to_string(); // **An alias is followed**, because `Shape` is what the use wrote and `std::variant<…>` is what it means. The - // target comes from the declaration's own `type_of`, **arguments included** — `resolve_aliases` answers the class - // name alone, which is right for a member lookup and loses exactly what this rule needs. - let mut resolved = written; + // target comes from the declaration's own `ComputedType`, **arguments included** — `resolve_aliases` answers the + // class name alone, which is right for a member lookup and loses exactly what this rule needs. Nothing is parsed + // on the way: the use's type is converted once, and each alias's target is materialized. + let mut resolved = type_of.clone(); for _ in 0..4 { - let parsed = parse_type_spelling(&resolved); - let Some(name) = parsed.class_name() else { + let Some(name) = resolved.class_name().map(str::to_string) else { break; }; if name == "std::variant" || name == "variant" { break; } let target = index - .files_declaring(name, path) + .files_declaring(&name, path) .into_iter() - .find(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.type_of.is_some() - }) - .and_then(|declared| declared.fact.type_of.as_deref().map(str::to_string)); + .find(|declared| declared.fact.kind == DeclKind::Type && declared.fact.has_type_of()) + .and_then(|declared| index.computed_type_of(declared.fact)); match target { Some(target) if target != resolved => resolved = target, _ => break, } } - let parsed = parse_type_spelling(&resolved); - let class = parsed.class_name()?; + let class = resolved.class_name()?; if !(class == "std::variant" || class == "variant") { return None; } - let alternatives: Vec = parsed + let alternatives: Vec = resolved .arguments() .iter() - .map(|one| one.to_string()) + .map(ToString::to_string) .collect(); (!alternatives.is_empty()).then_some(alternatives) } @@ -678,13 +675,13 @@ pub(crate) fn the_two_operands_of_a_pipe( /// **The element a view adaptor yields from `element`** — the right-hand side of a pipe, applied. #[allow(clippy::too_many_arguments)] pub(crate) fn adapted_element( - element: &Known<(Type, PathBuf)>, + element: &Known<(ComputedType, PathBuf)>, adaptor: &CppSyntaxNode, index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { use cpp_parser::CppAstNode; let Known::Yes((element, file)) = element else { @@ -762,7 +759,7 @@ pub(crate) fn adapted_element( /// place rather than offering a member the class does not have. fn the_member_a_lambdas_return_names( lambda: &cpp_parser::CppLambdaExpr, - element: &Type, + element: &ComputedType, index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, @@ -792,7 +789,8 @@ fn the_member_a_lambdas_return_names( let spelled = if parameter.is_auto() { element.clone() } else { - parse_type_spelling(¶meter.get_type_text()) + sema::types::type_of_a_parameter(parameter) + .unwrap_or_else(|| parse_type_spelling(¶meter.get_type_text())) }; // **The class, not the reference the parameter binds** — `const Item&` and `Item` have the same members. let class = as_a_range(&spelled).to_string(); @@ -806,9 +804,10 @@ fn the_member_a_lambdas_return_names( return None; }; let member = listed.members.iter().find(|member| { - member.fact.name == access.member && member.fact.kind == DeclKind::Variable + index.member_name(member) == access.member + && index.member_kind(member) == Some(DeclKind::Variable) })?; - let written = member.fact.type_of.clone()?.to_string(); + let written = index.member_type_spelling(member)?; match &agreed { None => agreed = Some(written), Some(previous) if *previous == written => {} @@ -819,9 +818,11 @@ fn the_member_a_lambdas_return_names( } /// **One component of a `pair`-shaped type**, without the `const` a map's key carries. -pub(crate) fn pair_component(element: &Type, position: usize) -> Option { - let Type::Named { name, arguments } = element else { - return None; +pub(crate) fn pair_component(element: &ComputedType, position: usize) -> Option { + let (name, arguments) = match element { + ComputedType::Named(name) => (name.as_str(), &[][..]), + ComputedType::Generic(generic) => (generic.name.as_str(), &generic.arguments[..]), + _ => return None, }; let plain = name.rsplit("::").next().unwrap_or(name); if plain != "pair" && plain != "tuple" { @@ -833,18 +834,18 @@ pub(crate) fn pair_component(element: &Type, position: usize) -> Option { /// The same type without a leading `const` — `keys` yields the key, and the key of a `map` is `const K` **in the pair**, /// not in the view's element. -pub(crate) fn strip_a_leading_const(type_of: &Type) -> Type { - let written = type_of.to_string(); - match written.strip_prefix("const ") { - Some(rest) => parse_type_spelling(rest), - None => type_of.clone(), +pub(crate) fn strip_a_leading_const(type_of: &ComputedType) -> ComputedType { + match type_of { + ComputedType::Qualified(qualified) if qualified.is_const && !qualified.is_volatile => { + (*qualified.of).clone() + } + _ => type_of.clone(), } } /// **The element of the element** — `join`'s rule, for the shapes this layer can read. -pub(crate) fn element_of_the_element(element: &Type) -> Option { - let written = element_of(element, 0)?; - Some(parse_type_spelling(&written)) +pub(crate) fn element_of_the_element(element: &ComputedType) -> Option { + element_of(element, 0) } /// **The element of the range an iterator expression came from** — `numbers.begin()`, `numbers.begin() + 3`. @@ -860,7 +861,7 @@ pub(crate) fn element_of_an_iterator_expression( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Option> { +) -> Option> { // `v.begin()` / `v.end()` — a member call whose object is the range. if let Some(access) = sema::resolve::member_access_of(expression) { let written = access.member.clone(); @@ -879,7 +880,7 @@ pub(crate) fn element_of_an_iterator_expression( return None; }; let element = range_element_of(as_a_range(&container))?; - return Some(Known::Yes((parse_type_spelling(&element), file))); + return Some(Known::Yes((element, file))); } } // `begin + 3` — the iterator is the left operand, and the question is the same. @@ -914,10 +915,10 @@ pub(crate) fn a_call_to_a_function(expression: &CppSyntaxNode) -> Option&` and must stay one. -pub(crate) fn as_a_range(type_of: &Type) -> &Type { +pub(crate) fn as_a_range(type_of: &ComputedType) -> &ComputedType { match type_of { - Type::Reference { to, .. } => as_a_range(to), - Type::Qualified { of, .. } => as_a_range(of), + ComputedType::Reference { to, .. } => as_a_range(to), + ComputedType::Qualified(qualified) => as_a_range(&qualified.of), other => other, } } @@ -926,17 +927,17 @@ pub(crate) fn as_a_range(type_of: &Type) -> &Type { /// /// The difference is what the two spellings ask: `for (auto x : map)` binds the `pair` itself, while /// `for (auto [key, value] : map)` binds its two halves. -pub(crate) fn range_element_of(container: &Type) -> Option { +pub(crate) fn range_element_of(container: &ComputedType) -> Option { // **A reference and a qualifier are the binding's business**, and this is where the rule is load-bearing: // `const std::map>& configMap` is the ordinary spelling of a by-reference - // parameter, and a reader that matched `Type::Named` alone answered "this container has no element" for every + // parameter, and a reader that matched `ComputedType::Named` alone answered "this container has no element" for every // one of them. Measured on `CodeFormatCore/src/Config/LuaStyle.cpp:20` — `auto it = configMap.find(key);` was // typed `_Tree_const_iterator<_Scary_val>` (the class's own member, unsubstituted) instead of the element, and - // `it->second` answered "has no member `second`". [`Type::class_name`] and [`Type::arguments`] are the same two + // `it->second` answered "has no member `second`". [`ComputedType::class_name`] and [`ComputedType::arguments`] are the same two // questions the member walk asks, and both see through `Reference` and `Qualified`. let Some(name) = container.class_name() else { return match container { - Type::Array { of, .. } => Some(of.to_string()), + ComputedType::Array { of, .. } => Some((**of).clone()), _ => None, }; }; @@ -953,10 +954,15 @@ pub(crate) fn range_element_of(container: &Type) -> Option { "map" | "unordered_map" | "multimap" | "unordered_multimap" ) && arguments.len() >= 2 { - return Some(format!( - "std::pair", - arguments[0], arguments[1] - )); + let first = ComputedType::Qualified(Arc::new(index::types::QualifiedType { + of: Arc::new(arguments[0].clone()), + is_const: true, + is_volatile: false, + })); + return Some(ComputedType::Generic(Arc::new(index::types::GenericType { + name: smol_str::SmolStr::new("std::pair"), + arguments: Box::new([first, arguments[1].clone()]), + }))); } // The same allowance for the one-argument containers: a `vector` and a `set` are the same @@ -979,11 +985,11 @@ pub(crate) fn range_element_of(container: &Type) -> Option { | "valarray" ) { - return Some(arguments[0].to_string()); + return Some(arguments[0].clone()); } if matches!(plain, "array") && !arguments.is_empty() { - return Some(arguments[0].to_string()); + return Some(arguments[0].clone()); } None @@ -1003,7 +1009,7 @@ pub(crate) fn initializer_type( path: &Path, named: &NamedDeclaration, depth: usize, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { let Some((_, expression)) = deduction_inputs(root, named) else { // Either the declaration is in another file — the initializer is written where the declaration is, and this // layer holds one file's syntax — or it has none at all (`auto n;` is ill-formed, and saying so is the @@ -1219,7 +1225,7 @@ pub(crate) fn node_covering( /// declaration that does not compile rather than a type to report. pub(crate) fn auto_substituted( written: &str, - deduced: &Type, + deduced: &ComputedType, initializer_is_an_lvalue: bool, ) -> Option { // **`decltype(auto)` means "the type this expression has"** — so the deduced type *is* the answer, not a @@ -1357,29 +1363,17 @@ pub(crate) fn auto_substituted( Some(type_of) } -/// Is this a return spelling the *body* decides — `auto`, `auto&`, `decltype(auto)`? -pub(crate) fn is_a_placeholder(written: &str) -> bool { - matches!( - written.trim(), - "auto" | "auto&" | "auto&&" | "const auto" | "const auto&" | "decltype(auto)" - ) -} - -pub(crate) fn what_a_call_has_in(fact: &DeclFact) -> Option { +pub(crate) fn what_a_call_has_in(index: &ProjectIndex, fact: &DeclFact) -> Option { match fact.kind { // `Widget()` is a temporary of `Widget`, so a call of a class has the class. `DeclKind::Type` is exactly // "this declaration declares a class-like type", which is the case a call whose callee is a *type* lands in. - DeclKind::Type => Some(Type::named(fact.qualified_name())), - // **A placeholder is not a return type.** `auto copy_of() const { return value_; }` records `auto` as the spelling - // the file wrote, and parsing it answers a type *called* `auto` — which reads like an answer and is not one. `None` - // here is what lets the caller deduce from the body, which is the same thing the same-file arm already does; the - // body is read from the declaring file at the fact's offset **translated into that file's rendering**, which is - // where this path used to land on a neighbouring declaration instead. - _ => fact - .returns - .as_deref() - .filter(|written| !is_a_placeholder(written)) - .map(parse_type_spelling), + DeclKind::Type => Some(ComputedType::named(fact.qualified_name(), Vec::new())), + // **A placeholder is not a return type.** `auto copy_of() const { return value_; }` records `auto`, and + // converting it answers a type *called* `auto` — which reads like an answer and is not one. `None` here is what + // lets the caller deduce from the body, which is the same thing the same-file arm already does. + _ => index + .computed_returns_of(fact) + .filter(|returns| !returns.is_a_placeholder()), } } @@ -1428,7 +1422,7 @@ pub(crate) fn structured_binding_type( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Option> { +) -> Option> { // **The declaration the name resolves to**, and then the pattern it was declared in. let at = end_of_the_written_name(expression); let Known::Yes(binding) = sema::resolve::definition_at(scopes, root, at) else { @@ -1498,8 +1492,10 @@ pub(crate) fn structured_binding_type( // `int` and `double` and not the parameters it was declared with. The order is asked by **name** rather than by // position: the member list is sorted, so "the first data member" is not a question it can answer. let element = element_of(&container, position).or_else(|| { - let Type::Named { name, .. } = &container else { - return None; + let name: &str = match &container { + ComputedType::Named(name) => name.as_str(), + ComputedType::Generic(generic) => generic.name.as_str(), + _ => return None, }; let wanted = match position { 0 => "first", @@ -1520,12 +1516,15 @@ pub(crate) fn structured_binding_type( listed .members .iter() - .find(|member| member.fact.name == wanted && member.fact.kind == DeclKind::Variable) - .and_then(|member| member.fact.type_of.clone().map(|target| target.to_string())) + .find(|member| { + index.member_name(member) == wanted + && index.member_kind(member) == Some(DeclKind::Variable) + }) + .and_then(|member| index.member_computed_type(member)) }); Some(match element { - Some(element) => Known::Yes((parse_type_spelling(&element), file)), + Some(element) => Known::Yes((element, file)), None => Known::Unknown(UnknownReason::UnknownType(Box::from(container.to_string()))), }) } @@ -1629,13 +1628,17 @@ pub(crate) fn initializer_of_the_pattern(pattern: &CppSyntaxNode) -> Option Option { - let Type::Named { name, arguments } = container else { +pub(crate) fn element_of(container: &ComputedType, position: usize) -> Option { + let (name, arguments): (&str, &[ComputedType]) = match container { + ComputedType::Named(name) => (name.as_str(), &[]), + ComputedType::Generic(generic) => (generic.name.as_str(), &generic.arguments), // An array's element is its own type: `int[4]` binds `int`. - return match container { - Type::Array { of, .. } => Some(of.to_string()), - _ => None, - }; + _ => { + return match container { + ComputedType::Array { of, .. } => Some((**of).clone()), + _ => None, + }; + } }; let plain = name.rsplit("::").next().unwrap_or(name); @@ -1650,13 +1653,19 @@ pub(crate) fn element_of(container: &Type, position: usize) -> Option { // still a map of `pair`; requiring exactly two arguments made every `CaseInsensitive` map // untypeable, so a range-for's `[key, value]` stayed the `auto&[]` placeholder. return match position { - 0 => Some(format!("const {}", arguments[0])), - _ => Some(arguments[1].to_string()), + 0 => Some(ComputedType::Qualified(Arc::new( + index::types::QualifiedType { + of: Arc::new(arguments[0].clone()), + is_const: true, + is_volatile: false, + }, + ))), + _ => Some(arguments[1].clone()), }; } if matches!(plain, "array") && arguments.len() == 2 { - return Some(arguments[0].to_string()); + return Some(arguments[0].clone()); } // A sequence, a set, or a span: one argument, and the element is it. @@ -1678,14 +1687,12 @@ pub(crate) fn element_of(container: &Type, position: usize) -> Option { | "valarray" ) { - return Some(arguments[0].to_string()); + return Some(arguments[0].clone()); } // `pair` and `tuple` are the components themselves. if matches!(plain, "pair" | "tuple") { - return arguments - .get(position) - .map(|component| component.to_string()); + return arguments.get(position).cloned(); } None @@ -1765,12 +1772,15 @@ pub(crate) fn is_an_identifier(segment: &str) -> bool { /// The result is **positional against the template parameter names**, which is how every consumer of a substitution /// reads it: a name with no deduced argument stays itself, so `_Alloc` in `template ` does /// not silently become `_Ty`'s argument. -pub(crate) fn deduce_the_parameters( - names: &[String], +pub(crate) fn deduce_the_parameters>( + names: &[N], written_list: Option<&str>, - argument_types: &[Type], -) -> Vec { - let mut deduced: Vec = names.iter().map(Type::named).collect(); + argument_types: &[ComputedType], +) -> Vec { + let mut deduced: Vec = names + .iter() + .map(|name| ComputedType::named(name.as_ref(), Vec::new())) + .collect(); if names.is_empty() || argument_types.is_empty() { return deduced; } @@ -1818,7 +1828,7 @@ pub(crate) fn deduce_the_parameters( .map(str::trim) .unwrap_or(written_type); - let Some(name_at) = names.iter().position(|name| name == bare) else { + let Some(name_at) = names.iter().position(|name| name.as_ref() == bare) else { continue; }; let Some(argument) = argument_types.get(at) else { diff --git a/crates/cpp_code_analysis/src/index/project/macro_environment.rs b/crates/cpp_code_analysis/src/index/project/macro_environment.rs index 71a48d22..dbe683e6 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -7,10 +7,55 @@ use crate::Binding; use crate::BindingKind; use crate::DeclKind; use crate::DeclModifiers; +use crate::FileId; +use crate::index; +use crate::index::types::ComputedType; use smol_str::SmolStr; +use std::sync::Arc; use super::*; +/// **The identity of one immutable declaration inside its file's fact arena.** The index re-reads a file by +/// replacing its whole summary, so this id is meaningful only for the summary it was minted from. +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DeclFactId(u32); + +impl DeclFactId { + pub fn from_index(index: usize) -> DeclFactId { + DeclFactId(index as u32) + } + + pub fn index(self) -> usize { + self.0 as usize + } +} + +/// **A declaration reference that survives a moved member list**: the file's runtime id and the local fact id. +/// It never owns the `DeclFact` and it never stores a path. +/// +/// # The reading is part of the arena's identity +/// +/// A file has **more than one fact arena**: its summary (`reading == 0`) and one arena per cooked reading — the file +/// cooked on its own (`1`) and cooked inside a program (`2 + its position`), see `Readings`. The readings are what make +/// `DECLARE_HANDLE(HWND)` a declaration and what let two translation units read one header differently, so a reference +/// that could not name one would resolve to a different fact than the query found. `reading` names the arena; `fact` +/// is local to it, exactly as [`DeclFactId`] documents. +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FactRef { + pub file: FileId, + /// `0` is the file's summary; `1..` is a cooked reading (see `Readings`); [`FactRef::SYNTHETIC_READING`] is a + /// fact a query synthesized and the index interned for it (see [`ProjectIndex::intern_synthetic_fact`]). + pub reading: u32, + pub fact: DeclFactId, +} + +impl FactRef { + /// The reading value that names the index's arena of **query-synthesized facts** — one that no file's reading + /// holds, such as the members Unreal's build tool generates. Real readings are `0` and small positions, so the + /// largest value cannot collide with one. + pub const SYNTHETIC_READING: u32 = u32::MAX; +} + /// Every fact about one macro name that a file can reach — the answer to "what is this name here", before the /// question of *where* is asked. /// @@ -240,6 +285,8 @@ impl MacroCandidate { pub struct VisibleDeclaration<'a> { pub file: PathBuf, pub fact: &'a DeclFact, + /// The reference to the exact arena entry this fact was borrowed from — the summary's or one cooked reading's. + pub(crate) reference: FactRef, pub visibility: IncludeVisibility, } @@ -249,6 +296,8 @@ pub struct VisibleDeclaration<'a> { pub(crate) struct ProjectDeclaration { pub(crate) file: PathBuf, pub(crate) fact: DeclFact, + /// The arena entry the owned `fact` was copied from — what a [`ProjectDefinition`] answers with. + pub(crate) reference: FactRef, pub(crate) start_offset: usize, } @@ -257,6 +306,7 @@ impl ProjectDeclaration { ProjectDeclaration { file: found.file.clone(), fact: found.fact.clone(), + reference: found.reference, start_offset: found.fact.name_range.start_offset, } } @@ -328,7 +378,7 @@ impl IndexedKind { // answered `struct Pair`. Measured on `test_cpp/src/templates.cpp:166`. template: found.kind == DeclKind::Variable && !found.parameters().is_empty(), constructor: found.kind == DeclKind::Function - && found.returns.is_none() + && !found.has_returns() && found .scope .as_deref() @@ -338,12 +388,14 @@ impl IndexedKind { } /// The answer to a cross-file definition question. +/// +/// A **reference**, not a copy of the declaration: an answer is a location in a file the index holds, and the +/// declaration itself belongs to that file's fact arena. [`ProjectIndex::definition_fact`] resolves it and +/// [`ProjectIndex::definition_path`] spells the file; a consumer that needs a field of the fact reads it there. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProjectDefinition { - pub file: PathBuf, - /// The declaration, cloned out of the index so that an answer does not borrow the project for as long as a - /// consumer wants to hold it — a language server hands the location to a client and moves on. - pub fact: DeclFact, + pub file: FileId, + pub fact: FactRef, } /// **Every declaration a name refers to** — the plural answer to "where is this declared". @@ -431,11 +483,21 @@ impl MemberList { } } -/// One member of a type: where it is declared, and which class in the chain declares it. +/// One member of a type: **which declaration it names**, which class in the chain declares it, and this +/// instantiation's substitution. +/// +/// A reference row, not a copy of the declaration: the fact belongs to the file's fact arena, and +/// [`ProjectIndex::member_fact`] resolves it. Nothing here is a path or an owned [`DeclFact`], so a member list can be +/// moved, cloned and merged without copying the declarations it names. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProjectMember { - pub file: PathBuf, - pub fact: DeclFact, + /// The immutable declaration this row names. Resolve it through [`ProjectIndex::member_fact`]. + pub fact: FactRef, + /// The per-member instantiation context, when this row is a substituted view. + /// + /// The substitution is **never written into the fact**: reading a member's type or display spelling applies it at + /// the edge, through [`ProjectIndex::member_type_spelling`] and the other `member_*` accessors. + pub substitution: Option>, /// The **resolved** qualified name of the class that declares it — the type asked about, or one of its bases. /// /// The qualified name rather than the spelling the derived class wrote, because that is what makes the member @@ -454,6 +516,95 @@ pub struct ProjectMember { pub ambiguous: bool, } +/// **One member's instantiation context**: what the class template's parameters stand for, and the written context +/// the display layer needs to reproduce the substitution without rewriting the stored fact. +/// +/// The structured half is `bindings`, which the computation layer applies to a [`ComputedType`] with +/// [`ComputedType::substituted`]. `stages` is the same pairing as each instantiation wrote it — the parameter names, +/// their defaults, the arguments the use wrote, and the class's own aliases — because a member fact's *display* still +/// goes through the written form: the parameter list and the fact's spelling are substituted as text at that edge, and +/// the stages are what that rewrite runs with. Keeping it here is what lets the fact stay immutable: a substituted +/// view is a row with this context attached, not a rewritten declaration. +/// +/// A substitution may be **composed** of several stages: a member inherited from a base was first substituted with the +/// base clause's arguments, and the derived use's arguments are applied after that. The stages are kept in that order, +/// oldest first, which is exactly the order the two textual rewrites used to run in. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MemberSubstitution { + /// The class template's parameter names paired with the structured arguments, in declaration order, newest + /// instantiation first on a duplicate name. + pub bindings: Vec<(SmolStr, ComputedType)>, + /// **The class's own aliases, as types** — `value_type` → `_Tp` → (after `bindings`) `int`. + /// + /// A member is declared `void push_back(const value_type&)` with `using value_type = _Tp;` in the class, so the + /// structured substitution above alone leaves the *name* `value_type` standing. This is the structured twin of + /// [`MemberSubstitutionStage::alias_names`]/[`MemberSubstitutionStage::alias_targets`], which the display layer + /// has always applied as text: the target is parsed once where the alias list is collected, and + /// [`ComputedType::replacing`] applies it without touching a spelling. + pub alias_bindings: Vec<(SmolStr, ComputedType)>, + /// One written substitution per instantiation applied to the row, oldest first. + pub stages: Vec, +} + +/// **One written instantiation** — the text half of a [`MemberSubstitution`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MemberSubstitutionStage { + /// The declaration's parameter names, position for position — including parameters the use did not write, whose + /// defaults (`parameter_defaults`) stand in for them. + pub parameter_names: Vec, + /// The written defaults of `parameter_names`, position for position; empty entries for parameters with none. + pub parameter_defaults: Vec, + /// The arguments as the use wrote them, position for position with `parameter_names`. + pub written_arguments: Vec, + /// The class's own aliases, expanded before the parameters are — `value_type` -> `_Tp`. + pub alias_names: Vec, + /// The targets of [`MemberSubstitutionStage::alias_names`], position for position. + pub alias_targets: Vec, +} + +impl MemberSubstitutionStage { + /// **A lower-bound heap estimate**, in the style the memory report uses: the vectors' element arrays and the + /// payloads that fell out of line. + fn heap_bytes(&self) -> usize { + let lists = [ + &self.parameter_names, + &self.parameter_defaults, + &self.written_arguments, + &self.alias_names, + &self.alias_targets, + ]; + lists + .iter() + .map(|list| { + list.len() * size_of::() + + list + .iter() + .map(|text| text.len().saturating_sub(22)) + .sum::() + }) + .sum() + } +} + +impl MemberSubstitution { + /// **What this context costs outside the [`ProjectMember`] row** — the boxed vectors it owns, a lower bound. + pub fn heap_bytes(&self) -> usize { + size_of::() + + self.bindings.len() * size_of::<(SmolStr, ComputedType)>() + + self + .bindings + .iter() + .map(|(name, _)| name.len().saturating_sub(22)) + .sum::() + + self.stages.len() * size_of::() + + self + .stages + .iter() + .map(MemberSubstitutionStage::heap_bytes) + .sum::() + } +} + /// A base whose members are not in the list, and why. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnlistedBase { @@ -471,12 +622,15 @@ impl ProjectDefinition { /// /// [`crate::sema::resolve::definition_at`] answers with a [`Binding`], which carries a `Name` rather than a plain /// string and no qualified scope — so the two answers are made to look alike here, in one place, rather than - /// at every call site. + /// at every call site. The binding's shape is then **matched back to the arena entry** the file's reading already + /// holds: this type answers with a [`FactRef`], and a fact that exists only inside a binding has no arena entry to + /// point at. `None` is that case — a buffer the index has not read yet — and the caller answers `Unknown`. /// /// `scope` is what the *caller* knows and this does not: the qualified name a member access or a qualifier /// went through (`Widget` for `widget.size`, `ns` for `ns::Widget`), or `None` for a name written bare. It is /// passed rather than derived because deriving it here would mean re-reading the cursor, and left empty it - /// would make `widget.size` and a free `size` indistinguishable to a consumer showing the answer. + /// would make `widget.size` and a free `size` indistinguishable to a consumer showing the answer. It is part of + /// the **match key**, not of the answer: the resolved fact carries the scope the summary recorded. /// /// `local` is passed for the same reason, one step further out: whether the name can be reached from another /// file is a fact about the **scope chain** the binding was made in, and a `Binding` carries a [`crate::ScopeId`] @@ -484,48 +638,71 @@ impl ProjectDefinition { /// /// [`Binding`]: crate::Binding /// [`ScopeTree::declares_a_local`]: crate::ScopeTree::declares_a_local - pub fn from_binding(path: &Path, binding: Binding, scope: Option, local: bool) -> Self { - ProjectDefinition { - file: path.to_path_buf(), - fact: DeclFact { - enumerator: binding.kind == BindingKind::Enumerator, - // The same bits the index fills — see `DeclModifiers`. - modifiers: DeclModifiers::default(), - // The effects belong to the summary the index writes, and this answer is a *place to jump to*: a - // caller that wants `frees` asks the fact, which is the same rule `in_namespace` below follows. - frees: 0, - detail: None, - name: binding.name.identifier_text().unwrap_or_default().into(), - scope: scope.map(SmolStr::from), - local, - // `None` for the same reason `type_of` below is: this answer is a **place to jump to**, built - // from a binding, and the namespaces around a body are a fact about the file's text that lives in - // its summary. See [`DeclFact::in_namespace`]. - kind: DeclKind::from_binding_kind(binding.kind), - // Unknown here, and harmlessly so: this answer is a **place to jump to**, never a candidate a member - // query picks between definitions. See [`DeclFact::definition`]. - definition: false, - // No type, no return type and no bases, because this answer is a *place to jump to* and the binding - // it comes from carries none of them: they are facts about the file's text, and the file they - // belong to has the summary that holds them. A consumer asking what a name *is* asks the index, - // not this answer. - type_of: None, - returns: None, - split_by_a_directive: false, - // Same reason as `constraints` above: a clause is the declaration's text, and this is a place to jump to. - // Nor a pattern: this fact is a place to jump to, and the class it names is already the one the - // caller asked about. See [`DeclFact::pattern`]. - access: None, - exported: false, - range: binding.range, - name_range: binding.name_range, - // And no answer about diagnostics either, for the same reason `guard` has none: the binding came - // from the buffer's own scopes, which are built from a node rather than from a tree with a - // diagnostic list. See [`fact_from_binding`]. - clean: true, - guard: FactGuard::Unconditional, - }, + pub fn from_binding( + index: &ProjectIndex, + path: &Path, + binding: Binding, + scope: Option, + local: bool, + // The **file** offset for an offset in the tree the binding came from — the identity for a tree of the + // file's own text, and the view's reading→file map for a rendering. The arena's ranges are file + // coordinates, so a binding built from a rendering is placed before it is matched. + to_file: &dyn Fn(usize) -> Option, + ) -> Option { + let mut shaped = fact_from_a_binding(binding, scope, local); + if let Some(start) = to_file(shaped.name_range.start_offset) { + shaped.name_range = SourceRange::new(start, shaped.name_range.length); } + if let Some(start) = to_file(shaped.range.start_offset) { + shaped.range = SourceRange::new(start, shaped.range.length); + } + let reference = index.fact_ref_matching(path, &shaped)?; + Some(ProjectDefinition { + file: reference.file, + fact: reference, + }) + } +} + +/// The shape a binding answers with, for matching against the fact an arena holds. +fn fact_from_a_binding(binding: Binding, scope: Option, local: bool) -> DeclFact { + DeclFact { + enumerator: binding.kind == BindingKind::Enumerator, + // The same bits the index fills — see `DeclModifiers`. + modifiers: DeclModifiers::default(), + // The effects belong to the summary the index writes, and a binding carries none of them: they are facts + // about the file's text, and the file it belongs to has the summary that holds them. + frees: 0, + detail: None, + name: binding.name.identifier_text().unwrap_or_default().into(), + scope: scope.map(SmolStr::from), + local, + // A gap for the same reason `type_of` below is: a binding is a place in a scope chain, and the namespaces + // around a body are a fact about the file's text that lives in its summary. See [`DeclFact::in_namespace`]. + kind: DeclKind::from_binding_kind(binding.kind), + // Unknown here, and harmlessly so: the match key below does not read it. See [`DeclFact::definition`]. + definition: false, + // No type, no return type and no bases, because the binding it comes from carries none of them: they are + // facts about the file's text, and the file they belong to has the summary that holds them. This shaped fact + // is never answered with — [`ProjectDefinition`] answers with the reference to the arena entry. + type_of: DeclaredType::None, + returns: DeclaredType::None, + parameters: index::params::ParamsId::NONE, + // **No list to be variadic**, for the same reason: a binding is a place in a scope chain, and whether the + // declaration's list wrote `...` is in the summary that read the declaration. The match key below does not + // read it, and a shaped fact is never answered with — [`ProjectDefinition`] answers with the arena entry. + variadic_parameters: false, + split_by_a_directive: false, + // Same reason as `constraints` above: a clause is the declaration's text, and this shape is a match key. + // Nor a pattern: the class it names is already the one the caller asked about. See [`DeclFact::pattern`]. + access: None, + exported: false, + range: binding.range, + name_range: binding.name_range, + // And no answer about diagnostics either, for the same reason `guard` has none: the binding came from the + // buffer's own scopes, which are built from a node rather than from a tree with a diagnostic list. + clean: true, + guard: FactGuard::Unconditional, } } @@ -744,6 +921,10 @@ pub(crate) fn rank_of(qualified: &str, name: &str, wanted: &str) -> Option bool { one.name == other.name && one.scope == other.scope @@ -754,6 +935,7 @@ pub(crate) fn the_same_declaration(one: &DeclFact, other: &DeclFact) -> bool { && one.bases() == other.bases() && one.parameters() == other.parameters() && one.parameter_list() == other.parameter_list() + && one.variadic_parameters == other.variadic_parameters } /// Are these two candidates **one declaration recorded twice**, as far as this index can tell? @@ -787,7 +969,7 @@ pub(crate) fn the_same_declaration_in_one_file( match one.fact.kind { // A variable, and an alias (which this model records as a `Type` with a spelling): the type tells two of // them apart, and an absent one is silence rather than agreement. - DeclKind::Variable | DeclKind::Type => one.fact.type_of.is_some(), + DeclKind::Variable | DeclKind::Type => one.fact.has_type_of(), // A function: the parameter list, which is the field that separates overloads and the one this model reads // out of the declarator. `parameters` — the *template* parameter names — is not evidence about a function: // an ordinary function has none, so requiring it here would refuse to merge anything. diff --git a/crates/cpp_code_analysis/src/index/project/macro_walk.rs b/crates/cpp_code_analysis/src/index/project/macro_walk.rs index 885c17f6..2c1db817 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -5,13 +5,17 @@ //! decided which branch was taken, and the order the files were included in. use super::*; +use crate::DeclModifiers; use crate::FactGuard; +use crate::FileId; use crate::MacroKind; use crate::ProjectMember; use crate::UnlistedBase; use crate::Visibility; use crate::cache; use crate::index; +use crate::index::params::{ParameterFact, ParamsStore}; +use crate::index::types::ComputedType; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -149,10 +153,10 @@ impl ProjectIndex { let path = normalize(Path::new(path)); if let Ok(mut answers) = self.definition_answers.lock() { answers.retain(|_, answer| match answer { - Known::Yes(definitions) => definitions - .found - .iter() - .all(|declaration| normalize(&declaration.file) != path), + Known::Yes(definitions) => definitions.found.iter().all(|declaration| { + self.path_of(declaration.file) + .is_none_or(|file| normalize(file) != path) + }), _ => true, }); } @@ -218,6 +222,7 @@ impl ProjectIndex { names.push(OwnedVisibleDeclaration { file: declaration.file, fact: declaration.fact.clone(), + reference: declaration.reference, visibility: declaration.visibility, }); } @@ -375,6 +380,751 @@ impl ProjectIndex { } } + /// **The index-wide parameter arena**, append-only. It is not the resolver for a stored fact: a fact's + /// `ParamsId` is local to the arena that issued it, and [`ProjectIndex::parameter_facts_of`] is the query that + /// finds that arena — a summary's table, a cooked reading's, or the synthetic arena a view fact was interned into. + /// + /// There is no matching `types()`: a declaration's type is an immutable [`ComputedType`] value on the fact, not a + /// handle into an index-side arena. + pub fn parameters(&self) -> &ParamsStore { + &self.parameters + } + + /// **The parameter facts a fact names**, resolved through the arena that owns its `ParamsId` — the summary that + /// filed the fact, the cooked reading it came from, or the synthetic arena a view query interned it in. No text + /// fallback. + /// + /// # Which arena, and why in this order + /// + /// A `ParamsId` is local to one [`ParamsStore`], so the fact has to be resolved through the table that issued it: + /// + /// * **The synthetic arena first.** A synthesized fact may name a file the index *has* read (Unreal's generated + /// members do), and its handle is `NONE` or belongs to another arena — asking the summary first would resolve it + /// against the wrong table. The fact is matched by pointer identity, then by equality, because a caller may hold + /// a clone (`member_display_fact`, a completion's chosen fact). + /// * **A pointer-identical summary fact** resolves through the summary's own store. This is the ordinary case. + /// * **A cooked fact** resolves through its reading's `CookedFile::parameters`; a reading built by hand may carry + /// no table, and the last step is the file's own summary entry for the same declaration (same `name` and + /// `name_range`) — the two readings are about one declaration. + /// * **A copy of a summary fact** reaches the same final step, because it is not pointer-identical. + pub fn parameter_facts_of(&self, file: &Path, fact: &DeclFact) -> &[ParameterFact] { + // **A synthesized fact answers from its own entry.** See `ProjectIndex::synthetic_facts` for why the list is + // beside the fact rather than in a store. + if let Some(parameters) = self.synthetic_parameter_facts(fact) { + return parameters; + } + let key = normalize(file); + let summary = self.summaries.get(&key); + // **`NONE` means "this fact names no table"** — a copy a query built from a buffer's scopes + // ([`crate::sema::declarations::facts_with_their_types`] clears the handle, because the store it named does + // not travel with the copy). The declaration itself is the file's, so the file's own reading is asked for the + // list: the identity is `name` + `name_range`, the same one the last step below uses. Only when there is no + // such declaration does the empty answer stand. + if fact.parameters.is_none() { + let Some(summary) = summary else { + return &[]; + }; + return summary + .declarations + .iter() + .find(|candidate| { + candidate.name == fact.name + && candidate.name_range == fact.name_range + && candidate.kind == fact.kind + }) + .map_or(&[], |candidate| summary.parameter_facts(candidate)); + } + let Some(summary) = summary else { + return &[]; + }; + if summary + .declarations + .iter() + .any(|candidate| std::ptr::eq(candidate, fact)) + { + return summary.parameter_facts(fact); + } + // **A cooked fact carries a handle into the rendering's own table.** That table is the reading's, so it is + // asked first; a reading built by hand (or one read back from a record before the table travelled with it) + // leaves the handle unresolved, and the summary's entry for the same declaration is the fallback. + if let Some(readings) = self.cooked.get(&key) { + for (_, reading) in readings.every() { + if reading + .declarations + .iter() + .any(|candidate| std::ptr::eq(candidate, fact)) + && let Some(parameters) = reading.parameters.get(fact.parameters) + { + return parameters; + } + } + } + summary + .declarations + .iter() + .find(|candidate| { + candidate.name == fact.name && candidate.name_range == fact.name_range + }) + .map_or(&[], |candidate| summary.parameter_facts(candidate)) + } + + /// **The parameters a synthesized fact's arena entry carries**, when this fact is one of them. + /// + /// Pointer identity is the precise answer and the one the constructors produce; equality is for a caller holding + /// a clone of an interned fact (a display copy). Both answer with a `&'static` slice the arena leaked when it + /// filed the fact, so the answer outlives the lock. + fn synthetic_parameter_facts(&self, fact: &DeclFact) -> Option<&[ParameterFact]> { + let arena = self.synthetic_facts.lock().ok()?; + if let Some(entry) = arena.iter().find(|entry| std::ptr::eq(entry.fact, fact)) { + return Some(entry.parameters); + } + arena + .iter() + .find(|entry| *entry.fact == *fact) + .map(|entry| entry.parameters) + } + + /// **Record the session VFS's id for a path** — the one registration edge between the two tables. + /// + /// The index never mints a `FileId`: [`crate::Vfs::load`] does, and this is how the owner of that VFS tells the + /// index which id a path got. Every runtime reference the index hands out (`FactRef`, `ProjectDefinition`, + /// `ProjectMember`, `OfferedName`, `VisibleDeclaration`) names the VFS id for a registered file, so a consumer can + /// ask the VFS about it or compare it with one the VFS handed out. + /// + /// Called by the session for every file it loads before indexing it — see `Session::index_one`. Registering the + /// same pair again is a no-op. A **conflicting** registration (one id for two paths, one path for two ids) is + /// refused and leaves both maps unchanged; so is an id in the fallback half, which is the index's own namespace + /// (see [`FALLBACK_FILE_ID_BIT`]). The rule is deliberately first-wins: facts already filed under the first + /// answer name it, and silently re-pointing them would make a definition jump land in a file whose facts belong + /// to another. + pub fn register_file_id(&mut self, path: &Path, id: FileId) { + self.file_ids.register(path, id); + } + + /// **The runtime file id a path is named by.** A registered VFS id wins; a path with none — a hand-built index, + /// a test, a caller with no VFS — gets its insertion sequence encoded in the index's own high-bit namespace. + /// + /// ```text + /// VFS registered the id `register_file_id` was given + /// no registration FileId(0x8000_0000 | sequence) + /// ``` + /// + /// The high bit is what keeps a fallback sequence from being mistaken for a VFS id (or a view id, which is + /// allocated downward from the top of the range): [`ProjectIndex::path_of`] can therefore decide which table an + /// id came from by looking at the number. The sequence is the same number the name index's postings carry, which + /// is why the fallback keeps it rather than minting a second numbering. + pub fn file_id_of(&self, path: &Path) -> Option { + if let Some(id) = self.file_ids.id_of(path) { + return Some(id); + } + let sequence = self.sequence.get(&normalize(path)).copied()?; + fallback_file_id(sequence) + } + + /// **The path a runtime file id names**, in the spelling every other query keys on. + /// + /// The inverse of [`ProjectIndex::file_id_of`], and the only way a consumer of a [`ProjectDefinition`] can name the + /// file it points into: an answer stores a [`crate::FileId`], never a `PathBuf`. + /// + /// The three tables are asked in the order the id's namespace says they must be: + /// + /// 1. **the session VFS's table** — the id a registered file was read under; + /// 2. **the view table** — a file a query synthesized facts for but the index never read; + /// 3. **the fallback sequence table** — the high-bit encoding [`ProjectIndex::file_id_of`] mints. + /// + /// The **filed spelling** comes from the summary, not from the normalized key the maps search by — a client was + /// given the path the project listed, and the two differ by case and separator on Windows. A file that has been + /// forgotten keeps only the normalized key, and its facts no longer resolve anyway. + pub fn path_of(&self, file: FileId) -> Option<&Path> { + // **The VFS's own namespace.** Asked first, because a registered id is the truth even when the file was + // loaded before it was indexed (or after it was forgotten). + if let Some(key) = self.file_ids.key_of(file) { + return Some(match self.summaries.get(key) { + Some(summary) => summary.path.as_path(), + None => Path::new(key), + }); + } + // **A file a query synthesized facts for but the index has not read** — see + // [`ProjectIndex::intern_a_view_fact`]. Its id is in the view table, not the summary one. + let number = file.index() as u32; + if let Ok(viewed) = self.view_paths.lock() + && let Some(path) = viewed.by_id.get(&number).copied() + { + return Some(path); + } + // **The index's own fallback numbering**, decoded through the high bit it was minted with. + let key = self.order.get(&fallback_sequence(file)?)?; + match self.summaries.get(key) { + Some(summary) => Some(summary.path.as_path()), + None => Some(Path::new(key.as_str())), + } + } + + /// **The reference to one declaration in its arena.** `None` when the fact is not in the summary filed at + /// `path` or in any cooked reading of it — see [`ProjectIndex::fact_ref_matching`] for the same question asked of + /// a fact the caller copied rather than borrowed. + pub fn fact_ref(&self, path: &Path, fact: &DeclFact) -> Option { + let file = self.file_id_of(path)?; + let key = normalize(path); + if let Some(summary) = self.summaries.get(&key) + && let Some(at) = summary + .declarations + .iter() + .position(|candidate| std::ptr::eq(candidate, fact)) + { + return Some(FactRef { + file, + reading: 0, + fact: DeclFactId::from_index(at), + }); + } + let readings = self.cooked.get(&key)?; + for (reading, cooked) in readings.every() { + if let Some(at) = cooked + .declarations + .iter() + .position(|candidate| std::ptr::eq(candidate, fact)) + { + return Some(FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }); + } + } + None + } + + /// **The reference to one declaration the caller owns a copy of** — what a constructor that has a `DeclFact` and a + /// path (a binding-derived shape, a member row, a view-built fact) uses instead of fabricating an id. + /// + /// The match runs in four narrowing steps, so that the exact arena entry a copy came from is found before a + /// declaration that merely sits at the same place: pointer identity, then full equality, then the identity a + /// declaration is named by (`name`, `name_range`, `kind`, `scope`), then the two positional fields alone. The + /// last step is what matches a binding-derived shape, which records no scope when the caller did not know one. + pub fn fact_ref_matching(&self, path: &Path, fact: &DeclFact) -> Option { + let file = self.file_id_of(path)?; + let key = normalize(path); + // **The summary first**, because it is the arena that outlives a cook — a file cooked again replaces its + // readings in place, while the summary is what a query without a program falls back to. + let summary = self.summaries.get(&key); + let readings: Vec<(u32, &[DeclFact])> = self + .cooked + .get(&key) + .map(|readings| { + readings + .every() + .map(|(reading, cooked)| (reading, cooked.declarations.as_slice())) + .collect() + }) + .unwrap_or_default(); + let arenas = || { + summary + .map(|summary| (0u32, summary.declarations.as_slice())) + .into_iter() + .chain(readings.iter().copied()) + }; + + for (reading, facts) in arenas() { + if let Some(at) = facts + .iter() + .position(|candidate| std::ptr::eq(candidate, fact)) + { + return Some(FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }); + } + } + for (reading, facts) in arenas() { + if let Some(at) = facts.iter().position(|candidate| candidate == fact) { + return Some(FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }); + } + } + let named = |candidate: &DeclFact| { + candidate.name == fact.name + && candidate.name_range == fact.name_range + && candidate.kind == fact.kind + && candidate.scope == fact.scope + }; + for (reading, facts) in arenas() { + if let Some(at) = facts.iter().position(named) { + return Some(FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }); + } + } + let at_the_site = |candidate: &DeclFact| { + candidate.name == fact.name && candidate.name_range == fact.name_range + }; + for (reading, facts) in arenas() { + if let Some(at) = facts.iter().position(at_the_site) { + return Some(FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }); + } + } + // **A shape whose ranges are in a rendering's coordinates, not the file's.** A binding-derived fact comes + // from the tree the cursor is in, and a rendering's whitespace is not the file's — the cook collapses it, so + // an offset from that tree can name a different place in the file. The declaration's own identity is still + // exact, so the arena entry is found by comparing the fields that make it the declaration it is. Only a + // **unique** match counts: two candidates that agree in every one of these fields are two declarations this + // cannot tell apart, and answering either would be a guess. + let by_identity = |candidate: &DeclFact| { + candidate.name == fact.name + && candidate.kind == fact.kind + && candidate.scope == fact.scope + && candidate.parameter_list() == fact.parameter_list() + && candidate.type_of == fact.type_of + && candidate.returns == fact.returns + && candidate.requires_clause() == fact.requires_clause() + && candidate.parameters() == fact.parameters() + && candidate.modifiers == fact.modifiers + }; + // Only a **unique** match counts: two declarations in one arena that agree in every one of these fields are + // two this cannot tell apart, and answering either would be a guess. The same declaration read twice — the + // file's summary and its cooked reading — is one declaration, so the first arena that holds it answers. + let mut chosen: Option<(u32, usize)> = None; + for (reading, facts) in arenas() { + let mut matching = facts + .iter() + .enumerate() + .filter(|(_, candidate)| by_identity(candidate)) + .map(|(at, _)| at); + let Some(at) = matching.next() else { + continue; + }; + if matching.next().is_some() { + return None; + } + chosen.get_or_insert((reading, at)); + } + chosen.map(|(reading, at)| FactRef { + file, + reading, + fact: DeclFactId::from_index(at), + }) + } + + /// **The reference to one declaration in a file's own summary**, by the position it occupies in that summary's + /// declaration list — reading `0`, because a summary is its file's first fact arena. + /// + /// The caller already holds the summary (a completion's root names are read from it), so this is the precise way + /// to name one entry without scanning the arena for it: the index checks that the filed summary is still the + /// one at `path` and that the position is in range, and answers `None` for a stale summary or a position past + /// its end — never a guess. + pub fn summary_fact_ref(&self, path: &Path, at: usize) -> Option { + let file = self.file_id_of(path)?; + let key = normalize(path); + let summary = self.summaries.get(&key)?; + if at >= summary.declarations.len() { + return None; + } + Some(FactRef { + file, + reading: 0, + fact: DeclFactId::from_index(at), + }) + } + + /// **Resolve a `FactRef` to the immutable declaration.** The path is recovered through + /// [`ProjectIndex::path_of`], never from the fact itself — so a reference minted with a VFS id and one minted with + /// a fallback sequence id resolve through the same edge. + pub fn fact(&self, reference: FactRef) -> Option<&DeclFact> { + // **A synthesized fact belongs to the index, not to a file's reading** — see + // [`ProjectIndex::intern_synthetic_fact`]. Its arena holds leaked entries so that the borrow this method + // answers with stays valid for as long as the index does; the leak is bounded by the distinct generated + // members a project has, not by the number of queries. + if reference.reading == FactRef::SYNTHETIC_READING { + return self + .synthetic_facts + .lock() + .ok()? + .get(reference.fact.index()) + .map(|entry| entry.fact); + } + let key = normalize(self.path_of(reference.file)?); + if reference.reading == 0 { + return self + .summaries + .get(&key)? + .declarations + .get(reference.fact.index()); + } + self.cooked + .get(&key)? + .reading(reference.reading)? + .declarations + .get(reference.fact.index()) + } + + /// **Intern a fact a query synthesized**, giving it a real [`FactRef`] in the index's synthetic arena. + /// + /// The reference names `file` so that a consumer showing "where this member is declared" still names the file the + /// row belongs to, but the fact itself is not in that file's reading — it is a generated member, and the arena is + /// the only place it exists. Equal facts **for one file** share one entry, so a query that regenerates the same + /// member on every keystroke does not grow the arena. + /// + /// `parameters` is the declaration's parameter list: a synthesized fact has no `ParamsStore` to name, so the arena + /// carries the list beside the fact and [`ProjectIndex::parameter_facts_of`] resolves it from here. A caller with + /// no list (a macro, a generated member) passes the empty one. + pub fn intern_synthetic_fact( + &self, + file: FileId, + fact: DeclFact, + parameters: Box<[ParameterFact]>, + ) -> FactRef { + let mut arena = self + .synthetic_facts + .lock() + .expect("the synthetic fact arena is not poisoned"); + let at = match arena.iter().position(|held| { + held.file == file && *held.fact == fact && held.parameters == &*parameters + }) { + Some(at) => at, + None => { + // **Leaked on purpose**, and bounded: `fact()` and `parameter_facts_of` answer with borrows, so the + // arena has to hand out references that outlive the lock. The alternative — an owned answer for one + // arena and a borrowed one for the others — would make every consumer carry a `Cow` for a case only + // a generated member reaches. Equal facts are deduplicated above, so this grows with the project's + // synthesized declarations, not with its queries. + let leaked_fact: &'static DeclFact = Box::leak(Box::new(fact)); + let leaked_parameters: &'static [ParameterFact] = Box::leak(parameters); + arena.push(SyntheticFactEntry { + file, + fact: leaked_fact, + parameters: leaked_parameters, + }); + arena.len() - 1 + } + }; + FactRef { + file, + reading: FactRef::SYNTHETIC_READING, + fact: DeclFactId::from_index(at), + } + } + + /// **Intern a fact a query synthesized from a view the index has not read** — the buffer between a client's edit + /// and the pump's read, or a view a test built without indexing. + /// + /// Such a file has no summary, so [`ProjectIndex::fact_ref_matching`] cannot mint a reference for it. A file the + /// session has loaded into its VFS **does** have an id, though, and this uses it — a reference minted while the + /// pump has not caught up must name the same file the next reading will. Only a path with no VFS registration at + /// all (a test fixture, a caller with no VFS) gets an id from the view table + /// ([`ProjectIndex::view_paths`]), which keeps the path beside it so the row still answers "which file" and + /// "which declaration". The fact and its parameter list are stored in the synthetic arena — a view has no + /// `ParamsStore` to intern the list into. A file the index *has* read goes through + /// [`ProjectIndex::fact_ref_matching`] instead — this is the fallback that keeps a buffer's members from + /// disappearing before its summary exists. + pub fn intern_a_view_fact( + &self, + path: &Path, + fact: DeclFact, + parameters: Box<[ParameterFact]>, + ) -> FactRef { + let file = match self.file_id_of(path) { + Some(file) => file, + None => { + let mut paths = self + .view_paths + .lock() + .expect("the view fact table is not poisoned"); + FileId::new(paths.id_of(path)) + } + }; + self.intern_synthetic_fact(file, fact, parameters) + } + + /// **The declaration a [`ProjectDefinition`] answers with.** + pub fn definition_fact(&self, definition: &ProjectDefinition) -> Option<&DeclFact> { + self.fact(definition.fact) + } + + /// **The file a [`ProjectDefinition`] points into.** + pub fn definition_path(&self, definition: &ProjectDefinition) -> Option<&Path> { + self.path_of(definition.file) + } + + /// **Both halves at once** — the pair the older owned answer carried, for a consumer that needs the fact and the + /// path together (a fact's ranges are only meaningful in its own file's coordinates). + pub fn definition_parts(&self, definition: &ProjectDefinition) -> Option<(&DeclFact, &Path)> { + Some(( + self.definition_fact(definition)?, + self.definition_path(definition)?, + )) + } + + /// **The declaration a member row names.** The row stores a [`FactRef`]; this is the one resolver for it. + pub fn member_fact(&self, member: &ProjectMember) -> Option<&DeclFact> { + self.fact(member.fact) + } + + /// **The file a member row was declared in**, as the spelling the index files it under. + pub fn member_path(&self, member: &ProjectMember) -> Option<&Path> { + self.path_of(member.fact.file) + } + + /// **The declaration an offered name names.** The row stores a [`FactRef`]; this is its resolver. + pub fn offered_fact(&self, name: &OfferedName) -> Option<&DeclFact> { + self.fact(name.fact) + } + + /// **The file an offered name was written in**, as the spelling the index files it under — the path half of the + /// `(file, offset)` identity a completion item hands back to the client. + pub fn offered_path(&self, name: &OfferedName) -> Option<&Path> { + self.path_of(name.file) + } + + /// **An offered name's spelling**, or `""` for a row the index cannot resolve — a state a constructor that mints + /// through the index cannot produce. Borrowed rather than copied: ranking and hiding read it per row. + pub fn offered_name<'a>(&'a self, name: &OfferedName) -> &'a str { + self.offered_fact(name) + .map_or("", |fact| fact.name.as_str()) + } + + /// **An offered name's kind**, resolved through the index. + pub fn offered_kind(&self, name: &OfferedName) -> Option { + Some(self.offered_fact(name)?.kind) + } + + /// **A member's name**, or `""` for a row whose fact the index cannot resolve — which is a state a constructor + /// minted from the index cannot produce, so the empty answer is only ever a spelling with no name. + pub fn member_name<'a>(&'a self, member: &ProjectMember) -> &'a str { + self.member_fact(member) + .map_or("", |fact| fact.name.as_str()) + } + + /// **A member's kind**, resolved through the index. + pub fn member_kind(&self, member: &ProjectMember) -> Option { + Some(self.member_fact(member)?.kind) + } + + /// **A member's modifiers**, resolved through the index. + pub fn member_modifiers(&self, member: &ProjectMember) -> Option { + Some(self.member_fact(member)?.modifiers) + } + + /// **A member's written `type_of`, substituted with its instantiation** — the display/spelling edge. + /// + /// The stored fact is never rewritten; this applies [`MemberSubstitution`] to the spelling and answers a new + /// string. A consumer that needs the *unsubstituted* declaration asks [`ProjectIndex::member_fact`]. + pub fn member_type_spelling(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let written = self.type_spelling_of(fact)?.to_string(); + Some(self.substituted_spelling_of(member, fact, &written)) + } + + /// **A member's written return type, substituted with its instantiation** — see + /// [`ProjectIndex::member_type_spelling`]. + pub fn member_returns_spelling(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let written = self.returns_spelling_of(fact)?.to_string(); + Some(self.substituted_spelling_of(member, fact, &written)) + } + + /// **A member's parameter list, substituted with its instantiation** — `(int value)` for `push_back` on a + /// `std::vector`. + pub fn member_parameter_list(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let written = fact.parameter_list()?.to_string(); + Some(self.substituted_spelling_of(member, fact, &written)) + } + + /// **[`Self::member_type_spelling`] in the computation layer**: the fact's type — a stored handle materialized, + /// or a synthesized fact's own computed value — then this row's instantiation applied structurally. No spelling + /// is parsed. + pub fn member_computed_type(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let base = self.computed_type_of(fact)?; + Some(match &member.substitution { + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), + None => base, + }) + } + + /// **[`Self::member_returns_spelling`] in the computation layer** — the return type, stored or synthesized, with + /// this row's instantiation applied structurally. + pub fn member_computed_returns(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let base = self.computed_returns_of(fact)?; + Some(match &member.substitution { + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), + None => base, + }) + } + + /// **A member row's declaration as a display boundary wants it** — the arena fact with this row's instantiation + /// applied to the three spellings a card prints. + /// + /// This is the one place a *substituted copy* is allowed to exist: it is built by a display consumer for a single + /// answer and never stored in a row, a list or a cache — the row keeps its [`FactRef`] and its substitution, and + /// the stored declaration is never rewritten. A consumer that only prints a name or a kind should use the + /// `member_*` accessors instead. + /// + /// **The copy carries computed types, never spellings.** The substitution is applied structurally to the fact's + /// `ComputedType` (stored or synthesized), and the result is attached as this copy's [`DeclaredType::Computed`], + /// so a consumer printing it goes through the same display edge as any other fact. No handle is minted and no + /// spelling is parsed. + pub fn member_display_fact(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + if member.substitution.is_none() { + return Some(fact.clone()); + } + let mut shown = fact.clone(); + shown.type_of = self + .member_computed_type(member) + .map_or(DeclaredType::None, |computed| { + DeclaredType::Computed(Arc::new(computed)) + }); + shown.returns = self + .member_computed_returns(member) + .map_or(DeclaredType::None, |computed| { + DeclaredType::Computed(Arc::new(computed)) + }); + if let Some(parameters) = self.member_parameter_list(member) { + shown.detail_mut().parameter_list = Some(parameters.into()); + } + Some(shown) + } + + /// One spelling with a member row's substitution applied — the shared step of the three `member_*_spelling` + /// accessors. + fn substituted_spelling_of( + &self, + member: &ProjectMember, + fact: &DeclFact, + written: &str, + ) -> String { + match &member.substitution { + Some(substitution) => substitution.applied_to_spelling(written, fact), + None => written.to_string(), + } + } + + /// **The parameter facts of the declaration whose name starts at `offset`**, through whichever arena holds the + /// file's reading: its summary, the synthetic arena a view query interned into, or a cooked reading. This is what + /// a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. + /// + /// The summary is asked first because it is the file's own reading — a cooked declaration at the same offset is + /// the same declaration, and the summary's parameters are the answer either way. The synthetic arena is asked for + /// a file no summary covers (a buffer between an edit and the pump's read), and a cooked reading answers the + /// declarations only it holds (a name a macro produced, which the file's own reading never sees). + pub fn parameter_facts_at(&self, file: &Path, offset: usize) -> &[ParameterFact] { + let key = normalize(file); + if let Some(summary) = self.summaries.get(&key) + && let Some(fact) = summary + .declarations + .iter() + .find(|fact| fact.name_range.start_offset == offset) + { + return summary.parameter_facts(fact); + } + // **Either id the file may have been interned under** — the VFS's (or the fallback encoding of the summary + // sequence), and a view id a query minted before the file was registered. A buffer's chain can hold both: + // the completion between an edit and the pump's read interns into the view table, and the re-read registers + // the VFS id for the same path. Both name the same file, so both are asked. + let mut ids: Vec = Vec::new(); + if let Some(id) = self.file_id_of(file) { + ids.push(id); + } + if let Ok(viewed) = self.view_paths.lock() + && let Some(id) = viewed.get(file).map(FileId::new) + && !ids.contains(&id) + { + ids.push(id); + } + if !ids.is_empty() + && let Ok(arena) = self.synthetic_facts.lock() + && let Some(entry) = arena.iter().find(|entry| { + ids.contains(&entry.file) && entry.fact.name_range.start_offset == offset + }) + { + return entry.parameters; + } + if let Some(readings) = self.cooked.get(&key) { + for (_, reading) in readings.every() { + if let Some(fact) = reading + .declarations + .iter() + .find(|fact| fact.name_range.start_offset == offset) + && let Some(parameters) = reading.parameters.get(fact.parameters) + { + return parameters; + } + } + } + &[] + } + + /// **The canonical display spelling of a fact's type**, for a display consumer — an owned string produced at + /// this edge. + /// + /// [`ComputedType`]'s `Display` is the canonical form: a written alias (`short int`) prints as its primary + /// (`short`), and a C record's tag prints on the type that carries it. **Nothing is parsed here**, and no + /// spelling is stored on the fact; a computation consumer that needs the type itself asks + /// [`ProjectIndex::computed_type_of`] and gets the value. + pub fn type_spelling_of(&self, fact: &DeclFact) -> Option { + fact.type_of + .computed() + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + } + + /// The canonical return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. + pub fn returns_spelling_of(&self, fact: &DeclFact) -> Option { + fact.returns + .computed() + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + } + + /// **The computation-side type of a declaration's `type_of`.** The value is already on the fact: it is cloned, + /// never materialized from a table. + pub fn computed_type_of(&self, fact: &DeclFact) -> Option { + fact.type_of.as_computed() + } + + /// **The computation-side return type of a declaration**, by the same rule as + /// [`ProjectIndex::computed_type_of`]. + pub fn computed_returns_of(&self, fact: &DeclFact) -> Option { + fact.returns.as_computed() + } + + /// **One parameter's type as computation sees it.** The value is already on the parameter fact: it is cloned, + /// never materialized from a table, and **no spelling is parsed** — this is the resolver every consumer of a + /// [`ParameterFact`] asks instead of reading [`DeclFact::parameter_list`](crate::DeclFact::parameter_list). + pub fn parameter_type(&self, parameter: &ParameterFact) -> Option { + parameter.type_of.as_computed() + } + + /// **Every parameter of a fact's list, as computation sees it** — [`ProjectIndex::parameter_type`] for each. A + /// parameter whose type this reading could not lower (an unreadable one) is left out, which is the same answer the + /// spelling-level reader gave for a parameter whose type had no name. + pub fn parameter_types_of(&self, file: &Path, fact: &DeclFact) -> Vec { + self.parameter_facts_of(file, fact) + .iter() + .filter_map(|parameter| self.parameter_type(parameter)) + .collect() + } + + /// **The canonical spelling of one parameter's type**, for the display edge — a message quotes it, and + /// **nothing parses it**. Every computation consumer asks [`ProjectIndex::parameter_type`], whose + /// `ComputedType` carries the tag structurally. + pub fn parameter_spelling(&self, parameter: &ParameterFact) -> Option { + parameter + .type_of + .computed() + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + } + /// Add or replace one file's summary. /// /// The reverse edges are updated rather than rebuilt: an edit to one file changes only its own out-edges, @@ -639,7 +1389,7 @@ impl ProjectIndex { &self, path: &Path, expression: &CppSyntaxNode, - ) -> Option> { + ) -> Option> { let key = the_type_key(path, expression); let remembered = self .type_answers @@ -670,7 +1420,7 @@ impl ProjectIndex { &self, path: &Path, expression: &CppSyntaxNode, - answer: &Known<(Type, PathBuf)>, + answer: &Known<(ComputedType, PathBuf)>, ) { let key = the_type_key(path, expression); if let Ok(mut answers) = self.type_answers.lock() { @@ -822,6 +1572,8 @@ impl ProjectIndex { reading: CookedFile, ) { let path = normalize(path); + // **Its type handles are local to the reading until here.** Import the table into the index's one store and + // rewrite the facts' IDs, exactly as a summary's handles are bound on insertion. // **An empty reading never displaces one with declarations.** A render that declines — a provisional unit, a // program whose closure is not in hand — produces a `CookedFile` with nothing in it, and filing it under the @@ -1131,8 +1883,8 @@ impl ProjectIndex { .iter() .map(|(name, path)| name.len() + path.len() + 2 * size_of::()) .sum(); - // **The three memos that outlive a request.** `member_lists` is the big one — a list is hundreds of - // `ProjectMember`s, each carrying a `DeclFact` — and it is bounded at `MAX_CACHED_MEMBER_LISTS`. + // **The memos that outlive a request.** `member_lists` is the one worth counting: a list is hundreds of + // rows, and a row is a `FactRef` plus its substitution — the declarations themselves belong to the summaries. let (member_list_entries, member_lists, member_list_bytes) = self .member_lists .lock() @@ -1146,7 +1898,12 @@ impl ProjectIndex { .members .iter() .map(|member| { - size_of::() + DeclFact::heap_bytes(&member.fact) + size_of::() + + member.declared_in.len() + + member + .substitution + .as_ref() + .map_or(0, |held| held.heap_bytes()) }) .sum(); let unlisted = held.list.unlisted.len() * size_of::(); @@ -1207,6 +1964,8 @@ impl ProjectIndex { }) .unwrap_or_default(); // **The paths, twice**: `order` for iteration, `sequence` for identity. Both hold the file's own spelling. + // And the session's path↔id table, which holds one normalized key on each side of the pair — see + // [`ProjectIndex::register_file_id`]. let path_bytes: usize = self .order .values() @@ -1216,6 +1975,18 @@ impl ProjectIndex { .sequence .keys() .map(|path| path.len() + size_of::()) + .sum::() + + self + .file_ids + .by_path + .keys() + .map(|path| path.len() + size_of::() + size_of::()) + .sum::() + + self + .file_ids + .by_id + .values() + .map(|path| path.len() + size_of::() + size_of::()) .sum::(); TableCost { @@ -1615,8 +2386,8 @@ impl ProjectIndex { /// with — `["_Ty", "_Alloc"]` for `std::vector`. /// /// The half of substitution that is a *lookup*: the arguments are written at the use (`std::vector`, which - /// is the `Type` a caller has), and the names are written at the declaration, once. Pairing them is - /// [`crate::Type::substituted`], and this is where the names come from. + /// is the `ComputedType` a caller has), and the names are written at the declaration, once. Pairing them is + /// [`crate::ComputedType::substituted`], and this is where the names come from. /// /// # Why this reads a fact rather than a tree /// @@ -1722,8 +2493,18 @@ impl ProjectIndex { }) .map(|found| { ( - found.fact.parameters().to_vec(), - found.fact.parameter_defaults().to_vec(), + found + .fact + .parameters() + .iter() + .map(ToString::to_string) + .collect(), + found + .fact + .parameter_defaults() + .iter() + .map(ToString::to_string) + .collect(), ) }) } @@ -1741,7 +2522,12 @@ impl ProjectIndex { .iter() .map(|found| found.fact.parameters()) .find(|parameters| !parameters.is_empty()) - .map(<[String]>::to_vec) + .map(|parameters| { + parameters + .iter() + .map(ToString::to_string) + .collect::>() + }) .unwrap_or_default() } /// The files in which `name` is visible, in insertion order. @@ -2149,20 +2935,35 @@ impl ProjectIndex { None => (summary.declarations.as_slice(), 0), }; - let candidates: Box + '_> = match group { - None => Box::new(facts.iter()), + let candidates: Box + '_> = match group { + None => Box::new(facts.iter().enumerate()), Some(group) => Box::new( group .iter() .filter(|posting| posting.reading == reading) - .filter_map(|posting| facts.get(posting.index())), + .filter_map(|posting| { + facts + .get(posting.index()) + .map(|fact| (posting.index(), fact)) + }), ), }; - for fact in candidates.filter(|fact| contributes(fact)) { + // **The file's runtime id, from the one table that issues them** — the VFS id when the session has one, + // the fallback sequence encoding otherwise. Never the raw sequence number: a `FactRef` is resolved by + // [`ProjectIndex::path_of`], which expects the namespace this mints. + let Some(visible_file) = self.file_id_of(&summary.path) else { + continue; + }; + for (at, fact) in candidates.filter(|(_, fact)| contributes(fact)) { found.push(VisibleDeclaration { file: summary.path.clone(), fact, + reference: FactRef { + file: visible_file, + reading, + fact: DeclFactId::from_index(at), + }, visibility, }); } @@ -2970,9 +3771,11 @@ impl ProjectIndex { // Dropping the synonyms is not a guess about which declaration is meant: after the drop either exactly // one entity remains (the answer) or the name really does have several, and `Ambiguous` stays honest. Known::Yes(mut found) => { - found - .found - .retain(|declaration| declaration.fact.kind != DeclKind::Other); + found.found.retain(|declaration| { + !self + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Other) + }); // **Which *entity* the spelling names.** A class template asked without arguments is the fact with no // pattern; `vector` is a partial specialization with one. Mixing the two is what made a hover on // `std::vector` answer `Ambiguous` with four candidates listed: two forward declarations, the primary @@ -2982,7 +3785,10 @@ impl ProjectIndex { .found .iter() .enumerate() - .filter(|(_, declaration)| declaration.fact.pattern().is_none()) + .filter(|(_, declaration)| { + self.definition_fact(declaration) + .is_some_and(|fact| fact.pattern().is_none()) + }) .map(|(at, _)| at) .collect(); if plain.is_empty() { @@ -3000,7 +3806,10 @@ impl ProjectIndex { let definitions: Vec = group .iter() .copied() - .filter(|at| found.found[*at].fact.definition) + .filter(|at| { + self.definition_fact(&found.found[*at]) + .is_some_and(|fact| fact.definition) + }) .collect(); if definitions.len() == 1 { return Known::Yes(found.found.remove(definitions[0])); @@ -3051,7 +3860,7 @@ impl ProjectIndex { /// It does not substitute template arguments and it does not instantiate: `_Alloc_ptr_t` is /// `typename allocator_traits<_Alloc>::pointer`, and **finding the alias is not the same as finishing its /// type** — the answer here is the alias's own declaration, which is what a caller needs to say where the - /// name comes from. Substitution is [`crate::Type::substituted`], driven by a caller that has the arguments, + /// name comes from. Substitution is [`crate::ComputedType::substituted`], driven by a caller that has the arguments, /// and nothing drives it yet. Nor does it follow a **base class**: a name inherited from a base is written /// unqualified too, and finding it means walking the bases of every class on the chain. pub fn definition_where_written( @@ -3214,8 +4023,8 @@ impl ProjectIndex { found: certain .into_iter() .map(|found| ProjectDefinition { - file: found.file, - fact: found.fact, + file: found.reference.file, + fact: found.reference, }) .collect(), conditional, @@ -3277,7 +4086,10 @@ impl ProjectIndex { .is_some_and(|extension| extension == "c"); for declaration in found.found { - let Some(scope) = declaration.fact.scope.clone() else { + let Some(fact) = self.definition_fact(&declaration) else { + continue; + }; + let Some(scope) = fact.scope.clone() else { // File scope: exactly where a bare name looks. kept.push(declaration); continue; @@ -3292,7 +4104,7 @@ impl ProjectIndex { } }; - if !a_class || (c_file && declaration.fact.enumerator) { + if !a_class || (c_file && fact.enumerator) { kept.push(declaration); } } @@ -3650,7 +4462,7 @@ impl ProjectIndex { // rewrite. Measured: `std::views::filter` answered `NotDeclaredHere` while `std::ranges::views::filter` // was declared in `` all along. if alias.fact.kind == DeclKind::Namespace - && let Some(written_target) = alias.fact.type_of.as_deref() + && let Some(written_target) = self.type_spelling_of(alias.fact) { let qualified = if written_target.contains("::") { written_target.to_string() @@ -3668,7 +4480,7 @@ impl ProjectIndex { if alias.fact.kind != DeclKind::Type { return None; } - let target = parse_type_spelling(alias.fact.type_of.as_deref()?); + let target = self.computed_type_of(alias.fact)?; let class = target.class_name()?; let qualified = if class.contains("::") { diff --git a/crates/cpp_code_analysis/src/index/project/member_candidates.rs b/crates/cpp_code_analysis/src/index/project/member_candidates.rs index f71eb615..5ea3cb9c 100644 --- a/crates/cpp_code_analysis/src/index/project/member_candidates.rs +++ b/crates/cpp_code_analysis/src/index/project/member_candidates.rs @@ -33,6 +33,10 @@ use cpp_parser::CppSyntaxNode; /// **Every declaration of `member` in `class`**, in declaration order — the set a call's arguments choose from. /// +/// Each candidate carries its **resolved parameter types**: a declaration this file's scopes bind has them beside the +/// fact (the synthesizer lowers every parameter from its own node), and one the index files resolves them from the +/// arena that issued it. The ranking therefore never reads a parameter list's text. +/// /// The returned path is where the declaration's body is: the file the fact was read from, which is what a caller /// reading a member's body for a deduced return needs. pub(crate) fn member_candidates( @@ -44,7 +48,7 @@ pub(crate) fn member_candidates( class: &str, member: &str, arguments: Option<&[String]>, -) -> Vec<(DeclFact, PathBuf)> { +) -> Vec { // The same first step as `direct_member`: an alias has no members of its own. let class = &resolve_aliases(shapes, index, scopes, root, path, class); @@ -53,19 +57,24 @@ pub(crate) fn member_candidates( if let Some(scope) = scopes.scope_with_qualified_name(class) && let Some(scope_data) = scopes.scope(scope) { - let declared: Vec<(DeclFact, PathBuf)> = scope_data + let declared: Vec = scope_data .bindings .iter() .filter(|binding| binding.name.identifier_text() == Some(member)) .map(|binding| { - ( - fact_from_binding_with( - sema::declarations::shapes_from(shapes, root), - root, - class, - binding, - ), - path.to_path_buf(), + let synthesized = fact_from_binding_with( + sema::declarations::shapes_from(shapes, root), + root, + class, + binding, + ); + // **The parameter list the synthesizer returned beside the fact.** A view's fact names no store — + // its list was never interned — so it travels with the candidate, resolved structurally here. + CandidateDeclaration::with_parameters( + path, + synthesized.fact, + &synthesized.parameters, + index, ) }) .collect(); @@ -89,7 +98,7 @@ pub(crate) fn member_candidates( // `basic_json::operator[]` answered 0 while `members_of("basic_json")` listed 8 of them, because the alias step // handed it the unqualified spelling (see `operator_returns_of_with_arguments`). - let from_the_index: Vec<(DeclFact, PathBuf)> = all + let from_the_index: Vec = all .into_iter() .filter(|declaration| { declaration.fact.name == member @@ -99,7 +108,9 @@ pub(crate) fn member_candidates( written, ) }) - .map(|declaration| (declaration.fact.clone(), declaration.file.clone())) + .map(|declaration| { + CandidateDeclaration::resolved(index, declaration.file.as_path(), declaration.fact) + }) .collect(); if !from_the_index.is_empty() { return from_the_index; @@ -108,7 +119,11 @@ pub(crate) fn member_candidates( // Nothing is scoped to that class: a member defined out of line can be filed under `C::f`, which is what this // last lookup is for. match index.definition(&format!("{class}::{member}"), path) { - Known::Yes(found) => vec![(found.fact, found.file)], + Known::Yes(found) => index + .definition_parts(&found) + .map(|(fact, file)| CandidateDeclaration::resolved(index, file, fact)) + .into_iter() + .collect(), Known::Unknown(_) | Known::No => Vec::new(), } } diff --git a/crates/cpp_code_analysis/src/index/project/member_facts.rs b/crates/cpp_code_analysis/src/index/project/member_facts.rs index c8ed9487..3b622221 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -246,7 +246,7 @@ pub(crate) fn member_bindings( root: &CppSyntaxNode, path: &Path, class: &str, - arguments: &[Type], + arguments: &[ComputedType], ) -> TypeBindings { if arguments.is_empty() { return TypeBindings::default(); @@ -300,7 +300,7 @@ pub(crate) fn deduced_class_template_arguments( path: &Path, declaring: &mut dyn FnMut(&Path) -> Option, class: &str, - initializer: &Type, + initializer: &ComputedType, ) -> Option { let parameters = class_template_parameters( &sema::declarations::ShapeTable::new(), @@ -417,7 +417,7 @@ pub(crate) fn the_deduction_guide_deduces( class: &str, simple: &str, only: &str, - initializer: &Type, + initializer: &ComputedType, ) -> Option { let deduces_to = format!("{simple}<{only}>"); for declaration in root.descendants() { @@ -560,7 +560,7 @@ pub(crate) fn resolve_aliases_with_arguments( root: &CppSyntaxNode, path: &Path, class: &str, -) -> (String, Vec) { +) -> (String, Vec) { let (name, carried, _unresolved) = resolve_aliases_or_unresolved(shapes, index, scopes, root, path, class); (name, carried) @@ -583,9 +583,9 @@ pub(crate) fn resolve_aliases_or_unresolved( root: &CppSyntaxNode, path: &Path, class: &str, -) -> (String, Vec, Option) { +) -> (String, Vec, Option) { let mut current = class.to_string(); - let mut carried: Vec = Vec::new(); + let mut carried: Vec = Vec::new(); let mut seen: Vec = Vec::new(); for _ in 0..MAX_ALIAS_DEPTH { @@ -735,7 +735,8 @@ pub(crate) fn resolve_aliases_or_unresolved( let (prefix, name) = candidate.rsplit_once("::")?; let mut best: Option<(usize, String)> = None; for found in index.files_declaring(name, path) { - if found.fact.kind != DeclKind::Type || found.fact.type_of.is_some() { + if found.fact.kind != DeclKind::Type || index.type_spelling_of(found.fact).is_some() + { continue; } let Some(scope) = found.fact.scope.as_deref() else { @@ -891,7 +892,7 @@ pub(crate) fn alias_target_of( // **The alias's own parameters replaced by what the use wrote.** A bare alias has no parameters and this // changes nothing; a template alias is the case the split above exists for. let target = sema::types::substituted_spelling( - &target, + &target.to_string(), &sema::declarations::declared_template_parameters_with( sema::declarations::shapes_from(shapes, root), binding, @@ -915,22 +916,19 @@ pub(crate) fn alias_target_of( // that cannot be read, it is a name that has to be asked for in the plural. match index.definitions(class, path) { Known::Yes(found) => found.found.iter().find_map(|declaration| { - (declaration.fact.kind == DeclKind::Type) - .then(|| declaration.fact.type_of.clone()) + let fact = index.definition_fact(declaration)?; + (fact.kind == DeclKind::Type) + .then(|| index.type_spelling_of(fact)) .flatten() .map(|target| target.to_string()) .map(|target| { ( sema::types::substituted_spelling( &target, - declaration.fact.parameters(), + fact.parameters(), &written_arguments, ), - declaration - .fact - .scope - .clone() - .map(|scope| scope.to_string()), + fact.scope.clone().map(|scope| scope.to_string()), ) }) }), @@ -1021,10 +1019,13 @@ pub(crate) fn through_a_namespace_alias( let Some(found) = index.definition(&prefix, path).value() else { continue; }; - if found.fact.kind != DeclKind::Namespace { + let Some(found_fact) = index.definition_fact(&found) else { + continue; + }; + if found_fact.kind != DeclKind::Namespace { continue; } - let Some(target) = found.fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(found_fact) else { continue; }; if target == prefix { @@ -1033,7 +1034,7 @@ pub(crate) fn through_a_namespace_alias( let qualified = if target.contains("::") { target.to_string() } else { - match &found.fact.scope { + match &found_fact.scope { Some(scope) => format!("{scope}::{target}"), None => target.to_string(), } diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 55e450b5..6d5d1777 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -126,8 +126,8 @@ pub(crate) fn member_across_files_with( // **No template substitution here**, and the boundary is worth stating: this query answers "where is this // member declared", which is a *place* rather than a type. The pairing that finishes a member of a class // template is applied by the callers that ask for its type — see [`NamedDeclaration::type_of`] — and applying - // it here as well would have to rewrite the fact's own spelling, which is what - // `DeclFact::type_of` is documented to be *as the file wrote it*. + // it here as well would have to rewrite the fact's own declaration, while the store keeps the spelling the + // file wrote beside the handle. let found = member_fact( shapes, index, @@ -145,14 +145,23 @@ pub(crate) fn member_across_files_with( return Known::Unknown(reason); }; - Known::Yes(ProjectDefinition { file, fact }) + let Some(reference) = index.fact_ref_matching(&file, &fact) else { + return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(format!( + "{class}::{}", + access.member + )))); + }; + Known::Yes(ProjectDefinition { + file: reference.file, + fact: reference, + }) } /// **The class a member access is asked of** — the type's own class, or the class it points at. /// /// `p->size` and `(*p).size` are the same question, and a language server cannot ask the user to write the /// second one: a pointer's member access reaches through the pointer, and every consumer of this layer wants -/// the class on the other side. A **reference** is already seen through by [`Type::class_name`], because C++ +/// the class on the other side. A **reference** is already seen through by [`ComputedType::class_name`], because C++ /// does that for free; a **pointer** is not, because reaching a pointee is otherwise a `*` the caller writes. /// /// One level, which is the language's own rule: a `Widget**` needs two `*`s, and a query that kept descending @@ -186,21 +195,17 @@ pub(crate) fn the_braced_initialiser_of( .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::InitListExpr) } -/// **A member of the class the cursor is inside** — the second half of C++'s unqualified name lookup. -/// -/// Only a bare identifier is considered: `std::make` is qualified, and a qualified name is not looked up among a class's -/// members. The member list is the query that answers (`members_of` walks the bases and substitutes the class's -/// arguments), which is why a member inherited through a template base comes back with a finished type. -pub(crate) fn a_member_of_the_enclosing_class( +/// **A member row of the class the cursor is inside** — the second half of C++'s unqualified name lookup. The row +/// keeps the substituted fact (`Node *` for a base's `T *`), which a definition reference cannot: a +/// [`ProjectDefinition`] points at the declaration's own arena entry. +pub(crate) fn a_member_row_of_the_enclosing_class( index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, callee: &CppSyntaxNode, - // **What the caller does with it.** The card wants the declaration and can show a type the header wrote with the - // base's parameter in it; the type engine cannot use one, and a wrong type is worse than a refusal. a_finished_type_only: bool, -) -> Option { +) -> Option { let name = callee.text().to_string(); let name = name.trim(); let bare = !name.is_empty() @@ -218,42 +223,34 @@ pub(crate) fn a_member_of_the_enclosing_class( let member = listed .members .iter() - .find(|member| member.fact.name == name)?; + .find(|member| index.member_name(member) == name)?; // **A member of a base that is itself a template is not finished here.** `enable_shared_from_this`'s // `shared_from_this` is `_Tp`, and the member list does not carry the base's arguments — printing `_Tp (*)()` (which // is what a call of it answered) is worse than saying the type is not known. The refusal is the same one every other // unreadable spelling gets. + let parameters = index.member_fact(member)?.parameters(); let names_a_parameter = |written: &str| { written .split(|character: char| !character.is_alphanumeric() && character != '_') .any(|word| { - member - .fact - .parameters() + parameters .iter() .any(|parameter| !parameter.is_empty() && parameter == word) }) }; if a_finished_type_only - && (member - .fact - .returns - .as_deref() - .is_some_and(names_a_parameter) - || member - .fact - .type_of - .as_deref() - .is_some_and(names_a_parameter)) + && (index + .member_returns_spelling(member) + .is_some_and(|written| names_a_parameter(&written)) + || index + .member_type_spelling(member) + .is_some_and(|written| names_a_parameter(&written))) { return None; } // **No class argument pairing here**: `members_of` has already substituted the class's arguments through its - // members, so the fact's types are the ones a reader of this class sees. - Some(ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), - }) + // members, so the row's substitution is the one a reader of this class sees. + Some(member.clone()) } /// **The values of a braced list, flat** — `{1, 2.5}` and `std::pair{1, 2.5}` are the same values. @@ -291,7 +288,9 @@ pub(crate) fn a_type_the_expression_names( return Some(spelled.to_string()); } let names_a_type = match index.definition(spelled, path) { - Known::Yes(found) => found.fact.kind == DeclKind::Type, + Known::Yes(found) => index + .definition_fact(&found) + .is_some_and(|fact| fact.kind == DeclKind::Type), // **A name is a type when one of its declarations is one.** `std::string` is an alias (a `Type`) and also has a // constructor named `string`, so the name query answers `Ambiguous`; requiring *every* candidate to be a type // refused the head of `std::string{"three"}` and, with it, the whole `std::tuple{1, 2.5, std::string{"three"}}` @@ -301,10 +300,11 @@ pub(crate) fn a_type_the_expression_names( .definitions(spelled, path) .value() .is_some_and(|found| { - found - .found - .iter() - .any(|declaration| declaration.fact.kind == DeclKind::Type) + found.found.iter().any(|declaration| { + index + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Type) + }) }), // **An inline namespace is not part of the name a reader writes.** `std::string` is // `using string = basic_string;` inside `std::__cxx11`, so its qualified name is `std::__cxx11::string` and @@ -315,10 +315,11 @@ pub(crate) fn a_type_the_expression_names( let bare = spelled.rsplit("::").next().unwrap_or(spelled); bare != spelled && index.definitions(bare, path).value().is_some_and(|found| { - found - .found - .iter() - .any(|declaration| declaration.fact.kind == DeclKind::Type) + found.found.iter().any(|declaration| { + index + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Type) + }) }) } }; @@ -337,14 +338,17 @@ pub(crate) fn a_namespace_aliass_target( class: &str, ) -> Option { let found = index.definition(class, path).value()?; - if found.fact.kind != DeclKind::Namespace { + let found_fact = index.definition_fact(&found)?; + if found_fact.kind != DeclKind::Namespace { return None; } - let written = found.fact.type_of.clone()?.to_string(); + let written = index + .computed_type_of(found_fact) + .map(|computed| computed.to_string())?; if written.contains("::") || written.is_empty() { return Some(written); } - match &found.fact.scope { + match &found_fact.scope { Some(scope) => Some(format!("{scope}::{written}")), None => Some(written), } @@ -363,8 +367,8 @@ pub(crate) fn a_namespace_aliass_target( pub(crate) fn the_deduction_the_standard_fixes( name: &str, class_as_written: &str, - element_types: &[Type], -) -> Option> { + element_types: &[ComputedType], +) -> Option> { let plain = class_as_written .rsplit("::") .next() @@ -433,20 +437,17 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( elements: &[CppSyntaxNode], spelled: &str, depth: usize, -) -> Option { +) -> Option { // The written spelling must be a bare class name: a template-id has its arguments already. if spelled.contains('<') { return None; } let class = parse_type_spelling(spelled); - let Type::Named { name, arguments } = &class else { + let ComputedType::Named(name) = &class else { return None; }; - if !arguments.is_empty() { - return None; - } - let element_types: Vec = elements + let element_types: Vec = elements .iter() .filter_map(|element| { match type_of_expression_memoed( @@ -485,15 +486,18 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( .definitions(name, path) .value() .and_then(|found| { - found - .found - .into_iter() - .find(|declaration| !declaration.fact.parameters().is_empty()) + found.found.into_iter().find(|declaration| { + index + .definition_fact(declaration) + .is_some_and(|fact| !fact.parameters().is_empty()) + }) }) .or_else(|| index.definition(name, path).value()); let class_as_written = match &declared { - Some(declaration) => declaration.fact.qualified_name(), - None => name.clone(), + Some(declaration) => index + .definition_fact(declaration) + .map_or_else(|| name.to_string(), |fact| fact.qualified_name()), + None => name.to_string(), }; // **The standard's own guides, before the walk that reads a class's members.** The library's constructors are @@ -509,10 +513,7 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( // started: a table that exists so that a walk is unnecessary cannot be read after it. if let Some(deduced) = the_deduction_the_standard_fixes(name, &class_as_written, &element_types) { - return Some(Type::Named { - name: class_as_written, - arguments: deduced, - }); + return Some(ComputedType::named(class_as_written, deduced)); } let constructor_name = class_as_written .rsplit("::") @@ -523,36 +524,42 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( return None; }; let parameters = match declared { - Some(declaration) if !declaration.fact.parameters().is_empty() => { - declaration.fact.parameters().to_vec() + Some(declaration) + if index + .definition_fact(&declaration) + .is_some_and(|fact| !fact.parameters().is_empty()) => + { + index + .definition_fact(&declaration) + .map(|fact| fact.parameters().to_vec()) + .unwrap_or_default() } - _ => listed - .members - .iter() - .find(|member| !member.fact.parameters().is_empty()) - .map(|member| member.fact.parameters().to_vec())?, + _ => listed.members.iter().find_map(|member| { + let parameters = index.member_fact(member)?.parameters(); + (!parameters.is_empty()).then(|| parameters.to_vec()) + })?, }; if parameters.is_empty() { return None; } - let mut agreed: Option> = None; + let mut agreed: Option> = None; for constructor in listed .members .iter() - .filter(|member| member.fact.kind == DeclKind::Function) - .filter(|member| member.fact.name == constructor_name) + .filter(|member| index.member_kind(member) == Some(DeclKind::Function)) + .filter(|member| index.member_name(member) == constructor_name) { let deduced = deduce_the_parameters( ¶meters, - constructor.fact.parameter_list(), + index.member_parameter_list(constructor).as_deref(), &element_types, ); // Every parameter must have been replaced: one left standing is not a deduction. let every = deduced.iter().all(|argument| { - !matches!(argument, Type::Named { name, .. } - if parameters.iter().any(|parameter| parameter == name)) + !matches!(argument, ComputedType::Named(found) + if parameters.iter().any(|parameter| parameter == found)) }); if !every { continue; @@ -564,10 +571,7 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( } } - agreed.map(|arguments| Type::Named { - name: name.clone(), - arguments, - }) + agreed.map(|arguments| ComputedType::named(name.clone(), arguments)) } /// **What a pointer-like class's arrow reaches** — its `element_type`, with the class's parameters substituted. @@ -585,8 +589,8 @@ pub(crate) fn the_pointee_of_a_handle( root: &CppSyntaxNode, path: &Path, class: &str, - arguments: &[Type], -) -> Option<(String, Vec)> { + arguments: &[ComputedType], +) -> Option<(String, Vec)> { let written: Vec = arguments .iter() .map(|argument| argument.to_string()) @@ -603,9 +607,11 @@ pub(crate) fn the_pointee_of_a_handle( ) else { return None; }; - let written_type = fact.type_of.as_deref()?; + // **The fact's type is materialized, not parsed.** A fact from the index carries its handle (or a synthesized + // value); there is no spelling in between. + let written_type = index.computed_type_of(&fact)?; let bindings = member_bindings(index, scopes, root, path, class, arguments); - let finished = bindings.applied_to(&parse_type_spelling(written_type)); + let finished = bindings.applied_to(&written_type); // **A nested spelling is followed**, which is the ordinary shape in the standard library: `shared_ptr` inherits // `__shared_ptr<_Tp>` and `element_type` is written there as `_Tp`, so the fact found through the base walk says // `__shared_ptr<_Tp>::element_type`. Substituted, that is `__shared_ptr::element_type` — a member of the class @@ -628,18 +634,25 @@ pub(crate) fn the_pointee_of_a_handle( // `test_cpp`'s `smart_pointers.cpp`, the hover asked for members of that invented name and said // "`shared_ptr` has no member `identifier`". match finished.0 { - Type::Named { name, arguments } => { + ComputedType::Named(name) => { let declared = index.files_declaring(base_type_name(&name), path); declared .iter() .any(|declaration| declaration.fact.kind == DeclKind::Type) - .then_some((name, arguments)) + .then_some((name.to_string(), Vec::new())) + } + ComputedType::Generic(generic) => { + let declared = index.files_declaring(base_type_name(&generic.name), path); + declared + .iter() + .any(|declaration| declaration.fact.kind == DeclKind::Type) + .then_some((generic.name.to_string(), generic.arguments.to_vec())) } _ => None, } } -pub(crate) fn member_access_class(written: &Type) -> Option { +pub(crate) fn member_access_class(written: &ComputedType) -> Option { if let Some(class) = written.class_name() { return Some(class.to_string()); } @@ -661,10 +674,10 @@ pub(crate) fn member_access_class(written: &Type) -> Option { /// /// The recursion is the whole rule: a reference and a qualifier are transparent (C++ says so — a member of a /// `const Widget&` is a member of `Widget`), and anything else is its own spelling. -pub(crate) fn the_class_spelling(type_of: &Type) -> String { +pub(crate) fn the_class_spelling(type_of: &ComputedType) -> String { match type_of { - Type::Reference { to, .. } => the_class_spelling(to), - Type::Qualified { of, .. } => the_class_spelling(of), + ComputedType::Reference { to, .. } => the_class_spelling(to), + ComputedType::Qualified(qualified) => the_class_spelling(&qualified.of), other => other.to_string(), } } @@ -687,8 +700,8 @@ pub(crate) fn member_access_class_and_arguments( root: &CppSyntaxNode, path: &Path, class: &str, - written: &Type, -) -> (String, Vec) { + written: &ComputedType, +) -> (String, Vec) { let (class, from_the_alias) = resolve_aliases_with_arguments(shapes, index, scopes, root, path, class); @@ -731,24 +744,27 @@ pub(crate) fn offerable_members( offset: usize, members: &mut MemberList, ) -> usize { - members - .members - .retain(|member| !is_reserved_to_the_implementation(&member.fact)); + members.members.retain(|member| { + index + .member_fact(member) + .is_none_or(|fact| !is_reserved_to_the_implementation(fact)) + }); let open_to_the_cursor = classes_the_cursor_is_in(index, scopes, root, path, offset); let before = members.members.len(); members.members.retain(|member| { - let Some(access) = member.fact.access else { + let Some(fact) = index.member_fact(member) else { + return false; + }; + let Some(access) = fact.access else { return true; }; if access.is_open_to_everyone() { return true; } - member - .fact - .scope + fact.scope .as_deref() .is_some_and(|owner| open_to_the_cursor.iter().any(|seen| seen == owner)) }); @@ -897,7 +913,7 @@ pub fn own_members_of( root: &CppSyntaxNode, path: &Path, class: &str, -) -> Known> { +) -> Known> { own_members_of_with( &sema::declarations::ShapeTable::new(), index, @@ -916,7 +932,7 @@ pub fn own_members_of_with( root: &CppSyntaxNode, path: &Path, class: &str, -) -> Known> { +) -> Known> { direct_members(shapes, index, scopes, root, path, class) } @@ -942,6 +958,26 @@ pub fn members_of( ) } +/// **The computation-layer entry**: the class is already a `ComputedType`, so its name and arguments are +/// taken from the structure rather than from a spelling that would have to be split again. +pub fn members_of_computed( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + class: &ComputedType, +) -> Known { + let listed = members_of_inner( + &sema::declarations::ShapeTable::new(), + index, + scopes, + root, + path, + &class.to_string(), + ); + substituted_members_for(index, path, class, listed) +} + /// [`members_of`], with the file's declaration table threaded in — see [`crate::sema::declarations::ShapeTable`]. /// /// The table is the one thing this query needs from the tree and cannot get from the index, and a caller that @@ -1074,8 +1110,11 @@ impl ProjectIndex { let mut contributors: Vec = Vec::new(); for member in &list.members { - if !contributors.contains(&member.file) { - contributors.push(member.file.clone()); + let Some(file) = self.path_of(member.fact.file) else { + continue; + }; + if !contributors.iter().any(|held| held == file) { + contributors.push(file.to_path_buf()); } } // **A list made of not-yet-cooked facts is cached like any other**, and the invalidation rule is what makes @@ -1353,25 +1392,25 @@ pub(crate) fn members_of_inner( // *hide*, and a base is only reached after them. let mut own: Vec = own .into_iter() - .map(|(file, fact)| ProjectMember { - file, + .map(|fact| ProjectMember { fact, + substitution: None, declared_in: class.to_string(), depth: 0, ambiguous: false, }) .collect(); - own.sort_by(|one, other| one.fact.name.cmp(&other.fact.name)); - mark_ambiguity(&mut own); - hidden.extend(recorded_names(&own)); + own.sort_by(|one, other| index.member_name(one).cmp(index.member_name(other))); + mark_ambiguity(index, &mut own); + hidden.extend(recorded_names(index, &own)); list.members.extend(own); // **The names a using-declaration writes**, which are not names that hide — see the `retain` in the base walk. let re_exposed: HashSet = list .members .iter() - .filter(|member| member.fact.kind == DeclKind::Other) - .map(|member| member.fact.name.to_string()) + .filter(|member| index.member_kind(member) == Some(DeclKind::Other)) + .map(|member| index.member_name(member).to_string()) .collect(); // Then outward, one level of bases at a time — which is the order C++ hides in: a base's member is hidden by @@ -1482,7 +1521,8 @@ pub(crate) fn members_of_inner( .files_declaring(&head, path) .into_iter() .any(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.type_of.is_some() + declared.fact.kind == DeclKind::Type + && index.type_spelling_of(declared.fact).is_some() }); if head_is_an_alias { let candidates = the_classes_a_base_clause_names(index, path, &written); @@ -1531,9 +1571,9 @@ pub(crate) fn members_of_inner( let listed = MemberList { members: members .into_iter() - .map(|(file, fact)| ProjectMember { - file, + .map(|fact| ProjectMember { fact, + substitution: None, declared_in: shown.clone(), depth, ambiguous: false, @@ -1586,12 +1626,12 @@ pub(crate) fn members_of_inner( // that compiles. The name a using-declaration writes is therefore **not** a name that hides: what it brings // in is exactly the base's declarations, and they are the ones the list is missing. found.retain(|member| { - !hidden.contains(member.fact.name.as_str()) - || re_exposed.contains(member.fact.name.as_str()) + !hidden.contains(index.member_name(member)) + || re_exposed.contains(index.member_name(member)) }); - found.sort_by(|one, other| one.fact.name.cmp(&other.fact.name)); - mark_ambiguity(&mut found); - hidden.extend(recorded_names(&found)); + found.sort_by(|one, other| index.member_name(one).cmp(index.member_name(other))); + mark_ambiguity(index, &mut found); + hidden.extend(recorded_names(index, &found)); list.members.extend(found); level = next; @@ -1665,7 +1705,14 @@ pub(crate) fn the_base_clauses_of( .position(|declared| is_a_type(declared) && declared.fact.definition) .or_else(|| candidates.iter().position(is_a_type)); if let Some(at) = chosen { - return Known::Yes(candidates[at].fact.bases().to_vec()); + return Known::Yes( + candidates[at] + .fact + .bases() + .iter() + .map(ToString::to_string) + .collect(), + ); } bases_of(index, scopes, root, path, class) } @@ -1729,19 +1776,24 @@ fn the_file_of_a_class_body(index: &ProjectIndex, path: &Path, class: &str) -> O let mut types: Vec<&ProjectDefinition> = decl .found .iter() - .filter(|one| one.fact.kind == DeclKind::Type) + .filter(|one| { + index + .definition_fact(one) + .is_some_and(|fact| fact.kind == DeclKind::Type) + }) .collect(); if types.is_empty() { return None; } // A definition beats a declaration, and the general template beats a specialization. types.sort_by_key(|one| { + let fact = index.definition_fact(one); ( - !one.fact.definition, - std::cmp::Reverse(one.fact.parameters().len()), + !fact.is_some_and(|fact| fact.definition), + std::cmp::Reverse(fact.map_or(0, |fact| fact.parameters().len())), ) }); - Some(normalize(&types[0].file)) + index.definition_path(types[0]).map(normalize) } /// [`direct_members`]' answer, **restricted to the class body the spelling names** — see [`the_file_of_a_class_body`]. @@ -1868,8 +1920,8 @@ pub(crate) fn the_classes_a_base_clause_names( let scope = index .definition(bare, path) .value() - .map(|found| found.fact.qualified_name()) - .unwrap_or_else(|| head.clone()); + .and_then(|found| index.definition_fact(&found)) + .map_or_else(|| head.clone(), |fact| fact.qualified_name()); let Some(fact) = index .declarations_in(&scope, path) .into_iter() @@ -1877,7 +1929,7 @@ pub(crate) fn the_classes_a_base_clause_names( else { return Vec::new(); }; - let Some(target) = fact.fact.type_of.clone() else { + let Some(target) = index.type_spelling_of(fact.fact) else { return Vec::new(); }; let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); @@ -1894,9 +1946,9 @@ pub(crate) fn the_classes_a_base_clause_names( }; let declared = index.files_declaring(&head, path); if let Some(alias) = declared.iter().find(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.type_of.is_some() + declared.fact.kind == DeclKind::Type && index.type_spelling_of(declared.fact).is_some() }) { - let Some(target) = alias.fact.type_of.clone() else { + let Some(target) = index.type_spelling_of(alias.fact) else { return Vec::new(); }; let substituted = @@ -1988,7 +2040,7 @@ pub(crate) fn direct_members( root: &CppSyntaxNode, path: &Path, class: &str, -) -> Known> { +) -> Known> { // Followed here as well as in `direct_member`, for the same reason it is there: the members of `std::string` // are the members of `std::basic_string`, and the member-list query and the single-member query must not // disagree about which class a spelling names. @@ -2020,10 +2072,21 @@ pub(crate) fn direct_members( data.bindings .iter() .map(|binding| { - ( - path.to_path_buf(), - fact_from_binding_with(shapes, root, class, binding), - ) + // **The arena entry, never a guessed id.** A binding is a place in the scope tree, and the fact + // it describes belongs to the file's reading — the index is the only thing that can say which + // arena entry that is. The synthesized parameters travel only when the fact has no arena (the + // buffer the index has not read yet); see [`ProjectIndex::intern_a_view_fact`]. + let synthesized = fact_from_binding_with(shapes, root, class, binding); + match index.fact_ref_matching(path, &synthesized.fact) { + Some(reference) => reference, + // **The buffer the index has not read yet.** A member row has to name an arena entry, and a + // file between an edit and the pump's read has no summary; the index mints a view id and + // interns the fact rather than dropping the member. See + // [`ProjectIndex::intern_a_view_fact`]. + None => { + index.intern_a_view_fact(path, synthesized.fact, synthesized.parameters) + } + } }) .collect(), ); @@ -2054,10 +2117,13 @@ pub(crate) fn direct_members( data.bindings .iter() .map(|binding| { - ( - path.to_path_buf(), - fact_from_binding_with(shapes, root, &qualified, binding), - ) + let synthesized = fact_from_binding_with(shapes, root, &qualified, binding); + match index.fact_ref_matching(path, &synthesized.fact) { + Some(reference) => reference, + None => { + index.intern_a_view_fact(path, synthesized.fact, synthesized.parameters) + } + } }) .collect(), ); @@ -2086,7 +2152,7 @@ pub(crate) fn direct_members( return Known::Yes( found .into_iter() - .map(|declaration| (declaration.file.clone(), declaration.fact.clone())) + .map(|declaration| declaration.reference) .collect(), ); } @@ -2115,18 +2181,20 @@ pub(crate) fn direct_members( // `NotDeclaredHere`, which is why a retry that skipped this step changed nothing at all. The arguments are what // [`super::member_bindings`] pairs with the class's parameters *after* the class is found; they are not part of // its name. - if let Known::Yes(resolved) = index.definition(without_arguments(class), path) { - let qualified = resolved.fact.qualified_name(); - if qualified != *class { - let found = index.declarations_in(&qualified, path); - if !found.is_empty() { - return Known::Yes( - found - .into_iter() - .map(|declaration| (declaration.file.clone(), declaration.fact.clone())) - .collect(), - ); - } + if let Known::Yes(resolved) = index.definition(without_arguments(class), path) + && let Some(qualified) = index + .definition_fact(&resolved) + .map(|fact| fact.qualified_name()) + && qualified != *class + { + let found = index.declarations_in(&qualified, path); + if !found.is_empty() { + return Known::Yes( + found + .into_iter() + .map(|declaration| declaration.reference) + .collect(), + ); } } @@ -2142,7 +2210,13 @@ pub(crate) fn direct_members( // the truthful answer is "that class, and it has nothing written directly in it": the members are one // level out, which is what the base walk above is for. match index.definition(class, path) { - Known::Yes(found) if found.fact.qualified_name() == *class => Known::Yes(Vec::new()), + Known::Yes(found) + if index + .definition_fact(&found) + .is_some_and(|fact| fact.qualified_name() == *class) => + { + Known::Yes(Vec::new()) + } // **One class written twice is not two classes.** A class template that is forward-declared and then // defined is two declarations and one entity — `std::shared_ptr` is declared in `bits/shared_ptr.h` and // defined in `shared_ptr.h` — and the letter of "ambiguous" answered *"that class has nothing written in @@ -2159,8 +2233,10 @@ pub(crate) fn direct_members( let names: BTreeSet = found .found .iter() - .filter(|declaration| declaration.fact.kind == DeclKind::Type) - .map(|declaration| declaration.fact.qualified_name()) + .filter_map(|declaration| { + let fact = index.definition_fact(declaration)?; + (fact.kind == DeclKind::Type).then(|| fact.qualified_name()) + }) .collect(); if let [qualified] = names.iter().collect::>().as_slice() { let found = index.declarations_in(qualified, path); @@ -2168,9 +2244,7 @@ pub(crate) fn direct_members( return Known::Yes( found .into_iter() - .map(|declaration| { - (declaration.file.clone(), declaration.fact.clone()) - }) + .map(|declaration| declaration.reference) .collect(), ); } @@ -2223,10 +2297,13 @@ pub(crate) fn a_class_nested_in_another(scopes: &ScopeTree, class: &str) -> Opti /// /// What is still left out is a member with **no** name at all, which a fact now has only where the source has no /// spelling to read. -pub(crate) fn recorded_names(members: &[ProjectMember]) -> impl Iterator + '_ { +pub(crate) fn recorded_names<'a>( + index: &'a ProjectIndex, + members: &'a [ProjectMember], +) -> impl Iterator + 'a { members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| index.member_name(member).to_string()) .filter(|name| !name.is_empty()) } @@ -2243,20 +2320,24 @@ pub(crate) fn recorded_names(members: &[ProjectMember]) -> impl Iterator> = HashMap::new(); - for member in members.iter().filter(|member| !member.fact.name.is_empty()) { + for member in members + .iter() + .filter(|member| !index.member_name(member).is_empty()) + { declaring - .entry(member.fact.name.to_string()) + .entry(index.member_name(member).to_string()) .or_default() .insert(member.declared_in.clone()); } for member in members.iter_mut() { - member.ambiguous = !member.fact.name.is_empty() + let name = index.member_name(member).to_string(); + member.ambiguous = !name.is_empty() && declaring - .get(member.fact.name.as_str()) + .get(&name) .is_some_and(|classes| classes.len() > 1); } } diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 561a0202..3befe6b5 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -33,7 +33,9 @@ //! rest of the crate follows, and the reason [`IncludeFact`](crate::summary::IncludeFact) carries a guard at all. use crate::CookedDiagnostic; +use crate::FileId; use crate::IndexedRendering; +use crate::index; use cpp_parser::SourceRange; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; @@ -45,9 +47,10 @@ use super::names::{NameIndex, Posting}; use crate::Visibility; use crate::file::paths::normalize_path; use crate::include::graph::Marked; +use crate::index::types::ComputedType; use crate::preprocess::directive::IncludeForm; -use crate::sema::types::{Type, TypeBindings, parse_type_spelling}; -use crate::summary::{DeclFact, DeclKind, FactGuard, FileSummary, MacroFact}; +use crate::sema::types::{TypeBindings, parse_type_spelling}; +use crate::summary::{DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, MacroFact}; use crate::symbol::{Known, UnknownReason}; #[cfg(test)] @@ -108,6 +111,16 @@ pub const DEFAULT_COOKED_BUDGET_BYTES: usize = 256 * 1024 * 1024; pub struct CookedFile { /// The declarations the rendering read as, every range mapped back into the file. pub declarations: Vec, + /// **The reading's local parameter table**, indexed by [`DeclFact::parameters`] — the same contract a + /// [`crate::FileSummary`]'s table has, and for the same reason: a rendering is parsed into *its own* summary, so + /// its facts name `ParamsId`s in that summary's store, and that store has to travel with the declarations or the + /// handles would be resolved against an unrelated table. [`crate::ProjectIndex::insert_cooked`] imports this + /// table once. (Types need no matching table: each fact carries its immutable `ComputedType`.) + /// + /// This is not a second global store: a fact of a cooked reading is resolved by the reading that filed it (see + /// [`crate::ProjectIndex::parameter_facts_of`]), and a reading built by hand may leave the table empty — its + /// facts then resolve through the file's summary entry for the same declaration. + pub parameters: index::params::ParamsStore, /// **The macros the rendering was read with** — and this is the half that answers a question the file's own /// reading cannot. /// @@ -141,6 +154,7 @@ impl CookedFile { pub fn declarations(declarations: Vec) -> Self { CookedFile { declarations, + parameters: index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: Vec::new(), unplaced: 0, @@ -155,14 +169,15 @@ impl CookedFile { .iter() .map(DeclFact::heap_bytes) .sum::() + + self.parameters.accounting() + self.macros.iter().map(MacroFact::heap_bytes).sum::() + self.diagnostics.len() * size_of::() } } impl From for CookedFile { - /// What the index keeps of a rendering's reading: the declarations, **the macros it was read with**, the errors - /// this file can show, and the count of the ones it cannot. + /// What the index keeps of a rendering's reading: the declarations, **the type values they carry**, the + /// macros it was read with, the errors this file can show, and the count of the ones it cannot. /// /// The summary itself is still not kept, and the reason stands: a rendering's **directives and includes** are /// empty, because that text was spelled out by this crate rather than by the file, and keeping them would invite @@ -171,6 +186,7 @@ impl From for CookedFile { fn from(indexed: IndexedRendering) -> Self { CookedFile { declarations: indexed.summary.declarations, + parameters: indexed.summary.parameters, macros: indexed.summary.macros, diagnostics: indexed.diagnostics, unplaced: indexed.unplaced, @@ -262,12 +278,116 @@ impl Readings { } } +/// **The high bit of a runtime [`crate::FileId`] the index minted itself** — see [`ProjectIndex::file_id_of`]. +/// +/// A `FileId` has three possible origins, and the top bits are what keeps their ranges apart without changing the +/// id's type: +/// +/// ```text +/// 0x0000_0000 ..= 0x7FFF_FFFF the session VFS's own ids, registered through `register_file_id` +/// 0x8000_0000 ..= 0xFFFF_FFFD a fallback id: the index's insertion sequence, high bit set +/// 0xFFFF_FFFE and downward a view id (see `ViewFactPaths`) +/// ``` +/// +/// The split is what lets [`ProjectIndex::path_of`] decode an id without a tag: the VFS table is asked first, the +/// view table second, and only a number left over after those two can be a fallback sequence. It is also why +/// [`ProjectIndex::register_file_id`] refuses an id in the fallback half — a VFS that had read `2^31` distinct files +/// would otherwise hand out an id the index would have to read as its own numbering. That many files cannot be held +/// by the VFS (one `Option` per id, and an id is never reused), and a view would have to go through two +/// billion files before its downward allocation met the fallback range, so the ranges are disjoint at every size a +/// session can reach. +const FALLBACK_FILE_ID_BIT: u32 = 0x8000_0000; + +/// The largest insertion sequence a fallback id may encode — see [`FALLBACK_FILE_ID_BIT`]. +/// +/// The cap is what keeps a fallback id out of the top two numbers, which the view table allocates from. A project +/// would need two thousand million files before a sequence reached it. +const FALLBACK_SEQUENCE_LIMIT: u32 = FALLBACK_FILE_ID_BIT - 3; + +/// Encode an insertion sequence as a fallback runtime [`crate::FileId`] — see [`FALLBACK_FILE_ID_BIT`]. +fn fallback_file_id(sequence: u32) -> Option { + (sequence <= FALLBACK_SEQUENCE_LIMIT).then(|| FileId::new(FALLBACK_FILE_ID_BIT | sequence)) +} + +/// The insertion sequence a fallback [`crate::FileId`] encodes. +/// +/// `None` for an id in the VFS or view half. The caller still asks those tables first — this only says whether the +/// number *may* be a fallback id, not that it is one. +fn fallback_sequence(file: FileId) -> Option { + let number = file.index() as u32; + (number & FALLBACK_FILE_ID_BIT != 0).then_some(number & !FALLBACK_FILE_ID_BIT) +} + +/// **The session VFS's path↔id table, as the index keeps it** — see [`ProjectIndex::register_file_id`]. +/// +/// Two maps because both directions are asked on the way through a query: `by_path` when a fact is filed under a +/// path and `by_id` when a [`FactRef`] names a file. The key is the index's normalized spelling; the answer to +/// `path_of` prefers the summary's filed spelling when the file has one, and falls back to the normalized key for a +/// file the VFS has loaded but the index has not read (or has forgotten). +/// +/// **Registration is first-wins per side, and a conflict leaves both maps untouched.** A VFS that renumbers a path +/// — which it does not — or hands one id to two paths would otherwise make `path_of` answer a file whose facts +/// belong to another, and there is no repair for that after the fact; refusing the registration keeps every answer +/// the table already gave true. +#[derive(Debug, Default)] +struct FileIdTable { + by_path: HashMap, + by_id: HashMap, +} + +impl FileIdTable { + /// The VFS id of a path, if the session registered one. + fn id_of(&self, path: &Path) -> Option { + self.by_path.get(&normalize(path)).copied() + } + + /// The normalized key an id was registered under, if any. + fn key_of(&self, id: FileId) -> Option<&str> { + self.by_id.get(&id).map(String::as_str) + } + + /// Record one `path → id` pair, answering whether the table now holds it. + /// + /// Refused, with both maps unchanged, when: + /// + /// * the id is in the index's own fallback half ([`FALLBACK_FILE_ID_BIT`]) — the two namespaces would stop being + /// separable in [`ProjectIndex::path_of`]; + /// * the path is already registered to a **different** id — the first registration is the answer a fact filed + /// under that path already names; + /// * the id is already registered to a **different** path — the fact arena behind that id belongs to that path. + /// + /// Registering the same pair again is a no-op that answers `true`, so the session may register on every entry to + /// a file without checking first. + fn register(&mut self, path: &Path, id: FileId) -> bool { + if fallback_sequence(id).is_some() { + return false; + } + let key = normalize(path); + match (self.by_path.get(&key), self.by_id.get(&id)) { + (Some(&known), _) => known == id, + (None, Some(known)) => known == &key, + (None, None) => { + self.by_path.insert(key.clone(), id); + self.by_id.insert(id, key); + true + } + } + } +} + /// A project's summaries, and the queries that need more than one of them. /// /// Built incrementally: [`ProjectIndex::insert`] takes a summary that some other layer produced, which is what /// keeps this type free of any opinion about parsing, caching or the filesystem. #[derive(Debug, Default)] pub struct ProjectIndex { + /// **The session VFS's path↔id table** — registered by whoever holds the VFS, never minted here. + /// + /// This is the only path→[`crate::FileId`] map outside the VFS itself: a runtime reference to a file names the + /// VFS's own id, and this table is how a query that has only a path (or only an id) gets to the other side. A + /// file with no registration — a hand-built index, a test, a caller with no VFS — still gets an id from the + /// insertion sequence, in the high-bit namespace [`ProjectIndex::file_id_of`] documents. + file_ids: FileIdTable, /// The summaries, by normalized path. summaries: HashMap, /// The paths **by sequence number**, which is insertion order: a query over all of them is deterministic rather @@ -343,6 +463,8 @@ pub struct ProjectIndex { /// still does for a caller that builds an index by hand. See [`crate::index::environment`] for what the field /// is complete about and what it deliberately is not. macros: Marked, + /// The interned parameter lists of every declaration this index has inserted. + parameters: index::params::ParamsStore, /// **What the cooked reading found**, by normalized path — the declarations a compiler sees, and the errors the /// parse of the rendering reported. /// @@ -466,7 +588,7 @@ pub struct ProjectIndex { /// above have — **every insert and every forget clears it** — so a hit is always an answer about the index as it /// stands. Bounded, and cleared when it reaches the bound: an answer is cheap to recompute and a map that grows with /// a session is not. - type_answers: std::sync::Mutex>>, + type_answers: std::sync::Mutex>>, /// How many questions the memo answered and how many it had to compute — what says whether it is earning its map. type_hits: std::sync::atomic::AtomicU64, type_misses: std::sync::atomic::AtomicU64, @@ -554,6 +676,78 @@ pub struct ProjectIndex { /// entry per contributor, and a closure here is over a thousand files, so hashing their includes and macro facts /// on every query would cost more than the walk it is validating. walk_inputs: HashMap, + /// **Facts a query synthesized and the index interned for it** — the arena [`FactRef::SYNTHETIC_READING`] names. + /// + /// A [`FactRef`] has to name an arena entry, and a row a query *made up* — Unreal's generated `Super`/`ThisClass` + /// members are one case, a buffer's members before the pump has read it the other — has no file reading behind + /// it. Interning it here is what keeps the rule "constructors mint references through the index, never guess ids" + /// true for those rows too. Append-only; tiny in practice, because equal facts for one file share an entry. + /// + /// # Why each entry carries a parameter list + /// + /// A fact's `parameters` is a `ParamsId` in the [`crate::index::params::ParamsStore`] that issued it, and a + /// synthesized fact has no such table: a view has no summary, and a generated member belongs to a class whose + /// table is the summary's. So the list travels **beside the fact**, in this arena, and + /// [`ProjectIndex::parameter_facts_of`] resolves it by the fact's identity. This is deliberately not a second + /// `ParamsStore`: there is no id space to collide with the summary's, and nothing is interned beyond the list a + /// synthesized declaration already had to build. The parameters are leaked with the fact because `fact()` and + /// `parameter_facts_of()` answer with borrows; equal facts are deduplicated, so the arena grows with the + /// project's synthesized declarations, not with the number of queries. + synthetic_facts: std::sync::Mutex>, + /// **Files a query has synthesized facts for but the index has not read** — the buffer a completion is asked + /// about between the client's edit and the pump's read, or a view a test built without indexing. + /// + /// Such a file has no entry in `sequence`/`order`, so it has no [`crate::FileId`] the normal path can name. Rather + /// than drop its members — which is what "a reference row needs an arena" would otherwise mean — the index mints + /// an id for it and keeps the path here, so [`ProjectIndex::path_of`] and [`ProjectIndex::member_path`] can name + /// it. The ids are allocated downward from the top of the range, away from the summary numbering, and the path is + /// leaked only so that `path_of` can hand out a borrow; a session has a handful of open buffers, not thousands. + view_paths: std::sync::Mutex, +} + +/// The lazily minted file ids and their paths — see [`ProjectIndex::view_paths`]. +#[derive(Debug, Default)] +struct ViewFactPaths { + next: u32, + by_path: HashMap, + by_id: HashMap, +} + +impl ViewFactPaths { + /// The id this path was given, minting one the first time it is asked for. + fn id_of(&mut self, path: &Path) -> u32 { + let key = normalize(path); + if let Some(id) = self.by_path.get(&key) { + return *id; + } + if self.next == 0 { + // The summary numbering starts at zero and grows; this starts at the top and shrinks. `u32::MAX` is not + // used so a future sentinel has room. + self.next = u32::MAX - 1; + } + let id = self.next; + self.next = id.saturating_sub(1); + let leaked: &'static Path = Box::leak(path.to_path_buf().into_boxed_path()); + self.by_path.insert(key, id); + self.by_id.insert(id, leaked); + id + } + + /// The id this path **was** given, without minting one — what a read-only query needs. + fn get(&self, path: &Path) -> Option { + self.by_path.get(&normalize(path)).copied() + } +} + +/// One entry of the synthetic fact arena — a fact a query built, and the parameter list that has no `ParamsStore`. +/// +/// The list belongs to the entry rather than to the fact because `DeclFact` carries a handle, not an owned list; see +/// [`ProjectIndex`]'s `synthetic_facts` field for why this is an arena and not a second store. +#[derive(Debug)] +struct SyntheticFactEntry { + file: FileId, + fact: &'static DeclFact, + parameters: &'static [index::params::ParameterFact], } /// One entry of [`ProjectIndex::member_lists`]: the members, and **what the answer was made of**. @@ -610,6 +804,10 @@ struct CachedMacroState { pub(crate) struct OwnedVisibleDeclaration { pub file: PathBuf, pub fact: DeclFact, + /// The arena entry the owned `fact` was copied from — what a [`crate::OfferedName`] row points at. Carried + /// beside the copy for the same reason [`VisibleDeclaration::reference`] is: a fact is resolved through the + /// index, never found again by comparing its fields. + pub reference: FactRef, pub visibility: IncludeVisibility, } diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 7209389a..943fdb65 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -9,9 +9,32 @@ use super::*; use crate::Binding; use crate::FileView; use crate::ScopeTree; +use crate::index::types::ComputedType; use crate::sema; +use cpp_parser::CppAstNode; +use cpp_parser::CppExpr; +use cpp_parser::CppNameExpr; +use cpp_parser::CppRequiresClause; +use cpp_parser::CppSyntaxKind; use cpp_parser::CppSyntaxNode; +use cpp_parser::CppTemplateParamList; use cpp_parser::token_at; +use smol_str::SmolStr; + +/// **Is this answer of one kind?** — a [`ProjectDefinition`] carries a reference, so the question is asked of the +/// index that owns the declaration. +fn is_of_kind(index: &ProjectIndex, definition: &ProjectDefinition, kind: DeclKind) -> bool { + index + .definition_fact(definition) + .is_some_and(|fact| fact.kind == kind) +} + +/// **Is this answer a definition** (rather than a forward declaration)? See [`DeclFact::definition`]. +fn is_a_definition(index: &ProjectIndex, definition: &ProjectDefinition) -> bool { + index + .definition_fact(definition) + .is_some_and(|fact| fact.definition) +} /// The `#include` whose **directive** covers `offset`, if there is one and it resolved. /// @@ -128,6 +151,10 @@ pub fn definition_across_files( root: &CppSyntaxNode, path: &Path, offset: usize, + // The **file** offset for an offset in the tree being searched — the identity when the tree is of the file's + // own text, and the view's reading→file map when it is a rendering. A binding-derived answer is matched back to + // the fact arena by its name's offset, and the arena is in file coordinates. + to_file: &dyn Fn(usize) -> Option, ) -> Known { // **An unqualified name inside its class's own method is that class's member**, and the plural query cannot say // so: it lists every declaration of the spelling (a references list narrows that itself, see @@ -135,7 +162,7 @@ pub fn definition_across_files( // without qualifying it, so the class the definition is written for decides the singular question — and when it // declares nothing of that spelling, the answer is that the class does not declare it rather than another // class's member of the same name. - let found = definitions_across_files(index, declaring, scopes, root, path, offset); + let found = definitions_across_files(index, declaring, scopes, root, path, offset, to_file); // **The rule is for an *unqualified* name.** `nlohmann::json::object` in the body of // `WorkspaceDiagnosticReport::Serialize` is a qualified name: it names the class it wants, and what the enclosing // definition's class declares has no bearing on it. Measured: reading it as this class's member turned the correct @@ -154,9 +181,9 @@ pub fn definition_across_files( let named: Vec = list .members .into_iter() - .filter(|member| member.fact.name.as_str() == written.as_str()) + .filter(|member| index.member_name(member) == written.as_str()) .map(|member| ProjectDefinition { - file: member.file, + file: member.fact.file, fact: member.fact, }) .collect(); @@ -182,17 +209,17 @@ pub fn definition_across_files( if found .found .iter() - .any(|declaration| declaration.fact.kind != DeclKind::Other) + .any(|declaration| !is_of_kind(index, declaration, DeclKind::Other)) { found .found - .retain(|declaration| declaration.fact.kind != DeclKind::Other); + .retain(|declaration| !is_of_kind(index, declaration, DeclKind::Other)); } if found.found.len() > 1 { let definitions: Vec<&ProjectDefinition> = found .found .iter() - .filter(|declaration| declaration.fact.definition) + .filter(|declaration| is_a_definition(index, declaration)) .collect(); if let [only] = definitions.as_slice() { return Known::Yes((*only).clone()); @@ -205,10 +232,12 @@ pub fn definition_across_files( if definitions.len() > 1 && definitions .iter() - .all(|declaration| declaration.fact.kind == DeclKind::Type) - && let Some(general) = definitions - .iter() - .max_by_key(|declaration| declaration.fact.parameters().len()) + .all(|declaration| is_of_kind(index, declaration, DeclKind::Type)) + && let Some(general) = definitions.iter().max_by_key(|declaration| { + index + .definition_fact(declaration) + .map_or(0, |fact| fact.parameters().len()) + }) { return Known::Yes((*general).clone()); } @@ -311,10 +340,10 @@ pub fn member_definitions_across_files( let found: Vec = members .members .iter() - .filter(|member| member.fact.name == access.member) + .filter(|member| index.member_name(member) == access.member) .map(|member| ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: member.fact.file, + fact: member.fact, }) .collect(); @@ -377,6 +406,7 @@ pub fn definitions_across_files( root: &CppSyntaxNode, path: &Path, offset: usize, + to_file: &dyn Fn(usize) -> Option, ) -> Known { // **A cursor on a member asks about the object's type, not about the name.** `line.empty()` is // `std::basic_string::empty`, and asking by name instead reaches every `empty` in the library — measured, 12 @@ -424,9 +454,14 @@ pub fn definitions_across_files( .unwrap_or_else(|| candidates[0].clone()); let scope = the_scope_of_the_answer(scopes, root, offset, &chosen); let local = scopes.declares_a_local(chosen.scope); - return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding( - path, chosen, scope, local, - ))); + let name = chosen.name.text(); + let found = ProjectDefinition::from_binding(index, path, chosen, scope, local, to_file); + return match found { + Some(found) => Known::Yes(ProjectDefinitions::one(found)), + // **A buffer the index has not read.** A binding is a place in the scope tree, not an arena entry; + // when the entry is not there the honest answer is the one every unread declaration gets. + None => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name))), + }; } Known::Yes(mut candidates) => { let binding = candidates.remove(0); @@ -438,9 +473,13 @@ pub fn definitions_across_files( // reachable elsewhere. Asked before the binding is moved, and from the tree that can answer it. let local = scopes.declares_a_local(binding.scope); - return Known::Yes(ProjectDefinitions::one(ProjectDefinition::from_binding( - path, binding, scope, local, - ))); + let name = binding.name.text(); + return match ProjectDefinition::from_binding( + index, path, binding, scope, local, to_file, + ) { + Some(found) => Known::Yes(ProjectDefinitions::one(found)), + None => Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(name))), + }; } Known::Unknown(UnknownReason::NotDeclaredHere(name)) => { // The single-file layer has already established the spelling, so the project layer is asked about @@ -477,9 +516,9 @@ pub fn definitions_across_files( let inherited: Vec = list .members .into_iter() - .filter(|member| member.fact.name == last) + .filter(|member| index.member_name(member) == last) .map(|member| ProjectDefinition { - file: member.file, + file: member.fact.file, fact: member.fact, }) .collect(); @@ -522,7 +561,13 @@ pub fn definitions_across_files( definitions.found.retain(|definition| { // A definition in another file is a name this file can see through its includes; the point // here is only the file the cursor is in, where "below" is a fact in the same coordinates. - definition.file != path || definition.fact.name_range.start_offset <= offset + let Some(declared_in) = index.definition_path(definition) else { + return false; + }; + let Some(fact) = index.definition_fact(definition) else { + return false; + }; + declared_in != path || fact.name_range.start_offset <= offset }); match definitions.found.is_empty() { true => Known::No, @@ -541,62 +586,48 @@ pub fn definitions_across_files( Known::Unknown(UnknownReason::UnparsableName) } /// -/// A concept's body is written in terms of its parameter, so expanding `integral` means substituting `double` for +/// A concept's body is written in terms of its parameter, so expanding `integral` means binding `double` to /// that name. Read from the concept's own declaration rather than guessed from the use site. -pub(crate) fn the_concept_parameters(root: &CppSyntaxNode, name: &str) -> Option { - for declaration in root.descendants() { +/// +/// The `template <…>` is a **sibling** of the `ConceptDecl`, not part of it: measured, the tree is +/// `Declaration > [TemplateDecl, ConceptDecl]`, so the parameter list is read from the enclosing declaration. Both are +/// typed nodes; no declaration text is split. +pub(crate) fn the_concept_parameters(root: &CppSyntaxNode, name: &str) -> Option { + let declaration = the_concept_declaration(root, name)?; + let with_the_parameters = declaration.parent()?; + template_parameters_in(&with_the_parameters) + .into_iter() + .next() +} + +/// **The `ConceptDecl` node a name defines**, found in the tree the caller holds. +fn the_concept_declaration(root: &CppSyntaxNode, name: &str) -> Option { + root.descendants().find(|declaration| { if CppSyntaxKind::from(declaration.kind()) != CppSyntaxKind::ConceptDecl { - continue; - } - let text = declaration.text().to_string(); - let Some(at) = text.find('=') else { - continue; - }; - let declared = text[..at].split_whitespace().last().unwrap_or_default(); - if declared != name { - continue; + return false; } - // **The `template <…>` is a *sibling* of the `ConceptDecl`**, not part of it: measured, the tree is - // `Declaration > [TemplateDecl, ConceptDecl]` and the concept node's own text is `concept integral = …`. So the - // parameter list is read from the enclosing declaration. - let with_the_parameters = declaration - .parent() - .map(|parent| parent.text().to_string()) - .unwrap_or(text); - return template_parameters_in(&with_the_parameters) - .into_iter() - .next(); - } - None + // `concept integral = …` — the concept's own name is the declaration's first child name. + declaration + .children() + .find_map(CppNameExpr::cast) + .is_some_and(|declared| declared.get_qualified_name() == name) + }) } /// **A concept's right-hand side**, found by name: `template concept integral = std::is_integral_v;` -/// answers `std::is_integral_v`. +/// answers the `std::is_integral_v` node. /// /// Searched in the tree the caller holds — the file being edited and, when a `.cpp` is asking, the header its class is -/// declared in, which is the same walk the condition itself takes. Only the *definition* is read: a concept that composes -/// other concepts (`concept signed_integral = integral && is_signed_v`) answers a name this layer cannot expand, so -/// the verdict is `None` and the candidate stays. -pub(crate) fn the_concept_definition(root: &CppSyntaxNode, name: &str) -> Option { - for declaration in root.descendants() { - if CppSyntaxKind::from(declaration.kind()) != CppSyntaxKind::ConceptDecl { - continue; - } - let text = declaration.text().to_string(); - let Some(at) = text.find('=') else { - continue; - }; - // `concept integral = …` — the name is the word before the `=`. - let declared = text[..at].split_whitespace().last().unwrap_or_default(); - if declared != name { - continue; - } - let body = text[at + 1..].trim().trim_end_matches(';').trim(); - if !body.is_empty() { - return Some(body.to_string()); - } - } - None +/// declared in, which is the same walk the condition itself takes. The body is the declaration's own expression node, +/// so a concept that composes other concepts (`concept signed_integral = integral && is_signed_v`) is read as +/// the `BinaryExpr` it is; evaluating it is the constraint layer's job. +pub(crate) fn the_concept_definition(root: &CppSyntaxNode, name: &str) -> Option { + let declaration = the_concept_declaration(root, name)?; + // The declaration's children are its **name** and then its body — `concept integral = …` is + // `ConceptDecl > [NameExpr "integral", ]`. + let mut expressions = declaration.children().filter_map(CppExpr::cast); + let _name = expressions.next()?; + expressions.next().map(|body| body.syntax().clone()) } /// **The overload a call actually names**, when the condition in its signature can decide it. @@ -646,11 +677,11 @@ pub(crate) fn the_overload_a_call_names( Some(list) => list.children().collect(), None => call.children().skip(1).collect(), }; - let argument_types: Vec> = arguments + let argument_types: Vec> = arguments .iter() .map(|argument| { match type_of_expression(index, declaring, scopes, root, path, argument, 0) { - Known::Yes((found, _)) => Some(found.to_string()), + Known::Yes((found, _)) => Some(found), _ => None, } }) @@ -674,34 +705,30 @@ pub(crate) fn the_overload_a_call_names( .ancestors() .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declaration) .unwrap_or_else(|| the_candidate.clone()); - let declaration = declaration_node.text().to_string(); // **A `requires` clause is read from its own node**, because the clause and the declaration that follows it are // separated by nothing but a newline: a text scan cannot tell `requires is_integral_v` from - // `requires is_integral_v std::string describe(T)`. `enable_if` is a name inside the type, so it is found in - // the text and needs no node. + // `requires is_integral_v std::string describe(T)`. `enable_if` is a name inside the type, and its first + // template argument is the condition. Both answers are **typed CST nodes** — nothing here is a spelling. let requires_clause = declaration_node .descendants() - .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::RequiresClause) - .map(|node| node.text().to_string()) - .and_then(|text| sema::constraint::a_requires_clause(&text).map(str::to_string)); - let condition_owned = requires_clause - .as_deref() - .map(str::to_string) - .or_else(|| sema::constraint::the_condition_of(&declaration).map(str::to_string)); + .find_map(CppRequiresClause::cast) + .and_then(|clause| sema::constraint::a_requires_clause_node(&clause)); + let condition = + requires_clause.or_else(|| sema::constraint::the_condition_of_node(&declaration_node)); // **A constraint written as a *concept*'s name** — `template ` — holds no expression to evaluate, so // the concept's own definition is found and its right-hand side evaluated with the same bindings. Measured: a // pair of overloads gated by `integral`/`floating` stayed an unresolved set and the call answered the first. - let condition_owned = condition_owned.or_else(|| { - let name = sema::constraint::a_concept_name(&declaration)?; + let condition = condition.or_else(|| { + let name = sema::constraint::a_concept_name(&declaration_node)?; the_concept_definition(root, &name) }); - let Some(condition) = condition_owned.as_deref() else { + let Some(condition) = condition.as_ref() else { // An ordinary function, or a template enabled unconditionally. survivors.push(candidate.clone()); continue; }; - let parameters = template_parameters_in(&declaration); - let bound: Vec<(String, String)> = parameters + let parameters = template_parameters_in(&declaration_node); + let bound: Vec<(SmolStr, ComputedType)> = parameters .into_iter() .zip(argument_types.iter()) .filter_map(|(parameter, found)| Some((parameter, found.clone()?))) @@ -710,9 +737,9 @@ pub(crate) fn the_overload_a_call_names( // `integral && is_signed_v`, and `integral` is another concept. Without this, a composed concept answered // "cannot tell" and both candidates stayed — measured, `describe(1.5)` resolved to the `signed_integral` overload. let verdict = sema::constraint::satisfies_with(condition, &bound, &mut |name| { - the_concept_definition(root, name).and_then(|body| { - the_concept_parameters(root, name).map(|parameter| (parameter, body)) - }) + let body = the_concept_definition(root, name)?; + let parameter = the_concept_parameters(root, name)?; + Some((parameter, body)) }); match verdict { Some(false) => {} @@ -724,42 +751,24 @@ pub(crate) fn the_overload_a_call_names( } /// The names a declaration's `template <…>` introduces, in order — `template ` answers `["T", "U"]`. -pub(crate) fn template_parameters_in(declaration: &str) -> Vec { - let Some(at) = declaration.find("template") else { - return Vec::new(); - }; - let after = &declaration[at + "template".len()..]; - let Some(open) = after.find('<') else { +/// +/// Read from the `TemplateParameterList` node and each parameter's own name accessor, not from the declaration's text: +/// a parameter names itself in one of several ways (`typename T`, `int N`, `class... Args`, `int N = sizeof(T)`), and +/// the rules that separate the name from its default are the parser's own +/// ([`cpp_parser::CppTemplateParam::get_name`]). +pub(crate) fn template_parameters_in(declaration: &CppSyntaxNode) -> Vec { + let Some(template) = declaration + .children() + .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateDecl) + else { return Vec::new(); }; - let mut depth = 0isize; - let mut close = None; - for (index, character) in after[open..].char_indices() { - match character { - '<' => depth += 1, - '>' => { - depth -= 1; - if depth == 0 { - close = Some(open + index); - break; - } - } - _ => {} - } - } - let Some(close) = close else { + let Some(list) = template.children().find_map(CppTemplateParamList::cast) else { return Vec::new(); }; - after[open + 1..close] - .split(',') - .filter_map(|parameter| { - // `typename T`, `class U`, `typename... Args` — the name is the last word, and a pack keeps its `...`. - parameter - .split_whitespace() - .last() - .map(|word| word.trim_end_matches("...").trim().to_string()) - .filter(|word| !word.is_empty()) - }) + list.get_params() + .filter_map(|parameter| parameter.get_name()) + .map(|name| SmolStr::new(name.get_name_text())) .collect() } diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 0ec2f8f5..333446f1 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -4,15 +4,20 @@ //! `names_define_static_array`) that the member and call walks rely on. use super::*; +use crate::DeclFact; use crate::DeclKind; use crate::FileView; use crate::ScopeTree; use crate::index; +use crate::index::types::ComputedType; use crate::sema; +use crate::sema::types::TypeSubstitutions; use cpp_parser::CppDeclaration; use cpp_parser::CppReturnStat; use cpp_parser::CppSyntaxNode; use cpp_parser::token_at; +use smol_str::SmolStr; +use std::sync::Arc; /// **What a template-id's own arguments do to the type its declaration wrote.** /// @@ -35,8 +40,8 @@ pub(crate) fn substituted_at_the_use( path: &Path, expression: &CppSyntaxNode, named: &NamedDeclaration, - type_of: Type, -) -> Type { + type_of: ComputedType, +) -> ComputedType { let arguments = written_template_arguments(expression); if arguments.is_empty() { return type_of; @@ -59,22 +64,18 @@ pub(crate) fn substituted_at_the_use( // (`U = T`), so each one is substituted with what the use wrote before it stands for anything; a default that // names itself is left alone by `TypeSubstitutions::get`. let written_defaults = named.parameter_defaults_of(index, root); - let written_arguments: Vec = arguments.clone(); - let mut defaults: Vec = Vec::with_capacity(written_defaults.len()); + let written_arguments: Vec = arguments.clone(); + let mut defaults: Vec = Vec::with_capacity(written_defaults.len()); for default in &written_defaults { if default.trim().is_empty() { - defaults.push(Type::builtin("")); + defaults.push(ComputedType::builtin("")); continue; } let parsed = parse_type_spelling(default); - defaults.push(parsed.substituted(&sema::types::TypeSubstitutions::new( - &names, - &written_arguments, - ))); + defaults.push(parsed.substituted(&TypeSubstitutions::new(&names, &written_arguments))); } - let substitutions = - sema::types::TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults); + let substitutions = TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults); type_of.substituted(&substitutions) } /// **An argument spelling as the pattern comparison should see it**: a decidable compiler builtin, folded. @@ -112,14 +113,14 @@ pub(crate) fn the_alias_behind( let Known::Yes(found) = index.definition(head.trim(), declaring) else { return None; }; - if found.fact.kind != DeclKind::Type { + let found = index.definition_fact(&found)?; + if found.kind != DeclKind::Type { return None; } - let target = found.fact.type_of.as_deref()?; + let target = index.type_spelling_of(found)?; let arguments = sema::builtins::split_arguments(inside); - let substituted = - sema::types::substituted_spelling(target, found.fact.parameters(), &arguments); + let substituted = sema::types::substituted_spelling(&target, found.parameters(), &arguments); // `typename enable_if<_Test, _Ty>::type` — the last `::` separates the class from the member it names. let substituted = substituted @@ -163,6 +164,31 @@ pub fn substituted_members( from: &Path, class: &str, listed: Known, +) -> Known { + substituted_members_with(index, from, class, None, None, listed) +} + +/// **The computation-layer entry**: the class and its arguments are already structured, so no spelling is split. +pub(crate) fn substituted_members_for( + index: &ProjectIndex, + from: &Path, + class: &ComputedType, + listed: Known, +) -> Known { + let Some(base) = class.class_name() else { + return listed; + }; + let arguments: Vec = class.arguments().iter().map(ToString::to_string).collect(); + substituted_members_with(index, from, base, Some(&arguments), Some(class), listed) +} + +fn substituted_members_with( + index: &ProjectIndex, + from: &Path, + class: &str, + prepared_arguments: Option<&[String]>, + prepared_type: Option<&ComputedType>, + listed: Known, ) -> Known { let Known::Yes(mut list) = listed else { return listed; @@ -173,17 +199,27 @@ pub fn substituted_members( // template, and the type layer answered the parameter: measured through the server, `s[0]` on a `std::string&` // was **`_Elem&`** where a compiler answers `char&`, while the same class spelled `std::basic_string` // answered correctly (`value_type: char`, `reference: char&`). - let Some((base, arguments)) = split_template_arguments(class).or_else(|| { - let target = index - .files_declaring(class, from) - .into_iter() - .find(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.type_of.is_some() - }) - .and_then(|declared| declared.fact.type_of.clone())?; - split_template_arguments(&target) - }) else { - return Known::Yes(list); + let (base, arguments) = if let Some(arguments) = prepared_arguments { + (class.to_string(), arguments.to_vec()) + } else { + let Some((base, arguments)) = split_template_arguments(class).or_else(|| { + // **The alias target is already a `ComputedType`.** Split it structurally rather than printing it and + // parsing the display spelling back into a class and arguments. + let target = index + .files_declaring(class, from) + .into_iter() + .find(|declared| { + declared.fact.kind == DeclKind::Type && declared.fact.has_type_of() + }) + .and_then(|declared| index.computed_type_of(declared.fact))?; + Some(( + target.class_name()?.to_string(), + target.arguments().iter().map(ToString::to_string).collect(), + )) + }) else { + return Known::Yes(list); + }; + (base, arguments) }; let Some(declared) = index .files_declaring(&base, from) @@ -207,9 +243,6 @@ pub fn substituted_members( // silent while the one-parameter fixture beside it reported — the arguments were cut to the shorter side and the // defaulted parameter was simply left standing. let defaults = index.template_parameter_defaults_for(&base, from, &arguments); - if names.is_empty() { - return Known::Yes(list); - } // **The class's own aliases, expanded before the arguments go in.** `std::vector` declares its parameter as // `void push_back(const value_type& __x);` with `using value_type = _Tp;` in the class — so substituting @@ -223,109 +256,225 @@ pub fn substituted_members( // A plain `using value_type = _Tp;` inside a class template records the **class's** parameters as its own // (`declared_template_parameters_with` pairs the `template <…>` head with the declaration it introduces), so // there is deliberately no `parameters.is_empty()` test here: the alias that matters most has one. - let mut alias_names: Vec = Vec::new(); - let mut alias_targets: Vec = Vec::new(); - for member in list - .members - .iter() - .filter(|member| member.depth == 0 && member.fact.kind == DeclKind::Type) - { - let Some(target) = member.fact.type_of.clone() else { + let mut alias_names: Vec = Vec::new(); + let mut alias_targets: Vec = Vec::new(); + // **The aliases as types too**, so a structured substitution can expand `value_type` the way the written one + // always could. The target is the alias fact's own `type_of`, resolved through the one store — `T` inside it was + // already marked a template parameter when the fact was built, so nothing is parsed here. + let mut alias_bindings: Vec<(SmolStr, ComputedType)> = Vec::new(); + for member in list.members.iter().filter(|member| member.depth == 0) { + let Some(fact) = index.member_fact(member) else { + continue; + }; + if fact.kind != DeclKind::Type { + continue; + } + let Some(target) = index.type_spelling_of(fact) else { continue; }; // **Not the alias itself**: `type_of` is the target, and a member whose target names itself would make // `value_type` → `value_type` a rewrite that changes nothing but costs a pass. - if target == member.fact.name { + if target == fact.name.as_str() { continue; } - alias_names.push(member.fact.name.to_string()); - alias_targets.push(target.to_string()); + alias_names.push(fact.name.clone()); + alias_targets.push(SmolStr::new(target)); + if let Some(target_type) = index.computed_type_of(fact) { + alias_bindings.push((fact.name.clone(), target_type)); + } } - // **An alias's own target is not an alias to expand.** `std::shared_ptr`'s `element_type` is written - // `using element_type = typename __shared_ptr<_Tp>::element_type;`, so the target contains its own name and - // replacing that name with the target doubles the prefix — - // `typename __shared_ptr::typename __shared_ptr::element_type`, measured. The member's own - // `type_of` *is* the target, so the expansion is a step for the other members only. - let declares_an_alias = |member: &ProjectMember| { - member.fact.kind == DeclKind::Type - && alias_names - .iter() - .any(|name| name == member.fact.name.as_str()) - }; - // **One pass is not enough, and the pass's own order is what decides.** A class's aliases name each other: - // libstdc++'s `basic_string_view` writes `using value_type = _CharT;` and `using const_pointer = const - // value_type*;`, so expanding `const_pointer` produces a spelling that still holds `value_type` — and - // `substituted_spelling` walks the alias list once, in its own order, which may already have passed the name the - // expansion introduced. Measured: `data()`'s answer came out `const value_type*`, `convertible_to` compared it - // with a parameter written `const char*`, answered `No`, and every `std::from_chars(text.data(), …)` in a real - // project was reported as *"this passes `text.data()` where `const char*` is declared"*. + // **The per-member substitution context** — the class's parameters paired with this use's arguments, plus the + // written context the display layer needs. It is carried beside the fact; the fact itself is never rewritten. // - // So the rewrite is repeated until it stops changing, bounded by a handful of passes rather than a `changed` flag: - // an alias that names itself would otherwise spin, and an alias chain deeper than four is a library experiment - // rather than a spelling. **The scan that guards the loop is what makes it affordable** — a member's type usually - // mentions no alias of its class at all, and the pass below is O(names × length), so asking "does this spelling - // hold any of them" first is the difference between one scan and one pass per member of every standard-library - // class. Measured after the first version of this loop: a cold start of a four-header project went from 27 s to - // over 30 s, which is what put the guard here. - let through_the_aliases = |spelling: &str| -> String { - let mut spelling = spelling.to_string(); + // `bindings` is the structured half (`_Tp` -> `int` as a `ComputedType`), which the computation layer applies + // without a spelling. The stage is the same pairing as the declaration wrote it, because a fact's parameter list + // is still text; its aliases are the class's own, expanded before the parameters are. + let stage = MemberSubstitutionStage { + parameter_names: names.to_vec(), + parameter_defaults: defaults.iter().map(SmolStr::from).collect(), + written_arguments: arguments.iter().map(SmolStr::from).collect(), + alias_names, + alias_targets, + }; + + // **A substitution that changes nothing is not carried.** A class written without arguments and without + // defaults — `std::vector` in `members_of("std::vector")` — has nothing to put in; attaching a context would + // cost every member an `Arc` and answer the same spelling. + let changes_a_spelling = !stage.alias_names.is_empty() + || stage + .written_arguments + .iter() + .any(|argument| !argument.is_empty()) + || stage + .parameter_defaults + .iter() + .any(|default| !default.trim().is_empty()); + if !changes_a_spelling { + return Known::Yes(list); + } + + // `bindings` is the structured half (`_Tp` -> `int` as a `ComputedType`), which the computation layer applies + // without a spelling. It is built from the same pairing the stage records: the class's parameter names with the + // use's written arguments, and the declaration's defaults for the slots the use left out. Each argument is a + // *use-site spelling*, so it is parsed once here — the construction edge — and never on a query. + let bindings: Vec<(SmolStr, ComputedType)> = match prepared_type { + Some(class) => names + .iter() + .zip(class.arguments().iter()) + .map(|(name, argument)| (name.clone(), an_argument_as_a_type(argument))) + .collect(), + None => { + let mut bindings = Vec::with_capacity(names.len()); + for (at, name) in names.iter().enumerate() { + let written = arguments + .get(at) + .map(|argument| argument.trim()) + .filter(|argument| !argument.is_empty()) + .map(str::to_string) + .or_else(|| { + defaults + .get(at) + .map(|default| default.trim()) + .filter(|default| !default.is_empty() && *default != name.as_str()) + .map(|default| { + sema::types::substituted_spelling(default, &names, &arguments) + }) + }); + let Some(written) = written else { + continue; + }; + let parsed = parse_type_spelling(&written); + let parsed = sema::types::with_template_parameters(parsed, &names); + bindings.push((name.clone(), an_argument_as_a_type(&parsed))); + } + bindings + } + }; + let substitution = MemberSubstitution { + alias_bindings, + bindings, + stages: vec![stage], + }; + + // **The list itself is never rewritten.** Each row keeps its `FactRef` and gains this instantiation's context; + // a row that already carries one — a base's member that the walk above substituted — composes the new context + // *over* the old, which is the same order the two rewrites used to run in. + let substitution = Arc::new(substitution); + for member in &mut list.members { + member.substitution = Some(match &member.substitution { + Some(existing) => Arc::new(MemberSubstitution::compose(existing, &substitution)), + None => Arc::clone(&substitution), + }); + } + Known::Yes(list) +} + +/// **One structured template argument as the type it names.** +/// +/// `read_template_arguments` answers a computed name for an argument the tree gave no typed node — in some +/// shapes `std::vector` reaches this layer with `int` as a token, and reading it as a *class* named `int` makes +/// every substitution through it a target the conversion relation cannot classify (`push_back("x")` on a +/// `std::vector` stayed silent). A builtin's spelling written where a type goes is that primary type; a name that +/// is not a primary stays the name it is. +fn an_argument_as_a_type(argument: &ComputedType) -> ComputedType { + match argument { + ComputedType::Named(name) => index::types::PrimaryType::from_spelling(name) + .map_or_else(|| argument.clone(), ComputedType::Primary), + other => other.clone(), + } +} + +impl MemberSubstitution { + /// **One instantiation's written substitution** — the stage a row with a single substitution carries. + pub fn of(stage: MemberSubstitutionStage) -> MemberSubstitution { + MemberSubstitution { + bindings: Vec::new(), + alias_bindings: Vec::new(), + stages: vec![stage], + } + } + + /// **`new` applied over `existing`.** The stages keep their order (the older rewrite ran first), and a parameter + /// name both bindings mention takes the **newest** meaning — the instantiation the reader is looking at. + pub fn compose(existing: &MemberSubstitution, new: &MemberSubstitution) -> MemberSubstitution { + let mut bindings: Vec<(SmolStr, ComputedType)> = new.bindings.clone(); + for (name, value) in &existing.bindings { + if bindings.iter().any(|(taken, _)| taken == name) { + continue; + } + bindings.push((name.clone(), value.substituted_by_bindings(&new.bindings))); + } + let mut alias_bindings: Vec<(SmolStr, ComputedType)> = new.alias_bindings.clone(); + for (name, value) in &existing.alias_bindings { + if alias_bindings.iter().any(|(taken, _)| taken == name) { + continue; + } + alias_bindings.push((name.clone(), value.substituted_by_bindings(&new.bindings))); + } + let mut stages = existing.stages.clone(); + stages.extend(new.stages.iter().cloned()); + MemberSubstitution { + bindings, + alias_bindings, + stages, + } + } + + /// **A written spelling with this instantiation applied**, stage by stage — aliases first, then the parameters, + /// exactly as the two rewrites used to run. + /// + /// `member` is the declaration the spelling came from: a member that **is** an alias of its class is not expanded + /// through that class's aliases, because its own target is what `type_of` already holds. See the note the alias + /// collection in [`substituted_members`] states about `std::shared_ptr`'s `element_type`. + pub fn applied_to_spelling(&self, written: &str, member: &DeclFact) -> String { + let mut spelling = written.to_string(); + for stage in &self.stages { + let is_an_alias_of_the_class = member.kind == DeclKind::Type + && stage + .alias_names + .iter() + .any(|name| name.as_str() == member.name.as_str()); + if !is_an_alias_of_the_class { + spelling = stage.through_the_aliases(&spelling); + } + if !stage.parameter_names.is_empty() { + spelling = sema::types::substituted_spelling_with_defaults( + &spelling, + &stage.parameter_names, + &stage.parameter_defaults, + &stage.written_arguments, + ); + } + } + spelling + } +} + +impl MemberSubstitutionStage { + /// **One pass's alias expansion, repeated until it stops changing** — see the measurement in [`substituted_members`]. + fn through_the_aliases(&self, written: &str) -> String { + let mut spelling = written.to_string(); for _ in 0..MAX_ALIAS_PASSES { - if !alias_names + if !self + .alias_names .iter() .any(|name| spelling.contains(name.as_str())) { break; } - let next = sema::types::substituted_spelling(&spelling, &alias_names, &alias_targets); + let next = sema::types::substituted_spelling( + &spelling, + &self.alias_names, + &self.alias_targets, + ); if next == spelling { break; } spelling = next; } spelling - }; - for member in list - .members - .iter_mut() - .filter(|member| !declares_an_alias(member)) - { - if !alias_names.is_empty() { - if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { - *spelling = through_the_aliases(spelling).into(); - } - if let Some(spelling) = member.fact.returns.as_mut() { - *spelling = through_the_aliases(spelling).into(); - } - } - // **`type_of` is a `SmolStr`**, so it takes the same rewrite and converts its own result back. - if !alias_names.is_empty() - && let Some(spelling) = member.fact.type_of.as_mut() - { - *spelling = through_the_aliases(spelling).into(); - } - } - for member in &mut list.members { - if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { - *spelling = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ) - .into(); - } - if let Some(spelling) = member.fact.returns.as_mut() { - *spelling = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ) - .into(); - } - if let Some(spelling) = member.fact.type_of.as_mut() { - *spelling = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ) - .into(); - } } - Known::Yes(list) } /// **Split `std::vector` into its name and its arguments** — `("std::vector", ["int"])`. @@ -477,12 +626,12 @@ pub(crate) fn is_a_parameter_name(name: &str) -> bool { /// substituted into, because no spelling of a body equals the empty string, and its presence keeps the *later* /// arguments aligned with their names. So a list that has names beside its slots is exactly a list a substitution can /// use — and one that is all slots (`template class vector;`) has nothing to substitute. -pub(crate) fn lists_usable_parameter_names(names: &[String]) -> bool { +pub(crate) fn lists_usable_parameter_names>(names: &[N]) -> bool { !names.is_empty() - && names.iter().any(|name| !name.is_empty()) + && names.iter().any(|name| !name.as_ref().is_empty()) && names .iter() - .all(|name| name.is_empty() || is_a_parameter_name(name)) + .all(|name| name.as_ref().is_empty() || is_a_parameter_name(name.as_ref())) } /// **`element_type` read through the member that names the base** — `using _Mybase = _Ptr_base<_Ty>;` and then @@ -515,16 +664,16 @@ pub(crate) fn an_element_type_through_the_members( let Some(fact) = members .members .iter() - .filter(|member| member.fact.name == name) - .map(|member| &member.fact) - .find(|fact| fact.type_of.is_some()) + .filter(|member| index.member_name(member) == name) + .filter_map(|member| index.member_fact(member)) + .find(|fact| index.type_spelling_of(fact).is_some()) else { continue; }; - let Some(written) = fact.type_of.as_deref() else { + let Some(written) = index.type_spelling_of(fact) else { continue; }; - let substituted = sema::types::substituted_spelling(written, parameters, arguments); + let substituted = sema::types::substituted_spelling(&written, parameters, arguments); let target = base_type_name(&substituted).to_string(); if !target.is_empty() @@ -537,13 +686,16 @@ pub(crate) fn an_element_type_through_the_members( // A member of kind `Type` whose target names another class — the alias of the base. for member in &members.members { - if member.fact.kind != DeclKind::Type { + let Some(fact) = index.member_fact(member) else { + continue; + }; + if fact.kind != DeclKind::Type { continue; } - let Some(target) = member.fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(fact) else { continue; }; - if base_type_name(target) == base_type_name(class) { + if base_type_name(&target) == base_type_name(class) { continue; } // **The target is written inside the class's own namespace and carries the class's arguments**: `_Mybase` is @@ -714,13 +866,13 @@ pub(crate) fn the_return_the_body_gives_back( // took the same sample from **75.6 s to 26.7 s**, the number it had before the deduction existed. A `return` this // layer reads is therefore one in the file the cursor is in; a wrapper in a header stays unknown, which is the // answer it gave before. - if candidate.file != path { + if index.definition_path(candidate) != Some(path) { return None; } let the_root = root; let the_scopes = scopes; let the_path = path; - let in_the_reading = candidate.fact.name_range.start_offset; + let in_the_reading = index.definition_fact(candidate)?.name_range.start_offset; let token = token_at(the_root, in_the_reading)?; let declaration = token diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 5365c9aa..81b4ba18 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -3,6 +3,7 @@ //! Moved out of `project/mod.rs` without a change. `use super::*` is how a test reaches the module's private //! machinery, which is the point of testing it from here. +use super::FactRef; use super::MAX_COLLECTED_NAMES; use super::MemberCompletions; use super::MemberList; @@ -10,16 +11,19 @@ use super::NameCompletions; use super::ProjectDefinition; use super::ProjectMember; use super::ProjectSymbol; +use super::UnlistedBase; use super::definition_across_files; use super::macro_across_files; use super::member_across_files; use super::member_completions_at; use super::members_of; use super::name_completions_at; -use super::{IncludeVisibility, ProjectIndex}; +use super::{FALLBACK_FILE_ID_BIT, IncludeVisibility, ProjectIndex}; use crate::CompilerConfig; use crate::CookedFile; +use crate::DeclFact; use crate::DeclKind; +use crate::FileId; use crate::FileIndexer; use crate::MacroDefinitions; use crate::Marked; @@ -28,6 +32,7 @@ use crate::NoMacroBodies; use crate::TranslationUnit; use crate::WalkCache; use crate::build_scopes; +use crate::cache; use crate::cache::SummaryKey; use crate::index::summarize; use crate::preprocess; @@ -36,8 +41,9 @@ use cpp_parser::CppParser; use cpp_parser::CppSyntaxTree; use cpp_parser::LexerConfig; use cpp_parser::ParserConfig; +use cpp_parser::SourceRange; use cpp_parser::lex; -use std::path::Path; +use std::path::{Path, PathBuf}; /// **A member named like its class does not hide the class** — the reader's report "`LSPHandle` was read as the /// constructor itself rather than the class", as a test at the layer that broke it. @@ -66,11 +72,11 @@ fn a_member_named_like_its_class_does_not_hide_the_class() { panic!("the class must resolve, not fall to its constructor: {found:?}"); }; assert_eq!( - definition.fact.kind, + the_fact(&index, &definition).kind, DeclKind::Type, "the name `LSPHandle` resolved to {:?} in {}", - definition.fact.kind, - definition.file.display() + the_fact(&index, &definition).kind, + the_file(&index, &definition).display() ); } @@ -82,7 +88,7 @@ fn index(files: &[(&str, &str)]) -> ProjectIndex { // tests are about is the graph that results — not the search that produced it. let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0)); for include in &mut summary.includes { - include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling))); + include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling))); } index.insert(summary); } @@ -90,6 +96,363 @@ fn index(files: &[(&str, &str)]) -> ProjectIndex { index } +/// The declaration a definition answer resolves to, through the index that issued it. +fn the_fact<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a DeclFact { + index + .definition_fact(definition) + .expect("the answer resolves through the index") +} + +/// The file a definition answer points into, in the index's spelling. +fn the_file<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a Path { + index + .definition_path(definition) + .expect("the answer names a file the index holds") +} + +/// **The VFS namespace and the index's own fallback namespace cannot alias**, and both resolve through `path_of` +/// and `fact`. +/// +/// A fallback id sets the high bit; a registered VFS id does not. That is what lets `path_of` decide which table an +/// id came from, and this is the test that pins the encoding: if a future change minted fallback ids from the bare +/// sequence (as the index did before the VFS table existed), the two ids below would collide and a `FactRef` about +/// one file would resolve to the other's facts. +#[test] +fn a_registered_vfs_id_and_a_fallback_id_cannot_alias() { + let mut index = index(&[ + ("/p/one.cpp", "struct One {};\n"), + ("/p/two.cpp", "struct Two {};\n"), + ]); + + // The session says the first file is VFS file 7. It never mints ids this small from the fallback sequence. + let vfs = FileId::new(7); + index.register_file_id(Path::new("/p/one.cpp"), vfs); + assert_eq!(index.file_id_of(Path::new("/p/one.cpp")), Some(vfs)); + + let fallback = index + .file_id_of(Path::new("/p/two.cpp")) + .expect("the file was inserted, so it has a fallback id"); + assert_ne!( + fallback, vfs, + "a fallback sequence number must not be mistaken for a VFS id" + ); + assert_ne!( + fallback.index() as u32 & FALLBACK_FILE_ID_BIT, + 0, + "the fallback is in the index's high-bit namespace: {fallback:?}" + ); + assert_eq!( + vfs.index() as u32 & FALLBACK_FILE_ID_BIT, + 0, + "a registered VFS id is in the low half, or `register_file_id` refuses it" + ); + + assert_eq!(index.path_of(vfs), Some(Path::new("/p/one.cpp"))); + assert_eq!(index.path_of(fallback), Some(Path::new("/p/two.cpp"))); + + // Both halves resolve through the one resolver a reference goes through. + let one = index + .summary_fact_ref(Path::new("/p/one.cpp"), 0) + .expect("the first declaration of the file"); + let two = index + .summary_fact_ref(Path::new("/p/two.cpp"), 0) + .expect("the first declaration of the file"); + assert_eq!(one.file, vfs); + assert_eq!(two.file, fallback); + assert_eq!(index.fact(one).map(|fact| fact.name.as_str()), Some("One")); + assert_eq!(index.fact(two).map(|fact| fact.name.as_str()), Some("Two")); + // …and the path a reference names is the path `path_of` answers, not the other file's. + assert_eq!( + index.member_path(&member_row(one)), + Some(Path::new("/p/one.cpp")) + ); + assert_eq!( + index.member_path(&member_row(two)), + Some(Path::new("/p/two.cpp")) + ); +} + +/// **A conflicting registration is ignored and corrupts neither map** — the first pair stays the answer, and the +/// path/id that lost still has a usable fallback id. +#[test] +fn a_conflicting_file_id_registration_is_ignored() { + let mut index = index(&[ + ("/p/one.cpp", "struct One {};\n"), + ("/p/two.cpp", "struct Two {};\n"), + ]); + + let kept = FileId::new(3); + index.register_file_id(Path::new("/p/one.cpp"), kept); + + // One id, two paths: the second path must not steal an id whose facts belong to the first. + index.register_file_id(Path::new("/p/two.cpp"), kept); + assert_eq!(index.file_id_of(Path::new("/p/one.cpp")), Some(kept)); + assert_eq!( + index.path_of(kept), + Some(Path::new("/p/one.cpp")), + "the id still names the path it was registered for" + ); + let fallback = index + .file_id_of(Path::new("/p/two.cpp")) + .expect("the rejected path keeps its fallback id"); + assert_ne!(fallback, kept); + + // One path, two ids: the first id is what facts already filed under the path name. + let later = FileId::new(4); + index.register_file_id(Path::new("/p/one.cpp"), later); + assert_eq!(index.file_id_of(Path::new("/p/one.cpp")), Some(kept)); + assert_eq!( + index.path_of(later), + None, + "the refused id must not resolve to a path it never named" + ); + + // Re-registering the pair that won is a no-op, which is what lets the session register on every read. + index.register_file_id(Path::new("/p/one.cpp"), kept); + assert_eq!(index.file_id_of(Path::new("/p/one.cpp")), Some(kept)); + assert_eq!(index.path_of(kept), Some(Path::new("/p/one.cpp"))); + + // **An id in the index's own half is refused even when nothing owns it.** Accepting it would make the two + // namespaces indistinguishable in `path_of`: the number could be a fallback sequence of another file. + let in_the_high_half = FileId::new(FALLBACK_FILE_ID_BIT | 9); + index.register_file_id(Path::new("/p/two.cpp"), in_the_high_half); + assert_eq!( + index.file_id_of(Path::new("/p/two.cpp")), + Some(fallback), + "the refused id changes nothing" + ); + assert_eq!( + index.path_of(in_the_high_half), + None, + "and it resolves no path, because it was never registered" + ); +} + +/// **A file registered before its summary exists resolves** — the order the session uses on a cache load: the VFS +/// answers with an id, the index is told it, and only then does the summary (here, the inserted one) arrive. +#[test] +fn a_vfs_id_registered_before_the_summary_resolves_the_path_and_the_facts() { + let mut index = ProjectIndex::new(); + let vfs = FileId::new(12); + index.register_file_id(Path::new("/p/early.cpp"), vfs); + + assert_eq!(index.file_id_of(Path::new("/p/early.cpp")), Some(vfs)); + assert_eq!( + index.path_of(vfs), + Some(Path::new("/p/early.cpp")), + "the VFS table alone can name a file the index has not read" + ); + + // A view-built fact minted in that window names the same id the summary will be filed under. + let summary = summarize( + Path::new("/p/early.cpp"), + "struct Early {};\n", + SummaryKey::new(0, 0), + ); + let synthesized = summary.declarations[0].clone(); + let reference = + index.intern_a_view_fact(Path::new("/p/early.cpp"), synthesized, Box::default()); + assert_eq!(reference.file, vfs); + assert!( + index.fact(reference).is_some(), + "a synthetic fact resolves through the arena it was interned in" + ); + + index.insert(summary); + assert_eq!( + index.file_id_of(Path::new("/p/early.cpp")), + Some(vfs), + "the summary arriving does not renumber the file" + ); + assert_eq!(index.path_of(vfs), Some(Path::new("/p/early.cpp"))); + let fact = index + .summary_fact_ref(Path::new("/p/early.cpp"), 0) + .expect("the inserted summary has a declaration"); + assert_eq!(fact.file, vfs); + assert_eq!( + index.fact(fact).map(|fact| fact.name.as_str()), + Some("Early") + ); +} + +/// A row whose only content is a fact reference, for asking the resolvers that take a `ProjectMember`. +fn member_row(fact: FactRef) -> ProjectMember { + ProjectMember { + fact, + substitution: None, + declared_in: "One".to_string(), + depth: 0, + ambiguous: false, + } +} + +/// **A summary's fact carries its type as a value**, so inserting it needs no type store and no handle rewrite. +/// +/// The two `int` declarations carry equal values; `double` is another value. Equality is the value's, not an id's: +/// there is no intern table behind it. +#[test] +fn a_summary_stores_each_declaration_type_as_a_value() { + let mut index = ProjectIndex::new(); + let summary = summarize( + Path::new("/p/a.cpp"), + "int first;\nint second;\ndouble third;\n", + SummaryKey::new(0, 0), + ); + index.insert(summary); + + let stored = index.summary(Path::new("/p/a.cpp")).expect("inserted"); + let types: Vec<_> = stored + .declarations + .iter() + .filter_map(|fact| fact.type_of.computed().map(|computed| computed.to_string())) + .collect(); + assert_eq!( + types.len(), + 3, + "every declaration with a written type got one" + ); + assert_eq!(types[0], types[1], "`int` is the same value"); + assert_ne!(types[0], types[2], "`double` is another"); + assert_eq!(types[0], "int"); + assert_eq!(types[2], "double"); +} + +/// **A decoded summary keeps its types as values.** Encode/decode a real inserted summary, then insert the decoded +/// copy into a fresh index: there is no table to import and no id to rewrite, so the same values come back. +#[test] +fn a_cached_summary_keeps_its_type_values() { + let path = Path::new("/p/types.cpp"); + let source = "int first;\nstd::vector items;\nint f(double value);\n"; + let mut first = ProjectIndex::new(); + first.insert(summarize(path, source, SummaryKey::new(0, 0))); + let stored = first.summary(path).expect("inserted"); + let decoded = cache::summary_codec::decode(&cache::summary_codec::encode(stored)) + .expect("the summary round-trips"); + let restored = decoded + .declarations + .iter() + .find(|fact| fact.name == "items") + .expect("the vector"); + assert_eq!( + restored + .type_of + .computed() + .map(|computed| computed.to_string()), + Some("std::vector".to_string()), + "the decoder restores the type value itself" + ); + + let mut second = ProjectIndex::new(); + second.insert(decoded); + let stored = second.summary(path).expect("re-inserted"); + let vector = stored + .declarations + .iter() + .find(|fact| fact.name == "items") + .expect("the vector declaration"); + assert_eq!( + vector + .type_of + .computed() + .map(|computed| computed.to_string()), + Some("std::vector".to_string()) + ); + let function = stored + .declarations + .iter() + .find(|fact| fact.name == "f") + .expect("the function"); + let parameter = second + .parameter_facts_of(path, function) + .first() + .and_then(|parameter| second.parameter_type(parameter)) + .expect("a parameter"); + assert_eq!(parameter.to_string(), "double"); +} + +#[test] +fn a_function_detail_stores_its_parameter_types() { + let path = Path::new("/p/params.cpp"); + let mut index = ProjectIndex::new(); + index.insert(summarize( + path, + "int f(double value, const char* name);\n", + SummaryKey::new(0, 0), + )); + let stored = index.summary(path).expect("inserted"); + let function = stored + .declarations + .iter() + .find(|fact| fact.name == "f") + .expect("the function"); + assert!( + !function.parameters.is_none(), + "the fact has a parameter handle" + ); + assert_eq!( + stored.parameters.parameters(function.parameters).len(), + 2, + "the summary's parameter arena holds both" + ); + assert_eq!( + index.parameter_facts_of(path, function).len(), + 2, + "the index resolves the summary-local handle" + ); + let parameters = index.parameter_facts_of(path, function); + assert_eq!(parameters.len(), 2, "both parameters are CST facts"); + assert_eq!( + index + .parameter_type(¶meters[0]) + .expect("the parameter type was lowered") + .to_string(), + "double" + ); + assert_eq!( + index + .parameter_type(¶meters[1]) + .expect("the parameter type was lowered") + .to_string(), + "const char*" + ); + assert_eq!(parameters[0].name.as_deref(), Some("value")); + assert_eq!(parameters[1].name.as_deref(), Some("name")); + assert!(parameters[0].default_value.is_none()); + let types: Vec<_> = index + .parameter_facts_of(path, function) + .iter() + .filter_map(|parameter| index.parameter_type(parameter)) + .collect(); + assert_eq!(types.len(), 2, "both parameters resolve to a type"); + assert_eq!(types[0].to_string(), "double"); + assert_eq!(types[1].to_string(), "const char*"); +} + +/// **A repeated type is the same value on every fact**, and no table or intern count stands behind it. +#[test] +fn repeated_declarations_carry_the_same_type_value() { + let path = Path::new("/p/repeated.cpp"); + let source: String = (0..100) + .map(|at| format!("std::vector value{at};\n")) + .collect(); + let mut index = ProjectIndex::new(); + index.insert(summarize(path, &source, SummaryKey::new(0, 0))); + let stored = index.summary(path).expect("inserted"); + assert_eq!(stored.declarations.len(), 100); + let displayed: Vec = stored + .declarations + .iter() + .filter_map(|fact| fact.type_of.computed().map(|computed| computed.to_string())) + .collect(); + assert_eq!(displayed.len(), 100); + assert!( + displayed + .iter() + .all(|spelling| spelling == "std::vector"), + "every fact carries the same type value" + ); +} + #[test] fn a_declaration_in_an_included_header_is_found() { let index = index(&[ @@ -105,8 +468,8 @@ fn a_declaration_in_an_included_header_is_found() { panic!("the class in the included header must be found: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/widget.h")); - assert_eq!(definition.fact.name, "Widget"); + assert_eq!(the_file(&index, &definition), Path::new("/p/widget.h")); + assert_eq!(the_fact(&index, &definition).name, "Widget"); } /// **A name only a compiler can see is a name the index answers for — once the file is cooked.** @@ -131,7 +494,7 @@ fn a_declaration_a_macro_makes_is_found_once_the_file_is_cooked() { for (path, source) in files { let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0)); for include in &mut summary.includes { - include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling))); + include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling))); } let _ = source; index.insert(summary); @@ -184,8 +547,9 @@ fn a_declaration_a_macro_makes_is_found_once_the_file_is_cooked() { let Known::Yes(definition) = after else { panic!("the cooked reading declares it: {after:?}"); }; - assert_eq!(definition.file, api); - let written = &source[definition.fact.range.start_offset..definition.fact.range.end_offset()]; + assert_eq!(the_file(&index, &definition), api); + let written = &source[the_fact(&index, &definition).range.start_offset + ..the_fact(&index, &definition).range.end_offset()]; assert!( written.contains("DECLARE_HANDLE"), "the declaration is reported at the invocation: {written:?}" @@ -385,7 +749,7 @@ fn visibility_follows_a_chain_of_includes() { let Known::Yes(definition) = found else { panic!("a transitively included declaration is visible: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/deep.h")); + assert_eq!(the_file(&index, &definition), Path::new("/p/deep.h")); } #[test] @@ -404,7 +768,7 @@ fn the_files_own_declaration_wins_over_an_included_one() { let Known::Yes(definition) = found else { panic!("the local declaration wins: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/main.cpp")); + assert_eq!(the_file(&index, &definition), Path::new("/p/main.cpp")); } #[test] @@ -446,12 +810,12 @@ fn two_declarations_of_one_name_are_a_list_for_a_consumer_that_shows_one() { assert_eq!(found.found.len(), 2); assert_eq!(found.conditional, 0); assert_eq!( - found.found[0].file, + the_file(&index, &found.found[0]), Path::new("/p/one.h"), "the order is imposed (by file, then offset), so a client's peek list cannot reorder itself between \ two identical requests" ); - assert_eq!(found.found[1].file, Path::new("/p/two.h")); + assert_eq!(the_file(&index, &found.found[1]), Path::new("/p/two.h")); } /// **A bare name does not reach into a class** — the scope half of the key a name lookup needs. @@ -490,10 +854,10 @@ fn a_bare_name_does_not_reach_a_class_member() { found .found .iter() - .map(|definition| definition.file.display().to_string()) + .map(|definition| the_file(&index, definition).display().to_string()) .collect::>() ); - assert_eq!(found.found[0].file, Path::new("/p/stdio.h")); + assert_eq!(the_file(&index, &found.found[0]), Path::new("/p/stdio.h")); // **The unfiltered list is what a member fallback wants**, and the member is in it. // @@ -648,7 +1012,7 @@ fn a_declaration_behind_a_conditional_include_is_counted_not_offered() { }; assert_eq!(found.found.len(), 1); - assert_eq!(found.found[0].file, Path::new("/p/one.h")); + assert_eq!(the_file(&index, &found.found[0]), Path::new("/p/one.h")); assert_eq!( found.conditional, 1, "and the one that might also be there is counted, so the answer does not claim there is nothing else" @@ -695,8 +1059,8 @@ fn a_qualified_name_prefers_the_declaration_that_matches_it() { panic!("the qualified name must select one of them: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/a.h")); - assert_eq!(definition.fact.qualified_name(), "a::Widget"); + assert_eq!(the_file(&index, &definition), Path::new("/p/a.h")); + assert_eq!(the_fact(&index, &definition).qualified_name(), "a::Widget"); } #[test] @@ -735,7 +1099,7 @@ fn an_unconditional_include_beats_a_guarded_one() { let Known::Yes(definition) = found else { panic!("the unconditional path wins: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/real.h")); + assert_eq!(the_file(&index, &definition), Path::new("/p/real.h")); } #[test] @@ -747,7 +1111,7 @@ fn a_file_that_includes_nothing_sees_only_itself() { let Known::Yes(definition) = found else { panic!("{path} must find its own count: {found:?}"); }; - assert_eq!(definition.file, Path::new(path)); + assert_eq!(the_file(&index, &definition), Path::new(path)); } } @@ -763,7 +1127,7 @@ fn a_cycle_of_includes_does_not_hang_the_visibility_walk() { let Known::Yes(definition) = found else { panic!("a cycle must not stop a name being found: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/b.h")); + assert_eq!(the_file(&index, &definition), Path::new("/p/b.h")); } #[test] @@ -803,7 +1167,7 @@ fn reindexing_a_file_removes_the_edges_its_old_text_had() { SummaryKey::new(1, 0), ); for include in &mut edited.includes { - include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling))); + include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling))); } index.insert(edited); @@ -871,7 +1235,7 @@ fn analysed_while_typing( let mut summary = summarize(Path::new(from), source, SummaryKey::new(0, 0)); for include in &mut summary.includes { - include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling))); + include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling))); } index.insert(summary); @@ -894,14 +1258,15 @@ fn a_local_declaration_is_answered_without_looking_in_the_index() { &root, Path::new("/p/main.cpp"), at(source, "count = 1;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("the local must win: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/main.cpp")); + assert_eq!(the_file(&index, &definition), Path::new("/p/main.cpp")); assert!( - definition.fact.range.start_offset > at(source, "void f"), + the_fact(&index, &definition).range.start_offset > at(source, "void f"), "the jump goes to the local, not to the header" ); } @@ -941,6 +1306,7 @@ fn another_files_local_is_never_the_answer() { &root, Path::new("/p/main.cpp"), at(source, "helper();"), + &|at: usize| Some(at), ); assert!( @@ -972,13 +1338,14 @@ fn another_files_local_is_never_the_answer() { &root, Path::new("/p/main.cpp"), at(source, "Widget w;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("`Widget` is at file scope in the header: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/widget.h")); - assert!(!definition.fact.local); + assert_eq!(the_file(&index, &definition), Path::new("/p/widget.h")); + assert!(!the_fact(&index, &definition).local); } #[test] @@ -1010,9 +1377,9 @@ fn a_call_resolves_through_the_return_type_of_a_header() { let Known::Yes(definition) = found else { panic!("`w.inner()` returns an `Inner`, which declares `size`: {found:?}"); }; - assert_eq!(definition.fact.name, "size"); + assert_eq!(the_fact(&index, &definition).name, "size"); assert_eq!( - definition.file, + the_file(&index, &definition), Path::new("/p/widget.h"), "the member is in the header, like everything else on this chain" ); @@ -1036,13 +1403,14 @@ fn a_name_only_a_header_declares_is_found_through_the_index() { &root, Path::new("/p/main.cpp"), at(source, "Widget w;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("the header's class must be found: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/widget.h")); - assert_eq!(definition.fact.name, "Widget"); + assert_eq!(the_file(&index, &definition), Path::new("/p/widget.h")); + assert_eq!(the_fact(&index, &definition).name, "Widget"); } #[test] @@ -1066,13 +1434,14 @@ fn a_qualified_name_resolves_into_an_included_header() { &root, Path::new("/p/main.cpp"), at(source, "Widget w;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("the header's `a::Widget` must be found: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/a.h")); - assert_eq!(definition.fact.qualified_name(), "a::Widget"); + assert_eq!(the_file(&index, &definition), Path::new("/p/a.h")); + assert_eq!(the_fact(&index, &definition).qualified_name(), "a::Widget"); } #[test] @@ -1096,6 +1465,7 @@ fn a_qualified_name_is_not_answered_by_a_same_named_declaration_elsewhere() { &root, Path::new("/p/main.cpp"), at(source, "Widget w;"), + &|at: usize| Some(at), ); assert!( @@ -1127,13 +1497,14 @@ fn a_global_spelling_does_not_match_a_namespaced_declaration() { &root, Path::new("/p/main.cpp"), at(source, "Widget w;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("the global `Widget` is the one asked for: {found:?}"); }; - assert_eq!(definition.fact.scope, None); - assert_eq!(definition.fact.name, "Widget"); + assert_eq!(the_fact(&index, &definition).scope, None); + assert_eq!(the_fact(&index, &definition).name, "Widget"); } // ------------------------------------------------------------------------------------------- @@ -1146,24 +1517,41 @@ fn a_global_spelling_does_not_match_a_namespaced_declaration() { // ------------------------------------------------------------------------------------------- /// The member a `needle` position names, with the file analysed and indexed the way a real query has it. +/// +/// The answer comes back as a [`ProjectMember`] rather than a [`ProjectDefinition`] because that is the shape these +/// tests read: the definition is a reference now, and the fact and path are resolved through the index that issued +/// it — which is the same step a consumer makes. fn member_of( files: &[(&str, &str)], from: &str, source: &str, needle: &str, -) -> Known { +) -> Known { let (index, tree) = analysed(files, from, source); let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); - member_across_files( + match member_across_files( &index, &mut |_: &Path| None, &scopes, &root, Path::new(from), at(source, needle), - ) + ) { + Known::Yes(found) => { + let row = ProjectMember { + fact: found.fact, + substitution: None, + declared_in: String::new(), + depth: 0, + ambiguous: false, + }; + Known::Yes(ResolvedMember::resolve(&index, row)) + } + Known::Unknown(reason) => Known::Unknown(reason), + Known::No => Known::No, + } } // ------------------------------------------------------------------------------------------- @@ -1301,9 +1689,9 @@ fn an_alias_to_a_non_class_is_not_a_member_lookup() { #[test] fn a_function_pointer_typedef_records_the_whole_type() { - // `typedef void (*F)(int);` — the type is the specifiers *and* the declarator with the alias's own name - // cut out, which is `void (*)(int)`. Reading only the specifiers would give `void`, and reading the - // declarator without cutting would give a type whose *name* is `F`. + // `typedef void (*F)(int);` — the type is a pointer to a function taking an `int` and returning `void`, shown + // canonically as `void(int)*`. Reading only the specifiers would give `void`, and reading the declarator + // without cutting the name out would give a type whose *name* is `F`. let source = "typedef void (*F)(int);\nvoid f() {\n F callback;\n callback();\n}\n"; let (index, tree) = analysed(&[], "/p/a.cpp", source); let root = tree.get_red_root(); @@ -1312,9 +1700,9 @@ fn a_function_pointer_typedef_records_the_whole_type() { panic!("the alias is a fact") }; assert_eq!( - fact.fact.type_of.as_deref(), - Some("void (*)(int)"), - "specifiers plus declarator minus the name" + index.type_spelling_of(the_fact(&index, &fact)).as_deref(), + Some("void(int)*"), + "a pointer to a function, not a function returning a pointer" ); // And a `typedef` of a plain type needs no such surgery. @@ -1323,7 +1711,10 @@ fn a_function_pointer_typedef_records_the_whole_type() { let Known::Yes(fact) = index.definition("String", Path::new("/p/b.cpp")) else { panic!("the alias is a fact") }; - assert_eq!(fact.fact.type_of.as_deref(), Some("basic_string")); + assert_eq!( + index.type_spelling_of(the_fact(&index, &fact)).as_deref(), + Some("basic_string") + ); let _ = (root, tree); } @@ -1339,11 +1730,17 @@ fn a_complex_type_keeps_the_adjective_in_its_spelling() { let Known::Yes(z) = index.definition("z", Path::new("/p/a.c")) else { panic!("`z` is a declaration") }; - assert_eq!(z.fact.type_of.as_deref(), Some("_Complex double")); + assert_eq!( + index.type_spelling_of(the_fact(&index, &z)).as_deref(), + Some("_Complex double") + ); let Known::Yes(w) = index.definition("w", Path::new("/p/a.c")) else { panic!("`w` is a declaration") }; - assert_eq!(w.fact.type_of.as_deref(), Some("double _Complex")); + assert_eq!( + index.type_spelling_of(the_fact(&index, &w)).as_deref(), + Some("double _Complex") + ); } #[test] @@ -1365,7 +1762,7 @@ fn a_gnu_label_declaration_binds_labels_not_variables() { DeclKind::Other, "`{name}` is a label, not a variable" ); - assert_eq!(fact.type_of, None, "a label writes no type"); + assert!(!fact.has_type_of(), "a label writes no type"); } } @@ -1459,8 +1856,8 @@ fn a_member_access_reaches_a_class_in_an_included_header() { let Known::Yes(member) = found else { panic!("the member declared in the header is the answer: {found:?}"); }; - assert_eq!(member.file, Path::new("/p/widget.h")); - assert_eq!(member.fact.name, "size"); + assert_eq!(the_file(&index, &member), Path::new("/p/widget.h")); + assert_eq!(the_fact(&index, &member).name, "size"); } #[test] @@ -1505,7 +1902,7 @@ fn a_member_access_on_a_call_is_the_callees_return_type() { panic!("`make()` returns a `Widget`, so `size` is its member: {found:?}"); }; assert_eq!(definition.fact.name, "size"); - assert_eq!(definition.fact.type_of.as_deref(), Some("int")); + assert_eq!(definition.type_of.as_deref(), Some("int")); // The other reading of the same tokens: `Widget()` is a **temporary** of the class rather than a call of // anything, and the declaration is what says which one this is. @@ -1865,8 +2262,8 @@ fn a_member_inherited_across_a_header_resolves() { let Known::Yes(member) = found else { panic!("the inherited member is declared in the header: {found:?}"); }; - assert_eq!(member.file, Path::new("/p/base.h")); - assert_eq!(member.fact.name, "size"); + assert_eq!(the_file(&index, &member), Path::new("/p/base.h")); + assert_eq!(the_fact(&index, &member).name, "size"); } #[test] @@ -1930,12 +2327,13 @@ fn a_local_declaration_still_wins_when_the_header_also_has_the_name() { &root, Path::new("/p/main.cpp"), at(source, "count = 1;"), + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("the file's own declaration wins: {found:?}"); }; - assert_eq!(definition.file, Path::new("/p/main.cpp")); + assert_eq!(the_file(&index, &definition), Path::new("/p/main.cpp")); } // ------------------------------------------------------------------------------------------- @@ -1946,22 +2344,96 @@ fn a_local_declaration_still_wins_when_the_header_also_has_the_name() { // staleness test at the end is the reason none of it is stored. // ------------------------------------------------------------------------------------------- +/// **A member row as these tests read it**: the reference row plus the declaration and file the index resolves it to. +/// +/// A [`ProjectMember`] no longer owns its `DeclFact` or its path — it names them — so a test that asserts on the +/// declaration resolves it through the index that issued the row, exactly as a consumer does. The resolved fields +/// keep the assertions in this file about what they were always about: the declaration the row names. +#[derive(Debug)] +struct ResolvedMember { + fact: DeclFact, + /// **The display form of the fact's type**, produced here at the test's own display edge: the stored handle is + /// printed by the index, a substituted display copy's computed value is printed directly. + type_of: Option, + file: PathBuf, + declared_in: String, + depth: usize, + ambiguous: bool, +} + +impl ResolvedMember { + fn resolve(index: &ProjectIndex, row: ProjectMember) -> ResolvedMember { + let fact = index + .member_display_fact(&row) + .expect("a member row names a declaration the index holds"); + let type_of = index + .type_spelling_of(&fact) + .map(|spelled| spelled.to_string()); + let file = index + .member_path(&row) + .expect("a member row names a file the index holds") + .to_path_buf(); + ResolvedMember { + fact, + type_of, + file, + declared_in: row.declared_in.clone(), + depth: row.depth, + ambiguous: row.ambiguous, + } + } +} + +/// A [`MemberList`] with every row resolved — see [`ResolvedMember`]. +#[derive(Debug)] +struct ResolvedList { + members: Vec, + unlisted: Vec, +} + +impl ResolvedList { + fn resolve(index: &ProjectIndex, list: MemberList) -> ResolvedList { + ResolvedList { + members: list + .members + .into_iter() + .map(|row| ResolvedMember::resolve(index, row)) + .collect(), + unlisted: list.unlisted, + } + } + + fn own(&self) -> impl Iterator { + self.members.iter().filter(|member| member.depth == 0) + } + + fn at_depth(&self, depth: usize) -> impl Iterator { + self.members + .iter() + .filter(move |member| member.depth == depth) + } +} + /// The members of `class`, with the file analysed and indexed the way a real query has them. fn members_of_class( files: &[(&str, &str)], from: &str, source: &str, class: &str, -) -> Known { +) -> Known { let (index, tree) = analysed(files, from, source); let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); - members_of(&index, &scopes, &root, Path::new(from), class) + match members_of(&index, &scopes, &root, Path::new(from), class) { + Known::Yes(list) => Known::Yes(ResolvedList::resolve(&index, list)), + Known::Unknown(reason) => Known::Unknown(reason), + Known::No => Known::No, + } } /// The member names, in the order the query produced them. -fn names(list: &MemberList) -> Vec<&str> { +fn names(list: &ResolvedList) -> Vec<&str> { list.members .iter() .map(|member| member.fact.name.as_str()) @@ -2045,17 +2517,18 @@ fn an_elaborated_type_specifier_does_not_declare_the_tag() { &root, Path::new("/p/bits.c"), at(source, "struct bits make_bits") + 7, + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("`struct bits` names the header's type: {found:?}"); }; assert_eq!( - definition.file, + the_file(&index, &definition), Path::new("/p/corpus.h"), "the jump goes to the definition, not to this file's `make_bits`" ); - assert_eq!(definition.fact.name, "bits"); + assert_eq!(the_fact(&index, &definition).name, "bits"); } #[test] @@ -2075,17 +2548,18 @@ fn an_elaborated_enum_specifier_does_not_declare_the_tag() { &root, Path::new("/p/bits.c"), at(source, "enum Color pick") + 5, + &|at: usize| Some(at), ); let Known::Yes(definition) = found else { panic!("`enum Color` names the header's enumeration: {found:?}"); }; assert_eq!( - definition.file, + the_file(&index, &definition), Path::new("/p/corpus.h"), "the jump goes to the definition, not to this file's `pick`" ); - assert_eq!(definition.fact.name, "Color"); + assert_eq!(the_fact(&index, &definition).name, "Color"); } #[test] @@ -2153,7 +2627,7 @@ fn a_class_lists_the_members_written_in_it() { assert!(!size.ambiguous); assert_eq!(size.file, Path::new("/p/a.cpp")); assert_eq!( - size.fact.type_of.as_deref(), + size.type_of.as_deref(), Some("int"), "the type a completion shows beside the name" ); @@ -2190,7 +2664,7 @@ fn a_derived_class_lists_its_own_members_before_the_ones_it_inherits() { ); assert_eq!(list.members[1].depth, 1); assert_eq!( - list.members[1].fact.type_of.as_deref(), + list.members[1].type_of.as_deref(), Some("int"), "and it carries its own declaration's type" ); @@ -2215,7 +2689,7 @@ fn a_member_the_class_redeclares_hides_the_one_in_its_base() { "one `size`, and it is the derived class's" ); assert_eq!(list.members[0].declared_in, "Derived"); - assert_eq!(list.members[0].fact.type_of.as_deref(), Some("double")); + assert_eq!(list.members[0].type_of.as_deref(), Some("double")); } #[test] @@ -2233,7 +2707,7 @@ fn a_name_two_bases_declare_is_listed_twice_and_marked_ambiguous() { assert_eq!(names(&list), ["own", "value", "value"]); - let values: Vec<&ProjectMember> = list + let values: Vec<&ResolvedMember> = list .members .iter() .filter(|member| member.fact.name == "value") @@ -2274,7 +2748,7 @@ fn a_destructor_hides_nothing_in_a_base_because_its_spelling_is_its_own() { panic!("`Derived` is declared in this file: {found:?}"); }; - let destructors: Vec<&ProjectMember> = list + let destructors: Vec<&ResolvedMember> = list .members .iter() .filter(|member| member.fact.name.starts_with('~')) @@ -2399,7 +2873,7 @@ fn a_template_class_lists_the_members_it_was_written_with() { assert_eq!(names(&list), ["count", "value"]); assert_eq!( - list.members[1].fact.type_of.as_deref(), + list.members[1].type_of.as_deref(), Some("T"), "the parameter as written, not an instantiated type" ); @@ -2470,6 +2944,7 @@ fn a_member_list_crosses_a_header_and_keeps_the_base_tagged() { let Known::Yes(list) = found else { panic!("`Derived` is declared in the buffer: {found:?}"); }; + let list = ResolvedList::resolve(&index, list); assert_eq!(names(&list), ["d", "size"]); assert_eq!(list.members[1].file, Path::new("/p/base.h")); @@ -2495,7 +2970,7 @@ fn a_base_that_resolves_to_a_template_is_listed_without_instantiating_it() { assert_eq!(names(&list), ["d", "size"]); assert_eq!( - list.members[1].fact.type_of.as_deref(), + list.members[1].type_of.as_deref(), Some("int"), "the base's parameter is substituted: {list:?}" ); @@ -2622,7 +3097,7 @@ fn a_member_added_to_a_base_appears_without_reindexing_the_derived_class() { Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| index.member_name(member).to_string()) .collect::>(), other => panic!("`A` is declared in an included header: {other:?}"), }; @@ -2632,7 +3107,7 @@ fn a_member_added_to_a_base_appears_without_reindexing_the_derived_class() { // `b.h` and nothing else. `a.h` keeps the summary it was built with, which is the whole point. let mut rebuilt = summarize(Path::new("/p/b.h"), after, SummaryKey::new(1, 0)); for include in &mut rebuilt.includes { - include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling))); + include.resolved = Some(PathBuf::from(format!("/p/{}", include.spelling))); } index.insert(rebuilt); @@ -2677,25 +3152,51 @@ fn after(source: &str, needle: &str) -> usize { + needle.len() } +/// A [`MemberCompletions`] with every offered row resolved — see [`ResolvedMember`]. +#[derive(Debug)] +struct ResolvedCompletions { + class: String, + members: ResolvedList, + member_range: SourceRange, + prefix: String, + hidden_by_access: usize, +} + +impl ResolvedCompletions { + fn resolve(index: &ProjectIndex, completions: MemberCompletions) -> ResolvedCompletions { + ResolvedCompletions { + class: completions.class, + members: ResolvedList::resolve(index, completions.members), + member_range: completions.member_range, + prefix: completions.prefix, + hidden_by_access: completions.hidden_by_access, + } + } +} + /// The members offered at the cursor just past `needle`. fn completions_at( files: &[(&str, &str)], from: &str, source: &str, needle: &str, -) -> Known { +) -> Known { let (index, tree) = analysed_while_typing(files, from, source); let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); - member_completions_at( + match member_completions_at( &index, &mut |_: &Path| None, &scopes, &root, Path::new(from), after(source, needle), - ) + ) { + Known::Yes(completions) => Known::Yes(ResolvedCompletions::resolve(&index, completions)), + Known::Unknown(reason) => Known::Unknown(reason), + Known::No => Known::No, + } } /// **A `private` member is not offered from outside the class**, and is offered from inside it. @@ -3016,6 +3517,7 @@ fn the_members_offered_cross_a_header() { let Known::Yes(completions) = found else { panic!("the class is in the included header: {found:?}"); }; + let completions = ResolvedCompletions::resolve(&index, completions); assert_eq!(completions.class, "Widget"); assert_eq!( completions.members.members[0].file, @@ -3224,30 +3726,38 @@ fn a_jump_on_a_member_that_is_not_written_yet_has_nothing_to_jump_to() { // ------------------------------------------------------------------------------------------- /// The names offered at the cursor just past `needle`. +/// +/// The **index comes back with the answer**: an [`OfferedName`] names a declaration rather than carrying one, so +/// resolving a name's spelling is a question for the index it was asked of. fn names_at( files: &[(&str, &str)], from: &str, source: &str, needle: &str, -) -> Known { +) -> (ProjectIndex, Known) { let (index, tree) = analysed_while_typing(files, from, source); let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); - name_completions_at( + let found = name_completions_at( &index, &scopes, &root, Path::new(from), after(source, needle), - ) + ); + (index, found) } /// The names offered at the **first offset of the body** of `source` — where nothing is written yet. /// /// The position with no prefix, which is a different question from [`names_at`]'s and cannot be spelled as one: /// a needle is what a test looks for, and "the cursor is at the start of a line" is not a spelling. -fn names_at_blank(files: &[(&str, &str)], from: &str, source: &str) -> Known { +fn names_at_blank( + files: &[(&str, &str)], + from: &str, + source: &str, +) -> (ProjectIndex, Known) { let (index, tree) = analysed_while_typing(files, from, source); let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); @@ -3257,17 +3767,18 @@ fn names_at_blank(files: &[(&str, &str)], from: &str, source: &str) -> Known) -> Vec { +fn offered(index: &ProjectIndex, found: &Known) -> Vec { match found { Known::Yes(completions) => completions .names .iter() - .map(|name| name.fact.name.to_string()) + .map(|name| index.offered_name(name).to_string()) .collect(), other => panic!("expected names: {other:?}"), } @@ -3302,8 +3813,8 @@ fn a_name_in_a_late_file_of_a_namespace_is_still_offered() { ("/p/a.cpp", source), ]; - let found = names_at(&files, "/p/a.cpp", source, "ns::"); - let names = offered(&found); + let (index, found) = names_at(&files, "/p/a.cpp", source, "ns::"); + let names = offered(&index, &found); assert!( names.iter().any(|name| name == "zebra"), @@ -3333,8 +3844,8 @@ fn the_members_of_a_class_template_reached_through_an_alias_are_offered() { let source = "#include \"basic.h\"\nvoid f() {\n ns::String::\n}\n"; let files = [("/p/basic.h", header), ("/p/a.cpp", source)]; - let found = names_at(&files, "/p/a.cpp", source, "ns::String::"); - let names = offered(&found); + let (index, found) = names_at(&files, "/p/a.cpp", source, "ns::String::"); + let names = offered(&index, &found); assert!( names.iter().any(|name| name == "size") && names.iter().any(|name| name == "data"), @@ -3346,10 +3857,10 @@ fn the_members_of_a_class_template_reached_through_an_alias_are_offered() { fn a_qualified_scope_offers_the_names_written_in_it() { let source = "namespace ns {\n struct Widget { };\n int helper();\n}\nvoid f() {\n ns::\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "ns::"); + let (index, found) = names_at(&[], "/p/a.cpp", source, "ns::"); assert_eq!( - offered(&found), + offered(&index, &found), ["Widget", "helper"], "sorted within the scope" ); @@ -3371,7 +3882,8 @@ fn a_half_typed_name_keeps_the_prefix_and_replaces_the_whole_segment() { // The two halves of one edit, as in the member query: the range covers what the client replaces (`Wid`), // and the prefix is what it filters by — the part before the cursor. let source = "namespace ns {\n struct Widget { };\n}\nvoid f() {\n ns::Wid\n}\n"; - let Known::Yes(completions) = names_at(&[], "/p/a.cpp", source, "ns::Wid") else { + let (_, found) = names_at(&[], "/p/a.cpp", source, "ns::Wid"); + let Known::Yes(completions) = found else { panic!("the cursor is on the name being typed"); }; @@ -3392,10 +3904,10 @@ fn a_class_scope_offers_its_members_and_the_ones_its_bases_declare() { let source = "struct Base {\n typedef int size_type;\n};\n\ struct Derived : Base {\n typedef int value_type;\n};\n\ void f() {\n Derived::\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "Derived::"); + let (index, found) = names_at(&[], "/p/a.cpp", source, "Derived::"); assert_eq!( - offered(&found), + offered(&index, &found), ["value_type", "size_type"], "the class's own names first, then the ones a base declares" ); @@ -3421,15 +3933,15 @@ fn a_global_scope_offers_only_what_is_declared_at_file_scope() { // and namespace included, because those are written there. let source = "int global;\nnamespace ns {\n int inner;\n}\nvoid f() {\n int local;\n ::\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "::"); + let (index, found) = names_at(&[], "/p/a.cpp", source, "::"); - assert_eq!(offered(&found), ["f", "global", "ns"]); + assert_eq!(offered(&index, &found), ["f", "global", "ns"]); let Known::Yes(completions) = found else { unreachable!("asserted above") }; assert_eq!(completions.scope, "::", "the global name space, as spelled"); - let names = offered(&Known::Yes(completions.clone())); + let names = offered(&index, &Known::Yes(completions.clone())); assert!( !names.contains(&"inner".to_string()) && !names.contains(&"local".to_string()), "a namespace member and a local are not in the global name space: {names:?}" @@ -3442,10 +3954,10 @@ fn a_bare_name_offers_the_scopes_the_cursor_is_inside_innermost_first() { // then the namespace's, then the file's. let source = "int at_file_scope;\nnamespace ns {\n int in_a_namespace;\n struct C {\n int member;\n \ void g() {\n int local;\n loc\n }\n };\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "loc"); + let (index, found) = names_at(&[], "/p/a.cpp", source, "loc"); assert_eq!( - offered(&found), + offered(&index, &found), [ // depth 0: the body the cursor is in "local", @@ -3485,9 +3997,9 @@ fn another_files_local_is_not_offered_by_a_bare_name() { let header = "/p/widget.h"; let declaration = "void g() {\n int __first = 0;\n int helper;\n}\nint global_name;\n"; let source = "#include \"widget.h\"\nvoid f() {\n int mine;\n min\n}\n"; - let found = names_at(&[(header, declaration)], "/p/main.cpp", source, "min"); + let (index, found) = names_at(&[(header, declaration)], "/p/main.cpp", source, "min"); - let names = offered(&found); + let names = offered(&index, &found); assert!( names.contains(&"mine".to_string()), "the local of *this* file is offered, from its own scopes: {names:?}" @@ -3501,8 +4013,8 @@ fn another_files_local_is_not_offered_by_a_bare_name() { // ranking: `global_name` cannot be completed from `min`, and a client would drop it. So the same question // is asked once more at the **blank** position the feature exists for, which is where the file-scope name // has to appear — asking it at `min` would be asserting two things at once. - let at_a_blank = names_at_blank(&[(header, declaration)], "/p/main.cpp", source); - let names = offered(&at_a_blank); + let (index, at_a_blank) = names_at_blank(&[(header, declaration)], "/p/main.cpp", source); + let names = offered(&index, &at_a_blank); assert!( names.contains(&"global_name".to_string()), "…while a file-scope name in the same header is offered where nothing is typed: {names:?}" @@ -3515,14 +4027,14 @@ fn a_namespace_is_merged_across_the_buffer_and_the_header() { // answer — the difference from a class, which is defined once and listed from one place. let source = "#include \"ns.h\"\nnamespace ns {\n int in_the_buffer;\n}\nvoid f() {\n ns::\n}\n"; - let found = names_at( + let (index, found) = names_at( &[("/p/ns.h", "namespace ns {\n int in_the_header;\n}\n")], "/p/main.cpp", source, "ns::", ); - assert_eq!(offered(&found), ["in_the_buffer", "in_the_header"]); + assert_eq!(offered(&index, &found), ["in_the_buffer", "in_the_header"]); } #[test] @@ -3530,7 +4042,7 @@ fn a_scope_nothing_declares_is_not_an_empty_list() { // "Declared and empty" and "no such scope" are different answers, and the second one is what stops a // consumer from reporting that the user is looking at a namespace with nothing in it. let source = "void f() {\n nowhere::\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "nowhere::"); + let (_, found) = names_at(&[], "/p/a.cpp", source, "nowhere::"); assert!( matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))), @@ -3551,7 +4063,7 @@ fn a_cursor_where_a_name_can_be_written_offers_the_visible_names() { // The cursor is just past the name `Widget` — the position a client reports when the user puts the cursor // on the identifier and presses the completion key. let source = "struct Widget { int size; };\nvoid f() {\n Widget w;\n}\n"; - let found = names_at(&[], "/p/a.cpp", source, "Widget"); + let (index, found) = names_at(&[], "/p/a.cpp", source, "Widget"); let Known::Yes(found) = found else { panic!("a name can be written here: {found:?}"); @@ -3559,7 +4071,7 @@ fn a_cursor_where_a_name_can_be_written_offers_the_visible_names() { let names: Vec<&str> = found .names .iter() - .map(|offered| offered.fact.name.as_str()) + .map(|offered| index.offered_name(offered)) .collect(); assert!( names.contains(&"Widget") && names.contains(&"f"), @@ -4044,7 +4556,7 @@ fn a_body_edit_keeps_the_completion_snapshot() { let after = "#include \"widget.h\"\nvoid f() { int b = 2; }\n"; let mut summary = summarize(Path::new(main), before, SummaryKey::new(0, 0)); for include in &mut summary.includes { - include.resolved = Some(std::path::PathBuf::from("/p/widget.h")); + include.resolved = Some(PathBuf::from("/p/widget.h")); } index.insert(header); index.insert(summary); @@ -4062,7 +4574,7 @@ fn a_body_edit_keeps_the_completion_snapshot() { index.forget(Path::new(main)); let mut edited = summarize(Path::new(main), after, SummaryKey::new(0, 1)); for include in &mut edited.includes { - include.resolved = Some(std::path::PathBuf::from("/p/widget.h")); + include.resolved = Some(PathBuf::from("/p/widget.h")); } index.insert(edited); let second = index.completion_visible_declarations(Path::new(main)); @@ -4196,3 +4708,149 @@ fn declaration_accounting_separates_boxed_details() { "the boxed detail has a measured cost: {accounting:?}" ); } + +/// **A view fact's parameters resolve through the index before the file has a summary.** +/// +/// A buffer between an edit and the pump's read has no `FileSummary`, so there is no `ParamsStore` to intern a member +/// function's parameters into. The index's synthetic arena carries the list beside the fact, and this pins the two +/// questions a consumer asks: by fact ([`ProjectIndex::parameter_facts_of`]) and by offset +/// ([`ProjectIndex::parameter_facts_at`]). The fact's own `ParamsId` is `NONE` — that is the mechanism, not a gap: a +/// second store would collide with the summary's. +#[test] +fn a_view_facts_parameters_resolve_through_the_synthetic_arena() { + let source = "struct Widget {\n void resize(int width, int height);\n};\n"; + let tree = CppParser::parse(source, ParserConfig::default()); + let root = tree.get_red_root(); + let scopes = build_scopes(&root, &NoMacroBodies); + let index = ProjectIndex::new(); + let path = Path::new("/p/view.cpp"); + + let Known::Yes(listed) = members_of(&index, &scopes, &root, path, "Widget") else { + panic!("a class in the buffer lists its members"); + }; + let member = listed + .members + .iter() + .find(|member| index.member_name(member) == "resize") + .expect("the function is a member"); + let fact = index + .member_fact(member) + .expect("the row names an arena entry"); + assert_eq!( + fact.parameters, + crate::index::params::ParamsId::NONE, + "a view fact has no summary table to name" + ); + + let parameters = index.parameter_facts_of(path, fact); + assert_eq!(parameters.len(), 2, "both parameters came back"); + assert_eq!(parameters[0].name.as_deref(), Some("width")); + assert_eq!(parameters[1].name.as_deref(), Some("height")); + assert_eq!( + index + .parameter_facts_at(path, fact.name_range.start_offset) + .len(), + 2, + "and the offset question answers from the same arena" + ); + // **A clone of the interned fact answers too** — a completion holds `member_fact(...).clone()`. + let copied = fact.clone(); + let parameters = index.parameter_facts_of(path, &copied); + assert_eq!(parameters.len(), 2); + assert_eq!(parameters[0].name.as_deref(), Some("width")); +} + +/// **A view fact carries the list-level `...` itself**, because no `ParamsStore` does. +/// +/// The synthetic arena holds a view's parameter list and nothing else — the variadic bit is +/// [`crate::DeclFact::variadic_parameters`], read from the same `CppParamList` the parameters came from. `void +/// log(const char*, ...)` is true with one parameter; `void forwards(double... rest)` is false because its `...` is +/// the parameter's own pack marker; and a plain member is false. +#[test] +fn a_view_fact_carries_the_lists_variadic_bit() { + let source = "\ +struct Widget { + void log(const char* format, ...); + void forwards(double... rest); + void fixed(int value); +}; +"; + let tree = CppParser::parse(source, ParserConfig::default()); + let root = tree.get_red_root(); + let scopes = build_scopes(&root, &NoMacroBodies); + let index = ProjectIndex::new(); + let path = Path::new("/p/view_variadic.cpp"); + + let Known::Yes(listed) = members_of(&index, &scopes, &root, path, "Widget") else { + panic!("a class in the buffer lists its members"); + }; + let fact = |name: &str| { + let member = listed + .members + .iter() + .find(|member| index.member_name(member) == name) + .unwrap_or_else(|| panic!("{name} must be a member")); + index + .member_fact(member) + .unwrap_or_else(|| panic!("{name} names an arena entry")) + }; + + let log = fact("log"); + assert!( + log.variadic_parameters, + "the view builder reads the same list token the summary builder does" + ); + assert_eq!( + index.parameter_facts_of(path, log).len(), + 1, + "and the marker is not one of the parameters" + ); + + let forwards = fact("forwards"); + assert!( + !forwards.variadic_parameters, + "a pack is the parameter's marker, not the list's" + ); + assert!(index.parameter_facts_of(path, forwards)[0].pack); + + assert!( + !fact("fixed").variadic_parameters, + "an ordinary list is not variadic" + ); +} + +/// **A cooked fact's `ParamsId` names its reading's own parameter table**, not the summary's. +/// +/// The two readings of this file declare one `f` at the same place with different parameters — the rendering is what +/// a compiler sees, and a macro may well change the list. Resolving the cooked fact against the summary's table would +/// answer `other`; the reading's table answers `value`, which is the whole point of the table travelling with it. +#[test] +fn a_cooked_facts_parameters_resolve_through_its_own_reading() { + let path = "/p/params_cooked.cpp"; + let mut index = index(&[(path, "int f(int other);\n")]); + let cooked = cooked_reading_of(path, "int f(double value);\n"); + index.insert_cooked(Path::new(path), cooked); + + let reading = index + .cooked_reading(Path::new(path)) + .expect("the reading is filed"); + let fact = reading + .declarations + .iter() + .find(|fact| fact.name == "f") + .expect("the function is in the reading"); + let parameters = index.parameter_facts_of(Path::new(path), fact); + assert_eq!(parameters.len(), 1); + assert_eq!( + parameters[0].name.as_deref(), + Some("value"), + "the reading's table answers, not the summary's `other`" + ); + assert_eq!( + index + .parameter_type(¶meters[0]) + .expect("the parameter's type was imported with the reading") + .to_string(), + "double" + ); +} diff --git a/crates/cpp_code_analysis/src/index/project/type_of.rs b/crates/cpp_code_analysis/src/index/project/type_of.rs index ec47d598..51df53cb 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -16,11 +16,12 @@ use crate::ScopeTree; use crate::cache; use crate::completion; use crate::file; +use crate::index::types::{ComputedType, QualifiedType}; use crate::sema; +use crate::sema::types::TypeSubstitutions; use crate::symbol; use cpp_parser::CppSyntaxNode; use cpp_parser::CppTokenKind; -use smol_str::SmolStr; /// How deep the type question may ask itself before it gives up. /// @@ -54,6 +55,13 @@ pub(crate) const MAX_TYPE_DEPTH: usize = 24; /// **How many inference answers the index keeps** — see `ProjectIndex::type_answers`. pub(crate) const MAX_TYPE_ANSWERS: usize = 8192; +/// **The computed type of a fact**, from its stored handle or its synthetic computed value. This is the one reader +/// the inference engine uses: the fact's type is materialized once (no spelling, no store write), and there is no +/// conversion because [`ComputedType`] is the only type definition. +pub(crate) fn the_type_of_a_fact(index: &ProjectIndex, fact: &DeclFact) -> Option { + index.computed_type_of(fact) +} + /// **What an inference answer is a function of**, as one number: the file, the expression's range, its kind and its text. /// /// The range is part of it on purpose: the same spelling at two places is two questions (`Widget` inside a class and @@ -132,7 +140,7 @@ pub(crate) fn type_of_expression( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { // **One memo per entry point**, which is the smallest scope that already removes the duplication: the questions // asked *inside* one expression are the ones that repeat. A caller that asks about many expressions shares a // larger memo by calling [`type_of_expression_memoed`] itself — see `SemanticModel`. @@ -157,7 +165,7 @@ pub(crate) fn type_of_expression( /// memo of the *lookup*, not of the answer's use: each caller still gets its own `DeclFact` clone. #[derive(Default)] pub(crate) struct TypeMemo { - types: std::cell::RefCell>>, + types: std::cell::RefCell>>, /// **The questions being answered right now** — see [`TypeMemo::enter`]. Keyed like `types`, because a node is /// unique within one tree and a tree is not mutated while a query runs. in_flight: std::cell::RefCell>, @@ -166,7 +174,10 @@ pub(crate) struct TypeMemo { impl TypeMemo { /// **The type of a node already asked about, if it was.** - pub(crate) fn remembered_type(&self, key: &(u32, u32)) -> Option> { + pub(crate) fn remembered_type( + &self, + key: &(u32, u32), + ) -> Option> { self.types.borrow().get(key).cloned() } @@ -233,7 +244,7 @@ pub(crate) fn type_of_expression_memoed( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { let range = expression.text_range(); let key = ( u32::try_from(usize::from(range.start())).unwrap_or(u32::MAX), @@ -297,7 +308,7 @@ pub(crate) fn type_of_expression_inner( path: &Path, expression: &CppSyntaxNode, depth: usize, -) -> Known<(Type, PathBuf)> { +) -> Known<(ComputedType, PathBuf)> { let text = expression.text().to_string(); let written = text.trim(); @@ -353,7 +364,7 @@ pub(crate) fn type_of_expression_inner( depth + 1, ); if let Known::Yes((awaiter, _)) = awaited - && let Some(returns) = operator_returns_of( + && let Some(settled) = operator_returns_of( index, declaring, scopes, @@ -362,9 +373,7 @@ pub(crate) fn type_of_expression_inner( &awaiter, "await_resume", ) - && !returns.trim().is_empty() { - let settled = parse_type_spelling(&returns); return Known::Yes((settled, path.to_path_buf())); } return Known::Unknown(UnknownReason::UnknownType(Box::from(written))); @@ -379,7 +388,7 @@ pub(crate) fn type_of_expression_inner( // The spelling is the standard's, and the header that declares it (``) is not one this machine has: the // answer names the type rather than resolving it, exactly as it would for a type from a header nobody read. if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::ReflectExpr { - let info = parse_type_spelling("std::meta::info"); + let info = ComputedType::named("std::meta::info", Vec::new()); return Known::Yes((info, path.to_path_buf())); } @@ -429,22 +438,19 @@ pub(crate) fn type_of_expression_inner( if kind == CppTokenKind::UserDefinedLiteral { // **An unknown answer says what is unknown**: the literal, with its suffix, rather than the whole // expression, because the suffix is the part that did not resolve. - let a_user_defined_literal_is = - |returns: String| Known::Yes((parse_type_spelling(&returns), path.to_path_buf())); if let Some(suffix) = a_user_defined_literals_suffix(&written_as) && let Some(declared) = index .files_declaring(&format!("operator\"\"{suffix}"), path) .into_iter() .find(|declared| declared.fact.kind == DeclKind::Function) - && let Some(returns) = declared.fact.returns.as_deref() - && !returns.trim().is_empty() + && let Some(returns) = index.computed_returns_of(declared.fact) { - return a_user_defined_literal_is(returns.to_string()); + return Known::Yes((returns, path.to_path_buf())); } return Known::Unknown(UnknownReason::UnknownType(Box::from(written))); } if let Some(spelled) = literal { - // **Parsed, not named.** `Type::named("int")` is a type whose *name* is `int` — a class as far as every + // **Parsed, not named.** `ComputedType::named("int")` is a type whose *name* is `int` — a class as far as every // later question is concerned — and the same for `const char*`. Measured: a string literal came back as // `Named { name: "const char*" }`, so `has an arithmetic type` was false for `int` and the conversion // relation answered `Unknown` for `int count = "three";`, which is the one pair it is certain about. @@ -517,7 +523,10 @@ pub(crate) fn type_of_expression_inner( .chars() .all(|character| !character.is_ascii_lowercase()) { - return Known::Yes((Type::named(callee.trim()), path.to_path_buf())); + return Known::Yes(( + ComputedType::named(callee.trim(), Vec::new()), + path.to_path_buf(), + )); } // `this` is the enclosing class, and no inference is involved: the scope chain already knows which class this @@ -526,7 +535,7 @@ pub(crate) fn type_of_expression_inner( if written == "this" { let offset = usize::from(expression.text_range().start()); return match class_of_the_enclosing_definition(scopes, offset) { - Some(class) => Known::Yes((Type::named(class), path.to_path_buf())), + Some(class) => Known::Yes((ComputedType::named(class, Vec::new()), path.to_path_buf())), None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), }; } @@ -544,7 +553,7 @@ pub(crate) fn type_of_expression_inner( if CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::NewExpr { return match new_expression_allocates(expression) { Some(allocated) => Known::Yes(( - parse_type_spelling(&format!("{allocated}*")), + ComputedType::Pointer(Arc::new(parse_type_spelling(&allocated))), path.to_path_buf(), )), None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), @@ -657,7 +666,7 @@ pub(crate) fn type_of_expression_inner( Known::Unknown(UnknownReason::UnknownType(Box::from(written))) } _ => match declaration_of_expression(index, scopes, root, path, &first) { - // **The spelling is read, not named.** `Type::named("Pair")` is a class whose *name* is + // **The spelling is read, not named.** `ComputedType::named("Pair")` is a class whose *name* is // `Pair` and whose argument list is empty — so nothing downstream substitutes: the member // lookup is handed that spelling, `TypeBindings` gets no arguments, and `sum`'s written `T` comes back as // `T`. `parse_type_spelling` is the crate's reader for a written type and answers @@ -726,11 +735,10 @@ pub(crate) fn type_of_expression_inner( .children() .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId); return match target { - Some(target) => { - let written = target.text().to_string(); - let written = written.trim(); - Known::Yes((parse_type_spelling(written), path.to_path_buf())) - } + Some(target) => match sema::types::type_of_a_type_id(&target) { + Some(type_of) => Known::Yes((type_of, path.to_path_buf())), + None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), + }, // A `CastExpr` with no type in it is one the recovery built around a keyword with nothing after it, // which is a file being typed at rather than a cast. None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), @@ -789,7 +797,10 @@ pub(crate) fn type_of_expression_inner( let spelled = expression.text().to_string(); let spelled = spelled.trim_start(); if spelled.starts_with("sizeof") || spelled.starts_with("alignof") { - return Known::Yes((parse_type_spelling("size_t"), path.to_path_buf())); + return Known::Yes(( + ComputedType::named("size_t", Vec::new()), + path.to_path_buf(), + )); } } @@ -887,25 +898,26 @@ pub(crate) fn type_of_expression_inner( path, &left, depth + 1, - ) && matches!(left_class, Type::Named { .. }) - && let Some(returns) = operator_returns_of( - index, - declaring, - scopes, - root, - path, - &left_class, - &format!("operator{operator}"), - ) - { - return Known::Yes((parse_type_spelling(&returns), file)); + ) && matches!( + left_class, + ComputedType::Named(_) | ComputedType::Generic(_) + ) && let Some(returns) = operator_returns_of( + index, + declaring, + scopes, + root, + path, + &left_class, + &format!("operator{operator}"), + ) { + return Known::Yes((returns, file)); } if matches!( operator.as_str(), "==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||" ) { - return Known::Yes((Type::named("bool"), path.to_path_buf())); + return Known::Yes((ComputedType::named("bool", Vec::new()), path.to_path_buf())); } let left_type = type_of_expression_memoed( @@ -933,6 +945,14 @@ pub(crate) fn type_of_expression_inner( }; }; + // **A `|` whose left operand is a class is a pipe, not bitwise or.** A standard adaptor was answered above; + // a project's own `items | filter(items)` is a call this layer does not model, and letting the arithmetic + // agreement below answer it reports the right operand's type as if the pipe were `a | b` on two integers. + // That is a wrong type where "nothing is known" is the true answer. + if operator == "|" && left_type.class_name().is_some() { + return Known::Unknown(UnknownReason::UnknownType(Box::from(written))); + } + return match type_of_expression_memoed( memo, shapes, @@ -998,7 +1018,12 @@ pub(crate) fn type_of_expression_inner( // below even though `pointee()` answers for it too: what `*` means for a class is what the class // declared, and a class that declared nothing is the iterator model's case. Some(pointee) - if !matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. }) => + if !matches!( + type_of, + ComputedType::Named(_) + | ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) + ) => { Known::Yes(((*pointee).clone(), file)) } @@ -1014,14 +1039,14 @@ pub(crate) fn type_of_expression_inner( &type_of, "operator*", ) { - return Known::Yes((parse_type_spelling(&returns), file)); + return Known::Yes((returns, file)); } // **The iterator model**, for a class with no `operator*` that came from `begin()`: it is a // view of its container's element, so `*it` is the element the type already is. match &type_of { - Type::Named { .. } | Type::TemplateParameter { .. } => { - Known::Yes((type_of, file)) - } + ComputedType::Named(_) + | ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) => Known::Yes((type_of, file)), // An operand whose type has no `*` on it: the program is ill-formed, and a type invented // here would be a wrong answer rather than a missing one. _ => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), @@ -1055,13 +1080,8 @@ pub(crate) fn type_of_expression_inner( // which matched nothing. A *function* is the one that does decay: `&f` and `f` are both pointers to // the function, so the wrap would give a pointer to a pointer. Known::Yes(match type_of { - Type::Function { .. } => (type_of.decay(), file), - other => ( - Type::Pointer { - to: Arc::new(other), - }, - file, - ), + ComputedType::Function(_) => (type_of.decay(), file), + other => (ComputedType::Pointer(Arc::new(other)), file), }) } Known::Unknown(reason) => Known::Unknown(reason), @@ -1097,21 +1117,24 @@ pub(crate) fn type_of_expression_inner( ); return match operand_type { Known::Yes((type_of, file)) => { - if matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. }) - && let Some(returns) = operator_returns_of( - index, - declaring, - scopes, - root, - path, - &type_of, - &format!("operator{symbol}"), - ) - { - return Known::Yes((parse_type_spelling(&returns), file)); + if matches!( + type_of, + ComputedType::Named(_) + | ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) + ) && let Some(returns) = operator_returns_of( + index, + declaring, + scopes, + root, + path, + &type_of, + &format!("operator{symbol}"), + ) { + return Known::Yes((returns, file)); } if symbol == "!" { - Known::Yes((Type::named("bool"), path.to_path_buf())) + Known::Yes((ComputedType::named("bool", Vec::new()), path.to_path_buf())) } else { Known::Yes((type_of, file)) } @@ -1199,10 +1222,10 @@ pub(crate) fn type_of_expression_inner( // **A pointer's subscript is the pointee.** `int* a; a[0]` is `*(a + 0)`, and C++ fixes its type as `int` // — no class, no instance, nothing this layer cannot read. Reported: `auto x = a[0];` answered "the type // of `a[0]` is not known here". - Some(element) if matches!(type_of, Type::Pointer { .. }) => { + Some(element) if matches!(type_of, ComputedType::Pointer(_)) => { Known::Yes(((*element).clone(), file)) } - Some(element) if matches!(type_of, Type::Array { .. }) => { + Some(element) if matches!(type_of, ComputedType::Array { .. }) => { Known::Yes(((*element).clone(), file)) } // **The class case**: a `std::vector`'s `operator[]` returns `T&`, and `members_of` has already @@ -1214,7 +1237,7 @@ pub(crate) fn type_of_expression_inner( // without the argument answered the first (`int&` — measured). The type of the index expression is // this expression's own question, one step down, and the memo makes it one. _ => { - let argument_types: Vec = subscript_index(expression) + let argument_types: Vec = subscript_index(expression) .map(|argument| { type_of_expression_memoed( memo, @@ -1248,11 +1271,11 @@ pub(crate) fn type_of_expression_inner( // **The answer is a *type*, not the spelling the member wrote.** `reference` is the class's // own alias for `T&`, and both halves — the alias and the parameter — are what this reads; // see [`a_members_answer_as_a_type`] for the measurement. - let written = a_members_answer_as_a_type( + let settled = a_members_answer_as_a_type( index, scopes, root, path, &type_of, &returns, ); - Known::Yes((parse_type_spelling(&written), file)) + Known::Yes((settled, file)) } // A class with no `operator[]`: nothing this layer can say, and saying nothing is the rule. None => Known::Unknown(UnknownReason::UnknownType(Box::from(written))), @@ -1474,7 +1497,8 @@ pub(crate) fn type_of_expression_inner( // a member of the same class. Without the second use of this walk, `auto y = x.back()` recorded the *name* // `reference` as `y`'s type — measured, and it is what a reader saw when hovering an `auto` variable: a type // that is not a type, on a declaration the compiler types as `char&`. - if let Some(type_of) = fact.type_of.as_deref() { + if let Some(written_type) = the_type_of_a_fact(index, &fact) { + let type_of = written_type.to_string(); // **An alias template at the head of the spelling is followed here, and this is the exit that needed it.** // // A member whose type is `enable_if_t<__is_same(int, int), double>` answered with exactly that spelling: @@ -1484,7 +1508,7 @@ pub(crate) fn type_of_expression_inner( // that resolves such a member, by the pattern comparison that folds a decidable builtin to the `true` // the library wrote its `enable_if` for. - if let Some((named, member)) = the_alias_behind(index, &file, type_of) { + if let Some((named, member)) = the_alias_behind(index, &file, &type_of) { // **The chain is what has already been *resolved*, not what is about to be asked.** Pushing the member // here made the walk refuse its first question — `asked.contains("type")` — and the answer came back as // the member's own name (measured: `Some("type")` where the file means `double`). @@ -1493,7 +1517,7 @@ pub(crate) fn type_of_expression_inner( // about to read `enable_if<…, double>::type`, whose declaration says `_Ty`, and `_Ty` is `double` here // because that class was applied to `double`. Passing the object's bindings (`Widget`'s, which pair // nothing with nothing) left the parameter's own name standing — measured: `Some("_Ty")`. - // **The arguments split where the *language* splits them.** `Type::arguments` (from + // **The arguments split where the *language* splits them.** `ComputedType::arguments` (from // `parse_type_spelling`) read `__is_same(int, int)` as two arguments — it does not count parentheses — // so the substitution paired `_Ty` with `int)` and the answer was `Some("int)")`. `split_arguments` // counts brackets and parentheses, which is the rule the pattern comparison already uses; the class @@ -1502,7 +1526,7 @@ pub(crate) fn type_of_expression_inner( .split_once('<') .map(|(_, rest)| rest.trim_end().strip_suffix('>').unwrap_or(rest)) .unwrap_or_default(); - let argument_types: Vec = sema::builtins::split_arguments(inner) + let argument_types: Vec = sema::builtins::split_arguments(inner) .iter() .map(|one| parse_type_spelling(one)) .collect(); @@ -1527,7 +1551,7 @@ pub(crate) fn type_of_expression_inner( return Known::Yes(finished); } - let finished = bindings.applied_to(&parse_type_spelling(type_of)); + let finished = bindings.applied_to(&written_type); return Known::Yes(finish_a_nested_name( index, scopes, @@ -1543,7 +1567,7 @@ pub(crate) fn type_of_expression_inner( // No `type_of`: the declaration is a function (or a class). For a function being **called**, the answer is // what the call has; for one merely named, there is no type and saying so is the honest answer. - if being_called && let Some(returns) = what_a_call_has_in(&fact) { + if being_called && let Some(returns) = what_a_call_has_in(index, &fact) { return Known::Yes(finish_a_nested_name( index, scopes, @@ -1580,6 +1604,15 @@ pub(crate) fn agreeing_type( ) -> Option<(DeclFact, PathBuf)> { let candidates = index.files_declaring(name, path); let mut agreeing: Option<(DeclFact, PathBuf)> = None; + // **The candidate's type, computed.** A class candidate's type is the class itself — see the note below — and + // every other candidate's is materialized from its fact. Comparing the computed values keeps this a question + // about types rather than about two spellings that may differ only in whitespace. + let the_type = |fact: &DeclFact| -> Option { + match fact.kind { + DeclKind::Type => Some(ComputedType::named(fact.qualified_name(), Vec::new())), + _ => index.computed_type_of(fact), + } + }; for found in &candidates { // **A class's type is the class**, and reading `type_of` alone said otherwise. @@ -1594,16 +1627,11 @@ pub(crate) fn agreeing_type( // // A class candidate therefore agrees with every other class candidate **of the same qualified name**, which // is what makes `std::vector` and its partial specialisations one answer rather than thirteen. - let type_of = match found.fact.kind { - DeclKind::Type => found.fact.qualified_name(), - _ => found.fact.type_of.clone()?.to_string(), - }; + let type_of = the_type(found.fact)?; match &agreeing { None => agreeing = Some((found.fact.clone(), found.file.clone())), - Some((first, _)) if first.type_of.as_deref() == Some(type_of.as_str()) => {} - Some((first, _)) - if first.kind == DeclKind::Type && first.qualified_name() == type_of => {} + Some((first, _)) if the_type(first).as_ref() == Some(&type_of) => {} Some(_) => return None, } } @@ -1646,19 +1674,29 @@ pub(crate) fn declared_class( if let Some((head, rest)) = class.split_once('<') && let Some(inside) = rest.trim_end().strip_suffix('>') && let Known::Yes(found) = index.definition(head.trim(), declaring) - && found.fact.kind == DeclKind::Type - && let Some(target) = found.fact.type_of.as_deref() + && let Some(found) = index.definition_fact(&found) + && found.kind == DeclKind::Type + && let Some(target) = index.computed_type_of(found) { + // **The arguments are source text and are parsed here, once** — they are what the *use* wrote, not a stored + // type being turned back into one. The target is the alias's own `ComputedType`, substituted structurally, so + // nothing of the declaration's type goes through a spelling. let written = sema::builtins::split_arguments(inside); - let target = sema::types::substituted_spelling(target, found.fact.parameters(), &written); - if let Some(named) = parse_type_spelling(&target).class_name() { + let bindings: Vec<(smol_str::SmolStr, ComputedType)> = found + .parameters() + .iter() + .zip(written.iter()) + .map(|(parameter, argument)| (parameter.clone(), parse_type_spelling(argument))) + .collect(); + let target = target.substituted_by_bindings(&bindings); + if let Some(named) = target.class_name() { return Some(named.to_string()); } } match index.definition(class, declaring) { Known::Yes(found) => { - let qualified = found.fact.qualified_name(); + let qualified = index.definition_fact(&found)?.qualified_name(); (qualified != class).then_some(qualified) } Known::Unknown(_) | Known::No => None, @@ -1748,7 +1786,7 @@ fn the_view_a_pipeline_names( left: &CppSyntaxNode, right: &CppSyntaxNode, depth: usize, -) -> Option<(Type, PathBuf)> { +) -> Option<(ComputedType, PathBuf)> { let (view, carries_the_callable, callable) = the_adaptor_a_use_names(right)?; // **`views::all_t`.** The left operand's type first; a pipeline is already a view because that is what the // call it stands for returns (checked by its spelling, which this layer wrote itself for the inner pipeline). @@ -1782,23 +1820,14 @@ fn the_view_a_pipeline_names( true => "std::ranges::ref_view", false => "std::ranges::owning_view", }; - Type::Named { - name: of.to_string(), - arguments: vec![left_type], - } + ComputedType::named(of, vec![left_type]) } }; let mut arguments = vec![all]; if carries_the_callable { arguments.push(callable?); } - Some(( - Type::Named { - name: view.to_string(), - arguments, - }, - file, - )) + Some((ComputedType::named(view, arguments), file)) } /// **The view class an adaptor use names, and the callable it carries** — `None` for anything that is not one of the @@ -1809,7 +1838,9 @@ fn the_view_a_pipeline_names( /// **lambda written at the call** — a lambda has no name, so it is described by where it is /// (`(lambda at a.cpp:12:34)`), which is the one spelling that designates it; a named function's type is a function /// reference, which is a second deduction this rule does not do. -fn the_adaptor_a_use_names(right: &CppSyntaxNode) -> Option<(&'static str, bool, Option)> { +fn the_adaptor_a_use_names( + right: &CppSyntaxNode, +) -> Option<(&'static str, bool, Option)> { let kind = CppSyntaxKind::from(right.kind()); // `std::views::take(2)` — a call whose callee names the adaptor, and whose arguments are the adaptor's own. let (callee, arguments) = match kind { @@ -1871,11 +1902,11 @@ fn the_adaptor_a_use_names(right: &CppSyntaxNode) -> Option<(&'static str, bool, /// served the fallback: `inspect inlay` alone printed `(lambda at a.cpp:7:17)`, and the same command with `--index` /// printed `(lambda)`. A type that changes with the order of the questions is not a type; `(lambda)` is the same /// answer from every caller. -fn a_lambdas_spelling(node: &CppSyntaxNode) -> Option { +fn a_lambdas_spelling(node: &CppSyntaxNode) -> Option { if CppSyntaxKind::from(node.kind()) != CppSyntaxKind::LambdaExpr { return None; } - Some(Type::named("(lambda)")) + Some(ComputedType::named("(lambda)", Vec::new())) } /// **Is this spelling one this layer writes for a view?** — `std::ranges::filter_view<…>`. @@ -1891,18 +1922,20 @@ fn is_a_view_spelling(written: &str) -> bool { /// **What a class's `operator` returns** — the member's own return type, read from the file that declares the /// class, which is the only place its member list can be read from. /// -/// `None` for a class that declares no such operator, for one nobody declared (a template parameter, a name from a -/// header the project never read), and for an operator whose declaration did not spell a return type. Every `None` -/// means "this layer has no answer", never "the program has no answer". +/// The answer is a **type**, not a spelling: the fact carries the declaration's `ComputedType`, and the class's +/// template parameters are paired with the object type's arguments structurally. `None` for a class that declares no +/// such operator, for one nobody declared (a template parameter, a name from a header the project never read), and +/// for an operator whose declaration did not spell a return type. Every `None` means "this layer has no answer", +/// never "the program has no answer". pub(crate) fn operator_returns_of( index: &ProjectIndex, declaring: &mut dyn FnMut(&Path) -> Option, scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, + class_type: &ComputedType, operator: &str, -) -> Option { +) -> Option { operator_returns_of_with_arguments( index, declaring, @@ -1925,13 +1958,13 @@ pub(crate) fn operator_returns_of_with_arguments( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, + class_type: &ComputedType, operator: &str, - argument_types: &[Type], + argument_types: &[ComputedType], // **How many arguments the call wrote** — the types can be fewer, because a lambda's type is unnamed and a // conversion that failed records nothing. The count is what picks an overload; the types are what fill it in. argument_count: Option, -) -> Option { +) -> Option { let class = class_type.class_name()?.to_string(); // **A name that is an alias is not a class, and asking for its operator parses a file.** `files_declaring` // answers with the declarations of the *name*, and the next step asks the session for the view of the file the @@ -1948,34 +1981,46 @@ pub(crate) fn operator_returns_of_with_arguments( let first = declared .iter() .find(|declared| declared.fact.kind == DeclKind::Type)?; - if let Some(target) = first.fact.type_of.as_deref() { + if let Some(target) = index.computed_type_of(first.fact) { // **An alias is not a class, and its operator is the target's.** `nlohmann::json` is `using json = // basic_json<>;`, and the eight `operator[]` overloads the report needs are `basic_json`'s — stopping here is // what answered `UnknownType("json[\"data\"]")` while `members_of("nlohmann::json")`, which follows the alias, // listed 242 members. // - // **One step, read out of the declaration's own `type_of`** — no file is read and no search is made, which is - // the cost the note below was written for: what that measurement paid for was a *search* for `std::size_t`'s - // operators, not the one substitution that turns an alias into the class it names. The recursion ends at a - // class (its declaration carries no `type_of`), and a name that resolves to itself ends it here. - let alias_arguments: Vec = - class_type.arguments().iter().map(Type::to_string).collect(); - let target = - sema::types::substituted_spelling(target, first.fact.parameters(), &alias_arguments); - let target_type = parse_type_spelling(&target); + // **One step, read out of the declaration's own computed type** — no file is read and no search is made, which + // is the cost the note below was written for: what that measurement paid for was a *search* for + // `std::size_t`'s operators, not the one substitution that turns an alias into the class it names. The + // recursion ends at a class (its declaration carries no type of its own), and a name that resolves to itself + // ends it here. + // + // The substitution is structural: the alias's arguments are the use's own `ComputedType`s, converted to the + // computation layer — no spelling of the declaration's target is parsed. + let bindings: Vec<(smol_str::SmolStr, ComputedType)> = first + .fact + .parameters() + .iter() + .zip(class_type.arguments()) + .map(|(parameter, argument)| (parameter.clone(), argument.clone())) + .collect(); + let target = if bindings.is_empty() { + target + } else { + target.substituted_by_bindings(&bindings) + }; // **The alias's target does not carry the object's qualifier, and the recursion needs it.** `const // std::string& s` resolved to `basic_string` — unqualified — so the recursive call saw a non-const // object and chose the non-const `operator[]`: `s[0]` answered `char&` where the compiler answers // `const char&`. A qualifier is written on the *use*, so it is put back on the target. - let target_type = if class_type.is_const() && !target_type.is_const() { - Type::Qualified { - of: Arc::new(target_type), - qualifiers: sema::types::Qualifiers::CONST, - } + let target = if class_type.is_const() && !target.is_const() { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(target), + is_const: true, + is_volatile: false, + })) } else { - target_type + target }; - if target_type + if target .class_name() .is_some_and(|named| named != class.as_str()) { @@ -1991,21 +2036,25 @@ pub(crate) fn operator_returns_of_with_arguments( // unqualified one is kept as the fallback — an alias whose target is a class at file scope has no such // qualifier, and qualifying it would find nothing. let qualified = match ( - class - .rsplit_once("::") - .map(|(qualifier, _)| qualifier.to_string()), - target_type.class_name(), + class.rsplit_once("::").map(|(qualifier, _)| qualifier), + target.class_name(), ) { - (Some(qualifier), Some(bare)) if !bare.contains("::") => { - let mut named = target_type.clone(); - if let Type::Named { name, .. } = &mut named { - *name = format!("{qualifier}::{bare}"); - } - Some(named) - } + (Some(qualifier), Some(bare)) if !bare.contains("::") => match &target { + ComputedType::Named(name) => Some(ComputedType::named( + format!("{qualifier}::{name}"), + Vec::new(), + )), + ComputedType::Generic(generic) => Some(ComputedType::named( + format!("{qualifier}::{}", generic.name), + generic.arguments.to_vec(), + )), + // A qualified target (a `const` alias, a pointer) has no bare class name to re-qualify; the + // unqualified candidate below is still tried. + _ => None, + }, _ => None, }; - for candidate in qualified.iter().chain(std::iter::once(&target_type)) { + for candidate in qualified.iter().chain(std::iter::once(&target)) { if candidate .class_name() .is_some_and(|named| named == class.as_str()) @@ -2094,7 +2143,7 @@ pub(crate) fn operator_returns_of_with_arguments( // arm gave before. let arity = argument_count.or((!argument_types.is_empty()).then_some(argument_types.len())); // **The qualifier the object has**, for the choice among overloads of one name — see - // [`a_member_with_that_arity`] and [`Type::is_const`]. + // [`a_member_with_that_arity`] and [`ComputedType::is_const`]. let object_is_const = class_type.is_const(); // **The arguments choose among overloads, and the ranking that does it already exists.** // @@ -2121,26 +2170,27 @@ pub(crate) fn operator_returns_of_with_arguments( Some(&written_arguments), ); // **A `const` object can only call a `const` member**, which is the same rule the arity preference below - // applies — a candidate it could not call is not a candidate. A non-const object may call both. - let callable: Vec<(DeclFact, PathBuf)> = declared + // applies — a candidate it could not call is not a candidate. A non-const object may call both. Each + // candidate arrived with its parameters resolved, so the ranking is handed structures. + let callable: Vec = declared .into_iter() - .filter(|(fact, _)| { - !object_is_const || fact.modifiers.contains(DeclModifiers::CONST) + .filter(|candidate| { + !object_is_const || candidate.fact.modifiers.contains(DeclModifiers::CONST) }) .collect(); if callable.len() < 2 { return None; } - let types: Vec> = argument_types + let types: Vec> = argument_types .iter() - .map(|argument| Known::Yes(argument.to_string())) + .map(|argument| Known::Yes(argument.clone())) .collect(); let at = the_one_the_arguments_select(&types, &callable, &[])?; // The shape the rest of this function uses: the fact, and where its body is as a **spelling** — the // declaration found by name carries the class it was declared in there, while a candidate carries the file. - let (fact, file) = callable.get(at)?; - Some((fact.clone(), file.display().to_string())) + let candidate = callable.get(at)?; + Some((candidate.fact.clone(), candidate.file.display().to_string())) }) .flatten(); let mut matching = match (ranked, arity) { @@ -2204,6 +2254,7 @@ pub(crate) fn operator_returns_of_with_arguments( .as_deref() .unwrap_or_else(|| Path::new(&member_file)), parameter_names, + class_type.arguments(), &written_arguments, argument_types, ) @@ -2251,6 +2302,7 @@ pub(crate) fn operator_returns_of_with_arguments( &fact, member_file.as_path(), parameter_names, + class_type.arguments(), &written_arguments, argument_types, ) { @@ -2281,22 +2333,26 @@ pub(crate) fn operator_returns_of_with_arguments( .members .iter() .filter(|member| { - let name: String = member - .fact - .name + let name: String = index + .member_name(member) .chars() .filter(|character| !character.is_whitespace()) .collect(); name == wanted || name == symbol }) .min_by_key(|member| { - member.fact.modifiers.contains(DeclModifiers::CONST) != object_is_const + index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) + != object_is_const })?; - let returns = found - .fact - .returns - .clone() - .or(found.fact.returns_in_the_class().map(SmolStr::from))?; + let found_fact = index.member_fact(found)?; + // **The declaration's return type is a value.** `DeclFact::returns` is the stored `ComputedType`; the one + // spelling a fact keeps *for the class* — `reference operator[]`, which a reader with no class cannot resolve — + // is read here once, at that boundary. Nothing below turns a type back into text. + let returns = index + .computed_returns_of(found_fact) + .or_else(|| found_fact.returns_in_the_class().and_then(a_type_spelling)); // **An operator inherited from a base answers in the base's spelling.** `template struct Base { T* // operator->(); }; template struct Ptr : Base {};` — `Ptr`'s arrow is `Base::operator->`, @@ -2305,7 +2361,15 @@ pub(crate) fn operator_returns_of_with_arguments( // through the derived class's own), which is what this asks before the class's own parameters are tried. // Measured on that fixture: 0 items before, the pointee's members after; the same shape is libstdc++'s // `shared_ptr`, whose `operator->` is declared in `__shared_ptr<_Tp, _Lp>`. + // + // The base clause is written as spellings (`Base`), so this one fallback works on a spelling and parses its + // answer once at its own boundary ([`a_base_operators_return`]); the declaration's own spelling comes from the + // fact, never from the structured `returns` above. if found.declared_in != class + && let Some(written) = index + .returns_spelling_of(found_fact) + .map(|spelled| spelled.to_string()) + .or_else(|| found_fact.returns_in_the_class().map(str::to_string)) && let Some(substituted) = a_base_operators_return( index, scopes, @@ -2313,7 +2377,7 @@ pub(crate) fn operator_returns_of_with_arguments( path, &class, &found.declared_in, - &returns, + &written, parameter_names, &written_arguments, ) @@ -2321,19 +2385,47 @@ pub(crate) fn operator_returns_of_with_arguments( return Some(substituted); } - Some(sema::types::substituted_spelling( - &returns, - parameter_names, - &written_arguments, - )) + // **The class's parameters against the use's arguments, structurally.** `T&` is stored as a reference to a + // template parameter, and the pairing replaces it with the argument type — the same substitution + // [`ComputedType::substituted_by_bindings`] performs everywhere else. No spelling is written or read. + Some( + returns? + .substituted_by_bindings(&the_class_bindings(parameter_names, class_type.arguments())), + ) +} + +/// **A spelling a fact kept, as the type it names** — the one parse at the boundary of a fact whose return type only +/// the class can resolve (`reference operator[]`, see [`crate::DeclFact::returns_in_the_class`]). +/// +/// `None` for a spelling with nothing in it: that is "no type to answer", not the type `void`. +fn a_type_spelling(written: &str) -> Option { + let written = written.trim(); + (!written.is_empty()).then(|| parse_type_spelling(written)) +} + +/// **The class's template parameters paired with the arguments the use wrote**, as the structural substitution +/// [`ComputedType::substituted_by_bindings`] takes. +/// +/// The names are the declaration's own and the arguments are the object type's values — nothing is written out and +/// read back. A use that wrote fewer arguments than the class declares leaves the rest of the names unbound, which +/// is the same answer the spelling-level pairing gave: a parameter with nothing to stand for stays itself. +fn the_class_bindings( + parameter_names: &[String], + arguments: &[ComputedType], +) -> Vec<(smol_str::SmolStr, ComputedType)> { + parameter_names + .iter() + .zip(arguments) + .map(|(parameter, argument)| (smol_str::SmolStr::new(parameter.as_str()), argument.clone())) + .collect() } /// **What one member returns, by its written type or by its body.** /// -/// A member whose return type is written returns that spelling, substituted with the class's arguments; one whose -/// type is the placeholder `auto` — every range adaptor's `operator()` — has its body read instead. Both the -/// first-declaration path and the arity-matched path of [`operator_returns_of_with_arguments`] go through here, so -/// the two cannot disagree about the same declaration. +/// A member whose return type is written answers that type, substituted with the class's arguments; one whose type is +/// the placeholder `auto` — every range adaptor's `operator()` — has its body read instead. Both the first-declaration +/// path and the arity-matched path of [`operator_returns_of_with_arguments`] go through here, so the two cannot +/// disagree about the same declaration. #[allow(clippy::too_many_arguments)] fn the_members_return( declaring: &mut dyn FnMut(&Path) -> Option, @@ -2344,15 +2436,17 @@ fn the_members_return( fact: &DeclFact, member_file: &Path, parameter_names: &[String], + class_arguments: &[ComputedType], written_arguments: &[String], - argument_types: &[Type], -) -> Option { + argument_types: &[ComputedType], +) -> Option { let _ = (index, scopes, root, path); - let returns = fact - .returns - .clone() - .or(fact.returns_in_the_class().map(SmolStr::from)); - if returns.as_deref().is_none_or(is_a_placeholder) + // **The declaration's return type as a value**, with the one spelling a fact keeps for the class parsed once + // here — see [`a_type_spelling`]. + let returns = index + .computed_returns_of(fact) + .or_else(|| fact.returns_in_the_class().and_then(a_type_spelling)); + if returns.as_ref().is_none_or(ComputedType::is_a_placeholder) && let Some(deduced) = deduced_returns_of_the_member( declaring, fact, @@ -2365,11 +2459,7 @@ fn the_members_return( return Some(deduced); } let returns = returns?; - Some(sema::types::substituted_spelling( - &returns, - parameter_names, - written_arguments, - )) + Some(returns.substituted_by_bindings(&the_class_bindings(parameter_names, class_arguments))) } /// **How many parameters a fact's declaration takes**, from the names it recorded or the list it wrote. @@ -2426,21 +2516,30 @@ fn a_member_with_that_arity( .members .iter() .filter(|member| { - let name: String = member - .fact - .name + let name: String = index + .member_name(member) .chars() .filter(|character| !character.is_whitespace()) .collect(); (name == wanted || name == symbol) - && arity.is_none_or(|wanted| a_facts_parameter_count(&member.fact) == Some(wanted)) + && arity.is_none_or(|wanted| { + index + .member_fact(member) + .is_some_and(|fact| a_facts_parameter_count(fact) == Some(wanted)) + }) }) // **The one whose qualifier agrees, and the first one when none does** — `false` sorts before `true`, so an // agreeing declaration wins and a class with only the other qualifier keeps the answer it had. .min_by_key(|member| { - member.fact.modifiers.contains(DeclModifiers::CONST) != object_is_const + index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) + != object_is_const })?; - Some((found.fact.clone(), found.declared_in.clone())) + // **The displayed form of the row**, so the caller reads the return type *this instantiation* has: a member + // inherited from `enable_shared_from_this` says `Node *`, not the base's `T *`. The row keeps its + // `FactRef`; this is the one copy the computation edge is allowed to make of a substituted declaration. + Some((index.member_display_fact(found)?, found.declared_in.clone())) } /// **What a member whose return type is `auto` returns**, read from its body. @@ -2470,8 +2569,8 @@ fn deduced_returns_of_the_member( file: &Path, parameter_names: &[String], written_arguments: &[String], - argument_types: &[Type], -) -> Option { + argument_types: &[ComputedType], +) -> Option { // **The fact's offset is a *file* offset; the tree speaks the *reading*.** The same translation the `Indexed` // arm of `what_a_call_has_in` makes, for the same reason: `name_range` comes from the index and counts the // file's own bytes, while `definition_at` walks a tree whose offsets count the rendered text (the file with its @@ -2532,8 +2631,7 @@ fn deduced_returns_of_the_member( // two lists are written with different names. let deduced_from_the_call = deduce_the_parameters(fact.parameters(), fact.parameter_list(), argument_types); - let substitutions = - sema::types::TypeSubstitutions::new(fact.parameters(), &deduced_from_the_call); + let substitutions = TypeSubstitutions::new(fact.parameters(), &deduced_from_the_call); let deduced = sema::declarations::deduced_returns_of_substituted( &declared_in.root, binding, @@ -2548,11 +2646,13 @@ fn deduced_returns_of_the_member( .map(|argument| argument.to_string()) .collect(); let deduced = sema::types::substituted_spelling(&deduced, fact.parameters(), &as_written); - Some(sema::types::substituted_spelling( + // **Parsed once, here**, at this fallback's own boundary: what the body wrote is a spelling, and from this point + // on the answer is the type it names. + Some(parse_type_spelling(&sema::types::substituted_spelling( &deduced, parameter_names, written_arguments, - )) + ))) } /// **The operand of a `co_await`, when this node is one.** @@ -2600,8 +2700,11 @@ pub(crate) fn a_bare_type_and_its_operators(written: &str) -> Option<(&str, Stri } /// **A base's operator return, read through the base clause's arguments.** `None` when the clause that names this -/// base cannot be found or its arguments cannot be read — the caller then answers with the spelling as written, which -/// is what this function refines. +/// base cannot be found or its arguments cannot be read — the caller then answers from the class's own parameters, +/// which is what this function refines. +/// +/// The base clause is written as spellings (`Base`), so the composition along it is spelling-level; the answer is +/// parsed **once, at the end of this function**, and the caller gets a type. pub(crate) fn a_base_operators_return( index: &ProjectIndex, scopes: &ScopeTree, @@ -2612,7 +2715,7 @@ pub(crate) fn a_base_operators_return( returns: &str, parameter_names: &[String], written_arguments: &[String], -) -> Option { +) -> Option { // The base list is asked for as a **precondition**: this returns before any substitution when the class's clause // cannot be read. The value is dropped on purpose — [`the_arguments_of_a_base`] below reads what is in it. let Known::Yes(_) = bases_of(index, scopes, root, path, class) else { @@ -2654,17 +2757,17 @@ pub(crate) fn a_base_operators_return( name, None, ) - && let Some(target) = alias.type_of.clone() + && let Some(target) = index.type_spelling_of(&alias) { let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); - return Some(format!("{substituted}{suffix}")); + return Some(parse_type_spelling(&format!("{substituted}{suffix}"))); } - Some(sema::types::substituted_spelling( + Some(parse_type_spelling(&sema::types::substituted_spelling( returns, ¶meters, &arguments, - )) + ))) } /// **The substitution that reaches `wanted` from `class` along the base clauses** — its template parameters and their @@ -2887,7 +2990,12 @@ impl NamedDeclaration { /// /// `None` for a function — `make` is not a `Widget` and has no members — which is the distinction /// [`DeclFact::type_of`] documents. - pub(crate) fn type_of(&self, root: &CppSyntaxNode, scopes: &ScopeTree) -> Option { + pub(crate) fn type_of( + &self, + index: &ProjectIndex, + root: &CppSyntaxNode, + scopes: &ScopeTree, + ) -> Option { match self { // **Read from the syntax**, which is where a type is written: the specifier sequence and the // declarator, handed to the one reader that knows how to assemble them. For a declaration in this @@ -2917,7 +3025,7 @@ impl NamedDeclaration { return scopes .scope(binding.scope) .and_then(|scope| scope.name.clone()) - .map(Type::named); + .map(|scope| ComputedType::named(scope, Vec::new())); } let declarator = sema::types::declarator_declaring(root, binding.name_range)?; let specifiers = declarator.ancestors().find_map(|node| { @@ -2960,20 +3068,20 @@ impl NamedDeclaration { written.to_string().is_empty(), an_unnamed_class_body(&specifiers), ) { - (true, Some(_)) if keyed_by_the_declarator => { - Some(Type::named(binding.name.identifier_text()?)) - } + (true, Some(_)) if keyed_by_the_declarator => Some(ComputedType::named( + binding.name.identifier_text()?, + Vec::new(), + )), _ => Some(written), } } - // **Read from the spelling**, which is all the index has: a fact is a `String` on disk and the file - // it came from is not open. `parse_type_spelling` is the bridge, and `class_name` the one field of - // it that a member query needs. + // **Read from the fact's computed type**, stored or synthesized. A fact is what the index has; the type + // is materialized without parsing and finished with the lookup's own bindings. NamedDeclaration::Indexed(fact, _, bindings) => { let _ = scopes; - fact.type_of - .as_deref() - .map(|written| bindings.applied_to(&parse_type_spelling(written))) + index + .computed_type_of(fact) + .map(|computed| bindings.applied_to(&computed)) } } } @@ -2996,9 +3104,9 @@ impl NamedDeclaration { scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - written_arguments: &[Type], - argument_types: &[Type], - ) -> Option { + written_arguments: &[ComputedType], + argument_types: &[ComputedType], + ) -> Option { // **The template arguments the call did not write**, deduced from the types of the arguments it did. // // Writing `` is one way to say what a function template's parameter stands for; passing an @@ -3025,7 +3133,10 @@ impl NamedDeclaration { match self { NamedDeclaration::Here(binding) => { if binding.kind == BindingKind::Class { - return binding.name.identifier_text().map(Type::named); + return binding + .name + .identifier_text() + .map(|name| ComputedType::named(name, Vec::new())); } // **A body that `if constexpr` decides, read again with what the call site knows.** // @@ -3042,14 +3153,12 @@ impl NamedDeclaration { sema::declarations::shapes_from(shapes, root), binding, ) - .filter(|returns| !is_a_placeholder(returns)) + .filter(|returns| !returns.is_a_placeholder()) { - Some(returns) => parse_type_spelling(&returns), + Some(returns) => returns, None => { - let substitutions = sema::types::TypeSubstitutions::new( - &names_for_the_call, - written_arguments, - ); + let substitutions = + TypeSubstitutions::new(&names_for_the_call, written_arguments); let written = sema::declarations::deduced_returns_of_substituted( root, binding.clone(), @@ -3075,7 +3184,7 @@ impl NamedDeclaration { if names.is_empty() || written_arguments.is_empty() { return Some(returns); } - let substitutions = sema::types::TypeSubstitutions::new(&names, written_arguments); + let substitutions = TypeSubstitutions::new(&names, written_arguments); Some(returns.substituted(&substitutions)) } // A **call of a member**: `v.data()` has what `data` returns, and what it returns is written with the @@ -3093,13 +3202,11 @@ impl NamedDeclaration { // `_Get_unwrapped` finally agree. let name = fact.name.to_string(); let offset = fact.name_range.start_offset; - let returns = match what_a_call_has_in(fact) { + let returns = match what_a_call_has_in(index, fact) { Some(returns) => returns, None => { - let substitutions = sema::types::TypeSubstitutions::new( - fact.parameters(), - written_arguments, - ); + let substitutions = + TypeSubstitutions::new(fact.parameters(), written_arguments); let declared_in = declaring(file.as_path())?; // **The fact's offset is a *file* offset; the tree speaks the *reading*.** // @@ -3150,6 +3257,16 @@ impl NamedDeclaration { // asic_string::_Convert_size - so the order does not decide the answer; it decides // which name is left standing when the two lists overlap, and the function's is the nearer. let started = bindings.applied_to(&returns); + if fact.name == "find" { + eprintln!( + "[find] returns={returns} started={started} bindings_args={:?}", + bindings + .arguments() + .iter() + .map(|a| a.to_string()) + .collect::>() + ); + } let started = if fact.parameters().is_empty() || written_arguments.is_empty() { started } else { @@ -3160,7 +3277,7 @@ impl NamedDeclaration { // /: 11 uto refusals were exactly this call, every one of them a return // type that had been read and left unpaired. let substitutions = - sema::types::TypeSubstitutions::new(fact.parameters(), written_arguments); + TypeSubstitutions::new(fact.parameters(), written_arguments); started.substituted(&substitutions) }; @@ -3178,12 +3295,7 @@ impl NamedDeclaration { .as_deref() .is_some_and(|scope| scope.rsplit("::").next() == Some(name)) => { - let arguments: Vec = bindings - .arguments() - .iter() - .map(|argument| argument.to_string()) - .collect(); - parse_type_spelling(&format!("{name}<{}>", arguments.join(", "))) + ComputedType::named(name, bindings.arguments().to_vec()) } _ => started, }; @@ -3235,7 +3347,7 @@ impl NamedDeclaration { sema::declarations::parameter_list_at(root, binding.name_range.start_offset), ), NamedDeclaration::Indexed(fact, _, _) => ( - fact.parameters().to_vec(), + fact.parameters().iter().map(ToString::to_string).collect(), fact.parameter_list().map(str::to_string), ), } @@ -3260,7 +3372,11 @@ impl NamedDeclaration { binding, ) } - NamedDeclaration::Indexed(fact, _, _) => fact.parameter_defaults().to_vec(), + NamedDeclaration::Indexed(fact, _, _) => fact + .parameter_defaults() + .iter() + .map(ToString::to_string) + .collect(), } } /// @@ -3304,12 +3420,12 @@ impl NamedDeclaration { /// /// # What it looks up, and where it stops /// -/// The name looked up is the type's **base** rather than its whole spelling ([`Type::class_name`], to which a +/// The name looked up is the type's **base** rather than its whole spelling ([`ComputedType::class_name`], to which a /// reference is transparent): `value_type&` is a reference to the member alias `value_type`, and it is the alias /// that has to be followed. A pointer is where the walk stops, because following one is a *decay* — a decision /// about the expression rather than about the declaration, and the caller's to make. /// -/// The operators stay where they are written ([`Type::replacing`]): `value_type&` with `value_type` = `_Ty*` is +/// The operators stay where they are written ([`ComputedType::replacing`]): `value_type&` with `value_type` = `_Ty*` is /// `_Ty*&`, and dropping either would answer a different type. /// /// The walk is bounded by [`MAX_NESTED_TYPE_DEPTH`] rather than by an argument about termination: each step asks @@ -3324,10 +3440,10 @@ pub(crate) fn finish_a_nested_name( path: &Path, class: &str, bindings: &TypeBindings, - mut current: Type, + mut current: ComputedType, mut current_file: PathBuf, mut asked: Vec, -) -> (Type, PathBuf) { +) -> (ComputedType, PathBuf) { for _ in 0..MAX_NESTED_TYPE_DEPTH { // **The class *with* the arguments the use wrote.** A return type's qualifier may name the class's own // parameters — `_Tree::find` answers `_Mybase::iterator`, and `_Mybase` is `_Tree<_Tmap_traits<_Kty, _Ty, …>>` — @@ -3448,11 +3564,11 @@ pub(crate) fn finish_a_nested_name( let Known::Yes((inner, inner_file)) = found else { break; }; - let Some(inner_type) = inner.type_of.as_deref() else { + let Some(inner_type) = the_type_of_a_fact(index, &inner) else { break; }; - let resolved = bindings.applied_to(&parse_type_spelling(inner_type)); + let resolved = bindings.applied_to(&inner_type); current = current.replacing(&nested, &resolved); current_file = inner_file; } @@ -3473,10 +3589,11 @@ pub(crate) fn names_a_namespace(index: &ProjectIndex, path: &Path, spelling: &st .value() .is_some_and(|found| { !found.found.is_empty() - && found - .found - .iter() - .all(|one| one.fact.kind == DeclKind::Namespace) + && found.found.iter().all(|one| { + index + .definition_fact(one) + .is_some_and(|fact| fact.kind == DeclKind::Namespace) + }) }) } @@ -3524,8 +3641,8 @@ pub(crate) fn a_trait_alias_resolved( root: &CppSyntaxNode, path: &Path, named: &NamedDeclaration, - written: &Type, -) -> Option { + written: &ComputedType, +) -> Option { let spelling = written.to_string(); if !spelling.contains('<') { return None; @@ -3543,7 +3660,10 @@ pub(crate) fn a_trait_alias_resolved( ) else { return None; }; - let target = fact.type_of.as_deref()?; + // **The target is materialized, not parsed.** The use's arguments and the declaration's defaults are *source* + // spellings, so those are read once here; the declaration's own target is structure from the store, substituted + // structurally. A default is written in the declaration's parameter names, so it is substituted before being read. + let target = index.computed_type_of(&fact)?; let arguments: Vec = parse_type_spelling(&class) .arguments() .iter() @@ -3553,9 +3673,25 @@ pub(crate) fn a_trait_alias_resolved( let class_name = bare.class_name()?; let parameters = index.template_parameters_for(class_name, path, &arguments); let defaults = index.template_parameter_defaults_for(class_name, path, &arguments); - let resolved = - sema::types::substituted_spelling_with_defaults(target, ¶meters, &defaults, &arguments); - Some(parse_type_spelling(&resolved)) + let mut bindings: Vec<(smol_str::SmolStr, ComputedType)> = Vec::new(); + for (at, parameter) in parameters.iter().enumerate() { + let argument = arguments + .get(at) + .filter(|argument| !argument.is_empty()) + .cloned(); + let default = defaults + .get(at) + .map(|default| default.trim()) + .filter(|default| !default.is_empty() && *default != parameter.as_str()) + .map(|default| sema::types::substituted_spelling(default, ¶meters, &arguments)); + if let Some(written) = argument.or(default) { + bindings.push(( + smol_str::SmolStr::new(parameter.as_str()), + parse_type_spelling(&written), + )); + } + } + Some(target.substituted_by_bindings(&bindings)) } /// The type a declaration was written with — or, where it wrote `auto`, the type its **initializer** has. /// @@ -3593,25 +3729,27 @@ pub(crate) fn declared_type( path: &Path, named: &NamedDeclaration, depth: usize, -) -> Known { +) -> Known { // **An enumerator's type is its enumeration** — the *indexed* half of the rule `NamedDeclaration::type_of` carries for // a declaration in this file. `enum class Colour { Red };` writes no type beside `Red`, so the fact records // `type_of: None` and this answered nothing: measured, `auto colour = Colour::Red;` in a `.cpp` whose enum is in the // header had no type at all, while the same declaration in one file worked. if let NamedDeclaration::Indexed(fact, _, _) = named - && fact.type_of.is_none() + && !fact.has_type_of() // **An enumerator only.** `DeclKind` has no enumerator — it is a `Variable` in the enum's scope — and a // *function* has the same (`type_of: None`, scope = a class). Without this guard `shared_from_this` declared in // `Base` answered the type `Base`, which is the class it is a member of, not what it is. && fact.kind == DeclKind::Variable && let Some(scope) = fact.scope.as_deref() && let Known::Yes(enclosing) = index.definition(scope, path) - && enclosing.fact.kind == DeclKind::Type + && index + .definition_fact(&enclosing) + .is_some_and(|fact| fact.kind == DeclKind::Type) { - return Known::Yes(Type::named(scope)); + return Known::Yes(ComputedType::named(scope, Vec::new())); } - let declaration = named.type_of(root, scopes); + let declaration = named.type_of(index, root, scopes); let Some(declaration) = declaration else { return Known::No; }; @@ -3640,8 +3778,7 @@ pub(crate) fn declared_type( // Measured on a C++20 project (`techniques.h` + `techniques.cpp`): `techniques::Box box(7)` typed as // `techniques::Box` while `techniques::Box box(7)` typed correctly, so what was missing was the deduction // rather than the template. - if let Type::Named { name, arguments } = &declaration - && arguments.is_empty() + if let ComputedType::Named(name) = &declaration && !name.contains('<') { // **The braced initialiser's elements are the constructor's arguments.** `std::pair pair{1, 2}` is a @@ -3704,7 +3841,7 @@ pub(crate) fn declared_type( let unknown = || Known::Unknown(UnknownReason::UnknownType(Box::from(placeholder.clone()))); // The **written** spelling, with the qualifiers the reader drops: `const auto& r = x;` has to deduce a `const` - // type, and `Type` models no qualifiers — so the spelling is carried beside the shape rather than inside it. + // type, and `ComputedType` models no qualifiers — so the spelling is carried beside the shape rather than inside it. // See `deduction_inputs`, which is the one place that reads a declaration's text for this reason. // **A range-based `for` head** — `for (auto x : range)`: the type is the range's **element**, not the range, // and there is no initializer for `deduction_inputs` to find. This is the ordinary spelling of a loop over a diff --git a/crates/cpp_code_analysis/src/index/store.rs b/crates/cpp_code_analysis/src/index/store.rs index 12919c6a..6b6edf3e 100644 --- a/crates/cpp_code_analysis/src/index/store.rs +++ b/crates/cpp_code_analysis/src/index/store.rs @@ -1297,6 +1297,8 @@ impl SummaryStore { // cooked reading (what a program saw, filed as L2). `CookedFile::from` says which four things those are. let cooked = CookedFile { declarations: indexed.summary.declarations.clone(), + // **And the same local parameter table**, for the same reason: `DeclFact::parameters` is a handle into it. + parameters: indexed.summary.parameters.clone(), macros: indexed.summary.macros.clone(), diagnostics: indexed.diagnostics, unplaced: indexed.unplaced, diff --git a/crates/cpp_code_analysis/src/index/syntax.rs b/crates/cpp_code_analysis/src/index/syntax.rs new file mode 100644 index 00000000..5f3fbbe7 --- /dev/null +++ b/crates/cpp_code_analysis/src/index/syntax.rs @@ -0,0 +1,125 @@ +//! **Syntax handles that can cross a fact boundary.** +//! +//! A fact must not store text for a default argument, a requires-clause or a declarator: the CST already has the node, +//! and re-parsing the text is a second grammar. This module is the resolution layer for the handle that replaces the +//! text. +//! +//! The stored handle is the parser's [`CppSyntaxId`] — `(kind, TextRange)` — and a resolver is the tree it belongs to: +//! +//! ```text +//! fact: SyntaxId ──► FileSyntax (root + generation) ──► CppSyntaxNode +//! ├─ CppParam +//! ├─ CppInitializer +//! └─ CppRequiresClause +//! ``` +//! +//! A resolver never parses. If the tree is not available the answer is `None`; the caller must report `Unknown`, not +//! manufacture a fragment. +use std::path::Path; + +use cpp_parser::CppAstNode; +use cpp_parser::CppInitializer; +use cpp_parser::CppParam; +use cpp_parser::CppRequiresClause; +use cpp_parser::CppSyntaxId; +use cpp_parser::CppSyntaxNode; + +/// The stored syntax handle. Kept as an alias so the rest of the refactor can speak `SyntaxId` without wrapping a +/// transparent value. +pub type SyntaxId = CppSyntaxId; + +/// **A tree a `SyntaxId` can be resolved against.** The implementation is a parsed file and its generation; it does +/// not own the tree, so a fact cannot accidentally keep a file alive. +pub trait SyntaxResolver { + fn resolve_syntax(&self, id: SyntaxId) -> Option; + + fn resolve_parameter(&self, id: SyntaxId) -> Option { + CppParam::cast(self.resolve_syntax(id)?) + } + + fn resolve_initializer(&self, id: SyntaxId) -> Option { + CppInitializer::cast(self.resolve_syntax(id)?) + } + + fn resolve_requires(&self, id: SyntaxId) -> Option { + CppRequiresClause::cast(self.resolve_syntax(id)?) + } +} + +/// A parsed file's root, as a resolver. The generation/content check belongs to the caller that owns the file. +pub struct FileSyntax<'a> { + path: &'a Path, + root: &'a CppSyntaxNode, +} + +impl<'a> FileSyntax<'a> { + pub fn new(path: &'a Path, root: &'a CppSyntaxNode) -> FileSyntax<'a> { + FileSyntax { path, root } + } + + pub fn path(&self) -> &Path { + self.path + } +} + +impl SyntaxResolver for FileSyntax<'_> { + fn resolve_syntax(&self, id: SyntaxId) -> Option { + id.to_node_from_root(self.root) + } +} + +/// Resolve one parameter against a root without constructing a resolver, for the callers that already have the node. +pub fn resolve_parameter(root: &CppSyntaxNode, id: SyntaxId) -> Option { + CppParam::cast(id.to_node_from_root(root)?) +} + +#[cfg(test)] +mod tests { + use super::*; + use cpp_parser::{CppParamList, CppParser, ParserConfig}; + + #[test] + fn a_parameter_id_resolves_to_the_typed_node() { + let tree = CppParser::parse( + "void f(int a, std::map m = {{1, 2}});\n", + ParserConfig::default(), + ); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let parameter = list.get_params().next().expect("the first parameter"); + let id = CppSyntaxId::from_node(parameter.syntax()); + let resolved = resolve_parameter(&root, id).expect("resolves"); + assert_eq!(resolved.get_name_text().as_deref(), Some("a")); + + let resolver = FileSyntax::new(Path::new("/p/a.cpp"), &root); + assert_eq!(resolver.path(), Path::new("/p/a.cpp")); + assert!(resolver.resolve_parameter(id).is_some()); + } + + #[test] + fn a_default_initializer_resolves_without_text() { + let tree = CppParser::parse( + "void f(std::map m = {{1, 2}});\n", + ParserConfig::default(), + ); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let initializer = list + .get_params() + .next() + .and_then(|parameter| parameter.get_default_value()) + .expect("the default"); + let id = CppSyntaxId::from_node(initializer.syntax()); + assert!( + FileSyntax::new(Path::new("/p/a.cpp"), &root) + .resolve_initializer(id) + .is_some() + ); + } +} diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs new file mode 100644 index 00000000..daadb8e9 --- /dev/null +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -0,0 +1,1091 @@ +//! **The computed type** — the immutable value a fact carries and a query works on. +//! +//! There is no storage-side type arena. A declaration's syntax is lowered to this type once at the construction +//! edge, and the value travels with the fact through the index, a cooked reading, a request, and the cache: +//! +//! ```text +//! declaration's syntax ComputedType, 32 bytes +//! specifiers + declarator SmolStr names, Arc children +//! read once at indexing immutable, cheap to clone +//! ``` +//! +//! A query never interns a temporary type and never parses a spelling to recover one. +//! +//! # The primary forms +//! +//! A builtin is not a name with an odd spelling: `int` is the language's own type, and a class can never be it. So the +//! computation layer holds the **primary** it denotes ([`PrimaryType`]) rather than the word the file happened to +//! write. There is no written-spelling side table: the mapping happens once, at the construction edge. +//! +//! A concrete name is one of two shapes, and the difference is structural: a name with no template arguments is +//! [`ComputedType::Named`], a name with arguments is [`ComputedType::Generic`]. Comparing names is a comparison of the +//! `SmolStr`, not of a rendered spelling, and the arguments are children a walk reaches without re-reading text. +//! +//! The large variants are boxed (`Generic`, `Function`, `Qualified`) so the enum stays 32 bytes. A `SmolStr` holds a +//! short name inline or shares a long one, and children are shared through `Arc`. The result is cheap to build and +//! cheap to clone, and it owns no borrow of the index. +use std::fmt; +use std::mem::size_of; +use std::sync::Arc; + +use smol_str::SmolStr; + +use super::semantics::RecordTag; + +/// **One of the language's own fundamental types.** +/// +/// The set is the primary types a C or C++ declaration can spell. The aliases a source may write instead — `short +/// int`, `signed`, `unsigned long int` — are not separate identities here: they denote one of these primaries, and +/// [`PrimaryType::from_spelling`] is the one table that says which. `auto` and `decltype(auto)` are primaries too: +/// they are placeholders the type layer must recognize structurally (see [`ComputedType::is_a_placeholder`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PrimaryType { + Void, + Bool, + Char, + SignedChar, + UnsignedChar, + Short, + UnsignedShort, + Int, + UnsignedInt, + Long, + UnsignedLong, + LongLong, + UnsignedLongLong, + Float, + Double, + LongDouble, + WChar, + Char8, + Char16, + Char32, + Auto, + DecltypeAuto, +} + +impl PrimaryType { + /// The canonical spelling a display consumer is shown — `int`, `unsigned long long`, `decltype(auto)`. + pub const fn spelling(self) -> &'static str { + match self { + PrimaryType::Void => "void", + PrimaryType::Bool => "bool", + PrimaryType::Char => "char", + PrimaryType::SignedChar => "signed char", + PrimaryType::UnsignedChar => "unsigned char", + PrimaryType::Short => "short", + PrimaryType::UnsignedShort => "unsigned short", + PrimaryType::Int => "int", + PrimaryType::UnsignedInt => "unsigned int", + PrimaryType::Long => "long", + PrimaryType::UnsignedLong => "unsigned long", + PrimaryType::LongLong => "long long", + PrimaryType::UnsignedLongLong => "unsigned long long", + PrimaryType::Float => "float", + PrimaryType::Double => "double", + PrimaryType::LongDouble => "long double", + PrimaryType::WChar => "wchar_t", + PrimaryType::Char8 => "char8_t", + PrimaryType::Char16 => "char16_t", + PrimaryType::Char32 => "char32_t", + PrimaryType::Auto => "auto", + PrimaryType::DecltypeAuto => "decltype(auto)", + } + } + + /// **The primary a written builtin spelling denotes** — a table lookup at a construction edge, never a parse of a + /// type. + /// + /// The standard's alternative spellings are folded into the primary they mean: `short int` and `signed short` are + /// [`PrimaryType::Short`], `signed` alone is [`PrimaryType::Int`], `unsigned` is + /// [`PrimaryType::UnsignedInt`]. An implementation-specific type word (`__int128`, `_Float16`, `_Atomic int`, + /// the empty spelling a deduction writes) is not one of these primaries and answers `None`; the caller keeps it as + /// a [`ComputedType::Named`] so its spelling still displays. + pub fn from_spelling(spelling: &str) -> Option { + Some(match spelling.trim() { + "void" => PrimaryType::Void, + "bool" | "_Bool" => PrimaryType::Bool, + "char" => PrimaryType::Char, + "signed char" => PrimaryType::SignedChar, + "unsigned char" => PrimaryType::UnsignedChar, + "short" | "short int" | "signed short" | "signed short int" => PrimaryType::Short, + "unsigned short" | "unsigned short int" => PrimaryType::UnsignedShort, + "int" | "signed" | "signed int" => PrimaryType::Int, + "unsigned" | "unsigned int" => PrimaryType::UnsignedInt, + "long" | "long int" | "signed long" | "signed long int" => PrimaryType::Long, + "unsigned long" | "unsigned long int" => PrimaryType::UnsignedLong, + "long long" | "long long int" | "signed long long" | "signed long long int" => { + PrimaryType::LongLong + } + "unsigned long long" | "unsigned long long int" => PrimaryType::UnsignedLongLong, + "float" => PrimaryType::Float, + "double" => PrimaryType::Double, + "long double" => PrimaryType::LongDouble, + "wchar_t" => PrimaryType::WChar, + "char8_t" => PrimaryType::Char8, + "char16_t" => PrimaryType::Char16, + "char32_t" => PrimaryType::Char32, + "auto" => PrimaryType::Auto, + "decltype(auto)" => PrimaryType::DecltypeAuto, + _ => return None, + }) + } + + /// Is this one of the integral primaries? `bool`, the character types and every signed/unsigned integer count; + /// `void` and the floating types do not. + pub const fn is_integral(self) -> bool { + matches!( + self, + PrimaryType::Bool + | PrimaryType::Char + | PrimaryType::SignedChar + | PrimaryType::UnsignedChar + | PrimaryType::Short + | PrimaryType::UnsignedShort + | PrimaryType::Int + | PrimaryType::UnsignedInt + | PrimaryType::Long + | PrimaryType::UnsignedLong + | PrimaryType::LongLong + | PrimaryType::UnsignedLongLong + | PrimaryType::WChar + | PrimaryType::Char8 + | PrimaryType::Char16 + | PrimaryType::Char32 + ) + } + + /// Is this `float`, `double` or `long double`? + pub const fn is_floating_point(self) -> bool { + matches!( + self, + PrimaryType::Float | PrimaryType::Double | PrimaryType::LongDouble + ) + } + + /// Is this a value a number converts to — the integral and floating primaries, but not `void` and not a + /// placeholder? + pub const fn is_arithmetic(self) -> bool { + self.is_integral() || self.is_floating_point() + } + + /// Is this one of the unsigned primaries? `bool` counts as unsigned for the sign question; a plain `char`'s + /// signedness is implementation-defined and is treated as signed, which is the answer the previous spelling test + /// gave it. + pub const fn is_unsigned(self) -> bool { + matches!( + self, + PrimaryType::UnsignedChar + | PrimaryType::UnsignedShort + | PrimaryType::UnsignedInt + | PrimaryType::UnsignedLong + | PrimaryType::UnsignedLongLong + | PrimaryType::Bool + ) + } + + /// Is this a placeholder whose type the compiler deduces — `auto` or `decltype(auto)`? + pub const fn is_a_placeholder(self) -> bool { + matches!(self, PrimaryType::Auto | PrimaryType::DecltypeAuto) + } +} + +/// **A name with template arguments** — `std::vector`, `std::pair`. The name is a cooked copy from +/// the storage name table and the arguments are computed children, shared through `Arc` by the enum. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct GenericType { + pub name: SmolStr, + pub arguments: Box<[ComputedType]>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct FunctionType { + pub returns: Arc, + pub parameters: Box<[ComputedType]>, +} + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct QualifiedType { + pub of: Arc, + pub is_const: bool, + pub is_volatile: bool, +} + +/// **The bound an array type was written with**, as the declaration gave it. +/// +/// Carrying the dimension rather than only a number is what keeps a *name* from being lost at the reader: `Point +/// points[COUNT]` used to record "some array of `Point`" and count as zero, and a layout question then had to find +/// the declaration's spelling again in the file's tree and evaluate `COUNT` there. The three states are the three +/// things a declaration can write: +/// +/// ```text +/// int a[]; Unspecified a flexible array member — no storage of its own +/// int a[4]; Literal(4) a bound that is a value +/// int a[COUNT]; Written("COUNT") a macro or enumerator +/// int a[('z'-'a'+1)]; Written("('z'-'a'+1)") a constant expression +/// int a[N]; Written("N") a template argument +/// ``` +/// +/// A `Written` dimension is *evaluated* where it stands by the consumer that needs a number +/// ([`crate::sema::layout`]'s caller, through the macro/enumerator lookup); nothing here decides its value. +/// +/// The text is boxed **only** so [`ComputedType`] keeps its 32-byte budget — `SmolStr` is 24 bytes, and putting one +/// inline beside the element `Arc` would grow every type value in every fact, member row and cache record. A written +/// bound is the rare case; a literal or flexible array costs nothing. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum ArrayExtent { + /// `int a[]` — the declaration states no bound (a flexible array member, or an unspecified array parameter). + Unspecified, + /// `int a[4]` — a bound the reader could evaluate from the declaration alone. + Literal(u64), + /// `int a[COUNT]` — a bound that is a name or a constant expression, kept as the file wrote it. + Written(Box), +} + +impl ArrayExtent { + /// **The dimension `written` names** — `COUNT`, or `('z' - 'a' + 1)` — kept for the consumer that evaluates it. + pub fn written(written: impl Into) -> Self { + Self::Written(Box::new(written.into())) + } + + /// Does this array state a bound at all? `false` only for `int a[]`. + pub fn is_specified(&self) -> bool { + !matches!(self, Self::Unspecified) + } + + /// **What this dimension costs outside its own slot** — the boxed `SmolStr` a written bound owns. + fn heap_bytes(&self) -> usize { + match self { + Self::Written(written) => size_of::() + written.len(), + Self::Unspecified | Self::Literal(_) => 0, + } + } +} + +/// The dimension as a file writes it **inside the brackets** — `4`, `COUNT`, or nothing for `[]`. +/// +/// The brackets belong to the array, which is why this writer is the extent's and not the type's; `[4]`, `[COUNT]` +/// and `[]` are what [`ComputedType`]'s own `Display` puts around it. +impl fmt::Display for ArrayExtent { + fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unspecified => Ok(()), + Self::Literal(extent) => write!(out, "{extent}"), + Self::Written(written) => write!(out, "{written}"), + } + } +} + +/// **A type a query can work on without touching the index.** Names are copied from the store's `SmolStr` table; +/// children are shared through `Arc`, so a substitution or a member walk copies a pointer rather than a tree. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum ComputedType { + /// A fundamental type the language names: `int`, `unsigned long long`, `bool`, `auto`, `decltype(auto)`. + Primary(PrimaryType), + /// A concrete name without template arguments: `Widget`, `std::string`, `T::value_type`. + Named(SmolStr), + /// A concrete name with template arguments: `std::vector`, `std::pair`. + Generic(Arc), + /// `T` / `_Ty` — a declaration's own template parameter, which a substitution replaces. + TemplateParameter(SmolStr), + /// **A C record written with its tag** — `struct point`, `union value`. The tag is display and C-conversion + /// evidence; the shape is the type underneath, so every structural question looks through it. + ElaboratedRecord { + tag: RecordTag, + of: Arc, + }, + Pointer(Arc), + Reference { + to: Arc, + rvalue: bool, + }, + /// **An array, with the bound the declaration wrote.** `of` is the element type and `extent` keeps the + /// dimension structurally — see [`ArrayExtent`], which is what makes `Point points[COUNT]` different from + /// `Point points[]` without the fact having to remember a spelling. + Array { + of: Arc, + extent: ArrayExtent, + }, + Function(Arc), + Pack(Arc), + Qualified(Arc), +} + +impl ComputedType { + /// **A name and, if it has any, its template arguments.** Empty arguments mean a plain [`ComputedType::Named`]; + /// a non-empty list means a [`ComputedType::Generic`]. This is the one constructor that decides the distinction, + /// so a caller never has to choose the variant by hand. + pub fn named(name: impl Into, arguments: Vec) -> ComputedType { + let name = name.into(); + if arguments.is_empty() { + ComputedType::Named(name) + } else { + ComputedType::Generic(Arc::new(GenericType { + name, + arguments: arguments.into_boxed_slice(), + })) + } + } + + /// **The name this type is made of, without its template arguments** — `std::vector` for both + /// `std::vector` and `std::vector`. `None` for a fundamental type, a function, or a placeholder. + pub fn name(&self) -> Option<&str> { + match self { + ComputedType::Named(name) => Some(name.as_str()), + ComputedType::Generic(generic) => Some(generic.name.as_str()), + ComputedType::TemplateParameter(name) => Some(name.as_str()), + _ => None, + } + } + + /// The class this type names, looking through a reference or a qualifier. A pointer is not transparent. + /// + /// `None` for the empty spelling a deduced or unnamed declaration records: that is "no type to name", not a + /// class whose name is empty. + pub fn class_name(&self) -> Option<&str> { + match self { + ComputedType::Named(name) if !name.is_empty() => Some(name.as_str()), + ComputedType::Generic(generic) => Some(generic.name.as_str()), + ComputedType::Reference { to, .. } => to.class_name(), + ComputedType::Qualified(qualified) => qualified.of.class_name(), + // **C's tag is transparent to a class question** — `struct point` names the record `point`. + ComputedType::ElaboratedRecord { of, .. } => of.class_name(), + _ => None, + } + } + + /// **The name this type is made of, seen through every operator a name lookup does not care about** — `Fn&&`, + /// `const Fn*` and `Fn[4]` all answer `Fn`; a primary answers its canonical spelling. + /// + /// The question a caller asks when it has a *spelling* in mind (`this parameter names the callee's `Fn`) but a + /// structured type in hand: comparing the name is a string comparison, while deciding where the name is is a + /// structural walk — this method, which is the one place that walk lives. + pub fn bare_name(&self) -> Option<&str> { + match self { + // **A placeholder names no type** — the same answer `auto` gave when it was its own variant. + ComputedType::Primary(primary) if primary.is_a_placeholder() => None, + ComputedType::Primary(primary) => Some(primary.spelling()), + ComputedType::Named(name) | ComputedType::TemplateParameter(name) => { + Some(name.as_str()) + } + ComputedType::Generic(generic) => Some(generic.name.as_str()), + ComputedType::Pointer(to) | ComputedType::Pack(to) => to.bare_name(), + ComputedType::Reference { to, .. } => to.bare_name(), + ComputedType::Array { of, .. } => of.bare_name(), + ComputedType::Qualified(qualified) => qualified.of.bare_name(), + ComputedType::ElaboratedRecord { of, .. } => of.bare_name(), + ComputedType::Function(_) => None, + } + } + + /// The template arguments written on the type, looking through a reference or a qualifier. + pub fn arguments(&self) -> &[ComputedType] { + match self { + ComputedType::Generic(generic) => &generic.arguments, + ComputedType::Reference { to, .. } => to.arguments(), + ComputedType::Qualified(qualified) => qualified.of.arguments(), + ComputedType::ElaboratedRecord { of, .. } => of.arguments(), + _ => &[], + } + } + + pub fn is_const(&self) -> bool { + match self { + ComputedType::Qualified(qualified) => qualified.is_const, + ComputedType::Reference { to, .. } => to.is_const(), + ComputedType::ElaboratedRecord { of, .. } => of.is_const(), + _ => false, + } + } + + /// The type a `*` on this one gives: the pointee of a pointer or the element of an array, seen through a + /// qualifier — **as a shared handle**, because the pointee is already an allocation inside this type. + /// + /// `None` for everything else, **including a reference**: a reference has no `operator*`, and the reason a caller + /// wants a pointee is to apply one. A `Named` type with an `operator*` of its own needs the class's members and + /// therefore the index, which is the same answer at this level. + pub fn pointee(&self) -> Option<&ComputedType> { + match self { + ComputedType::Pointer(to) | ComputedType::Array { of: to, .. } => Some(to), + // **A qualifier is transparent here too**: `*p` on a `const Widget*` gives a `const Widget`. + ComputedType::Qualified(qualified) => qualified.of.pointee(), + _ => None, + } + } + + /// Is this `void` — the incomplete type no object can have? A qualifier is looked through; nothing else is. + pub fn is_void(&self) -> bool { + match self { + ComputedType::Primary(PrimaryType::Void) => true, + ComputedType::Qualified(qualified) => qualified.of.is_void(), + _ => false, + } + } + + /// **Is this the `auto`/`decltype(auto)` placeholder**, however it was written around — `auto`, `auto&`, + /// `const auto*`? + /// + /// A placeholder is not a type a query can answer with: `auto copy_of() const { … }` records `auto`, and what the + /// call has is what its body returns. See [`crate::sema::types::is_a_deduced_type`], the spelling-level twin. + pub fn is_a_placeholder(&self) -> bool { + match self { + ComputedType::Primary(primary) => primary.is_a_placeholder(), + ComputedType::Pointer(to) | ComputedType::Pack(to) => to.is_a_placeholder(), + ComputedType::Reference { to, .. } => to.is_a_placeholder(), + ComputedType::Qualified(qualified) => qualified.of.is_a_placeholder(), + ComputedType::ElaboratedRecord { of, .. } => of.is_a_placeholder(), + _ => false, + } + } + + /// **What this value costs outside its own slot**, for the session's memory report: the boxed node, the names + /// that fell out of a `SmolStr`, and the children (each of which may be shared through an `Arc`). + /// + /// An estimate in the same style as [`crate::MemoryReport`]: live bytes, not the allocator's high-water mark. + pub fn heap_bytes(&self) -> usize { + let text = |name: &SmolStr| name.len(); + size_of::() + + match self { + ComputedType::Primary(_) => 0, + ComputedType::Named(name) | ComputedType::TemplateParameter(name) => text(name), + ComputedType::Generic(generic) => { + size_of::() + + text(&generic.name) + + generic + .arguments + .iter() + .map(ComputedType::heap_bytes) + .sum::() + } + ComputedType::Pointer(to) | ComputedType::Pack(to) => to.heap_bytes(), + ComputedType::Reference { to, .. } => to.heap_bytes(), + ComputedType::Array { of, extent } => of.heap_bytes() + extent.heap_bytes(), + ComputedType::ElaboratedRecord { of, .. } => of.heap_bytes(), + ComputedType::Function(function) => { + size_of::() + + function.returns.heap_bytes() + + function + .parameters + .iter() + .map(ComputedType::heap_bytes) + .sum::() + } + ComputedType::Qualified(qualified) => { + size_of::() + qualified.of.heap_bytes() + } + } + } + + /// **This type with one name in it replaced** — the structural twin of + /// [`ComputedType::replacing`], and the computation layer's step for a class's own **aliases**. + /// + /// A member of `std::vector` is declared `void push_back(const value_type&)` with `using value_type = _Tp;` in + /// the class, so substituting `_Tp` by `int` alone leaves the word `value_type`. This replaces that name — bare, + /// with no arguments of its own — wherever it stands, and leaves the operators around it where they are, which is + /// the same rule the `ComputedType` version follows. + pub fn replacing(&self, name: &str, with: &ComputedType) -> ComputedType { + match self { + ComputedType::Named(found) if found == name => with.clone(), + ComputedType::Named(_) => self.clone(), + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(|argument| argument.replacing(name, with)) + .collect(), + })), + ComputedType::Primary(_) | ComputedType::TemplateParameter(_) => self.clone(), + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.replacing(name, with)), + }, + ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.replacing(name, with))), + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(to.replacing(name, with)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(of.replacing(name, with)), + extent: extent.clone(), + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(function.returns.replacing(name, with)), + parameters: function + .parameters + .iter() + .map(|parameter| parameter.replacing(name, with)) + .collect(), + })), + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(of.replacing(name, with))), + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified.of.replacing(name, with)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + } + } + + /// **Apply one instantiation's template bindings without touching the store.** The result is another + /// `ComputedType`; no `TypeId` is interned and no spelling is parsed. This is the computation-layer substitution + /// the member view is built on. + pub fn substituted_by_bindings(&self, bindings: &[(SmolStr, ComputedType)]) -> ComputedType { + match self { + ComputedType::TemplateParameter(name) => bindings + .iter() + .find(|(parameter, _)| parameter == name) + .map_or_else(|| self.clone(), |(_, concrete)| concrete.clone()), + ComputedType::Primary(_) | ComputedType::Named(_) => self.clone(), + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(|argument| argument.substituted_by_bindings(bindings)) + .collect(), + })), + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.substituted_by_bindings(bindings)), + }, + ComputedType::Pointer(to) => { + ComputedType::Pointer(Arc::new(to.substituted_by_bindings(bindings))) + } + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(to.substituted_by_bindings(bindings)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(of.substituted_by_bindings(bindings)), + extent: extent.clone(), + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(function.returns.substituted_by_bindings(bindings)), + parameters: function + .parameters + .iter() + .map(|parameter| parameter.substituted_by_bindings(bindings)) + .collect(), + })), + ComputedType::Pack(of) => { + ComputedType::Pack(Arc::new(of.substituted_by_bindings(bindings))) + } + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified.of.substituted_by_bindings(bindings)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + } + } +} + +impl fmt::Display for ComputedType { + /// The type **as a file would write it**, which is what a consumer shows: the canonical spelling each part was + /// read with, put back together in the order the syntax wrote it. + /// + /// This is a writer for a human, not a parser's inverse: `int* const` and `const int*` differ by which side the + /// `const` was on, and that difference is in the shape rather than in a text. A qualified pointer or array writes + /// its qualifier **after** the operator run, because that is the position the file wrote it in; a pointer or + /// array in a function's return position gets the declarator's parentheses, because `void*(int)` would read as a + /// function returning a pointer. + fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ComputedType::Primary(primary) => write!(out, "{}", primary.spelling()), + ComputedType::Named(name) | ComputedType::TemplateParameter(name) => { + write!(out, "{name}") + } + ComputedType::Generic(generic) => { + write!(out, "{}<", generic.name)?; + for (at, argument) in generic.arguments.iter().enumerate() { + if at > 0 { + write!(out, ", ")?; + } + write!(out, "{argument}")?; + } + write!(out, ">") + } + // **The tag is written back**, which is what a display consumer quotes; the shape is what every other + // consumer reads. + ComputedType::ElaboratedRecord { tag, of } => write!(out, "{} {of}", tag.word()), + ComputedType::Pointer(to) => write!(out, "{to}*"), + ComputedType::Reference { to, rvalue } => { + write!(out, "{to}{}", if *rvalue { "&&" } else { "&" }) + } + ComputedType::Array { of, extent } => write!(out, "{of}[{extent}]"), + // **A pointer or an array in the return position needs its parentheses**, and they go around the + // *declarator* rather than around the whole type: `void (*)(int)` is a pointer to a function, while + // `void*(int)` reads as a function returning a pointer. + ComputedType::Function(function) => { + match &*function.returns { + pointer @ ComputedType::Pointer(_) => { + write!(out, "{}", pointer.as_a_declarator())? + } + array @ ComputedType::Array { .. } => { + write!(out, "{}", array.as_a_declarator())? + } + other => write!(out, "{other}")?, + } + write!(out, "(")?; + for (at, parameter) in function.parameters.iter().enumerate() { + if at > 0 { + write!(out, ", ")?; + } + write!(out, "{parameter}")?; + } + write!(out, ")") + } + ComputedType::Pack(of) => write!(out, "{of}..."), + // `const Widget`, in the position the file wrote it — which is what makes `const Widget*` and + // `Widget* const` two different answers here rather than one. + ComputedType::Qualified(qualified) + if matches!( + &*qualified.of, + ComputedType::Pointer(_) | ComputedType::Array { .. } + ) => + { + let mut words = Vec::new(); + if qualified.is_const { + words.push("const"); + } + if qualified.is_volatile { + words.push("volatile"); + } + write!(out, "{} {}", qualified.of, words.join(" ")) + } + ComputedType::Qualified(qualified) => { + let mut words = Vec::new(); + if qualified.is_const { + words.push("const"); + } + if qualified.is_volatile { + words.push("volatile"); + } + if words.is_empty() { + write!(out, "{}", qualified.of) + } else { + write!(out, "{} {}", words.join(" "), qualified.of) + } + } + } + } +} + +impl ComputedType { + /// **This type written the way a declarator writes it** — the shape `void (*)(int)` needs, and nothing else + /// does. + /// + /// The operators are collected on the way down — `*` for a pointer, `[4]` for an array — and the base is written + /// when the bottom is reached, in front of them. The parentheses go around the operators, not around the base: + /// `void (*)(int)` is `void (*F)(int)` with the `F` left out. + fn as_a_declarator(&self) -> String { + let mut suffix = String::new(); + let mut qualified = false; + let mut current = self; + + loop { + match current { + ComputedType::Pointer(to) => { + suffix.push('*'); + current = to; + } + ComputedType::Array { of, extent } => { + suffix.push_str(&format!("[{extent}]")); + current = of; + } + // `void* const`: the qualifier is written after what it qualifies, which is why it is part of the + // operator run rather than of the base. + ComputedType::Qualified(qualified_type) + if matches!( + &*qualified_type.of, + ComputedType::Pointer(_) | ComputedType::Array { .. } + ) => + { + qualified = true; + current = &qualified_type.of; + } + _ => break, + } + } + + format!( + "{current} ({suffix}{})", + if qualified { " const" } else { "" } + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem::size_of; + + #[test] + fn a_computed_type_stays_within_the_agreed_budget() { + assert!( + size_of::() <= 32, + "ComputedType is {} bytes", + size_of::() + ); + } + + /// The primary forms are the language's own types, and the display is the same word a reader wrote for the + /// canonical spelling. + #[test] + fn a_primary_type_is_one_of_the_languages_own_types() { + assert_eq!(ComputedType::Primary(PrimaryType::Int).to_string(), "int"); + assert_eq!( + ComputedType::Primary(PrimaryType::UnsignedLongLong).to_string(), + "unsigned long long" + ); + assert_eq!( + ComputedType::Primary(PrimaryType::DecltypeAuto).to_string(), + "decltype(auto)" + ); + assert!( + ComputedType::Primary(PrimaryType::Void) + .class_name() + .is_none() + ); + assert_eq!( + ComputedType::Primary(PrimaryType::Float).bare_name(), + Some("float") + ); + assert!(!PrimaryType::Void.is_arithmetic()); + assert!(PrimaryType::Bool.is_integral()); + assert!(PrimaryType::Double.is_floating_point()); + assert!( + ComputedType::Primary(PrimaryType::Auto).is_a_placeholder(), + "`auto` is a primary, not a name" + ); + } + + /// A name with no arguments is `Named`; `name()` and `class_name()` answer it, and there is nothing to walk. + #[test] + fn a_name_without_arguments_is_named() { + let value = ComputedType::named("std::string", Vec::new()); + assert!(matches!(value, ComputedType::Named(_))); + assert_eq!(value.to_string(), "std::string"); + assert_eq!(value.class_name(), Some("std::string")); + assert_eq!(value.name(), Some("std::string")); + assert!(value.arguments().is_empty()); + } + + /// A name with arguments is `Generic`; the arguments are children, and display writes them comma-separated. + #[test] + fn a_name_with_arguments_is_generic() { + let value = ComputedType::named( + "std::pair", + vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Double), + ], + ); + assert!(matches!(value, ComputedType::Generic(_))); + assert_eq!(value.to_string(), "std::pair"); + assert_eq!(value.class_name(), Some("std::pair")); + assert_eq!(value.name(), Some("std::pair")); + assert_eq!(value.arguments().len(), 2); + assert_eq!(value.arguments()[0].to_string(), "int"); + } + + /// **The distinction is structural, not a spelling.** A bare `std::vector` and a `std::vector` are different + /// values, and only the second one walks an argument list. + #[test] + fn generic_and_named_are_different_shapes() { + let bare = ComputedType::named("std::vector", Vec::new()); + let concrete = + ComputedType::named("std::vector", vec![ComputedType::Primary(PrimaryType::Int)]); + assert!(matches!(bare, ComputedType::Named(_))); + assert!(matches!(concrete, ComputedType::Generic(_))); + assert_ne!(bare, concrete); + assert_eq!(bare.class_name(), concrete.class_name()); + assert!(bare.arguments().is_empty()); + assert_eq!(concrete.arguments().len(), 1); + } + + /// A dependent parameter is its own variant, and a substitution replaces it structurally. + #[test] + fn a_template_parameter_is_its_name() { + let parameter = ComputedType::TemplateParameter(SmolStr::new("T")); + assert_eq!(parameter.to_string(), "T"); + assert_eq!(parameter.bare_name(), Some("T")); + assert!(parameter.class_name().is_none()); + assert_eq!( + parameter + .substituted_by_bindings(&[( + SmolStr::new("T"), + ComputedType::Primary(PrimaryType::Int) + )]) + .to_string(), + "int" + ); + } + + /// The operator forms keep the spellings display always produced. + #[test] + fn the_operator_forms_keep_their_spellings() { + let point = ComputedType::ElaboratedRecord { + tag: RecordTag::Struct, + of: Arc::new(ComputedType::named("point", Vec::new())), + }; + assert_eq!(point.to_string(), "struct point"); + assert_eq!( + ComputedType::Pointer(Arc::new(point)).to_string(), + "struct point*" + ); + assert_eq!( + ComputedType::Reference { + to: Arc::new(ComputedType::Primary(PrimaryType::Int)), + rvalue: true, + } + .to_string(), + "int&&" + ); + assert_eq!( + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Literal(4), + } + .to_string(), + "int[4]" + ); + assert_eq!( + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Unspecified, + } + .to_string(), + "int[]" + ); + assert_eq!( + ComputedType::Array { + of: Arc::new(ComputedType::named("Point", Vec::new())), + extent: ArrayExtent::written("COUNT"), + } + .to_string(), + "Point[COUNT]", + "a written dimension survives Display as the file wrote it" + ); + assert_eq!( + ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(ComputedType::Primary(PrimaryType::Int)), + parameters: vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Double), + ] + .into_boxed_slice(), + })) + .to_string(), + "int(int, double)" + ); + assert_eq!( + ComputedType::Pack(Arc::new(ComputedType::TemplateParameter(SmolStr::new("T")))) + .to_string(), + "T..." + ); + assert_eq!( + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + is_const: true, + is_volatile: true, + })) + .to_string(), + "const volatile int" + ); + } + + /// **Display is the agreed spellings**, including the empty argument list and the comma-space between arguments. + #[test] + fn display_writes_the_agreed_spellings() { + let spelling = |value: ComputedType| value.to_string(); + assert_eq!(spelling(ComputedType::Primary(PrimaryType::Int)), "int"); + assert_eq!( + spelling(ComputedType::named( + "std::vector", + vec![ComputedType::Primary(PrimaryType::Int)], + )), + "std::vector" + ); + assert_eq!( + spelling(ComputedType::named( + "std::pair", + vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Int), + ], + )), + "std::pair" + ); + assert_eq!( + spelling(ComputedType::TemplateParameter(SmolStr::new("T"))), + "T" + ); + assert_eq!( + spelling(ComputedType::Pointer(Arc::new( + ComputedType::ElaboratedRecord { + tag: RecordTag::Struct, + of: Arc::new(ComputedType::named("point", Vec::new())), + } + ))), + "struct point*" + ); + } + + /// **The builtin aliases fold into their primary, and the ambiguous spellings are recorded here.** The + /// construction edge carries the identity; an implementation-specific word is not a primary and is kept as a name + /// so its display survives. + #[test] + fn a_written_builtin_maps_to_its_primary_or_stays_a_name() { + let short_int = ComputedType::builtin("short int"); + assert_eq!(short_int, ComputedType::Primary(PrimaryType::Short)); + assert_eq!(short_int.to_string(), "short", "the canonical spelling"); + + assert_eq!( + ComputedType::builtin("unsigned"), + ComputedType::Primary(PrimaryType::UnsignedInt) + ); + assert_eq!( + ComputedType::builtin("decltype(auto)"), + ComputedType::Primary(PrimaryType::DecltypeAuto) + ); + assert_eq!( + ComputedType::builtin("auto"), + ComputedType::Primary(PrimaryType::Auto) + ); + + let extension = ComputedType::builtin("__int128"); + assert_eq!(extension, ComputedType::Named(SmolStr::new("__int128"))); + assert_eq!(extension.to_string(), "__int128", "the spelling survives"); + assert_eq!( + ComputedType::builtin(""), + ComputedType::Named(SmolStr::new("")) + ); + } + + /// **The one spelling parser round-trips the shapes a fact carries.** Its input is text that genuinely crossed + /// the display/external boundary; its output is the same structure `Display` writes back. The template-parameter + /// case is pinned through `with_template_parameters`, because a bare `T` is a name to a parser with no scope. + #[test] + fn parse_type_spelling_round_trips_the_shapes_a_fact_carries() { + use crate::sema::types::{parse_type_spelling, with_template_parameters}; + + for value in [ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::UnsignedLongLong), + ComputedType::Primary(PrimaryType::DecltypeAuto), + ComputedType::named("std::string", Vec::new()), + ComputedType::named( + "std::pair", + vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Double), + ], + ), + ComputedType::Pointer(Arc::new(ComputedType::Primary(PrimaryType::Int))), + ComputedType::Reference { + to: Arc::new(ComputedType::Primary(PrimaryType::Int)), + rvalue: true, + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Literal(4), + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Unspecified, + }, + // **A dimension that is a name is part of the type**, not a spelling that has to be recovered from the + // declaration: `int[COUNT]` must display and parse back as `[COUNT]`, not as `[]`. + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::written("COUNT"), + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::written("('z' - 'a' + 1)"), + }, + ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(ComputedType::Primary(PrimaryType::Void)), + parameters: vec![ComputedType::Primary(PrimaryType::Int)].into_boxed_slice(), + })), + ComputedType::ElaboratedRecord { + tag: RecordTag::Struct, + of: Arc::new(ComputedType::named("point", Vec::new())), + }, + ComputedType::Pack(Arc::new(ComputedType::Primary(PrimaryType::Int))), + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + is_const: true, + is_volatile: false, + })), + ] { + let parsed = parse_type_spelling(&value.to_string()); + assert_eq!( + parsed, value, + "`{}` parsed back to a different shape", + value + ); + assert_eq!(parsed.to_string(), value.to_string()); + } + + let parameter = ComputedType::TemplateParameter(SmolStr::new("T")); + let parsed = with_template_parameters(parse_type_spelling("T"), &["T"]); + assert_eq!(parsed, parameter); + assert_eq!(parsed.to_string(), parameter.to_string()); + } + + #[test] + fn a_boxed_named_type_renders_and_answers_members() { + let value = + ComputedType::named("std::vector", vec![ComputedType::Primary(PrimaryType::Int)]); + assert_eq!(value.to_string(), "std::vector"); + assert_eq!(value.class_name(), Some("std::vector")); + assert_eq!(value.arguments().len(), 1); + assert_eq!(value.arguments()[0].to_string(), "int"); + } + + #[test] + fn a_generic_type_renders_its_arguments() { + let value = ComputedType::named( + "std::vector", + vec![ComputedType::Pointer(Arc::new(ComputedType::Primary( + PrimaryType::Int, + )))], + ); + assert_eq!(value.to_string(), "std::vector"); + } + + #[test] + fn a_computed_type_substitutes_without_the_store() { + let value = ComputedType::named( + "std::pair", + vec![ + ComputedType::TemplateParameter(SmolStr::new("T")), + ComputedType::Pointer(Arc::new(ComputedType::TemplateParameter(SmolStr::new("T")))), + ], + ); + let concretely = value.substituted_by_bindings(&[( + SmolStr::new("T"), + ComputedType::Primary(PrimaryType::Int), + )]); + assert_eq!(concretely.to_string(), "std::pair"); + } + + /// **`replacing` still replaces a bare name and keeps the operators**, including inside a generic's arguments. + #[test] + fn replacing_a_name_keeps_the_shape() { + let value = ComputedType::Reference { + to: Arc::new(ComputedType::named( + "std::vector", + vec![ComputedType::named("value_type", Vec::new())], + )), + rvalue: false, + }; + let replaced = value.replacing("value_type", &ComputedType::Primary(PrimaryType::Int)); + assert_eq!(replaced.to_string(), "std::vector&"); + } +} diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 8b137891..0cbb19f9 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -1 +1,24 @@ +//! **Types as the index stores them** — as values, not as handles into an arena. +//! +//! A declaration's type used to be an interned handle into a `TypeStore`, resolved through the index that owned +//! the store. That arena is gone: a fact now carries the immutable [`ComputedType`] the builder lowered +//! from the declaration's own syntax, so a fact is meaningful wherever it travels — a summary, a cooked reading, a +//! query's display copy, or a decoded cache record — without a process-local id beside it. +//! +//! ```text +//! a declaration's syntax -> ComputedType (the one type definition, built at the parser boundary) +//! ``` +//! +//! There is no `TypeId`, no interning, no source-spelling side table, and no second type enum. Display is +//! [`ComputedType`]'s own `Display`, which is canonical: the written alias `short int` displays as `short`, and a +//! `struct` tag displays on the type that carries it. The semantic questions (`convertible_to`, `decay`, +//! `class_name`, `qualifiers`, `substituted`, …) live on [`ComputedType`] in [`semantics`]. +//! +//! The design and the migration order are in `docs/type-system-redesign.md`. +pub mod compute; +pub mod semantics; +pub use compute::{ + ArrayExtent, ComputedType, FunctionType, GenericType, PrimaryType, QualifiedType, +}; +pub use semantics::{Qualifiers, RecordTag}; diff --git a/crates/cpp_code_analysis/src/index/types/semantics.rs b/crates/cpp_code_analysis/src/index/types/semantics.rs new file mode 100644 index 00000000..4cf2f411 --- /dev/null +++ b/crates/cpp_code_analysis/src/index/types/semantics.rs @@ -0,0 +1,577 @@ +//! **The semantic questions a computed type answers** — conversion, decay, qualifiers, dependence and substitution. +//! +//! [`ComputedType`] is the crate's one type definition. This module holds the questions the old semantic type enum +//! used to answer, moved here so they operate on the value the facts actually carry: a conversion check, an +//! array-to-pointer decay, the class a type names, the `const`/`volatile` words written on it, and the template +//! substitution a member read out of a class template needs. +//! +//! ```text +//! convertible_to can a value of this type initialise that one? +//! decay what a value of this type is when it is used +//! qualifiers the const/volatile words written on the object +//! depends_on_a_parameter does only instantiation finish this type? +//! substituted this type with a class template's arguments written in +//! ``` +//! +//! The structural walks (`class_name`, `arguments`, `pointee`, `replacing`) live beside the enum in +//! [`super::compute`]; this module is the relation and the rewrite, which are the operations that used to make the +//! second type enum worth having. +use super::GenericType; +use std::sync::Arc; + +use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; +use crate::sema; +use crate::sema::symbol::Known; +use crate::sema::types::TypeSubstitutions; + +/// **The qualifiers written on a type** — `const`, `volatile`, or both. +/// +/// The two are separate bits because they are separate questions: `volatile` says every access is an observable side +/// effect, `const` says assignment is not allowed, and a member list can hold `f()`, `f() const` and `f() volatile` at +/// once. Kept apart from [`ComputedType::Qualified`], which is the `is_const`/`is_volatile` shape the computed value +/// stores. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Qualifiers { + is_const: bool, + is_volatile: bool, +} + +impl Qualifiers { + pub const NONE: Qualifiers = Qualifiers { + is_const: false, + is_volatile: false, + }; + pub const CONST: Qualifiers = Qualifiers { + is_const: true, + is_volatile: false, + }; + pub const VOLATILE: Qualifiers = Qualifiers { + is_const: false, + is_volatile: true, + }; + + /// The qualifier a single word spells, if it is one. + pub fn of_a_word(word: &str) -> Option { + match word { + "const" => Some(Qualifiers::CONST), + "volatile" => Some(Qualifiers::VOLATILE), + _ => None, + } + } + + /// Both, in either order — `const volatile` and `volatile const` are one type. + pub fn with(self, other: Qualifiers) -> Qualifiers { + Qualifiers { + is_const: self.is_const || other.is_const, + is_volatile: self.is_volatile || other.is_volatile, + } + } + + pub fn is_const(self) -> bool { + self.is_const + } + + pub fn is_volatile(self) -> bool { + self.is_volatile + } + + pub fn is_none(self) -> bool { + !self.is_const && !self.is_volatile + } + + /// **The words when they lead the type** — `"const "`, `"volatile "`, `"const volatile "`, or nothing. + pub fn leading_words(self) -> &'static str { + match (self.is_const, self.is_volatile) { + (true, true) => "const volatile ", + (true, false) => "const ", + (false, true) => "volatile ", + (false, false) => "", + } + } + + /// **The words when they trail it** — `" const"`, `" volatile"`, `" const volatile"`, or nothing. + pub fn trailing_words(self) -> &'static str { + match (self.is_const, self.is_volatile) { + (true, true) => " const volatile", + (true, false) => " const", + (false, true) => " volatile", + (false, false) => "", + } + } +} + +/// **The keyword a C record type is written with** — `struct point`, `union value`. +/// +/// C's tag syntax is the one piece of a type's written form that the name alone cannot recover: a `typedef` can make +/// `point` a builtin in disguise, and only the keyword says that the name denotes a record. It is carried on the type +/// ([`ComputedType::ElaboratedRecord`]) rather than passed beside it, so a query that materializes a fact's type still +/// has the evidence and no consumer reads a spelling for it. +/// +/// `enum` is deliberately **not** here: an enumeration is an arithmetic type in C, and `enum colour c = 3;` is +/// ordinary code. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum RecordTag { + /// `struct point` + Struct, + /// `union value` + Union, +} + +impl RecordTag { + /// The keyword this tag is written with. + pub fn word(self) -> &'static str { + match self { + RecordTag::Struct => "struct", + RecordTag::Union => "union", + } + } + + /// **The record tag a written word introduces** — `struct`/`union`, and nothing else. + /// + /// `class`, `enum` and `typename` are elaborated specifiers too, and none of them is a C record tag: a `class` is + /// C++, an `enum` is arithmetic in C, and `typename` is a disambiguator. + pub fn of_a_word(word: &str) -> Option { + match word { + "struct" => Some(RecordTag::Struct), + "union" => Some(RecordTag::Union), + _ => None, + } + } +} + +/// **A pointee without its qualifiers**, and whether it had any — the shape a pointer-conversion question asks. +/// +/// `const char*` is a pointer to a *qualified* `char`, and the qualification is the whole difference between that and +/// `char*`: the first converts to the second and not the other way. Nothing else about a pointee is peeled here. +fn a_pointee_without_its_qualifiers(type_of: &ComputedType) -> (&ComputedType, bool) { + let mut current = type_of; + let mut qualified = false; + while let ComputedType::Qualified(of) = current { + qualified = true; + current = &of.of; + } + (current, qualified) +} + +/// **Does this type write a C record's tag anywhere in it?** — the cheap test that keeps the relation below from +/// rebuilding a type that carries none, which is nearly every type in a C++ project. +fn has_an_elaborated_record(type_of: &ComputedType) -> bool { + match type_of { + ComputedType::ElaboratedRecord { .. } => true, + ComputedType::Generic(generic) => generic.arguments.iter().any(has_an_elaborated_record), + ComputedType::Pointer(to) | ComputedType::Pack(to) => has_an_elaborated_record(to), + ComputedType::Reference { to, .. } => has_an_elaborated_record(to), + ComputedType::Qualified(qualified) => has_an_elaborated_record(&qualified.of), + ComputedType::Array { of, .. } => has_an_elaborated_record(of), + ComputedType::Function(function) => { + has_an_elaborated_record(&function.returns) + || function.parameters.iter().any(has_an_elaborated_record) + } + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + false + } + } +} + +/// **This type with C's record tags stripped** — the shape the conversion relation compares. +/// +/// The tag is evidence about *what a name denotes*, not a different structure: `struct point` and `point` are one +/// shape to the conversion relation. The one consumer that needs the tag — C's record rule — reads it *before* asking +/// this relation, in [`crate::sema::convert::conversion_to`]. +/// +/// Only called when [`has_an_elaborated_record`] is true, so a type with no tag is never rebuilt. +fn without_elaborated_records(type_of: &ComputedType) -> ComputedType { + match type_of { + ComputedType::ElaboratedRecord { of, .. } => without_elaborated_records(of), + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(without_elaborated_records) + .collect(), + })), + ComputedType::Pointer(to) => { + ComputedType::Pointer(Arc::new(without_elaborated_records(to))) + } + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(without_elaborated_records(to)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(without_elaborated_records(of)), + extent: extent.clone(), + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(without_elaborated_records(&function.returns)), + parameters: function + .parameters + .iter() + .map(without_elaborated_records) + .collect(), + })), + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(without_elaborated_records(of))), + ComputedType::Qualified(qualified) => ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(without_elaborated_records(&qualified.of)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })), + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + type_of.clone() + } + } +} + +impl ComputedType { + /// **A written builtin spelling as the computation layer holds it.** A primary this layer models answers a + /// [`PrimaryType`]; a spelling outside that set — a compiler extension such as `__int128`, or the empty spelling + /// of a deduced type — has no primary variant and is kept as a name, so its display is unchanged. + pub fn builtin(spelling: impl AsRef) -> ComputedType { + let spelling = spelling.as_ref(); + match PrimaryType::from_spelling(spelling) { + Some(primary) => ComputedType::Primary(primary), + None => ComputedType::Named(spelling.trim().into()), + } + } + + /// The qualifiers this type was written with, when it was written with any. + pub fn qualifiers(&self) -> Qualifiers { + match self { + ComputedType::Qualified(qualified) => { + let mut qualifiers = Qualifiers::NONE; + if qualified.is_const { + qualifiers = qualifiers.with(Qualifiers::CONST); + } + if qualified.is_volatile { + qualifiers = qualifiers.with(Qualifiers::VOLATILE); + } + qualifiers + } + ComputedType::Reference { to, .. } => to.qualifiers(), + _ => Qualifiers::NONE, + } + } + + /// **Is the object this type describes `volatile`** — the same rule as [`ComputedType::is_const`], and a + /// separate bit because `volatile int` is neither a const object nor an unqualified one. + pub fn is_volatile(&self) -> bool { + match self { + ComputedType::Qualified(qualified) => qualified.is_volatile, + ComputedType::Reference { to, .. } => to.is_volatile(), + _ => false, + } + } + + /// **Is this `bool`** — the type a condition already is, and therefore not a conversion of anything. + /// + /// Asked through the qualifiers on purpose: `bool const flag = …; if (flag)` converts nothing. + pub fn is_bool(&self) -> bool { + match self { + ComputedType::Primary(primary) => *primary == PrimaryType::Bool, + ComputedType::Qualified(qualified) => qualified.of.is_bool(), + _ => false, + } + } + + /// Is this one of the arithmetic primaries, possibly under a qualifier? + pub fn is_arithmetic(&self) -> bool { + match self { + ComputedType::Primary(primary) => primary.is_arithmetic(), + ComputedType::Qualified(qualified) => qualified.of.is_arithmetic(), + _ => false, + } + } + + /// **What an expression of this type is when it is *used*** — the two conversions C++ applies before almost every + /// operator: an lvalue-to-rvalue conversion, which drops the top-level reference, and an array-to-pointer decay. + /// + /// The decay is **one level**: `int[2][3]` decays to `int[3]*`, not `int**`. A qualifier survives the decay, + /// because the thing it qualifies does: `const int arr[4]` used as a value is a pointer to a const `int`. + pub fn decay(&self) -> ComputedType { + match self { + ComputedType::Reference { to, .. } => to.decay(), + ComputedType::Array { of, .. } => ComputedType::Pointer(Arc::clone(of)), + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified.of.decay()), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + other => other.clone(), + } + } + + /// **Can a value of this type initialise one of `target`?** + /// + /// The one relation the two type checks are made of — `int x = "three";` is an assignment and `f("three")` is a + /// parameter, and both are the same question asked at a different place. `Known::Yes` and `Known::No` are answers; + /// `Known::Unknown` is the absence of one, and a check reports only a definite `No`. + /// + /// What it answers: + /// + /// ```text + /// identical after decay -> Yes `int` to `int`, `const char*` to `const char*` + /// arithmetic to arithmetic -> Yes `double` to `int`, `char` to `long` + /// array or function to pointer -> Yes `int[4]` to `int*` + /// pointer to arithmetic, or the reverse -> No `const char*` to `int` + /// any object pointer to `void*` -> Yes `int*` to `void*`, `Widget*` to `void*` + /// a pointer that drops `const` into it -> No `const char*` to `void*` + /// `void*` to an object pointer -> Unknown C converts it and C++ does not; the language is not known here + /// anything to `void`, or `void` to it -> No no object has type `void` + /// anything named, or a template parameter-> Unknown `S` may have a converting constructor + /// pointer to a different pointee -> Unknown `Derived*` to `Base*` is a real conversion + /// a reference target -> the referent's question `const int&` asked as `int` + /// ``` + pub fn convertible_to(&self, target: &ComputedType) -> Known<()> { + use crate::sema::symbol::Known; + + // **C's record tags are not part of the relation.** `struct point` and `point` are one shape here — the tag is + // evidence about what the name denotes, and [`crate::sema::convert::conversion_to`] reads it before asking + // this question. Stripping the wrapper keeps the relation's answers exactly what they were when the + // declaration reader dropped the keyword, and the guard avoids rebuilding the many types that carry none. + let from_without_tags; + let from = if has_an_elaborated_record(self) { + from_without_tags = without_elaborated_records(self); + &from_without_tags + } else { + self + }; + let from = from.decay(); + let target_without_tags; + let target = if has_an_elaborated_record(target) { + target_without_tags = without_elaborated_records(target); + &target_without_tags + } else { + target + }; + // **A pointer does not bind to a non-const lvalue reference.** The peel below judges a reference by its + // referent, which is right for values and wrong for a pointer: `void println(ostream& __os)` called with a + // string literal is not a conversion to `ostream` at all, because the temporary a converting constructor could + // build cannot bind to a non-const reference. A **`const`** reference is left alone: there a temporary may be + // built, which is a class's constructors' question and not this relation's. + if let ComputedType::Reference { + to: referent, + rvalue: false, + } = target + && matches!(from, ComputedType::Pointer(_)) + && matches!( + &**referent, + ComputedType::Named(_) | ComputedType::Generic(_) + ) + { + return Known::No; + } + // **The target is not decayed**: array-to-pointer is a conversion the *source* undergoes; the destination of + // an initialisation keeps whatever shape it was written with. + // + // **A reference binds to its referent**, so the question is the one about the referent. A `const char*` + // argument against `const int&` is the same mistake as against `int`. + let to = match target { + ComputedType::Reference { to, .. } => &**to, + other => other, + }; + + // **Identical is always convertible**, before anything else is asked. + if &from == to { + return Known::Yes(()); + } + + // **`void` is not a value.** An object cannot have it, so nothing converts *to* it and it converts to + // nothing — written before the arithmetic rule, which would otherwise call `void` an arithmetic type. + if from.is_void() || to.is_void() { + return Known::No; + } + + match (&from, to) { + // The standard conversions between arithmetic types, which are unconditional. + (a, b) if a.is_arithmetic() && b.is_arithmetic() => Known::Yes(()), + + // Array-to-pointer and function-to-pointer. `decay` already did this, so a pair that arrives here with + // one side an array did not come through `decay` — kept for a caller that built the types by hand. + (ComputedType::Array { .. } | ComputedType::Function(_), ComputedType::Pointer(_)) => { + Known::Yes(()) + } + + // **A pointer and a number are not interconvertible here.** + (ComputedType::Pointer(_), b) if b.is_arithmetic() => Known::No, + (a, ComputedType::Pointer(_)) if a.is_arithmetic() => Known::No, + + // **Two pointers to different *builtin* pointees do not convert.** Class-to-class stays `Unknown` (a + // derived pointer converts), and a `void` pointee is decided by the arm below. + (ComputedType::Pointer(from_pointee), ComputedType::Pointer(to_pointee)) => { + let (from_core, from_qualified) = a_pointee_without_its_qualifiers(from_pointee); + let (to_core, to_qualified) = a_pointee_without_its_qualifiers(to_pointee); + let is_void = |type_of: &ComputedType| { + matches!(type_of, ComputedType::Primary(PrimaryType::Void)) + }; + if is_void(to_core) + && !is_void(from_core) + && !matches!(from_core, ComputedType::Function(_)) + { + // **`T*` to `void*` is a standard conversion** — and it is the conversion `malloc`, `free`, + // `memcpy`, `qsort` and every generic container in C is written with. The one thing a `void*` + // can get wrong is **dropping `const`**. A **function pointer** stays `Unknown`: the standard does + // not convert one to `void*`, POSIX does. + if from_qualified && !to_qualified { + Known::No + } else { + Known::Yes(()) + } + } else if is_void(from_core) || is_void(to_core) { + // **`void*` to `T*`** — C converts it implicitly and C++ needs a cast. This relation does not + // know which language it is answering for, so it declines. + Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( + "a conversion through `void*` is not decided here", + ))) + } else if from_core == to_core { + // **Qualification is the one difference that converts**: `char*` → `const char*` is implicit, the + // other direction is not (it drops the `const`). + if from_qualified && !to_qualified { + Known::No + } else { + Known::Yes(()) + } + } else if let ( + ComputedType::Array { + of: from_element, .. + }, + ComputedType::Array { of: to_element, .. }, + ) = (from_core, to_core) + { + // **Two arrays are one shape only when their elements are.** There is no array covariance. + let (from_element, _) = a_pointee_without_its_qualifiers(from_element); + let (to_element, _) = a_pointee_without_its_qualifiers(to_element); + if matches!(from_element, ComputedType::Primary(_)) + && matches!(to_element, ComputedType::Primary(_)) + { + Known::No + } else { + Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( + "a conversion between two arrays of named elements is not decided here", + ))) + } + } else if matches!(from_core, ComputedType::Primary(_)) + && matches!(to_core, ComputedType::Primary(_)) + { + // **Both pointees builtin, or no answer.** A `Named` pointee is a class *or an alias this layer + // has not substituted*, and comparing it with a builtin is a guess about a name rather than + // about a type. + Known::No + } else { + Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( + "a conversion between two class pointers is a hierarchy question", + ))) + } + } + + _ => Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( + "a conversion between these two types is not decided by their shapes", + ))), + } + } + + /// Is this a template parameter, or does it *contain* one anywhere? + /// + /// The predicate a caller uses to tell "the answer is not known yet" from "the answer is not here": a type + /// holding a template parameter is one that only instantiation can finish, and this analysis does not instantiate. + pub fn depends_on_a_parameter(&self) -> bool { + match self { + ComputedType::TemplateParameter(_) => true, + ComputedType::Generic(generic) => generic + .arguments + .iter() + .any(ComputedType::depends_on_a_parameter), + ComputedType::Pointer(to) | ComputedType::Pack(to) => to.depends_on_a_parameter(), + ComputedType::Reference { to, .. } | ComputedType::ElaboratedRecord { of: to, .. } => { + to.depends_on_a_parameter() + } + ComputedType::Qualified(qualified) => qualified.of.depends_on_a_parameter(), + ComputedType::Array { of, .. } => of.depends_on_a_parameter(), + ComputedType::Function(function) => { + function.returns.depends_on_a_parameter() + || function + .parameters + .iter() + .any(ComputedType::depends_on_a_parameter) + } + ComputedType::Primary(_) | ComputedType::Named(_) => false, + } + } + + /// **This type with the template parameters in `substitutions` replaced** — the one operation that makes a + /// member of a class template answerable. + /// + /// `std::vector::size_type` with `T = int` is `std::size_t`, and the substitution is by **name**: the + /// parameters of a class template are a fixed list, the arguments are written at the use, and the pairing between + /// them is positional. This is not instantiation — no body is re-read, no overload is chosen, no dependent name + /// is resolved. + /// + /// * a parameter that appears **inside an expression** (`T::value_type`, `decltype(sizeof(T))`) is substituted as + /// a name and not evaluated; + /// * a **dependent** name (`typename T::value_type`) has nothing to substitute *into* until `T` is known, and + /// this returns it unchanged — see [`ComputedType::depends_on_a_parameter`]; + /// * a **partial** substitution is the ordinary case: `std::pair` with `T` unknown substitutes the + /// `int`, which is what makes `second` answerable and `first` not. + pub fn substituted>( + &self, + substitutions: &TypeSubstitutions<'_, N>, + ) -> ComputedType { + match self { + // **A name that is in the parameter list *is* the parameter**, and this arm is why the substitution can be + // done at all for a member read out of a header: `template struct vector { _Ty& front; };` + // writes `_Ty` and spells it exactly like a class name — what makes it a parameter is the list it was + // declared in. + ComputedType::Named(name) => substitutions + .get(name) + .cloned() + .unwrap_or_else(|| self.clone()), + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(|argument| argument.substituted(substitutions)) + .collect(), + })), + ComputedType::TemplateParameter(name) => substitutions + .get(name) + .cloned() + .unwrap_or_else(|| self.clone()), + ComputedType::Pointer(to) => { + ComputedType::Pointer(Arc::new(to.substituted(substitutions))) + } + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(to.substituted(substitutions)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(of.substituted(substitutions)), + extent: extent.clone(), + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(function.returns.substituted(substitutions)), + parameters: function + .parameters + .iter() + .map(|parameter| parameter.substituted(substitutions)) + .collect(), + })), + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(of.substituted(substitutions))), + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified.of.substituted(substitutions)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + // **The tag stays where it was written.** Substituting a name inside `struct point` is not the ordinary + // case (a record's name is not a template parameter), and keeping the wrapper is the structural rule. + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.substituted(substitutions)), + }, + ComputedType::Primary(_) => self.clone(), + } + } +} diff --git a/crates/cpp_code_analysis/src/lib.rs b/crates/cpp_code_analysis/src/lib.rs index 4e7f0419..dcfc64ab 100644 --- a/crates/cpp_code_analysis/src/lib.rs +++ b/crates/cpp_code_analysis/src/lib.rs @@ -55,7 +55,7 @@ // preprocessor's state, not a public API. // // `type_complexity`: the memo tables are spelled out where they are declared — -// `RefCell>>` is the answer to "what have I already been asked", and naming +// `RefCell>>` is the answer to "what have I already been asked", and naming // it `TypeMemo` would move the shape away from the one place a reader checks it against the code that inserts into it. #![allow(clippy::too_many_arguments, clippy::type_complexity)] #[macro_use] @@ -128,7 +128,8 @@ pub use align::{ pub use completion::{ BUILTIN_TYPES, CompletionContext, CompletionItem, CompletionSet, DIRECTIVES, DirectiveName, Header, HeaderIndex, HeaderKind, ItemKind, KEYWORDS, Keyword, KeywordUse, SNIPPETS, - SharedHeaders, Snippet, completion_at, context_at, detail_of, header_index, why_no_members, + SharedHeaders, Snippet, completion_at, context_at, detail_of_with_types, header_index, + why_no_members, }; pub use cooked::{FileMacros, Over, ParsedDefinitions, configuration_from_environment_and}; pub use file::token; @@ -136,19 +137,22 @@ pub use include::{config, graph, msvc, paths, system_headers, toolchain}; pub use macros::{MacroBindings, UnitSources}; pub use preprocess::{condition, cooked, directive, expand, guards, macros}; pub use sema::check::{CheckConfig, CheckContext, DiagnosticCode, Finding}; -pub use sema::declarations::{build_facts, by_name, declared_type_of, scope_of}; +pub use sema::declarations::{ + build_facts, by_name, declared_type_of, facts_with_their_types, scope_of, +}; pub use sema::{check, module_info, modules, parser_symbols, scopes, symbol}; // `tu_cache` is gone: a built `TranslationUnit` is not persisted any more — see `Session::translation_unit_of`. pub use memory::MemoryReport; pub use summary::ConditionalBody; pub use summary::{ - ClosureEvidence, ConditionAt, ConditionalRegion, CookedDiagnostic, DeclFact, DeclKind, - DeclModifiers, FactGuard, FileSummary, GuardBranch, IncludeFact, IndexedRendering, IndexedUnit, - MacroAt, MacroDefinitions, MacroFact, MacroKind, MacroView, MapReport, OutlineSymbol, - ReflectionFact, RenderedUnit, SummaryGuards, TranslationUnit, UnitDefinitions, UnitReading, - UnitSpan, macros_from_direct_includes, macros_from_direct_includes_with_bodies, - macros_from_the_closure_with_bodies, macros_in_force_before_the_include, outline_of, + ClosureEvidence, ConditionAt, ConditionalRegion, ConstraintArgument, ConstraintFact, + CookedDiagnostic, DeclFact, DeclKind, DeclModifiers, DeclaredType, FactGuard, FileSummary, + GuardBranch, IncludeFact, IndexedRendering, IndexedUnit, MacroAt, MacroDefinitions, MacroFact, + MacroKind, MacroView, MapReport, OutlineSymbol, ReflectionFact, RenderedUnit, SummaryGuards, + TranslationUnit, UnitDefinitions, UnitReading, UnitSpan, macros_from_direct_includes, + macros_from_direct_includes_with_bodies, macros_from_the_closure_with_bodies, + macros_in_force_before_the_include, outline_of, }; // `guard` is the exception: `preprocess::guard` and `preprocess::guards` differ by one letter, which is exactly // the hazard the folders are meant to remove, so the *analysis* keeps the plural name and the types are reached diff --git a/crates/cpp_code_analysis/src/sema/builtins/mod.rs b/crates/cpp_code_analysis/src/sema/builtins/mod.rs index 38c17483..a8cb5611 100644 --- a/crates/cpp_code_analysis/src/sema/builtins/mod.rs +++ b/crates/cpp_code_analysis/src/sema/builtins/mod.rs @@ -33,7 +33,7 @@ //! * [`traits`] — the `__is_*` family: what each one asks, and which of them the written arguments decide. //! * [`transforms`] — the builtins that *are* a type rather than a question about one. -use crate::sema; +use crate::index::types::ComputedType; pub mod traits; pub mod transforms; @@ -49,7 +49,7 @@ pub enum Answer { /// A `bool` whose value is not decided: the type is `bool` and the question is left open. UndecidedBoolean, /// A builtin that produces a type: `__decay(x)` is `int` for an `int&`. - Type(sema::types::Type), + Type(ComputedType), /// A name this layer knows is a builtin and will not answer for. Unmodelled, } diff --git a/crates/cpp_code_analysis/src/sema/builtins/traits.rs b/crates/cpp_code_analysis/src/sema/builtins/traits.rs index b7638dd2..ae1936a3 100644 --- a/crates/cpp_code_analysis/src/sema/builtins/traits.rs +++ b/crates/cpp_code_analysis/src/sema/builtins/traits.rs @@ -23,6 +23,7 @@ //! is right" — see the note on `DeclFact::pattern`. use super::{Answer, Builtin, Kind}; +use crate::index::types::ComputedType; use crate::sema; /// **Which question a trait asks.** One variant per question this layer can tell apart, because two intrinsics that @@ -284,13 +285,15 @@ fn same(arguments: &[String]) -> Option { fn shape(written: &str) -> Shape<'_> { let written = written.trim(); match sema::types::parse_type_spelling(written) { - sema::types::Type::Pointer { .. } => Shape::Pointer, - sema::types::Type::Reference { rvalue, .. } => Shape::Reference { rvalue }, - sema::types::Type::Array { extent, .. } => Shape::Array(extent.is_some()), - sema::types::Type::Function { .. } => Shape::Function, + ComputedType::Pointer(_) => Shape::Pointer, + ComputedType::Reference { rvalue, .. } => Shape::Reference { rvalue }, + // **A named bound is a bound**: `int a[COUNT]` is a bounded array even though this layer does not know + // `COUNT`, and `int a[]` is the unbounded one. + ComputedType::Array { extent, .. } => Shape::Array(extent.is_specified()), + ComputedType::Function(_) => Shape::Function, // The name a builtin was written with, read back off the spelling rather than off the parsed type: the // parsed type of `void` carries the same word, and this keeps the two spellings' agreement obvious. - sema::types::Type::Builtin { .. } => Shape::Builtin(written), + ComputedType::Primary(_) => Shape::Builtin(written), _ => Shape::Open, } } diff --git a/crates/cpp_code_analysis/src/sema/builtins/transforms.rs b/crates/cpp_code_analysis/src/sema/builtins/transforms.rs index d345cd23..1482d47c 100644 --- a/crates/cpp_code_analysis/src/sema/builtins/transforms.rs +++ b/crates/cpp_code_analysis/src/sema/builtins/transforms.rs @@ -15,7 +15,7 @@ //! # What a real transform would look like //! //! The shape is ready for one: [`apply`] takes the written arguments and answers an [`Answer`], and the type algebra -//! it needs already exists (`Type::Pointer`, `Type::Reference`, `Type::Array`, and the pack variant). The two names +//! it needs already exists (`ComputedType::Pointer`, `ComputedType::Reference`, `ComputedType::Array`, and the pack variant). The two names //! below are the ones that would have to be answered by something *other* than the algebra — an enum's underlying //! type is a fact about a declaration, and `__make_integer_seq` builds a sequence this layer has no spelling for — //! which is exactly why they are the two left unmodelled rather than the two that were hard to reach. diff --git a/crates/cpp_code_analysis/src/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index 9264eba2..db9ec3de 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -14,90 +14,62 @@ //! Nothing here decides anything: each function answers `None` for the shapes a reader cannot place (a macro's //! arguments, a list with no parameter), and every caller turns that into its own kind of silence. +use crate::index; use cpp_parser::CppDeclarator; +use cpp_parser::CppParam; use cpp_parser::CppParamList; -use cpp_parser::CppParser; -use cpp_parser::ParserConfig; -use cpp_parser::first_child_of_kind; use cpp_parser::token_at; use cpp_parser::{CppAstNode, CppSyntaxKind, CppSyntaxNode}; use crate::FileView; use crate::sema::scopes::parameters_of; -/// **The parameter names of a declaration read from its own text**, for a file with no rendering. -/// -/// `parameter_list` is what the index stores — `(const char* __format, ...)`, parentheses included — so the names -/// are read by **parsing one synthetic declaration** around it: `void __hint(const char* __format, ...);`. The -/// tree then tells a name from a type, which is the one thing splitting on commas gets wrong: `int (*f)(int)`, -/// `const Widget& w`, a default argument containing a comma (`map m = {}`), and `...` all come out -/// right because they are not text to this function. -/// -/// `None` for a list with no parameter (a `()`), which is also the answer for a declaration whose fact was written -/// before the field existed. -pub(crate) fn parameter_names_from_text(parameter_list: &str) -> Option>> { - let text = format!("void __hint{parameter_list};"); - let tree = CppParser::parse(&text, ParserConfig::default()); - let root = tree.get_red_root(); - - let declarator = root - .descendants() - .find(|node| CppDeclarator::can_cast(node.kind().into()))?; - let list = first_child_of_kind(&declarator, &[CppSyntaxKind::ParameterList])?; - - let names: Vec> = parameters_of(&list) +/// **Parameter names from the CST list itself**, slot for slot. +pub(crate) fn parameter_names_of_list(list: &CppParamList) -> Vec> { + parameters_of(list.syntax()) .into_iter() .map(|(_, declared)| declared.map(|(name, _)| name.text())) - .collect(); + .collect() +} - (!names.is_empty()).then_some(names) +/// **A parameter list with a pack expansion**, read from its tokens. +pub(crate) fn parameter_list_has_a_pack(list: &CppParamList) -> bool { + list.syntax() + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .any(|token| { + cpp_parser::CppTokenKind::from(token.kind()) == cpp_parser::CppTokenKind::Ellipsis + }) } -/// **The parameters of a written list, with their spans in that list** — the tree's answer to a question a -/// fallback signature has only text for. -/// -/// A fact's `parameter_list` is a string such as `(const char* __format, ...)`. Splitting it on top-level commas is -/// not the grammar: `operator<`, a default argument containing a comma (`std::map m = {}`), a function -/// pointer's nested list, and a lambda's braces all have commas that are not separators. The string is parsed as one -/// synthetic declaration — `void __hint(const char* __format, ...);` — and the parameter nodes are then the answer. -/// This is the same synthetic parse [`parameter_names_from_text`] uses, reused rather than growing a second scanner. +/// The names of a declaration's parameters, from the **index-resolved** CST facts. /// -/// The returned ranges are byte offsets **into `parameter_list`**, and the text is right-trimmed as the signature -/// label spells it. `None` when the text is not a parameter list this parser can read; a signature should then show -/// its label without parameter spans rather than point a client at the wrong bytes. -pub(crate) fn parameters_in_a_written_list( - parameter_list: &str, -) -> Option, String)>> { - if !parameter_list.trim_start().starts_with('(') { +/// The caller resolves the facts through the arena that owns the declaration — a summary's `ParamsStore`, a cooked +/// reading's, or the index's synthetic arena — with [`crate::ProjectIndex::parameter_facts_of`]; there is no second +/// copy on the fact to fall back to. +pub(crate) fn parameter_names_of_fact( + indexed: &[index::params::ParameterFact], +) -> Option>> { + parameter_names_of_facts(indexed) +} + +pub(crate) fn parameter_names_of_facts( + facts: &[index::params::ParameterFact], +) -> Option>> { + if facts.is_empty() { return None; } + Some( + facts + .iter() + .map(|fact| fact.name.as_ref().map(ToString::to_string)) + .collect(), + ) +} - let text = format!("void __hint{parameter_list};"); - let tree = CppParser::parse(&text, ParserConfig::default()); - let root = tree.get_red_root(); - let declarator = root - .descendants() - .find(|node| CppDeclarator::can_cast(node.kind().into()))?; - let list = first_child_of_kind(&declarator, &[CppSyntaxKind::ParameterList])?; - let list_start = usize::from(list.text_range().start()); - - let parameters: Vec<(std::ops::Range, String)> = parameters_of(&list) - .into_iter() - .filter_map(|(parameter, _)| { - let raw = parameter.text().to_string(); - let text = raw.trim(); - if text.is_empty() { - return None; - } - let leading = raw.len() - raw.trim_start().len(); - let trailing = raw.len() - raw.trim_end().len(); - let start = usize::from(parameter.text_range().start()) - list_start + leading; - let end = usize::from(parameter.text_range().end()) - list_start - trailing; - Some((start..end, text.to_string())) - }) - .collect(); - - Some(parameters) +/// **The parameter list node a declarator owns.** The fact builder calls this; no synthetic text parse. +pub(crate) fn parameter_list_node(declarator: &CppSyntaxNode) -> Option { + the_param_list_rising(declarator) } /// The declaration's **own** parameter list: the one belonging to the declarator the named at `offset` is a name @@ -154,6 +126,30 @@ fn the_param_list_rising(declarator: &CppSyntaxNode) -> Option { None } +/// **A parameter list as one display line**, built from its `CppParam` nodes. It never re-parses the list; each +/// parameter's source text is collapsed only for the label. +pub(crate) fn render_parameter_list(list: &CppParamList) -> String { + let mut out = String::from("("); + for (at, (parameter, _)) in parameters_of(list.syntax()).into_iter().enumerate() { + if at > 0 { + out.push_str(", "); + } + out.push_str( + &CppParam::cast(parameter.clone()) + .map(|parameter| parameter.one_line_text()) + .unwrap_or_else(|| parameter.text().to_string()), + ); + } + if list.is_variadic() && !out.ends_with("...") { + if out != "(" { + out.push_str(", "); + } + out.push_str("..."); + } + out.push(')'); + out +} + /// The **text** of that list, as the file writes it — `(_Ty* _First, size_type _Count)`, parentheses included. /// /// One function for the two readers that want the spelling rather than the nodes: a declaration's fact @@ -167,116 +163,7 @@ pub(crate) fn parameter_list_text(declarator: &CppSyntaxNode) -> Option // card printed `lua_setfield(…)` and no inlay hint was placed — Lua writes its whole public API that way. let list = the_param_list_rising(declarator)?; - Some(tidy_list_text(&list.syntax().text().to_string()).0) -} - -/// **A list as one line, and where every byte of the original went.** -/// -/// # The layout is taken out, and the spelling is not -/// -/// A node's text is the *source* text, which is laid out for a reader of the file rather than for a one-line -/// summary: measured on MSVC's ``, `basic_istream<_Elem, _Traits>&& _Istr` arrives with a `\r\n` and four -/// spaces of indentation in the middle, and MSVC's `` wraps three of `basic_string::append`'s nine -/// overloads the same way. A **cooked** reading arrives with the rendering's own separator instead — one space -/// between every token, so `format_string<_Types...>` is spelled `format_string < _Types ... >`. -/// -/// So whitespace runs become one space, and the space inside the brackets this list is made of goes: after `(` and -/// before `)` and `,`. Those three are safe to decide lexically — a parameter list's own parentheses and commas are -/// never comparison operators — while `<`, `>` and `...` are deliberately left alone, because `(bool _B = 1 < 2)` -/// is a parameter list too and a rule that pulled `1 <2` together would be inventing a different expression. -/// -/// What is *not* done is the rest of the rendering's spacing (`_Elem * ()`, `_NODISCARD _CONSTEXPR20 size_type`): -/// that is how every spelling in a fact is written, and a parameter list that read differently from the return type -/// beside it would be two conventions in one line. -/// -/// # Why the map comes back with it -/// -/// Because the other reader is a **signature**, whose parameters are byte spans *inside* the label it builds -/// ([`crate::signature::CallSignature::parameters`]) — a client bolds them. Tidying the text without moving the -/// spans would put the highlight on the wrong bytes, which is worse than the newline it removed. `map[i]` is where -/// byte `i` of `text` ended up, with one entry per byte plus one for the end, so a span `a..b` becomes -/// `map[a]..map[b]` whatever the two ends are. -pub(crate) fn tidy_list_text(text: &str) -> (String, Vec) { - let bytes = text.as_bytes(); - let mut out = String::with_capacity(text.len()); - let mut map = vec![0usize; text.len() + 1]; - let mut wrote_a_word = false; - let mut at = 0usize; - - while at < bytes.len() { - // **A comment is not part of the list.** A summary's parameter list is the *file's* text, and a declaration - // written across lines with a comment beside each parameter keeps those comments in it: - // - // ```c - // static Decimal *decimal_new( - // sqlite3_context *pCtx, /* Report error here, if not null */ - // sqlite3_value *pIn, /* Construct the decimal object from this */ - // ``` - // - // `parameters_in` then split on the comma *inside* the comment, and the spelling of one parameter became - // "`if not null */ sqlite3_value *`" — measured on sqlite, six `param-type-check` findings about a type no - // file writes. The bytes are dropped from the text and land on the position of the next word, so a span - // inside a comment maps into the word that follows it rather than into nothing. - if bytes[at] == b'/' - && at + 1 < bytes.len() - && (bytes[at + 1] == b'*' || bytes[at + 1] == b'/') - { - let line_comment = bytes[at + 1] == b'/'; - let mut end = at + 2; - while end < bytes.len() { - if line_comment && bytes[end] == b'\n' { - break; - } - if !line_comment - && bytes[end] == b'*' - && end + 1 < bytes.len() - && bytes[end + 1] == b'/' - { - end += 2; - break; - } - end += 1; - } - for slot in &mut map[at..end.min(bytes.len())] { - *slot = out.len(); - } - at = end; - continue; - } - - if bytes[at].is_ascii_whitespace() { - // Whitespace lands where the next word will start, before the separator is decided: no span begins or - // ends in it — a span is a whole parameter, and each is trimmed. - map[at] = out.len(); - at += 1; - continue; - } - - let mut end = at; - while end < bytes.len() && !bytes[end].is_ascii_whitespace() { - end += 1; - } - let word = &text[at..end]; - - if wrote_a_word { - let after_an_open = out.ends_with('(') || out.ends_with('['); - let before_a_close = - word.starts_with(')') || word.starts_with(']') || word.starts_with(','); - if !after_an_open && !before_a_close { - out.push(' '); - } - } - - for (offset, slot) in map[at..end].iter_mut().enumerate() { - *slot = out.len() + offset; - } - out.push_str(word); - wrote_a_word = true; - at = end; - } - - map[text.len()] = out.len(); - (out, map) + Some(render_parameter_list(&list)) } /// The argument expressions of a call, in order. @@ -302,79 +189,3 @@ pub(crate) fn arguments_of(call: &CppSyntaxNode) -> Option> { (!arguments.is_empty() && !unread).then_some(arguments) } - -#[cfg(test)] -mod tests { - use super::*; - - /// **A comment between two parameters is not part of the list.** A summary`s parameter list is the file`s own - /// text, and sqlite writes one declaration per parameter with a comment beside each: - /// - /// ```c - /// static Decimal *decimal_new( - /// sqlite3_context *pCtx, /* Report error here, if not null */ - /// sqlite3_value *pIn, /* Construct the decimal object from this */ - /// ``` - /// - /// The comma inside the first comment split the list, and a parameter`s spelling became - /// `if not null */ sqlite3_value *` — measured on sqlite, six `param-type-check` findings about a type no file - /// writes. - #[test] - fn a_comment_inside_a_parameter_list_is_dropped() { - let (text, _map) = tidy_list_text( - "(sqlite3_context *pCtx, /* Report error here, if not null */\n sqlite3_value *pIn)", - ); - assert_eq!(text, "(sqlite3_context *pCtx, sqlite3_value *pIn)"); - assert!( - !text.contains("*/") && !text.contains("if not null"), - "no comment text survives: {text}" - ); - } - - /// A line comment ends at the newline, and the parameter after it is still one word. - #[test] - fn a_line_comment_ends_at_the_newline() { - let (text, _map) = tidy_list_text("(int a, // the first\n int b)"); - assert_eq!(text, "(int a, int b)"); - } - - /// **A comma inside a default argument does not split a parameter**, and neither does a comparison operator. - /// - /// This is the fallback signature's splitter replaced by the parser: the old text walk treated `<` as a template - /// depth and `std::map` as nested, which was right there, but `bool ok = 1 < 2` opened a depth it never - /// closed and swallowed the next parameter. - #[test] - fn parameters_in_a_written_list_follow_the_grammar() { - let parameters = parameters_in_a_written_list( - "(int first, bool ok = 1 < 2, std::map values = {})", - ) - .expect("the synthetic declaration parses"); - - let texts: Vec<&str> = parameters.iter().map(|(_, text)| text.as_str()).collect(); - assert_eq!( - texts, - [ - "int first", - "bool ok = 1 < 2", - "std::map values = {}" - ], - "the commas inside the default argument and the template stay inside their parameter" - ); - for (range, text) in ¶meters { - assert_eq!( - &"(int first, bool ok = 1 < 2, std::map values = {})"[range.clone()], - text, - "each span points at the parameter it names" - ); - } - } - - /// A function pointer's nested list is one parameter, not two. - #[test] - fn a_function_pointer_parameter_is_one_span() { - let parameters = parameters_in_a_written_list("(int (*callback)(int a, int b), int count)") - .expect("the synthetic declaration parses"); - let texts: Vec<&str> = parameters.iter().map(|(_, text)| text.as_str()).collect(); - assert_eq!(texts, ["int (*callback)(int a, int b)", "int count"]); - } -} diff --git a/crates/cpp_code_analysis/src/sema/check/abstract_class_instantiated.rs b/crates/cpp_code_analysis/src/sema/check/abstract_class_instantiated.rs index 9ce88afc..6441224d 100644 --- a/crates/cpp_code_analysis/src/sema/check/abstract_class_instantiated.rs +++ b/crates/cpp_code_analysis/src/sema/check/abstract_class_instantiated.rs @@ -60,7 +60,8 @@ impl Check for AbstractClassInstantiated { .iter() .filter(|fact| fact.kind == DeclKind::Variable) .filter_map(|fact| { - let class = a_class_name(fact.type_of.as_deref()?)?; + let spelled = context.index().type_spelling_of(fact)?; + let class = a_class_name(&spelled)?; Some((class, fact.name.to_string(), fact.name_range)) }) .collect(); @@ -74,14 +75,21 @@ impl Check for AbstractClassInstantiated { // override is still abstract. let mut every_pure_is_overridden = true; for member in list.members.iter().filter(|member| { - member.fact.kind == DeclKind::Function - && member.fact.modifiers.contains(DeclModifiers::PURE) + context.index().member_kind(member) == Some(DeclKind::Function) + && context + .index() + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::PURE)) }) { let overridden = list.members.iter().any(|other| { - other.fact.kind == DeclKind::Function - && other.fact.name == member.fact.name + context.index().member_kind(other) == Some(DeclKind::Function) + && context.index().member_name(other) + == context.index().member_name(member) && other.depth < member.depth - && !other.fact.modifiers.contains(DeclModifiers::PURE) + && context + .index() + .member_modifiers(other) + .is_some_and(|modifiers| !modifiers.contains(DeclModifiers::PURE)) }); if !overridden { every_pure_is_overridden = false; diff --git a/crates/cpp_code_analysis/src/sema/check/access_invisible.rs b/crates/cpp_code_analysis/src/sema/check/access_invisible.rs index 7642a7e6..42c03a4c 100644 --- a/crates/cpp_code_analysis/src/sema/check/access_invisible.rs +++ b/crates/cpp_code_analysis/src/sema/check/access_invisible.rs @@ -43,6 +43,7 @@ use super::is_a_class_definition; use crate::Known; use crate::ScopeKind; +use crate::file::coordinates::FileOffset; use cpp_parser::CppSyntaxNode; use cpp_parser::CppTokenKind; use cpp_parser::source_range; @@ -132,15 +133,24 @@ impl Check for AccessInvisible { let Some(member) = members .members .iter() - .find(|member| member.fact.name == access.member) + .find(|member| context.index().member_name(member) == access.member) else { // Not this rule's question: a name that is not there is `undefined-field`'s. continue; }; + let Some(member_range) = context + .index() + .member_fact(member) + .map(|fact| fact.range.start_offset) + else { + continue; + }; // **The declaration of that member, in this file** — found by the range the member list reports, which - // is the name's. A member declared in another file is not here, and this check does not judge it, so the - // node must also be one this file wrote (see `own_syntax_nodes`). + // is the name's. The range is the **file's** (the fact belongs to the file's arena), and this check's + // tree is the rendering, so it is mapped before it is used as a tree offset. A member declared in + // another file is not here, and this check does not judge it, so the node must also be one this file + // wrote (see `own_syntax_nodes`). // // **Not `own_syntax_nodes().find(..)`**, which is what this was: that iterator walks the whole file's // tree, and it did so **once per member access**. Measured on `LuaSyntaxTree.cpp` — a 2 800-line file @@ -148,11 +158,16 @@ impl Check for AccessInvisible { // `CPPLS_NO_INFERENCE=1` makes the rule answer before it ever gets here, so the A/B that attributed // 96% of the layer to inference did not see it. A token at the offset and its ancestors reach the same // node in O(depth). - let Some(declaration) = - declaration_starting_at(context, member.fact.range.start_offset) + let Some(in_the_rendering) = context + .view + .reading_offset_of(FileOffset::new(member_range)) else { continue; }; + let member_range = in_the_rendering.get(); + let Some(declaration) = declaration_starting_at(context, member_range) else { + continue; + }; if !context .view .was_written_here(source_range(declaration.text_range())) @@ -163,7 +178,7 @@ impl Check for AccessInvisible { continue; }; - let visibility = visibility_of(&class, member.fact.range.start_offset); + let visibility = visibility_of(&class, member_range); if visibility == Access::Public { continue; } diff --git a/crates/cpp_code_analysis/src/sema/check/argument_count.rs b/crates/cpp_code_analysis/src/sema/check/argument_count.rs index 5d519468..853148c5 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -41,10 +41,13 @@ use crate::BindingKind; use crate::DeclKind; use crate::Known; use crate::file; +use crate::index; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppAstNode; use cpp_parser::CppCallExpr; use cpp_parser::CppDeclaration; +use cpp_parser::CppParam; use cpp_parser::CppParamList; use cpp_parser::CppTokenKind; use cpp_parser::source_range; @@ -63,9 +66,10 @@ struct Callee { written: usize, /// The declaration ends in `...`, so any number of arguments above `required` is allowed. variadic: bool, - /// **The parameter types**, in order, with the parameter names dropped — what the overload resolver ranks a call - /// against. `f(int)` and `f(const char*)` are `["int"]` and `["const char*"]`; `f(int n)` is `["int"]`. - parameters: Vec, + /// **The parameter types**, in order, structurally — what the overload resolver ranks a call against. A parameter + /// is lowered from its own node (`f(int n)` is `int`) or resolved from its fact; no name is stripped from text and + /// no spelling is parsed. + parameters: Vec, } impl Check for ArgumentCount { @@ -171,14 +175,14 @@ impl Check for ArgumentCount { let declared = match declared.as_slice() { [only] => only, several => { - // The engine answers with a parsed `Type` and the file it came from; the resolver ranks spellings, - // which is the same information in the form both the file half and the index half of this check - // have. An `Unknown` travels with its reason rather than becoming "no type". - let types: Vec> = call + // The engine answers with a parsed `ComputedType` and the file it came from; the resolver ranks + // structures, which is the same information in the form both the file half and the index half of + // this check have. An `Unknown` travels with its reason rather than becoming "no type". + let types: Vec> = call .get_args() .iter() .map(|argument| match context.type_of(argument.syntax()) { - Known::Yes((a_type, _)) => Known::Yes(a_type.to_string()), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -189,7 +193,12 @@ impl Check for ArgumentCount { sema::overload::Candidate::new( callee.parameters.clone(), callee.variadic, - callee.parameters.join(", "), + callee + .parameters + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "), ) }) .collect(); @@ -253,7 +262,7 @@ fn callees_in_this_file( let mut written = 0usize; let mut required = 0usize; let mut variadic = false; - let mut spellings: Vec = Vec::new(); + let mut parameters_written: Vec = Vec::new(); for parameter in parameters.children() { // **Read from the tokens**, not from the parameter's text: a `...` is a token, an `=` is a different // token, and a default value that happens to hold an `=` — `int n = a == b` — is a string of tokens @@ -275,12 +284,16 @@ fn callees_in_this_file( if !kinds.contains(&CppTokenKind::Assign) { required += 1; } - // **The parameter's own text.** `spelling_of` is for the declarator and expression nodes a declaration's - // name is read from, and answers `None` for a parameter node — measured: two overloads of `f` with - // different arities produced two candidates whose parameter lists were both **empty**, so the dedupe below - // kept one of them and every call was judged against it. `text()` is the node's own source text. - let written_as = parameter.text().to_string(); - spellings.push(sema::overload::a_type_without_its_name(&written_as)); + // **The parameter's own type, lowered from its node.** `type_of_a_parameter` reads the specifier sequence + // and the declarator the tree already separates, so the name is not part of the type and no spelling is + // parsed — `int count`, `const Widget& w` and `char *text` are `int`, `const Widget&` and `char*`. + let lowered = CppParam::cast(parameter.clone()) + .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); + parameters_written.push(lowered.unwrap_or_else(|| { + // The honest reading of a parameter this layer cannot shape: its own text as the type's *name*, which + // ranks `Unranked` rather than wrong. See `type_of_declaration`'s note on the same fallback. + ComputedType::named(parameter.text().to_string(), Vec::new()) + })); } // **A `...` is a token of the list, not a parameter *node*.** `int count, ...` has one child (`int count`) and @@ -300,21 +313,24 @@ fn callees_in_this_file( // corpus, `f(void)` called as `f()` produced **two** findings on one line — *"takes 1 argument(s) and this // call passes fewer"* from here, and *"is not declared"* from another reader. The rule is the language's: a // parameter list of exactly one unnamed `void` declares nothing. - if written == 1 && spellings.len() == 1 && spellings[0].trim() == "void" { + if written == 1 && parameters_written.len() == 1 && parameters_written[0].is_void() { written = 0; required = 0; - spellings.clear(); + parameters_written.clear(); } // A declaration and its definition name the same function; the same list twice is one candidate, not an // ambiguous call to something nobody overloaded. let declared = callees.entry(name).or_default(); - if !declared.iter().any(|known| known.parameters == spellings) { + if !declared + .iter() + .any(|known| known.parameters == parameters_written) + { declared.push(Callee { required, written, variadic, - parameters: spellings, + parameters: parameters_written, }); } } @@ -394,10 +410,16 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec if !visible.contains(&normalized) { continue; } - let Some(parameters) = fact.parameter_list() else { + if fact.parameter_list().is_none() { continue; - }; - let Some(callee) = the_callee_in(parameters) else { + } + // **The index is the only stored parameter representation** — a summary's table, a cooked reading's, or the + // synthetic arena. There is no build-time copy on the fact to fall back to. + let facts = context.index().parameter_facts_of(&file, fact); + // **The list-level `...` is the fact's own bit**, not a scan of `parameters`. It is a token of the list rather + // than a parameter, so no `ParameterFact` carries it; `the_callee_in_facts` combines it with each parameter's + // pack flag. + let Some(callee) = the_callee_in_facts(facts, fact.variadic_parameters) else { continue; }; // **The same signature declared twice is one candidate at the most permissive arity** — see @@ -407,57 +429,44 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec callees } -/// **One candidate out of a `parameter_list` spelling** — the text side of [`callees_from_the_index`]. -fn the_callee_in(parameters: &str) -> Option { - // **The parameters, split by the parser rather than by a comma walk.** This list is a `DeclFact`'s text, so - // there is no tree to ask for the declaration itself — but the text can be parsed as one synthetic declaration, - // which makes `std::pair`, a function-pointer parameter and `bool ok = 1 < 2` one parameter each. The - // old walk treated every `<` as a template bracket and never closed it in a comparison, so it could swallow the - // parameters after the default. - let written_parameters = sema::call_syntax::parameters_in_a_written_list(parameters)?; - +/// **One candidate out of the CST parameter facts.** The types come from the fact's [`DeclaredType`] — resolved +/// structurally, never parsed — and a parameter whose type this reading could not record drops the candidate rather +/// than guessing at it. +/// +/// `variadic` is the list-level `...`: a C-style ellipsis is a token of the parameter list rather than a parameter, so +/// no fact carries it — the caller reads it from the declaration's [`crate::DeclFact::variadic_parameters`]. A pack is +/// read from the parameter facts here, because that one **is** a parameter's own flag. +/// +/// [`DeclaredType`]: crate::cache::summary::DeclaredType +fn the_callee_in_facts( + facts: &[index::params::ParameterFact], + mut variadic: bool, +) -> Option { let mut written = 0usize; let mut required = 0usize; - // **The C-style `...` is a token, not a `CppParam`**, so the synthetic tree does not hand it back as a parameter. - // The whole list is checked for it with the same literal guard the old text walk used. - let mut variadic = has_an_ellipsis(parameters); - let mut spellings: Vec = Vec::new(); - for parameter in written_parameters.into_iter().map(|(_, text)| text) { - let parameter = parameter.trim(); - if parameter.is_empty() { - continue; - } - // **A pack is a `...` that is not the whole parameter** — `Args&&... args` and the C-style `...` alike. The - // file-scope half asks the tokens; this half has only text, and the token half's literal guard would need a - // lexer, so a `"..."` default is the one false positive this leaves. It is stated here rather than hidden. - if has_an_ellipsis(parameter) { + let mut parameters: Vec = Vec::new(); + for parameter in facts { + if parameter.pack { variadic = true; continue; } + let type_of = parameter.type_of.as_computed()?; written += 1; - // A default is the `=` the declaration writes. - if !parameter.contains('=') { + if parameter.default_value.is_none() { required += 1; } - // The type, with any default and any parameter name dropped — see `a_type_without_its_name`. - let without_default = parameter.split('=').next().unwrap_or(parameter).trim(); - spellings.push(sema::overload::a_type_without_its_name(without_default)); + parameters.push(type_of); } - - // **`(void)` is the C spelling of *no parameters*** — the same rule the token half applies, and it has to be - // applied here too or a declaration read from **another file** keeps the wrong arity: `int f(void);` answered one - // parameter, so a call `f()` in a file that merely includes the header was reported as passing too few. - if written == 1 && spellings.len() == 1 && spellings[0].trim() == "void" { + if written == 1 && parameters.len() == 1 && parameters[0].is_void() { written = 0; required = 0; - spellings.clear(); + parameters.clear(); } - Some(Callee { required, written, variadic, - parameters: spellings, + parameters, }) } @@ -481,54 +490,18 @@ fn at_least(name: &str, required: usize) -> String { ) .to_string() } -/// **Is there a `...` in this parameter that the language would call one?** -/// -/// The parameter list of a declaration in another file arrives as text, so this is a scan rather than a token walk — -/// and the one thing a scan gets wrong is an ellipsis written inside a literal. `void log(const char* dots = "...")` -/// is not variadic, and `standardese`'s own `Args... args` is. Quotes are tracked with a backslash escape and no -/// attempt at raw strings: a raw string holding an odd number of quotes is the one case this misreads, and it errs -/// towards calling the callee variadic, which is the quiet direction. -fn has_an_ellipsis(parameter: &str) -> bool { - let bytes = parameter.as_bytes(); - let mut at = 0usize; - let mut quoted: Option = None; - - while at < bytes.len() { - let byte = bytes[at]; - match quoted { - Some(quote) => { - if byte == b'\\' { - at += 2; - continue; - } - if byte == quote { - quoted = None; - } - } - None => { - if byte == b'"' || byte == b'\'' { - quoted = Some(byte); - } else if parameter[at..].starts_with("...") { - return true; - } - } - } - - at += 1; - } - - false -} /// **Is this name a type as well as a function?** — see the guard that calls this. fn names_a_type(context: &CheckContext<'_>, name: &str) -> bool { let Known::Yes(definitions) = context.index().definitions(name, context.path) else { return false; }; - definitions - .found - .iter() - .any(|definition| definition.fact.kind != DeclKind::Function) + definitions.found.iter().any(|definition| { + context + .index() + .definition_fact(definition) + .is_some_and(|fact| fact.kind != DeclKind::Function) + }) } /// **A member call, judged against the member it names.** @@ -566,7 +539,13 @@ fn judge_a_member_call( // the full list, which walks the bases. let mut re_exposed = false; if let Known::Yes(own) = context.model.own_members_of(&class) { - for (_, fact) in &own { + for reference in &own { + let Some(fact) = context.index().fact(*reference) else { + continue; + }; + let Some(file) = context.index().path_of(reference.file) else { + continue; + }; if fact.name != access.member { continue; } @@ -574,10 +553,11 @@ fn judge_a_member_call( re_exposed = true; continue; } - let Some(parameters) = fact.parameter_list() else { + if fact.parameter_list().is_none() { continue; - }; - if let Some(callee) = the_callee_in(parameters) { + } + let facts = context.index().parameter_facts_of(file, fact); + if let Some(callee) = the_callee_in_facts(facts, fact.variadic_parameters) { members.push(callee); } } @@ -589,9 +569,18 @@ fn judge_a_member_call( members = list .members .iter() - .filter(|member| member.fact.name == access.member) - .filter_map(|member| member.fact.parameter_list()) - .filter_map(the_callee_in) + .filter(|member| context.index().member_name(member) == access.member) + .filter_map(|member| { + let fact = context.index().member_fact(member)?; + // **A member with no recorded list decides nothing**, and `?` is the same early return: a field's + // declaration has no parameter list, so it is not a call candidate. + let _ = fact.parameter_list()?; + let file = context.index().member_path(member)?; + let facts = context.index().parameter_facts_of(file, fact); + // **The list's `...` from the fact; a pack from the parameters.** See + // [`crate::DeclFact::variadic_parameters`]. + the_callee_in_facts(facts, fact.variadic_parameters) + }) .collect(); } if members.is_empty() { diff --git a/crates/cpp_code_analysis/src/sema/check/assign_type_check.rs b/crates/cpp_code_analysis/src/sema/check/assign_type_check.rs index be481844..e2c5b2dc 100644 --- a/crates/cpp_code_analysis/src/sema/check/assign_type_check.rs +++ b/crates/cpp_code_analysis/src/sema/check/assign_type_check.rs @@ -17,7 +17,7 @@ //! is what the model answers for `x` //! ``` //! -//! Both end in the same comparison against [`Type::convertible_to`], so this is one rule rather than two. +//! Both end in the same comparison against [`ComputedType::convertible_to`], so this is one rule rather than two. //! //! # What is not reported //! @@ -46,6 +46,7 @@ use super::a_literal_zero; use super::callee_name_of; use crate::DeclKind; use crate::Known; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppBinaryExpr; use cpp_parser::CppCallExpr; @@ -99,21 +100,36 @@ impl Check for AssignTypeCheck { let declarations = context .declarations(DeclarationSource::Cooked) .unwrap_or_default(); - let mut declared: HashMap<&str, Option<&str>> = HashMap::new(); + let mut declared: HashMap<&str, Option> = HashMap::new(); for fact in declarations { if fact.kind != DeclKind::Variable { continue; } - let Some(written) = fact.type_of.as_deref() else { + // **The type the fact carries**, structurally — the one place this check crosses from a fact into the + // conversion question. A stored or synthesized type resolves through [`crate::ProjectIndex::computed_type_of`]; + // a deduced `auto` is the type's own placeholder rather than a word compared against a string. + let Some(type_of) = context.index().computed_type_of(fact) else { continue; }; - let written = (!is_a_deduced_auto(written)).then_some(written); + let written = (!type_of.is_a_placeholder()).then(|| { + context + .index() + .type_spelling_of(fact) + .unwrap_or_else(|| smol_str::SmolStr::new(type_of.to_string())) + }); + eprintln!( + "[decl] {} : {} -> {:?}", + fact.name, + type_of, + written.as_deref() + ); + let target = written.and_then(|written| Target::of(&type_of, &written)); match declared.entry(fact.name.as_str()) { std::collections::hash_map::Entry::Vacant(entry) => { - entry.insert(written); + entry.insert(target); } std::collections::hash_map::Entry::Occupied(mut entry) => { - if *entry.get() != written { + if *entry.get() != target { entry.insert(None); } } @@ -183,7 +199,7 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).copied() else { + let Some(Some(target)) = declared.get(name.as_str()).cloned() else { continue; }; @@ -211,7 +227,7 @@ impl Check for AssignTypeCheck { // `LineSpace line_space_after_if_statement = LineSpace(LineSpaceType::Keep);` produced ten findings. The // initialiser is a call to the type's **own name**, and what the type engine answers for that call is not // the type it constructs — so there is nothing here for this rule to compare. - if constructs_the_written_type(&expression, written) { + if constructs_the_written_type(&expression, &target) { continue; } @@ -227,7 +243,7 @@ impl Check for AssignTypeCheck { continue; } - report_if_it_does_not_convert(context, &expression, written, &name, "initialised"); + report_if_it_does_not_convert(context, &expression, &target, &name, "initialised"); } // **And the assignments**: `x = expr;`. Which object it is comes from the left-hand side being **a name and @@ -269,11 +285,11 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).copied() else { + let Some(Some(target)) = declared.get(name.as_str()).cloned() else { continue; }; - report_if_it_does_not_convert(context, right.syntax(), written, &name, "assigned"); + report_if_it_does_not_convert(context, right.syntax(), &target, &name, "assigned"); } // **A designated initialiser names the member it initialises**, so the question is *that member's* type: @@ -297,16 +313,26 @@ impl Check for AssignTypeCheck { continue; }; let name = member.get_name_text().to_string(); - let Some(declared) = members + // **The member's type, computed** — the row's substitution applied structurally to the declaration's own + // type. The spelling is the popup's display edge; the comparison reads the value. + let Some(found) = members .members .iter() - .find(|found| found.fact.name.as_str() == name) - .and_then(|found| found.fact.type_of.as_deref()) + .find(|found| context.index().member_name(found) == name) else { continue; }; - let written = declared.to_string(); - report_if_it_does_not_convert(context, value.syntax(), &written, &name, "initialised"); + let Some(type_of) = context.index().member_computed_type(found) else { + continue; + }; + let written = context + .index() + .member_type_spelling(found) + .map_or_else(|| smol_str::SmolStr::new(type_of.to_string()), Into::into); + let Some(target) = Target::of(&type_of, &written) else { + continue; + }; + report_if_it_does_not_convert(context, value.syntax(), &target, &name, "initialised"); } // **The object an assignment writes to has to be writable at all.** The loop above judges the *value* @@ -370,26 +396,51 @@ enum NotAssignable { AnArray, } -fn not_assignable(type_of: &sema::types::Type) -> Option { +fn not_assignable(type_of: &ComputedType) -> Option { match type_of { - sema::types::Type::Qualified { qualifiers, .. } if qualifiers.is_const() => { - Some(NotAssignable::Const) - } - sema::types::Type::Array { .. } => Some(NotAssignable::AnArray), + ComputedType::Qualified(qualified) if qualified.is_const => Some(NotAssignable::Const), + ComputedType::Array { .. } => Some(NotAssignable::AnArray), _ => None, } } -/// **A type the compiler deduces is not a conversion this check may judge** — `auto`, and every spelling of it. +// **A type the compiler deduces is not a conversion this check may judge** — `auto`, and every form of it. +// +// The rule itself is [`crate::sema::types::is_a_deduced_type`], because the hover card asks the same question ("is +// the written type the whole answer, or is there a deduced one to show?"). What was measured here: the first version +// compared the written type against exactly `"auto"` and `"decltype(auto)"`, so `auto&`, `const auto&` and `auto&&` +// were judged as *written* types — reported from an editor, `auto& config = configs.emplace_back(…)` was underlined +// as "`config` is initialised with a value that does not convert to `auto&`", which is a claim about a type that is +// not the type. +// +// The structural twin is [`crate::index::types::ComputedType::is_a_placeholder`], which is what this check reads now: +// a fact's type is a value, and "is this a placeholder?" is a question about its variants. + +/// **A type a value is being put into** — the structure the conversion question takes, plus the spelling a message +/// quotes. /// -/// The rule itself is [`crate::sema::types::is_a_deduced_type`], because the hover card asks the same question ("is -/// the written type the whole answer, or is there a deduced one to show?"). What was measured here: the first version -/// compared the written type against exactly `"auto"` and `"decltype(auto)"`, so `auto&`, `const auto&` and `auto&&` -/// were judged as *written* types — reported from an editor, `auto& config = configs.emplace_back(…)` was underlined -/// as "`config` is initialised with a value that does not convert to `auto&`", which is a claim about a type that is -/// not the type. -fn is_a_deduced_auto(written: &str) -> bool { - sema::types::is_a_deduced_type(written) +/// Built once per declaration, from the fact's [`DeclaredType`](crate::cache::summary::DeclaredType): the type is +/// resolved structurally (never parsed), and the spelling is the display edge. Two declarations of one name are +/// compared by their **types**, which is the honest rule — `typedef int count;` and `int count;` are one type written +/// two ways. +#[derive(Clone, PartialEq, Eq)] +struct Target { + type_of: ComputedType, + written: smol_str::SmolStr, +} + +impl Target { + /// From a computed type and the spelling the file wrote. `None` for a type this layer cannot name at all — an + /// empty spelling is "no type", the same answer as a declaration that states none. + fn of(computed: &ComputedType, written: &str) -> Option { + if written.trim().is_empty() { + return None; + } + Some(Target { + type_of: computed.clone(), + written: smol_str::SmolStr::new(written.trim()), + }) + } } /// **One place a value enters an object whose type is written down**, reported when it does not convert. @@ -399,7 +450,7 @@ fn is_a_deduced_auto(written: &str) -> bool { fn report_if_it_does_not_convert( context: &CheckContext<'_>, expression: &CppSyntaxNode, - written: &str, + target: &Target, name: &str, how: &str, ) { @@ -413,22 +464,22 @@ fn report_if_it_does_not_convert( return; } let known_from = context.type_of(expression); - let target = sema::types::parse_type_spelling(written); let Known::Yes((from, _)) = known_from else { return; }; - // **One facility, shared with `param-type-check`** — `sema::convert` normalises the spelling (a `const std::string&` - // assignment target is `Reference { to: Named(..) }`, and `class_name()` answers `None` for a reference), asks the type - // relation first and the index only for the class question, and answers `Unknown` — silence — when neither can speak. + // **One facility, shared with `param-type-check`** — `sema::convert` asks the type relation first and the index + // only for the class question, and answers `Unknown` — silence — when neither can speak. The target is the fact's + // own **type**, resolved once above, and C's tag is part of it — nothing here reads a spelling for it. // **C's string-literal rule** — see [`CheckContext::a_string_literal_in_a_char_pointer_position`]. - if context.a_string_literal_in_a_char_pointer_position(expression, written) { + if context.a_string_literal_in_a_char_pointer_position(expression, &target.type_of) { return; } - if sema::convert::conversion(&from, written, context.language.family(), |class| { + eprintln!("[convert] from={from} to={}", target.type_of); + if sema::convert::conversion_to(&from, &target.type_of, context.language.family(), |class| { a_class_can_be_built_from(context, class, &from) }) == sema::convert::Conversion::Refused { - report(context, expression, name, how, written); + report(context, expression, name, how, &target.written); return; } @@ -436,15 +487,17 @@ fn report_if_it_does_not_convert( // cannot see a declaration, so a class target always answers `Unknown` — the honest answer to "can this convert", // and the *wrong* answer to "does this class have a constructor that could take this". // - // The question therefore goes to the **index**: `a_class_can_be_built_from` reads the class's member facts, whose - // `parameter_list` is the parameter list as the declaring file spells it. That field exists for exactly this — a - // query holds one file and the parameters are written in another — so the answer is a fact the cook already - // produced rather than a walk over a rendered header. A class from `` is as answerable as one written two - // lines up, which is the point: **the finding is about this file, the knowledge is the project's.** - if a_class_can_be_built_from(context, target.class_name().unwrap_or_default(), &from) - == Some(false) + // The question therefore goes to the **index**: `a_class_can_be_built_from` reads the class's members' parameter + // **facts**, whose types are structured, so the answer is a fact the cook already produced rather than a walk + // over a rendered header. A class from `` is as answerable as one written two lines up, which is the + // point: **the finding is about this file, the knowledge is the project's.** + if a_class_can_be_built_from( + context, + target.type_of.class_name().unwrap_or_default(), + &from, + ) == Some(false) { - report(context, expression, name, how, written); + report(context, expression, name, how, &target.written); } } @@ -471,8 +524,10 @@ fn report( /// **Is this expression a call to the very type it is assigned to?** — `LineSpace(…)` for a `LineSpace`. /// -/// The last component of a qualified spelling is what a construction writes: `std::string(…)` for a `std::string`. -fn constructs_the_written_type(expression: &CppSyntaxNode, written: &str) -> bool { +/// The class the target's own type names is what a construction writes: `std::string(…)` for a `std::string`. The +/// class name comes from the **type**, and the written spelling is compared too so a spelling this layer cannot shape +/// still keeps the exemption. +fn constructs_the_written_type(expression: &CppSyntaxNode, target: &Target) -> bool { let Some(call) = CppCallExpr::cast(expression.clone()) else { return false; }; @@ -482,8 +537,14 @@ fn constructs_the_written_type(expression: &CppSyntaxNode, written: &str) -> boo let Some(spelled) = callee_name_of(&callee) else { return false; }; - let target = written.rsplit("::").next().unwrap_or(written).trim(); - spelled.trim() == written.trim() || spelled.trim() == target + let spelled = spelled.trim(); + let bare = target + .type_of + .class_name() + .and_then(|class| class.rsplit("::").next()) + .map(str::trim) + .unwrap_or_default(); + spelled == target.written.trim() || (!bare.is_empty() && spelled == bare) } /// **The aggregate a designated initialiser belongs to** — the class name of the declaration's own type. /// diff --git a/crates/cpp_code_analysis/src/sema/check/concept_not_satisfied.rs b/crates/cpp_code_analysis/src/sema/check/concept_not_satisfied.rs index 13125afd..44a99668 100644 --- a/crates/cpp_code_analysis/src/sema/check/concept_not_satisfied.rs +++ b/crates/cpp_code_analysis/src/sema/check/concept_not_satisfied.rs @@ -28,17 +28,24 @@ //! # 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". +//! here, and the **summary** when it is not — `DeclFact::constraint_facts` is the head's other half, stored beside the +//! parameter names for exactly this question. It is a [`ConstraintFact`](crate::ConstraintFact): the concept's name +//! and its arguments, lowered from the head's own `CppTemplateParam` nodes when the fact was built. An argument is a +//! [`ConstraintArgument`](crate::ConstraintArgument) — a type, or the written text of a value — and the concepts this +//! check decides ask about types, so a value argument leaves their question unanswered rather than answered with a +//! fake type. Nothing here splits a spelling or parses a type back out of one. 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 super::callee_name_of; +use crate::ConstraintArgument; +use crate::ConstraintFact; use crate::DeclKind; use crate::Known; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::source_range; use cpp_parser::{CppAstNode, CppCallExpr}; @@ -55,9 +62,9 @@ impl Check for ConceptNotSatisfied { // **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`). + // `DeclFact::constraint_facts` 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. @@ -68,20 +75,20 @@ impl Check for ConceptNotSatisfied { let Some(name) = 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 { + let Some(constraints) = constraints_of_a_declaration(context, &name) else { continue; }; + // **The concepts, resolved once per call from the structured facts.** The vector owns its argument + // types, so the borrow of `context` that `constraints` holds ends before the finding below needs + // `&mut context`. Nothing is split or parsed: a fact already carries the concept's name and its + // [`ComputedType`] arguments. + let concepts: Vec> = constraints + .iter() + .map(|constraint| constraint.as_ref().and_then(Concept::from_fact)) + .collect(); 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 { + let Some(concept) = concepts.get(at).and_then(Option::as_ref) else { continue; }; let Known::Yes((passed, _)) = context.type_of(argument.syntax()) else { @@ -89,8 +96,10 @@ impl Check for ConceptNotSatisfied { }; // **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 - // ``, `_Tp&&` was reported as not satisfying `std::floating_point`. - if sema::convert::names_a_template_parameter_for_a_check(&passed.to_string()) { + // ``, `_Tp&&` was reported as not satisfying `std::floating_point`. The question is asked of + // the `ComputedType` — structurally for `TemplateParameter`, by the naming convention on a `Named` — not of a + // spelling written back out of it. + if sema::convert::names_a_template_parameter_for_a_check(&passed) { continue; } if concept.is_satisfied_by(&passed, context) != Some(false) { @@ -120,8 +129,8 @@ impl Check for ConceptNotSatisfied { fn constraints_of_a_declaration<'a>( context: &'a CheckContext<'_>, name: &str, -) -> Option<&'a [String]> { - let mut own: Option<&[String]> = None; +) -> Option<&'a [Option]> { + let mut own: Option<&[Option]> = None; let mut own_declarations = 0; for fact in context .declarations(DeclarationSource::Cooked) @@ -131,7 +140,7 @@ fn constraints_of_a_declaration<'a>( continue; } own_declarations += 1; - own = Some(fact.constraints()); + own = Some(fact.constraint_facts()); } match own_declarations { 0 => {} @@ -141,14 +150,14 @@ fn constraints_of_a_declaration<'a>( let index = context.model.index(); let declared = index.files_declaring(name, context.path); - let mut elsewhere: Option<&[String]> = None; + let mut elsewhere: Option<&[Option]> = 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()); + elsewhere = Some(found.fact.constraint_facts()); } match elsewhere_declarations { 1 => elsewhere, @@ -163,12 +172,12 @@ enum Concept { Integral, /// `std::floating_point`. FloatingPoint, - /// `std::same_as`. - SameAs(String), - /// `std::convertible_to`. - ConvertibleTo(String), + /// `std::same_as` — the constraint's first written type argument, as the head lowered it. + SameAs(ComputedType), + /// `std::convertible_to` — the constraint's first written type argument. + ConvertibleTo(ComputedType), /// `std::derived_from` — decided through the index, which is where a class's bases are. - DerivedFrom(String), + DerivedFrom(ComputedType), /// **The object family**: `std::default_initializable`, `move_constructible`, `copy_constructible`, /// `movable`, `copyable`, `semiregular`, `regular`. /// @@ -179,50 +188,49 @@ enum Concept { } impl Concept { - /// **Which concept a constraint names**, from the head's own spelling — with or without `std::`. + /// **Which concept a [`ConstraintFact`] names** — the last segment the head read, 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>` answered a concept called `vector>` — so the arguments are - /// cut first, and the scope is then the head's own. - fn from_constraint(constraint: &str) -> Option { - let (head, arguments) = match constraint.trim().split_once('<') { - Some((head, rest)) => (head.trim(), Some(rest.trim_end_matches('>'))), - None => (constraint.trim(), None), + /// The fact is already the head's own answer: `sema::types` lowered the constrained parameter's `NamedType` or + /// `TemplateType` into a [`ConstraintFact`] and kept the concept's name and arguments. So this is a match on + /// that name, not the old split of a spelling — `std::derived_from>` used to answer a concept + /// called `vector>` when the scope was taken before the arguments were cut, and there is no spelling here + /// to cut in the wrong order. + /// + /// **`same_as`, `convertible_to` and `derived_from` ask about a type**, so they read the first argument only + /// when it is a [`ConstraintArgument::Type`]. A value argument — `SomeConcept<42>`, or the syntactically + /// possible `std::same_as<42>` — makes the question unanswerable and the answer is `None`, which keeps the + /// check silent. It is not read as a type: a made-up type would be a claim about a type the file never wrote. + /// The integral/floating/object concepts take no argument in the forms they decide, so they ignore the + /// arguments as they always did. + fn from_fact(constraint: &ConstraintFact) -> Option { + let first_type_argument = || match constraint.arguments.first()? { + ConstraintArgument::Type(argument) => Some(argument.clone()), + ConstraintArgument::Value(_) => None, }; - let name = head.rsplit("::").next().unwrap_or(head).trim(); - match name { + match constraint.concept.as_str() { "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())) - } + "same_as" => Some(Concept::SameAs(first_type_argument()?)), + "convertible_to" => Some(Concept::ConvertibleTo(first_type_argument()?)), + "derived_from" => Some(Concept::DerivedFrom(first_type_argument()?)), "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", - })), + | "regular" => Some(Concept::NeedsAnObjectType( + match constraint.concept.as_str() { + "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, } } @@ -240,19 +248,17 @@ impl Concept { /// `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: &sema::types::Type, - context: &CheckContext<'_>, - ) -> Option { + fn is_satisfied_by(&self, passed: &ComputedType, context: &CheckContext<'_>) -> Option { match self { Concept::Integral => Some(is_an_integer(passed)), Concept::FloatingPoint => Some(is_a_floating_point(passed)), Concept::SameAs(declared) => { - let declared = sema::types::parse_type_spelling(declared); - match passed.convertible_to(&declared) { + // **Structural equality** — the fact carried the argument as a type, so `same_as` is `==` on the + // two [`ComputedType`]s. The conversion relation is still asked first, because a pair it refuses is + // definitely not the same type either, and that is a cheaper answer than comparing the trees. + match passed.convertible_to(declared) { Known::No => Some(false), - Known::Yes(()) => Some(passed.to_string() == declared.to_string()), + Known::Yes(()) => Some(passed == declared), Known::Unknown(_) => None, } } @@ -260,26 +266,29 @@ impl Concept { 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 + // `ComputedType::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 { - sema::types::Type::Reference { .. } => Some(false), + ComputedType::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. - sema::types::Type::Array { .. } => None, + ComputedType::Array { .. } => None, _ => Some(true), } } Concept::ConvertibleTo(target) => { - let target = sema::types::parse_type_spelling(target); - match passed.convertible_to(&target) { + // **The concept's argument is the `ComputedType` the fact carries.** The conversion below takes that + // value, not a spelling: the old form parsed the argument once here and the check's own type had + // already been parsed, which is a second reader of the same question. C's tag is part of the type + // now, so nothing is read beside it. + 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. Known::No => Some(false), Known::Yes(()) => Some(true), Known::Unknown(_) => Some(!matches!( - sema::convert::conversion(passed, &target.to_string(), None, |_| None), + sema::convert::conversion_to(passed, target, None, |_| None), sema::convert::Conversion::Refused )), } @@ -288,16 +297,16 @@ impl Concept { } } -/// **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 spelling of a type that is a plain name** — `Some("int")` for `ComputedType::Primary`, `Some("size_t")` for a +/// `ComputedType::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 +/// The **tree's own reading**, not a scan for `*` and `&`: `ComputedType` 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: &sema::types::Type) -> Option { +fn plain_type_spelling(passed: &ComputedType) -> Option { match passed { - sema::types::Type::Builtin { spelling } => Some(spelling.clone()), - sema::types::Type::Named { name, arguments } if arguments.is_empty() => Some(name.clone()), + ComputedType::Primary(primary) => Some(primary.spelling().to_string()), + ComputedType::Named(name) => Some(name.to_string()), _ => None, } } @@ -307,7 +316,7 @@ fn plain_type_spelling(passed: &sema::types::Type) -> Option { /// `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: &sema::types::Type) -> bool { +fn is_an_integer(passed: &ComputedType) -> bool { let Some(spelling) = plain_type_spelling(passed) else { return false; }; @@ -360,47 +369,33 @@ fn is_an_integer(passed: &sema::types::Type) -> bool { ) } -fn is_a_floating_point(passed: &sema::types::Type) -> bool { +fn is_a_floating_point(passed: &ComputedType) -> 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 { - 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. /// +/// `base` is the `ComputedType` the constraint's own argument lowered to, so the name this compares is read off the +/// type (`bare_name`, the class's own name without scope or arguments) and never parsed out of a spelling. A base +/// whose type has no name — a builtin, a function — can match no class, and the walk then answers the same way it +/// always did: `Some(false)` once every class on the way was read, `None` as soon as one was not. +/// /// `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: &sema::types::Type, - base: &str, + derived: &ComputedType, + base: &ComputedType, ) -> Option { - use crate::sema::types::Type; - - let Type::Named { name, arguments } = derived else { + let (name, arguments): (&str, &[ComputedType]) = match derived { + ComputedType::Named(name) => (name.as_str(), &[]), + ComputedType::Generic(generic) => (generic.name.as_str(), &generic.arguments), // A builtin, a pointer, a reference, an array: none of them is a class, and `derived_from` needs one. - return Some(false); + _ => return Some(false), }; if !arguments.is_empty() { // `derived_from vector` asks whether the *instantiation* derives from `B`; the index is keyed by the @@ -409,9 +404,11 @@ fn derives_from( } let index = context.model.index(); - let base = the_class_name(base); + // **The base's own name, read from its type.** `std::vector` answers `vector`, exactly what the old + // `the_class_name(&str)` cut out of the constraint spelling — but from the structured argument the fact carries. + let base = base.bare_name().map(the_class_name); - let mut waiting = vec![name.clone()]; + let mut waiting = vec![name.to_string()]; let mut seen = std::collections::HashSet::new(); let mut answered = true; @@ -419,7 +416,7 @@ fn derives_from( if !seen.insert(class.clone()) { continue; } - if the_class_name(&class) == base { + if Some(the_class_name(&class)) == base { return Some(true); } diff --git a/crates/cpp_code_analysis/src/sema/check/deref_type_check.rs b/crates/cpp_code_analysis/src/sema/check/deref_type_check.rs index e219882a..6904db6d 100644 --- a/crates/cpp_code_analysis/src/sema/check/deref_type_check.rs +++ b/crates/cpp_code_analysis/src/sema/check/deref_type_check.rs @@ -35,7 +35,7 @@ //! `Builtin`, and no declaration can make it a pointer. use crate::Known; -use crate::sema; +use crate::index::types::ComputedType; use cpp_parser::CppUnaryExpr; use cpp_parser::source_range; @@ -90,20 +90,20 @@ impl Check for DerefTypeCheck { } /// **Why a `*` cannot be applied to a value of this type**, or `None` when it can. -fn nothing_to_dereference(type_of: &sema::types::Type) -> Option { +fn nothing_to_dereference(type_of: &ComputedType) -> Option { // A reference dereferences to its referent, and a qualifier is not a type: peel both before asking. let mut type_of = type_of; - while let sema::types::Type::Reference { to, .. } = type_of { + while let ComputedType::Reference { to, .. } = type_of { type_of = to; } - while let sema::types::Type::Qualified { of, .. } = type_of { - type_of = of; + while let ComputedType::Qualified(qualified) = type_of { + type_of = &qualified.of; } match type_of { - sema::types::Type::Pointer { to } => to.is_void().then_some(Why::AVoidPointer), + ComputedType::Pointer(to) => to.is_void().then_some(Why::AVoidPointer), // An array dereferences to its first element, which is what a `*` means for one. - sema::types::Type::Array { .. } => None, + ComputedType::Array { .. } => None, // **An arithmetic type is certainly not a pointer.** This is the only shape the rule decides from the // spelling alone: a `Named` may be a typedef for a pointer, so it is left to the answers above. other if other.is_arithmetic() => Some(Why::ANumber), diff --git a/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs b/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs index fe9d2d45..1c00a323 100644 --- a/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs +++ b/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs @@ -57,7 +57,10 @@ impl Check for FinalHierarchy { .map(|fact| { ( fact.name.to_string(), - fact.bases().to_vec(), + fact.bases() + .iter() + .map(ToString::to_string) + .collect::>(), fact.name_range, ) }) @@ -70,7 +73,11 @@ impl Check for FinalHierarchy { let Known::Yes(declared) = context.index().definition(base, context.path) else { continue; }; - if !declared.fact.modifiers.contains(DeclModifiers::FINAL) { + if !context + .index() + .definition_fact(&declared) + .is_some_and(|fact| fact.modifiers.contains(DeclModifiers::FINAL)) + { continue; } context.add_in_the_file( @@ -120,11 +127,17 @@ impl Check for FinalHierarchy { could_not_read_a_base = true; } for member in &list.members { - if member.fact.kind != DeclKind::Function || member.fact.name != *name { + let index = context.index(); + if index.member_kind(member) != Some(DeclKind::Function) + || index.member_name(member) != *name + { continue; } any_overridable = true; - if !member.fact.modifiers.contains(DeclModifiers::FINAL) { + if !index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::FINAL)) + { all_final = false; } } diff --git a/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs b/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs index 6a23aa95..478d96d2 100644 --- a/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs +++ b/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs @@ -45,7 +45,12 @@ impl Check for FinalMisplaced { .declarations .iter() .filter(|fact| fact.kind == DeclKind::Type) - .map(|fact| (fact.name.to_string(), fact.bases().to_vec())) + .map(|fact| { + ( + fact.name.to_string(), + fact.bases().iter().map(ToString::to_string).collect(), + ) + }) .collect(); let finals: Vec<(String, Option, SourceRange)> = context @@ -111,7 +116,11 @@ impl Check for FinalMisplaced { if !list.unlisted.is_empty() { could_not_read_a_base = true; } - if list.members.iter().any(|member| member.fact.name == *name) { + if list + .members + .iter() + .any(|member| context.index().member_name(member) == *name) + { a_base_names_it = true; break; } diff --git a/crates/cpp_code_analysis/src/sema/check/missing_include.rs b/crates/cpp_code_analysis/src/sema/check/missing_include.rs index e1b3f0c4..2439dee5 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -66,8 +66,8 @@ //! turned the channel off; the switch makes that a decision rather than a habit. use crate::DeclFact; +use crate::ProjectIndex; use crate::file; -use crate::sema::call_syntax::parameters_in_a_written_list; use std::path::Path; use super::{Check, CheckContext, DeclarationSource, DiagnosticCode}; @@ -128,7 +128,7 @@ impl Check for MissingInclude { if fact.local || matches!(fact.kind, DeclKind::MacroLike | DeclKind::Other) { continue; } - for spelling in types_this_declaration_uses(fact) { + for spelling in types_this_declaration_uses(context.index(), &path, fact) { // **A qualified spelling is not this rule's** — `asio::io_context` would name `asio` (a namespace), // and the fix cannot express "include the header for a nested name" without guessing. Measured on a // real project: without this, `function`, `less` and `asio` were reported from qualified spellings. @@ -306,25 +306,25 @@ pub(super) fn is_ours(context: &CheckContext<'_>, file: &Path) -> bool { } /// The type spellings a declaration uses — its own type, its return type, and the types in its parameter list. -pub(super) fn types_this_declaration_uses(fact: &DeclFact) -> Vec { +pub(super) fn types_this_declaration_uses( + index: &ProjectIndex, + file: &Path, + fact: &DeclFact, +) -> Vec { let mut spellings: Vec = Vec::new(); - if let Some(of) = &fact.type_of { + if let Some(of) = index.type_spelling_of(fact) { spellings.push(of.to_string()); } - // **A function's return type is a spelling too.** `OnlyHere* make();` uses the type exactly as `OnlyHere x;` does, - // and the fact records it (`DeclFact::returns`) — but only `type_of` and the parameter list were read here, so no - // function's return type could ever be reported. Measured on the corpus: `auto returns_one() -> OnlyHere;` was - // silent while `OnlyHere a_variable;` on the line above was reported. - if let Some(returns) = &fact.returns { + if let Some(returns) = index.returns_spelling_of(fact) { spellings.push(returns.to_string()); } - if let Some(parameters) = &fact.parameter_list() { - // **A comma walk is not the language's split.** `std::pair` is one parameter and a function - // pointer's list is one parameter too. The synthetic declaration is the same one the signature fallback - // uses; when it cannot read the spelling, keep the old split rather than losing the whole parameter list. - match parameters_in_a_written_list(parameters) { - Some(parsed) => spellings.extend(parsed.into_iter().map(|(_, text)| text)), - None => spellings.extend(parameters.split(',').map(|one| one.trim().to_string())), + for parameter in index.parameter_facts_of(file, fact) { + // **The display spelling, read at this edge.** The check asks what *words* a declaration writes, which is a + // question about text; the parameter's type itself is structured and is never parsed here. + if let Some(spelling) = index.parameter_spelling(parameter) + && !spelling.trim().is_empty() + { + spellings.push(spelling.to_string()); } } spellings diff --git a/crates/cpp_code_analysis/src/sema/check/missing_return.rs b/crates/cpp_code_analysis/src/sema/check/missing_return.rs index 379bdcf6..848118a4 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_return.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_return.rs @@ -168,24 +168,29 @@ fn the_promise_of_a_name(context: &CheckContext<'_>, spelling: &str, depth: usiz let Known::Yes(known) = context.index().definition(spelled, context.path) else { return Promise::NotKnown; }; - let fact = &known.fact; + let Some(fact) = context.index().definition_fact(&known) else { + return Promise::NotKnown; + }; // A class, a struct, an enum — something with a size, which is a value. if fact.kind != DeclKind::Type { return Promise::AValue; } - match fact.type_of.as_deref().map(str::trim) { + let Some(spelled) = context.index().type_spelling_of(fact) else { + return Promise::AValue; + }; + match spelled.trim() { // A type declared through its own name (`class Widget;`) is an ordinary class. - None | Some("") => Promise::AValue, - Some("void") => Promise::Nothing, + "" => Promise::AValue, + "void" => Promise::Nothing, // **A built-in target is a value** — `typedef int myint;` — and a pointer to anything is a value too. - Some(target) + target if target.contains('*') || target.contains('&') || sema::layout::a_builtin_in_memory(target).is_some() => { Promise::AValue } - Some(target) => the_promise_of_a_name(context, target, depth + 1), + target => the_promise_of_a_name(context, target, depth + 1), } } impl Check for MissingReturn { diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index e408da61..f2c8d00b 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -94,6 +94,8 @@ use crate::IncludeForm; use crate::Known; use crate::ScopeTree; use crate::file; +use crate::index; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppAttributeList; use cpp_parser::CppDeclarator; @@ -510,15 +512,16 @@ impl<'a> CheckContext<'a> { /// Only a **literal** expression counts: a `const char *` *variable* dropped into a `char *` is a /// discarded qualifier in C too, and the compilers warn about it (`-Wdiscarded-qualifiers`). /// - /// Measured on redis 8.x: eleven `assign-type-check`, eight `return-type-mismatch` and one `param-type-check` - /// finding, every one of them this pair — `char *cset = "…";` is how that code was written (`docs/c-support.md` - /// §8). + /// The target is asked **structurally** — [`is_a_char_pointer`] reads the type's own variants, so `char const *` + /// and `const char*` are one question and no spelling is scanned. Measured on redis 8.x: eleven + /// `assign-type-check`, eight `return-type-mismatch` and one `param-type-check` finding, every one of them this + /// pair — `char *cset = "…";` is how that code was written (`docs/c-support.md` §8). pub fn a_string_literal_in_a_char_pointer_position( &self, expression: &CppSyntaxNode, - written: &str, + target: &ComputedType, ) -> bool { - self.is_c() && is_a_string_literal(expression) && is_a_char_pointer_spelling(written) + self.is_c() && is_a_string_literal(expression) && is_a_char_pointer(target) } /// **The comment and literal ranges of the file as written**, for the rules that read the *text* rather than the tree. /// @@ -584,6 +587,21 @@ impl<'a> CheckContext<'a> { SourceRange::new(start.get(), end.get().saturating_sub(start.get())) } + /// **The summary fact for a name this file's own tree writes** — the answer a check needs when it has the + /// function's *node* and wants what the fact layer recorded (its return `DeclaredType`, its parameters). + /// + /// The name's range is mapped into the file's own coordinates first ([`CheckContext::in_the_file`]), because the + /// tree the checks walk is the rendering, where a macro expansion shifts every offset after it. A function whose + /// name a macro produced has no fact of its own, and answers `None` — the caller says nothing rather than + /// guessing at a declaration it does not have. + pub fn fact_declared_at(&self, name_range: SourceRange) -> Option<&DeclFact> { + let in_the_file = self.in_the_file(name_range); + self.summary.declarations.iter().find(|fact| { + fact.name_range.start_offset == in_the_file.start_offset + && fact.name_range.end_offset() == in_the_file.end_offset() + }) + } + /// The one place a finding becomes a [`Finding`] — see [`CheckContext::add`]. fn push( &self, @@ -682,10 +700,7 @@ impl<'a> CheckContext<'a> { CppTranslationUnit::cast(self.tree().clone()) } /// **The type of an expression** — the model's, remembered per node for as long as this request lasts. - pub fn type_of( - &self, - expression: &CppSyntaxNode, - ) -> Known<(sema::types::Type, std::path::PathBuf)> { + pub fn type_of(&self, expression: &CppSyntaxNode) -> Known<(ComputedType, std::path::PathBuf)> { self.model.type_of(expression) } @@ -1152,7 +1167,7 @@ pub fn qualified_class_and_bases(fact: &DeclFact) -> (String, Vec) { .iter() .map(|base| match space { Some(space) if !base.contains("::") => format!("{space}::{base}"), - _ => base.clone(), + _ => base.to_string(), }) .collect(); (class, bases) @@ -1537,24 +1552,6 @@ pub fn name_declared_by(function: &CppSyntaxNode) -> Option { Some(function_head(function)?.name) } -/// **A function's parameters as the declaration spells them** — `int count`, `const Widget& w`, `...`. -/// -/// Read from the **tree** and never from [`DeclFact::parameters`](crate::DeclFact::parameters), which is the -/// template parameter list: the check this one replaces read that field and reported 119 findings on 200 MSVC -/// headers, every one of them a function whose real parameters were in the tree all along. -pub fn parameter_spellings_of(function: &CppSyntaxNode) -> Vec { - use cpp_parser::{CppAstNode, CppDeclaration, CppParam}; - let Some(parameters) = - CppDeclaration::cast(function.clone()).and_then(|declaration| declaration.get_param_list()) - else { - return Vec::new(); - }; - parameters - .children::() - .map(|parameter| parameter.get_type_text()) - .filter(|spelling| !spelling.is_empty()) - .collect() -} /// **Can a value of this type build an object of that class?** — asked of the **index**, never of a tree. /// /// ```text @@ -1602,23 +1599,33 @@ fn is_a_string_literal(expression: &CppSyntaxNode) -> bool { }) } -/// **Is this spelling `char *`**, once the top-level qualifiers and the whitespace are off? `const char *` converts -/// already, and `unsigned char *` is a different target that a string literal does not convert to in any language. -fn is_a_char_pointer_spelling(written: &str) -> bool { - let mut spelling = String::new(); - for word in written.split_whitespace() { - if matches!(word, "const" | "volatile") { - continue; - } - spelling.push_str(word); - } +/// **Is this type `char *`**, once the top-level qualifiers are off? `const char *` converts already, and +/// `unsigned char *` is a different target that a string literal does not convert to in any language. +/// +/// Asked of the **variants**, not of a spelling: a qualifier is a wrapper here, so `char const *` and `const char*` +/// are the same structure, and a type this layer cannot see through is not a `char *`. +/// +/// **`void *` is the same question in C.** A literal is `char[]` there — `char *` converts to `void *` — while the +/// type layer spells the literal `const char *` in both languages. Without this arm +/// `static void takes(void *); takes("text");` was refused as a discarded qualifier the C program does not have, on a +/// file whose whole point is that a `void *` takes any object pointer (`probes/void_star.c`). +fn is_a_char_pointer(type_of: &ComputedType) -> bool { + let type_of = match type_of { + ComputedType::Qualified(qualified) => &qualified.of, + other => other, + }; // A reference or an array is not a pointer target: `char *&` and `char[]` are different questions. - // - // **`void *` is the same question in C.** A literal is `char[]` there — `char *` converts to `void *` — while - // the type layer spells the literal `const char *` in both languages. Without this arm - // `static void takes(void *); takes("text");` was refused as a discarded qualifier the C program does not - // have, on a file whose whole point is that a `void *` takes any object pointer (`probes/void_star.c`). - spelling == "char*" || spelling == "void*" + let ComputedType::Pointer(to) = type_of else { + return false; + }; + let pointee = match &**to { + ComputedType::Qualified(qualified) => &qualified.of, + other => other, + }; + matches!( + pointee, + ComputedType::Primary(index::types::PrimaryType::Char | index::types::PrimaryType::Void) + ) } /// **A type written back as a spelling** — for a message, and only for the shapes a call's parameter list holds. @@ -1629,36 +1636,37 @@ fn is_a_char_pointer_spelling(written: &str) -> bool { /// /// `None` for anything this cannot write **exactly**: a template parameter, a pack, a class written with arguments, a /// nested function type. A caller that gets `None` stays silent, which is the direction a message must fail in. -pub fn a_spelling_of(type_of: &sema::types::Type) -> Option { - use sema::types::Type; +pub fn a_spelling_of(type_of: &ComputedType) -> Option { Some(match type_of { - Type::Builtin { spelling } => spelling.clone(), - Type::Named { name, arguments } if arguments.is_empty() => name.clone(), - Type::Named { .. } - | Type::TemplateParameter { .. } - | Type::Pack { .. } - | Type::Function { .. } => return None, - Type::Pointer { to } => format!("{} *", a_spelling_of(to)?), - Type::Reference { to, rvalue } => format!( + ComputedType::Primary(primary) => primary.spelling().to_string(), + ComputedType::Named(name) => name.to_string(), + ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) + | ComputedType::Pack(_) + | ComputedType::Function(_) => return None, + // **C's tag is part of the spelling a message quotes** — and the inner type has to be one this can write + // exactly, which `?` enforces. + ComputedType::ElaboratedRecord { tag, of } => { + format!("{} {}", tag.word(), a_spelling_of(of)?) + } + ComputedType::Pointer(to) => format!("{} *", a_spelling_of(to)?), + ComputedType::Reference { to, rvalue } => format!( "{} {}", a_spelling_of(to)?, if *rvalue { "&&" } else { "&" } ), - Type::Qualified { of, qualifiers } => { + ComputedType::Qualified(qualified) => { let mut spelling = String::new(); - if qualifiers.is_const() { + if qualified.is_const { spelling.push_str("const "); } - if qualifiers.is_volatile() { + if qualified.is_volatile { spelling.push_str("volatile "); } - spelling.push_str(&a_spelling_of(of)?); + spelling.push_str(&a_spelling_of(&qualified.of)?); spelling } - Type::Array { of, extent } => match extent { - Some(extent) => format!("{}[{extent}]", a_spelling_of(of)?), - None => format!("{}[]", a_spelling_of(of)?), - }, + ComputedType::Array { of, extent } => format!("{}[{extent}]", a_spelling_of(of)?), }) } @@ -1670,7 +1678,7 @@ pub fn an_arrow_access(expression: &CppSyntaxNode) -> bool { pub fn a_class_can_be_built_from( context: &CheckContext<'_>, class: &str, - value: &sema::types::Type, + value: &ComputedType, ) -> Option { // **A target that names no class is a question this cannot answer**, and asking it is not free: the name goes to // the index, which resolves it, finds nothing, and falls back to a definition query and a member walk. Measured on @@ -1726,7 +1734,10 @@ pub fn a_class_can_be_built_from( // **The members declared in the class itself**: an inherited constructor is not this class's, which is the other // half of why the base walk was not needed — nothing it adds can be a constructor of this class. let mut constructors = 0usize; - for (_, fact) in &members { + for reference in &members { + let Some(fact) = context.index().fact(*reference) else { + continue; + }; let name = fact.name.as_str(); let is_a_constructor = name == class.rsplit("::").next().unwrap_or(class); // **A conversion operator is a way to build the class that has no parameter list to compare against** — @@ -1737,12 +1748,18 @@ pub fn a_class_can_be_built_from( if !is_a_constructor { continue; } - let Some(parameters) = fact.parameter_list() else { + // **The constructor's parameters, structurally.** A constructor with no recorded list decides nothing (the + // reading could not reach it), and its *facts* are what say so now — no parameter list is parsed. + let Some(file) = context.index().path_of(reference.file) else { continue; }; + let parameters = context.index().parameter_facts_of(file, fact); + if parameters.is_empty() { + continue; + } constructors += 1; - match parameters_that_could_accept(parameters, value) { + match parameters_that_could_accept(context.index(), parameters, value) { // One constructor that could take the value is enough for this rule to have nothing to say. Some(true) => return Some(true), // A parameter written in a way that decides nothing: the class may still be buildable. @@ -1758,41 +1775,32 @@ pub fn a_class_can_be_built_from( Some(false) } -/// **Whether one written parameter list holds a parameter that could accept this value** — see +/// **Whether one constructor's parameter facts hold a parameter that could accept this value** — see /// [`a_class_can_be_built_from`] for the rule and why it is this narrow. -fn parameters_that_could_accept(written: &str, value: &sema::types::Type) -> Option { +/// +/// The facts give the two things the old spelling walk had to cut out of text: the **types** (resolved structurally) +/// and the **defaults** (`ParameterFact::default_value`), so the arity and the classification are read from the +/// declaration rather than guessed from commas and `=`. +fn parameters_that_could_accept( + index: &ProjectIndex, + parameters: &[index::params::ParameterFact], + value: &ComputedType, +) -> Option { // The value has to be something this can classify. A class-to-class conversion is a question about two // declarations, and this is asked with one of them in hand. if !value.is_arithmetic() { return None; } - let inner = written.trim().trim_start_matches('(').trim_end_matches(')'); - let mut depth = 0i32; - let mut parameters: Vec = Vec::new(); - let mut current = String::new(); - for character in inner.chars() { - match character { - '<' | '(' | '[' => depth += 1, - '>' | ')' | ']' => depth -= 1, - // **A comma at depth zero separates parameters** — the whole reason this is counted rather than split: - // `std::pair` is one parameter with a comma in it. - ',' if depth == 0 => { - parameters.push(std::mem::take(&mut current)); - continue; - } - _ => {} - } - current.push(character); - } - parameters.push(current); - // **One value fills one parameter.** A constructor written with two parameters cannot be built from one value, // unless one of them has a default — `basic_string(size_type _Count, _Elem _Ch)` takes two, `_Ty(int, int = 0)` // takes one. Without this, `struct S { S(int, int); }; S s = 123;` was read as buildable because `int` accepts an // `int`, which is the arity question answered by the wrong rule. if parameters.len() > 1 { - return if parameters.iter().any(|parameter| parameter.contains('=')) { + return if parameters + .iter() + .any(|parameter| parameter.default_value.is_some()) + { None } else { Some(false) @@ -1801,7 +1809,8 @@ fn parameters_that_could_accept(written: &str, value: &sema::types::Type) -> Opt let mut any = false; for parameter in parameters { - let Some(classified) = could_take_an_arithmetic_value(¶meter) else { + let type_of = index.parameter_type(parameter)?; + let Some(classified) = could_take_an_arithmetic_value(&type_of) else { // A parameter this cannot classify decides nothing — a template parameter, an unknown name. return None; }; @@ -1813,31 +1822,18 @@ fn parameters_that_could_accept(written: &str, value: &sema::types::Type) -> Opt any.then_some(false) } -/// **Could a parameter written like this accept an arithmetic value?** +/// **Could a parameter of this type accept an arithmetic value?** /// -/// `None` for a parameter that decides nothing: a template parameter (`_Ty`, `T`, `class _Elem`), an `auto`, or a -/// name that is neither an arithmetic type nor a pointer to one. -fn could_take_an_arithmetic_value(parameter: &str) -> Option { - let mut written = parameter.trim(); - - // Drop a default argument: `int n = 0` is an `int`, and the `=` and everything after it is not the type. - if let Some(at) = written.find('=') { - written = written[..at].trim(); - } - if written.is_empty() || written == "..." || written.ends_with("...") { - // `...` takes anything, which is a parameter that could accept the value. - return Some(written == "..." || written.ends_with("...")); - } - - // The type is everything before the name: `const Widget& w` and `const Widget&` are the same type. - let words: Vec<&str> = written.split_whitespace().collect(); - let (type_words, _name) = match words.as_slice() { - [] => return None, - [only] => (vec![*only], ""), - [rest @ .., last] => (rest.to_vec(), *last), - }; - let type_written = type_words.join(" "); - +/// `None` for a parameter that decides nothing: a template parameter (`_Ty`, `T`), an `auto`, or a type this layer +/// cannot see through. `Some(false)` for a class by value and for a pointer, which no number converts to. +fn could_take_an_arithmetic_value(type_of: &ComputedType) -> Option { + use crate::index::types::{ComputedType, PrimaryType}; + + // **A name that stands for an arithmetic type.** A fact's builtin is a [`PrimaryType`] now, but a *name* can still + // be one of these spellings: `read_template_arguments` answers a `Named` for a template argument the tree gave no + // typed node (`std::vector` written as tokens), and a parameter this layer could not lower keeps its text as + // a name. The standard library's typedefs (`size_t`, `int64_t`) are names in any case — no declaration here calls + // them builtins. let arithmetic = |word: &str| { let word = word.trim_start_matches("const").trim(); matches!( @@ -1866,46 +1862,66 @@ fn could_take_an_arithmetic_value(parameter: &str) -> Option { | "std::uint64_t" ) }; - - // A pointer or reference **to something that is not arithmetic** cannot be built from a number: - // `MyString(const char*)` is the constructor `std::string` has and `1231` does not fit it. - let behind_the_operator = type_written - .split(['*', '&']) - .next() - .unwrap_or_default() - .trim() - .trim_start_matches("const") - .trim(); - let is_a_pointer_or_reference = type_written.contains('*') || type_written.contains('&'); - - if is_a_pointer_or_reference { - // **A pointer is not an arithmetic value; a reference to one is.** `const int&` binds an `int`, so the reference case - // asks about the type behind it — but `const char*` is a pointer, and an `int` does not convert to it. The first - // version asked the same question for both, which is how `std::string(const char*)` came back "this constructor can - // take `123131`" and the whole class case answered `Some(true)`. - if type_written.contains('*') { - return Some(false); + // **A template parameter takes whatever it is instantiated with** — `_Ty`, `_Elem`, `T`. Answered `None` because + // the call decides it, not this check. + let looks_like_a_template_parameter = |name: &str| { + name.starts_with('_') + || name == "T" + || name.len() == 1 + || name.starts_with("class ") + || name.starts_with("typename ") + }; + let a_primary = |primary: PrimaryType| { + if primary.is_a_placeholder() { + None + } else { + Some(primary.is_arithmetic()) } - return Some(arithmetic(behind_the_operator)); - } - - let bare = type_written.trim_start_matches("const").trim(); - if arithmetic(bare) { - return Some(true); - } - - // **A template parameter takes whatever it is instantiated with** — `_Ty`, `_Elem`, `class _Ty`, `typename T`. - let looks_like_a_template_parameter = bare.starts_with('_') - || bare == "T" - || bare.len() == 1 - || bare.starts_with("class ") - || bare.starts_with("typename "); - if looks_like_a_template_parameter { - return None; - } + }; - // **A name with no `*` or `&` and no `(` is a class by value** — `MyString(Widget)` cannot take a number. - Some(false) + Some(match type_of { + ComputedType::Primary(primary) => return a_primary(*primary), + // **A name with no arguments is a class by value** — `MyString(Widget)` cannot take a number — unless it is + // one of the standard arithmetic spellings (`size_t`, `int64_t`), which are names rather than builtins. + ComputedType::Named(name) => { + if arithmetic(name) { + true + } else if looks_like_a_template_parameter(name) { + return None; + } else { + false + } + } + ComputedType::Generic(_) => false, + ComputedType::TemplateParameter(_) => return None, + // **A pointer is not an arithmetic value; a reference to one is.** `const int&` binds an `int`, so the reference + // case asks about the type behind it — but `const char*` is a pointer, and an `int` does not convert to it. + ComputedType::Pointer(_) => false, + ComputedType::Reference { to, .. } => match &**to { + ComputedType::Primary(primary) => return a_primary(*primary), + ComputedType::Named(name) => { + if arithmetic(name) { + true + } else if looks_like_a_template_parameter(name) { + return None; + } else { + false + } + } + ComputedType::Qualified(qualified) => { + return could_take_an_arithmetic_value(&qualified.of); + } + ComputedType::Generic(_) => false, + _ => return None, + }, + ComputedType::Qualified(qualified) => { + return could_take_an_arithmetic_value(&qualified.of); + } + // **C's tag is transparent** — `struct int` is not a spelling, and what the tag wraps is the type in question. + ComputedType::ElaboratedRecord { of, .. } => return could_take_an_arithmetic_value(of), + ComputedType::Array { .. } | ComputedType::Function(_) => false, + ComputedType::Pack(of) => return could_take_an_arithmetic_value(of), + }) } /// **Run every check, in the order a consumer should show them**, and answer what they found. diff --git a/crates/cpp_code_analysis/src/sema/check/override_nonexistent.rs b/crates/cpp_code_analysis/src/sema/check/override_nonexistent.rs index 50b3c0d3..0430485b 100644 --- a/crates/cpp_code_analysis/src/sema/check/override_nonexistent.rs +++ b/crates/cpp_code_analysis/src/sema/check/override_nonexistent.rs @@ -121,7 +121,11 @@ impl Check for OverrideNonexistent { if !list.unlisted.is_empty() { could_not_read_a_base = true; } - if list.members.iter().any(|member| member.fact.name == *name) { + if list + .members + .iter() + .any(|member| context.index().member_name(member) == *name) + { declared_somewhere = true; break; } diff --git a/crates/cpp_code_analysis/src/sema/check/param_type_check.rs b/crates/cpp_code_analysis/src/sema/check/param_type_check.rs index 563f169c..79b185d2 100644 --- a/crates/cpp_code_analysis/src/sema/check/param_type_check.rs +++ b/crates/cpp_code_analysis/src/sema/check/param_type_check.rs @@ -15,10 +15,19 @@ //! one function of that name in this file a name that denotes an **overload set** is a call whose meaning //! is the language's resolution, and a check with a rule of its own //! would be wrong about every overload it did not pick -//! the parameters come from **this file's tree** see [`super::parameter_spellings_of`] for what reading -//! `DeclFact::parameters` instead cost — 119 findings on 200 MSVC headers +//! the parameters come from the declaration's **type**, not from `DeclFact::parameters` +//! that field is the *template* parameter list; reading it reported +//! 119 findings on 200 MSVC headers //! ``` //! +//! **Every candidate parameter is a structured type.** A function this file defines has its parameter lowered from the +//! `CppParam` node; a declaration the index holds resolves the type from its [`ParameterFact`]s, and a member applies +//! its instantiation's substitution and its class's aliases structurally — so nothing below this boundary parses a +//! spelling. The written form survives for one display-only job: the message quotes it. C's tag (`struct point`) is +//! part of the `ComputedType` (`ComputedType::ElaboratedRecord`), not a second reading of that text. +//! +//! [`ParameterFact`]: crate::index::params::ParameterFact +//! //! **A member call is the exception, and it is the ordinary case in the standard library.** A member's parameters //! come from the index (`members_of`, with the class's arguments substituted), and the library writes every //! mutator twice — `push_back(const _Ty&)` and `push_back(_Ty&&)` — so "several declarations, say nothing" was @@ -28,7 +37,7 @@ //! //! # `Known::No` and nothing else //! -//! [`Type::convertible_to`](crate::sema::types::Type::convertible_to) is the crate's single answer to "can a value +//! [`ComputedType::convertible_to`](ComputedType::convertible_to) is the crate's single answer to "can a value //! of this type be used where that one is declared", and it is `Known`-valued: a class with a conversion //! constructor, a template, a type from a header nobody read all answer `Unknown`, and **`Unknown` reports //! nothing**. A conversion this layer cannot see is not a conversion the program does not have. @@ -40,16 +49,24 @@ use super::callee_name_of; use super::is_a_function_definition; use super::member_access_above; use super::name_declared_by; -use super::parameter_spellings_of; +use crate::DeclFact; use crate::DeclKind; use crate::Known; +use crate::ProjectIndex; +use crate::ProjectMember; +use crate::index; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppAstNode; use cpp_parser::CppCallExpr; +use cpp_parser::CppDeclaration; use cpp_parser::CppNamespaceDecl; +use cpp_parser::CppParam; +use cpp_parser::CppParamList; use cpp_parser::CppSyntaxNode; use cpp_parser::source_range; use cpp_parser::subtree_text_spaced; +use std::path::Path; use super::{Check, CheckContext, DiagnosticCode}; @@ -68,8 +85,10 @@ impl Check for ParamTypeCheck { // needs its namespace: `techniques::describe(41)` and `techniques_app::describe(const Shape&)` are two different // functions, and a table keyed by the bare name compared the first against the second's parameter. Measured on the // project this layer is measured on: two findings, both against a definition the call does not name. - let mut by_name: std::collections::HashMap, Vec)>> = - std::collections::HashMap::new(); + let mut by_name: std::collections::HashMap< + String, + Option<(Vec, Vec)>, + > = std::collections::HashMap::new(); // **This file's own functions** - see CheckContext::own_syntax_nodes. for function in context .own_syntax_nodes() @@ -79,11 +98,10 @@ impl Check for ParamTypeCheck { let Some(name) = name_declared_by(&function) else { continue; }; - // **The name is not part of the type**, and `parameter_spellings_of` answers the type itself: - // `CppParam::get_type_text` composes it from the specifier sequence and the declarator's pointer, reference and - // array parts, so there is no name to strip. (This used to strip one from a spelling, which reported the same - // call when the parameter was unnamed and stayed silent when it was named.) - let parameters: Vec = parameter_spellings_of(&function); + // **Read once, here.** The parameter's type is lowered from its own node — the tree separates the type + // from the name, so there is nothing to strip — and the conversion question takes the value, so the + // conversion never parses. `written` is what the finding quotes; the type carries C's tag. + let parameters: Vec = candidates_of_a_function(&function); let namespaces = enclosing_namespaces(&function); match by_name.entry(name) { std::collections::hash_map::Entry::Occupied(mut e) => { @@ -111,10 +129,11 @@ impl Check for ParamTypeCheck { }; // **A member call is checked against the member.** `members_of` has already substituted the class's - // arguments into its members — `push_back(T value)` on a `std::vector` is `(int value)` — and - // `parameters_in` strips the parameter name, so the comparison is the same one the free-function path - // makes. Without this, a member call was skipped by the `by_name` lookup below: a member of a class is a - // **declaration**, and that table is built from this file's function **definitions**. + // arguments into its members — `push_back(T value)` on a `std::vector` is `(int value)` — and the + // row's substitution is applied to the parameter's **type** here, so the comparison is the same one the + // free-function path makes. Without this, a member call was skipped by the `by_name` lookup below: a + // member of a class is a **declaration**, and that table is built from this file's function + // **definitions**. if let Some(access) = member_access_above(&callee) { let parameters = member_parameter_lists(context, &access); if !parameters.is_empty() { @@ -135,7 +154,7 @@ impl Check for ParamTypeCheck { let qualifier = written_callee .rfind("::") .map(|at| written_callee[..at].trim().to_string()); - let parameters: Vec = match by_name.get(name.as_str()) { + let parameters: Vec = match by_name.get(name.as_str()) { Some(Some((namespaces, parameters))) => { if !a_qualifier_names_the_namespaces(qualifier.as_deref(), namespaces) { continue; @@ -150,22 +169,22 @@ impl Check for ParamTypeCheck { // **A call through a function pointer.** `int (*callback)(int)` called with `"text"` names // no function declaration — the callee is a **variable** whose type *is* the signature — so // both tables above answer nothing and the call went unchecked. The model answers the - // variable's type, and its parameters are `Type`s; they are written back as spellings so - // that this is the same comparison, with the same exemptions, as every other call. + // variable's type, and its parameters are already `ComputedType`s: they are the conversion question's + // own input, and only the spelling the message quotes is written at this boundary. // // A type this cannot write — a template parameter, a pack, a nested function type — skips the // call rather than guessing at a spelling. if let Some(parameters) = a_function_pointer_signature(context, &callee) - && let Some(spellings) = parameters + && let Some(parameters) = parameters .iter() - .map(a_spelling_of) - .collect::>>() + .map(CandidateParameter::from_type) + .collect::>>() { check_the_arguments( context, &call, &name, - std::slice::from_ref(&spellings), + std::slice::from_ref(¶meters), ); } continue; @@ -187,26 +206,135 @@ impl Check for ParamTypeCheck { /// overload resolution, and a check with a rule of its own would be wrong about every candidate it did not pick) /// but the rule [`check_the_arguments`] applies: a finding needs **every** candidate to disagree. /// -/// `parameters_in` strips each parameter's name, so what comes back is comparable with a type spelling. A member -/// with no parameter list — a field — is not a candidate: it is not a call. +/// The parameters come from the member's **facts** — the same list `parameter_facts_of` resolves through a summary, +/// a cooked reading or the synthetic arena — and each type is resolved structurally. A member with no parameter list — +/// a field — is not a candidate: it is not a call. fn member_parameter_lists( context: &CheckContext<'_>, access: &sema::resolve::MemberAccess, -) -> Vec> { +) -> Vec> { let Known::Yes((a_type, _)) = context.type_of(&access.object) else { return Vec::new(); }; - let Known::Yes(list) = context.model.members_of(&a_type.to_string()) else { + let Known::Yes(list) = context.model.members_of_computed(&a_type) else { return Vec::new(); }; + let index = context.index(); list.members .iter() - .filter(|member| member.fact.name == access.member) - .filter_map(|member| member.fact.parameter_list()) - .map(|written| sema::overload::parameters_in(written).0) + .filter(|member| context.model.member_name(member) == access.member) + .filter_map(|member| { + let fact = index.member_fact(member)?; + let file = index.member_path(member)?; + let parameters: Vec = index + .parameter_facts_of(file, fact) + .iter() + .filter_map(|parameter| { + CandidateParameter::from_a_member(index, member, fact, parameter) + }) + .collect(); + (!parameters.is_empty()).then_some(parameters) + }) + .collect() +} + +/// **The candidates a function definition's own parameter nodes give** — the file's own text, read once. +fn candidates_of_a_function(function: &CppSyntaxNode) -> Vec { + let Some(parameters) = + CppDeclaration::cast(function.clone()).and_then(|declaration| declaration.get_param_list()) + else { + return Vec::new(); + }; + candidates_of_a_list(¶meters) +} + +/// **Every candidate parameter of one CST list**, lowered from each `CppParam` node. +fn candidates_of_a_list(parameters: &CppParamList) -> Vec { + parameters + .children::() + .filter_map(|parameter| CandidateParameter::from_a_node(¶meter)) .collect() } +/// **One candidate parameter, read once at this boundary** — the spelling the declaring file wrote (the finding +/// quotes it) and the [`ComputedType`](ComputedType) the conversion question takes, which carries C's tag. +/// +/// The type is **lowered structurally**: from the parameter's own `CppParam` when the tree is in hand, or from the +/// [`crate::index::params::ParameterFact`] a summary or a cooked reading filed — which holds a +/// [`DeclaredType`](crate::cache::summary::DeclaredType) and resolves through the one store. No spelling is parsed: +/// `written` exists for the message alone. +#[derive(Clone)] +struct CandidateParameter { + written: String, + type_of: ComputedType, +} + +impl CandidateParameter { + /// **From a parameter node this file's own tree holds** — the type is lowered from the same node the spelling is + /// printed from, so the two cannot disagree about what was declared. + fn from_a_node(parameter: &CppParam) -> Option { + let type_of = sema::types::type_of_a_parameter(parameter)?; + let written = parameter.get_type_text(); + Some(Self { written, type_of }) + } + + /// **From a parameter fact** — a summary's, a cooked reading's, or the synthetic arena's. The fact's type is + /// resolved by [`crate::ProjectIndex::parameter_type`] and the spelling by + /// [`crate::ProjectIndex::parameter_spelling`], both read-only; the C tag is part of the resolved type. + fn from_fact(index: &ProjectIndex, parameter: &index::params::ParameterFact) -> Option { + let type_of = index.parameter_type(parameter)?; + let written = index.parameter_spelling(parameter)?; + Some(Self { + written: written.to_string(), + type_of, + }) + } + + /// **From a member row**, which may carry its class's instantiation. + /// + /// `std::vector::push_back` declares `T value`, and what the call faces is `int` — so the substitution the row + /// carries is applied **structurally** to the type ([`crate::index::types::ComputedType::substituted`]) and, for + /// the message only, to the spelling as text. That is the computation twin of + /// [`crate::ProjectIndex::member_parameter_list`], which the display layer already had. + fn from_a_member( + index: &ProjectIndex, + member: &ProjectMember, + fact: &DeclFact, + parameter: &index::params::ParameterFact, + ) -> Option { + let mut type_of = index.parameter_type(parameter)?; + let mut written = index.parameter_spelling(parameter)?; + if let Some(substitution) = &member.substitution { + // **The class's own aliases first, then its parameters** — the order the textual rewrite runs in. + // `void push_back(const value_type&)` with `using value_type = _Tp;` becomes `const _Tp&` and then + // `const int&`, and the conversion question is asked of that. + for (name, target) in &substitution.alias_bindings { + type_of = type_of.replacing( + name, + &target.substituted_by_bindings(&substitution.bindings), + ); + } + type_of = type_of.substituted_by_bindings(&substitution.bindings); + written = smol_str::SmolStr::new(substitution.applied_to_spelling(&written, fact)); + } + Some(Self { + written: written.to_string(), + type_of, + }) + } + + /// **From a type the model already holds** — the function-pointer signature's parameters. + /// + /// The spelling is written only because the finding quotes it, and it is written by [`a_spelling_of`], which + /// writes C's tag from the type when there is one. + fn from_type(type_of: &ComputedType) -> Option { + Some(Self { + written: a_spelling_of(type_of)?, + type_of: type_of.clone(), + }) + } +} + /// **One call's arguments against every declaration the name has** — the comparison both paths make. /// /// # The rule for more than one declaration @@ -220,7 +348,7 @@ fn check_the_arguments( context: &mut CheckContext<'_>, call: &CppSyntaxNode, name: &str, - candidates: &[Vec], + candidates: &[Vec], ) { // **The typed accessor, not `children()`.** A simple argument is a **token** in this grammar — a string literal is // one — so a walk over the argument list's child *nodes* comes out empty and this comparison never ran. `get_args` @@ -243,60 +371,47 @@ fn check_the_arguments( // **The candidates that can take an argument in this position.** A list with fewer parameters is a call // the arity check owns, not a disagreement about this one. - let mut disagreed_with: Option<&String> = None; + let mut disagreed_with: Option<&str> = None; let mut every_candidate_disagrees = true; for parameters in candidates { let Some(parameter) = parameters.get(at) else { continue; }; - // **A parameter written as a template parameter accepts anything.** `const _Ty&` for `push_back`, `T&&`, - // `_Ty2*`: what each takes is decided by the call, and there is nothing to compare an argument against. The - // relation below answers `No` for every such target — it names a type nothing declares — and that refusal - // is not this layer's to report. `convert::conversion` has the same rule for the class question, in its - // `Unknown` arm; a `No` never reached it. - if sema::convert::names_a_template_parameter_for_a_check(parameter) { + // **A parameter that is a template parameter accepts anything.** `const _Ty&` for `push_back`, `T&&`, + // `_Ty2*`: what each takes is decided by the call, and there is nothing to compare an argument against. + // The relation below answers `No` for every such target — it names a type nothing declares — and that + // refusal is not this layer's to report. The check is structural (`ComputedType::TemplateParameter`) plus the + // naming convention on a `Named`; it is asked of the parsed parameter before any comparison. + if sema::convert::names_a_template_parameter_for_a_check(¶meter.type_of) { every_candidate_disagrees = false; break; } // **C's string-literal rule** — the same one the other two rules ask, see // [`CheckContext::a_string_literal_in_a_char_pointer_position`]: a literal is `char[]` in C, so a - // `char *` parameter takes it exactly. - if context.a_string_literal_in_a_char_pointer_position(argument.syntax(), parameter) { + // `char *` parameter takes it exactly. The target is the candidate's **type**, asked structurally. + if context + .a_string_literal_in_a_char_pointer_position(argument.syntax(), ¶meter.type_of) + { every_candidate_disagrees = false; break; } - let target = sema::types::parse_type_spelling(parameter); - match from.convertible_to(&target) { - Known::No => { - disagreed_with.get_or_insert(parameter); - } - // `Yes` is fine, and `Unknown` is not this layer's to guess about. Either way **this** candidate - // could take the argument, and one that could is enough for silence. - Known::Yes(()) => { - every_candidate_disagrees = false; - break; - } - // **The class case, inside the `Unknown` arm.** `convertible_to` answers `Unknown` for every class target — - // it lives in the type algebra and never sees a constructor — so a parameter written `const std::string&` was - // silent whatever the argument was. The question goes to the index instead, and **only a definite refusal - // counts**: a class nobody has read, or a template parameter, still answers `None` and stays quiet. - // **The class case, through the shared facility** — see `sema::convert`. It normalises the spelling (a - // `const std::string&` parameter is `Reference { to: Named(..) }`, and `class_name()` answers `None` for a - // reference) and asks the index only for the class question, so a class nobody has read stays quiet. - Known::Unknown(_) => { - let conversion = sema::convert::conversion( - &from, - parameter, - context.language.family(), - |class| a_class_can_be_built_from(context, class, &from), - ); - if !conversion.is_refused() { - every_candidate_disagrees = false; - break; - } - disagreed_with.get_or_insert(parameter); - } + // **The class case, through the shared facility** — see `sema::convert`. It asks the type relation + // first and the index only for the class question, so a class nobody has read answers `Unknown` and + // stays quiet, and **only a definite refusal counts**: a candidate that could take the argument, or one + // this layer cannot compare, keeps its place. The parameter was parsed once when the candidates were + // built, and its type carries C's tag, which the shared facility reads structurally. + if !sema::convert::conversion_to( + &from, + ¶meter.type_of, + context.language.family(), + |class| a_class_can_be_built_from(context, class, &from), + ) + .is_refused() + { + every_candidate_disagrees = false; + break; } + disagreed_with.get_or_insert(parameter.written.as_str()); } let Some(parameter) = disagreed_with else { continue; @@ -359,33 +474,63 @@ fn a_qualifier_names_the_namespaces(qualifier: Option<&str>, namespaces: &[Strin /// /// `None` when the index knows no such function, knows several (an overload set, which this check declines), or when the /// declaration has no parameter list to compare against. -fn the_index_declares_one(context: &CheckContext<'_>, name: &str) -> Option> { +fn the_index_declares_one( + context: &CheckContext<'_>, + name: &str, +) -> Option> { // **The file's own summary first, then the index.** The summary holds what this file declares; `definitions` answers for // the rest of the project. A name declared once in either is one parameter list; several is an overload set, which this // check declines to resolve. - let mut written: Vec = context + // + // **The parameter facts, not the parameter list's text.** A summary's fact resolves through this file's own + // arena; an index definition's through the file that filed it. Two declarations of one name are compared by their + // facts, so "the same signature twice" is still one candidate and two different signatures are an overload set. + let index = context.index(); + let mut found: Vec<(&Path, &DeclFact)> = context .summary .declarations .iter() .filter(|fact| fact.kind == DeclKind::Function && fact.name == name) - .filter_map(|fact| fact.parameter_list().map(str::to_string)) + .filter(|fact| !index.parameter_facts_of(context.path, fact).is_empty()) + .map(|fact| (context.path, fact)) .collect(); - if written.is_empty() - && let Known::Yes(definitions) = context.index().definitions(name, context.path) + if found.is_empty() + && let Known::Yes(definitions) = index.definitions(name, context.path) { - written = definitions - .found - .iter() - .filter(|definition| definition.fact.kind == DeclKind::Function) - .filter_map(|definition| definition.fact.parameter_list().map(str::to_string)) - .collect(); + for definition in &definitions.found { + let Some(fact) = index.definition_fact(definition) else { + continue; + }; + if fact.kind != DeclKind::Function { + continue; + } + let Some(file) = index.definition_path(definition) else { + continue; + }; + if index.parameter_facts_of(file, fact).is_empty() { + continue; + } + found.push((file, fact)); + } } - written.dedup(); - if written.len() != 1 { + // **One signature, however many declarations state it.** A declaration and its definition name one function, and + // their facts may be two objects describing the same list. + let mut lists: Vec<&[index::params::ParameterFact]> = Vec::new(); + for (file, fact) in &found { + let facts = index.parameter_facts_of(file, fact); + if !lists.contains(&facts) { + lists.push(facts); + } + } + if lists.len() != 1 { return None; } - let (parameters, _variadic) = sema::overload::parameters_in(&written[0]); - Some(parameters) + Some( + lists[0] + .iter() + .filter_map(|parameter| CandidateParameter::from_fact(index, parameter)) + .collect(), + ) } /// **The parameter types of a function pointer**, when the callee's type is one. @@ -396,23 +541,23 @@ fn the_index_declares_one(context: &CheckContext<'_>, name: &str) -> Option, callee: &CppSyntaxNode, -) -> Option> { +) -> Option> { let Known::Yes((type_of, _)) = context.type_of(callee) else { return None; }; let mut type_of = &type_of; - while let sema::types::Type::Qualified { of, .. } = type_of { - type_of = of; + while let ComputedType::Qualified(qualified) = type_of { + type_of = &qualified.of; } // **Two shapes, because the model answers both**: `Pointer { to: Function }` is the type this is looking for, and // a bare `Function` is what the declaration reader answers for `int (*callback)(int)` — measured, and the reason // the first version of this function returned `None` for the case it was written for. The parameter list is the // same either way, and that is all a call needs. - if let sema::types::Type::Pointer { to } = type_of { + if let ComputedType::Pointer(to) = type_of { type_of = to; } match type_of { - sema::types::Type::Function { parameters, .. } => Some(parameters.clone()), + ComputedType::Function(function) => Some(function.parameters.to_vec()), _ => None, } } diff --git a/crates/cpp_code_analysis/src/sema/check/pure_virtual_not_overridden.rs b/crates/cpp_code_analysis/src/sema/check/pure_virtual_not_overridden.rs index f798f355..e15fbd84 100644 --- a/crates/cpp_code_analysis/src/sema/check/pure_virtual_not_overridden.rs +++ b/crates/cpp_code_analysis/src/sema/check/pure_virtual_not_overridden.rs @@ -77,19 +77,29 @@ impl Check for PureVirtualNotOverridden { // **Every pure virtual the hierarchy shows**, minus the ones something below already implemented. let mut missing: Vec = Vec::new(); for member in &list.members { - if member.fact.kind != DeclKind::Function - || !member.fact.modifiers.contains(DeclModifiers::PURE) + if context.index().member_kind(member) != Some(DeclKind::Function) + || !context + .index() + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::PURE)) { continue; } let overridden = list.members.iter().any(|other| { - other.fact.kind == DeclKind::Function - && other.fact.name == member.fact.name + context.index().member_kind(other) == Some(DeclKind::Function) + && context.index().member_name(other) == context.index().member_name(member) && other.depth < member.depth - && !other.fact.modifiers.contains(DeclModifiers::PURE) + && context + .index() + .member_modifiers(other) + .is_some_and(|modifiers| !modifiers.contains(DeclModifiers::PURE)) }); - if !overridden && !missing.iter().any(|name| name == member.fact.name.as_str()) { - missing.push(member.fact.name.to_string()); + if !overridden + && !missing + .iter() + .any(|name| name == context.index().member_name(member)) + { + missing.push(context.index().member_name(member).to_string()); } } if missing.is_empty() { diff --git a/crates/cpp_code_analysis/src/sema/check/redefinition.rs b/crates/cpp_code_analysis/src/sema/check/redefinition.rs index 73c44bce..7a1888c5 100644 --- a/crates/cpp_code_analysis/src/sema/check/redefinition.rs +++ b/crates/cpp_code_analysis/src/sema/check/redefinition.rs @@ -151,7 +151,7 @@ impl Check for Redefinition { // Measured on a C project of twenty-five files with one defect each: `int same(void); double same(void);` // was silent, and is an error in every compiler. if context.is_c() { - let mut returns: HashMap<&str, (&str, SourceRange)> = HashMap::new(); + let mut returns: HashMap<&str, (smol_str::SmolStr, SourceRange)> = HashMap::new(); let mut conflicts: Vec<(SourceRange, String, String, String)> = Vec::new(); for fact in context .declarations(DeclarationSource::Cooked) @@ -162,21 +162,22 @@ impl Check for Redefinition { if fact.local || fact.scope.is_some() || fact.kind != DeclKind::Function { continue; } - let Some(written) = fact.returns.as_deref().map(str::trim) else { + let Some(spelled) = context.index().returns_spelling_of(fact) else { continue; }; + let written = spelled.trim(); match returns.get(fact.name.as_str()) { - Some((first, _)) if *first != written => { + Some((first, _)) if first.as_str() != written => { conflicts.push(( fact.name_range, fact.name.to_string(), - (*first).to_string(), + first.to_string(), written.to_string(), )); } Some(_) => {} None => { - returns.insert(fact.name.as_str(), (written, fact.name_range)); + returns.insert(fact.name.as_str(), (spelled, fact.name_range)); } } } @@ -239,6 +240,11 @@ fn the_declaration_is_really_a_call(context: &CheckContext<'_>, range: SourceRan let name = first.text().to_string(); matches!( context.model.index().definition(name.as_str(), context.path), - Known::Yes(found) if found.fact.kind == DeclKind::Function + Known::Yes(found) + if context + .model + .index() + .definition_fact(&found) + .is_some_and(|fact| fact.kind == DeclKind::Function) ) } diff --git a/crates/cpp_code_analysis/src/sema/check/return_type_mismatch.rs b/crates/cpp_code_analysis/src/sema/check/return_type_mismatch.rs index 77593a1d..83d619fe 100644 --- a/crates/cpp_code_analysis/src/sema/check/return_type_mismatch.rs +++ b/crates/cpp_code_analysis/src/sema/check/return_type_mismatch.rs @@ -15,7 +15,7 @@ //! not reported a function whose return type is `auto` — a deduction question, not a conversion one //! ``` //! -//! # Why the conversion question is asked of [`Type::convertible_to`] +//! # Why the conversion question is asked of [`ComputedType::convertible_to`] //! //! Because that is the crate's single answer to "can a value of this type be used where that one is declared", and //! a check with an opinion of its own would be a second answer that drifts from the first. It is `Known`-valued, so @@ -28,10 +28,11 @@ use super::a_class_can_be_built_from; use super::a_literal_zero; +use super::function_head; use super::is_a_function_definition; -use super::return_type_written_by; use super::the_returns_in; use super::{Check, CheckContext, DiagnosticCode}; +use crate::DeclKind; use crate::Known; use crate::sema; use cpp_parser::CppAstNode; @@ -51,13 +52,35 @@ impl Check for ReturnTypeMismatch { .filter(is_a_function_definition) .collect::>() { - let Some(declared) = return_type_written_by(&function) else { + // **The type the declaration's fact recorded**, not the text before the name: `static int f()` is + // `int` and `explicit S(int)` is no return type at all, and the fact is the layer that already decided + // both — it holds a [`DeclaredType`](crate::cache::summary::DeclaredType) resolved once when the file + // was read. The node's name range finds the fact, in the file's own coordinates. + let Some(head) = function_head(&function) else { continue; }; - // A placeholder is a deduction question, not a conversion one. - if declared == "auto" || declared == "decltype(auto)" { + let Some(fact) = context + .fact_declared_at(head.name_range) + .filter(|fact| fact.kind == DeclKind::Function) + else { + continue; + }; + let Some(computed) = context.index().computed_returns_of(fact) else { + continue; + }; + // A placeholder is a deduction question, not a conversion one — asked of the **type's variants**, so + // `auto&` is the same answer as `auto`. + if computed.is_a_placeholder() { continue; } + // **The return type as the conversion question takes it**, and the spelling the message quotes. The two + // come from the same fact, and the type carries C's tag (`struct point`) — nothing here reads the + // spelling for it. + let declared = context + .index() + .returns_spelling_of(fact) + .map_or_else(|| computed.to_string(), |written| written.to_string()); + let declared_type = computed.clone(); for returned in the_returns_in(&function) { // **A `co_return` is the coroutine promise`s business, not a conversion.** The parser files @@ -85,7 +108,7 @@ impl Check for ReturnTypeMismatch { // defines it is absent: measured on sqlite's JNI binding, every `return;` in such a function was // reported. `parse_type_spelling` drops the convention, and `is_void` is the question. None => { - if !sema::types::parse_type_spelling(&declared).is_void() { + if !declared_type.is_void() { context.add( DiagnosticCode::ReturnTypeMismatch, source_range(returned.get_range()), @@ -97,7 +120,7 @@ impl Check for ReturnTypeMismatch { ); } } - Some(_) if declared == "void" => { + Some(_) if declared_type.is_void() => { // A value from a `void` function is legal when the expression is itself `void` — which is // the common shape `return f();` — and this layer does not distinguish them. } @@ -118,21 +141,22 @@ impl Check for ReturnTypeMismatch { continue; }; // **C's string-literal rule** — see - // [`CheckContext::a_string_literal_in_a_char_pointer_position`]. + // [`CheckContext::a_string_literal_in_a_char_pointer_position`]. The target is the fact's + // **type**, asked structurally. if context.a_string_literal_in_a_char_pointer_position( expression.syntax(), - &declared, + &declared_type, ) { continue; } - // **The shared facility**, the same one `param-type-check` and `assign-type-check` ask: it normalises - // the spelling (a return type written `const std::string&` is a reference, and `class_name()` answers - // `None` for one), asks the type relation first and the index only for the class question. Only - // `Refused` reports, so an unread class stays quiet — which is the rule the module's own note above - // is about. - let conversion = sema::convert::conversion( + // **The shared facility**, the same one `param-type-check` and `assign-type-check` ask. It + // takes the parsed return type — the shape a reference or a qualifier is transparent + // through — asks the type relation first and the index only for the class question. Only + // `Refused` reports, so an unread class stays quiet — which is the rule the module's own + // note above is about. + let conversion = sema::convert::conversion_to( &from, - &declared, + &declared_type, context.language.family(), |class| a_class_can_be_built_from(context, class, &from), ); diff --git a/crates/cpp_code_analysis/src/sema/check/test/argument_count.rs b/crates/cpp_code_analysis/src/sema/check/test/argument_count.rs index 04acd00b..5f9811fe 100644 --- a/crates/cpp_code_analysis/src/sema/check/test/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/test/argument_count.rs @@ -208,6 +208,53 @@ fn a_call_through_a_variable_is_not_a_free_function_of_that_name() { ); } +/// **A member call reads the list-level `...` from the fact, and a member without one keeps its arity.** +/// +/// The member path is the one that resolves a member's parameters through the index +/// (`ProjectIndex::parameter_facts_of`) rather than through a definition node, so it is where the fact's +/// [`crate::DeclFact::variadic_parameters`] is the answer: no text is scanned, and `void f(...)` — variadic with no +/// parameter at all — is representable because the bit is not a parameter fact. A member without the bit and without a +/// pack is still judged at its written arity, which is the half that says the change did not make every callee +/// variadic. +#[test] +fn a_member_call_reads_the_lists_ellipsis_from_the_fact() { + let variadic = codes_of( + "struct Logger {\n\ + \x20 void log(const char* format, ...);\n\ + };\n\ + void g(Logger& logger) { logger.log(\"%d %d\", 1, 2); }\n", + ); + assert_silent_about( + &variadic, + DiagnosticCode::ArgumentCount, + "`...` leaves room for the extra arguments", + ); + + let pack = codes_of( + "struct Logger {\n\ + \x20 template void forward(Args&&... args);\n\ + };\n\ + void g(Logger& logger) { logger.forward(1, 2, 3); }\n", + ); + assert_silent_about( + &pack, + DiagnosticCode::ArgumentCount, + "a pack leaves room for the rest", + ); + + let fixed = codes_of( + "struct Logger {\n\ + \x20 void log(const char* format, int value);\n\ + };\n\ + void g(Logger& logger) { logger.log(\"%d\", 1, 2); }\n", + ); + assert_reported( + &fixed, + DiagnosticCode::ArgumentCount, + "two parameters and three arguments is the finding", + ); +} + /// **A comparison in a default argument does not swallow the rest of the parameter list.** /// /// The old text walk treated every `<` as a template depth; `bool ok = 1 < 2` therefore left the depth open and diff --git a/crates/cpp_code_analysis/src/sema/check/test/concept_not_satisfied.rs b/crates/cpp_code_analysis/src/sema/check/test/concept_not_satisfied.rs index 5d0d0390..b3e3d8a0 100644 --- a/crates/cpp_code_analysis/src/sema/check/test/concept_not_satisfied.rs +++ b/crates/cpp_code_analysis/src/sema/check/test/concept_not_satisfied.rs @@ -92,6 +92,44 @@ fn an_overload_set_is_silent() { ); } +/// **`std::same_as` compares the argument's type structurally** — the constraint's argument is a `ComputedType` the +/// fact carries, so `same_as` is satisfied by `int` and refused by `long` (which converts, but is not the same +/// type). +#[test] +fn same_as_compares_the_type_the_constraint_names() { + let codes = codes_of( + "template T>\nT keep(T value);\n\n\ + int f() {\n int number = 0;\n long wide = 0;\n keep(number);\n keep(wide);\n return 0;\n}\n", + ); + assert_eq!( + codes + .iter() + .filter(|code| **code == DiagnosticCode::ConceptNotSatisfied) + .count(), + 1, + "`keep(number)` is the same type and silent; `keep(wide)` is not: {codes:?}" + ); +} + +/// **`std::convertible_to` asks the crate's one conversion relation** — an arithmetic widening converts and stays +/// silent, while a pointer to an `int` does not and is reported. The constraint's argument is the `ComputedType` the +/// fact holds; nothing is parsed at the call site. +#[test] +fn convertible_to_uses_the_conversion_relation() { + let codes = codes_of( + "template T>\nT take(T value);\n\n\ + int f() {\n double real = 1.0;\n const char* text = \"x\";\n take(real);\n take(text);\n return 0;\n}\n", + ); + assert_eq!( + codes + .iter() + .filter(|code| **code == DiagnosticCode::ConceptNotSatisfied) + .count(), + 1, + "`double` converts to `int`; `const char*` does not: {codes:?}" + ); +} + /// **An "object" concept over a value type is silence**: a class's answer needs its constructors, which this layer does /// not read, so only a reference is definitely not an object type. #[test] @@ -106,3 +144,23 @@ fn an_object_concept_over_a_value_type_is_silent() { "a value type is not answered about", ); } + +/// **A value argument makes a type concept's question unanswerable**, and the check stays silent. +/// +/// `template T>` is a user-written concept, so it was silent before this arm existed. The case that +/// pins the new representation is `std::same_as<42>`: it is a concept this check decides, and its first argument is +/// a **value**, not a type. There is no type to compare `int` against, so the honest answer is "not known" — the old +/// representation handed the check a fake type *named* `42` to compare against instead of no type at all. +#[test] +fn a_value_argument_is_not_a_type_to_compare() { + let codes = codes_of( + "template T>\nvoid take(T value);\n\n\ + template U>\nvoid keep(U value);\n\n\ + int f() {\n int number = 0;\n take(1.0);\n keep(number);\n return 0;\n}\n", + ); + assert_silent_about( + &codes, + DiagnosticCode::ConceptNotSatisfied, + "`SomeConcept<42>` is not evaluated, and `same_as<42>` asks about a value", + ); +} diff --git a/crates/cpp_code_analysis/src/sema/check/test/undefined_field.rs b/crates/cpp_code_analysis/src/sema/check/test/undefined_field.rs index 831c9b26..24f7984c 100644 --- a/crates/cpp_code_analysis/src/sema/check/test/undefined_field.rs +++ b/crates/cpp_code_analysis/src/sema/check/test/undefined_field.rs @@ -100,7 +100,7 @@ fn an_arrow_with_no_typed_pointee_is_silent() { /// **A typedef whose tag spells the same name in lowercase, beside a variable of that name, does not cycle.** /// `typedef struct proc { … } Proc;` with a global `Proc proc;` used to make the alias lookup follow the *variable* /// (`proc`: `type_of = Proc`) back to the typedef (`Proc`: `type_of = proc`) forever — neovim's `channel.c` opened -/// `proc->status` and the language server died with a stack overflow. Only a `Type` declaration may be an alias. +/// `proc->status` and the language server died with a stack overflow. Only a `ComputedType` declaration may be an alias. #[test] fn an_alias_and_a_variable_that_share_a_name_do_not_cycle() { let codes = codes_of( diff --git a/crates/cpp_code_analysis/src/sema/check/undefined_field.rs b/crates/cpp_code_analysis/src/sema/check/undefined_field.rs index 8efeabdd..f02c317d 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_field.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_field.rs @@ -200,7 +200,7 @@ impl Check for UndefinedField { if members .members .iter() - .any(|member| member.fact.name == access.member) + .any(|member| context.index().member_name(member) == access.member) { continue; } diff --git a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs index 83804901..4f9650db 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs @@ -59,7 +59,7 @@ use crate::ScopeKind; use crate::UnknownReason; use crate::file::coordinates::ReadingOffset; use crate::index; -use crate::sema; +use crate::index::types::ComputedType; use cpp_parser::CppCallExpr; use cpp_parser::CppDeclSpecifierSeq; use cpp_parser::CppDeclaration; @@ -352,13 +352,17 @@ fn the_declaration_is_a_value(context: &CheckContext<'_>, name: &str, at: usize) // declaration in a header. Only a definite answer is used: an unread header may declare the function this calls. match context.model.index().definitions(name, context.path) { Known::Yes(found) => { + let index = context.model.index(); let mut is_a_value = false; for declaration in found .found .iter() - .filter(|entry| entry.file != context.path) + .filter(|entry| index.path_of(entry.file) != Some(context.path)) { - if declaration.fact.kind == DeclKind::Function { + if index + .definition_fact(declaration) + .is_some_and(|fact| fact.kind == DeclKind::Function) + { return false; } is_a_value = true; @@ -378,19 +382,15 @@ fn the_declaration_is_a_value(context: &CheckContext<'_>, name: &str, at: usize) /// project writes (measured: two findings in this very corpus). Only a `Builtin` — a number — and a pointer to one are /// certainly not callable. Both shapes of a callable are real: the model answers `Pointer { to: Function }` for /// `int (*p)(int)` in some places and a bare `Function` in others (see `param_type_check`'s note on it). -fn whether_it_can_be_called(type_of: &sema::types::Type) -> Option { +fn whether_it_can_be_called(type_of: &ComputedType) -> Option { match type_of { - sema::types::Type::Qualified { of, .. } => whether_it_can_be_called(of), - sema::types::Type::Reference { to, .. } => whether_it_can_be_called(to), - sema::types::Type::Function { .. } => Some(true), + ComputedType::Qualified(qualified) => whether_it_can_be_called(&qualified.of), + ComputedType::Reference { to, .. } => whether_it_can_be_called(to), + ComputedType::Function(_) => Some(true), // A pointer to a function is the one callable pointer; a pointer to a *name* may be one through a typedef, and // this layer cannot see through it. - sema::types::Type::Pointer { to } => whether_it_can_be_called(to), - sema::types::Type::Builtin { spelling } - if !matches!(spelling.as_str(), "void" | "auto" | "decltype(auto)") => - { - Some(false) - } + ComputedType::Pointer(to) => whether_it_can_be_called(to), + ComputedType::Primary(primary) if primary.is_arithmetic() => Some(false), _ => None, } } @@ -648,7 +648,7 @@ fn a_declaration_is_visible(context: &CheckContext<'_>, name: &str, at: usize) - && members .members .iter() - .any(|member| member.fact.name.as_str() == name) + .any(|member| context.index().member_name(member) == name) { return true; } @@ -657,10 +657,9 @@ fn a_declaration_is_visible(context: &CheckContext<'_>, name: &str, at: usize) - // is the scope tree's answer above, in the rendering's coordinates — the index records the file's own offsets, // and the two are not comparable one by one once a directive has been expanded. match context.model.index().definitions(name, context.path) { - Known::Yes(found) => found - .found - .iter() - .any(|declaration| declaration.file != context.path), + Known::Yes(found) => found.found.iter().any(|declaration| { + context.model.index().path_of(declaration.file) != Some(context.path) + }), // **"Not declared here" is the answer this rule exists for**, and it is an `Unknown` — the index does not // claim absence unless it was asked and found nothing. Every other reason is a name this layer cannot speak // about: ambiguous (declared twice), behind an unread include, in a module the project does not contain — diff --git a/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs b/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs index 81a75069..46b88a30 100644 --- a/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs +++ b/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs @@ -104,7 +104,7 @@ impl Check for UnresolvedType { }; let template_parameters: std::collections::HashSet<&str> = declarations .iter() - .flat_map(|fact| fact.parameters().iter().map(String::as_str)) + .flat_map(|fact| fact.parameters().iter().map(smol_str::SmolStr::as_str)) .collect(); // **A macro is not a type** — `#define MYTYPE int` then `MYTYPE x;`. let macros: std::collections::HashSet<&str> = context @@ -123,7 +123,7 @@ impl Check for UnresolvedType { if fact.local || matches!(fact.kind, DeclKind::MacroLike | DeclKind::Other) { continue; } - for spelling in types_this_declaration_uses(fact) { + for spelling in types_this_declaration_uses(context.index(), context.path, fact) { // **The declarator is not a type.** A parameter list is a string of *declarations* — `(std::vector // vec)` — and its last word at depth zero is the name being declared, which the rule must not ask about // (`vec` is not a type, and `definitions` cannot say so in a way that reads as an answer). diff --git a/crates/cpp_code_analysis/src/sema/check/unused.rs b/crates/cpp_code_analysis/src/sema/check/unused.rs index e83a63f8..4516ff9a 100644 --- a/crates/cpp_code_analysis/src/sema/check/unused.rs +++ b/crates/cpp_code_analysis/src/sema/check/unused.rs @@ -74,10 +74,11 @@ fn is_deliberately_unused(name: &str) -> bool { /// /// The declared type is the evidence and the only evidence: `auto` says nothing about a destructor either, so a local /// whose type the fact did not record is left alone. -fn its_type_cannot_have_a_destructor(fact: &DeclFact) -> bool { - fact.type_of - .as_deref() - .is_some_and(undefined_name::is_a_builtin_spelling) +fn its_type_cannot_have_a_destructor(context: &CheckContext<'_>, fact: &DeclFact) -> bool { + context + .index() + .type_spelling_of(fact) + .is_some_and(|spelled| undefined_name::is_a_builtin_spelling(&spelled)) } /// A name that is not worth asking about: a keyword-shaped spelling, or nothing at all. fn is_a_candidate(name: &str) -> bool { @@ -220,7 +221,7 @@ impl Check for Unused { // [`its_type_cannot_have_a_destructor`]. `Guard guard(counter);` and `std::shared_lock reader(mutex);` // were the two findings on `exceptions.cpp` and `concurrency.cpp` of the C++ corpus, and both are objects // whose whole use is the side effect of their lifetime. - if !its_type_cannot_have_a_destructor(fact) { + if !its_type_cannot_have_a_destructor(context, fact) { continue; } diff --git a/crates/cpp_code_analysis/src/sema/check/use_after_free.rs b/crates/cpp_code_analysis/src/sema/check/use_after_free.rs index 2f81af8f..ce5bc5c6 100644 --- a/crates/cpp_code_analysis/src/sema/check/use_after_free.rs +++ b/crates/cpp_code_analysis/src/sema/check/use_after_free.rs @@ -317,8 +317,10 @@ fn the_frees_of(context: &CheckContext<'_>, callee: &CppSyntaxNode) -> Option format!("{scope}::{name}"), _ => name, }; - if let Known::Yes(found) = context.index().definition(&spelling, context.path) { - return Some(u64::from(found.fact.frees)); + if let Known::Yes(found) = context.index().definition(&spelling, context.path) + && let Some(fact) = context.index().definition_fact(&found) + { + return Some(u64::from(fact.frees)); } } // **The spelling alone**, for a helper the reading cannot resolve. Only a free function: a member call's name is @@ -328,7 +330,10 @@ fn the_frees_of(context: &CheckContext<'_>, callee: &CppSyntaxNode) -> Option Some(u64::from(found.fact.frees)), + Known::Yes(found) => context + .index() + .definition_fact(&found) + .map(|fact| u64::from(fact.frees)), _ => None, } } diff --git a/crates/cpp_code_analysis/src/sema/check/use_override.rs b/crates/cpp_code_analysis/src/sema/check/use_override.rs index f23a8252..a39d2abb 100644 --- a/crates/cpp_code_analysis/src/sema/check/use_override.rs +++ b/crates/cpp_code_analysis/src/sema/check/use_override.rs @@ -87,10 +87,14 @@ impl Check for UseOverride { .members .iter() .filter(|member| { - member.fact.modifiers.contains(DeclModifiers::VIRTUAL) - || member.fact.modifiers.contains(DeclModifiers::OVERRIDE) + context.index().member_modifiers(member).is_some_and( + |modifiers| { + modifiers.contains(DeclModifiers::VIRTUAL) + || modifiers.contains(DeclModifiers::OVERRIDE) + }, + ) }) - .map(|member| member.fact.name.to_string()) + .map(|member| context.index().member_name(member).to_string()) .collect(), _ => Vec::new(), }; diff --git a/crates/cpp_code_analysis/src/sema/constant.rs b/crates/cpp_code_analysis/src/sema/constant.rs index e944431b..1d1eba48 100644 --- a/crates/cpp_code_analysis/src/sema/constant.rs +++ b/crates/cpp_code_analysis/src/sema/constant.rs @@ -18,11 +18,10 @@ use crate::FileView; use crate::preprocess; use cpp_parser::CppAstNode; use cpp_parser::CppEnumerator; -use cpp_parser::CppParser; -use cpp_parser::ParserConfig; use cpp_parser::is_trivia; use cpp_parser::token_at; use cpp_parser::{CppSyntaxKind, CppSyntaxNode, CppTokenKind}; +use cpp_parser::{LexerConfig, lex}; /// **How many names one value may be followed through** — `A = B + 1`, `B = C << 2`, … A cycle (`const int a = b; /// const int b = a;`) is not something anyone writes, and a language server meets whatever is written: past this depth @@ -56,47 +55,59 @@ pub fn value_at( } } -/// Is this declarator's declaration `const` or `constexpr`? — read from the declaration's own text, up to the name. +/// Is this declarator's declaration `const` or `constexpr`? — read from the declaration's **tokens**, up to the name. /// /// Up to the name and no further: a `const` in a *sibling* declarator (`int a = 1, b = 2;` after a `const int c = 3;` /// in the same statement) is that sibling's, and reading the whole statement would claim it here. +/// +/// The question is asked of the tokens the tree already holds (`const` and `constexpr` are token kinds, not words to +/// find), so a comment that mentions `const` before the name cannot make an ordinary variable look constant. fn is_a_constant_declaration(declarator: &CppSyntaxNode) -> bool { - let mut node = declarator.parent(); - let declaration = loop { - let Some(inner) = node else { - return false; - }; - if matches!( - CppSyntaxKind::from(inner.kind()), + let Some(declaration) = declarator.ancestors().skip(1).find(|node| { + matches!( + CppSyntaxKind::from(node.kind()), CppSyntaxKind::Declaration | CppSyntaxKind::InitDeclarator - ) { - break inner; - } - node = inner.parent(); + ) + }) else { + return false; }; - let together = declaration.text_range().start(); - let up_to_the_name = declarator - .text_range() - .start() - .checked_sub(together) - .and_then(|offset| { - declaration - .text() - .to_string() - .get(..usize::from(offset)) - .map(str::to_string) + let up_to_the_name = declarator.text_range().start(); + declaration + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .take_while(|token| token.text_range().start() < up_to_the_name) + .map(|token| CppTokenKind::from(token.kind())) + .any(|kind| { + matches!( + kind, + CppTokenKind::ConstKeyword + | CppTokenKind::ConstexprKeyword + | CppTokenKind::ConstevalKeyword + | CppTokenKind::ConstinitKeyword + ) }) - .unwrap_or_default(); - up_to_the_name - .split(|character: char| !character.is_alphanumeric() && character != '_') - .any(|word| matches!(word, "const" | "constexpr" | "consteval" | "constinit")) } -/// **The value of a constant expression written as text**, with `names` answering for the identifiers in it. +/// **The value of a constant expression written as text** — the **lexer boundary**, and only that. +/// +/// A macro body is not a CST node in this crate: a caller's macro table hands one over as text, so it has to be lexed +/// before the token evaluator can fold it. This function does exactly that one step and nothing else — it does **not** +/// parse a declaration, and it is not the analysis path. The analysis path is [`value_of_tokens`] with the CST's own +/// tokens; a **test** may use this because a test starts from a spelling, and this file's own `#define` bodies are read +/// as tokens already ([`own_macro_body`]), so the only caller left is the macro body another file supplies. pub fn value_of(written: &str, names: &mut dyn FnMut(&str) -> Option) -> Option { let tokens = tokens_of(written); + value_of_tokens(&tokens, names) +} + +/// **The value of a token sequence**, with `names` answering for the identifiers in it. No parse and no string +/// reconstruction: the tokens come from the CST or from the lexer. +pub fn value_of_tokens( + tokens: &[(CppTokenKind, String)], + names: &mut dyn FnMut(&str) -> Option, +) -> Option { let mut at = 0usize; - let value = an_expression(&tokens, &mut at, names)?; + let value = an_expression(tokens, &mut at, names)?; (at == tokens.len()).then_some(value) } @@ -119,8 +130,7 @@ fn an_enumerators_value( let after_the_name = tokens_after_the_name(&each)?; match after_the_name.first() { Some((kind, _)) if *kind == CppTokenKind::Assign => { - let written = join(&after_the_name[1..]); - value = value_of(&written, &mut |name| { + value = value_of_tokens(&after_the_name[1..], &mut |name| { a_names_value(view, name, macro_body, depth + 1) })?; } @@ -146,7 +156,7 @@ fn a_declarators_value( return None; } let written = initialiser_of(declarator)?; - value_of(&written, &mut |name| { + value_of_tokens(&written, &mut |name| { a_names_value(view, name, macro_body, depth + 1) }) } @@ -162,7 +172,14 @@ fn a_names_value( return None; } // **A macro first**, because that is what the preprocessor would have done: `UCHAR_MAX` is `0xff` to the compiler. - if let Some(body) = own_macro_body(view, name).or_else(|| macro_body(name)) { + // This file's own `#define` is already a token list, so it goes straight to the evaluator; a macro body the caller + // reads out of another file arrives as text and is lexed at that boundary (see [`value_of`]). + if let Some(body) = own_macro_body(view, name) { + return value_of_tokens(&body, &mut |inner| { + a_names_value(view, inner, macro_body, depth + 1) + }); + } + if let Some(body) = macro_body(name) { return value_of(&body, &mut |inner| { a_names_value(view, inner, macro_body, depth + 1) }); @@ -189,8 +206,9 @@ fn a_names_value( } } -/// **This file's own object-like macro**, when it writes one with that name — the body is the text after the name. -fn own_macro_body(view: &FileView, name: &str) -> Option { +/// **This file's own object-like macro**, when it writes one with that name — the body as the **tokens** the +/// preprocessor read, never as one concatenated string. +fn own_macro_body(view: &FileView, name: &str) -> Option> { let preprocessing = preprocess(&view.source, view.tree.get_tokens()); for spanned in &preprocessing.directives { if let preprocess::directive::Directive::Define(define) = &spanned.directive @@ -201,14 +219,16 @@ fn own_macro_body(view: &FileView, name: &str) -> Option { .as_ref() .is_none_or(|params| params.is_empty()) { - // The body is **tokens**, and their own text is the spelling the folder reads: `0xff`, `1 << 4`. + // The body is already a token list — `0xff`, `1`, `<<`, `4` — and the evaluator reads tokens. Keeping the + // boundaries is also what makes `0xff` one literal rather than a spelling that has to be re-lexed. return Some( definition .body .tokens .iter() - .map(|token| token.text.as_ref()) - .collect::(), + .filter(|token| !is_trivia(token.kind)) + .map(|token| (token.kind, token.text.to_string())) + .collect(), ); } } @@ -216,13 +236,13 @@ fn own_macro_body(view: &FileView, name: &str) -> Option { } /// **The initialiser a declarator writes**, as text — everything after its `=` and before its `,`/`;`. -fn initialiser_of(declarator: &CppSyntaxNode) -> Option { +fn initialiser_of(declarator: &CppSyntaxNode) -> Option> { let tokens = tokens_of_the_node(declarator); let equals = tokens .iter() .position(|(kind, _)| *kind == CppTokenKind::Assign)?; let mut depth = 0i32; - let mut written = String::new(); + let mut written = Vec::new(); for (kind, text) in &tokens[equals + 1..] { match text.as_str() { "(" | "[" | "{" | "<" => depth += 1, @@ -230,11 +250,9 @@ fn initialiser_of(declarator: &CppSyntaxNode) -> Option { "," | ";" if depth == 0 => break, _ => {} } - let _ = kind; - written.push_str(text); - written.push(' '); + written.push((*kind, text.clone())); } - (!written.trim().is_empty()).then(|| written.trim().to_string()) + (!written.is_empty()).then_some(written) } /// The tokens after a declaration's own name, trivia dropped. @@ -254,29 +272,19 @@ fn tokens_of_the_node(node: &CppSyntaxNode) -> Vec<(CppTokenKind, String)> { .collect() } -fn join(tokens: &[(CppTokenKind, String)]) -> String { - tokens - .iter() - .map(|(_, text)| text.as_str()) - .collect::>() - .join(" ") -} - /// A constant expression's tokens, read by the crate's own lexer rather than split by hand: `0xff` and `'a'` are one /// token each, and `<<` is one operator. fn tokens_of(written: &str) -> Vec<(CppTokenKind, String)> { - let tree = CppParser::parse(written, ParserConfig::default()); - let source = written.to_string(); - tree.get_tokens() - .iter() - .filter(|token| { - let kind = token.kind; - !is_trivia(kind) - }) + // **The lexer, not a synthetic parse.** A constant expression is a token sequence; parsing it as a declaration + // adds a grammar and a configuration for no answer the evaluator does not already have. + let (tokens, _errors) = lex(written, &LexerConfig::default()); + tokens + .into_iter() + .filter(|token| !is_trivia(token.kind)) .map(|token| { - let start = token.range.start_offset.min(source.len()); - let end = token.range.end_offset().min(source.len()); - (token.kind, source[start..end].to_string()) + let start = token.range.start_offset.min(written.len()); + let end = token.range.end_offset().min(written.len()); + (token.kind, written[start..end].to_string()) }) .collect() } @@ -465,38 +473,26 @@ mod tests { "FIRST_RESERVED" => Some(256), _ => None, }; - assert_eq!(value_of("UCHAR_MAX + 1", &mut names), Some(256)); - assert_eq!(value_of("FIRST_RESERVED", &mut names), Some(256)); - assert_eq!(value_of("1 << 4", &mut names), Some(16)); - assert_eq!(value_of("0xff", &mut names), Some(255)); - assert_eq!(value_of("(1 + 2) * 3", &mut names), Some(9)); - assert_eq!(value_of("'a'", &mut names), Some(97)); - assert_eq!(value_of("10 / 3", &mut names), Some(3)); - assert_eq!( - value_of("1 +", &mut names), - None, - "a truncated expression is not a value" - ); - assert_eq!( - value_of("1.5", &mut names), - None, - "a float is not this layer's" - ); - assert_eq!(value_of("unknown + 1", &mut names), None); - assert_eq!(value_of("0xff", &mut names), Some(255)); - assert_eq!(value_of("(1 + 2) * 3", &mut names), Some(9)); - assert_eq!(value_of("'a'", &mut names), Some(97)); - assert_eq!(value_of("10 / 3", &mut names), Some(3)); + // **The evaluator's input is tokens.** `tokens_of` is the lexer helper this module's boundary uses, and a test + // that started from a spelling would otherwise not exercise the token path at all. + let fold = |written: &str, names: &mut dyn FnMut(&str) -> Option| { + value_of_tokens(&tokens_of(written), names) + }; + assert_eq!(fold("UCHAR_MAX + 1", &mut names), Some(256)); + assert_eq!(fold("FIRST_RESERVED", &mut names), Some(256)); + assert_eq!(fold("1 << 4", &mut names), Some(16)); + assert_eq!(fold("0xff", &mut names), Some(255)); + assert_eq!(fold("(1 + 2) * 3", &mut names), Some(9)); + assert_eq!(fold("'a'", &mut names), Some(97)); + assert_eq!(fold("10 / 3", &mut names), Some(3)); assert_eq!( - value_of("1 +", &mut names), + fold("1 +", &mut names), None, "a truncated expression is not a value" ); - assert_eq!( - value_of("1.5", &mut names), - None, - "a float is not this layer's" - ); - assert_eq!(value_of("unknown + 1", &mut names), None); + assert_eq!(fold("1.5", &mut names), None, "a float is not this layer's"); + assert_eq!(fold("unknown + 1", &mut names), None); + // …and the lexer boundary is the same evaluator over the same tokens. + assert_eq!(value_of("UCHAR_MAX + 1", &mut names), Some(256)); } } diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index 4b7e3c8c..8eff3be3 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -9,6 +9,19 @@ //! question `textDocument/definition` has to answer — and until this module existed the answer was the first declaration //! the scope happened to bind, for either call. //! +//! # The condition is a tree, not a spelling +//! +//! Everything this module decides is read from the **typed CST the grammar built**: a `requires`-clause hands over its +//! condition expression ([`CppRequiresClause::get_condition`]), `enable_if<…>` hands over its first template argument +//! ([`the_condition_of_node`]), and the operators, the literals and the trait calls are the nodes the expression +//! grammar already made — `BinaryExpr` for `&&`/`||`, `UnaryExpr` for `!`, `NameExpr` with a `TemplateArgumentList` +//! for `std::is_integral`. Nothing is split, re-lexed or re-parsed here: a condition that cannot be decided from +//! the tree answers [`None`], and no spelling is read back. +//! +//! The **arguments** are structured too: a trait argument is read with the type layer's own reader +//! ([`crate::sema::types::type_of_a_type_id`]) and the caller's template bindings are [`ComputedType`]s, so +//! `is_same` is a comparison of two types rather than of two spellings. +//! //! # What it decides, and what it refuses //! //! The condition is a **constant expression over types**, and this is not a compiler: it knows the fundamental traits by @@ -17,7 +30,29 @@ //! that nothing has bound — answers [`None`], meaning *this layer cannot tell*, and a caller must keep the candidate //! rather than delete it. Deleting on "unknown" is how a reader loses the overload their program actually chose. -/// **The fundamental traits this layer can answer** — the ones whose answer follows from the spelling alone. +use crate::index::types::{ComputedType, PrimaryType}; +use crate::sema::types::{type_of_a_type_id, with_template_parameters}; +use cpp_parser::CppAstNode; +use cpp_parser::CppAstToken; +use cpp_parser::CppBinaryExpr; +use cpp_parser::CppCallExpr; +use cpp_parser::CppExpr; +use cpp_parser::CppInitListExpr; +use cpp_parser::CppLiteralExpr; +use cpp_parser::CppNameExpr; +use cpp_parser::CppParenExpr; +use cpp_parser::CppRequiresClause; +use cpp_parser::CppSyntaxElement; +use cpp_parser::CppSyntaxKind; +use cpp_parser::CppSyntaxNode; +use cpp_parser::CppTemplateArg; +use cpp_parser::CppTemplateArgList; +use cpp_parser::CppTemplateParamList; +use cpp_parser::CppTokenKind; +use cpp_parser::CppUnaryExpr; +use smol_str::SmolStr; + +/// **The fundamental traits this layer can answer** — the ones whose answer follows from the type's shape alone. /// /// Deliberately short: each is a property of a builtin type that needs no declaration to decide, and adding a name here /// is claiming to know what the standard library's own definition says. @@ -56,10 +91,9 @@ impl Trait { }) } - /// `None` when the spelling is not a type this layer knows — an unbound template parameter, a `decltype` — because a - /// trait of an unknown type is *cannot tell*, and answering `false` would delete a candidate. + /// **The answer the trait gives about a structured type**, or `None` when the type is one this layer cannot place. /// - /// # What the spelling alone can answer + /// # What the shape alone can answer /// /// ```text /// the scalar int, double, void … is_integral, is_floating_point, is_arithmetic, is_void @@ -68,126 +102,129 @@ impl Trait { /// int[4] int(int) is_array, is_function /// ``` /// - /// The decorators are read off the same pieces the scalar is read from, so `const int*` is a pointer that is **not** - /// const and `const int&` is a reference that **is** — in that order, which is what the language means by each. + /// The decorators are read off the structure, in the order the language means them: a **reference** is the + /// outermost `&`, the **qualifiers that belong to the object itself** are the ones written outside any pointer + /// (`const int*` is a pointer to a const `int` and is **not** const, `int* const` is), and the outermost pointer, + /// array or function is what `*`, `[…]` and `(…)` state. The scalar underneath all of them is what the fundamental + /// traits are a property of. + /// + /// **The one thing that is still a name** is the scalar's own: `int`, `unsigned long long`, `size_t` are matched + /// against the type model's builtin spelling. That is the type's identity in this layer, not the condition's + /// spelling — no part of the condition is re-read to obtain it. /// - /// **`is_class` and `is_enum` are not here**, and the refusal is the honest answer rather than an omission: a name is a - /// class, an enum or a typedef, and only a symbol table says which. `is_class` answered `false` would delete - /// the overload the program chose; answered `true` it would delete the other. So would `is_base_of` and - /// `is_convertible`, which are relations between two types rather than a property of one spelling. - fn of(self, spelling: &str) -> Option { - let spelling = spelling.trim(); - // **A reference is a trailing `&`**, one or two, and the rest of the spelling is what it refers to. - let reference = spelling.ends_with('&'); - let without_reference = spelling.trim_end_matches('&').trim(); - // **`const` and `volatile` on the *topmost* type** — not on what it points at or refers to. `const int` is const; - // `const int*` is a pointer to a const int and is **not** const itself, and `const int&` is a reference to one. - // The outermost qualifier is either at the front with nothing wrapping it after it, or written after the `*` - // (`int* const`). Read from the spelling as it was given, before the decorators are peeled. - let topmost = without_reference; - let qualified_const = (topmost.starts_with("const ") && !topmost.contains('*')) - || topmost.ends_with(" const"); - let qualified_volatile = (topmost.starts_with("volatile ") && !topmost.contains('*')) - || topmost.ends_with(" volatile"); - // **The qualifiers are then peeled** so the scalar underneath can be read: `const volatile int` is an `int`. - let mut bare = without_reference; + /// **`is_class` and `is_enum` are not here**, and the refusal is the honest answer rather than an omission: a name + /// is a class, an enum or a typedef, and only a symbol table says which. `is_class` answered `false` + /// would delete the overload the program chose; answered `true` it would delete the other. So would `is_base_of` + /// and `is_convertible`, which are relations between two types rather than a property of one type. + fn of(self, written: &ComputedType) -> Option { + // **The outermost decorations, from the outside in.** A reference is transparent to every question below it; + // a qualifier counts only while nothing derived has been crossed, because `const int*` is a pointer whose + // pointee is const rather than a const pointer. + let mut current = written; + let mut reference = false; + let mut topmost_const = false; + let mut topmost_volatile = false; loop { - if let Some(rest) = bare.strip_prefix("const ") { - bare = rest.trim(); - continue; - } - if let Some(rest) = bare.strip_prefix("volatile ") { - bare = rest.trim(); - continue; - } - break; - } - let mut pointers_start = bare; - while let Some(rest) = pointers_start.strip_suffix('*') { - pointers_start = rest.trim(); - } - let pointers = bare.ends_with('*'); - let scalars = pointers_start.trim(); - // **A declaration's own shape**: an array writes `[`, a function type writes `(` and no object type does. - let array = scalars.contains('['); - let function = !array && scalars.contains('('); - let integral = matches!( - scalars, - "char" - | "signed char" - | "unsigned char" - | "short" - | "unsigned short" - | "int" - | "unsigned int" - | "unsigned" - | "long" - | "unsigned long" - | "long long" - | "unsigned long long" - | "bool" - | "wchar_t" - | "char8_t" - | "char16_t" - | "char32_t" - | "size_t" - | "ptrdiff_t" - | "std::size_t" - ); - let floating = matches!(scalars, "float" | "double" | "long double"); - let signed = - !scalars.starts_with("unsigned") && !matches!(scalars, "bool" | "unsigned") && integral; - // **A name this layer cannot classify is not evidence of anything.** The convention that names a template - // parameter is one capital letter (T, U, V) is what separates "a type nobody bound" from "a type the program - // named" — the first is *cannot tell*. `decltype(…)` and `auto` are not types until something decides them, and - // a name whose own spelling this cannot place is left to the traits that need no scalar at all (a name with `&` - // *is* a reference whatever it names). - let a_parameter_by_convention = scalars.len() == 1 - && scalars - .chars() - .all(|character| character.is_ascii_uppercase()); - let unknown = - a_parameter_by_convention || scalars.starts_with("decltype") || scalars == "auto"; - - // The decorators answer for **any** type, known or not: `std::string&` is a reference whichever class `string` is. - match self { - Trait::Reference => return Some(reference), - Trait::Const => { - if unknown { - return None; + match current { + ComputedType::Reference { to, .. } => { + reference = true; + current = to; } - return Some(qualified_const); - } - Trait::Volatile => { - if unknown { - return None; + ComputedType::Qualified(qualified) => { + topmost_const |= qualified.is_const; + topmost_volatile |= qualified.is_volatile; + current = &qualified.of; } - return Some(qualified_volatile); + _ => break, } - Trait::Array => { - if unknown { - return None; - } - return Some(array); + } + // **The one derived type the file wrote around the scalar** — `*`, `[…]`, `(…)`, or a pack's `...`. + let mut pointer = false; + let mut array = false; + let mut function = false; + let mut pack = false; + match current { + ComputedType::Pointer(to) => { + pointer = true; + current = to; } - Trait::Function => { - if unknown { - return None; - } - return Some(function); + ComputedType::Array { of, .. } => { + array = true; + current = of; + } + ComputedType::Function(_) => function = true, + ComputedType::Pack(of) => { + pack = true; + current = of; } _ => {} } + // **The scalar underneath every decoration**, which is the part the fundamental traits are asked about. + let mut base = current; + loop { + match base { + ComputedType::Pointer(to) | ComputedType::Pack(to) => base = to, + ComputedType::Reference { to, .. } => base = to, + ComputedType::Qualified(qualified) => base = &qualified.of, + ComputedType::Array { of, .. } => base = of, + ComputedType::Function(function) => base = &function.returns, + // **C's record tag is transparent to the trait question** — `std::integral` asked the + // scalar under the keyword, which is the name; the tag is `sema::convert`'s evidence, not a shape. + ComputedType::ElaboratedRecord { of, .. } => base = of, + _ => break, + } + } + // **A builtin is its primary; a name with no arguments is a scalar this layer can place.** `size_t`, + // `std::size_t` and `ptrdiff_t` are the standard's names for builtin types; a class template is not. + let scalar = match base { + ComputedType::Primary(primary) => Some(Scalar::Primary(*primary)), + ComputedType::Named(name) => Some(Scalar::Named(name)), + _ => None, + }; + // **A name nothing has bound is not evidence of anything.** The convention that names a template parameter + // is one capital letter (T, U, V) is what separates "a type nobody bound" from "a type the program named" — + // the first is *cannot tell*. A decorated type with an array or function shape is not a bare parameter, which + // is why the convention is asked only when the scalar is the whole type: `T[4]` is an array whatever `T` is. + let a_parameter_by_convention = |name: &str| { + name.len() == 1 && name.chars().all(|character| character.is_ascii_uppercase()) + }; + let unknown = !array + && !function + && !pack + && match base { + ComputedType::Primary(primary) => primary.is_a_placeholder(), + ComputedType::TemplateParameter(_) => true, + ComputedType::Named(name) => a_parameter_by_convention(name), + _ => false, + }; + // The scalar shape, read once, for the traits that are a property of it. + let integral = scalar.is_some_and(Scalar::is_integral) && !array && !function && !pack; + let floating = + scalar.is_some_and(Scalar::is_floating_point) && !array && !function && !pack; + let signed = integral && scalar.is_some_and(|scalar| !scalar.is_unsigned()); + + // The decorators answer for **any** type, known or not: `std::string&` is a reference whichever class + // `string` is. The scalar traits cannot answer for a name this layer cannot place. + match self { + Trait::Reference => return Some(reference), + Trait::Const => return (!unknown).then_some(topmost_const), + Trait::Volatile => return (!unknown).then_some(topmost_volatile), + Trait::Array => return (!unknown).then_some(array), + Trait::Function => return (!unknown).then_some(function), + _ => {} + } if unknown { return None; } Some(match self { - Trait::Integral => integral && !pointers && !reference, - Trait::FloatingPoint => floating && !pointers && !reference, - Trait::Arithmetic => (integral || floating) && !pointers && !reference, - Trait::Pointer => pointers && !reference, - Trait::Void => scalars == "void" && !pointers && !reference, + Trait::Integral => integral && !pointer && !reference, + Trait::FloatingPoint => floating && !pointer && !reference, + Trait::Arithmetic => (integral || floating) && !pointer && !reference, + Trait::Pointer => pointer && !reference, + Trait::Void => { + scalar.is_some_and(Scalar::is_void) && !pointer && !reference && !array && !function + } Trait::Signed => signed, Trait::Unsigned => integral && !signed, // Answered above, before the scalar was needed. @@ -198,305 +235,182 @@ impl Trait { } } -/// **Decide a condition**, with the template parameters bound to the types a call deduced. -/// -/// `bindings` is `[("T", "int")]` for `describe(41)`: the call's argument types are what the template parameter stands -/// for, in order. `None` means *cannot tell* — an unbound parameter, a trait this layer does not know, a clause that is -/// not a condition it reads. -pub fn satisfies(condition: &str, bindings: &[(String, String)]) -> Option { - let condition = condition.trim(); - if condition.is_empty() { - return None; - } +/// **The scalar a decorated type reduces to** — a primary the type layer models, or a name that stands for one +/// (`size_t`, `std::size_t`, `ptrdiff_t`). The trait questions about integrality and sign are a property of the +/// primary, and this is the one place that asks them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Scalar<'a> { + Primary(PrimaryType), + Named(&'a str), +} - // The operators, from weakest to strongest, split at the *top level* so a nested `is_same` is not cut in two. - for operator in ["||", "&&"] { - let parts = top_level_split(condition, operator); - if parts.len() > 1 { - let mut decided = Vec::with_capacity(parts.len()); - for part in parts { - decided.push(satisfies(&part, bindings)?); - } - return Some(if operator == "||" { - decided.iter().any(|one| *one) - } else { - decided.iter().all(|one| *one) - }); +impl Scalar<'_> { + fn is_integral(self) -> bool { + match self { + Scalar::Primary(primary) => primary.is_integral(), + Scalar::Named(name) => matches!(name, "size_t" | "ptrdiff_t" | "std::size_t"), } } - if let Some(rest) = condition.strip_prefix('!') { - return Some(!satisfies(rest, bindings)?); - } - if condition == "true" { - return Some(true); - } - if condition == "false" { - return Some(false); - } - // **`std::is_same`** — the one trait with two arguments, and the one every `!is_same` needs. - if let Some(arguments) = a_trait_call_with_name(condition, "is_same") { - let mut parts = top_level_split(arguments, ",").into_iter(); - let left = substitute(&parts.next()?, bindings); - let right = substitute(&parts.next()?, bindings); - if left.contains('<') || right.contains('<') { - return None; - } - return Some(left.trim() == right.trim()); + fn is_floating_point(self) -> bool { + matches!(self, Scalar::Primary(primary) if primary.is_floating_point()) } - // **`std::is_same`** — the one trait with two arguments, and the one every `!is_same` needs. - if let Some(arguments) = a_trait_call_with_name(condition, "is_same") { - let mut parts = top_level_split(arguments, ",").into_iter(); - let left = substitute(&parts.next()?, bindings); - let right = substitute(&parts.next()?, bindings); - if left.contains('<') || right.contains('<') { - return None; + fn is_unsigned(self) -> bool { + match self { + Scalar::Primary(primary) => primary.is_unsigned(), + Scalar::Named(name) => name.starts_with("unsigned") || name == "uint64_t", } - return Some(left.trim() == right.trim()); } - // **`std::is_integral::value`**, `std::is_integral{}`, `std::is_integral_v` — one trait, three spellings. - let trait_call = a_trait_call(condition)?; - let argument = substitute(trait_call.argument, bindings); - if argument.contains('<') || argument.is_empty() { - return None; + fn is_void(self) -> bool { + matches!(self, Scalar::Primary(PrimaryType::Void)) } - Trait::named(&trait_call.name)?.of(&argument) } -/// **A condition spliced out of a declaration** — the text between `enable_if<` and its closing `>`, or the expression a -/// `requires` clause states. +/// **Decide a condition**, with the template parameters bound to the types a call deduced. /// -/// ```cpp -/// typename std::enable_if::value, std::string>::type describe(T); // the C++11 spelling -/// template requires std::is_integral_v std::string describe(T); // C++20's own -/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -/// ``` +/// `condition` is the typed expression node a caller got from [`the_condition_of_node`] or +/// [`a_requires_clause_node`]. `bindings` is `[("T", int)]` for `describe(41)`: the call's argument types are what +/// the template parameter stands for, in order. `None` means *cannot tell* — an unbound parameter, a trait this +/// layer does not know, a condition that is not one it reads. +pub fn satisfies(condition: &CppSyntaxNode, bindings: &[(SmolStr, ComputedType)]) -> Option { + let mut no_concepts = |_: &str| -> Option<(SmolStr, CppSyntaxNode)> { None }; + satisfies_inside(condition, bindings, &mut no_concepts, 0) +} + +/// **The `enable_if` condition, found through the declaration's typed name nodes.** The condition is the first +/// template argument of `enable_if<…>`/`enable_if_t<…>`, handed over as the typed expression node it was written as. /// -/// `None` when the declaration has no condition at all, which is the ordinary function. A **requires-expression** -/// (`requires { value.size(); }`) is also `None`: it is a block of statements asking whether each one is well formed, not a -/// constant expression this layer can decide, and answering it as if it were would drop the wrong candidate. -pub fn the_condition_of(declaration: &str) -> Option<&str> { - the_enable_if_argument(declaration) +/// No declaration text is scanned: the name is a `CppNameExpr`, its arguments are a `CppTemplateArgList`, and the first +/// argument is the node this returns. An argument that is a pure type (`enable_if`, which is not a condition +/// this layer reads) answers `None` rather than being turned into a spelling and tried. +pub fn the_condition_of_node(declaration: &CppSyntaxNode) -> Option { + let name = declaration.descendants().find_map(|node| { + let name = CppNameExpr::cast(node)?; + // The name's **own last segment**, read from its tokens: `std::enable_if<…>::type` answers `enable_if`, and a + // function merely called `describe` answers nothing. + matches!( + the_name_a_trait_call_writes(&name)?.as_str(), + "enable_if" | "enable_if_t" + ) + .then_some(name) + })?; + let list = name + .syntax() + .descendants() + .find_map(CppTemplateArgList::cast)?; + let first = list.get_args().next()?; + the_condition_in_a_template_argument(&first) } -/// The first argument of the first `enable_if<…>` — the condition, in both `enable_if` and `enable_if_t`. -fn the_enable_if_argument(declaration: &str) -> Option<&str> { - let at = declaration.find("enable_if")?; - let after = &declaration[at + "enable_if".len()..]; - let open = after.find('<')?; - let mut depth = 0isize; - for (index, character) in after[open..].char_indices() { - match character { - '<' => depth += 1, - '>' => { - depth -= 1; - if depth == 0 { - let inside = &after[open + 1..open + index]; - // The first argument is the condition; `enable_if` and `enable_if_t` both put it - // first, and `enable_if` has nothing else. - return Some(inside.split(',').next().unwrap_or_default().trim()); - } - } - _ => {} - } +/// **The condition a template argument writes**, as the typed node the grammar built. +/// +/// A template argument is `TemplateArgument > TypeId > … > NameExpr` when the grammar read it as a type +/// (`enable_if::value, …>`) and `TemplateArgument > InitListExpr` when it read it as a value +/// (`enable_if{}, …>`). The condition is the expression node inside it. An argument with no +/// expression — `enable_if` — states no condition this layer reads, and answers `None`. +fn the_condition_in_a_template_argument(argument: &CppTemplateArg) -> Option { + if let Some(expression) = argument.get_expr() { + return Some(expression.syntax().clone()); } - None + let type_id = argument.get_type_id()?; + type_id + .syntax() + .descendants() + .find(|node| CppExpr::cast(node.clone()).is_some()) } -/// **The constraint a `RequiresClause` node states** — the node's own text without its keyword. +/// **The condition a `RequiresClause` states**, as the typed expression the grammar built. /// /// ```cpp /// template requires std::is_integral_v /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /// ``` /// -/// Read from the **node**, not from the declaration's text: the clause and the declaration that follows it are separated -/// by nothing but a newline, so a text scan cannot tell `requires is_integral_v` from `requires is_integral_v -/// std::string describe(T)`. The grammar knows, and this is that knowledge. -/// -/// `None` when the node is a **requires-expression** (`requires { … }`), which asks whether statements compile rather than -/// stating a condition this layer could decide. -pub fn a_requires_clause(clause: &str) -> Option<&str> { - let text = clause.trim_start(); - let rest = text.strip_prefix("requires")?.trim_start(); - if rest.starts_with('{') { - return None; - } - (!rest.is_empty()).then_some(rest) -} - -/// The argument list of `[std::]`name`<…>`, when the condition *is* that trait. -fn a_trait_call_with_name<'a>(condition: &'a str, wanted: &str) -> Option<&'a str> { - let call = a_trait_call(condition)?; - (call.name == wanted).then_some(call.argument) -} -struct TraitCall<'a> { - name: String, - argument: &'a str, -} - -/// `[std::]is_X[::value | {} | _v]` — the three spellings, and nothing else. -fn a_trait_call(condition: &str) -> Option> { - let condition = condition.trim(); - let condition = condition.strip_suffix("::value").unwrap_or(condition); - let condition = condition.strip_suffix("{}").unwrap_or(condition); - let condition = condition.strip_suffix("()").unwrap_or(condition); - let condition = condition.trim(); - let open = condition.find('<')?; - let name = condition[..open].trim(); - let name = name.strip_suffix("_v").unwrap_or(name); - let name = name.rsplit("::").next().unwrap_or(name).trim(); - let close = condition.rfind('>')?; - Some(TraitCall { - name: name.to_string(), - argument: condition[open + 1..close].trim(), - }) -} - -/// Replace a bound template parameter with its type, as a **word** — `std::is_integral_v` with `T = double` answers -/// `std::is_integral_v`. +/// Read from the **node**, not from the declaration's text: the clause and the declaration that follows it are +/// separated by nothing but a newline, so a text scan cannot tell `requires is_integral_v` from `requires +/// is_integral_v std::string describe(T)`. The grammar knows, and this is that knowledge. /// -/// The word boundary is the whole of it: the first version split the spelling into words, joined them with a separator, -/// replaced, and joined them again **without restoring the punctuation** — so `std::is_integral_v` became -/// `stdis_integral_vdouble`, and a condition that named a concept answered "cannot tell" for a reason that had nothing to do -/// with concepts. -fn substitute(spelling: &str, bindings: &[(String, String)]) -> String { - let mut out = String::with_capacity(spelling.len()); - let mut at = 0usize; - let characters: Vec<(usize, char)> = spelling.char_indices().collect(); - while at < characters.len() { - let (start, character) = characters[at]; - if !character.is_alphanumeric() && character != '_' { - out.push(character); - at += 1; - continue; - } - let mut end = at; - while end < characters.len() - && (characters[end].1.is_alphanumeric() || characters[end].1 == '_') - { - end += 1; - } - let word = &spelling[start - ..characters - .get(end) - .map_or(spelling.len(), |(offset, _)| *offset)]; - match bindings.iter().find(|(parameter, _)| parameter == word) { - Some((_, concrete)) => out.push_str(concrete), - None => out.push_str(word), - } - at = end; - } - out -} -/// Split at `operator` outside any angle brackets or parentheses. -fn top_level_split(text: &str, operator: &str) -> Vec { - let mut parts = Vec::new(); - let mut depth = 0isize; - let mut start = 0usize; - let bytes = text.as_bytes(); - let mut at = 0usize; - while at < bytes.len() { - match bytes[at] as char { - '<' | '(' => depth += 1, - '>' | ')' => depth -= 1, - _ => {} - } - if depth == 0 && text[at..].starts_with(operator) { - parts.push(text[start..at].trim().to_string()); - at += operator.len(); - start = at; - continue; - } - at += 1; - } - parts.push(text[start..].trim().to_string()); - parts +/// `None` when the clause holds a **requires-expression** (`requires { … }`), which asks whether statements compile +/// rather than stating a condition this layer could decide. +pub fn a_requires_clause_node(clause: &CppRequiresClause) -> Option { + let condition = clause.get_condition()?; + (!matches!(condition, CppExpr::RequiresExpr(_))).then(|| condition.syntax().clone()) } /// **The concept a declaration's template parameter names**, if it names one. /// /// ```cpp /// template std::string describe(T); // `integral` here -/// template requires integral … // and here /// ``` /// -/// A constraint that is a *name* has no expression in the declaration to evaluate, so this answers the name and the caller -/// finds the definition. `None` for the ordinary `typename T` / `class T` / `auto`, which name no concept. -pub fn a_concept_name(declaration: &str) -> Option { - // The `requires NAME<…>` form first: the keyword makes the name unambiguous. - if let Some(at) = declaration.find("requires") { - let after = declaration[at + "requires".len()..].trim_start(); - if let Some(open) = after.find('<') { - let name = after[..open].trim(); - if is_a_name(name) { - return Some(name.to_string()); - } - } - } - - // **The template parameter list** — `template `: a parameter whose first word is a name and whose second - // is the parameter it constrains. `typename T`, `class U` and `auto` are the ones that are *not* this. - let at = declaration.find("template")?; - let after = &declaration[at + "template".len()..]; - let open = after.find('<')?; - let mut depth = 0isize; - let mut close = None; - for (index, character) in after[open..].char_indices() { - match character { - '<' => depth += 1, - '>' => { - depth -= 1; - if depth == 0 { - close = Some(open + index); - break; - } - } - _ => {} +/// A constraint that is a *name* has no expression in the declaration to evaluate, so this answers the name and the +/// caller finds the definition. `None` for the ordinary `typename T` / `class T` / `auto`, which name no concept. +/// +/// The parameter list is read from the `TemplateParameterList` node, and the concept is the **type name written before +/// the parameter's own name** — `integral` in `template `. The grammar may put the declared name in a +/// declarator of its own (`TemplateParameter > [DeclSpecifierSeq "integral", Declarator "T"]`) or in the specifier +/// sequence beside the concept (`DeclSpecifierSeq > [NamedType "integral", NamedType "T"]`), so the name that is not +/// the parameter's is the answer. Nothing is split, and a parameter whose specifier is a builtin (`int N`), a scoped +/// name (`std::size_t... I`) or a placeholder (`auto`) names no concept and is skipped. +pub fn a_concept_name(declaration: &CppSyntaxNode) -> Option { + let template = declaration + .children() + .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateDecl)?; + let list = template.children().find_map(CppTemplateParamList::cast)?; + for parameter in list.get_params() { + // `typename T`, `class T`, `concept C`, and the template-template parameters name no concept constraint. + if parameter.is_type_param() { + continue; } - } - let inside = &after[open + 1..close?]; - for parameter in inside.split(',') { - let words: Vec<&str> = parameter.split_whitespace().collect(); - let [first, second, ..] = words.as_slice() else { + let Some(specifiers) = parameter.get_decl_specifiers() else { continue; }; - if matches!(*first, "typename" | "class" | "auto" | "template") - || first.contains('=') - || !is_a_name(first) - || !is_a_name(second) - { - continue; + let declared = parameter + .get_name() + .map(|name| SmolStr::new(name.get_name_text())); + for child in specifiers.syntax().children() { + // The type the parameter is written with — `integral` in `integral T`. A plain name is a `NamedType` and a + // template-id a `TemplateType`, and the name inside either is what the concept is called. + if !matches!( + CppSyntaxKind::from(child.kind()), + CppSyntaxKind::NamedType | CppSyntaxKind::TemplateType + ) { + continue; + } + let Some(name) = child.children().find_map(CppNameExpr::cast) else { + continue; + }; + let written = name.get_qualified_name(); + // The parameter's own name can sit in this same sequence — see the two shapes above. + if declared.as_deref() == Some(written.as_str()) { + continue; + } + if matches!(written.as_str(), "auto" | "decltype(auto)" | "decltype") + || !is_a_name(&written) + { + continue; + } + return Some(written); } - return Some((*first).to_string()); } None } -/// An identifier as this layer spells one: letters, digits and `_`, starting with a letter or `_`. -fn is_a_name(word: &str) -> bool { - !word.is_empty() - && word - .chars() - .next() - .is_some_and(|first| first.is_alphabetic() || first == '_') - && word - .chars() - .all(|character| character.is_alphanumeric() || character == '_') -} - /// **Decide a condition, expanding the concepts it names** — [`satisfies`] with a way to look a concept up. /// -/// `expand` answers `(parameter, body)` for a concept name: `signed_integral` → `("T", "integral && is_signed_v")`. -/// The body is then evaluated with the parameter bound to the argument the concept was applied to, and a body that names -/// another concept recurses the same way. The depth is bounded because a concept may name itself (`concept X = X`), and -/// a walk that trusted the text would never end. +/// `expand` answers `(parameter, body)` for a concept name: `signed_integral` → `("T", && is_signed_v`>)`. The body is evaluated with the parameter bound to the argument the concept was +/// applied to, and a body that names another concept recurses the same way. Nothing is substituted into a spelling: +/// the binding is a [`ComputedType`], the same currency [`satisfies`] compares in. +/// +/// The depth is bounded because a concept may name itself (`concept X = X`), and a walk that trusted the text would +/// never end. pub fn satisfies_with( - condition: &str, - bindings: &[(String, String)], - expand: &mut dyn FnMut(&str) -> Option<(String, String)>, + condition: &CppSyntaxNode, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, ) -> Option { satisfies_inside(condition, bindings, expand, 0) } @@ -506,74 +420,242 @@ pub fn satisfies_with( const MAX_CONCEPT_DEPTH: usize = 8; fn satisfies_inside( - condition: &str, - bindings: &[(String, String)], - expand: &mut dyn FnMut(&str) -> Option<(String, String)>, + condition: &CppSyntaxNode, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, depth: usize, ) -> Option { - let condition = condition.trim(); - if condition.is_empty() { - return None; + match CppExpr::cast(condition.clone())? { + CppExpr::BinaryExpr(binary) => a_binary_answer(&binary, bindings, expand, depth), + CppExpr::UnaryExpr(unary) => a_unary_answer(&unary, bindings, expand, depth), + CppExpr::ParenExpr(paren) => a_parenthesised_answer(&paren, bindings, expand, depth), + CppExpr::LiteralExpr(literal) => a_literal_answer(&literal), + CppExpr::NameExpr(name) => a_name_answer(name, bindings, expand, depth), + CppExpr::CallExpr(call) => a_called_name_answer(&call, bindings, expand, depth), + CppExpr::InitListExpr(list) => a_braced_name_answer(&list, bindings, expand, depth), + _ => None, } +} - // The operators, from weakest to strongest, split at the *top level* so a nested `is_same` is not cut in two. - for operator in ["||", "&&"] { - let parts = top_level_split(condition, operator); - if parts.len() > 1 { - let mut decided = Vec::with_capacity(parts.len()); - for part in parts { - let verdict = satisfies_inside(&part, bindings, expand, depth); - decided.push(verdict?); - } - return Some(if operator == "||" { - decided.iter().any(|one| *one) - } else { - decided.iter().all(|one| *one) - }); - } +/// **`a && b`, `a || b`** — the operator is the node's own token, so nothing is split and no precedence is guessed. +/// +/// Both operands are decided, even when the left one already fixes the answer, because a verdict of `None` on either +/// side is the caller's signal to keep the candidate: `false && ` is not `false` to a caller who would +/// delete a declaration on it. +fn a_binary_answer( + binary: &CppBinaryExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + let operator = CppTokenKind::from(binary.get_operator_token()?.syntax().kind()); + let (left, right) = match operator { + CppTokenKind::LogicalAnd => (binary.get_lhs()?, binary.get_rhs()?), + CppTokenKind::LogicalOr => (binary.get_lhs()?, binary.get_rhs()?), + _ => return None, + }; + let left = satisfies_inside(left.syntax(), bindings, expand, depth)?; + let right = satisfies_inside(right.syntax(), bindings, expand, depth)?; + Some(match operator { + CppTokenKind::LogicalOr => left || right, + _ => left && right, + }) +} + +/// **`!a`** — the prefix `!` only; a postfix operator is not a condition. +fn a_unary_answer( + unary: &CppUnaryExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + if CppTokenKind::from(unary.get_operator_token()?.syntax().kind()) != CppTokenKind::LogicalNot + || !unary.is_prefix() + { + return None; } - if let Some(rest) = condition.strip_prefix('!') { - return Some(!satisfies_inside(rest, bindings, expand, depth)?); + Some(!satisfies_inside( + unary.get_operand()?.syntax(), + bindings, + expand, + depth, + )?) +} + +/// **`(a)`** — the parentheses are the grammar's, so their only meaning here is the expression inside. +fn a_parenthesised_answer( + paren: &CppParenExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + satisfies_inside(paren.get_expr()?.syntax(), bindings, expand, depth) +} + +/// **`true` / `false`** — the literal's own token kind, not its spelling. +fn a_literal_answer(literal: &CppLiteralExpr) -> Option { + match CppTokenKind::from(literal.get_literal_token()?.syntax().kind()) { + CppTokenKind::TrueKeyword => Some(true), + CppTokenKind::FalseKeyword => Some(false), + _ => None, } - if condition == "true" { - return Some(true); +} + +/// **`[std::]trait`** — a name whose template arguments are the trait's. +fn a_name_answer( + name: CppNameExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + let call = a_trait_call(&name)?; + a_trait_calls_answer(&call, bindings, expand, depth) +} + +/// **`[std::]trait()`** — the same call, written with an empty argument list. +fn a_called_name_answer( + call: &CppCallExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + if !call.get_args().is_empty() { + return None; } - if condition == "false" { - return Some(false); + let CppExpr::NameExpr(name) = call.get_callee()? else { + return None; + }; + let call = a_trait_call(&name)?; + a_trait_calls_answer(&call, bindings, expand, depth) +} + +/// **`[std::]trait{}`** — the braced spelling of the answer; only the empty braces mean the trait's value. +fn a_braced_name_answer( + list: &CppInitListExpr, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + let name = list.get_constructed_type()?; + // The braced list is a child node of the construction (`InitListExpr > [NameExpr, InitListExpr "{}"]`), and a + // non-empty one is a value being built rather than the trait's answer. + let braces = list.syntax().children().find_map(CppInitListExpr::cast)?; + if !braces.is_empty() || braces.get_designators().next().is_some() { + return None; } + let call = a_trait_call(&name)?; + a_trait_calls_answer(&call, bindings, expand, depth) +} - // **`std::is_same`** — the one trait with two arguments, and the one every `!is_same` needs. - if let Some(arguments) = a_trait_call_with_name(condition, "is_same") { - let mut parts = top_level_split(arguments, ",").into_iter(); - let left = substitute(&parts.next()?, bindings); - let right = substitute(&parts.next()?, bindings); - if left.contains('<') || right.contains('<') { - return None; +/// **One trait or concept application** — `[std::]name`, however its answer was spelled. +struct TraitCall { + /// The last `::` segment of the name, without the `_v` suffix: `std::is_integral_v` answers `is_integral`. + name: SmolStr, + /// The template arguments as the typed nodes the grammar built. + arguments: Vec, +} + +/// The trait a name expression applies, when it applies one. +fn a_trait_call(name: &CppNameExpr) -> Option { + let arguments = name.get_template_arg_lists().next()?.get_args().collect(); + Some(TraitCall { + name: the_name_a_trait_call_writes(name)?, + arguments, + }) +} + +/// **The trait's own name** — the last `::` segment before the template argument list, without the `_v` suffix. +/// +/// Read from the name node's **direct tokens**, not from its text: the argument list is a child node, and the tokens +/// after it (`::value`) belong to the answer's spelling rather than to the trait's name. `std::is_integral::value` +/// therefore answers `is_integral`, `std::is_integral_v` answers `is_integral`, and `is_same_v` answers +/// `is_same`. +fn the_name_a_trait_call_writes(name: &CppNameExpr) -> Option { + let mut last: Option = None; + for element in name.syntax().children_with_tokens() { + match element { + CppSyntaxElement::Node(node) => { + if CppTemplateArgList::can_cast(node.kind().into()) { + break; + } + } + CppSyntaxElement::Token(token) => { + if CppTokenKind::from(token.kind()) == CppTokenKind::Identifier { + last = Some(SmolStr::new(token.text())); + } + } } - return Some(left.trim() == right.trim()); } + let last = last?; + Some(SmolStr::new( + last.strip_suffix("_v").unwrap_or(last.as_str()), + )) +} - // **`std::is_integral::value`**, `{}`, `_v`, `()` — one trait, four spellings. - let trait_call = a_trait_call(condition)?; - let argument = substitute(trait_call.argument, bindings); - if argument.contains('<') || argument.is_empty() { +/// **The answer one trait or concept application gives**, with its argument read as a structured type. +fn a_trait_calls_answer( + call: &TraitCall, + bindings: &[(SmolStr, ComputedType)], + expand: &mut dyn FnMut(&str) -> Option<(SmolStr, CppSyntaxNode)>, + depth: usize, +) -> Option { + // **`std::is_same`** — the one trait with two arguments, and the one every `!is_same` needs. Both + // arguments are read as **structured types** and compared by the type layer's own equality rule, which is the + // canonical spelling (see the `sema::types` module: two spellings that mean one type are two answers here). That + // is one conversion per argument and not a parse of the condition — the comparison is between the two types the + // arguments denote, after the caller's bindings have been applied structurally. + if call.name == "is_same" { + let left = the_type_of_a_trait_argument(call.arguments.first()?, bindings)?; + let right = the_type_of_a_trait_argument(call.arguments.get(1)?, bindings)?; + return Some(left.to_string() == right.to_string()); + } + // Every other trait this layer knows takes exactly one type; a call with another arity is not one it reads. + if call.arguments.len() != 1 { return None; } - if let Some(trait_) = Trait::named(&trait_call.name) { + let argument = the_type_of_a_trait_argument(&call.arguments[0], bindings)?; + if let Some(trait_) = Trait::named(&call.name) { return trait_.of(&argument); } - // **A concept the caller knows** — `integral` inside another concept's body. Expanded with its own parameter bound - // to this argument, then decided. + // **A concept the caller knows** — `integral` inside another concept's body. Expanded with its own parameter + // bound to this argument's type, then decided. if depth >= MAX_CONCEPT_DEPTH { return None; } - let (parameter, body) = match expand(&trait_call.name) { - Some(found) => found, - None => { - return None; - } - }; - let substituted = substitute(&body, &[(parameter, argument)]); - satisfies_inside(&substituted, bindings, expand, depth + 1) + let (parameter, body) = expand(&call.name)?; + let mut extended = Vec::with_capacity(bindings.len() + 1); + extended.push((parameter, argument)); + extended.extend_from_slice(bindings); + satisfies_inside(&body, &extended, expand, depth + 1) +} + +/// **The type a trait argument writes**, with the condition's template parameters replaced by what the caller bound +/// them to. +/// +/// The argument is a template argument node (`TemplateArgument > TypeId > …`), read with the type layer's own reader. +/// The binding is applied structurally: a name the caller bound is marked as a template parameter +/// ([`with_template_parameters`]) and [`ComputedType::substituted`] replaces it — no spelling is parsed and no store +/// is touched. +fn the_type_of_a_trait_argument( + argument: &CppTemplateArg, + bindings: &[(SmolStr, ComputedType)], +) -> Option { + let type_id = argument.get_type_id()?; + let written = type_of_a_type_id(type_id.syntax())?; + let names: Vec<&SmolStr> = bindings.iter().map(|(name, _)| name).collect(); + let marked = with_template_parameters(written, &names); + Some(marked.substituted_by_bindings(bindings)) +} + +/// An identifier as this layer spells one: letters, digits and `_`, starting with a letter or `_`. +fn is_a_name(word: &str) -> bool { + !word.is_empty() + && word + .chars() + .next() + .is_some_and(|first| first.is_alphabetic() || first == '_') + && word + .chars() + .all(|character| character.is_alphanumeric() || character == '_') } diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index 0ca22421..63678eb8 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -4,13 +4,21 @@ //! themselves, which is how one of them lost a step without the others noticing. That work belongs //! here, done once. //! +//! **The question is asked of two parsed types** ([`conversion_to`]). The declaration layers record spellings — a +//! summary's `parameter_list`, a return type written in a header — so each caller parses its target once at its own +//! boundary and passes the [`ComputedType`]; this module never parses the same spelling again. C's tag +//! (`struct point`) is not an exception: the type carries it as [`ComputedType::ElaboratedRecord`] (see +//! [`RecordTag`]), so the rule below reads the type and no caller hands over a spelling. +//! //! # The one rule that must not be lost //! //! `Unknown` is a real answer, and a check that reports on it is a check a reader learns to ignore. A class nobody has read, //! a template parameter, a dependent type — all of those are `Unknown`, and all of them are silent. use crate::Known; -use crate::sema; +use crate::index; +use crate::index::types::ComputedType; +use crate::sema::types::RecordTag; use cpp_parser::features; /// **What it takes to use a value of one type where another is expected.** @@ -36,63 +44,65 @@ impl Conversion { } /// **Is this a pointer, through any qualifiers?** — `const char*`, `T* const`, `T*`. -fn a_pointer(type_of: &sema::types::Type) -> bool { +fn a_pointer(type_of: &ComputedType) -> bool { match type_of { - sema::types::Type::Pointer { .. } => true, - sema::types::Type::Qualified { of, .. } => a_pointer(of), + ComputedType::Pointer(_) => true, + ComputedType::Qualified(qualified) => a_pointer(&qualified.of), // An array decays to a pointer in an assignment to a scalar; `bool b = array;` is the same conversion. - sema::types::Type::Array { .. } => true, + ComputedType::Array { .. } => true, _ => false, } } -/// **A written parameter without its reference and top-level `const`** — `const std::string&` → `std::string`. +/// **The type a reference or a qualifier is about** — `const std::string&` → `std::string`. /// -/// `Type::class_name()` answers `None` for `Reference { to: Named(..) }`, which is how the class question was never asked at -/// all: the parameter parsed to a reference, the class name came back empty, and the index was skipped. Every caller that -/// wants to ask about the class behind a parameter needs this first, so it lives here rather than in each check. -pub fn strip_references(parameter: &str) -> &str { - let mut written = parameter.trim(); - while let Some(rest) = written.strip_prefix("const ") { - written = rest.trim(); - } - while let Some(rest) = written.strip_suffix('&') { - written = rest.trim(); +/// This is the structural form of the old `strip_references` string helper. A reference binds to its referent and a +/// qualifier belongs to the type it was written on, so both are transparent to the class question: `const Widget&` +/// asks about `Widget`, and `Widget*` deliberately keeps its pointer (a pointer is a different question from a +/// reference to the same type, and `class_name()` answers `None` for it). +fn the_referent(type_of: &ComputedType) -> &ComputedType { + match type_of { + ComputedType::Reference { to, .. } => the_referent(to), + ComputedType::Qualified(qualified) => the_referent(&qualified.of), + other => other, } - written } -/// **Can a value of `from` be used where the parameter written `written` is expected?** +/// **Can a value of `from` be used where the parsed `target` is expected?** /// -/// `written` is the **spelling** the declaring file wrote, not a parsed type: the class question needs the name under the -/// reference, and a pointer is a different question from a reference to the same type. +/// `target` is a [`ComputedType`], not a spelling: nothing in this function parses a string, and the +/// class question reads the type's structure ([`the_referent`]) rather than trimming a written form. A caller that +/// holds only a spelling parses it **once, at its own boundary**, and passes the parsed value here. +/// +/// **C's tag is part of the type.** `struct point *` is a [`ComputedType::ElaboratedRecord`] reached through a pointer, +/// which the declaration reader and `parse_type_spelling` produce from the written keyword; +/// [`a_tagged_record_in`] finds it structurally. A `Named` type cannot say whether its name was tagged — +/// `typedef int point;` makes the tag the only evidence that the name is a record — so the keyword is carried on the +/// type rather than read from a spelling beside it. /// /// `family` is the language **this file** is compiled as, which the checks know per file — a project mixes C and C++, /// and a header's language is the language of the source that compiles it (see /// [`cpp_toolchain::include::config::CompilerConfig::language_for`]). `None` is "not told", and it takes the same /// path as C++: only what is certain in both languages is refused. /// -/// `is_a_record` answers "is this name a struct/class this project declares?", and it is the second half of the C -/// rule below: **in C a record is nobody else's type** — there is no inheritance, no converting constructor and no -/// overload, so `struct first` and `struct second` are two types and `struct point *` is not an `int *`. The -/// question goes to the index because a *name* is not a type: `typedef int point;` makes the two above the same, -/// so a refusal needs evidence rather than a difference of spelling. -pub fn conversion( - from: &sema::types::Type, - written: &str, +/// `answer_the_class_question` answers "could a constructor of this class build the value?", and it is the second +/// half of the C rule below: **in C a record is nobody else's type** — there is no inheritance, no converting +/// constructor and no overload, so `struct first` and `struct second` are two types and `struct point *` is not an +/// `int *`. The question goes to the index because a *name* is not a type: `typedef int point;` makes the two above +/// the same, so a refusal needs evidence rather than a difference of spelling. +pub fn conversion_to( + from: &ComputedType, + target: &ComputedType, family: Option, answer_the_class_question: impl FnOnce(&str) -> Option, ) -> Conversion { - let target = sema::types::parse_type_spelling(written); - // **A pointer converts to `bool`/`_Bool`.** The relation is about the classes and arithmetic the type algebra // knows; a scalar-to-bool conversion is a standard conversion in both languages, and `const char *defs[…]; // bool has = defs[i];` is ordinary C (neovim's `tui.c`). Reporting it refused was a false positive on every // capability lookup of that shape. if matches!( - &target, - sema::types::Type::Builtin { spelling } - if spelling == "bool" || spelling == "_Bool" + target, + ComputedType::Primary(index::types::PrimaryType::Bool) ) && a_pointer(from) { return Conversion::Implicit; @@ -100,42 +110,50 @@ pub fn conversion( // **A record written with its tag is a type of its own, in C.** `struct point *` and `struct first` say "a // record" in the language's own syntax, and C has no inheritance, no converting constructor and no overload: - // what is not that record does not convert. The evidence is the *spelling*, because a name alone is not a type - // — `typedef int point;` makes a name a builtin in disguise, and the index cannot tell the two apart (a summary - // records both as `DeclKind::Type`). A parameter written `point *` after such a typedef therefore stays - // `Unknown`, which is the safe direction. + // what is not that record does not convert. The evidence is the **tag on the target type** + // ([`ComputedType::ElaboratedRecord`]), not a spelling beside it: a name alone is not a type — `typedef int point;` + // makes a name a builtin in disguise, and the index cannot tell the two apart (a summary records both as + // `DeclKind::Type`). A parameter written `point *` after such a typedef therefore stays `Unknown`, which is the + // safe direction, while a `struct point *` parameter is decided from its structure. // // A `void *` is exempt on the source side: C converts it to any object pointer (`int *p = malloc(n)`), and // refusing that would be a false positive on the commonest allocation in the language. if family == Some(features::Family::C) - && let Some(record) = a_tagged_record(written) - && !the_value_is_that_record(from, &record) + && let Some((tag, record)) = a_tagged_record_in(target) + && !the_value_is_that_record(from, tag, record) { return Conversion::Refused; } // **The relation first.** It is exact for arithmetic, pointers and plain names, and it is the only half that knows about // `const` and references at all. - match from.convertible_to(&target) { + match from.convertible_to(target) { Known::Yes(()) => return Conversion::Implicit, Known::No => return Conversion::Refused, Known::Unknown(_) => {} } // **The class case**, which the relation cannot answer: it lives in the type algebra and never sees a constructor. - let bare = sema::types::parse_type_spelling(strip_references(written)); - let Some(class) = bare.class_name().filter(|class| !class.is_empty()) else { + let bare = the_referent(target); + // **A template parameter is not a class to ask about.** `ComputedType::TemplateParameter` is the structural answer: the + // declaration's own template parameter list said so. `template T value_or(_Ty2&&)` — the + // standard library's own spelling — names a type that the *call* decides, so there is nothing to check an + // argument against. Measured on a C++ project: `number.value_or(0)` reported *"this passes `0` where `_Ty2&&` + // is declared for `value_or`"*, and the class question below answered `Some(false)` for `_Ty2` — a name no file + // declares — which turned "cannot tell" into a refusal. + if matches!(bare, ComputedType::TemplateParameter(_)) { + return Conversion::Unknown; + } + let Some(class) = bare.class_name() else { return Conversion::Unknown; }; - // **A parameter written as a *template parameter* is not a class to ask about.** `template T - // value_or(_Ty2&&)` — the standard library's own spelling — names a type that the *call* decides, so there is nothing - // to check an argument against. Measured on a C++ project: `number.value_or(0)` reported *"this passes `0` where - // `_Ty2&&` is declared for `value_or`"*, and the class question below answered `Some(false)` for `_Ty2` — a name no - // file declares — which turned "cannot tell" into a refusal. - // - // The convention is what makes this readable without a symbol table: one capital letter (`T`, `U`, `V`), or the - // library's underscore-prefixed form (`_Ty2`, `_Up`, `_Elem`). A program's own class is spelled otherwise, and answering - // `Unknown` for one of these costs a diagnostic rather than producing a false one. + // **A `Named` that merely looks like a template parameter keeps the convention.** The type store does not carry + // the template parameter list at this boundary, so a name spelled the way the standard libraries spell their + // parameters — one capital letter (`T`, `U`, `V`), or the underscore-prefixed form (`_Ty2`, `_Up`, `_Elem`) — is + // read as one. This is a **name check on [`ComputedType::class_name`](ComputedType::class_name)**, never a type + // parse: the spelling was parsed once at the boundary, and what is left here is the class name a `Named` carries. + // A program's own class is spelled otherwise, and answering `Unknown` for one of these costs a diagnostic rather + // than producing a false one. if names_a_template_parameter(class) { return Conversion::Unknown; } @@ -146,21 +164,33 @@ pub fn conversion( } } -/// **The record a spelling writes with its tag** — `struct point *` and `union value` answer the name; everything -/// else answers `None`. +/// **The C record a type was written with its tag** — `struct point *` and `union value` answer the keyword and the +/// name; a type written without one answers `None`. +/// +/// The evidence is **on the type** ([`ComputedType::ElaboratedRecord`]), which the declaration reader and +/// `parse_type_spelling` produce from the written keyword and which a fact's `ComputedType` keeps. No caller hands +/// this function a spelling, and nothing here scans one: a type that crossed a fact boundary still carries its tag. +/// +/// The whole type is searched rather than only its outermost operator, because C's rule is about what the +/// declaration named: `struct point *` is a pointer *to* the record, and `struct point[4]` an array of it. /// -/// C's own syntax: `struct`/`union` before a name is a tag, and no typedef can write one. `enum` is deliberately not -/// here — an enumeration *is* an arithmetic type in C, and `enum colour c = 3;` is ordinary code. -fn a_tagged_record(written: &str) -> Option { - let mut words = written - .split(|character: char| !(character.is_alphanumeric() || character == '_')) - .filter(|word| !word.is_empty()); - while let Some(word) = words.next() { - if matches!(word, "struct" | "union") { - return words.next().map(str::to_string); +/// `enum` is deliberately not here — an enumeration *is* an arithmetic type in C, and `enum colour c = 3;` is +/// ordinary code. See [`RecordTag`]. +fn a_tagged_record_in(type_of: &ComputedType) -> Option<(RecordTag, &str)> { + match type_of { + ComputedType::ElaboratedRecord { tag, of } => of.class_name().map(|name| (*tag, name)), + ComputedType::Pointer(to) + | ComputedType::Reference { to, .. } + | ComputedType::Pack(to) + | ComputedType::Array { of: to, .. } => a_tagged_record_in(to), + ComputedType::Qualified(qualified) => a_tagged_record_in(&qualified.of), + ComputedType::Function(function) => a_tagged_record_in(&function.returns) + .or_else(|| function.parameters.iter().find_map(a_tagged_record_in)), + ComputedType::Generic(generic) => generic.arguments.iter().find_map(a_tagged_record_in), + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + None } } - None } /// **Is this value that record?** — through any qualifiers, pointers and array bounds, because `struct point **` and @@ -168,31 +198,50 @@ fn a_tagged_record(written: &str) -> Option { /// /// A `void` pointee answers `true`: C converts `void *` to any object pointer, so `struct point *p = malloc(n);` is /// correct and the tag rule must not report it. -fn the_value_is_that_record(type_of: &sema::types::Type, record: &str) -> bool { +/// +/// An **unelaborated** name that matches answers `true` as well, and that is the safe direction rather than a +/// guess: a source declaration may have written the same record without its tag (`typedef struct point point;` then +/// `point *p`), so a refusal needs evidence that the value is *not* the record. An elaborated name on the source +/// side **is** evidence, so the keyword it wrote has to agree — `struct point` is not a `union point`. +fn the_value_is_that_record(type_of: &ComputedType, tag: RecordTag, record: &str) -> bool { match type_of { - sema::types::Type::Qualified { of, .. } => the_value_is_that_record(of, record), - sema::types::Type::Named { name, .. } => { - name == record || name.rsplit("::").next() == Some(record) - } - sema::types::Type::Pointer { to } => { - matches!(&**to, sema::types::Type::Builtin { spelling } if spelling == "void") - || the_value_is_that_record(to, record) + ComputedType::Qualified(qualified) => the_value_is_that_record(&qualified.of, tag, record), + ComputedType::ElaboratedRecord { tag: written, of } => { + *written == tag + && of + .class_name() + .is_some_and(|name| names_the_record(name, record)) } - sema::types::Type::Array { of, .. } => the_value_is_that_record(of, record), + ComputedType::Named(name) => names_the_record(name, record), + ComputedType::Generic(generic) => names_the_record(&generic.name, record), + ComputedType::Pointer(to) => to.is_void() || the_value_is_that_record(to, tag, record), + ComputedType::Array { of, .. } => the_value_is_that_record(of, tag, record), _ => false, } } -/// Is this spelling the convention for a template parameter — `T`, `Ts`, `_Ty2`, `_Up`?/// **Is this spelling a template parameter, as a check sees one?** — the class rule applied to a whole type. + +/// Is this name the record a tag names? — exactly, or as the last segment of a qualified spelling. +fn names_the_record(name: &str, record: &str) -> bool { + name == record || name.rsplit("::").next() == Some(record) +} + +/// **Is this type a template parameter, as a check sees one?** — the structural answer plus the naming convention. +/// +/// `_Tp&&` and `const _U&` are the same question as `_Tp`, and a check that asks it of a *type* peels the operators +/// first: a parameter is never a reference or a pointer, so anything wrapped around one is the same parameter. /// -/// `_Tp&&` and `const _U&` are the same question as `_Tp`, and a check that asks it of a *type* rather than of a -/// class has to strip the operators first: a parameter is never a reference or a pointer, and the spelling around it -/// is what the drop is. -pub(crate) fn names_a_template_parameter_for_a_check(spelled: &str) -> bool { - let bare = spelled - .trim() - .trim_start_matches("const ") - .trim_end_matches(['&', '*', ' ']); - names_a_template_parameter(bare) +/// [`ComputedType::TemplateParameter`] is the structural answer — the declaration's own +/// parameter list said so. A `Named` that is spelled the convention's way (`T`, `_Ty2`) is still recognised by its +/// **class name**, which is a name check and not a type parse; see [`conversion_to`] for why that convention is kept. +pub(crate) fn names_a_template_parameter_for_a_check(type_of: &ComputedType) -> bool { + match type_of { + ComputedType::TemplateParameter(_) => true, + ComputedType::Pointer(to) | ComputedType::Reference { to, .. } => { + names_a_template_parameter_for_a_check(to) + } + ComputedType::Qualified(qualified) => names_a_template_parameter_for_a_check(&qualified.of), + other => other.class_name().is_some_and(names_a_template_parameter), + } } fn names_a_template_parameter(class: &str) -> bool { diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 421bc435..94789ccd 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -28,14 +28,17 @@ //! directives, keeping a stack of the regions currently open. The result is the same answer for a fraction of //! the work, and it is the reason this module rather than `summary` owns the walk. +use crate::ConstraintFact; use crate::DeclModifiers; use crate::Name; +use crate::index; +use crate::index::types::ComputedType; use crate::scopes; use crate::sema; +use crate::sema::types::TypeSubstitutions; use crate::summary; use crate::token; use cpp_parser::CppBinaryExpr; -use cpp_parser::CppInitializer; use cpp_parser::CppParam; use cpp_parser::CppParamList; use cpp_parser::CppPreprocessorDirective; @@ -52,6 +55,7 @@ use cpp_parser::typed_ancestors_until; use cpp_parser::typed_children; use cpp_parser::typed_descendants; use cpp_parser::typed_previous_sibling; +use cpp_parser::{CppInitListExpr, CppInitializer}; use smol_str::SmolStr; use std::collections::{HashMap, HashSet}; @@ -59,8 +63,8 @@ use crate::preprocess::FilePreprocessing; use crate::preprocess::directive::{Directive, DirectiveKind, SpannedDirective}; use crate::sema::symbol::{Binding, BindingKind, ScopeId, ScopeKind, ScopeTree}; use crate::summary::{ - Access, ConditionalRegion, DeclFact, DeclKind, FactGuard, GuardBranch, MacroFact, MacroKind, - SummaryGuards, + Access, ConditionalRegion, DeclFact, DeclKind, DeclaredType, FactGuard, GuardBranch, MacroFact, + MacroKind, SummaryGuards, }; use cpp_parser::CppAstNode; use cpp_parser::CppSyntaxKind; @@ -91,6 +95,47 @@ use cpp_parser::{CppSyntaxNode, SourceRange}; /// [`crate::DeclFact::clean`]'s documentation warns about. An empty slice means "this file has no diagnostics", /// which is the truth for a file that parses cleanly and is what the tests that do not care about the field /// pass. +pub struct BuiltFacts { + pub facts: Vec, + pub guards: SummaryGuards, + /// **The parameter facts the declarations' `ParamsId`s name.** The builder interns a declaration's parameter list + /// here *before* the fact is pushed, so this table is the only stored parameter representation — there is no + /// build-time copy left on [`crate::summary::DeclDetail`]. A caller that files the facts inserts this table as the + /// summary's `ParamsStore` (see [`crate::FileIndexer::index_tree`]); one that only reads the facts drops it and + /// clears the handles ([`facts_with_their_types`]). + pub parameters: index::params::ParamsStore, +} + +/// **A freshly built fact set for a caller that keeps no parameter store**: the parameter handle is cleared. +/// +/// [`build_facts`] returns a **local** `ParamsStore`; a caller that files the facts in a summary hands the table to +/// the index, but a caller that only reads the facts (a hover completed from a buffer's view, an outline) has nowhere +/// to keep it. Leaving the local handle on those facts would let a query resolve an index into an arena that was +/// dropped — another store's `ParamsId(3)` — so the handle is cleared here, once. The **types** are not affected: +/// they are immutable `ComputedType` values that travel with the fact already. +/// +/// **A cleared parameter handle is not a lost list.** The declaration is still the file's: the summary that owns it +/// files the list, and [`crate::ProjectIndex::parameter_facts_of`] answers a handle-less copy through that reading by +/// the declaration's own name and ranges. A caller that reads the facts directly — a member rank, a parameter check — +/// uses the same resolver, or the [`SynthesizedFact`]'s list when it has just built the fact +/// ([`crate::index::project::fact_from_binding_with`]). +/// +/// [`SynthesizedFact`]: crate::index::project::SynthesizedFact +pub fn facts_with_their_types(built: BuiltFacts) -> Vec { + let BuiltFacts { mut facts, .. } = built; + for fact in &mut facts { + // **The parameter handle does not travel either.** The list it names lives in the builder's `ParamsStore`, and + // clearing the handle is what keeps a caller from resolving a local id through an arena that was dropped. A + // caller that needs a declaration's parameters asks the index (`ProjectIndex::parameter_facts_of`), which + // resolves through the summary that owns them. + // **The list-level `...` stays**, because it is stored on the fact rather than in the arena (see + // [`DeclFact::variadic_parameters`]): a copied fact keeps a fact about the declaration, and only the handle + // to another arena is dropped. + fact.parameters = index::params::ParamsId::NONE; + } + facts +} + pub fn build_facts( scopes: &ScopeTree, preprocessing: &FilePreprocessing, @@ -101,9 +146,8 @@ pub fn build_facts( // reading does not: a local of an inline function in a header is a name no importer can write, and nearly // half of the standard library's facts are those locals (measured on `import std;`: 29 067 of 61 337). keep_locals: bool, -) -> (Vec, SummaryGuards) { - let file = DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals); - file.build() +) -> BuiltFacts { + DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals).build() } /// The type a variable-like declaration was written with, as it is spelled before the name. @@ -131,7 +175,7 @@ pub fn build_facts( /// /// `None` for a declaration that declares no type: a class, a namespace, a function, an alias. See /// [`DeclFact::type_of`]. -pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option { +pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option { declared_type_of_with(&DeclarationShapes::of(root), binding) } @@ -182,18 +226,20 @@ pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option Option { +/// **The type a `using` alias names**, read structurally from the `TypeId` its declaration writes. +/// +/// The node is the grammar's own type node, so the answer is +/// [`type_of_a_type_id`](crate::sema::types::type_of_a_type_id)'s: no spelling is assembled and none is parsed. +fn using_alias_target(shapes: &DeclarationShapes, name: SourceRange) -> Option { // **The innermost `using` the name is inside**: `on_the_path` visits outermost first, so the last one that // holds the name is the one that declares it — which is what "the smallest such node" meant when this walked. let mut target = None; shapes.on_the_path(name.start_offset, |shape| { if shape.kind == CppSyntaxKind::UsingDecl && let Some(type_id) = &shape.type_id + && let Some(written) = sema::types::type_of_a_type_id(type_id) { - let spelling = type_id.text().to_string().trim().to_string(); - if !spelling.is_empty() { - target = Some(spelling); - } + target = Some(written); } }); target @@ -225,7 +271,7 @@ pub(crate) fn an_unnamed_class_body_named( name: &str, shapes: &DeclarationShapes, binding: &Binding, -) -> Option { +) -> Option { let scope = scope.filter(|scope| !scope.is_empty())?; if name.is_empty() { return None; @@ -238,7 +284,7 @@ pub(crate) fn an_unnamed_class_body_named( unnamed = a_class_body_without_a_tag(specifiers); } }); - unnamed.then(|| format!("{scope}::{name}")) + unnamed.then(|| ComputedType::named(format!("{scope}::{name}"), Vec::new())) } /// Does this specifier sequence hold an **unnamed class body** — `struct { … }` with no tag of its own? @@ -267,7 +313,7 @@ fn reaches_the_name(node: &CppSyntaxNode, name: SourceRange) -> bool { pub(crate) fn declared_type_of_with( shapes: &DeclarationShapes, binding: &Binding, -) -> Option { +) -> Option { // **The kinds that name a type.** A field and a parameter are `Variable` too — they are what a member access is // asked *from* — and so is an **alias**, which is the kind this list was missing: `typedef _Ty& reference;` // records nothing under a rule that only allows `Variable`, so every member a class declares with its own @@ -377,6 +423,11 @@ pub(crate) fn declared_type_of_with( _ if the_declarator_holds_the_name => None, _ => Some(binding.name.spelled()), }; + // **The structure the reader produced is the answer.** It used to be printed and then re-spliced with the + // declarator's own operator text, because writing a complex declarator back from the shape could get C's + // precedence wrong (`int ([3]*)(int)` for `int (*table[3])(int);`). A fact now carries the structure itself, and + // display is `ComputedType`'s canonical rendering, so there is nothing to splice and nothing to parse again: the + // operators the shape knows about are in `ComputedType` already. let found = sema::types::type_of_declaration_named( &specifiers, declarator.as_ref(), @@ -389,33 +440,9 @@ pub(crate) fn declared_type_of_with( // which it is, so it never builds the function type this used to strip afterwards. matches!(binding.kind, BindingKind::Variable), ); - - // **The operators are spliced from the declarator's own text**, and the base comes from the specifiers read as - // syntax. Writing the operators back from the `Type` is what produced `int ([3]*)(int)` for - // `int (*table[3])(int);` — the shape knows the nesting (array of three pointers to a function), but the writer - // that turns it back into a declarator has to reproduce C's precedence, and one nesting it does not reproduce is - // exactly this one. The source wrote the spelling already, and the name is the only thing to cut out of it — the - // same arithmetic [`without`] does for a return type. - let written = match declarator - .as_ref() - .filter(|node| reaches_the_name(node, binding.name_range)) - .map(|node| the_operators_around_the_name(node, binding.name_range)) - .map(|operators| operators.trim().to_string()) - .filter(|operators| !operators.is_empty()) - { - Some(operators) => { - let base = sema::types::read_specifiers_named( - &specifiers, - spelled.as_deref(), - source_range(specifiers.text_range()), - ) - .to_string(); - format!("{base} {operators}") - } - None => found.to_string(), - }; - let written = written.split_whitespace().collect::>().join(" "); - (!written.is_empty()).then_some(written) + // **An empty spelling is "no type"**, which is what a declaration specifier sequence the reader could not + // place produces; `ComputedType::Named("")` is the shape that means it. + (!found.to_string().trim().is_empty()).then_some(found) } /// **The modifiers a declaration is written with**, from the tokens the shape table already holds. @@ -693,8 +720,8 @@ fn modifiers_in(node: &CppSyntaxNode) -> DeclModifiers { // descendant scan answered "this class is `virtual`" because a member function was — measured by // `the_virt_specifiers_are_bits`. The walk stops at a `ClassBody` or a `CompoundStat` and keeps everything else: // specifier nodes, the declarator's suffix (`override`, `final`), a parameter list, an attribute. - let mut stack: Vec<(CppSyntaxNode, bool)> = vec![(node.clone(), false)]; - while let Some((current, in_a_parameter_list)) = stack.pop() { + let mut stack: Vec = vec![node.clone()]; + while let Some(current) = stack.pop() { for element in current.children_with_tokens() { if let Some(token) = element.as_token().cloned() { let word = token.text(); @@ -717,22 +744,14 @@ fn modifiers_in(node: &CppSyntaxNode) -> DeclModifiers { if let Some(bit) = bit { found = found.union(bit); } - // **A variadic parameter list**, which is the `...` of a function rather than of a pack expansion - // inside an expression: only a `...` inside a parameter list counts. - if in_a_parameter_list - && cpp_parser::CppTokenKind::from(token.kind()) - == cpp_parser::CppTokenKind::Ellipsis - { - found = found.union(DeclModifiers::VARIADIC); - } continue; } let Some(child) = element.as_node().cloned() else { continue; }; // **A body is not the declaration's own words**: a class's specifier sequence contains its body, so the walk stops - // at a `ClassBody` or a `CompoundStat`. The parameter-list flag is what separates a variadic function's `...` from a - // pack expansion in an expression. + // at a `ClassBody` or a `CompoundStat`. The parameter-list `...` is no longer a modifier either — see + // `DeclFact::variadic_parameters` — so the walk does not descend into an old-style list for one. if cpp_parser::CppClassBody::can_cast(child.kind().into()) || cpp_parser::CppCompoundStat::can_cast(child.kind().into()) || matches!( @@ -742,8 +761,7 @@ fn modifiers_in(node: &CppSyntaxNode) -> DeclModifiers { { continue; } - let child_is_a_parameter_list = CppParamList::can_cast(child.kind().into()); - stack.push((child, in_a_parameter_list || child_is_a_parameter_list)); + stack.push(child); } } @@ -784,9 +802,9 @@ fn the_offset_to_descend_by(binding: &Binding) -> usize { /// `TrailingReturnType`, `Declarator`, a `using`'s `TypeId`, a class's base names) or a kind that is a declaration /// in its own right (`using`/`typedef`, and the class-like definitions whose bases are read). A node with none of /// those is not a shape — no question in this module is answered by one. -/// **One template parameter, as the three questions want it** — `_Alloc`, its constraint (`""` when none), and its -/// default (`None` when none). -pub type TemplateParameters = (String, String, Option); +/// **One template parameter, as the three questions want it** — its name, its constraint (display text and the +/// structured fact a check reads), and its default. See [`sema::types::TemplateParameter`]. +pub type TemplateParameters = sema::types::TemplateParameter; #[derive(Default)] pub struct DeclarationShapes { @@ -1381,7 +1399,7 @@ fn declared_namespace_alias_target_with(root: &CppSyntaxNode, binding: &Binding) /// /// The query layer needs the same answer for an alias declared in the buffer it is looking at, without a summary: /// the same reason [`declared_type_of`] is public, and the same rule about one implementation. -pub fn declared_alias_target(root: &CppSyntaxNode, binding: &Binding) -> Option { +pub fn declared_alias_target(root: &CppSyntaxNode, binding: &Binding) -> Option { declared_alias_target_with(&DeclarationShapes::of(root), binding) } @@ -1389,7 +1407,7 @@ pub fn declared_alias_target(root: &CppSyntaxNode, binding: &Binding) -> Option< pub(crate) fn declared_alias_target_with( shapes: &DeclarationShapes, binding: &Binding, -) -> Option { +) -> Option { if !matches!(binding.kind, BindingKind::Alias | BindingKind::Typedef) { return None; } @@ -1414,15 +1432,11 @@ pub(crate) fn declared_alias_target_with( let (kind, type_id, specifiers, declarator) = declaration?; if kind == CppSyntaxKind::UsingDecl { - // `using X = ;` — the target is that node's whole text, template arguments and all. - return type_id - .as_ref() - .map(|target| target.text().to_string().trim().to_string()) - .filter(|target| !target.is_empty()); + // `using X = ;` — the type-id node is the target, template arguments and all. + return type_id.as_ref().and_then(sema::types::type_of_a_type_id); } let specifiers = specifiers.as_ref()?; - let declarator = declarator.as_ref(); // **A `typedef` of a class body names the class, not the body's text.** // @@ -1431,35 +1445,42 @@ pub(crate) fn declared_alias_target_with( // typedef struct Tag { int d; } Alias; // the members are filed under `Tag` // ``` // - // The general rule below builds the target as "the specifiers minus the declarator's name", which for a body - // is the *definition's text*: `struct { int a; int b; }`. Nothing declares that spelling, so following the - // alias ended in a name no scope has — measured as the whole of `members_of("Object")` answering an **empty** - // list with `unlisted ["{inta;intb;}"]` while its two members sat under the scope `Object`, and as the - // **21 539 of 40 000** refusals in neovim's member questions. C declares almost every struct this way, so the - // shape is the common one rather than a corner. + // The general rule below reads the specifiers and declarator, which for a body is the *definition*: nothing + // declares `struct { int a; int b; }`, so following the alias ended in a name no scope has — measured as the + // whole of `members_of("Object")` answering an **empty** list with `unlisted ["{inta;intb;}"]` while its two + // members sat under the scope `Object`, and as the **21 539 of 40 000** refusals in neovim's member questions. + // C declares almost every struct this way, so the shape is the common one rather than a corner. if let Some(named) = the_class_a_typedef_body_names(specifiers, binding.name.spelled().as_ref()) { - return Some(named); + return Some(ComputedType::named(named, Vec::new())); } // No declarator: `typedef struct { … } ;` has no name to bind either, so this cannot be reached with a fact - // to build — but returning the specifiers is the honest answer if it ever is. + // to build — but the specifiers are the honest answer if it ever is. let Some(declarator) = declarator else { - let spelling = strip_declaration_specifiers(&specifiers.text().to_string()); - return (!spelling.is_empty()).then_some(spelling); + let written = sema::types::read_specifiers(specifiers); + return (!written.to_string().trim().is_empty()).then_some(written); }; - let spelling = format!( - "{} {}", - strip_declaration_specifiers(&specifiers.text().to_string()), - // The same splice a variable's type takes: the name out, an initialiser and a constructor call out, and a - // type's parameter **names** out — `typedef int (*binary_op)(int left, int right);` names the type - // `int (*)(int, int)`, and a consumer that compares spellings reads the names as part of it. - the_operators_around_the_name(declarator, binding.name_range) - ); - let spelling = spelling.split_whitespace().collect::>().join(" "); + // **A `typedef` of a function pointer** — `typedef void (*F)(int);` — is the shape the declaration reader + // cannot unwrap through its ordinary declarator walk: the pointed-to function's parameter list sits *outside* + // the parenthesised declarator, and applying it after the pointer would answer a function returning a pointer. + // [`a_parenthesised_return_type`] reads the suffix-then-operator order that is the whole type here. + let base = sema::types::read_specifiers(specifiers); + if let Some(written) = a_parenthesised_return_type(&declarator, binding.name_range, &base) { + return Some(written); + } - (!spelling.is_empty()).then_some(spelling) + // `typedef basic_string B;` and every other operator shape are the declaration reader's ordinary form: + // the declarator is a chain of operators around the alias's own name. + let written = sema::types::type_of_declaration_named( + specifiers, + Some(&declarator), + binding.name_range, + None, + false, + ); + (!written.to_string().trim().is_empty()).then_some(written) } /// **The name a `typedef`'s class body gives the type it declares** — the tag when the body has one, and the @@ -1490,99 +1511,6 @@ fn the_class_a_typedef_body_names( Some(tag.unwrap_or_else(|| typedef_name.trim().to_string())) } -/// `text` with the span `name` occupies removed. -/// -/// The one place a spelling has to be *edited* rather than read, because a `typedef`'s type is its specifiers -/// plus its declarator and the alias's own name sits inside the second: cutting it out is what turns `(*F)(int)` -/// into `(*)(int)`. Offsets are byte offsets into the same source, so this is arithmetic on the two ranges rather -/// than a search for a word — a search would cut the wrong one in `typedef int int32_t;`(the second `int` is the -/// name, and the first is the type). -/// **The operators a declarator writes around its name** — `(*[3])(int)` for `int (*table[3])(int);`. -/// -/// The declarator's own text with three things cut out of it: the **name**, an **initialiser** (`lock(mutex, 1)` — the -/// call is not part of the type) and a **parameter list that belongs to the name** of an object (`T x(a, b)`, a -/// constructor call). Everything else is the type's: the `*`, the `[3]`, the list of a function the pointer points to. -/// -/// Written from the source rather than from the [`crate::sema::types::Type`], because turning the shape back into a -/// declarator is a spelling problem with C's precedence in it: writing `Array { Pointer { Function } }` back gave -/// `int ([3]*)(int)` for `int (*table[3])(int);` — the operators in the wrong order around the name — and a helper -/// that reproduced precedence would be a second grammar. The file wrote the spelling; this keeps it. -fn the_operators_around_the_name(declarator: &CppSyntaxNode, name: SourceRange) -> String { - let text = declarator.text().to_string(); - let start = usize::from(declarator.text_range().start()); - let mut cut: Vec<(usize, usize)> = Vec::new(); - // The name itself. - let (from, to) = ( - name.start_offset.saturating_sub(start), - name.end_offset().saturating_sub(start), - ); - if from <= to && to <= text.len() { - cut.push((from, to)); - } - // An initialiser, which the grammar keeps inside the declarator. - use cpp_parser::CppAstNode; - let names_the_binding = typed_children::(declarator).any(|child| { - let range = child.get_range(); - usize::from(range.start()) <= name.start_offset - && name.start_offset + name.length <= usize::from(range.end()) - }); - // **What is not part of the type**: an initialiser, a parameter list that is a constructor call, and a type's - // parameter *names* — `int (*)(int left, int right)` is the spelling of the type, and writing the names into it - // makes `int (*)(int left, int right)` a different answer for consumers that compare spellings. - let mut replacements: Vec<(usize, usize, String)> = Vec::new(); - for child in declarator.children() { - let kind = CppSyntaxKind::from(child.kind()); - let is_initialiser = kind == CppSyntaxKind::Initializer; - // …and a parameter list at the name's own level is a constructor call when the declarator spells the name. - let is_a_constructor_call = names_the_binding && kind == CppSyntaxKind::ParameterList; - if is_initialiser || is_a_constructor_call { - let range = child.text_range(); - let (from, to) = ( - usize::from(range.start()).saturating_sub(start), - usize::from(range.end()).saturating_sub(start), - ); - if from <= to && to <= text.len() { - cut.push((from, to)); - } - continue; - } - if kind == CppSyntaxKind::ParameterList { - let range = child.text_range(); - let (from, to) = ( - usize::from(range.start()).saturating_sub(start), - usize::from(range.end()).saturating_sub(start), - ); - if from <= to && to <= text.len() { - let parameters = sema::types::read_parameters(&child); - let spelled = parameters - .iter() - .map(|parameter| parameter.to_string()) - .collect::>() - .join(", "); - replacements.push((from, to, format!("({spelled})"))); - cut.push((from, to)); - } - } - } - cut.sort_unstable(); - let mut out = String::new(); - let mut at = 0usize; - for (from, to) in cut { - if from > at { - out.push_str(&text[at..from]); - } - // A parameter list is **replaced** by its types rather than dropped — see `replacements`. - if let Some((_, _, spelled)) = replacements.iter().find(|(start, _, _)| *start == from) { - out.push_str(spelled); - } - at = at.max(to); - } - if at < text.len() { - out.push_str(&text[at..]); - } - out.trim().to_string() -} - /// The type a **function** declaration returns, as the file spells it. /// /// The sibling of [`declared_type_of`], with the same walk down to the declaration and the same two answers — a @@ -1598,12 +1526,14 @@ fn the_operators_around_the_name(declarator: &CppSyntaxNode, name: SourceRange) /// `None` for a return type the file does not *state*: a deduced `auto` is not a class to look a member up in, and /// recording it as one would answer `make().size` with "the type `auto` has no members" — a wrong answer where /// "nothing is known" is the true one. See [`DeclFact::returns`]. -pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option { +pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option { let written = declared_returns_of_with(&DeclarationShapes::of(root), binding); if written.is_some() { return written; } - deduced_returns_of(root, binding) + // **A deduced answer is a spelling the deduction layer produced**, not a CST node, so this is the one + // construction edge that lowers it. The parse is not new: it is the same boundary the fact builder always had. + deduced_returns_of(root, binding).map(|spelling| sema::types::parse_type_spelling(&spelling)) } /// **The type a function with no written return type returns** — `auto f() { … }` and `decltype(auto) f()`. @@ -1646,13 +1576,13 @@ pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option>( root: &CppSyntaxNode, binding: Binding, - substitutions: &sema::types::TypeSubstitutions<'_>, + substitutions: &TypeSubstitutions<'_, N>, // **The types the call passed**, in order — what a *pack* stands for. A fold expression widens all of them // (`sum_of(1, 2.5)` is a `double`), and a pack has no single substitution to read that from. - argument_types: &[sema::types::Type], + argument_types: &[ComputedType], ) -> Option { if binding.kind != BindingKind::Function { return None; @@ -1687,10 +1617,10 @@ pub fn deduced_returns_of_substituted( /// the substitutions. A condition that cannot be decided answers `true` as well — leaving the return in play is what /// this layer did before it could read conditions, and dropping a return because a trait was unfamiliar would turn an /// unknown into a wrong answer. -fn a_branch_that_is_taken( +fn a_branch_that_is_taken>( expression: &cpp_parser::CppExpr, body: &cpp_parser::CppCompoundStat, - substitutions: &sema::types::TypeSubstitutions<'_>, + substitutions: &TypeSubstitutions<'_, N>, ) -> bool { use cpp_parser::{CppAstNode, CppIfStat}; // **The `if constexpr` statements that enclose this return**, innermost first — an ancestor walk. Asking the body for all of @@ -1753,9 +1683,9 @@ fn constexpr_condition_of(statement: &cpp_parser::CppIfStat) -> Option { /// direction that costs an answer rather than giving a wrong one. /// is_same_v the two spellings are equal after `decay_t` and whitespace. /// ``` -fn evaluate_a_trait( +fn evaluate_a_trait>( condition: &str, - substitutions: &sema::types::TypeSubstitutions<'_>, + substitutions: &TypeSubstitutions<'_, N>, ) -> Option { let condition = condition.trim(); @@ -1823,9 +1753,9 @@ fn evaluate_a_trait( } /// A spelling with `decay_t<…>` applied and the template parameters substituted — see [`evaluate_a_trait`]. -fn substituted_spelling( +fn substituted_spelling>( written: &str, - substitutions: &sema::types::TypeSubstitutions<'_>, + substitutions: &TypeSubstitutions<'_, N>, ) -> String { let mut text = written.trim(); while let Some(inner) = text @@ -2403,7 +2333,7 @@ fn declaration_of(root: &CppSyntaxNode, binding: &Binding) -> Option Option { use cpp_parser::{CppAstNode, CppLambdaExpr}; // **The lambda's own body and parameters**, and nothing else: a lambda has no name, so the caller resolves the variable @@ -2419,7 +2349,7 @@ pub fn a_lambdas_return_type( if receives_a_placeholder && placeholder_types.is_empty() { return None; } - let substitutions = sema::types::TypeSubstitutions::new(&[], argument_types); + let substitutions = TypeSubstitutions::::new(&[], argument_types); let mut agreed: Option = None; for statement in the_returns_of(&body, lambda.syntax()) { let Some(expression) = statement.get_expr() else { @@ -2456,8 +2386,8 @@ pub fn a_lambdas_return_type( /// what a `return` of the name then means is the value's type. fn the_auto_parameters_with_their_arguments( parameters: &[CppParam], - argument_types: &[sema::types::Type], -) -> Vec<(String, sema::types::Type)> { + argument_types: &[ComputedType], +) -> Vec<(String, ComputedType)> { parameters .iter() .enumerate() @@ -2506,7 +2436,7 @@ fn is_a_literal_zero(expression: &cpp_parser::CppExpr) -> bool { /// lambda with no `auto` parameters uses. fn type_with_the_auto_parameters( expression: &cpp_parser::CppExpr, - paired: &[(String, sema::types::Type)], + paired: &[(String, ComputedType)], ) -> Option { use cpp_parser::{CppAstNode, CppExpr}; match expression { @@ -2609,7 +2539,7 @@ fn returned_expressions_in(body: &cpp_parser::CppCompoundStat) -> Vec Option { +pub(crate) fn the_widest_of(types: &[ComputedType]) -> Option { let mut widest: Option<(u8, String)> = None; for a_type in types { let spelling = a_type.to_string(); @@ -2684,11 +2614,11 @@ fn a_data_member_type(expression: &CppSyntaxNode, declaration: &CppSyntaxNode) - /// The same reading as [`type_a_return_states`], plus the two shapes a template body writes that a plain one does not: a **fold /// expression** (`(values + ...)`), whose type is every argument the call passed widened by `+`, and a name that came from a /// template parameter, which is substituted before it is answered. -fn type_a_return_states_with( +fn type_a_return_states_with>( expression: &cpp_parser::CppExpr, declaration: &CppSyntaxNode, - substitutions: &sema::types::TypeSubstitutions<'_>, - argument_types: &[sema::types::Type], + substitutions: &TypeSubstitutions<'_, N>, + argument_types: &[ComputedType], ) -> Option { use cpp_parser::{CppAstNode, CppExpr}; match expression { @@ -2878,7 +2808,7 @@ fn a_captures_type(expression: &CppSyntaxNode) -> Option { type_a_return_states_with( &initializer, enclosing.syntax(), - &sema::types::TypeSubstitutions::new(&[], &[]), + &TypeSubstitutions::::new(&[], &[]), &[], ) } @@ -2940,20 +2870,21 @@ pub(crate) fn declared_returns_of_in( shapes: &DeclarationShapes, root: &CppSyntaxNode, binding: &Binding, -) -> Option { +) -> Option { let written = declared_returns_of_with(shapes, binding); - if let Some(spelling) = written { - // **An operator's return type, when the fact's readers can resolve the spelling.** See + if let Some(written) = written { + // **An operator's return type, when the fact's readers can resolve the shape.** See // [`an_operator_return_is_usable`]: `std::vector::operator[]` says `reference`, a typedef inside the // class, and a fact that carried it typed `tokens[i]` as a class called `reference`. if binding.kind != BindingKind::OperatorFunction - || an_operator_return_is_usable(root, binding, &spelling) + || an_operator_return_is_usable(root, binding, &written) { - return Some(spelling); + return Some(written); } - return deduced_returns_of(root, binding); + return deduced_returns_of(root, binding) + .map(|spelling| sema::types::parse_type_spelling(&spelling)); } - deduced_returns_of(root, binding) + deduced_returns_of(root, binding).map(|spelling| sema::types::parse_type_spelling(&spelling)) } /// **The return spelling [`an_operator_return_is_usable`] refused** — [`crate::DeclFact::returns_in_the_class`]. @@ -2970,7 +2901,8 @@ pub(crate) fn the_returns_the_class_has_to_resolve( return None; } declared_returns_of_with(shapes, binding) - .filter(|spelling| !an_operator_return_is_usable(root, binding, spelling)) + .filter(|written| !an_operator_return_is_usable(root, binding, written)) + .map(|written| written.to_string()) } /// **May an operator's return spelling be stored in a fact?** @@ -2984,29 +2916,31 @@ pub(crate) fn the_returns_the_class_has_to_resolve( /// that declares the operator does **not** declare a name of its own with that spelling — which is the same rule as /// the language's (an unqualified name in a member's return type is looked up in the class first), asked of the tree /// instead of the scope table because this reader is handed the file's tree. -fn an_operator_return_is_usable(root: &CppSyntaxNode, binding: &Binding, spelling: &str) -> bool { - fn means_the_same_everywhere(kind: &sema::types::Type) -> bool { - use crate::sema::types::Type; +fn an_operator_return_is_usable( + root: &CppSyntaxNode, + binding: &Binding, + written: &ComputedType, +) -> bool { + fn means_the_same_everywhere(kind: &ComputedType) -> bool { match kind { - Type::Builtin { .. } => true, - Type::Named { name, arguments } => { - name.contains("::") && arguments.iter().all(means_the_same_everywhere) + ComputedType::Primary(_) => true, + ComputedType::Named(name) => name.contains("::"), + ComputedType::Generic(generic) => { + generic.name.contains("::") + && generic.arguments.iter().all(means_the_same_everywhere) } - Type::Pointer { to } - | Type::Qualified { of: to, .. } - | Type::Reference { to, .. } - | Type::Array { of: to, .. } => means_the_same_everywhere(to), + ComputedType::Pointer(to) + | ComputedType::Reference { to, .. } + | ComputedType::Array { of: to, .. } => means_the_same_everywhere(to), + ComputedType::Qualified(qualified) => means_the_same_everywhere(&qualified.of), _ => false, } } - if means_the_same_everywhere(&sema::types::parse_type_spelling(spelling)) { + if means_the_same_everywhere(written) { return true; } - let Some(head) = sema::types::parse_type_spelling(spelling) - .class_name() - .map(str::to_string) - else { + let Some(head) = written.class_name().map(str::to_string) else { return true; }; !the_enclosing_body_declares(root, binding, &head) @@ -3060,8 +2994,8 @@ fn the_enclosing_body_declares(root: &CppSyntaxNode, binding: &Binding, name: &s pub(crate) fn declared_returns_of_with( shapes: &DeclarationShapes, binding: &Binding, -) -> Option { - // **A `Function`, and an operator when the spelling cannot be a name from the class's own body.** +) -> Option { + // **A `Function`, and an operator when the type cannot be a name from the class's own body.** // // An operator does declare a return type, and recording every one of them was measured and rejected once: // `std::vector::operator[]` says `reference`, and `reference` is a *typedef inside the class* — so the @@ -3086,11 +3020,15 @@ pub(crate) fn declared_returns_of_with( // The rule is the **spelling**, not the kind: the walker classifies `operator bool` as an operator, and a // conversion operator is the one operator whose name carries a space and a type (`operator[]` and `operator+` do // not match this pattern, and their return type is a real specifier). + // + // **The target is written as part of the operator's name**, not as a type node, so this one construction edge + // lowers the spelling the grammar hands over. It used to be interned through the type store; it is a `ComputedType` here + // and nothing downstream parses it back. let spelled = binding.name.spelled(); if let Some(target) = spelled.trim().strip_prefix("operator ").map(str::trim) && !target.is_empty() { - return Some(target.to_string()); + return Some(sema::types::parse_type_spelling(target)); } if !matches!( @@ -3102,10 +3040,10 @@ pub(crate) fn declared_returns_of_with( // Three things are collected on the way past the declaration, and **the direction each is kept in is not // decoration**: the specifier sequence and the trailing return type are the innermost on the path ("the last - // one seen going down"), while the declarator is the outermost — its text *before the name* is where the - // operators in front of it live, and the nested declarators are its pointer parts. + // one seen going down"), while the declarator is the outermost — its own operators are where the pointer parts + // in front of the name live. let mut specifiers = None; - let mut trailing = None; + let mut trailing: Option = None; let mut declarator = None; shapes.on_the_path(the_offset_to_descend_by(binding), |shape| { if let Some(node) = &shape.specifiers { @@ -3114,10 +3052,7 @@ pub(crate) fn declared_returns_of_with( if let Some(node) = &shape.trailing && let Some(type_id) = typed_children::(node).next() { - let spelling = type_id.get_type_text().trim().to_string(); - if !spelling.is_empty() { - trailing = Some(spelling); - } + trailing = Some(type_id.syntax().clone()); } // The **outermost** declarator on the path, which is the one whose own text holds the name: the nested // ones are its pointer/reference parts, and reading the text before the name off the outer one gets every @@ -3129,95 +3064,49 @@ pub(crate) fn declared_returns_of_with( } }); - if let Some(trailing) = trailing { - let spelling = trailing.trim().to_string(); - return (!spelling.is_empty()).then_some(spelling); + // **A trailing return type wins** — `auto make() -> Widget` spells the type after the parameter list, and it is + // a `TypeId` node: the structural reader owns it. + if let Some(type_id) = trailing { + return sema::types::type_of_a_type_id(&type_id); } - // **The operators written before the name are part of the return type**: `Widget* make()`, `const Widget& - // get()`. They live in the *declarator*, so the specifier sequence does not have them, and reading only the - // specifiers answered `Widget` for `Widget* make()` — a return type with no pointer on it. Everything that - // follows a return type reads that spelling, so `(*make()).size` looked like a member lookup on a value and - // `make()->size` was unanswerable. - // - // Only the operators, and only when they are *purely* operators: `int (*f)(int)` returns a function pointer - // and its text before the name is `(*` — a spelling this cannot assemble, so it keeps the specifiers instead - // of returning something that is not a type. + // An **empty** specifier sequence is `None` rather than `void`: a constructor spells no return type, and the + // node-based reader's fallback (`void`) is the right answer for "this declaration wrote nothing as a type" only + // when there is a declaration — see the `None` half of this function's contract. + let specifiers = specifiers?; + // **The declarator's own qualified name is not a return type**, for the same reason it is not a variable's type — + // `std::size_t LuaSource::GetLine(std::size_t offset)` recorded `returns: LuaSource::GetLine`, and a hover + // showed that as the function's answer where the file wrote `std::size_t`. See + // [`crate::sema::types::type_of_declaration_named`]. + let declared = binding.name.spelled(); + let base = sema::types::read_specifiers_named( + &specifiers, + Some(declared.as_ref()), + source_range(specifiers.text_range()), + ); + // **A function returning a function pointer** — `int (*maker(int a))(int b);` returns `int (*)(int)`, and the - // assembly below could not say so: the text before the name is `(*`, which is not "purely operators", so the whole - // thing was refused and the fact answered the bare specifiers (`returns int`). Measured on the shape this round - // fixed (`docs/declarator-shapes.md`): the declarator's own spelling is `(*maker(int a))(int b)` — the `(` before - // the `*` is the return type's, `(int a)` is the function's own list, and `(int b)` describes the pointed-to - // function. [`a_parenthesised_return_type`] reads exactly that. - let parenthesised = declarator - .as_ref() - .and_then(|declarator| a_parenthesised_return_type(declarator, binding.name_range)); - let from_the_text = match parenthesised { - // A parenthesised return type is a *whole* spelling — `(*)(int b)` — so it is not put through the operator - // filter below, which is there to reject text that is not purely operators. - Some(_) => None, - None => declarator - .as_ref() - .map(|declarator| { - let text = before( - &declarator.text().to_string(), - declarator, - binding.name_range, - ); - // **A parenthesized name is not a function pointer.** Lua's C API writes - // `LUALIB_API const char *(luaL_tolstring) (lua_State *L, …)` — the `*` is the *return type's*, and the - // parentheses only wrap the name. The text before the name is `*(`, which the operator filter below - // refused, so the fact recorded `const char` and every call was reported as returning something that - // does not convert (measured: `assign-type-check` on `const char *sep = luaL_optlstring(…)`, Lua 5.5.0). - // - // `int (*f)(int)` has the same two characters — `(*` — and there the `*` **is** the declarator's (a - // pointer to function), which this cannot assemble. The two differ in where the `(` is: after the - // operators for a function returning a pointer, before them for a pointer to function. Only the first - // is unparenthesised here. - let trimmed = text.trim_end(); - match trimmed.strip_suffix('(') { - Some(rest) - if rest - .trim_end() - .chars() - .all(|c| c == '*' || c == '&' || c.is_whitespace()) => - { - rest.to_string() - } - _ => text, - } - }) - .filter(|operators| { - operators - .chars() - .all(|c| c == '*' || c == '&' || c.is_whitespace()) - }), - }; + // declarator's own spelling is `(*maker(int a))(int b)` — the `(` before the `*` is the return type's, `(int a)` + // is the function's own list, and `(int b)` describes the pointed-to function. + // [`a_parenthesised_return_type`] reads exactly that, structurally. + if let Some(declarator) = declarator.as_ref() + && let Some(written) = a_parenthesised_return_type(declarator, binding.name_range, &base) + { + return Some(written); + } - // **A calling convention is written *inside* the pointer**, so the text above carries its name and the operator - // filter refuses the whole thing. `char *__cdecl strchr(const char *, int)` is MinGW's own spelling: the tree is - // `Declarator { Declarator { PointerType { Star, Identifier "__cdecl" } }, NameExpr "strchr", … }`, so the text - // before the name is `*__cdecl` — not "purely operators" — and the fact recorded `returns: char`. Every caller - // then read `strchr` as returning a `char`, and redis's `char *pch = strrchr(path, '/')` was reported as a - // conversion that does not exist (`docs/c-support.md` §8). - // - // The operators are therefore read from the **tree** as well: one `*` per `PointerType` before the name, one `&` - // per `ReferenceType`. A word inside the pointer node — the convention, or a macro standing in for one - // (`APIENTRY`) — has no effect, because it is not a node of those kinds. - let pointer_operators = { - let mut operators = String::new(); + // **The operators written before the name are the return type's** — `Widget* make()`, `const Widget& get()`. + // They live in the declarator, not in the specifier sequence, and there are two places to read them: the tree + // (`PointerType`/`ReferenceType` nodes, which survive a calling convention written inside the pointer — + // `char *__cdecl strchr(…)`) and the text (a bare `*` is often a token rather than a node, and + // `const char *(paren_name)(void)` writes one). The tree wins when it has anything; the text is the fallback. + let tree_operators = declarator.as_ref().map_or_else(String::new, |declarator| { let mut nodes: Vec = declarator - .as_ref() - .map(|declarator| { - declarator - .descendants() - .filter(|node| { - usize::from(node.text_range().start()) < binding.name_range.start_offset - }) - .collect() - }) - .unwrap_or_default(); + .descendants() + .filter(|node| usize::from(node.text_range().start()) < binding.name_range.start_offset) + .collect(); nodes.sort_by_key(|node| node.text_range().start()); + let mut operators = String::new(); for node in nodes { match CppSyntaxKind::from(node.kind()) { CppSyntaxKind::PointerType => operators.push('*'), @@ -3227,61 +3116,80 @@ pub(crate) fn declared_returns_of_with( } } operators - }; - - // **Which reading wins, and in what order.** A parenthesised return type is a whole spelling the operators alone - // cannot express (`int (*)(int b)`), so it is first. Then the tree's operators, which survive a calling - // convention. Then the text's own filtered reading, which is what a shape with none of the above has. - let before_the_name = match parenthesised { - Some(spelling) => spelling, - None if !pointer_operators.is_empty() => pointer_operators, - None => from_the_text.unwrap_or_default(), - }; - - // **The specifiers are read as syntax, not as text**, which is the rule [`crate::sema::types::read_specifiers`] - // states and the one that already fixed `std::cin`: a macro standing where a specifier goes is a *name* to the - // grammar, no C++ type is spelled as two unqualified names in a row, so **the last name wins** — and everything - // that is not a type's name (attributes, `constexpr`, storage class) is dropped by node kind rather than by - // being on a list of keywords. - // - // What the text-based rule cost, measured on MSVC's ``: `_NODISCARD _CONSTEXPR20 reference back()` - // recorded `_NODISCARD _CONSTEXPR20 reference` as the return type, because neither macro is in - // `DECLARATION_SPECIFIERS`. Nothing can resolve that spelling — the macros are the library's, the name is last — - // so `auto y = x.back()` answered with it, and `y` had no type at all. Read as syntax the same declaration says - // `reference`, which is a member alias the substitution step can follow (`typedef _Ty& reference` with - // `_Ty = char` → `char&`). - // - // An **empty** specifier sequence is still `None` rather than `void`: a constructor spells no return type, and - // the node-based reader's fallback (`void`) is the right answer for "this declaration wrote nothing as a type" - // only when there is a declaration — see the `None` half of this function's contract. - let specifiers = specifiers?; - // **The declarator's own qualified name is not a return type**, for the same reason it is not a variable's type — - // `std::size_t LuaSource::GetLine(std::size_t offset)` recorded `returns: Some("LuaSource::GetLine")`, and a hover - // showed that as the function's answer where the file wrote `std::size_t`. See - // [`crate::sema::types::type_of_declaration_named`]. - let declared = binding.name.spelled(); - let spelling = if specifiers.text().is_empty() { - String::new() + }); + let text_operators = declarator.as_ref().map_or_else(String::new, |declarator| { + let text = before( + &declarator.text().to_string(), + declarator, + binding.name_range, + ); + // **A parenthesised name is not a function pointer.** `const char *(paren_name)(void)` writes the `(` after + // its operator, so the text before the name is `*(`; cutting that `(` leaves the `*` the return type owns. + let text = match text.trim_end().strip_suffix('(') { + Some(rest) + if rest + .chars() + .all(|c| matches!(c, '*' | '&') || c.is_whitespace()) => + { + rest.to_string() + } + _ => text, + }; + if text + .chars() + .all(|c| matches!(c, '*' | '&') || c.is_whitespace()) + { + text + } else { + String::new() + } + }); + let before_the_name = if tree_operators.is_empty() { + text_operators } else { - sema::types::read_specifiers_named( - &specifiers, - Some(declared.as_ref()), - source_range(specifiers.text_range()), - ) - .to_string() + tree_operators }; - - let spelling = format!("{spelling} {before_the_name}"); - let spelling = spelling.split_whitespace().collect::>().join(" "); + let written = with_operators(base, &before_the_name); // A **deduced** return type is not a type this layer can name. `auto` and `decltype(auto)` are the two // spellings, and both would otherwise be looked up as class names — answering "no member `size` in `auto`" - // where the honest answer is that the file never said. - if spelling == "auto" || spelling == "decltype(auto)" { + // where the honest answer is that the file never said. (`auto&` keeps its reference, and the computation layer's + // placeholder walk sees through it.) + if before_the_name.is_empty() + && let ComputedType::Primary(primary) = &written + && primary.is_a_placeholder() + { return None; } - (!spelling.is_empty()).then_some(spelling) + (!written.to_string().trim().is_empty()).then_some(written) +} + +/// **Apply a declarator's written operators to a base type.** The operators come before the name in the runtime +/// order, so `**` wraps twice and `&` makes a reference; whitespace is ignored. +fn with_operators(base: ComputedType, operators: &str) -> ComputedType { + use std::sync::Arc; + let operators: Vec = operators.chars().filter(|c| !c.is_whitespace()).collect(); + let mut written = base; + let mut at = 0; + while at < operators.len() { + match operators[at] { + '*' => { + written = ComputedType::Pointer(Arc::new(written)); + at += 1; + } + '&' => { + let rvalue = operators.get(at + 1) == Some(&'&'); + written = ComputedType::Reference { + to: Arc::new(written), + rvalue, + }; + at += if rvalue { 2 } else { 1 }; + } + _ => at += 1, + } + } + written } /// `text` up to the span `name` occupies — the mirror of [`without`], which cuts the name *out*. @@ -3302,8 +3210,13 @@ pub(crate) fn declared_returns_of_with( /// The operators before the name (`*`) go inside parentheses, and what follows the name's **own** parameter list is /// the rest — so `(int b)` stays attached in the right place. `None` for every other shape, which is what keeps the /// ordinary assembly ([`before`] plus its operator filter) answering `Widget *` and `const char *`. -fn a_parenthesised_return_type(declarator: &CppSyntaxNode, name: SourceRange) -> Option { +fn a_parenthesised_return_type( + declarator: &CppSyntaxNode, + name: SourceRange, + base: &ComputedType, +) -> Option { use cpp_parser::CppAstNode; + use std::sync::Arc; // The declarator that names the binding: the innermost one holding the name as a direct child. let mut naming = declarator.clone(); @@ -3329,8 +3242,8 @@ fn a_parenthesised_return_type(declarator: &CppSyntaxNode, name: SourceRange) -> // The operators written before the name are the pointer (or reference) the function returns. Read off the // prefix's text rather than its nodes: a `*` in a declarator is often a bare token rather than a `PointerType`. - let operators: String = prefix.chars().filter(|c| matches!(c, '*' | '&')).collect(); - if operators.trim().is_empty() + let operators: Vec = prefix.chars().filter(|c| matches!(c, '*' | '&')).collect(); + if operators.is_empty() || !prefix .chars() .all(|c| matches!(c, '(' | '*' | '&') || c.is_whitespace()) @@ -3339,14 +3252,15 @@ fn a_parenthesised_return_type(declarator: &CppSyntaxNode, name: SourceRange) -> } // …and what follows the name's own parameters is the pointed-to function's: the outer declarator's suffixes that - // are not on the path to the name. + // are not on the path to the name. They are **nodes**, and each one wraps the base structurally: a parameter + // list makes it a function type, an array type an array. let from = u32::try_from(name.start_offset).unwrap_or(u32::MAX); let to = from.saturating_add(u32::try_from(name.length).unwrap_or_default()); let path = declarator.children().find(|child| { let range = child.text_range(); u32::from(range.start()) <= from && to <= u32::from(range.end()) })?; - let after: String = declarator + let suffixes: Vec = declarator .children() .filter(|child| { child.text_range() != path.text_range() @@ -3355,13 +3269,36 @@ fn a_parenthesised_return_type(declarator: &CppSyntaxNode, name: SourceRange) -> CppSyntaxKind::ParameterList | CppSyntaxKind::ArrayType ) }) - .map(|suffix| suffix.text().to_string()) - .collect::>() - .join(""); - if after.trim().is_empty() { + .collect(); + if suffixes.is_empty() { return None; } - Some(format!("({operators}){after}")) + let mut wrapped = base.clone(); + for suffix in &suffixes { + if CppParamList::can_cast(suffix.kind().into()) { + wrapped = ComputedType::Function(Arc::new(index::types::FunctionType { + returns: Arc::new(wrapped), + parameters: sema::types::read_parameters(suffix).into_boxed_slice(), + })); + } else { + wrapped = ComputedType::Array { + of: Arc::new(wrapped), + extent: sema::types::array_extent(suffix), + }; + } + } + // The pointer (or reference) the function returns is written *outside* the parentheses, so it wraps the whole + // suffix chain last. + for operator in operators { + wrapped = match operator { + '*' => ComputedType::Pointer(Arc::new(wrapped)), + _ => ComputedType::Reference { + to: Arc::new(wrapped), + rvalue: false, + }, + }; + } + Some(wrapped) } fn before(text: &str, node: &CppSyntaxNode, name: SourceRange) -> String { @@ -3532,19 +3469,47 @@ pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option sema::call_syntax::parameter_list_text(declarator.syntax()) } -/// **The parameter list as the file spells it, read from the shape table** — `"(int a, int b)"`. +/// **A declaration's parameter list, as CST facts — and the list's own `...`.** +/// +/// The two travel together because they are one reader's answer: the `CppParamList` is in hand for both, and no +/// consumer should have to find the list a second time to ask whether it is variadic. [`facts`](Self::facts) holds +/// the `CppParam` nodes (a pack's marker lives on its parameter — see +/// [`crate::index::params::ParameterFact::pack`]); [`variadic`](Self::variadic) is the list-level token, which is +/// **not** a parameter (`void f(int, ...)` has one parameter, `void f(...)` has none). +#[derive(Debug, Default)] +pub(crate) struct ParameterListFacts { + pub facts: Vec, + pub variadic: bool, +} + +/// **Parameters as CST facts**, from the declarator the shape table already found. This is the only builder a fact +/// uses: the summary writer interns the list into the summary's `ParamsStore` (see [`fact_for`]), and the view-fact +/// synthesizer hands it to the index's synthetic arena (see [`crate::ProjectIndex::intern_a_view_fact`]). +/// [`DeclDetail::parameter_list`] is the display spelling, not a copy of these. /// -/// [`parameter_list_at`] answers the same question from a root and an offset: it asks the tree for the token at the -/// offset and walks the ancestor chain until it meets a `Declarator`. That is a walk per **declaration**, and the -/// `Declarator` it is looking for is already recorded on the shape ([`Shape::declarator`], collected in the pass -/// that builds the table) — so the walk is asking the tree a question the table has already answered. +/// The list-level `...` is read here, from the same `CppParamList`, and becomes +/// [`crate::DeclFact::variadic_parameters`] on the fact the caller is about to build. +pub(crate) fn declared_parameter_facts_with( + shapes: &DeclarationShapes, + binding: &Binding, +) -> ParameterListFacts { + let Some(list) = declared_parameter_list_with(shapes, binding) else { + return ParameterListFacts::default(); + }; + ParameterListFacts { + facts: index::params::parameter_facts_of(&list), + variadic: list.is_variadic(), + } +} + +/// **The parameter list node the declarator that names this binding owns**, from the shape table. /// -/// Measured together with [`enclosing_namespaces_of`]: the two were **1576 ms of a 4562 ms `Facts` stage** over 126 -/// files of MSVC's standard library. -pub(crate) fn declared_parameters_with( +/// The one finder the fact and display readers share: both need the same declarator, and asking the tree twice per +/// declaration is what [`declared_parameters_with`]'s measurement is about. +fn declared_parameter_list_with( shapes: &DeclarationShapes, binding: &Binding, -) -> Option { +) -> Option { let mut found = None; shapes.on_the_path(binding.name_range.start_offset, |shape| { // **The declarator that names this binding**, not merely the last one on the path. @@ -3571,7 +3536,25 @@ pub(crate) fn declared_parameters_with( } }); - sema::call_syntax::parameter_list_text(&found?) + sema::call_syntax::parameter_list_node(&found?) +} + +/// **The parameter list as the file spells it, read from the shape table** — `"(int a, int b)"`. +/// +/// [`parameter_list_at`] answers the same question from a root and an offset: it asks the tree for the token at the +/// offset and walks the ancestor chain until it meets a `Declarator`. That is a walk per **declaration**, and the +/// `Declarator` it is looking for is already recorded on the shape ([`Shape::declarator`], collected in the pass +/// that builds the table) — so the walk is asking the tree a question the table has already answered. +/// +/// Measured together with [`enclosing_namespaces_of`]: the two were **1576 ms of a 4562 ms `Facts` stage** over 126 +/// files of MSVC's standard library. +pub(crate) fn declared_parameters_with( + shapes: &DeclarationShapes, + binding: &Binding, +) -> Option { + Some(sema::call_syntax::render_parameter_list( + &declared_parameter_list_with(shapes, binding)?, + )) } /// Is the **name this declarator declares** the one at `offset`? @@ -3694,32 +3677,47 @@ pub(crate) fn declared_template_parameters_with( // **One parse per template head, shared by every declaration under it** — see [`DeclarationShapes`]`s note on // `templates`. match shapes.template_at(at) { - Some(shared) => shared.iter().map(|(name, _, _)| name.clone()).collect(), + Some(shared) => shared + .iter() + .map(|parameter| parameter.name.clone()) + .collect(), None => Vec::new(), } } -/// **The constraint that applies to each *parameter*** — `["std::integral", ""]` for +/// **The constraints that apply to each *parameter*** — `["std::integral", ""]` and, structurally, +/// `[Some(ConstraintFact { concept: "integral", … }), None]` for /// `template T twice(T a, int n)`. /// /// One entry per parameter of the declaration, because that is the pairing a call site asks about ("does this /// argument satisfy what *its* parameter was constrained by"). It is decided here, once, from the tree — so a file's /// own answer and the index's answer cannot disagree, and no consumer has to re-derive the pairing by matching names /// in raw text. -fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> Vec { +/// +/// The two rows are **one answer with two audiences**, read from the same template-parameter list: the spellings are +/// display text, and the facts are what a check reads. The structured half is lowered while the head is read (see +/// [`sema::types::TemplateParameter::constraint_fact`]), never split out of the spelling here. +#[derive(Debug, Default)] +pub(crate) struct DeclaredConstraints { + /// The constraint's display spelling per parameter, `""` where unconstrained. + pub spellings: Vec, + /// The same constraint per parameter, structurally — see [`crate::ConstraintFact`]. + pub facts: Vec>, +} + +fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> DeclaredConstraints { let at = binding.name_range.start_offset; // **One parse per template head, shared by every declaration under it** — see the note on `templates`. let Some(shared) = shapes.template_at(at) else { - return Vec::new(); + return DeclaredConstraints::default(); }; - let constrained: Vec<(String, String)> = shared + let constrained: Vec<&TemplateParameters> = shared .iter() - .filter(|(_, constraint, _)| !constraint.is_empty()) - .map(|(name, constraint, _)| (name.clone(), constraint.clone())) + .filter(|parameter| !parameter.constraint.is_empty()) .collect(); if constrained.is_empty() { - return Vec::new(); + return DeclaredConstraints::default(); } // **Where the parameters are written**, found the same way the names were: the innermost shape that has a @@ -3731,17 +3729,17 @@ fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> V } }); let Some(declarator) = declarator else { - return Vec::new(); + return DeclaredConstraints::default(); }; use cpp_parser::CppAstNode; let Some(declarator) = cpp_parser::CppDeclarator::cast(declarator) else { - return Vec::new(); + return DeclaredConstraints::default(); }; let Some(list) = declarator.get_param_list() else { - return Vec::new(); + return DeclaredConstraints::default(); }; - let mut per_parameter = Vec::new(); + let mut found = DeclaredConstraints::default(); for parameter in list.get_params() { // **The type is the template parameter**, and the question is asked of the type's *name node*: `const T& a` and `T a` // write the name `T`, while `T::value_type a` writes a qualified name — a different one — and `Total` was never `T` @@ -3752,13 +3750,18 @@ fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> V .and_then(|name| name.get_name_text()); let constraint = constrained .iter() - .find(|(name, _)| written.as_deref() == Some(name.as_str())) - .map(|(_, constraint)| constraint.clone()) - .unwrap_or_default(); - per_parameter.push(constraint); + .find(|parameter| written.as_deref() == Some(parameter.name.as_str())); + found.spellings.push( + constraint + .map(|parameter| parameter.constraint.clone()) + .unwrap_or_default(), + ); + found + .facts + .push(constraint.and_then(|parameter| parameter.constraint_fact.clone())); } - per_parameter + found } /// The base classes a class-like declaration was written with, in declaration order. /// @@ -3806,63 +3809,58 @@ pub(crate) fn declared_bases_of_with(shapes: &DeclarationShapes, binding: &Bindi .collect() } -/// The specifier keywords that can precede a type without being part of it. -/// -/// Deliberately *not* in this list: `unsigned`, `signed`, `long`, `short`. Those four *are* the type: stripping -/// `unsigned` from `unsigned long` leaves a different type. -/// -/// `struct`, `class`, `union` and `enum` **are** in it, and the first version of this list had them out — on the -/// reasoning that "stripping `struct` from `struct Widget` would leave nothing to look up". It leaves `Widget`, -/// which is the only spelling anything looks up (`base_type_name` strips the same four keywords from every -/// receiver): an elaborated keyword says *what kind of* name follows, not what the name is. Measured, keeping them -/// cost `typedef struct exarg exarg_T;` its alias target — the target came out as `struct exarg`, a spelling no -/// scope has, so `exarg_T` answered an empty member list while `struct exarg`'s thirty members sat in the index -/// under `exarg`. -const DECLARATION_SPECIFIERS: &[&str] = &[ - "static", - "extern", - "inline", - "virtual", - "explicit", - "friend", - "mutable", - "register", - "thread_local", - "constexpr", - "consteval", - "constinit", - "typedef", - "const", - "volatile", - "struct", - "class", - "union", - "enum", -]; - -/// The type a specifier sequence spells: its own text, or — when it holds **several names** — from the last one on. -/// -/// Remove declaration specifiers from the front of a type spelling, and trim what is left. -fn strip_declaration_specifiers(spelling: &str) -> String { - let mut rest = spelling.trim(); - - loop { - let Some(word) = rest.split_whitespace().next() else { - return String::new(); - }; - - if !DECLARATION_SPECIFIERS.contains(&word) || word.len() == rest.len() { - return rest.trim().to_string(); - } - - rest = rest[word.len()..].trim_start(); - } -} - /// One fact, or `None` for a binding the index has no use for. /// /// A free function rather than a method so that the borrow of the fact list and the borrow of the scope tree /// cannot be confused for each other while the walk is filling one from the other. +/// **The arguments a `std::pair`/`std::tuple` declaration's braced initialiser fixes.** The fact builder has no +/// index, so it reads only the shapes whose type the syntax itself states: a literal element. `std::pair pair{1, 2}` +/// is `std::pair` before any lookup; without this the fact kept the bare class name and every member stayed +/// `_T1`/`_T2`. Elements this cannot type leave the written name alone — a partial instantiation is worse than none. +fn a_standard_braced_deduction( + root: &CppSyntaxNode, + binding: &Binding, + written: &ComputedType, +) -> Option { + let ComputedType::Named(name) = written else { + return None; + }; + let plain = name.rsplit("::").next().unwrap_or(name); + if !matches!(plain, "pair" | "tuple") || name.contains('<') { + return None; + } + let declarator = sema::types::declarator_declaring(root, binding.name_range)?; + let parent = declarator.parent()?; + let initializer = parent + .children() + .find(|node| CppInitializer::can_cast(node.kind().into()))?; + let list = initializer + .children() + .find(|node| CppInitListExpr::can_cast(node.kind().into()))?; + let mut elements = Vec::new(); + for element in list.children() { + let text = element.text().to_string(); + let text = text.trim(); + // Only the shapes whose type the syntax states. `std::string{"three"}` is a construction, not a literal, + // and answering `int` for it would instantiate a type the program does not have. + let is_a_literal = text.starts_with('"') + || text.starts_with('\'') + || text == "true" + || text == "false" + || text == "nullptr" + || text.starts_with(|character: char| character.is_ascii_digit()) + || text.starts_with(['+', '-']); + if !is_a_literal { + return None; + } + elements.push(ComputedType::named(literal_type(text), Vec::new())); + } + if elements.is_empty() || (plain == "pair" && elements.len() != 2) { + return None; + } + Some(ComputedType::named(name.clone(), elements)) +} + fn fact_for( root: &CppSyntaxNode, shapes: &DeclarationShapes, @@ -3874,6 +3872,11 @@ fn fact_for( // scope in the file per declaration. in_namespace: Option, declarations: &Declarations<'_>, + // **The summary's local parameter arena.** Each parameter's type is lowered once from its own `CppParam` + // (structurally) and the list itself interned into this table, *before* the fact is pushed — so the fact carries + // only a `ParamsId`, and no build-time copy of the list survives on the declaration. The table is returned beside + // the facts and becomes the summary's `ParamsStore`; see [`BuiltFacts::parameters`]. + parameter_arena: &mut index::params::ParamsStore, // than the macro table, because the answer is the same for every declaration in the file and asking per ) -> Option { // A binding whose name has no identifier is a destructor, an operator, or a conversion function. Its @@ -3933,6 +3936,9 @@ fn fact_for( // branch: a consumer holding a **rendering** (the reading where the directive is resolved) has the real type, and // one that holds only this summary is told the truth. let split_by_a_directive = split_by_a_directive_with(shapes, binding); + // **The three type questions are lowered structurally, once, here.** Each reader below walks the syntax and + // answers a `ComputedType`; the fact then stores the immutable `ComputedType` that value denotes. No spelling is + // assembled, interned or parsed on this path. let type_of = if split_by_a_directive { None } else { @@ -3940,8 +3946,12 @@ fn fact_for( .or_else(|| declared_alias_target_with(shapes, binding)) // **A namespace alias, recognised by its shape.** See [`declared_namespace_alias_target_with`] for why the // character after the name cannot answer: the binding's range and the text `fact_for` is handed are not - // always the same ruler, and a header's alias was filed with no target because of it. - .or_else(|| declared_namespace_alias_target_with(root, binding)) + // always the same ruler, and a header's alias was filed with no target because of it. A namespace name is + // a name as far as the type layer is concerned, so it is a `ComputedType::Named`. + .or_else(|| { + declared_namespace_alias_target_with(root, binding) + .map(|name| ComputedType::named(name, Vec::new())) + }) // **A member whose type is an unnamed class body** — `union { … } U;`. The type has no spelling, so // `type_of` was `None` and every access through the member stopped there: measured on // `EmmyLuaCodeStyle`, `e.U.Start.Kind` answered "the type of `e.U` is not known here". The name used is @@ -3961,15 +3971,22 @@ fn fact_for( // **An operator's written return type is kept only when a fact may carry it** — see // [`an_operator_return_is_usable`]; this is the index's own writer, so the gate is asked here as well as in // [`declared_returns_of_in`]. + // + // **A deduced answer is the one spelling-shaped input**: the deduction layer produces the type's text, and + // it is lowered once here with the same reader the old construction edge used. It is not a CST node to + // hand over, because the answer came from a `return` expression's own spelling. if split_by_a_directive { None } else { declared_returns_of_with(shapes, binding) - .filter(|spelling| { + .filter(|written| { binding.kind != BindingKind::OperatorFunction - || an_operator_return_is_usable(root, binding, spelling) + || an_operator_return_is_usable(root, binding, written) + }) + .or_else(|| { + deduced_returns_of(root, binding) + .map(|spelling| sema::types::parse_type_spelling(&spelling)) }) - .or_else(|| deduced_returns_of(root, binding)) } }; // **The spelling that filter threw away**, for the one reader that can resolve it — see @@ -3977,19 +3994,21 @@ fn fact_for( let returns_in_the_class = if split_by_a_directive || returns.is_some() { None } else { - declared_returns_of_with(shapes, binding).filter(|spelling| { - binding.kind == BindingKind::OperatorFunction - && !an_operator_return_is_usable(root, binding, spelling) - }) + declared_returns_of_with(shapes, binding) + .filter(|written| { + binding.kind == BindingKind::OperatorFunction + && !an_operator_return_is_usable(root, binding, written) + }) + .map(|written| written.to_string()) }; let bases = { declared_bases_of_with(shapes, binding) }; // The class template's parameter names, for the members whose types are written with them. Answered from the // shapes like the four questions above it, and on a unit read it is the reason they are all asked of a table // rather than of the tree — see [`declared_template_parameters_of`]. let parameters = { declared_template_parameters_with(shapes, binding) }; - // **The constraint in front of each of those names**, from the same head — see [`DeclFact::constraints`]. A - // check at another file`s call site can only ask the summary, and names without their constraints cannot say - // whether an argument satisfied what the declaration asked for. + // **The constraint in front of each of those names**, from the same head — see [`DeclFact::constraints`] and + // [`DeclFact::constraint_facts`]. A check at another file's call site can only ask the summary, and names without + // their constraints cannot say whether an argument satisfied what the declaration asked for. let constraints = { declared_constraints_with(shapes, binding) }; // **And what each of them defaults to**, which is the other half of a use that writes fewer arguments than the // declaration has parameters — see [`DeclFact::parameter_defaults`]. @@ -4065,6 +4084,56 @@ fn fact_for( // scope it reports untrustworthy. A file whose macros are all inside conditions, or inside bodies, invokes none // at file level and keeps the file scope it earned. + // **The parameter list as CST facts, interned before the fact exists.** Each parameter's type is lowered from its + // own `CppParam` node — the specifier sequence and the declarator the tree already separates — so the parameter's + // name is never part of the type and no spelling is parsed. The declaration's template parameters are applied to + // the structured type, so a parameter written `T&&` is stored as a parameter rather than as a class called `T` (the + // structural form of [`sema::types::with_template_parameters`]). The spelling printed from the same node is kept as + // the store node's display value only: every consumer resolves + // [`crate::ProjectIndex::parameter_type`], which reads the structure. + // + // **The list-level `...` is read beside the facts**, from the same `CppParamList`: it is a token of the list rather + // than a parameter, so it is stored on the fact as [`crate::DeclFact::variadic_parameters`], independently of the + // `ParamsId` (a variadic list may have no parameter: `void f(...)`). + let declared_parameters = declared_parameter_facts_with(shapes, binding); + let variadic_parameters = declared_parameters.variadic; + let parameter_facts = { + let mut declared = declared_parameters.facts; + for parameter in &mut declared { + if let Some(node) = parameter.declaration.to_node_from_root(root) + && let Some(cpp) = CppParam::cast(node) + && let Some(written) = sema::types::type_of_a_parameter(&cpp) + { + // **The declaration's template parameters are applied structurally**, so a parameter written + // `T&&` is a parameter rather than a class called `T`, and a member list that instantiates the + // class substitutes it. The value the fact stores is the lowered `ComputedType` itself. + let written = sema::types::with_template_parameters(written, ¶meters); + parameter.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); + } + } + parameter_arena.intern(declared) + }; + + // **The type values, lowered at the construction edge.** The two `ComputedType`s above are the only place this fact ever + // sees a type, and they are lowered here with the declaration's own template parameters applied — the same step + // the parameters' types take. A declaration that stated no type carries `DeclaredType::None`, and nothing below + // this point parses a spelling or consults a table. + let lower = |written: Option| { + written.map_or(DeclaredType::None, |written| { + let written = sema::types::with_template_parameters(written, ¶meters); + DeclaredType::Computed(std::sync::Arc::new(written)) + }) + }; + let type_of = match binding.kind { + BindingKind::Variable => type_of + .as_ref() + .and_then(|written| a_standard_braced_deduction(root, binding, written)) + .or(type_of), + _ => type_of, + }; + let type_of = lower(type_of); + let returns = lower(returns); + Some(DeclFact { kind: DeclKind::from_binding_kind(binding.kind), // **Read off the binding, which is the only layer that knows it** — `DeclKind` folds an enumerator into a @@ -4087,20 +4156,29 @@ fn fact_for( // answer a *shape* cannot give, because `void f() { int x; }` and `void f() { }` differ by a declaration // that is not in a scope at all. See [`ScopeTree::declares_a_local`]. local, - type_of: type_of.map(SmolStr::from), - returns: returns.map(SmolStr::from), + type_of, + returns, + parameters: parameter_facts, + // **The list's own `...`, read from the same `CppParamList` as the facts** — see + // [`DeclFact::variadic_parameters`]. A pack parameter is not this: its marker lives on the `ParameterFact`. + variadic_parameters, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { in_namespace: in_namespace.map(Into::into), returns_in_the_class: returns_in_the_class.map(Into::into), - bases, + bases: bases.into_iter().map(SmolStr::from).collect(), // **The annotation is filled after the facts exist** — see `fill_the_reflection`, which reads the file // text once for the whole file rather than once per declaration. reflection: None, - parameters, - constraints, + parameters: parameters.into_iter().map(SmolStr::from).collect(), + constraints: constraints + .spellings + .into_iter() + .map(SmolStr::from) + .collect(), + constraint_facts: constraints.facts, requires_clause: the_requires_clause_with(shapes, binding).map(Into::into), - parameter_defaults, + parameter_defaults: parameter_defaults.into_iter().map(SmolStr::from).collect(), pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), }), @@ -4145,10 +4223,10 @@ pub(crate) fn declared_parameter_defaults_with( // **A row of "no default" is not stored.** The field is cloned and compared per fact, and most templates have no // default at all: storing the empties would put sixteen bytes on every class template in the standard library to // say nothing. - if shared.iter().any(|(_, _, default)| default.is_some()) { + if shared.iter().any(|parameter| parameter.default.is_some()) { shared .iter() - .map(|(_, _, default)| default.clone().unwrap_or_default()) + .map(|parameter| parameter.default.clone().unwrap_or_default()) .collect() } else { Default::default() @@ -4719,6 +4797,11 @@ struct DeclarationFacts<'a> { guards: SummaryGuards, /// Every fact, in the order the scopes hold them — sorted by offset once, before the guard sweep. facts: Vec, + /// **The summary's local parameter arena**, filled by [`fact_for`] as each declaration's parameters are interned. + /// Returned beside the facts so that [`crate::FileIndexer::index_tree`] can put it in the summary, and this is the + /// only place the parameter list is stored — a fact holds a `ParamsId`, never the list itself. Types need no + /// table: they are immutable values on the fact. + parameters: index::params::ParamsStore, // **Are the declarations inside function bodies wanted?** See `build_facts`: a per-file reading needs them, // a program's reading does not, and nearly half of the standard library's facts are locals. keep_locals: bool, @@ -4741,11 +4824,12 @@ impl<'a> DeclarationFacts<'a> { declarations: Declarations::of(root, errors), guards: SummaryGuards::default(), facts: Vec::new(), + parameters: index::params::ParamsStore::new(), } } - fn build(self) -> (Vec, SummaryGuards) { - // Destructured so that the walk below holds the inputs and the two outputs as separate bindings: the loop + fn build(self) -> BuiltFacts { + // Destructured so that the walk below holds the inputs and the outputs as separate bindings: the loop // pushes into `facts` while reading `shapes` and `declarations`, which a `&mut self` method could not do. let DeclarationFacts { keep_locals, @@ -4756,6 +4840,7 @@ impl<'a> DeclarationFacts<'a> { declarations, mut guards, mut facts, + mut parameters, } = self; // per declaration copies the whole file each time. @@ -4834,6 +4919,7 @@ impl<'a> DeclarationFacts<'a> { local, in_namespace.clone(), &declarations, + &mut parameters, ) { facts.push(fact); } @@ -4875,7 +4961,7 @@ impl<'a> DeclarationFacts<'a> { } else { Vec::new() }; - for (binding, scope, parameters) in qualified { + for (binding, scope, parameter_list) in qualified { // **The walker may already have filed this declaration, with no scope.** A definition written in the // declarator — `std::vector &LuaLexer::GetErrors() { … }` — is bound by the scope walker as a // plain function of this file, because the class is in a header the file only includes: its fact came out @@ -4902,12 +4988,13 @@ impl<'a> DeclarationFacts<'a> { false, None, &declarations, + &mut parameters, ) { // **The walker answered `None` for a definition's list**, because the shape it reads the declarator // from has no name (a qualified definition's name is in the specifier sequence). The pass read the // list from the declaration itself, so the fact a call site's signature is built from is complete. if fact.parameter_list().is_none() { - fact.detail_mut().parameter_list = parameters.map(Into::into); + fact.detail_mut().parameter_list = parameter_list.map(Into::into); } by_offset .entry(fact.name_range.start_offset) @@ -4952,7 +5039,11 @@ impl<'a> DeclarationFacts<'a> { // **What the four halves of `build_facts` cost**, in the order they run: the one line that says whether the // next optimisation belongs in the scope walk, in `fact_for`, or in the sweeps. - (facts, guards) + BuiltFacts { + facts, + guards, + parameters, + } } } @@ -5130,7 +5221,7 @@ fn qualified_declarations(root: &CppSyntaxNode) -> Vec<(Binding, String, Option< // shape, so a fact read through it carried `parameter_list: None` and a signature had no fallback label. declaration .get_param_list() - .map(|list| sema::call_syntax::tidy_list_text(&list.syntax().text().to_string()).0), + .map(|list| sema::call_syntax::render_parameter_list(&list)), )); } @@ -5744,9 +5835,9 @@ pub fn scope_of<'a>(scopes: &'a ScopeTree, fact: &DeclFact) -> Option<(ScopeId, /// **The template parameters a declaration can name** — what keeps "not known yet" apart from "not here". /// /// A parameter and a class of the same spelling are indistinguishable **in the type's text**, and -/// [`crate::sema::types::Type::depends_on_a_parameter`] answers only for a type that was *told* which names are +/// [`ComputedType::depends_on_a_parameter`] answers only for a type that was *told* which names are /// parameters. Nothing tells it for a member of a class template: [`DeclFact::type_of`] is the `Display` -/// rendering of a `Type` — `_Alloc` and `_Alloc::value_type` render exactly as a class of that name would — so +/// rendering of a `ComputedType` — `_Alloc` and `_Alloc::value_type` render exactly as a class of that name would — so /// the question "is this type one only instantiation can finish" **cannot be asked of the summary at all**. /// /// It can be asked of the scope tree, which is where the answer lives: `template ` opens a @@ -5834,9 +5925,9 @@ pub fn split_by_a_directive_with(shapes: &DeclarationShapes, binding: &Binding) #[cfg(test)] mod tests { - use super::tests; use super::{build_facts, by_name, template_parameters_for}; use crate::NoMacroBodies; + use crate::index; use crate::preprocess::preprocess; use crate::sema::scopes::build_scopes; use crate::summary; @@ -5887,7 +5978,7 @@ mod tests { /// **A parameter of an enclosing template is visible to everything inside it, and to nothing outside.** /// /// This is the predicate that keeps "not known yet" apart from "not here", and it has to be asked of the - /// **scope tree** rather than of the type: [`DeclFact::type_of`] is the `Display` rendering of a `Type`, so + /// **scope tree** rather than of the type: [`DeclFact::type_of`] is the `Display` rendering of a `ComputedType`, so /// `_Alloc` and a class named `_Alloc` are the same text, and `_Alloc::value_type` is a name no lookup can /// ever answer. /// @@ -5908,13 +5999,14 @@ mod tests { let root = tree.get_red_root(); let scopes = build_scopes(&root, &NoMacroBodies); - let (facts, _) = build_facts( + let facts = build_facts( &scopes, &preprocess(source, tree.get_tokens()), &root, &[], true, - ); + ) + .facts; let parameters_of = |name: &str| -> Vec { let fact = facts @@ -6067,7 +6159,9 @@ mod tests { .find(|fact| fact.name == name) .unwrap_or_else(|| panic!("{name} must be a fact")) .bases() - .to_vec() + .iter() + .map(ToString::to_string) + .collect() }; assert_eq!( @@ -6170,20 +6264,19 @@ mod tests { let (facts, _) = facts(source); let type_of = |name: &str| { - facts + let fact = facts .iter() .find(|fact| fact.name == name) - .unwrap_or_else(|| panic!("{name} must be a fact")) - .type_of - .clone() + .unwrap_or_else(|| panic!("{name} must be a fact")); + type_spelling_of(fact) }; assert_eq!(type_of("A").as_deref(), Some("basic_string")); assert_eq!(type_of("B").as_deref(), Some("basic_string")); assert_eq!( type_of("F").as_deref(), - Some("void (*)(int)"), - "the specifiers plus the declarator with the alias's own name cut out" + Some("void(int)*"), + "the alias is a pointer to a function type — the canonical display of the shape the declarator writes" ); assert_eq!(type_of("int32_t").as_deref(), Some("int")); } @@ -6253,7 +6346,7 @@ mod tests { .find(|fact| fact.name == "Widget") .expect("the class is a fact"); - assert_eq!(widget.type_of, None); + assert!(!widget.has_type_of()); assert_eq!(widget.kind, DeclKind::Type); } @@ -6319,18 +6412,149 @@ int Box::Inner::deep = 0; ); } + /// **A template head's constraint is stored twice, for two audiences** — the display spelling, and the concept + /// name with its arguments lowered from the head's own nodes. The multi-argument case is the one worth pinning: + /// the check reads the first argument (the one the abbreviated syntax does not supply), but the fact keeps + /// **both** so nothing the file wrote is lost. + #[test] + fn a_constraint_is_recorded_structurally_beside_its_spelling() { + use crate::ConstraintArgument; + use crate::index::types::{ComputedType, PrimaryType}; + + let (facts, _) = facts( + "template T>\nvoid f(T value);\n\ + template \nvoid g(U value);\n\ + template \nvoid h(V value);\n", + ); + let fact_of = |name: &str| { + facts + .iter() + .find(|fact| fact.name == name) + .unwrap_or_else(|| panic!("`{name}` must be a fact: {facts:?}")) + }; + + let f = fact_of("f"); + assert_eq!(f.constraints(), ["std::same_as"]); + let structured = f.constraint_facts()[0] + .as_ref() + .expect("`same_as` is structured"); + assert_eq!(structured.concept, "same_as"); + assert_eq!( + structured.arguments.len(), + 2, + "a multi-argument constraint keeps every argument: {structured:?}" + ); + assert_eq!( + structured.arguments[0], + ConstraintArgument::Type(ComputedType::Primary(PrimaryType::Int)) + ); + assert_eq!( + structured.arguments[1], + ConstraintArgument::Type(ComputedType::Primary(PrimaryType::Long)) + ); + + let g = fact_of("g"); + assert_eq!(g.constraints(), ["std::integral"]); + let structured = g.constraint_facts()[0] + .as_ref() + .expect("`integral` is structured"); + assert_eq!(structured.concept, "integral"); + assert!( + structured.arguments.is_empty(), + "`std::integral` writes no type argument" + ); + + let h = fact_of("h"); + assert!(h.constraints().is_empty(), "`class V` is unconstrained"); + assert!( + h.constraint_facts().is_empty(), + "an unconstrained template stores no row" + ); + } + + /// **A value argument is a value, not a type** — `SomeConcept<42>` carries `42`, and nothing in the fact claims + /// `42` is a type name. The display spelling is derived from that structured argument, so the two agree. + #[test] + fn a_constraint_value_argument_stays_a_value() { + use crate::ConstraintArgument; + + let (facts, _) = facts( + "template T>\nvoid take(T value);\n\ + template U>\nvoid keep(U value);\n", + ); + let fact_of = |name: &str| { + facts + .iter() + .find(|fact| fact.name == name) + .unwrap_or_else(|| panic!("`{name}` must be a fact: {facts:?}")) + }; + + let take = fact_of("take"); + assert_eq!(take.constraints(), ["SomeConcept<42>"]); + let structured = take.constraint_facts()[0] + .as_ref() + .expect("`SomeConcept<42>` is structured"); + assert_eq!(structured.concept, "SomeConcept"); + assert_eq!( + structured.arguments.as_ref(), + [ConstraintArgument::Value("42".into())], + "the literal is the written text, never `ComputedType::named(\"42\")`" + ); + + // **A type argument still lowers**, so the tag is not a blanket "everything is a value". + let keep = fact_of("keep"); + let structured = keep.constraint_facts()[0] + .as_ref() + .expect("`same_as` is structured"); + assert!( + matches!( + structured.arguments.first(), + Some(ConstraintArgument::Type(_)) + ), + "`same_as` writes a type: {:?}", + structured.arguments + ); + } + fn facts(source: &str) -> (Vec, summary::SummaryGuards) { let tree = CppParser::parse(source, ParserConfig::default()); assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); let root = tree.get_red_root(); - build_facts( + let built = build_facts( &build_scopes(&root, &NoMacroBodies), &preprocess(source, tree.get_tokens()), &root, &[], true, - ) + ); + (built.facts, built.guards) + } + + /// The same facts, with the parameter table their `ParamsId`s name — what a test that reads a declaration's + /// parameters needs. + fn facts_with_parameters(source: &str) -> (Vec, index::params::ParamsStore) { + let tree = CppParser::parse(source, ParserConfig::default()); + assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); + + let root = tree.get_red_root(); + let built = build_facts( + &build_scopes(&root, &NoMacroBodies), + &preprocess(source, tree.get_tokens()), + &root, + &[], + true, + ); + (built.facts, built.parameters) + } + + /// **A fact's written type or return spelling**, which is now the display edge on the value the fact carries. + fn type_spelling_of(fact: &DeclFact) -> Option { + fact.type_of.computed().map(|computed| computed.to_string()) + } + + fn returns_spelling_of(fact: &DeclFact) -> Option { + fact.returns.computed().map(|computed| computed.to_string()) } /// **The memory report's detail numbers are computed from the box, not from the struct's width.** A function's @@ -6370,6 +6594,74 @@ int Box::Inner::deep = 0; ); } + /// **The list-level `...` is a bit on the fact, read from the declaration's own `CppParamList`.** + /// + /// Four shapes, one assertion each: `void f(int, ...)` is variadic with one parameter; `void f(...)` is variadic + /// with **none** (which is why the bit cannot live in the parameter table, whose empty answer is `NONE`); a pack + /// parameter writes its marker inside the parameter and does **not** make the list variadic; and an ordinary list + /// is neither. The builder reads all four from the same list node as the facts, so the two cannot disagree. + #[test] + fn a_variadic_list_is_a_bit_on_the_fact() { + let source = "\ +void fixed(int a); +void named(int a, ...); +void only_ellipsis(...); +void forwards(double... rest); +void dots(const char* text = \"...\"); +"; + let (facts, parameters) = facts_with_parameters(source); + let fact = |name: &str| { + facts + .iter() + .find(|fact| fact.name == name) + .unwrap_or_else(|| panic!("{name} must be a fact")) + }; + + let fixed = fact("fixed"); + assert!(!fixed.variadic_parameters, "an ordinary list has no `...`"); + assert_eq!(parameters.parameters(fixed.parameters).len(), 1); + + let named = fact("named"); + assert!( + named.variadic_parameters, + "the trailing `...` is the list's, and the fact records it" + ); + assert_eq!( + parameters.parameters(named.parameters).len(), + 1, + "and it is not a parameter: `int a` is the only one" + ); + + let only_ellipsis = fact("only_ellipsis"); + assert!( + only_ellipsis.variadic_parameters, + "`(...)` is a variadic list with no parameter at all" + ); + assert_eq!( + only_ellipsis.parameters, + index::params::ParamsId::NONE, + "the empty list is `NONE`, which is exactly why the bit is on the fact" + ); + assert!(parameters.parameters(only_ellipsis.parameters).is_empty()); + + let forwards = fact("forwards"); + assert!( + !forwards.variadic_parameters, + "a pack is a parameter's marker, not the list's" + ); + let forwarded = parameters.parameters(forwards.parameters); + assert_eq!(forwarded.len(), 1); + assert!(forwarded[0].pack, "and the parameter records it"); + + let dots = fact("dots"); + assert!( + !dots.variadic_parameters, + "a `...` inside a default's string literal is not the list's token — the scan this bit replaces \ + called `void log(const char* dots = \"...\")` variadic" + ); + assert_eq!(parameters.parameters(dots.parameters).len(), 1); + } + /// **The reflection annotation a declaration was written under**, with its specifiers as the file spelled them. /// /// `UCLASS` and `UPROPERTY` expand to nothing, so the tree a fact is built from holds neither: the specifiers survive @@ -6462,7 +6754,7 @@ public: &errors, true, ) - .0, + .facts, errors, ) } @@ -6810,7 +7102,7 @@ void f(int value); fn a_function_records_what_it_returns_and_nothing_else_does() { // The other half of `type_of`, and the two are deliberately exclusive: `make` is not a `Widget` — a member // access on the *name* has nothing to look in — while a call of it has one. - let (facts, _) = facts( + let (declared_facts, _) = facts( "Widget make();\n\ Widget w;\n\ struct C { Widget member(); };\n\ @@ -6825,26 +7117,31 @@ void f(int value); ); let of = |name: &str| { - facts + declared_facts .iter() .find(|fact| fact.name == name) .unwrap_or_else(|| panic!("`{name}` is declared in the fixture")) }; - - // **A function returning a function pointer** — `int (*maker(int a))(int b);` returns `int (*)(int)`, and the - // declarator's own spelling says so (see `a_parenthesised_return_type`). Measured before: `returns int`. - let (returning, _) = { - let source = "int (*maker(int a))(int b);\nvoid (*signal(int, void (*)(int)))(int);\n"; - tests::facts(source) - }; - for (name, expected) in [("maker", "int (*)(int b)"), ("signal", "void (*)(int)")] { + let type_of = |name: &str| type_spelling_of(of(name)); + let returns_of = |name: &str| returns_spelling_of(of(name)); + + // **A function returning a function pointer** — `int (*maker(int a))(int b);` returns a pointer to a + // function taking `b` and returning `int`; the parenthesised declarator shape is read structurally by + // `a_parenthesised_return_type`. Measured before: `returns int`. + let (returning, _) = + facts("int (*maker(int a))(int b);\nvoid (*signal(int, void (*)(int)))(int);\n"); + for (name, expected) in [("maker", "int(int)*"), ("signal", "void(int)*")] { let fact = returning .iter() .find(|fact| fact.name == name) .unwrap_or_else(|| panic!("`{name}` is declared in the fixture")); - assert_eq!(fact.returns.as_deref(), Some(expected), "`{name}` returns"); + assert_eq!( + returns_spelling_of(fact).as_deref(), + Some(expected), + "`{name}` returns a pointer to a function — the canonical display of that shape" + ); } - assert_eq!(of("make").returns.as_deref(), Some("Widget")); + assert_eq!(returns_of("make").as_deref(), Some("Widget")); // **A parenthesized name keeps the return type's operators.** Lua's C API writes // `LUALIB_API const char *(luaL_tolstring) (lua_State *L, …)`; the text before the name is `*(`, which the // operator filter refused, so the fact said `const char` — and every call was then reported as returning a @@ -6852,33 +7149,29 @@ void f(int value); // `int (*through_pointer)(int)` has the same two characters and is the *other* shape: there the `*` is the // declarator's, so only a `(` **after** the operators is a parenthesized name. assert_eq!( - of("paren_name").returns.as_deref(), - Some("const char *"), + returns_of("paren_name").as_deref(), + Some("const char*"), "a parenthesized declarator name is not a function pointer" ); assert_eq!( - of("through_pointer").type_of.as_deref(), - Some("int (*)(int)"), + type_of("through_pointer").as_deref(), + Some("int(int)*"), "…and a pointer to function keeps its own shape" ); + assert_eq!(type_of("make"), None, "a function has no type of its own"); assert_eq!( - of("make").type_of, - None, - "a function has no type of its own" - ); - assert_eq!( - of("w").type_of.as_deref(), + type_of("w").as_deref(), Some("Widget"), "…and a variable returns nothing" ); - assert_eq!(of("w").returns, None); + assert_eq!(returns_of("w"), None); assert_eq!( - of("decorated").returns.as_deref(), + returns_of("decorated").as_deref(), Some("Widget"), "declaration specifiers are stripped, as they are from `type_of`" ); assert_eq!( - of("trailing").returns.as_deref(), + returns_of("trailing").as_deref(), Some("Widget"), "a trailing return type wins — it is the one the file stated, and the specifiers say `auto`" ); @@ -6888,24 +7181,24 @@ void f(int value); // line. Refusing the second is what left the hover without a return type and a caller without an input to // substitute into (reported, fig 5). assert_eq!( - of("deduced").returns.as_deref(), + returns_of("deduced").as_deref(), Some("Widget"), "a construction in a `return` states the type it returns" ); assert_eq!( - of("unclearable").returns, + returns_of("unclearable"), None, "a return this layer cannot type is still refused rather than guessed" ); - assert_eq!(of("plain").returns.as_deref(), Some("void")); + assert_eq!(returns_of("plain").as_deref(), Some("void")); // **A calling convention sits inside the pointer**, so the text before the name is `*__cdecl` and the // operator filter used to refuse it — recording `char` for MinGW's own `char *__cdecl strchr(…)`. Every // caller then read `strchr` as returning a `char`, and redis's `char *pch = strrchr(path, '/')` was reported // as a conversion that does not exist (`docs/c-support.md` §8). The operators now come from the tree, where // the convention is a word beside the `*` rather than part of it. assert_eq!( - of("conventional").returns.as_deref(), - Some("char *"), + returns_of("conventional").as_deref(), + Some("char*"), "a pointer whose calling convention stands before the name is still a pointer" ); } diff --git a/crates/cpp_code_analysis/src/sema/deduce.rs b/crates/cpp_code_analysis/src/sema/deduce.rs index 0a6cecd5..ab657e35 100644 --- a/crates/cpp_code_analysis/src/sema/deduce.rs +++ b/crates/cpp_code_analysis/src/sema/deduce.rs @@ -64,13 +64,23 @@ pub fn deduced_type_of( // question: a variable's type is its initializer's, while a function's is what its `return` statements agree // on, and agreeing is a walk this does not do. Refused with that reason rather than reported as "the question // does not apply", which would say the declaration has no placeholder at all. - if fact.returns.as_deref() == Some("auto") { + if index.computed_returns_of(fact).is_some_and(|returns| { + matches!( + returns, + index::types::ComputedType::Primary(index::types::PrimaryType::Auto) + ) + }) { return Known::Unknown(UnknownReason::UnknownType(Box::from( "a deduced return type — the return statements, not an initializer", ))); } - if fact.type_of.as_deref() != Some("auto") { + if !index.computed_type_of(fact).is_some_and(|type_of| { + matches!( + type_of, + index::types::ComputedType::Primary(index::types::PrimaryType::Auto) + ) + }) { return Known::No; } diff --git a/crates/cpp_code_analysis/src/sema/deduction.rs b/crates/cpp_code_analysis/src/sema/deduction.rs index 57cf5949..dc4efe0b 100644 --- a/crates/cpp_code_analysis/src/sema/deduction.rs +++ b/crates/cpp_code_analysis/src/sema/deduction.rs @@ -7,9 +7,9 @@ //! ``` //! //! A template is not a function until it is instantiated, and the call is what instantiates it. The resolver in -//! [`crate::sema::overload`] ranks **spellings**, so a template candidate has to arrive at it already substituted — +//! [`crate::sema::overload`] ranks **types**, so a template candidate has to arrive at it already substituted — //! that is what this module produces: the template arguments, in the order the template declares them, which -//! [`crate::sema::types::substituted_spelling`] turns into the parameter types the call is really facing. +//! [`ComputedType::substituted`] turns into the parameter types the call is really facing. //! //! # The subset, and why it is small on purpose //! @@ -17,13 +17,22 @@ //! deduced `T` the parameter is exactly the parameter //! `const T&` / `T&&` the same type seen through a reference and a cv-qualifier //! `T*` / `T&` / `T[]` a shape the argument has and the parameter names -//! deduced `T` twice if both agree, once; if they disagree, not at all — the call does not compile -//! refused anything else `std::vector`, `T::value_type`, a pack. Each is a real rule of the language and -//! each needs a unifier that this module does not have; refusing gives the caller a -//! candidate it can rank as `Unranked`, which is the quiet direction, instead of a -//! substitution that is wrong for some calls and right for others +//! `T` twice if both agree, once; if they disagree, not at all — the call does not compile +//! refused anything else `T::value_type`, a pack. Each is a real rule of the language and each needs a +//! unifier that this module does not have; refusing gives the caller a candidate it +//! can rank as `Unranked`, which is the quiet direction, instead of a substitution that +//! is wrong for some calls and right for others //! ``` //! +//! # Why the types are structured +//! +//! A deduction is a comparison of two **types**, not of two spellings: `T*` against `int *` is the same question as +//! `T*` against `int*`, and the old spelling split had to normalise whitespace to say so. The parameter side arrives +//! structurally (a declaration's facts materialize a [`ComputedType`], with the declaration's own template parameters +//! marked as [`ComputedType::TemplateParameter`] by `with_template_parameters`), and the argument side is what the +//! inference engine already worked out. Nothing here parses a spelling, and a substitution is +//! [`ComputedType::substituted`]. +//! //! # Why a failure is `None` and not a partial answer //! //! A substitution is used to *rank* a call and, in signature help, to *show* a reader what the callee's parameters are. @@ -33,6 +42,7 @@ use std::collections::HashMap; +use crate::index::types::ComputedType; use crate::sema::symbol::Known; /// **The template arguments a call fixes**, in the order the template declares them. @@ -41,9 +51,9 @@ use crate::sema::symbol::Known; /// gives too few arguments to reach every parameter that mentions one. pub(crate) fn deduce( names: &[String], - parameters: &[String], - arguments: &[Known], -) -> Option> { + parameters: &[ComputedType], + arguments: &[Known], +) -> Option> { deduce_seeded(names, parameters, arguments, &[], HashMap::new()) } @@ -61,11 +71,11 @@ pub(crate) fn deduce( /// written list is a call this module cannot read rather than a deduction to guess at. pub(crate) fn deduce_with_written( names: &[String], - parameters: &[String], - arguments: &[Known], - written: &[String], -) -> Option> { - let mut bound: HashMap = HashMap::new(); + parameters: &[ComputedType], + arguments: &[Known], + written: &[ComputedType], +) -> Option> { + let mut bound: HashMap = HashMap::new(); let mut fixed: Vec = Vec::new(); for (name, value) in names.iter().zip(written) { bound.insert(name.clone(), value.clone()); @@ -74,17 +84,36 @@ pub(crate) fn deduce_with_written( deduce_seeded(names, parameters, arguments, &fixed, bound) } +/// **A declaration's parameter type with a deduction applied** — the substitution step after [`deduce`], structural. +/// +/// `deduced` is in `names` order, which is what [`deduce`] answers with, so the pairing is positional and no text is +/// involved: [`ComputedType::substituted`] replaces each [`ComputedType::TemplateParameter`] by the type the call +/// fixed for it. +pub(crate) fn substituted( + type_of: &ComputedType, + names: &[String], + deduced: &[ComputedType], +) -> ComputedType { + let bindings: Vec<(smol_str::SmolStr, ComputedType)> = names + .iter() + .cloned() + .map(smol_str::SmolStr::from) + .zip(deduced.iter().cloned()) + .collect(); + type_of.substituted_by_bindings(&bindings) +} + /// The deduction itself, with a set of names already fixed. fn deduce_seeded( names: &[String], - parameters: &[String], - arguments: &[Known], + parameters: &[ComputedType], + arguments: &[Known], // **The names the call wrote**, which are fixed rather than deduced: `f(1)` states `T`, and the argument's // `int` converts to it instead of disagreeing with it. They are a list of their own rather than "whatever is already // bound", because a name bound by an *earlier argument* must still agree with the next one. fixed: &[String], - mut bound: HashMap, -) -> Option> { + mut bound: HashMap, +) -> Option> { let is_fixed = |name: &str| fixed.iter().any(|written| written == name); if names.is_empty() { return None; @@ -100,44 +129,13 @@ fn deduce_seeded( let parameter = the_shape_of(parameter); let argument = the_shape_of(argument); - // **The parameter is exactly a template parameter.** The whole of the commonest case. - // - // **A written template argument is not deduced.** `f(1)` fixes `T = long`, and the argument's `int` does - // not disagree with it — it converts to it. Deducting anyway made a written argument and an argument type that - // are not identical a refusal, which is the opposite of what the call means. - if names.iter().any(|name| name == ¶meter) { - if is_fixed(¶meter) { - continue; - } - if !bind(&mut bound, ¶meter, &argument) { - return None; - } - continue; - } - - // **The parameter names a template parameter inside a shape**: `T*`, `T&`, `T[]`. The argument has to have the - // same shape before and after the name, and the part where the name was is its argument. - if let Some((before, name, after)) = around_a_name(¶meter, names) { - // A name the call already wrote is fixed — see the note above. - if is_fixed(&name) { - continue; - } - let Some(rest) = argument.strip_prefix(&before) else { - continue; - }; - let Some(rest) = rest.strip_suffix(&after) else { - continue; - }; - if rest.is_empty() { - continue; - } - if !bind(&mut bound, &name, rest) { - return None; - } - continue; + // **A reference and a cv-qualifier are not part of the deduced shape**, which is why both sides are peeled + // first: `const T&` against a `std::string` argument is the question `T` against `std::string`. + match bind_inside(&mut bound, parameter, argument, names, &is_fixed) { + Some(_) => {} + // A parameter that names no template parameter in a way this can split binds nothing. + None => return None, } - - // Anything else mentions no Template parameter in a way this can split, and binds nothing. } // Every declared parameter must have a value: a substitution missing one is not an instantiation. @@ -148,85 +146,137 @@ fn deduce_seeded( Some(deduced) } -/// Bind one name, and refuse a second deduction that disagrees — `f(T, T)` called with `int` and `long` does not -/// compile, and the analysis should not pretend it does. -fn bind(bound: &mut HashMap, name: &str, argument: &str) -> bool { - match bound.get(name) { - Some(known) => known == argument, - None => { - bound.insert(name.to_string(), argument.to_string()); - true +/// **Bind whatever template parameters `parameter` names, matching its shape against `argument`.** +/// +/// `Some(true)` when something was bound (or was already fixed), `Some(false)` when this parameter mentions no template +/// parameter, and `None` when a name was bound twice with two different meanings — `f(T, T)` called with `int` and +/// `long` does not compile, and the analysis should not pretend it does. +fn bind_inside( + bound: &mut HashMap, + parameter: &ComputedType, + argument: &ComputedType, + names: &[String], + is_fixed: &dyn Fn(&str) -> bool, +) -> Option { + // **The parameter is exactly a template parameter.** The whole of the commonest case. + if let ComputedType::TemplateParameter(name) = parameter + && names.iter().any(|known| known == name.as_str()) + { + if is_fixed(name) { + return Some(true); } + return bind(bound, name, argument).then_some(true); } -} -/// **`T*` as `("", "T", "*")`** — the text before and after the first template parameter the spelling names. -fn around_a_name(parameter: &str, names: &[String]) -> Option<(String, String, String)> { - for name in names { - let mut from = 0usize; - while let Some(at) = parameter[from..].find(name.as_str()) { - let start = from + at; - let end = start + name.len(); - let before = ¶meter[..start]; - let after = ¶meter[end..]; - // Only a **whole word**: `T` must not match inside `Type`. - let whole_start = start == 0 - || !parameter[..start] - .chars() - .next_back() - .is_some_and(|character| character.is_alphanumeric() || character == '_'); - let whole_end = end == parameter.len() - || !parameter[end..] - .chars() - .next() - .is_some_and(|character| character.is_alphanumeric() || character == '_'); - if whole_start && whole_end && !(before.is_empty() && after.is_empty()) { - return Some(( - before.trim().to_string(), - name.clone(), - after.trim().to_string(), - )); + // **C's record tag is not part of a deduced shape** — [`the_shape_of`] peels a whole argument, and this covers + // the interior of `Pointer { ElaboratedRecord }`: `struct T *` against an `int *` is the question `T` against + // `int`, exactly as it was when the reader dropped the keyword. + if let ComputedType::ElaboratedRecord { of, .. } = parameter { + return bind_inside(bound, of, argument, names, is_fixed); + } + if let ComputedType::ElaboratedRecord { of, .. } = argument { + return bind_inside(bound, parameter, of, names, is_fixed); + } + + match (parameter, argument) { + // **A bare name has no arguments to pair**, so it is not a shape this can bind inside; two of them are the + // same question rather than a deduction. + (ComputedType::Named(_), ComputedType::Named(_)) => Some(false), + // A name is not a shape: two different class templates are not unified, and the arguments are paired + // positionally only when the names agree. + (ComputedType::Generic(written), ComputedType::Generic(found)) => { + if written.name != found.name || written.arguments.len() != found.arguments.len() { + Some(false) + } else { + let mut any = false; + for (parameter, argument) in written.arguments.iter().zip(found.arguments.iter()) { + any |= bind_inside(bound, parameter, argument, names, is_fixed)?; + } + Some(any) } - from = end; } + (ComputedType::Pointer(written), ComputedType::Pointer(found)) => { + bind_inside(bound, written, found, names, is_fixed) + } + ( + ComputedType::Reference { + to: written, + rvalue: written_rvalue, + }, + ComputedType::Reference { + to: found, + rvalue: found_rvalue, + }, + ) if written_rvalue == found_rvalue => bind_inside(bound, written, found, names, is_fixed), + ( + ComputedType::Array { + of: written, + extent: written_extent, + }, + ComputedType::Array { + of: found, + extent: found_extent, + }, + ) if written_extent == found_extent => bind_inside(bound, written, found, names, is_fixed), + (ComputedType::Pack(written), ComputedType::Pack(found)) => { + bind_inside(bound, written, found, names, is_fixed) + } + (ComputedType::Qualified(written), ComputedType::Qualified(found)) + if written.is_const == found.is_const && written.is_volatile == found.is_volatile => + { + bind_inside(bound, &written.of, &found.of, names, is_fixed) + } + (ComputedType::Function(written), ComputedType::Function(found)) + if written.parameters.len() == found.parameters.len() => + { + let mut any = bind_inside(bound, &written.returns, &found.returns, names, is_fixed)?; + for (parameter, argument) in written.parameters.iter().zip(found.parameters.iter()) { + any |= bind_inside(bound, parameter, argument, names, is_fixed)?; + } + Some(any) + } + // Everything else mentions no template parameter this can split, or has a shape the argument does not. Either + // way nothing is bound, and the caller's own arity of answers is unchanged: a name left unbound is a refusal. + _ => Some(false), } - None } -/// A spelling without the reference and cv-qualifiers a call does not choose on — the same normalisation the resolver -/// ranks with, kept here so that a deduction and a rank agree about what two types are. -fn the_shape_of(spelling: &str) -> String { - let mut text = spelling.trim().to_string(); - loop { - let trimmed = text.trim(); - if let Some(before) = trimmed - .strip_suffix("&&") - .or_else(|| trimmed.strip_suffix('&')) - { - text = before.trim_end().to_string(); - } else { - break; +/// Bind one name, and refuse a second deduction that disagrees — `f(T, T)` called with `int` and `long` does not +/// compile, and the analysis should not pretend it does. +fn bind(bound: &mut HashMap, name: &str, argument: &ComputedType) -> bool { + match bound.get(name) { + Some(known) => known == argument, + None => { + bound.insert(name.to_string(), argument.clone()); + true } } +} + +/// A type without the reference and cv-qualifiers a call does not choose on — the same normalisation the resolver +/// ranks with, kept here so that a deduction and a rank agree about what two types are. C's record tag is peeled +/// too: `struct point` and `point` are one type to the language, and the tag is `sema::convert`'s evidence rather +/// than a shape a deduction binds against. +fn the_shape_of(type_of: &ComputedType) -> &ComputedType { + let mut shape = type_of; loop { - let trimmed = text.trim_start(); - if let Some(after) = trimmed - .strip_prefix("const ") - .or_else(|| trimmed.strip_prefix("volatile ")) - { - text = after.trim_start().to_string(); - } else { - break; - } + shape = match shape { + ComputedType::Reference { to, .. } => to, + ComputedType::Qualified(qualified) if qualified.is_const || qualified.is_volatile => { + &qualified.of + } + ComputedType::ElaboratedRecord { of, .. } => of, + other => return other, + }; } - text.split_whitespace().collect::>().join(" ") } /// **The template parameters a declaration owns**, read from the text before it. /// /// A heuristic, and stated as one — the same one `signature.rs` grew for the same reason: /// `DeclFact` has no template header, so the nearest `template` before the declaration's name is -/// the only evidence there is. +/// the only evidence there is. The answer is **names**, not types: it is the key set the structured deduction above +/// binds, and it travels with a declaration rather than with a type. pub fn template_parameters_before(source: &str, name_offset: usize) -> Vec { let before = &source[..name_offset.min(source.len())]; let Some(at) = before.rfind("template") else { @@ -282,23 +332,31 @@ mod tests { use super::*; use crate::sema; - fn yes(spelling: &str) -> Known { - Known::Yes(spelling.to_string()) + /// The tests' own notation for a type — a product path never parses a spelling, but a fixture says `int` more + /// readably than a constructor tree would. The declaration's template parameter names are applied, because that is + /// what the fact builder does before a type reaches a deduction. + fn a_type(spelling: &str) -> ComputedType { + let parsed = sema::types::parse_type_spelling(spelling); + sema::types::with_template_parameters(parsed, &["T", "U", "N", "_Tp", "_Args"]) + } + + fn yes(spelling: &str) -> Known { + Known::Yes(a_type(spelling)) } fn names(values: &[&str]) -> Vec { values.iter().map(|value| (*value).to_string()).collect() } - fn parameters(values: &[&str]) -> Vec { - values.iter().map(|value| (*value).to_string()).collect() + fn parameters(values: &[&str]) -> Vec { + values.iter().map(|value| a_type(value)).collect() } #[test] fn the_parameter_that_is_just_the_parameter_is_the_commonest_case() { assert_eq!( deduce(&names(&["T"]), ¶meters(&["T"]), &[yes("int")]), - Some(names(&["int"])) + Some(vec![a_type("int")]) ); } @@ -310,7 +368,7 @@ mod tests { ¶meters(&["const T&"]), &[yes("std::string")] ), - Some(names(&["std::string"])) + Some(vec![a_type("std::string")]) ); } @@ -318,7 +376,7 @@ mod tests { fn a_shape_is_carried_by_the_argument_and_the_name_is_what_is_inside_it() { assert_eq!( deduce(&names(&["T"]), ¶meters(&["T*"]), &[yes("int*")]), - Some(names(&["int"])) + Some(vec![a_type("int")]) ); } @@ -330,7 +388,7 @@ mod tests { ¶meters(&["T", "T"]), &[yes("int"), yes("int")] ), - Some(names(&["int"])), + Some(vec![a_type("int")]), "two deductions that agree are one deduction" ); assert_eq!( @@ -355,7 +413,7 @@ mod tests { yes("int") ], ), - Some(names(&["int"])), + Some(vec![a_type("int")]), "the second parameter still fixes T" ); } @@ -376,16 +434,16 @@ mod tests { #[test] fn a_single_level_template_id_is_deduced_by_what_surrounds_the_name() { - // The split `around_a_name` makes is "everything before the name" and "everything after it", so a one-level - // template-id is a shape like any other: `vector` against `vector` leaves `int` where `T` was. The - // first version of this test asserted a refusal here, which was wrong about what this can do. + // The structural walk pairs a class template's arguments positionally, so a one-level template-id is a shape + // like any other: `vector` against `vector` binds `T` to `int`. The first version of this test + // asserted a refusal here, which was wrong about what this can do. assert_eq!( deduce( &names(&["T"]), ¶meters(&["std::vector"]), &[yes("std::vector")] ), - Some(names(&["int"])) + Some(vec![a_type("int")]) ); } @@ -399,9 +457,9 @@ mod tests { &names(&["_Tp", "_Args"]), ¶meters(&["_Args&&"]), &[yes("int")], - &names(&["Resource"]), + &[a_type("Resource")], ), - Some(names(&["Resource", "int"])), + Some(vec![a_type("Resource"), a_type("int")]), "`_Tp` comes from the call's own ``; `_Args` from the argument" ); @@ -411,9 +469,9 @@ mod tests { &names(&["T"]), ¶meters(&["T"]), &[yes("int")], - &names(&["long", "extra"]), + &[a_type("long"), a_type("extra")], ), - Some(names(&["long"])), + Some(vec![a_type("long")]), "the first written argument is the first template parameter's" ); } @@ -427,7 +485,7 @@ mod tests { &[yes("std::map")] ), None, - "`std::map` does not begin with `std::vector<`, so nothing binds and the answer is no" + "`std::map` does not name `std::vector`, so nothing binds and the answer is no" ); } } diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index 23ea1a6d..30dc4fe7 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -42,18 +42,19 @@ //! are — stay with [`ProjectIndex`], which is the one implementation of them. The model's reason to exist is narrow //! and hard: it is the only thing that holds both this file's tree **and** a way to get another's. -use crate::DeclFact; +use crate::DeclKind; use crate::FileView; +use crate::ProjectMember; use crate::completion; use crate::sema; use std::cell::RefCell; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::path::{Path, PathBuf}; use cpp_parser::CppSyntaxNode; use crate::index::project::{self, MemberList, ProjectIndex}; -use crate::sema::types::Type; +use crate::index::types::ComputedType; use crate::{Known, ScopeTree}; /// **A file, the index, and a way to read another file** — see the module documentation. @@ -77,6 +78,9 @@ pub struct SemanticModel<'a> { /// **What `members_of` was asked, and what it answered** — a class's members do not change during one file's checks, and /// the same class is asked once per member access. See `members_of` for the measurement that made this necessary. members: RefCell>>, + /// The same answers keyed by the **computed** type, so a caller entering through `members_of_computed` does not + /// stringify its arguments on every request. This is the computation-side memo; the index has no part in it. + computed_members: RefCell>>, /// **This file's declaration table**, built at most once for the model's lifetime. /// /// Every member query used to build one for itself: the table is a pass over the whole tree, and a pull asks @@ -110,6 +114,7 @@ impl<'a> SemanticModel<'a> { resolver: RefCell::new(resolver), types: project::TypeMemo::default(), members: RefCell::new(BTreeMap::new()), + computed_members: RefCell::new(HashMap::new()), shapes: sema::declarations::ShapeTable::new(), } } @@ -124,7 +129,7 @@ impl<'a> SemanticModel<'a> { /// map and pass the recursion through unfiltered — so `e.U.Start.Kind` re-deduced the `auto` declaration behind /// `e` eleven times, and a 2 800-line file was 382 questions that cost 5 923 ms. The map is now the same one /// [`project::type_of_expression_memoed`] consults for every sub-expression. - pub fn type_of(&self, expression: &CppSyntaxNode) -> Known<(Type, PathBuf)> { + pub fn type_of(&self, expression: &CppSyntaxNode) -> Known<(ComputedType, PathBuf)> { // **A/B switch, kept**: `CPPLS_NO_INFERENCE=1` answers every question `Unknown`, which is the only way to // measure what the rules cost *without* the inference they do — the difference between this and the normal // run is the inference layer's share of a diagnostics pull, and it is what says whether the next work is in @@ -148,6 +153,77 @@ impl<'a> SemanticModel<'a> { ) } + /// **A member's type in the computation layer**: the stored handle materialized once, then the member's own + /// instantiation bindings applied structurally. No spelling is parsed and no type is interned. + pub fn computed_type_of_member(&self, member: &ProjectMember) -> Option { + let fact = self.index.member_fact(member)?; + let base = fact.type_of.as_computed()?; + Some(match &member.substitution { + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), + None => base, + }) + } + + /// **A member's return type in the computation layer** — [`SemanticModel::computed_type_of_member`]'s other + /// half, for the member functions whose declared type is the one they return. + pub fn member_returns(&self, member: &ProjectMember) -> Option { + let fact = self.index.member_fact(member)?; + let base = fact.returns.as_computed()?; + Some(match &member.substitution { + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), + None => base, + }) + } + + /// **A member's name**, resolved through the index — the accessor a consumer uses where it used to read + /// `member.fact.name`. + pub fn member_name<'m>(&'m self, member: &'m ProjectMember) -> &'m str { + self.index.member_name(member) + } + + /// **A member's kind**, resolved through the index. + pub fn member_kind(&self, member: &ProjectMember) -> Option { + self.index.member_kind(member) + } + + /// **A member's written type, substituted with its instantiation** — the display edge. + pub fn member_type_spelling(&self, member: &ProjectMember) -> Option { + self.index.member_type_spelling(member) + } + + /// **A member's written return type, substituted with its instantiation** — the display edge. + pub fn member_returns_spelling(&self, member: &ProjectMember) -> Option { + self.index.member_returns_spelling(member) + } + + /// **A member's parameter list, substituted with its instantiation** — `(int value)` for `push_back` on a + /// `std::vector`. + pub fn member_parameter_list(&self, member: &ProjectMember) -> Option { + self.index.member_parameter_list(member) + } + + /// **The members of a computed type**, with its arguments kept as data rather than re-parsed from a spelling. + /// The current index entry still takes the written class string; this method is the computation-side entry point + /// the per-member substitution view will use. + pub fn members_of_computed(&self, class: &ComputedType) -> Known { + if let Some(answer) = self.computed_members.borrow().get(class) { + return answer.clone(); + } + let listed = project::members_of_inner( + &self.shapes, + self.index, + self.scopes, + self.root, + self.path, + &class.to_string(), + ); + let answer = project::substituted_members_for(self.index, self.path, class, listed); + self.computed_members + .borrow_mut() + .insert(class.clone(), answer.clone()); + answer + } + /// **The members of a class, inherited ones included** — see [`project::members_of`]. /// pub fn members_of(&self, class: &str) -> Known { @@ -166,7 +242,10 @@ impl<'a> SemanticModel<'a> { } fn members_of_uncached(&self, class: &str) -> Known { - let listed = project::members_of_with( + // **The computation layer reads the uncached answer.** The index's member-list cache is a project-wide + // memo; this model is the request. Two caches for one question is how a stale substitution outlives the + // request that made it, so `members` above is the only memo on this path. + let listed = project::members_of_inner( &self.shapes, self.index, self.scopes, @@ -184,7 +263,7 @@ impl<'a> SemanticModel<'a> { /// from [`crate::completion::the_class_after_the_operator`], which `ptr->` completion has used since the smart /// pointers landed. `undefined-field` asks it for an arrow, which it used to skip outright: "an arrow is not /// evidence" was the right answer while nothing here could follow one. - pub fn the_class_after_an_arrow(&self, written: &Type) -> Option<(String, bool)> { + pub fn the_class_after_an_arrow(&self, written: &ComputedType) -> Option<(String, bool)> { completion::the_class_after_the_operator( self.index, self.scopes, @@ -201,7 +280,7 @@ impl<'a> SemanticModel<'a> { /// chain: measured on `test_module`'s `import std;` file, `members_of("std::vector")` is **ten bases and 583 ms** /// of walking for a class whose own list is empty. A check that only needs the class's own constructors — /// `assign-type-check` — was paying that on every pull. See [`project::own_members_of`]. - pub fn own_members_of(&self, class: &str) -> Known> { + pub fn own_members_of(&self, class: &str) -> Known> { project::own_members_of_with( &self.shapes, self.index, diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 81f6d85b..79c42e03 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -35,9 +35,10 @@ //! ranking it as `Exact` would let it win an argument it knows nothing about. So it is its own rank: it neither wins //! nor loses, and a candidate that has one can win only by being the sole viable candidate. +use crate::index; +use crate::index::types::{ComputedType, PrimaryType}; use crate::sema; use crate::sema::symbol::Known; -use crate::sema::types::parse_type_spelling; /// **How well one argument matches one parameter**, best first. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] @@ -55,12 +56,32 @@ pub(crate) enum Match { NotViable, } +/// **A declaration's parameters as a caller hands them to the resolver** — the structured types in order, and the +/// list-level `...`, which is a property of the declaration rather than of any one parameter. +/// +/// This is the boundary type of [`crate::Session::the_declaration_a_call_means`]: a caller that holds a declaration's +/// facts resolves them once with [`crate::ProjectIndex::parameter_type`] +/// ([`crate::ProjectIndex::parameter_types_of`] does the whole list) and passes the values. There is deliberately no +/// spelling here — a resolver that took text would be a resolver that parsed it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DeclaredParameters { + pub types: Vec, + pub variadic: bool, +} + +impl DeclaredParameters { + pub fn new(types: Vec, variadic: bool) -> DeclaredParameters { + DeclaredParameters { types, variadic } + } +} + /// **One candidate** — a declaration a call could be calling. #[derive(Clone, Debug)] pub(crate) struct Candidate { - /// The parameter spellings, in order. A spelling rather than a [`crate::sema::types::Type`] because the callers - /// have spellings and the parse is cheap; see [`rank`]. - pub(crate) parameters: Vec, + /// The parameter types, in order, **as structures**. The callers that have a declaration's facts materialize + /// them once ([`crate::ProjectIndex::parameter_type`]); the CST callers read them from the parameter nodes. A + /// spelling is never the input here: [`rank`] compares types, not text. + pub(crate) parameters: Vec, /// Does the parameter list end in `...`? Then any number of arguments may follow. pub(crate) variadic: bool, /// What to show a reader when this candidate is chosen: the spelling of the signature. @@ -69,20 +90,20 @@ pub(crate) struct Candidate { /// [`choose`] — which is the language's rule and the reason `f(1)` means `f(int)` when both `f(int)` and a /// `template f(T)` are in view. pub(crate) is_a_template: bool, - /// **What the declaration wrote**, before substitution — the spellings partial ordering compares. Empty for an - /// ordinary function. - pub(crate) declared: Vec, - /// The template's parameter names, for deducing one declaration's spellings from another's. + /// **What the declaration wrote**, before substitution — the types partial ordering compares, structurally. Empty + /// for an ordinary function. + pub(crate) declared: Vec, + /// The template's parameter names, for deducing one declaration's types from another's. pub(crate) template_parameters: Vec, /// **How many parameters a call must supply** — the ones without a default argument. Equal to /// `parameters.len()` until a caller says otherwise, because the defaulted count is not in the type - /// spellings this candidate is built from. + /// structures this candidate is built from. pub(crate) required: usize, } impl Candidate { - /// The candidate an ordinary declaration writes: `void f(int, ...)` as `["int"]` and `variadic`. - pub(crate) fn new(parameters: Vec, variadic: bool, signature: String) -> Self { + /// The candidate an ordinary declaration writes: `void f(int, ...)` as `[int]` and `variadic`. + pub(crate) fn new(parameters: Vec, variadic: bool, signature: String) -> Self { Self { required: parameters.len(), parameters, @@ -95,8 +116,8 @@ impl Candidate { } /// **The same candidate, with the parameters a call must supply.** A caller that has the declaration's - /// *spelling* can count the defaulted parameters — see [`defaults_in`] — and a defaulted tail is exactly what - /// makes a two-parameter overload reachable from a one-argument call. + /// [`crate::index::params::ParameterFact`]s knows which ones carry a default (`default_value`), and a defaulted + /// tail is exactly what makes a two-parameter overload reachable from a one-argument call. pub(crate) fn with_required(mut self, required: usize) -> Self { self.required = required.min(self.parameters.len()); self @@ -108,11 +129,11 @@ impl Candidate { self } - /// **The same candidate, with what the declaration wrote** — the spellings and the template names partial ordering - /// needs, kept beside the substituted ones the ranking uses. + /// **The same candidate, with what the declaration wrote** — the structured types and the template names partial + /// ordering needs, kept beside the substituted ones the ranking uses. pub(crate) fn with_declaration( mut self, - declared: Vec, + declared: Vec, template_parameters: Vec, ) -> Self { self.is_a_template = !template_parameters.is_empty(); @@ -124,11 +145,11 @@ impl Candidate { /// **Can a call with this many arguments reach this candidate?** /// /// One rule is stated in the conservative direction: a parameter list that is longer than the argument list is - /// **viable**, because the extra parameters may have defaults and the default arguments are not in the spelling + /// **viable**, because the extra parameters may have defaults and the default arguments are not in the structure /// this reads. Treating them as "no" would delete the overload a program chose — `void f(int, int = 0);` is a /// real candidate for `f(1)`. fn takes(&self, arguments: usize) -> bool { - // **A default argument is a parameter the call may leave off, and the spelling says which ones.** Without the + // **A default argument is a parameter the call may leave off, and the fact says which ones.** Without the // count, `append(const _StringViewIsh&, size_type, size_type = npos)` was "viable" for `append(x)` and every // two- and three-parameter overload survived an arity filter it should not have. self.variadic || (arguments >= self.required && arguments <= self.parameters.len()) @@ -153,7 +174,7 @@ pub(crate) enum Choice { /// **The declarations a call can reach** — the candidates whose parameter list the arguments fit, in declaration /// order. The set [`choose`] ranks; a caller that shows a hover wants exactly these when nothing decides between them. pub(crate) fn viable_candidates( - argument_types: &[Known], + argument_types: &[Known], candidates: &[Candidate], ) -> Vec { (0..candidates.len()) @@ -171,7 +192,7 @@ pub(crate) fn viable_candidates( .collect() } -pub(crate) fn choose(argument_types: &[Known], candidates: &[Candidate]) -> Choice { +pub(crate) fn choose(argument_types: &[Known], candidates: &[Candidate]) -> Choice { let viable = viable_candidates(argument_types, candidates); if viable.is_empty() { @@ -285,7 +306,11 @@ fn better(mine: &[Match], theirs: &[Match]) -> bool { } /// **How well one argument matches one parameter** — see [`Match`]. -pub(crate) fn rank(parameter: &str, argument: &Known) -> Match { +/// +/// Both sides are **structured types**. The caller materializes a declaration's parameter from its +/// [`crate::index::params::ParameterFact`] and the argument from the inference engine, and nothing here parses a +/// spelling: the shape comparison, the promotion test and the conversion relation all read the structure. +pub(crate) fn rank(parameter: &ComputedType, argument: &Known) -> Match { let argument = match argument { Known::Yes(argument) => argument, Known::No => return Match::NotViable, @@ -298,46 +323,36 @@ pub(crate) fn rank(parameter: &str, argument: &Known) -> Match { return Match::Exact; } - if is_a_promotion(&argument_shape, ¶meter_shape) { + if is_a_promotion(argument_shape, parameter_shape) { return Match::Promotion; } - match parse_type_spelling(argument).convertible_to(&parse_type_spelling(parameter)) { + // The relation asks the question of the types themselves — the reference-and-`const` peel `the_shape_of` made is + // for *shape*, and the conversion question keeps the qualifiers that decide it. + match argument.convertible_to(parameter) { Known::Yes(()) => Match::Conversion, Known::No => Match::NotViable, Known::Unknown(_) => Match::Unranked, } } -/// **A type without the things a call does not choose on**: top-level `const`, a reference, and the whitespace around -/// them. `const T&` and `T` are one type as far as which overload a call picks. -fn the_shape_of(spelling: &str) -> String { - let mut text = spelling.trim().to_string(); - // Pointers and arrays are shape: strip the reference markers only. - loop { - let trimmed = text.trim(); - if let Some(before) = trimmed - .strip_suffix("&&") - .or_else(|| trimmed.strip_suffix('&')) - { - text = before.trim_end().to_string(); - } else { - break; - } - } - // A leading `const`/`volatile` on the object itself is not part of the choice. +/// **A type without the things a call does not choose on**: top-level `const`/`volatile` and a reference. `const T&` +/// and `T` are one type as far as which overload a call picks. +fn the_shape_of(type_of: &ComputedType) -> &ComputedType { + let mut shape = type_of; loop { - let trimmed = text.trim_start(); - if let Some(after) = trimmed - .strip_prefix("const ") - .or_else(|| trimmed.strip_prefix("volatile ")) - { - text = after.trim_start().to_string(); - } else { - break; - } + shape = match shape { + ComputedType::Reference { to, .. } => to, + ComputedType::Qualified(qualified) if qualified.is_const || qualified.is_volatile => { + &qualified.of + } + // **C's record tag is not a shape a call chooses on.** `struct point` and a `point` written without the + // keyword are one type to the language, and the tag is evidence for `sema::convert` rather than a + // difference between two candidates. + ComputedType::ElaboratedRecord { of, .. } => of, + other => return other, + }; } - text.split_whitespace().collect::>().join(" ") } /// The promotions a compiler ranks above a conversion, and only those. @@ -346,18 +361,20 @@ fn the_shape_of(spelling: &str) -> String { /// promotion, and the first version of this function said otherwise (it listed every wider integral type as a /// destination) — which made `f(long)` preferred over `f(int)` for a `short`, the opposite of what the language says. /// The other promotion is `float` to `double`. -fn is_a_promotion(from: &str, to: &str) -> bool { - const NARROW: [&str; 6] = [ - "char", - "signed char", - "unsigned char", - "short", - "short int", - "unsigned short", - ]; - const TO_INT: [&str; 2] = ["int", "unsigned int"]; - - (NARROW.contains(&from) && TO_INT.contains(&to)) || (from == "float" && to == "double") +fn is_a_promotion(from: &ComputedType, to: &ComputedType) -> bool { + let (ComputedType::Primary(from), ComputedType::Primary(to)) = (from, to) else { + return false; + }; + + (matches!( + from, + PrimaryType::Char + | PrimaryType::SignedChar + | PrimaryType::UnsignedChar + | PrimaryType::Short + | PrimaryType::UnsignedShort + ) && matches!(to, PrimaryType::Int | PrimaryType::UnsignedInt)) + || (*from == PrimaryType::Float && *to == PrimaryType::Double) } #[cfg(test)] @@ -365,15 +382,18 @@ mod tests { use super::*; use crate::sema; - fn a_type(spelling: &str) -> Known { - Known::Yes(spelling.to_string()) + /// **The tests' own notation for a type.** A product path never parses a spelling — this module's inputs are + /// `ComputedType`s built from facts or from the inference engine — but a unit test says `int` more readably than a + /// constructor tree would. + fn a_type(spelling: &str) -> Known { + Known::Yes(sema::types::parse_type_spelling(spelling)) } fn candidate(parameters: &[&str]) -> Candidate { Candidate::new( parameters .iter() - .map(|parameter| (*parameter).to_string()) + .map(|parameter| sema::types::parse_type_spelling(parameter)) .collect(), false, parameters.join(", "), @@ -494,7 +514,7 @@ mod tests { } #[test] - fn a_more_parameterful_candidate_stays_viable_because_defaults_are_not_in_the_spelling() { + fn a_more_parameterful_candidate_stays_viable_because_defaults_are_not_in_the_structure() { let candidates = vec![candidate(&["int"]), candidate(&["int", "int"])]; assert_eq!( choose(&[a_type("int")], &candidates), @@ -504,222 +524,37 @@ mod tests { } } -/// **A parameter's type without its name.** -/// -/// `int n` and `const char* s` are how parameters are written, and a type comparison has to see `int` and -/// `const char*`. The name is the last identifier when what precedes it is a type — a `const char* s` keeps its `*`, -/// which is before the name. A heuristic, stated as one: a parameter this cannot separate keeps its whole spelling, and -/// the resolver reads the pair as `Match::Unranked`, which is the quiet direction. -pub(crate) fn a_type_without_its_name(parameter: &str) -> String { - let parameter = parameter.split('=').next().unwrap_or(parameter).trim(); - let Some(last) = parameter.split_whitespace().last() else { - return parameter.to_string(); - }; - if last == parameter { - return parameter.to_string(); - } - // **A name the pointer operators are attached to** — `char *text` is how most C writes a parameter, and the - // whitespace split leaves `*text` as the last token: not an identifier, so the existing test below failed, the - // name survived, and the spelling became a type *containing* a name. `parse_type_spelling("char *text")` - // answers a `Named` that no comparison can use, so every call through such a declaration answered `Unknown`: - // measured on a C project, `void takes(char *text);` declared and never defined — the ordinary header shape — - // made `param-type-check` blind to `takes(42)`. The operators stay with the type: `char *text` minus `text` is - // `char *`. - let operators = last - .chars() - .take_while(|character| *character == '*' || *character == '&') - .count(); - if operators > 0 { - let name = &last[operators..]; - if is_an_identifier(name) { - return parameter[..parameter.len() - name.len()] - .trim_end() - .to_string(); - } - } - // **A name written inside parentheses** — `int (*callback)(int)`, `double (*row)[4]`. The declarator puts the - // name between `(*` and its `)`, and the type is the same spelling with the name taken out: `int (*)(int)`, - // `double (*)[4]`. Left in, the whole spelling is a `Named` that no comparison can use — the same failure the - // pointer case above records, for the shape a C header uses for every callback parameter. - if let Some(without) = a_pointer_to_a_named_thing(parameter) { - return without; - } - let is_a_name = is_an_identifier(last); - if is_a_name { - return parameter[..parameter.len() - last.len()] - .trim_end() - .to_string(); - } - parameter.to_string() -} - -/// **The same spelling with a parenthesised declarator's name taken out** — `int (*callback)(int)` → -/// `int (*)(int)`, `double (*row)[4]` → `double (*)[4]`. +/// **The parameter types from CST facts**, with no parameter list parsing and no spelling in sight. /// -/// `None` when the parentheses hold something that is not one identifier (`(*)(int)` needs nothing, and -/// `(*a, b)` is not a declarator). -fn a_pointer_to_a_named_thing(parameter: &str) -> Option { - let open = parameter.find("(*")?; - let rest = ¶meter[open + 2..]; - let close = rest.find(')')?; - let name = rest[..close].trim(); - if !is_an_identifier(name) { - return None; - } - Some(format!("{}(*){}", ¶meter[..open], &rest[close + 1..])) -} - -/// Is this the spelling of one identifier — a parameter's own name? -fn is_an_identifier(text: &str) -> bool { - text.chars() - .next() - .is_some_and(|character| character.is_alphabetic() || character == '_') - && text - .chars() - .all(|character| character.is_alphanumeric() || character == '_') -} - -/// **How many parameters of a `parameter_list` spelling have a default argument** — the arguments a call may leave -/// off. +/// Each fact already carries its lowered [`ComputedType`] — a declaration's parameters are values, not handles into +/// a table — so this clones it. `c_style_variadic` is the list-level `...`, which is not a parameter and therefore has +/// no fact of its own: the caller passes the bit the declaration recorded. /// -/// Counted at the spelling level, at the same top-level commas [`parameters_in`] splits on, because a default value -/// carries commas of its own: `void f(std::map m = {})` has one defaulted parameter, not two parameters. -pub fn defaults_in(parameter_list: &str) -> usize { - let inner = parameter_list - .trim() - .trim_start_matches('(') - .trim_end_matches(')'); - let mut defaults = 0usize; - let mut depth = 0i32; - let mut current = String::new(); - let count = |parameter: &str, defaults: &mut usize| { - let outside = { - let mut without = String::new(); - let mut depth = 0i32; - for character in parameter.trim().chars() { - match character { - '<' | '(' | '[' => depth += 1, - '>' | ')' | ']' => depth -= 1, - _ if depth > 0 => continue, - _ => {} - } - without.push(character); - } - without - }; - if outside.contains('=') { - *defaults += 1; - } - }; - for character in inner.chars() { - match character { - '<' | '(' | '[' => depth += 1, - '>' | ')' | ']' => depth -= 1, - ',' if depth == 0 => { - count(¤t, &mut defaults); - current.clear(); - continue; - } - _ => {} - } - current.push(character); - } - if !current.trim().is_empty() && current.trim() != "..." { - count(¤t, &mut defaults); - } - defaults -} - -/// **The parameter types in a `parameter_list` spelling**, and whether it ends in `...`. -/// -/// `(int a, const char* b = 0)` is `["int", "const char*"]`; `(Args&&... args)` is `([], true)`. The split is at a -/// comma at depth zero, because `std::pair` is one parameter; the default and the parameter's own name are -/// dropped by [`a_type_without_its_name`]. A spelling whose parentheses are unbalanced answers what it could read — -/// a caller that cannot parse a declaration is a caller that should rank it as `Unranked`, not that should panic. -pub fn parameters_in(parameter_list: &str) -> (Vec, bool) { - let inner = parameter_list - .trim() - .trim_start_matches('(') - .trim_end_matches(')'); - +/// A **pack** is one parameter whose `...` belongs to its declaration rather than to its type: the element type is +/// what the ranking compares an argument against, and a `Pack` wrapper a structural reading produced is peeled here. +pub fn parameters_in_facts( + facts: &[index::params::ParameterFact], + c_style_variadic: bool, +) -> (Vec, bool) { let mut parameters = Vec::new(); - let mut variadic = false; - let mut depth = 0i32; - let mut current = String::new(); - let take = |parameter: &str, parameters: &mut Vec, variadic: &mut bool| { - let parameter = parameter.trim(); - if parameter.is_empty() { - return; - } - // **`...` declares a pack only where the parameter writes one.** `const format_string<_Types...> _Fmt` has a - // *template* argument pack inside its type and is an ordinary parameter — dropping it as the pack erased the - // whole list for `std::format`: measured, `(const format_string<_Types...> _Fmt, _Types&&... _Args)` came back - // `([], true)` and the locale overload kept only its first parameter, which left the ranking with nothing to - // compare and `auto enenn = std::format(…)` with no type. The angles are skipped before the question is asked. - let outside_the_arguments = { - let mut without = String::new(); - let mut depth = 0i32; - for character in parameter.chars() { - match character { - '<' => depth += 1, - '>' => depth -= 1, - _ if depth > 0 => continue, - _ => {} - } - without.push(character); - } - without + let mut variadic = c_style_variadic; + for fact in facts { + let Some(type_of) = fact.type_of.as_computed() else { + continue; }; - if outside_the_arguments.contains("...") { - *variadic = true; + if fact.pack { + variadic = true; // **A pack is ranked by its element type.** `_Args&&... _Args` faces as many arguments as the call writes, - // and every one of them is `_Args&&` — so the spelling without the `...` and without the parameter's own - // name is what the ranking compares an argument against. Dropped whole (as it was), the candidate had no - // parameters at all: measured on libstdc++'s `make_unique`, whose `_Args&&...` overload ranked `Unranked` - // against a plain `size_t` one, so the call was ambiguous and `auto unique = std::make_unique(1);` - // had no type. A C-style `...` writes no type, and its element is empty — it still ends the list and adds no - // parameter. - let element = a_type_without_its_name(&outside_the_arguments.replace("...", "")); - if !element.trim().is_empty() { - parameters.push(element); - } - return; - } - parameters.push(a_type_without_its_name(parameter)); - }; - - // **The list is split by the parser when it can be**, so a comparison in a default argument (`bool ok = 1 < 2`) - // and a function-pointer parameter are one parameter each. The old walk is kept as the fallback for a spelling - // the synthetic declaration cannot parse. A C-style `...` is a token rather than a `CppParam`, so the whole-list - // guard below still supplies it. - let parsed = sema::call_syntax::parameters_in_a_written_list(parameter_list); - if parsed.is_some() { - variadic |= parameter_list.contains("..."); - } - match parsed { - Some(parts) => { - for (_, parameter) in parts { - take(¶meter, &mut parameters, &mut variadic); - } - } - None => { - for character in inner.chars() { - match character { - '<' | '(' | '[' => depth += 1, - '>' | ')' | ']' => depth -= 1, - ',' if depth == 0 => { - take(¤t, &mut parameters, &mut variadic); - current.clear(); - continue; - } - _ => {} - } - current.push(character); - } - take(¤t, &mut parameters, &mut variadic); + // and every one of them is `_Args&&`, so the element — not the pack — is what an argument is compared + // against. A C-style `...` writes no parameter at all and never reaches this arm. + parameters.push(match type_of { + ComputedType::Pack(of) => (*of).clone(), + other => other, + }); + } else { + parameters.push(type_of); } } - (parameters, variadic) } @@ -740,11 +575,11 @@ pub(crate) fn more_specialized(mine: &Candidate, theirs: &Candidate) -> bool { .declared .iter() .zip(&to.declared) - .all(|(from_spelling, to_spelling)| { + .all(|(from_type, to_type)| { sema::deduction::deduce( &from.template_parameters, - std::slice::from_ref(from_spelling), - &[Known::Yes(to_spelling.clone())], + std::slice::from_ref(from_type), + &[Known::Yes(to_type.clone())], ) .is_some() }) @@ -755,98 +590,125 @@ pub(crate) fn more_specialized(mine: &Candidate, theirs: &Candidate) -> bool { theirs_deduces_into_mine && !mine_deduces_into_theirs } +fn lowered(source: &str) -> (Vec, bool) { + use crate::cache::summary::DeclaredType; + use crate::index::params::parameter_facts_of; + use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; + + let tree = CppParser::parse(source, ParserConfig::default()); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let mut facts = parameter_facts_of(&list); + for fact in &mut facts { + let node = fact + .declaration + .to_node_from_root(&root) + .expect("the parameter node"); + let parameter = CppParam::cast(node).expect("typed parameter"); + let written = sema::types::type_of_a_parameter(¶meter).expect("a parameter type"); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); + } + parameters_in_facts(&facts, list.is_variadic()) +} + #[test] fn a_template_argument_pack_inside_a_parameter_is_not_the_parameter_pack() { - // `std::format`'s own spelling, and the bug the reader had: **any** `...` dropped the parameter, so both of its - // overloads came back with an empty list and the ranking had nothing to compare. Measured before the fix: - // `(const format_string<_Types...> _Fmt, _Types&&... _Args)` → `([], true)`. - // - // The trailing pack now contributes its **element** (`_Types&&`) rather than nothing — see `parameters_in`'s note on - // `make_unique` — while the pack *inside* `format_string<_Types...>` is still part of that parameter's own spelling. + // `std::format`'s own declaration, and the bug the spelling reader had: **any** `...` dropped the parameter, so + // both overloads came back with an empty list and the ranking had nothing to compare. The trailing pack now + // contributes its **element** (`_Types&&`) while the pack *inside* `format_string<_Types...>` is part of that + // parameter's own type. + let (parameters, variadic) = + lowered("void f(const format_string<_Types...> _Fmt, _Types&&... _Args);\n"); + assert_eq!(parameters.len(), 2); + assert_eq!(parameters[0].class_name(), Some("format_string")); + assert_eq!(parameters[0].arguments().len(), 1); assert_eq!( - parameters_in("(const format_string<_Types...> _Fmt, _Types&&... _Args)"), - ( - vec![ - "const format_string<_Types...>".to_string(), - "_Types&&".to_string() - ], - true - ) - ); - assert_eq!( - parameters_in( - "(const locale& _Loc, const wformat_string<_Types...> _Fmt, _Types&&... _Args)" - ), - ( - vec![ - "const locale&".to_string(), - "const wformat_string<_Types...>".to_string(), - "_Types&&".to_string() - ], - true - ) + parameters[1].to_string(), + "_Types&&", + "a pack is ranked by its element type" ); + assert!(variadic); // **An ordinary parameter is still ordinary**, and a real pack is still the pack — the two halves the fix has to // keep apart. + let (parameters, variadic) = lowered("void f(int first, bool ok = 1 < 2, int last);\n"); assert_eq!( - parameters_in("(int a, double b)"), - (vec!["int".to_string(), "double".to_string()], false) - ); - // **A comparison in a default argument is not a template bracket.** The old depth walk never closed it and - // merged the parameters after it; the parser keeps the list. - assert_eq!( - parameters_in("(int first, bool ok = 1 < 2, int last)"), - ( - vec!["int".to_string(), "bool".to_string(), "int".to_string()], - false - ) - ); - // **The parameter's name is not part of its type, even with no space in front of it.** `const char *format` is - // how most C writes a parameter: the whitespace split leaves `*format` as the last token, which is not an - // identifier, so the name used to survive — and a spelling that contains a name is a `Named` no comparison can - // use, which made `param-type-check` blind to every function *declared* (rather than defined) with a pointer - // parameter. Measured on a C project: `static void takes(char *text);` with `takes(42)` was silent. - assert_eq!( - parameters_in("(const char *format, ...)"), - (vec!["const char *".to_string()], true), - "a C-style variadic still ends the list, and the name goes: {:?}", - parameters_in("(const char *format, ...)") + parameters.len(), + 3, + "a comparison in a default is not a bracket" ); - assert_eq!(a_type_without_its_name("char *text"), "char *"); - assert_eq!(a_type_without_its_name("char **text"), "char **"); - assert_eq!(a_type_without_its_name("const char *text"), "const char *"); - assert_eq!(a_type_without_its_name("int &value"), "int &"); - assert_eq!(a_type_without_its_name("void *"), "void *"); - // **A name inside parentheses comes out too**, and the type it leaves is a type-id a spelling parser reads: - // `int (*)(int)` is a pointer to a function, `double (*)[4]` a pointer to an array. The name had stayed in, which - // made the whole spelling a `Named` no comparison could use — every callback parameter of a header-declared - // function answered `Unknown`. assert_eq!( - a_type_without_its_name("int (*callback)(int)"), - "int (*)(int)" + parameters, + vec![ + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Bool), + ComputedType::Primary(PrimaryType::Int), + ] ); - assert_eq!(a_type_without_its_name("double (*row)[4]"), "double (*)[4]"); - assert_eq!( - a_type_without_its_name("void (*handler)(int, const char *)"), - "void (*)(int, const char *)" - ); - // **A pack keeps its element type.** The test used to assert an empty list here, which is what made every pack - // candidate compare equal to every other one — see `parameters_in`'s note on `make_unique`. - assert_eq!( - parameters_in("(Args &&... args)"), - (vec!["Args &&".to_string()], true) + assert!(!variadic); + + // **The parameter's name is not part of its type**: `const char *format` is `const char*`, read from the node's + // own specifier sequence and declarator. + let (parameters, variadic) = lowered("void f(const char *format, ...);\n"); + assert_eq!(parameters.len(), 1); + assert_eq!(parameters[0].class_name(), None, "a pointer is not a class"); + assert_eq!(parameters[0].to_string(), "const char*"); + assert!(variadic, "a C-style variadic still ends the list"); +} + +#[test] +fn a_parameter_written_with_the_declarations_template_parameter_is_a_parameter() { + use crate::DeclaredType; + use crate::index::params::parameter_facts_of; + use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; + + // The declaration's own template parameter names applied to the **structured** type — the structural form of + // `with_template_parameters`, which is what makes a member's `T&&` substitutable. + let tree = CppParser::parse("void f(T&& value);\n", ParserConfig::default()); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let mut facts = parameter_facts_of(&list); + let node = facts[0] + .declaration + .to_node_from_root(&root) + .expect("the parameter node"); + let parameter = CppParam::cast(node).expect("typed parameter"); + let written = sema::types::type_of_a_parameter(¶meter).expect("a parameter type"); + let written = sema::types::with_template_parameters(written, &["T".to_string()]); + facts[0].type_of = DeclaredType::Computed(std::sync::Arc::new(written)); + + let (parameters, _) = parameters_in_facts(&facts, false); + assert_eq!(parameters.len(), 1); + assert!( + matches!( + ¶meters[0], + ComputedType::Reference { to, rvalue: true } if matches!(&**to, ComputedType::TemplateParameter(name) if name == "T") + ), + "`T&&` is a reference to the template parameter, not to a class called `T`: {parameters:?}" ); } #[test] fn the_more_specialized_of_two_templates_wins() { + // **A declaration's written type carries its template parameters structurally** — the fact builder applies + // `with_template_parameters`, and this notation does the same for a hand-built candidate. + let a_written_type = |spelling: &str| { + let parsed = sema::types::parse_type_spelling(spelling); + sema::types::with_template_parameters(parsed, &["T".to_string()]) + }; + let an_argument = |spelling: &str| Known::Yes(sema::types::parse_type_spelling(spelling)); // The shape that needed it: `take(T*)` and `take(T)` both deduce to `int*` for an `int*` argument, so the // ranking ties and the language's answer is partial ordering — `T*` is more specialized. - let by_pointer = Candidate::new(vec!["int*".to_string()], false, "take(T*)".to_string()) - .with_declaration(vec!["T*".to_string()], vec!["T".to_string()]); - let by_value = Candidate::new(vec!["int*".to_string()], false, "take(T)".to_string()) - .with_declaration(vec!["T".to_string()], vec!["T".to_string()]); + let by_pointer = Candidate::new(vec![a_written_type("int*")], false, "take(T*)".to_string()) + .with_declaration(vec![a_written_type("T*")], vec!["T".to_string()]); + let by_value = Candidate::new(vec![a_written_type("int*")], false, "take(T)".to_string()) + .with_declaration(vec![a_written_type("T")], vec!["T".to_string()]); assert!( more_specialized(&by_pointer, &by_value), @@ -858,7 +720,7 @@ fn the_more_specialized_of_two_templates_wins() { ); let chosen = choose( - &[Known::Yes("int*".to_string())], + &[an_argument("int*")], &[by_pointer.clone(), by_value.clone()], ); assert_eq!( @@ -871,7 +733,7 @@ fn the_more_specialized_of_two_templates_wins() { assert!(!more_specialized(&by_value, &by_value)); assert_eq!( choose( - &[Known::Yes("int*".to_string())], + &[an_argument("int*")], &[by_value.clone(), by_value.clone()] ), Choice::Ambiguous diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index ae9a37bf..99a8f4e8 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -3,7 +3,7 @@ //! **The hover card's code block is generated, never sliced.** A declaration's own text is the wrong thing to show: it //! carries the vendor's macro noise (`& _CLR_OR_THIS_CALL read(…)`), the line breaks the file happened to use, and the //! spelling of one particular declaration rather than the shape of the thing. So every character here comes from the -//! analysis's model — [`Type`]s printed by their own writer, parameters parsed out of the recorded list, the template +//! analysis's model — [`ComputedType`]s printed by their own writer, parameters parsed out of the recorded list, the template //! head built from the declaration's parameters — and this module is the **only** place the hover's code block is //! composed. //! @@ -96,10 +96,14 @@ pub struct TemplateParameter { /// /// `value` is a constant the analysis folded — an enumerator's number, a `constexpr` initializer — and is shown only /// where it is part of what the name *is*. -pub fn an_item( +/// **The renderer with its type spellings supplied by the caller.** A fact carries its own type values; the caller owns the +/// table that turns them into text. This is the boundary the string fields are being removed behind. +pub fn an_item_with( fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option, + type_of: &dyn Fn(&DeclFact) -> Option, + returns: &dyn Fn(&DeclFact) -> Option, ) -> Vec { let mut lines = Vec::new(); // **A reflection annotation is part of the declaration**, not decoration around it: `UCLASS(Blueprintable)` is what @@ -130,7 +134,7 @@ pub fn an_item( lines.push(clause.to_string()); } } - lines.push(a_line(fact, syntax, value)); + lines.push(a_line_with(fact, syntax, value, type_of, returns)); lines } @@ -210,11 +214,19 @@ fn without_comments(text: &str) -> String { } /// **The declaration's own line**, without a template head — what an overload list prints per declaration. -pub fn a_line(fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option) -> String { +pub fn a_line_with( + fact: &DeclFact, + syntax: Option<&CppDeclaration>, + value: Option, + type_of: &dyn Fn(&DeclFact) -> Option, + returns: &dyn Fn(&DeclFact) -> Option, +) -> String { + let type_of = type_of(fact); + let returns = returns(fact); match fact.kind { - DeclKind::Function => a_function(fact), - DeclKind::Type if fact.type_of.is_some() => { - let target = fact.type_of.as_deref().unwrap_or("").trim(); + DeclKind::Function => a_function(fact, returns.as_deref()), + DeclKind::Type if type_of.is_some() => { + let target = type_of.as_deref().unwrap_or("").trim(); // **A typedef of a class has itself as its recorded type.** `typedef struct { … } T;` binds one name for // both the anonymous class and the alias, and the type reader answers the name it was asked about — so // the generic alias line printed `using T = T;`, which says nothing. The source's own `typedef` line is @@ -235,18 +247,20 @@ pub fn a_line(fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option a_class(fact, syntax), - DeclKind::Variable => a_variable(fact, value, syntax), - DeclKind::Namespace => match &fact.type_of { + DeclKind::Variable => a_variable(fact, value, syntax, type_of.as_deref()), + DeclKind::Namespace => match type_of.as_deref() { Some(target) => format!("namespace {} = {target}", fact.name), None => format!("namespace {}", fact.name), }, - DeclKind::MacroLike | DeclKind::Other => a_variable(fact, value, syntax), + DeclKind::MacroLike | DeclKind::Other => { + a_variable(fact, value, syntax, type_of.as_deref()) + } } } @@ -286,7 +300,7 @@ fn a_template_head(fact: &DeclFact, syntax: Option<&CppDeclaration>) -> Option TemplateParameter { } /// **A function or method**, rebuilt: `static constexpr int f(const T& value) const & noexcept`. -fn a_function(fact: &DeclFact) -> String { +fn a_function(fact: &DeclFact, returns: Option<&str>) -> String { let mut out = String::new(); for (bit, word) in [ (DeclModifiers::STATIC, "static "), @@ -379,11 +393,7 @@ fn a_function(fact: &DeclFact) -> String { out.push_str(word); } } - if let Some(returns) = fact - .returns - .as_deref() - .filter(|returns| !returns.trim().is_empty()) - { + if let Some(returns) = returns.filter(|returns| !returns.trim().is_empty()) { out.push_str(&a_type(returns)); out.push(' '); } @@ -493,7 +503,12 @@ fn a_class_keyword(declaration: &CppDeclaration) -> Option { /// /// The initializer is not part of the interface, so it is not shown; the **value** is when the analysis folded one, /// because for an enumerator (`Red = 3`) or a `constexpr` constant the number *is* what the name means. -fn a_variable(fact: &DeclFact, value: Option, syntax: Option<&CppDeclaration>) -> String { +fn a_variable( + fact: &DeclFact, + value: Option, + syntax: Option<&CppDeclaration>, + type_of: Option<&str>, +) -> String { let mut out = String::new(); for (bit, word) in [ (DeclModifiers::STATIC, "static "), @@ -505,7 +520,7 @@ fn a_variable(fact: &DeclFact, value: Option, syntax: Option<&CppDeclaratio out.push_str(word); } } - if let Some(ty) = fact.type_of.as_deref().filter(|ty| !ty.trim().is_empty()) { + if let Some(ty) = type_of.filter(|ty| !ty.trim().is_empty()) { // **The qualifiers the fact drops.** `declared_type_of` strips `const` and `volatile` on purpose — it is a // spelling to look a class up by, and a qualifier changes nothing about which class that is — so // `static const Widget* first` recorded `Widget*`. A card that hides `const` tells the reader the variable may be @@ -566,7 +581,7 @@ fn the_qualifiers_in(syntax: Option<&CppSyntaxNode>) -> &'static str { } } -/// **A type, as the model writes it** — parsed from the recorded spelling and printed by [`Type`]'s own writer, which is +/// **A type, as the model writes it** — parsed from the recorded spelling and printed by [`ComputedType`]'s own writer, which is /// what turns `std::vector &` into `std::vector&` and drops the `typename` disambiguator. /// /// The spelling is the *input*; the output is generated. A spelling this layer cannot parse is printed back as a name, @@ -602,8 +617,8 @@ pub fn a_type(written: &str) -> String { if written.is_empty() { return String::new(); } - // **The qualifiers are part of the spelling and the model does not carry them.** `Type` answers *which class* a - // spelling names, so `const std::string&` is the same `Type` as `std::string&` — right for a member lookup, and + // **The qualifiers are part of the spelling and the model does not carry them.** `ComputedType` answers *which class* a + // spelling names, so `const std::string&` is the same `ComputedType` as `std::string&` — right for a member lookup, and // wrong for a popup, where the qualifier is the one word that says whether the object may be written through. // Measured on the reported screen: `[](auto const& value)` hovered as `auto& value`, and // `bool operator()(std::string const& left, …)` as `std::string& left`. @@ -1026,13 +1041,14 @@ mod tests { assert_eq!(tree.get_errors(), [], "the fixture must parse cleanly"); let root = tree.get_red_root(); let scopes = sema::scopes::build_scopes(&root, &NoMacroBodies); - let (facts, _) = sema::declarations::build_facts( + let built = sema::declarations::build_facts( &scopes, &preprocess(source, tree.get_tokens()), &root, &[], true, ); + let facts = built.facts; let fact = facts .iter() .find(|fact| fact.name == name) @@ -1041,7 +1057,13 @@ mod tests { // `template`, and a class's fact starts at `class`, so a range match on the fact's start finds neither. let declaration = token_at(&root, fact.name_range.start_offset) .and_then(|token| token.parent_ancestors().find_map(CppDeclaration::cast)); - an_item(fact, declaration.as_ref(), None) + an_item_with( + fact, + declaration.as_ref(), + None, + &|fact: &DeclFact| fact.type_of.computed().map(|computed| computed.to_string()), + &|fact: &DeclFact| fact.returns.computed().map(|computed| computed.to_string()), + ) } /// **A function is rebuilt**, not quoted: canonical types, the parameters' names kept, defaults said, and the @@ -1094,7 +1116,7 @@ mod tests { /// **An alias is a `using` line**, whatever the file wrote it as — the target rendered by the type writer. /// /// A typedef of a class is the exception: its recorded target is its own name, and the source's `typedef` line is - /// rendered instead so the body is not lost — see [`a_line`]. + /// rendered instead so the body is not lost — see [`a_line_with`]. #[test] fn an_alias_is_a_using_line() { assert_eq!( @@ -1129,7 +1151,7 @@ mod tests { /// **A `const` written on a type is printed back**, whichever side of the name it is on. /// - /// `Type` answers *which class* a spelling names, so `const std::string&` and `std::string&` are the same `Type` — + /// `ComputedType` answers *which class* a spelling names, so `const std::string&` and `std::string&` are the same `ComputedType` — /// correct for a member lookup and wrong for a popup, where the qualifier is the one word that says whether the /// object may be written through. Measured: `a_type("std::string const&")` printed `std::string&` and /// `a_type("auto const&")` printed `auto&`, which is how `[](auto const& value)` hovered as `auto& value` and diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 86cd1b29..14fa8f0f 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -12,108 +12,87 @@ //! const [[nodiscard]] … attributes and specifiers left in → not a type at all //! ``` //! -//! # The shape is modelled, the spelling is carried +//! # One type definition +//! +//! [`ComputedType`] is the crate's **only** type value; this module holds the syntax and spelling readers that +//! construct it, and [`crate::index::types::semantics`] holds the questions it answers. The computed forms are: //! //! ```text -//! Type::Builtin { spelling } `int`, `unsigned long long`, `bool` -//! Type::Named { name, arguments } `Widget`, `std::vector`, `T` -//! Type::TemplateParameter { name } `T` in a context where nothing has said what it stands for -//! Type::Pointer { to } `Widget*` -//! Type::Reference { to, rvalue } `Widget&`, `Widget&&` -//! Type::Array { of, extent } `int[4]`, `int[]` -//! Type::Function { returns, … } `int(int)`, `int (*)(int)` -//! Type::Pack { of } `Args...` -//! Type::Qualified { of, .. } `const Widget`, `volatile int` +//! ComputedType::Primary(PrimaryType) `int`, `unsigned long long`, `bool` +//! ComputedType::Named(name) `Widget`, `T` — a name with no template arguments +//! ComputedType::Generic { name, arguments } `std::vector`, `std::pair` +//! ComputedType::TemplateParameter(name) `T` in a context where nothing has said what it stands for +//! ComputedType::ElaboratedRecord { tag, of } `struct point`, `union value` — C's tag, kept on the type +//! ComputedType::Pointer(to) `Widget*` +//! ComputedType::Reference { to, rvalue } `Widget&`, `Widget&&` +//! ComputedType::Array { of, extent } `int[4]`, `int[]`, `int[COUNT]` +//! ComputedType::Function(function) `int(int)`, `int (*)(int)` +//! ComputedType::Pack(of) `Args...` +//! ComputedType::Qualified(of) `const Widget`, `volatile int` //! ``` //! //! Three of those exist for reasons worth stating, because each replaced a bug rather than a gap: //! -//! * **`Named` carries a name without its arguments** and the arguments beside it, which is the one distinction a +//! * **`Named` carries a name without its arguments and `Generic` beside it**, which is the one distinction a //! member query needs: `std::vector` is a *type*, `std::vector` is the *class* whose members it has, and a //! query handed the first answered "nothing declares it" — true, and useless. -//! * **`Builtin` is separate from `Named`** so that `int` is not a class called `int`. Reading it as a name made a +//! * **`Primary` is separate from `Named`** so that `int` is not a class called `int`. Reading it as a name made a //! member access on an `int` ask the index for a class by that name and report *"not declared here"*, which a //! reader takes as "this class is missing" rather than "this is not a class". //! * **`Qualified` is a wrapper** rather than a flag, because a qualifier belongs to the type it is written on: //! `const Widget*` and `Widget* const` are the same three words in two places and two different types, and only //! the position tells them apart. //! -//! The **spelling** is kept for two reasons, and "why not intern everything" is the obvious question: -//! -//! * a consumer shows the type to a user, and the answer must be *what the file wrote* — `std::size_t` and -//! `unsigned long long` are one type and two different things to read, and this layer is not entitled to rewrite -//! a file's own spelling; -//! * an **alias** is a name, not a definition: `using Int = int;` makes `Int` a type whose structure this layer does -//! not have unless it resolves the alias, which is the index's job and a separate question. -//! -//! So the structure is what is *modelled* — enough to ask "what does this type name", "what does a `*` do to it", -//! "what are its template arguments" — and the spelling is what is *carried*. Equality is by spelling, which is the -//! honest rule for a layer that does not resolve aliases: two spellings that mean one type are two answers here. +//! A name is carried as a `SmolStr` and displayed with its own spelling: a consumer shows the type a user, and the +//! answer must be *what the file wrote* — `std::size_t` and `unsigned long long` are one type and two different +//! things to read. An **alias** is a name, not a definition: `using Int = int;` makes `Int` a type whose structure +//! this layer does not have unless it resolves the alias, which is the index's job and a separate question. Equality +//! is structural, and this layer does not resolve aliases. //! //! # The two ways in //! //! ```text //! type_of_declaration(specifiers, declarator, name) the syntax: what a declaration wrote -//! parse_type_spelling("std::vector") the text: what a `DeclFact` recorded on disk +//! parse_type_spelling("std::vector") the text: what a fact/display boundary handed back //! ``` //! -//! Both are needed and neither can replace the other: a declaration in the file being edited has syntax and no -//! need of a spelling, while a declaration the *index* holds is a `String` whose file is not even open. The parser -//! guarantees exactly one thing — [`Type::class_name`] — because everything else it could get wrong is recoverable -//! and a wrong class name is not. +//! Both are needed and neither can replace the other: a declaration in the file being edited has syntax and no need +//! of a spelling, while a string that genuinely came from outside (a display consumer, a cooked rendering) has no +//! tree. The syntax reader guarantees exactly one thing — [`ComputedType::class_name`] — because everything else it +//! could get wrong is recoverable and a wrong class name is not. //! //! # What this deliberately does not do //! //! No alias resolution, no template instantiation, no `typedef` chasing, no overload resolution. Each of those is a //! query against the index and belongs where the index is; this module is the shape they are asked about. What it -//! *does* offer towards them is [`Type::substituted`], which pairs a class template's parameters with the arguments -//! a use wrote — the operation an instantiation would start from, and the one that makes +//! *does* offer towards them is [`ComputedType::substituted`], which pairs a class template's parameters with the +//! arguments a use wrote — the operation an instantiation would start from, and the one that makes //! `std::vector::size_type` answerable once `T` is known. +use crate::index; +use crate::index::types::{ArrayExtent, ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; +use crate::summary::{ConstraintArgument, ConstraintFact}; use cpp_parser::CppArrayType; +use cpp_parser::CppAstNode; use cpp_parser::CppDeclaration; use cpp_parser::CppDeclarator; use cpp_parser::CppInitDeclarator; use cpp_parser::CppNameExpr; use cpp_parser::CppParam; use cpp_parser::CppParamList; -use cpp_parser::CppPointerType; +use cpp_parser::CppTemplateArg; use cpp_parser::CppTemplateParam; use cpp_parser::CppTypeId; use cpp_parser::SourceRange; use cpp_parser::source_range; use cpp_parser::subtree_text_spaced; use cpp_parser::typed_descendants; -use std::fmt; +use smol_str::SmolStr; use std::sync::Arc; -use cpp_parser::CppAstNode; use cpp_parser::{CppSyntaxKind, CppSyntaxNode}; -/// **The first two non-whitespace characters of a node's text**, or `None` when there are fewer. -/// -/// `node.text().to_string().trim_start().starts_with("(*")` copied the whole declarator — a type with template -/// arguments can be hundreds of bytes — to compare two characters, once per function declaration of every file. The -/// question is answered from the tree's own chunks here, with no string at all. -fn first_two_written(node: &CppSyntaxNode) -> Option<(char, char)> { - let text = node.text(); - let mut offset = 0u32; - let mut first = None; - while offset < u32::from(text.len()) { - let ch = text.char_at(offset.into())?; - offset += ch.len_utf8() as u32; - if ch.is_whitespace() { - continue; - } - match first { - None => first = Some(ch), - Some(f) => return Some((f, ch)), - } - } - None -} - /// **The node's text, trimmed, in one allocation.** `text().to_string().trim().to_string()` copied the node twice for /// every declaration that reads a written spelling, and the second copy is only needed when there is something to trim. fn written_trimmed(node: &CppSyntaxNode) -> String { @@ -126,855 +105,29 @@ fn written_trimmed(node: &CppSyntaxNode) -> String { } } -/// A type inside a type, **shared rather than owned**. -/// -/// Every compound type is a tree, and inference walks that tree constantly: a `substituted`, a `decay`, a -/// `pointee`, a `class_name` — each one asks about the inside of a type and each one produces a new type. With an -/// owned child (`TypeOf`) every one of those is a **deep clone of a tree**, so asking "what is `std::map::value_type`" clones the whole spelling of `K` and `V` to look at it, and a chain of member accesses clones -/// it once per link. The cost is invisible in a test with three identifiers and dominant in a header where the -/// same type is asked about a thousand times. -/// -/// [`Arc`] makes the clone a refcount bump, and it buys three things that matter more than the atomic: -/// -/// ```text -/// 1. a sub-type can be handed out `fn inner(&self) -> TypeOf` returns a handle, not a copy -/// 2. one spelling is one allocation `std::string` built a thousand times is one allocation, not a thousand -/// 3. nothing is mutated through it `Arc` has no `get_mut` in safe code, so a type is a value -/// ``` -/// -/// The third is not a consolation prize: a type that could be mutated in place is a cache key that can change -/// under a map, and this layer hashes types. It is [`Arc`] rather than `Rc` because the index is shared between -/// the LSP's reader threads — a type crossing a thread boundary is the ordinary case here, not an exotic one. -pub type TypeOf = Arc; - -/// **A type, as a shape.** See the module documentation for why the spelling is carried beside it. -/// **The qualifiers written on a type** — `const`, `volatile`, or both. -/// -/// A wrapper on [`Type::Qualified`] recorded only *that* a type was qualified, so every spelling came out `const`: -/// `volatile S v; auto x = v;` typed `x` as `const S`, and `int f() volatile` was read as a `const` member function — -/// a different overload (`docs/worklog.md` P1-3). The two are separate bits because they are separate -/// questions: `volatile` says every access is an observable side effect, `const` says assignment is not allowed, and a -/// member list can hold `f()`, `f() const` and `f() volatile` at once. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct Qualifiers { - is_const: bool, - is_volatile: bool, -} - -impl Qualifiers { - pub const NONE: Qualifiers = Qualifiers { - is_const: false, - is_volatile: false, - }; - pub const CONST: Qualifiers = Qualifiers { - is_const: true, - is_volatile: false, - }; - pub const VOLATILE: Qualifiers = Qualifiers { - is_const: false, - is_volatile: true, - }; - - /// The qualifier a single word spells, if it is one. - pub fn of_a_word(word: &str) -> Option { - match word { - "const" => Some(Qualifiers::CONST), - "volatile" => Some(Qualifiers::VOLATILE), - _ => None, - } - } - - /// Both, in either order — `const volatile` and `volatile const` are one type. - pub fn with(self, other: Qualifiers) -> Qualifiers { - Qualifiers { - is_const: self.is_const || other.is_const, - is_volatile: self.is_volatile || other.is_volatile, - } - } - - pub fn is_const(self) -> bool { - self.is_const - } - - pub fn is_volatile(self) -> bool { - self.is_volatile - } - - pub fn is_none(self) -> bool { - !self.is_const && !self.is_volatile - } - - /// **The words when they lead the type** — `"const "`, `"volatile "`, `"const volatile "`, or nothing. - pub fn leading_words(self) -> &'static str { - match (self.is_const, self.is_volatile) { - (true, true) => "const volatile ", - (true, false) => "const ", - (false, true) => "volatile ", - (false, false) => "", - } - } - - /// **The words when they trail it** — `" const"`, `" volatile"`, `" const volatile"`, or nothing. - pub fn trailing_words(self) -> &'static str { - match (self.is_const, self.is_volatile) { - (true, true) => " const volatile", - (true, false) => " const", - (false, true) => " volatile", - (false, false) => "", - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum Type { - /// A builtin: `int`, `void`, `unsigned long long`, `decltype(auto)`. - Builtin { - spelling: String, - }, - /// A name, with the template arguments it was written with — `Widget`, `std::vector`, `T`. - /// - /// Declared separately from [`Type::TemplateParameter`] because the difference is a *fact about the context* - /// rather than about the text: `T` inside `template class vector` is a parameter, and `T` in a file - /// that has a `struct T` is a class. This variant is the reading that does not know yet; a caller that has the - /// template parameter list in hand says so, and [`Type::TemplateParameter`] is that answer. - Named { - name: String, - arguments: Vec, - }, - /// A template parameter written where nothing has said what it stands for: the `T` of a template body. - TemplateParameter { - name: String, - }, - Pointer { - to: TypeOf, - }, - Reference { - to: TypeOf, - /// `&&` rather than `&`. Kept apart because it is the one difference deduction turns on — see - /// `a_forwarding_reference_is_not_deduced`, which is the rule this field exists for. - rvalue: bool, - }, - Array { - of: TypeOf, - /// `Some(4)` for `int[4]`, `None` for `int[]`. - extent: Option, - }, - /// A function type: what it returns, and how many parameters it takes. - Function { - returns: TypeOf, - parameters: Vec, - }, - /// A `pack`: `Args...` — a template parameter that stands for several arguments. - Pack { - of: TypeOf, - }, - /// **A qualified type**: `const Widget`, `volatile int`. - /// - /// A wrapper rather than a flag on every variant, because a qualifier belongs to *the type it is written on* - /// and the position is the whole of its meaning: `const Widget*` is a pointer to a const Widget and - /// `Widget* const` is a const pointer, the same words in a different place, and the operators between them are - /// what tells the two apart. A wrapper is also the shape a peel can build at the moment it knows which type the - /// qualifier was written on, which is exactly when it reads it. - Qualified { - of: TypeOf, - qualifiers: Qualifiers, - }, -} - -/// **A pointee without its qualifiers**, and whether it had any — the shape a pointer-conversion question asks. -/// -/// `const char*` is a pointer to a *qualified* `char`, and the qualification is the whole difference between that and -/// `char*`: the first converts to the second and not the other way. Nothing else about a pointee is peeled here. -fn a_pointee_without_its_qualifiers(type_of: &TypeOf) -> (&Type, bool) { - let mut current: &Type = type_of; - let mut qualified = false; - while let Type::Qualified { of, .. } = current { - qualified = true; - current = of; - } - (current, qualified) -} - -impl Type { - pub fn builtin(spelling: impl Into) -> Type { - Type::Builtin { - spelling: spelling.into(), - } - } - - pub fn named(name: impl Into) -> Type { - Type::Named { - name: name.into(), - arguments: Vec::new(), - } - } - - /// **The class this type names**, for a caller about to ask a class question — a member list, a base chain. - /// - /// This is the method the whole module exists for. `std::vector` is a *type* and `std::vector` is the - /// *class* whose members it has; a query that was handed the first and wanted the second answered "nothing - /// declares `std::vector`" — which is true and useless. - /// - /// `None` for a type that names no class: a builtin, a pointer (the caller decays first — see - /// [`Type::decay`]), an array, a function, a template parameter. A reference **is** transparent here: C++ says - /// `r.size` on a `Widget&` is a member of `Widget`, and the reference is the binding's business, not the - /// member's. - pub fn class_name(&self) -> Option<&str> { - match self { - Type::Named { name, .. } if !name.is_empty() => Some(name), - // A reference and a qualifier are both **transparent** to this question, and C++ is why: a member of a - // `Widget&` is a member of `Widget`, and a member of a `const Widget` is a member of `Widget` — you - // cannot assign to it, which is a fact about assignment and not about the class. - Type::Reference { to, .. } | Type::Qualified { of: to, .. } => to.class_name(), - _ => None, - } - } - - /// The type's template arguments, when it has a name to hang them on. - pub fn arguments(&self) -> &[Type] { - match self { - Type::Named { arguments, .. } => arguments, - Type::Reference { to, .. } | Type::Qualified { of: to, .. } => to.arguments(), - _ => &[], - } - } - - /// **Is the object this type describes `const`** — the question an overload choice asks. - /// - /// A qualifier and a reference are both looked through, and a pointer is not: `const Widget&` is a const object, - /// `Widget&` is not, `const Widget*` is a *pointer* (which can be reassigned) to a const `Widget`. That is the - /// same rule [`Type::class_name`] states for the class, and for the same reason: the qualifier belongs to the - /// type it was written on. - /// - /// Measured on the type layer's own answers: `const std::string& s; s[0]` was answered `char&` where a compiler - /// answers `const char&`, because the member list holds both `reference operator[]` and - /// `const_reference operator[] const` and the choice was by name and arity only. - pub fn is_const(&self) -> bool { - match self { - Type::Qualified { qualifiers, .. } => qualifiers.is_const(), - Type::Reference { to, .. } => to.is_const(), - _ => false, - } - } - - /// **Is the object this type describes `volatile`** — the same rule as [`Type::is_const`], and a separate bit - /// because `volatile int` is neither a const object nor an unqualified one (`docs/worklog.md` P1-3). - pub fn is_volatile(&self) -> bool { - match self { - Type::Qualified { qualifiers, .. } => qualifiers.is_volatile(), - Type::Reference { to, .. } => to.is_volatile(), - _ => false, - } - } - - /// The qualifiers this type was written with, when it was written with any. - pub fn qualifiers(&self) -> Qualifiers { - match self { - Type::Qualified { qualifiers, .. } => *qualifiers, - Type::Reference { to, .. } => to.qualifiers(), - _ => Qualifiers::NONE, - } - } - - /// **What an expression of this type is when it is *used*** — the two conversions C++ applies before almost - /// every operator. - /// - /// * an **lvalue-to-rvalue** conversion, which drops the top-level reference: `Widget& w` used as a value is a - /// `Widget`, and a member access on it is a member of `Widget` either way; - /// * an **array-to-pointer** decay: `int arr[4]` used as a value is an `int*`, which is why `arr[0]` and - /// `p[0]` are the same question. - /// - /// Functions decay to function pointers, which is spelled rather than modelled — see [`Type::Function`], whose - /// callers are a call (`f()`) and an address-of (`&f`), and neither of them needs the pointer. - /// - /// This is deliberately **not** applied by the reader: a declaration's type is what the declaration wrote - /// (`int arr[4]` is an array), and the decay belongs to the use. A layer that decayed at the declaration - /// would report `arr` as `int*`, which is a different declaration than the one the file has. - /// # The decay is **one level**, and that is the rule rather than a simplification - /// - /// `int[2][3]` decays to a pointer to the element of the *outer* array, which is itself an array: `int[2]*`. An - /// implementation that decayed the element too would answer `int**`, a different type — and the difference - /// shows in what a subscript on it gives. It also shares the element rather than copying it, which is what - /// [`Arc`] is there for. - pub fn decay(&self) -> Type { - match self { - Type::Reference { to, .. } => to.decay(), - Type::Array { of, .. } => Type::Pointer { to: Arc::clone(of) }, - // **A qualifier survives the decay**, because the thing it qualifies does: `const int arr[4]` used as a - // value is a pointer to a const `int`. Dropping it here would make `const` disappear from exactly the - // types a `auto p = &arr;` deduces. - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(of.decay()), - qualifiers: *qualifiers, - }, - other => other.clone(), - } - } - - /// **Can a value of this type initialise one of `target`?** - /// - /// The one relation the two type checks are made of — `int x = "three";` is an assignment and `f("three")` is a - /// parameter, and both are the same question asked at a different place. Written once here so that they cannot - /// disagree, which is the rule this crate keeps having to relearn: one question, one implementation. - /// - /// # Only what is certain - /// - /// `Known::Yes` and `Known::No` are answers; `Known::Unknown` is the absence of one, and a check reports only a - /// definite `No` — see `sema::check`'s contract. So this relation is deliberately **partial**: it answers for the - /// conversions the standard makes unconditionally and refuses to guess at everything that needs more of the - /// program than two types. - /// - /// What it answers: - /// - /// ```text - /// identical after decay -> Yes `int` to `int`, `const char*` to `const char*` - /// arithmetic to arithmetic -> Yes `double` to `int`, `char` to `long` - /// array or function to pointer -> Yes `int[4]` to `int*` - /// pointer to arithmetic, or the reverse -> No `const char*` to `int` - /// any object pointer to `void*` -> Yes `int*` to `void*`, `Widget*` to `void*` - /// a pointer that drops `const` into it -> No `const char*` to `void*` - /// `void*` to an object pointer -> Unknown C converts it and C++ does not; the language is not known here - /// anything to `void`, or `void` to it -> No no object has type `void` - /// anything named, or a template parameter-> Unknown `S` may have a converting constructor - /// pointer to a different pointee -> Unknown `Derived*` to `Base*` is a real conversion - /// a reference target -> the referent's question `const int&` asked as `int` - /// ``` - /// - /// # Why a class is never an answer - /// - /// `std::string s = "x";` is a conversion *constructor* and `int n = widget;` may be a conversion *operator*, and - /// neither is visible in the two types: the first needs the class's constructors and the second needs its - /// members. Answering either from the spellings alone is the invented finding the check layer exists to avoid — - /// and `std::string s = "x";` is the most ordinary line in modern C++. - pub fn convertible_to(&self, target: &Type) -> sema::symbol::Known<()> { - use crate::sema::symbol::Known; - - let from = self.decay(); - // **A pointer does not bind to a non-const lvalue reference.** The peel below judges a reference by its - // referent, which is right for values and wrong for a pointer: `void println(ostream& __os)` called with a - // string literal is not a conversion to `ostream` at all, because the temporary a converting constructor could - // build cannot bind to a non-const reference. Left `Unknown`, the overload ranking kept - // `println(ostream&)` as a candidate for `println("…")` and the hover offered it as the call's meaning. - // A **`const`** reference is left alone: there a temporary may be built, which is a class's constructors' - // question and not this relation's. - if let Type::Reference { - to: referent, - rvalue: false, - } = target - && matches!(from, Type::Pointer { .. }) - && matches!(**referent, Type::Named { .. }) - { - return Known::No; - } - // **The target is not decayed**, and that is the whole of a measured false positive: MSVC's - // `__msvc_formatter.hpp` declares `_CharT _Fill[]`, whose type is an **array** of a template parameter, and - // decaying the target turned it into `_CharT*` — so `int` met "a pointer" and the relation answered `No` for - // a pair it cannot decide at all. Array-to-pointer is a conversion the *source* undergoes; the destination - // of an initialisation keeps whatever shape it was written with. - // - // **A reference binds to its referent**, so the question is the one about the referent. `void - // push_back(const _Ty&)` instantiated at `int` declares `const int&`, and a `const char*` argument against - // it is the same mistake as against `int` — but this relation had no arm for a `Reference` on the right and - // answered `Unknown`, which is why `anotherVec.push_back("123131")` on a `std::vector` was never - // reported while the same mistake against a by-value `int` parameter was. Nothing is invented by the peel: - // binding a value to a reference of a type it does not convert to is exactly what the language rejects. - let to = match target { - Type::Reference { to, .. } => &**to, - other => other, - }; - - // **Identical is always convertible**, before anything else is asked: a spellings-equal pair needs no rule, - // and this is what makes `int` to `int` and a pointer to its own type answer `Yes` rather than falling into - // the "different pointee" case below. - if &from == to { - return Known::Yes(()); - } - - // **`void` is not a value.** An object cannot have it, so nothing converts *to* it and it converts to - // nothing — written before the arithmetic rule, which would otherwise call `void` an arithmetic type and - // answer `Yes` for `void x = 1;`. - if from.is_void() || to.is_void() { - return Known::No; - } - - match (&from, to) { - // The standard conversions between arithmetic types, which are unconditional. - (a, b) if a.is_arithmetic() && b.is_arithmetic() => Known::Yes(()), - - // Array-to-pointer and function-to-pointer. `decay` already did this, so a pair that arrives here with - // one side an array did not come through `decay` — kept for a caller that built the types by hand. - (Type::Array { .. } | Type::Function { .. }, Type::Pointer { .. }) => Known::Yes(()), - - // **A pointer and a number are not interconvertible here.** A literal `0` is, and that is a fact about - // the *value* rather than about the type this relation is handed — so it is `Unknown`'s neighbour rather - // than its case: a caller that knows the initialiser was the literal `0` does not ask. - (Type::Pointer { .. }, b) if b.is_arithmetic() => Known::No, - (a, Type::Pointer { .. }) if a.is_arithmetic() => Known::No, - - // **Two pointers to different *builtin* pointees do not convert.** This one is decided by the shapes, which - // is why it belongs here: no class hierarchy is involved, so `const char*` cannot become `FILE*` — and the - // relation's silence made every pointer-taking overload a candidate for every pointer argument. Measured on - // `std::println("…")`: `println(ostream&)` (a pointer does not bind to a non-const reference — the rule - // above) and `println(FILE*)` (this rule) were offered as meanings of the call, while the one overload that - // takes a format string was one candidate among three. Class-to-class stays `Unknown` (a derived pointer - // converts), and a `void` pointee is decided by the arm below. - (Type::Pointer { to: from_pointee }, Type::Pointer { to: to_pointee }) => { - let (from_core, from_qualified) = a_pointee_without_its_qualifiers(from_pointee); - let (to_core, to_qualified) = a_pointee_without_its_qualifiers(to_pointee); - let is_void = |type_of: &Type| matches!(type_of, Type::Builtin { spelling } if spelling == "void"); - if is_void(to_core) - && !is_void(from_core) - && !matches!(from_core, Type::Function { .. }) - { - // **`T*` to `void*` is a standard conversion** — C11 6.3.2.3p1 and [conv.ptr] both say so — and - // it is the conversion `malloc`, `free`, `memcpy`, `qsort` and every generic container in C is - // written with: `takes_void_star(&number)` is correct code. The relation answered `Unknown` here, - // which was safe and left the one thing a `void*` can get wrong unreported: **dropping `const`**. - // `const char *p` into a `void *` is a discarded qualifier in both languages, and every compiler - // warns about it; measured on a C project of twenty-five files, `takes_void_star(constant)` was - // the one defect of its file that nothing reported. - // - // A **function pointer** stays `Unknown`: the standard does not convert one to `void*`, POSIX - // does, and a project using the second is not making a mistake. - if from_qualified && !to_qualified { - Known::No - } else { - Known::Yes(()) - } - } else if is_void(from_core) || is_void(to_core) { - // **`void*` to `T*`** — the other direction — is the language's own C/C++ split: C converts it - // implicitly and C++ needs a cast. This relation does not know which language it is answering - // for, so it declines; `int *p = malloc(n)` is left alone in a C file, as it must be. - Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( - "a conversion through `void*` is not decided here", - ))) - } else if from_core == to_core { - // **Qualification is the one difference that converts**: `char*` → `const char*` is implicit, the - // other direction is not (it drops the `const`). - if from_qualified && !to_qualified { - Known::No - } else { - Known::Yes(()) - } - } else if let ( - Type::Array { - of: from_element, .. - }, - Type::Array { of: to_element, .. }, - ) = (from_core, to_core) - { - // **Two arrays are one shape only when their elements are.** `int (*)[4]` does not convert to - // `double (*)[4]` in either language — there is no array covariance — and the relation answered - // `Unknown` for every such pair because the two pointees are both `Array` and it compared their - // *names*. Measured on a C project: `double (*pointer)[4] = &int_values;` was silent, and gcc - // refuses it. - let (from_element, _) = a_pointee_without_its_qualifiers(from_element); - let (to_element, _) = a_pointee_without_its_qualifiers(to_element); - if matches!(from_element, Type::Builtin { .. }) - && matches!(to_element, Type::Builtin { .. }) - { - Known::No - } else { - Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( - "a conversion between two arrays of named elements is not decided here", - ))) - } - } else if matches!(from_core, Type::Builtin { .. }) - && matches!(to_core, Type::Builtin { .. }) - { - // **Both pointees, or no answer.** A `No` here says "these two builtins are different types", and - // that is the only pair this relation can decide: a `Named` pointee is a class *or an alias this - // layer has not substituted*, and comparing it with a builtin is a guess about a name rather than - // about a type. Measured on `test_cpp`'s `strings.cpp`: `std::string_view::data()` answered - // `const value_type*` (its class declares `using const_pointer = const value_type*;`), so every - // `std::from_chars(text.data(), …)` was reported as *"this passes `text.data()` where - // `const char*` is declared"* — a false `param-type-check` on a call that is correct. - Known::No - } else { - Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( - "a conversion between two class pointers is a hierarchy question", - ))) - } - } - - _ => Known::Unknown(sema::symbol::UnknownReason::UnknownType(Box::from( - "a conversion between these two types is not decided by their shapes", - ))), - } - } - - /// Is this spelling one of the arithmetic types? - /// **Is this `bool`** — the type a condition already is, and therefore not a conversion of anything. - /// - /// Asked through the qualifiers on purpose: `bool const flag = …; if (flag)` converts nothing, and the rule that - /// asks this used to compare the *spelling* with `"bool"`, which a qualified type spells `bool const`. - pub fn is_bool(&self) -> bool { - match self { - Type::Builtin { spelling } => spelling.as_str() == "bool", - Type::Qualified { of, .. } => of.is_bool(), - _ => false, - } - } - - pub fn is_arithmetic(&self) -> bool { - match self { - Type::Builtin { spelling } => !matches!(spelling.as_str(), "void" | "decltype(auto)"), - Type::Qualified { of, .. } => of.is_arithmetic(), - _ => false, - } - } - - /// Is this `void` — the incomplete type no object can have? - pub fn is_void(&self) -> bool { - match self { - Type::Builtin { spelling } => spelling == "void", - Type::Qualified { of, .. } => of.is_void(), - _ => false, - } - } - - /// The type a `*` on this one gives: the pointee, for a pointer or an array — **as a shared handle**, because - /// the pointee is already an allocation inside this type and a caller asking for it is looking at it rather - /// than taking it away. - /// - /// `None` for everything else, **including a reference**: a reference has no `operator*`, and the reason a - /// caller wants a pointee is to apply one. `Type::Reference` is seen through by [`Type::class_name`] and - /// [`Type::decay`], where C++ does see through it, and not here, where it does not. Nor for a `Named` type that - /// has an `operator*` of its own — that needs the class's members and therefore the index. A caller that gets - /// `None` has an ill-formed `*` **or** a class this layer cannot look inside, and those are the same answer at - /// this level. - pub fn pointee(&self) -> Option { - match self { - Type::Pointer { to } | Type::Array { of: to, .. } => Some(Arc::clone(to)), - // **A qualifier is transparent here too**, and C++ is again why: `*p` on a `const Widget*` gives a - // `const Widget`, which is the pointee. Only the operators are peeled. - Type::Qualified { of, .. } => of.pointee(), - _ => None, - } - } - - /// Is this a template parameter, or does it *contain* one anywhere? - /// - /// The predicate a caller uses to tell "the answer is not known yet" from "the answer is not here": a type - /// holding a template parameter is one that only instantiation can finish, and this analysis does not - /// instantiate. It is a fact about the type rather than about a position, which is what makes it cheap enough - /// to ask before every index query. - pub fn depends_on_a_parameter(&self) -> bool { - match self { - Type::TemplateParameter { .. } => true, - Type::Named { arguments, .. } => arguments.iter().any(Type::depends_on_a_parameter), - Type::Pointer { to } - | Type::Reference { to, .. } - | Type::Pack { of: to } - | Type::Qualified { of: to, .. } => to.depends_on_a_parameter(), - Type::Array { of, .. } => of.depends_on_a_parameter(), - Type::Function { - returns, - parameters, - } => { - returns.depends_on_a_parameter() - || parameters.iter().any(Type::depends_on_a_parameter) - } - Type::Builtin { .. } => false, - } - } - - /// **This type with the template parameters in `substitutions` replaced** — the one operation that makes a - /// member of a class template answerable. - /// - /// `std::vector::size_type` with `T = int` is `std::size_t`, and the substitution is by **name**: the - /// parameters of a class template are a fixed list, the arguments are written at the use, and the pairing - /// between them is positional. This is not instantiation — no body is re-read, no overload is chosen, no - /// dependent name is resolved — and the limits are worth stating rather than discovering: - /// - /// * a parameter that appears **inside an expression** (`T::value_type`, `decltype(sizeof(T))`) is - /// substituted as a name and not evaluated: the first is answered because it is a named type, the second is - /// not a type at all and was refused when it was read; - /// * a **dependent** name (`typename T::value_type`) has nothing to substitute *into* until `T` is known, and - /// this returns it unchanged — see [`Type::depends_on_a_parameter`], which is how a caller avoids asking a - /// question whose answer this cannot be; - /// * a **partial** substitution is the ordinary case: `std::pair` with `T` unknown substitutes the - /// `int`, which is what makes `second` answerable and `first` not. - pub fn substituted(&self, substitutions: &TypeSubstitutions<'_>) -> Type { - match self { - // **A name that is in the parameter list *is* the parameter**, and this arm is why the substitution can - // be done at all for a member read out of a header. A template parameter is not a kind of type that a - // reader can recognise from the text: `template struct vector { _Ty& front; };` writes - // `_Ty` and spells it exactly like a class name, because at that point it *is* one — what makes it a - // parameter is the list it was declared in, and that list belongs to the class rather than to the - // member. So the pairing is asked, by name, and an empty list means the name is an ordinary class. - // - // A class genuinely called `_Ty`, used inside a class template whose parameters are named `_Ty`, would - // be substituted wrongly. That is not a readable program (the parameter hides the class inside its own - // body — C++ would resolve it to the parameter too), so this is the language's rule rather than a - // guess, and getting it wrong in the other direction costs every member of every standard container. - Type::Named { name, arguments } => { - if arguments.is_empty() - && let Some(argument) = substitutions.get(name) - { - return argument.clone(); - } - - Type::Named { - name: name.clone(), - arguments: arguments - .iter() - .map(|argument| argument.substituted(substitutions)) - .collect(), - } - } - Type::TemplateParameter { name } => substitutions - .get(name) - .cloned() - .unwrap_or_else(|| self.clone()), - Type::Pointer { to } => Type::Pointer { - to: Arc::new(to.substituted(substitutions)), - }, - Type::Reference { to, rvalue } => Type::Reference { - to: Arc::new(to.substituted(substitutions)), - rvalue: *rvalue, - }, - Type::Array { of, extent } => Type::Array { - of: Arc::new(of.substituted(substitutions)), - extent: *extent, - }, - Type::Function { - returns, - parameters, - } => Type::Function { - returns: Arc::new(returns.substituted(substitutions)), - parameters: parameters - .iter() - .map(|parameter| parameter.substituted(substitutions)) - .collect(), - }, - Type::Pack { of } => Type::Pack { - of: Arc::new(of.substituted(substitutions)), - }, - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(of.substituted(substitutions)), - qualifiers: *qualifiers, - }, - Type::Builtin { .. } => self.clone(), - } - } - /// **This type with one name in it replaced** — `value_type&` with `value_type` = `char` is `char&`. - /// - /// The companion of [`Type::substituted`], and the difference is what is being replaced: that one replaces a - /// *template parameter* by the argument a use paired with it, this one replaces a name by whatever that name - /// turned out to mean. Both walk the same structure for the same reason — spellings cannot be edited as text — - /// and the walk is the whole point here: `value_type&` is not a bare name, so a reader that only ever looked at - /// whole spellings stopped one step short of the answer. - /// - /// Measured, in MSVC's ``: `back()` returns `reference`, which is `value_type&`, which is `_Ty&`, - /// which is `char&` for a `std::string`. Every step is a member alias of the same class, and every step after - /// the first is the **base** of a type rather than the whole of it. - /// - /// The operators around the name stay where they are, which is the language's rule: `value_type&` with - /// `value_type` = `_Ty*` is `_Ty*&` — a reference to a pointer — and dropping either would answer a different - /// type. A name carrying template arguments of its own (`value_type`) is deliberately **not** replaced: - /// the arguments would have to be substituted into the replacement, and a member alias of a class this walk is - /// about is not a template in any case it exists for. - pub fn replacing(&self, name: &str, with: &Type) -> Type { - match self { - Type::Named { - name: found, - arguments, - } if arguments.is_empty() && found == name => with.clone(), - Type::Named { - name: found, - arguments, - } => Type::Named { - name: found.clone(), - arguments: arguments - .iter() - .map(|argument| argument.replacing(name, with)) - .collect(), - }, - Type::TemplateParameter { .. } | Type::Builtin { .. } => self.clone(), - Type::Pointer { to } => Type::Pointer { - to: Arc::new(to.replacing(name, with)), - }, - Type::Reference { to, rvalue } => Type::Reference { - to: Arc::new(to.replacing(name, with)), - rvalue: *rvalue, - }, - Type::Array { of, extent } => Type::Array { - of: Arc::new(of.replacing(name, with)), - extent: *extent, - }, - Type::Function { - returns, - parameters, - } => Type::Function { - returns: Arc::new(returns.replacing(name, with)), - parameters: parameters - .iter() - .map(|parameter| parameter.replacing(name, with)) - .collect(), - }, - Type::Pack { of } => Type::Pack { - of: Arc::new(of.replacing(name, with)), - }, - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(of.replacing(name, with)), - qualifiers: *qualifiers, - }, - } - } -} - -impl fmt::Display for Type { - /// The type **as a file would write it**, which is what a consumer shows: the spelling each part was read - /// with, put back together in the order the syntax wrote it. - /// This is a writer for a human, not a parser's inverse: `int* const` and `const int*` differ by which side - /// the `const` was on, and that difference is in the spelling of the parts rather than in the shape. Where - /// this layer *does* know better than the source — a class named by a template's arguments — it still writes - /// what the source wrote, because a consumer comparing the answer against the file is the ordinary case. - fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Type::Builtin { spelling } => write!(out, "{spelling}"), - Type::TemplateParameter { name } => write!(out, "{name}"), - Type::Named { name, arguments } => { - write!(out, "{name}")?; - if !arguments.is_empty() { - write!(out, "<")?; - for (at, argument) in arguments.iter().enumerate() { - if at > 0 { - write!(out, ", ")?; - } - write!(out, "{argument}")?; - } - write!(out, ">")?; - } - Ok(()) - } - Type::Pointer { to } => write!(out, "{to}*"), - Type::Reference { to, rvalue } => { - if *rvalue { - write!(out, "{to}&&") - } else { - write!(out, "{to}&") - } - } - Type::Array { of, extent } => match extent { - Some(size) => write!(out, "{of}[{size}]"), - None => write!(out, "{of}[]"), - }, - // **A pointer or an array in the return position needs its parentheses**, and they go around the - // *declarator* rather than around the whole type: `void (*)(int)` is a pointer to a function, while - // `(void*)(int)` and `void*(int)` read as a function returning a pointer — the one mistake this reader - // is written not to make. The language's rule is that a declarator's operators bind in the order they are - // parenthesised, so writing the shape back has to put the parentheses in the same place. - Type::Function { - returns, - parameters, - } => { - match &**returns { - pointer @ Type::Pointer { .. } => write!(out, "{}", pointer.as_a_declarator())?, - array @ Type::Array { .. } => write!(out, "{}", array.as_a_declarator())?, - other => write!(out, "{other}")?, - } - write!(out, "(")?; - for (at, parameter) in parameters.iter().enumerate() { - if at > 0 { - write!(out, ", ")?; - } - write!(out, "{parameter}")?; - } - write!(out, ")") - } - Type::Pack { of } => write!(out, "{of}..."), - // `const Widget`, in the position the file wrote it — which is what makes `const Widget*` and - // `Widget* const` two different answers here rather than one. - Type::Qualified { of, qualifiers } - if matches!(**of, Type::Pointer { .. } | Type::Array { .. }) => - { - write!(out, "{of}{}", qualifiers.trailing_words()) - } - Type::Qualified { of, qualifiers } => { - write!(out, "{}{of}", qualifiers.leading_words()) - } - } - } -} - -impl Type { - /// **This type written the way a declarator writes it** — the shape `void (*)(int)` needs, and nothing else - /// does. - /// - /// A pointer or an array in the return position of a function type is the one place this layer has to write - /// parentheses: `void*(int)` reads as a function *returning* a pointer, which is a different type. The - /// parentheses go around the **declarator** rather than around the type — `void (*)(int)`, not `(void*)(int)` — - /// because that is where a name would stand, and a type read out of a declaration is that declaration with the - /// name taken out. `void (*)(int)` is `void (*F)(int)` minus the `F`. - /// - /// # Why the base goes on the left and the operators on the right - /// - /// Because that is the order a declaration writes them, and the shape holds them the other way round: - /// `Pointer { to: Builtin("void") }` has the `void` innermost. So the operators are collected on the way down — - /// `*` for a pointer, `[4]` for an array — and the base is written when the bottom is reached, in front of - /// them. A writer that emitted each level as it met it produced `(*void)(int)`. - fn as_a_declarator(&self) -> String { - let mut suffix = String::new(); - let mut qualified = false; - let mut current = self; - - loop { - match current { - Type::Pointer { to } => { - suffix.push('*'); - current = to; - } - Type::Array { of, extent } => { - suffix.push('['); - if let Some(size) = extent { - suffix.push_str(&size.to_string()); - } - suffix.push(']'); - current = of; - } - // `void* const`: the qualifier is written after what it qualifies, which is why it is part of the - // operator run rather than of the base. - Type::Qualified { of, .. } - if matches!(**of, Type::Pointer { .. } | Type::Array { .. }) => - { - qualified = true; - current = of; - } - _ => break, - } - } +/// **The qualifiers written on a type**, re-exported from the computed type module that now owns the type +/// model: `sema::types` keeps the parser, and [`ComputedType`] answers the semantic questions. +pub use crate::index::types::semantics::{Qualifiers, RecordTag}; - // **The parentheses go around the operators, not around the base**: `void (*)(int)` is `void (*F)(int)` with - // the `F` left out, and `(void*)(int)` — what wrapping the whole thing gives — puts the `void` inside them. - format!( - "{current} ({suffix}{})", - if qualified { " const" } else { "" } - ) - } -} - -/// What a set of template parameter names stands for, by name — the map [Type::substituted] reads. +/// What a set of template parameter names stands for, by name — the map [`ComputedType::substituted`] reads. /// /// A newtype over slices rather than a `HashMap`, because of how it is built and used: a class template's /// parameters are a short list in declaration order, the caller has just read them, and linear search over four /// names is faster than hashing them. It also makes the *pairing* explicit — the names and the arguments are two /// lists that must line up — which is the thing a bug here would get wrong. #[derive(Debug, Clone, Copy)] -pub struct TypeSubstitutions<'a> { - names: &'a [String], - arguments: &'a [Type], +pub struct TypeSubstitutions<'a, N: AsRef = String> { + names: &'a [N], + arguments: &'a [ComputedType], /// **What a parameter with no argument stands for** — the declaration's own default, already parsed and already /// substituted with the arguments the use wrote, so `template ` and `twice` give /// `U` the meaning `float`. Empty when the caller has no defaults, which is every caller that has no declaration /// in hand. - defaults: &'a [Type], + defaults: &'a [ComputedType], } -impl<'a> TypeSubstitutions<'a> { - pub fn new(names: &'a [String], arguments: &'a [Type]) -> TypeSubstitutions<'a> { +impl<'a, N: AsRef> TypeSubstitutions<'a, N> { + pub fn new(names: &'a [N], arguments: &'a [ComputedType]) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, arguments, @@ -986,10 +139,10 @@ impl<'a> TypeSubstitutions<'a> { /// arguments than the declaration has parameters — `std::vector` is `vector<_Ty, _Alloc>` with `_Alloc` /// defaulted, and `twice` writes one argument for two. pub fn with_defaults( - names: &'a [String], - arguments: &'a [Type], - defaults: &'a [Type], - ) -> TypeSubstitutions<'a> { + names: &'a [N], + arguments: &'a [ComputedType], + defaults: &'a [ComputedType], + ) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, arguments, @@ -1003,11 +156,11 @@ impl<'a> TypeSubstitutions<'a> { /// arguments is not a `std::vector` whose `T` happens to be called `T`, and answering the parameter name /// would be answering with a placeholder as if it were a type. A parameter with a **default** stands for the /// default, unless the default is the parameter itself (a spelling this layer cannot expand). - pub fn get(&self, name: &str) -> Option<&Type> { - let at = self - .names - .iter() - .position(|parameter| !parameter.is_empty() && parameter == name)?; + pub fn get(&self, name: &str) -> Option<&ComputedType> { + let at = self.names.iter().position(|parameter| { + let parameter = parameter.as_ref(); + !parameter.is_empty() && parameter == name + })?; if let Some(argument) = self.arguments.get(at) { return Some(argument); } @@ -1023,7 +176,7 @@ impl<'a> TypeSubstitutions<'a> { /// A *pack* has no single substitution — `template ` with `sum_of(1, 2.5)` pairs `Values` with the /// first argument — so a reader that needs the whole list (the type of a fold expression, which is what `+` widens all /// of them to) asks for it here rather than going through [`TypeSubstitutions::get`]. - pub fn arguments(&self) -> &'a [Type] { + pub fn arguments(&self) -> &'a [ComputedType] { self.arguments } } @@ -1039,7 +192,7 @@ impl<'a> TypeSubstitutions<'a> { #[derive(Debug, Clone, Default)] pub struct TypeBindings { names: Vec, - arguments: Vec, + arguments: Vec, } impl TypeBindings { @@ -1048,7 +201,7 @@ impl TypeBindings { /// The pairing is **positional**, and a mismatch in length is not an error to report: `std::vector` written /// without arguments has no argument for `_Ty`, and a parameter with nothing to stand for stays itself. See /// [`TypeBindings::is_empty`] for the ordinary case. - pub fn new(names: Vec, arguments: Vec) -> TypeBindings { + pub fn new(names: Vec, arguments: Vec) -> TypeBindings { TypeBindings { names, arguments } } @@ -1067,7 +220,7 @@ impl TypeBindings { /// `std::map` — which is what a qualifier inside the member's own return type needs in /// order to resolve: `_Tree<_Tmap_traits<_Kty, _Ty, …>>` names parameters that only the arguments can stand for. /// See `what_a_call_has`, which is the first caller. - pub fn arguments(&self) -> &[Type] { + pub fn arguments(&self) -> &[ComputedType] { &self.arguments } @@ -1077,11 +230,11 @@ impl TypeBindings { /// `written` with every parameter in this map replaced — the whole reason the map exists. /// - /// Takes and returns a `Type` rather than a spelling because the spellings are exactly what cannot be + /// Takes and returns a `ComputedType` rather than a spelling because the spellings are exactly what cannot be /// substituted textually: `_Ty&` and `_Ty*` and `std::vector<_Ty>` all contain the same four characters, and /// replacing them by text would also rewrite a class actually called `_Ty&` — or, in a real header, `_Ty` inside /// a longer identifier. - pub fn applied_to(&self, written: &Type) -> Type { + pub fn applied_to(&self, written: &ComputedType) -> ComputedType { if self.is_empty() { return written.clone(); } @@ -1090,38 +243,107 @@ impl TypeBindings { } } -/// **Read a type out of the spelling a `DeclFact` records.** +/// **A parsed type with the declaration's template parameters marked as such.** +/// +/// [`parse_type_spelling`] reads a spelling with no scope around it, so a bare `T` comes back as a class *named* `T`. +/// A stored member type written `T&` has to substitute when a member list instantiates the class, and +/// [`ComputedType::substituted`] only replaces [`ComputedType::TemplateParameter`] — so the names the declaration +/// itself lists are rewritten here, before the value is stored on a fact. +/// +/// This is a **construction-edge** step: the input is the written spelling of one declaration, and its parameter list +/// is in hand. A name with arguments (`T`) is left alone, because a type parameter takes no arguments unless the +/// parameter is a template-template parameter, which this layer does not model. +pub fn with_template_parameters>( + written: ComputedType, + parameters: &[N], +) -> ComputedType { + let names_a_parameter = + |name: &str| !parameters.is_empty() && parameters.iter().any(|one| one.as_ref() == name); + match written { + ComputedType::Named(name) if !name.is_empty() && names_a_parameter(&name) => { + ComputedType::TemplateParameter(name) + } + ComputedType::Named(_) | ComputedType::Primary(_) => written, + ComputedType::Generic(generic) => { + ComputedType::Generic(Arc::new(index::types::GenericType { + name: generic.name.clone(), + arguments: generic + .arguments + .iter() + .map(|argument| with_template_parameters(argument.clone(), parameters)) + .collect(), + })) + } + ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(with_template_parameters( + (*to).clone(), + parameters, + ))), + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(with_template_parameters((*to).clone(), parameters)), + rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(with_template_parameters((*of).clone(), parameters)), + extent, + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(with_template_parameters( + (*function.returns).clone(), + parameters, + )), + parameters: function + .parameters + .iter() + .map(|parameter| with_template_parameters(parameter.clone(), parameters)) + .collect(), + })), + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(with_template_parameters( + (*of).clone(), + parameters, + ))), + ComputedType::Qualified(qualified) => ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(with_template_parameters( + (*qualified.of).clone(), + parameters, + )), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })), + // See [`ComputedType::substituted`]: a tag written before a name stays before whatever that name became. + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag, + of: Arc::new(with_template_parameters((*of).clone(), parameters)), + }, + ComputedType::TemplateParameter(_) => written, + } +} + +/// **Read a type out of a spelling.** /// -/// # Why a spelling parser exists at all, when the syntax is the better source +/// This is the **one spelling parser boundary** in the crate. It is the inverse of [`ComputedType`]'s `Display`, and +/// it is deliberately a *reading* rather than a validator: it takes the spelling, peels the operators off the outside +/// in, and answers with the shape. What it cannot recognise becomes a [`ComputedType::Named`] holding the spelling, +/// which is what makes it usable on the shapes this layer does not model. /// -/// Because two layers of this crate do not have the syntax, and cannot get it cheaply: +/// # Why it exists at all, when the syntax is the better source +/// +/// Because some values genuinely arrive as text and have no tree: /// /// ```text -/// a declaration the index holds `DeclFact::type_of` is a `String` on disk, and a query that needs the class -/// it names has no tree to walk — the declaring file is not even open -/// a type written as a template arg `std::map` arrives as text inside a name node +/// a spelling a display/consumer handed back a hover or a diagnostic that kept a string +/// a type written as a template argument `std::map` arrives as text inside a name node +/// a declaration read from a cooked rendering `get_type_text()` is what the preprocessor's rendering says /// ``` /// -/// So this is the **inverse of [`Type::Display`]**, and it is deliberately a *reading* rather than a validator: -/// it takes the spelling, peels the operators off the outside in, and answers with the shape. What it cannot -/// recognise becomes a [`Type::Named`] holding the spelling — which is what makes it usable on the shapes this -/// layer does not model, and is why [`Type::class_name`] is the question a caller should ask rather than -/// inspecting the variants. -/// -/// # The one thing it must get right -/// -/// [`Type::class_name`]. Everything else here is recoverable — a caller that gets `Type::Named("int")` instead of -/// `Type::Builtin` loses nothing it was going to ask about — while a **class name** that is wrong sends a member -/// query to a class that does not exist. So the peeling is written around that: the trailing declarator operators -/// come off first (they are written last), then the array extents, then the name and its arguments. +/// It is the **inverse of [`ComputedType`]'s `Display`**, and the one thing it must get right is +/// [`ComputedType::class_name`]: everything else here is recoverable while a class name that is wrong sends a member +/// query to a class that does not exist. So the trailing declarator operators come off first (they are written last), +/// then the array extents, then the name and its arguments. /// -/// # What it does not do -/// -/// Qualifiers (`const`, `volatile`) are **dropped**, from the front and from the back: they change what may be -/// assigned to a type and not which class it is, and this layer models no assignment. A spelling whose parts this -/// parser splits differently from how it was written still answers the same class — see the tests, which pin the -/// round trip for the shapes a fact actually records. -pub fn parse_type_spelling(written: &str) -> Type { +/// **`auto` and `decltype(auto)` are placeholders, not names**: the base is built with +/// [`ComputedType::builtin`], which folds them into their [`crate::index::types::PrimaryType`], so a spelling +/// `auto&` becomes a reference to the placeholder rather than a class called `auto`. +pub fn parse_type_spelling(written: &str) -> ComputedType { // **A calling convention is not part of the type.** `void JNICALL` is a `void`-returning function with a // convention, and the compiler reads the word and not a type. Measured on sqlite`s JNI binding, where the // header that defines `JNICALL` is absent: every `return;` in such a function was reported as a value that does @@ -1140,19 +362,36 @@ pub fn parse_type_spelling(written: &str) -> Type { // `assign-type-check` for `const char *sep = luaL_optlstring(…)` (8 false positives, 2026-11-20). let (trailing, rest) = strip_trailing_qualifiers(written.trim()); let parsed = parse_type_spelling_without_a_trailing_qualifier(rest); - match trailing.is_none() { - true => parsed, - false => Type::Qualified { + if trailing.is_none() { + parsed + } else { + ComputedType::Qualified(Arc::new(QualifiedType { of: Arc::new(parsed), - qualifiers: trailing, - }, + is_const: trailing.is_const(), + is_volatile: trailing.is_volatile(), + })) } } /// [`parse_type_spelling`] with the trailing qualifiers already peeled — the body that reads the operators. -fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { +fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> ComputedType { let trimmed = written.trim(); + // **`decltype(auto)` is a placeholder, not a function type.** It ends in `)`, so the function-type peel below + // would read `decltype` with one parameter `auto`; the spelling is the language's other placeholder and answers + // its primary directly. + if trimmed == "decltype(auto)" { + return ComputedType::Primary(PrimaryType::DecltypeAuto); + } + + // **A pack expansion is a shape of its own.** `Args...` is a template parameter standing for several arguments, + // and the structure is the one a substitution walks; display writes the ellipsis back. + if let Some(rest) = trimmed.strip_suffix("...").map(str::trim_end) + && !rest.is_empty() + { + return ComputedType::Pack(Arc::new(parse_type_spelling(rest))); + } + // **A compiler builtin is not a class with an odd name.** // // `enable_if_t<__is_constructible(_Ty, _Args...), _Ty>` reaches this reader as a spelling, and before this the @@ -1166,14 +405,14 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { if let Some((builtin, arguments)) = sema::builtins::split_a_builtin_spelling(trimmed) { match sema::builtins::answer(builtin, &arguments) { sema::builtins::Answer::Boolean(_) | sema::builtins::Answer::UndecidedBoolean => { - return Type::builtin("bool"); + return ComputedType::builtin("bool"); } sema::builtins::Answer::Type(type_of) => return type_of, sema::builtins::Answer::Unmodelled => {} } } if trimmed.is_empty() { - return Type::builtin("void"); + return ComputedType::builtin("void"); } // **`typename` is a disambiguator, not part of a type.** @@ -1199,9 +438,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { let head = trimmed[..pointer].trim(); let rest = trimmed[pointer + 3..].trim(); if !head.is_empty() && rest.starts_with('[') { - return Type::Pointer { - to: Arc::new(parse_type_spelling(&format!("{head}{rest}"))), - }; + return ComputedType::Pointer(Arc::new(parse_type_spelling(&format!("{head}{rest}")))); } } @@ -1211,7 +448,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { if trimmed.ends_with(']') && let Some((element, extent)) = split_trailing_extent(trimmed) { - return Type::Array { + return ComputedType::Array { of: Arc::new(parse_type_spelling(element)), extent, }; @@ -1229,7 +466,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { if let Some(rest) = trimmed.strip_suffix(operator).map(str::trim_end) && !rest.is_empty() { - return Type::Reference { + return ComputedType::Reference { to: Arc::new(parse_type_spelling(rest)), rvalue, }; @@ -1239,9 +476,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { if let Some(rest) = trimmed.strip_suffix('*').map(str::trim_end) && !rest.is_empty() { - return Type::Pointer { - to: Arc::new(parse_type_spelling(rest)), - }; + return ComputedType::Pointer(Arc::new(parse_type_spelling(rest))); } // **A function type**: `int(int, double)`. Recognised by a parameter list at the very end whose opening @@ -1252,7 +487,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { && !returns.is_empty() && !returns.contains('(') { - return Type::Function { + return ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(parse_type_spelling(returns)), parameters: parameters .split(',') @@ -1260,16 +495,16 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { .filter(|part| !part.is_empty()) .map(parse_type_spelling) .collect(), - }; + })); } // **The base, and the qualifier written on it.** `const` is kept as a wrapper around whatever it qualifies // rather than dropped, because it is part of the type a reader is shown and part of what `auto` deduces: // `const auto& r = x` is a `const int&`, and a layer that answered `int&` would have lost the one word the // declaration was written to add. - let (qualifier, base) = split_leading_qualifiers(trimmed); + let (qualifier, record_tag, base) = split_leading_qualifiers(trimmed); if base.is_empty() { - return Type::builtin("void"); + return ComputedType::builtin("void"); } let qualified = match base.find('<') { @@ -1280,36 +515,48 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { .into_iter() .map(|argument| parse_type_spelling(&argument)) .collect(); - Type::Named { name, arguments } + ComputedType::named(name, arguments) } // **A builtin is not a class**, and the difference is not cosmetic: `int` as a `Named` type answers - // `Type::class_name` with `int`, so a member access on an `int` would send the index looking for a class - // called `int` and report "not declared here" — which a reader takes as "this class is missing" rather - // than "this is not a class". The words are the language's own list, and a builtin spelled in several - // words (`unsigned long long`) is on it as one spelling. - _ if is_a_builtin(base) => Type::builtin(base), - // Anything else is a name this layer cannot place — a dependent name, a macro that expands to a type — and - // carrying it as a name is what makes it usable by a caller that resolves names. - _ => Type::Named { - name: base.to_string(), - arguments: Vec::new(), - }, + // `class_name` with `int`, so a member access on an `int` would send the index looking for a class called + // `int`. [`ComputedType::builtin`] is the one table that decides: a word in it becomes a + // [`crate::index::types::PrimaryType`], and anything else is the name this layer cannot place — a dependent + // name, a macro that expands to a type. + _ => ComputedType::builtin(base), }; - match qualifier.is_none() { - true => qualified, - false => Type::Qualified { + // **C's tag is kept on the type.** `struct point` and `union value` wrote a record's keyword, and a type that + // dropped it could not tell the name from a `typedef` of an `int` — see [`RecordTag`]. + let qualified = match record_tag { + Some(tag) => ComputedType::ElaboratedRecord { + tag, of: Arc::new(qualified), - qualifiers: qualifier, }, + None => qualified, + }; + + if qualifier.is_none() { + qualified + } else { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified), + is_const: qualifier.is_const(), + is_volatile: qualifier.is_volatile(), + })) } } -/// `int[4]` → `("int", Some(4))`, and `int[]` → `("int", None)` — the **last** extent, from the right. +/// `int[4]` → `("int", Literal(4))`, `int[]` → `("int", Unspecified)` and `int[COUNT]` → `("int", Written("COUNT"))` +/// — the **last** extent, from the right. /// /// From the right because the last bracket pair is the one that applies to the whole type on its left: /// `int[2][3]` is an array of two of `int[3]`, so the outer peel takes `[3]` and leaves `int[2]` to the recursion. -fn split_trailing_extent(written: &str) -> Option<(&str, Option)> { +/// +/// A dimension this parser cannot turn into a number is kept **as written**, because it is part of the type: the +/// declaration `int a[COUNT]` and the declaration `int a[]` are different types, and a layout question has to be able +/// to evaluate the first. `Written` here is the spelling the text carried; no scope is available at this entry point, +/// so nothing decides its value — see [`crate::index::types::ArrayExtent`]. +fn split_trailing_extent(written: &str) -> Option<(&str, ArrayExtent)> { let mut depth = 0isize; for (index, character) in written.char_indices().rev() { @@ -1323,7 +570,15 @@ fn split_trailing_extent(written: &str) -> Option<(&str, Option)> { return None; } let inside = written[index + 1..written.len() - 1].trim(); - return Some((element, inside.parse().ok())); + let extent = if inside.is_empty() { + ArrayExtent::Unspecified + } else { + match inside.parse::() { + Ok(literal) => ArrayExtent::Literal(literal), + Err(_) => ArrayExtent::written(inside), + } + }; + return Some((element, extent)); } } _ => {} @@ -1436,15 +691,17 @@ fn strip_trailing_qualifiers(written: &str) -> (Qualifiers, &str) { } } -/// A spelling split into the **qualifier it leads with** and the type underneath — `const Widget` → -/// `(Some("const"), "Widget")`. +/// A spelling split into the **qualifier it leads with**, the **C record tag it leads with**, and the type +/// underneath — `const struct point` → `(Some("const"), Some(RecordTag::Struct), "point")`. /// -/// The elaborated keywords (`struct`, `class`, `enum`, `typename`) are stepped over and **not** reported: they are -/// how a type is disambiguated rather than anything about it, and `struct Widget` and `Widget` are one type. A -/// qualifier is reported because it is not. -fn split_leading_qualifiers(written: &str) -> (Qualifiers, &str) { +/// The elaborated keywords are stepped over: `class`, `enum` and `typename` say how a name is disambiguated and are +/// **not** reported, because none of them is a C record tag. `struct` and `union` **are** reported — they are the +/// one written evidence that the name denotes a record rather than a `typedef` of something else — and a qualifier is +/// reported because it is part of the type. +fn split_leading_qualifiers(written: &str) -> (Qualifiers, Option, &str) { let mut rest = written.trim(); let mut qualifier = Qualifiers::NONE; + let mut record_tag: Option = None; while let Some(word) = rest.split_whitespace().next() { if word.len() == rest.len() { @@ -1454,15 +711,21 @@ fn split_leading_qualifiers(written: &str) -> (Qualifiers, &str) { // **Both, in either order** — `const volatile S` and `volatile const S` are one type, and the second word // used to be dropped (`docs/worklog.md` P1-3). Some(found) => qualifier = qualifier.with(found), - None => match word { - "struct" | "class" | "enum" | "typename" => {} - _ => break, - }, + None => { + // **A C record's keyword is kept** — `struct point` says the name is a record, and a typedef can + // write the same name without saying it. `class` and `enum` are C++'s or arithmetic; `enum` is + // deliberately not a record tag. + if let Some(tag) = RecordTag::of_a_word(word) { + record_tag = Some(tag); + } else if !matches!(word, "class" | "enum" | "typename") { + break; + } + } } rest = rest[word.len()..].trim_start(); } - (qualifier, rest.trim_end()) + (qualifier, record_tag, rest.trim_end()) } /// Split a template argument list on the commas that are **not** inside a nested list. @@ -1506,7 +769,7 @@ impl ArgumentSplit for str { /// /// # Why this is the half that was missing /// -/// [`Type::substituted`] pairs a parameter list with the arguments a use wrote, and it has existed since the model +/// [`ComputedType::substituted`] pairs a parameter list with the arguments a use wrote, and it has existed since the model /// did. What did not exist was anybody to hand it the names: a class template's parameters are written **once**, at /// the declaration, and every use of the template says only what it passes. So a member's own recorded type keeps /// saying `_Ty` — `std::vector::reference` is declared `_Ty&` and *is* `int&` — and the layer answered about a @@ -1526,9 +789,9 @@ impl ArgumentSplit for str { /// constrained parameter (`template `) has words in front of the name that are not it. Taking the /// **last** identifier before the `=` gets every shape above right and is what this does. pub fn template_parameter_names(list: &CppSyntaxNode) -> Vec { - template_parameters_in(list) + template_parameters_with_defaults(list) .into_iter() - .map(|(name, _)| name) + .map(|parameter| parameter.name) .collect() } @@ -1539,12 +802,16 @@ pub fn template_parameter_names(list: &CppSyntaxNode) -> Vec { /// the names alone, and the concept check needs the constraint beside the name — "this argument does not satisfy what /// the declaration asked of its parameter" cannot be answered by either half on its own. /// -/// The constraint is what stands **before** the name, with `class`/`typename`/`template` and any `...` taken off, so -/// `class... Ts` is unconstrained and `std::integral T` is `std::integral`. +/// The constraint is read from the parameter's own type nodes, not cut out of the head's text: a parameter that +/// begins with a name is constrained by it (`std::integral T`, `Small T`), while `class T`, `typename T`, `int N` +/// and `class... Ts` are unconstrained and answer `""`. +/// +/// This is the **display spelling** of the value [`TemplateParameter::constraint_fact`] carries. A consumer that +/// decides satisfaction reads the fact, not this text. pub fn template_parameters_in(list: &CppSyntaxNode) -> Vec<(String, String)> { template_parameters_with_defaults(list) .into_iter() - .map(|(name, constraint, _)| (name, constraint)) + .map(|parameter| (parameter.name, parameter.constraint)) .collect() } @@ -1554,10 +821,31 @@ pub fn template_parameters_in(list: &CppSyntaxNode) -> Vec<(String, String)> { pub fn template_parameter_defaults(list: &CppSyntaxNode) -> Vec { template_parameters_with_defaults(list) .into_iter() - .map(|(_, _, default)| default.unwrap_or_default()) + .map(|parameter| parameter.default.unwrap_or_default()) .collect() } +/// **One template parameter, read from its own syntax** — the name, its constraint as a display spelling and as a +/// structured [`ConstraintFact`], and its default. +/// +/// The two constraint forms are one answer with two audiences. [`TemplateParameter::constraint`] is the text a +/// message or a hover shows; [`TemplateParameter::constraint_fact`] is the structured value a check reads, so no +/// consumer has to split a spelling back into a concept name and arguments. +#[derive(Debug, Clone, Default)] +pub struct TemplateParameter { + /// The parameter's own name; `""` for an unnamed parameter, whose slot is kept so later names stay aligned + /// with the arguments written at a use. + pub name: String, + /// The constraint written in front of the name, as display text — `""` when unconstrained. It is the canonical + /// spelling of the value [`TemplateParameter::constraint_fact`] carries; see [`template_parameters_in`]. + pub constraint: String, + /// **The same constraint structurally**, when this parameter writes one this layer can lower. `None` for an + /// unconstrained parameter and for a constraint whose syntax has no concept name to read. + pub constraint_fact: Option, + /// The default argument written for it, if any. + pub default: Option, +} + /// **Each template parameter's name, constraint and default** — `("_Alloc", "", Some("allocator<_Ty>"))`. /// /// # Why the default is kept @@ -1572,18 +860,25 @@ pub fn template_parameter_defaults(list: &CppSyntaxNode) -> Vec { /// The default is written in the **same parameter names** as the declaration (`_Alloc = allocator<_Ty>`), so a /// substitution that uses it has to substitute *into* it as well — see /// [`substituted_spelling_with_defaults`]. -pub fn template_parameters_with_defaults( - list: &CppSyntaxNode, -) -> Vec<(String, String, Option)> { +/// +/// # The constraint's structured half +/// +/// A constrained **type** parameter is written as a **type name followed by the parameter's own name** — the +/// grammar's own shape (`parse_template_parameter` records the name when a name precedes it): `std::integral T`, +/// `std::same_as T`, `Small T`. The parameter's [`CppTemplateParam::get_decl_specifiers`] therefore holds the +/// concept as a `NamedType`/`TemplateType`, and [`constrained_by`] lowers it with the same reader a declaration's +/// type uses. A constrained **non-type** parameter writes the concept in front of `auto` instead — `std::integral +/// auto N` — and its constraint is the node in front of the placeholder. Nothing here takes a constraint apart as +/// text, and a value argument (`SomeConcept<42>`) stays a [`ConstraintArgument::Value`] rather than becoming a type. +pub fn template_parameters_with_defaults(list: &CppSyntaxNode) -> Vec { let mut found = Vec::new(); for parameter in list.children() { - if !CppTemplateParam::can_cast(parameter.kind().into()) { + let Some(parameter) = CppTemplateParam::cast(parameter) else { continue; - } + }; - let written = parameter.text().to_string(); - let before_a_default = written.split('=').next().unwrap_or(&written); + let written = parameter.syntax().text().to_string(); // **The name is the last *identifier* before the default**, read from the **tokens** rather than from the // text. Splitting the text took "the last word", and for an **unnamed** parameter that word is the keyword @@ -1593,6 +888,7 @@ pub fn template_parameters_with_defaults( // not an identifier to the lexer, so the token stream answers what the text could not. let mut name: Option = None; for token in parameter + .syntax() .descendants_with_tokens() .filter_map(|element| element.into_token()) { @@ -1614,36 +910,213 @@ pub fn template_parameters_with_defaults( // substitute the *first* argument for `T`, and a `pair` would answer `pair`. The empty // string is a name no spelling can equal, which is exactly what a parameter with no name is. let Some(name) = name else { - found.push((String::new(), String::new(), default)); + found.push(TemplateParameter { + name: String::new(), + constraint: String::new(), + constraint_fact: None, + default, + }); continue; }; - // Everything before the name, minus the spellings that are not a constraint. - let before = before_a_default - .rfind(&name) - .map(|at| before_a_default[..at].trim()) - .unwrap_or(""); - let mut constraint = before.to_string(); - loop { - let mut trimmed = constraint.trim().trim_end_matches("...").trim().to_string(); - for keyword in ["class", "typename", "template", "struct"] { - if let Some(rest) = trimmed.strip_prefix(keyword) { - trimmed = rest.trim().to_string(); - } - } - trimmed = trimmed.trim().to_string(); - if trimmed == constraint || trimmed.is_empty() { - constraint = trimmed; - break; + // **The constraint comes from the same typed nodes as its structured half**, so this reader never splits + // the head's text. An unconstrained parameter — `class T`, `int N`, `typename... Ts` — answers `None`, and + // so does a constraint whose syntax has no concept name. + let (constraint, constraint_fact) = match constrained_by(¶meter) { + Some((fact, display)) => (display, Some(fact)), + None => (String::new(), None), + }; + found.push(TemplateParameter { + name, + constraint, + constraint_fact, + default, + }); + } + + found +} + +/// **The concept constraint a template parameter was written with, lowered from its own syntax** — the structured +/// fact and the display spelling its lowered type writes. +/// +/// A constrained **type** parameter is a **type name in front of the parameter's own name** — `std::integral T`, +/// `std::same_as T`, `Small T` — and the grammar records exactly that shape: the concept is a `NamedType` or a +/// `TemplateType` inside the parameter's [`CppDeclSpecifierSeq`], while the parameter's name is in a `Declarator` +/// beside it. `parse_template_parameter` decides the same way, from the first significant token, which is why this +/// asks that question the same way: a parameter that starts with `typename`, `class`, `struct`, `int`, `auto` or a +/// pack marker declares its own name instead of being constrained by one, and it answers `None`. +/// +/// A constrained **non-type** parameter is written the other way round — `std::integral auto N`, `C auto M` — +/// and its specifier sequence lowers to the `auto` placeholder, which is the parameter's *type*. The concept is the +/// typed node in front of the placeholder ([`CppDeclSpecifierSeq::get_type_constraint`]), so this reads that node +/// and leaves the parameter's type alone: `read_specifiers` still answers `Primary(Auto)`. +/// +/// The concept node is then lowered with [`read_named`], the reader a type name goes through, so the concept's own +/// name keeps its scope (`std::integral`) and its arguments are [`ConstraintArgument`]s: a **type** argument is a +/// [`ComputedType`] and a **value** argument — `SomeConcept<42>` — is kept as the text `42`. The display is built +/// from those structured arguments, never from a spelling that has to be cut apart. +/// +/// [`CppDeclSpecifierSeq`]: cpp_parser::CppDeclSpecifierSeq +fn constrained_by(parameter: &CppTemplateParam) -> Option<(ConstraintFact, String)> { + let specifiers = parameter.get_decl_specifiers()?; + let node = specifiers.syntax(); + + // **A constraint before a deduced placeholder is a non-type parameter's constraint.** Lowering the whole + // sequence answers `auto`, so the concept cannot come from it; the parser returns the typed node in front of the + // `auto` instead. The parameter's own type is not touched — it stays the placeholder the sequence lowers to. + if let Some(constraint) = specifiers.get_type_constraint() { + return a_constraint_from(&constraint); + } + + let first = node + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .find(|token| !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())))?; + if !matches!( + cpp_parser::CppTokenKind::from(first.kind()), + cpp_parser::CppTokenKind::Identifier | cpp_parser::CppTokenKind::Scope + ) { + return None; + } + + // **A concept is a name.** A builtin, a pointer, a qualifier, or any other type shape is not one, and answering + // a concept for it would be inventing a constraint the file did not write. Lowering the sequence is the same + // gate it always was; only the *arguments* are re-read below, because that lowering answers a value argument as + // a type name. + if !matches!( + read_specifiers(node), + ComputedType::Named(_) | ComputedType::Generic(_) + ) { + return None; + } + + // **The node the name came from** — the last name in the sequence, which is the one the lowering above used. + let concept = node + .children() + .filter(|child| { + matches!( + CppSyntaxKind::from(child.kind()), + CppSyntaxKind::NamedType | CppSyntaxKind::TemplateType + ) + }) + .last()?; + a_constraint_from(&concept) +} + +/// **One constraint's fact and display, read from the `NamedType`/`TemplateType` that writes the concept.** +/// +/// The name comes from [`read_named`] — the reader every type name goes through — so the scope is the file's +/// (`std::same_as`) and no spelling is cut. The **arguments** do not: [`read_named`] answers every template +/// argument as a [`ComputedType`], including a value one, and `SomeConcept<42>` would carry a type called `42`. +/// They are read here as [`ConstraintArgument`]s instead, and the display is put together from them, so the string +/// a hover shows and the value a check reads are the same answer. +fn a_constraint_from(constraint: &CppSyntaxNode) -> Option<(ConstraintFact, String)> { + let name = match read_named(constraint)? { + ComputedType::Named(name) => name, + ComputedType::Generic(generic) => generic.name.clone(), + _ => return None, + }; + let concept = name.rsplit("::").next().unwrap_or(&name).trim(); + if concept.is_empty() { + return None; + } + + let arguments = constraint_arguments_in(constraint); + let mut display = name.to_string(); + if !arguments.is_empty() { + display.push('<'); + for (at, argument) in arguments.iter().enumerate() { + if at > 0 { + display.push_str(", "); } - constraint = trimmed; + display.push_str(&argument.to_string()); } + display.push('>'); + } - // A pack whose name came first (`Ts...`) leaves nothing in front, and so does an unconstrained parameter. - found.push((name, constraint, default)); + Some(( + ConstraintFact { + concept: SmolStr::from(concept), + arguments: arguments.into_boxed_slice(), + }, + display, + )) +} + +/// **The arguments a concept's template-id writes**, in order, each as a type or a value. +/// +/// The list is the one **ending the concept node**: `C>` has two lists and only the outer one is `C`'s own. +/// Every element of a template argument list is a `TemplateArgument`, so the only question is what is *inside* it +/// — see [`constraint_argument`]. +fn constraint_arguments_in(constraint: &CppSyntaxNode) -> Vec { + let end = constraint.text_range().end(); + let Some(list) = constraint + .descendants() + .filter(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateArgumentList) + .find(|list| list.text_range().end() == end) + else { + return Vec::new(); + }; + + let mut arguments = Vec::new(); + for child in list.children() { + if CppTemplateArg::can_cast(child.kind().into()) { + arguments.push(constraint_argument(&child)); + } } + arguments +} - found +/// **One template argument of a constraint** — a type lowered structurally, or a value kept as written. +/// +/// The distinction is asked of the argument's **own child**, because that is where the parser puts its reading: +/// +/// ```text +/// C TemplateArgument > TypeId > DeclSpecifierSeq > BuiltinType a type +/// C TemplateArgument > TypeId > DeclSpecifierSeq > NamedType a type +/// C<42> TemplateArgument > LiteralExpr a value +/// C<1 + 2> TemplateArgument > BinaryExpr a value +/// C TemplateArgument > SizeofExpr > TypeId a value +/// ``` +/// +/// Only a **direct** type node makes the argument a type: the `TypeId` in `sizeof(int)` is inside the expression, +/// and that argument is a value. `C` is the pack expansion the type reader already has a shape for, and it +/// is kept as the same [`ComputedType::Pack`] `read_template_arguments` produces. +fn constraint_argument(argument: &CppSyntaxNode) -> ConstraintArgument { + let text = argument.text().to_string(); + let written = text.trim(); + + // A pack expansion is written as an argument ending in `...` — the shape `read_template_arguments` reads the + // same way, because substituting into a pack is not substituting into a name. + if let Some(inner) = written.strip_suffix("...") { + return ConstraintArgument::Type(ComputedType::Pack(Arc::new(ComputedType::named( + inner.trim(), + Vec::new(), + )))); + } + + let writes_a_type = argument.children_with_tokens().any(|child| { + child.into_node().is_some_and(|node| { + matches!( + CppSyntaxKind::from(node.kind()), + CppSyntaxKind::TypeId + | CppSyntaxKind::NamedType + | CppSyntaxKind::TemplateType + | CppSyntaxKind::TypenameType + | CppSyntaxKind::QualifiedType + | CppSyntaxKind::BuiltinType + ) + }) + }); + if writes_a_type { + return ConstraintArgument::Type(read_argument(argument)); + } + + // **Everything else is a value**, and it stays the text the file wrote. The type model has no value + // representation, and `ComputedType::named("42")` would be a claim that `42` is a type *name* — exactly what a + // name lookup or a type comparison would then act on. + ConstraintArgument::Value(SmolStr::from(written)) } /// **The default argument written for a template parameter**, if one is — `allocator<_Ty>` for @@ -1801,10 +1274,11 @@ pub fn declarator_declaring(root: &CppSyntaxNode, name: SourceRange) -> Option, @@ -1812,7 +1286,7 @@ pub fn type_of_declaration( // **Does this declaration declare an object?** See [`type_of_declaration_named`], which is where the question is // answered; this wrapper exists only because most callers do not need to say which name is being declared. declares_an_object: bool, -) -> Type { +) -> ComputedType { type_of_declaration_named(specifiers, declarator, name, None, declares_an_object) } @@ -1842,7 +1316,7 @@ pub fn type_of_declaration_named( // fact said `LuaParser` and the expression engine said `LuaParser(file, std::move)`, so `p.HasError()` reported // that the class was out of the index. declares_an_object: bool, -) -> Type { +) -> ComputedType { let base = read_specifiers_named(specifiers, declared_name, name); // **A base with no spelling has nothing for a declarator to be applied to.** `priority[]` of the unnamed class @@ -1866,40 +1340,84 @@ pub fn type_of_declaration_named( // written *around* the name and is therefore part of the type — see [`wrap`]. let inner = declarator_holding_the_name(declarator, name); - // **A pointer-to-function declarator keeps its parameter list one level up.** `int (*fp)(int)` is - // `InitDeclarator > [Declarator "(*fp)", ParameterList "(int)"]` — the list belongs to the *pointer*, and the - // walk above is handed the declarator alone, so the type came back as `int*` and a call through `fp` had no - // return type to read. Measured: `auto through_pointer = fp(3);` answered unknown while the declaration is - // plainly a function pointer. - let the_base = base.clone(); - let wrapped = wrap(base, declarator, &inner, name, declares_an_object); - let pointer_to_function = declarator.text().to_string().trim_start().starts_with("(*") - || declarator.text().to_string().trim_start().starts_with("(&"); - if pointer_to_function - && let Some(parent) = declarator.parent() - && let Some(list) = parent - .children() - .find(|child| CppParamList::can_cast(child.kind().into())) - { - // **The pointer is to the function, not the function of the pointer**: `int (*fp)(int)` is - // `Pointer { to: Function { returns: int } }`, and wrapping the pointer itself made it a function *returning* - // `int*` — which is a different type and a different call. - let function = Type::Function { - returns: Arc::new(the_base), - parameters: read_parameters(&list), - }; - return if matches!(first_two_written(declarator), Some(('(', '&'))) { - Type::Reference { - to: Arc::new(function), - rvalue: false, - } - } else { - Type::Pointer { - to: Arc::new(function), - } - }; + wrap(base, declarator, &inner, name, declares_an_object) +} + +/// **The structured type a parameter declares** — `int n` → `int`, `const std::string& name` → `const std::string&`, +/// `T&& rest` → `T&&`, `char *text` → `char*`. +/// +/// The parameter's own node is the anchor: a `CppParam` is a specifier sequence plus a declarator, exactly the two +/// halves [`type_of_declaration`] reads, and the declarator's operators (`*`, `&`, `&&`, `[]`, `(int)`) are applied +/// around the name by that reader. The parameter's **name is not part of the type**, so nothing has to be stripped +/// from a spelling — the tree already separates the two. +/// +/// `declares_an_object` is `true`: a `ParamList` at the name's own level is what the declarator wraps, not a +/// function's parameter list — see [`type_of_declaration_named`] for the object/function distinction. +/// +/// `None` for a parameter with no specifier sequence at all (an unreadable one), or one whose base type has the empty +/// spelling — this layer's way of saying "a type nobody can name". A caller that gets `None` records +/// [`DeclaredType::None`](crate::cache::summary::DeclaredType) rather than inventing a spelling. +pub fn type_of_a_parameter(parameter: &CppParam) -> Option { + let specifiers = parameter.get_decl_specifiers()?; + let declarator = parameter.get_declarator(); + let written = type_of_declaration( + specifiers.syntax(), + declarator.as_ref().map(CppAstNode::syntax), + source_range(parameter.get_range()), + true, + ); + (!written.to_string().trim().is_empty()).then_some(written) +} + +/// **The structured type a type-id writes** — `T`, `char`, `int*`, `const std::string&`, `int[4]`, `int(int)`. +/// +/// A type-id is where the grammar puts a type that is not a declaration's own: a template argument +/// (`is_same`), a cast's target, a `new` expression's allocation. Its shape is one +/// [`cpp_parser::CppDeclSpecifierSeq`] child plus the operators written around it, and the operators sit one level +/// down in two places depending on whether the type wrote a name: +/// +/// ```text +/// int* TypeId > [DeclSpecifierSeq "int", Declarator "*"] the operators are in a declarator +/// int[4] TypeId > [DeclSpecifierSeq "int", ArrayType "[4]"] … or directly, with no name +/// int(int) TypeId > [DeclSpecifierSeq "int", FunctionType "(int)"] +/// ``` +/// +/// So this reads the specifiers once and then applies each wrapping child, **without parsing a spelling** — the +/// declaration path ([`type_of_declaration`]) needs a name to anchor a declarator, and a type-id has none. +/// +/// `None` for a type-id with no specifier sequence (an unparsable one) or one whose base type is the empty +/// spelling, which is this layer's way of saying "a type nobody can name" — see [`type_of_declaration_named`]. +pub fn type_of_a_type_id(type_id: &CppSyntaxNode) -> Option { + let specifiers = type_id + .children() + .find(|child| cpp_parser::CppDeclSpecifierSeq::can_cast(child.kind().into()))?; + let mut wrapped = read_specifiers(&specifiers); + if wrapped.to_string().is_empty() { + return None; } - wrapped + for child in type_id.children() { + if CppDeclarator::can_cast(child.kind().into()) { + // A declarator carries every operator written around a name — `*`, `&`, `&&`, `[4]`, `(int)` — and the + // declaration reader already walks it outside in. A type-id has no name, so its own range is the anchor. + wrapped = type_of_declaration( + &specifiers, + Some(&child), + source_range(child.text_range()), + false, + ); + } else if CppArrayType::can_cast(child.kind().into()) { + wrapped = ComputedType::Array { + of: Arc::new(wrapped), + extent: array_extent(&child), + }; + } else if CppParamList::can_cast(child.kind().into()) { + wrapped = ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(wrapped), + parameters: read_parameters(&child).into_boxed_slice(), + })); + } + } + Some(wrapped) } /// **The range of the identifier a declarator declares** — its first `NameExpr`, which is the name. @@ -1919,9 +1437,9 @@ fn declared_name_range(declarator: &CppSyntaxNode) -> Option { /// **Attributes and declaration specifiers are dropped**, and that is the bug this function was written for: the /// old spelling-based reader answered `const [[nodiscard]] constexpr size_type` for a return type, because it /// stripped a list of known keywords from text rather than reading the syntax. Here the only nodes that contribute -/// are the ones that *are* the type's name — a builtin, a name, a `decltype`, an elaborated keyword — and -/// everything else (`const`, `volatile`, storage class, `constexpr`, attributes) is dropped because it is not part -/// of what the type is *called*. +/// are the ones that *are* the type — a builtin, a name, a `decltype`, and an elaborated keyword, whose +/// `struct`/`union` tag is kept on the type itself — and everything else (`const`, `volatile`, storage class, +/// `constexpr`, attributes) is dropped because it is not part of what the type is *called*. /// /// # Why the builtin words are gathered rather than taken from the first node /// @@ -1929,7 +1447,7 @@ fn declared_name_range(declarator: &CppSyntaxNode) -> Option { /// `unsigned`, which is a different type from the one the file wrote. They are joined in the order they appear, /// which is the order the words are written in, and that is the whole rule: a builtin type's name *is* its words. /// -/// The qualifiers are dropped rather than modelled, and the reason is the same one [`Type`] gives for keeping +/// The qualifiers are dropped rather than modelled, and the reason is the same one [`ComputedType`] gives for keeping /// spellings: this layer does not resolve aliases, so `const Int` and `Int` are already two names for one type, and /// a `const` on the base would be a third axis no query here asks about. /// Is this builtin specifier's text a **`typeof`/`decltype` spelling** — C23's, GNU's, or C++'s own? @@ -1951,7 +1469,7 @@ fn is_a_typeof_spelling(word: &str) -> bool { /// /// `None` when the payload is an expression — `typeof(value)` — because that answer needs the semantic model and this /// reader is given a tree and nothing else. -fn the_type_a_typeof_names(node: &CppSyntaxNode) -> Option { +fn the_type_a_typeof_names(node: &CppSyntaxNode) -> Option { // The payload is the node inside the parentheses; a type-id is written as a TypeId holding a // DeclSpecifierSeq, which is the node this reader understands. let payload = node.descendants().find(|child| { @@ -1966,12 +1484,13 @@ fn the_type_a_typeof_names(node: &CppSyntaxNode) -> Option { .find(|child| cpp_parser::CppDeclSpecifierSeq::can_cast(child.kind().into()))? }; let read = read_specifiers_named(&specifiers, None, source_range(specifiers.text_range())); - // An elaborated name is the type's *name* on its own: struct point reaches this reader as a specifier sequence - // holding BuiltinType "struct" and NamedType "point", and the answer is point — which is what a member list is - // keyed under. A payload that resolved to nothing is not an answer. + // An elaborated name keeps its keyword on the type: `struct point` reaches this reader as a specifier sequence + // holding BuiltinType "struct" and NamedType "point", and the answer is `ComputedType::ElaboratedRecord` around `point` + // — the class question sees through it, and C's conversion rule reads the tag. A payload that resolved to + // nothing is not an answer. (!read.to_string().trim().is_empty()).then_some(read) } -pub(crate) fn read_specifiers(specifiers: &CppSyntaxNode) -> Type { +pub(crate) fn read_specifiers(specifiers: &CppSyntaxNode) -> ComputedType { read_specifiers_named(specifiers, None, source_range(specifiers.text_range())) } @@ -2016,7 +1535,7 @@ pub(crate) fn read_specifiers_named( // Where the declared name is, so that a specifier which *is* that name (an out-of-line definition's // `LuaLexer::LuaReserved`) is told apart from a type that merely ends the same way (`std::any any`). declared_range: SourceRange, -) -> Type { +) -> ComputedType { // **A specifier that *deduces* the type declares no written type**, and the answer is the empty spelling — the // one [`type_of_declaration_named`] returns before wrapping a declarator, which records `type_of: None`. // @@ -2031,19 +1550,20 @@ pub(crate) fn read_specifiers_named( // `assign-type-check` then reported `v`'s initialisation as a conversion "from `int` to `void`", twice over a // name no reader wrote. A deduced type is the case the rule's own documentation says is not its question. if specifiers_deduce_the_type(specifiers) { - return Type::Builtin { - spelling: String::new(), - }; + return ComputedType::builtin(""); } let mut builtin: Vec = Vec::new(); // The **last** name in the sequence, and the last unmodelled node — see the two notes below. - let mut named: Option = None; + let mut named: Option = None; let mut spelling = None; // Was a class-like **body** written here without a name in front of it? See the answer below. let mut an_unnamed_body = false; // Was an **elaborated keyword** (`struct`, `class`, `union`, `enum`) written here? See the `BuiltinType` arm. let mut elaborated = false; + // **Which C record tag**, when the keyword was `struct`/`union` — see [`RecordTag`]. `class` and `enum` are + // elaborated too and are not record tags. + let mut record_tag: Option = None; // Was a **`const`** written in the sequence, before the type's name? See the end of this function. let mut qualifiers_written = Qualifiers::NONE; @@ -2073,7 +1593,14 @@ pub(crate) fn read_specifiers_named( // the alias's target (which a cross-file lookup reads out of that field) was `struct`, and // `exarg_T` — the receiver of thousands of member questions in neovim — answered a member list of // zero. `unsigned long long` is unaffected: those words *are* the type. - if matches!(word.as_str(), "struct" | "class" | "union" | "enum") { + // **A C record's keyword is evidence, and it is kept.** `struct point` and `typedef int point;` write + // the same name and mean different things, so the tag travels on the type ([`RecordTag`]) instead + // of being dropped here. `class` and `enum` are elaborated specifiers too and are *not* C record + // tags: a class is C++, and an enumeration is an arithmetic type. + if let Some(tag) = RecordTag::of_a_word(&word) { + elaborated = true; + record_tag = Some(tag); + } else if word == "class" || word == "enum" { elaborated = true; } else if is_a_typeof_spelling(&word) { // **`typeof(struct point)` *is* the type it names.** The payload of a `typeof`/`decltype` specifier @@ -2127,7 +1654,10 @@ pub(crate) fn read_specifiers_named( CppSyntaxKind::AutoType | CppSyntaxKind::DecltypeType => { let written = written_trimmed(&node); if !written.is_empty() && named.is_none() { - named = Some(Type::named(written)); + // **`auto` and `decltype(auto)` become their primaries**, so the placeholder question is + // structural wherever the value travels; a `decltype(x)` spelling is a name this layer cannot + // evaluate and keeps its display. + named = Some(ComputedType::builtin(written)); } } // Not part of what the type is called. Qualifiers, attributes, storage class, `constexpr`, `inline`, @@ -2192,7 +1722,18 @@ pub(crate) fn read_specifiers_named( match tag { // Assigned rather than only filled when empty: a tag is a name of the declaration's own, and // the "last name wins" rule below is exactly the one that should apply to it. - Some(tag) => named = Some(Type::named(tag)), + Some(tag) => { + // **A definition writes its keyword too.** `struct point { … } origin;` carries the + // keyword on the definition node rather than as a sibling `BuiltinType`, and `origin` is + // still a `struct point` — so the tag is read from the node's own kind. `class` and `enum` + // definitions are not C record tags. + record_tag = match CppSyntaxKind::from(node.kind()) { + CppSyntaxKind::StructDef => Some(RecordTag::Struct), + CppSyntaxKind::UnionDef => Some(RecordTag::Union), + _ => record_tag, + }; + named = Some(ComputedType::named(tag, Vec::new())); + } None => an_unnamed_body = true, } } @@ -2205,7 +1746,7 @@ pub(crate) fn read_specifiers_named( _ => { let written = written_trimmed(&node); if !written.is_empty() && spelling.is_none() { - spelling = Some(Type::named(written)); + spelling = Some(ComputedType::named(written, Vec::new())); } } } @@ -2213,7 +1754,7 @@ pub(crate) fn read_specifiers_named( // **A `const` written before the type's name stays with it.** This function used to drop it, with the argument // that "this layer does not resolve aliases, so `const Int` and `Int` are already two names for one type" — and - // that argument is true about *lookup*, which is what [`base_type_name`] and [`Type::class_name`] strip + // that argument is true about *lookup*, which is what [`base_type_name`] and [`ComputedType::class_name`] strip // qualifiers for. It is false about the two questions a **declaration's recorded type** answers: whether a value // converts to it (`const char*` accepts a string literal and `char*` does not, which is where a production // project's `static constexpr const char* Name = "…";` was reported as "does not convert to `char*`"), and what @@ -2229,9 +1770,18 @@ pub(crate) fn read_specifiers_named( // that took the first name recorded `__PURE_APPDOMAIN_GLOBAL` where the cooked reading of the same line recorded // `istream`, so the two declarations disagreed about the type and neither answered. let answer = if !builtin.is_empty() { - Type::builtin(builtin.join(" ")) + ComputedType::builtin(builtin.join(" ")) } else if let Some(named) = named { - named + // **The tag wraps the name it was written before.** `struct point` is one type whose written keyword has to + // survive the fact boundary — see [`RecordTag`] — and the wrapper is transparent to lookup and to the + // conversion relation, so only its display and C's record rule read it. + match record_tag { + Some(tag) => ComputedType::ElaboratedRecord { + tag, + of: Arc::new(named), + }, + None => named, + } } else if (an_unnamed_body || elaborated) && spelling.is_none() { // **A class body nothing named is a type, and it has no spelling here.** `void` is not "no answer": it is a // *different type*, and recording it made `static const struct { … } priority[];` answer `void[]` — measured @@ -2242,16 +1792,18 @@ pub(crate) fn read_specifiers_named( // **An elaborated keyword with no name after it is the same answer**, and it is the leftover half of the // `BuiltinType` note above: `struct` where an unexpanded macro should have named the type. Returning `void` // would claim a type the file never wrote. - return Type::builtin(""); + return ComputedType::builtin(""); } else { - spelling.unwrap_or_else(|| Type::builtin("void")) + spelling.unwrap_or_else(|| ComputedType::builtin("void")) }; - match qualifiers_written.is_none() { - true => answer, - false => Type::Qualified { + if qualifiers_written.is_none() { + answer + } else { + ComputedType::Qualified(Arc::new(QualifiedType { of: Arc::new(answer), - qualifiers: qualifiers_written, - }, + is_const: qualifiers_written.is_const(), + is_volatile: qualifiers_written.is_volatile(), + })) } } @@ -2308,17 +1860,17 @@ fn trailing_template_id(written: &str) -> Option { /// /// ```text /// what a class question asks `std::vector` what has members -/// what a consumer shows `std::vector` [`Type::Display`] writes it back +/// what a consumer shows `std::vector` [`ComputedType::Display`] writes it back /// ``` /// -/// Keeping the arguments **out** of the name rather than in it is what makes [`Type::class_name`] a field read +/// Keeping the arguments **out** of the name rather than in it is what makes [`ComputedType::class_name`] a field read /// instead of a second parse, and what makes a type with arguments compare unequal to the same class without them — /// `std::vector` and `std::vector` are different types, and a `std::vector` written as a template argument is /// not a vector of nothing. /// /// The arguments are read from their own child rather than by parsing the text, because an argument's text can /// contain commas and parentheses that a splitter would get wrong. -fn read_named(node: &CppSyntaxNode) -> Option { +fn read_named(node: &CppSyntaxNode) -> Option { let written = written_trimmed(node); if written.is_empty() { return None; @@ -2353,7 +1905,7 @@ fn read_named(node: &CppSyntaxNode) -> Option { return None; } - Some(Type::Named { name, arguments }) + Some(ComputedType::named(name, arguments)) } /// The types written in a template argument list, in order. @@ -2366,7 +1918,7 @@ fn read_named(node: &CppSyntaxNode) -> Option { /// `std::array`; /// * a **pack expansion** (`std::tuple`) is a parameter standing for several arguments, which is a shape /// of its own because substituting into it is not substituting into a name. -pub(crate) fn read_template_arguments(list: &CppSyntaxNode) -> Vec { +pub(crate) fn read_template_arguments(list: &CppSyntaxNode) -> Vec { let mut arguments = Vec::new(); for child in list.children() { @@ -2378,9 +1930,10 @@ pub(crate) fn read_template_arguments(list: &CppSyntaxNode) -> Vec { let trimmed = text.trim(); if trimmed.ends_with("...") { let inner = trimmed.trim_end_matches('.').trim(); - arguments.push(Type::Pack { - of: Arc::new(Type::named(inner)), - }); + arguments.push(ComputedType::Pack(Arc::new(ComputedType::named( + inner, + Vec::new(), + )))); continue; } @@ -2388,7 +1941,7 @@ pub(crate) fn read_template_arguments(list: &CppSyntaxNode) -> Vec { CppSyntaxKind::TemplateArgument => { arguments.push(read_argument(&child)); } - _ => arguments.push(Type::named(trimmed)), + _ => arguments.push(ComputedType::named(trimmed, Vec::new())), } } @@ -2396,7 +1949,7 @@ pub(crate) fn read_template_arguments(list: &CppSyntaxNode) -> Vec { } /// One template argument: its type if it writes one, and its own spelling otherwise. -fn read_argument(node: &CppSyntaxNode) -> Type { +fn read_argument(node: &CppSyntaxNode) -> ComputedType { // `typename T::type` is a dependent name: the parser wraps it, and the `typename` keyword is a claim that what // follows is a type. The name is what this layer can carry. for child in node.children_with_tokens() { @@ -2405,6 +1958,15 @@ fn read_argument(node: &CppSyntaxNode) -> Type { }; match CppSyntaxKind::from(inner.kind()) { + // **A nested type-id**, which the grammar wraps as `TemplateArgument > TypeId > DeclSpecifierSeq > …`. + // Read with the type-id reader rather than with `read_named`: the latter reconstructs the *spelling* + // `Duo` and would keep it as one opaque name, so a parameter inside it could never be substituted. + // Measured on `Cursor> find(…)`: the class's own `A`/`B` reached the card as the letters. + CppSyntaxKind::TypeId => { + if let Some(found) = type_of_a_type_id(&inner) { + return found; + } + } // Both wrappers: a written type name is what this arm is for, and a plain name is a `NamedType` while a // template-id is a `TemplateType`. CppSyntaxKind::TemplateType | CppSyntaxKind::NamedType => { @@ -2413,13 +1975,13 @@ fn read_argument(node: &CppSyntaxNode) -> Type { } } CppSyntaxKind::BuiltinType => { - return Type::builtin(inner.text().to_string().trim()); + return ComputedType::builtin(inner.text().to_string().trim()); } _ => {} } } - Type::named(node.text().to_string().trim()) + ComputedType::named(node.text().to_string().trim(), Vec::new()) } /// Does this node's span **contain the start** of that range? @@ -2463,209 +2025,168 @@ fn declarator_holding_the_name(declarator: &CppSyntaxNode, name: SourceRange) -> } } -/// **Wrap `base` in everything the declarator wrote around the name** — from the outside in. +/// **Wrap `base` in everything the declarator wrote around the name.** /// -/// # Why the outside comes first +/// # The reading, and why a level list is not enough /// -/// Because that is the order the type is built in, and the parentheses are what make it so. Without them a -/// declarator reads left to right and the operators apply in the order they are met: `Widget* p` is a pointer to -/// `Widget`, and iterating the levels from the name outwards gets that right by accident. With them the reading -/// flips: `int (*p)[4]` is a pointer to an array, and `typedef void (*Callback)(int)` is a pointer to a function — -/// while the same tokens without parentheses (`int *p[4]`, `void *Callback(int)`) are an array of pointers and a -/// function returning a pointer. A walk that started at the name produced `void*(int)` for the third of those: -/// **a function returning a pointer, which is the type the file did not write**. +/// A C declarator is read from the name outwards — `int (*p)[4]` says "`p` is a pointer to an array of four `int`s" +/// — and the type is built from the base in the **reverse** of that reading. Parentheses change the reading, which +/// is the whole difference between `int (*p)[4]` (a pointer to an array) and `int *p[4]` (an array of pointers). +/// A walk that applied a fixed level order got one of the two wrong: the earlier outside-in walk answered +/// `void*(int)` for `typedef void (*Callback)(int)` — a function returning a pointer, which is the type the file +/// did not write — and an inside-out walk answers `int(int)*`/`int*[4]` for the other grouping. /// -/// # The rule at one level +/// So this collects the declarator's operators in **reading order** (nearest the name first: the inner declarator, +/// then the postfix list/extent at this level, then the prefix pointer/reference wrappers), and applies them to the +/// base in reverse. That is exactly the language's rule, and it needs no special case for a parenthesised shape: /// /// ```text -/// a child Declarator the way further in: recurse, then apply this level's operators to the result -/// no child Declarator the name is here: apply this level's operators to the base +/// int (*p)[4] name p → * (pointer) → [4] (array) Pointer(Array(int)) +/// int *p[4] name p → [4] (array) → * (pointer) Array(Pointer(int)) +/// int (*table[3])(int) name table → [3] → * → (int) Array(Pointer(Function(int))) +/// Widget* make() name make → () → * Function(Pointer(Widget)) +/// int f(int) name f → (int) Function(int) /// ``` /// -/// and "this level's operators" are its children that are not that declarator — `PointerType`, `ReferenceType`, -/// `ArrayType`, `ParameterList`. The chain always ends at a level whose child *is* the name, because that is what -/// [`declarator_holding_the_name`] descended to; the `innermost` argument is only the stop condition. -/// -/// A `ParameterList` is an operator like the others, and that is the whole of the difference between a function and -/// a pointer to one: `int f(int)` has the list at the level holding `f`, while `int (*f)(int)` has it at the level -/// *outside* the parentheses, so the pointer is applied first and the list wraps the pointer. +/// A `ParameterList` at the name's own level is an **object's constructor call**, not a function type — see +/// [`type_of_declaration_named`] — and `declares_an_object` says so. fn wrap( - base: Type, + base: ComputedType, outermost: &CppSyntaxNode, innermost: &CppSyntaxNode, name: SourceRange, - // **Is the declared thing an object?** See [`type_of_declaration_named`]: an object's parameter list at the - // name's own level is its **constructor call**, not its type. declares_an_object: bool, -) -> Type { - /// One operator at one level, applied to the type read so far. - /// - /// `None` for a node that is not an operator, which is most of them: a `NameExpr`, a `DeclSpecifierSeq`, an - /// initializer, an attribute. The caller loops rather than matching, because a level can hold more than one - /// operator (`int (*p)[4]`), and the order among them is the order they are written in. - /// - /// `reserve_the_list` is false exactly for the level that holds the name of an **object** — that level's - /// parameter list is the constructor call, and wrapping it would answer the function type. - fn apply(wrapped: &Type, node: &CppSyntaxNode, reserve_the_list: bool) -> Option { - // **The three pointer kinds are one node type**: `*`, `&` and `&&` are a `CppPointerType`, and the reference questions are - // its own — the `&&` used to be read from the node's text. - if let Some(pointer) = CppPointerType::cast(node.clone()) { - return Some(if pointer.is_reference() { - Type::Reference { - to: Arc::new(wrapped.clone()), - rvalue: pointer.is_rvalue_reference(), +) -> ComputedType { + /// One operator the declarator wrote, in reading order. + enum Step { + Pointer, + Reference { rvalue: bool }, + Array { extent: ArrayExtent }, + Parameters(Vec), + } + + /// The pointer/reference wrappers inside a declarator that does **not** reach the name — a prefix operator. + fn prefix_steps(node: &CppSyntaxNode, steps: &mut Vec) { + for child in node.children() { + match CppSyntaxKind::from(child.kind()) { + CppSyntaxKind::PointerType => steps.push(Step::Pointer), + CppSyntaxKind::ReferenceType | CppSyntaxKind::RValueReferenceType => { + steps.push(Step::Reference { + rvalue: CppSyntaxKind::from(child.kind()) + == CppSyntaxKind::RValueReferenceType, + }) } - } else { - Type::Pointer { - to: Arc::new(wrapped.clone()), - } - }); - } - if CppArrayType::can_cast(node.kind().into()) { - return Some(Type::Array { - of: Arc::new(wrapped.clone()), - extent: array_extent(node), - }); - } - if CppParamList::can_cast(node.kind().into()) { - // **An object's own parameter list is its constructor call**, not its type — see - // [`type_of_declaration_named`]. The flag is false only at the level that holds the name, so - // `int (*fp)(int)` (a list at the *pointer*'s level) still wraps into a function type. - if !reserve_the_list { - return None; - } - return Some(Type::Function { - returns: Arc::new(wrapped.clone()), - parameters: read_parameters(node), - }); - } - // **A nested declarator that is not the way down is an operator wrapper.** - // - // The tree keeps the derived-type part of a declaration in a declarator of its own: `Widget* w` has the star inside an - // inner `Declarator` holding a `PointerType`, while the **name** sits at the outer level. [`at_level`] walks only the - // declarators that *reach the name*, and it treats everything else as an ordinary child — which is right for a `NameExpr` - // and wrong for this, so the star was never applied and `Widget* w` read as `Widget`. Measured: four type tests and three - // semantic ones failed on it. - // - // Recursing here applies the wrapper's own operators, in the order they are written, to what has been read so far — which - // is what [`at_level`] would have done with them had they been written one level up. - if !CppDeclarator::can_cast(node.kind().into()) { - return None; - } - let mut wrapped = wrapped.clone(); - for inner in node.children() { - // A nested declarator is an operator wrapper and never the name's own level: a parameter list it - // holds belongs to a pointer (or a reference), so it always wraps into a function type. - if let Some(next) = apply(&wrapped, &inner, true) { - wrapped = next; + CppSyntaxKind::Declarator => prefix_steps(&child, steps), + _ => {} } } - Some(wrapped) } - /// The type of one declarator level, given the type the level **inside** it produced. - /// - /// `inside` is the specifiers' type when this is the level holding the name, and `None` when the level inside - /// this one is still to be read — which is why the parameter is an `Option` and why the operators are applied - /// whether or not it is `Some`: a level that wraps nothing yet still *has* operators to contribute, and - /// skipping them because the inner answer had not arrived yet is how `Widget* p` came back as `Widget`. - fn at_level( + /// Collect one level's steps in reading order: the way down first, then its postfix operators, then its prefix + /// wrappers (nearest the name first, which is the reverse of the order they are written in). + fn steps_of( level: &CppSyntaxNode, name: SourceRange, - inside: Option, - base: &Type, - declares_an_object: bool, innermost: &CppSyntaxNode, - ) -> Type { - // **The way down is not an operator**, and this is the rule rather than a special case: the operators of a - // declaration are the nodes that are *not* on the path from the type to the name. Without the filter, - // `(*p)`'s only child is `*p` and the pointer would be applied twice. - let mut wrapped = inside.unwrap_or_else(|| base.clone()); + declares_an_object: bool, + steps: &mut Vec, + ) { + let down = level + .children() + .filter(|child| CppDeclarator::can_cast(child.kind().into())) + .find(|child| reaches(child, name)); + if let Some(down) = &down { + steps_of(down, name, innermost, declares_an_object, steps); + } + + let at_the_name = level.text_range() == innermost.text_range(); for child in level.children() { - // **Only a `Declarator` can be the way down**, and the test is its kind rather than "does it contain the - // name". The containment test is true of a `ParameterList` and an `ArrayType` as well — they are written - // after the name and their spans reach past it — so using it skipped exactly the operators this function - // exists to apply, which is how `void (*Callback)(int)` came back as `void*(int)`. - if CppDeclarator::can_cast(child.kind().into()) && reaches(&child, name) { + match CppSyntaxKind::from(child.kind()) { + CppSyntaxKind::ArrayType => steps.push(Step::Array { + extent: array_extent(&child), + }), + CppSyntaxKind::ParameterList if !(declares_an_object && at_the_name) => { + steps.push(Step::Parameters(read_parameters(&child))) + } + _ => {} + } + } + + // The prefix wrappers, nearest the name first. `down` is the way to the name and is not one of them. + let mut prefix = Vec::new(); + for child in level.children() { + if down + .as_ref() + .is_some_and(|down| child.text_range() == down.text_range()) + { continue; } - // **The level that holds the name owns its list.** An object's list there is its constructor call, so - // the list is reserved for no one; every other level's list belongs to a pointer and wraps. - let at_the_name = level.text_range() == innermost.text_range(); - if let Some(next) = apply(&wrapped, &child, !(declares_an_object && at_the_name)) { - wrapped = next; + if CppDeclarator::can_cast(child.kind().into()) { + prefix_steps(&child, &mut prefix); + } else { + match CppSyntaxKind::from(child.kind()) { + CppSyntaxKind::PointerType => prefix.push(Step::Pointer), + CppSyntaxKind::ReferenceType | CppSyntaxKind::RValueReferenceType => prefix + .push(Step::Reference { + rvalue: CppSyntaxKind::from(child.kind()) + == CppSyntaxKind::RValueReferenceType, + }), + _ => {} + } } } - - wrapped + steps.extend(prefix.into_iter().rev()); } - // The levels from the outside in, **found by the descent that already exists** rather than by a climb: - // [`declarator_holding_the_name`] walks from the outermost declarator to the one holding the name, one strict - // narrowing step at a time, and the path it takes *is* the list of levels. Writing the walk a second time here - // — upwards — is what produced an eight-gigabyte allocation, because `ancestors()` can answer with the node it - // was asked about and a loop that walks it never advances. - let mut levels: Vec = vec![outermost.clone()]; - let mut current = outermost.clone(); - while current.text_range() != innermost.text_range() { - let Some(down) = current - .children() - .filter(|child| CppDeclarator::can_cast(child.kind().into())) - .find(|child| reaches(child, name)) - else { - break; - }; - levels.push(down.clone()); - current = down; - } + let mut steps = Vec::new(); + steps_of(outermost, name, innermost, declares_an_object, &mut steps); - // Applied **outside in**, and that direction is the whole of the difference between a function and a pointer to - // one. Read the levels from the name outwards and each one is something done *to* what is inside it — that is - // what the parentheses are for, and it is why a member's own type is a function of the level nearest the name - // rather than of the outermost one: - // - // ```text - // int (*f(int))(int) `f` → call it with an int → `int(*)(int)(int)`'s inner part - // `*f` → dereference that → `int(*)(int)` - // `(*f)(int)` → call *that* with an int → `int` - // ``` - // - // so iterating **innermost first** builds the type the declaration wrote, and iterating outermost first builds - // `void*(int)` for `void (*cb)(int)` — a function returning a pointer where the file wrote a pointer to a - // function. Measured: five tests failed on that one inversion, and the two about arrays failed on it as well - // (`int (*p)[4]` came back as a function). - let mut wrapped: Option = None; - for level in levels.iter().rev() { - wrapped = Some(at_level( - level, - name, - wrapped, - &base, - declares_an_object, - innermost, - )); + let mut written = base; + for step in steps.into_iter().rev() { + written = match step { + Step::Pointer => ComputedType::Pointer(Arc::new(written)), + Step::Reference { rvalue } => ComputedType::Reference { + to: Arc::new(written), + rvalue, + }, + Step::Array { extent } => ComputedType::Array { + of: Arc::new(written), + extent, + }, + Step::Parameters(parameters) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(written), + parameters: parameters.into_boxed_slice(), + })), + }; } - - wrapped.unwrap_or(base) + written } -/// The `[4]` of an array declarator, when it is a number this layer can read. +/// The `[4]` of an array declarator, as the bound it states. /// -/// `None` for `[]` **and** for `[N]` — a size that is a name is a value this layer does not have, and the extent -/// of an array is not a question any query here asks. It is recorded so that a consumer showing the type can write -/// it back. -fn array_extent(node: &CppSyntaxNode) -> Option { +/// `[]` is [`ArrayExtent::Unspecified`], a number is [`ArrayExtent::Literal`], and **anything else is kept as the +/// declaration wrote it** — `COUNT`, `NSUBEXP`, `('z' - 'a' + 1)`, a template argument — because the bound is part of +/// the type and a layout question evaluates it where the declaration stands. Collapsing it to "no extent" made +/// `int a[COUNT]` indistinguishable from a flexible array `int a[]`, and the dimension survived only if a consumer +/// reassembled the declaration's spelling from the tree. +pub(crate) fn array_extent(node: &CppSyntaxNode) -> ArrayExtent { let text = node.text().to_string(); let inside = text .trim() .trim_start_matches('[') .trim_end_matches(']') .trim(); - inside.parse().ok() + if inside.is_empty() { + return ArrayExtent::Unspecified; + } + match inside.parse::() { + Ok(literal) => ArrayExtent::Literal(literal), + Err(_) => ArrayExtent::written(inside), + } } /// The parameters of a `ParameterList`, as types — for a function type's shape. -pub(crate) fn read_parameters(list: &CppSyntaxNode) -> Vec { +pub(crate) fn read_parameters(list: &CppSyntaxNode) -> Vec { let mut parameters = Vec::new(); for parameter in list.children() { @@ -2745,7 +2266,7 @@ pub fn is_a_deduced_type(written: &str) -> bool { /// **A type spelling with some names replaced by what they stand for** — whole words only. /// -/// This is the spelling-level twin of [`Type::substituted`], and it exists for the one step that has no `Type` to +/// This is the spelling-level twin of [`ComputedType::substituted`], and it exists for the one step that has no `ComputedType` to /// work with: an **alias template**'s target. `template using enable_if_t = typename /// enable_if<_Test, _Ty>::type;` is stored as the spelling after the `=`, and `enable_if_t` has to become /// `typename enable_if::type` before anything can be looked up in it. The target is text at that point — @@ -2754,7 +2275,11 @@ pub fn is_a_deduced_type(written: &str) -> bool { /// Whole words, because `_Ty` is a prefix of `_Ty2` and a substring replacement would rewrite a name the alias never /// mentioned. An identifier that is not one of `names` is left alone, which is the ordinary case: the target's own /// `enable_if` and its `typename` are not parameters. -pub fn substituted_spelling(written: &str, names: &[String], arguments: &[String]) -> String { +pub fn substituted_spelling, A: AsRef>( + written: &str, + names: &[N], + arguments: &[A], +) -> String { substituted_spelling_from(written, names, arguments) } @@ -2769,11 +2294,11 @@ pub fn substituted_spelling(written: &str, names: &[String], arguments: &[String /// The default is written in **the declaration's own parameter names** (`_Alloc = allocator<_Ty>`), so it is itself /// substituted with the same arguments before it is used. A default that names its own parameter is left alone — /// that is a spelling this layer cannot expand, and expanding it would not terminate. -pub fn substituted_spelling_with_defaults( +pub fn substituted_spelling_with_defaults, D: AsRef, A: AsRef>( written: &str, - names: &[String], - defaults: &[String], - arguments: &[String], + names: &[N], + defaults: &[D], + arguments: &[A], ) -> String { if names.is_empty() { return written.to_string(); @@ -2781,12 +2306,17 @@ pub fn substituted_spelling_with_defaults( let mut replacements: Vec = Vec::with_capacity(names.len()); for (at, name) in names.iter().enumerate() { - let written_argument = arguments.get(at).filter(|argument| !argument.is_empty()); + let name = name.as_ref(); + let written_argument = arguments + .get(at) + .map(AsRef::as_ref) + .filter(|argument| !argument.is_empty()); let replacement = match written_argument { - Some(argument) => argument.clone(), + Some(argument) => argument.to_string(), None => defaults .get(at) - .map(|default| default.trim()) + .map(AsRef::as_ref) + .map(str::trim) .filter(|default| !default.is_empty() && *default != name && !name.is_empty()) // **Substituted as it is read**, because a default is written in the same parameter names: // `_Alloc = allocator<_Ty>` has to become `allocator` before it can stand for `_Alloc`. @@ -2802,7 +2332,11 @@ pub fn substituted_spelling_with_defaults( /// The walk itself: replace whole words that are one of `names` with the replacement at the same position, and leave /// everything else alone. An **empty** replacement means "keep the word" — the parameter had neither an argument nor /// a default, which is the state the caller must not turn into an erasure. -fn substituted_spelling_from(written: &str, names: &[String], replacements: &[String]) -> String { +fn substituted_spelling_from, R: AsRef>( + written: &str, + names: &[N], + replacements: &[R], +) -> String { // **A use may write fewer arguments than the class declares parameters, and that is not a refusal.** // // `std::vector` writes one argument for a class declared with two parameters (`_Ty`, `_Alloc`), because @@ -2844,11 +2378,14 @@ fn substituted_spelling_from(written: &str, names: &[String], replacements: &[St // parameter's position was an out-of-bounds read waiting for the first use that omitted an argument. match names .iter() - .position(|name| !name.is_empty() && name == word) + .position(|name| { + let name = name.as_ref(); + !name.is_empty() && name == word + }) .and_then(|at| replacements.get(at)) - .filter(|replacement| !replacement.is_empty()) + .filter(|replacement| !replacement.as_ref().is_empty()) { - Some(replacement) => out.push_str(replacement), + Some(replacement) => out.push_str(replacement.as_ref()), None => out.push_str(word), } word.clear(); @@ -2938,7 +2475,7 @@ mod tests { /// /// The **last** declaration of that name, because every fixture declares before it uses and the question these /// tests ask is about the declaration's own type. - fn type_of(source: &str, name: &str) -> Type { + fn type_of(source: &str, name: &str) -> ComputedType { type_of_declarator(source, name) } @@ -2952,7 +2489,7 @@ mod tests { /// The **shortest** declarator containing the name is the one that declares it: a declaration holds the /// declarators of what it declares *and* of the parameters it takes, and both contain the name — so a search /// that took the first would answer about `g` when the question was about `value`. - fn type_of_declarator(source: &str, name: &str) -> Type { + fn type_of_declarator(source: &str, name: &str) -> ComputedType { let tree = CppParser::parse(source, ParserConfig::default()); let root = tree.get_red_root(); @@ -2996,6 +2533,71 @@ mod tests { assert_eq!(written("char c;", "c"), "char"); } + /// **C's tag is part of the type.** `struct point` and `union value` write a keyword that tells a record from a + /// `typedef` of something else. The CST reader keeps it on the type — as `ComputedType::ElaboratedRecord` — rather than + /// dropping it, so a stored fact and the conversion question both have it and neither reads + /// a spelling for it. + #[test] + fn a_c_record_keeps_its_tag_on_the_type() { + let pointed = type_of("struct point *p;", "p"); + assert_eq!(pointed.to_string(), "struct point*"); + let ComputedType::Pointer(to) = &pointed else { + panic!("`struct point *p` is a pointer: {pointed:?}"); + }; + assert!( + matches!( + &**to, + ComputedType::ElaboratedRecord { tag: RecordTag::Struct, of } + if of.class_name() == Some("point") + ), + "the pointer's pointee is the elaborated record: {to:?}" + ); + assert_eq!(pointed.class_name(), None, "a pointer names no class"); + + let value = type_of("union value v;", "v"); + assert_eq!(value.to_string(), "union value"); + assert!( + matches!( + value, + ComputedType::ElaboratedRecord { + tag: RecordTag::Union, + .. + } + ), + "a union writes its own tag: {value:?}" + ); + assert_eq!( + value.class_name(), + Some("value"), + "the tag is transparent to the class question" + ); + + // **The spelling parser and the tree agree**, so a type that crossed a fact boundary and came back is the + // same shape. + assert_eq!(parse_type_spelling(&pointed.to_string()), pointed); + assert_eq!(parse_type_spelling("union value"), value); + + // **An `enum` is not a record tag** — it is an arithmetic type in C, and `enum colour c = 3;` is ordinary + // code — so the reader reports the name alone. + assert_eq!(written("enum colour c = 3;", "c"), "colour"); + assert!(!matches!( + parse_type_spelling("colour"), + ComputedType::ElaboratedRecord { .. } + )); + + // **A typedef use writes no keyword** and stays unelaborated; the alias target may carry the record. + let typedef_use = type_of("typedef struct point point;\npoint p;", "p"); + assert!( + matches!(typedef_use, ComputedType::Named(_)), + "a typedef use writes no keyword: {typedef_use:?}" + ); + assert_eq!( + type_of("typedef struct point point;", "point").to_string(), + "struct point", + "the alias's target is the elaborated record the definition named" + ); + } + /// **The pointer lives in the declarator and the base in the specifiers**, and the two have to be joined in /// the right order — outermost operator nearest the type. /// @@ -3003,7 +2605,7 @@ mod tests { /// used to be `Widget*`, because the specifier reader dropped qualifiers on the argument that they say nothing /// about *which class* a spelling names — true for a member lookup, false for the type a declaration records: it /// made `static constexpr const char* Name = "…";` a `char*`, and a string literal "does not convert" to that. - /// `Type::class_name` remains transparent to the qualifier, so lookups are unaffected. + /// `ComputedType::class_name` remains transparent to the qualifier, so lookups are unaffected. #[test] fn a_pointer_and_a_reference_are_read_out_of_the_declarator() { assert_eq!(written("Widget* p;", "p"), "Widget*"); @@ -3035,15 +2637,68 @@ mod tests { /// An array's extent is kept, and an array **decays** to a pointer when it is used — which is the difference /// between what a declaration says and what an expression of it is. + /// + /// **A dimension that is a name is kept as written**, not collapsed into a flexible array's "no bound": `int + /// arr[COUNT]` displays `[COUNT]`, and its extent is the structured [`ArrayExtent::Written`] a layout question + /// evaluates rather than a lost dimension it has to find again by reassembling the declaration. #[test] fn an_array_keeps_its_extent_and_decays_when_used() { let array = type_of("int arr[4];", "arr"); assert_eq!(array.to_string(), "int[4]"); assert_eq!(array.decay().to_string(), "int*"); assert_eq!(array.class_name(), None); + assert_eq!( + array, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: ArrayExtent::Literal(4), + } + ); let unknown = type_of("int arr[];", "arr"); assert_eq!(unknown.to_string(), "int[]"); + assert!( + matches!( + &unknown, + ComputedType::Array { + extent: ArrayExtent::Unspecified, + .. + } + ), + "a flexible array is not a named dimension: {unknown:?}" + ); + + let named = type_of("enum { COUNT = 3 }; int arr[COUNT];", "arr"); + assert_eq!(named.to_string(), "int[COUNT]"); + assert!( + matches!( + &named, + ComputedType::Array { + extent: ArrayExtent::Written(written), + .. + } if written.as_str() == "COUNT" + ), + "the declaration keeps its dimension: {named:?}" + ); + + // **Both dimensions survive a multi-dimensional declarator.** The reader applies the suffix that is + // written last first (the declarator's own nesting), which this batch does not change; what matters here is + // that neither a literal nor a named bound is lost on the way. + let two_dimensional = type_of("int grid[2][COUNT];", "grid"); + let ComputedType::Array { extent, of } = &two_dimensional else { + panic!("a declarator with two extents is an array: {two_dimensional:?}"); + }; + assert_eq!(extent, &ArrayExtent::Literal(2)); + assert!( + matches!( + &**of, + ComputedType::Array { + extent: ArrayExtent::Written(written), + .. + } if written.as_str() == "COUNT" + ), + "the inner dimension is kept too: {two_dimensional:?}" + ); } /// A reference **decays to what it refers to**, which is what makes `Widget& w; w.size` a member of `Widget`. @@ -3091,11 +2746,9 @@ mod tests { "the text is a name either way" ); - let parameter = Type::TemplateParameter { - name: "T".to_string(), - }; + let parameter = ComputedType::TemplateParameter("T".into()); assert!(parameter.depends_on_a_parameter()); - assert!(!Type::named("Widget").depends_on_a_parameter()); + assert!(!ComputedType::named("Widget", Vec::new()).depends_on_a_parameter()); } /// **A name after `::` is a member, not a parameter and not an alias.** @@ -3130,28 +2783,25 @@ mod tests { #[test] fn a_parameter_is_substituted_by_name() { let names = vec!["T".to_string(), "Alloc".to_string()]; - let arguments = vec![Type::builtin("int"), Type::named("std::allocator")]; + let arguments = vec![ + ComputedType::builtin("int"), + ComputedType::named("std::allocator", Vec::new()), + ]; let substitutions = TypeSubstitutions::new(&names, &arguments); - let reference = Type::Reference { - to: Arc::new(Type::TemplateParameter { - name: "T".to_string(), - }), + let reference = ComputedType::Reference { + to: Arc::new(ComputedType::TemplateParameter("T".into())), rvalue: false, }; assert_eq!(reference.substituted(&substitutions).to_string(), "int&"); - let pair = Type::Named { - name: "std::pair".to_string(), - arguments: vec![ - Type::TemplateParameter { - name: "T".to_string(), - }, - Type::TemplateParameter { - name: "Alloc".to_string(), - }, + let pair = ComputedType::named( + "std::pair", + vec![ + ComputedType::TemplateParameter("T".into()), + ComputedType::TemplateParameter("Alloc".into()), ], - }; + ); assert_eq!( pair.substituted(&substitutions).to_string(), "std::pair>" @@ -3161,11 +2811,9 @@ mod tests { // arguments is not a vector of nothing. let none = TypeSubstitutions::new(&names, &[]); assert_eq!( - Type::TemplateParameter { - name: "T".to_string() - } - .substituted(&none) - .to_string(), + ComputedType::TemplateParameter("T".into()) + .substituted(&none) + .to_string(), "T" ); } @@ -3175,25 +2823,22 @@ mod tests { #[test] fn a_type_that_holds_a_parameter_says_so() { assert!( - Type::Pointer { - to: Arc::new(Type::TemplateParameter { - name: "T".to_string() - }) - } - .depends_on_a_parameter() + ComputedType::Pointer(Arc::new(ComputedType::TemplateParameter("T".into()))) + .depends_on_a_parameter() ); assert!( - Type::Named { - name: "std::vector".to_string(), - arguments: vec![Type::TemplateParameter { - name: "T".to_string() - }], - } + ComputedType::named( + "std::vector", + vec![ComputedType::TemplateParameter("T".into())], + ) .depends_on_a_parameter() ); - assert!(!Type::named("std::vector").depends_on_a_parameter()); + assert!( + !ComputedType::named("std::vector", vec![ComputedType::builtin("int")]) + .depends_on_a_parameter() + ); } /// **Attributes and declaration specifiers are not part of a type.** The old reader answered @@ -3233,7 +2878,7 @@ mod tests { /// **A spelling read back into a shape**, which is what the index path needs: a `DeclFact` records the type as /// text, and a member query needs the *class* in it. /// - /// The one thing pinned here is [`Type::class_name`], because everything else a wrong reading loses is + /// The one thing pinned here is [`ComputedType::class_name`], because everything else a wrong reading loses is /// recoverable and a wrong class name is not: it sends a member query to a class that does not exist. #[test] fn a_spelling_is_read_back_into_the_class_it_names() { @@ -3281,7 +2926,7 @@ mod tests { fn a_spelling_peels_its_operators_outside_in() { let pointed = parse_type_spelling("Widget*"); assert!( - matches!(pointed, Type::Pointer { .. }), + matches!(pointed, ComputedType::Pointer(_)), "a trailing `*` is a pointer, whatever it is written after: {pointed:?}" ); assert_eq!(pointed.to_string(), "Widget*"); @@ -3293,7 +2938,7 @@ mod tests { // the difference is which end was peeled first: the last operator written is the outermost one. let reference_to_pointer = parse_type_spelling("Widget*&"); assert!( - matches!(reference_to_pointer, Type::Reference { .. }), + matches!(reference_to_pointer, ComputedType::Reference { .. }), "the outermost operator is the one written last: {reference_to_pointer:?}" ); // **A reference is not a pointer**, and the two questions are deliberately different: `pointee` answers @@ -3328,15 +2973,11 @@ mod tests { let found = parse_type_spelling("int(int, double)"); assert_eq!(found.to_string(), "int(int, double)"); - let Type::Function { - returns, - parameters, - } = &found - else { + let ComputedType::Function(function) = &found else { panic!("a parameter list at the end is a function type: {found:?}"); }; - assert_eq!(returns.to_string(), "int"); - assert_eq!(parameters.len(), 2); + assert_eq!(function.returns.to_string(), "int"); + assert_eq!(function.parameters.len(), 2); } /// **A sub-type is shared, not copied.** This is the property the [`Arc`] is there for, and it is worth a test @@ -3347,20 +2988,18 @@ mod tests { /// allocations, so a `pointee` that answered with a fresh one would fail here. #[test] fn a_sub_type_is_handed_out_shared_rather_than_copied() { - let pointee: TypeOf = Arc::new(Type::named("Widget")); - let pointer = Type::Pointer { - to: Arc::clone(&pointee), - }; + let pointee = Arc::new(ComputedType::named("Widget", Vec::new())); + let pointer = ComputedType::Pointer(Arc::clone(&pointee)); let handed_out = pointer.pointee().expect("a pointer has a pointee"); assert!( - Arc::ptr_eq(&handed_out, &pointee), + std::ptr::eq(handed_out, &*pointee), "the pointee is the same allocation, not a copy of it" ); // A clone of a compound type shares its children rather than copying them down. let cloned = pointer.clone(); - let Type::Pointer { to } = &cloned else { + let ComputedType::Pointer(to) = &cloned else { panic!("a clone of a pointer is a pointer"); }; assert!(Arc::ptr_eq(to, &pointee)); @@ -3509,6 +3148,100 @@ mod tests { "and it converts to itself: {from:?} -> {to:?}" ); } + + /// **A constrained non-type parameter is a constraint fact, and `auto` is still its type.** + /// + /// `template ` writes the concept as a `NamedType` in front of the `auto` placeholder. The + /// sequence lowers to `Primary(Auto)` — the parameter's own type, which this reader must not replace with the + /// concept — while [`constrained_by`] reads the name in front of the placeholder. `C auto M` is the same + /// path with the concept's type argument, and it too stays a type. + #[test] + fn a_constrained_non_type_parameter_records_its_concept_and_keeps_auto() { + use cpp_parser::{CppAstNode, CppDeclSpecifierSeq, CppTemplateParamList}; + + let tree = CppParser::parse( + "template void f();\n\ + template auto M> void g();\n\ + template void h();\n", + ParserConfig::default(), + ); + assert_eq!(tree.get_errors(), [], "the fixture must parse cleanly"); + let parameters: Vec = tree + .get_red_root() + .descendants() + .filter_map(CppTemplateParam::cast) + .collect(); + assert_eq!(parameters.len(), 3); + + let specifiers = |at: usize| { + let specifiers = parameters[at] + .get_decl_specifiers() + .expect("a template parameter writes specifiers"); + assert!(CppDeclSpecifierSeq::can_cast( + specifiers.syntax().kind().into() + )); + specifiers + }; + + // **The constraint is the node in front of the placeholder**, and the parameter's type is still `auto`. + let integral = specifiers(0); + assert_eq!( + read_specifiers(integral.syntax()), + ComputedType::Primary(PrimaryType::Auto), + "`std::integral auto N` has the type `auto`" + ); + let (fact, display) = + constrained_by(¶meters[0]).expect("`std::integral` is a constraint fact"); + assert_eq!(fact.concept, "integral"); + assert!(fact.arguments.is_empty()); + assert_eq!(display, "std::integral"); + + // **`C auto M` uses the same path**, and the concept's argument is the type `T`. + let constrained = specifiers(1); + assert_eq!( + read_specifiers(constrained.syntax()), + ComputedType::Primary(PrimaryType::Auto), + "`C auto M` has the type `auto`" + ); + let (fact, display) = constrained_by(¶meters[1]).expect("`C` is a constraint fact"); + assert_eq!(fact.concept, "C"); + assert_eq!( + fact.arguments.as_ref(), + [ConstraintArgument::Type(ComputedType::Named(SmolStr::new( + "T" + )))], + "the concept's argument is a type" + ); + assert_eq!(display, "C"); + + // **An ordinary non-type parameter is unconstrained**: no placeholder, so no constraint to read. + assert!( + constrained_by(¶meters[2]).is_none(), + "`int K` writes no concept" + ); + + // **The template-parameter model carries the same answer** — this is the value the declaration builder + // stores, so the fact is reachable from both the tree and the summary. + let list = tree + .get_red_root() + .descendants() + .find(|node| CppTemplateParamList::can_cast(node.kind().into())) + .expect("the first template head"); + let read = template_parameters_with_defaults(&list); + assert_eq!(read[0].name, "N"); + assert_eq!( + read[0].constraint, "std::integral", + "the display half is the concept, not `std::integral auto`" + ); + assert_eq!( + read[0] + .constraint_fact + .as_ref() + .map(|fact| fact.concept.as_str()), + Some("integral"), + "and the structured half names the concept" + ); + } } #[cfg(test)] @@ -3569,7 +3302,11 @@ mod deducing_specifiers { #[test] fn a_written_type_is_still_read() { assert_eq!(read("int x = 1;"), "int"); - assert_eq!(read("struct point p = {0};"), "point"); + assert_eq!( + read("struct point p = {0};"), + "struct point", + "C's tag is part of the type, not a spelling to be stripped" + ); assert_eq!(read("unsigned long n = 0;"), "unsigned long"); } } diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 34df92ea..2cb9ee88 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -6,9 +6,11 @@ use super::*; use crate::DeclFact; use crate::DeclKind; use crate::DeclModifiers; +use crate::DeclaredType; use crate::Known; use crate::ProjectIndex; use crate::build_facts; +use crate::facts_with_their_types; use crate::index; use crate::outline_of; use crate::preprocess; @@ -405,10 +407,14 @@ fn the_nearest_class_keyword(before: &str) -> Option<&str> { } impl Session { - /// **The declarations a call at this offset can reach** — indices into `parameter_lists`. + /// **The declarations a call at this offset can reach** — indices into `parameters`. /// The same resolution the argument checks and the signature popup use, asked over the declarations a caller already /// holds: a hover has the facts of the name under the cursor and needs to know which of them the call can mean. /// + /// `parameters` are each declaration's **resolved** parameter types + /// ([`sema::overload::DeclaredParameters`], from [`Session::declared_parameters_of`]) — the resolver never sees a + /// parameter list's text. + /// /// ```text /// one index the resolution decided (`Choice::One`) /// several every one of them can accept the arguments, and nothing decides between them by type @@ -421,11 +427,11 @@ impl Session { &self, view: &FileView, offset: ReadingOffset, - parameter_lists: &[Option], + parameters: &[sema::overload::DeclaredParameters], template_parameters: &[Vec], ) -> Option> { let (types, candidates) = - self.the_candidates_of_a_call(view, offset, parameter_lists, template_parameters)?; + self.the_candidates_of_a_call(view, offset, parameters, template_parameters)?; match sema::overload::choose(&types, &candidates) { sema::overload::Choice::One(chosen) => Some(vec![chosen]), // **Nothing decides between them**, so the viable set is the answer: every one of them can accept this call, @@ -443,33 +449,57 @@ impl Session { &self, view: &FileView, offset: ReadingOffset, - parameter_lists: &[Option], + parameters: &[sema::overload::DeclaredParameters], template_parameters: &[Vec], ) -> Option { let (types, candidates) = - self.the_candidates_of_a_call(view, offset, parameter_lists, template_parameters)?; + self.the_candidates_of_a_call(view, offset, parameters, template_parameters)?; match sema::overload::choose(&types, &candidates) { sema::overload::Choice::One(chosen) => Some(chosen), _ => None, } } + /// **A declaration's parameters as the resolver takes them** — the structured types materialized from its facts, + /// and the two syntaxes that make the list accept a variable number of arguments: the fact's + /// [`DeclFact::variadic_parameters`] (a C-style `...`, a token of the list) and a parameter's + /// [`crate::index::params::ParameterFact::pack`] (a pack's marker, written inside the parameter). The one step + /// every caller of the two methods above needs, in one place. + /// + /// The types themselves never pass through text: they are resolved from each parameter's `DeclaredType`. + pub fn declared_parameters_of( + &self, + file: &Path, + fact: &DeclFact, + ) -> sema::overload::DeclaredParameters { + let index = self.store.index(); + let parameters = index.parameter_facts_of(file, fact); + let types = parameters + .iter() + .filter_map(|parameter| index.parameter_type(parameter)) + .collect(); + sema::overload::DeclaredParameters::new( + types, + fact.variadic_parameters || parameters.iter().any(|parameter| parameter.pack), + ) + } + /// **The declarations and the argument types of the call at `offset`** — the one walk the two questions above share. pub(crate) fn the_candidates_of_a_call( &self, view: &FileView, offset: ReadingOffset, - parameter_lists: &[Option], + parameters: &[sema::overload::DeclaredParameters], template_parameters: &[Vec], - ) -> Option<(Vec>, Vec)> { + ) -> Option<(Vec>, Vec)> { let token = token_at(&view.root, offset.get())?; let call = token .parent_ancestors() .find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr)?; let arguments = sema::call_syntax::arguments_of(&call)?; - // The engine answers with a parsed `Type` and the file it came from; the resolver ranks spellings, which is the - // same information the facts carry. + // The engine answers with a parsed `ComputedType` and the file it came from; the resolver ranks structures, which is + // the same information the facts carry, so the conversion here is representation rather than a parse. let session: &Session = self; let index: &ProjectIndex = session.store.index(); let resolver = @@ -482,23 +512,20 @@ impl Session { &view.path, resolver, ); - let types: Vec> = arguments + let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(a_type.to_string()), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) .collect(); - let candidates: Vec = parameter_lists + let candidates: Vec = parameters .iter() .enumerate() - .map(|(at, parameters)| { - let (declared, variadic) = parameters - .as_deref() - .map(sema::overload::parameters_in) - .unwrap_or_default(); + .map(|(at, declared)| { + let declared = declared.types.clone(); // **A template candidate is ranked as what the call instantiates**, when the caller // could read its header: `take(T*)` and `take(T)` say nothing about an `int*`, and // deduced they say `int*` and `int`. @@ -508,19 +535,22 @@ impl Session { let declared_for_ordering = declared.clone(); let (types, is_a_template) = match sema::deduction::deduce(&names, &declared, &types) { - Some(arguments) => ( + Some(deduced) => ( declared .iter() - .map(|spelling| { - sema::types::substituted_spelling(spelling, &names, &arguments) + .map(|type_of| { + sema::deduction::substituted(type_of, &names, &deduced) }) .collect(), true, ), None => (declared, !names.is_empty()), }; - let candidate = - sema::overload::Candidate::new(types, variadic, format!("declaration {at}")); + let candidate = sema::overload::Candidate::new( + types, + parameters[at].variadic, + format!("declaration {at}"), + ); if is_a_template { candidate.with_declaration(declared_for_ordering, names.clone()) } else { @@ -548,7 +578,13 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).0 + facts_with_their_types(build_facts( + &view.scopes, + &preprocessing, + &view.root, + &errors, + true, + )) } /// **The declaration's own node**, for a fact that names one — the syntax a rendering needs. @@ -587,7 +623,9 @@ impl Session { /// **The template arguments a call fixes**, for a declaration the caller already holds. /// /// Deduction needs the call's argument types, which is what a `SemanticModel` is for; the names come from the - /// declaration's own text ([`crate::sema::deduction::template_parameters_before`]) and the parameters from its fact. + /// declaration's own text ([`crate::sema::deduction::template_parameters_before`]) and the parameters are the + /// **types** the declaration's facts resolved (`ProjectIndex::parameter_types_of`), because the deduction compares + /// structures. /// `None` when the declaration is not a template, when the offset is not on a call, or when the call does not fix /// every parameter — the three answers for which nothing should be shown as an instantiation. pub fn the_deduced_arguments( @@ -595,8 +633,8 @@ impl Session { view: &FileView, offset: ReadingOffset, template_parameters: &[String], - parameters: &[String], - ) -> Option> { + parameters: &[ComputedType], + ) -> Option> { if template_parameters.is_empty() { return None; } @@ -618,10 +656,10 @@ impl Session { &view.path, resolver, ); - let types: Vec> = arguments + let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(a_type.to_string()), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -646,6 +684,19 @@ impl Session { self.the_generated_members(written_type, &view.path, listed) } + /// [`Session::members_of`] for a type this layer already holds structurally. The written-spelling entry + /// remains for API callers that only have text; this one never splits or parses it. + pub fn members_of_type(&self, view: &FileView, class: &ComputedType) -> Known { + let listed = crate::index::project::members_of_computed( + self.store.index(), + &view.scopes, + &view.root, + &view.path, + class, + ); + self.the_generated_members(&class.to_string(), &view.path, listed) + } + /// **What a class costs in memory**: its size, its alignment, and where each data member sits — see /// [`crate::sema::layout`]. /// /// `written_type` is a spelling (`Widget`, `ns::Widget`). `Known::No` when the name is not a class with a body, @@ -715,6 +766,22 @@ impl Session { _ => Known::No, }; }; + // **An enumeration is not a class layout.** Its enumerators are facts of kind `Variable`, but they occupy + // no storage in the enum value; the type is its underlying integer. Without this arm the member walk tried + // to size every enumerator, so `std::errc`'s card listed all 78 names as "cannot be sized here" instead of + // answering the four bytes the enumeration actually is. Every own member being an enumerator is the shape + // only an enum has; a class cannot contain an enumerator as a data member. + let own: Vec<_> = list.own().collect(); + if !own.is_empty() + && own.iter().all(|member| { + self.store + .index() + .member_fact(member) + .is_some_and(|fact| fact.enumerator) + }) + { + return Known::Yes(a_scalar_layout(4, 4)); + } if list.members.is_empty() { match self.the_size_of_an_alias(view, &head) { Some(Some((size, alignment))) => { @@ -753,8 +820,12 @@ impl Session { let data_members = list .own() .filter(|member| { - member.fact.kind == DeclKind::Variable - && !member.fact.modifiers.contains(DeclModifiers::STATIC) + self.store.index().member_kind(member) == Some(DeclKind::Variable) + && self + .store + .index() + .member_modifiers(member) + .is_some_and(|modifiers| !modifiers.contains(DeclModifiers::STATIC)) }) .count(); @@ -789,23 +860,36 @@ impl Session { // **Declaration order**, which is what decides the offsets: `members_of` answers in the index's own order // (names sorted, because a lookup by name is what it is for), and a layout computed in that order is a // different class. A member's own declaration offset is the only thing that says where it was written. + let index = self.store.index(); let mut own: Vec<&index::ProjectMember> = list.own().collect(); own.sort_by(|left, right| { - left.file.cmp(&right.file).then( - left.fact - .range - .start_offset - .cmp(&right.fact.range.start_offset), - ) + let at = |member: &index::ProjectMember| { + index + .member_fact(member) + .map_or(0, |fact| fact.range.start_offset) + }; + left.fact + .file + .cmp(&right.fact.file) + .then(at(left).cmp(&at(right))) }); for member in own { - let fact = &member.fact; + let Some(fact) = index.member_fact(member) else { + continue; + }; // **Data members only**: a member function, a nested type, a `static` — none of them take a byte in the // object, and `sizeof` does not count them. - if fact.kind != DeclKind::Variable || fact.modifiers.contains(DeclModifiers::STATIC) { + if fact.kind != DeclKind::Variable + || fact.enumerator + || fact.modifiers.contains(DeclModifiers::STATIC) + { continue; } - let Some(type_of) = fact.type_of.as_deref() else { + // **The member's type as its fact carries it, structurally.** An array dimension that is a macro or an + // enumerator is part of the type now (`ArrayExtent::Written`), so layout evaluates it where it stands; + // the declaration's own spelling is not reassembled from the tree, and the walk over the view that used + // to build it is gone. + let Some(type_of) = index.member_computed_type(member) else { unknown.push(fact.name.to_string()); continue; }; @@ -833,21 +917,26 @@ impl Session { unknown.push(fact.name.to_string()); continue; } - // **A type spelled through a macro.** `volatile l_signalT trap;` with `#define l_signalT sig_atomic_t`: + // **A type named through a macro.** `volatile l_signalT trap;` with `#define l_signalT sig_atomic_t`: // the fact records what was *written*, and only expanding it reaches a name the index can size. The // expansion is asked at the member's own offset in its own file, which is where the `#define` in force // is the one a compiler had. Measured on Lua 5.5.0's `lstate.h`: `trap` and `hookmask` are both spelled // `const l_signalT`, and with them unsized `CallInfo`, `lua_State::transferinfo`'s parents and finally // `lua_State` itself all withheld their layout. + // + // This is the **only string fallback left in the member sizing**: the structural type is asked first, + // and only a name that is itself a macro reaches the expansion. An array's dimension is no longer part + // of that spelling — it is in the type — so the fallback is never invited to reassemble the declaration. let measured = self - .the_size_of_a_type_in(view, type_of, depth, Some(&instantiation)) + .the_size_of_a_computed_type_in(view, &type_of, depth, Some(&instantiation)) .or_else(|| { + let spelled = index.member_type_spelling(member)?; let expanded = self.the_type_with_its_macros_expanded( - &member.file, + index.member_path(member)?, fact.range.start_offset, - type_of, + &spelled, )?; - if expanded == type_of { + if expanded == spelled { return None; } self.the_size_of_a_type_in(view, &expanded, depth, Some(&instantiation)) @@ -923,8 +1012,9 @@ impl Session { if let Some(value) = self.the_constant_a_declaration_writes(&found) { return Some(value); } - if let Some(value) = - self.constant_value_of_a_declaration(&found.file, found.fact.name_range, &view.path) + if let Some((file, fact)) = self.definition_parts(&found) + && let Some(value) = + self.constant_value_of_a_declaration(&file, fact.name_range, &view.path) && value >= 0 { return Some(value as usize); @@ -942,8 +1032,9 @@ impl Session { /// is the declaration's own; no `=` there means an enumerator that inherits its value, which this leaves to the /// folder rather than counting by hand. fn the_constant_a_declaration_writes(&self, found: &ProjectDefinition) -> Option { - let text = self.text(&found.file)?; - let after = text.get(found.fact.name_range.end_offset()..)?; + let (file, fact) = self.definition_parts(found)?; + let text = self.text(file)?; + let after = text.get(fact.name_range.end_offset()..)?; let boundary = after.find([',', ';', '}', '{'])?; let declaration = &after[..boundary]; let equals = declaration.find('=')?; @@ -982,10 +1073,12 @@ impl Session { let Known::Yes(alias) = self.store.index().definition(head, &view.path) else { return None; }; - if alias.fact.kind != DeclKind::Type { + let alias_fact = self.store.index().definition_fact(&alias)?; + if alias_fact.kind != DeclKind::Type { return None; } - let target = alias.fact.type_of.as_deref()?.trim(); + let target = self.store.index().type_spelling_of(alias_fact)?; + let target = target.trim(); if target.is_empty() || target == head.trim() { return None; } @@ -1031,8 +1124,9 @@ impl Session { .index() .definition(written_type, asked_from) .value()?; - let text = self.files.read(&found.file)?; - let summary = self.store.index().summary(&found.file)?; + let path = self.definition_path(&found)?; + let text = self.text(&path)?; + let summary = self.store.index().summary(&path)?; let simple = written_type.rsplit("::").next().unwrap_or(written_type); let class = summary.declarations.iter().find(|fact| { fact.name == simple && fact.kind == DeclKind::Type && fact.parameter_list().is_none() @@ -1055,9 +1149,13 @@ impl Session { text: text.to_string(), class_at: class.name_range.start_offset, members, - parameters: class.parameters().to_vec(), - parameter_defaults: class.parameter_defaults().to_vec(), - bases: class.bases().to_vec(), + parameters: class.parameters().iter().map(ToString::to_string).collect(), + parameter_defaults: class + .parameter_defaults() + .iter() + .map(ToString::to_string) + .collect(), + bases: class.bases().iter().map(ToString::to_string).collect(), }) } @@ -1101,6 +1199,98 @@ impl Session { digits.parse().ok() } + /// **The size and alignment of a member's structured type**, in the instantiation the member is written in — + /// the computation-layer twin of [`Session::the_size_of_a_type_in`], and the entry layout now uses. + /// + /// The shape that made the string path necessary is the **array dimension**: a fact carries it as + /// [`ArrayExtent`], so `Point points[COUNT]` is sized by evaluating `COUNT` where the declaration stands — a + /// literal, a macro, an enumerator, or a template argument — and multiplying the element's size. A flexible array + /// `Point points[]` is a zero-extent tail (C's `sizeof` leaves it out) and stays distinguishable from the named + /// bound, which the string path had already lost before it started. + /// + /// Everything the shape alone settles is answered here: a pointer and a reference are a word, a qualifier and + /// C's record tag are transparent, and a builtin is the table [`sema::layout::a_builtin_in_memory`] reads. Only a + /// **name** — a class, a typedef, a member alias — needs the index, and that lookup takes a spelling; the + /// conversion is [`ComputedType`]'s own `Display` of that name and its structural arguments, never the + /// declaration's text and never the whole array. + fn the_size_of_a_computed_type_in( + &self, + view: &FileView, + type_of: &ComputedType, + depth: usize, + instantiation: Option<&Instantiation<'_>>, + ) -> Option<(usize, usize)> { + if depth > 8 { + return None; + } + match type_of { + // **The array first**, because the dimension is the one thing a spelling loses and the reason this + // entry exists. An `Unspecified` bound is a flexible array: zero elements, so the member occupies no + // storage of its own. + ComputedType::Array { of, extent } => { + let count = match extent { + index::types::ArrayExtent::Unspecified => 0, + index::types::ArrayExtent::Literal(count) => usize::try_from(*count).ok()?, + index::types::ArrayExtent::Written(written) => { + self.the_value_of_a_written_extent(view, written, instantiation)? + } + }; + let (element_size, element_alignment) = + self.the_size_of_a_computed_type_in(view, of, depth + 1, instantiation)?; + element_size + .checked_mul(count) + .map(|size| (size, element_alignment)) + } + // **A pointer or a reference is a word**, whatever it names — eight bytes on the x64 ABI the card states. + ComputedType::Pointer(_) | ComputedType::Reference { .. } => Some((8, 8)), + // **A qualifier is not part of what the type is.** `const Widget` has the size of `Widget`. + ComputedType::Qualified(qualified) => { + self.the_size_of_a_computed_type_in(view, &qualified.of, depth + 1, instantiation) + } + // **C's tag is transparent**: `struct point` is the record `point`, and that is what has a size. + ComputedType::ElaboratedRecord { of, .. } => { + self.the_size_of_a_computed_type_in(view, of, depth + 1, instantiation) + } + ComputedType::Primary(primary) => sema::layout::a_builtin_in_memory(primary.spelling()), + // **A name needs the index**, and a class/typedef lookup takes a spelling. The narrow conversion is + // this one: the structural name, with its structural arguments if any — the declaration's own operators + // were consumed by this walk, and the array dimension was evaluated above. + ComputedType::Named(_) | ComputedType::Generic(_) => { + self.the_size_of_a_type_in(view, &type_of.to_string(), depth + 1, instantiation) + } + // A template parameter has a size only once a use binds it, which the member substitution above does; + // a function and a pack are not objects. + ComputedType::TemplateParameter(_) + | ComputedType::Function(_) + | ComputedType::Pack(_) => None, + } + } + + /// **The value of a dimension the declaration wrote as a name or an expression** — an `ArrayExtent::Written`. + /// + /// It is evaluated by the same reader the string path uses ([`Session::the_value_of_an_array_dimension`]): a + /// literal, a constant expression such as neovim's `('z' - 'a' + 1)`, a macro in force, or an enumerator the + /// index holds. A **template argument** is substituted first, because `_Elems[_Size]` is the shape the standard + /// containers write and `_Size` is a value parameter rather than a macro. That substitution is one name in one + /// dimension — no declaration is reassembled and no fragment is parsed. + fn the_value_of_a_written_extent( + &self, + view: &FileView, + written: &str, + instantiation: Option<&Instantiation<'_>>, + ) -> Option { + let written = match instantiation { + Some(environment) => sema::types::substituted_spelling_with_defaults( + written, + environment.parameters, + environment.defaults, + environment.arguments, + ), + None => written.to_string(), + }; + self.the_value_of_an_array_dimension(view, &written) + } + /// The size and alignment of a member's written type, **in the instantiation the member is written in**. /// /// `instantiation` is `None` for a class that is not a template — the ordinary member — and the class's own @@ -1167,11 +1357,15 @@ impl Session { } if let Some(environment) = instantiation && let Some(alias) = environment.members.iter().find(|member| { - member.fact.kind == DeclKind::Type - && member.fact.name == spelled - && member.fact.parameter_list().is_none() + self.store.index().member_kind(member) == Some(DeclKind::Type) + && self.store.index().member_name(member) == spelled + && self + .store + .index() + .member_fact(member) + .is_some_and(|fact| fact.parameter_list().is_none()) }) - && let Some(target) = alias.fact.type_of.clone() + && let Some(target) = self.store.index().member_type_spelling(alias) { return self.the_size_of_a_type_in(view, &target, depth + 1, instantiation); } @@ -1216,11 +1410,12 @@ impl Session { // `pos_T b_op_start`, `handle_T handle`, `memline_T b_ml` — so without this the layout of most real structs // is "not computed". The alias's own fact holds the spelling it expands to. if let Known::Yes(aliased) = self.store.index().definition(spelled, &view.path) - && let Some(target) = aliased.fact.type_of.as_deref() - && target != spelled + && let Some(aliased_fact) = self.store.index().definition_fact(&aliased) + && let Some(target) = self.store.index().type_spelling_of(aliased_fact) + && target.as_str() != spelled && depth <= 8 { - return self.the_size_of_a_type_in(view, target, depth + 1, instantiation); + return self.the_size_of_a_type_in(view, &target, depth + 1, instantiation); } let Known::Yes(nested) = self.the_layout_of_a_class_with(view, spelled, &[], depth + 1) else { @@ -1248,16 +1443,18 @@ impl Session { let Known::Yes(list) = self.members_of(view, owner) else { return None; }; + let index = self.store.index(); let alias = list.members.iter().find(|candidate| { - candidate.fact.name == member - && candidate.fact.kind == DeclKind::Type - && candidate.fact.type_of.is_some() + index.member_name(candidate) == member + && index.member_kind(candidate) == Some(DeclKind::Type) + && index.member_type_spelling(candidate).is_some() })?; - let written = alias.fact.type_of.as_deref()?; + let written = index.member_type_spelling(alias)?; + let alias_fact = index.member_fact(alias)?; let target = sema::types::substituted_spelling_with_defaults( - written, - alias.fact.parameters(), - alias.fact.parameter_defaults(), + &written, + alias_fact.parameters(), + alias_fact.parameter_defaults(), arguments, ); // **A member whose type *is itself* declares an anonymous class in place.** `struct CallInfo { union { struct @@ -1303,16 +1500,19 @@ impl Session { environment.defaults, environment.arguments, ); + let index = self.store.index(); let Some(alias) = environment.members.iter().find(|member| { - member.fact.kind == DeclKind::Type - && member.fact.name == spelled.trim() - && member.fact.parameter_list().is_none() + index.member_kind(member) == Some(DeclKind::Type) + && index.member_name(member) == spelled.trim() + && index + .member_fact(member) + .is_some_and(|fact| fact.parameter_list().is_none()) }) else { return spelled; }; - match alias.fact.type_of.as_deref() { + match index.member_type_spelling(alias) { Some(target) => sema::types::substituted_spelling_with_defaults( - target, + &target, environment.parameters, environment.defaults, environment.arguments, @@ -1330,14 +1530,15 @@ impl Session { path: &Path, ) -> Option { let known = self.store.index().definition(head, path).value()?; - let written = known.fact.type_of.as_deref()?; - if known.fact.parameters().is_empty() { + let known = self.store.index().definition_fact(&known)?; + let written = self.store.index().type_spelling_of(known)?; + if known.parameters().is_empty() { return None; } let target = sema::types::substituted_spelling_with_defaults( - written, - known.fact.parameters(), - known.fact.parameter_defaults(), + &written, + known.parameters(), + known.parameter_defaults(), arguments, ); (target != head).then_some(target) @@ -1372,34 +1573,55 @@ impl Session { let Known::Yes(mut list) = listed else { return listed; }; + let index = self.store.index(); let declares_static_class = list .members .iter() - .any(|member| member.fact.name == "StaticClass"); + .any(|member| index.member_name(member) == "StaticClass"); let already_generated = list .members .iter() - .any(|member| member.fact.name == "ThisClass"); + .any(|member| index.member_name(member) == "ThisClass"); if !declares_static_class || already_generated { return Known::Yes(list); } - let Known::Yes(declared) = self.store.index().definition(written_type, path) else { + let Known::Yes(declared) = index.definition(written_type, path) else { + return Known::Yes(list); + }; + let Some((_declared_in, declared_fact)) = self.definition_parts(&declared) else { return Known::Yes(list); }; // The synthetic members point at the class's own declaration: that is where the macro that generates them is // written, and it is the honest place for a hover to open. - let class_fact = declared.fact.clone(); + let class_fact = declared_fact.clone(); let class_name = class_fact.name.to_string(); - for (name, type_of) in project::ue::generated_members(&class_name, class_fact.bases()) { + for (name, type_of) in project::ue::generated_members( + &class_name, + &class_fact + .bases() + .iter() + .map(ToString::to_string) + .collect::>(), + ) { let mut fact = class_fact.clone(); fact.name = name.into(); fact.kind = DeclKind::Type; - fact.type_of = Some(type_of.into()); + // **A generated member's type is synthesized, so it is computed, not interned.** There is no file arena + // for this member to point into and no second store to mint a `TypeId` from; the spelling the generator + // wrote is parsed **once, here**, and the value is stored on the fact. Every later reader materializes it + // through `ProjectIndex::computed_type_of`. + fact.type_of = + DeclaredType::Computed(Arc::new(crate::sema::types::parse_type_spelling(&type_of))); + fact.returns = DeclaredType::None; // A generated member is not a member of a **namespace**: it belongs to the class it was generated for. fact.scope = Some(class_name.as_str().into()); + // **The index mints the reference**, in the arena it keeps for facts a query synthesized: the row must + // name a real arena entry even though no file declares this member. A generated member has no parameter + // list of its own, so the arena carries the empty one beside it. + let reference = index.intern_synthetic_fact(declared.file, fact, Box::default()); list.members.push(index::ProjectMember { - file: declared.file.clone(), - fact, + fact: reference, + substitution: None, declared_in: class_name.to_string(), depth: 0, ambiguous: false, @@ -1504,7 +1726,7 @@ impl Session { let mut found = list .members .iter() - .filter(|found| found.fact.name == member); + .filter(|found| self.store.index().member_name(found) == member); let Some(only) = found.next() else { // Nothing in the chain declares it, and the honest answer is the one the direct lookup gave: the @@ -1520,8 +1742,8 @@ impl Session { } Known::Yes(ProjectDefinition { - file: only.file.clone(), - fact: only.fact.clone(), + file: only.fact.file, + fact: only.fact, }) } @@ -1552,7 +1774,13 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - let (facts, _guards) = build_facts(&view.scopes, &preprocessing, &view.root, &errors, true); + let facts = facts_with_their_types(build_facts( + &view.scopes, + &preprocessing, + &view.root, + &errors, + true, + )); outline_of(&facts) } diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 82ad13d1..5e0a5c58 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -86,6 +86,7 @@ pub use table::{ BUILTIN_TYPES, DIRECTIVES, DirectiveName, KEYWORDS, Keyword, KeywordUse, SNIPPETS, Snippet, }; +use crate::index::types::ComputedType; use crate::sema::symbol::{Known, ScopeKind, ScopeTree}; use crate::summary::{DeclFact, DeclKind}; use crate::{ProjectIndex, ProjectMember}; @@ -251,7 +252,7 @@ impl CompletionItem { _ => fact.name.to_string(), }, snippet: false, - detail: detail_of(fact), + detail: detail_of_with_types(fact), identity, filter: None, fact: Some(fact.clone()), @@ -351,15 +352,19 @@ fn kind_of(kind: DeclKind) -> ItemKind { /// `(…)` survives for the one case it is still the honest answer to: a fact written before the field existed, or a /// function whose declarator the reading could not reach. It says "this function takes something", which is less /// than the truth and not more. -pub fn detail_of(fact: &DeclFact) -> Option { +/// **The row's detail, from the values the fact carries.** The declaration's types are immutable ComputedTypes, +/// so the display edge prints them directly; nothing is resolved through a table and nothing is parsed. +pub fn detail_of_with_types(fact: &DeclFact) -> Option { + let returns = fact.returns.computed().map(|returns| returns.to_string()); + let type_of = fact.type_of.computed().map(|type_of| type_of.to_string()); match fact.kind { - DeclKind::Function => match (&fact.returns, &fact.parameter_list()) { + DeclKind::Function => match (returns, fact.parameter_list()) { (Some(returns), Some(parameters)) => Some(format!("{returns} {parameters}")), (Some(returns), None) => Some(format!("{returns} (…)")), (None, Some(parameters)) => Some(parameters.to_string()), (None, None) => None, }, - DeclKind::Variable => fact.type_of.clone().map(|ty| ty.to_string()), + DeclKind::Variable => type_of, DeclKind::Type if !fact.bases().is_empty() => { Some(format!(": {}", fact.bases().join(", "))) } @@ -756,7 +761,7 @@ pub(crate) fn the_class_after_the_operator( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - written: &sema::types::Type, + written: &ComputedType, arrow: bool, ) -> Option<(String, bool)> { let (reached, followed_a_pointer) = @@ -781,13 +786,14 @@ pub(crate) fn the_type_after_the_operator( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - written: &sema::types::Type, + written: &ComputedType, arrow: bool, -) -> Option<(sema::types::Type, bool)> { +) -> Option<(ComputedType, bool)> { // **Whether a pointer was followed to find the class**, which is what says a `.` should have been a `->`. let mut followed_a_pointer = false; let mut current = written.clone(); for _ in 0..4 { + eprintln!("[arrow loop] current={current}"); if let Some(bare) = current.class_name().map(str::to_string) { // **The spelling the use wrote is not always the one the index keys the class on.** `auto unique = // std::make_unique(1);` makes `unique`'s type `unique_ptr`, whose class is declared as @@ -864,12 +870,13 @@ pub(crate) fn the_type_after_the_operator( // **A dot does not follow a class's `operator->`** — see the note on step 1 above. None }; + eprintln!("[arrow] class={class} current={current} returns={returns:?}"); let Some(returns) = returns else { // **3. Where the arrow stops.** A plain `struct` on the left of `->` is ill-formed, and its members // are the honest answer for a reader who typed one by mistake. return Some((current, followed_a_pointer)); }; - current = sema::types::parse_type_spelling(&returns); + current = returns; if !arrow { followed_a_pointer = true; } @@ -916,14 +923,14 @@ fn the_element_type_pointed_at( root: &CppSyntaxNode, path: &Path, class: &str, - written: &sema::types::Type, + written: &ComputedType, ) -> Option { let Known::Yes(members) = index::project::members_of(index, scopes, root, path, class) else { return None; }; let pointer_like = members.members.iter().any(|member| { matches!( - member.fact.name.as_str(), + index.member_name(member), "element_type" | "operator->" | "operator*" ) }); @@ -1098,7 +1105,7 @@ fn members_of_a_type( root: &CppSyntaxNode, path: &Path, offset: usize, - written: &sema::types::Type, + written: &ComputedType, arrow: bool, prefix: String, replace: SourceRange, @@ -1226,7 +1233,7 @@ fn members_of_a_type( { continue; } - let bases = declared_by.entry(member.fact.name.as_str()).or_default(); + let bases = declared_by.entry(index.member_name(member)).or_default(); if !bases.contains(&member.declared_in.as_str()) { bases.push(member.declared_in.as_str()); } @@ -1242,19 +1249,23 @@ fn members_of_a_type( for member in &members.members { // **A name the implementation owns is not offered to a reader who is not typing one.** See // [`reserved_for_the_implementation`] for the rule and the screenshot behind it. - if reserved_for_the_implementation(&member.fact.name, &prefix) { + if reserved_for_the_implementation(index.member_name(member), &prefix) { continue; } // **A member the reader cannot name is not offered** — and that decision is the *query's*, not this // layer's: `member_completions_at` compares each member's access level with the classes the cursor is in // and reports what it kept out (`MemberCompletions::hidden_by_access`). Filtering here as well would be a // second reader of one rule, which is the shape of every bug in this area. - if !seen.insert(member.fact.name.as_str()) { + if !seen.insert(index.member_name(member)) { continue; } - let mut item = CompletionItem::declared(&member.fact, &member.file); - item.kind = member_kind(member, &class); + let (Some(fact), Some(file)) = (index.member_fact(member), index.member_path(member)) + else { + continue; + }; + let mut item = CompletionItem::declared(fact, file); + item.kind = member_kind(index, member, &class); item.replace = replace; if member.depth > 0 { @@ -1288,7 +1299,7 @@ fn members_of_a_type( // // The label carries the `::` it inserts, which is also what tells it apart from an **inherited constructor** // of the same name — `First` (the constructor) and `First::` (the base) used to read the same. - if let Some(bases) = declared_by.get(member.fact.name.as_str()) + if let Some(bases) = declared_by.get(index.member_name(member)) && bases.len() >= 2 { for base in bases { @@ -1302,7 +1313,7 @@ fn members_of_a_type( if matched == matching::NONE { continue; } - let score = member_score(member, &class); + let score = member_score(index, member, &class); scored.push(Scored { score: Score { tier: score.tier + 60, @@ -1327,7 +1338,7 @@ fn members_of_a_type( } scored.push(Scored { - score: member_score(member, &class), + score: member_score(index, member, &class), matched, item, }); @@ -1590,11 +1601,14 @@ fn names( names: index .declarations_in(&resolved, path) .into_iter() - .map(|declaration| OfferedName { - fact: declaration.fact.clone(), - file: declaration.file.clone(), - depth: 0, - from: index::project::NameProvenance::Scope, + .map(|declaration| { + // The walk already carries the exact arena entry, so the row is minted from it rather than + // from a copy of the declaration. + OfferedName::of_a_visible_declaration( + &declaration, + 0, + index::project::NameProvenance::Scope, + ) }) .collect(), }) @@ -1626,20 +1640,28 @@ fn names( let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new(); for offered in &listed.names { + // **The row names a declaration; the index is what resolves it.** Every access below is that one + // resolution used at the display edge — a row whose fact cannot be resolved is not offered, which a + // constructor that minted it through the index cannot produce. + let (Some(fact), Some(file)) = + (index.offered_fact(offered), index.offered_path(offered)) + else { + continue; + }; // **A name the implementation owns is not offered to a reader who is not typing one.** This is what // kept the `std::` list full of `_Adl_verify_range`, `_Add_alloc_size`, `_Allocate_at_least_helper` — // reported with a screenshot from an editor. See [`reserved_for_the_implementation`]. - if reserved_for_the_implementation(&offered.fact.name, &listed_prefix) { + if reserved_for_the_implementation(&fact.name, &listed_prefix) { continue; } // The query hides what an inner scope hides. What it cannot hide is one spelling listed twice by // *two files* — a namespace two headers reopen, a declaration and its redeclaration — and the list // is a list of things to type. - if !seen.insert(offered.fact.name.as_str()) { + if !seen.insert(fact.name.as_str()) { continue; } - let mut item = CompletionItem::declared(&offered.fact, &offered.file); + let mut item = CompletionItem::declared(fact, file); item.replace = replace; // **What is being typed is the tail of the name.** Inside `std::` the reader writes `str` and means @@ -1647,7 +1669,7 @@ fn names( // substring), but a qualified detail is what makes the *ordering* stable when two scopes declare // one name. if !listed.scope.is_empty() { - item.filter = Some(format!("{}::{}", listed.scope, offered.fact.name)); + item.filter = Some(format!("{}::{}", listed.scope, fact.name)); } // **Matched against what the client would filter on**, which is `filter` when the item has one and the @@ -1662,7 +1684,7 @@ fn names( } scored.push(Scored { - score: name_score(offered), + score: name_score(index, offered), matched, item, }); @@ -1980,10 +2002,10 @@ fn doc_comments( .parameters() .iter() .filter(|name| !name.is_empty()) - .cloned() + .map(ToString::to_string) .collect(); - if let Some(list) = fact.parameter_list() - && let Some(found) = sema::call_syntax::parameter_names_from_text(list) + if let Some(found) = + sema::call_syntax::parameter_names_of_fact(index.parameter_facts_of(path, fact)) { names.extend(found.into_iter().flatten()); } @@ -2247,15 +2269,15 @@ fn written_before(access: &sema::resolve::MemberAccess, offset: usize) -> String /// Which kind of member this is, for the icon: a member function is a method, a variable is a field, and a function /// whose name spells its own class is a constructor. -fn member_kind(member: &ProjectMember, class: &str) -> ItemKind { - match member.fact.kind { - DeclKind::Function if member.fact.name == class => ItemKind::Function, - DeclKind::Function => ItemKind::Method, - DeclKind::Variable => ItemKind::Field, - DeclKind::Type => ItemKind::Class, - DeclKind::Namespace => ItemKind::Namespace, - DeclKind::MacroLike => ItemKind::Macro, - DeclKind::Other => ItemKind::Field, +fn member_kind(index: &ProjectIndex, member: &ProjectMember, class: &str) -> ItemKind { + match index.member_kind(member) { + Some(DeclKind::Function) if index.member_name(member) == class => ItemKind::Function, + Some(DeclKind::Function) => ItemKind::Method, + Some(DeclKind::Variable) => ItemKind::Field, + Some(DeclKind::Type) => ItemKind::Class, + Some(DeclKind::Namespace) => ItemKind::Namespace, + Some(DeclKind::MacroLike) => ItemKind::Macro, + Some(DeclKind::Other) | None => ItemKind::Field, } } @@ -2404,7 +2426,9 @@ impl Score { } /// The score of a name the scope walk produced: **how far from the cursor its file is**, plus what it declares. -fn name_score(offered: &OfferedName) -> Score { +/// +/// The kind and the spelling come from the index, because the row names a declaration rather than carrying one. +fn name_score(index: &ProjectIndex, offered: &OfferedName) -> Score { use crate::index::project::NameProvenance; let tier = match offered.from { @@ -2418,29 +2442,23 @@ fn name_score(offered: &OfferedName) -> Score { // A destructor is spelled `~D` and a conversion function is not reachable by its spelling either. Both are // listed — they are real declarations — but after everything a reader could be typing the start of. - let penalty = Score::kind_penalty(offered.fact.kind) - + if offered.fact.name.starts_with('~') { - 20 - } else { - 0 - }; + let name = index.offered_name(offered); + let penalty = Score::kind_penalty(index.offered_kind(offered).unwrap_or(DeclKind::Other)) + + if name.starts_with('~') { 20 } else { 0 }; Score::new(tier, penalty) } /// The score of a member of an accessed type. -fn member_score(member: &ProjectMember, class: &str) -> Score { +fn member_score(index: &ProjectIndex, member: &ProjectMember, class: &str) -> Score { // An inherited member is reachable but is not what the class itself declares, so it comes after the class's // own — the order C++ looks in, and the order a reader expects to see. The base walk produced the depth. let tier = Score::LOCAL + 10 * member.depth as i32; - let penalty = Score::kind_penalty(member.fact.kind) - + if member.fact.name == class { 6 } else { 0 } - + if member.fact.name.starts_with('~') { - 20 - } else { - 0 - }; + let name = index.member_name(member); + let penalty = Score::kind_penalty(index.member_kind(member).unwrap_or(DeclKind::Other)) + + if name == class { 6 } else { 0 } + + if name.starts_with('~') { 20 } else { 0 }; Score::new(tier, penalty) } @@ -2479,9 +2497,12 @@ pub fn header_index( #[cfg(test)] mod tests { + use crate::summary::DeclaredType; + use super::*; use crate::DeclModifiers; use crate::FactGuard; + use crate::index::params::ParamsId; use crate::summary; /// **A name that does not answer what was typed is dropped, not ranked low.** The rule itself lives in @@ -2534,7 +2555,15 @@ mod tests { /// fallback that silently stops working. #[test] fn a_functions_detail_line_is_what_it_takes() { - let fact = |returns: Option<&str>, parameter_list: Option<&str>| DeclFact { + use crate::index::types::ComputedType; + + // **A type the fixture writes by name.** A primary spelling becomes the primary; anything else is the name it + // is — `string` here is no builtin, and the detail line must still quote it. + let builtin = |name: &str| match index::types::PrimaryType::from_spelling(name) { + Some(primary) => ComputedType::Primary(primary), + None => ComputedType::named(name, Vec::new()), + }; + let fact = |returns: Option, parameter_list: Option<&str>| DeclFact { enumerator: false, frees: 0, name: "format".into(), @@ -2542,8 +2571,14 @@ mod tests { local: false, kind: DeclKind::Function, modifiers: DeclModifiers::VIRTUAL, - type_of: None, - returns: returns.map(smol_str::SmolStr::from), + type_of: DeclaredType::None, + returns: returns.map_or(DeclaredType::None, |returns| { + DeclaredType::Computed(Arc::new(returns)) + }), + parameters: ParamsId::NONE, + // The fixture's detail line comes from the display spelling, so the list-level `...` is not this + // test's question; `(…)` is what a missing list prints. + variadic_parameters: false, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), clean: true, @@ -2559,20 +2594,24 @@ mod tests { }), }; assert_eq!( - detail_of(&fact(Some("string"), Some("()"))).as_deref(), + detail_of_with_types(&fact(Some(builtin("string")), Some("()"))).as_deref(), Some("string ()"), "a function that takes nothing says so — that is an answer, not an absence" ); assert_eq!( - detail_of(&fact(Some("string"), None)).as_deref(), + detail_of_with_types(&fact(Some(builtin("string")), None)).as_deref(), Some("string (…)"), "and with no list recorded, the old spelling is still the honest one" ); assert_eq!( - detail_of(&fact(None, Some("(int)"))).as_deref(), + detail_of_with_types(&fact(None, Some("(int)"))).as_deref(), Some("(int)"), "a constructor has no return type, and its parameters are then the whole description" ); - assert_eq!(detail_of(&fact(None, None)), None, "nothing to say"); + assert_eq!( + detail_of_with_types(&fact(None, None)), + None, + "nothing to say" + ); } } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index f73a1021..0f2fe9ce 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -8,6 +8,7 @@ use crate::DeclKind; use crate::DeclModifiers; use crate::HeaderIndex; use crate::Known; +use crate::ProjectMember; use crate::completion; use crate::doc; use crate::file; @@ -557,11 +558,17 @@ impl Session { expression, 0, ) { - Known::Yes((type_of, file)) => Known::Yes(ExpressionType { - expression: written, - type_of: type_of.to_string(), - file, - }), + Known::Yes((type_of, file)) => { + if written.contains("transform") { + eprintln!("[expr transform] written={:?} type={:?}", written, type_of); + } + Known::Yes(ExpressionType { + expression: written, + type_of: type_of.to_string(), + type_value: Some(type_of), + file, + }) + } Known::Unknown(reason) => Known::Unknown(reason), Known::No => Known::No, } @@ -591,6 +598,7 @@ impl Session { Some(ExpressionType { expression: object.text().to_string().trim().to_string(), type_of: type_of.to_string(), + type_value: Some(type_of), file, }) } @@ -652,6 +660,7 @@ impl Session { Known::Yes((type_of, file)) => Known::Yes(ExpressionType { expression: written.clone(), type_of: type_of.to_string(), + type_value: Some(type_of), file, }), Known::Unknown(reason) => Known::Unknown(reason), @@ -665,7 +674,7 @@ impl Session { // Only when both are true: this reading has **nothing** to say, and the expression **contains an invocation**. // A crossing on anything else would be a second reading of the same text, and the two can disagree — that is // what a `#if` is for. - if matches!(answer, Known::Unknown(_)) { + if matches!(answer, Known::Unknown(_)) && expression_contains_a_macro_call(&expression) { // **A member of a macro's expansion is asked as a member, not as an expression.** A span cannot cross the // expansion exactly — the writer maps the invocation's trailing bytes to the end of what it expanded — so // asking the whole `tsvalue(o)->shrlen` in the rendering answered the *object*'s type (`TString*`) rather @@ -674,17 +683,26 @@ impl Session { if let Some(access) = sema::resolve::member_access_of(&expression) && let Some(object_type) = self.the_type_of_an_expression_in_the_rendering(&view.path, &access.object) - && let Known::Yes(list) = self.members_of(view, &object_type.type_of) + && let Known::Yes(list) = match &object_type.type_value { + Some(class) => self.members_of_type(view, class), + None => self.members_of(view, &object_type.type_of), + } && let Some(member) = list .members .iter() - .find(|member| member.fact.name == access.member) - && let Some(spelled) = member.fact.type_of.clone() + .find(|member| self.store.index().member_name(member) == access.member) + && let Some(file) = self + .store + .index() + .member_path(member) + .map(Path::to_path_buf) + && let Some(spelled) = self.store.index().member_type_spelling(member) { return Known::Yes(ExpressionType { expression: written, type_of: spelled.to_string(), - file: member.file.clone(), + type_value: None, + file, }); } // **A name alone is a declaration question, not a span.** A macro's name has no rendering counterpart at @@ -719,8 +737,22 @@ impl Session { view: &FileView, offset: ReadingOffset, ) -> Option { + let member = self.member_row_of_the_enclosing_class(view, offset)?; + Some(ProjectDefinition { + file: member.fact.file, + fact: member.fact, + }) + } + + /// **The same member as a row**, for a display consumer that wants the *substituted* fact — the card shows + /// `Node *` for a base's `T *`, and a [`ProjectDefinition`] is a reference to the declaration's own arena entry. + pub fn member_row_of_the_enclosing_class( + &self, + view: &FileView, + offset: ReadingOffset, + ) -> Option { let callee = sema::resolve::name_node_at(&view.root, offset.get())?; - index::project::a_member_of_the_enclosing_class( + index::project::a_member_row_of_the_enclosing_class( self.store.index(), &view.scopes, &view.root, @@ -806,26 +838,41 @@ impl Session { else { return None; }; - // **A binding is a place to jump to, not the declaration's facts.** `definition` answers the call's name from - // the file's own scope tree, and a binding records no parameter list or template parameters — the index's fact - // is the one that does. The same split the hover's card already makes. + // **A definition answer is a reference, not the declaration's facts.** `definition` answers the call's name + // from the file's own scope tree; the arena fact is the one that carries the parameter list and template + // parameters. The same split the hover's card already makes. + let fact_file = self.definition_path(&found)?; + let found_fact = self.definition_fact(&found)?; let fact = match self .store .index() - .definition(&found.fact.qualified_name(), &view.path) + .definition(&found_fact.qualified_name(), &view.path) { - Known::Yes(indexed) => indexed.fact, - _ => found.fact, + Known::Yes(indexed) => self.definition_fact(&indexed).unwrap_or(found_fact), + _ => found_fact, }; if fact.kind != DeclKind::Function || fact.parameters().is_empty() { return None; } - let parameter_list = fact.parameter_list()?; - let parameter_types = inlay::parameter_types_in_a_written_list(parameter_list); + // **The inserted summary already has parameter types.** A fact's parameter resolves to the computation layer + // through [`crate::ProjectIndex::parameter_type`] — a stored handle materialized read-only, so a + // template-argument hint costs no parse and no write to the type store — and the hint quotes it. + let parameter_types: Vec = self + .store + .index() + .parameter_facts_of(&fact_file, fact) + .iter() + .filter_map(|parameter| self.store.index().parameter_type(parameter)) + .map(|computed| computed.to_string()) + .collect(); if parameter_types.is_empty() { return None; } - Some((end, fact.parameters().to_vec(), parameter_types)) + Some(( + end, + fact.parameters().iter().map(ToString::to_string).collect(), + parameter_types, + )) } pub fn type_hints(&self, view: &FileView, range: SourceRange) -> Vec { @@ -843,16 +890,28 @@ impl Session { |at| { let local = self.definition(view, ReadingOffset::new(at)).value(); let indexed = local.as_ref().and_then(|found| { + let fact = self.definition_fact(found)?; self.store .index() - .definition(&found.fact.qualified_name(), &view.path) + .definition(&fact.qualified_name(), &view.path) .value() }); indexed - .and_then(|found| found.fact.returns.map(|returns| returns.to_string())) + .and_then(|found| { + let fact = self.definition_fact(&found)?; + self.store + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }) .or_else(|| { - local - .and_then(|found| found.fact.returns.map(|returns| returns.to_string())) + local.and_then(|found| { + let fact = self.definition_fact(&found)?; + self.store + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }) }) }, ); @@ -949,15 +1008,19 @@ impl Session { let object_is_const = self.the_object_is_const(view, object_at); let object_is_const = object_is_const?; - let members = self.members_of(view, &object.type_of); + let members = match &object.type_value { + Some(class) => self.members_of_type(view, class), + None => self.members_of(view, &object.type_of), + }; let Known::Yes(list) = members else { return None; }; - let mut candidates: Vec<&index::project::ProjectMember> = list + let index = self.store.index(); + let mut candidates: Vec<&ProjectMember> = list .members .iter() - .filter(|member| member.fact.kind == DeclKind::Function) - .filter(|member| member.fact.name == access.member) + .filter(|member| index.member_kind(member) == Some(DeclKind::Function)) + .filter(|member| index.member_name(member) == access.member) // **The argument has to be a *template parameter* of the callee.** `call(std::function)` // needs no deduction — the type is written — so a candidate with a concrete parameter is not this // question's. @@ -965,40 +1028,41 @@ impl Session { // **A parameter the callee *declares as a template parameter*** — its own head names it, which is a // question about that declaration rather than the naming convention a check reads // (`names_a_template_parameter_for_a_check` knows `T` and `_Ty`, and `Fn` is neither). - let Some(list) = member.fact.parameter_list() else { + let Some(fact) = index.member_fact(member) else { return false; }; - let types = sema::overload::parameters_in(list).0; - let Some(written) = types.get(at) else { + // **The parameter's own type, structurally.** A member's list is a fact like any other; each + // parameter carries its lowered type, and the name a template parameter is compared against is the + // type's bare name — no spelling is parsed and no text is split into words. + let file = index.member_path(member).unwrap_or(Path::new("")); + let (parameters, _) = sema::overload::parameters_in_facts( + index.parameter_facts_of(file, fact), + false, + ); + let Some(parameter) = parameters.get(at) else { return false; }; - // **The type is the first word** — `parameters_in` keeps the parameter's name (`"Fn &&fn"`), and - // `const` may stand in front of the type rather than after it. - let mut words = written.split_whitespace(); - let mut first = words.next().unwrap_or_default(); - if first == "const" { - first = words.next().unwrap_or_default(); - } - let core = first.trim_end_matches(['&', '*']); - member - .fact - .parameters() - .iter() - .any(|parameter| parameter == core) + let Some(core) = parameter.bare_name() else { + return false; + }; + fact.parameters().iter().any(|name| name == core) }) // Rule 1: a `const` object reaches only the `const` members. .filter(|member| { - !object_is_const || member.fact.modifiers.contains(DeclModifiers::CONST) + !object_is_const + || index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) }) .collect(); if candidates.is_empty() { return None; } // Rule 3: a constraint that cannot be evaluated leaves the choice open, while more than one survives. - let constrained = |member: &&index::project::ProjectMember| { - member - .fact - .requires_clause() + let constrained = |member: &&ProjectMember| { + index + .member_fact(member) + .and_then(|fact| fact.requires_clause()) .is_some_and(|clause| !clause.trim().is_empty()) }; if candidates.len() > 1 && candidates.iter().any(constrained) { @@ -1006,28 +1070,38 @@ impl Session { } // Rule 2: on a non-`const` object the non-`const` member is the better match. if !object_is_const - && candidates - .iter() - .any(|member| !member.fact.modifiers.contains(DeclModifiers::CONST)) + && candidates.iter().any(|member| { + !index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) + }) { - candidates.retain(|member| !member.fact.modifiers.contains(DeclModifiers::CONST)); + candidates.retain(|member| { + !index + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) + }); } if candidates.len() != 1 { return None; } let chosen = candidates[0]; + let chosen_fact = index.member_fact(chosen)?.clone(); + let chosen_file = index.member_path(chosen)?.to_path_buf(); // Rule 4: the parameter's name, and the body's call of it. - let name = sema::call_syntax::parameter_names_from_text(chosen.fact.parameter_list()?)? - .get(at) - .cloned() - .flatten()?; - let declaring = self.view_of_the_file(&chosen.file)?; + let name = sema::call_syntax::parameter_names_of_fact( + index.parameter_facts_of(&chosen_file, &chosen_fact), + )? + .get(at) + .cloned() + .flatten()?; + let declaring = self.view_of_the_file(&chosen_file)?; // **That member's own body**, not the file: the first call named `fn` in a file that declares two classes is // the other class's, and the report this answers is a project where it was — `cbar.call(…)` was answered with // the type `Foo::call` passes its callback. let declared_at = self - .the_declaration_node(&chosen.file, chosen.fact.name_range.start_offset) + .the_declaration_node(&chosen_file, chosen_fact.name_range.start_offset) .unwrap_or_else(|| declaring.root.clone()); let (argument, spelled) = the_argument_the_body_passes(&declaring, &declared_at, &name)?; let Known::Yes(passed) = self.type_at( @@ -1039,7 +1113,7 @@ impl Session { // **`*this` is `const T` in a `const` member** — the one qualifier the type of `this` does not carry here, and // the difference between `Foo&` and `const Foo&`, which is the whole answer for `cfoo.call(…)`. let mut deduced = passed.type_of; - if spelled.trim() == "*this" && chosen.fact.modifiers.contains(DeclModifiers::CONST) { + if spelled.trim() == "*this" && chosen_fact.modifiers.contains(DeclModifiers::CONST) { deduced = format!("const {deduced}"); } let lvalue = spelled.trim().starts_with('*') || is_a_name_expression(&argument); @@ -1136,3 +1210,14 @@ fn is_a_name_expression(argument: &CppSyntaxNode) -> bool { CppSyntaxKind::NameExpr | CppSyntaxKind::MemberExpr ) } + +/// **Does this expression contain a macro invocation?** The rendering fallback is for macros: their expansion +/// is in the cooked text, while the file's own tree has only a `MacroCall`. Crossing for an ordinary expression +/// can land on an unrelated expression when offsets map across an inlined header (measured: a monadic +/// `optional::transform` chain answered `divide(6, 2)`'s `int`). +fn expression_contains_a_macro_call(expression: &CppSyntaxNode) -> bool { + CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::MacroCall + || expression + .descendants() + .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::MacroCall) +} diff --git a/crates/cpp_code_analysis/src/session/constrained.rs b/crates/cpp_code_analysis/src/session/constrained.rs index 5dc68284..6ef810a1 100644 --- a/crates/cpp_code_analysis/src/session/constrained.rs +++ b/crates/cpp_code_analysis/src/session/constrained.rs @@ -132,10 +132,13 @@ impl Session { let Some(found) = self.store.index().definition(concept, path).value() else { return Vec::new(); }; - let Some(view) = self.view_of_the_file(&found.file) else { + let Some((file, fact)) = self.definition_parts(&found) else { return Vec::new(); }; - let Some(token) = token_at(&view.root, found.fact.name_range.start_offset) else { + let Some(view) = self.view_of_the_file(&file) else { + return Vec::new(); + }; + let Some(token) = token_at(&view.root, fact.name_range.start_offset) else { return Vec::new(); }; let Some(concept_node) = token @@ -205,10 +208,13 @@ impl Session { let Some(found) = self.store.index().definition(concept, path).value() else { return; }; - let Some(view) = self.view_of_the_file(&found.file) else { + let Some((file, fact)) = self.definition_parts(&found) else { + return; + }; + let Some(view) = self.view_of_the_file(&file) else { return; }; - let Some(token) = token_at(&view.root, found.fact.name_range.start_offset) else { + let Some(token) = token_at(&view.root, fact.name_range.start_offset) else { return; }; let Some(concept_node) = token @@ -255,7 +261,7 @@ impl Session { } for other in the_concepts_a_body_names(&concept_node) { - self.collect_the_members_of_a_concept(&other, &found.file, depth + 1, visited, names); + self.collect_the_members_of_a_concept(&other, &file, depth + 1, visited, names); } } } diff --git a/crates/cpp_code_analysis/src/session/cook.rs b/crates/cpp_code_analysis/src/session/cook.rs index 86572f93..b836c80b 100644 --- a/crates/cpp_code_analysis/src/session/cook.rs +++ b/crates/cpp_code_analysis/src/session/cook.rs @@ -956,13 +956,16 @@ impl Session { built } }; - summary + // **The fact is synthesized for the caller.** Its types are immutable `ComputedType` values that travel with + // it — there is no local table to leak a handle out of — so the clone is the whole of the conversion. + let fact = summary .declarations .iter() .find(|fact| { fact.name == name && fact.scope.as_deref() == scope && !fact.split_by_a_directive - }) - .cloned() + })? + .clone(); + Some(fact) } /// Cook every **open** file — what the indexing loop does when its queue drains. diff --git a/crates/cpp_code_analysis/src/session/definition.rs b/crates/cpp_code_analysis/src/session/definition.rs index 53cf3f9d..520cd15a 100644 --- a/crates/cpp_code_analysis/src/session/definition.rs +++ b/crates/cpp_code_analysis/src/session/definition.rs @@ -146,7 +146,10 @@ impl Session { qualified_name: format!("{class}::{name}"), class: class.to_string(), name: name.to_string(), - returns: fact.returns.as_deref().map(str::to_string), + returns: self + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template, @@ -163,31 +166,41 @@ impl Session { let Known::Yes(list) = self.members_of(view, class) else { return Vec::new(); }; + let index = self.index(); let mut found: Vec = Vec::new(); for member in &list.members { - if member.fact.kind != DeclKind::Function - || !member.fact.modifiers.contains(DeclModifiers::PURE) - { + let Some(fact) = index.member_fact(member) else { + continue; + }; + if fact.kind != DeclKind::Function || !fact.modifiers.contains(DeclModifiers::PURE) { continue; } let overridden = list.members.iter().any(|other| { - other.fact.kind == DeclKind::Function - && other.fact.name == member.fact.name + index.member_kind(other) == Some(DeclKind::Function) + && index.member_name(other) == index.member_name(member) && other.depth < member.depth - && !other.fact.modifiers.contains(DeclModifiers::PURE) + && index + .member_modifiers(other) + .is_some_and(|modifiers| !modifiers.contains(DeclModifiers::PURE)) }); if overridden { continue; } - let Some((parameters, qualifiers)) = signature_of(self, &member.file, &member.fact) + let written = index.member_parameter_list(member); + let Some(file) = index.member_path(member) else { + continue; + }; + let Some((parameters, qualifiers)) = signature_of(self, file, fact, written.as_deref()) else { continue; }; found.push(MissingDefinition { - qualified_name: format!("{class}::{}", member.fact.name), + qualified_name: format!("{class}::{}", fact.name), class: class.to_string(), - name: member.fact.name.to_string(), - returns: member.fact.returns.as_deref().map(str::to_string), + name: fact.name.to_string(), + returns: index + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template: false, @@ -206,8 +219,14 @@ fn signature_of( session: &Session, file: &std::path::Path, fact: &DeclFact, + // The row's instantiated parameter list, when the caller has a member substitution to apply; `None` reads the + // declaration's own text. + written_parameters: Option<&str>, ) -> Option<(String, String)> { - let parameters = match fact.parameter_list().map(str::to_string) { + let parameters = match written_parameters + .map(str::to_string) + .or_else(|| fact.parameter_list().map(str::to_string)) + { Some(parameters) => parameters, None => { let view = session diff --git a/crates/cpp_code_analysis/src/session/edits.rs b/crates/cpp_code_analysis/src/session/edits.rs index ce9b9150..9ffe4546 100644 --- a/crates/cpp_code_analysis/src/session/edits.rs +++ b/crates/cpp_code_analysis/src/session/edits.rs @@ -566,6 +566,14 @@ impl Session { self.documents.open(path, text); self.vfs.insert(path, text, true); + // **The id this buffer is filed under, registered before the pump reads it.** A reference minted between the + // edit and the re-read — a completion's synthesized member, a macro's fact — names this id through + // [`crate::ProjectIndex::file_id_of`], so the index has to know it before any fact is filed. The VFS keeps + // the id stable across the edit and the re-read, so registering again on the next keystroke is a no-op. + let held = self.vfs.held(path).map(|file| file.id); + if let Some(file) = held { + self.store.index_mut().register_file_id(path, file); + } // **Who read what this file used to say**, asked while it still says it: `forget` below takes the summary // with it, and the answer is "every file that includes this one, at any depth" — see diff --git a/crates/cpp_code_analysis/src/session/indexing.rs b/crates/cpp_code_analysis/src/session/indexing.rs index 31f21191..0fb8443f 100644 --- a/crates/cpp_code_analysis/src/session/indexing.rs +++ b/crates/cpp_code_analysis/src/session/indexing.rs @@ -170,7 +170,16 @@ impl Session { timeline: bool, ) -> Step { { - self.vfs.load(&path); + // **The id the VFS gave this file, registered before anything reads it.** Every runtime reference the + // index mints for a file names this id ([`ProjectIndex::file_id_of`]), so it has to be known before the + // first fact — summary or cached record — is filed. A reference minted in the window between the insert + // and the registration would name the index's fallback sequence instead, which resolves through the + // index but is not the id the VFS handed out and so is not comparable with one a consumer holds. A failed + // read has no id and no facts, so there is nothing to register and nothing to name. + let loaded = self.vfs.load(&path); + if let Some(file) = loaded { + self.store.index_mut().register_file_id(&path, file); + } } let before = self.store.stats(); diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index 5078386e..3907f50c 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -51,11 +51,8 @@ use crate::BindingKind; use crate::DeclKind; use crate::index; use crate::sema; -use cpp_parser::CppDeclarator; use cpp_parser::CppParamList; -use cpp_parser::CppParser; use cpp_parser::CppTokenKind; -use cpp_parser::ParserConfig; use cpp_parser::typed_descendants; use cpp_parser::{CppEnumDef, CppLambdaExpr}; use std::collections::HashMap; @@ -64,7 +61,10 @@ use std::path::{Path, PathBuf}; use cpp_parser::{CppSyntaxKind, CppSyntaxNode, SourceRange}; use crate::index::project::{Callee, callee_of_a_call}; -use crate::sema::call_syntax::{arguments_of, parameter_list_of, parameter_names_from_text}; +use crate::sema::call_syntax::{ + arguments_of, parameter_list_has_a_pack, parameter_list_of, parameter_names_of_fact, + parameter_names_of_list, +}; use crate::sema::scopes::parameters_of; use crate::{FileView, Known, ProjectIndex}; use cpp_parser::CppAstNode; @@ -363,7 +363,7 @@ fn the_name_of_a_declarator(node: &CppSyntaxNode) -> Option { /// **Is this spelling a type a reader can use** — not the placeholder, not empty? /// /// `auto` is the word the file already wrote: printing it in a hint says the analysis declined while looking like an -/// answer. `Type::to_string` of a deduced type never carries it, so this is a guard against a caller whose answer was the +/// answer. `Display` of a deduced type never carries it, so this is a guard against a caller whose answer was the /// placeholder's spelling. fn is_a_type_spelling(label: &str) -> bool { let label = label.trim(); @@ -503,16 +503,7 @@ where return a_variables_call(); }; - let names = - parameter_names_for(view, &callee, &mut declaring, &mut view_of).or_else(|| { - // **A declaration whose file has no rendering still has names.** The list is in its - // *fact*, which the index keeps as text — so the reading is made from the text - // instead of from the tree. - callee - .parameters - .as_deref() - .and_then(parameter_names_from_text) - }); + let names = parameter_names_for(view, &callee, &mut declaring, &mut view_of); let variables = a_variables_call(); names.or(variables) @@ -587,13 +578,15 @@ fn callable_object_parameter_names( }; let mut best: Option>> = None; for member in &list.members { - if member.fact.name != "operator()" { - continue; - } - let Some(text) = member.fact.parameter_list() else { + let Some(fact) = index.member_fact(member) else { continue; }; - let Some(names) = parameter_names_from_text(text) else { + if fact.name != "operator()" { + continue; + } + let Some(names) = + parameter_names_of_fact(index.parameter_facts_of(index.member_path(member)?, fact)) + else { continue; }; if names.len() != passed { @@ -645,9 +638,8 @@ fn a_lambdas_parameter_names( let holder = declarator.parent()?; let lambda = typed_descendants::(&holder).next()?; let list = lambda.get_params()?; - let text = list.syntax().text().to_string(); - let names = parameter_names_from_text(&text)?; - let a_pack = text.contains("..."); + let names = parameter_names_of_list(&list); + let a_pack = parameter_list_has_a_pack(&list); if names.len() != passed && !(a_pack && names.len() < passed) { return None; } @@ -693,7 +685,9 @@ fn constructor_parameter_names( }; let mut best: Option>> = None; for declaration in &found.found { - let fact = &declaration.fact; + let Some(fact) = index.definition_fact(declaration) else { + continue; + }; // A constructor is filed under its class's name, in the class's own scope. if fact.kind != DeclKind::Function || fact.name != name { continue; @@ -704,10 +698,10 @@ fn constructor_parameter_names( if scope.rsplit("::").next().map(str::trim) != Some(name) { continue; } - let Some(list) = fact.parameter_list() else { + let Some(file) = index.definition_path(declaration) else { continue; }; - let Some(names) = parameter_names_from_text(list) else { + let Some(names) = parameter_names_of_fact(index.parameter_facts_of(file, fact)) else { continue; }; if names.len() < passed { @@ -767,51 +761,6 @@ fn contains(range: SourceRange, offset: usize) -> bool { offset >= range.start_offset && offset <= range.end_offset() } -/// **The types a written parameter list spells**, position for position — `["T", "const U&"]` for -/// `(T first, const U& second)`. -/// -/// The fact stores the list as text (`(T first, U second)`), and this parses one synthetic declaration around it, the -/// same way [`parameter_names_from_text`] does. The type is what stands before the declared name; an unnamed parameter's -/// whole text is its type, and a default argument after the name is not part of it. -pub(crate) fn parameter_types_in_a_written_list(parameter_list: &str) -> Vec { - if !parameter_list.trim_start().starts_with('(') { - return Vec::new(); - } - let text = format!("void __hint{parameter_list};"); - let tree = CppParser::parse(&text, ParserConfig::default()); - let root = tree.get_red_root(); - let Some(declarator) = root - .descendants() - .find(|node| CppDeclarator::can_cast(node.kind().into())) - else { - return Vec::new(); - }; - let Some(list) = declarator - .descendants() - .find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::ParameterList) - else { - return Vec::new(); - }; - parameters_of(&list) - .into_iter() - .filter_map(|(parameter, declared)| { - let raw = parameter.text().to_string(); - let trimmed = raw.trim(); - if trimmed.is_empty() { - return None; - } - let parameter_start = usize::from(parameter.text_range().start()); - let written = match declared { - Some((_, range)) if range.start_offset >= parameter_start => { - raw[..range.start_offset - parameter_start].trim() - } - _ => trimmed, - }; - (!written.is_empty()).then(|| written.to_string()) - }) - .collect() -} - /// **Deduced template arguments at a call** — `make_pair(1, 2.0)`. /// /// `callee` answers the call's template parameter names, the parameter types as the declaration spells them, and where diff --git a/crates/cpp_code_analysis/src/session/mod.rs b/crates/cpp_code_analysis/src/session/mod.rs index 6874364d..3a0ccc7b 100644 --- a/crates/cpp_code_analysis/src/session/mod.rs +++ b/crates/cpp_code_analysis/src/session/mod.rs @@ -84,6 +84,7 @@ use crate::effect; use crate::file; use crate::include; use crate::index; +use crate::index::types::ComputedType; use crate::preprocess; use crate::sema; use cpp_parser::MacroEnvironment; @@ -2072,6 +2073,9 @@ pub struct ExpressionType { /// The type, spelled the way the declaration it was read from spells it. Not a canonical type: an alias is an /// alias name, and `const Widget&` is those three tokens, because that is what the file says. pub type_of: String, + /// **The same answer structurally**, when this layer has it. Member lookup, layout and type-definition follow + /// this rather than printing `type_of` and parsing the spelling back into a type. + pub type_value: Option, /// The file that declaration is in. pub file: PathBuf, } diff --git a/crates/cpp_code_analysis/src/session/navigation.rs b/crates/cpp_code_analysis/src/session/navigation.rs index 9be07d55..bae3276f 100644 --- a/crates/cpp_code_analysis/src/session/navigation.rs +++ b/crates/cpp_code_analysis/src/session/navigation.rs @@ -227,7 +227,9 @@ impl Session { .definition(spelling, &view.path) .value() .and_then(|found| { - semantic::kind_of_index(index::project::IndexedKind::of(&found.fact)) + self.store.index().definition_fact(&found).and_then(|fact| { + semantic::kind_of_index(index::project::IndexedKind::of(fact)) + }) }) // **A macro is a name too**, and the index holds no *declaration* for one: `[`MAX`]` names a // `#define`, which is a fact about text. The environment the file is compiled in is the same @@ -281,9 +283,9 @@ impl Session { .definition(spelling, &view.path) .value() .and_then(|found| { - semantic::kind_of_index(index::project::IndexedKind::of( - &found.fact, - )) + self.store.index().definition_fact(&found).and_then(|fact| { + semantic::kind_of_index(index::project::IndexedKind::of(fact)) + }) }) }; let Some(kind) = kind else { @@ -469,7 +471,9 @@ impl Session { ) -> Vec { let mut signatures = signature::signatures_at(self.store.index(), view, offset.get(), |path| { - self.view(path) + // **A rendering first; the file's own parsed tree second.** Both are parsed by the session with + // the file's own config, so the fallback is never a synthetic fragment. + self.view(path).or_else(|| self.view_of_the_file(path)) }); for signature in &mut signatures { diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index f186958b..b30e619d 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -5,9 +5,12 @@ use super::*; use crate::CompletionSet; use crate::DeclFact; +use crate::DeclKind; +use crate::FileId; use crate::HeaderTarget; use crate::MacroKind; use crate::ReferenceBudget; +use crate::ReflectionFact; use crate::SymbolReferences; use crate::SymbolToFind; use crate::completion; @@ -254,15 +257,23 @@ impl Session { let Known::Yes(definitions) = self.store.index().definitions(alias_name, &view.path) else { return None; }; + let index = self.store.index(); let alias = definitions.found.iter().find(|definition| { - definition.fact.kind == crate::DeclKind::Type && definition.fact.type_of.is_some() + index.definition_fact(definition).is_some_and(|fact| { + fact.kind == DeclKind::Type && index.type_spelling_of(fact).is_some() + }) })?; - let target = alias.fact.type_of.as_deref()?; - let substituted = sema::types::substituted_spelling_with_defaults( - target, - alias.fact.parameters(), - alias.fact.parameter_defaults(), + let alias_fact = index.definition_fact(alias)?; + let target = index.type_spelling_of(alias_fact)?; + let substituted = sema::types::substituted_spelling_with_defaults::< + smol_str::SmolStr, + smol_str::SmolStr, + String, + >( + &target, + alias_fact.parameters(), + alias_fact.parameter_defaults(), &[], ); let target = substituted.trim(); @@ -293,6 +304,12 @@ impl Session { // **A dependent alias member is asked before the ordinary spelling lookup.** The ordinary query can resolve // the alias name itself (and does: it returned `Viewer` for a cursor on `Viewer<>::Type`), which means the // fallback cannot wait for a `NotDeclaredHere`; the alias target's member is the more specific answer. + // **The binding path's offsets are the view's reading offsets**, and a fact arena is in file coordinates: this + // is where the one is turned into the other, so a binding-derived answer can be matched to its declaration. + let to_file = |at: usize| { + view.file_offset_of(ReadingOffset::new(at)) + .map(|in_the_file| in_the_file.get()) + }; let found = match self.definition_of_a_dependent_alias(view, offset) { Some(found) => Known::Yes(found), None => definition_across_files( @@ -302,6 +319,7 @@ impl Session { &view.root, &view.path, offset.get(), + &to_file, ), }; let found = if matches!(found, Known::No | Known::Unknown(_)) { @@ -311,13 +329,14 @@ impl Session { } else { found }; - let found = self.with_the_reflection(view, found); // **The answer came from L1, so ask for L2** — the L1/L2 split `docs/open-questions.md` records. A declaration the reader // jumped into is a file they are now looking at, and its refined reading is what its own members, types and // macro-shaped declarations are answered from. Asking here costs a `HashSet` insert under its own lock; the pump // then refines that one file (measured: **93.6 ms**, one timeline) while this answer is already on screen. - if let Known::Yes(found) = &found { - self.want_refinement(&found.file); + if let Known::Yes(found) = &found + && let Some(path) = self.store.index().path_of(found.file) + { + self.want_refinement(path); } // **A qualified name the shape reading does not hold: ask for the declaring file's *rendering*.** // @@ -363,20 +382,25 @@ impl Session { let Known::Yes(found) = index.definition(qualifier, from) else { return Vec::new(); }; - let mut files = vec![found.file.clone()]; + let Some((found_fact, found_path)) = index.definition_parts(&found) else { + return Vec::new(); + }; + let mut files = vec![found_path.to_path_buf()]; // `basic_json<>` → `basic_json`, and the target is qualified by the scope the alias was declared in unless it // already names one (`using simple = ::ns::basic<>;`). - if let Some(target) = found.fact.type_of.as_deref() { - let base = target.split('<').next().unwrap_or(target).trim(); - if !base.is_empty() && base != found.fact.name.as_str() { - let scope = found.fact.scope.as_deref().unwrap_or(""); + if let Some(target) = index.type_spelling_of(found_fact) { + let base = target.split('<').next().unwrap_or(target.as_str()).trim(); + if !base.is_empty() && base != found_fact.name.as_str() { + let scope = found_fact.scope.as_deref().unwrap_or(""); let qualified = if base.contains("::") || scope.is_empty() { base.to_string() } else { format!("{scope}::{base}") }; - if let Known::Yes(class) = index.definition(&qualified, from) { - files.push(class.file.clone()); + if let Known::Yes(class) = index.definition(&qualified, from) + && let Some(path) = index.definition_path(&class) + { + files.push(path.to_path_buf()); } } } @@ -386,7 +410,7 @@ impl Session { /// **Is the object this name denotes `const`?** — the one question a member access's overload set depends on, and /// the one a *type's spelling* cannot answer. /// - /// [`crate::DeclFact::type_of`] is a name for lookup and drops the declaration's specifiers on purpose (`static + /// [`crate::DeclFact::type_of`] is an interned handle, and it drops the declaration's specifiers on purpose (`static /// const Widget` records `Widget`, so that a lookup by name finds the class), and [`Session::type_at`]'s answer /// follows it: measured on `test_cpp/src/containers.cpp:57`, inside /// `bool operator()(std::string const& left, std::string const& right)`, `type_at` answers **`std::string&`** for @@ -432,40 +456,66 @@ impl Session { .is_some_and(|summary| summary.key.env_hash != 0) } - /// **The reflection annotation the summary recorded**, when a same-file answer came from the binding instead. + /// **The reflection annotation a declaration is written under** — recovered from the file's own text when the + /// arena's reading cannot carry it. /// - /// A definition inside the file being read is built from the scope tree, which holds the declaration's shape and no - /// annotation: `UPROPERTY(EditAnywhere)` is an empty macro and was expanded away before the tree existed. The - /// **summary** of the same file recorded it from the text, so the two answers are merged here rather than duplicating - /// the text walk in the binding path. A member declared in *another* file already carries it — that fact came from - /// the index. - pub(crate) fn with_the_reflection( + /// A definition answer is a reference now, so there is no fact here to merge an annotation into. The arena fact + /// usually carries it (the summary records the text), and the one case it cannot is a *rendering's* reading: + /// `UPROPERTY(EditAnywhere)` is an empty macro and was expanded away before that tree existed, so a declaration + /// inside a body whose reader asks for the card would show no annotation. The file's **own** reading still has it, + /// and this is where a display consumer asks for it — one field, cloned at the edge, exactly like a `ComputedType`. + pub fn reflection_of_definition( &self, - view: &FileView, - found: Known, - ) -> Known { - let Known::Yes(mut definition) = found else { - return found; - }; - if definition.fact.reflection().is_some() { - return Known::Yes(definition); + definition: &ProjectDefinition, + ) -> Option { + let found = self.store.index().definition_fact(definition)?; + if let Some(reflection) = found.reflection() { + return Some(reflection.clone()); } - let Some(in_the_file) = - view.file_offset_of(ReadingOffset::new(definition.fact.name_range.start_offset)) - else { - return Known::Yes(definition); - }; - let Some(summary) = self.parsed_summary(&view.path) else { - return Known::Yes(definition); - }; // **The name and its offset**, because an overload set shares the first and not the second. - let recorded = summary.declarations.iter().find(|fact| { - fact.name == definition.fact.name && fact.name_range.start_offset == in_the_file.get() - }); - if let Some(recorded) = recorded { - definition.fact.detail_mut().reflection = recorded.reflection().cloned(); - } - Known::Yes(definition) + let summary = self.parsed_summary(self.store.index().path_of(definition.file)?)?; + summary + .declarations + .iter() + .find(|fact| { + fact.name == found.name + && fact.name_range.start_offset == found.name_range.start_offset + }) + .and_then(|fact| fact.reflection().cloned()) + } + + /// **The file a definition answer points into**, in the project's spelling of the path. + /// + /// [`ProjectIndex::path_of`] answers the index's normalized spelling; a client was given the path the project + /// listed, and the two differ by a drive letter or a separator on Windows. This is the one place a consumer inside + /// the session turns a [`crate::FileId`] back into a path, so the spelling rule lives here rather than at every + /// handler. + pub fn path_of_file(&self, file: FileId) -> Option { + let path = self.store.index().path_of(file)?; + Some( + self.project_paths + .get(&queue_key(path)) + .cloned() + .unwrap_or_else(|| path.to_path_buf()), + ) + } + + /// **The path and declaration a definition answer names**, with the project's spelling of the path. + pub fn definition_parts(&self, definition: &ProjectDefinition) -> Option<(PathBuf, &DeclFact)> { + Some(( + self.path_of_file(definition.file)?, + self.store.index().definition_fact(definition)?, + )) + } + + /// **The declaration a definition answer names.** + pub fn definition_fact(&self, definition: &ProjectDefinition) -> Option<&DeclFact> { + self.store.index().definition_fact(definition) + } + + /// **The file a definition answer points into**, with the project's spelling of the path. + pub fn definition_path(&self, definition: &ProjectDefinition) -> Option { + self.path_of_file(definition.file) } /// **Every declaration the name at `offset` refers to** — an overload set, a redeclaration, or one entity. @@ -474,22 +524,19 @@ impl Session { /// entry. This is the query behind `textDocument/definition`: measured on one real file, **46** identifiers /// answered `Ambiguous` through the single-answer form, and every one of them had a usable list behind it. pub fn definitions(&self, view: &FileView, offset: ReadingOffset) -> Known { - let mut answer = definitions_across_files( + let to_file = |at: usize| { + view.file_offset_of(ReadingOffset::new(at)) + .map(|in_the_file| in_the_file.get()) + }; + definitions_across_files( self.store.index(), &mut |path| self.view(path), &view.scopes, &view.root, &view.path, offset.get(), - ); - if let Known::Yes(definitions) = &mut answer { - for definition in &mut definitions.found { - if let Some(path) = self.project_paths.get(&queue_key(&definition.file)) { - definition.file.clone_from(path); - } - } - } - answer + &to_file, + ) } /// **Every place the symbol at `offset` is written** — what `textDocument/references` asks. @@ -528,7 +575,10 @@ impl Session { return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(""))); }; - let symbol = SymbolToFind::of(&first.fact, first.file.clone()); + let Some((file, fact)) = self.definition_parts(first) else { + return Known::Unknown(UnknownReason::NotDeclaredHere(Box::from(""))); + }; + let symbol = SymbolToFind::of(fact, file); index::references::symbol_references(self.store.index(), &self.files, &symbol, budget) } diff --git a/crates/cpp_code_analysis/src/session/semantic.rs b/crates/cpp_code_analysis/src/session/semantic.rs index 3866c52d..0bdba749 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -92,6 +92,7 @@ use crate::ProjectLanguage; use crate::Visibility; use crate::ascend; use crate::index; +use crate::index::types::ComputedType; use crate::preprocess; use crate::sema; use cpp_parser::CppNameExpr; @@ -867,11 +868,14 @@ fn member_kinds( // The same mapping the index answer goes through — see [`kind_of_index`] — so `push_back` is a method and // not a function, which is the difference between the colour a member gets and the one a free function does. - let kind = match found.fact.kind { - DeclKind::Function if found.fact.scope.is_some() => NameKind::Method, + let Some(fact) = index.definition_fact(&found) else { + continue; + }; + let kind = match fact.kind { + DeclKind::Function if fact.scope.is_some() => NameKind::Method, DeclKind::Function => NameKind::Function, // **A variable with a scope is a field**, by the same reading as a function with a scope being a method. - DeclKind::Variable if found.fact.scope.is_some() => NameKind::Property, + DeclKind::Variable if fact.scope.is_some() => NameKind::Property, DeclKind::Variable => NameKind::Variable, DeclKind::Type => NameKind::Type, DeclKind::Namespace => NameKind::Namespace, @@ -1049,18 +1053,25 @@ fn spell(global: bool, written: &str) -> String { fn denotes_a_function_pointer(index: &ProjectIndex, declaring: &Path, written: &str) -> bool { let mut spelling = written.trim().to_string(); for _ in 0..4 { - // **The signature is the answer.** `int (*)(int, int)` and `void (*)(void)` both carry `(*`, and no other - // type spelling does — a pointer to a function is written exactly that way. - if spelling.contains("(*") { + // **The structured type is the answer.** A pointer to a function is `Pointer(Function(…))` — the canonical + // display of that shape is `int(int)*`, while an array, a plain pointer, or a function returning a pointer is + // a different tree. The check is structural rather than a spelling search so it cannot be fooled by an alias + // whose written form happens to contain `(*`. + if let ComputedType::Pointer(to) = sema::types::parse_type_spelling(&spelling) + && matches!(&*to, ComputedType::Function(_)) + { return true; } let Known::Yes(found) = index.definition(&spelling, declaring) else { return false; }; - if found.fact.kind != DeclKind::Type { + let Some(found) = index.definition_fact(&found) else { + return false; + }; + if found.kind != DeclKind::Type { return false; } - let Some(target) = found.fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(found) else { return false; }; let target = target.to_string(); @@ -1138,8 +1149,9 @@ fn kind_of_binding( sema::declarations::shapes_from(shapes, &view.root), binding, ) - .is_some_and(|written| denotes_a_function_pointer(index, &view.path, &written)) - { + .is_some_and(|written| { + denotes_a_function_pointer(index, &view.path, &written.to_string()) + }) { // **A function pointer is drawn as a function.** `binary_op operation = add;` declares a *variable* — // the fact says so and hover says so — but a reader scanning `operation(1, 2)` reads a call, and a // theme that colours functions is where that call belongs. The type is what decides, so an ordinary diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index ba6dc488..1fe39198 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -28,11 +28,16 @@ //! [`Ambiguous`]: crate::UnknownReason::Ambiguous use crate::DeclKind; +use crate::index::types::ComputedType; use crate::sema; use std::ops::Range; use std::path::{Path, PathBuf}; -use cpp_parser::{CppDocComment, CppSyntaxElement, CppSyntaxKind, CppSyntaxNode, CppTokenKind}; +use cpp_parser::CppParam; +use cpp_parser::CppParamList; +use cpp_parser::{ + CppAstNode, CppDocComment, CppSyntaxElement, CppSyntaxKind, CppSyntaxNode, CppTokenKind, +}; use crate::index::project::{Callee, callees_of_a_call}; use crate::sema::call_syntax::{arguments_of, parameter_list_of}; @@ -150,10 +155,12 @@ where let mut parsed: std::collections::HashMap> = std::collections::HashMap::new(); let mut signatures = Vec::new(); - // **The parameter spellings the ranking should see**, aligned with `signatures`. For a plain function they are the - // declaration's own; for a template they are **substituted** once the call's argument types are known, which is - // what makes `f(T)` and `f(int)` the same candidate for `f(1)`. - let mut rankable: Vec<(Vec, Vec)> = Vec::new(); + // **The parameter types the ranking should see**, aligned with `signatures`. For a plain function they are read + // from the declaration's own parameter nodes; for a template they are **substituted** once the call's argument + // types are known, which is what makes `f(T)` and `f(int)` the same candidate for `f(1)`. The label beside each + // signature stays text, because the popup prints it — and the third element is the list's `...`, which is a fact + // read from the `CppParamList` rather than something the ranking re-derives from that label. + let mut rankable: Vec<(Vec, Vec, bool)> = Vec::new(); for candidate in candidates { // The file being edited is already parsed; every other file is parsed once and kept for the rest of this @@ -165,45 +172,11 @@ where .entry(candidate.file.clone()) .or_insert_with(|| view_of(&candidate.file)); let Some(held) = held.as_ref() else { - // **The declaration's *rendering* is not built yet — and the popup is not allowed to wait for it.** - // A rendering is a unit walk, a preprocess and a render (65–190 ms for a header), so a query queues - // one and answers `None`; the next request would find it. For a signature popup "the next request" - // never comes — a client asks once per `(` — so the answer here is built from what the **index** - // already holds: the declaration's parameter list, which every fact carries. - // - // Measured on a C++23 module project: `math::add(` answered **nothing** on the first `(` and - // everything on the second, which is exactly the shape of "signature help almost never appears". - // - // **The fallback's spans come from a synthetic declaration**, not from the file's rendering: the - // fact's parameter list is parsed as `void __hint(…);`, so a comparison in a default argument or a - // function-pointer list is split by the grammar. A shape that parse cannot read leaves the spans empty - // rather than pointing a client at the wrong bytes; the label, the count and the active parameter - // remain right — unlike parsing the file's own text at a *rendering* offset, which would name the - // wrong declaration in any file with a macro above it. - if let Some(parameters) = &candidate.parameters { - let (tidy, _) = sema::call_syntax::tidy_list_text(parameters); - let label = format!("{spelling}{tidy}"); - signatures.push(CallSignature { - parameters: parameters_from_a_written_list(&tidy, spelling.len()), - label, - active_parameter: active, - declared_in: candidate.file.clone(), - declared_at: candidate.name_offset, - documentation: None, - }); - rankable.push((Vec::new(), Vec::new())); - } else { - // **A class with no rendering**: `LuaParser p(file, std::move(…))` is a constructor call, and a - // class fact carries no parameter list of its own — its constructors do, and the index files them - // under the class's name. Without this the popup was empty for the most ordinary line of code - // there is, in every header the session has not cooked. - let from_the_index = - constructors_in_the_index(index, &view.path, spelling, active); - if !from_the_index.is_empty() { - signatures.extend(from_the_index); - rankable.push((Vec::new(), Vec::new())); - } - } + // **The declaration's rendering is not built.** `view_of` already tried the file's own parsed + // tree as a second source; if neither exists there is no CST to read, so this candidate contributes + // nothing rather than parsing a stored parameter-list string. + // **No synthetic fact fallback.** A file with neither a rendering nor its own parsed tree has no + // signature; this branch is reached only when the session has no source for the declaration. continue; }; held @@ -232,7 +205,7 @@ where let from_the_index = constructors_in_the_index(index, &view.path, spelling, active); if !from_the_index.is_empty() { signatures.extend(from_the_index); - rankable.push((Vec::new(), Vec::new())); + rankable.push((Vec::new(), Vec::new(), false)); continue; } } @@ -243,23 +216,6 @@ where // measured on a real project, `SetupStyle(style, options);` answered no signature while the fact beside it // carried `(LuaStyle &style, const FormattingOptions &options)`. The fact is the same fallback the other-file // branch uses, so the label, the count and the active parameter are right even without the parameter spans. - if sources.is_empty() - && let Some(parameters) = &candidate.parameters - { - let (tidy, _) = sema::call_syntax::tidy_list_text(parameters); - let label = format!("{spelling}{tidy}"); - signatures.push(CallSignature { - parameters: parameters_from_a_written_list(&tidy, spelling.len()), - label, - active_parameter: active, - declared_in: candidate.file.clone(), - declared_at: candidate.name_offset, - documentation: None, - }); - rankable.push((Vec::new(), Vec::new())); - continue; - } - for source in sources { let Some(list) = parameter_list_of(declared_in, source.name_offset) else { continue; @@ -269,38 +225,42 @@ where // file (MSVC wraps three of `basic_string::append`'s nine overloads), and a popup label with a newline in it // is a popup with a broken signature — so the same tidying the fact's `parameter_list` gets is applied here, // *with its byte map*, because the spans a client bolds are offsets into this label. - let list_text = list.text().to_string(); - let list_text = list_text.trim_end(); - let list_begin = usize::from(list.text_range().start()); - let raw: Vec<(Range, String)> = parameters_of(&list) - .into_iter() - .map(|(parameter, _)| { - let text = parameter.text().to_string(); - let text = text.trim_end(); - let start = usize::from(parameter.text_range().start()) - list_begin; - (start..start + text.len(), text.to_string()) - }) - .collect(); - - let (tidy, moved) = sema::call_syntax::tidy_list_text(list_text); - let list_start = spelling.len(); - let label = format!("{spelling}{tidy}"); - let parameters: Vec<(Range, String)> = raw - .into_iter() - .map(|(range, text)| { - ( - list_start + moved[range.start]..list_start + moved[range.end], - text, - ) - }) - .collect(); - - // The declaration's own parameter texts, names dropped, and the template header it owns — the last read + // **Label and spans from the CST parameter nodes.** No text layout pass: each parameter's own source + // span is what a client bolds, and its text is collapsed only at this display boundary. + let mut label = format!("{spelling}("); + let mut parameters: Vec<(Range, String)> = Vec::new(); + // **The structured parameter types, from the same nodes the label is made of.** A parameter this layer + // cannot shape keeps its written form as the type's *name* — `type_of_declaration`'s own honest reading — + // so its arity is still counted and its ranking is `Unranked` rather than wrong. + let mut plain: Vec = Vec::new(); + for (at, (parameter, _)) in parameters_of(&list).into_iter().enumerate() { + let mut text = parameter.text().to_string(); + text = text.split_whitespace().collect::>().join(" "); + if at > 0 { + label.push_str(", "); + } + let start = label.len(); + label.push_str(&text); + parameters.push((start..label.len(), text.clone())); + let written = CppParam::cast(parameter) + .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); + plain.push(written.unwrap_or_else(|| ComputedType::named(text, Vec::new()))); + } + // **The list's own `...` is a token of the list, not a parameter node**, so the loop above cannot see + // it: `void f(int, ...)` has one `CppParam` and the marker beside it, and `void f(...)` has none. It is + // appended to the label here — the one place a display spelling is written — and travels to the ranking + // as a flag rather than as a suffix of this label. + let variadic = CppParamList::cast(list.clone()).is_some_and(|list| list.is_variadic()); + if variadic { + if !parameters.is_empty() { + label.push_str(", "); + } + label.push_str("..."); + } + label.push(')'); + + // The declaration's own parameter types, and the template header it owns — the last read // from the text before the declaration, which is a heuristic and is stated as one below. - let plain: Vec = parameters - .iter() - .map(|(_, text)| sema::overload::a_type_without_its_name(text)) - .collect(); let templates = sema::deduction::template_parameters_before( &declared_in.source, source.name_offset, @@ -314,7 +274,7 @@ where declared_at: source.name_offset, documentation: None, }); - rankable.push((plain, templates)); + rankable.push((plain, templates, variadic)); } } @@ -348,38 +308,34 @@ where // Every node of this file's own text, traversed once: `inlay::arguments_of` is the crate's answer to "where are // this call's arguments", and the `SemanticModel` is what types them. let arguments = arguments_of(&call).unwrap_or_default(); - let types: Vec> = arguments + let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(a_type.to_string()), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) .collect(); // **Deduce, then substitute, then rank.** A template candidate whose arguments the call fixes is ranked as the - // function it instantiates; one whose arguments the call does not fix keeps its declared spellings, and the + // function it instantiates; one whose arguments the call does not fix keeps its declared types, and the // resolver reads those as `Match::Unranked` — which is the quiet direction, and the right one: a template this - // analysis cannot deduce is a template whose ranking it does not know. + // analysis cannot deduce is a template whose ranking it does not know. Both the deduction and the substitution + // are structural; the label is the only text involved. let ranked: Vec = signatures .iter() .enumerate() .map(|(at, signature)| { - let (plain, templates) = rankable.get(at).cloned().unwrap_or_default(); + let (plain, templates, variadic) = rankable.get(at).cloned().unwrap_or_default(); let plain_for_ordering = plain.clone(); let parameters = match sema::deduction::deduce(&templates, &plain, &types) { - Some(arguments) => plain + Some(deduced) => plain .iter() - .map(|spelling| { - sema::types::substituted_spelling(spelling, &templates, &arguments) - }) + .map(|type_of| sema::deduction::substituted(type_of, &templates, &deduced)) .collect(), None => plain, }; - let candidate = sema::overload::Candidate::new( - parameters, - signature.label.trim_end().ends_with("...)"), - signature.label.clone(), - ); + let candidate = + sema::overload::Candidate::new(parameters, variadic, signature.label.clone()); candidate.with_declaration(plain_for_ordering, templates.clone()) }) .collect(); @@ -603,20 +559,6 @@ where }) } -/// **The parameters of a tidy list, with their spans in that list.** -/// -/// A fallback signature has the declaration's `parameter_list` text and no tree to ask, so the text is parsed as a -/// synthetic declaration by [`sema::call_syntax::parameters_in_a_written_list`]. That matters for the shapes a -/// top-level comma walk gets wrong: a default argument with a comma, a function pointer's nested list, and a -/// comparison such as `bool ok = 1 < 2`, whose `<` is not a template bracket. -fn parameters_from_a_written_list(tidy: &str, base: usize) -> Vec<(Range, String)> { - sema::call_syntax::parameters_in_a_written_list(tidy) - .unwrap_or_default() - .into_iter() - .map(|(range, text)| (base + range.start..base + range.end, text)) - .collect() -} - /// The `)` that closes the `(` at `open`, in `text`. fn matching_paren(text: &str, open: usize) -> Option { let mut depth = 0usize; @@ -787,29 +729,64 @@ fn constructors_in_the_index( }; let mut constructors = Vec::new(); for declaration in &found.found { - if declaration.fact.name != class { + let Some(fact) = index.definition_fact(declaration) else { + continue; + }; + let Some(file) = index.definition_path(declaration) else { + continue; + }; + if fact.name != class { continue; } - if declaration.fact.kind != DeclKind::Function { + if fact.kind != DeclKind::Function { continue; } - let Some(scope) = declaration.fact.scope.as_deref() else { + let Some(scope) = fact.scope.as_deref() else { continue; }; if scope.rsplit("::").next().map(str::trim) != Some(class) { continue; } - let Some(parameters) = declaration.fact.parameter_list() else { + let facts = index.parameter_facts_of(file, fact); + if facts.is_empty() { continue; - }; - let (tidy, _) = sema::call_syntax::tidy_list_text(parameters); - let label = format!("{class}{tidy}"); + } + let mut label = format!("{class}("); + let mut parameters: Vec<(Range, String)> = Vec::new(); + for (at, parameter) in facts.iter().enumerate() { + // **The display spelling, at the popup's own boundary.** The type is resolved structurally by + // [`crate::ProjectIndex::parameter_spelling`]; this label is the one place the text is written. + let Some(spelling) = index.parameter_spelling(parameter) else { + parameters.clear(); + break; + }; + if at > 0 { + label.push_str(", "); + } + let mut text = spelling.to_string(); + if let Some(name) = parameter.name.as_deref() { + text.push(' '); + text.push_str(name); + } + let start = label.len(); + label.push_str(&text); + parameters.push((start..label.len(), text)); + } + if parameters.is_empty() { + continue; + } + // **The list's own `...`** — from the fact, not from the label being built: `Widget(int, ...)` has one + // parameter fact and the marker is a token of the list. See [`crate::DeclFact::variadic_parameters`]. + if fact.variadic_parameters { + label.push_str(", ..."); + } + label.push(')'); constructors.push(CallSignature { - parameters: parameters_from_a_written_list(&tidy, class.len()), + parameters, label, active_parameter: active, - declared_in: declaration.file.clone(), - declared_at: declaration.fact.name_range.start_offset, + declared_in: file.to_path_buf(), + declared_at: fact.name_range.start_offset, documentation: None, }); } diff --git a/crates/cpp_code_analysis/src/session/tests/buffers.rs b/crates/cpp_code_analysis/src/session/tests/buffers.rs index 59f49c6d..9de4ed35 100644 --- a/crates/cpp_code_analysis/src/session/tests/buffers.rs +++ b/crates/cpp_code_analysis/src/session/tests/buffers.rs @@ -36,7 +36,7 @@ pub(crate) fn a_buffer_that_has_never_been_saved_is_a_file_like_any_other() { .find("Widget w") .expect("the use is in the text"); assert!( - matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")), + matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if session.index().definition_path(&found) == Some(Path::new("/p/widget.h"))), "a buffer no file has answers as the declaration's file" ); } @@ -86,7 +86,7 @@ pub(crate) fn an_edit_replaces_what_the_index_knew_and_the_gap_is_visible() { Known::Yes(members) => { let names: Vec<&str> = members .own() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!(names, ["after"]); } @@ -138,7 +138,7 @@ pub(crate) fn closing_a_document_goes_back_to_the_file() { Known::Yes(members) => { let names: Vec<&str> = members .own() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!(names, ["on_disk"]); } @@ -446,7 +446,7 @@ pub(crate) fn a_name_in_a_file_that_has_not_been_read_is_unknown_and_the_queue_s assert!(session.is_idle()); assert!( - matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")), + matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if session.index().definition_path(&found) == Some(Path::new("/p/widget.h"))), "the same question, answered once the file has been read" ); } @@ -500,7 +500,7 @@ pub(crate) fn a_view_is_the_buffer_parsed_and_maps_a_position_onto_an_offset() { // And the file's own scope answers the query, with no index involved at all. assert!( - matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/a.cpp")), + matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if session.index().definition_path(&found) == Some(Path::new("/p/a.cpp"))), "a local declaration is resolved by the file's scopes" ); @@ -570,3 +570,69 @@ pub(crate) fn a_position_maps_back_onto_the_offset_it_came_from() { "an offset past the end is not a position" ); } + +// ------------------------------------------------------------------------------------------- +// The runtime file id +// +// `FileId` is the VFS's, not the index's: a reference the index mints has to name the id the session's VFS gave +// the file, or a consumer holding a VFS id cannot ask the index about it and `path_of` cannot answer. +// ------------------------------------------------------------------------------------------- + +/// **A file the pump read is named by the VFS's id**, including the references the index mints for it. +/// +/// Before the VFS table existed, `ProjectIndex::file_id_of` answered the insertion sequence — a number that is not +/// the VFS's and that a consumer could not use to ask the session about the file. This is the end-to-end assertion +/// that `Session::index_one` registered the id `Vfs::load` returned, for the whole chain. +#[test] +pub(crate) fn a_read_files_runtime_id_is_the_vfs_id_and_its_facts_name_it() { + let files = MemoryFiles::new().with_file("/p/a.cpp", "struct A { int size; };\n"); + let fixture = Memory::new("vfs-file-id", &files); + let mut session = fixture.session(); + session.add_project_files([PathBuf::from("/p/a.cpp")]); + session.index_everything(); + + let vfs = session + .files() + .held("/p/a.cpp") + .expect("index_one loaded the file") + .id; + let index = session.index(); + assert_eq!(index.file_id_of(Path::new("/p/a.cpp")), Some(vfs)); + assert_eq!(index.path_of(vfs), Some(Path::new("/p/a.cpp"))); + + let fact = index + .summary_fact_ref(Path::new("/p/a.cpp"), 0) + .expect("the summary has a declaration"); + assert_eq!(fact.file, vfs, "the reference names the VFS's file"); + assert_eq!( + index.fact(fact).map(|fact| fact.name.as_str()), + Some("A"), + "and it resolves through the same table" + ); +} + +/// **A buffer is registered when it is opened, before the pump reads it.** A completion between the edit and the +/// re-read synthesizes facts through the index; those must name the VFS id the buffer already has. +#[test] +pub(crate) fn an_open_buffer_is_registered_before_the_pump_reads_it() { + let files = MemoryFiles::new(); + let fixture = Memory::new("vfs-buffer-id", &files); + let mut session = fixture.session(); + + session.did_open("/p/unsaved.cpp", "struct Buffer { int size; };\n"); + let vfs = session + .files() + .held("/p/unsaved.cpp") + .expect("did_open inserted the text") + .id; + assert_eq!( + session.index().file_id_of(Path::new("/p/unsaved.cpp")), + Some(vfs), + "the buffer's id is known before its summary exists" + ); + assert_eq!( + session.index().path_of(vfs), + Some(Path::new("/p/unsaved.cpp")), + "and the path resolves from the VFS table alone" + ); +} diff --git a/crates/cpp_code_analysis/src/session/tests/cache.rs b/crates/cpp_code_analysis/src/session/tests/cache.rs index c4ab72c2..71a26094 100644 --- a/crates/cpp_code_analysis/src/session/tests/cache.rs +++ b/crates/cpp_code_analysis/src/session/tests/cache.rs @@ -87,7 +87,13 @@ pub(crate) fn a_rendering_is_not_left_in_the_cache_for_the_next_session() { let found = session.index().definition("Live", Path::new("/p/api.h")); match found { Known::Yes(found) => assert_eq!( - found.fact.range.start_offset, alone, + session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .range + .start_offset, + alone, "and a query answers the branch this file has when nothing defines `FROM_THE_SOURCE`" ), Known::Unknown(UnknownReason::Ambiguous(_)) => {} diff --git a/crates/cpp_code_analysis/src/session/tests/closure.rs b/crates/cpp_code_analysis/src/session/tests/closure.rs index 73607508..2f042d2b 100644 --- a/crates/cpp_code_analysis/src/session/tests/closure.rs +++ b/crates/cpp_code_analysis/src/session/tests/closure.rs @@ -429,7 +429,7 @@ pub(crate) fn an_implementation_unit_sees_its_interface_units_declarations() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!( names.contains(&"x_") || names.contains(&"square"), @@ -510,7 +510,7 @@ pub(crate) fn a_modules_includes_define_what_a_later_condition_asks() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect::>() ); } @@ -701,11 +701,14 @@ pub(crate) fn a_parameter_of_an_out_of_class_definition_is_declared() { let Known::Yes(found) = found else { unreachable!() }; + let fact = session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index"); assert_eq!( - found.fact.name.as_str(), + fact.name.as_str(), "entry", - "and it is the parameter, not a type or a namespace member: {:?}", - found.fact + "and it is the parameter, not a type or a namespace member: {fact:?}" ); } diff --git a/crates/cpp_code_analysis/src/session/tests/cooked.rs b/crates/cpp_code_analysis/src/session/tests/cooked.rs index c67fd742..5663a580 100644 --- a/crates/cpp_code_analysis/src/session/tests/cooked.rs +++ b/crates/cpp_code_analysis/src/session/tests/cooked.rs @@ -45,8 +45,15 @@ pub(crate) fn a_declaration_only_a_macro_makes_is_found_once_the_session_has_coo let Known::Yes(found) = after else { panic!("the cooked reading declares it: {after:?}"); }; - assert_eq!(found.file, Path::new("/p/api.h")); - let at = found.fact.range; + assert_eq!( + session.index().definition_path(&found), + Some(Path::new("/p/api.h")) + ); + let at = session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .range; let written = &source[at.start_offset..at.end_offset()]; assert!( written.contains("DECLARE_HANDLE"), @@ -108,8 +115,8 @@ pub(crate) fn a_header_the_user_never_opened_is_cooked_when_a_request_names_it() panic!("`api.h`'s cooked reading declares it: {after:?}"); }; assert_eq!( - found.file, - Path::new("/p/api.h"), + session.index().definition_path(&found), + Some(Path::new("/p/api.h")), "the file that invoked the macro, which nobody opened" ); @@ -521,7 +528,10 @@ pub(crate) fn a_unit_read_reads_the_whole_program_once() { let Known::Yes(found) = after else { panic!("`api.h`'s cooked reading declares it: {after:?}"); }; - assert_eq!(found.file, Path::new("/p/api.h")); + assert_eq!( + session.index().definition_path(&found), + Some(Path::new("/p/api.h")) + ); // **And a file outside the program is not touched**: nothing compiles `other.cpp`, nobody opens it. assert!( @@ -596,8 +606,8 @@ pub(crate) fn a_program_is_read_when_the_reader_stops_editing() { panic!("the macro's declaration is in the index after the program was read: {found:?}"); }; assert_eq!( - found.file, - Path::new("/p/api.h"), + session.index().definition_path(&found), + Some(Path::new("/p/api.h")), "filed under the file that invoked the macro" ); } diff --git a/crates/cpp_code_analysis/src/session/tests/disk.rs b/crates/cpp_code_analysis/src/session/tests/disk.rs index 62c2f1f1..a85e1379 100644 --- a/crates/cpp_code_analysis/src/session/tests/disk.rs +++ b/crates/cpp_code_analysis/src/session/tests/disk.rs @@ -172,8 +172,19 @@ pub(crate) fn a_class_scoped_by_another_files_macro_body_is_scoped_through_the_s let Known::Yes(found) = found else { panic!("`Widget` is declared behind a macro body written in `open.h`: {found:?}"); }; - assert_eq!(found.file, widget); - assert_eq!(found.fact.scope.as_deref(), Some("std")); + assert_eq!( + session.index().definition_path(&found), + Some(widget.as_path()) + ); + assert_eq!( + session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .scope + .as_deref(), + Some("std") + ); // And the scope is a reading **of the body, not a conclusion about it**. The body is in `open.h`; the scope it // opens is in `widget.h` only because `widget.h` renders through it. So a changed body has to be a changed @@ -216,8 +227,11 @@ pub(crate) fn a_class_scoped_by_another_files_macro_body_is_scoped_through_the_s panic!("`Widget` is behind `namespace studio` now: {moved:?}"); }; assert_eq!( - moved.file.file_name(), - widget.file_name(), + session + .index() + .definition_path(&moved) + .and_then(|path| path.file_name().map(|name| name.to_os_string())), + widget.file_name().map(|name| name.to_os_string()), "the declaration is still `widget.h`'s" ); } diff --git a/crates/cpp_code_analysis/src/session/tests/names.rs b/crates/cpp_code_analysis/src/session/tests/names.rs index 8c7b92d4..62ea99f0 100644 --- a/crates/cpp_code_analysis/src/session/tests/names.rs +++ b/crates/cpp_code_analysis/src/session/tests/names.rs @@ -211,11 +211,15 @@ pub(crate) fn a_forward_declaration_does_not_shadow_the_definition() { .definition("Widget", Path::new("/p/use.cpp")) { Known::Yes(found) => { + let fact = session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index"); assert_eq!( - found.fact.range.start_offset, definition, + fact.range.start_offset, definition, "the answer is the definition, not the forward declaration written above it" ); - assert!(found.fact.definition, "and the fact says so"); + assert!(fact.definition, "and the fact says so"); } other => panic!("`Widget` is defined in the header: {other:?}"), } @@ -242,11 +246,16 @@ pub(crate) fn a_forward_declaration_does_not_shadow_the_definition() { .index() .definition("Gadget", Path::new("/p/use.cpp")) { - Known::Yes(found) => assert!( - found.file.ends_with("gadget.h") && !found.file.ends_with("gadget_forward.h"), - "the definition wins over the forward declaration in another file: {:?}", - found.file - ), + Known::Yes(found) => { + let path = session + .index() + .definition_path(&found) + .expect("the answer names a file the index holds"); + assert!( + path.ends_with("gadget.h") && !path.ends_with("gadget_forward.h"), + "the definition wins over the forward declaration in another file: {path:?}" + ); + } other => panic!("`Gadget` is defined in a header this file includes: {other:?}"), } } @@ -285,19 +294,17 @@ pub(crate) fn a_class_template_resolves_to_its_primary_definition() { .definition("vector", Path::new("/p/use.cpp")) { Known::Yes(found) => { - assert!( - found.fact.definition, - "a definition, not a forward declaration" - ); + let fact = session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index"); + assert!(fact.definition, "a definition, not a forward declaration"); assert_eq!( - found.fact.pattern(), + fact.pattern(), None, "the primary template, not `vector`" ); - assert_eq!( - found.fact.range.start_offset, primary, - "and its own declaration" - ); + assert_eq!(fact.range.start_offset, primary, "and its own declaration"); } other => panic!("`vector` has a primary definition in this closure: {other:?}"), } @@ -535,8 +542,18 @@ pub(crate) fn a_name_a_macro_writes_is_in_the_index_once_its_header_was_cooked() .expect("the call is in the text"); match editor.definition(&view, ReadingOffset::new(at)) { Known::Yes(found) => { - assert_eq!(found.file, Path::new("/p/lib.h")); - assert_eq!(found.fact.name, "lib_open"); + assert_eq!( + editor.index().definition_path(&found), + Some(Path::new("/p/lib.h")) + ); + assert_eq!( + editor + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .name, + "lib_open" + ); } other => panic!("the macro's declaration is not in the index: {other:?}"), } diff --git a/crates/cpp_code_analysis/src/session/tests/programs.rs b/crates/cpp_code_analysis/src/session/tests/programs.rs index 044c6332..f16db55b 100644 --- a/crates/cpp_code_analysis/src/session/tests/programs.rs +++ b/crates/cpp_code_analysis/src/session/tests/programs.rs @@ -191,16 +191,35 @@ pub(crate) fn a_files_rendering_is_its_reading_and_not_one_answer_beside_another found .found .iter() - .map(|one| one.fact.range) + .map(|one| session + .index() + .definition_fact(one) + .expect("the answer resolves through the index") + .range) .collect::>() ); assert_eq!( - found.found[0].fact.range.start_offset, taken, + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .range + .start_offset, + taken, "the answer is the branch `FROM_THE_SOURCE` selects: {:?}", - found.found[0].fact.range + session + .index() + .definition_fact(&found.found[0]) + .map(|fact| fact.range) ); assert_ne!( - found.found[0].fact.range.start_offset, not_taken, + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .range + .start_offset, + not_taken, "and not the one the file has when it is read on its own" ); } @@ -275,7 +294,12 @@ pub(crate) fn a_header_read_in_two_programs_answers_each_its_own_way() { let from_a = session.index().definitions("X", Path::new("/p/a.cpp")); let from_b = session.index().definitions("X", Path::new("/p/b.cpp")); let offset = |known: &Known| match known { - Known::Yes(found) => found.found.first().map(|one| one.fact.range.start_offset), + Known::Yes(found) => found.found.first().and_then(|one| { + session + .index() + .definition_fact(one) + .map(|fact| fact.range.start_offset) + }), _ => None, }; assert_eq!( @@ -1149,8 +1173,18 @@ pub(crate) fn a_buffer_is_the_text_the_analysis_reads() { match session.definition(&view, ReadingOffset::new(at)) { Known::Yes(found) => { - assert_eq!(found.file, Path::new("/p/widget.h")); - assert_eq!(found.fact.name, "Widget"); + assert_eq!( + session.index().definition_path(&found), + Some(Path::new("/p/widget.h")) + ); + assert_eq!( + session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .name, + "Widget" + ); } other => panic!("the buffer's declaration should be found, got {other:?}"), } @@ -1160,7 +1194,7 @@ pub(crate) fn a_buffer_is_the_text_the_analysis_reads() { Known::Yes(members) => { let names: Vec<&str> = members .own() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!( names, diff --git a/crates/cpp_code_analysis/src/session/tests/types.rs b/crates/cpp_code_analysis/src/session/tests/types.rs index 9fecd802..048adf3d 100644 --- a/crates/cpp_code_analysis/src/session/tests/types.rs +++ b/crates/cpp_code_analysis/src/session/tests/types.rs @@ -123,7 +123,14 @@ pub(crate) fn a_maps_find_reaches_the_element_when_the_comparator_is_written() { let Known::Yes(found) = found else { panic!("`find(1)->second` must resolve: {found:?}"); }; - assert_eq!(found.found[0].fact.name, "second"); + assert_eq!( + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name, + "second" + ); } /// **`map::find(…)`'s answer, the shape the real project has** — the call's type, then the arrow, then the element. /// @@ -164,8 +171,18 @@ pub(crate) fn a_calls_iterator_answer_reaches_the_element_through_a_trait_alias( }; assert_eq!( ( - found.found[0].fact.name.as_str(), - found.found[0].fact.scope.as_deref() + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name + .as_str(), + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .scope + .as_deref() ), ("second", Some("element")), "the call's iterator, its `pointer` alias, and the trait alias in it" @@ -265,7 +282,7 @@ pub(crate) fn a_member_list_is_reached_through_an_alias_written_absolutely() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); names.sort_unstable(); names.dedup(); @@ -374,7 +391,12 @@ pub(crate) fn an_unscoped_enumerations_member_is_visible_in_the_enclosing_scope( panic!("a bare `AnotherClass` must resolve: {found:?}"); }; assert_eq!( - found.found[0].fact.name, "AnotherClass", + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name, + "AnotherClass", "the enumerator, not the enumeration" ); @@ -414,13 +436,20 @@ pub(crate) fn an_unscoped_enumerations_member_is_visible_in_the_enclosing_scope( let Known::Yes(found) = found else { panic!("the declaration of `AnotherClass` must answer: {found:?}"); }; - assert_eq!(found.found[0].fact.name, "AnotherClass"); + assert_eq!( + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name, + "AnotherClass" + ); // **`enum class` still hides its enumerators**: `Scoped::Hidden` is the only way to name it. let hidden = text.find("= Hidden").expect("the fixture") + 2; let found = session.definitions(&view, file::coordinates::ReadingOffset::new(hidden)); assert!( - !matches!(&found, Known::Yes(found) if found.found[0].fact.name == "Hidden"), + !matches!(&found, Known::Yes(found) if session.index().definition_fact(&found.found[0]).expect("the answer resolves through the index").name == "Hidden"), "a scoped enumeration's member is not visible here: {found:?}" ); } @@ -460,7 +489,7 @@ pub(crate) fn a_trait_alias_selects_the_specialization_its_arguments_name() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!( completions.class, "Item", @@ -509,8 +538,18 @@ pub(crate) fn an_arrow_through_an_alias_reaches_the_pointee() { }; assert_eq!( ( - found.found[0].fact.name.as_str(), - found.found[0].fact.scope.as_deref() + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name + .as_str(), + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .scope + .as_deref() ), ("second", Some("pair")), "the arrow's `pointer` is the value type, and `second` is its member" @@ -548,25 +587,34 @@ pub(crate) fn an_out_of_line_definition_records_the_type_it_writes() { let path = std::path::PathBuf::from("/p/a.cpp"); let summary = session.index().summary(&path).expect("the file is read"); + let index = session.index(); for (name, expected) in [ ("Reserved", "std::map"), ("GetLine", "std::size_t"), ] { - let written: Vec> = summary + let written: Vec> = summary .declarations .iter() .filter(|fact| fact.name == name) - .map(|fact| fact.type_of.as_deref().or(fact.returns.as_deref())) + .map(|fact| { + index + .type_spelling_of(fact) + .or_else(|| index.returns_spelling_of(fact)) + }) .collect(); assert!( - written.contains(&Some(expected)), + written + .iter() + .flatten() + .any(|found| found.as_str() == expected), "`{name}` declares `{expected}`, and one of its facts must say so: {written:?}" ); let qualified = format!("::{name}"); assert!( !written .iter() - .any(|found| found.is_some_and(|found| found.ends_with(&qualified))), + .flatten() + .any(|found| found.ends_with(&qualified)), "and none of them may record the declarator's own qualified name (`…{qualified}`): {written:?}" ); } @@ -637,8 +685,18 @@ pub(crate) fn a_class_templates_members_are_read_through_the_uses_arguments() { }; assert_eq!( ( - found.found[0].fact.name.as_str(), - found.found[0].fact.scope.as_deref() + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name + .as_str(), + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .scope + .as_deref() ), expected, "`{written}` is the element's member" @@ -703,7 +761,7 @@ pub(crate) fn an_arrow_through_a_member_template_reaches_the_element_type() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!( completions.class, "Item", @@ -772,7 +830,7 @@ pub(crate) fn an_arrow_through_a_base_named_by_a_member_alias_in_another_file() .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!( completions.class, "Item", @@ -817,8 +875,18 @@ pub(crate) fn a_class_templates_alias_return_is_substituted_too() { }; assert_eq!( ( - found.found[0].fact.name.as_str(), - found.found[0].fact.scope.as_deref() + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .name + .as_str(), + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .scope + .as_deref() ), ("value", Some("Item")), "the alias's target is the use's argument, not the class's parameter name" @@ -846,7 +914,12 @@ pub(crate) fn an_anonymous_enum_declares_its_enumerators() { panic!("`{name}` is declared by the anonymous enum: {found:?}"); }; assert_eq!( - found.found[0].fact.scope, None, + session + .index() + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index") + .scope, + None, "an unnamed enum has no scope name" ); } @@ -923,7 +996,20 @@ pub(crate) fn a_member_through_an_operator_arrow_is_the_pointees() { panic!("`config->Generate` must resolve through `operator->`: {found:?}"); }; assert_eq!( - (found.fact.name.as_str(), found.fact.scope.as_deref()), + ( + session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .name + .as_str(), + session + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .scope + .as_deref() + ), ("Generate", Some("Config")), "the member is the pointee's" ); @@ -939,7 +1025,7 @@ pub(crate) fn a_member_through_an_operator_arrow_is_the_pointees() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert_eq!(names, ["Generate"], "and not the handle's own list"); } diff --git a/crates/cpp_code_analysis/src/session/units.rs b/crates/cpp_code_analysis/src/session/units.rs index 9180f8c1..cbcc1e78 100644 --- a/crates/cpp_code_analysis/src/session/units.rs +++ b/crates/cpp_code_analysis/src/session/units.rs @@ -17,6 +17,7 @@ use crate::cache; use crate::completion; use crate::effect; use crate::index; +use crate::index::types::ComputedType; use crate::paths; use crate::preprocess; use crate::sema; @@ -115,9 +116,14 @@ impl Session { /// Read a file in and hold it, answering with the id the VFS gave it. /// /// The **writer** path's way to hold a file: a notification, an indexing step, a caller that knows it is about - /// to ask several questions about one file. After this, [Session::view] and [Session::text] answer for it. + /// to ask several questions about one file. After this, [Session::view] and [Session::text] answer for it — and + /// the index knows the id the file will be indexed under, so a reference minted before the pump reaches the file + /// already names it (see [`crate::ProjectIndex::register_file_id`]). pub fn load(&mut self, path: impl AsRef) -> Option { - self.vfs.load(path) + let path = path.as_ref(); + let id = self.vfs.load(path)?; + self.store.index_mut().register_file_id(path, id); + Some(id) } /// The files the session is holding: their text and their line indexes. @@ -1581,7 +1587,6 @@ impl Session { arrow: bool, ) -> Option { let reached = self.the_type_after_the_operator(view, written, arrow)?; - let reached = sema::types::parse_type_spelling(&reached); let bare = reached.class_name().map(str::to_string)?; // **The class as the index files it.** A member is recorded under the class's qualified name, and a type // deduced from a `std::` function is spelled without the namespace: `make_shared` answers @@ -1606,24 +1611,29 @@ impl Session { view: &FileView, written: &str, arrow: bool, - ) -> Option { + ) -> Option { let written = sema::types::parse_type_spelling(written); // **The pointee, by `element_type` with the type's own arguments substituted** — `shared_ptr` reaches // `Node`, where the completion's resolver answered `std::shared_ptr` because `element_type` is written `_Tp`. See // [`crate::index::project::the_pointee_of_a_handle`]; the resolver below stays for a raw pointer and for an // `operator->` whose return type is a class. - if arrow && let sema::types::Type::Named { name, arguments } = &written { + let parts: Option<(&str, &[ComputedType])> = match &written { + ComputedType::Named(name) => Some((name.as_str(), &[])), + ComputedType::Generic(generic) => Some((generic.name.as_str(), &generic.arguments)), + _ => None, + }; + if arrow && let Some((name, arguments)) = parts { // **The class as the index files it.** A member is recorded under the class's qualified name, and a type // deduced from a `std::` function is spelled without the namespace: `make_shared` answers // `shared_ptr` while the class is `std::shared_ptr`, whose `element_type` is the member being read. let class = match name.contains("::") { - true => name.clone(), + true => name.to_string(), false => { index::project::qualified_from_the_index(self.store.index(), &view.path, name) - .unwrap_or_else(|| name.clone()) + .unwrap_or_else(|| name.to_string()) } }; - if let Some((pointee, _)) = index::project::the_pointee_of_a_handle( + if let Some((pointee, pointee_arguments)) = index::project::the_pointee_of_a_handle( self.store.index(), &view.scopes, &view.root, @@ -1631,7 +1641,7 @@ impl Session { &class, arguments, ) { - return Some(pointee); + return Some(ComputedType::named(pointee, pointee_arguments)); } } completion::the_type_after_the_operator( @@ -1642,7 +1652,7 @@ impl Session { &written, arrow, ) - .map(|(reached, _)| reached.to_string()) + .map(|(reached, _)| reached) } /// **Read one queued module unit as a program, now** — the compiler's reading of a module, for a caller that is diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs new file mode 100644 index 00000000..f35b67e8 --- /dev/null +++ b/crates/cpp_code_analysis/tests/params.rs @@ -0,0 +1,118 @@ +//! Parameter facts are the CST-side input to overload ranking; these tests pin that no parameter list text is parsed. +//! +//! **The lowering is structural, and these tests say so**: a parameter's type comes from its own `CppParam` — the +//! specifier sequence plus the declarator the tree already separates — is lowered to the `ComputedType` value a fact +//! carries, and is read back by `parameters_in_facts`. The assertions are on the **structure** (a class name, a +//! template argument count, a reference to a parameter), not on a spelling the fact would have had to record. + +use cpp_code_analysis::cache::summary::DeclaredType; +use cpp_code_analysis::index::params::parameter_facts_of; +use cpp_code_analysis::index::types::{ComputedType, PrimaryType}; +use cpp_code_analysis::sema; +use cpp_code_analysis::sema::overload::parameters_in_facts; +use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; + +/// One declaration's parameter list, lowered the way `sema::declarations::DeclarationFacts::fact_for` lowers it: +/// each parameter's own `CppParam` is read structurally once and the value is stored on the fact. +fn lowered(source: &str) -> (Vec, bool) { + let tree = CppParser::parse(source, ParserConfig::default()); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let mut facts = parameter_facts_of(&list); + for fact in &mut facts { + let node = fact + .declaration + .to_node_from_root(&root) + .expect("the parameter node"); + let parameter = CppParam::cast(node).expect("typed parameter"); + let written = sema::types::type_of_a_parameter(¶meter) + .expect("a parameter has a type this layer can read"); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); + } + parameters_in_facts(&facts, list.is_variadic()) +} + +#[test] +fn parameter_types_come_from_each_cpp_param() { + let (parameters, variadic) = lowered("void f(int a, std::pair p, double... rest);\n"); + assert_eq!(parameters.len(), 3, "one type per parameter"); + assert!( + matches!(¶meters[0], ComputedType::Primary(PrimaryType::Int)), + "`int a` is an `int`, and the name is not part of it: {:?}", + parameters[0] + ); + assert_eq!( + parameters[1].class_name(), + Some("std::pair"), + "`std::pair p` is the class `std::pair` with two arguments: {:?}", + parameters[1] + ); + assert_eq!( + parameters[1].arguments().len(), + 2, + "neither the name nor the comma split the arguments" + ); + assert!( + matches!(¶meters[2], ComputedType::Primary(PrimaryType::Double)), + "a pack is ranked by its element type: {:?}", + parameters[2] + ); + assert!(variadic, "a pack parameter makes the list variadic"); +} + +#[test] +fn a_c_style_ellipsis_is_reported_by_the_list_flag() { + let (parameters, variadic) = lowered("void f(const char* format, ...);\n"); + assert_eq!( + parameters.len(), + 1, + "the trailing ellipsis is not a parameter" + ); + assert!( + matches!( + ¶meters[0], + ComputedType::Pointer(pointee) + if matches!(&**pointee, ComputedType::Qualified(qualified) if qualified.is_const) + ), + "`const char* format` is a pointer to a const `char`: {:?}", + parameters[0] + ); + assert!(variadic, "the list-level `...` is the caller's flag"); +} + +/// **A parameter written with the declaration's template parameter is structured as one** — the step +/// `sema::declarations::fact_for` performs before lowering, pinned on the computation side. +#[test] +fn a_parameter_written_with_a_template_parameter_is_structured_as_one() { + let tree = CppParser::parse("void f(T&& value);\n", ParserConfig::default()); + let root = tree.get_red_root(); + let list = root + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + let mut facts = parameter_facts_of(&list); + let node = facts[0] + .declaration + .to_node_from_root(&root) + .expect("the parameter node"); + let parameter = CppParam::cast(node).expect("typed parameter"); + let written = sema::types::type_of_a_parameter(¶meter).expect("a parameter type"); + let written = sema::types::with_template_parameters(written, &["T".to_string()]); + facts[0].type_of = DeclaredType::Computed(std::sync::Arc::new(written)); + + let (parameters, variadic) = parameters_in_facts(&facts, false); + assert_eq!(parameters.len(), 1); + assert!( + matches!( + ¶meters[0], + ComputedType::Reference { to, rvalue: true } + if matches!(&**to, ComputedType::TemplateParameter(name) if name == "T") + ), + "`T&&` is a reference to the template parameter, not to a class called `T`: {:?}", + parameters[0] + ); + assert!(!variadic, "`T&&` is not a pack"); +} diff --git a/crates/cpp_code_analysis/tests/suite/alias_members.rs b/crates/cpp_code_analysis/tests/suite/alias_members.rs index a4d60ace..53712081 100644 --- a/crates/cpp_code_analysis/tests/suite/alias_members.rs +++ b/crates/cpp_code_analysis/tests/suite/alias_members.rs @@ -75,7 +75,7 @@ fn an_alias_templates_members_are_the_members_of_the_class_it_names() { let names: Vec = list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(); assert!( names.iter().any(|name| name == "put") && names.iter().any(|name| name == "get"), @@ -211,7 +211,7 @@ void use() { let names: Vec = list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(); assert!( names.iter().any(|name| name == "put"), diff --git a/crates/cpp_code_analysis/tests/suite/alias_qualified_members.rs b/crates/cpp_code_analysis/tests/suite/alias_qualified_members.rs index 00ba11e6..be77a9ae 100644 --- a/crates/cpp_code_analysis/tests/suite/alias_qualified_members.rs +++ b/crates/cpp_code_analysis/tests/suite/alias_qualified_members.rs @@ -46,10 +46,15 @@ fn where_at(session: &Session, path: &str, needle: &str) -> String .reading_offset_of(FileOffset::new(at)) .expect("the file offset is in the reading"); match session.definition(&view, ReadingOffset::new(reading.get())) { - Known::Yes(found) => match &found.fact.scope { - Some(scope) => format!("{scope}::{}", found.fact.name), - None => found.fact.name.to_string(), - }, + Known::Yes(found) => { + let Some(fact) = session.definition_fact(&found) else { + return "unknown: the answer does not resolve".to_string(); + }; + match &fact.scope { + Some(scope) => format!("{scope}::{}", fact.name), + None => fact.name.to_string(), + } + } Known::Unknown(reason) => format!("unknown: {reason:?}"), Known::No => "no".to_string(), } diff --git a/crates/cpp_code_analysis/tests/suite/c_declarators.rs b/crates/cpp_code_analysis/tests/suite/c_declarators.rs index 9133bc1c..a92b6c1f 100644 --- a/crates/cpp_code_analysis/tests/suite/c_declarators.rs +++ b/crates/cpp_code_analysis/tests/suite/c_declarators.rs @@ -115,7 +115,9 @@ fn a_parenthesised_declarators_parameters_are_locals() { let at = source.find("int a").expect("the parameter") + "int ".len(); match session.definitions(&view, ReadingOffset::new(at)) { Known::Yes(found) => { - let parameter = &found.found[0].fact; + let parameter = session + .definition_fact(&found.found[0]) + .expect("the answer resolves through the index"); assert_eq!(parameter.name, "a"); assert!( parameter.local, diff --git a/crates/cpp_code_analysis/tests/suite/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 29fd2dd7..fb34fdd5 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -1469,6 +1469,8 @@ template void forward_plain(Args... args); void classic(const char* format, ...); + +void only_ellipsis(...); "; let calls = "\ #include \"other.h\" @@ -1477,6 +1479,7 @@ void use() { forward_all(1, 2, 3); forward_plain(1, 2, 3); classic(\"%d %d %d\", 1, 2, 3); + only_ellipsis(1, 2, 3); } "; let codes = codes_with_two_files(calls, declarations); @@ -2097,14 +2100,13 @@ void f() { ); } -/// **A named parameter is not checked, and that is a gap rather than a rule.** +/// **A named parameter is checked like an unnamed one**, because the type is read from the parameter's own node. /// -/// `parameter_spellings_of` returns the parameter as the file wrote it — `int width` — and `parse_type_spelling` reads a -/// *type*, so the comparison sees a spelling it cannot parse and says nothing. Measured: the same call is reported when -/// the parameter is unnamed (`void resize(int)`) and silent when it is named, which is the shape every real codebase -/// writes. `sema::overload::parameters_in` already strips the name (`a_type_without_its_name`), so the fix is to read the -/// spellings through it — recorded here rather than asserted, because changing it makes this check fire on code it has -/// never judged before, which is a census to run first. +/// The check used to read the declaration's parameter *text* — `int width` — and parse it as a type, so it saw a +/// spelling it could not read and said nothing: the same call was reported when the parameter was unnamed +/// (`void resize(int)`) and silent when it was named, which is the shape every real codebase writes. The type is now +/// lowered from the `CppParam` — the specifier sequence plus the declarator, with the name a separate part of the tree +/// — so a parameter's name cannot reach the type at all. #[test] fn a_named_parameter_is_checked_too() { let source = "\ @@ -2224,12 +2226,16 @@ int main() match session.members_of(&view, "std::vector") { Known::Yes(list) => { for member in &list.members { + let fact = session + .index() + .member_fact(member) + .expect("the row names a declaration the index holds"); eprintln!( "PROBE {:?} kind {:?} params {:?} type_of {:?}", - member.fact.name, - member.fact.kind, - member.fact.parameter_list(), - member.fact.type_of + fact.name, + fact.kind, + fact.parameter_list(), + session.index().type_spelling_of(fact) ); } } @@ -4253,7 +4259,7 @@ int free_function() { } /// /// `_Ty` is `std::vector`'s own parameter, and what it accepts is decided by the call — there is nothing to compare an /// argument against. The relation answered `No` (the target names a type nothing declares), and that refusal is what -/// the diagnostic was made of; `convert::conversion`'s template-parameter rule sits in the `Unknown` arm and never ran +/// the diagnostic was made of; `convert::conversion_to`'s template-parameter rule sits in the `Unknown` arm and never /// for a `No`. #[test] fn a_template_parameter_parameter_is_never_a_mismatch() { @@ -4409,7 +4415,7 @@ int *find(int n) { /// **In C a record is nobody else's type.** `struct second` is not a `struct first`, and `int *` is not a /// `struct point *`: C has no inheritance, no converting constructor and no overload, so the pair is decided from -/// the two spellings and the tag keyword C writes for it. +/// the two types and the tag keyword C writes on the target. /// /// The negative half is the point of the language gate: in C++ the same pair is a *hierarchy* question — a base /// pointer converts, and a converting constructor may exist — so it stays `Unknown` there, as it did before. @@ -4444,12 +4450,53 @@ static int caller(void) { struct second other = {0}; return take(other); } ); } +/// **A `union` writes a record tag too.** The C rule is about the keyword C writes before a name, and `union value` +/// is as much a record as `struct point`: an `int *` is not a `union value *`, an `int` is not a `union value`, and a +/// `union value` converts to itself. The functions are **definitions**, so both sides of each call are lowered from +/// the CST rather than resolved from a stored spelling — which is the path the tag now travels structurally. +#[test] +fn a_union_is_a_record_type_in_c() { + let through_a_pointer = "\ +union value { int integer; double real; }; +static void takes_value(union value *value) { (void)value; } +static void caller(void) { int number = 0; takes_value(&number); } +"; + assert!( + codes_of_a_file("/p/a.c", through_a_pointer).contains(&DiagnosticCode::ParamTypeCheck), + "an `int *` is not a `union value *`: {:?}", + codes_of_a_file("/p/a.c", through_a_pointer) + ); + + let by_value = "\ +union value { int integer; double real; }; +static void takes_value(union value value) { (void)value; } +static void caller(void) { takes_value(1); } +"; + assert!( + codes_of_a_file("/p/b.c", by_value).contains(&DiagnosticCode::ParamTypeCheck), + "an `int` is not a `union value`: {:?}", + codes_of_a_file("/p/b.c", by_value) + ); + + let the_same_record = "\ +union value { int integer; double real; }; +static void takes_value(union value value) { (void)value; } +static void caller(union value v) { takes_value(v); } +"; + assert!( + !codes_of_a_file("/p/c.c", the_same_record).contains(&DiagnosticCode::ParamTypeCheck), + "a `union value` converts to itself: {:?}", + codes_of_a_file("/p/c.c", the_same_record) + ); +} + /// **The tag is the evidence, not the name.** A `typedef` that hides a builtin is not a record — `size_t` is an /// `unsigned long long` — and a `void *` converts to any object pointer in C. /// /// Measured doing it the other way: the first version asked the index "is this name a class?", and `members_of` /// answers `Yes` for a typedef's underlying type, so `takes_size_t(1)` was reported as a record conversion. The -/// spelling `struct …` cannot be written by a typedef, which is why the rule reads the *spelling*. +/// keyword `struct …` cannot be written by a typedef, and the type carries it as `Type::ElaboratedRecord`, which is +/// why the rule reads the *type* rather than a name. #[test] fn a_typedef_and_a_void_pointer_are_not_refused_as_records() { let typedef_hidden = "\ diff --git a/crates/cpp_code_analysis/tests/suite/class_body_continuity.rs b/crates/cpp_code_analysis/tests/suite/class_body_continuity.rs index 33239038..bf5f461c 100644 --- a/crates/cpp_code_analysis/tests/suite/class_body_continuity.rs +++ b/crates/cpp_code_analysis/tests/suite/class_body_continuity.rs @@ -37,7 +37,13 @@ fn session_of(files: &[(&str, &str)]) -> Session { session } -/// **The member a name at `needle` declares**, from the index, as `scope::name` — or the refusal. +/// **The member a name at `needle` declares**, as `scope::name` — the **scope tree's** answer, which is what "the +/// class body stays one body" is a property of. +/// +/// The definition query is still asked, so a name the analysis cannot place at all answers its refusal here; the +/// *scope* comes from the binding rather than from the resolved fact, because a fact's `scope` is derived from the +/// scope tree of the reading the index built while a binding is this view's own tree — and this fixture is exactly +/// the shape where the two recoveries differ (see the module note: the index files the later members with no scope). fn declared_at(session: &Session, path: &str, needle: &str) -> String { let path = std::path::Path::new(path); let view = session.view(path).expect("the file has a view"); @@ -49,13 +55,16 @@ fn declared_at(session: &Session, path: &str, needle: &str) -> Stri let reading = view .reading_offset_of(FileOffset::new(at)) .expect("the file offset is in the reading"); - let Some(name) = session.the_name_declared_at(&view, reading.get()) else { + let Known::Yes(binding) = + cpp_code_analysis::sema::resolve::definition_at(&view.scopes, &view.root, reading.get()) + else { return "no name".to_string(); }; + let name = binding.name.text(); match session.definition(&view, ReadingOffset::new(reading.get())) { - Known::Yes(found) => match &found.fact.scope { - Some(scope) => format!("{scope}::{name}"), - None => format!("(none)::{name}"), + Known::Yes(_) => match view.scopes.qualified_name_of(binding.scope) { + Some(scope) if !scope.is_empty() => format!("{scope}::{name}"), + _ => format!("(none)::{name}"), }, Known::Unknown(reason) => format!("unknown: {reason:?}"), Known::No => "no".to_string(), diff --git a/crates/cpp_code_analysis/tests/suite/completion.rs b/crates/cpp_code_analysis/tests/suite/completion.rs index 1cf1813a..55891526 100644 --- a/crates/cpp_code_analysis/tests/suite/completion.rs +++ b/crates/cpp_code_analysis/tests/suite/completion.rs @@ -110,7 +110,7 @@ fn offered_at(offset: usize) -> Option> { found .names .iter() - .map(|offered| offered.fact.name.to_string()) + .map(|offered| session.index().offered_name(offered).to_string()) .collect(), ), _ => None, @@ -165,7 +165,7 @@ fn a_local_is_offered_while_it_is_being_typed() { let local = found .names .iter() - .find(|offered| offered.fact.name == "local_variable") + .find(|offered| session.index().offered_name(offered) == "local_variable") .expect("the local is offered"); assert_eq!(local.depth, 0, "from the scope the cursor is in"); } @@ -224,7 +224,7 @@ fn a_member_position_is_not_a_name_position() { .members .members .iter() - .any(|member| member.fact.name == "size"), + .any(|member| session.index().member_name(member) == "size"), "with the members of the object's type" ); } @@ -298,7 +298,7 @@ void Widget::grow(int by) { .members .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(), other => panic!("the member query must answer here: {other:?}"), }; @@ -359,11 +359,11 @@ fn a_header_s_macro_ranks_after_a_keyword_and_names_its_own_file() { let macro_name = offered .names .iter() - .find(|name| name.fact.name == "FROM_THE_HEADER") + .find(|name| session.index().offered_name(name) == "FROM_THE_HEADER") .expect("the header's macro is offered"); assert_eq!( - macro_name.file, - std::path::PathBuf::from("/p/h.h"), + session.index().offered_path(macro_name), + Some(std::path::Path::new("/p/h.h")), "a macro's identity is the file that wrote it, or the item resolves against a stranger" ); } @@ -521,7 +521,7 @@ int f() { Known::Yes(found) => found .names .iter() - .map(|offered| offered.fact.name.to_string()) + .map(|offered| session.index().offered_name(offered).to_string()) .collect::>(), other => panic!("a blank cursor in a body is answerable: {other:?}"), }; @@ -549,7 +549,7 @@ int f() { .members .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!(names.contains(&"size"), "the ordinary member: {names:?}"); assert!( @@ -655,8 +655,8 @@ fn the_nearest_declaration_comes_first() { Known::Yes(found) => found .names .iter() - .filter(|name| name.fact.name.starts_with("from_")) - .map(|name| format!("{}: {:?}", name.fact.name, name.from)) + .filter(|name| session.index().offered_name(name).starts_with("from_")) + .map(|name| format!("{}: {:?}", session.index().offered_name(name), name.from)) .collect(), other => panic!("{other:?}"), }; @@ -706,7 +706,7 @@ fn a_blank_line_in_a_body_offers_the_keywords_and_the_snippets() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -1605,7 +1605,7 @@ fn a_constructors_parameters_are_in_scope() { Known::Yes(found) => found .names .iter() - .map(|offered| offered.fact.name.to_string()) + .map(|offered| session.index().offered_name(offered).to_string()) .collect::>(), other => panic!("{what} should be answerable, got {other:?}"), }; @@ -1720,7 +1720,7 @@ fn a_macro_is_not_shown_with_a_signature() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -1731,13 +1731,17 @@ fn a_macro_is_not_shown_with_a_signature() { .iter() .find(|item| item.label == "FULL_NAME_FORMAT") .expect("the macro is offered"); + let returns = item + .fact + .as_ref() + .and_then(|fact| session.index().returns_spelling_of(fact)); println!( "item: kind={:?} detail={:?} fact={:?}", item.kind, item.detail, item.fact .as_ref() - .map(|fact| (&fact.kind, &fact.returns, fact.parameter_list())) + .map(|fact| (&fact.kind, &returns, fact.parameter_list())) ); assert_eq!( item.detail, @@ -1745,7 +1749,7 @@ fn a_macro_is_not_shown_with_a_signature() { "a macro has no returns and no parameters: {:?}", item.fact .as_ref() - .map(|fact| (&fact.kind, &fact.returns, fact.parameter_list())) + .map(|fact| (&fact.kind, &returns, fact.parameter_list())) ); // **And its identity is the macro's own position.** The item a client resolves is a `(file, offset)` pair taken @@ -1815,7 +1819,7 @@ fn the_typed_prefix_is_the_word_being_replaced() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -1873,7 +1877,7 @@ fn a_statement_position_prefix_is_read_too() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -1934,7 +1938,7 @@ int main() "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2010,7 +2014,7 @@ struct Widget { int size; }; "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2044,7 +2048,7 @@ struct Widget { int size; }; "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2094,7 +2098,7 @@ fn a_macro_body_offers_its_own_parameters() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2171,7 +2175,7 @@ int neither; "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2193,7 +2197,7 @@ int neither; "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2260,7 +2264,7 @@ int f() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2343,7 +2347,7 @@ fn a_member_is_completed_in_a_separated_definition() { "members_of(Source) → {:?}", list.members .iter() - .map(|m| m.fact.name.to_string()) + .map(|m| session.index().member_name(m).to_string()) .collect::>() ), other => println!("members_of(Source) → {other:?}"), @@ -2891,7 +2895,7 @@ int f() { // And the member list of the bare spelling is the class's, not an empty one. let listed = session.members_of(&view, "shared_ptr"); assert!( - matches!(&listed, Known::Yes(list) if list.members.iter().any(|member| member.fact.name == "element_type")), + matches!(&listed, Known::Yes(list) if list.members.iter().any(|member| session.index().member_name(member) == "element_type")), "the bare spelling names the class: {listed:?}" ); } diff --git a/crates/cpp_code_analysis/tests/suite/conditional_environment.rs b/crates/cpp_code_analysis/tests/suite/conditional_environment.rs index baa6da9f..773546b9 100644 --- a/crates/cpp_code_analysis/tests/suite/conditional_environment.rs +++ b/crates/cpp_code_analysis/tests/suite/conditional_environment.rs @@ -101,7 +101,7 @@ fn a_definition_inside_an_if_reaches_the_rendering() { .find(|fact| fact.qualified_name() == "Widget::first") .expect("the fact"); assert_eq!( - first.type_of.as_deref(), + session.index().type_spelling_of(first).as_deref(), Some("int"), "the type is the one the taken branch wrote" ); diff --git a/crates/cpp_code_analysis/tests/suite/definition.rs b/crates/cpp_code_analysis/tests/suite/definition.rs index c1d37af9..95377921 100644 --- a/crates/cpp_code_analysis/tests/suite/definition.rs +++ b/crates/cpp_code_analysis/tests/suite/definition.rs @@ -200,11 +200,16 @@ fn a_c_enumerator_from_an_included_header_is_visible() { .expect("the name is in the rendering"); match session.definition(&view, reading) { Known::Yes(found) => { - assert_eq!(found.fact.name, "EVENT_BUFADD"); + let fact = session + .definition_fact(&found) + .expect("the answer resolves through the index"); + let file = session + .definition_path(&found) + .expect("the answer names a file the index holds"); + assert_eq!(fact.name, "EVENT_BUFADD"); assert!( - found.file.ends_with("events.h"), - "the enumerator's declaration is the header's: {:?}", - found.file + file.ends_with("events.h"), + "the enumerator's declaration is the header's: {file:?}" ); } other => panic!("the enumerator was not found: {other:?}"), diff --git a/crates/cpp_code_analysis/tests/suite/generics.rs b/crates/cpp_code_analysis/tests/suite/generics.rs index 162c5aed..5d5ff13c 100644 --- a/crates/cpp_code_analysis/tests/suite/generics.rs +++ b/crates/cpp_code_analysis/tests/suite/generics.rs @@ -51,7 +51,7 @@ fn members_after(source: &str, marker: &str) -> Vec { .members .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(), _ => Vec::new(), } @@ -168,10 +168,10 @@ fn an_instantiated_member_list_records_the_arguments() { let push_back = list .members .iter() - .find(|member| member.fact.name == "push_back") + .find(|member| session.index().member_name(member) == "push_back") .expect("the member is on the class"); assert_eq!( - push_back.fact.parameter_list(), + session.index().member_parameter_list(push_back).as_deref(), Some("(int value)"), "the class's parameter is substituted with the use's argument" ); @@ -179,14 +179,13 @@ fn an_instantiated_member_list_records_the_arguments() { let front = list .members .iter() - .find(|member| member.fact.name == "front") + .find(|member| session.index().member_name(member) == "front") .expect("the member is on the class"); // The substituted spelling keeps the class's own spacing (`int &`), which is the same type. assert_eq!( - front - .fact - .returns - .as_deref() + session + .index() + .member_returns_spelling(front) .map(|written| written.replace(' ', "")), Some("int&".to_string()) ); diff --git a/crates/cpp_code_analysis/tests/suite/header_context.rs b/crates/cpp_code_analysis/tests/suite/header_context.rs index 6470ef86..5f907cd6 100644 --- a/crates/cpp_code_analysis/tests/suite/header_context.rs +++ b/crates/cpp_code_analysis/tests/suite/header_context.rs @@ -84,9 +84,12 @@ fn a_declaration_a_macro_unlocks_in_a_header_is_visible_from_the_unit_that_inclu let Known::Yes(found) = &found else { panic!("`dollar_vcol` is declared in `globals.h`: {found:?}"); }; - assert_eq!(found.fact.name.as_str(), "dollar_vcol"); + let fact = session + .definition_fact(found) + .expect("the answer resolves through the index"); + assert_eq!(fact.name.as_str(), "dollar_vcol"); assert_eq!( - found.fact.type_of.as_deref(), + session.index().type_spelling_of(fact).as_deref(), Some("colnr_T"), "the type the header writes" ); diff --git a/crates/cpp_code_analysis/tests/suite/layout.rs b/crates/cpp_code_analysis/tests/suite/layout.rs index 6679dff9..79597b17 100644 --- a/crates/cpp_code_analysis/tests/suite/layout.rs +++ b/crates/cpp_code_analysis/tests/suite/layout.rs @@ -1,10 +1,12 @@ //! **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::index::types::{ArrayExtent, ComputedType}; use cpp_code_analysis::sema; use cpp_code_analysis::{ CompilerConfig, Known, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter, }; +use std::sync::Arc; /// The layout of `name` in a one-file fixture. fn layout(source: &str, name: &str) -> sema::layout::ClassLayout { @@ -21,10 +23,7 @@ fn layout(source: &str, name: &str) -> sema::layout::ClassLayout { 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 - } + Known::Yes(layout) => layout, other => panic!("`{name}` has no layout: {other:?}"), } } @@ -64,6 +63,27 @@ struct Widget { ); } +/// **An enumeration is its underlying integer**, not a class over its enumerators. `std::errc` has 78 enumerators, +/// every one a `Variable` fact; the class-layout walk tried to size each and answered "not computed" listing them all. +/// The enum itself is four bytes, and the enumerators are not data members. +#[test] +fn an_enumeration_is_sized_as_its_underlying_integer() { + let layout = layout( + "\ +enum class Error { + first, + second = 4, + third, +}; +", + "Error", + ); + assert_eq!(layout.size, 4); + assert_eq!(layout.alignment, 4); + assert!(layout.fields.is_empty()); + assert!(layout.unknown.is_empty()); +} + /// **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() { @@ -550,6 +570,65 @@ struct Path { assert_eq!(layout.alignment, 4); } +/// **A member's array dimension is sized from the type, not from the declaration's spelling.** +/// +/// The declaration reader keeps a named bound (`ArrayExtent::Written("COUNT")`) instead of collapsing it to the +/// flexible array's "no extent", so the fact itself says `Point points[COUNT]` and layout evaluates `COUNT` where the +/// declaration stands. Before this, the dimension survived only by reassembling `Point points[COUNT]` out of the +/// file's tree at request time. +#[test] +fn an_array_member_is_sized_from_its_structural_extent() { + let source = "\ +enum { COUNT = 3 }; +struct Point { int x; int y; }; +struct Path { + Point points[COUNT]; +}; +"; + 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"); + + // **The fact carries the dimension**, as the declaration wrote it. + let Known::Yes(list) = session.members_of(&view, "Path") else { + panic!("`Path` has members"); + }; + let points = list + .members + .iter() + .find(|member| session.index().member_name(member) == "points") + .expect("the `points` member"); + let type_of = session + .index() + .member_computed_type(points) + .expect("the member's structural type"); + assert_eq!( + type_of, + ComputedType::Array { + of: Arc::new(ComputedType::named("Point", Vec::new())), + extent: ArrayExtent::written("COUNT"), + } + ); + + // **And layout sizes it through that extent**: the enumerator is 3, `Point` is 8, so the member is 24. + let Known::Yes(layout) = session.the_layout_of(&view, "Path") else { + panic!("`Path` has a layout"); + }; + assert_eq!(layout.fields[0].offset, 0); + assert_eq!(layout.fields[0].size, 24); + assert_eq!(layout.size, 24); + assert_eq!(layout.alignment, 4); +} + /// **A macro dimension may be a constant expression**, not only a literal: neovim's `NMARKS` is /// `('z' - 'a' + 1)`. #[test] diff --git a/crates/cpp_code_analysis/tests/suite/macro_member_types.rs b/crates/cpp_code_analysis/tests/suite/macro_member_types.rs index 3a655b8b..53755fe2 100644 --- a/crates/cpp_code_analysis/tests/suite/macro_member_types.rs +++ b/crates/cpp_code_analysis/tests/suite/macro_member_types.rs @@ -79,7 +79,9 @@ fn a_member_of_a_macro_call_types_through_the_rendering() { let pointer = the_type_at_the_end_of(&session, "->p"); match pointer { - Known::Yes(found) => assert_eq!(found.type_of, "Proto*", "{}", found.expression), + // The member is declared `struct Proto *p`, so the tag is part of the type the chain answers; the pointee is + // still the record `Proto`, which is what the member lookup above follows. + Known::Yes(found) => assert_eq!(found.type_of, "struct Proto*", "{}", found.expression), other => panic!("`ci_func(ci)->p` types: {other:?}"), } } diff --git a/crates/cpp_code_analysis/tests/suite/macros.rs b/crates/cpp_code_analysis/tests/suite/macros.rs index 966baec4..9730d15b 100644 --- a/crates/cpp_code_analysis/tests/suite/macros.rs +++ b/crates/cpp_code_analysis/tests/suite/macros.rs @@ -57,8 +57,8 @@ fn session() -> (Session, std::path::PathBuf) { /// function-like macro that is **not called** survives the cook — `an_uncalled_function_like_macro_survives_the_cook` asserts /// that). What is missing is the **vocabulary**: `name_completions_at` collects the visible declarations from the index and /// never asks the file's own summary for its `macros`. The fix is one append — `summary.macros` as `OfferedName`s (the struct -/// is `file`, `fact: DeclFact`, `depth`, and a distance) — and it belongs in `name_completions_at`, where both `index` and -/// `path` are in hand. +/// is `file: FileId`, `fact: FactRef`, `depth`, and a distance) — and it belongs in `name_completions_at`, where both `index` +/// and `path` are in hand. #[test] fn a_macro_is_offered_by_completion() { let (session, path) = session(); diff --git a/crates/cpp_code_analysis/tests/suite/modifiers.rs b/crates/cpp_code_analysis/tests/suite/modifiers.rs index 7eb88f75..b4f369cb 100644 --- a/crates/cpp_code_analysis/tests/suite/modifiers.rs +++ b/crates/cpp_code_analysis/tests/suite/modifiers.rs @@ -74,17 +74,41 @@ constexpr int constant() { return 2; } constinit int at_start = 3; static void once() {} inline void often() {} -void log(const char* format, ...); "; assert!(modifiers_of(source, "immediate", None).contains(DeclModifiers::CONSTEVAL)); assert!(modifiers_of(source, "constant", None).contains(DeclModifiers::CONSTEXPR)); assert!(modifiers_of(source, "at_start", None).contains(DeclModifiers::CONSTINIT)); assert!(modifiers_of(source, "once", None).contains(DeclModifiers::STATIC)); assert!(modifiers_of(source, "often", None).contains(DeclModifiers::INLINE)); +} + +/// **A variadic parameter list is a fact bit, not a modifier.** +/// +/// The token walk that fills [`DeclModifiers`] once treated the list's `...` as a written modifier. It is not one: +/// `...` is a token of the **parameter list**, and a list may be variadic with no parameter at all (`void f(...)`), +/// which is why the answer is [`DeclFact::variadic_parameters`] — read from the declaration's `CppParamList` — and +/// the retired modifier bit is not set. See `sema::declarations::a_variadic_list_is_a_bit_on_the_fact` for the four +/// shapes and `index::params` for why a pack is a parameter's flag instead. +#[test] +fn a_variadic_list_is_a_fact_bit() { + let source = "\ +void log(const char* format, ...); +void fixed(int value); +"; + let facts = facts_of(source); + let log = facts + .iter() + .find(|fact| fact.name == "log") + .expect("the function"); assert!( - modifiers_of(source, "log", None).contains(DeclModifiers::VARIADIC), - "a parameter list that ends in `...` is variadic" + log.variadic_parameters, + "the declaration's list writes `...`" ); + let fixed = facts + .iter() + .find(|fact| fact.name == "fixed") + .expect("the other function"); + assert!(!fixed.variadic_parameters, "and an ordinary list does not"); } /// **`= delete` is a modifier of the declaration, and it is written after the declarator.** diff --git a/crates/cpp_code_analysis/tests/suite/modules.rs b/crates/cpp_code_analysis/tests/suite/modules.rs index 6f744e2c..766fade3 100644 --- a/crates/cpp_code_analysis/tests/suite/modules.rs +++ b/crates/cpp_code_analysis/tests/suite/modules.rs @@ -2170,7 +2170,7 @@ fn a_module_unit_is_read_as_a_translation_unit() { /// imports the module and uses what the partitions export. #[test] fn a_partition_named_with_an_underscore_is_found_and_its_names_are_visible() { - use cpp_code_analysis::{Known, OpenDocuments, Session, SessionFiles, WatchFilter}; + use cpp_code_analysis::{OpenDocuments, Session, SessionFiles, WatchFilter}; let files = MemoryFiles::new() .with_file( @@ -2210,12 +2210,18 @@ fn a_partition_named_with_an_underscore_is_found_and_its_names_are_visible() { let use_file = Path::new("src/use.cpp"); let rect = session.index().definition("Rect", use_file); assert!( - matches!(rect, Known::Yes(ref found) if found.file.ends_with("geometry_shapes.cppm")), + rect.clone() + .value() + .and_then(|found| session.definition_path(&found)) + .is_some_and(|path| path.ends_with("geometry_shapes.cppm")), "`Rect` comes from the `:shapes` partition: {rect:?}" ); let area = session.index().definition("rect_area", use_file); assert!( - matches!(area, Known::Yes(ref found) if found.file.ends_with("geometry_area.cppm")), + area.clone() + .value() + .and_then(|found| session.definition_path(&found)) + .is_some_and(|path| path.ends_with("geometry_area.cppm")), "`rect_area` comes from the `:area` partition: {area:?}" ); diff --git a/crates/cpp_code_analysis/tests/suite/out_of_class_members.rs b/crates/cpp_code_analysis/tests/suite/out_of_class_members.rs index d22eccf5..127704ca 100644 --- a/crates/cpp_code_analysis/tests/suite/out_of_class_members.rs +++ b/crates/cpp_code_analysis/tests/suite/out_of_class_members.rs @@ -47,10 +47,15 @@ fn where_at(session: &Session, path: &str, needle: &str) -> String .reading_offset_of(FileOffset::new(at)) .expect("the file offset is in the reading"); match session.definition(&view, ReadingOffset::new(reading.get())) { - Known::Yes(found) => match &found.fact.scope { - Some(scope) => format!("{scope}::{}", found.fact.name), - None => found.fact.name.to_string(), - }, + Known::Yes(found) => { + let Some(fact) = session.definition_fact(&found) else { + return "unknown: the answer does not resolve".to_string(); + }; + match &fact.scope { + Some(scope) => format!("{scope}::{}", fact.name), + None => fact.name.to_string(), + } + } Known::Unknown(reason) => format!("unknown: {reason:?}"), Known::No => "no".to_string(), } diff --git a/crates/cpp_code_analysis/tests/suite/rendered_reading.rs b/crates/cpp_code_analysis/tests/suite/rendered_reading.rs index a707557a..ba5b587b 100644 --- a/crates/cpp_code_analysis/tests/suite/rendered_reading.rs +++ b/crates/cpp_code_analysis/tests/suite/rendered_reading.rs @@ -99,11 +99,16 @@ fn where_at(session: &Session, path: &str, needle: &str) -> String return "no needle".to_string(); }; match session.definition(&view, ReadingOffset::new(at)) { - Known::Yes(found) => format!( - "{}::{}", - found.fact.scope.as_deref().unwrap_or("(none)"), - found.fact.name - ), + Known::Yes(found) => { + let fact = session + .definition_fact(&found) + .unwrap_or_else(|| panic!("the answer resolves through the index: {found:?}")); + format!( + "{}::{}", + fact.scope.as_deref().unwrap_or("(none)"), + fact.name + ) + } Known::Unknown(reason) => format!("unknown: {reason:?}"), Known::No => "no".to_string(), } diff --git a/crates/cpp_code_analysis/tests/suite/reported_defects.rs b/crates/cpp_code_analysis/tests/suite/reported_defects.rs index 00149e50..7de695da 100644 --- a/crates/cpp_code_analysis/tests/suite/reported_defects.rs +++ b/crates/cpp_code_analysis/tests/suite/reported_defects.rs @@ -44,12 +44,12 @@ fn session_with(files: &[(&str, &str)]) -> Session { session } -fn parameters_of<'a>(summary: &'a FileSummary, name: &str) -> Option<&'a [String]> { +fn parameters_of(summary: &FileSummary, name: &str) -> Option> { summary .declarations .iter() .find(|fact| fact.name == name) - .map(|fact| fact.parameters()) + .map(|fact| fact.parameters().iter().map(ToString::to_string).collect()) } /// **§B1 — a template parameter list is names, not the keywords that introduce them.** @@ -75,17 +75,17 @@ fn a_template_parameter_is_a_name_and_an_unnamed_one_is_a_slot() { assert_eq!( parameters_of(summary, "S"), - Some(&["A".to_string(), "B".to_string(), "N".to_string()][..]), + Some(vec!["A".to_string(), "B".to_string(), "N".to_string()]), "a named parameter answers its name" ); assert_eq!( parameters_of(summary, "an_unnamed_one"), - Some(&[String::new(), String::new()][..]), + Some(vec![String::new(), String::new()]), "two slots, and no keyword pretending to be a name" ); assert_eq!( parameters_of(summary, "partial"), - Some(&[String::new(), "T".to_string()][..]), + Some(vec![String::new(), "T".to_string()]), "the second slot keeps its name **and its position**" ); } @@ -105,20 +105,30 @@ fn an_anonymous_structs_variable_is_not_a_void() { .index() .summary(std::path::Path::new("/p/a.cpp")) .expect("indexed"); - let facts: Vec<(&str, Option<&str>)> = summary + let index = session.index(); + let facts: Vec<(&str, Option)> = summary .declarations .iter() .filter(|fact| fact.name == "priority" || fact.name == "left" || fact.name == "right") - .map(|fact| (&*fact.name, fact.type_of.as_deref())) + .map(|fact| { + ( + &*fact.name, + index + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()), + ) + }) .collect(); println!("facts: {facts:?}"); assert!( - !facts.iter().any(|(_, type_of)| *type_of == Some("void")), + !facts + .iter() + .any(|(_, type_of)| type_of.as_deref() == Some("void")), "nothing here is a `void`: {facts:?}" ); assert!( - facts.contains(&("left", Some("unsigned char"))), + facts.contains(&("left", Some("unsigned char".to_string()))), "and the members keep their own types: {facts:?}" ); } @@ -146,7 +156,7 @@ fn a_template_id_keeps_the_spelling_that_was_written() { .expect("the variable is a fact"); assert_eq!( - table.type_of.as_deref(), + session.index().type_spelling_of(table).as_deref(), Some("std::map"), "the type the file wrote" ); @@ -187,19 +197,20 @@ fn an_alias_of_a_qualified_type_is_not_a_void() { .iter() .find(|fact| fact.name == "reference" && fact.scope.as_deref() == Some("V")) .expect("the alias is a fact"); - println!("V::reference type_of {:?}", alias.type_of); + let wrote = session + .index() + .type_spelling_of(alias) + .map(|spelled| spelled.to_string()); + println!("V::reference type_of {wrote:?}"); assert!( - alias.type_of.as_deref() != Some("void"), - "an alias's type is never `void`: {:?}", - alias.type_of + wrote.as_deref() != Some("void"), + "an alias's type is never `void`: {wrote:?}" ); assert!( - alias - .type_of + wrote .as_deref() .is_some_and(|written| written.contains("Base::reference")), - "the type the typedef wrote: {:?}", - alias.type_of + "the type the typedef wrote: {wrote:?}" ); } @@ -353,8 +364,8 @@ fn a_member_function_records_its_qualifiers_and_its_requires_clause() { assert_eq!( foo.members .iter() - .filter(|member| member.fact.name == "call") - .filter(|member| is_const(&member.fact)) + .filter(|member| session.index().member_name(member) == "call") + .filter(|member| session.index().member_fact(member).is_some_and(is_const)) .count(), 1, "one const `call` in Foo's member list" @@ -365,10 +376,14 @@ fn a_member_function_records_its_qualifiers_and_its_requires_clause() { for member in bar .members .iter() - .filter(|member| member.fact.name == "call") + .filter(|member| session.index().member_name(member) == "call") { + let fact = session + .index() + .member_fact(member) + .expect("the row names a declaration the index holds"); assert_eq!( - member.fact.requires_clause(), + fact.requires_clause(), Some("requires requires { fn(*this); }"), "the member list's facts carry the clause too" ); @@ -592,12 +607,12 @@ fn a_member_of_a_template_base_is_substituted_with_the_base_arguments() { let member = listed .members .iter() - .find(|member| member.fact.name == "shared_from_this") + .find(|member| session.index().member_name(member) == "shared_from_this") .expect("the member comes through the base walk"); assert_eq!( - member.fact.returns.as_deref(), - Some("Node *"), - "the base's `T` is the class it was instantiated with: {member:?}" + session.index().member_returns_spelling(member).as_deref(), + Some("Node*"), + "the base's `T` is the class it was instantiated with (canonical display): {member:?}" ); assert_eq!( member.declared_in, "std::enable_shared_from_this", @@ -787,8 +802,11 @@ fn a_returned_local_states_its_type() { .definition("make", path) .value() .unwrap_or_else(|| panic!("`make` is in the index")); + let fact = session + .definition_fact(&known) + .expect("the answer resolves through the index"); assert_eq!( - known.fact.returns.as_deref(), + session.index().returns_spelling_of(fact).as_deref(), Some("std::vector"), "the local's declaration states the type the function returns" ); @@ -835,7 +853,10 @@ fn a_qualified_name_is_resolved_through_a_namespace_alias() { panic!("the alias names a declaration: {known:?}"); }; assert_eq!( - found.fact.qualified_name(), + session + .definition_fact(&found) + .expect("the answer resolves through the index") + .qualified_name(), "std::ranges::views::filter", "the answer is the target's declaration, under the scope that actually declares it" ); @@ -867,7 +888,7 @@ fn a_qualified_name_is_resolved_through_a_namespace_alias() { listed .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect::>(), ["arity"], "the member is looked for in the scope that declares it" @@ -1069,7 +1090,7 @@ struct Hashed { ); assert_eq!(operator.scope.as_deref(), Some("Hashed")); assert_eq!( - operator.returns.as_deref(), + session.index().returns_spelling_of(operator).as_deref(), Some("std::size_t"), "and the return type is the return type" ); diff --git a/crates/cpp_code_analysis/tests/suite/scopes.rs b/crates/cpp_code_analysis/tests/suite/scopes.rs index d66bee29..ce744c3c 100644 --- a/crates/cpp_code_analysis/tests/suite/scopes.rs +++ b/crates/cpp_code_analysis/tests/suite/scopes.rs @@ -1428,8 +1428,12 @@ fn a_scope_a_macro_body_opens_holds_the_declarations_behind_it() { .definition("std::vector", std::path::Path::new("/p/main.cpp")) { Known::Yes(found) => { - assert_eq!(found.fact.name, "vector"); - assert_eq!(found.fact.qualified_name(), "std::vector"); + let fact = store + .index() + .definition_fact(&found) + .expect("the answer resolves through the index"); + assert_eq!(fact.name, "vector"); + assert_eq!(fact.qualified_name(), "std::vector"); } other => panic!("`std::vector` must resolve through the scope a body opened: {other:?}"), } @@ -1635,7 +1639,14 @@ fn a_function_behind_an_export_macro_is_in_the_namespace_the_macro_opened() { .index() .definition("std::format", std::path::Path::new("/q/main.cpp")) { - Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "std::format"), + Known::Yes(found) => assert_eq!( + store + .index() + .definition_fact(&found) + .expect("the answer resolves through the index") + .qualified_name(), + "std::format" + ), other => { panic!("`std::format` must resolve for the same reason `std::vector` does: {other:?}") } @@ -1812,7 +1823,13 @@ fn a_member_of_an_aliased_class_resolves_through_the_alias() { ); match index.definition("std::string::size_type", main) { - Known::Yes(found) => assert_eq!(found.fact.name, "size_type"), + Known::Yes(found) => assert_eq!( + index + .definition_fact(&found) + .expect("the answer resolves through the index") + .name, + "size_type" + ), other => panic!("a member spelled through an alias must resolve through it: {other:?}"), } diff --git a/crates/cpp_code_analysis/tests/suite/semantic.rs b/crates/cpp_code_analysis/tests/suite/semantic.rs index 6664f6b6..033158ad 100644 --- a/crates/cpp_code_analysis/tests/suite/semantic.rs +++ b/crates/cpp_code_analysis/tests/suite/semantic.rs @@ -453,7 +453,13 @@ fn a_written_type_resolves_a_member_the_class_inherits() { let view = session.view("/p/a.cpp").expect("the file is held"); match session.definition_of_a_written_type(&view, "std::allocator_traits::pointer", None, 0) { - Known::Yes(found) => assert_eq!(found.fact.name, "pointer"), + Known::Yes(found) => assert_eq!( + session + .definition_fact(&found) + .expect("the answer resolves through the index") + .name, + "pointer" + ), other => panic!( "`pointer` is inherited from `_Normal` and has to be found through it: {other:?}" ), @@ -498,7 +504,13 @@ fn a_local_type_is_looked_up_from_the_namespace_around_it() { let at = "namespace app {\nstruct Widget { int size; };\nvoid f() { ".len(); match session.definition_of_a_written_type(&view, "Widget", None, at) { - Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"), + Known::Yes(found) => assert_eq!( + session + .definition_fact(&found) + .expect("the answer resolves through the index") + .qualified_name(), + "app::Widget" + ), other => panic!("a local `Widget` in `namespace app` names `app::Widget`: {other:?}"), } @@ -599,7 +611,13 @@ fn a_local_fact_carries_a_namespace_the_file_only_opens_with_a_macro() { local.in_namespace(), local.range.start_offset, ) { - Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "app::Widget"), + Known::Yes(found) => assert_eq!( + session + .definition_fact(&found) + .expect("the answer resolves through the index") + .qualified_name(), + "app::Widget" + ), other => panic!("`Widget` written in `app` names `app::Widget`: {other:?}"), } } @@ -997,7 +1015,10 @@ fn a_template_parameter_takes_the_type_of_the_argument() { let deduced = |name: &str| -> String { let fact = facts .iter() - .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == name + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes")); let offset = fact.name_range.start_offset; match session.type_at(&view, file::coordinates::ReadingOffset::new(offset)) { @@ -1049,13 +1070,16 @@ fn an_auto_is_deduced_from_its_initializer() { let deduced = |name: &str| -> String { let fact = facts .iter() - .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == name + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .unwrap_or_else(|| { panic!( "`{name}` is declared `auto`: {:?}", facts .iter() - .map(|f| (&f.name, &f.type_of)) + .map(|f| (&f.name, session.index().type_spelling_of(f))) .collect::>() ) }); @@ -1096,7 +1120,10 @@ fn an_auto_is_deduced_from_its_initializer() { let name = "no_initializer"; let fact = facts .iter() - .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == name + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .unwrap_or_else(|| panic!("`{name}` is declared `auto`")); assert!( @@ -1301,13 +1328,16 @@ fn an_auto_written_through_a_macro_is_still_deduced() { ] { let fact = facts .iter() - .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == name + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .unwrap_or_else(|| { panic!( "`{name}` is declared `auto`: {:?}", facts .iter() - .map(|fact| (&fact.name, &fact.type_of)) + .map(|fact| (&fact.name, session.index().type_spelling_of(fact))) .collect::>() ) }); @@ -1469,10 +1499,8 @@ fn a_function_with_no_written_return_type_states_one_in_its_body() { .summaries() .flat_map(|summary| summary.declarations.iter()) .find(|fact| fact.name == name) - .unwrap_or_else(|| panic!("`{name}` is declared")) - .returns - .as_deref() - .map(str::to_string) + .and_then(|fact| session.index().returns_spelling_of(fact)) + .map(|spelled| spelled.to_string()) }; assert_eq!( @@ -1550,7 +1578,10 @@ fn a_conditional_has_the_type_its_arms_agree_on() { let deduced = |name: &str| -> String { let fact = facts .iter() - .find(|fact| fact.name == name && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == name + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .unwrap_or_else(|| panic!("`{name}` is an `auto` the file writes")); match session.type_at( &view, @@ -1566,7 +1597,10 @@ fn a_conditional_has_the_type_its_arms_agree_on() { let mixed = facts .iter() - .find(|fact| fact.name == "from_mixed" && fact.type_of.as_deref() == Some("auto")) + .find(|fact| { + fact.name == "from_mixed" + && session.index().type_spelling_of(fact).as_deref() == Some("auto") + }) .expect("`from_mixed` is an `auto` the file writes"); assert!( !matches!( @@ -1809,7 +1843,12 @@ fn a_template_parameter_is_not_a_declaration_at_file_scope() { found .found .iter() - .map(|entry| entry.fact.qualified_name()) + .map(|entry| { + session + .definition_fact(entry) + .expect("the answer resolves through the index") + .qualified_name() + }) .collect::>() ), Known::No => panic!("`definitions` answers `Known`, not `No`"), @@ -1987,23 +2026,31 @@ fn a_return_type_a_directive_splits_is_the_branch_this_compilation_takes() { .index() .cooked_reading(std::path::Path::new("/p/a.cpp")) .expect("the file was read in its program"); - let found: Vec<(&str, Option<&str>)> = cooked + let found: Vec<(&str, Option)> = cooked .declarations .iter() .filter(|fact| matches!(fact.kind, DeclKind::Function)) - .map(|fact| (&*fact.name, fact.returns.as_deref())) + .map(|fact| { + ( + &*fact.name, + session + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()), + ) + }) .collect(); println!("returns: {found:?}"); assert!( found .iter() - .any(|(name, returns)| *name == "make" && *returns == Some("void")), + .any(|(name, returns)| *name == "make" && returns.as_deref() == Some("void")), "the `#else` branch is the one this configuration compiles, and one answer is named: {found:?}" ); assert!( found .iter() - .any(|(name, returns)| *name == "plain" && *returns == Some("int")), + .any(|(name, returns)| *name == "plain" && returns.as_deref() == Some("int")), "and an unsplit one keeps its type: {found:?}" ); } @@ -2238,7 +2285,7 @@ void f() { .find(|fact| fact.name == "lock" && fact.kind == DeclKind::Variable) .unwrap_or_else(|| panic!("`lock` is a variable: {:?}", summary.declarations)); assert_eq!( - declared.type_of.as_deref(), + session.index().type_spelling_of(declared).as_deref(), Some("std::unique_lock"), "the initialiser is not part of the type" ); diff --git a/crates/cpp_code_analysis/tests/suite/signature.rs b/crates/cpp_code_analysis/tests/suite/signature.rs index df4c2413..602a34ff 100644 --- a/crates/cpp_code_analysis/tests/suite/signature.rs +++ b/crates/cpp_code_analysis/tests/suite/signature.rs @@ -190,6 +190,56 @@ void g() { "a string literal selects the `const char*` overload: {label:?}" ); } + +/// **A variadic overload is labelled with its `...` and ranked as one.** +/// +/// The label is built from the list's parameter nodes, and the list-level `...` is a **token of the list** rather than +/// one of them — so before the bit was stored this signature printed `print(int value)` for a declaration that accepts +/// any number of arguments, and the ranking (which read the marker off the label's suffix) treated it as fixed-arity: +/// `print(1, 2)` had no viable candidate and the popup kept the wrong overload first. The two assertions are the two +/// halves of that: the label says `...`, and the overload with it is the one the call's two arguments select. +#[test] +fn a_variadic_overload_is_labelled_and_ranked_as_one() { + let source = "\ +void print(int value); +void print(int value, ...); +void g() { + print(1, |2); +} +"; + let (_, signature) = signature_where_marked(source); + let label = signature + .map(|signature| signature.label) + .unwrap_or_default(); + assert!( + label.contains("..."), + "the list's own `...` is part of the display label: {label:?}" + ); + assert!( + label.starts_with("print(int value, ...)"), + "and the variadic overload is the one two arguments select: {label:?}" + ); +} + +/// **A list that is variadic with no parameter at all still has a label** — `void ping(...)`. +/// +/// This is the shape the stored bit exists for rather than a parameter fact: there is no `CppParam` to render and no +/// `ParamsId` entry to name, so a label built only from parameters printed `ping()` and a ranking built only from +/// parameters saw a zero-argument callee. The call below passes one argument and is legal. +#[test] +fn a_variadic_list_with_no_parameters_is_labelled() { + let source = "\ +void ping(...); +void g() { + ping(|1); +} +"; + let (_, signature) = signature_where_marked(source); + let label = signature + .map(|signature| signature.label) + .unwrap_or_default(); + assert_eq!(label, "ping(...)", "the whole label"); +} /// **A template candidate is ranked as the function the call instantiates.** /// /// The distinguishing fixture: two templates whose declared spellings (`T*` and `T`) say nothing diff --git a/crates/cpp_code_analysis/tests/suite/subscript_overloads.rs b/crates/cpp_code_analysis/tests/suite/subscript_overloads.rs index 194d0e09..8284f967 100644 --- a/crates/cpp_code_analysis/tests/suite/subscript_overloads.rs +++ b/crates/cpp_code_analysis/tests/suite/subscript_overloads.rs @@ -77,9 +77,13 @@ fn session_with(files: &[(&str, &str)]) -> Session { /// The type of the subscript whose spelling is `expression` — the offset is the byte of its `[`, so the question lands /// on the index expression rather than on the base or the index. -fn the_subscripts_type(session: &Session, expression: &str) -> String { +fn the_type_of_the_subscript( + session: &Session, + source: &str, + expression: &str, +) -> String { let view = session.view("/p/a.cpp").expect("the file has a rendering"); - let at = SOURCE + let at = source .find(expression) .unwrap_or_else(|| panic!("{expression} is written")); let bracket = at + expression.find('[').expect("a bracket"); @@ -97,12 +101,12 @@ fn the_arguments_choose_the_overload_through_an_alias() { let session = session_with(&[("/p/t.h", HEADER), ("/p/a.cpp", SOURCE)]); assert_eq!( - the_subscripts_type(&session, "table[0]"), + the_type_of_the_subscript(&session, SOURCE, "table[0]"), "int&", "an `int` index selects `int& operator[](int)`" ); assert_eq!( - the_subscripts_type(&session, "table[\"k\"]"), + the_type_of_the_subscript(&session, SOURCE, "table[\"k\"]"), "double&", "a `const char*` key selects `double& operator[](const char*)`, the second declaration" ); @@ -113,13 +117,97 @@ fn the_objects_constness_chooses_the_overload_through_an_alias() { let session = session_with(&[("/p/t.h", HEADER), ("/p/a.cpp", SOURCE)]); assert_eq!( - the_subscripts_type(&session, "crate[0]"), + the_type_of_the_subscript(&session, SOURCE, "crate[0]"), "const int&", "a `const` object can only call the `const` overload" ); assert_eq!( - the_subscripts_type(&session, "boxed[0]"), + the_type_of_the_subscript(&session, SOURCE, "boxed[0]"), "int&", "while a mutable object keeps the non-const one" ); } + +/// **The standard containers' `reference` chain, answered structurally** — `std::string` is +/// `basic_string`, and `reference` is the class's own `value_type&`. +/// +/// ```text +/// string::operator[] reference +/// string basic_string a class alias +/// basic_string::reference value_type& +/// value_type char +/// ``` +/// +/// Every step is a member's computed type and a class alias; nothing is printed and parsed. The `const` case goes +/// through the same alias step and must keep the qualifier the *use* wrote (`const std::string`), which is why the +/// `const` overload is the one chosen. +#[test] +fn the_standard_reference_chain_answers_the_element_type() { + const HEADER: &str = "\ +#pragma once +namespace std { + +template +class basic_string { +public: + using value_type = Char; + using reference = value_type&; + using const_reference = const value_type&; + + reference operator[](unsigned long at); + const_reference operator[](unsigned long at) const; +}; + +using string = basic_string; + +template +class vector { +public: + using value_type = T; + using reference = value_type&; + using const_reference = const value_type&; + + reference operator[](unsigned long at); + const_reference operator[](unsigned long at) const; +}; + +} +"; + + const SOURCE: &str = "\ +#include \"t.h\" + +std::string text; +const std::string fixed_text; +std::vector numbers; +const std::vector fixed_numbers; + +char &mutable_char() { return text[0]; } +const char &constant_char() { return fixed_text[0]; } +int &mutable_number() { return numbers[0]; } +const int &constant_number() { return fixed_numbers[0]; } +"; + + let session = session_with(&[("/p/t.h", HEADER), ("/p/a.cpp", SOURCE)]); + + assert_eq!( + the_type_of_the_subscript(&session, SOURCE, "text[0]"), + "char&", + "`std::string`'s `reference` is `char&` once the class alias and `value_type` are resolved" + ); + assert_eq!( + the_type_of_the_subscript(&session, SOURCE, "fixed_text[0]"), + "const char&", + "a `const std::string` calls the `const_reference` overload and stays const" + ); + assert_eq!( + the_type_of_the_subscript(&session, SOURCE, "numbers[0]"), + "int&", + "`std::vector::reference` is `value_type&` with `T = int`" + ); + assert_eq!( + the_type_of_the_subscript(&session, SOURCE, "fixed_numbers[0]"), + "const int&", + "and the `const` vector's is `const int&`" + ); +} diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index fc4aa55d..ce739e42 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -387,7 +387,7 @@ int f() { .members .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(); assert!( names.contains(&"size".to_string()) && names.contains(&"scaled".to_string()), @@ -2075,7 +2075,10 @@ int f() { "members of Money: {:?}", list.members .iter() - .map(|member| (member.fact.name.to_string(), member.fact.returns.clone())) + .map(|member| ( + session.index().member_name(member).to_string(), + session.index().member_returns_spelling(member), + )) .collect::>() ), other => println!("members of Money: {other:?}"), @@ -2095,6 +2098,67 @@ int f() { ); } +/// **An operator's return type is substituted structurally, not as a spelling.** `Box::operator[]` is +/// declared `T&` and `Box::operator+` is declared `T*`; the answer must be a **reference** whose pointee is +/// `Widget` and a **pointer** to it — the class the argument named, as a value. +/// +/// The assertions are on the `ComputedType` variants rather than on the printed spelling, which is what says the +/// substitution happened *inside* the type: an implementation that answered the declaration's `T&` would parse to a +/// reference to a class called `T`, and one that printed and re-parsed a substituted spelling would still have to +/// produce these variants. The argument is a class — not an `int` — so a substitution that only ever reached a +/// builtin's spelling would be answered here as a class named `T`. +#[test] +fn an_operators_return_type_is_substituted_structurally() { + use cpp_code_analysis::index::types::ComputedType; + let source = "\ +struct Widget { int size; }; +template +struct Box { + T& operator[](int at) const; + T* operator+(const Box& other) const; +}; +void f() { + Box b; + auto& element = b[0]; + auto pointed = b + b; + (void)element; + (void)pointed; +} +"; + let session = session_with(&[("/p/a.cpp", source)]); + let view = session.view("/p/a.cpp").expect("the file is cooked"); + let answered = |needle: &str, into: usize| { + let at = source.find(needle).expect("the fixture writes it") + into; + let reading = view + .reading_offset_of(file::coordinates::FileOffset::new(at)) + .expect("the offset is in the file"); + match session.type_at(&view, reading) { + Known::Yes(found) => found.type_value, + other => panic!("`{needle}` has a type: {other:?}"), + } + }; + + // **`b[0]` is `T&` at `Widget`** — a reference whose pointee is the class the argument named. + match answered("b[0]", 1) { + Some(ComputedType::Reference { to, rvalue: false }) => assert_eq!( + to.class_name(), + Some("Widget"), + "the element is a reference to the class the argument named: {to:?}" + ), + other => panic!("`b[0]` is `Widget&`, structurally: {other:?}"), + } + + // **`b + b` is `T*` at `Widget`** — a pointer to that same class, not a pointer to the parameter's name. + match answered("b + b", 2) { + Some(ComputedType::Pointer(to)) => assert_eq!( + to.class_name(), + Some("Widget"), + "the answer is a pointer to the class the argument named: {to:?}" + ), + other => panic!("`b + b` is `Widget*`, structurally: {other:?}"), + } +} + /// **`typedef struct { … } Name;`** — C's ordinary way of naming a struct, and the shape whose members were missing. /// /// Three questions, and all three are the same one asked of a different spelling: @@ -2132,7 +2196,7 @@ int g(void) { return plain.d; } ); list.members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>() } other => panic!("`{class}` has a member list: {other:?}"), @@ -2148,11 +2212,13 @@ int g(void) { return plain.d; } assert_eq!(members("Plain"), ["e"], "a named body with a variable"); // **And the answers are reachable through the code**, which is what a member list is for: the receiver's type - // comes from the declaration, and the member's from the list. + // comes from the declaration, and the member's from the list. The variable's type keeps C's tag, because that is + // what the declaration wrote: the type is `Type::ElaboratedRecord` around `Plain`, and the class question sees + // through it to the record whose members answer. assert_eq!( type_of_use(source, "plain").as_deref(), - Some("Plain"), - "a named body types its variable as the tag" + Some("struct Plain"), + "a named body types its variable as the tagged record" ); assert_eq!( type_of_use(source, "o").as_deref(), @@ -2204,7 +2270,7 @@ int f(void) { exarg_T eap; return eap.addr_count; } Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>(), other => panic!("`{class}` has a member list: {other:?}"), }; @@ -2223,12 +2289,14 @@ int f(void) { exarg_T eap; return eap.addr_count; } Some("int"), "and its member access is typed through the tag's body" ); - // **The elaborated keyword is not part of the type.** `struct exarg raw;` used to record `struct` — the keyword - // alone — because the grammar reads `struct exarg` as a `BuiltinType` plus a `NamedType`, and the builtin won. + // **The keyword is kept on the type, and it is the whole point of the representation.** `struct exarg raw;` used + // to record `struct` — the keyword alone — because the grammar reads `struct exarg` as a `BuiltinType` plus a + // `NamedType` and the builtin won. The tag is now carried *with* the name (`Type::ElaboratedRecord`), so the + // type is the record `exarg` and its display is the file's own `struct exarg`. assert_eq!( type_of_use(source, "raw").as_deref(), - Some("exarg"), - "`struct exarg` spells the type `exarg`" + Some("struct exarg"), + "`struct exarg` spells the elaborated record" ); } @@ -2256,7 +2324,7 @@ struct line { Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>(), other => panic!("`line` has a member list: {other:?}"), }; @@ -2294,7 +2362,7 @@ fn an_unnamed_struct_type_is_keyed_by_the_variable_it_declares() { Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>(), other => panic!("`bits` has a member list: {other:?}"), }; @@ -2468,7 +2536,7 @@ int f() { Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>(), other => panic!("`{class}` has a member list: {other:?}"), }; @@ -2527,7 +2595,7 @@ int f() { Known::Yes(list) => list .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>(), other => panic!("`Box` has a member list: {other:?}"), }; @@ -2702,7 +2770,7 @@ std::string f() { // **The rendering's text**, because a fact's range is a range there — the include closure is inlined into it. let rendering = view.root.text().to_string(); let declaration_at = |which: usize| -> usize { - rendering + source .match_indices("describe(T value)") .nth(which) .map(|(at, _)| at) @@ -2721,7 +2789,11 @@ std::string f() { other => panic!("`describe(1.5)` resolves: {other:?}"), }; assert_eq!( - one.fact.name_range.start_offset, + session + .definition_fact(&one) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(1), "the condition picks the floating-point overload" ); @@ -2737,123 +2809,350 @@ std::string f() { other => panic!("`describe(41)` resolves: {other:?}"), }; assert_eq!( - integral.fact.name_range.start_offset, + session + .definition_fact(&integral) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(0), "the condition picks the integral overload" ); } /// **The condition evaluator**, decision by decision — the module the `enable_if` overloads rest on. +/// +/// Every condition here is the **typed CST node** the production entry points answer: an `enable_if` declaration's +/// first template argument, or a `requires`-clause's condition expression. The bindings are the structured types a +/// call deduces, so no assertion hands the evaluator a condition spelling. #[test] fn the_constraint_evaluator_decides_the_fundamental_traits() { - use cpp_code_analysis::sema::constraint::{satisfies, the_condition_of}; + use cpp_code_analysis::index::types::{ArrayExtent, ComputedType, FunctionType, QualifiedType}; + use cpp_code_analysis::sema::constraint::{ + a_requires_clause_node, satisfies, the_condition_of_node, + }; + use cpp_parser::{CppAstNode, CppParser, CppRequiresClause, CppSyntaxNode, ParserConfig}; + use smol_str::SmolStr; + use std::sync::Arc; + + /// The condition of an `enable_if` return type, through the production entry point. + fn an_enable_ifs_condition(declaration: &str) -> CppSyntaxNode { + let tree = CppParser::parse(declaration, ParserConfig::default()); + the_condition_of_node(&tree.get_red_root()).expect("the declaration carries a condition") + } + + /// The condition a `requires` clause states, through the production entry point. + fn a_requires_conditions(declaration: &str) -> CppSyntaxNode { + let tree = CppParser::parse(declaration, ParserConfig::default()); + let clause = tree + .get_red_root() + .descendants() + .find_map(CppRequiresClause::cast) + .expect("the declaration carries a requires clause"); + a_requires_clause_node(&clause).expect("the clause carries a condition") + } + + /// A condition written in a `requires` clause of `template void f(T value);`. + fn with_requires(condition: &str) -> CppSyntaxNode { + a_requires_conditions(&format!( + "template requires {condition} void f(T value);\n" + )) + } - let bind = |spelling: &str| vec![("T".to_string(), spelling.to_string())]; + /// The deducer's binding: `T` stands for one structured type. + fn bind(written: ComputedType) -> Vec<(SmolStr, ComputedType)> { + vec![(SmolStr::new("T"), written)] + } + + let a_reference = |of: ComputedType| ComputedType::Reference { + to: Arc::new(of), + rvalue: false, + }; + let an_rvalue_reference = |of: ComputedType| ComputedType::Reference { + to: Arc::new(of), + rvalue: true, + }; + let a_const = |of: ComputedType| { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(of), + is_const: true, + is_volatile: false, + })) + }; + let a_volatile = |of: ComputedType| { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(of), + is_const: false, + is_volatile: true, + })) + }; + let a_pointer = |of: ComputedType| ComputedType::Pointer(Arc::new(of)); + let an_array = |of: ComputedType, extent: ArrayExtent| ComputedType::Array { + of: Arc::new(of), + extent, + }; + let a_function = |returns: ComputedType, parameters: Vec| { + ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(returns), + parameters: parameters.into_boxed_slice(), + })) + }; // The two declarations of `describe`, verbatim. - let integral = the_condition_of( + let integral = an_enable_ifs_condition( "typename std::enable_if::value, std::string>::type describe(T value)", - ) - .expect("the declaration carries a condition"); - assert_eq!(integral, "std::is_integral::value"); - assert_eq!(satisfies(integral, &bind("int")), Some(true)); - assert_eq!(satisfies(integral, &bind("double")), Some(false)); + ); + assert_eq!( + integral.text().to_string().trim(), + "std::is_integral::value", + "the entry point answers the condition node, not the declaration" + ); assert_eq!( - satisfies(integral, &bind("std::string")), + satisfies(&integral, &bind(ComputedType::builtin("int"))), + Some(true) + ); + assert_eq!( + satisfies(&integral, &bind(ComputedType::builtin("double"))), + Some(false) + ); + assert_eq!( + satisfies( + &integral, + &bind(ComputedType::named("std::string", Vec::new())) + ), Some(false), "a class is not integral" ); - let floating = the_condition_of( + let floating = an_enable_ifs_condition( "typename std::enable_if::value, int>::type describe(T value)", - ) - .expect("the declaration carries a condition"); - assert_eq!(satisfies(floating, &bind("double")), Some(true)); - assert_eq!(satisfies(floating, &bind("int")), Some(false)); + ); + assert_eq!( + satisfies(&floating, &bind(ComputedType::builtin("double"))), + Some(true) + ); + assert_eq!( + satisfies(&floating, &bind(ComputedType::builtin("int"))), + Some(false) + ); - // The three spellings of one answer. - for spelling in [ - "std::is_integral::value", - "std::is_integral{}", - "std::is_integral_v", - "std::is_integral()", + // The three spellings of one answer — each read as the node its own syntax made: `::value` is a name with a + // template-id, `{}` a braced construction, `_v` a name, and `()` a call with no arguments. + for (spelling, condition) in [ + ( + "::value", + an_enable_ifs_condition( + "typename std::enable_if::value, int>::type describe(T)", + ), + ), + ( + "{}", + an_enable_ifs_condition( + "typename std::enable_if{}, int>::type describe(T)", + ), + ), + ("_v", with_requires("std::is_integral_v")), + ("()", with_requires("std::is_integral()")), ] { assert_eq!( - satisfies(spelling, &bind("long")), + satisfies(&condition, &bind(ComputedType::builtin("long"))), Some(true), "{spelling} says a `long` is integral" ); } - // The operators, and a trait this layer does not know. + // **The operators**, each its own node: `!` is a `UnaryExpr`, `&&`/`||` are `BinaryExpr`s, and `is_same` is the + // two-argument trait. assert_eq!( - satisfies("!std::is_integral::value", &bind("double")), + satisfies( + &with_requires("!std::is_integral::value"), + &bind(ComputedType::builtin("double")) + ), Some(true) ); assert_eq!( satisfies( - "std::is_integral::value && !std::is_same::value", - &bind("int") + &with_requires("std::is_integral::value && !std::is_same::value"), + &bind(ComputedType::builtin("int")) ), Some(true) ); assert_eq!( satisfies( - "std::is_integral::value || std::is_floating_point::value", - &bind("float") + &with_requires("std::is_integral::value || std::is_floating_point::value"), + &bind(ComputedType::builtin("float")) + ), + Some(true) + ); + assert_eq!( + satisfies( + &with_requires("std::is_same"), + &bind(ComputedType::builtin("char")) + ), + Some(true) + ); + assert_eq!( + satisfies( + &with_requires("std::is_same_v"), + &bind(ComputedType::builtin("int")) + ), + Some(false) + ); + // **A nested template-id is compared too.** The old text version refused any argument that contained `<`, + // because substituting into a nested template-id was a text rewrite it could not do safely; here both arguments + // are the structured types their nodes wrote, and the comparison is the type layer's canonical spelling of each. + assert_eq!( + satisfies( + &with_requires("std::is_same, std::vector>"), + &bind(ComputedType::builtin("int")) + ), + Some(true), + "the same class template with the same argument" + ); + assert_eq!( + satisfies( + &with_requires("std::is_same"), + &bind(a_reference(ComputedType::builtin("int"))) ), Some(true) ); + assert_eq!( - satisfies("std::is_user_defined::value", &bind("int")), + satisfies( + &with_requires("std::is_user_defined::value"), + &bind(ComputedType::builtin("int")) + ), None, "a trait this layer does not know is *cannot tell*, never `false`" ); assert_eq!( - satisfies("std::is_integral::value", &bind("int")), + satisfies( + &with_requires("std::is_integral::value"), + &bind(ComputedType::builtin("int")) + ), None, "an unbound parameter is cannot-tell as well" ); - // **The decorators**, which answer from the spelling alone — and for *any* type, so `std::string&` is a reference - // whichever class `string` is. + // **The decorators**, which answer from the type's shape alone — and for *any* type, so `std::string&` is a + // reference whichever class `string` is. for (condition, spelling, expected) in [ - ("std::is_reference_v", "int&", true), - ("std::is_reference_v", "int&&", true), - ("std::is_reference_v", "int", false), - ("std::is_reference_v", "std::string&", true), - ("std::is_const_v", "const int", true), - ("std::is_const_v", "int", false), - ("std::is_const_v", "const int*", false), - ("std::is_volatile_v", "volatile int", true), - ("std::is_volatile_v", "int", false), - ("std::is_array_v", "int[4]", true), - ("std::is_array_v", "int[]", true), - ("std::is_array_v", "int", false), - ("std::is_function_v", "int(int)", true), - ("std::is_function_v", "int", false), - ("std::is_pointer_v", "int*", true), - ("std::is_pointer_v", "int", false), + ( + "std::is_reference_v", + a_reference(ComputedType::builtin("int")), + true, + ), + ( + "std::is_reference_v", + an_rvalue_reference(ComputedType::builtin("int")), + true, + ), + ( + "std::is_reference_v", + ComputedType::builtin("int"), + false, + ), + ( + "std::is_reference_v", + a_reference(ComputedType::named("std::string", Vec::new())), + true, + ), + ( + "std::is_const_v", + a_const(ComputedType::builtin("int")), + true, + ), + ("std::is_const_v", ComputedType::builtin("int"), false), + ( + "std::is_const_v", + a_pointer(a_const(ComputedType::builtin("int"))), + false, + ), + ( + "std::is_volatile_v", + a_volatile(ComputedType::builtin("int")), + true, + ), + ("std::is_volatile_v", ComputedType::builtin("int"), false), + ( + "std::is_array_v", + an_array(ComputedType::builtin("int"), ArrayExtent::Literal(4)), + true, + ), + ( + "std::is_array_v", + an_array(ComputedType::builtin("int"), ArrayExtent::Unspecified), + true, + ), + ( + "std::is_array_v", + an_array(ComputedType::builtin("int"), ArrayExtent::written("COUNT")), + true, + ), + ("std::is_array_v", ComputedType::builtin("int"), false), + ( + "std::is_function_v", + a_function( + ComputedType::builtin("int"), + vec![ComputedType::builtin("int")], + ), + true, + ), + ("std::is_function_v", ComputedType::builtin("int"), false), + ( + "std::is_pointer_v", + a_pointer(ComputedType::builtin("int")), + true, + ), + ("std::is_pointer_v", ComputedType::builtin("int"), false), ] { assert_eq!( - satisfies(condition, &bind(spelling)), + satisfies(&with_requires(condition), &bind(spelling)), Some(expected), - "{condition} of {spelling}" + "{condition} of the structured type" ); } // **A class name is not a scalar this layer can place**, so a scalar trait of one is *cannot tell* — and an unbound // parameter stays unanswerable for the decorators too. assert_eq!( - satisfies("std::is_integral_v", &bind("std::string")), + satisfies( + &with_requires("std::is_integral_v"), + &bind(ComputedType::named("std::string", Vec::new())) + ), Some(false) ); - assert_eq!(satisfies("std::is_const_v", &bind("U")), None); - assert_eq!(satisfies("std::is_class_v", &bind("std::string")), None); - assert_eq!( - the_condition_of("void plain(int value)"), + satisfies( + &with_requires("std::is_const_v"), + &bind(ComputedType::named("U", Vec::new())) + ), + None + ); + assert_eq!( + satisfies( + &with_requires("std::is_class_v"), + &bind(ComputedType::named("std::string", Vec::new())) + ), None, + "`is_class` is a symbol-table question" + ); + + let plain = CppParser::parse("void plain(int value);\n", ParserConfig::default()); + assert!( + the_condition_of_node(&plain.get_red_root()).is_none(), "an ordinary function carries no condition" ); + let requires_expression = CppParser::parse( + "template requires requires(T t) { t.f(); } void f(T value);\n", + ParserConfig::default(), + ); + let clause = requires_expression + .get_red_root() + .descendants() + .find_map(CppRequiresClause::cast) + .expect("the declaration carries a requires clause"); + assert!( + a_requires_clause_node(&clause).is_none(), + "a requires-expression states no condition this layer decides" + ); } /// Doctors: how many `describe` bindings the scope tree keeps, looked up from inside the function body. @@ -2968,7 +3267,7 @@ std::string f() { let view = session.view("/p/a.cpp").expect("the file is held"); let rendering = view.root.text().to_string(); let declaration_at = |which: usize| -> usize { - rendering + source .match_indices("describe(T value)") .nth(which) .map(|(at, _)| at) @@ -2985,7 +3284,11 @@ std::string f() { other => panic!("`describe(1.5)` resolves: {other:?}"), }; assert_eq!( - one.fact.name_range.start_offset, + session + .definition_fact(&one) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(1), "the template parameter's condition picks the floating-point overload" ); @@ -3024,7 +3327,7 @@ std::string f() { let view = session.view("/p/a.cpp").expect("the file is held"); let rendering = view.root.text().to_string(); let declaration_at = |which: usize| -> usize { - rendering + source .match_indices("describe(T value)") .nth(which) .map(|(at, _)| at) @@ -3041,7 +3344,11 @@ std::string f() { other => panic!("`describe(1.5)` resolves: {other:?}"), }; assert_eq!( - one.fact.name_range.start_offset, + session + .definition_fact(&one) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(1), "the `requires` clause picks the floating-point overload" ); @@ -3057,7 +3364,11 @@ std::string f() { other => panic!("`describe(41)` resolves: {other:?}"), }; assert_eq!( - integral.fact.name_range.start_offset, + session + .definition_fact(&integral) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(0), "and the integral overload for an int" ); @@ -3104,7 +3415,7 @@ std::string f() { let view = session.view("/p/a.cpp").expect("the file is held"); let rendering = view.root.text().to_string(); let declaration_at = |which: usize| -> usize { - rendering + source .match_indices("describe(T value)") .nth(which) .map(|(at, _)| at) @@ -3121,7 +3432,11 @@ std::string f() { other => panic!("`describe(1.5)` resolves: {other:?}"), }; assert_eq!( - one.fact.name_range.start_offset, + session + .definition_fact(&one) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(1), "the concept picks the floating-point overload" ); @@ -3162,7 +3477,7 @@ std::string f() { let view = session.view("/p/a.cpp").expect("the file is held"); let rendering = view.root.text().to_string(); let declaration_at = |which: usize| -> usize { - rendering + source .match_indices("describe(T value)") .nth(which) .map(|(at, _)| at) @@ -3182,7 +3497,11 @@ std::string f() { other => panic!("`describe(1.5)` resolves: {other:?}"), }; assert_eq!( - floating.fact.name_range.start_offset, + session + .definition_fact(&floating) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(1), "the composed concept is false for a double" ); @@ -3197,7 +3516,11 @@ std::string f() { other => panic!("`describe(-3)` resolves: {other:?}"), }; assert_eq!( - signed.fact.name_range.start_offset, + session + .definition_fact(&signed) + .expect("the answer resolves through the index") + .name_range + .start_offset, declaration_at(0), "and true for a signed int" ); @@ -3207,33 +3530,133 @@ std::string f() { /// /// The relation answers `No` for `int` → `_Ty2&&` because `_Ty2` is not `int`, and `_Ty2` is a *template parameter*. Only a /// class the index can find decides those; one it cannot see makes the answer `Unknown`, and `Unknown` reports nothing. +/// +/// The conversion question takes **parsed types**, and C's tag (`struct point`) is part of the `Type` — the +/// declaration reader and `parse_type_spelling` produce `Type::ElaboratedRecord` from the written keyword — so the +/// conversion core derives the record structurally and no caller passes a spelling. This pins the rules the checks +/// rely on at that seam. #[test] fn a_template_parameter_target_is_not_a_refusal() { - use cpp_code_analysis::sema::convert::{Conversion, conversion}; - use cpp_code_analysis::sema::types::{Type, parse_type_spelling}; + use cpp_code_analysis::index::types::ComputedType; + use cpp_code_analysis::sema::convert::{Conversion, conversion_to}; + use cpp_code_analysis::sema::types::parse_type_spelling; + use cpp_parser::features::Family; - let an_int = Type::builtin("int"); + let an_int = ComputedType::builtin("int"); assert_eq!( - conversion(&an_int, "_Ty2&&", None, |_| None), + conversion_to(&an_int, &parse_type_spelling("_Ty2&&"), None, |_| None), Conversion::Unknown, "an unread template parameter is cannot-tell, not a refusal" ); assert_eq!( - conversion(&an_int, "T", None, |_| None), + conversion_to(&an_int, &parse_type_spelling("T"), None, |_| None), Conversion::Unknown, "and so is a bare `T`" ); + // **The structural answer**, when the declaration's template parameter list was in hand. + let a_parameter = ComputedType::TemplateParameter("T".into()); + assert_eq!( + conversion_to(&an_int, &a_parameter, None, |_| None), + Conversion::Unknown, + "a template parameter is a template parameter, structurally" + ); // **A class the index knows still refuses**: `int` cannot be built into a `Widget` that has no such constructor. assert_eq!( - conversion(&an_int, "const Widget&", None, |_| Some(false)), + conversion_to(&an_int, &parse_type_spelling("const Widget&"), None, |_| { + Some(false) + }), Conversion::Refused, ); // **And an unread class on the *source* side is cannot-tell too**, not a refusal. let a_string = parse_type_spelling("std::string"); assert_eq!( - conversion(&a_string, "int", None, |_| None), + conversion_to(&a_string, &ComputedType::builtin("int"), None, |_| None), Conversion::Unknown ); + + // **In C, a record written with its tag is nobody else's type.** The keyword is on the `Type` — a `struct point *` + // answers `Pointer { to: ElaboratedRecord { tag: Struct, of: Named("point") } }` — so the rule below is decided + // without a spelling being read. + let a_record_pointer = parse_type_spelling("struct point *"); + assert_eq!( + conversion_to( + &parse_type_spelling("int *"), + &a_record_pointer, + Some(Family::C), + |_| None + ), + Conversion::Refused, + "an `int *` is not a `struct point *` in C" + ); + assert_eq!( + conversion_to( + &a_record_pointer, + &a_record_pointer, + Some(Family::C), + |_| None + ), + Conversion::Implicit, + "and the record itself converts to the same record" + ); + // **A `union` tag is a record tag as well**, and the keyword written on each side has to agree. + let a_union_pointer = parse_type_spelling("union value *"); + assert_eq!( + conversion_to( + &parse_type_spelling("struct value *"), + &a_union_pointer, + Some(Family::C), + |_| None + ), + Conversion::Refused, + "a `struct value` is not a `union value`" + ); + assert_eq!( + conversion_to(&a_union_pointer, &a_union_pointer, Some(Family::C), |_| { + None + }), + Conversion::Implicit, + "a `union value *` converts to itself" + ); + // **The gate matters**: a target written without a tag is not the C record rule's question at all — `point *` + // after `typedef struct point point;` is the same record, and `typedef int point;` is not, so the answer stays + // `Unknown` (silence) rather than becoming a refusal. + assert_eq!( + conversion_to( + &parse_type_spelling("int *"), + &parse_type_spelling("point *"), + Some(Family::C), + |_| None + ), + Conversion::Unknown, + ); + // **A typedef writes no tag, and a `void *` converts to any object pointer in C** — neither is refused as a + // record conversion. + assert!( + !conversion_to( + &an_int, + &parse_type_spelling("size_t"), + Some(Family::C), + |_| None + ) + .is_refused(), + "an `int` reaching a typedef is not a record mismatch" + ); + assert!( + !conversion_to( + &parse_type_spelling("void *"), + &a_record_pointer, + Some(Family::C), + |_| None + ) + .is_refused(), + "`void *` converts to any object pointer in C" + ); + // **A pointer to `bool` is a standard conversion**, in both languages. + let a_pointer = parse_type_spelling("const char *"); + assert_eq!( + conversion_to(&a_pointer, &ComputedType::builtin("bool"), None, |_| None), + Conversion::Implicit, + ); } /// **A member's deduced return type, through the header that declares it** — `auto copy_of() const { return value_; }`. @@ -3818,7 +4241,7 @@ struct User : traits { }; let names: Vec<&str> = list .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!( names.contains(&"size_type"), @@ -3862,7 +4285,7 @@ struct User : traits { }; let names: Vec<&str> = list .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!( names.contains(&"size_type"), @@ -4256,11 +4679,13 @@ void f() { panic!("a class this file declares answers a member list: {bare:?}"); }; assert!( - bare.members.iter().any(|member| member.fact.name == "own"), + bare.members + .iter() + .any(|member| session.index().member_name(member) == "own"), "the class's own members are listed: {:?}", bare.members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect::>() ); assert_eq!( @@ -4328,12 +4753,12 @@ fn a_partial_specializations_members_are_not_the_primary_templates() { let begins: Vec<(String, usize)> = members .members .iter() - .filter(|member| member.fact.name == "begin") - .map(|member| { - ( - member.file.display().to_string(), - member.fact.range.start_offset, - ) + .filter(|member| session.index().member_name(member) == "begin") + .filter_map(|member| { + Some(( + session.index().member_path(member)?.display().to_string(), + session.index().member_fact(member)?.range.start_offset, + )) }) .collect(); assert_eq!( @@ -4376,7 +4801,7 @@ struct Hashed { let names: Vec = members .members .iter() - .map(|member| member.fact.name.to_string()) + .map(|member| session.index().member_name(member).to_string()) .collect(); assert!( names.iter().any(|name| name == "operator()"), diff --git a/crates/cpp_code_analysis/tests/suite/ue_engine.rs b/crates/cpp_code_analysis/tests/suite/ue_engine.rs index 912eac6d..42b917d2 100644 --- a/crates/cpp_code_analysis/tests/suite/ue_engine.rs +++ b/crates/cpp_code_analysis/tests/suite/ue_engine.rs @@ -287,7 +287,7 @@ public: let names: Vec<&str> = list .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); for expected in ["bIsReady", "Target", "Names", "StaticClass", "Generated"] { assert!(names.contains(&expected), "{expected} of {names:?}"); @@ -299,7 +299,7 @@ public: let generated_names: Vec<&str> = generated .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!(generated_names.contains(&"Value"), "{generated_names:?}"); @@ -308,15 +308,24 @@ public: let super_member = list .members .iter() - .find(|member| member.fact.name == "Super") + .find(|member| session.index().member_name(member) == "Super") .expect("the generated `Super`"); - assert_eq!(super_member.fact.type_of.as_deref(), Some("AActor")); + assert_eq!( + session + .index() + .member_type_spelling(super_member) + .as_deref(), + Some("AActor") + ); let this_class = list .members .iter() - .find(|member| member.fact.name == "ThisClass") + .find(|member| session.index().member_name(member) == "ThisClass") .expect("the generated `ThisClass`"); - assert_eq!(this_class.fact.type_of.as_deref(), Some("AMyActor")); + assert_eq!( + session.index().member_type_spelling(this_class).as_deref(), + Some("AMyActor") + ); // **And they resolve inside a body**, which is the half the generated code does for a compiler: `Super::BeginPlay()` // reaches the engine's `AActor::BeginPlay`, and `ThisClass` is the class the body is written in. @@ -329,15 +338,21 @@ public: else { panic!("`Super::BeginPlay` resolves"); }; - assert_eq!(base.fact.name, "BeginPlay", "{:?}", base.fact); + let base_fact = session + .definition_fact(&base) + .expect("the answer resolves through the index"); + let base_file = session + .definition_path(&base) + .expect("the answer names a file the index holds"); + assert_eq!(base_fact.name, "BeginPlay", "{base_fact:?}"); // The index spells a path in its own (lowercased) form on Windows. assert!( - base.file + base_file .to_string_lossy() + .replace('\\', "/") .to_ascii_lowercase() .ends_with("gameframework/actor.h"), - "the base's own declaration: {:?}", - base.file + "the base's own declaration: {base_file:?}" ); let this_at = source.find("ThisClass* Self").expect("the class itself"); @@ -345,14 +360,20 @@ public: else { panic!("`ThisClass` resolves"); }; - assert_eq!(own.fact.name, "AMyActor", "{:?}", own.fact); + let own_fact = session + .definition_fact(&own) + .expect("the answer resolves through the index"); + let own_file = session + .definition_path(&own) + .expect("the answer names a file the index holds"); + assert_eq!(own_fact.name, "AMyActor", "{own_fact:?}"); assert!( - own.file + own_file .to_string_lossy() + .replace('\\', "/") .to_ascii_lowercase() .ends_with("myactor.h"), - "{:?}", - own.file + "{own_file:?}" ); } @@ -387,7 +408,7 @@ struct FMyData let names: Vec<&str> = list .members .iter() - .map(|member| member.fact.name.as_str()) + .map(|member| session.index().member_name(member)) .collect(); assert!(names.contains(&"ThisClass"), "{names:?}"); assert!(!names.contains(&"Super"), "a struct has no base: {names:?}"); diff --git a/crates/cpp_inspect/src/questions.rs b/crates/cpp_inspect/src/questions.rs index d0fd23b5..b1e795de 100644 --- a/crates/cpp_inspect/src/questions.rs +++ b/crates/cpp_inspect/src/questions.rs @@ -45,16 +45,15 @@ fn at_a_place(text: &str, offset: usize) -> String { /// One declaration's own location — the **declaring** file's coordinates, which are not this file's. fn where_a_declaration(session: &Session, definition: &ProjectDefinition) -> String { - let name = definition - .file + let Some((file, fact)) = session.definition_parts(definition) else { + return "(unresolved)".to_string(); + }; + let name = file .file_name() .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| definition.file.display().to_string()); - match session.text(&definition.file) { - Some(text) => format!( - "{name}:{}", - at_a_place(&text, definition.fact.name_range.start_offset) - ), + .unwrap_or_else(|| file.display().to_string()); + match session.text(&file) { + Some(text) => format!("{name}:{}", at_a_place(&text, fact.name_range.start_offset)), None => name, } } @@ -71,20 +70,20 @@ fn kind_of(kind: DeclKind) -> &'static str { } /// The fields of a fact a reader asks about, in one line. -fn a_fact_and_what_it_says(fact: &DeclFact) -> String { - format!("{:<28} {}", fact.name, what_it_says(fact)) +fn a_fact_and_what_it_says(session: &Session, fact: &DeclFact) -> String { + format!("{:<28} {}", fact.name, what_it_says(session, fact)) } /// The same, without the name — for a caller that prints the name in a column of its own. -fn what_it_says(fact: &DeclFact) -> String { +fn what_it_says(session: &Session, fact: &DeclFact) -> String { let mut said = kind_of(fact.kind).to_string(); if let Some(scope) = &fact.scope { said.push_str(&format!(" in {scope}")); } - if let Some(type_of) = &fact.type_of { + if let Some(type_of) = session.index().type_spelling_of(fact) { said.push_str(&format!(" type `{type_of}`")); } - if let Some(returns) = &fact.returns { + if let Some(returns) = session.index().returns_spelling_of(fact) { said.push_str(&format!(" returns `{returns}`")); } if let Some(parameters) = fact.parameter_list() { @@ -108,20 +107,23 @@ fn what_it_says(fact: &DeclFact) -> String { } fn declaration_value(session: &Session, definition: &ProjectDefinition) -> Value { + let Some((file, fact)) = session.definition_parts(definition) else { + return json!({ "unresolved": true }); + }; json!({ - "file": definition.file.display().to_string(), + "file": file.display().to_string(), "where": where_a_declaration(session, definition), - "name": definition.fact.name, - "kind": kind_of(definition.fact.kind), - "scope": definition.fact.scope, - "type_of": definition.fact.type_of, - "returns": definition.fact.returns, - "parameter_list": definition.fact.parameter_list(), - "parameters": definition.fact.parameters(), - "requires_clause": definition.fact.requires_clause(), - "bases": definition.fact.bases(), - "reflection": definition.fact.reflection().map(|reflection| reflection.said()), - "modifiers": definition.fact.modifiers.bits(), + "name": fact.name, + "kind": kind_of(fact.kind), + "scope": fact.scope, + "type_of": session.index().type_spelling_of(fact).map(|spelled| spelled.to_string()), + "returns": session.index().returns_spelling_of(fact).map(|spelled| spelled.to_string()), + "parameter_list": fact.parameter_list(), + "parameters": fact.parameters(), + "requires_clause": fact.requires_clause(), + "bases": fact.bases(), + "reflection": fact.reflection().map(|reflection| reflection.said()), + "modifiers": fact.modifiers.bits(), }) } @@ -214,10 +216,14 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { match &picked { Known::Yes(definition) => { picked_value = declaration_value(session, definition); + let fact = session.definition_fact(definition); text.push_str(&format!( " picked {:<40} {}\n", where_a_declaration(session, definition), - a_fact_and_what_it_says(&definition.fact) + fact.map_or_else( + || "(unresolved)".to_string(), + |fact| a_fact_and_what_it_says(session, fact) + ) )); } Known::Unknown(reason) => text.push_str(&format!(" picked unknown — {reason:?}\n")), @@ -229,7 +235,10 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { text.push_str(&format!( " found {:<40} {}\n", where_a_declaration(session, definition), - a_fact_and_what_it_says(&definition.fact) + session.definition_fact(definition).map_or_else( + || "(unresolved)".to_string(), + |fact| a_fact_and_what_it_says(session, fact) + ) )); } if found.found.is_empty() { @@ -284,18 +293,22 @@ pub fn the_members(opened: &Opened, class: &str, limit: usize) -> Result>(), - "members": list.members.iter().take(shown).map(|member| json!({ - "name": member.fact.name, - "kind": kind_of(member.fact.kind), - "declared_in": member.declared_in, - "depth": member.depth, - "file": member.file.display().to_string(), - "type_of": member.fact.type_of, - "returns": member.fact.returns, - "parameter_list": member.fact.parameter_list(), - "requires_clause": member.fact.requires_clause(), - "modifiers": member.fact.modifiers.bits(), - })).collect::>(), + "members": list.members.iter().take(shown).map(|member| { + let index = session.index(); + let fact = index.member_fact(member); + json!({ + "name": index.member_name(member), + "kind": fact.map(|fact| kind_of(fact.kind)), + "declared_in": member.declared_in, + "depth": member.depth, + "file": index.member_path(member).map(|path| path.display().to_string()), + "type_of": index.member_type_spelling(member), + "returns": index.member_returns_spelling(member), + "parameter_list": index.member_parameter_list(member), + "requires_clause": fact.and_then(|fact| fact.requires_clause()), + "modifiers": fact.map(|fact| fact.modifiers.bits()), + }) + }).collect::>(), }) } Known::Unknown(reason) => { @@ -311,19 +324,26 @@ pub fn the_members(opened: &Opened, class: &str, limit: usize) -> Result, member: &ProjectMember) -> String { - let where_is = match session.text(&member.file) { - Some(text) => at_a_place(&text, member.fact.name_range.start_offset), - None => String::new(), + let index = session.index(); + let Some(fact) = index.member_fact(member) else { + return String::new(); }; - let name = member - .file - .file_name() + let path = index.member_path(member); + let where_is = path + .and_then(|path| session.text(path)) + .map(|text| at_a_place(&text, fact.name_range.start_offset)) + .unwrap_or_default(); + let name = path + .and_then(|path| path.file_name()) .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_default(); + let shown = index + .member_display_fact(member) + .unwrap_or_else(|| fact.clone()); format!( "{:<28} {:<40} (declared in `{}`) {name}:{where_is}", - member.fact.name, - what_it_says(&member.fact), + shown.name, + what_it_says(session, &shown), member.declared_in ) } @@ -459,7 +479,7 @@ pub fn the_facts(opened: &Opened, filters: &FactFilters<'_>) -> Result) -> Result( else { return None; }; - let definition = defined - .found - .iter() - .find(|definition| definition.fact.kind == DeclKind::Function)?; - item_of(session, &definition.file, &definition.fact) + let definition = defined.found.iter().find(|definition| { + session + .definition_fact(definition) + .is_some_and(|fact| fact.kind == DeclKind::Function) + })?; + let (file, fact) = session.definition_parts(definition)?; + item_of(session, &file, fact) } /// One fact, as the protocol's item. @@ -161,7 +166,10 @@ fn item_of( position_in_file(held, fact.name_range.start_offset)?, position_in_file(held, fact.name_range.end_offset())?, ); - let detail = match (&fact.returns, &fact.parameter_list()) { + // **The return spelling is printed from the index's store** (or from the fact's synthesized value), at the + // display edge; nothing is parsed. + let returns = session.index().returns_spelling_of(fact); + let detail = match (&returns, &fact.parameter_list()) { (Some(returns), Some(parameters)) => Some(format!("{returns} {}{parameters}", fact.name)), (None, Some(parameters)) => Some(format!("{}{parameters}", fact.name)), _ => None, @@ -420,14 +428,17 @@ pub fn outgoing_calls_of( else { continue; }; - let Some(definition) = defined - .found - .iter() - .find(|definition| definition.fact.kind == DeclKind::Function) - else { + let Some(definition) = defined.found.iter().find(|definition| { + session + .definition_fact(definition) + .is_some_and(|fact| fact.kind == DeclKind::Function) + }) else { + continue; + }; + let Some((file, fact)) = session.definition_parts(definition) else { continue; }; - let Some(item) = item_of(session, &definition.file, &definition.fact) else { + let Some(item) = item_of(session, &file, fact) else { continue; }; let Some(held) = session.files().held(&view.path) else { diff --git a/crates/cpp_ls/src/handlers/completion/mod.rs b/crates/cpp_ls/src/handlers/completion/mod.rs index 75001f8d..7e045136 100644 --- a/crates/cpp_ls/src/handlers/completion/mod.rs +++ b/crates/cpp_ls/src/handlers/completion/mod.rs @@ -52,7 +52,9 @@ use cpp_code_analysis::DeclFact; use cpp_code_analysis::FileView; use cpp_code_analysis::file::coordinates::ReadingOffset; use cpp_code_analysis::why_no_members; -use cpp_code_analysis::{CompletionItem as AnalysisItem, DiskFiles, ItemKind, Session, detail_of}; +use cpp_code_analysis::{ + CompletionItem as AnalysisItem, DiskFiles, ItemKind, Session, detail_of_with_types, +}; use cpp_parser::SourceRange; use lsp_types::{ ClientCapabilities, CompletionItem, CompletionItemKind, CompletionItemLabelDetails, @@ -499,7 +501,9 @@ pub async fn on_completion_resolve( // unchanged. The label is what the client echoed, and it is what selects between two declarations of one // name; the identity offset says which of them, so the first at or after it is the one. let fact = declaration_in(session, &looked_up, offset, &label); - let detail = fact.as_ref().and_then(detail_of); + // The stored handles are printed from the session's one type store; a synthesized fact carries its computed + // value, which the same helper prints. No spelling is parsed. + let detail = fact.as_ref().and_then(detail_of_with_types); let at = fact .as_ref() .map(|fact| fact.name_range.start_offset) diff --git a/crates/cpp_ls/src/handlers/definition/mod.rs b/crates/cpp_ls/src/handlers/definition/mod.rs index 108577cb..3a271116 100644 --- a/crates/cpp_ls/src/handlers/definition/mod.rs +++ b/crates/cpp_ls/src/handlers/definition/mod.rs @@ -162,7 +162,12 @@ pub async fn on_goto_definition_handler( // project declare `_diagnosticStyle` — so a cursor inside one of them was offered all three. The cursor's own // class decides which is meant; see `references::narrowed_to_the_cursors_class`, which is the same rule Find // References applies and the reason the two answer consistently. - let found = handlers::references::narrowed_to_the_cursors_class(&view, offset.get(), found); + let found = handlers::references::narrowed_to_the_cursors_class( + &view, + offset.get(), + found, + session.index(), + ); // **A declaration is not a definition, and this request is the one for definitions.** `class vector;` forward-declares the specialization `` then defines it, and both are candidates for the @@ -180,11 +185,13 @@ pub async fn on_goto_definition_handler( let mut ordered: Vec<(bool, Location)> = Vec::new(); for (at, declaration) in found.found.iter().enumerate() { - let Some(uri) = path_to_uri(&declaration.file) else { + let Some((file, fact)) = session.definition_parts(declaration) else { + continue; + }; + let Some(uri) = path_to_uri(&file) else { continue; }; - let range = - name_range(session, &declaration.file, &declaration.fact).unwrap_or_default(); + let range = name_range(session, &file, fact).unwrap_or_default(); ordered.push((Some(at) == chosen, Location { uri, range })); } // Stable, so everything that is not the chosen one keeps the order the index answered in. @@ -246,13 +253,14 @@ fn definition_of_a_documentation_link( // parentheses nor the bang is part of the name. let spelling = target.spelled_for_a_lookup(); if let Known::Yes(found) = session.index().definition(spelling, &view.path) { - let uri = path_to_uri(&found.file)?; - let declaring = session.files().held(&found.file)?; + let (file, fact) = session.definition_parts(&found)?; + let uri = path_to_uri(&file)?; + let declaring = session.files().held(&file)?; return Some(Location { uri, range: Range::new( - position_in_file(declaring, found.fact.name_range.start_offset)?, - position_in_file(declaring, found.fact.name_range.end_offset())?, + position_in_file(declaring, fact.name_range.start_offset)?, + position_in_file(declaring, fact.name_range.end_offset())?, ), }); } @@ -328,10 +336,23 @@ fn definitions_where_there_are_bodies( .found .iter() .map(|declaration| { - is_written_as_a_definition(session, &declaration.file, &declaration.fact) + session + .definition_parts(declaration) + .is_some_and(|(file, fact)| is_written_as_a_definition(session, &file, fact)) }) .collect(); + let describe = + |declaration: &ProjectDefinition| -> Option<(std::path::PathBuf, Option, String)> { + let file = session.definition_path(declaration)?; + let fact = session.definition_fact(declaration)?; + Some(( + file, + fact.scope.clone().map(|scope| scope.to_string()), + fact.name.to_string(), + )) + }; + // The groups that have one, and the ones that do not are left whole. let groups_with_a_body: std::collections::HashSet<( std::path::PathBuf, @@ -342,17 +363,7 @@ fn definitions_where_there_are_bodies( .iter() .zip(&written_as_a_definition) .filter(|(_, definition)| **definition) - .map(|(declaration, _)| { - ( - declaration.file.clone(), - declaration - .fact - .scope - .clone() - .map(|scope| scope.to_string()), - declaration.fact.name.to_string(), - ) - }) + .filter_map(|(declaration, _)| describe(declaration)) .collect(); if groups_with_a_body.is_empty() { return found; @@ -363,16 +374,8 @@ fn definitions_where_there_are_bodies( .into_iter() .zip(written_as_a_definition) .filter(|(declaration, definition)| { - let group = ( - declaration.file.clone(), - declaration - .fact - .scope - .clone() - .map(|scope| scope.to_string()), - declaration.fact.name.to_string(), - ); - !groups_with_a_body.contains(&group) || *definition + describe(declaration) + .is_none_or(|group| !groups_with_a_body.contains(&group) || *definition) }) .map(|(declaration, _)| declaration) .collect(); @@ -441,27 +444,40 @@ fn chosen_definition( if found.found.len() < 2 { return None; } - let parameter_lists: Vec> = found + // **Each declaration's parameters, structurally** — the facts resolved once through the index, which is also + // where the list-level `...` comes from. The resolver never sees a parameter list's text. + let parameters: Vec = found .found .iter() - .map(|declaration| declaration.fact.parameter_list().map(str::to_string)) + .map(|declaration| { + let Some(fact) = session.definition_fact(declaration) else { + return sema::overload::DeclaredParameters::default(); + }; + let Some(file) = session.definition_path(declaration) else { + return sema::overload::DeclaredParameters::default(); + }; + session.declared_parameters_of(&file, fact) + }) .collect(); let template_parameters: Vec> = found .found .iter() .map(|declaration| { + let Some(fact) = session.definition_fact(declaration) else { + return Vec::new(); + }; + let Some(file) = session.definition_path(declaration) else { + return Vec::new(); + }; session - .text(&declaration.file) + .text(file) .map(|text| { - sema::deduction::template_parameters_before( - &text, - declaration.fact.name_range.start_offset, - ) + sema::deduction::template_parameters_before(&text, fact.name_range.start_offset) }) .unwrap_or_default() }) .collect(); - session.the_declaration_a_call_means(view, offset, ¶meter_lists, &template_parameters) + session.the_declaration_a_call_means(view, offset, ¶meters, &template_parameters) } #[cfg(test)] @@ -559,10 +575,10 @@ class Promised; let written: Vec = kept .found .iter() - .map(|declaration| { - let text = session.text(&declaration.file).expect("held"); - text[declaration.fact.range.start_offset..declaration.fact.range.end_offset()] - .to_string() + .filter_map(|declaration| { + let (file, fact) = session.definition_parts(declaration)?; + let text = session.text(&file).expect("held"); + Some(text[fact.range.start_offset..fact.range.end_offset()].to_string()) }) .collect(); assert_eq!( diff --git a/crates/cpp_ls/src/handlers/document_highlight/mod.rs b/crates/cpp_ls/src/handlers/document_highlight/mod.rs index 278ff2ff..3ed96eb1 100644 --- a/crates/cpp_ls/src/handlers/document_highlight/mod.rs +++ b/crates/cpp_ls/src/handlers/document_highlight/mod.rs @@ -129,8 +129,11 @@ fn is_a_declaration_here( }; let normalized = file::paths::normalize_path(file, cfg!(windows)); defined.found.iter().any(|definition| { - file::paths::normalize_path(&definition.file, cfg!(windows)) == normalized - && definition.fact.name_range == range + let Some((declared_in, fact)) = session.definition_parts(definition) else { + return false; + }; + file::paths::normalize_path(&declared_in, cfg!(windows)) == normalized + && fact.name_range == range }) } /// Every occurrence of the local the cursor is on — or nothing when the cursor is not on one. diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 0d1b5897..6696ff0b 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -39,6 +39,7 @@ use cpp_code_analysis::HeaderTarget; use cpp_code_analysis::IncludeForm; use cpp_code_analysis::MacroFact; use cpp_code_analysis::ProjectDefinitions; +use cpp_code_analysis::ProjectIndex; use cpp_code_analysis::ProjectMember; use cpp_code_analysis::WrittenAttribute; use cpp_code_analysis::doc; @@ -47,8 +48,8 @@ use cpp_code_analysis::normalize_path; use cpp_code_analysis::sema; use cpp_code_analysis::session; use cpp_code_analysis::{ - DeclFact, DeclKind, DiskFiles, FactGuard, FileView, Known, ProjectDefinition, ProjectMacro, - Session, UnknownReason, + DeclFact, DeclKind, DeclaredType, DiskFiles, FactGuard, FileView, Known, ProjectDefinition, + ProjectMacro, Session, UnknownReason, }; use cpp_parser::CppDeclaration; use cpp_parser::CppDocComment; @@ -449,13 +450,14 @@ pub fn hover( && let Some(one) = found .found .iter() - .find(|one| one.fact.name_range.start_offset == in_the_file.get()) + .find(|one| { + session + .definition_fact(one) + .is_some_and(|fact| fact.name_range.start_offset == in_the_file.get()) + }) .or_else(|| found.found.first()) { - let definition = ProjectDefinition { - file: one.file.clone(), - fact: one.fact.clone(), - }; + let definition = one.clone(); return Some(markdown(declaration_markdown( session, view, @@ -827,8 +829,9 @@ fn hover_of_the_program( // **A declaration found for the *alias name* is not a declaration of its member.** The ordinary lookup // can resolve `Viewer` and hand back the alias itself when the member is dependent; say what the cursor // is on rather than leaving the reader with a card about a different name. - if found.fact.kind == DeclKind::Type - && found.fact.type_of.is_some() + if let Some(fact) = session.definition_fact(&found) + && fact.kind == DeclKind::Type + && fact.has_type_of() && let Some((member, alias)) = a_member_of_a_template_alias(view, offset) { card.push_str(&format!( @@ -851,8 +854,12 @@ fn hover_of_the_program( // `LuaLexer`'s and told the reader "which one a call means is decided by the arguments" — about a // **data member**, which has no arguments and no second reading. Find References and Go to Definition // narrow by the cursor's class; this is the same rule, at the same offset. - let found = - handlers::references::narrowed_to_the_cursors_class(view, offset.get(), found); + let found = handlers::references::narrowed_to_the_cursors_class( + view, + offset.get(), + found, + session.index(), + ); // **A class name is one declaration, not an overload set.** `LuaParser p(…)` hovers three facts — the // class and its two constructors, which are filed under the same name because a constructor's name is // its class's — and the answer listed the constructors as if a call were meant ("3 declarations … @@ -873,16 +880,21 @@ fn hover_of_the_program( if let Some(the_type) = found .found .iter() - .filter(|definition| matches!(definition.fact.kind, DeclKind::Type)) + .filter(|definition| { + session + .definition_fact(definition) + .is_some_and(|fact| matches!(fact.kind, DeclKind::Type)) + }) .max_by_key(|definition| { // **More template parameters is the more general declaration** — `fact.parameters()` is the // template head's own names, and it is what says which fact a partial specialization is: // the primary's are `[_Tp, _Alloc]`, `vector`'s are `[_Alloc]`, and a forward // declaration's are the empty names of `template `. (`pattern` is `None` // for all three here, so it cannot separate them — measured, not assumed.) + let fact = session.definition_fact(definition); ( - definition.fact.definition, - definition.fact.parameters().len(), + fact.is_some_and(|fact| fact.definition), + fact.map_or(0, |fact| fact.parameters().len()), ) }) { @@ -917,8 +929,21 @@ fn hover_of_the_program( // member list, substituted; without this the hover had **no content at all** for the call (reported, with a // screenshot of an empty popup). Known::No | Known::Unknown(_) => { - match session.member_of_the_enclosing_class(view, offset) { - Some(found) => Some(markdown(declaration_markdown(session, view, &found, None))), + match session.member_row_of_the_enclosing_class(view, offset) { + Some(row) => { + let found = ProjectDefinition { + file: row.fact.file, + fact: row.fact, + }; + let shown = session.index().member_display_fact(&row); + Some(markdown(declaration_markdown_with( + session, + view, + &found, + shown.as_ref(), + None, + ))) + } // The cursor may still be *in* something the analysis can type — `this`, `*p`, `f(1)` — which is a // different question about the same position, and the one a reader on a keyword is asking. None => expression_markdown(session, view, offset).map(markdown), @@ -999,18 +1024,32 @@ fn dependent_alias_member_markdown( return None; }; let alias = definitions.found.iter().find(|definition| { - definition.fact.kind == DeclKind::Type && definition.fact.type_of.is_some() + session + .definition_fact(definition) + .is_some_and(|fact| fact.kind == DeclKind::Type && fact.has_type_of()) })?; + let alias_fact = session.definition_fact(alias)?; // **The instantiated half.** `Viewer = Wrapper` with the default substituted gives `Wrapper`; an alias // chain such as `Text::StrV` is followed by the index's alias walk before the member is asked. The declaration // is then `Wrapper::Type`, which the index can answer without a C++ evaluator. - let target = alias.fact.type_of.as_deref().unwrap_or("its target"); + let target_spelling = session.index().type_spelling_of(alias_fact); + let target = target_spelling.as_deref().unwrap_or("its target"); + let parameters: Vec = alias_fact + .parameters() + .iter() + .map(ToString::to_string) + .collect(); + let defaults: Vec = alias_fact + .parameter_defaults() + .iter() + .map(ToString::to_string) + .collect(); let substituted = sema::types::substituted_spelling_with_defaults( target, - alias.fact.parameters(), - alias.fact.parameter_defaults(), - &[], + ¶meters, + &defaults, + &[] as &[String], ); if let Some(class) = the_class_an_alias_target_names(session, view, &substituted) && let Known::Yes(found) = session @@ -1089,7 +1128,10 @@ fn member_markdown( // the card said "the type of `ci_func(ci)` is not known here" beside a member the project's own headers // declare. The rendering holds the expansion, and the chain types there. The card still spells the object the // way the **file** writes it — the expansion is a compiler's text, not the reader's. - _ => session.the_type_of_an_expression_in_the_rendering(&view.path, &access.object), + _ if expression_contains_a_macro_call(&access.object) => { + session.the_type_of_an_expression_in_the_rendering(&view.path, &access.object) + } + _ => None, }; // **A generic lambda's parameter is narrowed by the `if constexpr` around it** — `std::visit([](auto const& // value) { if constexpr (std::is_same_v) { … value.radius … } }, shape)`. The parameter has no type of @@ -1106,6 +1148,7 @@ fn member_markdown( access.member, access.member ); }; + let found_type = found.type_value.clone(); let written = found.type_of; // **An arrow reaches the pointee's members**, and the completion already says so (`the_class_after_the_operator`): // `ptr->c_str` on a `std::shared_ptr` is `std::string`'s `c_str`, and asking `members_of` about the @@ -1129,12 +1172,23 @@ fn member_markdown( // `std::string` (measured). The written type is the one whose arguments are known, and `members_of` substitutes // them; the arrow's class is the fallback for a member the handle does not have (`ptr->twin` on a // `shared_ptr`), which is why it is still asked. - for class in std::iter::once(&written).chain(reached.iter()) { - if let Known::Yes(candidates) = session.members_of(view, class) { + let own = found_type + .as_ref() + .map(|class| session.members_of_type(view, class)); + for candidates in own + .into_iter() + .chain(std::iter::once_with(|| session.members_of(view, &written))) + .chain( + reached + .iter() + .map(|class| session.members_of_type(view, class)), + ) + { + if let Known::Yes(candidates) = candidates { if candidates .members .iter() - .any(|member| member.fact.name == access.member) + .any(|member| session.index().member_name(member) == access.member) { list = Some(candidates); break; @@ -1175,12 +1229,12 @@ fn member_markdown( .filter(|raw| { raw.members .iter() - .any(|member| member.fact.name == access.member) + .any(|member| session.index().member_name(member) == access.member) }) .map_or(&list.members, |raw| &raw.members); let candidates: Vec<&ProjectMember> = members .iter() - .filter(|member| member.fact.name == access.member) + .filter(|member| session.index().member_name(member) == access.member) .collect(); // **Which of them this call can reach**, when the cursor is on one. Members are where a reader meets an overload set @@ -1189,19 +1243,34 @@ fn member_markdown( // `parameter_list` spellings. let call_selected: Option> = (candidates.len() > 1) .then(|| { - let parameter_lists: Vec> = candidates + // **Each candidate's parameters, structurally** — resolved through the index, so the resolver is handed + // types rather than the declaration's spelling. + let parameters: Vec = candidates .iter() - .map(|candidate| candidate.fact.parameter_list().map(str::to_string)) + .map(|candidate| { + let Some(fact) = session.index().member_fact(candidate) else { + return sema::overload::DeclaredParameters::default(); + }; + let Some(file) = session.index().member_path(candidate) else { + return sema::overload::DeclaredParameters::default(); + }; + session.declared_parameters_of(file, fact) + }) .collect(); let template_parameters: Vec> = candidates .iter() .map(|candidate| { session - .text(&candidate.file) + .index() + .member_path(candidate) + .and_then(|path| session.text(path)) .map(|text| { sema::deduction::template_parameters_before( &text, - candidate.fact.name_range.start_offset, + session + .index() + .member_fact(candidate) + .map_or(0, |fact| fact.name_range.start_offset), ) }) .unwrap_or_default() @@ -1210,7 +1279,7 @@ fn member_markdown( session.the_declarations_a_call_means( view, file::coordinates::ReadingOffset::new(access.member_range.start_offset), - ¶meter_lists, + ¶meters, &template_parameters, ) }) @@ -1224,10 +1293,11 @@ fn member_markdown( && let Some(member) = candidates.get(selected[0]) { let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: member.fact.file, + fact: member.fact, }; - return declaration_markdown(session, view, &definition, None); + let shown = session.index().member_display_fact(member); + return declaration_markdown_with(session, view, &definition, shown.as_ref(), None); } // **Several can take the call, or the cursor is not on one** — print what the call can reach, or all of them. @@ -1258,7 +1328,12 @@ fn member_markdown( let const_ones: Vec<&ProjectMember> = shown .iter() .copied() - .filter(|candidate| candidate.fact.modifiers.contains(DeclModifiers::CONST)) + .filter(|candidate| { + session + .index() + .member_modifiers(candidate) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::CONST)) + }) .collect(); // **Only when one is left**: a class that declares no `const` overload at all (`std::list::remove`) is a // member no `const` object can call, and that is a *finding* about the code rather than a reason to empty the @@ -1271,21 +1346,31 @@ fn member_markdown( && let Some(member) = shown.first() { let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: member.fact.file, + fact: member.fact, }; - return declaration_markdown(session, view, &definition, None); + let displayed = session.index().member_display_fact(member); + return declaration_markdown_with(session, view, &definition, displayed.as_ref(), None); } if shown.len() > 1 { let mut out = String::from("```cpp\n"); for candidate in &shown { - out.push_str(&a_line(&candidate.fact)); + let Some(fact) = session.index().member_display_fact(candidate) else { + continue; + }; + out.push_str(&a_line(session, &fact)); out.push('\n'); } out.push_str("```\n\n"); let scope = shown .iter() - .find_map(|candidate| candidate.fact.scope.clone().map(|scope| scope.to_string())) + .find_map(|candidate| { + session + .index() + .member_fact(candidate) + .and_then(|fact| fact.scope.as_ref()) + .map(ToString::to_string) + }) .unwrap_or_else(|| written.clone()); let sentence = if call_selected.is_some() { format!( @@ -1310,7 +1395,7 @@ fn member_markdown( let Some(member) = candidates.first().copied().or_else(|| { list.members .iter() - .find(|member| member.fact.name == access.member) + .find(|member| session.index().member_name(member) == access.member) }) else { // **A member written through a macro is not a missing member**, and this is C's ordinary way of renaming a // field: neovim writes `#define b_fnum handle` *inside* `struct file_buffer`, so `buf->b_fnum` is @@ -1335,10 +1420,11 @@ fn member_markdown( }; let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: member.fact.file, + fact: member.fact, }; - declaration_markdown(session, view, &definition, None) + let displayed = session.index().member_display_fact(member); + declaration_markdown_with(session, view, &definition, displayed.as_ref(), None) } /// **Every declaration of one name**, as one popup — what a hover says about an overloaded function. @@ -1368,22 +1454,39 @@ fn overloads_markdown( // declarations of `basic_string::append`, several of which cannot accept one argument at all — a page about a call // that cannot be that call. let call_selected: Option> = view.and_then(|view| { - let parameter_lists: Vec> = found + // **The declarations' parameters, structurally.** The resolver takes types, so each declaration's facts are + // resolved once through the index — `declared_parameters_of` also says whether the list ends in `...` — and + // nothing here reads a parameter list's text. + let parameters: Vec = found .found .iter() - .map(|declaration| declaration.fact.parameter_list().map(str::to_string)) + .map(|declaration| { + let Some(fact) = session.definition_fact(declaration) else { + return sema::overload::DeclaredParameters::default(); + }; + let Some(file) = session.definition_path(declaration) else { + return sema::overload::DeclaredParameters::default(); + }; + session.declared_parameters_of(&file, fact) + }) .collect(); // One `text` read per declaration, and the files are held afterwards. let template_parameters: Vec> = found .found .iter() .map(|declaration| { + let Some(fact) = session.definition_fact(declaration) else { + return Vec::new(); + }; + let Some(file) = session.definition_path(declaration) else { + return Vec::new(); + }; session - .text(&declaration.file) + .text(file) .map(|text| { sema::deduction::template_parameters_before( &text, - declaration.fact.name_range.start_offset, + fact.name_range.start_offset, ) }) .unwrap_or_default() @@ -1393,7 +1496,7 @@ fn overloads_markdown( let selected = session.the_declarations_a_call_means( view, offset, - ¶meter_lists, + ¶meters, &template_parameters, )?; (!selected.is_empty()).then_some(selected) @@ -1422,43 +1525,50 @@ fn overloads_markdown( for index in &shown { let declaration = &found.found[*index]; let is_the_one = chosen_index == Some(*index); + let Some(declaration_fact) = session.definition_fact(declaration) else { + continue; + }; + let Some(declaration_file) = session.definition_path(declaration) else { + continue; + }; // **A declaration the file's own text splits across a directive has no written type** — see // [`DeclFact::split_by_a_directive`]. The handler holds the session, so it asks the reading where the // directive is *resolved*: `bits/stl_bvector.h` writes `emplace_back` returning `reference` under // `#if __cplusplus > 201402L` and `void` under `#else`, and only the rendering knows which one this // compilation means. - let mut fact = declaration.fact.clone(); + let mut fact = declaration_fact.clone(); if fact.split_by_a_directive && let Some(read) = session.fact_from_the_rendering( - &declaration.file, + &declaration_file, &fact.name, fact.scope.as_deref(), ) { - fact.returns = read.returns; - fact.type_of = read.type_of; + // **The rendering's facts are synthesized**, so they carry computed types rather than handles into a + // table this copy could not resolve. Adopting them clears the stale handles — see + // [`DeclFact::use_the_types_of`]. + fact.use_the_types_of(&read); } - let mut line = a_line(&fact); + let mut line = a_line(session, &fact); if is_the_one && let Some(view) = view - && let Some(text) = session.text(&declaration.file) + && let Some(text) = session.text(&declaration_file) { // **The instantiated spelling, when the call fixes it.** `take(T* value)` is what the declaration says and // `take(int* value)` is what this call means; a reader who sees only the first cannot tell that the analysis - // deduced anything. The substitution is whole-word (`types::substituted_spelling`), so `T` does not reach - // into `Trait`. + // deduced anything. The deduction is structural — the declaration's parameter **types**, resolved from its + // facts, and the call's argument types — and only the substituted line is text, because the card prints it. let names = sema::deduction::template_parameters_before( &text, - declaration.fact.name_range.start_offset, + declaration_fact.name_range.start_offset, ); - let (parameters, _) = declaration - .fact - .parameter_list() - .map(sema::overload::parameters_in) - .unwrap_or_default(); + let parameters = session + .index() + .parameter_types_of(&declaration_file, declaration_fact); if let Some(arguments) = session.the_deduced_arguments(view, offset, &names, ¶meters) { + let arguments: Vec = arguments.iter().map(ToString::to_string).collect(); line = sema::types::substituted_spelling(&line, &names, &arguments); } } @@ -1479,7 +1589,10 @@ fn overloads_markdown( // **The file a reader is sent to** is the declaration the card is about: the one the call selects when it selects // one, and the first declaration otherwise. let first = &found.found[chosen_index.unwrap_or(0)]; - let qualified = first.fact.qualified_name(); + let first_fact = session.definition_fact(first); + let qualified = first_fact + .map(|fact| fact.qualified_name()) + .unwrap_or_default(); let distinct = shown_lines .iter() .map(|line| line.trim_start_matches("→ ").trim_start_matches(" ")) @@ -1521,18 +1634,21 @@ fn overloads_markdown( )); } - let files: std::collections::BTreeSet<&std::path::Path> = found + let files: std::collections::BTreeSet = found .found .iter() - .map(|declaration| declaration.file.as_path()) + .filter_map(|declaration| session.definition_path(declaration)) .collect(); + let first_file = session.definition_path(first); out.push_str(&format!( "\nDeclared in {}", where_clause( session, view, - first.file.as_path(), - first.fact.name_range.start_offset + first_file + .as_deref() + .unwrap_or_else(|| std::path::Path::new("")), + first_fact.map_or(0, |fact| fact.name_range.start_offset) ) )); if files.len() > 1 { @@ -1692,9 +1808,67 @@ fn is_a_specifier_word(word: &str) -> bool { /// **The declaration's line, rebuilt** — the renderer's single-line form, for a card or an overload list. /// /// The type writer and the parameter parser live in [`cpp_code_analysis::sema::render`], so a line printed in a list and -/// the same line printed above a card are the same line, generated the same way. -fn a_line(fact: &DeclFact) -> String { - sema::render::a_line(fact, None, None) +/// the same line printed above a card are the same line, generated the same way. The two type spellings are asked of +/// the index: a stored fact's handle is printed from the store, a synthesized fact's computed value is printed directly. +fn a_line(session: &Session, fact: &DeclFact) -> String { + let index = session.index(); + sema::render::a_line_with( + fact, + None, + None, + &|fact| { + index + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, + &|fact| { + index + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, + ) +} + +/// Does this expression contain a macro invocation? See the session's matching helper; the hover fallback into +/// the rendering is for those expressions only. +fn expression_contains_a_macro_call(expression: &CppSyntaxNode) -> bool { + CppSyntaxKind::from(expression.kind()) == CppSyntaxKind::MacroCall + || expression + .descendants() + .any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::MacroCall) +} + +/// **A fact's type as the card prints it** — the stored handle printed from the index's store, or the synthesized +/// value printed directly. This is the display edge; nothing is parsed. +fn shown_type_of(index: &ProjectIndex, fact: &DeclFact) -> Option { + index + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()) +} + +/// [`shown_type_of`] for a function's return type. +fn shown_returns_of(index: &ProjectIndex, fact: &DeclFact) -> Option { + index + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) +} + +/// **Replace a display copy's type with a spelling produced here** — a deduced type, a macro-stripped one, a type with +/// the declaration's qualifiers put back. +/// +/// The copy is synthesized for one card and has no arena to hold a handle, so the spelling is parsed **once, at this +/// edge**, into the computation-layer value the rest of the path reads. No store is minted for it. +fn set_the_written_type(fact: &mut DeclFact, written: String) { + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(sema::types::parse_type_spelling( + &written, + ))); +} + +/// [`set_the_written_type`] for a function's return type. +fn set_the_written_returns(fact: &mut DeclFact, written: String) { + fact.returns = DeclaredType::Computed(std::sync::Arc::new(sema::types::parse_type_spelling( + &written, + ))); } pub(crate) fn markdown(value: String) -> Hover { @@ -1975,6 +2149,31 @@ fn declaration_markdown( found: &ProjectDefinition, written: Option<&str>, ) -> String { + declaration_markdown_with(session, view, found, None, written) +} + +/// The same card, with an **already-substituted fact** when the caller has one. +/// +/// A [`ProjectDefinition`] is a reference to the declaration's own arena entry, which is the unsubstituted spelling +/// (`std::optional`); a member accessed through `Box` is `std::optional`, and that fact exists only in the +/// member list. Display is where the substitution is allowed to be materialized — the same reason a `ComputedType` is. +fn declaration_markdown_with( + session: &Session, + view: &FileView, + found: &ProjectDefinition, + substituted: Option<&DeclFact>, + written: Option<&str>, +) -> String { + let Some(found_fact) = substituted + .cloned() + .or_else(|| session.definition_fact(found).cloned()) + else { + return code_block("the answer does not resolve through the index"); + }; + let Some(found_file) = session.definition_path(found) else { + return code_block("the answer names a file the index does not hold"); + }; + let found_fact = &found_fact; // **A return type read as a macro's name is corrected here.** `wincon.h` writes // // ```c @@ -2019,11 +2218,8 @@ fn declaration_markdown( // `std::vector`'s card was a forward declaration in `` and then the `vector` // specialization, never the definition the hover had just selected (`CPPLS_TRACE_HOVER=1` shows // `[card] heard vector … => indexed stl_bvector.h:vector`). See `docs/worklog.md`. - let indexed = if !found.fact.local - && !matches!( - found.fact.kind, - DeclKind::Type | DeclKind::Namespace - ) + let indexed = if !found_fact.local + && !matches!(found_fact.kind, DeclKind::Type | DeclKind::Namespace) // **Nothing to render at all**, which is what a *binding* leaves behind: a binding is a place to jump to and // carries no type, no return type, no parameter list and no annotation. // @@ -2035,25 +2231,33 @@ fn declaration_markdown( // whose `Box` arguments had already been substituted through it. Measured: `members_of("Box")` // answered `returns: Some("std::optional")`, and the card printed `std::optional` because of this // `||`. A conjunction asks exactly the question the comment asks — "does this fact have nothing at all". - && found.fact.type_of.is_none() - && found.fact.returns.is_none() - && found.fact.parameter_list().is_none() - && found.fact.reflection().is_none() + && !found_fact.has_type_of() + && !found_fact.has_returns() + && found_fact.parameter_list().is_none() + && found_fact.reflection().is_none() { session .index() - .definition(&found.fact.qualified_name(), &found.file) + .definition(&found_fact.qualified_name(), &found_file) .value() } else { None }; - let found = match &indexed { - Some(indexed) => indexed, - None => found, + let (found_file, found_fact) = match &indexed { + Some(indexed) => ( + session + .definition_path(indexed) + .unwrap_or_else(|| found_file.clone()), + session + .definition_fact(indexed) + .cloned() + .unwrap_or_else(|| found_fact.clone()), + ), + None => (found_file, found_fact.clone()), }; - let mut corrected = found.fact.clone(); + let mut corrected = found_fact.clone(); // **A binding is a place to jump to, and the card is about the declaration.** `definitions` answers a *binding* // while the file's summary is still being built — the first hover after a file is opened — and a binding records // no return type and no parameter list, so the card printed `name_of(…)`: a signature with the two things a @@ -2069,14 +2273,14 @@ fn declaration_markdown( // `clean` and its guard, and read "a type template over `_Ty`, `_Alloc`" beside two warnings about a conditional // block and a parse recovery that the cooked reading does not have (measured: `vector` cooked reports **0** // errors). A class is exactly the fact the index holds best; nothing here can complete it. - if corrected.type_of.is_none() - && corrected.returns.is_none() + if !corrected.has_type_of() + && !corrected.has_returns() && corrected.parameter_list().is_none() && !(corrected.definition && matches!(corrected.kind, DeclKind::Type | DeclKind::Namespace)) - && let Some(the_view) = if found.file == view.path { + && let Some(the_view) = if found_file == view.path { Some(view.clone()) } else { - session.view_of_the_file(&found.file) + session.view_of_the_file(&found_file) } && let Some(complete) = session .facts_of_the_view(&the_view) @@ -2096,31 +2300,35 @@ fn declaration_markdown( // // The spelling replaces the written one **whole**: the deduced type already carries the `&` (or `&&`) that the // declarator writes, so nothing is appended beside it and nothing of `auto` is kept. + let written_type = shown_type_of(session.index(), &corrected); if matches!(corrected.kind, DeclKind::Variable) - && corrected.type_of.as_deref().is_none_or(|written| { + && written_type.as_deref().is_none_or(|written| { sema::types::is_a_deduced_type(written) || is_a_structured_binding_type(written) }) - && is_the_viewed_file(view, &found.file) + && is_the_viewed_file(view, &found_file) && let Known::Yes(deduced) = session.type_at( view, file::coordinates::ReadingOffset::new(corrected.name_range.start_offset), ) + // **An empty type is "no answer", not `void`.** A declaration whose type has no spelling — an anonymous + // struct's variable — reaches this point with the empty `ComputedType`, and parsing that spelling is the one + // way this layer can turn "nothing was written" into the *type* `void`. + && !deduced.type_of.trim().is_empty() { // **The reference belongs to the binding, not to the element type.** `type_at` decomposes the pattern to the // element (`const std::string`); the `&` in `const auto& [key, value]` is still what the name denotes. - let reference = - structured_binding_reference(corrected.type_of.as_deref().unwrap_or_default()); + let reference = structured_binding_reference(written_type.as_deref().unwrap_or_default()); let deduced = if reference.is_empty() || deduced.type_of.ends_with('&') { deduced.type_of } else { format!("{}{reference}", deduced.type_of) }; - corrected.type_of = Some(deduced.into()); + set_the_written_type(&mut corrected, deduced); } - if let Some(returns) = corrected.returns.clone() - && let Some(better) = the_type_the_macros_leave(session, &found.file, &corrected, &returns) + if let Some(returns) = shown_returns_of(session.index(), &corrected) + && let Some(better) = the_type_the_macros_leave(session, &found_file, &corrected, &returns) { - corrected.returns = Some(better.into()); + set_the_written_returns(&mut corrected, better); } // **The annotation the file writes, when the index has not recorded it yet.** `UCLASS(Blueprintable)` is read into // the fact from the file's text, and the summary that holds it is built by the pump — a hover can arrive first. @@ -2128,7 +2336,7 @@ fn declaration_markdown( // the summary would hold, so the card reads them rather than showing a class with no annotation. if corrected.reflection().is_none() && let Some(facts) = session - .view_of_the_file(&found.file) + .view_of_the_file(&found_file) .map(|view| session.facts_of_the_view(&view)) && let Some(the_files) = facts .iter() @@ -2158,12 +2366,13 @@ fn declaration_markdown( && let Known::Yes(list) = session.members_of(view, class) && let Some(the_member) = list.members.iter().find(|member| { member.depth == 0 - && member.fact.name == fact.name - && member.fact.kind == DeclKind::Function + && session.index().member_name(member) == fact.name + && session.index().member_kind(member) == Some(DeclKind::Function) }) - && the_member.fact.returns.is_some() + && let Some(displayed) = session.index().member_display_fact(the_member) + && displayed.has_returns() { - *fact = the_member.fact.clone(); + *fact = displayed; } let mut out = String::new(); @@ -2205,13 +2414,13 @@ fn declaration_markdown( // passing them to the cursor's view found another enumerator's body — neovim's `EVENT_BUFADD` (= 0) was drawn // as `= 3` from whatever declaration happened to sit at that offset in `buffer.c`. let enumerator = session - .view_of_the_file(&found.file) + .view_of_the_file(&found_file) .and_then(|declaring_view| enumerator_value(&declaring_view, fact.name_range.start_offset)); // **The value is folded in the unit where the declaration is read**, not in the file the cursor happens to be // in: a header's `UCHAR_MAX` comes from ``, which the header itself need not include — every `.cpp` that // includes it does. See [`cpp_code_analysis::Session::constant_value_of_a_declaration`]. let constant_value = enumerator.or_else(|| { - session.constant_value_of_a_declaration(&found.file, fact.name_range, &view.path) + session.constant_value_of_a_declaration(&found_file, fact.name_range, &view.path) }); // **The code block is generated from the model** — see [`cpp_code_analysis::sema::render`]. Not the declaration's @@ -2243,7 +2452,7 @@ fn declaration_markdown( let annotations = if fact.local { Vec::new() } else { - session.the_attributes_before_a_declaration(&found.file, fact.range.start_offset) + session.the_attributes_before_a_declaration(&found_file, fact.range.start_offset) }; let (attributes, specifiers) = the_annotations_as_the_card_shows_them(&annotations); // **The declaration's node, from the name when the range starts before it.** A typedef's fact starts at its @@ -2251,8 +2460,8 @@ fn declaration_markdown( // start found no declaration at all, so `an_item` got no syntax and a typedef of a class rendered as // `using T = T;`. The name's own offset is inside the `TypedefDecl` both spellings share. let node = session - .the_declaration_node(&found.file, fact.range.start_offset) - .or_else(|| session.the_declaration_node(&found.file, fact.name_range.start_offset)); + .the_declaration_node(&found_file, fact.range.start_offset) + .or_else(|| session.the_declaration_node(&found_file, fact.name_range.start_offset)); // **The qualifiers a declaration keeps in its own specifier sequence.** They are not in the fact: `type_of` is a // name for lookup and drops the specifier words on purpose (`static const Widget` records `Widget`, so a lookup by // name finds the class). The node has them, and it is the *parameter's* node here even for a parameter — the @@ -2272,14 +2481,12 @@ fn declaration_markdown( if matches!(fact.kind, DeclKind::Variable) && let Some(qualifiers) = Some(sema::render::the_qualifiers_of_node(node.as_ref())) .filter(|qualifiers| !qualifiers.is_empty()) - && let Some(written) = fact - .type_of - .clone() - .filter(|written| !written.trim().is_empty()) + && let Some(written) = + shown_type_of(session.index(), fact).filter(|written| !written.trim().is_empty()) && !written.starts_with("const") && !written.starts_with("volatile") { - fact.type_of = Some(format!("{qualifiers}{written}").into()); + set_the_written_type(fact, format!("{qualifiers}{written}")); } let the_declaration = node.as_ref().and_then(|node| { use cpp_parser::CppAstNode as _; @@ -2290,7 +2497,23 @@ fn declaration_markdown( // typedef of a class rendered as `using T = T;` — the self-alias the ancestor can explain. .or_else(|| node.ancestors().find_map(CppDeclaration::cast)) }); - let mut declaration = sema::render::an_item(fact, the_declaration.as_ref(), constant_value); + let mut declaration = sema::render::an_item_with( + fact, + the_declaration.as_ref(), + constant_value, + &|fact| { + session + .index() + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, + &|fact| { + session + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, + ); if !attributes.is_empty() { declaration.insert(0, attributes.join(" ")); } @@ -2301,7 +2524,7 @@ fn declaration_markdown( // **A word the line already carries is not repeated.** A declaration written `inline NESTED int f()` renders // with its `inline` from the fact and would get a second one from the macro's expansion. let mut fresh: Vec<&str> = Vec::new(); - for specifier in specifiers.iter().map(String::as_str) { + for specifier in specifiers.iter().map(|specifier| specifier.as_str()) { if fresh.contains(&specifier) || line.split_whitespace().any(|word| word == specifier) { continue; } @@ -2332,7 +2555,15 @@ fn declaration_markdown( qualified, fact.scope.as_deref().unwrap_or("(an anonymous enum)") )), - None => out.push_str(&format!("\n`{}` — {}\n", qualified, kind_words(fact))), + None => { + let written_type = shown_type_of(session.index(), fact); + let written_returns = shown_returns_of(session.index(), fact); + out.push_str(&format!( + "\n`{}` — {}\n", + qualified, + kind_words(fact, written_type.as_deref(), written_returns.as_deref()) + )); + } } // **A variable whose type is deduced from an initializer that could not be typed** — say why, rather than @@ -2340,12 +2571,12 @@ fn declaration_markdown( // exactly this: the card said "a variable" and nothing else, and the reason the analysis had — `std::format` is // declared more than once in what this file can see, with nothing choosing between the declarations — was never // shown. The sentence is the analysis's own (`UnknownReason::describe`), not a second opinion. + let written_type = shown_type_of(session.index(), fact); if matches!(fact.kind, DeclKind::Variable) - && fact - .type_of + && written_type .as_deref() .is_none_or(|written| written == "auto") - && is_the_viewed_file(view, &found.file) + && is_the_viewed_file(view, &found_file) && let Known::Unknown(reason) = session.type_at( view, file::coordinates::ReadingOffset::new(fact.name_range.start_offset), @@ -2369,7 +2600,7 @@ fn declaration_markdown( // The comment the file writes above the declaration, in the place clangd and the C++ extension put it: after // the signature, before where it was declared from. if let Some(documentation) = - documentation_of_a_fact(session, view, &found.file, fact.range.start_offset) + documentation_of_a_fact(session, view, &found_file, fact.range.start_offset) { out.push_str(&format!("\n{documentation}\n")); } @@ -2379,7 +2610,7 @@ fn declaration_markdown( where_clause( session, Some(view), - &found.file, + &found_file, fact.name_range.start_offset ) )); @@ -2891,7 +3122,11 @@ fn an_integer(text: &str) -> Option { i64::from_str_radix(digits, radix).ok() } -fn kind_words(fact: &DeclFact) -> String { +fn kind_words( + fact: &DeclFact, + written_type: Option<&str>, + written_returns: Option<&str>, +) -> String { let kind = match fact.kind { DeclKind::Type => "a type", DeclKind::Function => "a function", @@ -2916,7 +3151,7 @@ fn kind_words(fact: &DeclFact) -> String { .parameters() .iter() .filter(|name| !name.is_empty()) - .map(String::as_str) + .map(|name| name.as_str()) .collect(); // **Only when the declaration is the template.** A *member* of a class template carries the class's parameters in // this field — the member-list builder fills them so a use's arguments can be paired — so printing them as the @@ -2941,10 +3176,10 @@ fn kind_words(fact: &DeclFact) -> String { // `a_type` parses the spelling and prints it from the model, so the qualifiers, the references and the arguments // come out the way every other type in the card does. `const char * const` → `const char*` is the same normalization // the card has had since the renderer landed. - match (&fact.type_of, &fact.returns) { + match (written_type, written_returns) { // **A typedef of a class records its own name as its type**, so "a type of type `T`" said nothing that the // code block does not say better. The alias's target is only prose when it is a different spelling. - (Some(written), _) if written.trim() != fact.name => { + (Some(written), _) if written.trim() != fact.name.as_str() => { words.push_str(&format!(" of type `{}`", sema::render::a_type(written))) } (Some(_), _) => {} @@ -3297,24 +3532,29 @@ mod tests { }) .expect("the declaration") .clone(); + let written_returns = session + .index() + .returns_spelling_of(&fact) + .map(|spelled| spelled.to_string()); let corrected = the_type_the_macros_leave( &session, std::path::Path::new("/p/wincon.h"), &fact, - fact.returns.as_deref().unwrap_or_default(), + written_returns.as_deref().unwrap_or_default(), ); assert_eq!( corrected.as_deref(), Some("WINBOOL"), - "the two macro names drop out and the type that is left is `WINBOOL` (the fact said {:?})", - fact.returns + "the two macro names drop out and the type that is left is `WINBOOL` (the fact said {written_returns:?})" ); // **And a name that is not a macro is left alone.** `std::size_t` has no definers, so the card keeps the - // fact's spelling rather than reconstructing anything. + // fact's spelling rather than reconstructing anything. The fixture is a display copy, which has no arena, so + // its return type is the computed value — exactly the shape `set_the_written_returns` produces. let other = DeclFact { - enumerator: false, - returns: Some("std::size_t".into()), + returns: DeclaredType::Computed(std::sync::Arc::new(sema::types::parse_type_spelling( + "std::size_t", + ))), ..fact.clone() }; assert_eq!( diff --git a/crates/cpp_ls/src/handlers/implementation/mod.rs b/crates/cpp_ls/src/handlers/implementation/mod.rs index ee3efc1e..8fe7ecd7 100644 --- a/crates/cpp_ls/src/handlers/implementation/mod.rs +++ b/crates/cpp_ls/src/handlers/implementation/mod.rs @@ -66,7 +66,10 @@ pub async fn on_goto_implementation( let Known::Yes(defined) = session.definitions(&view, offset) else { return None; }; - let name = defined.found.first()?.fact.name.clone(); + let name = session + .definition_fact(defined.found.first()?)? + .name + .clone(); // **The body, then the overrides.** A cursor on a declaration is asking "where is the code"; a cursor on a // base class or a virtual member is asking "what implements this". Both are answered, the definition first @@ -126,8 +129,10 @@ pub fn definitions_of( let mut wanted: Vec<(String, Option)> = found .found .iter() - .filter(|definition| definition.fact.kind == DeclKind::Function) - .map(|definition| (definition.fact.name.to_string(), owner.clone())) + .filter_map(|definition| { + let fact = session.definition_fact(definition)?; + (fact.kind == DeclKind::Function).then(|| (fact.name.to_string(), owner.clone())) + }) .collect(); wanted.sort(); wanted.dedup(); diff --git a/crates/cpp_ls/src/handlers/references/mod.rs b/crates/cpp_ls/src/handlers/references/mod.rs index e2bd94d6..2e25de3b 100644 --- a/crates/cpp_ls/src/handlers/references/mod.rs +++ b/crates/cpp_ls/src/handlers/references/mod.rs @@ -98,12 +98,8 @@ pub async fn on_references( match session.definitions(&written, in_the_file) { Known::Yes(defined) => { let first = defined.found.first()?; - let places = places_of( - session, - &first.fact, - first.file.clone(), - include_declaration, - ); + let (first_file, first_fact) = session.definition_parts(first)?; + let places = places_of(session, first_fact, first_file, include_declaration); let Known::Yes(places) = places else { return None; }; @@ -671,11 +667,14 @@ pub fn name_level_offsets( let Some(first) = defined.found.first() else { return Vec::new(); }; - let name = first.fact.name.clone(); + let Some(first_fact) = session.definition_fact(first) else { + return Vec::new(); + }; + let name = first_fact.name.clone(); // **The class the cursor is in**, which is what says *which* of the declarations is meant. let owner = the_class_the_cursor_is_in(&view.scopes, &view.root, offset.get()); - let defined = narrowed_to_the_cursors_class(view, offset.get(), defined); + let defined = narrowed_to_the_cursors_class(view, offset.get(), defined, session.index()); let aimed: Vec<&ProjectDefinition> = defined.found.iter().collect(); // **A local's rename stays inside its own function.** A local, a parameter and a range-`for` variable are names @@ -704,25 +703,36 @@ pub fn name_level_offsets( // **The declaration's own entry in that table is the test.** A file-scope variable is not in it — the table is // about names a function body owns — so a global keeps the name path below, where the index decides. let target_is_a_local = aimed.iter().any(|definition| { - definition.file == view.path - && locals_here - .iter() - .any(|entry| entry.declared_at as usize == definition.fact.name_range.start_offset) + session + .definition_parts(definition) + .is_some_and(|(file, fact)| { + file == view.path + && locals_here + .iter() + .any(|entry| entry.declared_at as usize == fact.name_range.start_offset) + }) }); if target_is_a_local { let length = aimed .first() - .map(|definition| definition.fact.name_range.length) + .and_then(|definition| session.definition_fact(definition)) + .map(|fact| fact.name_range.length) .unwrap_or(0); let mut found: Vec<(std::path::PathBuf, SourceRange)> = Vec::new(); if include_declaration { for definition in &aimed { - found.push((definition.file.clone(), definition.fact.name_range)); + if let Some((file, fact)) = session.definition_parts(definition) { + found.push((file, fact.name_range)); + } } } for entry in locals_here { if !aimed.iter().any(|definition| { - definition.fact.name_range.start_offset == entry.declared_at as usize + session + .definition_parts(definition) + .is_some_and(|(_, fact)| { + fact.name_range.start_offset == entry.declared_at as usize + }) }) { continue; } @@ -737,7 +747,7 @@ pub fn name_level_offsets( let mut declaring: Vec = aimed .iter() - .map(|definition| definition.file.clone()) + .filter_map(|definition| session.definition_parts(definition).map(|(file, _)| file)) .collect(); declaring.sort(); declaring.dedup(); @@ -754,7 +764,9 @@ pub fn name_level_offsets( if include_declaration { for definition in &aimed { - push(&definition.file, definition.fact.name_range, &mut found); + if let Some((file, fact)) = session.definition_parts(definition) { + push(&file, fact.name_range, &mut found); + } } } @@ -960,6 +972,7 @@ pub(crate) fn narrowed_to_the_cursors_class( view: &FileView, offset: usize, found: ProjectDefinitions, + index: &cpp_code_analysis::ProjectIndex, ) -> ProjectDefinitions { let Some(class) = the_class_the_cursor_is_in(&view.scopes, &view.root, offset) else { return found; @@ -967,7 +980,11 @@ pub(crate) fn narrowed_to_the_cursors_class( let inside: Vec = found .found .iter() - .filter(|definition| definition.fact.scope.as_deref() == Some(class.as_str())) + .filter(|definition| { + index + .definition_fact(definition) + .is_some_and(|fact| fact.scope.as_deref() == Some(class.as_str())) + }) .cloned() .collect(); if inside.is_empty() { @@ -1006,7 +1023,13 @@ fn an_occurrence_of_another_class( let at = file::coordinates::ReadingOffset::new(usize::from(access.object.text_range().start())); return match session.type_at(view, at) { - Known::Yes(found) => sema::types::parse_type_spelling(&found.type_of) + Known::Yes(found) => found + .type_value + .as_ref() + .map_or_else( + || sema::types::parse_type_spelling(&found.type_of), + Clone::clone, + ) .class_name() .is_some_and(|class| !the_same_class(class, owner)), _ => false, @@ -1294,16 +1317,26 @@ void First::update() { _value = 1; } found .found .iter() - .map(|definition| definition.fact.qualified_name()) + .map(|definition| { + session + .definition_fact(definition) + .map(|fact| fact.qualified_name()) + .unwrap_or_default() + }) .collect::>() ); assert_eq!(found.found.len(), 2, "the fixture is two classes' members"); - let narrowed = narrowed_to_the_cursors_class(&view, at, found); + let narrowed = narrowed_to_the_cursors_class(&view, at, found, session.index()); let names: Vec = narrowed .found .iter() - .map(|definition| definition.fact.qualified_name()) + .map(|definition| { + session + .definition_fact(definition) + .map(|fact| fact.qualified_name()) + .unwrap_or_default() + }) .collect(); println!("after: {names:?}"); assert_eq!( diff --git a/crates/cpp_ls/src/handlers/rename/mod.rs b/crates/cpp_ls/src/handlers/rename/mod.rs index 854e33e0..19250f65 100644 --- a/crates/cpp_ls/src/handlers/rename/mod.rs +++ b/crates/cpp_ls/src/handlers/rename/mod.rs @@ -200,7 +200,11 @@ pub fn workspace_edit_of_renaming_a_symbol( Known::Yes(defined) => defined, _ => return None, }; - if defined.found.iter().any(|definition| definition.fact.local) { + if defined.found.iter().any(|definition| { + session + .definition_fact(definition) + .is_some_and(|fact| fact.local) + }) { let locals = sema::declarations::local_references_of(&view.scopes, &view.root); // **The cursor's own name starts where the entry says**, not where the client's column does: a cursor lands // *inside* an identifier (`more` at column 9 is its second letter), while `local_references_of` records the diff --git a/crates/cpp_ls/src/handlers/semantic_token/mod.rs b/crates/cpp_ls/src/handlers/semantic_token/mod.rs index 2e93c356..187c00b7 100644 --- a/crates/cpp_ls/src/handlers/semantic_token/mod.rs +++ b/crates/cpp_ls/src/handlers/semantic_token/mod.rs @@ -1158,7 +1158,9 @@ using ContainerOf = Container; WatchFilter::new("/p"), CompilerConfig::default(), ); + session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]); session.load("/p/a.cpp"); + session.index_everything(); (session, std::path::PathBuf::from("/p/a.cpp")) } diff --git a/crates/cpp_ls/src/handlers/type_definition/mod.rs b/crates/cpp_ls/src/handlers/type_definition/mod.rs index f5eb07f7..7712d370 100644 --- a/crates/cpp_ls/src/handlers/type_definition/mod.rs +++ b/crates/cpp_ls/src/handlers/type_definition/mod.rs @@ -44,6 +44,7 @@ use cpp_code_analysis::DeclKind; use cpp_code_analysis::FileView; use cpp_code_analysis::file; +use cpp_code_analysis::index::types::ComputedType; use cpp_code_analysis::sema; use cpp_code_analysis::{FileProvider, Known, Session}; use cpp_parser::SourceRange; @@ -130,8 +131,12 @@ pub fn type_definitions_of( else { continue; }; - let spelling = found.type_of.to_string(); - if let Some(locations) = declarations_of_a_type(session, view, &spelling) { + if let Some(locations) = found + .type_value + .as_ref() + .and_then(|type_of| declarations_of_a_type_value(session, view, type_of)) + .or_else(|| declarations_of_a_type(session, view, &found.type_of)) + { return locations; } } @@ -155,8 +160,12 @@ pub fn type_definitions_of( let Known::Yes(found) = session.type_at(&rendering, at) else { continue; }; - let spelling = found.type_of.to_string(); - if let Some(locations) = declarations_of_a_type(session, view, &spelling) { + if let Some(locations) = found + .type_value + .as_ref() + .and_then(|type_of| declarations_of_a_type_value(session, view, type_of)) + .or_else(|| declarations_of_a_type(session, view, &found.type_of)) + { return locations; } } @@ -170,10 +179,13 @@ pub fn type_definitions_of( }; let mut found = Vec::new(); for definition in &defined.found { - if !matches!(definition.fact.kind, DeclKind::Type) { + let Some((file, fact)) = session.definition_parts(definition) else { + continue; + }; + if !matches!(fact.kind, DeclKind::Type) { continue; } - if let Some(location) = location_of(session, &definition.file, definition.fact.name_range) { + if let Some(location) = location_of(session, &file, fact.name_range) { found.push(location); } } @@ -186,23 +198,42 @@ pub fn type_definitions_of( /// `const Widget&`, `ns::Widget`, `Widget`. The lookup is by the **last segment without its template arguments**, /// which is the name a declaration is filed under; the filter to `DeclKind::Type` is what keeps a function of the same /// name from answering. +fn declarations_of_a_type_value( + session: &Session, + view: &FileView, + type_of: &ComputedType, +) -> Option> { + declarations_of_a_type_name(session, view, type_of.class_name()?) +} + fn declarations_of_a_type( session: &Session, view: &FileView, spelling: &str, ) -> Option> { let name = the_name_of_a_type(spelling)?; + declarations_of_a_type_name(session, view, &name) +} + +fn declarations_of_a_type_name( + session: &Session, + view: &FileView, + name: &str, +) -> Option> { // **One query, the same one every other name lookup makes**: the index answers with the declarations visible from // this file, "own file wins" included. let mut found = Vec::new(); - let Known::Yes(defined) = session.index().definitions(&name, &view.path) else { + let Known::Yes(defined) = session.index().definitions(name, &view.path) else { return None; }; for definition in &defined.found { - if !matches!(definition.fact.kind, DeclKind::Type) { + let Some((file, fact)) = session.definition_parts(definition) else { + continue; + }; + if !matches!(fact.kind, DeclKind::Type) { continue; } - if let Some(location) = location_of(session, &definition.file, definition.fact.name_range) { + if let Some(location) = location_of(session, &file, fact.name_range) { found.push(location); } } @@ -305,13 +336,11 @@ fn the_members_type( let member = listed .members .iter() - .find(|member| member.fact.name == *access.member)?; - member - .fact - .returns - .as_deref() - .map(str::to_string) - .or_else(|| member.fact.type_of.clone().map(|ty| ty.to_string())) + .find(|member| session.index().member_name(member) == access.member.as_str())?; + session + .index() + .member_returns_spelling(member) + .or_else(|| session.index().member_type_spelling(member)) } #[cfg(test)] mod tests { diff --git a/crates/cpp_ls/src/handlers/type_hierarchy/mod.rs b/crates/cpp_ls/src/handlers/type_hierarchy/mod.rs index d7885156..dcc04a5f 100644 --- a/crates/cpp_ls/src/handlers/type_hierarchy/mod.rs +++ b/crates/cpp_ls/src/handlers/type_hierarchy/mod.rs @@ -107,11 +107,13 @@ pub fn item_at( let Known::Yes(defined) = session.definitions(view, offset) else { return None; }; - defined - .found - .iter() - .find(|found| found.fact.kind == DeclKind::Type) - .and_then(|found| item_of_a_class(session, &found.file, &found.fact)) + let definition = defined.found.iter().find(|found| { + session + .definition_fact(found) + .is_some_and(|fact| fact.kind == DeclKind::Type) + })?; + let (file, fact) = session.definition_parts(definition)?; + item_of_a_class(session, &file, fact) } /// **The class's own base list, resolved** — `supertypes` of the class `name` written in `file`. @@ -123,19 +125,23 @@ pub fn supertypes_of( let Known::Yes(class) = session.index().definition(name, file) else { return Vec::new(); }; + let Some((class_file, class_fact)) = session.definition_parts(&class) else { + return Vec::new(); + }; let mut found: Vec = Vec::new(); // **The bases as the class wrote them**, then each resolved from the class's own file — where the names are // visible. A base that does not resolve whole is tried as its last segment: see the module documentation. - for base in class.fact.bases() { - let resolved = match session.index().definition(base, &class.file) { + for base in class_fact.bases() { + let resolved = match session.index().definition(base, &class_file) { Known::Yes(found) => Some(found), - _ => match session.index().definition(last_segment(base), &class.file) { + _ => match session.index().definition(last_segment(base), &class_file) { Known::Yes(found) => Some(found), _ => None, }, }; if let Some(resolved) = resolved - && let Some(item) = item_of_a_class(session, &resolved.file, &resolved.fact) + && let Some((file, fact)) = session.definition_parts(&resolved) + && let Some(item) = item_of_a_class(session, &file, fact) { found.push(item); } diff --git a/crates/cpp_ls/tests/suite/handshake/diagnostics.rs b/crates/cpp_ls/tests/suite/handshake/diagnostics.rs index a3ba56d2..547b09d9 100644 --- a/crates/cpp_ls/tests/suite/handshake/diagnostics.rs +++ b/crates/cpp_ls/tests/suite/handshake/diagnostics.rs @@ -1103,8 +1103,8 @@ extern \"C\" __global__ __aicore__ void add_kernel(GM_ADDR x) { .find(|item| item["label"] == json!("GetPhyAddr")) .expect("the LocalTensor member"); assert_eq!( - address["detail"], "T * ()", - "the toolkit type's own signature reaches the list: {address}" + address["detail"], "T* ()", + "the toolkit type's own signature reaches the list (canonical display): {address}" ); // **The family's vocabulary is offered too**, not only the toolkit's declarations: `__ai` lists the AICore diff --git a/crates/cpp_parser/src/syntax/id.rs b/crates/cpp_parser/src/syntax/id.rs index 9f0a6c71..ce124d4a 100644 --- a/crates/cpp_parser/src/syntax/id.rs +++ b/crates/cpp_parser/src/syntax/id.rs @@ -63,6 +63,26 @@ impl CppSyntaxId { self.range } + /// The serialisable parts, for a codec that does not want a second syntax model. + pub fn to_raw_parts(&self) -> (u16, u32, u32) { + ( + self.kind.get_raw(), + u32::from(self.range.start()), + u32::from(self.range.end()), + ) + } + + /// Reconstruct an ID from [`CppSyntaxId::to_raw_parts`]; a corrupted kind is rejected. + pub fn from_raw_parts(kind: u16, start: u32, end: u32) -> Option { + let kind = CppKind::try_from_raw(kind)?; + let start = TextSize::from(start); + let end = TextSize::from(end); + (start <= end).then(|| CppSyntaxId { + kind, + range: TextRange::new(start, end), + }) + } + /// Resolve back to a red node. Returns `None` if this id pointed at a token, if the tree is /// empty, or if the tree has changed shape since the id was created. pub fn to_node(&self, tree: &CppSyntaxTree) -> Option { diff --git a/crates/cpp_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 701437a1..0102bf2b 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -553,6 +553,42 @@ impl CppDeclSpecifierSeq { wrapped.children().find_map(CppNameExpr::cast) } + /// **The type-constraint written before a deduced placeholder** — the `std::integral` of + /// `template ` and the `C` of `template auto M>`. + /// + /// A constrained non-type parameter is written as a **type-constraint followed by `auto`**, and the grammar + /// records both in the parameter's specifier sequence: + /// + /// ```text + /// DeclSpecifierSeq "std::integral auto" + /// NamedType "std::integral" + /// BuiltinType "auto" + /// ``` + /// + /// The sequence's lowered type is the placeholder, so the constraint is not recoverable from the type and + /// [`CppDeclSpecifierSeq::get_type_name`] does not say it is one. This returns the `NamedType`/`TemplateType` + /// child that directly precedes an `auto` builtin, and `None` for every other sequence — `typename T`, `int N`, + /// the placeholder alone (`auto x`), and a `decltype(auto)` parameter. It is deliberately narrow: a name is a + /// constraint only when a placeholder follows it. + pub fn get_type_constraint(&self) -> Option { + // The last name before the placeholder is the constraint: a specifier sequence may carry a macro or a + // qualifier between the two, and `const std::integral auto` still writes one name in front of the `auto`. + let mut before_the_auto = None; + for child in self.syntax().children_with_tokens() { + let Some(node) = child.into_node() else { + continue; + }; + match CppSyntaxKind::from(node.kind()) { + CppSyntaxKind::NamedType | CppSyntaxKind::TemplateType => { + before_the_auto = Some(node); + } + CppSyntaxKind::BuiltinType if writes_auto(&node) => return before_the_auto, + _ => {} + } + } + None + } + /// The class-like definition this specifier sequence defines, if any. pub fn get_class_def(&self) -> Option { self.child() @@ -615,6 +651,24 @@ impl CppDeclSpecifierSeq { } } +/// **Does this `BuiltinType` write the `auto` placeholder?** — `auto` (and GNU's `__auto_type`, the same keyword +/// kind), but not `decltype(auto)`, whose first token is the `decltype` keyword. +/// +/// Asked by [`CppDeclSpecifierSeq::get_type_constraint`], which is the only caller: a name is a *constraint* only +/// when the placeholder follows it, so the placeholder has to be told apart from every other builtin. +fn writes_auto(builtin: &CppSyntaxNode) -> bool { + builtin + .children_with_tokens() + .filter_map(|child| child.into_token()) + .find(|token| { + !matches!( + CppTokenKind::from(token.kind()), + CppTokenKind::Whitespace | CppTokenKind::Newline + ) + }) + .is_some_and(|token| token.kind() == CppKind::Token(CppTokenKind::AutoKeyword)) +} + /// A built-in type specifier: `int`, `const char`, `decltype(x)`. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct CppBuiltinType { @@ -1368,6 +1422,19 @@ impl CppRequiresClause { pub fn get_clause_text(&self) -> String { syntax::node::traits::subtree_text_spaced(self.syntax()) } + + /// **The condition the clause states**, as the typed expression the grammar built — `None` when the clause holds + /// no expression this layer can name. + /// + /// The condition is a *logical-or-expression* ([temp.pre]), and the expression grammar reads it into its own nodes + /// (`BinaryExpr` for `C && C2`, `NameExpr` for `C`, `UnaryExpr` for `!C`). This accessor is the one a + /// reader uses: it hands over that node rather than a string, so no caller has to re-parse the clause's spelling. + /// A `requires`-expression (`requires { … }`) is itself an expression node — see [`CppRequiresExpr`] — and is + /// returned as such; the layer that decides constraints refuses it because it asks whether statements compile + /// rather than stating a condition. + pub fn get_condition(&self) -> Option { + self.syntax().children().find_map(CppExpr::cast) + } } /// An attribute list: `[[maybe_unused]]`, `[[nodiscard("why")]]`, `[[gnu::always_inline]]`. @@ -1438,7 +1505,13 @@ impl CppParamList { self.children() } - /// Is the list `(...)` — an old-style variadic function? + /// **Does the list write the C-style `...`** — `void f(...)` and `void f(int, ...)` alike? + /// + /// The ellipsis is a **token of the list**, written between the parentheses and after every parameter, so this + /// asks the list's own direct children. A **parameter pack** is the other spelling of `...` and is *not* this: + /// `T... rest` and `Args&&... args` put the marker inside the `Parameter` node, and [`CppParam`] records it as + /// the parameter's own pack bit. The two are different syntax, and a consumer that needs "accepts any number of + /// arguments" combines this bit with the parameters' pack flags. pub fn is_variadic(&self) -> bool { self.syntax() .children_with_tokens() @@ -1477,8 +1550,46 @@ impl CppParam { } /// The parameter name. Unnamed parameters (`void f(int)`) have none. + /// + /// **A pack declarator has no direct name on this tree**: `T... rest` puts the name inside the pack expansion, so + /// the declarator search answers `None` while the name is still there. The fallback is the last name before the + /// default initializer — the same rule as a non-type template parameter. pub fn get_name(&self) -> Option { - self.get_declarator()?.get_name() + if let Some(name) = self + .get_declarator() + .and_then(|declarator| declarator.get_name()) + { + return Some(name); + } + // **Only a pack needs the fallback.** A function-pointer parameter's nested parameters are `CppParam`s too; + // letting one search its subtree names the inner `ctx` as a parameter of the outer declaration. + let pack = self + .syntax() + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Ellipsis); + if !pack { + return None; + } + let default = self + .get_default_value() + .map(|initializer| initializer.syntax().text_range().start()); + let names: Vec = self + .syntax() + .descendants() + .filter_map(CppNameExpr::cast) + .collect(); + names + .iter() + .rev() + .find(|name| default.is_none_or(|default| name.syntax().text_range().end() <= default)) + .and_then(CppNameExpr::get_name_token) + } + + /// **The parameter's spelling with runs of whitespace collapsed**, for a one-line signature label. This is a + /// parser-owned display helper; callers do not split the node text themselves. + pub fn one_line_text(&self) -> String { + syntax::node::traits::subtree_text_spaced(self.syntax()) } /// The parameter's name as text, for comparing one name against another. diff --git a/crates/cpp_parser/tests/suite/concepts.rs b/crates/cpp_parser/tests/suite/concepts.rs index 2e9a65ec..6d675cf6 100644 --- a/crates/cpp_parser/tests/suite/concepts.rs +++ b/crates/cpp_parser/tests/suite/concepts.rs @@ -19,7 +19,10 @@ //! constraint has been absorbed by whatever follows. That is the A0 failure mode, and it is why the conjunction //! test below asks where the second template-id ended up. -use cpp_parser::{CppParser, CppSyntaxKind, CppSyntaxTree, ParserConfig}; +use cpp_parser::{ + CppAstNode, CppDeclSpecifierSeq, CppParser, CppSyntaxKind, CppSyntaxTree, CppTemplateParam, + ParserConfig, +}; fn tree(source: &str) -> CppSyntaxTree { CppParser::parse(source, ParserConfig::default()) @@ -526,6 +529,73 @@ fn a_constrained_template_parameter_is_read_as_a_parameter() { assert_eq!(count(source, CppSyntaxKind::ParameterList), 1); } +#[test] +fn a_constrained_non_type_parameter_exposes_its_type_constraint() { + // `template ` writes **two** things in the parameter's specifier sequence: the + // concept, a `NamedType`, and the placeholder, a `BuiltinType`. Lowering the sequence answers `auto` — the + // placeholder is the parameter's type — so `get_type_name` cannot say which name is the constraint. The + // accessor returns the node in front of the `auto`, which is the one a consumer asking "what constrains this + // parameter" needs, and `None` for every sequence where the name *is* the type. + let source = "\ +template void a(); +template auto M> void b(); +template void c(); +template void d(); +"; + let parsed = tree(source); + assert_eq!(parsed.get_errors(), [], "{source:?} must parse cleanly"); + + let parameters: Vec = parsed + .get_red_root() + .descendants() + .filter_map(CppTemplateParam::cast) + .collect(); + assert_eq!(parameters.len(), 4, "one parameter per head"); + + let constraint_of = |parameter: &CppTemplateParam| { + let specifiers = parameter + .get_decl_specifiers() + .expect("every template parameter writes a specifier sequence"); + assert!( + CppDeclSpecifierSeq::can_cast(specifiers.syntax().kind().into()), + "the accessor is asked of the typed sequence" + ); + specifiers + .get_type_constraint() + .map(|constraint| constraint.text().to_string().trim().to_string()) + }; + + let found: Vec> = parameters.iter().map(constraint_of).collect(); + assert_eq!( + found, + [ + Some("std::integral".to_string()), + Some("C".to_string()), + None, + None, + ], + "only a name in front of `auto` is a type-constraint; `int K` and a bare `auto X` write none" + ); + + // **The placeholder is still the sequence's type.** The constraint is a separate node, not a replacement: + // a reader that lowers the sequence still answers `auto`, which is what makes the parameter's type right. + let auto_parameter = parameters[0] + .get_decl_specifiers() + .expect("the parameter's specifiers"); + assert_eq!( + auto_parameter.get_type_text(), + "std::integral auto", + "the sequence keeps both halves" + ); + assert_eq!( + parameters[2] + .get_decl_specifiers() + .map(|specifiers| specifiers.get_type_text()), + Some("int".to_string()), + "an ordinary non-type parameter writes only its type" + ); +} + #[test] fn a_parenthesised_atomic_constraint_is_read_as_a_constraint() { // The standard allows the constraint of a clause to be written in parentheses: `requires (C)`. The diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md new file mode 100644 index 00000000..5807f80e --- /dev/null +++ b/docs/type-system-redesign.md @@ -0,0 +1,364 @@ +# Type, fact, and member identity redesign + +**This document replaces the earlier type-system redesign in this file.** The earlier plan kept +string spellings in facts and gradually moved readers to `ComputedType`; that perpetuated the +`TypeId -> string -> parse` round trip and left `ProjectMember` owning a large `DeclFact`. This plan +starts from identity and ownership instead. + +## 1. The three layers + +### 1.1 Storage layer + +The storage layer owns immutable data and small handles into it: + +```text +FileId a run-local VFS file identity +PathId a persistable path identity (only for on-disk records) +DeclFactId an identity for one immutable DeclFact in one fact arena +ParamsId an identity for one parameter list in one ParamsStore +SyntaxId a CST node identity, valid with the tree it came from +``` + +Rules: + +- A handle is valid only with the arena/store that issued it. +- A `DeclFactId` is never useful on its own. It must be resolved through its owning fact arena. +- **There is no type handle.** A type is an immutable `ComputedType` value stored on the fact; it travels + with the fact to every arena and to disk. (The earlier `TypeStore`/`TypeId` arena has been removed.) +- Persisted records never store run-local `FileId`/`DeclFactId` as if they were stable across runs. They + store their own relative keys and are rebound on load. Types travel as values, not as ids. + +### 1.2 Computing layer + +The computing layer works on materialized values: + +```text +ComputedType an owned, structured type; names are cooked, children are shared +ResolvedMember a member row whose types are computed, not spelled +``` + +`ComputedType` **is** the storage value: the fact builder lowers the declaration's syntax to it once at +construction, and it is passed through inference, overload ranking, conversion checks, member lookup, +alias substitution, and so on. There is **no** `TypeId -> spelling -> parse` step anywhere. + +### 1.3 Display layer + +Only the final presentation boundary turns a type into text: + +```rust +computed.to_string() +``` + +Hover, completion labels, signature help, and diagnostics messages are display consumers. They may +keep a `String`; they may not feed it back into type resolution. + +## 2. Identity of facts + +### 2.1 `DeclFactId` + +`DeclFact` remains immutable. Its identity is the pair: + +```rust +struct FactRef { + file: FileId, + fact: DeclFactId, +} +``` + +- `DeclFactId` is local to a fact arena. +- The owning arena is the file's fact arena, reachable from `ProjectIndex`. +- `ProjectIndex::fact(FactRef) -> &DeclFact` is the only resolver. +- A fact arena is append-only for the lifetime of the index entry. A re-read replaces the whole + file entry, so old `FactRef`s never observe a mixture of old and new facts. + +A row built from a view the index has not read yet — a buffer between the client's edit and the pump's +re-read — has no file arena to point into. The index mints an entry for it in its view-fact table +(`ProjectIndex::intern_a_view_fact`), so the row still names a real `FactRef`: the rule is the same one, +"constructors mint references through the index, never guess ids", applied to a fact that exists only in that +view. + +`FileId` is minted by the session's VFS. The index does not mint comparable IDs on its own. + +### 2.2 Persisted facts + +The cache is keyed by path/content, because `FileId` and `DeclFactId` are run-local. A persisted +summary stores its facts in file order. On load: + +1. the path is interned into the session's VFS (`FileId`); +2. the decoded facts form a fresh fact arena; +3. local indices are rebound to `DeclFactId`s in that arena. + +If a stable on-disk path identity is wanted later, it is a `PathId` table in the cache, never the +run-local `FileId`. + +## 3. `DeclFact` + +`DeclFact` stores only identities and structural syntax handles: + +```rust +struct DeclFact { + name: SmolStr, + kind: DeclKind, + scope: Option, + type_of: DeclaredType, + returns: DeclaredType, + parameters: ParamsId, + variadic_parameters: bool, + template_parameters: Box<[SmolStr]>, + parameter_defaults: Box<[SmolStr]>, + requires_clause: Option, + default_argument: Option, + range: SourceRange, + name_range: SourceRange, + ... +} +``` + +The two type fields are one enum, because a fact holds either kind of answer: + +```rust +enum DeclaredType { + None, + Computed(Arc), // the value itself; no id, no arena +} +``` + +There is no `type_of: Option>` and no `returns: Option>`. **The same representation is used +by `DeclFact::type_of`/`returns` and `ParameterFact::type_of`**, and there is no type table, no interning and +no source-spelling side table beside it. + +A fact with no written type has `DeclaredType::None`; a fact whose declaration stated one carries the +`ComputedType` the builder lowered from its own syntax. A view/synthesized fact carries the same kind of +value, which is why no store or handle is needed for it: + +```rust +index.computed_type_of(fact) // -> Option (a clone of the value) +index.type_spelling_of(fact) // -> canonical display +``` + +## 4. `ProjectMember` + +`ProjectMember` is a small row: + +```rust +struct ProjectMember { + /// Which immutable declaration this row names. + fact: FactRef, + + /// This instantiation's substitutions. Empty for a non-template member. + substitution: Option>, + + /// The class whose own declaration filed this row. + declared_in: DeclFactId, // or a qualified-name id, see below + + depth: usize, + ambiguous: bool, +} +``` + +It does **not** store: + +```text +PathBuf +DeclFact by value +substituted DeclFact copies +type/return strings +``` + +`declared_in` is a fact reference as well, not a path or a copied fact. The qualified spelling is +produced only at display. + +### 4.1 Reading a member + +The row is resolved through the index and the model: + +```rust +impl SemanticModel<'_> { + fn member_type(&self, member: &ProjectMember) -> Option; + fn member_returns(&self, member: &ProjectMember) -> Option; + fn member_parameters(&self, member: &ProjectMember) -> Option<&ParamsStore>; +} +``` + +The base type is the value on the member's fact, cloned and then substituted structurally: + +```rust +fact.type_of.as_computed()?.substituted(&substitution.bindings) +``` + +No spelling is parsed and no table is consulted. + +### 4.2 Substitution + +```rust +struct MemberSubstitution { + bindings: Vec<(SmolStr, ComputedType)>, + /// One written instantiation per substitution applied to the row, oldest first. A `DeclFact` still carries its + /// parameter list and type spellings as text until the type lowering lands, so the display edge applies this + /// pairing to those spellings instead of rewriting the fact. + stages: Vec, +} +``` + +- A substitution belongs to one row, not to a whole `MemberList`. +- `MemberList` merging/`extend` preserves each row's substitution. +- Composition of two substitutions is a new `MemberSubstitution`; facts are never rewritten. The composed + `bindings` take the newest meaning for a name both mention, and the stages stay in the order the rewrites ran — + the older instantiation first. +- `MemberSubstitution` lives in the request (`SemanticModel` cache) or in a `Arc` owned by the row. + It never enters a summary or the cache. + +`ProjectMember` rows can be merged from different bases with different substitutions; this is why +the substitution cannot be a field on `MemberList`. + +### 4.3 Caching + +`SemanticModel` owns the per-request caches: + +```text +member_types: HashMap<(FactRef, SubstitutionId?), ComputedType> +members: HashMap +``` + +Keys use `FactRef`, which is globally meaningful because it names a file and a fact in that file's arena. +The index owns no substituted member cache and no recomputation cache. + +## 5. File and path identities + +Runtime structures use `FileId`: + +```text +ProjectMember.fact.file +ProjectDefinition.file +Candidate.file +ProjectIndex queries that return a location +``` + +Persistent records keep paths or a persisted `PathId`: + +```text +FileSummary cache key +cooked-reading cache key +module/import records +``` + +`ProjectIndex` receives the path↔`FileId` mapping from the session/VFS at insertion time. It does +not create a parallel file-id namespace. + +## 6. Parameters + +`ParameterFact` is the single parameter representation: + +```rust +struct ParameterFact { + name: Option, + declaration: SyntaxId, + default_value: Option, + pack: bool, + type_of: DeclaredType, +} +``` + +**The list-level `...` is not a parameter fact.** `void f(int, ...)` writes one `CppParam` and a `...` beside it, +`void f(...)` writes no parameter at all, and `T... rest` writes the marker *inside* the parameter — so the C-style +marker is the list's token (`CppParamList::is_variadic`) and the pack is `ParameterFact::pack`. The list-level answer +is stored on the declaration as `DeclFact::variadic_parameters`, read from the same `CppParamList` at construction, +rather than as a bit in `ParamsStore`: a fact does not always have a store that travels with it (a view fact's list is +in the index's synthetic arena, and `facts_with_their_types` clears the handle), and it must not depend on a handle to +represent `(...)`, whose parameter list is empty. A consumer that needs "accepts a variable number of arguments" ORs the +two facts; neither is derived from a spelling. + +A parameter's type is the same [`DeclaredType`](#3-declfact) a fact's own types use — the immutable +`ComputedType` the builder lowered from the parameter's own `CppParam` at construction. There is no spelling +field and no handle: `ProjectIndex::parameter_type` clones the value, and nothing below it parses a parameter +list. + +`FileSummary.parameters: ParamsStore`; `DeclFact.parameters: ParamsId`. +`DeclDetail.parameter_facts` is deleted. The builder produces the `ParamsStore` and the fact builder +receives it; no build-time duplicate is retained. + +The other two owners of a `ParamsId` follow the same rule. A cooked reading carries its own +`CookedFile.parameters: ParamsStore`, imported at `insert_cooked`, because the rendering's facts name +parameter handles in the rendering's store. (Types need no matching table: they are values on the facts.) A +fact a query synthesized — a buffer's member +before the pump has read it, a generated member — has no summary and therefore no store; the index's +synthetic fact arena carries its `ParameterFact` list beside the fact, keyed by the `FactRef` it minted, and +that is a list rather than a second `ParamsStore` because there is no id space for it to collide with. +`ProjectIndex::parameter_facts_of`/`parameter_facts_at` are the only resolvers; between them they ask the +synthetic arena, the owning summary, and the cooked reading. + +## 7. Constants and constraints + +`constant.rs` evaluates a CST token sequence (`value_of_tokens`). A macro body, which is not a CST +node in this crate, is lexed at the boundary; it is never parsed as a declaration. + +`constraint.rs` reads: + +- a `RequiresClause` through `CppRequiresClause` token accessors; +- `enable_if`/`enable_if_t` through `CppNameExpr` + `CppTemplateArgList`; +- the condition expression through typed CST nodes. + +Text splitting and trait-string parsers are deleted. A condition that cannot be decided from the +typed tree returns `None`; it is not re-parsed from a spelling. + +## 8. Forbidden patterns + +The following are review blockers: + +```text +CppParser::parse(fragment, ParserConfig::default()) +fact.type_of as a string used by computation +fact.returns as a string used by computation +PathBuf in ProjectMember/ProjectDefinition/Candidate +a second TypeStore for a computed/substituted type +mutating a DeclFact owned by a summary or cached member list +list-level substitution applying to members from different bases +``` + +## 9. Migration phases + +### Phase 1: identity plumbing + +- Add `FactRef`/`DeclFactId` and the per-file fact arena. +- Add the session VFS path↔`FileId` mapping used by `ProjectIndex`. +- Change `ProjectMember`, `ProjectDefinition`, `Candidate` to store `FactRef`/`FileId`, not + `PathBuf`/`DeclFact`. +- Keep display adapters until consumers are migrated. + +### Phase 2: member views + +- `ProjectMember` stores `FactRef + substitution + declared_in + depth + ambiguous`. +- Remove all `member.fact` field access. Members are read through `SemanticModel`. +- `substituted_members` attaches `MemberSubstitution`; it does not clone or rewrite `DeclFact`. +- `SemanticModel` caches substituted member types by `FactRef`; the fact already holds a `ComputedType`. + +### Phase 3: types + +- Delete `DeclFact.type_of`/`returns` strings and the codec's spelling fields. +- All computation consumers use `ComputedType`; display converts at the edge. +- `ProjectIndex::type_spelling_of` is removed from computation and kept only if a display caller + genuinely has no model. + +### Phase 4: parameters and remaining text + +- Delete `DeclDetail.parameter_facts` and the codec fields that exist only for it. +- Delete the remaining `constant`/`constraint` string boundaries. +- Add a guard test that no fragment parser or type-string round trip remains. + +## 10. Acceptance + +```text +cargo test --workspace +cargo clippy --workspace --all-targets --all-features -- -D warnings +``` + +plus static guards: + +```text +no ParserConfig::default() parse outside whole-file entry points +no `DeclFact.type_of` / `DeclFact.returns` strings +no `PathBuf` in ProjectMember/ProjectDefinition/Candidate +no TypeStore/TypeId/TypeTable interning for facts or parameters +``` + +Each phase boundary must be green. Within a phase, intermediate commits may be red.