From e30f959e307e34ec87c54f376d392a1631fe86ef Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 16:56:30 +0800 Subject: [PATCH 001/102] feat(types): add the interned type store Phase 1 of the type-system redesign: TypeId/NameId handles, a hash-consed append-only TypeStore, TypeKind/TypeNode with source spelling, TypeRef accessors and conversion from sema::types::Type. Nothing in DeclFact or the queries moves yet; the design and staged migration are documented in docs/type-system-redesign.md. --- .../cpp_code_analysis/src/index/types/mod.rs | 529 ++++++++++++++++++ docs/type-system-redesign.md | 326 +++++++++++ 2 files changed, 855 insertions(+) create mode 100644 docs/type-system-redesign.md diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 8b137891..9f56e66f 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -1 +1,530 @@ +//! **Types as the index stores them**: a hash-consed graph of handles, not a spelling per declaration. +//! +//! [`sema::types::Type`](crate::sema::types::Type) is the parser-facing shape. This module is the *storage* shape: +//! the same information, but shared through an append-only store, so a declaration can hold an eight-byte +//! `Option` instead of a 24-byte `SmolStr` that every consumer has to parse again. +//! +//! ```text +//! one source spelling -> TypeStore -> TypeId +//! std::vector one node, one name, one ID 0x0000_0017 +//! std::vector the same node and ID 0x0000_0017 +//! ``` +//! +//! # What is shared, and what is not +//! +//! [`TypeId`] is a **process-local handle**, not a durable identifier. A summary that is written to disk keeps its +//! own local type table; importing that summary into a store rewrites the local IDs to store IDs. The design and +//! the migration order are in `docs/type-system-redesign.md`. +//! +//! The store interns the *shape* and the *source spelling*. It deliberately does not resolve aliases or instantiate +//! templates: those are index queries, and doing them here would make the cache depend on the whole project while +//! it is still being built. +use std::collections::HashMap; +use std::fmt; + +use crate::sema::types::Type; + +/// A handle to one node in a [`TypeStore`]. +/// +/// Four bytes, `Copy`, and meaningful only with the store that produced it. A [`TypeRef`] keeps the two together. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TypeId(u32); + +impl TypeId { + /// The index into the store's node vector. Public for diagnostics and tests; consumers should prefer + /// [`TypeRef`]. + pub fn index(self) -> usize { + self.0 as usize + } + + /// The handle for the `index`th node, used by a decoder that is rebuilding a store. + pub fn from_index(index: usize) -> TypeId { + TypeId(u32::try_from(index).expect("a type store with more than u32::MAX nodes")) + } +} + +impl fmt::Display for TypeId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "#{}", self.0) + } +} + +/// A handle to one interned spelling in a [`TypeStore`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct NameId(u32); + +impl NameId { + pub fn index(self) -> usize { + self.0 as usize + } + + pub fn from_index(index: usize) -> NameId { + NameId(u32::try_from(index).expect("a name store with more than u32::MAX names")) + } +} + +/// **The structural shape of one type.** The spelling lives on [`TypeNode`], because the same shape may have been +/// written two ways and a reader is owed the one in their file. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TypeKind { + /// `int`, `unsigned long long`, `bool` — the spelling is the name ID. + Builtin(NameId), + /// `Widget`, `std::vector`, `T` before the context says it is a parameter. + Named { + name: NameId, + arguments: Box<[TypeId]>, + }, + /// `T` inside a template body. + TemplateParameter(NameId), + /// `auto` as a placeholder. Deduced types are interned as their result, not as this. + Auto, + /// `decltype(auto)`, which is a placeholder with different deduction rules from `auto`. + DecltypeAuto, + Pointer(TypeId), + Reference { + to: TypeId, + /// `&&` rather than `&`; a forwarding reference is a deduction question, not a display detail. + rvalue: bool, + }, + Array { + of: TypeId, + /// `Some(4)` for `int[4]`, `None` for `int[]`. + extent: Option, + }, + Function { + returns: TypeId, + parameters: Box<[TypeId]>, + }, + Pack(TypeId), + Qualified { + of: TypeId, + qualifiers: crate::sema::types::Qualifiers, + }, +} + +/// One node: the shape and the spelling the source wrote, when it wrote one. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct TypeNode { + pub kind: TypeKind, + /// **The source spelling, kept for display.** `None` for a node the store synthesized (a substitution result, a + /// test), whose [`TypeRef::display`] is reconstructed from the shape. + pub spelling: Option, +} + +/// The interning key. Two nodes with the same shape **and** the same spelling are one node; two spellings of one +/// structural type stay distinct so a hover can show what the file wrote. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct TypeKey { + kind: TypeKind, + spelling: Option, +} + +/// **An append-only name table.** `NameId` is four bytes and a lookup is one hash; the strings live here once. +/// +/// The table is deliberately small: no removal, no refcount, no generation. A `TypeStore` is rebuilt with the index +/// generation it belongs to, and a summary's names are imported into it once. +#[derive(Default)] +pub struct NameInterner { + names: Vec>, + ids: HashMap, NameId>, +} + +impl NameInterner { + pub fn intern(&mut self, spelling: &str) -> NameId { + if let Some(id) = self.ids.get(spelling) { + return *id; + } + let id = NameId::from_index(self.names.len()); + let boxed: Box = spelling.into(); + self.names.push(boxed.clone()); + self.ids.insert(boxed, id); + id + } + + pub fn name(&self, id: NameId) -> Option<&str> { + self.names.get(id.index()).map(|name| &**name) + } + + pub fn len(&self) -> usize { + self.names.len() + } + + pub fn is_empty(&self) -> bool { + self.names.is_empty() + } +} + +/// **The type graph of one index generation**, hash-consed and append-only. +#[derive(Default)] +pub struct TypeStore { + nodes: Vec, + interned: HashMap, + names: NameInterner, +} + +impl TypeStore { + pub fn new() -> TypeStore { + TypeStore::default() + } + + /// The number of distinct types interned so far. + pub fn len(&self) -> usize { + self.nodes.len() + } + + pub fn is_empty(&self) -> bool { + self.nodes.is_empty() + } + + /// The name table, for a consumer that has to print a `name` field or build a new node. + pub fn names(&self) -> &NameInterner { + &self.names + } + + /// The name table, mutably — the entry point for a decoder or a synthetic node. + pub fn names_mut(&mut self) -> &mut NameInterner { + &mut self.names + } + + /// **Intern one already-structured node.** `spelling` is the source spelling when there is one; `None` asks + /// [`TypeRef::display`] to reconstruct it. + pub fn intern(&mut self, kind: TypeKind, spelling: Option<&str>) -> TypeId { + let spelling = spelling.map(|spelling| self.names.intern(spelling)); + let key = TypeKey { + kind: kind.clone(), + spelling, + }; + if let Some(id) = self.interned.get(&key) { + return *id; + } + let id = TypeId::from_index(self.nodes.len()); + self.nodes.push(TypeNode { kind, spelling }); + self.interned.insert(key, id); + id + } + + /// **Convert the parser's type into the store.** Every child is interned first, so the graph is a DAG rather + /// than a tree with repeated spellings. + pub fn intern_type(&mut self, written: &Type) -> TypeId { + let spelling = written.to_string(); + let kind = match written { + Type::Builtin { spelling } if spelling.trim() == "auto" => TypeKind::Auto, + Type::Builtin { spelling } if spelling.trim() == "decltype(auto)" => { + TypeKind::DecltypeAuto + } + Type::Builtin { spelling } => TypeKind::Builtin(self.names.intern(spelling.trim())), + Type::Named { name, arguments } => TypeKind::Named { + name: self.names.intern(name), + arguments: arguments + .iter() + .map(|argument| self.intern_type(argument)) + .collect::>() + .into_boxed_slice(), + }, + Type::TemplateParameter { name } => { + TypeKind::TemplateParameter(self.names.intern(name)) + } + Type::Pointer { to } => TypeKind::Pointer(self.intern_type(to)), + Type::Reference { to, rvalue } => TypeKind::Reference { + to: self.intern_type(to), + rvalue: *rvalue, + }, + Type::Array { of, extent } => TypeKind::Array { + of: self.intern_type(of), + extent: extent.map(|extent| extent as u64), + }, + Type::Function { + returns, + parameters, + } => TypeKind::Function { + returns: self.intern_type(returns), + parameters: parameters + .iter() + .map(|parameter| self.intern_type(parameter)) + .collect::>() + .into_boxed_slice(), + }, + Type::Pack { of } => TypeKind::Pack(self.intern_type(of)), + Type::Qualified { of, qualifiers } => TypeKind::Qualified { + of: self.intern_type(of), + qualifiers: *qualifiers, + }, + }; + self.intern(kind, Some(&spelling)) + } + + /// **The entry point for a spelling that came from outside the syntax** — a cache record, a CLI argument, a + /// test. Parsing remains one call, at this boundary; consumers below use [`TypeId`]. + pub fn intern_spelling(&mut self, spelling: &str) -> TypeId { + let parsed = crate::sema::types::parse_type_spelling(spelling); + self.intern_type(&parsed) + } + + /// The node a handle names, or `None` for a handle from a different store. + pub fn node(&self, id: TypeId) -> Option<&TypeNode> { + self.nodes.get(id.index()) + } + + /// A store-plus-handle pair, the read API used by everything above this module. + pub fn type_ref(&self, id: TypeId) -> Option> { + self.node(id).map(|_| TypeRef { store: self, id }) + } + + pub fn spelling(&self, id: TypeId) -> Option<&str> { + let node = self.node(id)?; + node.spelling.and_then(|spelling| self.names.name(spelling)) + } +} + +/// **A type handle with the store that gives it meaning.** The borrow is what makes it impossible to use an ID +/// from one generation in another. +#[derive(Clone, Copy)] +pub struct TypeRef<'a> { + store: &'a TypeStore, + id: TypeId, +} + +impl<'a> TypeRef<'a> { + pub fn id(self) -> TypeId { + self.id + } + + pub fn kind(self) -> &'a TypeKind { + &self.store.nodes[self.id.index()].kind + } + + /// The spelling the file wrote, if this node has one. + pub fn spelling(self) -> Option<&'a str> { + self.store.spelling(self.id) + } + + /// **How a reader sees the type.** The source spelling when there is one; otherwise a rendering of the shape, + /// used for a node a substitution or a test synthesized. + pub fn display(self) -> String { + if let Some(spelling) = self.spelling() { + return spelling.to_string(); + } + self.render() + } + + /// The class this type names, if it names one. A reference and a qualifier are transparent; a pointer is not. + pub fn class_name(self) -> Option<&'a str> { + match self.kind() { + TypeKind::Named { name, .. } => self.store.names.name(*name), + TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { + self.store.type_ref(*to)?.class_name() + } + _ => None, + } + } + + /// The template arguments written on the type, looking through a reference or a qualifier. + pub fn arguments(self) -> &'a [TypeId] { + match self.kind() { + TypeKind::Named { arguments, .. } => arguments, + TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { + self.store.type_ref(*to).map_or(&[], TypeRef::arguments) + } + _ => &[], + } + } + + /// The pointee of a pointer. A reference is a binding, not a pointer; a caller that wants through either asks + /// [`TypeRef::decay`] first. + pub fn pointee(self) -> Option> { + match self.kind() { + TypeKind::Pointer(to) => self.store.type_ref(*to), + _ => None, + } + } + + /// Is the object this type describes `const`? A qualifier and a reference are looked through; a pointer is not. + pub fn is_const(self) -> bool { + match self.kind() { + TypeKind::Qualified { qualifiers, .. } => qualifiers.is_const(), + TypeKind::Reference { to, .. } => self + .store + .type_ref(*to) + .is_some_and(|inner| inner.is_const()), + _ => false, + } + } + + fn render(self) -> String { + match self.kind() { + TypeKind::Builtin(name) | TypeKind::TemplateParameter(name) => self + .store + .names + .name(*name) + .unwrap_or("") + .to_string(), + TypeKind::Named { name, arguments } => { + let name = self.store.names.name(*name).unwrap_or(""); + if arguments.is_empty() { + name.to_string() + } else { + let arguments = arguments + .iter() + .filter_map(|argument| self.store.type_ref(*argument)) + .map(TypeRef::render) + .collect::>() + .join(", "); + format!("{name}<{arguments}>") + } + } + TypeKind::Auto => "auto".to_string(), + TypeKind::DecltypeAuto => "decltype(auto)".to_string(), + TypeKind::Pointer(to) => self.store.type_ref(*to).map_or_else( + || "*".to_string(), + |inner| format!("{}*", inner.render()), + ), + TypeKind::Reference { to, rvalue } => self.store.type_ref(*to).map_or_else( + || "&".to_string(), + |inner| format!("{}{}", inner.render(), if *rvalue { "&&" } else { "&" }), + ), + TypeKind::Array { of, extent } => self.store.type_ref(*of).map_or_else( + || "[]".to_string(), + |inner| match extent { + Some(extent) => format!("{}[{extent}]", inner.render()), + None => format!("{}[]", inner.render()), + }, + ), + TypeKind::Function { + returns, + parameters, + } => { + let returns = self + .store + .type_ref(*returns) + .map_or_else(|| "".to_string(), TypeRef::render); + let parameters = parameters + .iter() + .filter_map(|parameter| self.store.type_ref(*parameter)) + .map(TypeRef::render) + .collect::>() + .join(", "); + format!("{returns}({parameters})") + } + TypeKind::Pack(of) => self.store.type_ref(*of).map_or_else( + || "...".to_string(), + |inner| format!("{}...", inner.render()), + ), + TypeKind::Qualified { of, qualifiers } => self.store.type_ref(*of).map_or_else( + || "".to_string(), + |inner| format!("{}{}", qualifiers.leading_words(), inner.render()), + ), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sema::types::{Qualifiers, Type}; + use std::sync::Arc; + + #[test] + fn the_same_spelling_is_one_node() { + let mut store = TypeStore::new(); + let first = store.intern_spelling("std::vector"); + let second = store.intern_spelling("std::vector"); + + assert_eq!(first, second); + assert_eq!( + store.len(), + 2, + "int and the vector node; vector itself is not a separate node" + ); + } + + #[test] + fn two_spellings_of_one_shape_are_two_nodes() { + let mut store = TypeStore::new(); + let size_t = store.intern_spelling("std::size_t"); + let unsigned = store.intern_spelling("unsigned long long"); + + assert_ne!(size_t, unsigned); + assert_eq!(store.type_ref(size_t).unwrap().display(), "std::size_t"); + assert_eq!( + store.type_ref(unsigned).unwrap().display(), + "unsigned long long" + ); + } + + #[test] + fn a_named_type_keeps_its_class_and_arguments() { + let mut store = TypeStore::new(); + let vector = store.intern_spelling("std::vector"); + let reference = store.type_ref(vector).expect("interned"); + + assert_eq!(reference.class_name(), Some("std::vector")); + assert_eq!(reference.arguments().len(), 1); + assert_eq!( + store + .type_ref(reference.arguments()[0]) + .expect("argument") + .display(), + "int" + ); + } + + #[test] + fn a_qualified_pointer_keeps_the_qualifier_where_it_was_written() { + let mut store = TypeStore::new(); + let pointer_to_const = store.intern_spelling("const Widget*"); + let const_pointer = store.intern_spelling("Widget* const"); + + assert_ne!(pointer_to_const, const_pointer); + assert!( + !store.type_ref(pointer_to_const).unwrap().is_const(), + "the pointee is const, not the pointer" + ); + assert!( + store.type_ref(const_pointer).unwrap().is_const(), + "the pointer itself is const" + ); + } + + #[test] + fn a_synthetic_node_renders_without_a_spelling() { + let mut store = TypeStore::new(); + let int = store.intern_spelling("int"); + let pointer = store.intern(TypeKind::Pointer(int), None); + + assert_eq!(store.type_ref(pointer).unwrap().display(), "int*"); + } + + #[test] + fn a_source_spelling_is_displayed_even_when_the_shape_is_synthetic() { + let mut store = TypeStore::new(); + let int = store.intern_spelling("int"); + let alias = store.intern( + TypeKind::Qualified { + of: int, + qualifiers: Qualifiers::CONST, + }, + Some("cint"), + ); + + assert_eq!(store.type_ref(alias).unwrap().display(), "cint"); + assert!(store.type_ref(alias).unwrap().is_const()); + } + + #[test] + fn converting_a_parser_type_returns_the_same_id_as_the_spelling_entry() { + let parsed = Type::Function { + returns: Arc::new(Type::builtin("int")), + parameters: vec![Type::builtin("int"), Type::builtin("double")], + }; + let mut store = TypeStore::new(); + let from_syntax = store.intern_type(&parsed); + let from_spelling = store.intern_spelling("int(int, double)"); + + assert_eq!(from_syntax, from_spelling); + assert_eq!( + store.type_ref(from_syntax).unwrap().display(), + "int(int, double)" + ); + } +} diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md new file mode 100644 index 00000000..1e3bda23 --- /dev/null +++ b/docs/type-system-redesign.md @@ -0,0 +1,326 @@ +# Type system and Fact storage redesign + +Status: design, branch `refactor-type`. + +This document is the contract for the refactor. It records the current problem, the target representation, the +serialization boundary, and the order in which the code moves. It deliberately separates **the type store** (Phase 1) +from **changing `DeclFact`** (Phase 2+): the type engine is useful before any stored fact changes shape, and a +500-call-site refactor must not start with a broken build. + +## 1. What is wrong today + +`sema::types::Type` is already a discriminated union: + +```rust +enum Type { + Builtin { spelling }, + Named { name, arguments }, + TemplateParameter { name }, + Pointer { to }, + Reference { to, rvalue }, + Array { of, extent }, + Function { returns, parameters }, + Pack { of }, + Qualified { of, qualifiers }, +} +``` + +The index throws that shape away at the persistence boundary: + +```rust +DeclFact { + type_of: Option, + returns: Option, + // ... +} + +DeclDetail { + parameters: Vec, + parameter_defaults: Vec, + parameter_list: Option, + // ... +} +``` + +Consequences: + +* every declaration pays for a type spelling, even when thousands of declarations share one type; +* every consumer parses the same spelling again (`parse_type_spelling` is spread across queries, checks, hover, + completion and inlay); +* type equality is string equality, so two spellings of one structural type are not shared; +* `DeclFact` is 160 bytes and `DeclDetail` is 264 bytes; the detail box and its strings are paid per fact; +* `SmolStr`'s inline capacity is good for identifiers but wrong for `std::vector<...>` spellings. + +Measured shape before this design: 486,783 declarations over 1,761 files, `DeclFact` 424 bytes before the detail box +and 160 bytes after it; `DeclDetail` is 264 bytes when present. The summary is the dominant memory consumer. + +## 2. Goals and non-goals + +Goals: + +1. One canonical, immutable type graph per index generation. +2. A type is parsed **once**, when the file is read; queries use handles. +3. Repeated types share storage; repeated names share storage. +4. Type identity is structural (plus source spelling for display), not string comparison. +5. `DeclFact` and `DeclDetail` become compact and cache-friendly. +6. Summaries remain self-contained on disk; type handles are not persisted as process addresses or global IDs. +7. The migration is incremental and each phase keeps the workspace green. + +Non-goals for the first pass: + +* alias resolution inside the type store (that remains an index query); +* full C++ template instantiation (substitution remains a query over the store); +* replacing expression storage (`requires`-clauses, default argument expressions) with a full expression IR; +* changing the parser's `Type` grammar in the same commit. + +## 3. Core representation + +The new module is `crates/cpp_code_analysis/src/index/types/`. + +```rust +pub struct TypeId(u32); +pub struct NameId(u32); + +pub struct TypeStore { + nodes: Vec, + interned: HashMap, + names: NameInterner, +} + +pub struct TypeNode { + pub kind: TypeKind, + /// The spelling the source used, when one exists. + pub spelling: Option, +} + +pub enum TypeKind { + Builtin(NameId), + Named { name: NameId, arguments: Box<[TypeId]> }, + TemplateParameter(NameId), + Auto, + DecltypeAuto, + Pointer(TypeId), + Reference { to: TypeId, rvalue: bool }, + Array { of: TypeId, extent: Option }, + Function { returns: TypeId, parameters: Box<[TypeId]> }, + Pack(TypeId), + Qualified { of: TypeId, qualifiers: Qualifiers }, +} +``` + +Design rules: + +* **`TypeId` is 4 bytes**, not an `Arc` pointer. A fact pays 8 bytes for two optional handles. +* **`Box<[TypeId]>`** for children: no capacity field, no spare allocation for the common zero/one-child cases. +* **`NameInterner` owns the strings.** `TypeStore` hands out `NameId`; facts eventually store name IDs too. +* **Append-only.** Nodes are never mutated. A file edit creates a new summary and a new generation; old handles + either die with the generation or are dropped with the index. +* **Hash-consed.** Interning key is `(TypeKind, Option)`; the same structure and spelling produce one ID. +* **Spelling is part of identity.** `std::size_t` and `unsigned long long` may be structurally equivalent, but the + source spelling is what a hover must display. Alias resolution is a separate query, not a rewrite at intern time. +* **No AST inside facts.** A `DeclFact` stores handles; `TypeRef` is the read API, borrowing the store. + +## 4. The read API + +Consumers should not pattern-match `TypeKind` and walk the store themselves. + +```rust +pub struct TypeRef<'a> { + store: &'a TypeStore, + id: TypeId, +} + +impl TypeRef<'_> { + pub fn kind(&self) -> &TypeKind; + pub fn display(&self) -> String; + pub fn class_name(&self) -> Option<&str>; + pub fn arguments(&self) -> &[TypeId]; + pub fn pointee(&self) -> Option>; + pub fn is_const(&self) -> bool; + pub fn substituted(&self, parameters: &[NameId], arguments: &[TypeId]) -> TypeRef<'_>; +} +``` + +`TypeRef` keeps the store and handle together. A caller cannot accidentally use an ID from another store, and a +function that needs to return a derived type does so through `TypeStore::intern_*`, not by allocating an AST. + +`SemanticModel` will hold `&TypeStore` alongside its existing resolver and `TypeMemo`; the model remains the +request-scoped owner of derived-answer caches. The store itself is owned by `ProjectIndex`, because it survives +individual requests and must be shareable across reader threads. + +## 5. Fact storage + +### 5.1 Phase 2 shape + +```rust +pub struct DeclFact { + pub name: NameId, + pub scope: Option, + pub kind: DeclKind, + pub flags: FactFlags, + pub type_of: Option, + pub returns: Option, + pub range: SourceRange, + pub name_range: SourceRange, + pub detail: Option, +} +``` + +`FactFlags` packs: + +```text +enumerator local exported definition +split_by_a_directive clean guard +access +``` + +`DeclKind` and `Access` are `#[repr(u8)]`; booleans do not each occupy a byte after alignment. + +Target: 48–56 bytes for the common fact, down from 160. + +### 5.2 Detail as a side table + +`Option>` is eight bytes **plus one allocation per fact with detail**, and puts the detail far from +the fact. `FileSummary` gets a parallel detail store: + +```rust +pub struct FileSummary { + pub facts: Vec, + pub details: Vec>>, + // ... +} +``` + +A fact holds a `DetailId` (or no detail). Ordinary variables, enumerators and fields pay four bytes, not a pointer +and not a 264-byte record. Detail records stay contiguous for the declarations that need them. + +### 5.3 Structured parameter lists + +`DeclDetail.parameter_list` is a string today because the declaration is often in another file and the consumer +needs names and types. Store the structure instead: + +```rust +pub struct Parameter { + pub name: Option, + pub type_id: TypeId, + pub default: Option, +} + +pub struct DeclDetail { + pub parameters: Box<[Parameter]>, + pub parameter_types: Box<[TypeId]>, + pub bases: Box<[BaseSpec]>, + pub pattern: Option, + pub requires_clause: Option, + // ... +} +``` + +Rendering a signature becomes a walk over `Parameter` and `TypeRef::display`. A `parameter_list` spelling can be +kept only as a display fallback for a construct whose structure is incomplete; it is no longer the primary storage. + +## 6. Serialization + +`TypeId` is a process-local handle and must never be written to disk directly. Each `FileSummary` carries a local +type table: + +```rust +pub struct FileSummary { + pub types: TypeTable, // local IDs -> encoded nodes + pub facts: Vec, // local TypeId values + // ... +} +``` + +Write path: + +1. syntax -> `Type` -> `TypeStore` (in memory); +2. build a compact `TypeTable` for the summary and assign local IDs; +3. write facts with local `TypeId` values; +4. write the table before the facts. + +Read path: + +1. decode `TypeTable`; +2. import each node into the global `TypeStore` (deduplicating); +3. rewrite the summary's facts to global IDs; +4. insert the summary. + +This gives self-contained cache entries and cross-file deduplication after load. It also means type IDs never have +to be stable across process restarts, which is the property a global interner cannot honestly offer. Bump +`FORMAT_VERSION` and `CODEC_VERSION`; old entries are unreachable rather than decoded into a different type model. + +## 7. Migration phases + +### Phase 1 — type store only (no fact changes) + +* implement `TypeId`, `TypeKind`, `TypeNode`, `TypeStore`, `NameInterner`, `TypeRef`; +* conversion from `sema::types::Type`; +* `display`, `class_name`, `arguments`, `pointee`, `is_const`; +* tests for interning, spelling preservation, structural equality and ID stability; +* no `DeclFact` edits and no query migrations. + +### Phase 2 — additive facts + +* add `type_of_id` / `returns_id` beside the existing fields; +* add `FileSummary.types` and the codec table; +* populate both representations; +* add `MemoryReport` counters: type nodes, intern hits, bytes saved, facts with types; +* keep every existing consumer working from the old fields. + +### Phase 3 — migrate hot consumers + +In order: + +1. `type_of` / `type_at`; +2. `members_of` / `class_name` / argument substitution; +3. alias resolution; +4. completion; +5. hover and inlay; +6. diagnostics and checks. + +Each step deletes one class of `parse_type_spelling` calls. The type store becomes the only input; string parsing +remains only at external boundaries (CLI spellings, tests, malformed cache migration). + +### Phase 4 — remove the old storage + +* `DeclFact.type_of` / `returns` become `Option`; +* `DeclDetail.parameter_list` becomes structured `Parameter` values; +* pack flags, add the detail side table; +* update the codec and bump versions; +* remove the compatibility accessors; +* run the memory probe and the full test suite. + +## 8. Risks and decisions + +* **Alias identity.** The store interns the spelling and the structure; it does not resolve aliases. `using Int = + int;` creates an alias declaration, and a consumer that needs the target asks the index. This keeps the type store + a pure cache and avoids cycles during indexing. +* **Generation lifetime.** The store is append-only per index generation. A file edit drops the summaries that + depended on it and creates new nodes; facts from dropped summaries must not keep old IDs alive. The index + generation is the boundary, not a reference count per node. +* **Thread safety.** `TypeStore` is immutable after a drain / behind the same lock as the index. `TypeId` is a + plain integer and can cross reader threads; `TypeRef` borrows the store and cannot outlive a request. +* **Name interning.** Names are far more repetitive than types (`_Tp`, `size`, `std`). They use the same + append-only interner, but IDs are not persisted globally; the summary name table is local. +* **Cache duplication.** A long type is written once per summary's type table, not once per fact. Cross-file + duplication is resolved when the summary is imported. +* **No big-bang.** The old string fields remain until every consumer has an ID path. The codec version is the + switch that prevents a half-migrated cache from being read. + +## 9. First implementation slice + +Phase 1 lands only `index::types`: + +```text +TypeId / NameId +TypeKind / TypeNode +TypeStore / NameInterner / TypeKey +TypeRef +Type -> TypeStore conversion +display / class_name / arguments / pointee / is_const +unit tests +``` + +`DeclFact`, `DeclDetail`, the codec and every query remain untouched in that slice. The next slice starts by +measuring interning on a real standard-library closure before adding a single field to a fact. From 7cd161a9ad00b9fa74c9aee7543f25c3af24aafa Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 17:28:55 +0800 Subject: [PATCH 002/102] feat(types): intern summary types and compact the type node Phase 2a: ProjectIndex owns a TypeStore, DeclFact carries type_of_id/returns_id, and insert interns each non-empty spelling once. TypeKind is now 16 bytes: Named/Function argument lists live in an ArgsId arena, Array uses an UNKNOWN_EXTENT sentinel, spelling is a parallel table, NameInterner uses SmolStr and FxHashMap. The strings remain for the codec and current queries until the summary TypeTable lands. --- crates/cpp_code_analysis/src/cache/summary.rs | 19 +++ .../src/cache/summary_codec.rs | 14 ++ .../src/index/project/bases.rs | 3 + .../src/index/project/macro_environment.rs | 3 + .../src/index/project/macro_walk.rs | 27 +++ .../src/index/project/mod.rs | 3 + .../src/index/project/tests.rs | 38 +++++ .../cpp_code_analysis/src/index/types/mod.rs | 159 +++++++++++++----- .../src/sema/declarations.rs | 3 + .../src/session/completion/mod.rs | 3 + docs/type-system-redesign.md | 51 +++++- 11 files changed, 281 insertions(+), 42 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 30eec791..b27f14e6 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -32,6 +32,7 @@ use crate::Token; use crate::cache; use crate::condition; use crate::index; +use crate::index::types::TypeId; use crate::macros; use crate::paths; use crate::preprocess; @@ -237,6 +238,12 @@ pub struct DeclFact { /// 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 same type in the index's interned store** — [`TypeId::NONE`] until the summary is inserted. + /// + /// The string remains the transition field: a summary is built from syntax, and the store does not exist while + /// the parser is producing it. `ProjectIndex::insert_at` interns the spelling once and fills this handle; a + /// consumer that has the store uses it instead of parsing the string again. + pub type_of_id: TypeId, /// 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 @@ -256,6 +263,8 @@ pub struct DeclFact { /// `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, + /// The same return type in the index's interned store; see [`DeclFact::type_of_id`]. + pub returns_id: TypeId, /// **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 @@ -489,6 +498,16 @@ impl DeclarationAccounting { } impl DeclFact { + /// The interned form of [`DeclFact::type_of`], when the summary has been inserted into an index. + pub fn type_of_id(&self) -> Option { + (!self.type_of_id.is_none()).then_some(self.type_of_id) + } + + /// The interned form of [`DeclFact::returns`], when the summary has been inserted into an index. + pub fn returns_id(&self) -> Option { + (!self.returns_id.is_none()).then_some(self.returns_id) + } + /// 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) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index ed17eea8..06167623 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -26,6 +26,7 @@ use crate::DeclModifiers; use crate::DirectiveKind; use crate::FORMAT_VERSION; use crate::READING_FINGERPRINT; +use crate::index::types::TypeId; use crate::macros; use crate::preprocess; use crate::summary; @@ -1181,6 +1182,7 @@ mod tests { use crate::DeclModifiers; use crate::DirectiveKind; use crate::cache::SummaryKey; + use crate::index::types::TypeId; use crate::preprocess::directive::IncludeForm; use crate::summary; use crate::summary::MacroKind; @@ -1216,8 +1218,10 @@ mod tests { 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_id: TypeId::NONE, // A class returns nothing either, so `None` — and the second fact below covers the other value. returns: None, + returns_id: TypeId::NONE, // 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), @@ -1276,7 +1280,9 @@ mod tests { // 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, + type_of_id: TypeId::NONE, returns: Some("ns::Container".into()), + returns_id: TypeId::NONE, // 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, @@ -1304,7 +1310,9 @@ mod tests { kind: DeclKind::Other, modifiers: DeclModifiers::default(), type_of: None, + type_of_id: TypeId::NONE, returns: None, + returns_id: TypeId::NONE, access: None, exported: false, // A round trip that always wrote one value would not notice a decoder that dropped the byte. @@ -1697,7 +1705,9 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { modifiers, frees, type_of, + type_of_id: TypeId::NONE, returns: returns.map(SmolStr::from), + returns_id: TypeId::NONE, split_by_a_directive, range, name_range, @@ -2032,7 +2042,9 @@ fn a_cooked_reading_round_trips() { scope: Some("std".into()), kind: DeclKind::Type, type_of: None, + type_of_id: TypeId::NONE, returns: None, + returns_id: TypeId::NONE, range: SourceRange::new(10, 20), name_range: SourceRange::new(16, 6), local: false, @@ -2067,7 +2079,9 @@ fn a_cooked_reading_round_trips() { scope: None, kind: DeclKind::Function, type_of: Some("int".into()), + type_of_id: TypeId::NONE, returns: Some("void".into()), + returns_id: TypeId::NONE, range: SourceRange::new(40, 30), name_range: SourceRange::new(44, 1), local: true, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 73e2a86a..0764e06a 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -9,6 +9,7 @@ use crate::BindingKind; use crate::DeclKind; use crate::ScopeKind; use crate::ScopeTree; +use crate::index::types::TypeId; use crate::sema; use crate::summary; use cpp_parser::CppSyntaxNode; @@ -352,9 +353,11 @@ pub(crate) fn fact_from_binding_with( // (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. + type_of_id: TypeId::NONE, returns: sema::declarations::declared_returns_of_in(shapes, root, binding) .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)) .map(SmolStr::from), + returns_id: TypeId::NONE, // **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`]. // 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..18aaa30b 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -7,6 +7,7 @@ use crate::Binding; use crate::BindingKind; use crate::DeclKind; use crate::DeclModifiers; +use crate::index::types::TypeId; use smol_str::SmolStr; use super::*; @@ -510,7 +511,9 @@ impl ProjectDefinition { // belong to has the summary that holds them. A consumer asking what a name *is* asks the index, // not this answer. type_of: None, + type_of_id: TypeId::NONE, returns: None, + returns_id: TypeId::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 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..927d24ff 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -375,6 +375,32 @@ impl ProjectIndex { } } + /// **The interned types this index has built.** Append-only with the index; a summary's string fields remain + /// the transition source until the codec carries a local type table. + pub fn types(&self) -> &TypeStore { + &self.types + } + + /// **Intern every type spelling a summary carries, once**, before the summary is filed. Saves the string fields + /// from being parsed by every later query; a fact that already has a handle (a summary re-inserted from a store) + /// keeps it. + fn intern_the_types_of(&mut self, summary: &mut FileSummary) { + for fact in &mut summary.declarations { + if fact.type_of_id.is_none() + && let Some(type_of) = fact.type_of.as_deref() + && !type_of.trim().is_empty() + { + fact.type_of_id = self.types.intern_spelling(type_of); + } + if fact.returns_id.is_none() + && let Some(returns) = fact.returns.as_deref() + && !returns.trim().is_empty() + { + fact.returns_id = self.types.intern_spelling(returns); + } + } + } + /// 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, @@ -439,6 +465,7 @@ impl ProjectIndex { self.forget_macro_walks(path, known_to_the_index); let mut summary = summary; summary.path = path.to_path_buf(); + self.intern_the_types_of(&mut summary); let path = normalize(path); diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 561a0202..8b4b08ae 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -32,6 +32,7 @@ //! **guarded** include is reported as [`Known::Unknown`] rather than as visible or invisible — the same rule the //! rest of the crate follows, and the reason [`IncludeFact`](crate::summary::IncludeFact) carries a guard at all. +use super::types::TypeStore; use crate::CookedDiagnostic; use crate::IndexedRendering; use cpp_parser::SourceRange; @@ -343,6 +344,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 types of every declaration this index has inserted. + types: TypeStore, /// **What the cooked reading found**, by normalized path — the declarations a compiler sees, and the errors the /// parse of the rendering reported. /// diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 5365c9aa..1bd5db6d 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -90,6 +90,44 @@ fn index(files: &[(&str, &str)]) -> ProjectIndex { index } +/// **The index interns a summary's type spellings once**, and two declarations of one type share the handle. +/// +/// The string fields are still the source a query may read during the transition; this test pins the store's side +/// of the contract: insert fills `type_of_id`, and `int` is one node rather than one per declaration. +#[test] +fn the_index_interns_the_types_a_summary_declares_once() { + 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 ids: Vec<_> = stored + .declarations + .iter() + .filter_map(|fact| fact.type_of_id()) + .collect(); + assert_eq!( + ids.len(), + 3, + "every declaration with a written type got a handle" + ); + assert_eq!(ids[0], ids[1], "`int` is one interned type"); + assert_ne!(ids[0], ids[2], "`double` is another"); + assert_eq!(index.types().len(), 2, "int and double, once each"); + assert_eq!( + index + .types() + .type_ref(ids[0]) + .expect("the handle belongs to the store") + .display(), + "int" + ); +} + #[test] fn a_declaration_in_an_included_header_is_found() { let index = index(&[ diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 9f56e66f..e182b9e9 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -20,9 +20,11 @@ //! templates: those are index queries, and doing them here would make the cache depend on the whole project while //! it is still being built. -use std::collections::HashMap; use std::fmt; +use rustc_hash::FxHashMap; +use smol_str::SmolStr; + use crate::sema::types::Type; /// A handle to one node in a [`TypeStore`]. @@ -32,6 +34,10 @@ use crate::sema::types::Type; pub struct TypeId(u32); impl TypeId { + /// The sentinel a fact uses for "no type". Zero is a valid node, so the reserved value is the top of the + /// `u32` range and a store never hands it out. + pub const NONE: TypeId = TypeId(u32::MAX); + /// The index into the store's node vector. Public for diagnostics and tests; consumers should prefer /// [`TypeRef`]. pub fn index(self) -> usize { @@ -40,7 +46,16 @@ impl TypeId { /// The handle for the `index`th node, used by a decoder that is rebuilding a store. pub fn from_index(index: usize) -> TypeId { - TypeId(u32::try_from(index).expect("a type store with more than u32::MAX nodes")) + assert!( + index < u32::MAX as usize, + "a type store with more than u32::MAX - 1 nodes" + ); + TypeId(u32::try_from(index).expect("a type index that fits in u32")) + } + + /// Is this the sentinel rather than a node? + pub fn is_none(self) -> bool { + self == TypeId::NONE } } @@ -64,6 +79,28 @@ impl NameId { } } +/// A handle to one interned argument list. Keeping the list out of [`TypeKind`] is what makes a named type fit in +/// eight payload bytes — see the size assertion in the tests. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ArgsId(u32); + +impl ArgsId { + /// The empty list, which every argument-free type shares. + pub const EMPTY: ArgsId = ArgsId(u32::MAX); + + pub fn index(self) -> Option { + (self != ArgsId::EMPTY).then_some(self.0 as usize) + } + + pub fn from_index(index: usize) -> ArgsId { + assert!( + index < u32::MAX as usize, + "more argument lists than u32 can hold" + ); + ArgsId(index as u32) + } +} + /// **The structural shape of one type.** The spelling lives on [`TypeNode`], because the same shape may have been /// written two ways and a reader is owed the one in their file. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -73,7 +110,7 @@ pub enum TypeKind { /// `Widget`, `std::vector`, `T` before the context says it is a parameter. Named { name: NameId, - arguments: Box<[TypeId]>, + arguments: ArgsId, }, /// `T` inside a template body. TemplateParameter(NameId), @@ -89,12 +126,13 @@ pub enum TypeKind { }, Array { of: TypeId, - /// `Some(4)` for `int[4]`, `None` for `int[]`. - extent: Option, + /// The extent, or [`UNKNOWN_EXTENT`] for `int[]`. A sentinel rather than `Option` keeps this variant + /// inside the same eight payload bytes as the others. + extent: u64, }, Function { returns: TypeId, - parameters: Box<[TypeId]>, + parameters: ArgsId, }, Pack(TypeId), Qualified { @@ -103,13 +141,13 @@ pub enum TypeKind { }, } -/// One node: the shape and the spelling the source wrote, when it wrote one. +/// The extent written for `int[]`, and the value [`TypeKind::Array`] uses when the source wrote no bound. +pub const UNKNOWN_EXTENT: u64 = u64::MAX; + +/// One node: the shape of the type. The spelling is a parallel table in [`TypeStore`], so this stays 16 bytes. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct TypeNode { pub kind: TypeKind, - /// **The source spelling, kept for display.** `None` for a node the store synthesized (a substitution result, a - /// test), whose [`TypeRef::display`] is reconstructed from the shape. - pub spelling: Option, } /// The interning key. Two nodes with the same shape **and** the same spelling are one node; two spellings of one @@ -124,10 +162,10 @@ struct TypeKey { /// /// The table is deliberately small: no removal, no refcount, no generation. A `TypeStore` is rebuilt with the index /// generation it belongs to, and a summary's names are imported into it once. -#[derive(Default)] +#[derive(Debug, Default)] pub struct NameInterner { - names: Vec>, - ids: HashMap, NameId>, + names: Vec, + ids: FxHashMap, } impl NameInterner { @@ -136,9 +174,9 @@ impl NameInterner { return *id; } let id = NameId::from_index(self.names.len()); - let boxed: Box = spelling.into(); - self.names.push(boxed.clone()); - self.ids.insert(boxed, id); + let name = SmolStr::new(spelling); + self.names.push(name.clone()); + self.ids.insert(name, id); id } @@ -156,10 +194,13 @@ impl NameInterner { } /// **The type graph of one index generation**, hash-consed and append-only. -#[derive(Default)] +#[derive(Debug, Default)] pub struct TypeStore { nodes: Vec, - interned: HashMap, + spellings: Vec>, + arguments: Vec>, + argument_ids: FxHashMap, ArgsId>, + interned: FxHashMap, names: NameInterner, } @@ -199,7 +240,8 @@ impl TypeStore { return *id; } let id = TypeId::from_index(self.nodes.len()); - self.nodes.push(TypeNode { kind, spelling }); + self.nodes.push(TypeNode { kind }); + self.spellings.push(spelling); self.interned.insert(key, id); id } @@ -214,14 +256,17 @@ impl TypeStore { TypeKind::DecltypeAuto } Type::Builtin { spelling } => TypeKind::Builtin(self.names.intern(spelling.trim())), - Type::Named { name, arguments } => TypeKind::Named { - name: self.names.intern(name), - arguments: arguments + Type::Named { name, arguments } => { + let name = self.names.intern(name); + let arguments = arguments .iter() .map(|argument| self.intern_type(argument)) - .collect::>() - .into_boxed_slice(), - }, + .collect(); + TypeKind::Named { + name, + arguments: self.intern_arguments(arguments), + } + } Type::TemplateParameter { name } => { TypeKind::TemplateParameter(self.names.intern(name)) } @@ -232,19 +277,22 @@ impl TypeStore { }, Type::Array { of, extent } => TypeKind::Array { of: self.intern_type(of), - extent: extent.map(|extent| extent as u64), + extent: extent.map_or(UNKNOWN_EXTENT, |extent| extent as u64), }, Type::Function { returns, parameters, - } => TypeKind::Function { - returns: self.intern_type(returns), - parameters: parameters + } => { + let returns = self.intern_type(returns); + let parameters = parameters .iter() .map(|parameter| self.intern_type(parameter)) - .collect::>() - .into_boxed_slice(), - }, + .collect(); + TypeKind::Function { + returns, + parameters: self.intern_arguments(parameters), + } + } Type::Pack { of } => TypeKind::Pack(self.intern_type(of)), Type::Qualified { of, qualifiers } => TypeKind::Qualified { of: self.intern_type(of), @@ -254,6 +302,28 @@ impl TypeStore { self.intern(kind, Some(&spelling)) } + /// **Intern one argument sequence**, so two `std::vector` nodes share the same argument list as well as the + /// same name. An empty sequence is [`ArgsId::EMPTY`] and costs no arena slot. + pub fn intern_arguments(&mut self, arguments: Vec) -> ArgsId { + if arguments.is_empty() { + return ArgsId::EMPTY; + } + let arguments: Box<[TypeId]> = arguments.into_boxed_slice(); + if let Some(id) = self.argument_ids.get(&arguments) { + return *id; + } + let id = ArgsId::from_index(self.arguments.len()); + self.arguments.push(arguments.clone()); + self.argument_ids.insert(arguments, id); + id + } + + pub fn arguments(&self, id: ArgsId) -> &[TypeId] { + id.index() + .and_then(|at| self.arguments.get(at)) + .map_or(&[], |arguments| arguments) + } + /// **The entry point for a spelling that came from outside the syntax** — a cache record, a CLI argument, a /// test. Parsing remains one call, at this boundary; consumers below use [`TypeId`]. pub fn intern_spelling(&mut self, spelling: &str) -> TypeId { @@ -272,8 +342,10 @@ impl TypeStore { } pub fn spelling(&self, id: TypeId) -> Option<&str> { - let node = self.node(id)?; - node.spelling.and_then(|spelling| self.names.name(spelling)) + self.spellings + .get(id.index()) + .and_then(|spelling| *spelling) + .and_then(|spelling| self.names.name(spelling)) } } @@ -322,7 +394,7 @@ impl<'a> TypeRef<'a> { /// The template arguments written on the type, looking through a reference or a qualifier. pub fn arguments(self) -> &'a [TypeId] { match self.kind() { - TypeKind::Named { arguments, .. } => arguments, + TypeKind::Named { arguments, .. } => self.store.arguments(*arguments), TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { self.store.type_ref(*to).map_or(&[], TypeRef::arguments) } @@ -361,6 +433,7 @@ impl<'a> TypeRef<'a> { .to_string(), TypeKind::Named { name, arguments } => { let name = self.store.names.name(*name).unwrap_or(""); + let arguments = self.store.arguments(*arguments); if arguments.is_empty() { name.to_string() } else { @@ -385,9 +458,9 @@ impl<'a> TypeRef<'a> { ), TypeKind::Array { of, extent } => self.store.type_ref(*of).map_or_else( || "[]".to_string(), - |inner| match extent { - Some(extent) => format!("{}[{extent}]", inner.render()), - None => format!("{}[]", inner.render()), + |inner| match *extent { + UNKNOWN_EXTENT => format!("{}[]", inner.render()), + extent => format!("{}[{extent}]", inner.render()), }, ), TypeKind::Function { @@ -398,6 +471,7 @@ impl<'a> TypeRef<'a> { .store .type_ref(*returns) .map_or_else(|| "".to_string(), TypeRef::render); + let parameters = self.store.arguments(*parameters); let parameters = parameters .iter() .filter_map(|parameter| self.store.type_ref(*parameter)) @@ -422,8 +496,17 @@ impl<'a> TypeRef<'a> { mod tests { use super::*; use crate::sema::types::{Qualifiers, Type}; + use std::mem::size_of; use std::sync::Arc; + /// **The storage shape stays small.** `Named` is the variant that used to push `TypeKind` to 32 bytes; its + /// argument list lives in the store's arena, so the enum is one tag plus eight payload bytes. + #[test] + fn a_type_kind_is_sixteen_bytes() { + assert_eq!(size_of::(), 16); + assert_eq!(size_of::(), 16); + } + #[test] fn the_same_spelling_is_one_node() { let mut store = TypeStore::new(); diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 421bc435..18d42049 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -30,6 +30,7 @@ use crate::DeclModifiers; use crate::Name; +use crate::index::types::TypeId; use crate::scopes; use crate::sema; use crate::summary; @@ -4088,7 +4089,9 @@ fn fact_for( // that is not in a scope at all. See [`ScopeTree::declares_a_local`]. local, type_of: type_of.map(SmolStr::from), + type_of_id: TypeId::NONE, returns: returns.map(SmolStr::from), + returns_id: TypeId::NONE, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { in_namespace: in_namespace.map(Into::into), diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 82ad13d1..002a10e1 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2482,6 +2482,7 @@ mod tests { use super::*; use crate::DeclModifiers; use crate::FactGuard; + use crate::index::types::TypeId; use crate::summary; /// **A name that does not answer what was typed is dropped, not ranked low.** The rule itself lives in @@ -2543,7 +2544,9 @@ mod tests { kind: DeclKind::Function, modifiers: DeclModifiers::VIRTUAL, type_of: None, + type_of_id: TypeId::NONE, returns: returns.map(smol_str::SmolStr::from), + returns_id: TypeId::NONE, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), clean: true, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 1e3bda23..f1ea0ed9 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -93,16 +93,18 @@ pub struct TypeNode { pub spelling: Option, } +pub struct ArgsId(u32); + pub enum TypeKind { Builtin(NameId), - Named { name: NameId, arguments: Box<[TypeId]> }, + Named { name: NameId, arguments: ArgsId }, TemplateParameter(NameId), Auto, DecltypeAuto, Pointer(TypeId), Reference { to: TypeId, rvalue: bool }, - Array { of: TypeId, extent: Option }, - Function { returns: TypeId, parameters: Box<[TypeId]> }, + Array { of: TypeId, extent: u64 }, // UNKNOWN_EXTENT is the `int[]` sentinel + Function { returns: TypeId, parameters: ArgsId }, Pack(TypeId), Qualified { of: TypeId, qualifiers: Qualifiers }, } @@ -111,7 +113,12 @@ pub enum TypeKind { Design rules: * **`TypeId` is 4 bytes**, not an `Arc` pointer. A fact pays 8 bytes for two optional handles. -* **`Box<[TypeId]>`** for children: no capacity field, no spare allocation for the common zero/one-child cases. +* **`ArgsId` and an argument arena** for children: a `Box<[TypeId]>` is sixteen bytes before the enum tag, which + made `TypeKind` 32 bytes because of `Named` alone. The arena keeps the enum at **16 bytes**; the same argument + sequence is interned once and shared by every type that names it. +* **Spelling lives in a parallel table**, not on `TypeNode`, for the same reason: `TypeNode` stays 16 bytes. +* **`NameInterner` uses `SmolStr` and `rustc_hash::FxHashMap`**: most names fit inline, and the map is an internal + cache rather than a DoS-facing table. * **`NameInterner` owns the strings.** `TypeStore` hands out `NameId`; facts eventually store name IDs too. * **Append-only.** Nodes are never mutated. A file edit creates a new summary and a new generation; old handles either die with the generation or are dropped with the index. @@ -324,3 +331,39 @@ unit tests `DeclFact`, `DeclDetail`, the codec and every query remain untouched in that slice. The next slice starts by measuring interning on a real standard-library closure before adding a single field to a fact. + +## 10. One canonical type, not two + +There are currently two semantic enums: + +```text +sema::types::Type parser-facing, children are Arc transient +index::types::TypeKind storage-facing, children are TypeId canonical after Phase 3 +``` + +That duplication is **not the target**. It exists because the parser builds a type before an index/store exists. The +canonical representation is `index::types::TypeKind`/`TypeNode`; `sema::types::Type` is a construction and conversion +format, not a second semantic model. + +Phase 3 therefore moves `parse_type_spelling`, `type_of_declaration`, `class_name`, `substituted` and the type +operations onto `TypeStore`/`TypeRef`, then removes `sema::types::Type` (or leaves it only as a parser-internal +builder with no public type answers). A query must never choose which of two type enums to use. + +## 11. Progress + +**Phase 1 — done.** `index::types` has the store, handles, interning, spelling-preserving `TypeRef` and tests. +No consumer changed. + +**Phase 2a — in progress.** `ProjectIndex` owns a `TypeStore`; `DeclFact` carries `type_of_id` / `returns_id` +(with `TypeId::NONE` as the transition sentinel), and `ProjectIndex::insert_at` interns every non-empty spelling once. +The string fields remain the source of truth for the codec and all current queries; a summary read from disk gets +its handles when it is inserted. + +Still to do for Phase 2: + +* the per-summary `TypeTable` and its codec (the current IDs are deliberately not persisted); +* memory-report counters for store nodes and intern hits; +* migrating the first query (`class_name` / `members_of`) to the handles. + +The two fields add eight bytes to a fact until Phase 4 removes the strings; that is a deliberate temporary cost, not +the target shape. From 1102f00ddaacb0f923342c9652e91443cac5ef56 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:06:46 +0800 Subject: [PATCH 003/102] feat(types): persist the type table and add the computed type Phase 2b: FileSummary carries a local TypeTable, summary_codec writes/reads it and fact type IDs (CODEC_VERSION 41), and ProjectIndex::insert_at imports the table and rewrites local IDs. Add TypeStore::materialize -> ComputedType (<=32 bytes, SmolStr names, Arc children) so queries can compute without writing the store; add type-store counters to the memory report. --- crates/cpp_code_analysis/src/cache/memory.rs | 5 + crates/cpp_code_analysis/src/cache/summary.rs | 6 +- .../src/cache/summary_codec.rs | 162 +++++++- .../cpp_code_analysis/src/cache/unit_codec.rs | 1 + crates/cpp_code_analysis/src/index/mod.rs | 3 + .../src/index/project/macro_walk.rs | 23 ++ .../src/index/project/tests.rs | 31 ++ .../src/index/types/compute.rs | 198 ++++++++++ .../cpp_code_analysis/src/index/types/mod.rs | 345 ++++++++++++++++++ .../cpp_code_analysis/src/session/memory.rs | 5 + docs/type-system-redesign.md | 59 ++- 11 files changed, 813 insertions(+), 25 deletions(-) create mode 100644 crates/cpp_code_analysis/src/index/types/compute.rs diff --git a/crates/cpp_code_analysis/src/cache/memory.rs b/crates/cpp_code_analysis/src/cache/memory.rs index 43efbfa1..5b464406 100644 --- a/crates/cpp_code_analysis/src/cache/memory.rs +++ b/crates/cpp_code_analysis/src/cache/memory.rs @@ -48,6 +48,11 @@ pub struct MemoryReport { pub declarations: usize, pub declarations_with_detail: usize, pub declaration_detail_bytes: usize, + /// **The interned type store** — distinct types, names and argument lists, plus the store's estimated bytes. + pub types: usize, + pub type_names: usize, + pub type_argument_lists: usize, + pub type_store_bytes: usize, /// The cooked reading: how many files have one, and their estimated bytes. pub cooked_files: usize, pub cooked_bytes: usize, diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index b27f14e6..42852183 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -32,7 +32,7 @@ use crate::Token; use crate::cache; use crate::condition; use crate::index; -use crate::index::types::TypeId; +use crate::index::types::{TypeId, TypeTable}; use crate::macros; use crate::paths; use crate::preprocess; @@ -5321,6 +5321,9 @@ 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 type table.** Facts hold local IDs on disk; inserting into a `ProjectIndex` imports + /// this table and rewrites them to process-local handles. Empty for a summary built directly from syntax. + pub types: TypeTable, pub macros: Vec, pub includes: Vec, pub guards: SummaryGuards, @@ -5506,6 +5509,7 @@ impl FileSummary { path: path.into(), key, declarations: Vec::new(), + types: TypeTable::default(), macros: Vec::new(), includes: Vec::new(), guards: SummaryGuards::default(), diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 06167623..49653ed9 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -26,7 +26,7 @@ use crate::DeclModifiers; use crate::DirectiveKind; use crate::FORMAT_VERSION; use crate::READING_FINGERPRINT; -use crate::index::types::TypeId; +use crate::index::types::{EncodedType, EncodedTypeKind, TypeId, TypeTable}; use crate::macros; use crate::preprocess; use crate::summary; @@ -283,7 +283,7 @@ 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; +pub const CODEC_VERSION: u32 = 41; /// Write a summary as bytes. /// @@ -399,6 +399,11 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.use_filter.len() as u32); out.extend_from_slice(&summary.use_filter); + // **The local type table**, last for the same reason the filter is: the decoder reads the sections in the + // order they were written. A fact's IDs are local to this table; `ProjectIndex::insert_at` imports the table + // and rewrites them, so a process-local handle is never written to disk. + put_type_table(&mut out, &summary.types); + out } @@ -787,6 +792,8 @@ pub fn decode(bytes: &[u8]) -> Result { bytes }; + let types = get_type_table(&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. @@ -798,6 +805,7 @@ pub fn decode(bytes: &[u8]) -> Result { path, key, declarations, + types, macros, includes, guards, @@ -972,6 +980,129 @@ fn put_str(out: &mut Vec, value: &str) { out.extend_from_slice(value.as_bytes()); } +/// **The type table**, as a count-prefixed list of nodes. The IDs are the summary's local handles; they are +/// meaningful only beside this table and are rewritten when the summary is inserted into an index. +fn put_type_table(out: &mut Vec, table: &TypeTable) { + put_u32(out, table.entries.len() as u32); + for entry in &table.entries { + put_u32(out, entry.id); + put_opt_str(out, entry.spelling.as_deref()); + match &entry.kind { + EncodedTypeKind::Builtin(name) => { + put_u8(out, 0); + put_str(out, name); + } + EncodedTypeKind::Named { name, arguments } => { + put_u8(out, 1); + put_str(out, name); + put_u32(out, arguments.len() as u32); + for argument in arguments { + put_u32(out, *argument); + } + } + EncodedTypeKind::TemplateParameter(name) => { + put_u8(out, 2); + put_str(out, name); + } + EncodedTypeKind::Auto => put_u8(out, 3), + EncodedTypeKind::DecltypeAuto => put_u8(out, 4), + EncodedTypeKind::Pointer(to) => { + put_u8(out, 5); + put_u32(out, *to); + } + EncodedTypeKind::Reference { to, rvalue } => { + put_u8(out, 6); + put_u32(out, *to); + put_u8(out, u8::from(*rvalue)); + } + EncodedTypeKind::Array { of, extent } => { + put_u8(out, 7); + put_u32(out, *of); + put_u64(out, *extent); + } + EncodedTypeKind::Function { + returns, + parameters, + } => { + put_u8(out, 8); + put_u32(out, *returns); + put_u32(out, parameters.len() as u32); + for parameter in parameters { + put_u32(out, *parameter); + } + } + EncodedTypeKind::Pack(of) => { + put_u8(out, 9); + put_u32(out, *of); + } + EncodedTypeKind::Qualified { + of, + is_const, + is_volatile, + } => { + put_u8(out, 10); + put_u32(out, *of); + put_u8(out, u8::from(*is_const)); + put_u8(out, u8::from(*is_volatile)); + } + } + } +} + +fn get_type_table(reader: &mut Reader<'_>) -> Result { + let count = reader.count()?; + let mut entries = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + let id = reader.u32()?; + let spelling = reader.optional_string()?; + let kind = match reader.u8()? { + 0 => EncodedTypeKind::Builtin(reader.string()?), + 1 => { + let name = reader.string()?; + let count = reader.count()?; + let mut arguments = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + arguments.push(reader.u32()?); + } + EncodedTypeKind::Named { name, arguments } + } + 2 => EncodedTypeKind::TemplateParameter(reader.string()?), + 3 => EncodedTypeKind::Auto, + 4 => EncodedTypeKind::DecltypeAuto, + 5 => EncodedTypeKind::Pointer(reader.u32()?), + 6 => EncodedTypeKind::Reference { + to: reader.u32()?, + rvalue: reader.u8()? != 0, + }, + 7 => EncodedTypeKind::Array { + of: reader.u32()?, + extent: reader.u64()?, + }, + 8 => { + let returns = reader.u32()?; + let count = reader.count()?; + let mut parameters = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + parameters.push(reader.u32()?); + } + EncodedTypeKind::Function { + returns, + parameters, + } + } + 9 => EncodedTypeKind::Pack(reader.u32()?), + 10 => EncodedTypeKind::Qualified { + of: reader.u32()?, + is_const: reader.u8()? != 0, + is_volatile: reader.u8()? != 0, + }, + _ => return Err(DecodeError::BadDiscriminant), + }; + entries.push(EncodedType { id, spelling, kind }); + } + Ok(TypeTable { entries }) +} + fn put_opt_str(out: &mut Vec, value: Option<&str>) { match value { Some(text) => { @@ -1182,7 +1313,7 @@ mod tests { use crate::DeclModifiers; use crate::DirectiveKind; use crate::cache::SummaryKey; - use crate::index::types::TypeId; + use crate::index::types::{EncodedType, EncodedTypeKind, TypeId, TypeTable}; use crate::preprocess::directive::IncludeForm; use crate::summary; use crate::summary::MacroKind; @@ -1206,6 +1337,23 @@ 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], + types: TypeTable { + entries: vec![ + EncodedType { + id: 0, + spelling: Some("int".to_string()), + kind: EncodedTypeKind::Builtin("int".to_string()), + }, + EncodedType { + id: 1, + spelling: Some("std::pair".to_string()), + kind: EncodedTypeKind::Named { + name: "std::pair".to_string(), + arguments: vec![0, 0], + }, + }, + ], + }, declarations: vec![ DeclFact { // **The flag at `true`**, on this of the three declarations, so the byte is covered at both ends — the @@ -1572,7 +1720,9 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { 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_u32(out, fact.type_of_id.raw()); put_opt_str(out, fact.returns.as_deref()); + put_u32(out, fact.returns_id.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()); @@ -1658,7 +1808,9 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { 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 type_of_id = TypeId::from_raw(reader.u32()?); let returns = reader.optional_string()?; + let returns_id = TypeId::from_raw(reader.u32()?); let returns_in_the_class = reader.optional_string()?; let bases = get_strings(reader)?; let parameters = get_strings(reader)?; @@ -1705,9 +1857,9 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { modifiers, frees, type_of, - type_of_id: TypeId::NONE, + type_of_id, returns: returns.map(SmolStr::from), - returns_id: TypeId::NONE, + returns_id, split_by_a_directive, range, name_range, diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 0448985e..5ce7ded3 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -488,6 +488,7 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { path: path.to_path_buf(), key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), + types: crate::index::types::TypeTable::default(), macros: cooked.macros.clone(), includes: Vec::new(), guards: SummaryGuards::default(), diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index e060c3f6..f8ab8593 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::types::TypeTable; use crate::preprocess; use crate::sema; use crate::summary; @@ -959,6 +960,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { path: path.to_path_buf(), key, declarations, + types: TypeTable::default(), macros, includes, guards, @@ -1093,6 +1095,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(), + types: TypeTable::default(), macros, includes, guards, 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 927d24ff..791a0c34 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -385,6 +385,23 @@ impl ProjectIndex { /// from being parsed by every later query; a fact that already has a handle (a summary re-inserted from a store) /// keeps it. fn intern_the_types_of(&mut self, summary: &mut FileSummary) { + // **A summary read from the cache already has local handles.** Import its table first, rewrite the local + // IDs to this store's IDs, then fill only the facts the old format left without one. + if !summary.types.is_empty() { + let mapping = self.types.import(&summary.types); + for fact in &mut summary.declarations { + if !fact.type_of_id.is_none() + && let Some(store_id) = mapping.get(&(fact.type_of_id.index() as u32)) + { + fact.type_of_id = *store_id; + } + if !fact.returns_id.is_none() + && let Some(store_id) = mapping.get(&(fact.returns_id.index() as u32)) + { + fact.returns_id = *store_id; + } + } + } for fact in &mut summary.declarations { if fact.type_of_id.is_none() && let Some(type_of) = fact.type_of.as_deref() @@ -399,6 +416,12 @@ impl ProjectIndex { fact.returns_id = self.types.intern_spelling(returns); } } + let ids: Vec<_> = summary + .declarations + .iter() + .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .collect(); + summary.types = self.types.export(ids); } /// Add or replace one file's summary. diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 1bd5db6d..32589e30 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -128,6 +128,37 @@ fn the_index_interns_the_types_a_summary_declares_once() { ); } +/// **A summary's local type table is imported, not trusted.** Encode/decode a real inserted summary, then insert the +/// decoded copy into a fresh index: the IDs are rewritten to the new store and the display survives. +#[test] +fn a_cached_summary_remaps_its_type_ids_on_insert() { + let path = Path::new("/p/types.cpp"); + let source = "int first;\nstd::vector items;\n"; + let mut first = ProjectIndex::new(); + first.insert(summarize(path, source, SummaryKey::new(0, 0))); + let stored = first.summary(path).expect("inserted"); + let decoded = crate::cache::summary_codec::decode(&crate::cache::summary_codec::encode(stored)) + .expect("the summary round-trips"); + + 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") + .and_then(|fact| fact.type_of_id()) + .expect("the vector declaration kept a type"); + assert_eq!( + second + .types() + .type_ref(vector) + .expect("the imported handle") + .display(), + "std::vector" + ); +} + #[test] fn a_declaration_in_an_included_header_is_found() { let index = index(&[ 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..b4e8b65b --- /dev/null +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -0,0 +1,198 @@ +//! **The computed type** — what a query works on, separate from the index's compact storage. +//! +//! [`TypeStore`](super::TypeStore) is append-only and written only by the indexing side. A query must not intern a +//! temporary type into it: that would put a write lock on the path every hover, completion and inlay request takes, +//! and the whole point of the read side is that many readers can run at once. +//! +//! So a fact stores a [`TypeId`](super::TypeId), and a query materializes the small amount it needs into this type: +//! +//! ```text +//! storage computation +//! TypeKind, 16 bytes ComputedType, 32 bytes +//! IDs, arena-owned names SmolStr names, Arc children +//! immutable after indexing owned by the request / SemanticModel +//! ``` +//! +//! The large variants are boxed (`Named`, `Function`, `Qualified`) so the enum stays 32 bytes. A `SmolStr` is a small +//! copy from the store's name table; a long name shares its `Arc` with the store. The result is cheap to build +//! and cheap to clone, and it owns no borrow of the index. +use std::fmt; +use std::sync::Arc; + +use smol_str::SmolStr; + +/// A name and its arguments — boxed inside [`ComputedType::Named`] so the enum's inline size stays small. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct NamedType { + 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, +} + +/// **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 { + Builtin(SmolStr), + Named(Arc), + TemplateParameter(SmolStr), + Auto, + DecltypeAuto, + Pointer(Arc), + Reference { + to: Arc, + rvalue: bool, + }, + Array { + of: Arc, + extent: Option, + }, + Function(Arc), + Pack(Arc), + Qualified(Arc), +} + +impl ComputedType { + pub fn named(name: impl Into, arguments: Vec) -> ComputedType { + ComputedType::Named(Arc::new(NamedType { + name: name.into(), + arguments: arguments.into_boxed_slice(), + })) + } + + /// The class this type names, looking through a reference or a qualifier. A pointer is not transparent. + pub fn class_name(&self) -> Option<&str> { + match self { + ComputedType::Named(named) => Some(named.name.as_str()), + ComputedType::Reference { to, .. } => to.class_name(), + ComputedType::Qualified(qualified) => qualified.of.class_name(), + _ => None, + } + } + + /// The template arguments written on the type, looking through a reference or a qualifier. + pub fn arguments(&self) -> &[ComputedType] { + match self { + ComputedType::Named(named) => &named.arguments, + ComputedType::Reference { to, .. } => to.arguments(), + ComputedType::Qualified(qualified) => qualified.of.arguments(), + _ => &[], + } + } + + pub fn is_const(&self) -> bool { + match self { + ComputedType::Qualified(qualified) => qualified.is_const, + ComputedType::Reference { to, .. } => to.is_const(), + _ => false, + } + } + + pub fn pointee(&self) -> Option<&ComputedType> { + match self { + ComputedType::Pointer(to) => Some(to), + _ => None, + } + } +} + +impl fmt::Display for ComputedType { + fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => { + write!(out, "{name}") + } + ComputedType::Named(named) => { + if named.arguments.is_empty() { + write!(out, "{}", named.name) + } else { + write!(out, "{}<", named.name)?; + for (at, argument) in named.arguments.iter().enumerate() { + if at > 0 { + write!(out, ", ")?; + } + write!(out, "{argument}")?; + } + write!(out, ">") + } + } + ComputedType::Auto => write!(out, "auto"), + ComputedType::DecltypeAuto => write!(out, "decltype(auto)"), + ComputedType::Pointer(to) => write!(out, "{to}*"), + ComputedType::Reference { to, rvalue } => { + write!(out, "{to}{}", if *rvalue { "&&" } else { "&" }) + } + ComputedType::Array { of, extent } => { + write!(out, "{of}[")?; + if let Some(extent) = extent { + write!(out, "{extent}")?; + } + write!(out, "]") + } + ComputedType::Function(function) => { + write!(out, "{}(", function.returns)?; + for (at, parameter) in function.parameters.iter().enumerate() { + if at > 0 { + write!(out, ", ")?; + } + write!(out, "{parameter}")?; + } + write!(out, ")") + } + ComputedType::Pack(of) => write!(out, "{of}..."), + ComputedType::Qualified(qualified) => { + let mut separators = Vec::new(); + if qualified.is_const { + separators.push("const"); + } + if qualified.is_volatile { + separators.push("volatile"); + } + if separators.is_empty() { + write!(out, "{}", qualified.of) + } else { + write!(out, "{} {}", separators.join(" "), qualified.of) + } + } + } + } +} + +#[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::() + ); + } + + #[test] + fn a_boxed_named_type_renders_and_answers_members() { + let value = ComputedType::named( + "std::vector", + vec![ComputedType::Builtin(SmolStr::new("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"); + } +} diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index e182b9e9..8fdad11f 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -27,6 +27,9 @@ use smol_str::SmolStr; use crate::sema::types::Type; +pub mod compute; +pub use compute::{ComputedType, FunctionType, NamedType, QualifiedType}; + /// A handle to one node in a [`TypeStore`]. /// /// Four bytes, `Copy`, and meaningful only with the store that produced it. A [`TypeRef`] keeps the two together. @@ -44,6 +47,16 @@ impl TypeId { self.0 as usize } + /// The raw value, for a codec that writes it beside the summary's type table. + pub fn raw(self) -> u32 { + self.0 + } + + /// A value read back from a codec; `u32::MAX` is [`TypeId::NONE`]. + pub fn from_raw(raw: u32) -> TypeId { + TypeId(raw) + } + /// The handle for the `index`th node, used by a decoder that is rebuilding a store. pub fn from_index(index: usize) -> TypeId { assert!( @@ -184,6 +197,11 @@ impl NameInterner { self.names.get(id.index()).map(|name| &**name) } + /// A `SmolStr` copy for a computed type: short names are inline, long names share the `Arc`. + pub fn smol(&self, id: NameId) -> Option { + self.name(id).map(SmolStr::new) + } + pub fn len(&self) -> usize { self.names.len() } @@ -347,6 +365,302 @@ impl TypeStore { .and_then(|spelling| *spelling) .and_then(|spelling| self.names.name(spelling)) } + + /// **Build the computation-side type for one handle.** No mutation: a query can call this while other readers + /// use the same store, and the result owns its names (or shares their long backing strings) and its children. + pub fn materialize(&self, id: TypeId) -> Option { + let node = self.node(id)?; + Some(match &node.kind { + TypeKind::Builtin(name) => ComputedType::Builtin(self.names.smol(*name)?), + TypeKind::Named { name, arguments } => { + ComputedType::Named(std::sync::Arc::new(NamedType { + name: self.names.smol(*name)?, + arguments: self + .arguments(*arguments) + .iter() + .filter_map(|argument| self.materialize(*argument)) + .collect::>() + .into_boxed_slice(), + })) + } + TypeKind::TemplateParameter(name) => { + ComputedType::TemplateParameter(self.names.smol(*name)?) + } + TypeKind::Auto => ComputedType::Auto, + TypeKind::DecltypeAuto => ComputedType::DecltypeAuto, + TypeKind::Pointer(to) => { + ComputedType::Pointer(std::sync::Arc::new(self.materialize(*to)?)) + } + TypeKind::Reference { to, rvalue } => ComputedType::Reference { + to: std::sync::Arc::new(self.materialize(*to)?), + rvalue: *rvalue, + }, + TypeKind::Array { of, extent } => ComputedType::Array { + of: std::sync::Arc::new(self.materialize(*of)?), + extent: (*extent != UNKNOWN_EXTENT).then_some(*extent), + }, + TypeKind::Function { + returns, + parameters, + } => ComputedType::Function(std::sync::Arc::new(FunctionType { + returns: std::sync::Arc::new(self.materialize(*returns)?), + parameters: self + .arguments(*parameters) + .iter() + .filter_map(|parameter| self.materialize(*parameter)) + .collect::>() + .into_boxed_slice(), + })), + TypeKind::Pack(of) => ComputedType::Pack(std::sync::Arc::new(self.materialize(*of)?)), + TypeKind::Qualified { of, qualifiers } => { + ComputedType::Qualified(std::sync::Arc::new(QualifiedType { + of: std::sync::Arc::new(self.materialize(*of)?), + is_const: qualifiers.is_const(), + is_volatile: qualifiers.is_volatile(), + })) + } + }) + } + + /// **Collect every node reachable from `ids` into a self-contained table.** Children always have lower IDs than + /// the nodes that name them, because interning is post-order, so a decoder can import entries in ascending ID + /// order without a second topological sort. + pub fn export(&self, ids: impl IntoIterator) -> TypeTable { + let mut seen = FxHashMap::::default(); + let mut pending: Vec = ids.into_iter().collect(); + let mut entries: Vec = Vec::new(); + while let Some(id) = pending.pop() { + if id.is_none() || seen.insert(id.0, ()).is_some() { + continue; + } + let Some(node) = self.node(id) else { + continue; + }; + let kind = match &node.kind { + TypeKind::Builtin(name) => { + EncodedTypeKind::Builtin(self.names.name(*name).unwrap_or_default().to_string()) + } + TypeKind::Named { name, arguments } => { + let arguments = self.arguments(*arguments).to_vec(); + pending.extend(arguments.iter().copied()); + EncodedTypeKind::Named { + name: self.names.name(*name).unwrap_or_default().to_string(), + arguments: arguments.iter().map(|id| id.0).collect(), + } + } + TypeKind::TemplateParameter(name) => EncodedTypeKind::TemplateParameter( + self.names.name(*name).unwrap_or_default().to_string(), + ), + TypeKind::Auto => EncodedTypeKind::Auto, + TypeKind::DecltypeAuto => EncodedTypeKind::DecltypeAuto, + TypeKind::Pointer(to) => { + pending.push(*to); + EncodedTypeKind::Pointer(to.0) + } + TypeKind::Reference { to, rvalue } => { + pending.push(*to); + EncodedTypeKind::Reference { + to: to.0, + rvalue: *rvalue, + } + } + TypeKind::Array { of, extent } => { + pending.push(*of); + EncodedTypeKind::Array { + of: of.0, + extent: *extent, + } + } + TypeKind::Function { + returns, + parameters, + } => { + let parameters = self.arguments(*parameters).to_vec(); + pending.push(*returns); + pending.extend(parameters.iter().copied()); + EncodedTypeKind::Function { + returns: returns.0, + parameters: parameters.iter().map(|id| id.0).collect(), + } + } + TypeKind::Pack(of) => { + pending.push(*of); + EncodedTypeKind::Pack(of.0) + } + TypeKind::Qualified { of, qualifiers } => { + pending.push(*of); + EncodedTypeKind::Qualified { + of: of.0, + is_const: qualifiers.is_const(), + is_volatile: qualifiers.is_volatile(), + } + } + }; + entries.push(EncodedType { + id: id.0, + spelling: self.spelling(id).map(str::to_string), + kind, + }); + } + entries.sort_by_key(|entry| entry.id); + TypeTable { entries } + } + + /// **Import a summary's local table into this store**, returning the old-ID to store-ID map. + /// + /// Entries are sorted by their local ID; a child therefore always precedes the node that names it. + pub fn import(&mut self, table: &TypeTable) -> FxHashMap { + use crate::sema::types::Qualifiers; + let mut map = FxHashMap::::default(); + for entry in &table.entries { + let child = |map: &FxHashMap, id: u32| { + map.get(&id).copied().unwrap_or(TypeId::NONE) + }; + let kind = match &entry.kind { + EncodedTypeKind::Builtin(name) => TypeKind::Builtin(self.names.intern(name)), + EncodedTypeKind::Named { name, arguments } => { + let arguments = arguments.iter().map(|id| child(&map, *id)).collect(); + TypeKind::Named { + name: self.names.intern(name), + arguments: self.intern_arguments(arguments), + } + } + EncodedTypeKind::TemplateParameter(name) => { + TypeKind::TemplateParameter(self.names.intern(name)) + } + EncodedTypeKind::Auto => TypeKind::Auto, + EncodedTypeKind::DecltypeAuto => TypeKind::DecltypeAuto, + EncodedTypeKind::Pointer(to) => TypeKind::Pointer(child(&map, *to)), + EncodedTypeKind::Reference { to, rvalue } => TypeKind::Reference { + to: child(&map, *to), + rvalue: *rvalue, + }, + EncodedTypeKind::Array { of, extent } => TypeKind::Array { + of: child(&map, *of), + extent: *extent, + }, + EncodedTypeKind::Function { + returns, + parameters, + } => { + let parameters = parameters.iter().map(|id| child(&map, *id)).collect(); + TypeKind::Function { + returns: child(&map, *returns), + parameters: self.intern_arguments(parameters), + } + } + EncodedTypeKind::Pack(of) => TypeKind::Pack(child(&map, *of)), + EncodedTypeKind::Qualified { + of, + is_const, + is_volatile, + } => { + let mut qualifiers = Qualifiers::NONE; + if *is_const { + qualifiers = qualifiers.with(Qualifiers::CONST); + } + if *is_volatile { + qualifiers = qualifiers.with(Qualifiers::VOLATILE); + } + TypeKind::Qualified { + of: child(&map, *of), + qualifiers, + } + } + }; + let id = self.intern(kind, entry.spelling.as_deref()); + map.insert(entry.id, id); + } + map + } + + /// **What the store costs**, in the same lower-bound style as [`crate::MemoryReport`]: live nodes, live names, + /// argument-list payloads, and the maps' table entries. Spare capacity is not counted. + pub fn accounting(&self) -> TypeAccounting { + let argument_payload = self + .arguments + .iter() + .map(|arguments| arguments.len() * size_of::()) + .sum::(); + TypeAccounting { + types: self.nodes.len(), + names: self.names.len(), + argument_lists: self.arguments.len(), + bytes: self.nodes.len() * size_of::() + + self.spellings.len() * size_of::>() + + self.arguments.len() * size_of::>() + + argument_payload + + self.argument_ids.len() * size_of::<(Box<[TypeId]>, ArgsId)>() + + self.interned.len() * size_of::<(TypeKey, TypeId)>() + + self + .names + .names + .iter() + .map(|name| name.len()) + .sum::() + + self.names.ids.len() * size_of::<(SmolStr, NameId)>(), + } + } +} + +/// **One type as a summary writes it** — local IDs, names as strings, argument lists inline. The process-local +/// [`TypeStore`] is rebuilt from a table when the summary is loaded. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TypeTable { + pub entries: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EncodedType { + pub id: u32, + pub spelling: Option, + pub kind: EncodedTypeKind, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EncodedTypeKind { + Builtin(String), + Named { + name: String, + arguments: Vec, + }, + TemplateParameter(String), + Auto, + DecltypeAuto, + Pointer(u32), + Reference { + to: u32, + rvalue: bool, + }, + Array { + of: u32, + extent: u64, + }, + Function { + returns: u32, + parameters: Vec, + }, + Pack(u32), + Qualified { + of: u32, + is_const: bool, + is_volatile: bool, + }, +} + +impl TypeTable { + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } +} + +/// The store's contribution to the session's memory report. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TypeAccounting { + pub types: usize, + pub names: usize, + pub argument_lists: usize, + pub bytes: usize, } /// **A type handle with the store that gives it meaning.** The borrow is what makes it impossible to use an ID @@ -501,6 +815,37 @@ mod tests { /// **The storage shape stays small.** `Named` is the variant that used to push `TypeKind` to 32 bytes; its /// argument list lives in the store's arena, so the enum is one tag plus eight payload bytes. + #[test] + fn a_stored_type_materializes_without_touching_the_store() { + let mut store = TypeStore::new(); + let stored = store.intern_spelling("std::vector"); + let before = store.len(); + let computed = store.materialize(stored).expect("materialized"); + assert_eq!(computed.to_string(), "std::vector"); + assert_eq!(computed.class_name(), Some("std::vector")); + assert_eq!(store.len(), before, "materializing interned nothing"); + } + + #[test] + fn a_type_table_round_trips_every_node_a_fact_needs() { + let mut store = TypeStore::new(); + let written = store.intern_spelling("std::vector"); + let table = store.export([written]); + assert!(!table.is_empty()); + + let mut loaded = TypeStore::new(); + let mapping = loaded.import(&table); + let restored = mapping[&written.0]; + assert_eq!( + loaded.type_ref(restored).unwrap().display(), + "std::vector" + ); + assert_eq!( + loaded.type_ref(restored).unwrap().class_name(), + Some("std::vector") + ); + } + #[test] fn a_type_kind_is_sixteen_bytes() { assert_eq!(size_of::(), 16); diff --git a/crates/cpp_code_analysis/src/session/memory.rs b/crates/cpp_code_analysis/src/session/memory.rs index fa476f71..d032abb7 100644 --- a/crates/cpp_code_analysis/src/session/memory.rs +++ b/crates/cpp_code_analysis/src/session/memory.rs @@ -139,6 +139,7 @@ impl Session { let (summaries, summary_bytes, cooked_files, cooked_bytes) = self.store.index().accounting(); let declarations = self.store.index().declaration_accounting(); + let types = self.store.index().types().accounting(); let (definitions, definition_bytes) = self .definitions .lock() @@ -221,6 +222,10 @@ impl Session { declarations: declarations.declarations, declarations_with_detail: declarations.with_detail, declaration_detail_bytes: declarations.detail_bytes, + types: types.types, + type_names: types.names, + type_argument_lists: types.argument_lists, + type_store_bytes: types.bytes, cooked_files, cooked_bytes, cooked_budget_bytes: self.store.index().cooked_budget_bytes(), diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index f1ea0ed9..e1c61e2c 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -332,38 +332,59 @@ unit tests `DeclFact`, `DeclDetail`, the codec and every query remain untouched in that slice. The next slice starts by measuring interning on a real standard-library closure before adding a single field to a fact. -## 10. One canonical type, not two +## 10. Storage and computation are two different jobs -There are currently two semantic enums: +The two layers are deliberate, and they are not two semantic models: ```text -sema::types::Type parser-facing, children are Arc transient -index::types::TypeKind storage-facing, children are TypeId canonical after Phase 3 +index::types::TypeKind / TypeId storage: 16-byte nodes, append-only, writer-only +index::types::ComputedType computation: <=32 bytes, owned by a request/model +sema::types::Type parser bridge: the syntax-facing construction format ``` -That duplication is **not the target**. It exists because the parser builds a type before an index/store exists. The -canonical representation is `index::types::TypeKind`/`TypeNode`; `sema::types::Type` is a construction and conversion -format, not a second semantic model. +`TypeId` is assigned only while indexing. A query must never call `intern*`: the store is read-only for readers, which +is what keeps hover, completion and inlay on different threads from serializing on a write lock. -Phase 3 therefore moves `parse_type_spelling`, `type_of_declaration`, `class_name`, `substituted` and the type -operations onto `TypeStore`/`TypeRef`, then removes `sema::types::Type` (or leaves it only as a parser-internal -builder with no public type answers). A query must never choose which of two type enums to use. +A query materializes what it needs: + +```rust +let computed: ComputedType = index.types().materialize(fact.type_of_id())?; +``` + +`ComputedType`: + +* is at most 32 bytes (`size_of` is asserted); +* copies names from the store as `SmolStr` — short names inline, long names share the store's `Arc`; +* shares children through `Arc`, so substitution and member walks are pointer copies; +* owns no borrow of the index and writes nothing; +* is cached by the request's `SemanticModel`, not by the global index. + +`Named`, `Function` and `Qualified` are boxed inside `ComputedType` so the enum stays in the budget. `sema::types::Type` +is the parser bridge; Phase 3 makes `ComputedType` the query-facing type and reduces `sema::types::Type` to +construction/conversion (or removes it). ## 11. Progress **Phase 1 — done.** `index::types` has the store, handles, interning, spelling-preserving `TypeRef` and tests. No consumer changed. -**Phase 2a — in progress.** `ProjectIndex` owns a `TypeStore`; `DeclFact` carries `type_of_id` / `returns_id` +**Phase 2a — done.** `ProjectIndex` owns a `TypeStore`; `DeclFact` carries `type_of_id` / `returns_id` (with `TypeId::NONE` as the transition sentinel), and `ProjectIndex::insert_at` interns every non-empty spelling once. -The string fields remain the source of truth for the codec and all current queries; a summary read from disk gets -its handles when it is inserted. +`TypeKind` and `TypeNode` are 16 bytes. + +**Phase 2b — done.** `FileSummary` carries a local `TypeTable`; `summary_codec` writes and reads it with +`CODEC_VERSION` 41. Fact IDs are written beside the strings; decoding leaves them local, and +`ProjectIndex::insert_at` imports the table and rewrites them to store handles. The round trip is covered by +`a_cached_summary_remaps_its_type_ids_on_insert`. `TypeStore::materialize` builds `ComputedType` without mutation; +`ComputedType` is asserted to be <= 32 bytes. The memory report has `types`, `type_names`, `type_argument_lists` and +`type_store_bytes`. -Still to do for Phase 2: +Still to do: -* the per-summary `TypeTable` and its codec (the current IDs are deliberately not persisted); -* memory-report counters for store nodes and intern hits; -* migrating the first query (`class_name` / `members_of`) to the handles. +* migrate the first query (`class_name` / `members_of`) to `ComputedType`; +* remove the fact strings and shrink `DeclFact` to the target shape; +* add the summary type-table size to `summary_bytes` and its display. +* remove `sema::types::Type` as a public query type. -The two fields add eight bytes to a fact until Phase 4 removes the strings; that is a deliberate temporary cost, not -the target shape. +The two ID fields add eight bytes to a fact until Phase 4 removes the strings; that is a deliberate temporary cost, +not the target shape. From d7d4f061e504d124cb18f6b490d885efd190c3ee Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:15:06 +0800 Subject: [PATCH 004/102] feat(types): add the fact-to-computed-type query bridge ProjectIndex::computed_type_of materializes a fact's stored TypeId with no interning; the namespace-alias query now uses it before falling back to the transition string. This is the first query-side use of ComputedType. --- .../cpp_code_analysis/src/index/project/macro_walk.rs | 7 +++++++ crates/cpp_code_analysis/src/index/project/members.rs | 11 ++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) 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 791a0c34..5c1b1cfa 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -12,6 +12,7 @@ use crate::UnlistedBase; use crate::Visibility; use crate::cache; use crate::index; +use crate::index::types::ComputedType; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -381,6 +382,12 @@ impl ProjectIndex { &self.types } + /// **The computation-side type of a declaration's `type_of`**, when the fact has a storage handle. This is the + /// read-side bridge from [`DeclFact::type_of_id`] to [`ComputedType`]; it never interns. + pub fn computed_type_of(&self, fact: &DeclFact) -> Option { + self.types.materialize(fact.type_of_id()?) + } + /// **Intern every type spelling a summary carries, once**, before the summary is filed. Saves the string fields /// from being parsed by every later query; a fact that already has a handle (a summary re-inserted from a store) /// keeps it. diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 55e450b5..d984f042 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -340,7 +340,16 @@ pub(crate) fn a_namespace_aliass_target( 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()) + .or_else(|| { + found + .fact + .type_of + .clone() + .map(|written| written.to_string()) + })?; if written.contains("::") || written.is_empty() { return Some(written); } From 29bb6f190e48dcb26f1e0ffe3e51431d9959365d Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:21:37 +0800 Subject: [PATCH 005/102] feat(types): cache computed types per request ProjectIndex::computed_type_of bridges a fact's stored handle to ComputedType without interning, and SemanticModel owns a request-scoped TypeId -> ComputedType cache so one member walk does not copy the same type repeatedly. The namespace-alias query is the first consumer; the design doc records the bridge and the remaining query migration. --- crates/cpp_code_analysis/src/sema/model.rs | 17 +++++++++++++++++ docs/type-system-redesign.md | 13 +++++++++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index 23ea1a6d..fd8fd8b2 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -53,6 +53,7 @@ use std::path::{Path, PathBuf}; use cpp_parser::CppSyntaxNode; use crate::index::project::{self, MemberList, ProjectIndex}; +use crate::index::types::{ComputedType, TypeId}; use crate::sema::types::Type; use crate::{Known, ScopeTree}; @@ -74,6 +75,10 @@ pub struct SemanticModel<'a> { /// shared model is the ordinary case, and a check that had to hold `&mut` would not be able to ask two questions /// while iterating the file. types: project::TypeMemo, + /// **The computed form of the storage handles this request has already materialized.** Materializing copies names + /// and shares children; one member walk asks the same handle many times, and the request, not the index, is the + /// right owner of that cache. + computed: RefCell>, /// **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>>, @@ -109,6 +114,7 @@ impl<'a> SemanticModel<'a> { path, resolver: RefCell::new(resolver), types: project::TypeMemo::default(), + computed: RefCell::new(BTreeMap::new()), members: RefCell::new(BTreeMap::new()), shapes: sema::declarations::ShapeTable::new(), } @@ -148,6 +154,17 @@ impl<'a> SemanticModel<'a> { ) } + /// **Materialize a stored handle once per request.** The store stays read-only; this is the computation-side + /// cache the query is allowed to own. + pub fn computed_type(&self, id: TypeId) -> Option { + if let Some(found) = self.computed.borrow().get(&id) { + return Some(found.clone()); + } + let found = self.index.types().materialize(id)?; + self.computed.borrow_mut().insert(id, found.clone()); + Some(found) + } + /// **The members of a class, inherited ones included** — see [`project::members_of`]. /// pub fn members_of(&self, class: &str) -> Known { diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index e1c61e2c..f100f410 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -379,11 +379,20 @@ No consumer changed. `ComputedType` is asserted to be <= 32 bytes. The memory report has `types`, `type_names`, `type_argument_lists` and `type_store_bytes`. +**Phase 3 — started.** + +* `ProjectIndex::computed_type_of` is the first read-side bridge from a fact handle to `ComputedType`; the + namespace-alias member query uses it before the transition string. +* `SemanticModel` owns a request-scoped `computed` cache, keyed by `TypeId`; `materialize` is called at most once per + handle per request, and the cache is dropped with the model. +* `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. + Still to do: -* migrate the first query (`class_name` / `members_of`) to `ComputedType`; +* migrate the bulk of `class_name` / `members_of` / `type_at` to `ComputedType` and delete their + `parse_type_spelling` calls; * remove the fact strings and shrink `DeclFact` to the target shape; -* add the summary type-table size to `summary_bytes` and its display. +* add the summary type-table size to `summary_bytes` and its display; * remove `sema::types::Type` as a public query type. The two ID fields add eight bytes to a fact until Phase 4 removes the strings; that is a deliberate temporary cost, From 5ea590932e3a3ef18b262fb1f2324a60d679260d Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:30:23 +0800 Subject: [PATCH 006/102] feat(types): account for the summary type tables TypeTable::heap_bytes counts encoded entries, spellings and argument vectors; FileSummary::heap_bytes includes it, and the memory report prints the interned store's types, names, argument lists and bytes. This closes the measurement gap created by persisting type tables. --- crates/cpp_code_analysis/src/cache/memory.rs | 8 +++++++ crates/cpp_code_analysis/src/cache/summary.rs | 1 + .../cpp_code_analysis/src/index/types/mod.rs | 23 +++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/crates/cpp_code_analysis/src/cache/memory.rs b/crates/cpp_code_analysis/src/cache/memory.rs index 5b464406..fea6841f 100644 --- a/crates/cpp_code_analysis/src/cache/memory.rs +++ b/crates/cpp_code_analysis/src/cache/memory.rs @@ -231,6 +231,14 @@ impl std::fmt::Display for MemoryReport { mb(self.walks_by_content_bytes), mb(self.shared_timeline_bytes), )?; + write!( + formatter, + " | types {} ({} name(s), {} argument list(s), {})", + thousands(self.types), + thousands(self.type_names), + thousands(self.type_argument_lists), + mb(self.type_store_bytes), + )?; write!( formatter, " | index tables {} ({} name(s) / {} name posting(s), {} scope(s) / {} scope posting(s), \ diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 42852183..7f99209d 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -1465,6 +1465,7 @@ impl FileSummary { .iter() .map(DeclFact::heap_bytes) .sum::() + + self.types.heap_bytes() + self.macros.iter().map(MacroFact::heap_bytes).sum::() + self .includes diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 8fdad11f..70b3727d 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -652,6 +652,29 @@ impl TypeTable { pub fn is_empty(&self) -> bool { self.entries.is_empty() } + + /// The encoded table's heap cost: entries, spelling strings, named and function argument vectors. + pub fn heap_bytes(&self) -> usize { + self.entries.len() * size_of::() + + self + .entries + .iter() + .map(|entry| { + entry.spelling.as_ref().map_or(0, String::len) + + match &entry.kind { + EncodedTypeKind::Named { name, arguments } => { + name.len() + arguments.len() * size_of::() + } + EncodedTypeKind::Function { parameters, .. } => { + parameters.len() * size_of::() + } + EncodedTypeKind::Builtin(name) + | EncodedTypeKind::TemplateParameter(name) => name.len(), + _ => 0, + } + }) + .sum::() + } } /// The store's contribution to the session's memory report. From b34c8dbec2b7b4f96c94885935b3c7792a9a7a75 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:39:21 +0800 Subject: [PATCH 007/102] feat(types): use the stored handle in the pointee member path ComputedType::to_sema_type converts the computation type back to the parser-facing shape without parsing; the pointee/element_type member path now materializes the fact's TypeId and applies bindings to that structure, falling back to parse_type_spelling only for a binding-built fact without a handle. --- .../src/index/project/members.rs | 9 ++- .../src/index/types/compute.rs | 74 +++++++++++++++++++ 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index d984f042..3a2f5205 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -612,9 +612,14 @@ pub(crate) fn the_pointee_of_a_handle( ) else { return None; }; - let written_type = fact.type_of.as_deref()?; + // **The fact's stored handle is converted, not parsed.** `parse_type_spelling` remains the fallback for a + // binding-built fact that predates the store; a fact from the index carries the structure already. + let written_type = index + .computed_type_of(&fact) + .map(|computed| computed.to_sema_type()) + .or_else(|| fact.type_of.as_deref().map(parse_type_spelling))?; 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 diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index b4e8b65b..9e39c01b 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -21,6 +21,8 @@ use std::sync::Arc; use smol_str::SmolStr; +use crate::sema::types::{Qualifiers, Type}; + /// A name and its arguments — boxed inside [`ComputedType::Named`] so the enum's inline size stays small. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct NamedType { @@ -106,6 +108,61 @@ impl ComputedType { _ => None, } } + + /// **The parser-facing form**, for the transition period. This is a conversion, not a parse: the structure is + /// already known and only its representation changes. Queries should prefer the `ComputedType` methods; this + /// exists because the current type engine still speaks `sema::types::Type`. + pub fn to_sema_type(&self) -> Type { + match self { + ComputedType::Builtin(spelling) => Type::Builtin { + spelling: spelling.to_string(), + }, + ComputedType::Named(named) => Type::Named { + name: named.name.to_string(), + arguments: named.arguments.iter().map(Self::to_sema_type).collect(), + }, + ComputedType::TemplateParameter(name) => Type::TemplateParameter { + name: name.to_string(), + }, + ComputedType::Auto => Type::Builtin { + spelling: "auto".to_string(), + }, + ComputedType::DecltypeAuto => Type::Builtin { + spelling: "decltype(auto)".to_string(), + }, + ComputedType::Pointer(to) => Type::Pointer { + to: Arc::new(to.to_sema_type()), + }, + ComputedType::Reference { to, rvalue } => Type::Reference { + to: Arc::new(to.to_sema_type()), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => Type::Array { + of: Arc::new(of.to_sema_type()), + extent: extent.map(|extent| extent as usize), + }, + ComputedType::Function(function) => Type::Function { + returns: Arc::new(function.returns.to_sema_type()), + parameters: function.parameters.iter().map(Self::to_sema_type).collect(), + }, + ComputedType::Pack(of) => Type::Pack { + of: Arc::new(of.to_sema_type()), + }, + 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); + } + Type::Qualified { + of: Arc::new(qualified.of.to_sema_type()), + qualifiers, + } + } + } + } } impl fmt::Display for ComputedType { @@ -184,6 +241,23 @@ mod tests { ); } + #[test] + fn the_parser_bridge_preserves_the_shape() { + let value = ComputedType::Pointer(Arc::new(ComputedType::Reference { + to: Arc::new(ComputedType::named( + "std::vector", + vec![ComputedType::Builtin(SmolStr::new("int"))], + )), + rvalue: false, + })); + let parser = value.to_sema_type(); + assert_eq!(parser.to_string(), value.to_string()); + assert!( + matches!(parser, Type::Pointer { .. }), + "the outer operator is kept" + ); + } + #[test] fn a_boxed_named_type_renders_and_answers_members() { let value = ComputedType::named( From c4eef8c84c8901efe27bd45d37058d3fc391ec7a Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:46:19 +0800 Subject: [PATCH 008/102] feat(types): route fact type inference through the stored handle Add the_type_of_a_fact as the one fact-to-parser bridge; indexed facts convert their TypeId through ComputedType instead of parsing type_of, while binding-built facts keep the spelling fallback. The nested-member inference and alias-return paths use it. --- .../src/index/project/type_of.rs | 22 ++++++++++++++----- docs/type-system-redesign.md | 2 ++ 2 files changed, 19 insertions(+), 5 deletions(-) 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..fcebdc01 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -54,6 +54,17 @@ 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 parser-facing type of a fact, from its stored handle when it has one.** This is the transition bridge for +/// the inference engine: a fact inserted into an index carries a `TypeId`, which is converted without parsing; a +/// binding-built fact has no store and still uses the spelling parser. The helper is the single place that decides +/// which path a fact takes, so the two cannot disagree about a type. +pub(crate) fn the_type_of_a_fact(index: &ProjectIndex, fact: &DeclFact) -> Option { + index + .computed_type_of(fact) + .map(|computed| computed.to_sema_type()) + .or_else(|| fact.type_of.as_deref().map(parse_type_spelling)) +} + /// **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 @@ -1474,7 +1485,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 +1496,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`). @@ -1527,7 +1539,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, @@ -3448,11 +3460,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; } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index f100f410..692532c3 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -386,6 +386,8 @@ No consumer changed. * `SemanticModel` owns a request-scoped `computed` cache, keyed by `TypeId`; `materialize` is called at most once per handle per request, and the cache is dropped with the model. * `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. +* `the_type_of_a_fact` centralizes the fact-to-parser bridge: an indexed fact converts its handle, a binding-built fact + falls back to the spelling parser. The member `element_type` and two type-inference paths use it. Still to do: From 81a6be8752b27b978be39d817b5b4d3bd9373b8c Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 18:59:24 +0800 Subject: [PATCH 009/102] feat(types): store parameter type handles in DeclDetail DeclDetail carries parameter_type_ids alongside the written parameter list. insert_at parses and interns the list once, the summary type table exports the handles, CODEC_VERSION 42 writes/reads them, and insertion remaps them. The parser bridge for fact types also moved two inference paths off parse_type_spelling. --- crates/cpp_code_analysis/src/cache/summary.rs | 11 +++++ .../src/cache/summary_codec.rs | 16 ++++++- .../src/index/project/bases.rs | 1 + .../src/index/project/macro_walk.rs | 27 ++++++++++- .../src/index/project/tests.rs | 47 ++++++++++++++++++- .../src/sema/declarations.rs | 1 + docs/type-system-redesign.md | 3 ++ 7 files changed, 103 insertions(+), 3 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 7f99209d..004722b1 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -411,6 +411,9 @@ pub struct DeclDetail { pub pattern: Option, /// The parameter list as the file spells it, parentheses included. pub parameter_list: Option, + /// **The parameter types in the index's interned store**, position for position. Empty until the summary is + /// inserted or for an old record; [`DeclDetail::parameter_list`] remains the display/fallback source. + pub parameter_type_ids: Box<[TypeId]>, } impl DeclDetail { @@ -437,6 +440,7 @@ impl DeclDetail { && self.parameter_defaults.is_empty() && self.pattern.is_none() && self.parameter_list.is_none() + && self.parameter_type_ids.is_empty() } } @@ -459,6 +463,7 @@ impl DeclDetail { + strings_bytes(&self.parameters) + strings_bytes(&self.constraints) + strings_bytes(&self.parameter_defaults) + + self.parameter_type_ids.len() * size_of::() + self.reflection.as_ref().map_or(0, |reflection| { on_the_heap(&reflection.macro_name) + reflection.specifiers.len() * size_of::() @@ -563,6 +568,12 @@ impl DeclFact { self.detail().and_then(|detail| detail.pattern.as_deref()) } + /// The parameter types in the index's interned store, position for position; empty until inserted. + pub fn parameter_type_ids(&self) -> &[TypeId] { + self.detail() + .map_or(&[], |detail| &detail.parameter_type_ids) + } + pub fn parameter_list(&self) -> Option<&str> { self.detail() .and_then(|detail| detail.parameter_list.as_deref()) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 49653ed9..563f0b2c 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -283,7 +283,7 @@ 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 = 41; +pub const CODEC_VERSION: u32 = 42; /// Write a summary as bytes. /// @@ -1413,6 +1413,8 @@ mod tests { // partial specialization from its primary template. `None` is covered by the facts below. pattern: Some("Widget<_Ty, _Alloc>".into()), parameter_list: Some("(int, int)".into()), + parameter_type_ids: vec![TypeId::from_raw(0), TypeId::from_raw(1)] + .into_boxed_slice(), // The `Some` branch, which is the one only a **local** ever has — see // [`DeclFact::in_namespace`]. The two facts below cover `None`. in_namespace: Some("std::ranges".into()), @@ -1744,6 +1746,10 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { put_str(out, default); } put_opt_str(out, fact.parameter_list()); + put_u32(out, fact.parameter_type_ids().len() as u32); + for type_id in fact.parameter_type_ids() { + put_u32(out, type_id.raw()); + } put_opt_str(out, fact.pattern()); put_range(out, fact.range); put_range(out, fact.name_range); @@ -1818,6 +1824,11 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let requires_clause = reader.optional_string()?; let parameter_defaults = get_strings(reader)?; let parameter_list = reader.optional_string()?; + let count = reader.count()?; + let mut parameter_type_ids = Vec::with_capacity(count.min(64 * 1024)); + for _ in 0..count { + parameter_type_ids.push(TypeId::from_raw(reader.u32()?)); + } let pattern = reader.optional_string()?; let range = reader.range()?; let name_range = reader.range()?; @@ -1879,6 +1890,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { parameter_defaults, pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), + parameter_type_ids: parameter_type_ids.into_boxed_slice(), }), }) } @@ -2217,6 +2229,7 @@ fn a_cooked_reading_round_trips() { requires_clause: Some("sizeof(T) > 0".into()), parameter_defaults: Vec::new(), parameter_list: None, + parameter_type_ids: Box::default(), pattern: Some("Widget".into()), in_namespace: Some("std".into()), reflection: Some(summary::ReflectionFact { @@ -2254,6 +2267,7 @@ fn a_cooked_reading_round_trips() { requires_clause: None, parameter_defaults: vec!["0".to_string()], parameter_list: Some("(int a)".into()), + parameter_type_ids: Box::default(), pattern: None, in_namespace: None, reflection: None, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 0764e06a..36e7db65 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -409,6 +409,7 @@ pub(crate) fn fact_from_binding_with( } _ => None, }, + parameter_type_ids: Box::default(), }), // **Who may name it**, read the same way and for the same reason: a member list built from the buffer is // what a completion after `.` offers, and a `private:` member must not be in it. See [DeclFact::access]. 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 5c1b1cfa..dbee99be 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -407,6 +407,13 @@ impl ProjectIndex { { fact.returns_id = *store_id; } + if let Some(detail) = fact.detail.as_mut() { + for type_id in &mut detail.parameter_type_ids { + if let Some(store_id) = mapping.get(&(type_id.index() as u32)) { + *type_id = *store_id; + } + } + } } } for fact in &mut summary.declarations { @@ -422,11 +429,29 @@ impl ProjectIndex { { fact.returns_id = self.types.intern_spelling(returns); } + if let Some(detail) = fact.detail.as_mut() + && detail.parameter_type_ids.is_empty() + && let Some(parameter_list) = detail.parameter_list.as_deref() + { + let written = + crate::session::inlay::parameter_types_in_a_written_list(parameter_list); + detail.parameter_type_ids = written + .iter() + .map(|written| self.types.intern_spelling(written)) + .collect::>() + .into_boxed_slice(); + } } let ids: Vec<_> = summary .declarations .iter() - .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .flat_map(|fact| { + let mut ids = vec![fact.type_of_id, fact.returns_id]; + if let Some(detail) = fact.detail.as_deref() { + ids.extend(detail.parameter_type_ids.iter().copied()); + } + ids + }) .collect(); summary.types = self.types.export(ids); } diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 32589e30..02eb238b 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -133,7 +133,7 @@ fn the_index_interns_the_types_a_summary_declares_once() { #[test] fn a_cached_summary_remaps_its_type_ids_on_insert() { let path = Path::new("/p/types.cpp"); - let source = "int first;\nstd::vector items;\n"; + 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"); @@ -157,6 +157,51 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { .display(), "std::vector" ); + let function = stored + .declarations + .iter() + .find(|fact| fact.name == "f") + .expect("the function"); + let parameter = function + .parameter_type_ids() + .first() + .copied() + .expect("a parameter"); + assert_eq!( + second + .types() + .type_ref(parameter) + .expect("the imported parameter") + .display(), + "double" + ); +} + +#[test] +fn a_function_detail_interns_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"); + let types = function.parameter_type_ids(); + assert_eq!(types.len(), 2, "both parameters got a handle"); + assert_eq!( + index.types().type_ref(types[0]).unwrap().display(), + "double" + ); + assert_eq!( + index.types().type_ref(types[1]).unwrap().display(), + "const char*" + ); } #[test] diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 18d42049..9e2f358b 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -4106,6 +4106,7 @@ fn fact_for( parameter_defaults, pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), + parameter_type_ids: Box::default(), }), access, exported, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 692532c3..00edc85a 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -388,6 +388,9 @@ No consumer changed. * `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. * `the_type_of_a_fact` centralizes the fact-to-parser bridge: an indexed fact converts its handle, a binding-built fact falls back to the spelling parser. The member `element_type` and two type-inference paths use it. +* `DeclDetail` now carries `parameter_type_ids`: `insert_at` parses the parameter list once, interns each type and + includes those handles in the summary's `TypeTable`; the codec writes and reads them, and insertion remaps them. + The string `parameter_list` remains for display and as the transition fallback. Still to do: From 10ed866a6ae9a2294144f2e7fbf6a475502cb3b2 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:06:48 +0800 Subject: [PATCH 010/102] feat(types): read template-hint parameters from the type store Template-argument deduction now materializes the callee's parameter_type_ids instead of parsing its parameter_list. The written list remains the fallback for facts that predate the store, so the transition is additive. --- .../src/session/completion/request.rs | 25 +++++++++++++++++-- docs/type-system-redesign.md | 3 ++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index f73a1021..fbffb922 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -820,8 +820,29 @@ impl Session { 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.** Parse the written list only for a fact that predates + // the store; a stored handle is materialized read-only, so a template-argument hint costs no parse and no + // write to the type store. + let parameter_types: Vec = { + let stored: Option> = fact + .parameter_type_ids() + .iter() + .map(|id| { + self.store + .index() + .types() + .materialize(*id) + .map(|computed| computed.to_string()) + }) + .collect(); + match stored { + Some(types) if !types.is_empty() => types, + _ => { + let parameter_list = fact.parameter_list()?; + inlay::parameter_types_in_a_written_list(parameter_list) + } + } + }; if parameter_types.is_empty() { return None; } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 00edc85a..b5739b8f 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -390,7 +390,8 @@ No consumer changed. falls back to the spelling parser. The member `element_type` and two type-inference paths use it. * `DeclDetail` now carries `parameter_type_ids`: `insert_at` parses the parameter list once, interns each type and includes those handles in the summary's `TypeTable`; the codec writes and reads them, and insertion remaps them. - The string `parameter_list` remains for display and as the transition fallback. + The string `parameter_list` remains for display and as the transition fallback. Template-argument hints now materialize + `parameter_type_ids` from the store instead of parsing the list. Still to do: From 633147d5407adaeb89ab47df1f993be8f09fc922 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:29:05 +0800 Subject: [PATCH 011/102] feat(types): read completion detail and inlay returns from handles CompletionItem detail falls back to the stored type/return handles when the spelling field is absent, and the inlay return-type hint materializes returns_id before the string field. The written spelling still wins for display, preserving the file's spacing. --- .../src/session/completion/mod.rs | 60 +++++++++++++++++-- .../src/session/completion/request.rs | 15 ++++- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 002a10e1..fc81aaaf 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -63,6 +63,7 @@ use crate::cuda; use crate::file; use crate::include; use crate::index; +use crate::index::types::TypeStore; use crate::sema; use cpp_parser::every_command; pub mod context; @@ -234,7 +235,7 @@ pub fn the_include_spelling( impl CompletionItem { /// A declaration, as an item. - fn declared(fact: &DeclFact, file: &Path) -> CompletionItem { + fn declared(fact: &DeclFact, file: &Path, types: Option<&TypeStore>) -> CompletionItem { // An item with no name — a destructor the index could not spell — has nothing to resolve *to*, and an // identity pointing at an empty range would fetch another declaration's documentation. let identity = @@ -251,7 +252,7 @@ impl CompletionItem { _ => fact.name.to_string(), }, snippet: false, - detail: detail_of(fact), + detail: detail_of_with_types(fact, types), identity, filter: None, fact: Some(fact.clone()), @@ -294,8 +295,13 @@ impl CompletionItem { } /// **A declaration from a header this file does not include**, with the include that would make it usable. - fn unincluded(fact: &DeclFact, file: &Path, inclusion: Inclusion) -> CompletionItem { - let mut item = CompletionItem::declared(fact, file); + fn unincluded( + fact: &DeclFact, + file: &Path, + inclusion: Inclusion, + types: Option<&TypeStore>, + ) -> CompletionItem { + let mut item = CompletionItem::declared(fact, file, types); let line = inclusion.line(); item.detail = Some(format!( "not included — accepting this adds `{}`", @@ -351,6 +357,46 @@ 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. +/// **The row's detail, preferring the stored type handles.** A completion is built from a summary that has been +/// inserted, so its type/return IDs are available; the spelling is the fallback for a binding-built fact and for +/// fields whose structure the old record still carries. +pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Option { + let displayed = |id| { + types.and_then(|types| { + types + .spelling(id) + .map(str::to_string) + .or_else(|| types.materialize(id).map(|computed| computed.to_string())) + }) + }; + // **The written spelling wins when it exists**, because it is what the reader sees in the declaration; the stored + // handle is the fallback for a record whose string field is gone. (The two must agree structurally, but `T *` and + // `T*` are different display forms and the completion row keeps the file's.) + let returns = fact + .returns + .clone() + .map(|returns| returns.to_string()) + .or_else(|| fact.returns_id().and_then(displayed)); + let type_of = fact + .type_of + .clone() + .map(|ty| ty.to_string()) + .or_else(|| fact.type_of_id().and_then(displayed)); + match fact.kind { + 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 => type_of, + DeclKind::Type if !fact.bases().is_empty() => { + Some(format!(": {}", fact.bases().join(", "))) + } + _ => None, + } +} + pub fn detail_of(fact: &DeclFact) -> Option { match fact.kind { DeclKind::Function => match (&fact.returns, &fact.parameter_list()) { @@ -1253,7 +1299,7 @@ fn members_of_a_type( continue; } - let mut item = CompletionItem::declared(&member.fact, &member.file); + let mut item = CompletionItem::declared(&member.fact, &member.file, Some(index.types())); item.kind = member_kind(member, &class); item.replace = replace; @@ -1639,7 +1685,8 @@ fn names( continue; } - let mut item = CompletionItem::declared(&offered.fact, &offered.file); + let mut item = + CompletionItem::declared(&offered.fact, &offered.file, Some(index.types())); item.replace = replace; // **What is being typed is the tail of the name.** Inside `std::` the reader writes `str` and means @@ -1863,6 +1910,7 @@ fn names( fact, &related.file, related.inclusion.clone(), + Some(index.types()), ), }); } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index fbffb922..965131bd 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -870,7 +870,20 @@ impl Session { .value() }); indexed - .and_then(|found| found.fact.returns.map(|returns| returns.to_string())) + .and_then(|found| { + found + .fact + .returns_id() + .and_then(|id| self.store.index().types().materialize(id)) + .map(|computed| computed.to_string()) + .or_else(|| { + found + .fact + .returns + .clone() + .map(|returns| returns.to_string()) + }) + }) .or_else(|| { local .and_then(|found| found.fact.returns.map(|returns| returns.to_string())) From 934acb17ec96379c9f90abfe3ab5999f167109c4 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:33:13 +0800 Subject: [PATCH 012/102] test(types): pin type deduplication across declarations A hundred std::vector declarations produce two store nodes and a two-entry summary table, with non-zero accounting bytes. This is the memory regression the compact store exists for. --- .../src/index/project/tests.rs | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 02eb238b..37b84f3c 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -204,6 +204,34 @@ fn a_function_detail_interns_its_parameter_types() { ); } +/// **A repeated type is one node, not one per declaration.** This is the memory contract of the store: a header +/// with a hundred `std::vector` members must not carry a hundred type records. The check is on the store and on +/// the summary's exported table, because both are counted by the memory report. +#[test] +fn repeated_declarations_share_one_type_node() { + 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); + assert_eq!( + index.types().len(), + 2, + "`std::vector` and `int`, once each" + ); + assert_eq!( + stored.types.entries.len(), + 2, + "the exported table is deduplicated too" + ); + let accounting = index.types().accounting(); + assert!(accounting.types >= 2); + assert!(accounting.bytes > 0); +} + #[test] fn a_declaration_in_an_included_header_is_found() { let index = index(&[ From 7480d7b8c21e5d1a59ead17a958b7b3839740a24 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:42:06 +0800 Subject: [PATCH 013/102] feat(types): source fact spellings from the type store ProjectIndex::type_spelling_of / returns_spelling_of prefer the stored node's spelling and fall back to the transition string. The member, alias and type-inference paths use them, so removing the string fields later does not revisit those queries. --- .../src/index/project/macro_walk.rs | 16 ++++++++++++++++ .../src/index/project/members.rs | 2 +- .../src/index/project/type_of.rs | 8 ++++---- 3 files changed, 21 insertions(+), 5 deletions(-) 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 dbee99be..cefd6cbf 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -382,6 +382,22 @@ impl ProjectIndex { &self.types } + /// **The written type spelling of a fact**, from its handle when the store has one and from the transition + /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so + /// deleting the string field later does not require revisiting them. + pub fn type_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { + fact.type_of_id() + .and_then(|id| self.types.spelling(id)) + .or(fact.type_of.as_deref()) + } + + /// The written return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. + pub fn returns_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { + fact.returns_id() + .and_then(|id| self.types.spelling(id)) + .or(fact.returns.as_deref()) + } + /// **The computation-side type of a declaration's `type_of`**, when the fact has a storage handle. This is the /// read-side bridge from [`DeclFact::type_of_id`] to [`ComputedType`]; it never interns. pub fn computed_type_of(&self, fact: &DeclFact) -> Option { diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 3a2f5205..07a684bf 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -617,7 +617,7 @@ pub(crate) fn the_pointee_of_a_handle( let written_type = index .computed_type_of(&fact) .map(|computed| computed.to_sema_type()) - .or_else(|| fact.type_of.as_deref().map(parse_type_spelling))?; + .or_else(|| index.type_spelling_of(&fact).map(parse_type_spelling))?; let bindings = member_bindings(index, scopes, root, path, class, arguments); let finished = bindings.applied_to(&written_type); // **A nested spelling is followed**, which is the ordinary shape in the standard library: `shared_ptr` inherits 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 fcebdc01..84009c23 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -62,7 +62,7 @@ pub(crate) fn the_type_of_a_fact(index: &ProjectIndex, fact: &DeclFact) -> Optio index .computed_type_of(fact) .map(|computed| computed.to_sema_type()) - .or_else(|| fact.type_of.as_deref().map(parse_type_spelling)) + .or_else(|| index.type_spelling_of(fact).map(parse_type_spelling)) } /// **What an inference answer is a function of**, as one number: the file, the expression's range, its kind and its text. @@ -1659,7 +1659,7 @@ pub(crate) fn declared_class( && 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(target) = index.type_spelling_of(&found.fact) { let written = sema::builtins::split_arguments(inside); let target = sema::types::substituted_spelling(target, found.fact.parameters(), &written); @@ -1960,7 +1960,7 @@ 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.type_spelling_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, @@ -3555,7 +3555,7 @@ pub(crate) fn a_trait_alias_resolved( ) else { return None; }; - let target = fact.type_of.as_deref()?; + let target = index.type_spelling_of(&fact)?; let arguments: Vec = parse_type_spelling(&class) .arguments() .iter() From 8a5d646a94a9a00aed60c55b749b1182a3cf978a Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:49:52 +0800 Subject: [PATCH 014/102] feat(types): read alias targets through the store spelling Substitution, alias and call walks now ask ProjectIndex::type_spelling_of, so the stored node's spelling is the primary source and the transition string is only a fallback. No behavior change; this removes direct field reads before the field is deleted. --- crates/cpp_code_analysis/src/index/project/aliases.rs | 4 ++-- crates/cpp_code_analysis/src/index/project/calls.rs | 4 ++-- crates/cpp_code_analysis/src/index/project/substituted.rs | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index cba62f15..258b12dc 100644 --- a/crates/cpp_code_analysis/src/index/project/aliases.rs +++ b/crates/cpp_code_analysis/src/index/project/aliases.rs @@ -259,7 +259,7 @@ 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: @@ -938,7 +938,7 @@ pub(crate) fn the_element_type_of( 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); diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 157bd9a0..d2c22fa3 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1806,7 +1806,7 @@ pub(crate) fn a_members_answer_as_a_type( ) else { return substituted; }; - let Some(target) = fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(&fact) else { return substituted; }; let target = @@ -1900,7 +1900,7 @@ fn a_reference_resolved_through_its_value_type( ) else { return None; }; - let written = fact.type_of.as_deref()?; + let written = index.type_spelling_of(&fact)?; let value_type = sema::types::substituted_spelling_with_defaults(written, parameters, defaults, arguments); if value_type.trim().is_empty() || value_type.contains("::value_type") { diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 0ec2f8f5..2d80f78e 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -116,7 +116,7 @@ pub(crate) fn the_alias_behind( return None; } - let target = found.fact.type_of.as_deref()?; + let target = index.type_spelling_of(&found.fact)?; let arguments = sema::builtins::split_arguments(inside); let substituted = sema::types::substituted_spelling(target, found.fact.parameters(), &arguments); @@ -517,11 +517,11 @@ pub(crate) fn an_element_type_through_the_members( .iter() .filter(|member| member.fact.name == name) .map(|member| &member.fact) - .find(|fact| fact.type_of.is_some()) + .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); @@ -540,7 +540,7 @@ pub(crate) fn an_element_type_through_the_members( if member.fact.kind != DeclKind::Type { continue; } - let Some(target) = member.fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(&member.fact) else { continue; }; if base_type_name(target) == base_type_name(class) { From 437b54a118f1e4d2c5e2b9cbe7d95ef87fc27f82 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:58:33 +0800 Subject: [PATCH 015/102] feat(types): stop duplicating type spellings in the cache When a fact has a stored handle and the summary record carries its type table, summary_codec omits the per-fact type_of/returns spelling and the decoder restores it from the table (CODEC_VERSION 43). Parser-built facts without handles keep their spelling; the unit codec still writes it. --- .../src/cache/summary_codec.rs | 49 ++++++++++++++++--- .../src/index/project/tests.rs | 10 ++++ .../cpp_code_analysis/src/index/types/mod.rs | 8 +++ 3 files changed, 59 insertions(+), 8 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 563f0b2c..a88f271f 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -283,7 +283,7 @@ 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 = 42; +pub const CODEC_VERSION: u32 = 43; /// Write a summary as bytes. /// @@ -304,7 +304,7 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.declarations.len() as u32); for fact in &summary.declarations { - put_declaration(&mut out, fact); + put_declaration(&mut out, fact, true); } put_u32(&mut out, summary.macros.len() as u32); @@ -801,7 +801,7 @@ pub fn decode(bytes: &[u8]) -> Result { return Err(DecodeError::TrailingBytes); } - Ok(FileSummary { + let mut summary = FileSummary { path, key, declarations, @@ -812,7 +812,27 @@ pub fn decode(bytes: &[u8]) -> Result { macro_readings, use_filter, modules, - }) + }; + restore_type_spellings(&mut summary); + Ok(summary) +} + +/// **Fill the facts' transition strings from the table the encoder wrote once.** A fact with a stored handle did not +/// carry its spelling in the record; the table entry did. This keeps the in-memory shape the rest of the crate reads +/// while the cache format stops duplicating the same string per declaration. +fn restore_type_spellings(summary: &mut FileSummary) { + for fact in &mut summary.declarations { + if fact.type_of.is_none() + && let Some(spelling) = summary.types.spelling_for(fact.type_of_id.raw()) + { + fact.type_of = Some(SmolStr::from(spelling)); + } + if fact.returns.is_none() + && let Some(spelling) = summary.types.spelling_for(fact.returns_id.raw()) + { + fact.returns = Some(SmolStr::from(spelling)); + } + } } /// Why a byte stream is not a summary. @@ -1717,13 +1737,26 @@ mod tests { /// **One writer, two records, on purpose.** A cooked reading's declarations are the same `DeclFact`s a summary /// holds; a second copy of these eighty lines would be a second place to add the next field to, and the failure it /// would produce is silent — a field written by one record and not the other, decoding as whatever follows it. -fn put_declaration(out: &mut Vec, fact: &DeclFact) { +fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bool) { 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()); + // **The type table already carries the spelling.** When the fact has a stored handle and this record includes + // the table, writing the string again is a duplicate the reader can reconstruct; a fact without a handle (a + // parser-built summary) still writes its spelling. + let type_of = if skip_stored_spellings && !fact.type_of_id.is_none() { + None + } else { + fact.type_of.as_deref() + }; + put_opt_str(out, type_of); put_u32(out, fact.type_of_id.raw()); - put_opt_str(out, fact.returns.as_deref()); + let returns = if skip_stored_spellings && !fact.returns_id.is_none() { + None + } else { + fact.returns.as_deref() + }; + put_opt_str(out, returns); put_u32(out, fact.returns_id.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. @@ -2009,7 +2042,7 @@ pub fn encode_the_cooked_record( fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { put_u32(out, reading.declarations.len() as u32); for fact in &reading.declarations { - put_declaration(out, fact); + put_declaration(out, fact, false); } put_u32(out, reading.macros.len() as u32); for fact in &reading.macros { diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 37b84f3c..d2010ff0 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -139,6 +139,16 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { let stored = first.summary(path).expect("inserted"); let decoded = crate::cache::summary_codec::decode(&crate::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.as_deref(), + Some("std::vector"), + "the decoder restores the spelling from the type table" + ); let mut second = ProjectIndex::new(); second.insert(decoded); diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 70b3727d..10a0b206 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -653,6 +653,14 @@ impl TypeTable { self.entries.is_empty() } + /// The written spelling of a local table entry, when the encoder kept one. + pub fn spelling_for(&self, id: u32) -> Option<&str> { + self.entries + .iter() + .find(|entry| entry.id == id) + .and_then(|entry| entry.spelling.as_deref()) + } + /// The encoded table's heap cost: entries, spelling strings, named and function argument vectors. pub fn heap_bytes(&self) -> usize { self.entries.len() * size_of::() From ca35acb2ada300f2b6da759fbd02c360a4e5d723 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 19:58:42 +0800 Subject: [PATCH 016/102] docs(types): record codec 43 spelling dedup --- docs/type-system-redesign.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index b5739b8f..6e3ed481 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -373,8 +373,9 @@ No consumer changed. `TypeKind` and `TypeNode` are 16 bytes. **Phase 2b — done.** `FileSummary` carries a local `TypeTable`; `summary_codec` writes and reads it with -`CODEC_VERSION` 41. Fact IDs are written beside the strings; decoding leaves them local, and -`ProjectIndex::insert_at` imports the table and rewrites them to store handles. The round trip is covered by +`CODEC_VERSION` 43. Fact IDs are written; when a fact has a handle its per-fact spelling is omitted and the decoder +restores it from the table. `ProjectIndex::insert_at` imports the table and rewrites the IDs to store handles. The +round trip is covered by `a_cached_summary_remaps_its_type_ids_on_insert`. `TypeStore::materialize` builds `ComputedType` without mutation; `ComputedType` is asserted to be <= 32 bytes. The memory report has `types`, `type_names`, `type_argument_lists` and `type_store_bytes`. From 932d2999c6424797498a4cbcdcc74b4a58d63c89 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 20:16:06 +0800 Subject: [PATCH 017/102] feat(facts): share type spellings through Arc DeclFact.type_of and returns use Option>: each field shrinks from 24 to 16 bytes and cloning a fact shares the spelling instead of copying it. serde's rc feature preserves the JSON shape; a size test pins the transition fact below 176 bytes. --- Cargo.toml | 2 +- crates/cpp_code_analysis/src/cache/summary.rs | 46 ++++++++++++++----- .../src/cache/summary_codec.rs | 8 ++-- .../src/index/project/bases.rs | 4 +- .../src/index/project/substituted.rs | 2 +- .../src/index/project/type_of.rs | 5 +- .../src/sema/declarations.rs | 4 +- .../src/session/completion/mod.rs | 2 +- docs/type-system-redesign.md | 3 ++ 9 files changed, 50 insertions(+), 26 deletions(-) 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/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 004722b1..742ddc63 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -237,7 +237,7 @@ pub struct DeclFact { /// * **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, + pub type_of: Option>, /// **The same type in the index's interned store** — [`TypeId::NONE`] until the summary is inserted. /// /// The string remains the transition field: a summary is built from syntax, and the store does not exist while @@ -262,7 +262,7 @@ pub struct DeclFact { /// 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, + pub returns: Option>, /// The same return type in the index's interned store; see [`DeclFact::type_of_id`]. pub returns_id: TypeId, /// **Does the file's own text state this declaration's type across a directive?** @@ -454,11 +454,11 @@ 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) @@ -477,11 +477,16 @@ fn strings_bytes(values: &[String]) -> usize { size_of_val(values) + values.iter().map(String::len).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) } +/// The bytes an optional shared string owns outside the `Option` that holds it. +fn on_the_heap_shared_option(text: &Option>) -> usize { + text.as_ref().map_or(0, |text| text.len()) +} + /// **The facts in one file, and how much of their storage is in [`DeclFact::detail`]** — the measurement a memory /// decision about the box needs. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -1411,9 +1416,9 @@ 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) + + on_the_heap_shared_option(&self.type_of) + + on_the_heap_shared_option(&self.returns) + self.detail_bytes() } } @@ -1449,6 +1454,23 @@ 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() { + // **The four handles and the two shared strings are the transition shape.** The strings leave in Phase 4; + // until then the shared `Arc` keeps the fact well below two hundred bytes without cloning their payloads. + assert!( + size_of::() <= 176, + "DeclFact is {} bytes", + size_of::() + ); + } +} + impl FileSummary { /// **The declaration population and its boxed shares** — the data a decision about `DeclFact::detail` needs. pub fn declaration_accounting(&self) -> DeclarationAccounting { diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index a88f271f..3bdde971 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -825,12 +825,12 @@ fn restore_type_spellings(summary: &mut FileSummary) { if fact.type_of.is_none() && let Some(spelling) = summary.types.spelling_for(fact.type_of_id.raw()) { - fact.type_of = Some(SmolStr::from(spelling)); + fact.type_of = Some(std::sync::Arc::from(spelling)); } if fact.returns.is_none() && let Some(spelling) = summary.types.spelling_for(fact.returns_id.raw()) { - fact.returns = Some(SmolStr::from(spelling)); + fact.returns = Some(std::sync::Arc::from(spelling)); } } } @@ -1846,7 +1846,7 @@ 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 type_of = reader.optional_string()?.map(std::sync::Arc::from); let type_of_id = TypeId::from_raw(reader.u32()?); let returns = reader.optional_string()?; let returns_id = TypeId::from_raw(reader.u32()?); @@ -1902,7 +1902,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { frees, type_of, type_of_id, - returns: returns.map(SmolStr::from), + returns: returns.map(std::sync::Arc::from), returns_id, split_by_a_directive, range, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 36e7db65..b02d74fb 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -342,7 +342,7 @@ pub(crate) fn fact_from_binding_with( binding, ) }) - .map(SmolStr::from), + .map(|written| Arc::from(written.as_str())), // 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`]. // **The deduction, when the file wrote no return type.** `declared_returns_of_in` answers only what is written, and @@ -356,7 +356,7 @@ pub(crate) fn fact_from_binding_with( type_of_id: TypeId::NONE, returns: sema::declarations::declared_returns_of_in(shapes, root, binding) .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)) - .map(SmolStr::from), + .map(|written| Arc::from(written.as_str())), returns_id: TypeId::NONE, // **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`]. diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 2d80f78e..8ebe68db 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -235,7 +235,7 @@ pub fn substituted_members( }; // **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.as_ref() == member.fact.name.as_str() { continue; } alias_names.push(member.fact.name.to_string()); 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 84009c23..3414d22d 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -20,7 +20,6 @@ use crate::sema; 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. /// @@ -2308,7 +2307,7 @@ pub(crate) fn operator_returns_of_with_arguments( .fact .returns .clone() - .or(found.fact.returns_in_the_class().map(SmolStr::from))?; + .or(found.fact.returns_in_the_class().map(Arc::from))?; // **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->`, @@ -2363,7 +2362,7 @@ fn the_members_return( let returns = fact .returns .clone() - .or(fact.returns_in_the_class().map(SmolStr::from)); + .or(fact.returns_in_the_class().map(Arc::from)); if returns.as_deref().is_none_or(is_a_placeholder) && let Some(deduced) = deduced_returns_of_the_member( declaring, diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 9e2f358b..e28fee71 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -4088,9 +4088,9 @@ 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), + type_of: type_of.map(std::sync::Arc::from), type_of_id: TypeId::NONE, - returns: returns.map(SmolStr::from), + returns: returns.map(std::sync::Arc::from), returns_id: TypeId::NONE, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index fc81aaaf..9374550d 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2593,7 +2593,7 @@ mod tests { modifiers: DeclModifiers::VIRTUAL, type_of: None, type_of_id: TypeId::NONE, - returns: returns.map(smol_str::SmolStr::from), + returns: returns.map(Arc::from), returns_id: TypeId::NONE, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6e3ed481..6effd500 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -389,6 +389,9 @@ round trip is covered by * `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. * `the_type_of_a_fact` centralizes the fact-to-parser bridge: an indexed fact converts its handle, a binding-built fact falls back to the spelling parser. The member `element_type` and two type-inference paths use it. +* `DeclFact.type_of` / `returns` are now `Option>` rather than `Option`: the fact is sixteen + bytes smaller and a clone shares the string instead of copying it. `serde`'s `rc` feature keeps the existing JSON + shape. A size test pins the transition fact under 176 bytes. * `DeclDetail` now carries `parameter_type_ids`: `insert_at` parses the parameter list once, interns each type and includes those handles in the summary's `TypeTable`; the codec writes and reads them, and insertion remaps them. The string `parameter_list` remains for display and as the transition fallback. Template-argument hints now materialize From 2facb5201e182598a5f9f8a8da3de1d7a50863ab Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Tue, 1 Dec 2026 20:48:37 +0800 Subject: [PATCH 018/102] feat(facts): keep declaration detail vectors inline DeclDetail's base, parameter, constraint and default vectors are Vec, so a short name no longer allocates. TypeSubstitutions, substituted_spelling, deduction and pattern matching are generic over AsRef; call sites that still need Vec convert at the boundary. --- crates/cpp_code_analysis/src/cache/summary.rs | 26 ++++---- .../src/cache/summary_codec.rs | 18 +++--- .../src/index/project/bases.rs | 31 ++++++---- .../src/index/project/calls.rs | 7 ++- .../src/index/project/deductions.rs | 11 ++-- .../src/index/project/macro_walk.rs | 21 ++++++- .../src/index/project/members.rs | 9 ++- .../src/index/project/substituted.rs | 6 +- .../src/index/project/type_of.rs | 8 ++- .../src/sema/check/concept_not_satisfied.rs | 13 ++-- .../src/sema/check/final_hierarchy.rs | 5 +- .../src/sema/check/final_misplaced.rs | 7 ++- .../cpp_code_analysis/src/sema/check/mod.rs | 2 +- .../src/sema/check/unresolved_type.rs | 2 +- .../src/sema/declarations.rs | 36 ++++++----- crates/cpp_code_analysis/src/sema/render.rs | 2 +- crates/cpp_code_analysis/src/sema/types.rs | 62 ++++++++++++------- crates/cpp_code_analysis/src/session/calls.rs | 19 ++++-- .../src/session/completion/mod.rs | 2 +- .../src/session/completion/request.rs | 6 +- .../cpp_code_analysis/src/session/queries.rs | 6 +- .../tests/suite/reported_defects.rs | 10 +-- crates/cpp_ls/src/handlers/hover/mod.rs | 22 +++++-- docs/type-system-redesign.md | 3 + 24 files changed, 220 insertions(+), 114 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 742ddc63..ca5edeb4 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -387,8 +387,8 @@ 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`. #[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. @@ -396,17 +396,17 @@ 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, + pub parameters: Vec, /// The constraints a `template <…>` head writes after its parameters. - pub constraints: Vec, + pub constraints: 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. @@ -472,9 +472,9 @@ 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 an optional inline string owns outside the `Option` that holds it. @@ -543,7 +543,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) } @@ -551,11 +551,11 @@ 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] { + pub fn constraints(&self) -> &[SmolStr] { self.detail().map_or(&[], |detail| &detail.constraints) } @@ -564,7 +564,7 @@ impl DeclFact { .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) } diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 3bdde971..a3703c62 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1420,12 +1420,12 @@ 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()], // 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(), @@ -1929,11 +1929,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) } @@ -2256,8 +2256,8 @@ fn a_cooked_reading_round_trips() { frees: 0, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { returns_in_the_class: None, - bases: vec!["Base".to_string()], - parameters: vec!["T".to_string()], + bases: vec!["Base".into()], + parameters: vec!["T".into()], constraints: Vec::new(), requires_clause: Some("sizeof(T) > 0".into()), parameter_defaults: Vec::new(), @@ -2296,9 +2296,9 @@ fn a_cooked_reading_round_trips() { returns_in_the_class: None, bases: Vec::new(), parameters: Vec::new(), - constraints: vec!["Copyable".to_string()], + constraints: vec!["Copyable".into()], requires_clause: None, - parameter_defaults: vec!["0".to_string()], + parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), parameter_type_ids: Box::default(), pattern: None, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index b02d74fb..06f519a5 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -141,10 +141,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; @@ -166,7 +166,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) }) } @@ -182,9 +182,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); @@ -377,7 +377,10 @@ pub(crate) fn fact_from_binding_with( .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. @@ -385,7 +388,10 @@ 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: sema::declarations::declared_template_parameters_with(shapes, binding) + .into_iter() + .map(SmolStr::from) + .collect(), constraints: 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. @@ -393,7 +399,10 @@ pub(crate) fn fact_from_binding_with( .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. @@ -595,11 +604,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); } diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index d2c22fa3..7dd70db8 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1483,7 +1483,7 @@ pub(crate) fn the_one_the_arguments_select( .parameter_list() .map(sema::overload::parameters_in) .unwrap_or_default(); - let names = fact.parameters().to_vec(); + let names: Vec = 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`. @@ -1510,7 +1510,10 @@ 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.iter().map(ToString::to_string).collect(), + ) } else { candidate } diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index f3502a5d..c621372c 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -1765,12 +1765,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(); + let mut deduced: Vec = names + .iter() + .map(|name| Type::named(name.as_ref())) + .collect(); if names.is_empty() || argument_types.is_empty() { return deduced; } @@ -1818,7 +1821,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_walk.rs b/crates/cpp_code_analysis/src/index/project/macro_walk.rs index cefd6cbf..d50f50e1 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -1820,8 +1820,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(), ) }) } @@ -1839,7 +1849,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. diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 07a684bf..22c9b822 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -1679,7 +1679,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) } diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 8ebe68db..34599d53 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -477,12 +477,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 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 3414d22d..0cb64b7e 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -3246,7 +3246,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), ), } @@ -3271,7 +3271,11 @@ impl NamedDeclaration { binding, ) } - NamedDeclaration::Indexed(fact, _, _) => fact.parameter_defaults().to_vec(), + NamedDeclaration::Indexed(fact, _, _) => fact + .parameter_defaults() + .iter() + .map(ToString::to_string) + .collect(), } } /// 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..e3834425 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 @@ -71,7 +71,12 @@ impl Check for ConceptNotSatisfied { // 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) + constraints_of_a_declaration(context, &name).map(|constraints| { + constraints + .iter() + .map(ToString::to_string) + .collect::>() + }) else { continue; }; @@ -120,8 +125,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 [smol_str::SmolStr]> { + let mut own: Option<&[smol_str::SmolStr]> = None; let mut own_declarations = 0; for fact in context .declarations(DeclarationSource::Cooked) @@ -141,7 +146,7 @@ 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<&[smol_str::SmolStr]> = None; let mut elsewhere_declarations = 0; for found in &declared { if found.fact.parameter_list().is_none() { 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..6771da5e 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, ) }) 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..b9c2d84f 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 diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index e408da61..5555e935 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -1152,7 +1152,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) 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..e89cb9b2 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 diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index e28fee71..0cde2417 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -1647,10 +1647,10 @@ pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option>( root: &CppSyntaxNode, binding: Binding, - substitutions: &sema::types::TypeSubstitutions<'_>, + substitutions: &sema::types::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], @@ -1688,10 +1688,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: &sema::types::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 @@ -1754,9 +1754,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: &sema::types::TypeSubstitutions<'_, N>, ) -> Option { let condition = condition.trim(); @@ -1824,9 +1824,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: &sema::types::TypeSubstitutions<'_, N>, ) -> String { let mut text = written.trim(); while let Some(inner) = text @@ -2420,7 +2420,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 = sema::types::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 { @@ -2685,10 +2685,10 @@ 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<'_>, + substitutions: &sema::types::TypeSubstitutions<'_, N>, argument_types: &[sema::types::Type], ) -> Option { use cpp_parser::{CppAstNode, CppExpr}; @@ -2879,7 +2879,7 @@ fn a_captures_type(expression: &CppSyntaxNode) -> Option { type_a_return_states_with( &initializer, enclosing.syntax(), - &sema::types::TypeSubstitutions::new(&[], &[]), + &sema::types::TypeSubstitutions::::new(&[], &[]), &[], ) } @@ -4096,14 +4096,14 @@ fn fact_for( 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.into_iter().map(SmolStr::from).collect(), 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), parameter_type_ids: Box::default(), @@ -6071,7 +6071,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!( diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index ae9a37bf..009eadc9 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -286,7 +286,7 @@ fn a_template_head(fact: &DeclFact, syntax: Option<&CppDeclaration>) -> Option` with `T` unknown substitutes the /// `int`, which is what makes `second` answerable and `first` not. - pub fn substituted(&self, substitutions: &TypeSubstitutions<'_>) -> Type { + pub fn substituted>(&self, substitutions: &TypeSubstitutions<'_, N>) -> 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 @@ -963,8 +963,8 @@ impl Type { /// 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], +pub struct TypeSubstitutions<'a, N: AsRef = String> { + names: &'a [N], arguments: &'a [Type], /// **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 @@ -973,8 +973,8 @@ pub struct TypeSubstitutions<'a> { defaults: &'a [Type], } -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 [Type]) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, arguments, @@ -986,10 +986,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], + names: &'a [N], arguments: &'a [Type], defaults: &'a [Type], - ) -> TypeSubstitutions<'a> { + ) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, arguments, @@ -1004,10 +1004,10 @@ impl<'a> TypeSubstitutions<'a> { /// 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)?; + 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); } @@ -2754,7 +2754,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 +2773,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 +2785,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 +2811,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 +2857,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(); diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 34df92ea..e8c399bd 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -1055,9 +1055,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(), }) } @@ -1390,7 +1394,14 @@ impl Session { // written, and it is the honest place for a hover to open. 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; diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 9374550d..2e2c01a9 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2028,7 +2028,7 @@ 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) diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 965131bd..39e17362 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -846,7 +846,11 @@ impl Session { 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 { diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index f186958b..6fc5c333 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -259,7 +259,11 @@ impl Session { })?; let target = alias.fact.type_of.as_deref()?; - let substituted = sema::types::substituted_spelling_with_defaults( + let substituted = sema::types::substituted_spelling_with_defaults::< + smol_str::SmolStr, + smol_str::SmolStr, + String, + >( target, alias.fact.parameters(), alias.fact.parameter_defaults(), diff --git a/crates/cpp_code_analysis/tests/suite/reported_defects.rs b/crates/cpp_code_analysis/tests/suite/reported_defects.rs index 00149e50..e8d6d1af 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**" ); } diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 0d1b5897..e7c2b3f4 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1006,11 +1006,23 @@ fn dependent_alias_member_markdown( // 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 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 @@ -2301,7 +2313,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; } @@ -2916,7 +2928,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 diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6effd500..9f1e587c 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -389,6 +389,9 @@ round trip is covered by * `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. * `the_type_of_a_fact` centralizes the fact-to-parser bridge: an indexed fact converts its handle, a binding-built fact falls back to the spelling parser. The member `element_type` and two type-inference paths use it. +* `DeclDetail`'s `bases`, `parameters`, `constraints` and `parameter_defaults` are `Vec`; the substitution + APIs (`substituted_spelling`, `TypeSubstitutions`, deduction) are generic over `AsRef`, so the storage type + reaches them without a heap `String` copy. * `DeclFact.type_of` / `returns` are now `Option>` rather than `Option`: the fact is sixteen bytes smaller and a clone shares the string instead of copying it. `serde`'s `rc` feature keeps the existing JSON shape. A size test pins the transition fact under 176 bytes. From bc8ff7cb3acfadf5e268082eed3ec74b3691bae6 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 10:25:48 +0800 Subject: [PATCH 019/102] docs: redesign facts around CST identities Replace the incremental fact design with the CST/TypeId model: facts store NameId/TypeId/ParamsId/DetailId/SyntaxId, not type or parameter text; default arguments and requires-clauses are SyntaxIds into the real tree. Document the removal of the synthetic parameter/constant/constraint parsers and allow red intermediate commits with green phase boundaries. --- docs/type-system-redesign.md | 718 +++++++++++++++++++++-------------- 1 file changed, 424 insertions(+), 294 deletions(-) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 9f1e587c..ad7e928d 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -1,101 +1,139 @@ # Type system and Fact storage redesign -Status: design, branch `refactor-type`. +Status: **redesign in progress**, branch `refactor-type`. -This document is the contract for the refactor. It records the current problem, the target representation, the -serialization boundary, and the order in which the code moves. It deliberately separates **the type store** (Phase 1) -from **changing `DeclFact`** (Phase 2+): the type engine is useful before any stored fact changes shape, and a -500-call-site refactor must not start with a broken build. +This document supersedes the earlier incremental version. That version treated `DeclFact`'s strings as a compatibility +transition and tried to keep every intermediate commit green. Both premises were wrong: -## 1. What is wrong today +* a type string kept "for the transition" becomes an API, and every workaround built on it survives longer than the + type store; +* a rewrite that must stay green at every step is a rewrite of the workarounds rather than of the model. -`sema::types::Type` is already a discriminated union: +The contract below is stricter. Facts contain **IDs**, not type text, parameter text, or default-argument text. +The CST is the only syntax reader. The parser is never called on a fragment with `ParserConfig::default()`. + +## 1. What is actually wrong + +The type store is not the main problem. The main problem is that the project has two sources of truth for syntax: + +```text +real CST ──► fact strings ──► parse the string again ──► another tree +``` + +The second tree is built from a fragment, with a default configuration, and then its offsets are mapped back to the +first tree's text. This is what the current code does in: + +```text +sema::call_syntax::parameter_names_from_text +sema::call_syntax::parameters_in_a_written_list +sema::call_syntax::tidy_list_text +sema::constant::tokens_of +sema::constraint::* (top-level text splitting) +``` + +Concrete examples: ```rust -enum Type { - Builtin { spelling }, - Named { name, arguments }, - TemplateParameter { name }, - Pointer { to }, - Reference { to, rvalue }, - Array { of, extent }, - Function { returns, parameters }, - Pack { of }, - Qualified { of, qualifiers }, -} +let text = format!("void __hint{parameter_list};"); +let tree = CppParser::parse(&text, ParserConfig::default()); +``` + +```rust +let tree = CppParser::parse(written, ParserConfig::default()); ``` -The index throws that shape away at the persistence boundary: +The default configuration is not the project's language. It loses: + +* `CppLanguageLevel` (C++17/20/23, C vs C++); +* `ProjectLanguage` (CUDA, Ascend, Unreal conventions); +* `Dialect` and `dialect_was_named`; +* the lexer configuration; +* the macro facts and symbol table of the file; +* file boundaries and the parse generation. + +Even when the same text happens to parse the same way, the work is wrong: + +1. **It is a second parser.** The real CST already has the parameter nodes, declarations, default expressions and + requires-clauses. The fragment parse reconstructs a lossy copy. +2. **It loses the AST.** `CppParam`, `CppInitializer`, `CppRequiresClause` and the typed expression nodes are gone; + only strings and a generic syntax tree remain. +3. **It loses positions.** The stored parameter list is tidied text, not file text. The synthetic tree's offsets are + into the tidied string; mapping them back to a source range through a hand-written byte map is fragile for + comments, CRLF, multi-byte characters and nested parameter lists. +4. **It cannot represent a default argument.** A default is an expression, not a string: + `= std::map{1, 2}`, `= [] { return 1; }()`, `= sizeof(T) * 2`. Storing it as text forces a third parse + and makes it impossible to type or evaluate without guessing. +5. **It cannot represent a requires-clause.** The constraint language is a syntax tree, and the current + `top_level_split`/`contains("<")` logic is a text parser for a grammar that is already parsed. + +The consequence is visible in the storage shape: ```rust DeclFact { - type_of: Option, - returns: Option, + type_of: Option>, + returns: Option>, // ... } DeclDetail { - parameters: Vec, - parameter_defaults: Vec, + bases: Vec, + parameters: Vec, + parameter_defaults: Vec, parameter_list: Option, + parameter_type_ids: Box<[TypeId]>, + parameter_names: Box<[Option]>, // ... } ``` -Consequences: - -* every declaration pays for a type spelling, even when thousands of declarations share one type; -* every consumer parses the same spelling again (`parse_type_spelling` is spread across queries, checks, hover, - completion and inlay); -* type equality is string equality, so two spellings of one structural type are not shared; -* `DeclFact` is 160 bytes and `DeclDetail` is 264 bytes; the detail box and its strings are paid per fact; -* `SmolStr`'s inline capacity is good for identifiers but wrong for `std::vector<...>` spellings. - -Measured shape before this design: 486,783 declarations over 1,761 files, `DeclFact` 424 bytes before the detail box -and 160 bytes after it; `DeclDetail` is 264 bytes when present. The summary is the dominant memory consumer. - -## 2. Goals and non-goals +`parameter_names`, `parameter_type_ids` and a `parameter_list` string can coexist only because the real parameter +facts were never designed. Adding more fields to this shape is not migration; it is accumulating workarounds. + +## 2. Invariants + +These are non-negotiable. A change that violates one is rejected even if it makes a test pass. + +1. **The parser parses whole files/translation units, not source fragments.** A synthetic `void __hint(...)` parse is + forbidden outside parser tests. There is no `CppParser::parse` on a fact's type, parameter list, default argument + or constraint text in production code. +2. **`ParserConfig` comes from the project.** A parse of a file uses the file's `LanguageConfig`, macros, symbols, + dialect, family and lexer settings. `ParserConfig::default()` in a production path is a bug; tests may use it only + for a self-contained source string. +3. **Facts store identities, not syntax text.** + * types → `TypeId`; + * names → `NameId`; + * parameters → `ParamsId` (an arena) and `ParameterFact`; + * expressions/defaults/constraints/declarations → `SyntaxId` (or a typed `AstPtr` while live); + * source positions → `SourceRange`. +4. **A `SyntaxId` is resolved against a tree generation.** It is `(kind, TextRange, generation)` and is only valid + for the file content it was made from. A cache entry whose content hash/generation differs is invalid; it is never + repaired by reparsing a fragment. +5. **The type store is read-only during queries.** It is append-only while indexing. Query-time substitution creates + `ComputedType`, never `intern`. +6. **Strings in the type/name stores are canonical spellings only.** A fact does not own a duplicate type spelling, + parameter text or default text. +7. **No test-only compatibility API survives as production code.** If a field exists for an old cache, the codec + version is bumped and the old entry is discarded. + +## 3. The ID model -Goals: - -1. One canonical, immutable type graph per index generation. -2. A type is parsed **once**, when the file is read; queries use handles. -3. Repeated types share storage; repeated names share storage. -4. Type identity is structural (plus source spelling for display), not string comparison. -5. `DeclFact` and `DeclDetail` become compact and cache-friendly. -6. Summaries remain self-contained on disk; type handles are not persisted as process addresses or global IDs. -7. The migration is incremental and each phase keeps the workspace green. - -Non-goals for the first pass: +```text +NameId(u32) interned spelling, 4 bytes +TypeId(u32) TypeStore node, 4 bytes +ParamsId(u32) parameter arena entry, 4 bytes +DetailId(u32) DeclDetail side-table entry, 4 bytes +SyntaxId CppSyntaxId: kind + TextRange, plus generation externally +``` -* alias resolution inside the type store (that remains an index query); -* full C++ template instantiation (substitution remains a query over the store); -* replacing expression storage (`requires`-clauses, default argument expressions) with a full expression IR; -* changing the parser's `Type` grammar in the same commit. +`NONE = u32::MAX` for every optional handle. IDs are process-local within one index generation and are rebased when a +summary is imported. They are never persisted as global IDs. -## 3. Core representation +### 3.1 TypeId -The new module is `crates/cpp_code_analysis/src/index/types/`. +`TypeStore` keeps the compact graph already implemented: ```rust -pub struct TypeId(u32); -pub struct NameId(u32); - -pub struct TypeStore { - nodes: Vec, - interned: HashMap, - names: NameInterner, -} - -pub struct TypeNode { - pub kind: TypeKind, - /// The spelling the source used, when one exists. - pub spelling: Option, -} - -pub struct ArgsId(u32); - -pub enum TypeKind { +TypeKind { Builtin(NameId), Named { name: NameId, arguments: ArgsId }, TemplateParameter(NameId), @@ -103,310 +141,402 @@ pub enum TypeKind { DecltypeAuto, Pointer(TypeId), Reference { to: TypeId, rvalue: bool }, - Array { of: TypeId, extent: u64 }, // UNKNOWN_EXTENT is the `int[]` sentinel + Array { of: TypeId, extent: u64 }, Function { returns: TypeId, parameters: ArgsId }, Pack(TypeId), Qualified { of: TypeId, qualifiers: Qualifiers }, } ``` -Design rules: +`TypeKind` is 16 bytes; `TypeNode` is 16 bytes; argument lists live in an `ArgsId` arena. The store is immutable +after the index drain. `ComputedType` (≤32 bytes, `SmolStr` names, `Arc` children) is the query-side materialization. -* **`TypeId` is 4 bytes**, not an `Arc` pointer. A fact pays 8 bytes for two optional handles. -* **`ArgsId` and an argument arena** for children: a `Box<[TypeId]>` is sixteen bytes before the enum tag, which - made `TypeKind` 32 bytes because of `Named` alone. The arena keeps the enum at **16 bytes**; the same argument - sequence is interned once and shared by every type that names it. -* **Spelling lives in a parallel table**, not on `TypeNode`, for the same reason: `TypeNode` stays 16 bytes. -* **`NameInterner` uses `SmolStr` and `rustc_hash::FxHashMap`**: most names fit inline, and the map is an internal - cache rather than a DoS-facing table. -* **`NameInterner` owns the strings.** `TypeStore` hands out `NameId`; facts eventually store name IDs too. -* **Append-only.** Nodes are never mutated. A file edit creates a new summary and a new generation; old handles - either die with the generation or are dropped with the index. -* **Hash-consed.** Interning key is `(TypeKind, Option)`; the same structure and spelling produce one ID. -* **Spelling is part of identity.** `std::size_t` and `unsigned long long` may be structurally equivalent, but the - source spelling is what a hover must display. Alias resolution is a separate query, not a rewrite at intern time. -* **No AST inside facts.** A `DeclFact` stores handles; `TypeRef` is the read API, borrowing the store. +**Type construction must be from CST nodes, not from `parse_type_spelling`.** The parser's typed nodes +(`CppDeclSpecifierSeq`, `CppDeclarator`, `CppTypeId`, `CppPointerType`, `CppArrayType`, `CppTrailingReturnType`) can be +lowered directly into `TypeKind`. `parse_type_spelling` remains only at external boundaries: CLI input, tests, and a +malformed cache migration that is immediately re-read. -## 4. The read API +### 3.2 SyntaxId -Consumers should not pattern-match `TypeKind` and walk the store themselves. +Use the existing `CppSyntaxId`/`CppSyntaxNodePtr` machinery: ```rust -pub struct TypeRef<'a> { - store: &'a TypeStore, - id: TypeId, +pub struct SyntaxId { + kind: CppKind, + range: TextRange, + generation: u64, } +``` + +* `CppSyntaxId::from_node` gives `(kind, range)`. +* `CppSyntaxId::to_node_from_root` resolves against the real tree. +* A typed `AstPtr` is the live form: `CppParam`, `CppInitializer`, `CppRequiresClause`, `CppExpr`. +* The cache stores only `SyntaxId` (kind + range); it never stores a red node or a `&CppSyntaxNode`. +* Resolution API: -impl TypeRef<'_> { - pub fn kind(&self) -> &TypeKind; - pub fn display(&self) -> String; - pub fn class_name(&self) -> Option<&str>; - pub fn arguments(&self) -> &[TypeId]; - pub fn pointee(&self) -> Option>; - pub fn is_const(&self) -> bool; - pub fn substituted(&self, parameters: &[NameId], arguments: &[TypeId]) -> TypeRef<'_>; +```rust +pub trait SyntaxResolver { + fn resolve(&self, file: &Path, id: SyntaxId) -> Option; + fn resolve_param(&self, file: &Path, id: SyntaxId) -> Option; + fn resolve_initializer(&self, file: &Path, id: SyntaxId) -> Option; + fn resolve_requires(&self, file: &Path, id: SyntaxId) -> Option; } ``` -`TypeRef` keeps the store and handle together. A caller cannot accidentally use an ID from another store, and a -function that needs to return a derived type does so through `TypeStore::intern_*`, not by allocating an AST. +If the tree is not available, the answer is `Unknown`/`None`. The query does **not** parse the stored fragment to +manufacture a tree. -`SemanticModel` will hold `&TypeStore` alongside its existing resolver and `TypeMemo`; the model remains the -request-scoped owner of derived-answer caches. The store itself is owned by `ProjectIndex`, because it survives -individual requests and must be shareable across reader threads. +### 3.3 NameId -## 5. Fact storage +`NameInterner` is a store-local `Vec` plus `FxHashMap`. A fact's `name` and `scope` are +`NameId`s. Displaying a name asks the store; a long name is one shared allocation in the name table, not one per +fact. -### 5.1 Phase 2 shape +### 3.4 ParamsId and ParameterFact + +Parameters live in a side arena, not in `DeclFact`: ```rust -pub struct DeclFact { - pub name: NameId, - pub scope: Option, - pub kind: DeclKind, - pub flags: FactFlags, - pub type_of: Option, - pub returns: Option, - pub range: SourceRange, - pub name_range: SourceRange, - pub detail: Option, +pub struct ParameterFact { + pub name: Option, + pub type_of: TypeId, + pub declarator: SyntaxId, // the Parameter node in the real CST + pub default_value: Option, // the Initializer expression, if any + pub pack: bool, // parameter pack / ellipsis + flags: ParamFlags, } ``` -`FactFlags` packs: +There is no `text`, no `type_of: String`, no `parameter_list: String`. A parameter's source spelling is read from +its `SyntaxId` range when a signature is rendered; the type is the `TypeId`; the default is the `SyntaxId` of the +initializer. + +`ParameterFact` is produced by the **summary builder** from `CppParamList`: ```text -enumerator local exported definition -split_by_a_directive clean guard -access +CppParamList + └─ CppParam + ├─ CppDeclSpecifierSeq / CppDeclarator → TypeStore::lower_cpp_type → TypeId + ├─ CppNameToken → NameInterner → NameId + ├─ CppInitializer → CppSyntaxId → SyntaxId + └─ CppSyntaxId of the Parameter node ``` -`DeclKind` and `Access` are `#[repr(u8)]`; booleans do not each occupy a byte after alignment. +`CppParam::get_type_text()` is not the source of a `TypeId`; it is a debugging helper. The lowering reads the typed +nodes so pointer/reference/array/function shapes are structural, not re-parsed. -Target: 48–56 bytes for the common fact, down from 160. +## 4. Fact storage, v2 -### 5.2 Detail as a side table - -`Option>` is eight bytes **plus one allocation per fact with detail**, and puts the detail far from -the fact. `FileSummary` gets a parallel detail store: +### 4.1 DeclFact ```rust -pub struct FileSummary { - pub facts: Vec, - pub details: Vec>>, - // ... +pub struct DeclFact { + pub name: NameId, + pub scope: NameId, // NONE for file scope + pub kind: DeclKind, + pub flags: FactFlags, // local, definition, exported, enumerator, split-by-directive, clean + pub type_of: TypeId, // variables and aliases; NONE otherwise + pub returns: TypeId, // functions; NONE otherwise + pub parameters: ParamsId, // NONE when there is no parameter list + pub detail: DetailId, // NONE when there are no rare fields + pub declaration: SyntaxId, // the declaration/declarator node + pub name_range: SourceRange, } ``` -A fact holds a `DetailId` (or no detail). Ordinary variables, enumerators and fields pay four bytes, not a pointer -and not a 264-byte record. Detail records stay contiguous for the declarations that need them. +No `String`, no `SmolStr`, no `Option>`, no `Option>`. -### 5.3 Structured parameter lists +`FactFlags` is a `u16`/`u32` bit set. `range` is derivable from `declaration` but `name_range` is kept because it is +the hot key for navigation and rename. -`DeclDetail.parameter_list` is a string today because the declaration is often in another file and the consumer -needs names and types. Store the structure instead: +### 4.2 DeclDetail side table -```rust -pub struct Parameter { - pub name: Option, - pub type_id: TypeId, - pub default: Option, -} +`DeclDetail` is no longer boxed per fact; it is a row in a side table: +```rust pub struct DeclDetail { - pub parameters: Box<[Parameter]>, - pub parameter_types: Box<[TypeId]>, - pub bases: Box<[BaseSpec]>, + pub in_namespace: Option, + pub returns_in_the_class: Option, + pub bases: Box<[TypeId]>, + pub template_parameters: Box<[TemplateParameterFact]>, + pub constraints: Box<[SyntaxId]>, + pub requires_clause: Option, pub pattern: Option, - pub requires_clause: Option, - // ... + pub reflection: Option, +} + +pub struct TemplateParameterFact { + pub name: NameId, + pub default: Option, // an expression, not a string } ``` -Rendering a signature becomes a walk over `Parameter` and `TypeRef::display`. A `parameter_list` spelling can be -kept only as a display fallback for a construct whose structure is incomplete; it is no longer the primary storage. +`DetailId` is an index into `Vec>>` or a flat arena. A fact without any detail pays four +bytes, not eight for a box and not a heap allocation. -## 6. Serialization +### 4.3 Parameter arena -`TypeId` is a process-local handle and must never be written to disk directly. Each `FileSummary` carries a local -type table: +`ParamsId` indexes a `ParamsStore`: ```rust -pub struct FileSummary { - pub types: TypeTable, // local IDs -> encoded nodes - pub facts: Vec, // local TypeId values - // ... +pub struct ParamsStore { + entries: Vec>, + ids: FxHashMap, ParamsId>, } ``` -Write path: +Parameters are compared structurally; a declaration with the same parameter list in two files shares one entry. +The arena is built only during indexing. Queries get `&[ParameterFact]`. -1. syntax -> `Type` -> `TypeStore` (in memory); -2. build a compact `TypeTable` for the summary and assign local IDs; -3. write facts with local `TypeId` values; -4. write the table before the facts. +### 4.4 What is deliberately absent -Read path: +```text +type_of: String / SmolStr / Arc absent +returns: String / SmolStr / Arc absent +parameter_list: String absent +parameters: Vec absent +parameter_defaults: Vec absent +parameter_names: Vec> absent +text: String absent +``` -1. decode `TypeTable`; -2. import each node into the global `TypeStore` (deduplicating); -3. rewrite the summary's facts to global IDs; -4. insert the summary. +Source text remains only in the VFS/cooked rendering and in the parser's tree. A fact that needs a spelling asks the +`NameId`/`TypeStore` or resolves a `SyntaxId`; there is nothing to reparse. -This gives self-contained cache entries and cross-file deduplication after load. It also means type IDs never have -to be stable across process restarts, which is the property a global interner cannot honestly offer. Bump -`FORMAT_VERSION` and `CODEC_VERSION`; old entries are unreachable rather than decoded into a different type model. +## 5. Syntax-derived features -## 7. Migration phases +### 5.1 Parameters and signatures -### Phase 1 — type store only (no fact changes) +The signature popup is built from the declaration's `ParamsId`: -* implement `TypeId`, `TypeKind`, `TypeNode`, `TypeStore`, `NameInterner`, `TypeRef`; -* conversion from `sema::types::Type`; -* `display`, `class_name`, `arguments`, `pointee`, `is_const`; -* tests for interning, spelling preservation, structural equality and ID stability; -* no `DeclFact` edits and no query migrations. +* parameter names → `NameId`; +* parameter types → `TypeId` (render with `ComputedType`); +* default arguments → `SyntaxId` resolved to `CppInitializer` (or omitted if the file is unavailable); +* parameter spans → the `SyntaxId` ranges in the real source; the label is composed from source slices at those + ranges, not from a stored `parameter_list` and not from a synthetic tree. + +The old string functions are deleted: + +```text +parameter_names_from_text +parameters_in_a_written_list +tidy_list_text +``` -### Phase 2 — additive facts +Callers move as follows: -* add `type_of_id` / `returns_id` beside the existing fields; -* add `FileSummary.types` and the codec table; -* populate both representations; -* add `MemoryReport` counters: type nodes, intern hits, bytes saved, facts with types; -* keep every existing consumer working from the old fields. +| caller | new source | +| --- | --- | +| `signature` | `CppParamList` nodes / `ParameterFact` | +| `overload::parameters_in` | `&[ParameterFact]` | +| `argument_count` | parameter facts + `pack` flag | +| `missing_include` | parameter `TypeId`s | +| `inlay` / `completion` | `ParameterFact.name` | +| `member_facts` | `ParameterFact` | -### Phase 3 — migrate hot consumers +### 5.2 Constant evaluation -In order: +`constant.rs` must not parse a constant expression from a string: -1. `type_of` / `type_at`; -2. `members_of` / `class_name` / argument substitution; -3. alias resolution; -4. completion; -5. hover and inlay; -6. diagnostics and checks. +```text +old: written: &str → CppParser::parse(written, default) → tokens → evaluator +new: CppExpr / SyntaxId → resolve → CppExpr nodes / real token stream → evaluator +``` -Each step deletes one class of `parse_type_spelling` calls. The type store becomes the only input; string parsing -remains only at external boundaries (CLI spellings, tests, malformed cache migration). +The evaluator accepts a typed expression (`CppExpr`) or a `CppSyntaxNode` from the CST. It never manufactures a +translation unit. Default arguments use the same path: `ParameterFact.default_value` is a `SyntaxId`, resolved to +`CppInitializer` and evaluated from the tree. -### Phase 4 — remove the old storage +### 5.3 Constraints and requires-clauses -* `DeclFact.type_of` / `returns` become `Option`; -* `DeclDetail.parameter_list` becomes structured `Parameter` values; -* pack flags, add the detail side table; -* update the codec and bump versions; -* remove the compatibility accessors; -* run the memory probe and the full test suite. +`constraint.rs`/`requires` evaluation is a CST/AST walk: -## 8. Risks and decisions +```text +old: condition: &str → top_level_split/contains('<') → string trait parser +new: CppRequiresClause / CppConstraint expression → typed AST walk → trait evaluation +``` -* **Alias identity.** The store interns the spelling and the structure; it does not resolve aliases. `using Int = - int;` creates an alias declaration, and a consumer that needs the target asks the index. This keeps the type store - a pure cache and avoids cycles during indexing. -* **Generation lifetime.** The store is append-only per index generation. A file edit drops the summaries that - depended on it and creates new nodes; facts from dropped summaries must not keep old IDs alive. The index - generation is the boundary, not a reference count per node. -* **Thread safety.** `TypeStore` is immutable after a drain / behind the same lock as the index. `TypeId` is a - plain integer and can cross reader threads; `TypeRef` borrows the store and cannot outlive a request. -* **Name interning.** Names are far more repetitive than types (`_Tp`, `size`, `std`). They use the same - append-only interner, but IDs are not persisted globally; the summary name table is local. -* **Cache duplication.** A long type is written once per summary's type table, not once per fact. Cross-file - duplication is resolved when the summary is imported. -* **No big-bang.** The old string fields remain until every consumer has an ID path. The codec version is the - switch that prevents a half-migrated cache from being read. +`DeclDetail.constraints` and `requires_clause` hold `SyntaxId`s. The trait evaluator matches `CppExpr` variants +(`!`, `&&`, `||`, `CppCallExpr`, `CppBinaryExpr`, type arguments) rather than splitting text. -## 9. First implementation slice +### 5.4 No `parse_type_spelling` in facts or checks -Phase 1 lands only `index::types`: +Type lowering from CST: ```text -TypeId / NameId -TypeKind / TypeNode -TypeStore / NameInterner / TypeKey -TypeRef -Type -> TypeStore conversion -display / class_name / arguments / pointee / is_const -unit tests +CppDeclSpecifierSeq + CppDeclarator + → TypeStore::lower_cpp_type + → TypeId ``` -`DeclFact`, `DeclDetail`, the codec and every query remain untouched in that slice. The next slice starts by -measuring interning on a real standard-library closure before adding a single field to a fact. +`parse_type_spelling` is allowed only for: + +* CLI/tool input; +* test fixtures written as strings; +* an external API that explicitly accepts a spelling. + +It is not called from `DeclFact`, `DeclDetail`, `constant`, `constraint`, `signature`, `inlay`, `completion`, +`overload`, or any diagnostic. -## 10. Storage and computation are two different jobs +## 6. Serialization and generations -The two layers are deliberate, and they are not two semantic models: +A summary record contains local tables: ```text -index::types::TypeKind / TypeId storage: 16-byte nodes, append-only, writer-only -index::types::ComputedType computation: <=32 bytes, owned by a request/model -sema::types::Type parser bridge: the syntax-facing construction format +NameTable NameId -> spelling +TypeTable local TypeId -> EncodedType +ParamsTable local ParamsId -> [ParameterFact with local TypeId/SyntaxId] +DetailTable local DetailId -> DeclDetail with local handles +SyntaxTable local SyntaxId -> kind + range ``` -`TypeId` is assigned only while indexing. A query must never call `intern*`: the store is read-only for readers, which -is what keeps hover, completion and inlay on different threads from serializing on a write lock. +Facts reference local IDs, never process-global IDs. On decode: -A query materializes what it needs: +1. verify codec version; +2. verify every `SyntaxId`'s file content hash/generation; +3. import names/types/params/details into the destination stores; +4. rebase all local IDs; +5. reject the summary if a `SyntaxId` cannot be validated (do not parse a fragment to repair it). -```rust -let computed: ComputedType = index.types().materialize(fact.type_of_id())?; +`CODEC_VERSION` is bumped for every schema change. There is no compatibility branch that reconstructs a missing +string. + +## 7. Workarounds to delete, not port + +Delete these functions and their tests that assert string behavior: + +```text +sema::call_syntax::parameter_names_from_text +sema::call_syntax::parameters_in_a_written_list +sema::call_syntax::tidy_list_text +sema::constant::tokens_of +constraint.rs' top_level_split and text-level trait parser +``` + +Delete these fields/APIs: + +```text +DeclFact::type_of (string) +DeclFact::returns (string) +DeclDetail::parameter_list +DeclDetail::parameter_names +DeclDetail::parameter_type_ids (replaced by ParameterFact) +DeclDetail::parameters / parameter_defaults as strings +DeclDetail::bases as strings +``` + +Delete these call patterns: + +```text +CppParser::parse(&format!("void __hint…"), ParserConfig::default()) +CppParser::parse(parameter_list, ParserConfig::default()) +CppParser::parse(written, ParserConfig::default()) // constant/constraint +parse_type_spelling(fact.type_of) ``` -`ComputedType`: - -* is at most 32 bytes (`size_of` is asserted); -* copies names from the store as `SmolStr` — short names inline, long names share the store's `Arc`; -* shares children through `Arc`, so substitution and member walks are pointer copies; -* owns no borrow of the index and writes nothing; -* is cached by the request's `SemanticModel`, not by the global index. - -`Named`, `Function` and `Qualified` are boxed inside `ComputedType` so the enum stays in the budget. `sema::types::Type` -is the parser bridge; Phase 3 makes `ComputedType` the query-facing type and reduces `sema::types::Type` to -construction/conversion (or removes it). - -## 11. Progress - -**Phase 1 — done.** `index::types` has the store, handles, interning, spelling-preserving `TypeRef` and tests. -No consumer changed. - -**Phase 2a — done.** `ProjectIndex` owns a `TypeStore`; `DeclFact` carries `type_of_id` / `returns_id` -(with `TypeId::NONE` as the transition sentinel), and `ProjectIndex::insert_at` interns every non-empty spelling once. -`TypeKind` and `TypeNode` are 16 bytes. - -**Phase 2b — done.** `FileSummary` carries a local `TypeTable`; `summary_codec` writes and reads it with -`CODEC_VERSION` 43. Fact IDs are written; when a fact has a handle its per-fact spelling is omitted and the decoder -restores it from the table. `ProjectIndex::insert_at` imports the table and rewrites the IDs to store handles. The -round trip is covered by -`a_cached_summary_remaps_its_type_ids_on_insert`. `TypeStore::materialize` builds `ComputedType` without mutation; -`ComputedType` is asserted to be <= 32 bytes. The memory report has `types`, `type_names`, `type_argument_lists` and -`type_store_bytes`. - -**Phase 3 — started.** - -* `ProjectIndex::computed_type_of` is the first read-side bridge from a fact handle to `ComputedType`; the - namespace-alias member query uses it before the transition string. -* `SemanticModel` owns a request-scoped `computed` cache, keyed by `TypeId`; `materialize` is called at most once per - handle per request, and the cache is dropped with the model. -* `ComputedType` is asserted to be <= 32 bytes and materialization is asserted not to change `TypeStore::len()`. -* `the_type_of_a_fact` centralizes the fact-to-parser bridge: an indexed fact converts its handle, a binding-built fact - falls back to the spelling parser. The member `element_type` and two type-inference paths use it. -* `DeclDetail`'s `bases`, `parameters`, `constraints` and `parameter_defaults` are `Vec`; the substitution - APIs (`substituted_spelling`, `TypeSubstitutions`, deduction) are generic over `AsRef`, so the storage type - reaches them without a heap `String` copy. -* `DeclFact.type_of` / `returns` are now `Option>` rather than `Option`: the fact is sixteen - bytes smaller and a clone shares the string instead of copying it. `serde`'s `rc` feature keeps the existing JSON - shape. A size test pins the transition fact under 176 bytes. -* `DeclDetail` now carries `parameter_type_ids`: `insert_at` parses the parameter list once, interns each type and - includes those handles in the summary's `TypeTable`; the codec writes and reads them, and insertion remaps them. - The string `parameter_list` remains for display and as the transition fallback. Template-argument hints now materialize - `parameter_type_ids` from the store instead of parsing the list. - -Still to do: - -* migrate the bulk of `class_name` / `members_of` / `type_at` to `ComputedType` and delete their - `parse_type_spelling` calls; -* remove the fact strings and shrink `DeclFact` to the target shape; -* add the summary type-table size to `summary_bytes` and its display; -* remove `sema::types::Type` as a public query type. - -The two ID fields add eight bytes to a fact until Phase 4 removes the strings; that is a deliberate temporary cost, -not the target shape. +A CI guard should fail if `CppParser::parse` appears in `cpp_code_analysis/src` outside: + +* `FileView::parse` / the session's whole-file parser; +* `cpp_parser` tests; +* an explicit external-input boundary with a comment naming it. + +## 8. Migration plan + +Intermediate commits may be red. This is a branch rewrite, not a sequence of production hot patches. Each *merge +point* must be green: + +### Phase 0 — foundations + +* add `SyntaxId`/resolver and generation tracking around `CppSyntaxId`; +* add `ParamsStore`, `ParameterFact`, `DetailStore` skeletons; +* add codec v-next with local tables; +* add tests that resolve typed CST nodes. + +### Phase 1 — parameter facts + +* build `ParameterFact` in the summary builder from `CppParamList`; +* store parameter `TypeId`s built from CST; +* migrate signature, inlay, completion, argument-count, overload, missing-include; +* delete the three call_syntax functions; +* merge point: full tests green, no synthetic parameter parse. + +### Phase 2 — type identities + +* lower types from CST into `TypeStore` at fact-build time; +* remove `type_of`/`returns` strings; +* migrate all readers to `TypeId` / `ComputedType` / `type_spelling_of` from the store only; +* merge point: no `parse_type_spelling` in production fact paths. + +### Phase 3 — expressions and constraints + +* store default initializers and requires-clauses as `SyntaxId`; +* rewrite constant evaluator over `CppExpr`/real CST tokens; +* rewrite constraint evaluator over the typed AST; +* delete text splitters; +* merge point: no fragment parse in constant/constraint. + +### Phase 4 — fact layout + +* move `DeclDetail` to a side table (`DetailId`); +* move parameters to `ParamsId`; +* pack flags, shrink `DeclFact` to the target schema; +* update codec and memory report; +* merge point: size/benchmark gates. + +### Phase 5 — remove the old model + +* delete `sema::types::Type` as a public query type (keep only parser lowering if needed); +* delete remaining compatibility accessors; +* delete `parse_type_spelling` from analysis except external boundaries; +* run the repository-wide no-reparse guard. + +**It is accepted that intermediate commits do not pass all tests.** Compile errors and test failures are expected +while a caller migration is in flight. The branch is merged only at a phase boundary, with the full suite and clippy +green. + +## 9. Tests and measurements + +Required regression tests: + +1. **Configuration parity**: the same declaration with a CUDA/Unreal/C++23 config produces parameter/type facts from + the real tree; no default-config synthetic parse exists. +2. **Complex default**: `void f(std::map m = {{1, 2}});` stores a `SyntaxId`; resolving it yields a + `CppInitializer` whose expression can be evaluated. +3. **Constraint**: `requires requires(T t) { t.size(); }` stores a `SyntaxId` and evaluates through typed AST nodes. +4. **Signature spans**: a parameter list with comments/CRLF/multibyte text produces spans that slice the real source + text correctly. +5. **Cache**: `SyntaxId` generation/content-hash mismatch invalidates the summary; no fragment parse occurs. +6. **Memory**: `DeclFact` size, `ParameterFact` arena bytes, no per-fact type strings, type dedup. +7. **No-reparse guard**: source grep fails on forbidden `CppParser::parse` call sites. + +## 10. Open decisions to settle before Phase 1 + +1. **`SyntaxId` representation**: keep `(CppKind, TextRange)` plus an external generation, or add a compact + `SyntaxId { file: SyntaxFileId, start: u32, len: u32, kind: u16 }` to fit in 12/16 bytes. The latter is preferable + for `ParameterFact` and default expressions. +2. **`AstPtr`**: a typed `rowan` pointer is cheap live but not serializable; confirm that persisted data uses + `SyntaxId` and live query caches use `AstPtr`. +3. **Template parameter defaults**: `SyntaxId` of the default expression plus a `TypeId` for its lowered type, or + `SyntaxId` only until evaluation. +4. **Constraint evaluation**: a typed constraint AST or direct `CppRequiresClause` walking; do not introduce a + second grammar. +5. **`SyntaxFileId`**: one per VFS file/generation; a `SyntaxId` must be resolvable without a path string in the hot + path. + +## 11. Current state (superseded pieces) + +The type store in `index/types/` is a valid foundation: + +* `TypeKind`/`TypeNode` 16 bytes, `ArgsId` arena; +* `TypeTable` and local-ID import/export; +* `ComputedType` ≤32 bytes and request-scoped cache; +* `TypeId`/`TypeRef` read APIs. + +The following pieces are **not** the target and will be removed: + +* `DeclFact.type_of` / `returns` as strings; +* `DeclDetail.parameter_list`, `parameter_names`, `parameter_type_ids`; +* `sema::types::Type` as a public query type; +* all synthetic parameter/constant/constraint parsing. + +No new code may build on those fields or functions. The next commit starts Phase 0/1 from the model above. From 7c1071289985f4effd73bcae0bed8015be5ae766 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 10:50:11 +0800 Subject: [PATCH 020/102] feat(params): add CST-derived parameter facts ParameterFact carries a CppSyntaxId declaration, an optional default-initializer SyntaxId, a pack flag, a name and a TypeId placeholder; parameter_facts_of reads CppParamList directly. Fix CppParam::get_name for pack declarators without letting nested function-pointer parameters steal a name. --- crates/cpp_code_analysis/src/index/mod.rs | 1 + crates/cpp_code_analysis/src/index/params.rs | 105 +++++++++++++++++++ crates/cpp_parser/src/syntax/node/cpp/mod.rs | 34 +++++- docs/type-system-redesign.md | 5 + 4 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 crates/cpp_code_analysis/src/index/params.rs diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index f8ab8593..a39ef1e2 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -70,6 +70,7 @@ 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; 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..c9d62d91 --- /dev/null +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -0,0 +1,105 @@ +//! **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 type of a parameter is a [`TypeId`] in the target schema. Until the CST type-lowering lands it is +//! [`TypeId::NONE`]; the field is deliberately an ID rather than a spelling, so adding the lowering is not a schema +//! change to every consumer. +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 super::types::TypeId; + +/// **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 / ellipsis parameter. + pub pack: bool, + /// Filled by the CST type lowering; `NONE` until that phase lands. + pub type_of: TypeId, +} + +/// **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() +} + +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), + type_of: TypeId::NONE, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cpp_parser::{CppParser, ParserConfig}; + + fn parameters(source: &str) -> Vec { + let tree = CppParser::parse(source, ParserConfig::default()); + let list = tree + .get_red_root() + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + parameter_facts_of(&list) + } + + #[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); + assert_eq!( + facts[2].type_of, + TypeId::NONE, + "until the type lowering lands" + ); + } + + #[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_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 701437a1..7024f96f 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -1477,8 +1477,40 @@ 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 name as text, for comparing one name against another. diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index ad7e928d..5cedfa95 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -525,6 +525,11 @@ Required regression tests: ## 11. Current state (superseded pieces) +**Phase 0 started.** `index::params::ParameterFact` now stores a parameter's `CppSyntaxId` declaration, its optional +default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from +the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function +pointer's nested parameters. `TypeId` is present as `NONE` until the CST type lowering lands. + The type store in `index/types/` is a valid foundation: * `TypeKind`/`TypeNode` 16 bytes, `ArgsId` arena; From 3605aec68d578ef2da5c9e99d3e25313b4b394a9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:04:16 +0800 Subject: [PATCH 021/102] feat(facts): store CST parameter facts on declarations DeclDetail carries ParameterFact values built from CppParamList; the codec persists their CppSyntaxId/name/default/pack/type handle (CODEC_VERSION 45). Name consumers in inlay and completion read the facts before falling back to text. --- crates/cpp_code_analysis/src/cache/summary.rs | 11 +++ .../src/cache/summary_codec.rs | 68 +++++++++++++++++++ .../src/index/project/bases.rs | 2 + .../src/index/project/tests.rs | 5 ++ .../cpp_code_analysis/src/sema/call_syntax.rs | 20 ++++++ .../src/sema/declarations.rs | 21 ++++++ .../src/session/completion/mod.rs | 4 +- .../src/session/completion/request.rs | 2 +- crates/cpp_code_analysis/src/session/inlay.rs | 14 ++-- crates/cpp_parser/src/syntax/id.rs | 20 ++++++ docs/type-system-redesign.md | 3 +- 11 files changed, 156 insertions(+), 14 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index ca5edeb4..8169aca3 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -32,6 +32,7 @@ use crate::Token; use crate::cache; use crate::condition; use crate::index; +use crate::index::params::ParameterFact; use crate::index::types::{TypeId, TypeTable}; use crate::macros; use crate::paths; @@ -414,6 +415,9 @@ pub struct DeclDetail { /// **The parameter types in the index's interned store**, position for position. Empty until the summary is /// inserted or for an old record; [`DeclDetail::parameter_list`] remains the display/fallback source. pub parameter_type_ids: Box<[TypeId]>, + /// **Parameters as CST facts**, not text. This is the storage signature/inlay/argument-count readers move to; + /// `parameter_list` is display fallback only. + pub parameter_facts: Box<[ParameterFact]>, } impl DeclDetail { @@ -441,6 +445,7 @@ impl DeclDetail { && self.pattern.is_none() && self.parameter_list.is_none() && self.parameter_type_ids.is_empty() + && self.parameter_facts.is_empty() } } @@ -464,6 +469,7 @@ impl DeclDetail { + strings_bytes(&self.constraints) + strings_bytes(&self.parameter_defaults) + self.parameter_type_ids.len() * size_of::() + + self.parameter_facts.len() * size_of::() + self.reflection.as_ref().map_or(0, |reflection| { on_the_heap(&reflection.macro_name) + reflection.specifiers.len() * size_of::() @@ -579,6 +585,11 @@ impl DeclFact { .map_or(&[], |detail| &detail.parameter_type_ids) } + /// **Parameters as the CST declared them.** Empty for a fact built before this field existed. + pub fn parameter_facts(&self) -> &[ParameterFact] { + self.detail().map_or(&[], |detail| &detail.parameter_facts) + } + pub fn parameter_list(&self) -> Option<&str> { self.detail() .and_then(|detail| detail.parameter_list.as_deref()) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index a3703c62..8de23beb 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1123,6 +1123,68 @@ fn get_type_table(reader: &mut Reader<'_>) -> Result { Ok(TypeTable { entries }) } +fn put_parameter_facts(out: &mut Vec, facts: &[crate::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)); + put_u32(out, fact.type_of.raw()); + } +} + +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 = cpp_parser::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( + cpp_parser::CppSyntaxId::from_raw_parts(kind, start, end) + .ok_or(DecodeError::BadDiscriminant)?, + ) + } + _ => return Err(DecodeError::BadDiscriminant), + }; + let pack = reader.u8()? != 0; + let type_of = TypeId::from_raw(reader.u32()?); + facts.push(crate::index::params::ParameterFact { + name, + declaration, + default_value, + pack, + type_of, + }); + } + Ok(facts) +} + fn put_opt_str(out: &mut Vec, value: Option<&str>) { match value { Some(text) => { @@ -1435,6 +1497,7 @@ mod tests { parameter_list: Some("(int, int)".into()), parameter_type_ids: vec![TypeId::from_raw(0), TypeId::from_raw(1)] .into_boxed_slice(), + parameter_facts: Box::default(), // The `Some` branch, which is the one only a **local** ever has — see // [`DeclFact::in_namespace`]. The two facts below cover `None`. in_namespace: Some("std::ranges".into()), @@ -1783,6 +1846,7 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bo for type_id in fact.parameter_type_ids() { put_u32(out, type_id.raw()); } + put_parameter_facts(out, fact.parameter_facts()); put_opt_str(out, fact.pattern()); put_range(out, fact.range); put_range(out, fact.name_range); @@ -1862,6 +1926,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { for _ in 0..count { parameter_type_ids.push(TypeId::from_raw(reader.u32()?)); } + let parameter_facts = get_parameter_facts(reader)?; let pattern = reader.optional_string()?; let range = reader.range()?; let name_range = reader.range()?; @@ -1924,6 +1989,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), parameter_type_ids: parameter_type_ids.into_boxed_slice(), + parameter_facts: parameter_facts.into_boxed_slice(), }), }) } @@ -2263,6 +2329,7 @@ fn a_cooked_reading_round_trips() { parameter_defaults: Vec::new(), parameter_list: None, parameter_type_ids: Box::default(), + parameter_facts: Box::default(), pattern: Some("Widget".into()), in_namespace: Some("std".into()), reflection: Some(summary::ReflectionFact { @@ -2301,6 +2368,7 @@ fn a_cooked_reading_round_trips() { parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), parameter_type_ids: Box::default(), + parameter_facts: Box::default(), pattern: None, in_namespace: None, reflection: None, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 06f519a5..f2a76605 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -419,6 +419,8 @@ pub(crate) fn fact_from_binding_with( _ => None, }, parameter_type_ids: Box::default(), + parameter_facts: sema::declarations::declared_parameter_facts_with(shapes, binding) + .into_boxed_slice(), }), // **Who may name it**, read the same way and for the same reason: a member list built from the buffer is // what a completion after `.` offers, and a `private:` member must not be in it. See [DeclFact::access]. diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index d2010ff0..f9fd5e65 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -202,6 +202,11 @@ fn a_function_detail_interns_its_parameter_types() { .iter() .find(|fact| fact.name == "f") .expect("the function"); + let parameters = function.parameter_facts(); + assert_eq!(parameters.len(), 2, "both parameters are CST facts"); + 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 = function.parameter_type_ids(); assert_eq!(types.len(), 2, "both parameters got a handle"); assert_eq!( diff --git a/crates/cpp_code_analysis/src/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index 9264eba2..dbf0d817 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -53,6 +53,21 @@ pub(crate) fn parameter_names_from_text(parameter_list: &str) -> Option Option>> { + let facts = fact.parameter_facts(); + if !facts.is_empty() { + return Some( + facts + .iter() + .map(|fact| fact.name.as_ref().map(ToString::to_string)) + .collect(), + ); + } + fact.parameter_list().and_then(parameter_names_from_text) +} + /// **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. /// @@ -100,6 +115,11 @@ pub(crate) fn parameters_in_a_written_list( 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 /// of. /// diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 0cde2417..d3f06fc8 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -3533,6 +3533,26 @@ pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option sema::call_syntax::parameter_list_text(declarator.syntax()) } +/// **Parameters as CST facts**, from the declarator the shape table already found. This is the only builder a fact +/// uses; [`DeclDetail::parameter_list`] is display fallback. +pub(crate) fn declared_parameter_facts_with( + shapes: &DeclarationShapes, + binding: &Binding, +) -> Vec { + let mut found = None; + shapes.on_the_path(binding.name_range.start_offset, |shape| { + if let Some(declarator) = &shape.declarator + && names_the_binding(declarator, binding.name_range.start_offset) + { + found = Some(declarator.clone()); + } + }); + found + .and_then(|declarator| sema::call_syntax::parameter_list_node(&declarator)) + .map(|list| crate::index::params::parameter_facts_of(&list)) + .unwrap_or_default() +} + /// **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 @@ -4107,6 +4127,7 @@ fn fact_for( pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), parameter_type_ids: Box::default(), + parameter_facts: declared_parameter_facts_with(shapes, binding).into_boxed_slice(), }), access, exported, diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 2e2c01a9..4170894e 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2030,9 +2030,7 @@ fn doc_comments( .filter(|name| !name.is_empty()) .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(fact) { names.extend(found.into_iter().flatten()); } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 39e17362..c5b6d36b 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -1056,7 +1056,7 @@ impl Session { let chosen = candidates[0]; // 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()?)? + let name = sema::call_syntax::parameter_names_of_fact(&chosen.fact)? .get(at) .cloned() .flatten()?; diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index 5078386e..cb69f3f7 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -64,7 +64,9 @@ 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_of, parameter_names_from_text, parameter_names_of_fact, +}; use crate::sema::scopes::parameters_of; use crate::{FileView, Known, ProjectIndex}; use cpp_parser::CppAstNode; @@ -590,10 +592,7 @@ fn callable_object_parameter_names( if member.fact.name != "operator()" { continue; } - let Some(text) = member.fact.parameter_list() else { - continue; - }; - let Some(names) = parameter_names_from_text(text) else { + let Some(names) = parameter_names_of_fact(&member.fact) else { continue; }; if names.len() != passed { @@ -704,10 +703,7 @@ fn constructor_parameter_names( if scope.rsplit("::").next().map(str::trim) != Some(name) { continue; } - let Some(list) = fact.parameter_list() else { - continue; - }; - let Some(names) = parameter_names_from_text(list) else { + let Some(names) = parameter_names_of_fact(fact) else { continue; }; if names.len() < passed { 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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 5cedfa95..6c75cc3d 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -528,7 +528,8 @@ Required regression tests: **Phase 0 started.** `index::params::ParameterFact` now stores a parameter's `CppSyntaxId` declaration, its optional default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function -pointer's nested parameters. `TypeId` is present as `NONE` until the CST type lowering lands. +pointer's nested parameters. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` +writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them before the text fallback. The type store in `index/types/` is a valid foundation: From f101d2aa6014812d57ef320041b617a99c2ff2d7 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:14:15 +0800 Subject: [PATCH 022/102] refactor(params): delete the synthetic parameter-name parser Parameter names now come from ParameterFact or from CppParamList via parameter_names_of_list; inlay reads the lambda's own CppParamList instead of parsing its text, and the unavailable-file fallback returns no hint rather than a default-config parse. --- .../cpp_code_analysis/src/sema/call_syntax.rs | 58 ++++++++----------- crates/cpp_code_analysis/src/session/inlay.rs | 21 ++----- docs/type-system-redesign.md | 5 +- 3 files changed, 34 insertions(+), 50 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index dbf0d817..496c0540 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -25,47 +25,36 @@ 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 names of a declaration's parameters, from the CST-derived facts.** The text reader is a fallback only for -/// a fact that was not built through the current summary path. +/// The names of a declaration's parameters, from its CST-derived facts. pub(crate) fn parameter_names_of_fact(fact: &crate::DeclFact) -> Option>> { let facts = fact.parameter_facts(); - if !facts.is_empty() { - return Some( - facts - .iter() - .map(|fact| fact.name.as_ref().map(ToString::to_string)) - .collect(), - ); + if facts.is_empty() { + return None; } - fact.parameter_list().and_then(parameter_names_from_text) + Some( + facts + .iter() + .map(|fact| fact.name.as_ref().map(ToString::to_string)) + .collect(), + ) } /// **The parameters of a written list, with their spans in that list** — the tree's answer to a question a @@ -75,7 +64,8 @@ pub(crate) fn parameter_names_of_fact(fact: &crate::DeclFact) -> Option 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. +/// This is the remaining synthetic parser for parameter *spans*; its callers are being moved to `ParameterFact`, after +/// which it and `tidy_list_text` are deleted. /// /// 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 diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index cb69f3f7..cdd89916 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -65,7 +65,8 @@ 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, parameter_names_of_fact, + 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}; @@ -505,16 +506,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) @@ -644,9 +636,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; } @@ -767,7 +758,7 @@ fn contains(range: SourceRange, offset: usize) -> bool { /// `(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 +/// same way the parameter-span reader 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('(') { diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6c75cc3d..74e5d2e7 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -529,7 +529,10 @@ Required regression tests: default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function pointer's nested parameters. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` -writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them before the text fallback. +writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is +deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is +no synthetic name parse. The remaining synthetic reader is the parameter-span/type path (`parameters_in_a_written_list`, +`parameter_types_in_a_written_list`), which the next phase removes. The type store in `index/types/` is a valid foundation: From 67828d3df01cc9129c7f9759a8607a5a51338eda Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:24:34 +0800 Subject: [PATCH 023/102] feat(params): add the hash-consed parameter store ParamsStore interns Box<[ParameterFact]> lists and returns a four-byte ParamsId; equal parameter lists share one entry and the store has lower-bound accounting. DeclFact does not reference it yet; this is the handle the detail side table will use. --- crates/cpp_code_analysis/src/index/params.rs | 90 ++++++++++++++++++++ docs/type-system-redesign.md | 3 +- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index c9d62d91..e03b74bb 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -16,6 +16,8 @@ use cpp_parser::CppTokenKind; use smol_str::SmolStr; use super::types::TypeId; +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`). @@ -37,6 +39,81 @@ 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)] +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.entries.get(id.index()).map_or(&[], |facts| facts) + } + + /// 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() @@ -95,6 +172,19 @@ mod tests { ); } + #[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 an_unnamed_parameter_keeps_its_node() { let facts = parameters("void f(int);\n"); diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 74e5d2e7..789369fa 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -528,7 +528,8 @@ Required regression tests: **Phase 0 started.** `index::params::ParameterFact` now stores a parameter's `CppSyntaxId` declaration, its optional default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function -pointer's nested parameters. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` +pointer's nested parameters. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists. `TypeId` is present as `NONE` until the CST +type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is no synthetic name parse. The remaining synthetic reader is the parameter-span/type path (`parameters_in_a_written_list`, From 92ded90029b4f5b88122e286d5a7b6ed5550e760 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:33:40 +0800 Subject: [PATCH 024/102] feat(syntax): add the SyntaxId resolver SyntaxId is the parser's CppSyntaxId; FileSyntax resolves it against a real tree and typed helpers cast to CppParam/CppInitializer/CppRequiresClause. Tests round-trip a parameter and a braced default initializer, so facts have a path to syntax that never parses text. --- crates/cpp_code_analysis/src/index/mod.rs | 1 + crates/cpp_code_analysis/src/index/syntax.rs | 125 +++++++++++++++++++ docs/type-system-redesign.md | 4 +- 3 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 crates/cpp_code_analysis/src/index/syntax.rs diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index a39ef1e2..03b1e9b2 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -75,6 +75,7 @@ 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; 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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 789369fa..d0af5ab1 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -528,7 +528,9 @@ Required regression tests: **Phase 0 started.** `index::params::ParameterFact` now stores a parameter's `CppSyntaxId` declaration, its optional default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function -pointer's nested parameters. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists. `TypeId` is present as `NONE` until the CST +pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser's `CppSyntaxId`), a `SyntaxResolver` for a parsed file and typed +`resolve_parameter` / `resolve_initializer` / `resolve_requires`; the tests round-trip a parameter and a braced default +initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From fdf6e54d3716856582afe0fcb1ecf3fa4813f3af Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:44:50 +0800 Subject: [PATCH 025/102] feat(params): import local parameter tables ParamsStore exposes its entries and can rebuild/import another local table, returning the old-to-new ParamsId mapping. This is the piece a summary's local parameter arena needs before it can be attached to DeclFact. --- crates/cpp_code_analysis/src/index/params.rs | 41 ++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index e03b74bb..4640331d 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -102,6 +102,28 @@ impl ParamsStore { self.entries.get(id.index()).map_or(&[], |facts| facts) } + 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::>() @@ -185,6 +207,25 @@ mod tests { 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"); From 13e630ad593071c9bd7816cbe34a7d9ff36a02d6 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 11:52:58 +0800 Subject: [PATCH 026/102] feat(params): give the project index a parameter store ProjectIndex owns the ParamsStore that DeclFact::parameters will index, and exposes it read-only. The summary-local table and insert-time import are the next step; this keeps the handle and arena in one place without a half-wired fact field. --- crates/cpp_code_analysis/src/index/project/macro_walk.rs | 6 ++++++ crates/cpp_code_analysis/src/index/project/mod.rs | 2 ++ docs/type-system-redesign.md | 3 ++- 3 files changed, 10 insertions(+), 1 deletion(-) 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 d50f50e1..653d1c5e 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -12,6 +12,7 @@ use crate::UnlistedBase; use crate::Visibility; use crate::cache; use crate::index; +use crate::index::params::ParamsStore; use crate::index::types::ComputedType; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -382,6 +383,11 @@ impl ProjectIndex { &self.types } + /// The index's parameter arena; facts reach it by `DeclFact::parameters` after the side table lands. + pub fn parameters(&self) -> &ParamsStore { + &self.parameters + } + /// **The written type spelling of a fact**, from its handle when the store has one and from the transition /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so /// deleting the string field later does not require revisiting them. diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 8b4b08ae..f35e4e7b 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -346,6 +346,8 @@ pub struct ProjectIndex { macros: Marked, /// The interned types of every declaration this index has inserted. types: TypeStore, + /// The interned parameter lists of every declaration this index has inserted. + parameters: crate::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. /// diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index d0af5ab1..23dbbcc7 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -530,7 +530,8 @@ default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of( the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser's `CppSyntaxId`), a `SyntaxResolver` for a parsed file and typed `resolve_parameter` / `resolve_initializer` / `resolve_requires`; the tests round-trip a parameter and a braced default -initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists. `TypeId` is present as `NONE` until the CST +initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes +`parameters()`, ready for `DeclFact::parameters` when the summary-local table is wired. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From 585a61fa4590dadef80a8eccc053a7efc1a5ae27 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 12:04:30 +0800 Subject: [PATCH 027/102] feat(facts): attach parameter handles to declarations FileSummary carries its local ParamsStore; the index builder interns each fact's CST parameter facts and stores a ParamsId; summary_codec writes the table and fact handles (CODEC_VERSION 46). DeclDetail keeps a temporary copy for raw facts until all readers use the arena. --- crates/cpp_code_analysis/src/cache/summary.rs | 7 ++++- .../src/cache/summary_codec.rs | 30 +++++++++++++++++++ .../cpp_code_analysis/src/cache/unit_codec.rs | 1 + crates/cpp_code_analysis/src/index/mod.rs | 12 ++++++++ crates/cpp_code_analysis/src/index/params.rs | 2 +- .../src/index/project/bases.rs | 1 + .../src/index/project/macro_environment.rs | 1 + .../src/index/project/tests.rs | 9 ++++++ .../src/sema/declarations.rs | 1 + .../src/session/completion/mod.rs | 2 ++ docs/type-system-redesign.md | 4 ++- 11 files changed, 67 insertions(+), 3 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 8169aca3..1c141cf3 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -32,7 +32,7 @@ use crate::Token; use crate::cache; use crate::condition; use crate::index; -use crate::index::params::ParameterFact; +use crate::index::params::{ParameterFact, ParamsId, ParamsStore}; use crate::index::types::{TypeId, TypeTable}; use crate::macros; use crate::paths; @@ -266,6 +266,8 @@ pub struct DeclFact { pub returns: Option>, /// The same return type in the index's interned store; see [`DeclFact::type_of_id`]. pub returns_id: TypeId, + /// The parameter-list handle in the summary's/global `ParamsStore`; `NONE` when there is no list. + pub parameters: ParamsId, /// **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 @@ -5369,6 +5371,8 @@ pub struct FileSummary { /// **The summary's local type table.** Facts hold local IDs on disk; inserting into a `ProjectIndex` imports /// this table and rewrites them to process-local handles. Empty for a summary built directly from syntax. pub types: TypeTable, + /// The summary's local parameter arena, indexed by `DeclFact::parameters`. + pub parameters: ParamsStore, pub macros: Vec, pub includes: Vec, pub guards: SummaryGuards, @@ -5555,6 +5559,7 @@ impl FileSummary { key, declarations: Vec::new(), types: TypeTable::default(), + parameters: ParamsStore::default(), macros: Vec::new(), includes: Vec::new(), guards: SummaryGuards::default(), diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 8de23beb..51344499 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -403,6 +403,7 @@ pub fn encode(summary: &FileSummary) -> Vec { // order they were written. A fact's IDs are local to this table; `ProjectIndex::insert_at` imports the table // and rewrites them, so a process-local handle is never written to disk. put_type_table(&mut out, &summary.types); + put_params_store(&mut out, &summary.parameters); out } @@ -793,6 +794,7 @@ pub fn decode(bytes: &[u8]) -> Result { }; let types = get_type_table(&mut reader)?; + 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 @@ -806,6 +808,7 @@ pub fn decode(bytes: &[u8]) -> Result { key, declarations, types, + parameters, macros, includes, guards, @@ -1185,6 +1188,24 @@ fn get_parameter_facts( Ok(facts) } +fn put_params_store(out: &mut Vec, store: &crate::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(crate::index::params::ParamsStore::from_entries(entries)) +} + fn put_opt_str(out: &mut Vec, value: Option<&str>) { match value { Some(text) => { @@ -1419,6 +1440,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: crate::index::params::ParamsStore::default(), types: TypeTable { entries: vec![ EncodedType { @@ -1452,6 +1474,7 @@ mod tests { // A class returns nothing either, so `None` — and the second fact below covers the other value. returns: None, returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, // 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), @@ -1516,6 +1539,7 @@ mod tests { type_of_id: TypeId::NONE, returns: Some("ns::Container".into()), returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, // 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, @@ -1546,6 +1570,7 @@ mod tests { type_of_id: TypeId::NONE, returns: None, returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, access: None, exported: false, // A round trip that always wrote one value would not notice a decoder that dropped the byte. @@ -1821,6 +1846,7 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bo }; put_opt_str(out, returns); put_u32(out, fact.returns_id.raw()); + 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()); @@ -1914,6 +1940,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let type_of_id = TypeId::from_raw(reader.u32()?); let returns = reader.optional_string()?; let returns_id = TypeId::from_raw(reader.u32()?); + let parameters_id = crate::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)?; @@ -1969,6 +1996,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { type_of_id, returns: returns.map(std::sync::Arc::from), returns_id, + parameters: parameters_id, split_by_a_directive, range, name_range, @@ -2308,6 +2336,7 @@ fn a_cooked_reading_round_trips() { type_of_id: TypeId::NONE, returns: None, returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, range: SourceRange::new(10, 20), name_range: SourceRange::new(16, 6), local: false, @@ -2347,6 +2376,7 @@ fn a_cooked_reading_round_trips() { type_of_id: TypeId::NONE, returns: Some("void".into()), returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, range: SourceRange::new(40, 30), name_range: SourceRange::new(44, 1), local: true, diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 5ce7ded3..b72df5c1 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -489,6 +489,7 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), types: crate::index::types::TypeTable::default(), + parameters: crate::index::params::ParamsStore::default(), macros: cooked.macros.clone(), includes: Vec::new(), guards: SummaryGuards::default(), diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index 03b1e9b2..2162e363 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::index::types::TypeTable; use crate::preprocess; use crate::sema; @@ -831,6 +832,15 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { let (mut declarations, mut guards) = { build_facts(&scopes, &preprocessing, &root, &errors, keep_locals) }; + let mut parameters = ParamsStore::new(); + for fact in &mut declarations { + let Some(detail) = fact.detail.as_ref() else { + continue; + }; + if !detail.parameter_facts.is_empty() { + fact.parameters = parameters.intern(detail.parameter_facts.to_vec()); + } + } let mut interner = PathInterner::new(cfg!(windows)); // **This file's compilation, not the project's** — see `CompilerConfig::for_file`. @@ -963,6 +973,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { key, declarations, types: TypeTable::default(), + parameters, macros, includes, guards, @@ -1098,6 +1109,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { key: SummaryKey::new(0, 0), declarations: Vec::new(), types: TypeTable::default(), + parameters: ParamsStore::default(), macros, includes, guards, diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index 4640331d..15892f80 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -65,7 +65,7 @@ impl ParamsId { /// **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)] +#[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct ParamsStore { entries: Vec>, ids: FxHashMap, ParamsId>, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index f2a76605..ede8b6bb 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -358,6 +358,7 @@ pub(crate) fn fact_from_binding_with( .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)) .map(|written| Arc::from(written.as_str())), returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, // **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`]. // 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 18aaa30b..6a503283 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -514,6 +514,7 @@ impl ProjectDefinition { type_of_id: TypeId::NONE, returns: None, returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::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 diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index f9fd5e65..22ed570f 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -202,6 +202,15 @@ fn a_function_detail_interns_its_parameter_types() { .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" + ); let parameters = function.parameter_facts(); assert_eq!(parameters.len(), 2, "both parameters are CST facts"); assert_eq!(parameters[0].name.as_deref(), Some("value")); diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index d3f06fc8..37a86dd2 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -4112,6 +4112,7 @@ fn fact_for( type_of_id: TypeId::NONE, returns: returns.map(std::sync::Arc::from), returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { in_namespace: in_namespace.map(Into::into), diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 4170894e..1aacd01c 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2528,6 +2528,7 @@ mod tests { use super::*; use crate::DeclModifiers; use crate::FactGuard; + use crate::index::params::ParamsId; use crate::index::types::TypeId; use crate::summary; @@ -2593,6 +2594,7 @@ mod tests { type_of_id: TypeId::NONE, returns: returns.map(Arc::from), returns_id: TypeId::NONE, + parameters: ParamsId::NONE, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), clean: true, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 23dbbcc7..12cf7067 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -531,7 +531,9 @@ the CST. The parser's `CppParam::get_name` now handles pack declarations without pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser's `CppSyntaxId`), a `SyntaxResolver` for a parsed file and typed `resolve_parameter` / `resolve_initializer` / `resolve_requires`; the tests round-trip a parameter and a braced default initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes -`parameters()`, ready for `DeclFact::parameters` when the summary-local table is wired. `TypeId` is present as `NONE` until the CST +`parameters()`. `FileSummary` now carries the local `ParamsStore`; `DeclFact::parameters` is a local `ParamsId`, the +index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` +still keeps a copy for raw facts outside the index; removing it is the next step. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From 8797f4f05f4c89e7f4babbdab2a501564a1d6d57 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 12:13:21 +0800 Subject: [PATCH 028/102] feat(params): resolve a fact's local parameter handle FileSummary::parameter_facts and ProjectIndex::parameter_facts_of resolve DeclFact::parameters through the summary's local ParamsStore; a raw fact outside the summary still has the detail copy, but an indexed one no longer needs text. --- crates/cpp_code_analysis/src/cache/summary.rs | 6 ++++++ crates/cpp_code_analysis/src/index/project/macro_walk.rs | 9 ++++++++- crates/cpp_code_analysis/src/index/project/tests.rs | 5 +++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 1c141cf3..87f6729c 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -743,6 +743,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. /// 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 653d1c5e..b0b2d9f6 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -12,7 +12,7 @@ use crate::UnlistedBase; use crate::Visibility; use crate::cache; use crate::index; -use crate::index::params::ParamsStore; +use crate::index::params::{ParameterFact, ParamsStore}; use crate::index::types::ComputedType; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -388,6 +388,13 @@ impl ProjectIndex { &self.parameters } + /// **The parameter facts a fact names, through the summary that owns its local `ParamsId`.** No text fallback. + pub fn parameter_facts_of(&self, file: &Path, fact: &DeclFact) -> &[ParameterFact] { + self.summaries + .get(&normalize(file)) + .map_or(&[], |summary| summary.parameter_facts(fact)) + } + /// **The written type spelling of a fact**, from its handle when the store has one and from the transition /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so /// deleting the string field later does not require revisiting them. diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 22ed570f..8644ab5d 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -211,6 +211,11 @@ fn a_function_detail_interns_its_parameter_types() { 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 = function.parameter_facts(); assert_eq!(parameters.len(), 2, "both parameters are CST facts"); assert_eq!(parameters[0].name.as_deref(), Some("value")); From d754efd29f18703828f9eda16910465db161c125 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 12:24:44 +0800 Subject: [PATCH 029/102] feat(params): lower parameter types and read argument counts from facts ParameterFact.type_of is filled from each CppParam's CST type and exported through the summary TypeTable; ProjectIndex::parameter_facts_of resolves the local ParamsId. argument_count uses the facts' defaults, packs and TypeId spellings, falling back to the old text path only for a fact with no arena entry. --- crates/cpp_code_analysis/src/index/mod.rs | 30 +++++++++++- crates/cpp_code_analysis/src/index/params.rs | 12 +++++ .../src/index/project/macro_walk.rs | 6 +++ .../src/index/project/tests.rs | 18 +++++++- .../src/sema/check/argument_count.rs | 46 ++++++++++++++++++- docs/type-system-redesign.md | 4 +- 6 files changed, 111 insertions(+), 5 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index 2162e363..f26a9262 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -45,11 +45,13 @@ use crate::RenderedUnit; use crate::directive; use crate::guards; use crate::index::params::ParamsStore; +use crate::index::types::TypeStore; use crate::index::types::TypeTable; use crate::preprocess; use crate::sema; use crate::summary; use crate::summary_codec; +use cpp_parser::CppAstNode; use cpp_parser::CppSyntaxNode; use cpp_parser::CppTokenData; use cpp_parser::LexerConfig; @@ -833,14 +835,38 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { let (mut declarations, mut guards) = { build_facts(&scopes, &preprocessing, &root, &errors, keep_locals) }; let mut parameters = ParamsStore::new(); + let mut parameter_types = TypeStore::new(); for fact in &mut declarations { - let Some(detail) = fact.detail.as_ref() else { + let Some(detail) = fact.detail.as_mut() else { continue; }; + for parameter in detail.parameter_facts.iter_mut() { + if let Some(node) = parameter.declaration.to_node_from_root(&root) + && let Some(cpp_parameter) = cpp_parser::CppParam::cast(node) + { + parameter.type_of = + parameter_types.intern_spelling(&cpp_parameter.get_type_text()); + } + } if !detail.parameter_facts.is_empty() { fact.parameters = parameters.intern(detail.parameter_facts.to_vec()); } } + let parameter_type_ids: Vec<_> = declarations + .iter() + .flat_map(|fact| { + fact.detail + .as_deref() + .map(|detail| { + detail + .parameter_facts + .iter() + .map(|parameter| parameter.type_of) + }) + .into_iter() + .flatten() + }) + .collect(); let mut interner = PathInterner::new(cfg!(windows)); // **This file's compilation, not the project's** — see `CompilerConfig::for_file`. @@ -972,7 +998,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { path: path.to_path_buf(), key, declarations, - types: TypeTable::default(), + types: parameter_types.export(parameter_type_ids), parameters, macros, includes, diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index 15892f80..ce2e4037 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -115,6 +115,18 @@ impl ParamsStore { store } + /// **Rewrite the parameter type handles after a summary's type table is imported.** The keys are the local + /// `TypeId` values the summary was encoded with. + pub fn remap_types(&mut self, mapping: &FxHashMap) { + for facts in &mut self.entries { + for fact in facts.iter_mut() { + if let Some(store_id) = mapping.get(&fact.type_of.raw()) { + fact.type_of = *store_id; + } + } + } + } + /// **Import another store's local handles**, deduplicating against this one. pub fn import(&mut self, from: &ParamsStore) -> FxHashMap { let mut mapping = FxHashMap::default(); 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 b0b2d9f6..fae37da5 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -425,6 +425,7 @@ impl ProjectIndex { // IDs to this store's IDs, then fill only the facts the old format left without one. if !summary.types.is_empty() { let mapping = self.types.import(&summary.types); + summary.parameters.remap_types(&mapping); for fact in &mut summary.declarations { if !fact.type_of_id.is_none() && let Some(store_id) = mapping.get(&(fact.type_of_id.index() as u32)) @@ -442,6 +443,11 @@ impl ProjectIndex { *type_id = *store_id; } } + for parameter in &mut detail.parameter_facts { + if let Some(store_id) = mapping.get(¶meter.type_of.raw()) { + parameter.type_of = *store_id; + } + } } } } diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 8644ab5d..7fc689d8 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -216,8 +216,24 @@ fn a_function_detail_interns_its_parameter_types() { 2, "the index resolves the summary-local handle" ); - let parameters = function.parameter_facts(); + let parameters = index.parameter_facts_of(path, function); assert_eq!(parameters.len(), 2, "both parameters are CST facts"); + assert_eq!( + index + .types() + .type_ref(parameters[0].type_of) + .expect("the parameter type was lowered") + .display(), + "double" + ); + assert_eq!( + index + .types() + .type_ref(parameters[1].type_of) + .expect("the parameter type was lowered") + .display(), + "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()); 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..af554daf 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -397,7 +397,13 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec let Some(parameters) = fact.parameter_list() else { continue; }; - let Some(callee) = the_callee_in(parameters) else { + let facts = context.index().parameter_facts_of(&file, fact); + let callee = if facts.is_empty() { + the_callee_in(parameters) + } else { + the_callee_in_facts(facts, context.index().types(), parameters) + }; + let Some(callee) = callee else { continue; }; // **The same signature declared twice is one candidate at the most permissive arity** — see @@ -407,6 +413,44 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec callees } +/// **One candidate out of the CST parameter facts.** Type spellings come from the type store; nothing is parsed. +fn the_callee_in_facts( + facts: &[crate::index::params::ParameterFact], + types: &crate::index::types::TypeStore, + parameter_list: &str, +) -> Option { + let mut written = 0usize; + let mut required = 0usize; + let mut variadic = has_an_ellipsis(parameter_list); + let mut spellings: Vec = Vec::new(); + for parameter in facts { + if parameter.pack { + variadic = true; + continue; + } + let spelling = types.spelling(parameter.type_of)?; + if spelling.trim().is_empty() { + return None; + } + written += 1; + if parameter.default_value.is_none() { + required += 1; + } + spellings.push(spelling.to_string()); + } + if written == 1 && spellings.len() == 1 && spellings[0].trim() == "void" { + written = 0; + required = 0; + spellings.clear(); + } + Some(Callee { + required, + written, + variadic, + parameters: spellings, + }) +} + /// **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 diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 12cf7067..970422a7 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -533,7 +533,9 @@ pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser' initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes `parameters()`. `FileSummary` now carries the local `ParamsStore`; `DeclFact::parameters` is a local `ParamsId`, the index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` -still keeps a copy for raw facts outside the index; removing it is the next step. `TypeId` is present as `NONE` until the CST +still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from +each `CppParam` (`get_type_text`) into the summary's `TypeTable`, and `argument_count` now reads counts, defaults and +type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From e0020e98d207da991c9ec31451172f4884ec6bd9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 12:33:08 +0800 Subject: [PATCH 030/102] refactor(overload): read parameter types from facts Add parameters_in_facts and use it in completion's template-parameter filter and the overload tie-break, with the ProjectIndex/TypeStore resolving each ParameterFact's TypeId. The text parser remains only as a fallback for a fact with no arena entry. --- .../src/index/project/calls.rs | 35 ++++++++++++++----- .../src/index/project/type_of.rs | 2 +- crates/cpp_code_analysis/src/sema/overload.rs | 25 +++++++++++++ .../src/session/completion/request.rs | 15 +++++++- docs/type-system-redesign.md | 4 ++- 5 files changed, 70 insertions(+), 11 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 7dd70db8..39c03f3e 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1036,7 +1036,7 @@ pub(crate) fn declaration_of_a_callee( && 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(chosen) = the_one_the_arguments_select(index, &types, &callable, &[]) && let Some((fact, file)) = callable.get(chosen) { return Known::Yes(NamedDeclaration::Indexed( @@ -1095,7 +1095,8 @@ pub(crate) fn declaration_of_a_callee( .iter() .map(Type::to_string) .collect(); - if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments) + if let Some(chosen) = + the_one_the_arguments_select(index, &types, &candidates, &explicit_arguments) && let Some(binding) = bindings.get(chosen) { return Known::Yes(NamedDeclaration::Here(binding.clone())); @@ -1376,7 +1377,7 @@ pub(crate) fn the_declaration_the_arguments_pick( .iter() .map(Type::to_string) .collect(); - let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?; + let chosen = the_one_the_arguments_select(index, &types, &candidates, &explicit_arguments)?; candidates.get(chosen).cloned() } @@ -1458,6 +1459,7 @@ 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( + index: &ProjectIndex, types: &[Known], candidates: &[(DeclFact, PathBuf)], explicit_arguments: &[String], @@ -1533,11 +1535,28 @@ pub(crate) fn the_one_the_arguments_select( 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)) - == Some(written) + let (fact, file) = &candidates[**at]; + { + let facts = index.parameter_facts_of(file, fact); + let parameters = if facts.is_empty() { + fact.parameter_list() + .map(|list| sema::overload::parameters_in(list).0) + .unwrap_or_default() + } else { + sema::overload::parameters_in_facts( + facts, + index.types(), + fact.parameter_list() + .is_some_and(|list| list.contains("...")), + ) + .0 + }; + parameters + .into_iter() + .next() + .and_then(|first| the_character_width(&first)) + == Some(written) + } }) .copied() .collect(); 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 0cb64b7e..723c99eb 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -2147,7 +2147,7 @@ pub(crate) fn operator_returns_of_with_arguments( .iter() .map(|argument| Known::Yes(argument.to_string())) .collect(); - let at = the_one_the_arguments_select(&types, &callable, &[])?; + let at = the_one_the_arguments_select(index, &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)?; diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 81f6d85b..4f964760 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -636,6 +636,31 @@ pub fn defaults_in(parameter_list: &str) -> usize { /// 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. +/// **The parameter types from CST facts**, with no parameter list parsing. The type spelling comes from the type +/// store; a pack is one parameter whose `...` is already gone. +pub fn parameters_in_facts( + facts: &[crate::index::params::ParameterFact], + types: &crate::index::types::TypeStore, + c_style_variadic: bool, +) -> (Vec, bool) { + let mut parameters = Vec::new(); + let mut variadic = c_style_variadic; + for fact in facts { + let Some(spelling) = types.spelling(fact.type_of) else { + continue; + }; + if fact.pack { + variadic = true; + if !spelling.trim().is_empty() { + parameters.push(spelling.to_string()); + } + } else { + parameters.push(spelling.to_string()); + } + } + (parameters, variadic) +} + pub fn parameters_in(parameter_list: &str) -> (Vec, bool) { let inner = parameter_list .trim() diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index c5b6d36b..c03aa9a4 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -1006,7 +1006,20 @@ impl Session { let Some(list) = member.fact.parameter_list() else { return false; }; - let types = sema::overload::parameters_in(list).0; + let facts = self + .store + .index() + .parameter_facts_of(&member.file, &member.fact); + let types = if facts.is_empty() { + sema::overload::parameters_in(list).0 + } else { + sema::overload::parameters_in_facts( + facts, + self.store.index().types(), + list.contains("..."), + ) + .0 + }; let Some(written) = types.get(at) else { return false; }; diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 970422a7..80e443f0 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -535,7 +535,9 @@ initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash- index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from each `CppParam` (`get_type_text`) into the summary's `TypeTable`, and `argument_count` now reads counts, defaults and -type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. `TypeId` is present as `NONE` until the CST +type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The +completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use +`parameters_in_facts`, so their normal indexed path no longer parses the list. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From 3a7874f5c0c2c7d63d83049dd56c123a2d7978f9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 12:58:58 +0800 Subject: [PATCH 031/102] test(params): pin overload input to CST parameter facts parameters_in_facts strips a pack's ellipsis from the CST type spelling; the integration test builds the facts from CppParam nodes and verifies types, packs and the C-style variadic flag without parsing a parameter list. --- crates/cpp_code_analysis/src/sema/overload.rs | 5 ++- crates/cpp_code_analysis/tests/params.rs | 44 +++++++++++++++++++ docs/type-system-redesign.md | 4 +- 3 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 crates/cpp_code_analysis/tests/params.rs diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 4f964760..8e5149ab 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -651,8 +651,9 @@ pub fn parameters_in_facts( }; if fact.pack { variadic = true; - if !spelling.trim().is_empty() { - parameters.push(spelling.to_string()); + let element = spelling.trim().trim_end_matches("...").trim(); + if !element.is_empty() { + parameters.push(element.to_string()); } } else { parameters.push(spelling.to_string()); diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs new file mode 100644 index 00000000..cdc19e16 --- /dev/null +++ b/crates/cpp_code_analysis/tests/params.rs @@ -0,0 +1,44 @@ +//! Parameter facts are the CST-side input to overload ranking; these tests pin that no parameter list text is parsed. + +use cpp_code_analysis::index::params::parameter_facts_of; +use cpp_code_analysis::index::types::TypeStore; +use cpp_code_analysis::sema::overload::parameters_in_facts; +use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; + +fn facts(source: &str) -> (cpp_parser::CppSyntaxTree, Vec) { + let tree = CppParser::parse(source, ParserConfig::default()); + let list = tree + .get_red_root() + .descendants() + .find_map(CppParamList::cast) + .expect("a parameter list"); + (tree, parameter_facts_of(&list)) +} + +#[test] +fn parameter_types_come_from_each_cpp_param() { + let (tree, mut facts) = facts("void f(int a, std::pair p, double... rest);\n"); + let mut types = TypeStore::new(); + for fact in &mut facts { + let node = fact + .declaration + .to_node_from_root(&tree.get_red_root()) + .expect("the parameter node"); + let parameter = CppParam::cast(node).expect("typed parameter"); + fact.type_of = types.intern_spelling(¶meter.get_type_text()); + } + let (parameters, variadic) = parameters_in_facts(&facts, &types, false); + assert_eq!(parameters, vec!["int", "std::pair", "double"]); + assert!(variadic); +} + +#[test] +fn a_c_style_ellipsis_is_reported_by_the_list_flag() { + let (_tree, facts) = facts("void f(const char* format, ...);\n"); + let mut types = TypeStore::new(); + let mut facts = facts; + facts[0].type_of = types.intern_spelling("const char*"); + let (parameters, variadic) = parameters_in_facts(&facts, &types, true); + assert_eq!(parameters, vec!["const char*"]); + assert!(variadic); +} diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 80e443f0..2940c399 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -537,7 +537,9 @@ still keeps a copy for raw facts outside the index; removing it is the next step each `CppParam` (`get_type_text`) into the summary's `TypeTable`, and `argument_count` now reads counts, defaults and type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use -`parameters_in_facts`, so their normal indexed path no longer parses the list. `TypeId` is present as `NONE` until the CST +`parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the +fact (the `...` is stripped from the CST type spelling), and an integration test pins the overload input to +`CppParam` nodes. `TypeId` is present as `NONE` until the CST type lowering lands. `DeclDetail` now carries the facts, `summary_codec` writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is From f5a51daf9fe63e02337b3f15f63a9a664ab51464 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 13:09:42 +0800 Subject: [PATCH 032/102] feat(params): resolve cooked facts through the source summary A cooked fact carries its own reading's local ParamsId. When the direct lookup is empty, parameter_facts_of finds the source summary declaration with the same name range and resolves that handle, so check paths over cooked declarations do not need a second synthetic parameter list. --- .../src/index/project/macro_walk.rs | 20 ++++++++++++++++--- docs/type-system-redesign.md | 4 +++- 2 files changed, 20 insertions(+), 4 deletions(-) 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 fae37da5..f6a9fd51 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -390,9 +390,23 @@ impl ProjectIndex { /// **The parameter facts a fact names, through the summary that owns its local `ParamsId`.** No text fallback. pub fn parameter_facts_of(&self, file: &Path, fact: &DeclFact) -> &[ParameterFact] { - self.summaries - .get(&normalize(file)) - .map_or(&[], |summary| summary.parameter_facts(fact)) + let Some(summary) = self.summaries.get(&normalize(file)) else { + return &[]; + }; + let direct = summary.parameter_facts(fact); + if !direct.is_empty() { + return direct; + } + // **A cooked fact carries its own reading's local id.** The source summary is a different arena, so find the + // declaration the two readings are both about by its name range and use *that* handle. A macro-only + // declaration is absent from the source summary and stays empty; the caller then falls back to its text path. + summary + .declarations + .iter() + .find(|candidate| { + candidate.name == fact.name && candidate.name_range == fact.name_range + }) + .map_or(&[], |candidate| summary.parameter_facts(candidate)) } /// **The written type spelling of a fact**, from its handle when the store has one and from the transition diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 2940c399..de4ed633 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -534,7 +534,9 @@ initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash- `parameters()`. `FileSummary` now carries the local `ParamsStore`; `DeclFact::parameters` is a local `ParamsId`, the index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from -each `CppParam` (`get_type_text`) into the summary's `TypeTable`, and `argument_count` now reads counts, defaults and +each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally +maps a cooked fact with a different arena to the source summary's declaration by name range, so checks over cooked +facts can resolve the same parameter list., and `argument_count` now reads counts, defaults and type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use `parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the From 4f9b87dfe66b7a7f63f525e2b40b1e9db243c0b0 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 13:17:44 +0800 Subject: [PATCH 033/102] refactor(checks): read missing-include types from parameter facts types_this_declaration_uses resolves the fact's ParamsId through ProjectIndex and reads parameter TypeIds; the synthetic parameter list parser is only the fallback for raw facts with no resolvable type spelling. missing_include and unresolved_type share the one reader. --- .../src/sema/check/missing_include.rs | 36 +++++++++++-------- .../src/sema/check/unresolved_type.rs | 2 +- docs/type-system-redesign.md | 5 +-- 3 files changed, 25 insertions(+), 18 deletions(-) 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..e9b9dce0 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -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,27 +306,33 @@ 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: &crate::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())), + let mut from_facts = 0usize; + for parameter in index.parameter_facts_of(file, fact) { + if let Some(spelling) = index.types().spelling(parameter.type_of) + && !spelling.trim().is_empty() + { + spellings.push(spelling.to_string()); + from_facts += 1; } } + if from_facts == 0 + && let Some(parameters) = fact.parameter_list() + && let Some(parsed) = parameters_in_a_written_list(parameters) + { + spellings.extend(parsed.into_iter().map(|(_, text)| text)); + } spellings } 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 e89cb9b2..46b88a30 100644 --- a/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs +++ b/crates/cpp_code_analysis/src/sema/check/unresolved_type.rs @@ -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/docs/type-system-redesign.md b/docs/type-system-redesign.md index de4ed633..23f8ea65 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -535,8 +535,9 @@ initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash- index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally -maps a cooked fact with a different arena to the source summary's declaration by name range, so checks over cooked -facts can resolve the same parameter list., and `argument_count` now reads counts, defaults and +maps a cooked fact with a different arena to the source summary's declaration by name range. `missing_include` and +`unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact +whose arena produced no type spelling at all., and `argument_count` now reads counts, defaults and type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use `parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the From 4580bfceadc43fa21f2f059901ccdae7cfe0b829 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 13:29:03 +0800 Subject: [PATCH 034/102] refactor(params): delete the synthetic parameter-type parser Template hints read ParameterFact.type_of through the type store, and the insert path no longer fills parameter_type_ids from parameter_list. parameter_types_in_a_written_list is removed; the project tests read the parameter arena instead. --- .../src/index/project/macro_walk.rs | 12 ----- .../src/index/project/tests.rs | 12 +++-- .../src/session/completion/request.rs | 15 ++++-- crates/cpp_code_analysis/src/session/inlay.rs | 48 ------------------- docs/type-system-redesign.md | 3 +- 5 files changed, 21 insertions(+), 69 deletions(-) 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 f6a9fd51..9402cc67 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -478,18 +478,6 @@ impl ProjectIndex { { fact.returns_id = self.types.intern_spelling(returns); } - if let Some(detail) = fact.detail.as_mut() - && detail.parameter_type_ids.is_empty() - && let Some(parameter_list) = detail.parameter_list.as_deref() - { - let written = - crate::session::inlay::parameter_types_in_a_written_list(parameter_list); - detail.parameter_type_ids = written - .iter() - .map(|written| self.types.intern_spelling(written)) - .collect::>() - .into_boxed_slice(); - } } let ids: Vec<_> = summary .declarations diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 7fc689d8..b9044baf 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -172,10 +172,10 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { .iter() .find(|fact| fact.name == "f") .expect("the function"); - let parameter = function - .parameter_type_ids() + let parameter = second + .parameter_facts_of(path, function) .first() - .copied() + .map(|parameter| parameter.type_of) .expect("a parameter"); assert_eq!( second @@ -237,7 +237,11 @@ fn a_function_detail_interns_its_parameter_types() { 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 = function.parameter_type_ids(); + let types: Vec<_> = index + .parameter_facts_of(path, function) + .iter() + .map(|parameter| parameter.type_of) + .collect(); assert_eq!(types.len(), 2, "both parameters got a handle"); assert_eq!( index.types().type_ref(types[0]).unwrap().display(), diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index c03aa9a4..9d5e5d41 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -837,10 +837,17 @@ impl Session { .collect(); match stored { Some(types) if !types.is_empty() => types, - _ => { - let parameter_list = fact.parameter_list()?; - inlay::parameter_types_in_a_written_list(parameter_list) - } + _ => fact + .parameter_facts() + .iter() + .filter_map(|parameter| { + self.store + .index() + .types() + .materialize(parameter.type_of) + .map(|computed| computed.to_string()) + }) + .collect(), } }; if parameter_types.is_empty() { diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index cdd89916..a5da32fe 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; @@ -754,51 +751,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 the parameter-span reader 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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 23f8ea65..6c375318 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -537,7 +537,8 @@ still keeps a copy for raw facts outside the index; removing it is the next step each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally maps a cooked fact with a different arena to the source summary's declaration by name range. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact -whose arena produced no type spelling at all., and `argument_count` now reads counts, defaults and +whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints +materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list., and `argument_count` now reads counts, defaults and type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use `parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the From d797fc26aa9b188abfd62835a95c69cb555c813a Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 13:38:02 +0800 Subject: [PATCH 035/102] refactor(facts): delete the duplicate parameter type ids DeclDetail::parameter_type_ids and its codec bytes are removed (CODEC_VERSION 47). Template hints and the project tests read ParameterFact.type_of through the ParamsStore; the detail field no longer shadows the arena. --- crates/cpp_code_analysis/src/cache/summary.rs | 11 ------ .../src/cache/summary_codec.rs | 14 ------- .../src/index/project/bases.rs | 1 - .../src/index/project/macro_walk.rs | 10 +---- .../src/sema/declarations.rs | 1 - .../src/session/completion/request.rs | 38 ++++++------------- docs/type-system-redesign.md | 4 +- 7 files changed, 15 insertions(+), 64 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 87f6729c..e4ddb279 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -414,9 +414,6 @@ pub struct DeclDetail { pub pattern: Option, /// The parameter list as the file spells it, parentheses included. pub parameter_list: Option, - /// **The parameter types in the index's interned store**, position for position. Empty until the summary is - /// inserted or for an old record; [`DeclDetail::parameter_list`] remains the display/fallback source. - pub parameter_type_ids: Box<[TypeId]>, /// **Parameters as CST facts**, not text. This is the storage signature/inlay/argument-count readers move to; /// `parameter_list` is display fallback only. pub parameter_facts: Box<[ParameterFact]>, @@ -446,7 +443,6 @@ impl DeclDetail { && self.parameter_defaults.is_empty() && self.pattern.is_none() && self.parameter_list.is_none() - && self.parameter_type_ids.is_empty() && self.parameter_facts.is_empty() } } @@ -470,7 +466,6 @@ impl DeclDetail { + strings_bytes(&self.parameters) + strings_bytes(&self.constraints) + strings_bytes(&self.parameter_defaults) - + self.parameter_type_ids.len() * size_of::() + self.parameter_facts.len() * size_of::() + self.reflection.as_ref().map_or(0, |reflection| { on_the_heap(&reflection.macro_name) @@ -581,12 +576,6 @@ impl DeclFact { self.detail().and_then(|detail| detail.pattern.as_deref()) } - /// The parameter types in the index's interned store, position for position; empty until inserted. - pub fn parameter_type_ids(&self) -> &[TypeId] { - self.detail() - .map_or(&[], |detail| &detail.parameter_type_ids) - } - /// **Parameters as the CST declared them.** Empty for a fact built before this field existed. pub fn parameter_facts(&self) -> &[ParameterFact] { self.detail().map_or(&[], |detail| &detail.parameter_facts) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 51344499..9e3945d8 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1518,8 +1518,6 @@ mod tests { // partial specialization from its primary template. `None` is covered by the facts below. pattern: Some("Widget<_Ty, _Alloc>".into()), parameter_list: Some("(int, int)".into()), - parameter_type_ids: vec![TypeId::from_raw(0), TypeId::from_raw(1)] - .into_boxed_slice(), parameter_facts: Box::default(), // The `Some` branch, which is the one only a **local** ever has — see // [`DeclFact::in_namespace`]. The two facts below cover `None`. @@ -1868,10 +1866,6 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bo put_str(out, default); } put_opt_str(out, fact.parameter_list()); - put_u32(out, fact.parameter_type_ids().len() as u32); - for type_id in fact.parameter_type_ids() { - put_u32(out, type_id.raw()); - } put_parameter_facts(out, fact.parameter_facts()); put_opt_str(out, fact.pattern()); put_range(out, fact.range); @@ -1948,11 +1942,6 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let requires_clause = reader.optional_string()?; let parameter_defaults = get_strings(reader)?; let parameter_list = reader.optional_string()?; - let count = reader.count()?; - let mut parameter_type_ids = Vec::with_capacity(count.min(64 * 1024)); - for _ in 0..count { - parameter_type_ids.push(TypeId::from_raw(reader.u32()?)); - } let parameter_facts = get_parameter_facts(reader)?; let pattern = reader.optional_string()?; let range = reader.range()?; @@ -2016,7 +2005,6 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { parameter_defaults, pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), - parameter_type_ids: parameter_type_ids.into_boxed_slice(), parameter_facts: parameter_facts.into_boxed_slice(), }), }) @@ -2357,7 +2345,6 @@ fn a_cooked_reading_round_trips() { requires_clause: Some("sizeof(T) > 0".into()), parameter_defaults: Vec::new(), parameter_list: None, - parameter_type_ids: Box::default(), parameter_facts: Box::default(), pattern: Some("Widget".into()), in_namespace: Some("std".into()), @@ -2397,7 +2384,6 @@ fn a_cooked_reading_round_trips() { requires_clause: None, parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), - parameter_type_ids: Box::default(), parameter_facts: Box::default(), pattern: None, in_namespace: None, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index ede8b6bb..c704830c 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -419,7 +419,6 @@ pub(crate) fn fact_from_binding_with( } _ => None, }, - parameter_type_ids: Box::default(), parameter_facts: sema::declarations::declared_parameter_facts_with(shapes, binding) .into_boxed_slice(), }), 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 9402cc67..bccfc39d 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -452,11 +452,6 @@ impl ProjectIndex { fact.returns_id = *store_id; } if let Some(detail) = fact.detail.as_mut() { - for type_id in &mut detail.parameter_type_ids { - if let Some(store_id) = mapping.get(&(type_id.index() as u32)) { - *type_id = *store_id; - } - } for parameter in &mut detail.parameter_facts { if let Some(store_id) = mapping.get(¶meter.type_of.raw()) { parameter.type_of = *store_id; @@ -483,10 +478,7 @@ impl ProjectIndex { .declarations .iter() .flat_map(|fact| { - let mut ids = vec![fact.type_of_id, fact.returns_id]; - if let Some(detail) = fact.detail.as_deref() { - ids.extend(detail.parameter_type_ids.iter().copied()); - } + let ids = vec![fact.type_of_id, fact.returns_id]; ids }) .collect(); diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 37a86dd2..450b3d44 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -4127,7 +4127,6 @@ fn fact_for( parameter_defaults: parameter_defaults.into_iter().map(SmolStr::from).collect(), pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), - parameter_type_ids: Box::default(), parameter_facts: declared_parameter_facts_with(shapes, binding).into_boxed_slice(), }), access, diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 9d5e5d41..d516f2f0 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -823,33 +823,17 @@ impl Session { // **The inserted summary already has parameter types.** Parse the written list only for a fact that predates // the store; a stored handle is materialized read-only, so a template-argument hint costs no parse and no // write to the type store. - let parameter_types: Vec = { - let stored: Option> = fact - .parameter_type_ids() - .iter() - .map(|id| { - self.store - .index() - .types() - .materialize(*id) - .map(|computed| computed.to_string()) - }) - .collect(); - match stored { - Some(types) if !types.is_empty() => types, - _ => fact - .parameter_facts() - .iter() - .filter_map(|parameter| { - self.store - .index() - .types() - .materialize(parameter.type_of) - .map(|computed| computed.to_string()) - }) - .collect(), - } - }; + let parameter_types: Vec = fact + .parameter_facts() + .iter() + .filter_map(|parameter| { + self.store + .index() + .types() + .materialize(parameter.type_of) + .map(|computed| computed.to_string()) + }) + .collect(); if parameter_types.is_empty() { return None; } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6c375318..27948094 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -538,7 +538,9 @@ each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex: maps a cooked fact with a different arena to the source summary's declaration by name range. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints -materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list., and `argument_count` now reads counts, defaults and +materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. +`DeclDetail::parameter_type_ids` and its codec bytes are deleted; the parameter arena is the only type source +(CODEC_VERSION 47)., and `argument_count` now reads counts, defaults and type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use `parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the From bd522ccff9d04ffdf98773651673713d7601c717 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 13:53:08 +0800 Subject: [PATCH 036/102] refactor(params): resolve parameter names through the summary arena Completion and inlay ask ProjectIndex::parameter_facts_of for the names; the build-time detail copy is consulted only for a fact that has no summary arena entry. This removes the normal path's reliance on DeclDetail.parameter_facts. --- .../cpp_code_analysis/src/sema/call_syntax.rs | 17 ++++++++++++++-- .../src/session/completion/mod.rs | 5 ++++- .../src/session/completion/request.rs | 20 +++++++++++++------ crates/cpp_code_analysis/src/session/inlay.rs | 9 +++++++-- 4 files changed, 40 insertions(+), 11 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index 496c0540..411ac2cf 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -44,8 +44,21 @@ pub(crate) fn parameter_list_has_a_pack(list: &CppParamList) -> bool { } /// The names of a declaration's parameters, from its CST-derived facts. -pub(crate) fn parameter_names_of_fact(fact: &crate::DeclFact) -> Option>> { - let facts = fact.parameter_facts(); +/// **The names from the summary arena, else from the raw fact's build-time copy.** The latter exists only for a +/// fact that has not been inserted through `ProjectIndex`; it is removed with that copy. +pub(crate) fn parameter_names_of_fact( + fact: &crate::DeclFact, + indexed: &[crate::index::params::ParameterFact], +) -> Option>> { + if !indexed.is_empty() { + return parameter_names_of_facts(indexed); + } + parameter_names_of_facts(fact.parameter_facts()) +} + +pub(crate) fn parameter_names_of_facts( + facts: &[crate::index::params::ParameterFact], +) -> Option>> { if facts.is_empty() { return None; } diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 1aacd01c..f2544236 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2030,7 +2030,10 @@ fn doc_comments( .filter(|name| !name.is_empty()) .map(ToString::to_string) .collect(); - if let Some(found) = sema::call_syntax::parameter_names_of_fact(fact) { + if let Some(found) = sema::call_syntax::parameter_names_of_fact( + fact, + index.parameter_facts_of(path, fact), + ) { names.extend(found.into_iter().flatten()); } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index d516f2f0..85a8ed76 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -809,6 +809,7 @@ impl Session { // **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. + let fact_file = found.file.clone(); let fact = match self .store .index() @@ -823,8 +824,10 @@ impl Session { // **The inserted summary already has parameter types.** Parse the written list only for a fact that predates // the store; a stored handle is materialized read-only, so a template-argument hint costs no parse and no // write to the type store. - let parameter_types: Vec = fact - .parameter_facts() + let parameter_types: Vec = self + .store + .index() + .parameter_facts_of(&fact_file, &fact) .iter() .filter_map(|parameter| { self.store @@ -1060,10 +1063,15 @@ impl Session { let chosen = candidates[0]; // Rule 4: the parameter's name, and the body's call of it. - let name = sema::call_syntax::parameter_names_of_fact(&chosen.fact)? - .get(at) - .cloned() - .flatten()?; + let name = sema::call_syntax::parameter_names_of_fact( + &chosen.fact, + self.store + .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 diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index a5da32fe..63db4433 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -581,7 +581,10 @@ fn callable_object_parameter_names( if member.fact.name != "operator()" { continue; } - let Some(names) = parameter_names_of_fact(&member.fact) else { + let Some(names) = parameter_names_of_fact( + &member.fact, + index.parameter_facts_of(&member.file, &member.fact), + ) else { continue; }; if names.len() != passed { @@ -691,7 +694,9 @@ fn constructor_parameter_names( if scope.rsplit("::").next().map(str::trim) != Some(name) { continue; } - let Some(names) = parameter_names_of_fact(fact) else { + let Some(names) = + parameter_names_of_fact(fact, index.parameter_facts_of(&declaration.file, fact)) + else { continue; }; if names.len() < passed { From 8343d38b2ca93bdf2a0d20935a61eaa760f9fb53 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 14:13:55 +0800 Subject: [PATCH 037/102] refactor(facts): build parameter arenas in the fact builder build_facts returns BuiltFacts with the parameter arena and lowered parameter TypeStore. The builder interns each CST parameter list, clears the build-time detail copy, and the index uses the returned table; callers receive facts through BuiltFacts. --- crates/cpp_code_analysis/src/cache/summary.rs | 5 +- .../src/cache/summary_codec.rs | 5 +- crates/cpp_code_analysis/src/index/mod.rs | 46 ++++-------------- .../src/sema/declarations.rs | 47 ++++++++++++++++--- crates/cpp_code_analysis/src/sema/render.rs | 5 +- crates/cpp_code_analysis/src/session/calls.rs | 4 +- docs/type-system-redesign.md | 4 +- 7 files changed, 60 insertions(+), 56 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index e4ddb279..58947565 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -414,8 +414,7 @@ pub struct DeclDetail { pub pattern: Option, /// The parameter list as the file spells it, parentheses included. pub parameter_list: Option, - /// **Parameters as CST facts**, not text. This is the storage signature/inlay/argument-count readers move to; - /// `parameter_list` is display fallback only. + /// Build-time CST parameter facts; the inserted summary moves them to `ParamsStore` and clears this box. pub parameter_facts: Box<[ParameterFact]>, } @@ -576,7 +575,7 @@ impl DeclFact { self.detail().and_then(|detail| detail.pattern.as_deref()) } - /// **Parameters as the CST declared them.** Empty for a fact built before this field existed. + /// Build-time CST parameter facts; empty on a fact whose summary moved them to `ParamsStore`. pub fn parameter_facts(&self) -> &[ParameterFact] { self.detail().map_or(&[], |detail| &detail.parameter_facts) } diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 9e3945d8..73197280 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1554,6 +1554,7 @@ mod tests { // answer, and `None` would be "nobody looked". detail: summary::DeclDetail::in_a_box(summary::DeclDetail { parameter_list: Some("()".into()), + parameter_facts: Box::default(), ..Default::default() }), }, @@ -1866,7 +1867,6 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bo put_str(out, default); } put_opt_str(out, fact.parameter_list()); - put_parameter_facts(out, fact.parameter_facts()); put_opt_str(out, fact.pattern()); put_range(out, fact.range); put_range(out, fact.name_range); @@ -1942,7 +1942,6 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let requires_clause = reader.optional_string()?; let parameter_defaults = get_strings(reader)?; let parameter_list = reader.optional_string()?; - let parameter_facts = get_parameter_facts(reader)?; let pattern = reader.optional_string()?; let range = reader.range()?; let name_range = reader.range()?; @@ -2005,7 +2004,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { parameter_defaults, pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), - parameter_facts: parameter_facts.into_boxed_slice(), + parameter_facts: Box::default(), }), }) } diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index f26a9262..60c3c8ce 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -45,13 +45,11 @@ use crate::RenderedUnit; use crate::directive; use crate::guards; use crate::index::params::ParamsStore; -use crate::index::types::TypeStore; -use crate::index::types::TypeTable; +use crate::index::types::{TypeId, TypeTable}; use crate::preprocess; use crate::sema; use crate::summary; use crate::summary_codec; -use cpp_parser::CppAstNode; use cpp_parser::CppSyntaxNode; use cpp_parser::CppTokenData; use cpp_parser::LexerConfig; @@ -832,41 +830,13 @@ 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 mut parameters = ParamsStore::new(); - let mut parameter_types = TypeStore::new(); - for fact in &mut declarations { - let Some(detail) = fact.detail.as_mut() else { - continue; - }; - for parameter in detail.parameter_facts.iter_mut() { - if let Some(node) = parameter.declaration.to_node_from_root(&root) - && let Some(cpp_parameter) = cpp_parser::CppParam::cast(node) - { - parameter.type_of = - parameter_types.intern_spelling(&cpp_parameter.get_type_text()); - } - } - if !detail.parameter_facts.is_empty() { - fact.parameters = parameters.intern(detail.parameter_facts.to_vec()); - } - } - let parameter_type_ids: Vec<_> = declarations - .iter() - .flat_map(|fact| { - fact.detail - .as_deref() - .map(|detail| { - detail - .parameter_facts - .iter() - .map(|parameter| parameter.type_of) - }) - .into_iter() - .flatten() - }) - .collect(); + 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 parameter_types = built.types; + let parameter_type_ids: Vec<_> = + (0..parameter_types.len()).map(TypeId::from_index).collect(); let mut interner = PathInterner::new(cfg!(windows)); // **This file's compilation, not the project's** — see `CompilerConfig::for_file`. diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 450b3d44..df3e7fd6 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -92,6 +92,13 @@ 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, + pub parameters: crate::index::params::ParamsStore, + pub types: crate::index::types::TypeStore, +} + pub fn build_facts( scopes: &ScopeTree, preprocessing: &FilePreprocessing, @@ -102,9 +109,33 @@ 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) { +) -> BuiltFacts { let file = DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals); - file.build() + let (mut facts, guards) = file.build(); + let mut parameters = crate::index::params::ParamsStore::new(); + let mut types = crate::index::types::TypeStore::new(); + for fact in &mut facts { + let Some(detail) = fact.detail.as_mut() else { + continue; + }; + for parameter in &mut detail.parameter_facts { + if let Some(node) = parameter.declaration.to_node_from_root(root) + && let Some(cpp) = CppParam::cast(node) + { + parameter.type_of = types.intern_spelling(&cpp.get_type_text()); + } + } + if !detail.parameter_facts.is_empty() { + let facts = std::mem::take(&mut detail.parameter_facts); + fact.parameters = parameters.intern(facts.into_vec()); + } + } + BuiltFacts { + facts, + guards, + parameters, + types, + } } /// The type a variable-like declaration was written with, as it is spelled before the name. @@ -5933,13 +5964,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 @@ -6351,13 +6383,14 @@ int Box::Inner::deep = 0; 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 memory report's detail numbers are computed from the box, not from the struct's width.** A function's @@ -6489,7 +6522,7 @@ public: &errors, true, ) - .0, + .facts, errors, ) } diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index 009eadc9..7b7ee1c9 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -1026,13 +1026,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 facts = sema::declarations::build_facts( &scopes, &preprocess(source, tree.get_tokens()), &root, &[], true, - ); + ) + .facts; let fact = facts .iter() .find(|fact| fact.name == name) diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index e8c399bd..c09f20de 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -548,7 +548,7 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).0 + build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).facts } /// **The declaration's own node**, for a fact that names one — the syntax a rendering needs. @@ -1563,7 +1563,7 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - let (facts, _guards) = build_facts(&view.scopes, &preprocessing, &view.root, &errors, true); + let facts = build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).facts; outline_of(&facts) } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 27948094..ca6384db 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -530,7 +530,9 @@ default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of( the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser's `CppSyntaxId`), a `SyntaxResolver` for a parsed file and typed `resolve_parameter` / `resolve_initializer` / `resolve_requires`; the tests round-trip a parameter and a braced default -initializer without any text parse. `ParamsStore`/`ParamsId` now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes +initializer without any text parse. `build_facts` now returns `BuiltFacts { facts, guards, parameters, types }`: the builder lowers each `CppParam` type, +interns the parameter list and clears the build-time detail copy before the summary is filed. `ParamsStore`/`ParamsId` +now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes `parameters()`. `FileSummary` now carries the local `ParamsStore`; `DeclFact::parameters` is a local `ParamsId`, the index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from From b120481406c485d9e3ed42c1dbe4e76fd98a7dc2 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 14:22:57 +0800 Subject: [PATCH 038/102] refactor(signature): use the file's own tree instead of a synthetic fact parse When a declaration has no rendering, Session::signatures_at resolves its file through view_of_the_file, a full parse with the project's config. The fact-only branches that parsed parameter_list as void __hint(...) are removed; a file with no tree contributes no signature. --- .../src/index/project/macro_walk.rs | 13 ++++++ .../src/session/navigation.rs | 4 +- .../src/session/signature.rs | 43 +------------------ 3 files changed, 18 insertions(+), 42 deletions(-) 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 bccfc39d..4822c9ed 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -409,6 +409,19 @@ impl ProjectIndex { .map_or(&[], |candidate| summary.parameter_facts(candidate)) } + /// **The parameter facts of the declaration whose name starts at `offset`**, through its source summary. This is + /// what a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. + pub fn parameter_facts_at(&self, file: &Path, offset: usize) -> &[ParameterFact] { + let Some(summary) = self.summaries.get(&normalize(file)) else { + return &[]; + }; + summary + .declarations + .iter() + .find(|fact| fact.name_range.start_offset == offset) + .map_or(&[], |fact| summary.parameter_facts(fact)) + } + /// **The written type spelling of a fact**, from its handle when the store has one and from the transition /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so /// deleting the string field later does not require revisiting them. diff --git a/crates/cpp_code_analysis/src/session/navigation.rs b/crates/cpp_code_analysis/src/session/navigation.rs index 9be07d55..ce594861 100644 --- a/crates/cpp_code_analysis/src/session/navigation.rs +++ b/crates/cpp_code_analysis/src/session/navigation.rs @@ -469,7 +469,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/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index ba6dc488..c8f7393b 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -180,30 +180,8 @@ where // 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())); - } - } + // **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 @@ -243,23 +221,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; From 0f66a606f500121783ff77bed28eddfdcc41cd43 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 14:23:06 +0800 Subject: [PATCH 039/102] docs: record the signature tree fallback --- docs/type-system-redesign.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index ca6384db..65f2e34b 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -537,7 +537,8 @@ now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and expos index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally -maps a cooked fact with a different arena to the source summary's declaration by name range. `missing_include` and +maps a cooked fact with a different arena to the source summary's declaration by name range. A signature whose declaration has no rendering now falls back to `view_of_the_file`, i.e. a **full parse of that +file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From ed5c0865b977c455bfbf1191b6531219f163810b Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:05:45 +0800 Subject: [PATCH 040/102] refactor(params): delete the last parameter-list text parsers parameter_names_from_text, parameters_in_a_written_list and tidy_list_text are gone. Signatures build labels from CppParam via CppParam::one_line_text; argument_count and overload read CST parameter facts with a typed text walk only as the raw-fact fallback. All workspace tests and clippy pass. --- crates/cpp_code_analysis/src/cache/mod.rs | 2 +- .../cpp_code_analysis/src/sema/call_syntax.rs | 263 ++---------------- .../src/sema/check/argument_count.rs | 100 +++---- .../src/sema/check/missing_include.rs | 9 - .../src/sema/declarations.rs | 5 +- crates/cpp_code_analysis/src/sema/overload.rs | 63 +++-- .../src/session/signature.rs | 84 +++--- crates/cpp_code_analysis/tests/params.rs | 7 +- crates/cpp_parser/src/syntax/node/cpp/mod.rs | 6 + docs/type-system-redesign.md | 4 +- 10 files changed, 161 insertions(+), 382 deletions(-) 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/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index 411ac2cf..2f259592 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -15,10 +15,8 @@ //! arguments, a list with no parameter), and every caller turns that into its own kind of silence. 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}; @@ -70,54 +68,6 @@ pub(crate) fn parameter_names_of_facts( ) } -/// **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 remaining synthetic parser for parameter *spans*; its callers are being moved to `ParameterFact`, after -/// which it and `tidy_list_text` are deleted. -/// -/// 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('(') { - return None; - } - - 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) @@ -177,6 +127,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 @@ -190,116 +164,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. @@ -325,79 +190,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/argument_count.rs b/crates/cpp_code_analysis/src/sema/check/argument_count.rs index af554daf..f0b96ead 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -397,13 +397,15 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec let Some(parameters) = fact.parameter_list() else { continue; }; - let facts = context.index().parameter_facts_of(&file, fact); - let callee = if facts.is_empty() { - the_callee_in(parameters) + let indexed = context.index().parameter_facts_of(&file, fact); + let facts = if indexed.is_empty() { + fact.parameter_facts() } else { - the_callee_in_facts(facts, context.index().types(), parameters) + indexed }; - let Some(callee) = callee else { + let Some(callee) = the_callee_in_facts(facts, context.index().types(), parameters) + .or_else(|| the_callee_in_text(parameters)) + else { continue; }; // **The same signature declared twice is one candidate at the most permissive arity** — see @@ -413,6 +415,20 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec callees } +/// **The last-resort text candidate** for a fact whose parameter type handles are not in this index. This is a +/// top-level comma walk, not a parser; the indexed path above is the ordinary one. +fn the_callee_in_text(parameter_list: &str) -> Option { + let (spellings, variadic) = sema::overload::parameters_in(parameter_list); + let written = spellings.len(); + let required = written.saturating_sub(parameter_list.matches('=').count()); + Some(Callee { + required, + written, + variadic, + parameters: spellings, + }) +} + /// **One candidate out of the CST parameter facts.** Type spellings come from the type store; nothing is parsed. fn the_callee_in_facts( facts: &[crate::index::params::ParameterFact], @@ -451,60 +467,6 @@ fn the_callee_in_facts( }) } -/// **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)?; - - 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) { - variadic = true; - continue; - } - written += 1; - // A default is the `=` the declaration writes. - if !parameter.contains('=') { - 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)); - } - - // **`(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" { - written = 0; - required = 0; - spellings.clear(); - } - - Some(Callee { - required, - written, - variadic, - parameters: spellings, - }) -} - /// **The candidate to blame when none is viable**: the one whose arity is nearest the call's, so a message about a /// call that fits nothing can still say "too many" or "too few" about a real declaration. fn closest(candidates: &[Callee], passed: usize) -> Option<&Callee> { @@ -610,7 +572,7 @@ 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 (file, fact) in &own { if fact.name != access.member { continue; } @@ -621,7 +583,8 @@ fn judge_a_member_call( let Some(parameters) = fact.parameter_list() else { 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, context.index().types(), parameters) { members.push(callee); } } @@ -634,8 +597,19 @@ fn judge_a_member_call( .members .iter() .filter(|member| member.fact.name == access.member) - .filter_map(|member| member.fact.parameter_list()) - .filter_map(the_callee_in) + .filter_map(|member| { + let parameters = member.fact.parameter_list()?; + let indexed = context + .index() + .parameter_facts_of(&member.file, &member.fact); + let facts = if indexed.is_empty() { + member.fact.parameter_facts() + } else { + indexed + }; + the_callee_in_facts(facts, context.index().types(), parameters) + .or_else(|| the_callee_in_text(parameters)) + }) .collect(); } if members.is_empty() { 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 e9b9dce0..02e936d6 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -67,7 +67,6 @@ use crate::DeclFact; use crate::file; -use crate::sema::call_syntax::parameters_in_a_written_list; use std::path::Path; use super::{Check, CheckContext, DeclarationSource, DiagnosticCode}; @@ -318,21 +317,13 @@ pub(super) fn types_this_declaration_uses( if let Some(returns) = index.returns_spelling_of(fact) { spellings.push(returns.to_string()); } - let mut from_facts = 0usize; for parameter in index.parameter_facts_of(file, fact) { if let Some(spelling) = index.types().spelling(parameter.type_of) && !spelling.trim().is_empty() { spellings.push(spelling.to_string()); - from_facts += 1; } } - if from_facts == 0 - && let Some(parameters) = fact.parameter_list() - && let Some(parsed) = parameters_in_a_written_list(parameters) - { - spellings.extend(parsed.into_iter().map(|(_, text)| text)); - } spellings } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index df3e7fd6..08a881e5 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -126,8 +126,7 @@ pub fn build_facts( } } if !detail.parameter_facts.is_empty() { - let facts = std::mem::take(&mut detail.parameter_facts); - fact.parameters = parameters.intern(facts.into_vec()); + fact.parameters = parameters.intern(detail.parameter_facts.to_vec()); } } BuiltFacts { @@ -5186,7 +5185,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)), )); } diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 8e5149ab..d98d6697 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -598,7 +598,9 @@ pub fn defaults_in(parameter_list: &str) -> usize { let mut depth = 0i32; for character in parameter.trim().chars() { match character { - '<' | '(' | '[' => depth += 1, + '<' if inner[..].contains('>') => depth += 1, + '<' => {} + '(' | '[' => depth += 1, '>' | ')' | ']' => depth -= 1, _ if depth > 0 => continue, _ => {} @@ -714,37 +716,44 @@ pub fn parameters_in(parameter_list: &str) -> (Vec, bool) { 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); + // **No synthetic parameter-list parse.** This text path is only reached by a caller that has no `ParamsStore` + // entry; it splits at top-level commas, which is the old reader's rule. + variadic |= parameter_list.contains("..."); + let characters: Vec = inner.chars().collect(); + let closes_an_angle = |rest: &[char]| { + let mut depth = 0i32; + for character in rest { + match character { + '<' => depth += 1, + '>' if depth == 0 => return true, + '>' => depth -= 1, + _ => {} } } - 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); + false + }; + let mut at = 0usize; + while at < characters.len() { + let character = characters[at]; + match character { + // **A comparison is not a template bracket.** `bool ok = 1 < 2` has no closing `>`, so it must not + // raise the depth and swallow the parameters after its default. + '<' if closes_an_angle(&characters[at + 1..]) => depth += 1, + '<' => {} + '(' | '[' => depth += 1, + '>' | ')' | ']' => depth -= 1, + ',' if depth == 0 => { + take(¤t, &mut parameters, &mut variadic); + current.clear(); + at += 1; + continue; } - take(¤t, &mut parameters, &mut variadic); + _ => {} } + current.push(character); + at += 1; } + take(¤t, &mut parameters, &mut variadic); (parameters, variadic) } diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index c8f7393b..f13b478b 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -230,31 +230,27 @@ 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) + // **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(); + let written: Vec = 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, - ) + let mut text = parameter.text().to_string(); + text = text.split_whitespace().collect::>().join(" "); + text }) .collect(); + for (at, text) in written.iter().enumerate() { + if at > 0 { + label.push_str(", "); + } + let start = label.len(); + label.push_str(text); + parameters.push((start..label.len(), text.clone())); + } + label.push(')'); // The declaration's own parameter texts, names dropped, 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. @@ -564,20 +560,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; @@ -760,13 +742,35 @@ fn constructors_in_the_index( if scope.rsplit("::").next().map(str::trim) != Some(class) { continue; } - let Some(parameters) = declaration.fact.parameter_list() else { + let facts = index.parameter_facts_of(&declaration.file, &declaration.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() { + let Some(spelling) = index.types().spelling(parameter.type_of) 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; + } + label.push(')'); constructors.push(CallSignature { - parameters: parameters_from_a_written_list(&tidy, class.len()), + parameters, label, active_parameter: active, declared_in: declaration.file.clone(), diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs index cdc19e16..fc1fe3ef 100644 --- a/crates/cpp_code_analysis/tests/params.rs +++ b/crates/cpp_code_analysis/tests/params.rs @@ -5,7 +5,12 @@ use cpp_code_analysis::index::types::TypeStore; use cpp_code_analysis::sema::overload::parameters_in_facts; use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; -fn facts(source: &str) -> (cpp_parser::CppSyntaxTree, Vec) { +fn facts( + source: &str, +) -> ( + cpp_parser::CppSyntaxTree, + Vec, +) { let tree = CppParser::parse(source, ParserConfig::default()); let list = tree .get_red_root() diff --git a/crates/cpp_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 7024f96f..4406e5d5 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -1513,6 +1513,12 @@ impl CppParam { .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. pub fn get_name_text(&self) -> Option { self.get_name().map(|name| name.get_name_text().to_string()) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 65f2e34b..410a7de9 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -538,7 +538,9 @@ index builder interns each detail's facts, and `summary_codec` writes the table still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally maps a cooked fact with a different arena to the source summary's declaration by name range. A signature whose declaration has no rendering now falls back to `view_of_the_file`, i.e. a **full parse of that -file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. `missing_include` and +file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. The signature label is +built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_from_text`, +`parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 6539a90a33153b3b3c007d38070da4c700573554 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:06:32 +0800 Subject: [PATCH 041/102] docs(signature): describe the tree fallback after deleting the synthetic parse --- .../cpp_code_analysis/src/session/signature.rs | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index f13b478b..f721707d 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -165,21 +165,9 @@ 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. + // **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; From 65dee4184c9d92c1e129bfad065af8aec21a4503 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:19:11 +0800 Subject: [PATCH 042/102] refactor(constant): lex an expression instead of parsing a fragment value_of's token reader uses cpp_parser::lex with LexerConfig, so a constant expression is no longer parsed as a declaration with ParserConfig::default(). This is the first constant.rs step toward SyntaxId/typed evaluation. --- crates/cpp_code_analysis/src/sema/constant.rs | 23 ++++++++----------- docs/type-system-redesign.md | 3 ++- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/constant.rs b/crates/cpp_code_analysis/src/sema/constant.rs index e944431b..97aec3d4 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 @@ -265,18 +264,16 @@ fn join(tokens: &[(CppTokenKind, String)]) -> String { /// 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() } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 410a7de9..37907796 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -540,7 +540,8 @@ each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex: maps a cooked fact with a different arena to the source summary's declaration by name range. A signature whose declaration has no rendering now falls back to `view_of_the_file`, i.e. a **full parse of that file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. The signature label is built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_from_text`, -`parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `missing_include` and +`parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `constant.rs` now +lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 2d027e287bd7d14fa876fe5a187a23e8463c935d Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:27:45 +0800 Subject: [PATCH 043/102] refactor(constant): evaluate the CST's own tokens value_of_tokens is the evaluator's entry; enumerator initialisers and declarator initialisers pass their CST token slices directly. value_of remains the public spelling boundary using the lexer. The join helper is deleted. --- crates/cpp_code_analysis/src/sema/constant.rs | 38 +++++++++---------- docs/type-system-redesign.md | 4 +- 2 files changed, 22 insertions(+), 20 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/constant.rs b/crates/cpp_code_analysis/src/sema/constant.rs index 97aec3d4..0b173763 100644 --- a/crates/cpp_code_analysis/src/sema/constant.rs +++ b/crates/cpp_code_analysis/src/sema/constant.rs @@ -91,11 +91,22 @@ fn is_a_constant_declaration(declarator: &CppSyntaxNode) -> bool { .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 public boundary. The analysis path uses +/// [`value_of_tokens`] with the CST's own tokens; this is for callers that only hold a spelling (a macro body, or a +/// test). 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) } @@ -118,8 +129,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) })?; } @@ -145,7 +155,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) }) } @@ -215,13 +225,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, @@ -229,11 +239,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. @@ -253,14 +261,6 @@ 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)> { diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 37907796..f3f23f61 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -541,7 +541,9 @@ maps a cooked fact with a different arena to the source summary's declaration by file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. The signature label is built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_from_text`, `parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `constant.rs` now -lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`. `missing_include` and +lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`; +its internal evaluator takes the CST's own tokens through `value_of_tokens`, and only the public spelling boundary +calls the lexer. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From c215e35f4b4c773b950bf1c7162e7c526f77c473 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:31:52 +0800 Subject: [PATCH 044/102] refactor(constraint): read the requires condition from its node CppRequiresClause::get_condition_text is token-based and rejects a requires-expression. The overload filter casts the node and asks it directly instead of scanning declaration text for the keyword. --- .../src/index/project/queries.rs | 5 ++--- .../cpp_code_analysis/src/sema/constraint.rs | 6 ++++++ crates/cpp_parser/src/syntax/node/cpp/mod.rs | 21 +++++++++++++++++++ docs/type-system-redesign.md | 3 ++- 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 7209389a..8768bfcd 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -681,9 +681,8 @@ pub(crate) fn the_overload_a_call_names( // the text and needs no node. 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)); + .find_map(::cast) + .and_then(|clause| sema::constraint::a_requires_clause_node(&clause)); let condition_owned = requires_clause .as_deref() .map(str::to_string) diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index 4b7e3c8c..a662fe28 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -318,6 +318,12 @@ fn the_enable_if_argument(declaration: &str) -> Option<&str> { /// /// `None` when the node is a **requires-expression** (`requires { … }`), which asks whether statements compile rather than /// stating a condition this layer could decide. +/// **The condition a `CppRequiresClause` states**, read from its own tokens. This is the CST entry point; the text +/// form remains for callers that only hold a spelling. +pub fn a_requires_clause_node(clause: &cpp_parser::CppRequiresClause) -> Option { + clause.get_condition_text() +} + pub fn a_requires_clause(clause: &str) -> Option<&str> { let text = clause.trim_start(); let rest = text.strip_prefix("requires")?.trim_start(); diff --git a/crates/cpp_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 4406e5d5..4cc81143 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -1368,6 +1368,27 @@ impl CppRequiresClause { pub fn get_clause_text(&self) -> String { syntax::node::traits::subtree_text_spaced(self.syntax()) } + + /// **The condition the clause states**, without the `requires` keyword — `None` for a requires-expression + /// (`requires { … }`), which states no condition this layer can decide. Token-based, so a comment or a newline + /// between the keyword and the condition does not change the answer. + pub fn get_condition_text(&self) -> Option { + let mut tokens = self + .syntax() + .descendants_with_tokens() + .filter_map(|element| element.into_token()) + .filter(|token| !syntax::node::traits::is_trivia(token.kind().into())) + .map(|token| token.text().to_string()); + let keyword = tokens.next()?; + if keyword != "requires" { + return None; + } + let rest: Vec = tokens.collect(); + if rest.first().is_some_and(|token| token == "{") { + return None; + } + (!rest.is_empty()).then(|| rest.join(" ")) + } } /// An attribute list: `[[maybe_unused]]`, `[[nodiscard("why")]]`, `[[gnu::always_inline]]`. diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index f3f23f61..65c0c004 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -543,7 +543,8 @@ built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_ `parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `constant.rs` now lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`; its internal evaluator takes the CST's own tokens through `value_of_tokens`, and only the public spelling boundary -calls the lexer. `missing_include` and +calls the lexer. `CppRequiresClause::get_condition_text` exposes the clause condition token-by-token, and the overload +filter uses that typed accessor instead of stripping `requires` from the declaration text. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 21372db014eee3b908fd9c2b345d02be68512444 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 15:58:18 +0800 Subject: [PATCH 045/102] refactor(constraint): find enable_if through typed template arguments the_condition_of_node walks CppNameExpr and CppTemplateArgList instead of scanning declaration text. The text scanner the_condition_of/the_enable_if_argument is deleted; the evaluator test parses the declaration and uses the typed entry point. --- .../src/index/project/queries.rs | 2 +- .../cpp_code_analysis/src/sema/constraint.rs | 56 ++++++------------- crates/cpp_code_analysis/tests/suite/types.rs | 22 +++++--- docs/type-system-redesign.md | 4 +- 4 files changed, 35 insertions(+), 49 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 8768bfcd..687e2f8a 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -686,7 +686,7 @@ pub(crate) fn the_overload_a_call_names( let condition_owned = requires_clause .as_deref() .map(str::to_string) - .or_else(|| sema::constraint::the_condition_of(&declaration).map(str::to_string)); + .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. diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index a662fe28..bf2d1a06 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -265,44 +265,24 @@ pub fn satisfies(condition: &str, bindings: &[(String, String)]) -> Option 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. -/// -/// ```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 -/// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -/// ``` -/// -/// `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) -} - -/// 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()); - } - } - _ => {} - } - } - None +/// **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<…>`; no declaration text is scanned. +pub fn the_condition_of_node(declaration: &cpp_parser::CppSyntaxNode) -> Option { + use cpp_parser::CppAstNode; + let name = declaration.descendants().find_map(|node| { + let name = cpp_parser::CppNameExpr::cast(node)?; + name.get_qualified_name() + .contains("enable_if") + .then_some(name) + })?; + let list = name + .syntax() + .descendants() + .find_map(cpp_parser::CppTemplateArgList::cast)?; + let first = list.get_args().next()?; + let text = first.syntax().text().to_string(); + let text = text.trim(); + (!text.is_empty()).then(|| text.to_string()) } /// **The constraint a `RequiresClause` node states** — the node's own text without its keyword. diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index fc4aa55d..e70d41f7 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2746,30 +2746,34 @@ std::string f() { /// **The condition evaluator**, decision by decision — the module the `enable_if` overloads rest on. #[test] fn the_constraint_evaluator_decides_the_fundamental_traits() { - use cpp_code_analysis::sema::constraint::{satisfies, the_condition_of}; + use cpp_code_analysis::sema::constraint::{satisfies, the_condition_of_node}; let bind = |spelling: &str| vec![("T".to_string(), spelling.to_string())]; + let condition = |written: &str| { + let tree = cpp_parser::CppParser::parse(written, cpp_parser::ParserConfig::default()); + the_condition_of_node(&tree.get_red_root()) + }; // The two declarations of `describe`, verbatim. - let integral = the_condition_of( + let integral = 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!(satisfies(&integral, &bind("int")), Some(true)); + assert_eq!(satisfies(&integral, &bind("double")), Some(false)); assert_eq!( - satisfies(integral, &bind("std::string")), + satisfies(&integral, &bind("std::string")), Some(false), "a class is not integral" ); - let floating = the_condition_of( + let floating = 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("double")), Some(true)); + assert_eq!(satisfies(&floating, &bind("int")), Some(false)); // The three spellings of one answer. for spelling in [ @@ -2850,7 +2854,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!(satisfies("std::is_class_v", &bind("std::string")), None); assert_eq!( - the_condition_of("void plain(int value)"), + condition("void plain(int value)"), None, "an ordinary function carries no condition" ); diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 65c0c004..6d56aa3a 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -544,7 +544,9 @@ built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_ lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`; its internal evaluator takes the CST's own tokens through `value_of_tokens`, and only the public spelling boundary calls the lexer. `CppRequiresClause::get_condition_text` exposes the clause condition token-by-token, and the overload -filter uses that typed accessor instead of stripping `requires` from the declaration text. `missing_include` and +filter uses that typed accessor instead of stripping `requires` from the declaration text. `the_condition_of_node` +finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTemplateArg`; the old string scanner +`the_condition_of`/`the_enable_if_argument` is deleted. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 340c6d0509c9d36cbc82d10b457e694c5812507c Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 16:08:36 +0800 Subject: [PATCH 046/102] refactor(checks): read type spellings through the index Five checks ask ProjectIndex::type_spelling_of/returns_spelling_of instead of the DeclFact transition strings. This is the consumer-side half of removing the string fields. --- .../src/sema/check/abstract_class_instantiated.rs | 2 +- .../src/sema/check/assign_type_check.rs | 4 ++-- .../cpp_code_analysis/src/sema/check/missing_return.rs | 2 +- crates/cpp_code_analysis/src/sema/check/redefinition.rs | 2 +- crates/cpp_code_analysis/src/sema/check/unused.rs | 9 +++++---- docs/type-system-redesign.md | 4 +++- 6 files changed, 13 insertions(+), 10 deletions(-) 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..3e1e82e5 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,7 @@ 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 class = a_class_name(context.index().type_spelling_of(fact)?)?; Some((class, fact.name.to_string(), fact.name_range)) }) .collect(); 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..e85ff61c 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 @@ -104,7 +104,7 @@ impl Check for AssignTypeCheck { if fact.kind != DeclKind::Variable { continue; } - let Some(written) = fact.type_of.as_deref() else { + let Some(written) = context.index().type_spelling_of(fact) else { continue; }; let written = (!is_a_deduced_auto(written)).then_some(written); @@ -301,7 +301,7 @@ impl Check for AssignTypeCheck { .members .iter() .find(|found| found.fact.name.as_str() == name) - .and_then(|found| found.fact.type_of.as_deref()) + .and_then(|found| context.index().type_spelling_of(&found.fact)) else { continue; }; 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..843a9335 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_return.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_return.rs @@ -173,7 +173,7 @@ fn the_promise_of_a_name(context: &CheckContext<'_>, spelling: &str, depth: usiz if fact.kind != DeclKind::Type { return Promise::AValue; } - match fact.type_of.as_deref().map(str::trim) { + match context.index().type_spelling_of(fact).map(str::trim) { // A type declared through its own name (`class Widget;`) is an ordinary class. None | Some("") => Promise::AValue, Some("void") => Promise::Nothing, diff --git a/crates/cpp_code_analysis/src/sema/check/redefinition.rs b/crates/cpp_code_analysis/src/sema/check/redefinition.rs index 73c44bce..f5b2b064 100644 --- a/crates/cpp_code_analysis/src/sema/check/redefinition.rs +++ b/crates/cpp_code_analysis/src/sema/check/redefinition.rs @@ -162,7 +162,7 @@ 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(written) = context.index().returns_spelling_of(fact).map(str::trim) else { continue; }; match returns.get(fact.name.as_str()) { diff --git a/crates/cpp_code_analysis/src/sema/check/unused.rs b/crates/cpp_code_analysis/src/sema/check/unused.rs index e83a63f8..5d673d7c 100644 --- a/crates/cpp_code_analysis/src/sema/check/unused.rs +++ b/crates/cpp_code_analysis/src/sema/check/unused.rs @@ -74,9 +74,10 @@ 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() +fn its_type_cannot_have_a_destructor(context: &CheckContext<'_>, fact: &DeclFact) -> bool { + context + .index() + .type_spelling_of(fact) .is_some_and(undefined_name::is_a_builtin_spelling) } /// A name that is not worth asking about: a keyword-shaped spelling, or nothing at all. @@ -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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6d56aa3a..3fe663c7 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -546,7 +546,9 @@ its internal evaluator takes the CST's own tokens through `value_of_tokens`, and calls the lexer. `CppRequiresClause::get_condition_text` exposes the clause condition token-by-token, and the overload filter uses that typed accessor instead of stripping `requires` from the declaration text. `the_condition_of_node` finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTemplateArg`; the old string scanner -`the_condition_of`/`the_enable_if_argument` is deleted. `missing_include` and +`the_condition_of`/`the_enable_if_argument` is deleted. The check layer now reads `type_of`/`returns` through +`ProjectIndex::type_spelling_of`/`returns_spelling_of` in `abstract_class_instantiated`, `assign_type_check`, +`missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From d9d37ac8ba27fdf5ef86faeb258ba48633d34bd3 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 16:15:58 +0800 Subject: [PATCH 047/102] refactor(session): read fact types through the index Definition, completion, alias queries, semantic resolution and the sizeof/alias paths use ProjectIndex::type_spelling_of/returns_spelling_of rather than the DeclFact transition strings. This removes the session layer's direct dependence on the fields. --- crates/cpp_code_analysis/src/session/calls.rs | 24 ++++++++++++------- .../src/session/completion/request.rs | 6 ++++- .../src/session/definition.rs | 7 ++++-- .../cpp_code_analysis/src/session/queries.rs | 11 ++++++--- .../cpp_code_analysis/src/session/semantic.rs | 2 +- docs/type-system-redesign.md | 4 +++- 6 files changed, 38 insertions(+), 16 deletions(-) diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index c09f20de..a750875d 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -805,7 +805,7 @@ impl Session { if fact.kind != DeclKind::Variable || fact.modifiers.contains(DeclModifiers::STATIC) { continue; } - let Some(type_of) = fact.type_of.as_deref() else { + let Some(type_of) = self.store.index().type_spelling_of(fact) else { unknown.push(fact.name.to_string()); continue; }; @@ -985,7 +985,7 @@ impl Session { 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)?.trim(); if target.is_empty() || target == head.trim() { return None; } @@ -1175,7 +1175,11 @@ impl Session { && member.fact.name == spelled && member.fact.parameter_list().is_none() }) - && let Some(target) = alias.fact.type_of.clone() + && let Some(target) = self + .store + .index() + .type_spelling_of(&alias.fact) + .map(str::to_string) { return self.the_size_of_a_type_in(view, &target, depth + 1, instantiation); } @@ -1220,7 +1224,7 @@ 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() + && let Some(target) = self.store.index().type_spelling_of(&aliased.fact) && target != spelled && depth <= 8 { @@ -1255,9 +1259,13 @@ impl Session { let alias = list.members.iter().find(|candidate| { candidate.fact.name == member && candidate.fact.kind == DeclKind::Type - && candidate.fact.type_of.is_some() + && self + .store + .index() + .type_spelling_of(&candidate.fact) + .is_some() })?; - let written = alias.fact.type_of.as_deref()?; + let written = self.store.index().type_spelling_of(&alias.fact)?; let target = sema::types::substituted_spelling_with_defaults( written, alias.fact.parameters(), @@ -1314,7 +1322,7 @@ impl Session { }) else { return spelled; }; - match alias.fact.type_of.as_deref() { + match self.store.index().type_spelling_of(&alias.fact) { Some(target) => sema::types::substituted_spelling_with_defaults( target, environment.parameters, @@ -1334,7 +1342,7 @@ impl Session { path: &Path, ) -> Option { let known = self.store.index().definition(head, path).value()?; - let written = known.fact.type_of.as_deref()?; + let written = self.store.index().type_spelling_of(&known.fact)?; if known.fact.parameters().is_empty() { return None; } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 85a8ed76..02cdc28d 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -679,7 +679,11 @@ impl Session { .members .iter() .find(|member| member.fact.name == access.member) - && let Some(spelled) = member.fact.type_of.clone() + && let Some(spelled) = self + .store + .index() + .type_spelling_of(&member.fact) + .map(str::to_string) { return Known::Yes(ExpressionType { expression: written, diff --git a/crates/cpp_code_analysis/src/session/definition.rs b/crates/cpp_code_analysis/src/session/definition.rs index 53cf3f9d..f49946c9 100644 --- a/crates/cpp_code_analysis/src/session/definition.rs +++ b/crates/cpp_code_analysis/src/session/definition.rs @@ -146,7 +146,7 @@ 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(str::to_string), parameters, qualifiers, is_a_template, @@ -187,7 +187,10 @@ impl Session { qualified_name: format!("{class}::{}", member.fact.name), class: class.to_string(), name: member.fact.name.to_string(), - returns: member.fact.returns.as_deref().map(str::to_string), + returns: self + .index() + .returns_spelling_of(&member.fact) + .map(str::to_string), parameters, qualifiers, is_a_template: false, diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index 6fc5c333..d6bc7340 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -255,10 +255,15 @@ impl Session { return None; }; let alias = definitions.found.iter().find(|definition| { - definition.fact.kind == crate::DeclKind::Type && definition.fact.type_of.is_some() + definition.fact.kind == crate::DeclKind::Type + && self + .store + .index() + .type_spelling_of(&definition.fact) + .is_some() })?; - let target = alias.fact.type_of.as_deref()?; + let target = self.store.index().type_spelling_of(&alias.fact)?; let substituted = sema::types::substituted_spelling_with_defaults::< smol_str::SmolStr, smol_str::SmolStr, @@ -370,7 +375,7 @@ impl Session { let mut files = vec![found.file.clone()]; // `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() { + if let Some(target) = self.store.index().type_spelling_of(&found.fact) { 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(""); diff --git a/crates/cpp_code_analysis/src/session/semantic.rs b/crates/cpp_code_analysis/src/session/semantic.rs index 3866c52d..69f5ace4 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -1060,7 +1060,7 @@ fn denotes_a_function_pointer(index: &ProjectIndex, declaring: &Path, written: & if found.fact.kind != DeclKind::Type { return false; } - let Some(target) = found.fact.type_of.as_deref() else { + let Some(target) = index.type_spelling_of(&found.fact) else { return false; }; let target = target.to_string(); diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 3fe663c7..ff1af9ba 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -548,7 +548,9 @@ filter uses that typed accessor instead of stripping `requires` from the declara finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTemplateArg`; the old string scanner `the_condition_of`/`the_enable_if_argument` is deleted. The check layer now reads `type_of`/`returns` through `ProjectIndex::type_spelling_of`/`returns_spelling_of` in `abstract_class_instantiated`, `assign_type_check`, -`missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. `missing_include` and +`missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. +The session's definition, completion, queries, semantic alias walk and sizeof/alias path read the same helpers; the +remaining direct field readers are in the index's own alias/member machinery, `render`, and tests. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 3eb4e753d23d79cdcf1a84aafba54b56b3434bbf Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 16:32:17 +0800 Subject: [PATCH 048/102] refactor(index): read fact types through the spelling bridge Alias, member, deduction, substituted, completion and type_of paths use ProjectIndex::type_spelling_of/returns_spelling_of rather than the DeclFact transition strings. The build-time intern bridge and display/deduction boundaries remain. --- .../cpp_code_analysis/src/index/project/aliases.rs | 6 +++--- .../src/index/project/completions.rs | 2 +- .../src/index/project/deductions.rs | 13 +++++++++---- .../src/index/project/macro_walk.rs | 4 ++-- .../src/index/project/member_facts.rs | 7 ++++--- .../cpp_code_analysis/src/index/project/members.rs | 9 +++++---- .../src/index/project/substituted.rs | 9 +++++---- .../cpp_code_analysis/src/index/project/type_of.rs | 8 ++++---- docs/type-system-redesign.md | 3 ++- 9 files changed, 35 insertions(+), 26 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index 258b12dc..afc8235a 100644 --- a/crates/cpp_code_analysis/src/index/project/aliases.rs +++ b/crates/cpp_code_analysis/src/index/project/aliases.rs @@ -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; @@ -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. @@ -526,7 +526,7 @@ pub(crate) fn a_member_the_class_declares( a_pattern_matches(member.fact.pattern(), ¶meters, Some(&arguments)) }) .map(|member| member.fact.clone()) - .find(|fact| fact.type_of.is_some()) + .find(|fact| index.type_spelling_of(fact).is_some()) }) { return Some(found); } diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index 0375ba86..e3407245 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -872,7 +872,7 @@ pub(crate) fn names_in_a_scope_at( 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(target) = index.type_spelling_of(&alias.fact) { let mut candidates: Vec = Vec::new(); if let Some(scope) = alias.fact.scope.as_deref() { diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index c621372c..fb882a56 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -617,9 +617,10 @@ fn the_alternatives_a_visit_hands( .files_declaring(name, path) .into_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() }) - .and_then(|declared| declared.fact.type_of.as_deref().map(str::to_string)); + .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string)); match target { Some(target) if target != resolved => resolved = target, _ => break, @@ -808,7 +809,7 @@ fn the_member_a_lambdas_return_names( let member = listed.members.iter().find(|member| { member.fact.name == access.member && member.fact.kind == DeclKind::Variable })?; - let written = member.fact.type_of.clone()?.to_string(); + let written = index.type_spelling_of(&member.fact)?.to_string(); match &agreed { None => agreed = Some(written), Some(previous) if *previous == written => {} @@ -1521,7 +1522,11 @@ pub(crate) fn structured_binding_type( .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())) + .and_then(|member| { + index + .type_spelling_of(&member.fact) + .map(|target| target.to_string()) + }) }); Some(match element { 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 4822c9ed..424d51a1 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -3789,7 +3789,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() @@ -3807,7 +3807,7 @@ impl ProjectIndex { if alias.fact.kind != DeclKind::Type { return None; } - let target = parse_type_spelling(alias.fact.type_of.as_deref()?); + let target = parse_type_spelling(self.type_spelling_of(alias.fact)?); let class = target.class_name()?; let qualified = if class.contains("::") { 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..e9ac9704 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -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 { @@ -916,7 +917,7 @@ pub(crate) fn alias_target_of( 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()) + .then(|| index.type_spelling_of(&declaration.fact)) .flatten() .map(|target| target.to_string()) .map(|target| { @@ -1024,7 +1025,7 @@ pub(crate) fn through_a_namespace_alias( 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 { diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 22c9b822..eecf96d7 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -1496,7 +1496,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); @@ -1898,7 +1899,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).map(str::to_string) else { return Vec::new(); }; let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); @@ -1915,9 +1916,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).map(str::to_string) else { return Vec::new(); }; let substituted = diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 34599d53..5eac0bfd 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -178,9 +178,10 @@ pub fn substituted_members( .files_declaring(class, from) .into_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() }) - .and_then(|declared| declared.fact.type_of.clone())?; + .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string))?; split_template_arguments(&target) }) else { return Known::Yes(list); @@ -230,12 +231,12 @@ pub fn substituted_members( .iter() .filter(|member| member.depth == 0 && member.fact.kind == DeclKind::Type) { - let Some(target) = member.fact.type_of.clone() else { + let Some(target) = index.type_spelling_of(&member.fact).map(str::to_string) 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.as_ref() == member.fact.name.as_str() { + if target.as_str() == member.fact.name.as_str() { continue; } alias_names.push(member.fact.name.to_string()); 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 723c99eb..0718dfcb 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -446,7 +446,7 @@ pub(crate) fn type_of_expression_inner( .files_declaring(&format!("operator\"\"{suffix}"), path) .into_iter() .find(|declared| declared.fact.kind == DeclKind::Function) - && let Some(returns) = declared.fact.returns.as_deref() + && let Some(returns) = index.returns_spelling_of(declared.fact) && !returns.trim().is_empty() { return a_user_defined_literal_is(returns.to_string()); @@ -1607,12 +1607,12 @@ pub(crate) fn agreeing_type( // 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(), + _ => index.type_spelling_of(found.fact)?.to_string(), }; 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 index.type_spelling_of(first) == Some(type_of.as_str()) => {} Some((first, _)) if first.kind == DeclKind::Type && first.qualified_name() == type_of => {} Some(_) => return None, @@ -2665,7 +2665,7 @@ pub(crate) fn a_base_operators_return( name, None, ) - && let Some(target) = alias.type_of.clone() + && let Some(target) = index.type_spelling_of(&alias).map(str::to_string) { let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); return Some(format!("{substituted}{suffix}")); diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index ff1af9ba..335ec212 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -550,7 +550,8 @@ finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTe `ProjectIndex::type_spelling_of`/`returns_spelling_of` in `abstract_class_instantiated`, `assign_type_check`, `missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. The session's definition, completion, queries, semantic alias walk and sizeof/alias path read the same helpers; the -remaining direct field readers are in the index's own alias/member machinery, `render`, and tests. `missing_include` and +index's own alias, member, deduction, substituted and completion machinery now does the same. The remaining direct +field readers are the build-time intern bridge in `macro_walk`, `render`/`deduce`, and tests. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 4c8aed3409030b1709662f8647888d4c29631500 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 16:40:44 +0800 Subject: [PATCH 049/102] refactor(deduce): read auto from the index spelling deduced_type_of compares the index's spelling handles for returns/type_of instead of the transition strings. --- crates/cpp_code_analysis/src/sema/deduce.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/deduce.rs b/crates/cpp_code_analysis/src/sema/deduce.rs index 0a6cecd5..d137bf51 100644 --- a/crates/cpp_code_analysis/src/sema/deduce.rs +++ b/crates/cpp_code_analysis/src/sema/deduce.rs @@ -64,13 +64,13 @@ 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.returns_spelling_of(fact) == Some("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.type_spelling_of(fact) != Some("auto") { return Known::No; } From d03cb7f1a0bf049f09e3683369dcb39e9b52a3f1 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 16:47:16 +0800 Subject: [PATCH 050/102] refactor(render): take type spellings from the caller an_item_with/a_line_with accept type_of and returns resolvers; hover supplies ProjectIndex::type_spelling_of/returns_spelling_of. The old wrappers remain for tests until the fields are removed. --- crates/cpp_code_analysis/src/sema/render.rs | 71 ++++++++++++++++----- crates/cpp_ls/src/handlers/hover/mod.rs | 13 +++- docs/type-system-redesign.md | 4 +- 3 files changed, 70 insertions(+), 18 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index 7b7ee1c9..a0b94892 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -100,6 +100,24 @@ pub fn an_item( fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option, +) -> Vec { + an_item_with( + fact, + syntax, + value, + &|fact| fact.type_of.as_deref().map(str::to_string), + &|fact| fact.returns.as_deref().map(str::to_string), + ) +} + +/// **The renderer with its type spellings supplied by the caller.** A summary fact has `TypeId`s; 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 +148,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 } @@ -211,10 +229,28 @@ 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 { + a_line_with( + fact, + syntax, + value, + &|fact| fact.type_of.as_deref().map(str::to_string), + &|fact| fact.returns.as_deref().map(str::to_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 +271,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()) + } } } @@ -364,7 +402,7 @@ fn a_template_parameter(parameter: &CppTemplateParam) -> 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 +417,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 +527,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 +544,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 diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index e7c2b3f4..e8f7aacd 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -2302,7 +2302,18 @@ 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(str::to_string), + &|fact| { + session + .index() + .returns_spelling_of(fact) + .map(str::to_string) + }, + ); if !attributes.is_empty() { declaration.insert(0, attributes.join(" ")); } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 335ec212..91c5abdb 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -551,7 +551,9 @@ finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTe `missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. The session's definition, completion, queries, semantic alias walk and sizeof/alias path read the same helpers; the index's own alias, member, deduction, substituted and completion machinery now does the same. The remaining direct -field readers are the build-time intern bridge in `macro_walk`, `render`/`deduce`, and tests. `missing_include` and +field readers are the build-time intern bridge in `macro_walk`, the public `render::an_item`/`a_line` wrappers, and +tests. `render::an_item_with`/`a_line_with` take a type-spelling resolver and are what the hover uses; the wrappers +exist only until the fields are deleted. `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From 408030b0eeb58632d996553d46e229289fc5dfa5 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:10:21 +0800 Subject: [PATCH 051/102] refactor(facts): intern type handles in the builder build_facts fills type_of_id/returns_id from the CST-built spellings, so the index no longer needs its string-to-ID bridge. The codec keeps raw spellings until the fields are deleted (CODEC_VERSION 48). --- .../src/cache/summary_codec.rs | 2 +- .../src/index/project/macro_walk.rs | 26 +++++-------------- .../src/sema/declarations.rs | 10 +++++++ docs/type-system-redesign.md | 4 ++- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 73197280..07505d0d 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -304,7 +304,7 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.declarations.len() as u32); for fact in &summary.declarations { - put_declaration(&mut out, fact, true); + put_declaration(&mut out, fact, false); } put_u32(&mut out, summary.macros.len() as u32); 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 424d51a1..018b8c7e 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -426,16 +426,16 @@ impl ProjectIndex { /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so /// deleting the string field later does not require revisiting them. pub fn type_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { - fact.type_of_id() - .and_then(|id| self.types.spelling(id)) - .or(fact.type_of.as_deref()) + fact.type_of + .as_deref() + .or_else(|| fact.type_of_id().and_then(|id| self.types.spelling(id))) } /// The written return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. pub fn returns_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { - fact.returns_id() - .and_then(|id| self.types.spelling(id)) - .or(fact.returns.as_deref()) + fact.returns + .as_deref() + .or_else(|| fact.returns_id().and_then(|id| self.types.spelling(id))) } /// **The computation-side type of a declaration's `type_of`**, when the fact has a storage handle. This is the @@ -473,20 +473,6 @@ impl ProjectIndex { } } } - for fact in &mut summary.declarations { - if fact.type_of_id.is_none() - && let Some(type_of) = fact.type_of.as_deref() - && !type_of.trim().is_empty() - { - fact.type_of_id = self.types.intern_spelling(type_of); - } - if fact.returns_id.is_none() - && let Some(returns) = fact.returns.as_deref() - && !returns.trim().is_empty() - { - fact.returns_id = self.types.intern_spelling(returns); - } - } let ids: Vec<_> = summary .declarations .iter() diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 08a881e5..eb1c79b3 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -115,6 +115,16 @@ pub fn build_facts( let mut parameters = crate::index::params::ParamsStore::new(); let mut types = crate::index::types::TypeStore::new(); for fact in &mut facts { + if let Some(type_of) = fact.type_of.as_deref() + && !type_of.trim().is_empty() + { + fact.type_of_id = types.intern_spelling(type_of); + } + if let Some(returns) = fact.returns.as_deref() + && !returns.trim().is_empty() + { + fact.returns_id = types.intern_spelling(returns); + } let Some(detail) = fact.detail.as_mut() else { continue; }; diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 91c5abdb..1d83cbbb 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -553,7 +553,9 @@ The session's definition, completion, queries, semantic alias walk and sizeof/al index's own alias, member, deduction, substituted and completion machinery now does the same. The remaining direct field readers are the build-time intern bridge in `macro_walk`, the public `render::an_item`/`a_line` wrappers, and tests. `render::an_item_with`/`a_line_with` take a type-spelling resolver and are what the hover uses; the wrappers -exist only until the fields are deleted. `missing_include` and +exist only until the fields are deleted. `build_facts` now interns every fact's `type_of`/`returns` into its +`BuiltFacts` type store, so `ProjectIndex::insert_at` no longer has a string-to-ID bridge in `macro_walk`; the codec +writes raw spellings until the fields are deleted (CODEC_VERSION 48). `missing_include` and `unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. From a25f595821c56ae00f0b88ab92a9600dec8c69ba Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:14:08 +0800 Subject: [PATCH 052/102] refactor(render): remove the an_item test wrapper an_item now always takes the caller's type resolvers; a_line remains as the one transition wrapper for cpp_ls's list formatter. --- crates/cpp_code_analysis/src/sema/render.rs | 23 +++++++-------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index a0b94892..ac97484e 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -96,20 +96,6 @@ 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( - fact: &DeclFact, - syntax: Option<&CppDeclaration>, - value: Option, -) -> Vec { - an_item_with( - fact, - syntax, - value, - &|fact| fact.type_of.as_deref().map(str::to_string), - &|fact| fact.returns.as_deref().map(str::to_string), - ) -} - /// **The renderer with its type spellings supplied by the caller.** A summary fact has `TypeId`s; 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( @@ -228,6 +214,7 @@ fn without_comments(text: &str) -> String { } /// **The declaration's own line**, without a template head — what an overload list prints per declaration. +/// Transition wrapper for callers without a `TypeStore`; remove with the string fields. pub fn a_line(fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option) -> String { a_line_with( fact, @@ -1081,7 +1068,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| fact.type_of.as_deref().map(str::to_string), + &|fact| fact.returns.as_deref().map(str::to_string), + ) } /// **A function is rebuilt**, not quoted: canonical types, the parameters' names kept, defaults said, and the From a69b1c36ca8d9c28f4ce4e18af35224b6c2f80a4 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:26:07 +0800 Subject: [PATCH 053/102] refactor(substituted): rebuild member facts instead of mutating them Template substitution no longer mutates a fact that belongs to a summary. Each member is cloned, rewritten and stored back as a fresh DeclFact, which is the shape needed to give generated facts their own TypeStore. --- .../src/index/project/substituted.rs | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 5eac0bfd..d4b8fc7e 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -286,45 +286,45 @@ pub fn substituted_members( } spelling }; - for member in list - .members - .iter_mut() - .filter(|member| !declares_an_alias(member)) - { + // **Never mutate a fact that already belongs to a summary.** A member list is a view: two instantiations of one + // class template ask for different substitutions of the same declarations. Each member is rebuilt into a fresh + // `DeclFact`, and the list stores the rebuilt value. The mutation is confined to the new value, which is what the + // eventual `TypeId` construction needs. + for member in &mut list.members { + if declares_an_alias(member) { + continue; + } + let mut fact = member.fact.clone(); if !alias_names.is_empty() { - if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { + if let Some(spelling) = fact.detail_mut().parameter_list.as_mut() { *spelling = through_the_aliases(spelling).into(); } - if let Some(spelling) = member.fact.returns.as_mut() { + if let Some(spelling) = fact.returns.as_mut() { + *spelling = through_the_aliases(spelling).into(); + } + if let Some(spelling) = fact.type_of.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() { + if let Some(spelling) = 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() { + if let Some(spelling) = 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() { + if let Some(spelling) = fact.type_of.as_mut() { *spelling = sema::types::substituted_spelling_with_defaults( spelling, &names, &defaults, &arguments, ) .into(); } + member.fact = fact; } Known::Yes(list) } From 912959d965501ec1ea7dd85b262686915350d021 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:37:19 +0800 Subject: [PATCH 054/102] Revert "refactor(substituted): rebuild member facts instead of mutating them" This reverts commit a69b1c36ca8d9c28f4ce4e18af35224b6c2f80a4. --- .../src/index/project/substituted.rs | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index d4b8fc7e..5eac0bfd 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -286,45 +286,45 @@ pub fn substituted_members( } spelling }; - // **Never mutate a fact that already belongs to a summary.** A member list is a view: two instantiations of one - // class template ask for different substitutions of the same declarations. Each member is rebuilt into a fresh - // `DeclFact`, and the list stores the rebuilt value. The mutation is confined to the new value, which is what the - // eventual `TypeId` construction needs. - for member in &mut list.members { - if declares_an_alias(member) { - continue; - } - let mut fact = member.fact.clone(); + for member in list + .members + .iter_mut() + .filter(|member| !declares_an_alias(member)) + { if !alias_names.is_empty() { - if let Some(spelling) = fact.detail_mut().parameter_list.as_mut() { + if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { *spelling = through_the_aliases(spelling).into(); } - if let Some(spelling) = fact.returns.as_mut() { - *spelling = through_the_aliases(spelling).into(); - } - if let Some(spelling) = fact.type_of.as_mut() { + if let Some(spelling) = member.fact.returns.as_mut() { *spelling = through_the_aliases(spelling).into(); } } - if let Some(spelling) = fact.detail_mut().parameter_list.as_mut() { + // **`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) = fact.returns.as_mut() { + 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) = fact.type_of.as_mut() { + if let Some(spelling) = member.fact.type_of.as_mut() { *spelling = sema::types::substituted_spelling_with_defaults( spelling, &names, &defaults, &arguments, ) .into(); } - member.fact = fact; } Known::Yes(list) } From 09e818f5feb6efba3cc979f1a1e3ad1668554689 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:48:50 +0800 Subject: [PATCH 055/102] docs: separate the index cache from the computation layer Records the corrected ownership rule: one global TypeStore; SemanticModel owns per-request substitution/materialization caches; substitutions are per-member, never written into DeclFact; computation consumes ComputedType. --- docs/type-system-redesign.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 1d83cbbb..0f95fe76 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -587,3 +587,30 @@ The following pieces are **not** the target and will be removed: * all synthetic parameter/constant/constraint parsing. No new code may build on those fields or functions. The next commit starts Phase 0/1 from the model above. + + +## Cache layer versus computation layer (the corrected boundary) + +The index/cache layer is the only owner of stored identities: `DeclFact`, +`TypeId`, `ParamsId`, and the project-wide `TypeStore`. A `TypeId` is valid only +inside the store that issued it, so there is exactly one store for stored facts. +Creating a second, local `TypeStore` for a substituted member is forbidden: its +`TypeId(3)` would silently alias the global `TypeId(3)`. + +`SemanticModel` is the computation layer's per-request home. It already owns +`computed: RefCell>` and the member-list cache; a +substitution cache belongs there too, because the model is discarded after one +file's request. The index must not cache substituted member lists or +substitution results. + +A template substitution is a property of **one member in one instantiation**, +not of the class list: base walks merge members with different substitutions +(`Base::value` and `Base::value` can be in one list). It is carried +per `ProjectMember` as a substitution context alongside the immutable +`DeclFact`, or materialized by `SemanticModel` into a resolved row. It is never +written back into the fact, and no new `DeclFact` is constructed for it. + +The computation layer consumes materialized `ComputedType`s. Converting a +`TypeId` to a string and parsing that string again is a bug in the boundary, not +a shortcut: the string exists only at the display/API edge (`hover`, +completion labels, diagnostics messages). From 2c8d9c13f0719a344c3c8fc44da62d3fbd65d8d7 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 17:56:14 +0800 Subject: [PATCH 056/102] refactor(model): keep member-list caching on the computation side SemanticModel::members_of asks members_of_inner directly instead of the index's cached members_of_with. The request owns the memo; the index cache stays for direct index callers. --- crates/cpp_code_analysis/src/sema/model.rs | 5 ++++- docs/type-system-redesign.md | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index fd8fd8b2..e0fd69ca 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -183,7 +183,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, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 0f95fe76..96a16114 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -601,7 +601,10 @@ Creating a second, local `TypeStore` for a substituted member is forbidden: its `computed: RefCell>` and the member-list cache; a substitution cache belongs there too, because the model is discarded after one file's request. The index must not cache substituted member lists or -substitution results. +substitution results. `SemanticModel::members_of` now calls +`project::members_of_inner` directly, so the model's `members` memo is the only +cache on that path; the index's project-wide `member_lists` remains for callers +that ask the index itself. A template substitution is a property of **one member in one instantiation**, not of the class list: base walks merge members with different substitutions From 7e0013d38aed1df7636fd3eb4c2762031fcd598b Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 19:12:31 +0800 Subject: [PATCH 057/102] feat(types): substitute a ComputedType without the store ComputedType::substituted applies template bindings recursively (named arguments, pointer/reference/array/function/qualified/pack) without interning a TypeId or parsing a spelling. This is the computation-side primitive the per-member substitution view needs. --- .../src/index/types/compute.rs | 64 +++++++++++++++++++ docs/type-system-redesign.md | 4 +- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 9e39c01b..e4599128 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -163,6 +163,54 @@ impl ComputedType { } } } + + /// **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(&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::Builtin(_) | ComputedType::Auto | ComputedType::DecltypeAuto => { + self.clone() + } + ComputedType::Named(named) => ComputedType::named( + named.name.clone(), + named + .arguments + .iter() + .map(|argument| argument.substituted(bindings)) + .collect(), + ), + ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.substituted(bindings))), + ComputedType::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(to.substituted(bindings)), + rvalue: *rvalue, + }, + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(of.substituted(bindings)), + extent: *extent, + }, + ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(function.returns.substituted(bindings)), + parameters: function + .parameters + .iter() + .map(|parameter| parameter.substituted(bindings)) + .collect(), + })), + ComputedType::Pack(of) => ComputedType::Pack(Arc::new(of.substituted(bindings))), + ComputedType::Qualified(qualified) => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(qualified.of.substituted(bindings)), + is_const: qualified.is_const, + is_volatile: qualified.is_volatile, + })) + } + } + } } impl fmt::Display for ComputedType { @@ -269,4 +317,20 @@ mod tests { assert_eq!(value.arguments().len(), 1); assert_eq!(value.arguments()[0].to_string(), "int"); } + + #[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(&[( + SmolStr::new("T"), + ComputedType::Builtin(SmolStr::new("int")), + )]); + assert_eq!(concretely.to_string(), "std::pair"); + } } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 96a16114..160fa007 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -616,4 +616,6 @@ written back into the fact, and no new `DeclFact` is constructed for it. The computation layer consumes materialized `ComputedType`s. Converting a `TypeId` to a string and parsing that string again is a bug in the boundary, not a shortcut: the string exists only at the display/API edge (`hover`, -completion labels, diagnostics messages). +completion labels, diagnostics messages). `ComputedType::substituted` applies +template bindings recursively without interning a `TypeId` or parsing a +spelling; the per-member substitution view is built on that operation. From 48143e6644f3940cfdd24a51cc6e36e4ec65fbd9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 19:28:19 +0800 Subject: [PATCH 058/102] feat(types): convert a semantic Type to ComputedType structurally From<&Type> for ComputedType maps every variant without a store lookup or spelling parse. This is the input conversion the ComputedType-based members_of API needs. --- .../src/index/types/compute.rs | 52 +++++++++++++++++++ docs/type-system-redesign.md | 3 ++ 2 files changed, 55 insertions(+) diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index e4599128..1b62cdc0 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -213,6 +213,45 @@ impl ComputedType { } } +impl From<&Type> for ComputedType { + /// **The computation-layer form of a semantic `Type`.** No store lookup and no spelling parse: every variant is + /// converted from the structure the query already holds. + fn from(value: &Type) -> ComputedType { + match value { + Type::Builtin { spelling } => ComputedType::Builtin(spelling.into()), + Type::Named { name, arguments } => ComputedType::named( + name.as_str(), + arguments.iter().map(ComputedType::from).collect(), + ), + Type::TemplateParameter { name } => ComputedType::TemplateParameter(name.into()), + Type::Pointer { to } => ComputedType::Pointer(Arc::new(ComputedType::from(&**to))), + Type::Reference { to, rvalue } => ComputedType::Reference { + to: Arc::new(ComputedType::from(&**to)), + rvalue: *rvalue, + }, + Type::Array { of, extent } => ComputedType::Array { + of: Arc::new(ComputedType::from(&**of)), + extent: extent.map(|extent| extent as u64), + }, + Type::Function { + returns, + parameters, + } => ComputedType::Function(Arc::new(FunctionType { + returns: Arc::new(ComputedType::from(&**returns)), + parameters: parameters.iter().map(ComputedType::from).collect(), + })), + Type::Pack { of } => ComputedType::Pack(Arc::new(ComputedType::from(&**of))), + Type::Qualified { of, qualifiers } => { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(ComputedType::from(&**of)), + is_const: qualifiers.is_const(), + is_volatile: qualifiers.is_volatile(), + })) + } + } + } +} + impl fmt::Display for ComputedType { fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -318,6 +357,19 @@ mod tests { assert_eq!(value.arguments()[0].to_string(), "int"); } + #[test] + fn a_semantic_type_converts_without_the_store() { + let value = Type::Named { + name: "std::vector".to_string(), + arguments: vec![Type::Pointer { + to: Arc::new(Type::Builtin { + spelling: "int".to_string(), + }), + }], + }; + assert_eq!(ComputedType::from(&value).to_string(), "std::vector"); + } + #[test] fn a_computed_type_substitutes_without_the_store() { let value = ComputedType::named( diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 160fa007..05f58037 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -619,3 +619,6 @@ a shortcut: the string exists only at the display/API edge (`hover`, completion labels, diagnostics messages). `ComputedType::substituted` applies template bindings recursively without interning a `TypeId` or parsing a spelling; the per-member substitution view is built on that operation. +`ComputedType::from(&Type)` is the same boundary in the other direction: the +semantic `Type` a query already holds becomes a `ComputedType` structurally, so +the member query can take `ComputedType` rather than re-parsing a spelling. From 75afab67d59f1cfb65f70d8db907736d737c6815 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 19:36:21 +0800 Subject: [PATCH 059/102] feat(model): add the ComputedType members entry point members_of_computed takes the type structure; param_type_check converts its Type without stringifying it first. The index still resolves the written class, so this is the first caller of the transition API, not the end state. --- .../cpp_code_analysis/src/sema/check/param_type_check.rs | 5 ++++- crates/cpp_code_analysis/src/sema/model.rs | 7 +++++++ docs/type-system-redesign.md | 2 ++ 3 files changed, 13 insertions(+), 1 deletion(-) 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..56182535 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 @@ -196,7 +196,10 @@ fn member_parameter_lists( 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(&crate::index::types::ComputedType::from(&a_type)) + else { return Vec::new(); }; list.members diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index e0fd69ca..ce7f2a97 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -165,6 +165,13 @@ impl<'a> SemanticModel<'a> { Some(found) } + /// **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 { + self.members_of(&class.to_string()) + } + /// **The members of a class, inherited ones included** — see [`project::members_of`]. /// pub fn members_of(&self, class: &str) -> Known { diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 05f58037..106ca528 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -622,3 +622,5 @@ spelling; the per-member substitution view is built on that operation. `ComputedType::from(&Type)` is the same boundary in the other direction: the semantic `Type` a query already holds becomes a `ComputedType` structurally, so the member query can take `ComputedType` rather than re-parsing a spelling. +`SemanticModel::members_of_computed` is that computation-side entry point; the +first caller is `param_type_check`. From 04eef8dc60b8beec4ee51d0835a29ca23e2d3c7e Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 19:38:24 +0800 Subject: [PATCH 060/102] feat(model): cache computed member answers by ComputedType members_of_computed keeps its own request-scoped HashMap keyed by the computed type, separate from the string-keyed members memo. This is the computation-side memo the index does not own. --- crates/cpp_code_analysis/src/sema/model.rs | 15 +++++++++++++-- docs/type-system-redesign.md | 4 +++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index ce7f2a97..d30dae03 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -47,7 +47,7 @@ use crate::FileView; 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; @@ -82,6 +82,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 @@ -116,6 +119,7 @@ impl<'a> SemanticModel<'a> { types: project::TypeMemo::default(), computed: RefCell::new(BTreeMap::new()), members: RefCell::new(BTreeMap::new()), + computed_members: RefCell::new(HashMap::new()), shapes: sema::declarations::ShapeTable::new(), } } @@ -169,7 +173,14 @@ impl<'a> SemanticModel<'a> { /// 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 { - self.members_of(&class.to_string()) + if let Some(answer) = self.computed_members.borrow().get(class) { + return answer.clone(); + } + let answer = self.members_of_uncached(&class.to_string()); + self.computed_members + .borrow_mut() + .insert(class.clone(), answer.clone()); + answer } /// **The members of a class, inherited ones included** — see [`project::members_of`]. diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 106ca528..6ef52d8b 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -623,4 +623,6 @@ spelling; the per-member substitution view is built on that operation. semantic `Type` a query already holds becomes a `ComputedType` structurally, so the member query can take `ComputedType` rather than re-parsing a spelling. `SemanticModel::members_of_computed` is that computation-side entry point; the -first caller is `param_type_check`. +first caller is `param_type_check`. Its answers are memoised in +`computed_members: HashMap`, so a computed-type query does not +stringify the class to consult the cache. From d5b3248df1827540acd56a3039619659b31175b0 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:07:02 +0800 Subject: [PATCH 061/102] refactor(members): substitute from ComputedType arguments substituted_members_for takes the class and arguments from ComputedType; SemanticModel's computed path uses it instead of parsing a class spelling. The old &str entry remains for index callers. --- .../src/index/project/substituted.rs | 54 ++++++++++++++----- crates/cpp_code_analysis/src/sema/model.rs | 10 +++- docs/type-system-redesign.md | 4 +- 3 files changed, 54 insertions(+), 14 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 5eac0bfd..e828699f 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -8,6 +8,7 @@ use crate::DeclKind; use crate::FileView; use crate::ScopeTree; use crate::index; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppDeclaration; use cpp_parser::CppReturnStat; @@ -163,6 +164,30 @@ pub fn substituted_members( from: &Path, class: &str, listed: Known, +) -> Known { + substituted_members_with(index, from, class, 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), listed) +} + +fn substituted_members_with( + index: &ProjectIndex, + from: &Path, + class: &str, + prepared_arguments: Option<&[String]>, + listed: Known, ) -> Known { let Known::Yes(mut list) = listed else { return listed; @@ -173,18 +198,23 @@ 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 - && index.type_spelling_of(declared.fact).is_some() - }) - .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string))?; - 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(|| { + let target = index + .files_declaring(class, from) + .into_iter() + .find(|declared| { + declared.fact.kind == DeclKind::Type + && index.type_spelling_of(declared.fact).is_some() + }) + .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string))?; + split_template_arguments(&target) + }) else { + return Known::Yes(list); + }; + (base, arguments) }; let Some(declared) = index .files_declaring(&base, from) diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index d30dae03..f7052314 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -176,7 +176,15 @@ impl<'a> SemanticModel<'a> { if let Some(answer) = self.computed_members.borrow().get(class) { return answer.clone(); } - let answer = self.members_of_uncached(&class.to_string()); + 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()); diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6ef52d8b..993ed62d 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -625,4 +625,6 @@ the member query can take `ComputedType` rather than re-parsing a spelling. `SemanticModel::members_of_computed` is that computation-side entry point; the first caller is `param_type_check`. Its answers are memoised in `computed_members: HashMap`, so a computed-type query does not -stringify the class to consult the cache. +stringify the class to consult the cache. On a miss it calls +`substituted_members_for`, which takes the class name and arguments from +`ComputedType` directly instead of splitting a class spelling. From 277f23db4ec51d635c7e96f04ced4af49758b1ff Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:14:45 +0800 Subject: [PATCH 062/102] refactor(substituted): build a fresh member view and clear stale type ids The index's cached member list is no longer rewritten. Each substituted member is a cloned DeclFact; a rewritten type/return clears its spelling-derived TypeId, so no local store and no cross-store id alias is possible. The computed path uses prepared arguments. --- .../src/index/project/substituted.rs | 65 ++++++++++++------- docs/type-system-redesign.md | 11 ++-- 2 files changed, 48 insertions(+), 28 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index e828699f..5044c5e1 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -8,7 +8,7 @@ use crate::DeclKind; use crate::FileView; use crate::ScopeTree; use crate::index; -use crate::index::types::ComputedType; +use crate::index::types::{ComputedType, TypeId}; use crate::sema; use cpp_parser::CppDeclaration; use cpp_parser::CppReturnStat; @@ -316,45 +316,62 @@ fn substituted_members_with( } spelling }; - for member in list - .members - .iter_mut() - .filter(|member| !declares_an_alias(member)) - { + // **The input list belongs to the index; the substituted list is a fresh view.** Each member's fact is cloned, + // rewritten, and any spelling-derived `TypeId` is cleared: the stored handle describes the *unsubstituted* + // spelling and would lie if it travelled with the rewritten one. No second `TypeStore` is created. + for member in list.members.iter_mut() { + if declares_an_alias(member) { + continue; + } + let mut fact = member.fact.clone(); if !alias_names.is_empty() { - if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { + if let Some(spelling) = 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(); + if let Some(spelling) = fact.returns.as_mut() { + let next = through_the_aliases(spelling); + if next.as_str() != spelling.as_ref() { + *spelling = next.into(); + fact.returns_id = TypeId::NONE; + } + } + if let Some(spelling) = fact.type_of.as_mut() { + let next = through_the_aliases(spelling); + if next.as_str() != spelling.as_ref() { + *spelling = next.into(); + fact.type_of_id = TypeId::NONE; + } } } - // **`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(); - } + member.fact = fact; } for member in &mut list.members { - if let Some(spelling) = member.fact.detail_mut().parameter_list.as_mut() { + let mut fact = member.fact.clone(); + if let Some(spelling) = 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( + if let Some(spelling) = fact.returns.as_mut() { + let next = sema::types::substituted_spelling_with_defaults( spelling, &names, &defaults, &arguments, - ) - .into(); + ); + if next.as_str() != spelling.as_ref() { + *spelling = next.into(); + fact.returns_id = TypeId::NONE; + } } - if let Some(spelling) = member.fact.type_of.as_mut() { - *spelling = sema::types::substituted_spelling_with_defaults( + if let Some(spelling) = fact.type_of.as_mut() { + let next = sema::types::substituted_spelling_with_defaults( spelling, &names, &defaults, &arguments, - ) - .into(); + ); + if next.as_str() != spelling.as_ref() { + *spelling = next.into(); + fact.type_of_id = TypeId::NONE; + } } + member.fact = fact; } Known::Yes(list) } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 993ed62d..3472720b 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -608,10 +608,13 @@ that ask the index itself. A template substitution is a property of **one member in one instantiation**, not of the class list: base walks merge members with different substitutions -(`Base::value` and `Base::value` can be in one list). It is carried -per `ProjectMember` as a substitution context alongside the immutable -`DeclFact`, or materialized by `SemanticModel` into a resolved row. It is never -written back into the fact, and no new `DeclFact` is constructed for it. +(`Base::value` and `Base::value` can be in one list). The index's +cached list is never rewritten. `substituted_members` now builds a fresh view +for the request: each member's fact is cloned, its spellings are substituted, +and the spelling-derived `TypeId`s are cleared because they describe the +unsubstituted spelling. No second `TypeStore` is created, so no `TypeId` can +alias another store's entry; the resolved values are display/transition data +until `SemanticModel` materializes `ComputedType`. The computation layer consumes materialized `ComputedType`s. Converting a `TypeId` to a string and parsing that string again is a bug in the boundary, not From 140cc4dc3517763b03e792278ac2b61035957bc6 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:25:29 +0800 Subject: [PATCH 063/102] feat(members): attach a per-member substitution context ProjectMember carries MemberSubstitution bindings (parameter names to ComputedType arguments). substituted_members_for fills it on the computed path; the cloned spelling view remains for existing readers until they migrate. --- .../src/index/project/macro_environment.rs | 12 +++++++++- .../src/index/project/members.rs | 2 ++ .../src/index/project/substituted.rs | 22 +++++++++++++++++-- crates/cpp_code_analysis/src/session/calls.rs | 1 + docs/type-system-redesign.md | 4 +++- 5 files changed, 37 insertions(+), 4 deletions(-) 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 6a503283..ba4c3035 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -7,8 +7,9 @@ use crate::Binding; use crate::BindingKind; use crate::DeclKind; use crate::DeclModifiers; -use crate::index::types::TypeId; +use crate::index::types::{ComputedType, TypeId}; use smol_str::SmolStr; +use std::sync::Arc; use super::*; @@ -436,7 +437,10 @@ impl MemberList { #[derive(Debug, Clone, PartialEq, Eq)] pub struct ProjectMember { pub file: PathBuf, + /// The declaration as the index stores it. Substitution is **not** written into it. pub fact: DeclFact, + /// The per-member instantiation context, when this row is a substituted view. + 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 @@ -455,6 +459,12 @@ pub struct ProjectMember { pub ambiguous: bool, } +/// **One member's instantiation context**: the class template's parameters paired with this use's arguments. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MemberSubstitution { + pub bindings: Vec<(SmolStr, ComputedType)>, +} + /// A base whose members are not in the list, and why. #[derive(Debug, Clone, PartialEq, Eq)] pub struct UnlistedBase { diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index eecf96d7..e3b09320 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -1370,6 +1370,7 @@ pub(crate) fn members_of_inner( .map(|(file, fact)| ProjectMember { file, fact, + substitution: None, declared_in: class.to_string(), depth: 0, ambiguous: false, @@ -1549,6 +1550,7 @@ pub(crate) fn members_of_inner( .map(|(file, fact)| ProjectMember { file, fact, + substitution: None, declared_in: shown.clone(), depth, ambiguous: false, diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 5044c5e1..3f014e52 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -14,6 +14,7 @@ use cpp_parser::CppDeclaration; use cpp_parser::CppReturnStat; use cpp_parser::CppSyntaxNode; use cpp_parser::token_at; +use std::sync::Arc; /// **What a template-id's own arguments do to the type its declaration wrote.** /// @@ -165,7 +166,7 @@ pub fn substituted_members( class: &str, listed: Known, ) -> Known { - substituted_members_with(index, from, class, None, listed) + 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. @@ -179,7 +180,7 @@ pub(crate) fn substituted_members_for( return listed; }; let arguments: Vec = class.arguments().iter().map(ToString::to_string).collect(); - substituted_members_with(index, from, base, Some(&arguments), listed) + substituted_members_with(index, from, base, Some(&arguments), Some(class), listed) } fn substituted_members_with( @@ -187,6 +188,7 @@ fn substituted_members_with( from: &Path, class: &str, prepared_arguments: Option<&[String]>, + prepared_type: Option<&ComputedType>, listed: Known, ) -> Known { let Known::Yes(mut list) = listed else { @@ -238,6 +240,17 @@ fn substituted_members_with( // 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); + // **The per-member substitution context** — parameter names paired with the structured arguments, not with + // re-parsed strings. It is carried beside the fact; the fact itself is never the owner of the substitution. + let substitution = prepared_type.map(|class| { + Arc::new(MemberSubstitution { + bindings: names + .iter() + .zip(class.arguments().iter()) + .map(|(name, argument)| (name.clone(), argument.clone())) + .collect(), + }) + }); if names.is_empty() { return Known::Yes(list); } @@ -373,6 +386,11 @@ fn substituted_members_with( } member.fact = fact; } + if let Some(substitution) = substitution { + for member in &mut list.members { + member.substitution = Some(Arc::clone(&substitution)); + } + } Known::Yes(list) } diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index a750875d..fc31b626 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -1419,6 +1419,7 @@ impl Session { list.members.push(index::ProjectMember { file: declared.file.clone(), fact, + substitution: None, declared_in: class_name.to_string(), depth: 0, ambiguous: false, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 3472720b..44a6dcae 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -612,7 +612,9 @@ not of the class list: base walks merge members with different substitutions cached list is never rewritten. `substituted_members` now builds a fresh view for the request: each member's fact is cloned, its spellings are substituted, and the spelling-derived `TypeId`s are cleared because they describe the -unsubstituted spelling. No second `TypeStore` is created, so no `TypeId` can +unsubstituted spelling. A `MemberSubstitution { bindings: Vec<(SmolStr, +ComputedType)> }` is attached to each row on the computed path, so the +calculation layer can later materialize the same substitution from structure. No second `TypeStore` is created, so no `TypeId` can alias another store's entry; the resolved values are display/transition data until `SemanticModel` materializes `ComputedType`. From b48d3de78c57fdaa1fa1237a6fd246d233913424 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:30:35 +0800 Subject: [PATCH 064/102] feat(model): materialize a substituted member type as ComputedType ProjectMember keeps the unsubstituted source TypeIds; SemanticModel::computed_type_of_member materializes the handle once and applies the member's bindings structurally. No spelling parse and no local TypeId. --- .../src/index/project/macro_environment.rs | 4 ++++ .../src/index/project/members.rs | 4 ++++ crates/cpp_code_analysis/src/sema/model.rs | 16 ++++++++++++++++ crates/cpp_code_analysis/src/session/calls.rs | 2 ++ docs/type-system-redesign.md | 5 ++++- 5 files changed, 30 insertions(+), 1 deletion(-) 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 ba4c3035..535fe73d 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -441,6 +441,10 @@ pub struct ProjectMember { pub fact: DeclFact, /// The per-member instantiation context, when this row is a substituted view. pub substitution: Option>, + /// The **unsubstituted** type/return handles, kept for the computation layer. A substituted view clears the + /// handles inside its cloned fact, because those describe the old spelling; these still name the stored type. + pub source_type_of_id: TypeId, + pub source_returns_id: TypeId, /// 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 diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index e3b09320..7d040507 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -1369,6 +1369,8 @@ pub(crate) fn members_of_inner( .into_iter() .map(|(file, fact)| ProjectMember { file, + source_type_of_id: fact.type_of_id, + source_returns_id: fact.returns_id, fact, substitution: None, declared_in: class.to_string(), @@ -1549,6 +1551,8 @@ pub(crate) fn members_of_inner( .into_iter() .map(|(file, fact)| ProjectMember { file, + source_type_of_id: fact.type_of_id, + source_returns_id: fact.returns_id, fact, substitution: None, declared_in: shown.clone(), diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index f7052314..957fadbf 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -169,6 +169,22 @@ impl<'a> SemanticModel<'a> { Some(found) } + /// **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 `TypeId` is interned. + pub fn computed_type_of_member(&self, member: &crate::ProjectMember) -> Option { + let id = member + .source_type_of_id + .is_none() + .then(|| member.fact.type_of_id()) + .flatten() + .unwrap_or(member.source_type_of_id); + let base = self.computed_type(id)?; + Some(match &member.substitution { + Some(substitution) => base.substituted(&substitution.bindings), + None => base, + }) + } + /// **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. diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index fc31b626..038c5f04 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -1420,6 +1420,8 @@ impl Session { file: declared.file.clone(), fact, substitution: None, + source_type_of_id: crate::index::types::TypeId::NONE, + source_returns_id: crate::index::types::TypeId::NONE, declared_in: class_name.to_string(), depth: 0, ambiguous: false, diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 44a6dcae..20cf7cb2 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -614,7 +614,10 @@ for the request: each member's fact is cloned, its spellings are substituted, and the spelling-derived `TypeId`s are cleared because they describe the unsubstituted spelling. A `MemberSubstitution { bindings: Vec<(SmolStr, ComputedType)> }` is attached to each row on the computed path, so the -calculation layer can later materialize the same substitution from structure. No second `TypeStore` is created, so no `TypeId` can +calculation layer can later materialize the same substitution from structure. +`ProjectMember` also keeps the unsubstituted `source_type_of_id` / +`source_returns_id`; `SemanticModel::computed_type_of_member` materializes that +handle and applies the bindings with `ComputedType::substituted`. No second `TypeStore` is created, so no `TypeId` can alias another store's entry; the resolved values are display/transition data until `SemanticModel` materializes `ComputedType`. From e96549274d0eefe4727a1d6e1ec62e10fc1de0c9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:40:17 +0800 Subject: [PATCH 065/102] refactor(calls): read returns through the index spelling Call and type-hint paths stop reading candidate.fact.returns directly; ProjectIndex::returns_spelling_of/type_spelling_of supplies the spelling. One fewer direct field consumer. --- .../src/index/project/calls.rs | 7 ++++--- .../src/session/completion/request.rs | 17 ++++++++++------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 39c03f3e..e3b03e48 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -734,7 +734,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, @@ -1746,9 +1746,10 @@ pub(crate) fn a_members_answer_as_a_type( .files_declaring(&name, path) .into_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() }) - .and_then(|declared| declared.fact.type_of.clone()) + .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string)) else { break; }; diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 02cdc28d..dfa01813 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -879,16 +879,19 @@ impl Session { .and_then(|id| self.store.index().types().materialize(id)) .map(|computed| computed.to_string()) .or_else(|| { - found - .fact - .returns - .clone() - .map(|returns| returns.to_string()) + self.store + .index() + .returns_spelling_of(&found.fact) + .map(str::to_string) }) }) .or_else(|| { - local - .and_then(|found| found.fact.returns.map(|returns| returns.to_string())) + local.and_then(|found| { + self.store + .index() + .returns_spelling_of(&found.fact) + .map(str::to_string) + }) }) }, ); From 644b586048ac2862aefb237d2200f6bf5b8ad585 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Wed, 2 Dec 2026 20:54:14 +0800 Subject: [PATCH 066/102] docs: replace the type redesign with the identity-based plan The new plan removes DeclFact strings, makes ProjectMember a small FactRef plus substitution row, introduces DeclFactId/FileId runtime identities, and reserves ComputedType for the computation layer. It explicitly forbids TypeId-to-string re-parsing and per-view TypeStores. --- docs/type-system-redesign.md | 729 ++++++++++------------------------- 1 file changed, 208 insertions(+), 521 deletions(-) diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 20cf7cb2..977b036d 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -1,638 +1,325 @@ -# Type system and Fact storage redesign +# Type, fact, and member identity redesign -Status: **redesign in progress**, branch `refactor-type`. +**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. -This document supersedes the earlier incremental version. That version treated `DeclFact`'s strings as a compatibility -transition and tried to keep every intermediate commit green. Both premises were wrong: +## 1. The three layers -* a type string kept "for the transition" becomes an API, and every workaround built on it survives longer than the - type store; -* a rewrite that must stay green at every step is a rewrite of the workarounds rather than of the model. +### 1.1 Storage layer -The contract below is stricter. Facts contain **IDs**, not type text, parameter text, or default-argument text. -The CST is the only syntax reader. The parser is never called on a fragment with `ParserConfig::default()`. +The storage layer owns immutable data and small handles into it: -## 1. What is actually wrong +```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 +TypeId an identity for one type in one TypeStore +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 `TypeId` is never useful on its own. It must be resolved through its owning `TypeStore`. +- A `DeclFactId` is never useful on its own. It must be resolved through its owning fact arena. +- No second/local `TypeStore` is created for a computed result. A local store would make + `TypeId(3)` alias the global `TypeId(3)`. +- Persisted records never store run-local `FileId`/`DeclFactId`/`TypeId` as if they were stable + across runs. They store their own relative keys and are rebound on load. -The type store is not the main problem. The main problem is that the project has two sources of truth for syntax: +### 1.2 Computing layer + +The computing layer works on materialized values: ```text -real CST ──► fact strings ──► parse the string again ──► another tree +ComputedType an owned, structured type; names are cooked, children are shared +ResolvedMember a member row whose types are computed, not spelled ``` -The second tree is built from a fragment, with a default configuration, and then its offsets are mapped back to the -first tree's text. This is what the current code does in: +`ComputedType` is produced from storage exactly once per request: ```text -sema::call_syntax::parameter_names_from_text -sema::call_syntax::parameters_in_a_written_list -sema::call_syntax::tidy_list_text -sema::constant::tokens_of -sema::constraint::* (top-level text splitting) +TypeId + TypeStore -> ComputedType ``` -Concrete examples: +It is then passed through inference, overload ranking, conversion checks, member lookup, alias +substitution, and so on. There is **no** `TypeId -> spelling -> parse` step in this layer. -```rust -let text = format!("void __hint{parameter_list};"); -let tree = CppParser::parse(&text, ParserConfig::default()); -``` +### 1.3 Display layer + +Only the final presentation boundary turns a type into text: ```rust -let tree = CppParser::parse(written, ParserConfig::default()); +computed.to_string() ``` -The default configuration is not the project's language. It loses: - -* `CppLanguageLevel` (C++17/20/23, C vs C++); -* `ProjectLanguage` (CUDA, Ascend, Unreal conventions); -* `Dialect` and `dialect_was_named`; -* the lexer configuration; -* the macro facts and symbol table of the file; -* file boundaries and the parse generation. +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. -Even when the same text happens to parse the same way, the work is wrong: +## 2. Identity of facts -1. **It is a second parser.** The real CST already has the parameter nodes, declarations, default expressions and - requires-clauses. The fragment parse reconstructs a lossy copy. -2. **It loses the AST.** `CppParam`, `CppInitializer`, `CppRequiresClause` and the typed expression nodes are gone; - only strings and a generic syntax tree remain. -3. **It loses positions.** The stored parameter list is tidied text, not file text. The synthetic tree's offsets are - into the tidied string; mapping them back to a source range through a hand-written byte map is fragile for - comments, CRLF, multi-byte characters and nested parameter lists. -4. **It cannot represent a default argument.** A default is an expression, not a string: - `= std::map{1, 2}`, `= [] { return 1; }()`, `= sizeof(T) * 2`. Storing it as text forces a third parse - and makes it impossible to type or evaluate without guessing. -5. **It cannot represent a requires-clause.** The constraint language is a syntax tree, and the current - `top_level_split`/`contains("<")` logic is a text parser for a grammar that is already parsed. +### 2.1 `DeclFactId` -The consequence is visible in the storage shape: +`DeclFact` remains immutable. Its identity is the pair: ```rust -DeclFact { - type_of: Option>, - returns: Option>, - // ... -} - -DeclDetail { - bases: Vec, - parameters: Vec, - parameter_defaults: Vec, - parameter_list: Option, - parameter_type_ids: Box<[TypeId]>, - parameter_names: Box<[Option]>, - // ... +struct FactRef { + file: FileId, + fact: DeclFactId, } ``` -`parameter_names`, `parameter_type_ids` and a `parameter_list` string can coexist only because the real parameter -facts were never designed. Adding more fields to this shape is not migration; it is accumulating workarounds. - -## 2. Invariants - -These are non-negotiable. A change that violates one is rejected even if it makes a test pass. - -1. **The parser parses whole files/translation units, not source fragments.** A synthetic `void __hint(...)` parse is - forbidden outside parser tests. There is no `CppParser::parse` on a fact's type, parameter list, default argument - or constraint text in production code. -2. **`ParserConfig` comes from the project.** A parse of a file uses the file's `LanguageConfig`, macros, symbols, - dialect, family and lexer settings. `ParserConfig::default()` in a production path is a bug; tests may use it only - for a self-contained source string. -3. **Facts store identities, not syntax text.** - * types → `TypeId`; - * names → `NameId`; - * parameters → `ParamsId` (an arena) and `ParameterFact`; - * expressions/defaults/constraints/declarations → `SyntaxId` (or a typed `AstPtr` while live); - * source positions → `SourceRange`. -4. **A `SyntaxId` is resolved against a tree generation.** It is `(kind, TextRange, generation)` and is only valid - for the file content it was made from. A cache entry whose content hash/generation differs is invalid; it is never - repaired by reparsing a fragment. -5. **The type store is read-only during queries.** It is append-only while indexing. Query-time substitution creates - `ComputedType`, never `intern`. -6. **Strings in the type/name stores are canonical spellings only.** A fact does not own a duplicate type spelling, - parameter text or default text. -7. **No test-only compatibility API survives as production code.** If a field exists for an old cache, the codec - version is bumped and the old entry is discarded. - -## 3. The ID model +- `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. -```text -NameId(u32) interned spelling, 4 bytes -TypeId(u32) TypeStore node, 4 bytes -ParamsId(u32) parameter arena entry, 4 bytes -DetailId(u32) DeclDetail side-table entry, 4 bytes -SyntaxId CppSyntaxId: kind + TextRange, plus generation externally -``` +`FileId` is minted by the session's VFS. The index does not mint comparable IDs on its own. -`NONE = u32::MAX` for every optional handle. IDs are process-local within one index generation and are rebased when a -summary is imported. They are never persisted as global IDs. +### 2.2 Persisted facts -### 3.1 TypeId +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: -`TypeStore` keeps the compact graph already implemented: +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. -```rust -TypeKind { - Builtin(NameId), - Named { name: NameId, arguments: ArgsId }, - TemplateParameter(NameId), - Auto, - DecltypeAuto, - Pointer(TypeId), - Reference { to: TypeId, rvalue: bool }, - Array { of: TypeId, extent: u64 }, - Function { returns: TypeId, parameters: ArgsId }, - Pack(TypeId), - Qualified { of: TypeId, qualifiers: Qualifiers }, -} -``` +If a stable on-disk path identity is wanted later, it is a `PathId` table in the cache, never the +run-local `FileId`. -`TypeKind` is 16 bytes; `TypeNode` is 16 bytes; argument lists live in an `ArgsId` arena. The store is immutable -after the index drain. `ComputedType` (≤32 bytes, `SmolStr` names, `Arc` children) is the query-side materialization. +## 3. `DeclFact` -**Type construction must be from CST nodes, not from `parse_type_spelling`.** The parser's typed nodes -(`CppDeclSpecifierSeq`, `CppDeclarator`, `CppTypeId`, `CppPointerType`, `CppArrayType`, `CppTrailingReturnType`) can be -lowered directly into `TypeKind`. `parse_type_spelling` remains only at external boundaries: CLI input, tests, and a -malformed cache migration that is immediately re-read. - -### 3.2 SyntaxId - -Use the existing `CppSyntaxId`/`CppSyntaxNodePtr` machinery: +`DeclFact` stores only identities and structural syntax handles: ```rust -pub struct SyntaxId { - kind: CppKind, - range: TextRange, - generation: u64, +struct DeclFact { + name: SmolStr, + kind: DeclKind, + scope: Option, + type_of: Option, + returns: Option, + parameters: ParamsId, + template_parameters: Box<[SmolStr]>, + parameter_defaults: Box<[SmolStr]>, + requires_clause: Option, + default_argument: Option, + range: SourceRange, + name_range: SourceRange, + ... } ``` -* `CppSyntaxId::from_node` gives `(kind, range)`. -* `CppSyntaxId::to_node_from_root` resolves against the real tree. -* A typed `AstPtr` is the live form: `CppParam`, `CppInitializer`, `CppRequiresClause`, `CppExpr`. -* The cache stores only `SyntaxId` (kind + range); it never stores a red node or a `&CppSyntaxNode`. -* Resolution API: +There is no `type_of: Option>` and no `returns: Option>`. + +A type that is needed for display is materialized: ```rust -pub trait SyntaxResolver { - fn resolve(&self, file: &Path, id: SyntaxId) -> Option; - fn resolve_param(&self, file: &Path, id: SyntaxId) -> Option; - fn resolve_initializer(&self, file: &Path, id: SyntaxId) -> Option; - fn resolve_requires(&self, file: &Path, id: SyntaxId) -> Option; -} +index.types().computed(fact.type_of?) // -> ComputedType ``` -If the tree is not available, the answer is `Unknown`/`None`. The query does **not** parse the stored fragment to -manufacture a tree. +A fact with no written type has `None`. A fact from a temporary/view arena also resolves through +that arena's `TypeStore`; it never gets a local store. -### 3.3 NameId +## 4. `ProjectMember` -`NameInterner` is a store-local `Vec` plus `FxHashMap`. A fact's `name` and `scope` are -`NameId`s. Displaying a name asks the store; a long name is one shared allocation in the name table, not one per -fact. +`ProjectMember` is a small row: -### 3.4 ParamsId and ParameterFact +```rust +struct ProjectMember { + /// Which immutable declaration this row names. + fact: FactRef, -Parameters live in a side arena, not in `DeclFact`: + /// This instantiation's substitutions. Empty for a non-template member. + substitution: Option>, -```rust -pub struct ParameterFact { - pub name: Option, - pub type_of: TypeId, - pub declarator: SyntaxId, // the Parameter node in the real CST - pub default_value: Option, // the Initializer expression, if any - pub pack: bool, // parameter pack / ellipsis - flags: ParamFlags, + /// The class whose own declaration filed this row. + declared_in: DeclFactId, // or a qualified-name id, see below + + depth: usize, + ambiguous: bool, } ``` -There is no `text`, no `type_of: String`, no `parameter_list: String`. A parameter's source spelling is read from -its `SyntaxId` range when a signature is rendered; the type is the `TypeId`; the default is the `SyntaxId` of the -initializer. - -`ParameterFact` is produced by the **summary builder** from `CppParamList`: +It does **not** store: ```text -CppParamList - └─ CppParam - ├─ CppDeclSpecifierSeq / CppDeclarator → TypeStore::lower_cpp_type → TypeId - ├─ CppNameToken → NameInterner → NameId - ├─ CppInitializer → CppSyntaxId → SyntaxId - └─ CppSyntaxId of the Parameter node +PathBuf +DeclFact by value +substituted DeclFact copies +type/return strings ``` -`CppParam::get_type_text()` is not the source of a `TypeId`; it is a debugging helper. The lowering reads the typed -nodes so pointer/reference/array/function shapes are structural, not re-parsed. +`declared_in` is a fact reference as well, not a path or a copied fact. The qualified spelling is +produced only at display. -## 4. Fact storage, v2 +### 4.1 Reading a member -### 4.1 DeclFact +The row is resolved through the index and the model: ```rust -pub struct DeclFact { - pub name: NameId, - pub scope: NameId, // NONE for file scope - pub kind: DeclKind, - pub flags: FactFlags, // local, definition, exported, enumerator, split-by-directive, clean - pub type_of: TypeId, // variables and aliases; NONE otherwise - pub returns: TypeId, // functions; NONE otherwise - pub parameters: ParamsId, // NONE when there is no parameter list - pub detail: DetailId, // NONE when there are no rare fields - pub declaration: SyntaxId, // the declaration/declarator node - pub name_range: SourceRange, +impl SemanticModel<'_> { + fn member_type(&self, member: &ProjectMember) -> Option; + fn member_returns(&self, member: &ProjectMember) -> Option; + fn member_parameters(&self, member: &ProjectMember) -> Option<&ParamsStore>; } ``` -No `String`, no `SmolStr`, no `Option>`, no `Option>`. - -`FactFlags` is a `u16`/`u32` bit set. `range` is derivable from `declaration` but `name_range` is kept because it is -the hot key for navigation and rename. - -### 4.2 DeclDetail side table - -`DeclDetail` is no longer boxed per fact; it is a row in a side table: +The base type is materialized from the fact arena's `TypeStore`, then the member substitution is +applied structurally: ```rust -pub struct DeclDetail { - pub in_namespace: Option, - pub returns_in_the_class: Option, - pub bases: Box<[TypeId]>, - pub template_parameters: Box<[TemplateParameterFact]>, - pub constraints: Box<[SyntaxId]>, - pub requires_clause: Option, - pub pattern: Option, - pub reflection: Option, -} - -pub struct TemplateParameterFact { - pub name: NameId, - pub default: Option, // an expression, not a string -} +base.substituted(&substitution.bindings) ``` -`DetailId` is an index into `Vec>>` or a flat arena. A fact without any detail pays four -bytes, not eight for a box and not a heap allocation. - -### 4.3 Parameter arena +No spelling is parsed. -`ParamsId` indexes a `ParamsStore`: +### 4.2 Substitution ```rust -pub struct ParamsStore { - entries: Vec>, - ids: FxHashMap, ParamsId>, +struct MemberSubstitution { + bindings: Vec<(SmolStr, ComputedType)>, } ``` -Parameters are compared structurally; a declaration with the same parameter list in two files shares one entry. -The arena is built only during indexing. Queries get `&[ParameterFact]`. +- 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. +- `MemberSubstitution` lives in the request (`SemanticModel` cache) or in a `Arc` owned by the row. + It never enters a summary or the cache. -### 4.4 What is deliberately absent +`ProjectMember` rows can be merged from different bases with different substitutions; this is why +the substitution cannot be a field on `MemberList`. -```text -type_of: String / SmolStr / Arc absent -returns: String / SmolStr / Arc absent -parameter_list: String absent -parameters: Vec absent -parameter_defaults: Vec absent -parameter_names: Vec> absent -text: String absent -``` - -Source text remains only in the VFS/cooked rendering and in the parser's tree. A fact that needs a spelling asks the -`NameId`/`TypeStore` or resolves a `SyntaxId`; there is nothing to reparse. +### 4.3 Caching -## 5. Syntax-derived features +`SemanticModel` owns the per-request caches: -### 5.1 Parameters and signatures +```text +computed_types: BTreeMap<(FileId, TypeId), ComputedType> +member_types: HashMap<(FactRef, SubstitutionId?), ComputedType> +members: HashMap +``` -The signature popup is built from the declaration's `ParamsId`: +Keys use `FileId`/`TypeId` pairs so two files' local handles cannot collide. The index owns no +substituted member cache and no recomputation cache. -* parameter names → `NameId`; -* parameter types → `TypeId` (render with `ComputedType`); -* default arguments → `SyntaxId` resolved to `CppInitializer` (or omitted if the file is unavailable); -* parameter spans → the `SyntaxId` ranges in the real source; the label is composed from source slices at those - ranges, not from a stored `parameter_list` and not from a synthetic tree. +## 5. File and path identities -The old string functions are deleted: +Runtime structures use `FileId`: ```text -parameter_names_from_text -parameters_in_a_written_list -tidy_list_text +ProjectMember.fact.file +ProjectDefinition.file +Candidate.file +ProjectIndex queries that return a location ``` -Callers move as follows: - -| caller | new source | -| --- | --- | -| `signature` | `CppParamList` nodes / `ParameterFact` | -| `overload::parameters_in` | `&[ParameterFact]` | -| `argument_count` | parameter facts + `pack` flag | -| `missing_include` | parameter `TypeId`s | -| `inlay` / `completion` | `ParameterFact.name` | -| `member_facts` | `ParameterFact` | - -### 5.2 Constant evaluation - -`constant.rs` must not parse a constant expression from a string: +Persistent records keep paths or a persisted `PathId`: ```text -old: written: &str → CppParser::parse(written, default) → tokens → evaluator -new: CppExpr / SyntaxId → resolve → CppExpr nodes / real token stream → evaluator +FileSummary cache key +cooked-reading cache key +module/import records ``` -The evaluator accepts a typed expression (`CppExpr`) or a `CppSyntaxNode` from the CST. It never manufactures a -translation unit. Default arguments use the same path: `ParameterFact.default_value` is a `SyntaxId`, resolved to -`CppInitializer` and evaluated from the tree. +`ProjectIndex` receives the path↔`FileId` mapping from the session/VFS at insertion time. It does +not create a parallel file-id namespace. -### 5.3 Constraints and requires-clauses +## 6. Parameters -`constraint.rs`/`requires` evaluation is a CST/AST walk: +`ParameterFact` is the single parameter representation: -```text -old: condition: &str → top_level_split/contains('<') → string trait parser -new: CppRequiresClause / CppConstraint expression → typed AST walk → trait evaluation +```rust +struct ParameterFact { + name: Option, + declaration: SyntaxId, + default_value: Option, + pack: bool, + type_of: TypeId, +} ``` -`DeclDetail.constraints` and `requires_clause` hold `SyntaxId`s. The trait evaluator matches `CppExpr` variants -(`!`, `&&`, `||`, `CppCallExpr`, `CppBinaryExpr`, type arguments) rather than splitting text. - -### 5.4 No `parse_type_spelling` in facts or checks +`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. -Type lowering from CST: +## 7. Constants and constraints -```text -CppDeclSpecifierSeq + CppDeclarator - → TypeStore::lower_cpp_type - → TypeId -``` +`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. -`parse_type_spelling` is allowed only for: +`constraint.rs` reads: -* CLI/tool input; -* test fixtures written as strings; -* an external API that explicitly accepts a spelling. +- a `RequiresClause` through `CppRequiresClause` token accessors; +- `enable_if`/`enable_if_t` through `CppNameExpr` + `CppTemplateArgList`; +- the condition expression through typed CST nodes. -It is not called from `DeclFact`, `DeclDetail`, `constant`, `constraint`, `signature`, `inlay`, `completion`, -`overload`, or any diagnostic. +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. -## 6. Serialization and generations +## 8. Forbidden patterns -A summary record contains local tables: +The following are review blockers: ```text -NameTable NameId -> spelling -TypeTable local TypeId -> EncodedType -ParamsTable local ParamsId -> [ParameterFact with local TypeId/SyntaxId] -DetailTable local DetailId -> DeclDetail with local handles -SyntaxTable local SyntaxId -> kind + range +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 ``` -Facts reference local IDs, never process-global IDs. On decode: +## 9. Migration phases -1. verify codec version; -2. verify every `SyntaxId`'s file content hash/generation; -3. import names/types/params/details into the destination stores; -4. rebase all local IDs; -5. reject the summary if a `SyntaxId` cannot be validated (do not parse a fragment to repair it). +### Phase 1: identity plumbing -`CODEC_VERSION` is bumped for every schema change. There is no compatibility branch that reconstructs a missing -string. +- 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. -## 7. Workarounds to delete, not port +### Phase 2: member views -Delete these functions and their tests that assert string behavior: +- `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 materialized `ComputedType`s by `(FileId, TypeId)`. -```text -sema::call_syntax::parameter_names_from_text -sema::call_syntax::parameters_in_a_written_list -sema::call_syntax::tidy_list_text -sema::constant::tokens_of -constraint.rs' top_level_split and text-level trait parser -``` +### 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. -Delete these fields/APIs: +## 10. Acceptance ```text -DeclFact::type_of (string) -DeclFact::returns (string) -DeclDetail::parameter_list -DeclDetail::parameter_names -DeclDetail::parameter_type_ids (replaced by ParameterFact) -DeclDetail::parameters / parameter_defaults as strings -DeclDetail::bases as strings +cargo test --workspace +cargo clippy --workspace --all-targets --all-features -- -D warnings ``` -Delete these call patterns: +plus static guards: ```text -CppParser::parse(&format!("void __hint…"), ParserConfig::default()) -CppParser::parse(parameter_list, ParserConfig::default()) -CppParser::parse(written, ParserConfig::default()) // constant/constraint -parse_type_spelling(fact.type_of) +no ParserConfig::default() parse outside whole-file entry points +no `DeclFact.type_of` / `DeclFact.returns` strings +no `PathBuf` in ProjectMember/ProjectDefinition/Candidate +no second TypeStore ``` -A CI guard should fail if `CppParser::parse` appears in `cpp_code_analysis/src` outside: - -* `FileView::parse` / the session's whole-file parser; -* `cpp_parser` tests; -* an explicit external-input boundary with a comment naming it. - -## 8. Migration plan - -Intermediate commits may be red. This is a branch rewrite, not a sequence of production hot patches. Each *merge -point* must be green: - -### Phase 0 — foundations - -* add `SyntaxId`/resolver and generation tracking around `CppSyntaxId`; -* add `ParamsStore`, `ParameterFact`, `DetailStore` skeletons; -* add codec v-next with local tables; -* add tests that resolve typed CST nodes. - -### Phase 1 — parameter facts - -* build `ParameterFact` in the summary builder from `CppParamList`; -* store parameter `TypeId`s built from CST; -* migrate signature, inlay, completion, argument-count, overload, missing-include; -* delete the three call_syntax functions; -* merge point: full tests green, no synthetic parameter parse. - -### Phase 2 — type identities - -* lower types from CST into `TypeStore` at fact-build time; -* remove `type_of`/`returns` strings; -* migrate all readers to `TypeId` / `ComputedType` / `type_spelling_of` from the store only; -* merge point: no `parse_type_spelling` in production fact paths. - -### Phase 3 — expressions and constraints - -* store default initializers and requires-clauses as `SyntaxId`; -* rewrite constant evaluator over `CppExpr`/real CST tokens; -* rewrite constraint evaluator over the typed AST; -* delete text splitters; -* merge point: no fragment parse in constant/constraint. - -### Phase 4 — fact layout - -* move `DeclDetail` to a side table (`DetailId`); -* move parameters to `ParamsId`; -* pack flags, shrink `DeclFact` to the target schema; -* update codec and memory report; -* merge point: size/benchmark gates. - -### Phase 5 — remove the old model - -* delete `sema::types::Type` as a public query type (keep only parser lowering if needed); -* delete remaining compatibility accessors; -* delete `parse_type_spelling` from analysis except external boundaries; -* run the repository-wide no-reparse guard. - -**It is accepted that intermediate commits do not pass all tests.** Compile errors and test failures are expected -while a caller migration is in flight. The branch is merged only at a phase boundary, with the full suite and clippy -green. - -## 9. Tests and measurements - -Required regression tests: - -1. **Configuration parity**: the same declaration with a CUDA/Unreal/C++23 config produces parameter/type facts from - the real tree; no default-config synthetic parse exists. -2. **Complex default**: `void f(std::map m = {{1, 2}});` stores a `SyntaxId`; resolving it yields a - `CppInitializer` whose expression can be evaluated. -3. **Constraint**: `requires requires(T t) { t.size(); }` stores a `SyntaxId` and evaluates through typed AST nodes. -4. **Signature spans**: a parameter list with comments/CRLF/multibyte text produces spans that slice the real source - text correctly. -5. **Cache**: `SyntaxId` generation/content-hash mismatch invalidates the summary; no fragment parse occurs. -6. **Memory**: `DeclFact` size, `ParameterFact` arena bytes, no per-fact type strings, type dedup. -7. **No-reparse guard**: source grep fails on forbidden `CppParser::parse` call sites. - -## 10. Open decisions to settle before Phase 1 - -1. **`SyntaxId` representation**: keep `(CppKind, TextRange)` plus an external generation, or add a compact - `SyntaxId { file: SyntaxFileId, start: u32, len: u32, kind: u16 }` to fit in 12/16 bytes. The latter is preferable - for `ParameterFact` and default expressions. -2. **`AstPtr`**: a typed `rowan` pointer is cheap live but not serializable; confirm that persisted data uses - `SyntaxId` and live query caches use `AstPtr`. -3. **Template parameter defaults**: `SyntaxId` of the default expression plus a `TypeId` for its lowered type, or - `SyntaxId` only until evaluation. -4. **Constraint evaluation**: a typed constraint AST or direct `CppRequiresClause` walking; do not introduce a - second grammar. -5. **`SyntaxFileId`**: one per VFS file/generation; a `SyntaxId` must be resolvable without a path string in the hot - path. - -## 11. Current state (superseded pieces) - -**Phase 0 started.** `index::params::ParameterFact` now stores a parameter's `CppSyntaxId` declaration, its optional -default-initializer `SyntaxId`, its pack flag and its name; `parameter_facts_of(&CppParamList)` builds the list from -the CST. The parser's `CppParam::get_name` now handles pack declarations without borrowing the names of a function -pointer's nested parameters. `index::syntax` now defines `SyntaxId` (the parser's `CppSyntaxId`), a `SyntaxResolver` for a parsed file and typed -`resolve_parameter` / `resolve_initializer` / `resolve_requires`; the tests round-trip a parameter and a braced default -initializer without any text parse. `build_facts` now returns `BuiltFacts { facts, guards, parameters, types }`: the builder lowers each `CppParam` type, -interns the parameter list and clears the build-time detail copy before the summary is filed. `ParamsStore`/`ParamsId` -now exist and hash-cons equal parameter lists; `ProjectIndex` owns one and exposes -`parameters()`. `FileSummary` now carries the local `ParamsStore`; `DeclFact::parameters` is a local `ParamsId`, the -index builder interns each detail's facts, and `summary_codec` writes the table (CODEC_VERSION 46). `DeclDetail` -still keeps a copy for raw facts outside the index; removing it is the next step. Parameter types are lowered from -each `CppParam` (`get_type_text`) into the summary's `TypeTable`. `ProjectIndex::parameter_facts_of` additionally -maps a cooked fact with a different arena to the source summary's declaration by name range. A signature whose declaration has no rendering now falls back to `view_of_the_file`, i.e. a **full parse of that -file with the session's config**; the synthetic `void __hint(...)` fact fallback is deleted. The signature label is -built from `CppParam` nodes via `CppParam::one_line_text`, and `parameter_names_from_text`, -`parameters_in_a_written_list` and `tidy_list_text` are all deleted from the analysis crate. `constant.rs` now -lexes its expression with `cpp_parser::lex` and `LexerConfig`, not `CppParser::parse(..., ParserConfig::default())`; -its internal evaluator takes the CST's own tokens through `value_of_tokens`, and only the public spelling boundary -calls the lexer. `CppRequiresClause::get_condition_text` exposes the clause condition token-by-token, and the overload -filter uses that typed accessor instead of stripping `requires` from the declaration text. `the_condition_of_node` -finds `enable_if`/`enable_if_t` through `CppNameExpr` and takes its first `CppTemplateArg`; the old string scanner -`the_condition_of`/`the_enable_if_argument` is deleted. The check layer now reads `type_of`/`returns` through -`ProjectIndex::type_spelling_of`/`returns_spelling_of` in `abstract_class_instantiated`, `assign_type_check`, -`missing_return`, `redefinition` and `unused`, so those consumers no longer depend on the transition string fields. -The session's definition, completion, queries, semantic alias walk and sizeof/alias path read the same helpers; the -index's own alias, member, deduction, substituted and completion machinery now does the same. The remaining direct -field readers are the build-time intern bridge in `macro_walk`, the public `render::an_item`/`a_line` wrappers, and -tests. `render::an_item_with`/`a_line_with` take a type-spelling resolver and are what the hover uses; the wrappers -exist only until the fields are deleted. `build_facts` now interns every fact's `type_of`/`returns` into its -`BuiltFacts` type store, so `ProjectIndex::insert_at` no longer has a string-to-ID bridge in `macro_walk`; the codec -writes raw spellings until the fields are deleted (CODEC_VERSION 48). `missing_include` and -`unresolved_type` read parameter TypeIds through that resolver; the text reader is now only the fallback for a fact -whose arena produced no type spelling at all. `parameter_types_in_a_written_list` is deleted: template-argument hints -materialize `ParameterFact.type_of` from the store, and no longer fill `parameter_type_ids` by parsing the list. -`DeclDetail::parameter_type_ids` and its codec bytes are deleted; the parameter arena is the only type source -(CODEC_VERSION 47)., and `argument_count` now reads counts, defaults and -type spellings from the parameter facts/type store instead of `parameters_in_a_written_list` when they exist. The -completion template-parameter filter and the overload tie-break (`the_one_the_arguments_select`) use -`parameters_in_facts`, so their normal indexed path no longer parses the list. The pack element type is read from the -fact (the `...` is stripped from the CST type spelling), and an integration test pins the overload input to -`CppParam` nodes. `TypeId` is present as `NONE` until the CST -type lowering lands. `DeclDetail` now carries the facts, `summary_codec` -writes/read them (CODEC_VERSION 45), and inlay/completion name consumers use them. `parameter_names_from_text` is -deleted: names come from `ParameterFact`, from `parameter_names_of_list(&CppParamList)`, or are unavailable; there is -no synthetic name parse. The remaining synthetic reader is the parameter-span/type path (`parameters_in_a_written_list`, -`parameter_types_in_a_written_list`), which the next phase removes. - -The type store in `index/types/` is a valid foundation: - -* `TypeKind`/`TypeNode` 16 bytes, `ArgsId` arena; -* `TypeTable` and local-ID import/export; -* `ComputedType` ≤32 bytes and request-scoped cache; -* `TypeId`/`TypeRef` read APIs. - -The following pieces are **not** the target and will be removed: - -* `DeclFact.type_of` / `returns` as strings; -* `DeclDetail.parameter_list`, `parameter_names`, `parameter_type_ids`; -* `sema::types::Type` as a public query type; -* all synthetic parameter/constant/constraint parsing. - -No new code may build on those fields or functions. The next commit starts Phase 0/1 from the model above. - - -## Cache layer versus computation layer (the corrected boundary) - -The index/cache layer is the only owner of stored identities: `DeclFact`, -`TypeId`, `ParamsId`, and the project-wide `TypeStore`. A `TypeId` is valid only -inside the store that issued it, so there is exactly one store for stored facts. -Creating a second, local `TypeStore` for a substituted member is forbidden: its -`TypeId(3)` would silently alias the global `TypeId(3)`. - -`SemanticModel` is the computation layer's per-request home. It already owns -`computed: RefCell>` and the member-list cache; a -substitution cache belongs there too, because the model is discarded after one -file's request. The index must not cache substituted member lists or -substitution results. `SemanticModel::members_of` now calls -`project::members_of_inner` directly, so the model's `members` memo is the only -cache on that path; the index's project-wide `member_lists` remains for callers -that ask the index itself. - -A template substitution is a property of **one member in one instantiation**, -not of the class list: base walks merge members with different substitutions -(`Base::value` and `Base::value` can be in one list). The index's -cached list is never rewritten. `substituted_members` now builds a fresh view -for the request: each member's fact is cloned, its spellings are substituted, -and the spelling-derived `TypeId`s are cleared because they describe the -unsubstituted spelling. A `MemberSubstitution { bindings: Vec<(SmolStr, -ComputedType)> }` is attached to each row on the computed path, so the -calculation layer can later materialize the same substitution from structure. -`ProjectMember` also keeps the unsubstituted `source_type_of_id` / -`source_returns_id`; `SemanticModel::computed_type_of_member` materializes that -handle and applies the bindings with `ComputedType::substituted`. No second `TypeStore` is created, so no `TypeId` can -alias another store's entry; the resolved values are display/transition data -until `SemanticModel` materializes `ComputedType`. - -The computation layer consumes materialized `ComputedType`s. Converting a -`TypeId` to a string and parsing that string again is a bug in the boundary, not -a shortcut: the string exists only at the display/API edge (`hover`, -completion labels, diagnostics messages). `ComputedType::substituted` applies -template bindings recursively without interning a `TypeId` or parsing a -spelling; the per-member substitution view is built on that operation. -`ComputedType::from(&Type)` is the same boundary in the other direction: the -semantic `Type` a query already holds becomes a `ComputedType` structurally, so -the member query can take `ComputedType` rather than re-parsing a spelling. -`SemanticModel::members_of_computed` is that computation-side entry point; the -first caller is `param_type_check`. Its answers are memoised in -`computed_members: HashMap`, so a computed-type query does not -stringify the class to consult the cache. On a miss it calls -`substituted_members_for`, which takes the class name and arguments from -`ComputedType` directly instead of splitting a class spelling. +Each phase boundary must be green. Within a phase, intermediate commits may be red. From a6a8bf99e2e9c30a33364cb6ffb79e976b67158e Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 10:29:43 +0800 Subject: [PATCH 067/102] feat(facts): add DeclFactId and FactRef resolution Introduces the per-file fact identity and a reference that resolves through ProjectIndex instead of owning a DeclFact. The current file number is the index sequence; the VFS handoff is the next Phase 1 step. --- .../src/index/project/macro_environment.rs | 23 +++++++++++++ .../src/index/project/macro_walk.rs | 34 +++++++++++++++++++ 2 files changed, 57 insertions(+) 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 535fe73d..04cd94bd 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -13,6 +13,29 @@ 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. +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct FactRef { + pub file: crate::FileId, + pub fact: DeclFactId, +} + /// 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. /// 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 018b8c7e..6d44a577 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -409,6 +409,40 @@ impl ProjectIndex { .map_or(&[], |candidate| summary.parameter_facts(candidate)) } + /// **The runtime file id the index assigned this path.** The numbering is the index's insertion sequence; a + /// session that owns a VFS will pass its own [`crate::FileId`] here once the two tables are unified. + pub fn file_id_of(&self, path: &Path) -> Option { + self.sequence + .get(&normalize(path)) + .copied() + .map(crate::FileId::new) + } + + /// **The reference to one declaration in its arena.** `None` when the fact is not in the summary filed at + /// `path` (a view-built fact has no arena entry yet). + pub fn fact_ref(&self, path: &Path, fact: &DeclFact) -> Option { + let file = self.file_id_of(path)?; + let summary = self.summaries.get(&normalize(path))?; + let at = summary + .declarations + .iter() + .position(|candidate| std::ptr::eq(candidate, fact))?; + Some(FactRef { + file, + fact: DeclFactId::from_index(at), + }) + } + + /// **Resolve a `FactRef` to the immutable declaration.** The path is recovered from the index's sequence, + /// never from the fact itself. + pub fn fact(&self, reference: FactRef) -> Option<&DeclFact> { + let path = self.order.get(&(reference.file.index() as u32))?; + self.summaries + .get(&normalize(Path::new(path)))? + .declarations + .get(reference.fact.index()) + } + /// **The parameter facts of the declaration whose name starts at `offset`**, through its source summary. This is /// what a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. pub fn parameter_facts_at(&self, file: &Path, offset: usize) -> &[ParameterFact] { From e134951d6a848498fd813bac73b8c1a33dd628a3 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 12:03:31 +0800 Subject: [PATCH 068/102] refactor(facts): make ProjectDefinition a FactRef ProjectDefinition now stores FileId + FactRef instead of PathBuf + owned DeclFact. FactRef gained the reading index because cooked readings are separate fact arenas. ProjectIndex resolves refs (fact/definition_fact/definition_path/definition_parts), Session threads a reading->file mapper for binding-derived answers, and cpp_ls/cpp_inspect materialize facts at their display/query edges. Tests updated to resolve through the index. Full workspace tests and clippy pass. Known gap: binding-derived class-body scope is now read from the view's binding because the index fact builder still loses that scope; recorded in the class_body_continuity tests, not hidden. --- .../src/index/project/bases.rs | 9 +- .../src/index/project/calls.rs | 85 ++++--- .../src/index/project/completions.rs | 20 +- .../src/index/project/macro_environment.rs | 138 ++++++---- .../src/index/project/macro_walk.rs | 223 +++++++++++++--- .../src/index/project/member_candidates.rs | 6 +- .../src/index/project/member_facts.rs | 22 +- .../src/index/project/members.rs | 143 ++++++----- .../src/index/project/queries.rs | 94 +++++-- .../src/index/project/substituted.rs | 12 +- .../src/index/project/tests.rs | 155 ++++++++---- .../src/index/project/type_of.rs | 22 +- .../src/sema/check/argument_count.rs | 10 +- .../src/sema/check/final_hierarchy.rs | 6 +- .../src/sema/check/missing_return.rs | 4 +- .../src/sema/check/param_type_check.rs | 8 +- .../src/sema/check/redefinition.rs | 7 +- .../src/sema/check/undefined_name.rs | 15 +- .../src/sema/check/use_after_free.rs | 11 +- crates/cpp_code_analysis/src/session/calls.rs | 46 ++-- .../src/session/completion/request.rs | 50 ++-- .../src/session/constrained.rs | 16 +- crates/cpp_code_analysis/src/session/inlay.rs | 10 +- .../src/session/navigation.rs | 10 +- .../cpp_code_analysis/src/session/queries.rs | 156 +++++++----- .../cpp_code_analysis/src/session/semantic.rs | 16 +- .../src/session/signature.rs | 18 +- .../src/session/tests/buffers.rs | 6 +- .../src/session/tests/cache.rs | 8 +- .../src/session/tests/closure.rs | 9 +- .../src/session/tests/cooked.rs | 24 +- .../src/session/tests/disk.rs | 22 +- .../src/session/tests/names.rs | 53 ++-- .../src/session/tests/programs.rs | 48 +++- .../src/session/tests/types.rs | 105 ++++++-- .../tests/suite/alias_qualified_members.rs | 13 +- .../tests/suite/c_declarators.rs | 4 +- .../tests/suite/class_body_continuity.rs | 19 +- .../tests/suite/definition.rs | 13 +- .../tests/suite/header_context.rs | 7 +- .../cpp_code_analysis/tests/suite/modules.rs | 12 +- .../tests/suite/out_of_class_members.rs | 13 +- .../tests/suite/rendered_reading.rs | 15 +- .../tests/suite/reported_defects.rs | 10 +- .../cpp_code_analysis/tests/suite/scopes.rs | 25 +- .../cpp_code_analysis/tests/suite/semantic.rs | 31 ++- crates/cpp_code_analysis/tests/suite/types.rs | 58 ++++- .../tests/suite/ue_engine.rs | 28 ++- crates/cpp_inspect/src/questions.rs | 49 ++-- .../cpp_ls/src/handlers/call_hierarchy/mod.rs | 32 ++- crates/cpp_ls/src/handlers/definition/mod.rs | 91 ++++--- .../src/handlers/document_highlight/mod.rs | 7 +- crates/cpp_ls/src/handlers/hover/mod.rs | 238 ++++++++++++------ .../cpp_ls/src/handlers/implementation/mod.rs | 11 +- crates/cpp_ls/src/handlers/references/mod.rs | 69 +++-- crates/cpp_ls/src/handlers/rename/mod.rs | 6 +- .../cpp_ls/src/handlers/semantic_token/mod.rs | 2 + .../src/handlers/type_definition/mod.rs | 14 +- .../cpp_ls/src/handlers/type_hierarchy/mod.rs | 24 +- 59 files changed, 1671 insertions(+), 707 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index c704830c..f4f9162c 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -130,7 +130,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, } } @@ -558,7 +560,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); } diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index e3b03e48..3b78d7c0 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -44,7 +44,7 @@ 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) { return Known::Yes(NamedDeclaration::Indexed( member.fact, @@ -103,7 +103,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 @@ -647,14 +649,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, @@ -717,16 +722,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 +742,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 index.returns_spelling_of(&candidate.fact) { + 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, @@ -744,14 +752,14 @@ pub(crate) fn the_return_the_overloads_agree_on( }, }; if !a_candidate_that_can_be_called_this_way( - candidate.fact.parameter_list(), + candidate_fact.parameter_list(), 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 +767,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; } @@ -1118,7 +1126,7 @@ 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) { return Known::Yes(NamedDeclaration::Indexed( member.fact, @@ -1146,11 +1154,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, }, @@ -1305,10 +1320,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(), ), @@ -1366,7 +1384,10 @@ pub(crate) fn the_declaration_the_arguments_pick( let candidates: Vec<(DeclFact, PathBuf)> = definitions .found .iter() - .map(|definition| (definition.fact.clone(), definition.file.clone())) + .filter_map(|definition| { + let (fact, file) = index.definition_parts(definition)?; + Some((fact.clone(), file.to_path_buf())) + }) .collect(); let types = the_types_of_the_arguments(memo, index, declaring, scopes, root, path, call)?; let explicit_arguments: Vec = call diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index e3407245..f8446074 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -710,13 +710,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; } } @@ -871,11 +874,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) = index.type_spelling_of(&alias.fact) + && 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,7 +896,11 @@ 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), 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 04cd94bd..f8706b24 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -30,9 +30,19 @@ impl DeclFactId { /// **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: crate::FileId, + /// `0` is the file's summary; `1..` is a cooked reading (see `Readings`). + pub reading: u32, pub fact: DeclFactId, } @@ -265,6 +275,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, } @@ -274,6 +286,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, } @@ -282,6 +296,7 @@ impl ProjectDeclaration { ProjectDeclaration { file: found.file.clone(), fact: found.fact.clone(), + reference: found.reference, start_offset: found.fact.name_range.start_offset, } } @@ -363,12 +378,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: crate::FileId, + pub fact: FactRef, } /// **Every declaration a name refers to** — the plural answer to "where is this declared". @@ -509,12 +526,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`] @@ -522,51 +542,69 @@ 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, - type_of_id: TypeId::NONE, - returns: None, - returns_id: TypeId::NONE, - parameters: crate::index::params::ParamsId::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: None, + type_of_id: TypeId::NONE, + returns: None, + returns_id: TypeId::NONE, + parameters: crate::index::params::ParamsId::NONE, + 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, } } 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 6d44a577..288be3c9 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -151,10 +151,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, }); } @@ -418,31 +418,176 @@ impl ProjectIndex { .map(crate::FileId::new) } + /// **The path the index assigned this file id**, 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 **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: crate::FileId) -> Option<&Path> { + let key = self.order.get(&(file.index() as u32))?; + 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` (a view-built fact has no arena entry yet). + /// `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 summary = self.summaries.get(&normalize(path))?; - let at = summary - .declarations - .iter() - .position(|candidate| std::ptr::eq(candidate, fact))?; - Some(FactRef { - file, - fact: DeclFactId::from_index(at), - }) + 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), + }); + } + } + None } /// **Resolve a `FactRef` to the immutable declaration.** The path is recovered from the index's sequence, /// never from the fact itself. pub fn fact(&self, reference: FactRef) -> Option<&DeclFact> { let path = self.order.get(&(reference.file.index() as u32))?; - self.summaries - .get(&normalize(Path::new(path)))? + let key = normalize(Path::new(path)); + 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()) } + /// **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 parameter facts of the declaration whose name starts at `offset`**, through its source summary. This is /// what a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. pub fn parameter_facts_at(&self, file: &Path, offset: usize) -> &[ParameterFact] { @@ -2308,20 +2453,29 @@ 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)) { + for (at, fact) in candidates.filter(|(_, fact)| contributes(fact)) { found.push(VisibleDeclaration { file: summary.path.clone(), fact, + reference: FactRef { + file: crate::FileId::new(file), + reading, + fact: DeclFactId::from_index(at), + }, visibility, }); } @@ -3129,9 +3283,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 @@ -3141,7 +3297,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() { @@ -3159,7 +3318,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])); @@ -3373,8 +3535,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, @@ -3436,7 +3598,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; @@ -3451,7 +3616,7 @@ impl ProjectIndex { } }; - if !a_class || (c_file && declaration.fact.enumerator) { + if !a_class || (c_file && fact.enumerator) { kept.push(declaration); } } 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..65d7a522 100644 --- a/crates/cpp_code_analysis/src/index/project/member_candidates.rs +++ b/crates/cpp_code_analysis/src/index/project/member_candidates.rs @@ -108,7 +108,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)| (fact.clone(), file.to_path_buf())) + .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 e9ac9704..773fd05c 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -916,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(|| index.type_spelling_of(&declaration.fact)) + 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()), ) }) }), @@ -1022,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) = index.type_spelling_of(&found.fact) else { + let Some(target) = index.type_spelling_of(found_fact) else { continue; }; if target == prefix { @@ -1034,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 7d040507..fe3103b5 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -145,7 +145,16 @@ 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. @@ -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() @@ -250,10 +255,7 @@ pub(crate) fn a_member_of_the_enclosing_class( } // **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(), - }) + 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 +293,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 +305,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 +320,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,15 +343,15 @@ 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 = index - .computed_type_of(&found.fact) + .computed_type_of(found_fact) .map(|computed| computed.to_string()) .or_else(|| { - found - .fact + found_fact .type_of .clone() .map(|written| written.to_string()) @@ -353,7 +359,7 @@ pub(crate) fn a_namespace_aliass_target( 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), } @@ -494,14 +500,17 @@ 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(), + Some(declaration) => index + .definition_fact(declaration) + .map_or_else(|| name.clone(), |fact| fact.qualified_name()), None => name.clone(), }; @@ -532,8 +541,15 @@ 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 @@ -1757,19 +1773,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`]. @@ -1896,8 +1917,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() @@ -2143,18 +2164,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.file.clone(), declaration.fact.clone())) + .collect(), + ); } } @@ -2170,7 +2193,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 @@ -2187,8 +2216,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); diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 687e2f8a..9d84f844 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -13,6 +13,21 @@ use crate::sema; use cpp_parser::CppSyntaxNode; use cpp_parser::token_at; +/// **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. /// /// # What it answers, and what it deliberately does not @@ -128,6 +143,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 +154,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 @@ -155,9 +174,12 @@ pub fn definition_across_files( .members .into_iter() .filter(|member| member.fact.name.as_str() == written.as_str()) - .map(|member| ProjectDefinition { - file: member.file, - fact: member.fact, + .filter_map(|member| { + let reference = index.fact_ref_matching(&member.file, &member.fact)?; + Some(ProjectDefinition { + file: reference.file, + fact: reference, + }) }) .collect(); if named.is_empty() { @@ -182,17 +204,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 +227,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()); } @@ -312,9 +336,12 @@ pub fn member_definitions_across_files( .members .iter() .filter(|member| member.fact.name == access.member) - .map(|member| ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + .filter_map(|member| { + let reference = index.fact_ref_matching(&member.file, &member.fact)?; + Some(ProjectDefinition { + file: reference.file, + fact: reference, + }) }) .collect(); @@ -377,6 +404,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 +452,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 +471,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 @@ -478,9 +515,12 @@ pub fn definitions_across_files( .members .into_iter() .filter(|member| member.fact.name == last) - .map(|member| ProjectDefinition { - file: member.file, - fact: member.fact, + .filter_map(|member| { + let reference = index.fact_ref_matching(&member.file, &member.fact)?; + Some(ProjectDefinition { + file: reference.file, + fact: reference, + }) }) .collect(); if !inherited.is_empty() { @@ -522,7 +562,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, diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 3f014e52..9f05f12f 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -114,14 +114,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 = index.type_spelling_of(&found.fact)?; + 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 @@ -780,13 +780,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 b9044baf..ebeda2c7 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -66,11 +66,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() ); } @@ -90,6 +90,20 @@ 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 crate::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 index interns a summary's type spellings once**, and two declarations of one type share the handle. /// /// The string fields are still the source a query may read during the transition; this test pins the store's side @@ -296,8 +310,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.** @@ -375,8 +389,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:?}" @@ -576,7 +591,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] @@ -595,7 +610,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] @@ -637,12 +652,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. @@ -681,10 +696,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. // @@ -839,7 +854,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" @@ -886,8 +901,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] @@ -926,7 +941,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] @@ -938,7 +953,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)); } } @@ -954,7 +969,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] @@ -1085,14 +1100,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" ); } @@ -1132,6 +1148,7 @@ fn another_files_local_is_never_the_answer() { &root, Path::new("/p/main.cpp"), at(source, "helper();"), + &|at: usize| Some(at), ); assert!( @@ -1163,13 +1180,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] @@ -1201,9 +1219,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" ); @@ -1227,13 +1245,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] @@ -1257,13 +1276,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] @@ -1287,6 +1307,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!( @@ -1318,13 +1339,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"); } // ------------------------------------------------------------------------------------------- @@ -1337,24 +1359,51 @@ 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 fact = index + .definition_fact(&found) + .expect("the answer resolves through the index") + .clone(); + let file = index + .path_of(found.file) + .expect("the answer names a file the index holds") + .to_path_buf(); + Known::Yes(ProjectMember { + file, + fact, + substitution: None, + source_type_of_id: crate::index::types::TypeId::NONE, + source_returns_id: crate::index::types::TypeId::NONE, + declared_in: String::new(), + depth: 0, + ambiguous: false, + }) + } + Known::Unknown(reason) => Known::Unknown(reason), + Known::No => Known::No, + } } // ------------------------------------------------------------------------------------------- @@ -1503,7 +1552,7 @@ fn a_function_pointer_typedef_records_the_whole_type() { panic!("the alias is a fact") }; assert_eq!( - fact.fact.type_of.as_deref(), + the_fact(&index, &fact).type_of.as_deref(), Some("void (*)(int)"), "specifiers plus declarator minus the name" ); @@ -1514,7 +1563,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!( + the_fact(&index, &fact).type_of.as_deref(), + Some("basic_string") + ); let _ = (root, tree); } @@ -1530,11 +1582,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!( + the_fact(&index, &z).type_of.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!( + the_fact(&index, &w).type_of.as_deref(), + Some("double _Complex") + ); } #[test] @@ -1650,8 +1708,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] @@ -2056,8 +2114,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] @@ -2121,12 +2179,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")); } // ------------------------------------------------------------------------------------------- @@ -2236,17 +2295,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] @@ -2266,17 +2326,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] 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 0718dfcb..3c39fab1 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -1657,11 +1657,12 @@ 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) = index.type_spelling_of(&found.fact) + && let Some(found) = index.definition_fact(&found) + && found.kind == DeclKind::Type + && let Some(target) = index.type_spelling_of(found) { let written = sema::builtins::split_arguments(inside); - let target = sema::types::substituted_spelling(target, found.fact.parameters(), &written); + let target = sema::types::substituted_spelling(target, found.parameters(), &written); if let Some(named) = parse_type_spelling(&target).class_name() { return Some(named.to_string()); } @@ -1669,7 +1670,7 @@ pub(crate) fn declared_class( 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, @@ -3488,10 +3489,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) + }) }) } @@ -3621,7 +3623,9 @@ pub(crate) fn declared_type( && 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)); } 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 f0b96ead..d4367bff 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -531,10 +531,12 @@ 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.** 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 6771da5e..d30f0b07 100644 --- a/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs +++ b/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs @@ -73,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( 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 843a9335..e459c6f9 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_return.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_return.rs @@ -168,7 +168,9 @@ 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; 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 56182535..b45de485 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 @@ -379,8 +379,12 @@ fn the_index_declares_one(context: &CheckContext<'_>, name: &str) -> Option, 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/undefined_name.rs b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs index 83804901..50be48cd 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs @@ -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; @@ -657,10 +661,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/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/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 038c5f04..60db5934 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -923,8 +923,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 +943,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 +984,11 @@ 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 = self.store.index().type_spelling_of(&alias.fact)?.trim(); + let target = self.store.index().type_spelling_of(alias_fact)?.trim(); if target.is_empty() || target == head.trim() { return None; } @@ -1031,8 +1034,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() @@ -1224,7 +1228,8 @@ 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) = self.store.index().type_spelling_of(&aliased.fact) + && let Some(aliased_fact) = self.store.index().definition_fact(&aliased) + && let Some(target) = self.store.index().type_spelling_of(aliased_fact) && target != spelled && depth <= 8 { @@ -1342,14 +1347,15 @@ impl Session { path: &Path, ) -> Option { let known = self.store.index().definition(head, path).value()?; - let written = self.store.index().type_spelling_of(&known.fact)?; - 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(), + known.parameters(), + known.parameter_defaults(), arguments, ); (target != head).then_some(target) @@ -1398,9 +1404,12 @@ impl Session { let Known::Yes(declared) = self.store.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, @@ -1417,7 +1426,7 @@ impl Session { // 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()); list.members.push(index::ProjectMember { - file: declared.file.clone(), + file: declared_in.clone(), fact, substitution: None, source_type_of_id: crate::index::types::TypeId::NONE, @@ -1541,9 +1550,12 @@ impl Session { return Known::Unknown(UnknownReason::Ambiguous(Box::from(written))); } + let Some(reference) = self.store.index().fact_ref_matching(&only.file, &only.fact) else { + return direct; + }; Known::Yes(ProjectDefinition { - file: only.file.clone(), - fact: only.fact.clone(), + file: reference.file, + fact: reference, }) } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index dfa01813..8d2cc9a8 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -723,8 +723,26 @@ impl Session { view: &FileView, offset: ReadingOffset, ) -> Option { + let member = self.member_row_of_the_enclosing_class(view, offset)?; + let reference = self + .store + .index() + .fact_ref_matching(&member.file, &member.fact)?; + Some(ProjectDefinition { + file: reference.file, + fact: reference, + }) + } + + /// **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, @@ -810,17 +828,18 @@ 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. - let fact_file = found.file.clone(); + // **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; @@ -831,7 +850,7 @@ impl Session { let parameter_types: Vec = self .store .index() - .parameter_facts_of(&fact_file, &fact) + .parameter_facts_of(&fact_file, fact) .iter() .filter_map(|parameter| { self.store @@ -866,30 +885,31 @@ 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_id() + let fact = self.definition_fact(&found)?; + fact.returns_id() .and_then(|id| self.store.index().types().materialize(id)) .map(|computed| computed.to_string()) .or_else(|| { self.store .index() - .returns_spelling_of(&found.fact) + .returns_spelling_of(fact) .map(str::to_string) }) }) .or_else(|| { local.and_then(|found| { + let fact = self.definition_fact(&found)?; self.store .index() - .returns_spelling_of(&found.fact) + .returns_spelling_of(fact) .map(str::to_string) }) }) 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/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index 63db4433..bee353c9 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -683,7 +683,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; @@ -694,8 +696,10 @@ fn constructor_parameter_names( if scope.rsplit("::").next().map(str::trim) != Some(name) { continue; } - let Some(names) = - parameter_names_of_fact(fact, index.parameter_facts_of(&declaration.file, fact)) + let Some(file) = index.definition_path(declaration) else { + continue; + }; + let Some(names) = parameter_names_of_fact(fact, index.parameter_facts_of(file, fact)) else { continue; }; diff --git a/crates/cpp_code_analysis/src/session/navigation.rs b/crates/cpp_code_analysis/src/session/navigation.rs index ce594861..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 { diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index d6bc7340..cc6db002 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -254,24 +254,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 - && self - .store - .index() - .type_spelling_of(&definition.fact) - .is_some() + index.definition_fact(definition).is_some_and(|fact| { + fact.kind == crate::DeclKind::Type && index.type_spelling_of(fact).is_some() + }) })?; - let target = self.store.index().type_spelling_of(&alias.fact)?; + 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(), + alias_fact.parameters(), + alias_fact.parameter_defaults(), &[], ); let target = substituted.trim(); @@ -302,6 +301,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( @@ -311,6 +316,7 @@ impl Session { &view.root, &view.path, offset.get(), + &to_file, ), }; let found = if matches!(found, Known::No | Known::Unknown(_)) { @@ -320,13 +326,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*.** // @@ -372,20 +379,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) = self.store.index().type_spelling_of(&found.fact) { + if let Some(target) = index.type_spelling_of(found_fact) { 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 !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()); } } } @@ -441,40 +453,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: crate::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. @@ -483,22 +521,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. @@ -537,7 +572,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 69f5ace4..a893d019 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -867,11 +867,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, @@ -1057,10 +1060,13 @@ fn denotes_a_function_pointer(index: &ProjectIndex, declaring: &Path, written: & 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) = index.type_spelling_of(&found.fact) else { + let Some(target) = index.type_spelling_of(found) else { return false; }; let target = target.to_string(); diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index f721707d..d8f49eaf 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -718,19 +718,25 @@ 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 facts = index.parameter_facts_of(&declaration.file, &declaration.fact); + let facts = index.parameter_facts_of(file, fact); if facts.is_empty() { continue; } @@ -761,8 +767,8 @@ fn constructors_in_the_index( 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..427aebcb 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" ); } @@ -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" ); 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..3bb9034a 100644 --- a/crates/cpp_code_analysis/src/session/tests/closure.rs +++ b/crates/cpp_code_analysis/src/session/tests/closure.rs @@ -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..25e32243 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:?}"), } diff --git a/crates/cpp_code_analysis/src/session/tests/types.rs b/crates/cpp_code_analysis/src/session/tests/types.rs index 9fecd802..78ee2698 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" @@ -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:?}" ); } @@ -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" @@ -637,8 +676,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" @@ -817,8 +866,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 +905,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 +987,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" ); 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/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/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/header_context.rs b/crates/cpp_code_analysis/tests/suite/header_context.rs index 6470ef86..d2b63ffd 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(), + fact.type_of.as_deref(), Some("colnr_T"), "the type the header writes" ); 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 e8d6d1af..f1f24fe8 100644 --- a/crates/cpp_code_analysis/tests/suite/reported_defects.rs +++ b/crates/cpp_code_analysis/tests/suite/reported_defects.rs @@ -787,8 +787,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(), + fact.returns.as_deref(), Some("std::vector"), "the local's declaration states the type the function returns" ); @@ -835,7 +838,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" ); 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..00a40259 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:?}"), } } @@ -1809,7 +1827,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`"), diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index e70d41f7..69ab0eef 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2702,7 +2702,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 +2721,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,7 +2741,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), "the condition picks the integral overload" ); @@ -2972,7 +2980,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) @@ -2989,7 +2997,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" ); @@ -3028,7 +3040,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) @@ -3045,7 +3057,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" ); @@ -3061,7 +3077,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" ); @@ -3108,7 +3128,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) @@ -3125,7 +3145,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" ); @@ -3166,7 +3190,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) @@ -3186,7 +3210,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" ); @@ -3201,7 +3229,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" ); diff --git a/crates/cpp_code_analysis/tests/suite/ue_engine.rs b/crates/cpp_code_analysis/tests/suite/ue_engine.rs index 912eac6d..4e431cb5 100644 --- a/crates/cpp_code_analysis/tests/suite/ue_engine.rs +++ b/crates/cpp_code_analysis/tests/suite/ue_engine.rs @@ -329,15 +329,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 +351,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:?}" ); } diff --git a/crates/cpp_inspect/src/questions.rs b/crates/cpp_inspect/src/questions.rs index d0fd23b5..617c19f4 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, } } @@ -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": fact.type_of, + "returns": fact.returns, + "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,11 @@ 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(), a_fact_and_what_it_says) )); } Known::Unknown(reason) => text.push_str(&format!(" picked unknown — {reason:?}\n")), @@ -229,7 +232,9 @@ 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(), a_fact_and_what_it_says) )); } if found.found.is_empty() { diff --git a/crates/cpp_ls/src/handlers/call_hierarchy/mod.rs b/crates/cpp_ls/src/handlers/call_hierarchy/mod.rs index 9617fc92..9513490d 100644 --- a/crates/cpp_ls/src/handlers/call_hierarchy/mod.rs +++ b/crates/cpp_ls/src/handlers/call_hierarchy/mod.rs @@ -100,7 +100,10 @@ pub async fn on_incoming_calls( let Known::Yes(defined) = session.definitions(&view, offset) else { return None; }; - let target = defined.found.first()?.fact.name.clone(); + let target = session + .definition_fact(defined.found.first()?)? + .name + .clone(); Some(incoming_calls_of(session, &view, offset.get(), &target)) }) .await @@ -138,11 +141,13 @@ pub fn item_at( 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. @@ -420,14 +425,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/definition/mod.rs b/crates/cpp_ls/src/handlers/definition/mod.rs index 108577cb..55b75641 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(); @@ -444,19 +447,27 @@ fn chosen_definition( let parameter_lists: Vec> = found .found .iter() - .map(|declaration| declaration.fact.parameter_list().map(str::to_string)) + .map(|declaration| { + session + .definition_fact(declaration) + .and_then(|fact| fact.parameter_list()) + .map(str::to_string) + }) .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() }) @@ -559,10 +570,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 e8f7aacd..26cfde2f 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -449,13 +449,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 +828,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.type_of.is_some() && let Some((member, alias)) = a_member_of_a_template_alias(view, offset) { card.push_str(&format!( @@ -851,8 +853,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 +879,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 +928,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 reference = session.index().fact_ref_matching(&row.file, &row.fact)?; + let found = ProjectDefinition { + file: reference.file, + fact: reference, + }; + Some(markdown(declaration_markdown_with( + session, + view, + &found, + Some(&row.fact), + 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,21 +1023,22 @@ 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.type_of.is_some()) })?; + 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 parameters: Vec = alias - .fact + let target = alias_fact.type_of.as_deref().unwrap_or("its target"); + let parameters: Vec = alias_fact .parameters() .iter() .map(ToString::to_string) .collect(); - let defaults: Vec = alias - .fact + let defaults: Vec = alias_fact .parameter_defaults() .iter() .map(ToString::to_string) @@ -1234,12 +1259,15 @@ fn member_markdown( .as_ref() .filter(|selected| selected.len() == 1) && let Some(member) = candidates.get(selected[0]) + && let Some(reference) = session + .index() + .fact_ref_matching(&member.file, &member.fact) { let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: reference.file, + fact: reference, }; - return declaration_markdown(session, view, &definition, None); + return declaration_markdown_with(session, view, &definition, Some(&member.fact), None); } // **Several can take the call, or the cursor is not on one** — print what the call can reach, or all of them. @@ -1281,12 +1309,15 @@ fn member_markdown( } if shown.len() == 1 && let Some(member) = shown.first() + && let Some(reference) = session + .index() + .fact_ref_matching(&member.file, &member.fact) { let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), + file: reference.file, + fact: reference, }; - return declaration_markdown(session, view, &definition, None); + return declaration_markdown_with(session, view, &definition, Some(&member.fact), None); } if shown.len() > 1 { let mut out = String::from("```cpp\n"); @@ -1346,11 +1377,22 @@ fn member_markdown( ); }; - let definition = ProjectDefinition { - file: member.file.clone(), - fact: member.fact.clone(), - }; - declaration_markdown(session, view, &definition, None) + match session + .index() + .fact_ref_matching(&member.file, &member.fact) + { + Some(reference) => { + let definition = ProjectDefinition { + file: reference.file, + fact: reference, + }; + declaration_markdown_with(session, view, &definition, Some(&member.fact), None) + } + None => format!( + "`{written}` has no member `{}`\n\n`{object}` is a `{written}`.", + access.member + ), + } } /// **Every declaration of one name**, as one popup — what a hover says about an overloaded function. @@ -1383,19 +1425,30 @@ fn overloads_markdown( let parameter_lists: Vec> = found .found .iter() - .map(|declaration| declaration.fact.parameter_list().map(str::to_string)) + .map(|declaration| { + session + .definition_fact(declaration) + .and_then(|fact| fact.parameter_list()) + .map(str::to_string) + }) .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() @@ -1434,15 +1487,21 @@ 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(), ) @@ -1453,7 +1512,7 @@ fn overloads_markdown( let mut line = a_line(&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 @@ -1461,10 +1520,9 @@ fn overloads_markdown( // into `Trait`. let names = sema::deduction::template_parameters_before( &text, - declaration.fact.name_range.start_offset, + declaration_fact.name_range.start_offset, ); - let (parameters, _) = declaration - .fact + let (parameters, _) = declaration_fact .parameter_list() .map(sema::overload::parameters_in) .unwrap_or_default(); @@ -1491,7 +1549,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(" ")) @@ -1533,18 +1594,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 { @@ -1987,6 +2051,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 @@ -2031,11 +2120,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. // @@ -2047,25 +2133,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.type_of.is_none() + && found_fact.returns.is_none() + && 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 @@ -2085,10 +2179,10 @@ fn declaration_markdown( && corrected.returns.is_none() && 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) @@ -2112,7 +2206,7 @@ fn declaration_markdown( && corrected.type_of.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), @@ -2130,7 +2224,7 @@ fn declaration_markdown( corrected.type_of = Some(deduced.into()); } if let Some(returns) = corrected.returns.clone() - && let Some(better) = the_type_the_macros_leave(session, &found.file, &corrected, &returns) + && let Some(better) = the_type_the_macros_leave(session, &found_file, &corrected, &returns) { corrected.returns = Some(better.into()); } @@ -2140,7 +2234,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() @@ -2217,13 +2311,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 @@ -2255,7 +2349,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 @@ -2263,8 +2357,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 @@ -2368,7 +2462,7 @@ fn declaration_markdown( .type_of .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), @@ -2392,7 +2486,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")); } @@ -2402,7 +2496,7 @@ fn declaration_markdown( where_clause( session, Some(view), - &found.file, + &found_file, fact.name_range.start_offset ) )); 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..1f4c43df 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() { @@ -1294,16 +1311,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..e27a904d 100644 --- a/crates/cpp_ls/src/handlers/type_definition/mod.rs +++ b/crates/cpp_ls/src/handlers/type_definition/mod.rs @@ -170,10 +170,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); } } @@ -199,10 +202,13 @@ fn declarations_of_a_type( 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); } } 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); } From 5a8e2437c0a174eb49d9fb495e0794171d864661 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 13:11:06 +0800 Subject: [PATCH 069/102] refactor(members): make ProjectMember a FactRef row ProjectMember now stores FactRef + per-member MemberSubstitution + declared_in/depth/ambiguous; no PathBuf, owned DeclFact, or source TypeIds. substituted_members only attaches/composes substitutions and never rewrites a fact. Members resolve through ProjectIndex::member_* and SemanticModel::computed_type_of_member. View-only and generated facts go through the index's synthetic/view fact tables; display materializes an owned fact only per answer. Full workspace tests (3595 passed) and clippy pass. Known gaps: synthesized view facts are interned for the session and synthetic facts are leaked (bounded by distinct generated/view declarations); member_display_fact still copies the text fields until Phase 3 removes them. --- .../src/index/project/aliases.rs | 13 +- .../src/index/project/calls.rs | 31 ++- .../src/index/project/completions.rs | 12 +- .../src/index/project/deductions.rs | 14 +- .../src/index/project/macro_environment.rs | 102 ++++++- .../src/index/project/macro_walk.rs | 234 +++++++++++++++- .../src/index/project/members.rs | 159 ++++++----- .../src/index/project/mod.rs | 45 +++ .../src/index/project/queries.rs | 33 +-- .../src/index/project/substituted.rs | 261 ++++++++++-------- .../src/index/project/tests.rs | 150 +++++++--- .../src/index/project/type_of.rs | 43 ++- .../sema/check/abstract_class_instantiated.rs | 17 +- .../src/sema/check/access_invisible.rs | 27 +- .../src/sema/check/argument_count.rs | 24 +- .../src/sema/check/assign_type_check.rs | 4 +- .../src/sema/check/final_hierarchy.rs | 10 +- .../src/sema/check/final_misplaced.rs | 6 +- .../cpp_code_analysis/src/sema/check/mod.rs | 5 +- .../src/sema/check/override_nonexistent.rs | 6 +- .../src/sema/check/param_type_check.rs | 6 +- .../sema/check/pure_virtual_not_overridden.rs | 20 +- .../src/sema/check/undefined_field.rs | 2 +- .../src/sema/check/undefined_name.rs | 2 +- .../src/sema/check/use_override.rs | 8 +- crates/cpp_code_analysis/src/sema/model.rs | 52 +++- crates/cpp_code_analysis/src/session/calls.rs | 111 ++++---- .../src/session/completion/mod.rs | 52 ++-- .../src/session/completion/request.rs | 89 +++--- .../src/session/definition.rs | 40 ++- crates/cpp_code_analysis/src/session/inlay.rs | 9 +- .../src/session/tests/buffers.rs | 4 +- .../src/session/tests/closure.rs | 4 +- .../src/session/tests/programs.rs | 2 +- .../src/session/tests/types.rs | 10 +- .../tests/suite/alias_members.rs | 4 +- .../cpp_code_analysis/tests/suite/checks.rs | 12 +- .../tests/suite/completion.rs | 32 +-- .../cpp_code_analysis/tests/suite/generics.rs | 15 +- .../tests/suite/reported_defects.rs | 18 +- crates/cpp_code_analysis/tests/suite/types.rs | 41 +-- .../tests/suite/ue_engine.rs | 20 +- crates/cpp_inspect/src/questions.rs | 51 ++-- crates/cpp_ls/src/handlers/hover/mod.rs | 96 ++++--- .../src/handlers/type_definition/mod.rs | 12 +- docs/type-system-redesign.md | 14 +- 46 files changed, 1283 insertions(+), 639 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index afc8235a..c110b263 100644 --- a/crates/cpp_code_analysis/src/index/project/aliases.rs +++ b/crates/cpp_code_analysis/src/index/project/aliases.rs @@ -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()) + .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); } @@ -933,8 +932,8 @@ 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; }; diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 3b78d7c0..b9e842a1 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -45,10 +45,17 @@ pub(crate) fn declaration_of_expression( // refused rather than answered with the parameter's spelling. if let Some(member) = 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(), )); } @@ -1127,10 +1134,14 @@ pub(crate) fn declaration_of_a_callee( Known::No | Known::Unknown(UnknownReason::NotDeclaredHere(_)) ) && let Some(member) = 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()), )); } @@ -1662,11 +1673,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(); diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index f8446074..f9f41a54 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -1324,14 +1324,18 @@ pub(crate) fn names_of_a_class( members .members .into_iter() - .map(|member| { + .filter_map(|member| { // 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); + // + // The candidate type still owns its `DeclFact` (it outlives the index borrow while the list is + // sorted), so the row is materialized here, at the edge. + let fact = index.member_fact(&member)?.clone(); + let file = index.member_path(&member)?.to_path_buf(); + let mut candidate = Candidate::new(file, fact, NameProvenance::Scope); candidate.steps = member.depth; - candidate + Some(candidate) }) .collect(), ), diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index fb882a56..fba8fcc7 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -807,9 +807,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 = index.type_spelling_of(&member.fact)?.to_string(); + let written = index.member_type_spelling(member)?; match &agreed { None => agreed = Some(written), Some(previous) if *previous == written => {} @@ -1521,12 +1522,11 @@ pub(crate) fn structured_binding_type( listed .members .iter() - .find(|member| member.fact.name == wanted && member.fact.kind == DeclKind::Variable) - .and_then(|member| { - index - .type_spelling_of(&member.fact) - .map(|target| target.to_string()) + .find(|member| { + index.member_name(member) == wanted + && index.member_kind(member) == Some(DeclKind::Variable) }) + .and_then(|member| index.member_type_spelling(member)) }); Some(match element { 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 f8706b24..b6fe40bc 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -41,11 +41,19 @@ impl DeclFactId { #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FactRef { pub file: crate::FileId, - /// `0` is the file's summary; `1..` is a cooked reading (see `Readings`). + /// `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. /// @@ -473,18 +481,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, - /// The declaration as the index stores it. Substitution is **not** written into it. - 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 **unsubstituted** type/return handles, kept for the computation layer. A substituted view clears the - /// handles inside its cloned fact, because those describe the old spelling; these still name the stored type. - pub source_type_of_id: TypeId, - pub source_returns_id: TypeId, /// 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 @@ -503,10 +514,81 @@ pub struct ProjectMember { pub ambiguous: bool, } -/// **One member's instantiation context**: the class template's parameters paired with this use's arguments. +/// **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 `DeclFact` keeps its parameter +/// list and type spellings as text until the type lowering lands, and the display layer has to substitute *those* +/// spellings too. 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)>, + /// 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. 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 288be3c9..13b3cae5 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -5,6 +5,7 @@ //! decided which branch was taken, and the order the files were included in. use super::*; +use crate::DeclModifiers; use crate::FactGuard; use crate::MacroKind; use crate::ProjectMember; @@ -13,7 +14,7 @@ use crate::Visibility; use crate::cache; use crate::index; use crate::index::params::{ParameterFact, ParamsStore}; -use crate::index::types::ComputedType; +use crate::index::types::{ComputedType, TypeId}; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -427,7 +428,12 @@ impl ProjectIndex { /// 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: crate::FileId) -> Option<&Path> { - let key = self.order.get(&(file.index() as u32))?; + let number = file.index() as u32; + let Some(key) = self.order.get(&number) else { + // **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. + return self.view_paths.lock().ok()?.by_id.get(&number).copied(); + }; match self.summaries.get(key) { Some(summary) => Some(summary.path.as_path()), None => Some(Path::new(key.as_str())), @@ -547,12 +553,63 @@ impl ProjectIndex { }); } } - None + // **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), + }) } /// **Resolve a `FactRef` to the immutable declaration.** The path is recovered from the index's sequence, /// never from the fact itself. 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()) + .copied(); + } let path = self.order.get(&(reference.file.index() as u32))?; let key = normalize(Path::new(path)); if reference.reading == 0 { @@ -569,6 +626,56 @@ impl ProjectIndex { .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 share one entry, so a query that regenerates the same member on every + /// keystroke does not grow the arena. + pub fn intern_synthetic_fact(&self, file: crate::FileId, fact: DeclFact) -> FactRef { + let mut arena = self + .synthetic_facts + .lock() + .expect("the synthetic fact arena is not poisoned"); + let at = match arena.iter().position(|held| **held == fact) { + Some(at) => at, + None => { + // **Leaked on purpose**, and bounded: `fact()` answers with a borrow, 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 generated members, + // not with its queries. + let leaked: &'static DeclFact = Box::leak(Box::new(fact)); + arena.push(leaked); + 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 it has no ordinary [`crate::FileId`]; the index mints one in the view table + /// ([`ProjectIndex::view_paths`]) and keeps the path with it, so the row still answers "which file" and "which + /// declaration". The fact is stored in the synthetic arena. 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) -> FactRef { + let file = { + let mut paths = self + .view_paths + .lock() + .expect("the view fact table is not poisoned"); + crate::FileId::new(paths.id_of(path)) + }; + self.intern_synthetic_fact(file, fact) + } + /// **The declaration a [`ProjectDefinition`] answers with.** pub fn definition_fact(&self, definition: &ProjectDefinition) -> Option<&DeclFact> { self.fact(definition.fact) @@ -588,6 +695,119 @@ impl ProjectIndex { )) } + /// **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) + } + + /// **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 stored handle materialized, then this row's + /// instantiation applied structurally. No spelling is parsed and no `TypeId` is interned. + pub fn member_computed_type(&self, member: &ProjectMember) -> Option { + let fact = self.member_fact(member)?; + let base = self.types.materialize(fact.type_of_id()?)?; + Some(match &member.substitution { + Some(substitution) => base.substituted(&substitution.bindings), + None => base, + }) + } + + /// **[`Self::member_returns_spelling`] in the computation layer** — the return type's stored handle 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.types.materialize(fact.returns_id()?)?; + Some(match &member.substitution { + Some(substitution) => base.substituted(&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. + 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_type_spelling(member).map(Into::into); + shown.returns = self.member_returns_spelling(member).map(Into::into); + // The handles describe the *unsubstituted* spelling and would lie beside a rewritten one. + shown.type_of_id = TypeId::NONE; + shown.returns_id = TypeId::NONE; + 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 its source summary. This is /// what a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. pub fn parameter_facts_at(&self, file: &Path, offset: usize) -> &[ParameterFact] { @@ -1420,8 +1640,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() @@ -1435,7 +1655,9 @@ 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::(); diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index fe3103b5..e3c7ad8d 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -223,38 +223,33 @@ pub(crate) fn a_member_row_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. + // members, so the row's substitution is the one a reader of this class sees. Some(member.clone()) } @@ -554,8 +549,10 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( _ => listed .members .iter() - .find(|member| !member.fact.parameters().is_empty()) - .map(|member| member.fact.parameters().to_vec())?, + .find_map(|member| { + let parameters = index.member_fact(member)?.parameters(); + (!parameters.is_empty()).then(|| parameters.to_vec()) + })?, }; if parameters.is_empty() { @@ -566,12 +563,12 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( 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. @@ -761,24 +758,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)) }); @@ -927,7 +927,7 @@ pub fn own_members_of( root: &CppSyntaxNode, path: &Path, class: &str, -) -> Known> { +) -> Known> { own_members_of_with( &sema::declarations::ShapeTable::new(), index, @@ -946,7 +946,7 @@ pub fn own_members_of_with( root: &CppSyntaxNode, path: &Path, class: &str, -) -> Known> { +) -> Known> { direct_members(shapes, index, scopes, root, path, class) } @@ -1104,8 +1104,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 @@ -1383,10 +1386,7 @@ 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, - source_type_of_id: fact.type_of_id, - source_returns_id: fact.returns_id, + .map(|fact| ProjectMember { fact, substitution: None, declared_in: class.to_string(), @@ -1394,17 +1394,21 @@ pub(crate) fn members_of_inner( 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 @@ -1565,10 +1569,7 @@ pub(crate) fn members_of_inner( let listed = MemberList { members: members .into_iter() - .map(|(file, fact)| ProjectMember { - file, - source_type_of_id: fact.type_of_id, - source_returns_id: fact.returns_id, + .map(|fact| ProjectMember { fact, substitution: None, declared_in: shown.clone(), @@ -1623,12 +1624,16 @@ 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| { + index + .member_name(one) + .cmp(index.member_name(other)) }); - found.sort_by(|one, other| one.fact.name.cmp(&other.fact.name)); - mark_ambiguity(&mut found); - hidden.extend(recorded_names(&found)); + mark_ambiguity(index, &mut found); + hidden.extend(recorded_names(index, &found)); list.members.extend(found); level = next; @@ -2037,7 +2042,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. @@ -2069,10 +2074,18 @@ 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. + let fact = fact_from_binding_with(shapes, root, class, binding); + match index.fact_ref_matching(path, &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, fact), + } }) .collect(), ); @@ -2103,10 +2116,11 @@ pub(crate) fn direct_members( data.bindings .iter() .map(|binding| { - ( - path.to_path_buf(), - fact_from_binding_with(shapes, root, &qualified, binding), - ) + let fact = fact_from_binding_with(shapes, root, &qualified, binding); + match index.fact_ref_matching(path, &fact) { + Some(reference) => reference, + None => index.intern_a_view_fact(path, fact), + } }) .collect(), ); @@ -2135,7 +2149,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(), ); } @@ -2175,7 +2189,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(), ); } @@ -2227,9 +2241,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(), ); } @@ -2282,10 +2294,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()) } @@ -2302,20 +2317,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 f35e4e7b..03bc35ac 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -559,6 +559,51 @@ 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 the one case — 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 only a configured Unreal project generates such members. + 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 + } } /// One entry of [`ProjectIndex::member_lists`]: the members, and **what the answer was made of**. diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 9d84f844..8ea3d20b 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -173,13 +173,10 @@ pub fn definition_across_files( let named: Vec = list .members .into_iter() - .filter(|member| member.fact.name.as_str() == written.as_str()) - .filter_map(|member| { - let reference = index.fact_ref_matching(&member.file, &member.fact)?; - Some(ProjectDefinition { - file: reference.file, - fact: reference, - }) + .filter(|member| index.member_name(member) == written.as_str()) + .map(|member| ProjectDefinition { + file: member.fact.file, + fact: member.fact, }) .collect(); if named.is_empty() { @@ -335,13 +332,10 @@ pub fn member_definitions_across_files( let found: Vec = members .members .iter() - .filter(|member| member.fact.name == access.member) - .filter_map(|member| { - let reference = index.fact_ref_matching(&member.file, &member.fact)?; - Some(ProjectDefinition { - file: reference.file, - fact: reference, - }) + .filter(|member| index.member_name(member) == access.member) + .map(|member| ProjectDefinition { + file: member.fact.file, + fact: member.fact, }) .collect(); @@ -514,13 +508,10 @@ pub fn definitions_across_files( let inherited: Vec = list .members .into_iter() - .filter(|member| member.fact.name == last) - .filter_map(|member| { - let reference = index.fact_ref_matching(&member.file, &member.fact)?; - Some(ProjectDefinition { - file: reference.file, - fact: reference, - }) + .filter(|member| index.member_name(member) == last) + .map(|member| ProjectDefinition { + file: member.fact.file, + fact: member.fact, }) .collect(); if !inherited.is_empty() { diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 9f05f12f..6a451752 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -4,16 +4,18 @@ //! `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, TypeId}; +use crate::index::types::ComputedType; use crate::sema; 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.** @@ -240,20 +242,6 @@ fn substituted_members_with( // 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); - // **The per-member substitution context** — parameter names paired with the structured arguments, not with - // re-parsed strings. It is carried beside the fact; the fact itself is never the owner of the substitution. - let substitution = prepared_type.map(|class| { - Arc::new(MemberSubstitution { - bindings: names - .iter() - .zip(class.arguments().iter()) - .map(|(name, argument)| (name.clone(), argument.clone())) - .collect(), - }) - }); - 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 @@ -267,131 +255,157 @@ fn substituted_members_with( // 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) = index.type_spelling_of(&member.fact).map(str::to_string) else { + 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) { + 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.as_str() == member.fact.name.as_str() { + 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)); } - // **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); + } + + let bindings: Vec<(SmolStr, ComputedType)> = prepared_type.map_or_else(Vec::new, |class| { + names + .iter() + .zip(class.arguments().iter()) + .map(|(name, argument)| (name.clone(), argument.clone())) + .collect() + }); + let substitution = MemberSubstitution { + 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) +} + +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(), + 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(&new.bindings))); + } + let mut stages = existing.stages.clone(); + stages.extend(new.stages.iter().cloned()); + MemberSubstitution { 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 - }; - // **The input list belongs to the index; the substituted list is a fresh view.** Each member's fact is cloned, - // rewritten, and any spelling-derived `TypeId` is cleared: the stored handle describes the *unsubstituted* - // spelling and would lie if it travelled with the rewritten one. No second `TypeStore` is created. - for member in list.members.iter_mut() { - if declares_an_alias(member) { - continue; - } - let mut fact = member.fact.clone(); - if !alias_names.is_empty() { - if let Some(spelling) = fact.detail_mut().parameter_list.as_mut() { - *spelling = through_the_aliases(spelling).into(); - } - if let Some(spelling) = fact.returns.as_mut() { - let next = through_the_aliases(spelling); - if next.as_str() != spelling.as_ref() { - *spelling = next.into(); - fact.returns_id = TypeId::NONE; - } - } - if let Some(spelling) = fact.type_of.as_mut() { - let next = through_the_aliases(spelling); - if next.as_str() != spelling.as_ref() { - *spelling = next.into(); - fact.type_of_id = TypeId::NONE; - } - } - } - member.fact = fact; } - for member in &mut list.members { - let mut fact = member.fact.clone(); - if let Some(spelling) = fact.detail_mut().parameter_list.as_mut() { - *spelling = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ) - .into(); - } - if let Some(spelling) = fact.returns.as_mut() { - let next = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ); - if next.as_str() != spelling.as_ref() { - *spelling = next.into(); - fact.returns_id = TypeId::NONE; - } - } - if let Some(spelling) = fact.type_of.as_mut() { - let next = sema::types::substituted_spelling_with_defaults( - spelling, &names, &defaults, &arguments, - ); - if next.as_str() != spelling.as_ref() { - *spelling = next.into(); - fact.type_of_id = TypeId::NONE; - } - } - member.fact = fact; - } - if let Some(substitution) = substitution { - for member in &mut list.members { - member.substitution = Some(Arc::clone(&substitution)); - } - } - Known::Yes(list) } /// **Split `std::vector` into its name and its arguments** — `("std::vector", ["int"])`. @@ -581,8 +595,8 @@ 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) + .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; @@ -603,10 +617,13 @@ 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) = index.type_spelling_of(&member.fact) else { + let Some(target) = index.type_spelling_of(fact) else { continue; }; if base_type_name(target) == base_type_name(class) { diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index ebeda2c7..e501c5ae 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -19,6 +19,7 @@ use super::name_completions_at; use super::{IncludeVisibility, ProjectIndex}; use crate::CompilerConfig; use crate::CookedFile; +use crate::DeclFact; use crate::DeclKind; use crate::FileIndexer; use crate::MacroDefinitions; @@ -37,7 +38,7 @@ use cpp_parser::CppSyntaxTree; use cpp_parser::LexerConfig; use cpp_parser::ParserConfig; 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. @@ -82,7 +83,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); } @@ -91,7 +92,7 @@ fn index(files: &[(&str, &str)]) -> ProjectIndex { } /// The declaration a definition answer resolves to, through the index that issued it. -fn the_fact<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a crate::DeclFact { +fn the_fact<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a DeclFact { index .definition_fact(definition) .expect("the answer resolves through the index") @@ -336,7 +337,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); @@ -1009,7 +1010,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); @@ -1077,7 +1078,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); @@ -1368,7 +1369,7 @@ fn member_of( 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); @@ -1382,24 +1383,14 @@ fn member_of( at(source, needle), ) { Known::Yes(found) => { - let fact = index - .definition_fact(&found) - .expect("the answer resolves through the index") - .clone(); - let file = index - .path_of(found.file) - .expect("the answer names a file the index holds") - .to_path_buf(); - Known::Yes(ProjectMember { - file, - fact, + let row = ProjectMember { + fact: found.fact, substitution: None, - source_type_of_id: crate::index::types::TypeId::NONE, - source_returns_id: crate::index::types::TypeId::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, @@ -2196,22 +2187,87 @@ 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, + 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 file = index + .member_path(&row) + .expect("a member row names a file the index holds") + .to_path_buf(); + ResolvedMember { + fact, + 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()) @@ -2485,7 +2541,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") @@ -2526,7 +2582,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('~')) @@ -2722,6 +2778,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")); @@ -2874,7 +2931,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:?}"), }; @@ -2884,7 +2941,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); @@ -2929,25 +2986,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: cpp_parser::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. @@ -3268,6 +3351,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, @@ -4296,7 +4380,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); @@ -4314,7 +4398,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)); 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 3c39fab1..ea676ff9 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -2293,22 +2293,23 @@ 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(Arc::from))?; + let found_fact = index.member_fact(found)?; + let returns = index + .member_returns_spelling(found) + .or_else(|| found_fact.returns_in_the_class().map(str::to_string))?; // **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->`, @@ -2438,21 +2439,33 @@ 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. 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 3e1e82e5..8a03d3f3 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 @@ -74,14 +74,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 d4367bff..987e171c 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -574,7 +574,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 (file, 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; } @@ -598,19 +604,19 @@ fn judge_a_member_call( members = list .members .iter() - .filter(|member| member.fact.name == access.member) + .filter(|member| context.index().member_name(member) == access.member) .filter_map(|member| { - let parameters = member.fact.parameter_list()?; - let indexed = context - .index() - .parameter_facts_of(&member.file, &member.fact); + let fact = context.index().member_fact(member)?; + let parameters = context.index().member_parameter_list(member)?; + let file = context.index().member_path(member)?; + let indexed = context.index().parameter_facts_of(file, fact); let facts = if indexed.is_empty() { - member.fact.parameter_facts() + fact.parameter_facts() } else { indexed }; - the_callee_in_facts(facts, context.index().types(), parameters) - .or_else(|| the_callee_in_text(parameters)) + the_callee_in_facts(facts, context.index().types(), ¶meters) + .or_else(|| the_callee_in_text(¶meters)) }) .collect(); } 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 e85ff61c..8dbf6c30 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 @@ -300,8 +300,8 @@ impl Check for AssignTypeCheck { let Some(declared) = members .members .iter() - .find(|found| found.fact.name.as_str() == name) - .and_then(|found| context.index().type_spelling_of(&found.fact)) + .find(|found| context.index().member_name(found) == name) + .and_then(|found| context.index().member_type_spelling(found)) else { continue; }; 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 d30f0b07..1c00a323 100644 --- a/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs +++ b/crates/cpp_code_analysis/src/sema/check/final_hierarchy.rs @@ -127,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 b9c2d84f..478d96d2 100644 --- a/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs +++ b/crates/cpp_code_analysis/src/sema/check/final_misplaced.rs @@ -116,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/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index 5555e935..27b1c360 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -1726,7 +1726,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** — 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 b45de485..f5d6e0d0 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 @@ -204,9 +204,9 @@ fn member_parameter_lists( }; 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| context.model.member_parameter_list(member)) + .map(|written| sema::overload::parameters_in(&written).0) .collect() } 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..f2230fc2 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,25 @@ 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/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 50be48cd..0f3390fc 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs @@ -652,7 +652,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; } 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..3b0aca5c 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,12 @@ 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/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index 957fadbf..b5981382 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -42,7 +42,6 @@ //! 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::FileView; use crate::completion; use crate::sema; @@ -170,21 +169,54 @@ 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 `TypeId` is interned. + /// instantiation bindings applied structurally. No spelling is parsed and no new `TypeId` is interned. pub fn computed_type_of_member(&self, member: &crate::ProjectMember) -> Option { - let id = member - .source_type_of_id - .is_none() - .then(|| member.fact.type_of_id()) - .flatten() - .unwrap_or(member.source_type_of_id); - let base = self.computed_type(id)?; + let fact = self.index.member_fact(member)?; + let base = self.computed_type(fact.type_of_id()?)?; Some(match &member.substitution { Some(substitution) => base.substituted(&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: &crate::ProjectMember) -> Option { + let fact = self.index.member_fact(member)?; + let base = self.computed_type(fact.returns_id()?)?; + Some(match &member.substitution { + Some(substitution) => base.substituted(&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 crate::ProjectMember) -> &'m str { + self.index.member_name(member) + } + + /// **A member's kind**, resolved through the index. + pub fn member_kind(&self, member: &crate::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: &crate::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: &crate::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: &crate::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. @@ -263,7 +295,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/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 60db5934..54d9538f 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -753,8 +753,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 +793,29 @@ 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) { continue; } - let Some(type_of) = self.store.index().type_spelling_of(fact) else { + let Some(type_of) = index.member_type_spelling(member) else { unknown.push(fact.name.to_string()); continue; }; @@ -840,12 +850,12 @@ impl Session { // `const l_signalT`, and with them unsized `CallInfo`, `lua_State::transferinfo`'s parents and finally // `lua_State` itself all withheld their layout. let measured = self - .the_size_of_a_type_in(view, type_of, depth, Some(&instantiation)) + .the_size_of_a_type_in(view, &type_of, depth, Some(&instantiation)) .or_else(|| { let expanded = self.the_type_with_its_macros_expanded( - &member.file, + index.member_path(member)?, fact.range.start_offset, - type_of, + &type_of, )?; if expanded == type_of { return None; @@ -1175,15 +1185,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) = self - .store - .index() - .type_spelling_of(&alias.fact) - .map(str::to_string) + && let Some(target) = self.store.index().member_type_spelling(alias) { return self.the_size_of_a_type_in(view, &target, depth + 1, instantiation); } @@ -1261,20 +1271,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 - && self - .store - .index() - .type_spelling_of(&candidate.fact) - .is_some() + index.member_name(candidate) == member + && index.member_kind(candidate) == Some(DeclKind::Type) + && index.member_type_spelling(candidate).is_some() })?; - let written = self.store.index().type_spelling_of(&alias.fact)?; + 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 @@ -1320,16 +1328,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 self.store.index().type_spelling_of(&alias.fact) { + match index.member_type_spelling(alias) { Some(target) => sema::types::substituted_spelling_with_defaults( - target, + &target, environment.parameters, environment.defaults, environment.arguments, @@ -1390,21 +1401,22 @@ 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 { + 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 @@ -1425,12 +1437,12 @@ impl Session { fact.type_of = Some(type_of.into()); // 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. + let reference = index.intern_synthetic_fact(declared.file, fact); list.members.push(index::ProjectMember { - file: declared_in.clone(), - fact, + fact: reference, substitution: None, - source_type_of_id: crate::index::types::TypeId::NONE, - source_returns_id: crate::index::types::TypeId::NONE, declared_in: class_name.to_string(), depth: 0, ambiguous: false, @@ -1535,7 +1547,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 @@ -1550,12 +1562,9 @@ impl Session { return Known::Unknown(UnknownReason::Ambiguous(Box::from(written))); } - let Some(reference) = self.store.index().fact_ref_matching(&only.file, &only.fact) else { - return direct; - }; Known::Yes(ProjectDefinition { - file: reference.file, - fact: reference, + file: only.fact.file, + fact: only.fact, }) } diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index f2544236..dc831515 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -969,7 +969,7 @@ fn the_element_type_pointed_at( }; let pointer_like = members.members.iter().any(|member| { matches!( - member.fact.name.as_str(), + index.member_name(member), "element_type" | "operator->" | "operator*" ) }); @@ -1272,7 +1272,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()); } @@ -1288,19 +1288,22 @@ 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, Some(index.types())); - 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, Some(index.types())); + item.kind = member_kind(index, member, &class); item.replace = replace; if member.depth > 0 { @@ -1334,7 +1337,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 { @@ -1348,7 +1351,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, @@ -1373,7 +1376,7 @@ fn members_of_a_type( } scored.push(Scored { - score: member_score(member, &class), + score: member_score(index, member, &class), matched, item, }); @@ -2296,15 +2299,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, } } @@ -2478,18 +2481,15 @@ fn name_score(offered: &OfferedName) -> Score { } /// 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) } diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 8d2cc9a8..9909f68e 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -678,17 +678,18 @@ impl Session { && let Some(member) = list .members .iter() - .find(|member| member.fact.name == access.member) - && let Some(spelled) = self + .find(|member| self.store.index().member_name(member) == access.member) + && let Some(file) = self .store .index() - .type_spelling_of(&member.fact) - .map(str::to_string) + .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(), + file, }); } // **A name alone is a declaration question, not a span.** A macro's name has no rendering counterpart at @@ -724,13 +725,9 @@ impl Session { offset: ReadingOffset, ) -> Option { let member = self.member_row_of_the_enclosing_class(view, offset)?; - let reference = self - .store - .index() - .fact_ref_matching(&member.file, &member.fact)?; Some(ProjectDefinition { - file: reference.file, - fact: reference, + file: member.fact.file, + fact: member.fact, }) } @@ -1012,11 +1009,12 @@ impl Session { let Known::Yes(list) = members else { return None; }; + let index = self.store.index(); let mut candidates: Vec<&index::project::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. @@ -1024,22 +1022,20 @@ 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 facts = self - .store - .index() - .parameter_facts_of(&member.file, &member.fact); + let Some(list) = index.member_parameter_list(member) else { + return false; + }; + let facts = index.parameter_facts_of( + index.member_path(member).unwrap_or(Path::new("")), + fact, + ); let types = if facts.is_empty() { - sema::overload::parameters_in(list).0 + sema::overload::parameters_in(&list).0 } else { - sema::overload::parameters_in_facts( - facts, - self.store.index().types(), - list.contains("..."), - ) - .0 + sema::overload::parameters_in_facts(facts, index.types(), list.contains("...")).0 }; let Some(written) = types.get(at) else { return false; @@ -1052,15 +1048,16 @@ impl Session { first = words.next().unwrap_or_default(); } let core = first.trim_end_matches(['&', '*']); - member - .fact - .parameters() + fact.parameters() .iter() .any(|parameter| parameter == 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() { @@ -1068,9 +1065,9 @@ impl Session { } // 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() + 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) { @@ -1078,33 +1075,39 @@ 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_of_fact( - &chosen.fact, - self.store - .index() - .parameter_facts_of(&chosen.file, &chosen.fact), + &chosen_fact, + index.parameter_facts_of(&chosen_file, &chosen_fact), )? .get(at) .cloned() .flatten()?; - let declaring = self.view_of_the_file(&chosen.file)?; + 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( @@ -1116,7 +1119,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); diff --git a/crates/cpp_code_analysis/src/session/definition.rs b/crates/cpp_code_analysis/src/session/definition.rs index f49946c9..3fce9b64 100644 --- a/crates/cpp_code_analysis/src/session/definition.rs +++ b/crates/cpp_code_analysis/src/session/definition.rs @@ -163,34 +163,42 @@ 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: self - .index() - .returns_spelling_of(&member.fact) - .map(str::to_string), + name: fact.name.to_string(), + returns: index.returns_spelling_of(fact).map(str::to_string), parameters, qualifiers, is_a_template: false, @@ -209,8 +217,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/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index bee353c9..c3c75ef2 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -578,12 +578,15 @@ fn callable_object_parameter_names( }; let mut best: Option>> = None; for member in &list.members { - if member.fact.name != "operator()" { + let Some(fact) = index.member_fact(member) else { + continue; + }; + if fact.name != "operator()" { continue; } let Some(names) = parameter_names_of_fact( - &member.fact, - index.parameter_facts_of(&member.file, &member.fact), + fact, + index.parameter_facts_of(index.member_path(member)?, fact), ) else { continue; }; diff --git a/crates/cpp_code_analysis/src/session/tests/buffers.rs b/crates/cpp_code_analysis/src/session/tests/buffers.rs index 427aebcb..397353c3 100644 --- a/crates/cpp_code_analysis/src/session/tests/buffers.rs +++ b/crates/cpp_code_analysis/src/session/tests/buffers.rs @@ -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"]); } diff --git a/crates/cpp_code_analysis/src/session/tests/closure.rs b/crates/cpp_code_analysis/src/session/tests/closure.rs index 3bb9034a..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::>() ); } diff --git a/crates/cpp_code_analysis/src/session/tests/programs.rs b/crates/cpp_code_analysis/src/session/tests/programs.rs index 25e32243..f16db55b 100644 --- a/crates/cpp_code_analysis/src/session/tests/programs.rs +++ b/crates/cpp_code_analysis/src/session/tests/programs.rs @@ -1194,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 78ee2698..ca3f20a4 100644 --- a/crates/cpp_code_analysis/src/session/tests/types.rs +++ b/crates/cpp_code_analysis/src/session/tests/types.rs @@ -282,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(); @@ -489,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", @@ -752,7 +752,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", @@ -821,7 +821,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", @@ -1016,7 +1016,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/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/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 29fd2dd7..9513ada0 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -2224,12 +2224,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(), + fact.type_of ); } } diff --git a/crates/cpp_code_analysis/tests/suite/completion.rs b/crates/cpp_code_analysis/tests/suite/completion.rs index 1cf1813a..7787389f 100644 --- a/crates/cpp_code_analysis/tests/suite/completion.rs +++ b/crates/cpp_code_analysis/tests/suite/completion.rs @@ -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:?}"), }; @@ -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!( @@ -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:?}"), @@ -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:?}"), @@ -1815,7 +1815,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 +1873,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 +1934,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 +2010,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 +2044,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 +2094,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 +2171,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 +2193,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 +2260,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 +2343,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 +2891,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/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/reported_defects.rs b/crates/cpp_code_analysis/tests/suite/reported_defects.rs index f1f24fe8..3e392cc0 100644 --- a/crates/cpp_code_analysis/tests/suite/reported_defects.rs +++ b/crates/cpp_code_analysis/tests/suite/reported_defects.rs @@ -353,8 +353,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 +365,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,10 +596,10 @@ 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(), + session.index().member_returns_spelling(member).as_deref(), Some("Node *"), "the base's `T` is the class it was instantiated with: {member:?}" ); @@ -873,7 +877,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" diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 69ab0eef..a7d5dde1 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:?}"), @@ -2132,7 +2135,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:?}"), @@ -2204,7 +2207,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:?}"), }; @@ -2256,7 +2259,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 +2297,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 +2471,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 +2530,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:?}"), }; @@ -3854,7 +3857,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"), @@ -3898,7 +3901,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"), @@ -4292,11 +4295,11 @@ 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!( @@ -4364,12 +4367,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!( @@ -4412,7 +4415,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 4e431cb5..6d6bdf97 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,21 @@ 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. @@ -399,7 +405,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 617c19f4..bf82a53f 100644 --- a/crates/cpp_inspect/src/questions.rs +++ b/crates/cpp_inspect/src/questions.rs @@ -289,18 +289,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) => { @@ -316,19 +320,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(&shown), member.declared_in ) } diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 26cfde2f..d7370483 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -930,16 +930,16 @@ fn hover_of_the_program( Known::No | Known::Unknown(_) => { match session.member_row_of_the_enclosing_class(view, offset) { Some(row) => { - let reference = session.index().fact_ref_matching(&row.file, &row.fact)?; let found = ProjectDefinition { - file: reference.file, - fact: reference, + file: row.fact.file, + fact: row.fact, }; + let shown = session.index().member_display_fact(&row); Some(markdown(declaration_markdown_with( session, view, &found, - Some(&row.fact), + shown.as_ref(), None, ))) } @@ -1171,7 +1171,7 @@ fn member_markdown( if candidates .members .iter() - .any(|member| member.fact.name == access.member) + .any(|member| session.index().member_name(member) == access.member) { list = Some(candidates); break; @@ -1212,12 +1212,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 @@ -1228,17 +1228,22 @@ fn member_markdown( .then(|| { let parameter_lists: Vec> = candidates .iter() - .map(|candidate| candidate.fact.parameter_list().map(str::to_string)) + .map(|candidate| session.index().member_parameter_list(candidate)) .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() @@ -1259,15 +1264,13 @@ fn member_markdown( .as_ref() .filter(|selected| selected.len() == 1) && let Some(member) = candidates.get(selected[0]) - && let Some(reference) = session - .index() - .fact_ref_matching(&member.file, &member.fact) { let definition = ProjectDefinition { - file: reference.file, - fact: reference, + file: member.fact.file, + fact: member.fact, }; - return declaration_markdown_with(session, view, &definition, Some(&member.fact), 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. @@ -1298,7 +1301,10 @@ 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 @@ -1309,26 +1315,33 @@ fn member_markdown( } if shown.len() == 1 && let Some(member) = shown.first() - && let Some(reference) = session - .index() - .fact_ref_matching(&member.file, &member.fact) { let definition = ProjectDefinition { - file: reference.file, - fact: reference, + file: member.fact.file, + fact: member.fact, }; - return declaration_markdown_with(session, view, &definition, Some(&member.fact), 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(&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!( @@ -1353,7 +1366,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 @@ -1377,22 +1390,12 @@ fn member_markdown( ); }; - match session - .index() - .fact_ref_matching(&member.file, &member.fact) - { - Some(reference) => { - let definition = ProjectDefinition { - file: reference.file, - fact: reference, - }; - declaration_markdown_with(session, view, &definition, Some(&member.fact), None) - } - None => format!( - "`{written}` has no member `{}`\n\n`{object}` is a `{written}`.", - access.member - ), - } + let definition = ProjectDefinition { + file: member.fact.file, + fact: member.fact, + }; + 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. @@ -2264,12 +2267,13 @@ fn declaration_markdown_with( && 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.returns.is_some() { - *fact = the_member.fact.clone(); + *fact = displayed; } let mut out = String::new(); diff --git a/crates/cpp_ls/src/handlers/type_definition/mod.rs b/crates/cpp_ls/src/handlers/type_definition/mod.rs index e27a904d..63e068ba 100644 --- a/crates/cpp_ls/src/handlers/type_definition/mod.rs +++ b/crates/cpp_ls/src/handlers/type_definition/mod.rs @@ -311,13 +311,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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 977b036d..2f0fc66d 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -78,6 +78,12 @@ struct FactRef { - 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 @@ -183,12 +189,18 @@ No spelling is parsed. ```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. +- 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. From 0c7d82f3fb7a2bb3391c49066c8f0dcd0b0cef3e Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 13:33:09 +0800 Subject: [PATCH 070/102] refactor(completion): make offered names FactRef rows OfferedName and Candidate now store FileId + FactRef; constructors mint references through the index (summary/cooked/view/synthetic arenas) and session completion resolves each row once for label/kind/detail. No completion row owns a PathBuf or DeclFact. Full workspace tests (3595 passed) and clippy pass. --- .../src/index/project/completions.rs | 260 ++++++++++++------ .../src/index/project/macro_walk.rs | 45 +++ .../src/index/project/mod.rs | 4 + .../src/index/project/tests.rs | 70 +++-- .../src/session/completion/mod.rs | 45 +-- .../tests/suite/completion.rs | 18 +- .../cpp_code_analysis/tests/suite/macros.rs | 4 +- 7 files changed, 302 insertions(+), 144 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index f9f41a54..bede5b39 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -213,10 +213,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: crate::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 +262,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 @@ -508,10 +534,18 @@ 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) { + Some(file) => index.intern_synthetic_fact(file, declaration), + None => index.intern_a_view_fact(written_in, declaration), + }; 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 +609,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 +633,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 +646,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 +672,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 +693,7 @@ pub(crate) fn visible_names( in_completion, )); - sort_and_hide(&mut names); + sort_and_hide(index, &mut names); Known::Yes(names) } @@ -677,10 +713,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 } @@ -776,7 +813,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(_) => { @@ -785,11 +822,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 @@ -857,7 +907,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 => {} } @@ -907,12 +957,12 @@ pub(crate) fn names_in_a_scope_at( _ => 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) } @@ -978,35 +1028,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 -/// -/// 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. +/// # Why it takes a fact rather than a row /// -/// 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: crate::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, @@ -1014,9 +1063,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, @@ -1077,20 +1128,43 @@ 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| { + .filter_map(|binding| { let mut fact = fact_from_binding(root, spelling, binding); 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 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), + }; + Some(Candidate::new(reference, NameProvenance::Scope)) }) .collect() } @@ -1109,7 +1183,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 @@ -1154,9 +1228,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, @@ -1189,8 +1264,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, @@ -1200,13 +1274,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)); } } } @@ -1226,8 +1303,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, @@ -1324,18 +1400,16 @@ pub(crate) fn names_of_a_class( members .members .into_iter() - .filter_map(|member| { + .map(|member| { // 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`. // - // The candidate type still owns its `DeclFact` (it outlives the index borrow while the list is - // sorted), so the row is materialized here, at the edge. - let fact = index.member_fact(&member)?.clone(); - let file = index.member_path(&member)?.to_path_buf(); - let mut candidate = Candidate::new(file, 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; - Some(candidate) + candidate }) .collect(), ), @@ -1350,16 +1424,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() } @@ -1414,15 +1499,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/macro_walk.rs b/crates/cpp_code_analysis/src/index/project/macro_walk.rs index 13b3cae5..dbe3a258 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -221,6 +221,7 @@ impl ProjectIndex { names.push(OwnedVisibleDeclaration { file: declaration.file, fact: declaration.fact.clone(), + reference: declaration.reference, visibility: declaration.visibility, }); } @@ -595,6 +596,27 @@ impl ProjectIndex { }) } + /// **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 from the index's sequence, /// never from the fact itself. pub fn fact(&self, reference: FactRef) -> Option<&DeclFact> { @@ -705,6 +727,29 @@ impl ProjectIndex { 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 { diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 03bc35ac..132ca897 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -660,6 +660,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/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index e501c5ae..28b4bb78 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -3560,30 +3560,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); @@ -3593,17 +3601,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:?}"), } @@ -3638,8 +3647,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"), @@ -3669,8 +3678,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"), @@ -3682,10 +3691,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" ); @@ -3707,7 +3716,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"); }; @@ -3728,10 +3738,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" ); @@ -3757,15 +3767,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:?}" @@ -3778,10 +3788,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", @@ -3821,9 +3831,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:?}" @@ -3837,8 +3847,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:?}" @@ -3851,14 +3861,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] @@ -3866,7 +3876,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(_))), @@ -3887,7 +3897,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:?}"); @@ -3895,7 +3905,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"), diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index dc831515..3c8dad80 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -1639,11 +1639,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(), }) @@ -1675,21 +1678,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, Some(index.types())); + let mut item = CompletionItem::declared(fact, file, Some(index.types())); item.replace = replace; // **What is being typed is the tail of the name.** Inside `std::` the reader writes `str` and means @@ -1697,7 +1707,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 @@ -1712,7 +1722,7 @@ fn names( } scored.push(Scored { - score: name_score(offered), + score: name_score(index, offered), matched, item, }); @@ -2456,7 +2466,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 { @@ -2470,12 +2482,9 @@ 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) } diff --git a/crates/cpp_code_analysis/tests/suite/completion.rs b/crates/cpp_code_analysis/tests/suite/completion.rs index 7787389f..4c9b8d46 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"); } @@ -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:?}"), }; @@ -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:?}"), }; @@ -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:?}"), }; 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(); From 85173385ebab5c0e73a212aabf50830fc7957d47 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 16:01:44 +0800 Subject: [PATCH 071/102] refactor(facts): remove the type strings from DeclFact DeclFact no longer stores type_of/returns spellings. Stored facts keep type_of_id/returns_id into the one global TypeStore; query-synthesized facts carry synthetic_type_of/synthetic_returns: Option> and keep IDs NONE, so there is no second store and no arena-tagged TypeId. ProjectIndex::computed_type_of/computed_returns_of prefer the synthetic value; type_spelling_of/returns_spelling_of print at the display edge. Codec drops per-fact spelling records (CODEC_VERSION 44); cooked readings carry a local TypeTable imported at insert (COOKED_VERSION 7, UNIT_CODEC_VERSION 6). Full workspace tests (3597 passed) and clippy pass. Remaining display/conversion string edges are documented in the design doc. --- crates/cpp_code_analysis/src/cache/summary.rs | 103 +++++---- .../src/cache/summary_codec.rs | 138 +++++++------ .../cpp_code_analysis/src/cache/unit_codec.rs | 16 +- crates/cpp_code_analysis/src/index/mod.rs | 18 +- .../src/index/project/aliases.rs | 12 +- .../src/index/project/bases.rs | 73 ++++--- .../src/index/project/calls.rs | 33 ++- .../src/index/project/completions.rs | 8 +- .../src/index/project/deductions.rs | 46 ++--- .../src/index/project/macro_environment.rs | 22 +- .../src/index/project/macro_walk.rs | 178 ++++++++++++---- .../src/index/project/member_facts.rs | 2 +- .../src/index/project/members.rs | 25 +-- .../src/index/project/mod.rs | 15 +- .../src/index/project/substituted.rs | 52 ++++- .../src/index/project/tests.rs | 37 ++-- .../src/index/project/type_of.rs | 195 +++++++++++------- crates/cpp_code_analysis/src/index/store.rs | 3 + .../src/index/types/compute.rs | 52 +++++ .../cpp_code_analysis/src/index/types/mod.rs | 115 ++++++++++- crates/cpp_code_analysis/src/lib.rs | 7 +- .../sema/check/abstract_class_instantiated.rs | 3 +- .../src/sema/check/assign_type_check.rs | 14 +- .../src/sema/check/missing_include.rs | 2 +- .../src/sema/check/missing_return.rs | 13 +- .../src/sema/check/redefinition.rs | 11 +- .../src/sema/check/unused.rs | 2 +- .../src/sema/declarations.rs | 191 ++++++++++++----- crates/cpp_code_analysis/src/sema/deduce.rs | 10 +- crates/cpp_code_analysis/src/sema/render.rs | 32 ++- crates/cpp_code_analysis/src/sema/types.rs | 133 +++++++++++- crates/cpp_code_analysis/src/session/calls.rs | 62 +++++- .../src/session/completion/mod.rs | 56 +++-- .../src/session/completion/request.rs | 4 +- crates/cpp_code_analysis/src/session/cook.rs | 26 ++- .../src/session/definition.rs | 4 +- .../cpp_code_analysis/src/session/queries.rs | 6 +- .../src/session/tests/types.rs | 17 +- .../cpp_code_analysis/tests/suite/checks.rs | 2 +- .../tests/suite/completion.rs | 8 +- .../tests/suite/conditional_environment.rs | 2 +- .../tests/suite/header_context.rs | 2 +- .../tests/suite/reported_defects.rs | 39 ++-- .../cpp_code_analysis/tests/suite/semantic.rs | 43 ++-- crates/cpp_inspect/src/questions.rs | 26 +-- .../cpp_ls/src/handlers/call_hierarchy/mod.rs | 5 +- crates/cpp_ls/src/handlers/completion/mod.rs | 10 +- crates/cpp_ls/src/handlers/hover/mod.rs | 156 ++++++++++---- 48 files changed, 1429 insertions(+), 600 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 58947565..df7fd7c0 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::condition; use crate::index; use crate::index::params::{ParameterFact, ParamsId, ParamsStore}; -use crate::index::types::{TypeId, TypeTable}; +use crate::index::types::{ComputedType, TypeId, TypeTable}; use crate::macros; use crate::paths; use crate::preprocess; @@ -221,7 +221,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**, in the index's interned [`TypeStore`]. /// /// 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 @@ -229,43 +229,41 @@ 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 store handle, not a spelling.** [`TypeStore`] keeps the source spelling beside the structure, so a + /// display edge can print what the file wrote and a computation edge can materialize a + /// [`ComputedType`] without parsing anything. /// * **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. + /// [`TypeId::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 same type in the index's interned store** — [`TypeId::NONE`] until the summary is inserted. /// - /// The string remains the transition field: a summary is built from syntax, and the store does not exist while - /// the parser is producing it. `ProjectIndex::insert_at` interns the spelling once and fills this handle; a - /// consumer that has the store uses it instead of parsing the string again. + /// [`TypeStore`]: crate::index::types::TypeStore pub type_of_id: TypeId, - /// 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. - /// - /// 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. + /// **A type that exists only in the computation layer**, for a fact that was *synthesized* — a view fact built + /// from a buffer the index has not read, a generated member, a substituted display copy. + /// + /// Such a fact has no [`TypeId`] to store: minting one would need a second `TypeStore`, and an ID from a second + /// store would silently alias the global one. It carries the computed value itself instead, parsed **once** at + /// the construction edge; every query reads it through [`crate::ProjectIndex::computed_type_of`], which checks + /// this field before materializing [`DeclFact::type_of_id`]. `None` for an ordinary stored fact, and + /// [`DeclFact::type_of_id`] is [`TypeId::NONE`] whenever this is `Some`. + pub synthetic_type_of: Option>, + /// The type a **function** returns, in the index's interned store; see [`DeclFact::type_of_id`]. + /// + /// 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>, - /// The same return type in the index's interned store; see [`DeclFact::type_of_id`]. + /// [`TypeId::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_id: TypeId, + /// The computation-layer return type of a **synthesized** fact; see [`DeclFact::synthetic_type_of`]. + pub synthetic_returns: Option>, /// The parameter-list handle in the summary's/global `ParamsStore`; `NONE` when there is no list. pub parameters: ParamsId, /// **Does the file's own text state this declaration's type across a directive?** @@ -273,7 +271,7 @@ pub struct DeclFact { /// `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_id`] are [`TypeId::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 @@ -484,11 +482,6 @@ fn on_the_heap_smol_option(text: &Option) -> usize { text.as_ref().map_or(0, on_the_heap) } -/// The bytes an optional shared string owns outside the `Option` that holds it. -fn on_the_heap_shared_option(text: &Option>) -> usize { - text.as_ref().map_or(0, |text| text.len()) -} - /// **The facts in one file, and how much of their storage is in [`DeclFact::detail`]** — the measurement a memory /// decision about the box needs. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -510,16 +503,39 @@ impl DeclarationAccounting { } impl DeclFact { - /// The interned form of [`DeclFact::type_of`], when the summary has been inserted into an index. + /// The interned form of [`DeclFact::type_of_id`], when the summary has been inserted into an index. pub fn type_of_id(&self) -> Option { (!self.type_of_id.is_none()).then_some(self.type_of_id) } - /// The interned form of [`DeclFact::returns`], when the summary has been inserted into an index. + /// The interned form of [`DeclFact::returns_id`], when the summary has been inserted into an index. pub fn returns_id(&self) -> Option { (!self.returns_id.is_none()).then_some(self.returns_id) } + /// **Does this fact carry a type at all** — stored or computed? A consumer deciding "is this a typedef" + /// asks this; one that wants the type itself asks [`crate::ProjectIndex::computed_type_of`]. + pub fn has_type_of(&self) -> bool { + self.type_of_id().is_some() || self.synthetic_type_of.is_some() + } + + /// Does this fact carry a return type, by the same rule as [`DeclFact::has_type_of`]? + pub fn has_returns(&self) -> bool { + self.returns_id().is_some() || self.synthetic_returns.is_some() + } + + /// **Take another fact's computed types**, for a display copy that was rebuilt from a second reading. + /// + /// The copy has no arena of its own, so it cannot keep the other fact's handles: they would index a table that + /// does not travel with it. It keeps the computed values instead, and clears the handles — the same shape a + /// synthesized fact has. + pub fn use_the_types_of(&mut self, other: &DeclFact) { + self.type_of_id = TypeId::NONE; + self.synthetic_type_of = other.synthetic_type_of.clone(); + self.returns_id = TypeId::NONE; + self.synthetic_returns = other.synthetic_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) @@ -1424,8 +1440,14 @@ impl DeclFact { size_of::() + on_the_heap(&self.name) + on_the_heap_smol_option(&self.scope) - + on_the_heap_shared_option(&self.type_of) - + on_the_heap_shared_option(&self.returns) + + self + .synthetic_type_of + .as_ref() + .map_or(0, |computed| computed.heap_bytes()) + + self + .synthetic_returns + .as_ref() + .map_or(0, |computed| computed.heap_bytes()) + self.detail_bytes() } } @@ -1468,8 +1490,9 @@ mod fact_size_tests { #[test] fn a_declaration_fact_stays_within_its_transition_budget() { - // **The four handles and the two shared strings are the transition shape.** The strings leave in Phase 4; - // until then the shared `Arc` keeps the fact well below two hundred bytes without cloning their payloads. + // **Two handles and two optional computed values are the current shape.** A stored fact pays eight bytes per + // handle; a synthesized fact pays a pointer to a shared `ComputedType` instead. 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", diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 07505d0d..ff176bcc 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -283,7 +283,15 @@ 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 = 43; +/// +/// # 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. +pub const CODEC_VERSION: u32 = 44; /// Write a summary as bytes. /// @@ -304,7 +312,7 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.declarations.len() as u32); for fact in &summary.declarations { - put_declaration(&mut out, fact, false); + put_declaration(&mut out, fact); } put_u32(&mut out, summary.macros.len() as u32); @@ -803,7 +811,7 @@ pub fn decode(bytes: &[u8]) -> Result { return Err(DecodeError::TrailingBytes); } - let mut summary = FileSummary { + Ok(FileSummary { path, key, declarations, @@ -815,27 +823,7 @@ pub fn decode(bytes: &[u8]) -> Result { macro_readings, use_filter, modules, - }; - restore_type_spellings(&mut summary); - Ok(summary) -} - -/// **Fill the facts' transition strings from the table the encoder wrote once.** A fact with a stored handle did not -/// carry its spelling in the record; the table entry did. This keeps the in-memory shape the rest of the crate reads -/// while the cache format stops duplicating the same string per declaration. -fn restore_type_spellings(summary: &mut FileSummary) { - for fact in &mut summary.declarations { - if fact.type_of.is_none() - && let Some(spelling) = summary.types.spelling_for(fact.type_of_id.raw()) - { - fact.type_of = Some(std::sync::Arc::from(spelling)); - } - if fact.returns.is_none() - && let Some(spelling) = summary.types.spelling_for(fact.returns_id.raw()) - { - fact.returns = Some(std::sync::Arc::from(spelling)); - } - } + }) } /// Why a byte stream is not a summary. @@ -1469,11 +1457,11 @@ 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_id: TypeId::NONE, + synthetic_type_of: None, // A class returns nothing either, so `None` — and the second fact below covers the other value. - returns: None, returns_id: TypeId::NONE, + synthetic_returns: None, parameters: crate::index::params::ParamsId::NONE, // 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. @@ -1533,10 +1521,11 @@ 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, type_of_id: TypeId::NONE, - returns: Some("ns::Container".into()), - returns_id: TypeId::NONE, + synthetic_type_of: None, + // The table's second node, so a fact's handle is part of what the round trip carries. + returns_id: TypeId::from_raw(1), + synthetic_returns: None, parameters: crate::index::params::ParamsId::NONE, // 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. @@ -1565,10 +1554,10 @@ mod tests { scope: None, kind: DeclKind::Other, modifiers: DeclModifiers::default(), - type_of: None, type_of_id: TypeId::NONE, - returns: None, + synthetic_type_of: None, returns_id: TypeId::NONE, + synthetic_returns: None, parameters: crate::index::params::ParamsId::NONE, access: None, exported: false, @@ -1824,26 +1813,13 @@ mod tests { /// **One writer, two records, on purpose.** A cooked reading's declarations are the same `DeclFact`s a summary /// holds; a second copy of these eighty lines would be a second place to add the next field to, and the failure it /// would produce is silent — a field written by one record and not the other, decoding as whatever follows it. -fn put_declaration(out: &mut Vec, fact: &DeclFact, skip_stored_spellings: bool) { +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)); - // **The type table already carries the spelling.** When the fact has a stored handle and this record includes - // the table, writing the string again is a duplicate the reader can reconstruct; a fact without a handle (a - // parser-built summary) still writes its spelling. - let type_of = if skip_stored_spellings && !fact.type_of_id.is_none() { - None - } else { - fact.type_of.as_deref() - }; - put_opt_str(out, type_of); + // **One handle per type, and no spelling** — the record's type table carries every spelling, and a fact that + // was synthesized has no handle to write (`NONE`) because it carries its computed type in memory only. put_u32(out, fact.type_of_id.raw()); - let returns = if skip_stored_spellings && !fact.returns_id.is_none() { - None - } else { - fact.returns.as_deref() - }; - put_opt_str(out, returns); put_u32(out, fact.returns_id.raw()); put_u32(out, fact.parameters.raw()); // **The spelling `returns` refused** — see [`DeclFact::returns_in_the_class`]. Written beside it because the two @@ -1930,9 +1906,7 @@ 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(std::sync::Arc::from); let type_of_id = TypeId::from_raw(reader.u32()?); - let returns = reader.optional_string()?; let returns_id = TypeId::from_raw(reader.u32()?); let parameters_id = crate::index::params::ParamsId::from_raw(reader.u32()?); let returns_in_the_class = reader.optional_string()?; @@ -1980,10 +1954,10 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { kind, modifiers, frees, - type_of, type_of_id, - returns: returns.map(std::sync::Arc::from), + synthetic_type_of: None, returns_id, + synthetic_returns: None, parameters: parameters_id, split_by_a_directive, range, @@ -2066,7 +2040,16 @@ 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. +const COOKED_VERSION: u32 = 7; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -2123,7 +2106,7 @@ pub fn encode_the_cooked_record( fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { put_u32(out, reading.declarations.len() as u32); for fact in &reading.declarations { - put_declaration(out, fact, false); + put_declaration(out, fact); } put_u32(out, reading.macros.len() as u32); for fact in &reading.macros { @@ -2135,6 +2118,10 @@ fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { put_str(out, &diagnostic.message); } put_u32(out, reading.unplaced as u32); + // **The reading's local type table**, for the same reason a summary writes one: the facts hold handles, and + // `ProjectIndex::insert_cooked` imports this table into the index's one store. A reading with no types writes an + // empty table, which is what a decoded reading from a caller that built one by hand has too. + put_type_table(out, &reading.types); } /// **One token of a rendering, with where it came from.** The origin is the half a `view` needs for navigation: @@ -2217,8 +2204,11 @@ pub fn decode_the_cooked_record( }); } let unplaced = reader.u32()? as usize; + // The reading's local type table, written by [`put_cooked_body`] before the optional rendering. + let types = get_type_table(&mut reader)?; let reading = CookedFile { declarations, + types, macros, diagnostics, unplaced, @@ -2313,16 +2303,32 @@ fn get_origin(reader: &mut Reader<'_>) -> Result Result { path, CookedFile { declarations: summary.declarations, + types: summary.types, macros: summary.macros, diagnostics, unplaced, }, - )); - } + )); } let unplaced = reader.u32()? as usize; let tokens = reader.u32()? as usize; @@ -488,7 +495,7 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { path: path.to_path_buf(), key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), - types: crate::index::types::TypeTable::default(), + types: cooked.types.clone(), parameters: crate::index::params::ParamsStore::default(), macros: cooked.macros.clone(), includes: Vec::new(), @@ -513,6 +520,7 @@ mod index_tests { PathBuf::from("/p/a.h"), CookedFile { declarations: Vec::new(), + types: crate::index::types::TypeTable::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 60c3c8ce..377a3bc1 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -690,6 +690,7 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { file_what_was_found( summary.declarations, + &summary.types, &tree, stream, &mut files, @@ -1654,6 +1655,7 @@ fn is_one_parenthesised_group(tokens: &[cpp_parser::CppTokenKind]) -> bool { /// gone there is one parse of one stream, and every fact from it belongs to the file the fact was written in. fn file_what_was_found( declarations: Vec, + types: &TypeTable, tree: &CppSyntaxTree, stream: &RenderedUnit, files: &mut [(PathBuf, CookedFile)], @@ -1688,6 +1690,20 @@ fn file_what_was_found( } } + // **Each file's own slice of the unit's type table.** A declaration's handle indexes the *unit's* local table, + // because every file was read by the one parse; the table travels with the reading so that + // `ProjectIndex::insert_cooked` can rewrite the handles once, at the insertion edge (`CookedFile::types`). A + // per-file export keeps one header's record from carrying every other file's types, and `TypeTable::export` + // pulls in each node's children, so a fact's handle is resolvable from its own file's table alone. + for (_, cooked) in files.iter_mut() { + let ids: Vec<_> = cooked + .declarations + .iter() + .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .collect(); + cooked.types = types.export(ids); + } + // **A stream's parse error is the program's, not a file's — so it is counted, not placed.** // // The loop that stood here asked `stream.written_span(range)` and pushed the answer into the file the error's @@ -1700,7 +1716,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/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index c110b263..9265a0d6 100644 --- a/crates/cpp_code_analysis/src/index/project/aliases.rs +++ b/crates/cpp_code_analysis/src/index/project/aliases.rs @@ -265,7 +265,7 @@ pub(crate) fn a_spelling_through_the_aliases_in( // **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| { @@ -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, @@ -756,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; @@ -824,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 { @@ -940,7 +940,7 @@ pub(crate) fn the_element_type_of( 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 f4f9162c..f0f2ed9e 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -9,7 +9,7 @@ use crate::BindingKind; use crate::DeclKind; use crate::ScopeKind; use crate::ScopeTree; -use crate::index::types::TypeId; +use crate::index::types::{ComputedType, TypeId}; use crate::sema; use crate::summary; use cpp_parser::CppSyntaxNode; @@ -291,6 +291,37 @@ pub(crate) fn fact_from_binding_with( binding: &Binding, ) -> DeclFact { let _ = root; + // **The two types this path can state, and the one place their spellings exist.** This builder has no + // `TypeStore` — it runs on the query side, against a buffer — so it converts the written spelling **once** into + // the computation layer and stores the value on the fact. No second store is minted, no `TypeId` is invented, and + // no consumer parses the spelling again. + 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 computed = |written: Option| { + written.map(|written| { + let parsed = parse_type_spelling(&written); + let parsed = sema::types::without_placeholders_written_as_names(parsed); + let parsed = sema::types::with_template_parameters(parsed, &template_parameters); + Arc::new(ComputedType::from(&parsed)) + }) + }; + let synthetic_type_of = computed(written_type_of); + let synthetic_returns = computed(written_returns.clone()); DeclFact { enumerator: binding.kind == BindingKind::Enumerator, split_by_a_directive: sema::declarations::split_by_a_directive_with(shapes, binding), @@ -332,34 +363,19 @@ 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(|written| Arc::from(written.as_str())), + // + // 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_id: TypeId::NONE, + synthetic_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. - type_of_id: TypeId::NONE, - returns: sema::declarations::declared_returns_of_in(shapes, root, binding) - .or_else(|| sema::declarations::declared_returns_of_with(shapes, binding)) - .map(|written| Arc::from(written.as_str())), returns_id: TypeId::NONE, + synthetic_returns, parameters: crate::index::params::ParamsId::NONE, // **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`]. @@ -371,9 +387,7 @@ 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 written_returns.is_some() { None } else { sema::declarations::the_returns_the_class_has_to_resolve(shapes, root, binding) @@ -391,10 +405,7 @@ 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) - .into_iter() - .map(SmolStr::from) - .collect(), + parameters: template_parameters.iter().cloned().map(SmolStr::from).collect(), constraints: 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. @@ -743,7 +754,7 @@ pub(crate) fn class_of_the_enclosing_definition( /// would also match `ns::Widget`, and [`matches`] honours it for exactly that reason. It is not a distinction for /// this walk, because the walk does not ask "which name space"; it asks for the qualified spelling the index keys /// on, and a global declaration's spelling is its bare name. Keeping the prefix made `::Widget w;` — the type -/// spelling a consumer hands over verbatim from `DeclFact.type_of` — fail to find a class sitting in the buffer. +/// spelling a consumer hands over verbatim from `DeclFact.type_of_id` — fail to find a class sitting in the buffer. /// **Where the `<` is that opens a template argument list running to the end of `written`.** /// /// `None` for a spelling with no such group — `outer::handle_type` ends with `type`, so its `<` belongs to a diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index b9e842a1..02eede33 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1776,41 +1776,34 @@ pub(crate) fn a_members_answer_as_a_type( let Some(name) = class_type.class_name().map(str::to_string) else { return returns.to_string(); }; + // **The alias's target is the declaration's computed type**, materialized rather than parsed. let Some(target) = index .files_declaring(&name, path) .into_iter() - .find(|declared| { - declared.fact.kind == DeclKind::Type - && index.type_spelling_of(declared.fact).is_some() - }) - .and_then(|declared| index.type_spelling_of(declared.fact).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)) else { break; }; - let resolved = parse_type_spelling(&target); - let Some(resolved_name) = resolved.class_name() else { + let Some(resolved_name) = target.class_name().map(str::to_string) 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()); + let qualified = qualified_from_the_index(index, path, &resolved_name) + .unwrap_or_else(|| resolved_name.clone()); if qualified == name { 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(", ")), - }); + let resolved = crate::index::types::ComputedType::named( + qualified, + target.arguments().to_vec(), + ) + .to_sema_type(); class_type = match class_type.is_const() && !resolved.is_const() { true => Type::Qualified { of: Arc::new(resolved), @@ -1867,7 +1860,7 @@ pub(crate) fn a_members_answer_as_a_type( return substituted; }; let target = - sema::types::substituted_spelling_with_defaults(target, ¶meters, &defaults, &arguments); + 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`. @@ -1959,7 +1952,7 @@ fn a_reference_resolved_through_its_value_type( }; let written = index.type_spelling_of(&fact)?; let value_type = - sema::types::substituted_spelling_with_defaults(written, parameters, defaults, arguments); + sema::types::substituted_spelling_with_defaults(&written, parameters, defaults, arguments); if value_type.trim().is_empty() || value_type.contains("::value_type") { return None; } diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index bede5b39..0b7040a1 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -153,7 +153,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) @@ -515,8 +515,10 @@ 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_id = crate::index::types::TypeId::NONE; + declaration.synthetic_type_of = None; + declaration.returns_id = crate::index::types::TypeId::NONE; + declaration.synthetic_returns = None; declaration.detail_mut().bases.clear(); declaration.detail_mut().parameters.clear(); declaration.local = false; diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index fba8fcc7..eed30b77 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -600,42 +600,35 @@ 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 = crate::index::types::ComputedType::from(&type_of); 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 - && index.type_spelling_of(declared.fact).is_some() + declared.fact.kind == DeclKind::Type && declared.fact.has_type_of() }) - .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string)); + .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 - .arguments() - .iter() - .map(|one| one.to_string()) - .collect(); + let alternatives: Vec = resolved.arguments().iter().map(ToString::to_string).collect(); (!alternatives.is_empty()).then_some(alternatives) } @@ -1367,21 +1360,18 @@ pub(crate) fn is_a_placeholder(written: &str) -> bool { ) } -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), + // **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()) + .map(|returns| returns.to_sema_type()), } } 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 b6fe40bc..4c86159d 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -376,7 +376,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() @@ -519,10 +519,10 @@ pub struct ProjectMember { /// /// 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 `DeclFact` keeps its parameter -/// list and type spellings as text until the type lowering lands, and the display layer has to substitute *those* -/// spellings too. Keeping it here is what lets the fact stay immutable: a substituted view is a row with this context -/// attached, not a rewritten declaration. +/// 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, @@ -671,10 +671,10 @@ fn fact_from_a_binding(binding: Binding, scope: Option, local: bool) -> // 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: None, type_of_id: TypeId::NONE, - returns: None, + synthetic_type_of: None, returns_id: TypeId::NONE, + synthetic_returns: None, parameters: crate::index::params::ParamsId::NONE, split_by_a_directive: false, // Same reason as `constraints` above: a clause is the declaration's text, and this shape is a match key. @@ -910,8 +910,10 @@ pub(crate) fn the_same_declaration(one: &DeclFact, other: &DeclFact) -> bool { && one.scope == other.scope && one.local == other.local && one.kind == other.kind - && one.type_of == other.type_of - && one.returns == other.returns + && one.type_of_id == other.type_of_id + && one.synthetic_type_of == other.synthetic_type_of + && one.returns_id == other.returns_id + && one.synthetic_returns == other.synthetic_returns && one.bases() == other.bases() && one.parameters() == other.parameters() && one.parameter_list() == other.parameter_list() @@ -948,7 +950,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 dbe3a258..6f20e13e 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -92,14 +92,16 @@ fn declaration_shape(summary: &FileSummary) -> u64 { the_walk_inputs_of(summary).hash(&mut hasher); for fact in summary.declarations.iter().filter(|fact| !fact.local) { format!( - "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", + "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", fact.enumerator, fact.name, fact.scope, fact.local, fact.kind, - fact.type_of, - fact.returns, + fact.type_of_id, + fact.synthetic_type_of, + fact.returns_id, + fact.synthetic_returns, fact.parameters(), fact.bases(), fact.pattern(), @@ -116,14 +118,16 @@ fn cooked_declaration_shape(declarations: &[DeclFact]) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); for fact in declarations.iter().filter(|fact| !fact.local) { format!( - "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", + "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", fact.enumerator, fact.name, fact.scope, fact.local, fact.kind, - fact.type_of, - fact.returns, + fact.type_of_id, + fact.synthetic_type_of, + fact.returns_id, + fact.synthetic_returns, fact.parameters(), fact.bases(), fact.pattern(), @@ -565,8 +569,10 @@ impl ProjectIndex { && 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.type_of_id == fact.type_of_id + && candidate.synthetic_type_of == fact.synthetic_type_of + && candidate.returns_id == fact.returns_id + && candidate.synthetic_returns == fact.synthetic_returns && candidate.requires_clause() == fact.requires_clause() && candidate.parameters() == fact.parameters() && candidate.modifiers == fact.modifiers @@ -793,22 +799,23 @@ impl ProjectIndex { Some(self.substituted_spelling_of(member, fact, &written)) } - /// **[`Self::member_type_spelling`] in the computation layer**: the stored handle materialized, then this row's - /// instantiation applied structurally. No spelling is parsed and no `TypeId` is interned. + /// **[`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 and no `TypeId` is interned. pub fn member_computed_type(&self, member: &ProjectMember) -> Option { let fact = self.member_fact(member)?; - let base = self.types.materialize(fact.type_of_id()?)?; + let base = self.computed_type_of(fact)?; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, }) } - /// **[`Self::member_returns_spelling`] in the computation layer** — the return type's stored handle with this - /// row's instantiation applied structurally. + /// **[`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.types.materialize(fact.returns_id()?)?; + let base = self.computed_returns_of(fact)?; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, @@ -822,17 +829,25 @@ impl ProjectIndex { /// 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 synthetic field, so a + /// consumer printing it goes through the same display edge as any other fact. No `TypeId` 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_type_spelling(member).map(Into::into); - shown.returns = self.member_returns_spelling(member).map(Into::into); - // The handles describe the *unsubstituted* spelling and would lie beside a rewritten one. shown.type_of_id = TypeId::NONE; + shown.synthetic_type_of = self + .member_computed_type(member) + .map(Arc::new); shown.returns_id = TypeId::NONE; + shown.synthetic_returns = self + .member_computed_returns(member) + .map(Arc::new); if let Some(parameters) = self.member_parameter_list(member) { shown.detail_mut().parameter_list = Some(parameters.into()); } @@ -866,34 +881,73 @@ impl ProjectIndex { .map_or(&[], |fact| summary.parameter_facts(fact)) } - /// **The written type spelling of a fact**, from its handle when the store has one and from the transition - /// string otherwise. Queries that need the spelling for an alias substitution or a display can start here, so - /// deleting the string field later does not require revisiting them. - pub fn type_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { - fact.type_of - .as_deref() - .or_else(|| fact.type_of_id().and_then(|id| self.types.spelling(id))) + /// **The written type spelling of a fact**, for a display consumer — an owned string produced at this edge. + /// + /// A synthesized fact answers its `ComputedType` printed; a stored fact answers the spelling the store recorded + /// for its handle (the file's own words), because that is the display form a reader is owed. If the store has a + /// node with no recorded spelling — a node a substitution synthesized — the materialized value is printed instead. + /// **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`]. + pub fn type_spelling_of(&self, fact: &DeclFact) -> Option { + if let Some(computed) = &fact.synthetic_type_of { + return Some(smol_str::SmolStr::new(computed.to_string())); + } + let id = fact.type_of_id()?; + let spelled = self + .types + .spelling(id) + .map(smol_str::SmolStr::new) + .or_else(|| { + self.types + .materialize(id) + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + })?; + Some(spelled) } /// The written return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. - pub fn returns_spelling_of<'a>(&'a self, fact: &'a DeclFact) -> Option<&'a str> { - fact.returns - .as_deref() - .or_else(|| fact.returns_id().and_then(|id| self.types.spelling(id))) + pub fn returns_spelling_of(&self, fact: &DeclFact) -> Option { + if let Some(computed) = &fact.synthetic_returns { + return Some(smol_str::SmolStr::new(computed.to_string())); + } + let id = fact.returns_id()?; + let spelled = self + .types + .spelling(id) + .map(smol_str::SmolStr::new) + .or_else(|| { + self.types + .materialize(id) + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + })?; + Some(spelled) } - /// **The computation-side type of a declaration's `type_of`**, when the fact has a storage handle. This is the - /// read-side bridge from [`DeclFact::type_of_id`] to [`ComputedType`]; it never interns. + /// **The computation-side type of a declaration's `type_of`.** A synthesized fact carries its value directly; + /// an ordinary fact's handle is materialized from the one global store. Neither path interns anything. pub fn computed_type_of(&self, fact: &DeclFact) -> Option { + if let Some(computed) = &fact.synthetic_type_of { + return Some((**computed).clone()); + } self.types.materialize(fact.type_of_id()?) } - /// **Intern every type spelling a summary carries, once**, before the summary is filed. Saves the string fields - /// from being parsed by every later query; a fact that already has a handle (a summary re-inserted from a store) - /// keeps it. + /// **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 { + if let Some(computed) = &fact.synthetic_returns { + return Some((**computed).clone()); + } + self.types.materialize(fact.returns_id()?) + } + + /// **Import every type a summary carries into the index's one store**, once, before the summary is filed. + /// + /// A summary built from syntax carries a local `TypeTable` — the IDs its facts hold are indices into that table, + /// not into this store. Importing rewrites them to this store's IDs, so a stored fact's handle can be resolved by + /// [`ProjectIndex::computed_type_of`] with no second store and no spelling in between. A summary read back from + /// the cache takes the same path; a synthesized fact carries no ID and is untouched. fn intern_the_types_of(&mut self, summary: &mut FileSummary) { - // **A summary read from the cache already has local handles.** Import its table first, rewrite the local - // IDs to this store's IDs, then fill only the facts the old format left without one. if !summary.types.is_empty() { let mapping = self.types.import(&summary.types); summary.parameters.remap_types(&mapping); @@ -920,14 +974,53 @@ impl ProjectIndex { let ids: Vec<_> = summary .declarations .iter() - .flat_map(|fact| { - let ids = vec![fact.type_of_id, fact.returns_id]; - ids - }) + .flat_map(|fact| [fact.type_of_id, fact.returns_id]) .collect(); summary.types = self.types.export(ids); } + /// **Import a cooked reading's types into the index's one store**, rewriting the facts' local IDs to store IDs. + /// + /// A cooked reading is built from a syntax pass of a whole translation unit, so its facts carry indices into + /// that pass's `TypeTable` exactly as a summary's do. The table travels with the reading (in memory and in the + /// cache record) and is imported here, at the moment the reading is filed — the same edge that binds a + /// summary's handles, so there is still one store that ever resolves a stored [`TypeId`]. + fn intern_the_types_of_a_reading(&mut self, reading: &mut CookedFile) { + if !reading.types.is_empty() { + let mapping = self.types.import(&reading.types); + for fact in &mut reading.declarations { + if !fact.type_of_id.is_none() + && let Some(store_id) = mapping.get(&(fact.type_of_id.index() as u32)) + { + fact.type_of_id = *store_id; + } + if !fact.returns_id.is_none() + && let Some(store_id) = mapping.get(&(fact.returns_id.index() as u32)) + { + fact.returns_id = *store_id; + } + if let Some(detail) = fact.detail.as_mut() { + for parameter in &mut detail.parameter_facts { + if let Some(store_id) = mapping.get(¶meter.type_of.raw()) { + parameter.type_of = *store_id; + } + } + } + } + } + // **The reading's table is rewritten alongside the handles**, exactly as a summary's is. Without this the + // stored reading would hold store handles beside a table in another ID space: harmless while nothing encoded + // it, but `Session::persist_cooked` writes the *live* reading, and the next session would decode that pair and + // resolve every handle through the wrong nodes. A re-import of this store-ID table is a no-op (hash-consing + // answers the same IDs), so a reading that is filed twice keeps meaning the same types. + let ids: Vec<_> = reading + .declarations + .iter() + .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .collect(); + reading.types = self.types.export(ids); + } + /// 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, @@ -1373,9 +1466,12 @@ impl ProjectIndex { &mut self, path: &Path, program: Option, - reading: CookedFile, + mut 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. + self.intern_the_types_of_a_reading(&mut reading); // **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 @@ -4259,7 +4355,7 @@ impl ProjectIndex { if alias.fact.kind != DeclKind::Type { return None; } - let target = parse_type_spelling(self.type_spelling_of(alias.fact)?); + 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_facts.rs b/crates/cpp_code_analysis/src/index/project/member_facts.rs index 773fd05c..0d9a1544 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -796,7 +796,7 @@ pub(crate) fn a_class_name_without_spaces(name: &str) -> String { /// /// # How an alias is recognised /// -/// In the buffer, by the binding's kind, which is exact. Through the index, by the rule [`DeclFact::type_of`] +/// In the buffer, by the binding's kind, which is exact. Through the index, by the rule [`DeclFact::type_of_id`] /// documents: a **type** fact with a `type_of` is an alias, and a class is a type fact without one. That is the /// whole of the test, and it is one test rather than a new field on purpose — the field was already there for /// variables, and what an alias *has* is a type in the same sense: the one it points at. diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index e3c7ad8d..316149d1 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, @@ -344,13 +344,7 @@ pub(crate) fn a_namespace_aliass_target( } let written = index .computed_type_of(found_fact) - .map(|computed| computed.to_string()) - .or_else(|| { - found_fact - .type_of - .clone() - .map(|written| written.to_string()) - })?; + .map(|computed| computed.to_string())?; if written.contains("::") || written.is_empty() { return Some(written); } @@ -625,12 +619,11 @@ pub(crate) fn the_pointee_of_a_handle( ) else { return None; }; - // **The fact's stored handle is converted, not parsed.** `parse_type_spelling` remains the fallback for a - // binding-built fact that predates the store; a fact from the index carries the structure already. + // **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) - .map(|computed| computed.to_sema_type()) - .or_else(|| index.type_spelling_of(&fact).map(parse_type_spelling))?; + .map(|computed| computed.to_sema_type())?; let bindings = member_bindings(index, scopes, root, path, class, arguments); let finished = bindings.applied_to(&written_type); // **A nested spelling is followed**, which is the ordinary shape in the standard library: `shared_ptr` inherits @@ -1288,7 +1281,7 @@ pub(crate) fn members_of_inner( // …>` kept `A`, so the trait matched no specialization and the wrong branch was taken. let with_arguments = class.to_string(); // The spelling is normalized once, at the entry, for the same reason a base's is: a consumer feeding this from - // `DeclFact.type_of` hands over what the file wrote — `const Widget&`, `::Widget`, `Base` — and every one + // `DeclFact.type_of_id` hands over what the file wrote — `const Widget&`, `::Widget`, `Base` — and every one // of those parts is about the type's shape rather than about which class declares the members. Normalizing // here also means `declared_in` is a qualified spelling from the first level on, and levels cannot disagree. // @@ -1931,7 +1924,7 @@ pub(crate) fn the_classes_a_base_clause_names( else { return Vec::new(); }; - let Some(target) = index.type_spelling_of(fact.fact).map(str::to_string) else { + let Some(target) = index.type_spelling_of(fact.fact) else { return Vec::new(); }; let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); @@ -1950,7 +1943,7 @@ pub(crate) fn the_classes_a_base_clause_names( if let Some(alias) = declared.iter().find(|declared| { declared.fact.kind == DeclKind::Type && index.type_spelling_of(declared.fact).is_some() }) { - let Some(target) = index.type_spelling_of(alias.fact).map(str::to_string) else { + let Some(target) = index.type_spelling_of(alias.fact) else { return Vec::new(); }; let substituted = diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 132ca897..41df5854 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -109,6 +109,14 @@ 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 local type table the declarations' handles index**, imported into the index's one global + /// [`crate::index::types::TypeStore`] when the reading is filed — see + /// [`crate::ProjectIndex::insert_cooked`]. + /// + /// The same contract a [`crate::FileSummary`]'s table has: a fact holds a local [`TypeId`], and the table travels + /// with it so the ID can be rewritten once at insertion. A reading built by hand (a test, a caller with facts and + /// no parse) leaves it empty and uses the facts' synthetic computed types instead. + pub types: crate::index::types::TypeTable, /// **The macros the rendering was read with** — and this is the half that answers a question the file's own /// reading cannot. /// @@ -142,6 +150,7 @@ impl CookedFile { pub fn declarations(declarations: Vec) -> Self { CookedFile { declarations, + types: crate::index::types::TypeTable::default(), macros: Vec::new(), diagnostics: Vec::new(), unplaced: 0, @@ -156,14 +165,15 @@ impl CookedFile { .iter() .map(DeclFact::heap_bytes) .sum::() + + self.types.heap_bytes() + 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 table their handles index**, 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 @@ -172,6 +182,7 @@ impl From for CookedFile { fn from(indexed: IndexedRendering) -> Self { CookedFile { declarations: indexed.summary.declarations, + types: indexed.summary.types, macros: indexed.summary.macros, diagnostics: indexed.diagnostics, unplaced: indexed.unplaced, diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 6a451752..3ace1de5 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -123,7 +123,7 @@ pub(crate) fn the_alias_behind( let target = index.type_spelling_of(found)?; let arguments = sema::builtins::split_arguments(inside); - let substituted = sema::types::substituted_spelling(target, found.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 @@ -210,10 +210,10 @@ fn substituted_members_with( .files_declaring(class, from) .into_iter() .find(|declared| { - declared.fact.kind == DeclKind::Type - && index.type_spelling_of(declared.fact).is_some() + declared.fact.kind == DeclKind::Type && declared.fact.has_type_of() }) - .and_then(|declared| index.type_spelling_of(declared.fact).map(str::to_string))?; + .and_then(|declared| index.computed_type_of(declared.fact)) + .map(|computed| computed.to_string())?; split_template_arguments(&target) }) else { return Known::Yes(list); @@ -248,7 +248,7 @@ fn substituted_members_with( // `_Tp → int` alone leaves the word `value_type`, which nothing in this layer can compare: measured on // `std::vector anotherVec; anotherVec.push_back("123131");`, the target stayed `const value_type&`, // `convertible_to(const char[7], const value_type&)` answered `Unknown`, and a check that cannot compare says - // nothing — the report. An alias's target is in its own fact (`DeclFact::type_of` is the target for an alias, + // nothing — the report. An alias's target is in its own fact (`DeclFact::type_of_id` is the target for an alias, // see `declared_alias_target`), and the aliases of *this* class are already in the list being substituted, // which is why no second lookup is needed. // @@ -306,13 +306,43 @@ fn substituted_members_with( return Known::Yes(list); } - let bindings: Vec<(SmolStr, ComputedType)> = prepared_type.map_or_else(Vec::new, |class| { - names + // `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(), argument.clone())) - .collect() - }); + .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(), ComputedType::from(&parsed))); + } + bindings + } + }; let substitution = MemberSubstitution { bindings, stages: vec![stage], @@ -604,7 +634,7 @@ pub(crate) fn an_element_type_through_the_members( 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() @@ -626,7 +656,7 @@ pub(crate) fn an_element_type_through_the_members( 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 diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 28b4bb78..8a8fcc78 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -160,9 +160,11 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { .find(|fact| fact.name == "items") .expect("the vector"); assert_eq!( - restored.type_of.as_deref(), + restored + .type_of_id() + .and_then(|id| decoded.types.spelling_for(id.raw())), Some("std::vector"), - "the decoder restores the spelling from the type table" + "the decoder restores the spelling from the type table through the fact's handle" ); let mut second = ProjectIndex::new(); @@ -1543,7 +1545,7 @@ fn a_function_pointer_typedef_records_the_whole_type() { panic!("the alias is a fact") }; assert_eq!( - the_fact(&index, &fact).type_of.as_deref(), + index.type_spelling_of(the_fact(&index, &fact)).as_deref(), Some("void (*)(int)"), "specifiers plus declarator minus the name" ); @@ -1555,7 +1557,7 @@ fn a_function_pointer_typedef_records_the_whole_type() { panic!("the alias is a fact") }; assert_eq!( - the_fact(&index, &fact).type_of.as_deref(), + index.type_spelling_of(the_fact(&index, &fact)).as_deref(), Some("basic_string") ); @@ -1574,14 +1576,14 @@ fn a_complex_type_keeps_the_adjective_in_its_spelling() { panic!("`z` is a declaration") }; assert_eq!( - the_fact(&index, &z).type_of.as_deref(), + 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!( - the_fact(&index, &w).type_of.as_deref(), + index.type_spelling_of(the_fact(&index, &w)).as_deref(), Some("double _Complex") ); } @@ -1605,7 +1607,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"); } } @@ -1745,7 +1747,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. @@ -2195,6 +2197,9 @@ fn a_local_declaration_still_wins_when_the_header_also_has_the_name() { #[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, @@ -2206,12 +2211,16 @@ impl 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, @@ -2461,7 +2470,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" ); @@ -2498,7 +2507,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" ); @@ -2523,7 +2532,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] @@ -2707,7 +2716,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" ); @@ -2804,7 +2813,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:?}" ); @@ -2885,7 +2894,7 @@ fn a_base_of_a_class_in_a_namespace_is_looked_up_in_that_namespace() { #[test] fn a_type_spelled_from_the_global_name_space_lists_the_same_members() { // `::Widget w;` is a declaration whose type spelling carries the leading `::`, and a consumer feeding this - // query from `DeclFact.type_of` therefore hands it `::Widget`. The index keys a global declaration under + // query from `DeclFact.type_of_id` therefore hands it `::Widget`. The index keys a global declaration under // its bare name — a file-scope declaration has no scope prefix — so the prefix has to come off before the // walk, or a class that is plainly in the buffer answers `Unknown(NotDeclaredHere("::Widget"))`. let source = "struct Widget {\n int size;\n};\nvoid f() {\n ::Widget w;\n}\n"; 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 ea676ff9..d018cb1e 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -16,6 +16,7 @@ use crate::ScopeTree; use crate::cache; use crate::completion; use crate::file; +use crate::index::types::{ComputedType, QualifiedType}; use crate::sema; use crate::symbol; use cpp_parser::CppSyntaxNode; @@ -53,15 +54,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 parser-facing type of a fact, from its stored handle when it has one.** This is the transition bridge for -/// the inference engine: a fact inserted into an index carries a `TypeId`, which is converted without parsing; a -/// binding-built fact has no store and still uses the spelling parser. The helper is the single place that decides -/// which path a fact takes, so the two cannot disagree about a type. +/// **The parser-facing type of a fact**, from its stored handle or its synthetic computed value. This is the +/// transition bridge for the inference engine: the fact's type is materialized once (no spelling, no store write) and +/// converted structurally to the shape the engine speaks. There is no spelling parse on this path. pub(crate) fn the_type_of_a_fact(index: &ProjectIndex, fact: &DeclFact) -> Option { index .computed_type_of(fact) .map(|computed| computed.to_sema_type()) - .or_else(|| index.type_spelling_of(fact).map(parse_type_spelling)) } /// **What an inference answer is a function of**, as one number: the file, the expression's range, its kind and its text. @@ -439,17 +438,14 @@ 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) = index.returns_spelling_of(declared.fact) - && !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.to_sema_type(), path.to_path_buf())); } return Known::Unknown(UnknownReason::UnknownType(Box::from(written))); } @@ -1554,7 +1550,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, @@ -1591,11 +1587,20 @@ 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. // - // `DeclFact::type_of` is what a declaration wrote *as a type of something else* — a variable's type, an + // `DeclFact::type_of_id` is what a declaration wrote *as a type of something else* — a variable's type, an // alias's target — and a class has none, so the `?` below returned `None` for the whole list the moment one // candidate was a class. Measured on the report that started this: `std::vector` is declared thirteen times // (the primary template, `vector`, the deduction guides), every one of them a class, and @@ -1605,16 +1610,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(), - _ => index.type_spelling_of(found.fact)?.to_string(), - }; + let type_of = the_type(found.fact)?; match &agreeing { None => agreeing = Some((found.fact.clone(), found.file.clone())), - Some((first, _)) if index.type_spelling_of(first) == 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, } } @@ -1659,11 +1659,25 @@ pub(crate) fn declared_class( && let Known::Yes(found) = index.definition(head.trim(), declaring) && let Some(found) = index.definition_fact(&found) && found.kind == DeclKind::Type - && let Some(target) = index.type_spelling_of(found) + && 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.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(), + ComputedType::from(&parse_type_spelling(argument)), + ) + }) + .collect(); + let target = target.substituted(&bindings); + if let Some(named) = target.class_name() { return Some(named.to_string()); } } @@ -1960,34 +1974,46 @@ pub(crate) fn operator_returns_of_with_arguments( let first = declared .iter() .find(|declared| declared.fact.kind == DeclKind::Type)?; - if let Some(target) = index.type_spelling_of(first.fact) { + 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 `Type`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(), ComputedType::from(argument))) + .collect(); + let target = if bindings.is_empty() { + target + } else { + target.substituted(&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()) { @@ -2003,21 +2029,21 @@ 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(named) => Some(ComputedType::named( + format!("{qualifier}::{bare}"), + named.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()) @@ -2030,7 +2056,7 @@ pub(crate) fn operator_returns_of_with_arguments( scopes, root, path, - candidate, + &candidate.to_sema_type(), operator, argument_types, argument_count, @@ -2361,10 +2387,10 @@ fn the_members_return( argument_types: &[Type], ) -> Option { let _ = (index, scopes, root, path); - let returns = fact - .returns - .clone() - .or(fact.returns_in_the_class().map(Arc::from)); + let returns = index + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) + .or_else(|| fact.returns_in_the_class().map(str::to_string)); if returns.as_deref().is_none_or(is_a_placeholder) && let Some(deduced) = deduced_returns_of_the_member( declaring, @@ -2679,7 +2705,7 @@ pub(crate) fn a_base_operators_return( name, None, ) - && let Some(target) = index.type_spelling_of(&alias).map(str::to_string) + && let Some(target) = index.type_spelling_of(&alias) { let substituted = sema::types::substituted_spelling(&target, ¶meters, &arguments); return Some(format!("{substituted}{suffix}")); @@ -2911,8 +2937,13 @@ impl NamedDeclaration { /// The type this declaration was written with. /// /// `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 { + /// [`DeclFact::type_of_id`] documents. + 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 @@ -2991,14 +3022,13 @@ impl NamedDeclaration { _ => 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.to_sema_type())) } } } @@ -3118,7 +3148,7 @@ 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( @@ -3573,7 +3603,10 @@ pub(crate) fn a_trait_alias_resolved( ) else { return None; }; - let target = index.type_spelling_of(&fact)?; + // **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() @@ -3583,9 +3616,27 @@ 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()), + ComputedType::from(&parse_type_spelling(&written)), + )); + } + } + Some(target.substituted(&bindings).to_sema_type()) } /// The type a declaration was written with — or, where it wrote `auto`, the type its **initializer** has. /// @@ -3629,7 +3680,7 @@ pub(crate) fn declared_type( // `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. @@ -3643,7 +3694,7 @@ pub(crate) fn declared_type( return Known::Yes(Type::named(scope)); } - let declaration = named.type_of(root, scopes); + let declaration = named.type_of(index, root, scopes); let Some(declaration) = declaration else { return Known::No; }; diff --git a/crates/cpp_code_analysis/src/index/store.rs b/crates/cpp_code_analysis/src/index/store.rs index 12919c6a..f96d8319 100644 --- a/crates/cpp_code_analysis/src/index/store.rs +++ b/crates/cpp_code_analysis/src/index/store.rs @@ -1297,6 +1297,9 @@ 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(), + // **The same local table the summary holds.** Both records index the same handles; each is imported into + // the index's one store at its own insertion edge, and hash-consing makes the two imports agree. + types: indexed.summary.types.clone(), macros: indexed.summary.macros.clone(), diagnostics: indexed.diagnostics, unplaced: indexed.unplaced, diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 1b62cdc0..68b8bd09 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -109,6 +109,58 @@ impl ComputedType { } } + /// **Is this the `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::Auto | ComputedType::DecltypeAuto => true, + 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(), + _ => 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 { + use std::mem::size_of; + let text = |name: &SmolStr| name.len(); + size_of::() + + match self { + ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => text(name), + ComputedType::Named(named) => { + size_of::() + + text(&named.name) + + named + .arguments + .iter() + .map(ComputedType::heap_bytes) + .sum::() + } + ComputedType::Auto | ComputedType::DecltypeAuto => 0, + ComputedType::Pointer(to) | ComputedType::Pack(to) => to.heap_bytes(), + ComputedType::Reference { to, .. } => to.heap_bytes(), + ComputedType::Array { 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() + } + } + } + /// **The parser-facing form**, for the transition period. This is a conversion, not a parse: the structure is /// already known and only its representation changes. Queries should prefer the `ComputedType` methods; this /// exists because the current type engine still speaks `sema::types::Type`. diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 10a0b206..15bf3174 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -267,7 +267,17 @@ impl TypeStore { /// **Convert the parser's type into the store.** Every child is interned first, so the graph is a DAG rather /// than a tree with repeated spellings. pub fn intern_type(&mut self, written: &Type) -> TypeId { - let spelling = written.to_string(); + self.intern_type_written_as(written, None) + } + + /// [`TypeStore::intern_type`] with **the source text kept as the node's display spelling**. + /// + /// A file writes `const char *` and a hover is owed those characters; rendering the parsed shape instead answers + /// `const char*`. The structure is the same either way, and only the top node's spelling is kept — children are + /// reached from the source spelling when it is printed, so the canonical spelling of each child is what a + /// synthesized child would show anyway. + fn intern_type_written_as(&mut self, written: &Type, source: Option<&str>) -> TypeId { + let spelling = source.map_or_else(|| written.to_string(), str::to_string); let kind = match written { Type::Builtin { spelling } if spelling.trim() == "auto" => TypeKind::Auto, Type::Builtin { spelling } if spelling.trim() == "decltype(auto)" => { @@ -343,10 +353,29 @@ impl TypeStore { } /// **The entry point for a spelling that came from outside the syntax** — a cache record, a CLI argument, a - /// test. Parsing remains one call, at this boundary; consumers below use [`TypeId`]. + /// test. Parsing remains one call, at this boundary; consumers below use [`TypeId`]. The spelling itself is kept + /// as the node's display value, so a caller that recorded `const char *` is shown those characters. pub fn intern_spelling(&mut self, spelling: &str) -> TypeId { let parsed = crate::sema::types::parse_type_spelling(spelling); - self.intern_type(&parsed) + let parsed = crate::sema::types::without_placeholders_written_as_names(parsed); + self.intern_type_written_as(&parsed, Some(spelling)) + } + + /// **Intern a type a declaration wrote**, with the declaration's own template parameter names marked as + /// [`TypeKind::TemplateParameter`], and the written spelling kept for display. + /// + /// The spelling is the file's, so this is a construction-edge parse — the one place the fact builder hands a + /// written type to the store. `parameters` is the fact's own template-parameter list: without it a member written + /// `T&` would be stored as a class *named* `T`, and instantiating the class would never substitute it. + pub fn intern_a_declared_type>( + &mut self, + spelling: &str, + parameters: &[N], + ) -> TypeId { + let parsed = crate::sema::types::parse_type_spelling(spelling); + let parsed = crate::sema::types::without_placeholders_written_as_names(parsed); + let parsed = crate::sema::types::with_template_parameters(parsed, parameters); + self.intern_type_written_as(&parsed, Some(spelling)) } /// The node a handle names, or `None` for a handle from a different store. @@ -661,6 +690,50 @@ impl TypeTable { .and_then(|entry| entry.spelling.as_deref()) } + /// **A self-contained table for the nodes reachable from `ids`.** Children are pulled in, so a decoder importing + /// the result can resolve every handle a fact holds; IDs keep their local values, because the importer builds its + /// own map from them. + /// + /// Used when one parse's table is split across the files it read: a cooked reading travels and is cached per + /// file, so each file's record carries only its own facts' types. + pub fn export(&self, ids: impl IntoIterator) -> TypeTable { + let by_id: FxHashMap = + self.entries.iter().map(|entry| (entry.id, entry)).collect(); + let mut seen = FxHashMap::::default(); + let mut pending: Vec = ids.into_iter().map(TypeId::raw).collect(); + let mut entries = Vec::new(); + while let Some(id) = pending.pop() { + if id == TypeId::NONE.raw() || seen.insert(id, ()).is_some() { + continue; + } + let Some(entry) = by_id.get(&id) else { + continue; + }; + match &entry.kind { + EncodedTypeKind::Named { arguments, .. } => pending.extend(arguments.iter().copied()), + EncodedTypeKind::Pointer(to) + | EncodedTypeKind::Pack(to) + | EncodedTypeKind::Qualified { of: to, .. } + | EncodedTypeKind::Reference { to, .. } + | EncodedTypeKind::Array { of: to, .. } => pending.push(*to), + EncodedTypeKind::Function { + returns, + parameters, + } => { + pending.push(*returns); + pending.extend(parameters.iter().copied()); + } + EncodedTypeKind::Builtin(_) + | EncodedTypeKind::TemplateParameter(_) + | EncodedTypeKind::Auto + | EncodedTypeKind::DecltypeAuto => {} + } + entries.push((*entry).clone()); + } + entries.sort_by_key(|entry| entry.id); + TypeTable { entries } + } + /// The encoded table's heap cost: entries, spelling strings, named and function argument vectors. pub fn heap_bytes(&self) -> usize { self.entries.len() * size_of::() @@ -857,6 +930,42 @@ mod tests { assert_eq!(store.len(), before, "materializing interned nothing"); } + #[test] + fn a_type_table_exports_the_nodes_one_fact_needs() { + // The unit read parses every file as one program and then splits the facts per file; each file's record has + // to carry the nodes its own handles reach, children included, and nothing else. + let mut store = TypeStore::new(); + let int = store.intern_spelling("int"); + let vector = store.intern_spelling("std::vector"); + let full = store.export([vector]); + assert_eq!(full.entries.len(), 2, "the node and its argument"); + + let subset = full.export([vector]); + assert_eq!( + subset.entries.len(), + 2, + "a subset by a parent still brings its children" + ); + let only_the_argument = full.export([int]); + assert_eq!(only_the_argument.entries.len(), 1); + assert_eq!(only_the_argument.entries[0].id, int.raw()); + } + + #[test] + fn a_declared_template_parameter_is_stored_as_one() { + // A fact's type is written by a declaration that also lists its template parameters; without that list a + // member's `const T&` is a class called `T` and instantiating the class would never substitute it. + let mut store = TypeStore::new(); + let written = store.intern_a_declared_type("const T&", &[SmolStr::new("T")]); + let computed = store.materialize(written).expect("materialized"); + assert_eq!(computed.to_string(), "const T&"); + let substituted = computed.substituted(&[( + SmolStr::new("T"), + ComputedType::Builtin(SmolStr::new("int")), + )]); + assert_eq!(substituted.to_string(), "const int&"); + } + #[test] fn a_type_table_round_trips_every_node_a_fact_needs() { let mut store = TypeStore::new(); diff --git a/crates/cpp_code_analysis/src/lib.rs b/crates/cpp_code_analysis/src/lib.rs index 4e7f0419..e268f4f3 100644 --- a/crates/cpp_code_analysis/src/lib.rs +++ b/crates/cpp_code_analysis/src/lib.rs @@ -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,7 +137,9 @@ 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`. 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 8a03d3f3..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(context.index().type_spelling_of(fact)?)?; + let spelled = context.index().type_spelling_of(fact)?; + let class = a_class_name(&spelled)?; Some((class, fact.name.to_string(), fact.name_range)) }) .collect(); 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 8dbf6c30..ff55126b 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 @@ -99,7 +99,7 @@ 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; @@ -107,7 +107,7 @@ impl Check for AssignTypeCheck { let Some(written) = context.index().type_spelling_of(fact) else { continue; }; - let written = (!is_a_deduced_auto(written)).then_some(written); + let written = (!is_a_deduced_auto(&written)).then_some(written); match declared.entry(fact.name.as_str()) { std::collections::hash_map::Entry::Vacant(entry) => { entry.insert(written); @@ -183,7 +183,7 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).copied() else { + let Some(Some(written)) = declared.get(name.as_str()).cloned() else { continue; }; @@ -211,7 +211,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, &written) { continue; } @@ -227,7 +227,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, &written, &name, "initialised"); } // **And the assignments**: `x = expr;`. Which object it is comes from the left-hand side being **a name and @@ -269,11 +269,11 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).copied() else { + let Some(Some(written)) = 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(), &written, &name, "assigned"); } // **A designated initialiser names the member it initialises**, so the question is *that member's* type: 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 02e936d6..a377beb6 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -18,7 +18,7 @@ //! //! Only **types a declaration spells**: the declared type of a variable, a field or a return value, and the types in a //! parameter list. That is where a missing include bites, and it is a position the file's own facts already record -//! (`DeclFact::type_of`, `DeclFact::parameter_list`) — so the rule costs no tree walk. +//! (`DeclFact::type_of_id`, `DeclFact::parameter_list`) — so the rule costs no tree walk. //! //! ```text //! reported Widget w; a type in a declaration 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 e459c6f9..848118a4 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_return.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_return.rs @@ -175,19 +175,22 @@ fn the_promise_of_a_name(context: &CheckContext<'_>, spelling: &str, depth: usiz if fact.kind != DeclKind::Type { return Promise::AValue; } - match context.index().type_spelling_of(fact).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/redefinition.rs b/crates/cpp_code_analysis/src/sema/check/redefinition.rs index 38a0dbe1..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) = context.index().returns_spelling_of(fact).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)); } } } diff --git a/crates/cpp_code_analysis/src/sema/check/unused.rs b/crates/cpp_code_analysis/src/sema/check/unused.rs index 5d673d7c..4516ff9a 100644 --- a/crates/cpp_code_analysis/src/sema/check/unused.rs +++ b/crates/cpp_code_analysis/src/sema/check/unused.rs @@ -78,7 +78,7 @@ fn its_type_cannot_have_a_destructor(context: &CheckContext<'_>, fact: &DeclFact context .index() .type_spelling_of(fact) - .is_some_and(undefined_name::is_a_builtin_spelling) + .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 { diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index eb1c79b3..a6e532ae 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -99,6 +99,32 @@ pub struct BuiltFacts { pub types: crate::index::types::TypeStore, } +/// **A freshly built fact set for a caller that keeps no store**: each type handle is materialized and kept as the +/// fact's computed value, and the handle is cleared. +/// +/// [`build_facts`] returns a **local** `TypeStore`; 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 handles on those facts would let a query resolve an index into a store that was +/// dropped — another store's `TypeId(3)` — so they are bound here, once, into the computation layer. +pub fn facts_with_their_types(built: BuiltFacts) -> Vec { + let BuiltFacts { + mut facts, types, .. + } = built; + for fact in &mut facts { + fact.synthetic_type_of = fact + .type_of_id() + .and_then(|id| types.materialize(id)) + .map(std::sync::Arc::new); + fact.synthetic_returns = fact + .returns_id() + .and_then(|id| types.materialize(id)) + .map(std::sync::Arc::new); + fact.type_of_id = TypeId::NONE; + fact.returns_id = TypeId::NONE; + } + facts +} + pub fn build_facts( scopes: &ScopeTree, preprocessing: &FilePreprocessing, @@ -111,20 +137,12 @@ pub fn build_facts( keep_locals: bool, ) -> BuiltFacts { let file = DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals); - let (mut facts, guards) = file.build(); + let (mut facts, guards, mut types) = file.build(); let mut parameters = crate::index::params::ParamsStore::new(); - let mut types = crate::index::types::TypeStore::new(); for fact in &mut facts { - if let Some(type_of) = fact.type_of.as_deref() - && !type_of.trim().is_empty() - { - fact.type_of_id = types.intern_spelling(type_of); - } - if let Some(returns) = fact.returns.as_deref() - && !returns.trim().is_empty() - { - fact.returns_id = types.intern_spelling(returns); - } + // The declaration's template parameters, so a parameter written `T&&` is stored as a parameter rather than a + // class called `T` — see [`TypeStore::intern_a_declared_type`]. + let template_parameters = fact.parameters().to_vec(); let Some(detail) = fact.detail.as_mut() else { continue; }; @@ -132,7 +150,8 @@ pub fn build_facts( if let Some(node) = parameter.declaration.to_node_from_root(root) && let Some(cpp) = CppParam::cast(node) { - parameter.type_of = types.intern_spelling(&cpp.get_type_text()); + parameter.type_of = + types.intern_a_declared_type(&cpp.get_type_text(), &template_parameters); } } if !detail.parameter_facts.is_empty() { @@ -171,7 +190,7 @@ pub fn build_facts( /// that the two cannot come to disagree about what `static const Widget` declares. /// /// `None` for a declaration that declares no type: a class, a namespace, a function, an alias. See -/// [`DeclFact::type_of`]. +/// [`DeclFact::type_of_id`]. pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option { declared_type_of_with(&DeclarationShapes::of(root), binding) } @@ -1401,7 +1420,7 @@ fn declared_namespace_alias_target_with(root: &CppSyntaxNode, binding: &Binding) /// whose answer goes into the *same* field as the first: a fact's `type_of` is "the type this declaration is /// about", which for a variable is the type it has and for an alias is the type it **points at**. An alias /// declares no members of its own, so a consumer that reads a name written as `std::string` has to be able to get -/// from it to `std::basic_string`, and this is where that spelling comes from. See [`DeclFact::type_of`] for the +/// from it to `std::basic_string`, and this is where that spelling comes from. See [`DeclFact::type_of_id`] for the /// rule that tells the two apart. /// /// # The two spellings a C++ alias comes in @@ -3935,6 +3954,10 @@ fn fact_for( // scope in the file per declaration. in_namespace: Option, declarations: &Declarations<'_>, + // **The summary's local type table.** A fact stores a handle, so the two spellings this declaration states are + // interned **once**, here, at the construction edge — never on a query. `ProjectIndex::insert_at` imports this + // table into the one global store and rewrites the handles; a query then materializes without parsing anything. + types: &mut crate::index::types::TypeStore, // 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 @@ -4126,6 +4149,25 @@ 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 type handles, interned at the construction edge.** The two spellings above are the only place this fact + // ever sees the text of a type; storing a handle here is what lets every later query materialize a + // `ComputedType` without parsing. An empty spelling means "no type to name", which is the handle `NONE` — the + // same answer as a declaration that declares no type. + let type_of_id = type_of.as_deref().map_or(TypeId::NONE, |spelling| { + if spelling.trim().is_empty() { + TypeId::NONE + } else { + types.intern_a_declared_type(spelling, ¶meters) + } + }); + let returns_id = returns.as_deref().map_or(TypeId::NONE, |spelling| { + if spelling.trim().is_empty() { + TypeId::NONE + } else { + types.intern_a_declared_type(spelling, ¶meters) + } + }); + 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 @@ -4148,10 +4190,10 @@ 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(std::sync::Arc::from), - type_of_id: TypeId::NONE, - returns: returns.map(std::sync::Arc::from), - returns_id: TypeId::NONE, + type_of_id, + synthetic_type_of: None, + returns_id, + synthetic_returns: None, parameters: crate::index::params::ParamsId::NONE, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { @@ -4784,6 +4826,10 @@ 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 type table**, filled by [`fact_for`] as each fact's spellings are interned. Returned + /// with the facts so that [`crate::FileIndexer::index_tree`] can put it in the summary and the index can import + /// it once, at insertion. + types: crate::index::types::TypeStore, // **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, @@ -4806,11 +4852,12 @@ impl<'a> DeclarationFacts<'a> { declarations: Declarations::of(root, errors), guards: SummaryGuards::default(), facts: Vec::new(), + types: crate::index::types::TypeStore::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) -> (Vec, SummaryGuards, crate::index::types::TypeStore) { + // 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, @@ -4821,6 +4868,7 @@ impl<'a> DeclarationFacts<'a> { declarations, mut guards, mut facts, + mut types, } = self; // per declaration copies the whole file each time. @@ -4899,6 +4947,7 @@ impl<'a> DeclarationFacts<'a> { local, in_namespace.clone(), &declarations, + &mut types, ) { facts.push(fact); } @@ -4967,6 +5016,7 @@ impl<'a> DeclarationFacts<'a> { false, None, &declarations, + &mut types, ) { // **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 @@ -5017,7 +5067,7 @@ 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) + (facts, guards, types) } } @@ -5810,7 +5860,7 @@ pub fn scope_of<'a>(scopes: &'a ScopeTree, fact: &DeclFact) -> Option<(ScopeId, /// /// 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 -/// parameters. Nothing tells it for a member of a class template: [`DeclFact::type_of`] is the `Display` +/// parameters. Nothing tells it for a member of a class template: [`DeclFact::type_of_id`] is the `Display` /// rendering of a `Type` — `_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**. /// @@ -5899,7 +5949,6 @@ 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::preprocess::preprocess; @@ -5952,7 +6001,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_id`] is the `Display` rendering of a `Type`, so /// `_Alloc` and a class named `_Alloc` are the same text, and `_Alloc::value_type` is a name no lookup can /// ever answer. /// @@ -6235,15 +6284,14 @@ mod tests { typedef basic_string B;\n\ typedef void (*F)(int);\n\ typedef int int32_t;\n"; - let (facts, _) = facts(source); + let (facts, _, types) = facts_and_types(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(&types, fact) }; assert_eq!(type_of("A").as_deref(), Some("basic_string")); @@ -6321,7 +6369,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); } @@ -6388,6 +6436,18 @@ int Box::Inner::deep = 0; } fn facts(source: &str) -> (Vec, summary::SummaryGuards) { + let (facts, guards, _) = facts_and_types(source); + (facts, guards) + } + + /// The same facts, with the local type table their handles index — what a test that prints a fact's type needs. + fn facts_and_types( + source: &str, + ) -> ( + Vec, + summary::SummaryGuards, + crate::index::types::TypeStore, + ) { let tree = CppParser::parse(source, ParserConfig::default()); assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); @@ -6399,7 +6459,36 @@ int Box::Inner::deep = 0; &[], true, ); - (built.facts, built.guards) + (built.facts, built.guards, built.types) + } + + /// **A fact's written type or return spelling**, from the local table — the display edge a consumer uses. + fn type_spelling_of( + types: &crate::index::types::TypeStore, + fact: &DeclFact, + ) -> Option { + spelled_at_the_edge(types, fact.type_of_id()) + } + + fn returns_spelling_of( + types: &crate::index::types::TypeStore, + fact: &DeclFact, + ) -> Option { + spelled_at_the_edge(types, fact.returns_id()) + } + + fn spelled_at_the_edge( + types: &crate::index::types::TypeStore, + id: Option, + ) -> Option { + let id = id?; + Some( + types + .spelling(id) + .map(str::to_string) + .or_else(|| types.materialize(id).map(|computed| computed.to_string())) + .unwrap_or_default(), + ) } /// **The memory report's detail numbers are computed from the box, not from the struct's width.** A function's @@ -6879,7 +6968,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 (facts, _, types) = facts_and_types( "Widget make();\n\ Widget w;\n\ struct C { Widget member(); };\n\ @@ -6899,21 +6988,27 @@ void f(int value); .find(|fact| fact.name == name) .unwrap_or_else(|| panic!("`{name}` is declared in the fixture")) }; + let type_of = |name: &str| type_spelling_of(&types, of(name)); + let returns_of = |name: &str| returns_spelling_of(&types, of(name)); // **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 (returning, _, returning_types) = { let source = "int (*maker(int a))(int b);\nvoid (*signal(int, void (*)(int)))(int);\n"; - tests::facts(source) + facts_and_types(source) }; for (name, expected) in [("maker", "int (*)(int b)"), ("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(&returning_types, fact).as_deref(), + Some(expected), + "`{name}` returns" + ); } - 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 @@ -6921,33 +7016,33 @@ 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(), + 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(), + type_of("through_pointer").as_deref(), Some("int (*)(int)"), "…and a pointer to function keeps its own shape" ); assert_eq!( - of("make").type_of, + type_of("make"), 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`" ); @@ -6957,23 +7052,23 @@ 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(), + 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 d137bf51..8bc05131 100644 --- a/crates/cpp_code_analysis/src/sema/deduce.rs +++ b/crates/cpp_code_analysis/src/sema/deduce.rs @@ -64,13 +64,19 @@ 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 index.returns_spelling_of(fact) == Some("auto") { + if index + .computed_returns_of(fact) + .is_some_and(|returns| matches!(returns, index::types::ComputedType::Auto)) + { return Known::Unknown(UnknownReason::UnknownType(Box::from( "a deduced return type — the return statements, not an initializer", ))); } - if index.type_spelling_of(fact) != Some("auto") { + if !index + .computed_type_of(fact) + .is_some_and(|type_of| matches!(type_of, index::types::ComputedType::Auto)) + { return Known::No; } diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index ac97484e..680899ac 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -214,17 +214,6 @@ fn without_comments(text: &str) -> String { } /// **The declaration's own line**, without a template head — what an overload list prints per declaration. -/// Transition wrapper for callers without a `TypeStore`; remove with the string fields. -pub fn a_line(fact: &DeclFact, syntax: Option<&CppDeclaration>, value: Option) -> String { - a_line_with( - fact, - syntax, - value, - &|fact| fact.type_of.as_deref().map(str::to_string), - &|fact| fact.returns.as_deref().map(str::to_string), - ) -} - pub fn a_line_with( fact: &DeclFact, syntax: Option<&CppDeclaration>, @@ -1052,14 +1041,15 @@ 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, - ) - .facts; + ); + let facts = built.facts; + let types = built.types; let fact = facts .iter() .find(|fact| fact.name == name) @@ -1072,8 +1062,16 @@ mod tests { fact, declaration.as_ref(), None, - &|fact| fact.type_of.as_deref().map(str::to_string), - &|fact| fact.returns.as_deref().map(str::to_string), + &|fact: &DeclFact| { + fact.type_of_id() + .and_then(|id| types.materialize(id)) + .map(|computed| computed.to_string()) + }, + &|fact: &DeclFact| { + fact.returns_id() + .and_then(|id| types.materialize(id)) + .map(|computed| computed.to_string()) + }, ) } @@ -1127,7 +1125,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!( diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 5bf0ac8c..77d4ade4 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -1097,8 +1097,8 @@ impl TypeBindings { /// Because two layers of this crate do not have the syntax, and cannot get it cheaply: /// /// ```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 declaration the index holds `DeclFact::type_of_id` is a handle into the global type store; the class it +/// names is materialized without a tree, because the declaring file need not be open /// a type written as a template arg `std::map` arrives as text inside a name node /// ``` /// @@ -1121,6 +1121,135 @@ impl TypeBindings { /// 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. +/// **`auto` and `decltype(auto)` are placeholders, not names.** +/// +/// [`parse_type_spelling`] has no context for them: `auto` is not one of the language's builtin words it knows, so a +/// spelling `auto&` becomes a reference to a class *named* `auto`. The storage layer has kinds for the placeholders +/// ([`crate::index::types::TypeKind::Auto`]), and `auto` is never a class a file can declare, so the name is rewritten +/// here before a fact's type is interned. This is the same normalization [`crate::index::types::TypeStore::intern_type`] +/// applies to a parser-built `Type::Builtin { spelling: "auto" }`. +pub fn without_placeholders_written_as_names(written: Type) -> Type { + match written { + Type::Named { name, arguments } if arguments.is_empty() && name.trim() == "auto" => { + Type::builtin("auto") + } + Type::Named { name, arguments } + if arguments.is_empty() && name.trim() == "decltype(auto)" => + { + Type::builtin("decltype(auto)") + } + // **`decltype(auto)` reads as a function type to the spelling parser** — it ends in `)`, and + // `split_trailing_parameters` sees `decltype` with one parameter, `auto`. It is the other placeholder, not a + // function, so the shape the parser produced is put back. + Type::Function { + returns, + parameters, + } if parameters.len() == 1 + && matches!(&*returns, Type::Builtin { spelling } if spelling.trim() == "decltype") + && matches!(¶meters[0], Type::Builtin { spelling } if spelling.trim() == "auto") => + { + Type::builtin("decltype(auto)") + } + Type::Named { name, arguments } => Type::Named { + name, + arguments: arguments + .into_iter() + .map(without_placeholders_written_as_names) + .collect(), + }, + Type::Pointer { to } => Type::Pointer { + to: Arc::new(without_placeholders_written_as_names((*to).clone())), + }, + Type::Reference { to, rvalue } => Type::Reference { + to: Arc::new(without_placeholders_written_as_names((*to).clone())), + rvalue, + }, + Type::Array { of, extent } => Type::Array { + of: Arc::new(without_placeholders_written_as_names((*of).clone())), + extent, + }, + Type::Function { + returns, + parameters, + } => Type::Function { + returns: Arc::new(without_placeholders_written_as_names((*returns).clone())), + parameters: parameters + .into_iter() + .map(without_placeholders_written_as_names) + .collect(), + }, + Type::Pack { of } => Type::Pack { + of: Arc::new(without_placeholders_written_as_names((*of).clone())), + }, + Type::Qualified { of, qualifiers } => Type::Qualified { + of: Arc::new(without_placeholders_written_as_names((*of).clone())), + qualifiers, + }, + builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, + } +} + +/// **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 +/// [`Type::substituted`] only replaces [`Type::TemplateParameter`] — so the names the declaration itself lists are +/// rewritten here, before the type is interned or converted to [`crate::index::types::ComputedType`]. +/// +/// 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: Type, parameters: &[N]) -> Type { + let names_a_parameter = + |name: &str| !parameters.is_empty() && parameters.iter().any(|one| one.as_ref() == name); + match written { + Type::Named { name, arguments } if arguments.is_empty() && names_a_parameter(&name) => { + Type::TemplateParameter { name } + } + Type::Named { name, arguments } => Type::Named { + name, + arguments: arguments + .into_iter() + .map(|argument| with_template_parameters(argument, parameters)) + .collect(), + }, + Type::Pointer { to } => Type::Pointer { + to: Arc::new(with_template_parameters_of(&to, parameters)), + }, + Type::Reference { to, rvalue } => Type::Reference { + to: Arc::new(with_template_parameters_of(&to, parameters)), + rvalue, + }, + Type::Array { of, extent } => Type::Array { + of: Arc::new(with_template_parameters_of(&of, parameters)), + extent, + }, + Type::Function { + returns, + parameters: written_parameters, + } => Type::Function { + returns: Arc::new(with_template_parameters_of(&returns, parameters)), + parameters: written_parameters + .into_iter() + .map(|parameter| with_template_parameters(parameter, parameters)) + .collect(), + }, + Type::Pack { of } => Type::Pack { + of: Arc::new(with_template_parameters_of(&of, parameters)), + }, + Type::Qualified { of, qualifiers } => Type::Qualified { + of: Arc::new(with_template_parameters_of(&of, parameters)), + qualifiers, + }, + builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, + } +} + +/// [`with_template_parameters`] through a shared child. +fn with_template_parameters_of>(written: &Type, parameters: &[N]) -> Type { + with_template_parameters(written.clone(), parameters) +} + pub fn parse_type_spelling(written: &str) -> Type { // **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 diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 54d9538f..596a6351 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -9,6 +9,7 @@ use crate::DeclModifiers; 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; @@ -102,7 +103,7 @@ fn a_scalar_layout(size: usize, alignment: usize) -> sema::layout::ClassLayout { /// **Split a trailing `[dimension]` from a type spelling**, or `None` when the spelling does not end in one. /// -/// The declarator's name is already gone — `DeclFact::type_of` holds a type, not a declaration — so the last bracket +/// The declarator's name is already gone — `DeclFact::type_of_id` holds a type, not a declaration — so the last bracket /// is the outermost array. A parenthesised declarator (`int (*table[3])(int)`) does not end in `]` and is left to the /// steps that can read it; a flexible array's dimension is empty, which the caller reads as zero extent. fn split_an_array_dimension(spelling: &str) -> Option<(&str, &str)> { @@ -548,7 +549,7 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).facts + 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. @@ -806,6 +807,22 @@ impl Session { .cmp(&right.fact.file) .then(at(left).cmp(&at(right))) }); + // **The written type of a member built from the buffer's own bindings.** Such a fact carries a + // `ComputedType` rather than a handle, and a rendered array whose extent is a macro or an enumerator prints as + // `int[]` — the dimension is an *expression*, not part of the type. Layout sizes that expression (needs its + // width), so it reads the member's writing back out of the view's tree, once per request. A fact from the + // index keeps the file's spelling in its store, so this is only for the asking file's own members. + let written_types = as_written.as_ref().and_then(|_| { + list.members + .iter() + .any(|member| { + index.member_fact(member).is_some_and(|fact| { + fact.synthetic_type_of.is_some() + && index.member_path(member) == Some(view.path.as_path()) + }) + }) + .then(|| sema::declarations::DeclarationShapes::of(&view.root)) + }); for member in own { let Some(fact) = index.member_fact(member) else { continue; @@ -819,6 +836,23 @@ impl Session { unknown.push(fact.name.to_string()); continue; }; + // **The spelling the file wrote**, for a member of the asking file — see `written_types`. + let type_of = match (&written_types, fact.synthetic_type_of.is_some()) { + (Some(shapes), true) if index.member_path(member) == Some(view.path.as_path()) => { + sema::resolve::definition_at( + &view.scopes, + &view.root, + fact.name_range.start_offset, + ) + .value() + .filter(|binding| binding.name.text() == fact.name.as_str()) + .and_then(|binding| { + sema::declarations::declared_type_of_with(shapes, &binding) + }) + .unwrap_or(type_of) + } + _ => type_of, + }; // **A bitfield's width is in the file's text, not in its fact.** It is read at the member's own file // offset, which is why the class was read out of its summary above: a member fact that came from a cooked // reading carries the rendering's offsets instead. A width that is not a literal (`: BITS`) stays @@ -998,7 +1032,8 @@ impl Session { if alias_fact.kind != DeclKind::Type { return None; } - let target = self.store.index().type_spelling_of(alias_fact)?.trim(); + let target = self.store.index().type_spelling_of(alias_fact)?; + let target = target.trim(); if target.is_empty() || target == head.trim() { return None; } @@ -1240,10 +1275,10 @@ impl Session { if let Known::Yes(aliased) = self.store.index().definition(spelled, &view.path) && let Some(aliased_fact) = self.store.index().definition_fact(&aliased) && let Some(target) = self.store.index().type_spelling_of(aliased_fact) - && target != spelled + && 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 { @@ -1364,7 +1399,7 @@ impl Session { return None; } let target = sema::types::substituted_spelling_with_defaults( - written, + &written, known.parameters(), known.parameter_defaults(), arguments, @@ -1434,7 +1469,18 @@ impl Session { 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_id = crate::index::types::TypeId::NONE; + fact.synthetic_type_of = Some(Arc::new( + crate::index::types::ComputedType::from( + &crate::sema::types::parse_type_spelling(&type_of), + ), + )); + fact.returns_id = crate::index::types::TypeId::NONE; + fact.synthetic_returns = 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 @@ -1595,7 +1641,7 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - let facts = build_facts(&view.scopes, &preprocessing, &view.root, &errors, true).facts; + 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 3c8dad80..f52aa55a 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -358,8 +358,8 @@ fn kind_of(kind: DeclKind) -> ItemKind { /// function whose declarator the reading could not reach. It says "this function takes something", which is less /// than the truth and not more. /// **The row's detail, preferring the stored type handles.** A completion is built from a summary that has been -/// inserted, so its type/return IDs are available; the spelling is the fallback for a binding-built fact and for -/// fields whose structure the old record still carries. +/// inserted, so its type/return IDs are available; a synthesized fact (a generated member, a display copy) carries its +/// computed value instead. Both are printed here, at the display edge — nothing is parsed. pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Option { let displayed = |id| { types.and_then(|types| { @@ -369,18 +369,17 @@ pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Optio .or_else(|| types.materialize(id).map(|computed| computed.to_string())) }) }; - // **The written spelling wins when it exists**, because it is what the reader sees in the declaration; the stored - // handle is the fallback for a record whose string field is gone. (The two must agree structurally, but `T *` and - // `T*` are different display forms and the completion row keeps the file's.) + // **The written spelling wins when it exists**, because it is what the reader sees in the declaration; a synthetic + // value is printed as its computed type. let returns = fact - .returns - .clone() + .synthetic_returns + .as_ref() .map(|returns| returns.to_string()) .or_else(|| fact.returns_id().and_then(displayed)); let type_of = fact - .type_of - .clone() - .map(|ty| ty.to_string()) + .synthetic_type_of + .as_ref() + .map(|type_of| type_of.to_string()) .or_else(|| fact.type_of_id().and_then(displayed)); match fact.kind { DeclKind::Function => match (returns, fact.parameter_list()) { @@ -397,22 +396,6 @@ pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Optio } } -pub fn detail_of(fact: &DeclFact) -> Option { - match fact.kind { - DeclKind::Function => match (&fact.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::Type if !fact.bases().is_empty() => { - Some(format!(": {}", fact.bases().join(", "))) - } - _ => None, - } -} - /// What a completion found: the items, in the order they should be shown, and **whether the answer is complete**. /// /// `Default` is written out rather than derived because [`SourceRange`] has no default of its own: a range of @@ -2594,7 +2577,10 @@ 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; + + let builtin = |name: &str| ComputedType::Builtin(name.into()); + let fact = |returns: Option, parameter_list: Option<&str>| DeclFact { enumerator: false, frees: 0, name: "format".into(), @@ -2602,10 +2588,10 @@ mod tests { local: false, kind: DeclKind::Function, modifiers: DeclModifiers::VIRTUAL, - type_of: None, type_of_id: TypeId::NONE, - returns: returns.map(Arc::from), + synthetic_type_of: None, returns_id: TypeId::NONE, + synthetic_returns: returns.map(Arc::new), parameters: ParamsId::NONE, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), @@ -2622,20 +2608,24 @@ mod tests { }), }; assert_eq!( - detail_of(&fact(Some("string"), Some("()"))).as_deref(), + detail_of_with_types(&fact(Some(builtin("string")), Some("()")), None).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), 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)")), None).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), + 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 9909f68e..f8dd866e 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -898,7 +898,7 @@ impl Session { self.store .index() .returns_spelling_of(fact) - .map(str::to_string) + .map(|spelled| spelled.to_string()) }) }) .or_else(|| { @@ -907,7 +907,7 @@ impl Session { self.store .index() .returns_spelling_of(fact) - .map(str::to_string) + .map(|spelled| spelled.to_string()) }) }) }, diff --git a/crates/cpp_code_analysis/src/session/cook.rs b/crates/cpp_code_analysis/src/session/cook.rs index 86572f93..a6fc0573 100644 --- a/crates/cpp_code_analysis/src/session/cook.rs +++ b/crates/cpp_code_analysis/src/session/cook.rs @@ -956,13 +956,33 @@ impl Session { built } }; - summary + // **The fact is synthesized for the caller**, so its types cannot stay as handles into this temporary + // summary's local table: the table does not travel with it. The table's written spelling is the one thing the + // caller can still read, so each is converted **once, here**, into the computation layer — the construction + // edge this path is — and the fact keeps the computed value instead. No store is minted and no handle leaks + // out of the summary. + let mut fact = summary .declarations .iter() .find(|fact| { fact.name == name && fact.scope.as_deref() == scope && !fact.split_by_a_directive - }) - .cloned() + })? + .clone(); + let template_parameters = fact.parameters().to_vec(); + let computed = |id: Option| { + id.and_then(|id| summary.types.spelling_for(id.raw())) + .map(|written| { + let parsed = sema::types::parse_type_spelling(written); + let parsed = sema::types::without_placeholders_written_as_names(parsed); + let parsed = sema::types::with_template_parameters(parsed, &template_parameters); + Arc::new(index::types::ComputedType::from(&parsed)) + }) + }; + fact.synthetic_type_of = computed(fact.type_of_id()); + fact.synthetic_returns = computed(fact.returns_id()); + fact.type_of_id = crate::index::types::TypeId::NONE; + fact.returns_id = crate::index::types::TypeId::NONE; + 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 3fce9b64..65c3db93 100644 --- a/crates/cpp_code_analysis/src/session/definition.rs +++ b/crates/cpp_code_analysis/src/session/definition.rs @@ -146,7 +146,7 @@ impl Session { qualified_name: format!("{class}::{name}"), class: class.to_string(), name: name.to_string(), - returns: self.index().returns_spelling_of(fact).map(str::to_string), + returns: self.index().returns_spelling_of(fact).map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template, @@ -198,7 +198,7 @@ impl Session { qualified_name: format!("{class}::{}", fact.name), class: class.to_string(), name: fact.name.to_string(), - returns: index.returns_spelling_of(fact).map(str::to_string), + returns: index.returns_spelling_of(fact).map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template: false, diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index cc6db002..66e5145a 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -268,7 +268,7 @@ impl Session { smol_str::SmolStr, String, >( - target, + &target, alias_fact.parameters(), alias_fact.parameter_defaults(), &[], @@ -386,7 +386,7 @@ impl Session { // `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) = index.type_spelling_of(found_fact) { - let base = target.split('<').next().unwrap_or(target).trim(); + 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() { @@ -407,7 +407,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_id`] 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 diff --git a/crates/cpp_code_analysis/src/session/tests/types.rs b/crates/cpp_code_analysis/src/session/tests/types.rs index ca3f20a4..048adf3d 100644 --- a/crates/cpp_code_analysis/src/session/tests/types.rs +++ b/crates/cpp_code_analysis/src/session/tests/types.rs @@ -587,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:?}" ); } diff --git a/crates/cpp_code_analysis/tests/suite/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 9513ada0..96dc5582 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -2233,7 +2233,7 @@ int main() fact.name, fact.kind, fact.parameter_list(), - fact.type_of + session.index().type_spelling_of(fact) ); } } diff --git a/crates/cpp_code_analysis/tests/suite/completion.rs b/crates/cpp_code_analysis/tests/suite/completion.rs index 4c9b8d46..55891526 100644 --- a/crates/cpp_code_analysis/tests/suite/completion.rs +++ b/crates/cpp_code_analysis/tests/suite/completion.rs @@ -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 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/header_context.rs b/crates/cpp_code_analysis/tests/suite/header_context.rs index d2b63ffd..5f907cd6 100644 --- a/crates/cpp_code_analysis/tests/suite/header_context.rs +++ b/crates/cpp_code_analysis/tests/suite/header_context.rs @@ -89,7 +89,7 @@ fn a_declaration_a_macro_unlocks_in_a_header_is_visible_from_the_unit_that_inclu .expect("the answer resolves through the index"); assert_eq!(fact.name.as_str(), "dollar_vcol"); assert_eq!( - 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/reported_defects.rs b/crates/cpp_code_analysis/tests/suite/reported_defects.rs index 3e392cc0..d355220c 100644 --- a/crates/cpp_code_analysis/tests/suite/reported_defects.rs +++ b/crates/cpp_code_analysis/tests/suite/reported_defects.rs @@ -105,20 +105,28 @@ 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 +154,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 +195,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:?}" ); } @@ -795,7 +804,7 @@ fn a_returned_local_states_its_type() { .definition_fact(&known) .expect("the answer resolves through the index"); assert_eq!( - 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" ); @@ -1079,7 +1088,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/semantic.rs b/crates/cpp_code_analysis/tests/suite/semantic.rs index 00a40259..a9f26f00 100644 --- a/crates/cpp_code_analysis/tests/suite/semantic.rs +++ b/crates/cpp_code_analysis/tests/suite/semantic.rs @@ -1015,7 +1015,7 @@ 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)) { @@ -1067,13 +1067,13 @@ 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::>() ) }); @@ -1114,7 +1114,7 @@ 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!( @@ -1319,13 +1319,13 @@ 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::>() ) }); @@ -1487,10 +1487,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!( @@ -1568,7 +1566,7 @@ 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, @@ -1584,7 +1582,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!( @@ -2010,23 +2011,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:?}" ); } @@ -2261,7 +2270,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_inspect/src/questions.rs b/crates/cpp_inspect/src/questions.rs index bf82a53f..f4366ed7 100644 --- a/crates/cpp_inspect/src/questions.rs +++ b/crates/cpp_inspect/src/questions.rs @@ -70,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() { @@ -116,8 +116,8 @@ fn declaration_value(session: &Session, definition: &ProjectDefinitio "name": fact.name, "kind": kind_of(fact.kind), "scope": fact.scope, - "type_of": fact.type_of, - "returns": fact.returns, + "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(), @@ -220,7 +220,7 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { text.push_str(&format!( " picked {:<40} {}\n", where_a_declaration(session, definition), - fact.map_or_else(|| "(unresolved)".to_string(), a_fact_and_what_it_says) + 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")), @@ -234,7 +234,7 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { where_a_declaration(session, definition), session .definition_fact(definition) - .map_or_else(|| "(unresolved)".to_string(), a_fact_and_what_it_says) + .map_or_else(|| "(unresolved)".to_string(), |fact| a_fact_and_what_it_says(session, fact)) )); } if found.found.is_empty() { @@ -339,7 +339,7 @@ fn a_member_and_where_it_is(session: &Session, member: &ProjectMember format!( "{:<28} {:<40} (declared in `{}`) {name}:{where_is}", shown.name, - what_it_says(&shown), + what_it_says(session, &shown), member.declared_in ) } @@ -475,7 +475,7 @@ pub fn the_facts(opened: &Opened, filters: &FactFilters<'_>) -> Result) -> Result( 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, diff --git a/crates/cpp_ls/src/handlers/completion/mod.rs b/crates/cpp_ls/src/handlers/completion/mod.rs index 75001f8d..1394a9b3 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,11 @@ 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(|fact| detail_of_with_types(fact, Some(session.index().types()))); let at = fact .as_ref() .map(|fact| fact.name_range.start_offset) diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index d7370483..a1ccd24a 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; @@ -830,7 +831,7 @@ fn hover_of_the_program( // is on rather than leaving the reader with a card about a different name. if let Some(fact) = session.definition_fact(&found) && fact.kind == DeclKind::Type - && fact.type_of.is_some() + && fact.has_type_of() && let Some((member, alias)) = a_member_of_a_template_alias(view, offset) { card.push_str(&format!( @@ -1025,14 +1026,15 @@ fn dependent_alias_member_markdown( let alias = definitions.found.iter().find(|definition| { session .definition_fact(definition) - .is_some_and(|fact| fact.kind == DeclKind::Type && fact.type_of.is_some()) + .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() @@ -1329,7 +1331,7 @@ fn member_markdown( let Some(fact) = session.index().member_display_fact(candidate) else { continue; }; - out.push_str(&a_line(&fact)); + out.push_str(&a_line(session, &fact)); out.push('\n'); } out.push_str("```\n\n"); @@ -1509,10 +1511,12 @@ fn overloads_markdown( 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) @@ -1771,9 +1775,60 @@ 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()) + }, + ) +} + +/// **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_id = cpp_code_analysis::index::types::TypeId::NONE; + fact.synthetic_type_of = Some(std::sync::Arc::new( + cpp_code_analysis::index::types::ComputedType::from( + &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_id = cpp_code_analysis::index::types::TypeId::NONE; + fact.synthetic_returns = Some(std::sync::Arc::new( + cpp_code_analysis::index::types::ComputedType::from( + &sema::types::parse_type_spelling(&written), + ), + )); } pub(crate) fn markdown(value: String) -> Hover { @@ -2136,8 +2191,8 @@ fn declaration_markdown_with( // 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.has_type_of() + && !found_fact.has_returns() && found_fact.parameter_list().is_none() && found_fact.reflection().is_none() { @@ -2178,8 +2233,8 @@ fn declaration_markdown_with( // `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 { @@ -2205,8 +2260,9 @@ fn declaration_markdown_with( // // 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) @@ -2217,19 +2273,18 @@ fn declaration_markdown_with( { // **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() + 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. @@ -2271,7 +2326,7 @@ fn declaration_markdown_with( && session.index().member_kind(member) == Some(DeclKind::Function) }) && let Some(displayed) = session.index().member_display_fact(the_member) - && displayed.returns.is_some() + && displayed.has_returns() { *fact = displayed; } @@ -2382,14 +2437,12 @@ fn declaration_markdown_with( 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() + && 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 _; @@ -2404,12 +2457,17 @@ fn declaration_markdown_with( fact, the_declaration.as_ref(), constant_value, - &|fact| session.index().type_spelling_of(fact).map(str::to_string), + &|fact| { + session + .index() + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, &|fact| { session .index() .returns_spelling_of(fact) - .map(str::to_string) + .map(|spelled| spelled.to_string()) }, ); if !attributes.is_empty() { @@ -2453,7 +2511,15 @@ fn declaration_markdown_with( 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 @@ -2461,9 +2527,9 @@ fn declaration_markdown_with( // 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) @@ -3012,7 +3078,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", @@ -3062,10 +3132,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(_), _) => {} @@ -3418,24 +3488,32 @@ 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_id: cpp_code_analysis::index::types::TypeId::NONE, + synthetic_returns: Some(std::sync::Arc::new( + cpp_code_analysis::index::types::ComputedType::from( + &sema::types::parse_type_spelling("std::size_t"), + ), + )), ..fact.clone() }; assert_eq!( From f00c6e7dea683102e1849d6196ee19dcbc33e346 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 16:27:02 +0800 Subject: [PATCH 072/102] refactor(facts): represent fact types as one enum DeclFact now has exactly two type fields, type_of and returns, each a DeclaredType: None, Stored(TypeId) into the one global TypeStore, or Computed(Arc) for synthesized/view facts. IDs are never invented for computed types, and the parallel synthetic/ID fields are gone. Compatibility type_of_id/returns_id accessors read the enum. Codec layout is unchanged; tests pin the three states. Workspace tests (3599 passed) and clippy pass. --- crates/cpp_code_analysis/src/cache/summary.rs | 203 ++++++++++++++---- .../src/cache/summary_codec.rs | 96 ++++++--- crates/cpp_code_analysis/src/index/mod.rs | 3 +- .../src/index/project/bases.rs | 18 +- .../src/index/project/completions.rs | 6 +- .../src/index/project/macro_environment.rs | 14 +- .../src/index/project/macro_walk.rs | 90 ++++---- .../src/index/project/member_facts.rs | 2 +- .../src/index/project/members.rs | 2 +- .../src/index/project/mod.rs | 2 +- .../src/index/project/substituted.rs | 2 +- .../src/index/project/tests.rs | 4 +- .../src/index/project/type_of.rs | 4 +- crates/cpp_code_analysis/src/lib.rs | 8 +- .../src/sema/check/missing_include.rs | 2 +- .../src/sema/declarations.rs | 40 ++-- crates/cpp_code_analysis/src/sema/model.rs | 13 +- crates/cpp_code_analysis/src/sema/types.rs | 2 +- crates/cpp_code_analysis/src/session/calls.rs | 12 +- .../src/session/completion/mod.rs | 31 ++- crates/cpp_code_analysis/src/session/cook.rs | 8 +- .../cpp_code_analysis/src/session/queries.rs | 2 +- crates/cpp_ls/src/handlers/hover/mod.rs | 13 +- docs/type-system-redesign.md | 25 ++- 24 files changed, 377 insertions(+), 225 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index df7fd7c0..2a97b56d 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -133,6 +133,77 @@ impl DeclModifiers { self.0 == 0 } } + +/// **The type a declaration carries** — the one value that answers "stored, synthesized, or absent?". +/// +/// A [`DeclFact`] moves between arenas. A fact filed in a summary holds a [`TypeId`] into the one global +/// [`TypeStore`], while a fact a query synthesized — a view fact built from a buffer the index has not read, a +/// generated member, a substituted display copy — has no arena to intern into. Storing an `Option` and an +/// `Option>` side by side made that a pair of fields that had to agree with each other; this enum +/// is the choice itself. +/// +/// There is **no second `TypeStore` and no arena tag**: [`DeclaredType::Stored`] is always a handle into the one +/// global store, and [`DeclaredType::Computed`] is a value for which no `TypeId` exists at all. +/// +/// [`TypeStore`]: crate::index::types::TypeStore +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum DeclaredType { + /// The declaration states no type, or none this reading could reach. + #[default] + None, + /// A handle into the one global [`TypeStore`]; valid only after the summary or reading is filed in an index. + Stored(TypeId), + /// A query-synthesized type. No [`TypeId`] exists for it and none is invented: an ID from a second store would + /// silently alias the global one. + Computed(std::sync::Arc), +} + +impl DeclaredType { + /// Is there no type at all — neither stored nor computed? + pub fn is_none(&self) -> bool { + matches!(self, Self::None) + } + + /// The handle this value holds, when it is stored. + pub fn stored_id(&self) -> Option { + match self { + Self::Stored(id) => Some(*id), + _ => None, + } + } + + /// The synthesized value this type holds, when it is computed. + pub fn computed(&self) -> Option<&std::sync::Arc> { + match self { + Self::Computed(computed) => Some(computed), + _ => None, + } + } + + /// **The type as the computation layer works on it.** A stored handle is materialized from `store` — the one + /// global store, never a local one — and a synthesized value is cloned. Nothing is parsed. + pub fn as_computed(&self, store: &index::types::TypeStore) -> Option { + match self { + Self::None => None, + Self::Stored(id) => store.materialize(*id), + Self::Computed(computed) => Some((**computed).clone()), + } + } + + /// Does this value carry a type at all, stored or computed? + pub fn has_value(&self) -> bool { + !self.is_none() + } + + /// A stored handle, or [`DeclaredType::None`] for the [`TypeId::NONE`] sentinel. + /// + /// A summary built from syntax marks "no type" with the sentinel, so the builder funnels the two through here + /// rather than letting a `Stored(NONE)` into the vocabulary. + pub(crate) fn from_stored(id: TypeId) -> Self { + if id.is_none() { Self::None } else { Self::Stored(id) } + } +} + /// 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 @@ -221,7 +292,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**, in the index's interned [`TypeStore`]. + /// **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 @@ -229,28 +300,22 @@ pub struct DeclFact { /// /// Three limits, all deliberate: /// - /// * **A store handle, not a spelling.** [`TypeStore`] keeps the source spelling beside the structure, so a - /// display edge can print what the file wrote and a computation edge can materialize a - /// [`ComputedType`] without parsing anything. + /// * **A value, not a spelling.** A stored fact holds a [`DeclaredType::Stored`] handle into the one global + /// [`TypeStore`], which keeps the source spelling beside the structure, so a display edge can print what the + /// file wrote and a computation edge can materialize a [`ComputedType`] without parsing anything. A fact a + /// query synthesized — a view fact built from a buffer the index has not read, a generated member, a + /// substituted display copy — carries a [`DeclaredType::Computed`] value instead: minting a `TypeId` for it + /// would need a second store, and an ID from a second store would silently alias the global one. /// * **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. - /// [`TypeId::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. /// /// [`TypeStore`]: crate::index::types::TypeStore - pub type_of_id: TypeId, - /// **A type that exists only in the computation layer**, for a fact that was *synthesized* — a view fact built - /// from a buffer the index has not read, a generated member, a substituted display copy. - /// - /// Such a fact has no [`TypeId`] to store: minting one would need a second `TypeStore`, and an ID from a second - /// store would silently alias the global one. It carries the computed value itself instead, parsed **once** at - /// the construction edge; every query reads it through [`crate::ProjectIndex::computed_type_of`], which checks - /// this field before materializing [`DeclFact::type_of_id`]. `None` for an ordinary stored fact, and - /// [`DeclFact::type_of_id`] is [`TypeId::NONE`] whenever this is `Some`. - pub synthetic_type_of: Option>, - /// The type a **function** returns, in the index's interned store; see [`DeclFact::type_of_id`]. + pub type_of: DeclaredType, + /// The type a **function** returns, by the same rule as [`DeclFact::type_of`] — see [`DeclaredType`]. /// /// 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 @@ -259,11 +324,9 @@ pub struct DeclFact { /// /// 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`. - /// [`TypeId::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_id: TypeId, - /// The computation-layer return type of a **synthesized** fact; see [`DeclFact::synthetic_type_of`]. - pub synthetic_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 summary's/global `ParamsStore`; `NONE` when there is no list. pub parameters: ParamsId, /// **Does the file's own text state this declaration's type across a directive?** @@ -271,7 +334,7 @@ pub struct DeclFact { /// `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_id`] are [`TypeId::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 @@ -503,37 +566,43 @@ impl DeclarationAccounting { } impl DeclFact { - /// The interned form of [`DeclFact::type_of_id`], when the summary has been inserted into an index. + /// The interned form of [`DeclFact::type_of`], when the summary has been inserted into an index. pub fn type_of_id(&self) -> Option { - (!self.type_of_id.is_none()).then_some(self.type_of_id) + self.type_of.stored_id() } - /// The interned form of [`DeclFact::returns_id`], when the summary has been inserted into an index. + /// The interned form of [`DeclFact::returns`], when the summary has been inserted into an index. pub fn returns_id(&self) -> Option { - (!self.returns_id.is_none()).then_some(self.returns_id) + self.returns.stored_id() } /// **Does this fact carry a type at all** — stored or computed? A consumer deciding "is this a typedef" /// asks this; one that wants the type itself asks [`crate::ProjectIndex::computed_type_of`]. pub fn has_type_of(&self) -> bool { - self.type_of_id().is_some() || self.synthetic_type_of.is_some() + 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_id().is_some() || self.synthetic_returns.is_some() + self.returns.has_value() } /// **Take another fact's computed types**, for a display copy that was rebuilt from a second reading. /// /// The copy has no arena of its own, so it cannot keep the other fact's handles: they would index a table that - /// does not travel with it. It keeps the computed values instead, and clears the handles — the same shape a - /// synthesized fact has. + /// does not travel with it. It keeps the computed values instead, and an ordinary stored type becomes + /// [`DeclaredType::None`] — the same shape a synthesized fact has. pub fn use_the_types_of(&mut self, other: &DeclFact) { - self.type_of_id = TypeId::NONE; - self.synthetic_type_of = other.synthetic_type_of.clone(); - self.returns_id = TypeId::NONE; - self.synthetic_returns = other.synthetic_returns.clone(); + self.type_of = other + .type_of + .computed() + .cloned() + .map_or(DeclaredType::None, DeclaredType::Computed); + self.returns = other + .returns + .computed() + .cloned() + .map_or(DeclaredType::None, DeclaredType::Computed); } /// The boxed half's cost, or zero for the common fact that has no box. @@ -1441,12 +1510,12 @@ impl DeclFact { + on_the_heap(&self.name) + on_the_heap_smol_option(&self.scope) + self - .synthetic_type_of - .as_ref() + .type_of + .computed() .map_or(0, |computed| computed.heap_bytes()) + self - .synthetic_returns - .as_ref() + .returns + .computed() .map_or(0, |computed| computed.heap_bytes()) + self.detail_bytes() } @@ -1490,9 +1559,9 @@ mod fact_size_tests { #[test] fn a_declaration_fact_stays_within_its_transition_budget() { - // **Two handles and two optional computed values are the current shape.** A stored fact pays eight bytes per - // handle; a synthesized fact pays a pointer to a shared `ComputedType` instead. Both are far below two hundred - // bytes, and the boxed detail is what keeps the common fact narrow. + // **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", @@ -1501,6 +1570,58 @@ mod fact_size_tests { } } +#[cfg(test)] +mod declared_type_tests { + use super::{ComputedType, DeclaredType}; + use crate::index::types::{TypeId, TypeStore}; + + /// **One enum, three answers** — the accessors a consumer uses to tell stored, computed and absent apart, and + /// `as_computed` as the single materialization edge. + #[test] + fn the_three_states_are_distinguishable() { + let mut store = TypeStore::new(); + let id = store.intern_spelling("int"); + + let stored = DeclaredType::Stored(id); + assert!(!stored.is_none()); + assert!(stored.has_value()); + assert_eq!(stored.stored_id(), Some(id)); + assert!(stored.computed().is_none()); + assert_eq!( + stored.as_computed(&store).map(|computed| computed.to_string()), + Some("int".to_string()), + "a stored handle is materialized through the store it names" + ); + + let computed = DeclaredType::Computed(std::sync::Arc::new(ComputedType::Builtin( + "unsigned long".into(), + ))); + assert!(!computed.is_none()); + assert!(computed.has_value()); + assert_eq!(computed.stored_id(), None); + assert!(computed.computed().is_some()); + assert_eq!( + computed.as_computed(&store).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_eq!(absent.stored_id(), None); + assert!(absent.computed().is_none()); + assert!(absent.as_computed(&store).is_none()); + assert_eq!(DeclaredType::default(), DeclaredType::None); + + assert_eq!( + DeclaredType::from_stored(TypeId::NONE), + DeclaredType::None, + "the sentinel is an absence, never `Stored(NONE)`" + ); + } +} + impl FileSummary { /// **The declaration population and its boxed shares** — the data a decision about `DeclFact::detail` needs. pub fn declaration_accounting(&self) -> DeclarationAccounting { diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index ff176bcc..24a2baee 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -41,7 +41,7 @@ use crate::index::CookedFile; use crate::preprocess::directive::IncludeForm; use crate::summary::CookedDiagnostic; use crate::summary::{ - Access, ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, + Access, ConditionalRegion, DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, GuardBranch, IncludeFact, MacroFact, MacroKind, MacroScopeReading, ModuleReading, SummaryGuards, TranslationUnit, TuEvent, TuFrame, }; @@ -291,6 +291,14 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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. pub const CODEC_VERSION: u32 = 44; /// Write a summary as bytes. @@ -1409,8 +1417,8 @@ mod tests { use crate::summary; use crate::summary::MacroKind; use crate::summary::{ - ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, IncludeFact, - MacroFact, MacroScopeReading, SummaryGuards, + ConditionalRegion, DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, GuardBranch, + IncludeFact, MacroFact, MacroScopeReading, SummaryGuards, }; use cpp_parser::{MacroBody, SourceRange}; use smol_str::SmolStr; @@ -1457,11 +1465,9 @@ 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_id: TypeId::NONE, - synthetic_type_of: None, + type_of: DeclaredType::None, // A class returns nothing either, so `None` — and the second fact below covers the other value. - returns_id: TypeId::NONE, - synthetic_returns: None, + returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, // 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. @@ -1521,11 +1527,9 @@ 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_id: TypeId::NONE, - synthetic_type_of: None, + type_of: DeclaredType::None, // The table's second node, so a fact's handle is part of what the round trip carries. - returns_id: TypeId::from_raw(1), - synthetic_returns: None, + returns: DeclaredType::Stored(TypeId::from_raw(1)), parameters: crate::index::params::ParamsId::NONE, // 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. @@ -1554,10 +1558,8 @@ mod tests { scope: None, kind: DeclKind::Other, modifiers: DeclModifiers::default(), - type_of_id: TypeId::NONE, - synthetic_type_of: None, - returns_id: TypeId::NONE, - synthetic_returns: None, + type_of: DeclaredType::None, + returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, access: None, exported: false, @@ -1697,6 +1699,31 @@ mod tests { ); } + #[test] + fn a_synthesized_type_is_not_persisted() { + // A `Computed` type has no handle into the record's type table, so the codec writes `NONE` for it — the same + // bytes an absent type writes. Decoding it back therefore answers `None`, and the fact keeps no + // `Stored(NONE)` in the process. + let mut original = every_field(); + original.declarations[1].type_of = DeclaredType::Computed(std::sync::Arc::new( + crate::index::types::ComputedType::Builtin("int".into()), + )); + original.declarations[1].returns = DeclaredType::Computed(std::sync::Arc::new( + crate::index::types::ComputedType::Builtin("void".into()), + )); + + let decoded = + decode(&encode(&original)).expect("the bytes this module wrote must be readable by it"); + + assert_eq!(decoded.declarations[1].type_of, DeclaredType::None); + assert_eq!(decoded.declarations[1].returns, DeclaredType::None); + assert_eq!( + decoded.declarations[1].type_of_id(), + None, + "a decoded fact never holds the `NONE` sentinel as a stored handle" + ); + } + #[test] fn an_empty_summary_round_trips() { let original = FileSummary::empty("/p/empty.h", SummaryKey::new(0, 0)); @@ -1817,10 +1844,10 @@ 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)); - // **One handle per type, and no spelling** — the record's type table carries every spelling, and a fact that - // was synthesized has no handle to write (`NONE`) because it carries its computed type in memory only. - put_u32(out, fact.type_of_id.raw()); - put_u32(out, fact.returns_id.raw()); + // **One stored handle per type, and no spelling** — the record's type table carries every spelling, and a fact + // that was synthesized has no handle to write (`NONE`) because it carries its computed type in memory only. + put_u32(out, fact.type_of.stored_id().unwrap_or(TypeId::NONE).raw()); + put_u32(out, fact.returns.stored_id().unwrap_or(TypeId::NONE).raw()); 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. @@ -1899,6 +1926,15 @@ fn put_macro(out: &mut Vec, fact: &MacroFact) { put_u8(out, u8::from(fact.settles_the_name)); } +/// A fact's type as the codec can carry it: a stored handle, or [`DeclaredType::None`]. +/// +/// A synthesized type is **not persisted** — it belongs to the query that built the fact and has no `TypeId` — so +/// [`DeclaredType::Computed`] writes the same `NONE` an absent type does. Neither is the sentinel ever wrapped: a +/// decoded fact holds `Stored` only for a real handle, which keeps `Stored(NONE)` out of the vocabulary. +fn declared_type_from_raw(raw: u32) -> DeclaredType { + DeclaredType::from_stored(TypeId::from_raw(raw)) +} + /// Read one declaration fact — the reader half of [`put_declaration`]. fn get_declaration(reader: &mut Reader<'_>) -> Result { // **Read in the order the bytes are written, then assemble** — the rare fields are boxed as a group (see @@ -1906,8 +1942,8 @@ 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_id = TypeId::from_raw(reader.u32()?); - let returns_id = TypeId::from_raw(reader.u32()?); + let type_of = declared_type_from_raw(reader.u32()?); + let returns = declared_type_from_raw(reader.u32()?); let parameters_id = crate::index::params::ParamsId::from_raw(reader.u32()?); let returns_in_the_class = reader.optional_string()?; let bases = get_strings(reader)?; @@ -1954,10 +1990,8 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { kind, modifiers, frees, - type_of_id, - synthetic_type_of: None, - returns_id, - synthetic_returns: None, + type_of, + returns, parameters: parameters_id, split_by_a_directive, range, @@ -2325,10 +2359,8 @@ fn a_cooked_reading_round_trips() { name: "Widget".into(), scope: Some("std".into()), kind: DeclKind::Type, - type_of_id: TypeId::NONE, - synthetic_type_of: None, - returns_id: TypeId::NONE, - synthetic_returns: None, + type_of: DeclaredType::None, + returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, range: SourceRange::new(10, 20), name_range: SourceRange::new(16, 6), @@ -2364,10 +2396,8 @@ fn a_cooked_reading_round_trips() { name: "f".into(), scope: None, kind: DeclKind::Function, - type_of_id: TypeId::from_raw(0), - synthetic_type_of: None, - returns_id: TypeId::from_raw(1), - synthetic_returns: None, + type_of: DeclaredType::Stored(TypeId::from_raw(0)), + returns: DeclaredType::Stored(TypeId::from_raw(1)), parameters: crate::index::params::ParamsId::NONE, range: SourceRange::new(40, 30), name_range: SourceRange::new(44, 1), diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index 377a3bc1..76ef3405 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -1699,7 +1699,8 @@ fn file_what_was_found( let ids: Vec<_> = cooked .declarations .iter() - .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) + .flatten() .collect(); cooked.types = types.export(ids); } diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index f0f2ed9e..893ddb98 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -9,7 +9,7 @@ use crate::BindingKind; use crate::DeclKind; use crate::ScopeKind; use crate::ScopeTree; -use crate::index::types::{ComputedType, TypeId}; +use crate::index::types::ComputedType; use crate::sema; use crate::summary; use cpp_parser::CppSyntaxNode; @@ -313,15 +313,15 @@ pub(crate) fn fact_from_binding_with( // 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 computed = |written: Option| { - written.map(|written| { + written.map_or(DeclaredType::None, |written| { let parsed = parse_type_spelling(&written); let parsed = sema::types::without_placeholders_written_as_names(parsed); let parsed = sema::types::with_template_parameters(parsed, &template_parameters); - Arc::new(ComputedType::from(&parsed)) + DeclaredType::Computed(Arc::new(ComputedType::from(&parsed))) }) }; - let synthetic_type_of = computed(written_type_of); - let synthetic_returns = computed(written_returns.clone()); + let type_of = computed(written_type_of); + let returns = computed(written_returns.clone()); DeclFact { enumerator: binding.kind == BindingKind::Enumerator, split_by_a_directive: sema::declarations::split_by_a_directive_with(shapes, binding), @@ -366,16 +366,14 @@ pub(crate) fn fact_from_binding_with( // // 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_id: TypeId::NONE, - synthetic_type_of, + 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. // **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. - returns_id: TypeId::NONE, - synthetic_returns, + returns, parameters: crate::index::params::ParamsId::NONE, // **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`]. @@ -754,7 +752,7 @@ pub(crate) fn class_of_the_enclosing_definition( /// would also match `ns::Widget`, and [`matches`] honours it for exactly that reason. It is not a distinction for /// this walk, because the walk does not ask "which name space"; it asks for the qualified spelling the index keys /// on, and a global declaration's spelling is its bare name. Keeping the prefix made `::Widget w;` — the type -/// spelling a consumer hands over verbatim from `DeclFact.type_of_id` — fail to find a class sitting in the buffer. +/// spelling a consumer hands over verbatim from `DeclFact.type_of` — fail to find a class sitting in the buffer. /// **Where the `<` is that opens a template argument list running to the end of `written`.** /// /// `None` for a spelling with no such group — `outer::handle_type` ends with `type`, so its `<` belongs to a diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index 0b7040a1..74599d4f 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -515,10 +515,8 @@ 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_id = crate::index::types::TypeId::NONE; - declaration.synthetic_type_of = None; - declaration.returns_id = crate::index::types::TypeId::NONE; - declaration.synthetic_returns = None; + declaration.type_of = DeclaredType::None; + declaration.returns = DeclaredType::None; declaration.detail_mut().bases.clear(); declaration.detail_mut().parameters.clear(); declaration.local = false; 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 4c86159d..71776bba 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -7,7 +7,7 @@ use crate::Binding; use crate::BindingKind; use crate::DeclKind; use crate::DeclModifiers; -use crate::index::types::{ComputedType, TypeId}; +use crate::index::types::ComputedType; use smol_str::SmolStr; use std::sync::Arc; @@ -671,10 +671,8 @@ fn fact_from_a_binding(binding: Binding, scope: Option, local: bool) -> // 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_id: TypeId::NONE, - synthetic_type_of: None, - returns_id: TypeId::NONE, - synthetic_returns: None, + type_of: DeclaredType::None, + returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, split_by_a_directive: false, // Same reason as `constraints` above: a clause is the declaration's text, and this shape is a match key. @@ -910,10 +908,8 @@ pub(crate) fn the_same_declaration(one: &DeclFact, other: &DeclFact) -> bool { && one.scope == other.scope && one.local == other.local && one.kind == other.kind - && one.type_of_id == other.type_of_id - && one.synthetic_type_of == other.synthetic_type_of - && one.returns_id == other.returns_id - && one.synthetic_returns == other.synthetic_returns + && one.type_of == other.type_of + && one.returns == other.returns && one.bases() == other.bases() && one.parameters() == other.parameters() && one.parameter_list() == other.parameter_list() 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 6f20e13e..21af001d 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -14,7 +14,7 @@ use crate::Visibility; use crate::cache; use crate::index; use crate::index::params::{ParameterFact, ParamsStore}; -use crate::index::types::{ComputedType, TypeId}; +use crate::index::types::ComputedType; use crate::summary::DeclarationAccounting; use cpp_parser::CppSyntaxNode; @@ -92,16 +92,14 @@ fn declaration_shape(summary: &FileSummary) -> u64 { the_walk_inputs_of(summary).hash(&mut hasher); for fact in summary.declarations.iter().filter(|fact| !fact.local) { format!( - "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", + "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", fact.enumerator, fact.name, fact.scope, fact.local, fact.kind, - fact.type_of_id, - fact.synthetic_type_of, - fact.returns_id, - fact.synthetic_returns, + fact.type_of, + fact.returns, fact.parameters(), fact.bases(), fact.pattern(), @@ -118,16 +116,14 @@ fn cooked_declaration_shape(declarations: &[DeclFact]) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); for fact in declarations.iter().filter(|fact| !fact.local) { format!( - "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", + "{:?}|{:?}|{:?}|{}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", fact.enumerator, fact.name, fact.scope, fact.local, fact.kind, - fact.type_of_id, - fact.synthetic_type_of, - fact.returns_id, - fact.synthetic_returns, + fact.type_of, + fact.returns, fact.parameters(), fact.bases(), fact.pattern(), @@ -569,10 +565,8 @@ impl ProjectIndex { && candidate.kind == fact.kind && candidate.scope == fact.scope && candidate.parameter_list() == fact.parameter_list() - && candidate.type_of_id == fact.type_of_id - && candidate.synthetic_type_of == fact.synthetic_type_of - && candidate.returns_id == fact.returns_id - && candidate.synthetic_returns == fact.synthetic_returns + && candidate.type_of == fact.type_of + && candidate.returns == fact.returns && candidate.requires_clause() == fact.requires_clause() && candidate.parameters() == fact.parameters() && candidate.modifiers == fact.modifiers @@ -831,8 +825,8 @@ impl ProjectIndex { /// `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 synthetic field, so a - /// consumer printing it goes through the same display edge as any other fact. No `TypeId` is minted and no + /// `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 `TypeId` is minted and no /// spelling is parsed. pub fn member_display_fact(&self, member: &ProjectMember) -> Option { let fact = self.member_fact(member)?; @@ -840,14 +834,16 @@ impl ProjectIndex { return Some(fact.clone()); } let mut shown = fact.clone(); - shown.type_of_id = TypeId::NONE; - shown.synthetic_type_of = self + shown.type_of = self .member_computed_type(member) - .map(Arc::new); - shown.returns_id = TypeId::NONE; - shown.synthetic_returns = self + .map_or(DeclaredType::None, |computed| { + DeclaredType::Computed(Arc::new(computed)) + }); + shown.returns = self .member_computed_returns(member) - .map(Arc::new); + .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()); } @@ -889,10 +885,10 @@ impl ProjectIndex { /// **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`]. pub fn type_spelling_of(&self, fact: &DeclFact) -> Option { - if let Some(computed) = &fact.synthetic_type_of { + if let Some(computed) = fact.type_of.computed() { return Some(smol_str::SmolStr::new(computed.to_string())); } - let id = fact.type_of_id()?; + let id = fact.type_of.stored_id()?; let spelled = self .types .spelling(id) @@ -907,10 +903,10 @@ impl ProjectIndex { /// The written return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. pub fn returns_spelling_of(&self, fact: &DeclFact) -> Option { - if let Some(computed) = &fact.synthetic_returns { + if let Some(computed) = fact.returns.computed() { return Some(smol_str::SmolStr::new(computed.to_string())); } - let id = fact.returns_id()?; + let id = fact.returns.stored_id()?; let spelled = self .types .spelling(id) @@ -926,19 +922,13 @@ impl ProjectIndex { /// **The computation-side type of a declaration's `type_of`.** A synthesized fact carries its value directly; /// an ordinary fact's handle is materialized from the one global store. Neither path interns anything. pub fn computed_type_of(&self, fact: &DeclFact) -> Option { - if let Some(computed) = &fact.synthetic_type_of { - return Some((**computed).clone()); - } - self.types.materialize(fact.type_of_id()?) + fact.type_of.as_computed(&self.types) } /// **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 { - if let Some(computed) = &fact.synthetic_returns { - return Some((**computed).clone()); - } - self.types.materialize(fact.returns_id()?) + fact.returns.as_computed(&self.types) } /// **Import every type a summary carries into the index's one store**, once, before the summary is filed. @@ -952,15 +942,15 @@ impl ProjectIndex { let mapping = self.types.import(&summary.types); summary.parameters.remap_types(&mapping); for fact in &mut summary.declarations { - if !fact.type_of_id.is_none() - && let Some(store_id) = mapping.get(&(fact.type_of_id.index() as u32)) + if let DeclaredType::Stored(id) = &mut fact.type_of + && let Some(store_id) = mapping.get(&(id.index() as u32)) { - fact.type_of_id = *store_id; + *id = *store_id; } - if !fact.returns_id.is_none() - && let Some(store_id) = mapping.get(&(fact.returns_id.index() as u32)) + if let DeclaredType::Stored(id) = &mut fact.returns + && let Some(store_id) = mapping.get(&(id.index() as u32)) { - fact.returns_id = *store_id; + *id = *store_id; } if let Some(detail) = fact.detail.as_mut() { for parameter in &mut detail.parameter_facts { @@ -974,7 +964,8 @@ impl ProjectIndex { let ids: Vec<_> = summary .declarations .iter() - .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) + .flatten() .collect(); summary.types = self.types.export(ids); } @@ -989,15 +980,15 @@ impl ProjectIndex { if !reading.types.is_empty() { let mapping = self.types.import(&reading.types); for fact in &mut reading.declarations { - if !fact.type_of_id.is_none() - && let Some(store_id) = mapping.get(&(fact.type_of_id.index() as u32)) + if let DeclaredType::Stored(id) = &mut fact.type_of + && let Some(store_id) = mapping.get(&(id.index() as u32)) { - fact.type_of_id = *store_id; + *id = *store_id; } - if !fact.returns_id.is_none() - && let Some(store_id) = mapping.get(&(fact.returns_id.index() as u32)) + if let DeclaredType::Stored(id) = &mut fact.returns + && let Some(store_id) = mapping.get(&(id.index() as u32)) { - fact.returns_id = *store_id; + *id = *store_id; } if let Some(detail) = fact.detail.as_mut() { for parameter in &mut detail.parameter_facts { @@ -1016,7 +1007,8 @@ impl ProjectIndex { let ids: Vec<_> = reading .declarations .iter() - .flat_map(|fact| [fact.type_of_id, fact.returns_id]) + .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) + .flatten() .collect(); reading.types = self.types.export(ids); } 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 0d9a1544..773fd05c 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -796,7 +796,7 @@ pub(crate) fn a_class_name_without_spaces(name: &str) -> String { /// /// # How an alias is recognised /// -/// In the buffer, by the binding's kind, which is exact. Through the index, by the rule [`DeclFact::type_of_id`] +/// In the buffer, by the binding's kind, which is exact. Through the index, by the rule [`DeclFact::type_of`] /// documents: a **type** fact with a `type_of` is an alias, and a class is a type fact without one. That is the /// whole of the test, and it is one test rather than a new field on purpose — the field was already there for /// variables, and what an alias *has* is a type in the same sense: the one it points at. diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 316149d1..1d582876 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -1281,7 +1281,7 @@ pub(crate) fn members_of_inner( // …>` kept `A`, so the trait matched no specialization and the wrong branch was taken. let with_arguments = class.to_string(); // The spelling is normalized once, at the entry, for the same reason a base's is: a consumer feeding this from - // `DeclFact.type_of_id` hands over what the file wrote — `const Widget&`, `::Widget`, `Base` — and every one + // `DeclFact.type_of` hands over what the file wrote — `const Widget&`, `::Widget`, `Base` — and every one // of those parts is about the type's shape rather than about which class declares the members. Normalizing // here also means `declared_in` is a qualified spelling from the first level on, and levels cannot disagree. // diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 41df5854..5eeb356c 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -48,7 +48,7 @@ use crate::file::paths::normalize_path; use crate::include::graph::Marked; use crate::preprocess::directive::IncludeForm; use crate::sema::types::{Type, TypeBindings, parse_type_spelling}; -use crate::summary::{DeclFact, DeclKind, FactGuard, FileSummary, MacroFact}; +use crate::summary::{DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, MacroFact}; use crate::symbol::{Known, UnknownReason}; #[cfg(test)] diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 3ace1de5..5f7ede5c 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -248,7 +248,7 @@ fn substituted_members_with( // `_Tp → int` alone leaves the word `value_type`, which nothing in this layer can compare: measured on // `std::vector anotherVec; anotherVec.push_back("123131");`, the target stayed `const value_type&`, // `convertible_to(const char[7], const value_type&)` answered `Unknown`, and a check that cannot compare says - // nothing — the report. An alias's target is in its own fact (`DeclFact::type_of_id` is the target for an alias, + // nothing — the report. An alias's target is in its own fact (`DeclFact::type_of` is the target for an alias, // see `declared_alias_target`), and the aliases of *this* class are already in the list being substituted, // which is why no second lookup is needed. // diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 8a8fcc78..28336c8d 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -108,7 +108,7 @@ fn the_file<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a /// **The index interns a summary's type spellings once**, and two declarations of one type share the handle. /// /// The string fields are still the source a query may read during the transition; this test pins the store's side -/// of the contract: insert fills `type_of_id`, and `int` is one node rather than one per declaration. +/// of the contract: insert fills `type_of`, and `int` is one node rather than one per declaration. #[test] fn the_index_interns_the_types_a_summary_declares_once() { let mut index = ProjectIndex::new(); @@ -2894,7 +2894,7 @@ fn a_base_of_a_class_in_a_namespace_is_looked_up_in_that_namespace() { #[test] fn a_type_spelled_from_the_global_name_space_lists_the_same_members() { // `::Widget w;` is a declaration whose type spelling carries the leading `::`, and a consumer feeding this - // query from `DeclFact.type_of_id` therefore hands it `::Widget`. The index keys a global declaration under + // query from `DeclFact.type_of` therefore hands it `::Widget`. The index keys a global declaration under // its bare name — a file-scope declaration has no scope prefix — so the prefix has to come off before the // walk, or a class that is plainly in the buffer answers `Unknown(NotDeclaredHere("::Widget"))`. let source = "struct Widget {\n int size;\n};\nvoid f() {\n ::Widget w;\n}\n"; 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 d018cb1e..0d87e429 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -1600,7 +1600,7 @@ pub(crate) fn agreeing_type( for found in &candidates { // **A class's type is the class**, and reading `type_of` alone said otherwise. // - // `DeclFact::type_of_id` is what a declaration wrote *as a type of something else* — a variable's type, an + // `DeclFact::type_of` is what a declaration wrote *as a type of something else* — a variable's type, an // alias's target — and a class has none, so the `?` below returned `None` for the whole list the moment one // candidate was a class. Measured on the report that started this: `std::vector` is declared thirteen times // (the primary template, `vector`, the deduction guides), every one of them a class, and @@ -2937,7 +2937,7 @@ impl NamedDeclaration { /// The type this declaration was written with. /// /// `None` for a function — `make` is not a `Widget` and has no members — which is the distinction - /// [`DeclFact::type_of_id`] documents. + /// [`DeclFact::type_of`] documents. pub(crate) fn type_of( &self, index: &ProjectIndex, diff --git a/crates/cpp_code_analysis/src/lib.rs b/crates/cpp_code_analysis/src/lib.rs index e268f4f3..cd5cf164 100644 --- a/crates/cpp_code_analysis/src/lib.rs +++ b/crates/cpp_code_analysis/src/lib.rs @@ -147,10 +147,10 @@ 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, + 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 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 a377beb6..02e936d6 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -18,7 +18,7 @@ //! //! Only **types a declaration spells**: the declared type of a variable, a field or a return value, and the types in a //! parameter list. That is where a missing include bites, and it is a position the file's own facts already record -//! (`DeclFact::type_of_id`, `DeclFact::parameter_list`) — so the rule costs no tree walk. +//! (`DeclFact::type_of`, `DeclFact::parameter_list`) — so the rule costs no tree walk. //! //! ```text //! reported Widget w; a type in a declaration diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index a6e532ae..f80280a7 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -60,8 +60,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; @@ -111,16 +111,18 @@ pub fn facts_with_their_types(built: BuiltFacts) -> Vec { mut facts, types, .. } = built; for fact in &mut facts { - fact.synthetic_type_of = fact - .type_of_id() - .and_then(|id| types.materialize(id)) - .map(std::sync::Arc::new); - fact.synthetic_returns = fact - .returns_id() - .and_then(|id| types.materialize(id)) - .map(std::sync::Arc::new); - fact.type_of_id = TypeId::NONE; - fact.returns_id = TypeId::NONE; + fact.type_of = fact + .type_of + .as_computed(&types) + .map_or(DeclaredType::None, |computed| { + DeclaredType::Computed(std::sync::Arc::new(computed)) + }); + fact.returns = fact + .returns + .as_computed(&types) + .map_or(DeclaredType::None, |computed| { + DeclaredType::Computed(std::sync::Arc::new(computed)) + }); } facts } @@ -190,7 +192,7 @@ pub fn build_facts( /// that the two cannot come to disagree about what `static const Widget` declares. /// /// `None` for a declaration that declares no type: a class, a namespace, a function, an alias. See -/// [`DeclFact::type_of_id`]. +/// [`DeclFact::type_of`]. pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option { declared_type_of_with(&DeclarationShapes::of(root), binding) } @@ -1420,7 +1422,7 @@ fn declared_namespace_alias_target_with(root: &CppSyntaxNode, binding: &Binding) /// whose answer goes into the *same* field as the first: a fact's `type_of` is "the type this declaration is /// about", which for a variable is the type it has and for an alias is the type it **points at**. An alias /// declares no members of its own, so a consumer that reads a name written as `std::string` has to be able to get -/// from it to `std::basic_string`, and this is where that spelling comes from. See [`DeclFact::type_of_id`] for the +/// from it to `std::basic_string`, and this is where that spelling comes from. See [`DeclFact::type_of`] for the /// rule that tells the two apart. /// /// # The two spellings a C++ alias comes in @@ -4190,10 +4192,8 @@ 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_id, - synthetic_type_of: None, - returns_id, - synthetic_returns: None, + type_of: DeclaredType::from_stored(type_of_id), + returns: DeclaredType::from_stored(returns_id), parameters: crate::index::params::ParamsId::NONE, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { @@ -5860,7 +5860,7 @@ pub fn scope_of<'a>(scopes: &'a ScopeTree, fact: &DeclFact) -> Option<(ScopeId, /// /// 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 -/// parameters. Nothing tells it for a member of a class template: [`DeclFact::type_of_id`] is the `Display` +/// 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 /// the question "is this type one only instantiation can finish" **cannot be asked of the summary at all**. /// @@ -6001,7 +6001,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_id`] is the `Display` rendering of a `Type`, so + /// **scope tree** rather than of the type: [`DeclFact::type_of`] is the `Display` rendering of a `Type`, so /// `_Alloc` and a class named `_Alloc` are the same text, and `_Alloc::value_type` is a name no lookup can /// ever answer. /// diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index b5981382..26f097ab 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -54,6 +54,7 @@ use cpp_parser::CppSyntaxNode; use crate::index::project::{self, MemberList, ProjectIndex}; use crate::index::types::{ComputedType, TypeId}; use crate::sema::types::Type; +use crate::summary::DeclaredType; use crate::{Known, ScopeTree}; /// **A file, the index, and a way to read another file** — see the module documentation. @@ -172,7 +173,11 @@ impl<'a> SemanticModel<'a> { /// instantiation bindings applied structurally. No spelling is parsed and no new `TypeId` is interned. pub fn computed_type_of_member(&self, member: &crate::ProjectMember) -> Option { let fact = self.index.member_fact(member)?; - let base = self.computed_type(fact.type_of_id()?)?; + let base = match &fact.type_of { + DeclaredType::Stored(id) => self.computed_type(*id)?, + DeclaredType::Computed(computed) => (**computed).clone(), + DeclaredType::None => return None, + }; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, @@ -183,7 +188,11 @@ impl<'a> SemanticModel<'a> { /// half, for the member functions whose declared type is the one they return. pub fn member_returns(&self, member: &crate::ProjectMember) -> Option { let fact = self.index.member_fact(member)?; - let base = self.computed_type(fact.returns_id()?)?; + let base = match &fact.returns { + DeclaredType::Stored(id) => self.computed_type(*id)?, + DeclaredType::Computed(computed) => (**computed).clone(), + DeclaredType::None => return None, + }; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 77d4ade4..3ba4204d 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -1097,7 +1097,7 @@ impl TypeBindings { /// Because two layers of this crate do not have the syntax, and cannot get it cheaply: /// /// ```text -/// a declaration the index holds `DeclFact::type_of_id` is a handle into the global type store; the class it +/// a declaration the index holds `DeclFact::type_of` is a handle into the global type store; the class it /// names is materialized without a tree, because the declaring file need not be open /// a type written as a template arg `std::map` arrives as text inside a name node /// ``` diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 596a6351..e4b286a3 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -103,7 +103,7 @@ fn a_scalar_layout(size: usize, alignment: usize) -> sema::layout::ClassLayout { /// **Split a trailing `[dimension]` from a type spelling**, or `None` when the spelling does not end in one. /// -/// The declarator's name is already gone — `DeclFact::type_of_id` holds a type, not a declaration — so the last bracket +/// The declarator's name is already gone — `DeclFact::type_of` holds a type, not a declaration — so the last bracket /// is the outermost array. A parenthesised declarator (`int (*table[3])(int)`) does not end in `]` and is left to the /// steps that can read it; a flexible array's dimension is empty, which the caller reads as zero extent. fn split_an_array_dimension(spelling: &str) -> Option<(&str, &str)> { @@ -817,7 +817,7 @@ impl Session { .iter() .any(|member| { index.member_fact(member).is_some_and(|fact| { - fact.synthetic_type_of.is_some() + fact.type_of.computed().is_some() && index.member_path(member) == Some(view.path.as_path()) }) }) @@ -837,7 +837,7 @@ impl Session { continue; }; // **The spelling the file wrote**, for a member of the asking file — see `written_types`. - let type_of = match (&written_types, fact.synthetic_type_of.is_some()) { + let type_of = match (&written_types, fact.type_of.computed().is_some()) { (Some(shapes), true) if index.member_path(member) == Some(view.path.as_path()) => { sema::resolve::definition_at( &view.scopes, @@ -1473,14 +1473,12 @@ impl Session { // 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_id = crate::index::types::TypeId::NONE; - fact.synthetic_type_of = Some(Arc::new( + fact.type_of = crate::DeclaredType::Computed(Arc::new( crate::index::types::ComputedType::from( &crate::sema::types::parse_type_spelling(&type_of), ), )); - fact.returns_id = crate::index::types::TypeId::NONE; - fact.synthetic_returns = None; + fact.returns = crate::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 diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index f52aa55a..efd7171d 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -88,7 +88,7 @@ pub use table::{ }; use crate::sema::symbol::{Known, ScopeKind, ScopeTree}; -use crate::summary::{DeclFact, DeclKind}; +use crate::summary::{DeclFact, DeclKind, DeclaredType}; use crate::{ProjectIndex, ProjectMember}; /// What an item is, in the vocabulary every consumer understands. @@ -371,16 +371,16 @@ pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Optio }; // **The written spelling wins when it exists**, because it is what the reader sees in the declaration; a synthetic // value is printed as its computed type. - let returns = fact - .synthetic_returns - .as_ref() - .map(|returns| returns.to_string()) - .or_else(|| fact.returns_id().and_then(displayed)); - let type_of = fact - .synthetic_type_of - .as_ref() - .map(|type_of| type_of.to_string()) - .or_else(|| fact.type_of_id().and_then(displayed)); + let returns = match &fact.returns { + DeclaredType::Computed(returns) => Some(returns.to_string()), + DeclaredType::Stored(id) => displayed(*id), + DeclaredType::None => None, + }; + let type_of = match &fact.type_of { + DeclaredType::Computed(type_of) => Some(type_of.to_string()), + DeclaredType::Stored(id) => displayed(*id), + DeclaredType::None => None, + }; match fact.kind { DeclKind::Function => match (returns, fact.parameter_list()) { (Some(returns), Some(parameters)) => Some(format!("{returns} {parameters}")), @@ -2524,7 +2524,6 @@ mod tests { use crate::DeclModifiers; use crate::FactGuard; use crate::index::params::ParamsId; - use crate::index::types::TypeId; use crate::summary; /// **A name that does not answer what was typed is dropped, not ranked low.** The rule itself lives in @@ -2588,10 +2587,10 @@ mod tests { local: false, kind: DeclKind::Function, modifiers: DeclModifiers::VIRTUAL, - type_of_id: TypeId::NONE, - synthetic_type_of: None, - returns_id: TypeId::NONE, - synthetic_returns: returns.map(Arc::new), + type_of: DeclaredType::None, + returns: returns.map_or(DeclaredType::None, |returns| { + DeclaredType::Computed(Arc::new(returns)) + }), parameters: ParamsId::NONE, range: SourceRange::new(0, 0), name_range: SourceRange::new(0, 0), diff --git a/crates/cpp_code_analysis/src/session/cook.rs b/crates/cpp_code_analysis/src/session/cook.rs index a6fc0573..eeeb25cb 100644 --- a/crates/cpp_code_analysis/src/session/cook.rs +++ b/crates/cpp_code_analysis/src/session/cook.rs @@ -978,10 +978,10 @@ impl Session { Arc::new(index::types::ComputedType::from(&parsed)) }) }; - fact.synthetic_type_of = computed(fact.type_of_id()); - fact.synthetic_returns = computed(fact.returns_id()); - fact.type_of_id = crate::index::types::TypeId::NONE; - fact.returns_id = crate::index::types::TypeId::NONE; + fact.type_of = computed(fact.type_of.stored_id()) + .map_or(crate::DeclaredType::None, crate::DeclaredType::Computed); + fact.returns = computed(fact.returns.stored_id()) + .map_or(crate::DeclaredType::None, crate::DeclaredType::Computed); Some(fact) } diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index 66e5145a..79a54949 100644 --- a/crates/cpp_code_analysis/src/session/queries.rs +++ b/crates/cpp_code_analysis/src/session/queries.rs @@ -407,7 +407,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_id`] is an interned handle, and it 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 diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index a1ccd24a..0077ee3d 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -48,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; @@ -1813,8 +1813,7 @@ fn shown_returns_of(index: &ProjectIndex, fact: &DeclFact) -> Option { /// 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_id = cpp_code_analysis::index::types::TypeId::NONE; - fact.synthetic_type_of = Some(std::sync::Arc::new( + fact.type_of = DeclaredType::Computed(std::sync::Arc::new( cpp_code_analysis::index::types::ComputedType::from( &sema::types::parse_type_spelling(&written), ), @@ -1823,8 +1822,7 @@ fn set_the_written_type(fact: &mut DeclFact, written: String) { /// [`set_the_written_type`] for a function's return type. fn set_the_written_returns(fact: &mut DeclFact, written: String) { - fact.returns_id = cpp_code_analysis::index::types::TypeId::NONE; - fact.synthetic_returns = Some(std::sync::Arc::new( + fact.returns = DeclaredType::Computed(std::sync::Arc::new( cpp_code_analysis::index::types::ComputedType::from( &sema::types::parse_type_spelling(&written), ), @@ -3508,8 +3506,7 @@ mod tests { // 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 { - returns_id: cpp_code_analysis::index::types::TypeId::NONE, - synthetic_returns: Some(std::sync::Arc::new( + returns: DeclaredType::Computed(std::sync::Arc::new( cpp_code_analysis::index::types::ComputedType::from( &sema::types::parse_type_spelling("std::size_t"), ), diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 2f0fc66d..7eed5dc6 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -107,8 +107,8 @@ struct DeclFact { name: SmolStr, kind: DeclKind, scope: Option, - type_of: Option, - returns: Option, + type_of: DeclaredType, + returns: DeclaredType, parameters: ParamsId, template_parameters: Box<[SmolStr]>, parameter_defaults: Box<[SmolStr]>, @@ -120,16 +120,29 @@ struct DeclFact { } ``` -There is no `type_of: Option>` and no `returns: Option>`. +The two type fields are one enum, because a fact holds either kind of answer: + +```rust +enum DeclaredType { + None, + Stored(TypeId), // valid only in the one global TypeStore + Computed(Arc), // a query-synthesized value; NO TypeId exists +} +``` + +There is no `type_of: Option>` and no `returns: Option>`. There is also **no second +`TypeStore` and no arena tag**: `Stored` is always a handle into the one global store, and `Computed` is a +value for which no `TypeId` is invented — an ID from a second store would silently alias the global one. A type that is needed for display is materialized: ```rust -index.types().computed(fact.type_of?) // -> ComputedType +index.computed_type_of(fact) // -> Option ``` -A fact with no written type has `None`. A fact from a temporary/view arena also resolves through -that arena's `TypeStore`; it never gets a local store. +A fact with no written type has `DeclaredType::None`. A fact built from a temporary/view arena or synthesized +by a query carries `DeclaredType::Computed` — the value the query already has — rather than a handle into a +store that does not travel with it; it never gets a local store. ## 4. `ProjectMember` From 66cf17580c6a37d2a0cfa5a771bded6dd86086ac Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 17:07:19 +0800 Subject: [PATCH 073/102] refactor(params): delete the build-time parameter fact copy DeclDetail.parameter_facts is gone; DeclFact.parameters: ParamsId is the only stored parameter handle. The fact builder interns parameter lists before filing and returns them in BuiltFacts; view/synthetic facts keep their lists in the index's synthetic arena (no id space), and cooked readings carry their own ParamsStore imported at insert. ProjectIndex::parameter_facts_of resolves synthetic, summary and cooked arenas in that order. COOKED_VERSION 8, UNIT_CODEC_VERSION 7; summary codec layout unchanged. Workspace tests (3601 passed) and clippy pass. --- crates/cpp_code_analysis/src/cache/summary.rs | 13 +- .../src/cache/summary_codec.rs | 57 ++++- .../cpp_code_analysis/src/cache/unit_codec.rs | 10 +- crates/cpp_code_analysis/src/index/params.rs | 9 +- .../src/index/project/bases.rs | 49 +++- .../src/index/project/calls.rs | 3 +- .../src/index/project/completions.rs | 15 +- .../src/index/project/macro_walk.rs | 217 +++++++++++++----- .../src/index/project/member_candidates.rs | 3 +- .../src/index/project/members.rs | 19 +- .../src/index/project/mod.rs | 48 +++- .../src/index/project/tests.rs | 86 +++++++ crates/cpp_code_analysis/src/index/store.rs | 2 + .../cpp_code_analysis/src/sema/call_syntax.rs | 14 +- .../src/sema/check/argument_count.rs | 16 +- .../src/sema/declarations.rs | 100 ++++---- crates/cpp_code_analysis/src/session/calls.rs | 5 +- .../src/session/completion/mod.rs | 1 - .../src/session/completion/request.rs | 6 +- crates/cpp_code_analysis/src/session/inlay.rs | 9 +- docs/type-system-redesign.md | 9 + 21 files changed, 520 insertions(+), 171 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 2a97b56d..768cf8d1 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -327,7 +327,9 @@ pub struct DeclFact { /// [`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 summary's/global `ParamsStore`; `NONE` when there is no list. + /// 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 file's own text state this declaration's type across a directive?** /// @@ -475,8 +477,6 @@ pub struct DeclDetail { pub pattern: Option, /// The parameter list as the file spells it, parentheses included. pub parameter_list: Option, - /// Build-time CST parameter facts; the inserted summary moves them to `ParamsStore` and clears this box. - pub parameter_facts: Box<[ParameterFact]>, } impl DeclDetail { @@ -503,7 +503,6 @@ impl DeclDetail { && self.parameter_defaults.is_empty() && self.pattern.is_none() && self.parameter_list.is_none() - && self.parameter_facts.is_empty() } } @@ -526,7 +525,6 @@ impl DeclDetail { + strings_bytes(&self.parameters) + strings_bytes(&self.constraints) + strings_bytes(&self.parameter_defaults) - + self.parameter_facts.len() * size_of::() + self.reflection.as_ref().map_or(0, |reflection| { on_the_heap(&reflection.macro_name) + reflection.specifiers.len() * size_of::() @@ -660,11 +658,6 @@ impl DeclFact { self.detail().and_then(|detail| detail.pattern.as_deref()) } - /// Build-time CST parameter facts; empty on a fact whose summary moved them to `ParamsStore`. - pub fn parameter_facts(&self) -> &[ParameterFact] { - self.detail().map_or(&[], |detail| &detail.parameter_facts) - } - pub fn parameter_list(&self) -> Option<&str> { self.detail() .and_then(|detail| detail.parameter_list.as_deref()) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 24a2baee..7d7db319 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -299,6 +299,14 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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. pub const CODEC_VERSION: u32 = 44; /// Write a summary as bytes. @@ -1512,7 +1520,6 @@ mod tests { // partial specialization from its primary template. `None` is covered by the facts below. pattern: Some("Widget<_Ty, _Alloc>".into()), parameter_list: Some("(int, int)".into()), - parameter_facts: Box::default(), // The `Some` branch, which is the one only a **local** ever has — see // [`DeclFact::in_namespace`]. The two facts below cover `None`. in_namespace: Some("std::ranges".into()), @@ -1547,7 +1554,6 @@ mod tests { // answer, and `None` would be "nobody looked". detail: summary::DeclDetail::in_a_box(summary::DeclDetail { parameter_list: Some("()".into()), - parameter_facts: Box::default(), ..Default::default() }), }, @@ -2012,7 +2018,6 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { parameter_defaults, pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), - parameter_facts: Box::default(), }), }) } @@ -2083,7 +2088,12 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// [`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. -const COOKED_VERSION: u32 = 7; +/// +/// 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. +const COOKED_VERSION: u32 = 8; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -2156,6 +2166,11 @@ fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { // `ProjectIndex::insert_cooked` imports this table into the index's one store. A reading with no types writes an // empty table, which is what a decoded reading from a caller that built one by hand has too. put_type_table(out, &reading.types); + // **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: @@ -2238,11 +2253,14 @@ pub fn decode_the_cooked_record( }); } let unplaced = reader.u32()? as usize; - // The reading's local type table, written by [`put_cooked_body`] before the optional rendering. + // The reading's local type table, written by [`put_cooked_body`] before the optional rendering, then its + // parameter table. let types = get_type_table(&mut reader)?; + let parameters = get_params_store(&mut reader)?; let reading = CookedFile { declarations, types, + parameters, macros, diagnostics, unplaced, @@ -2353,6 +2371,19 @@ fn a_cooked_reading_round_trips() { }, ], }, + // **The reading's own parameter table**, the sibling of the type table: a fact's `ParamsId` is local to the + // reading, so the table travels with the record and `ProjectIndex::insert_cooked` imports it. + parameters: crate::index::params::ParamsStore::from_entries(vec![vec![ + crate::index::params::ParameterFact { + name: Some("value".into()), + declaration: cpp_parser::CppSyntaxId::from_raw_parts(0, 0, 1) + .expect("a syntax id"), + default_value: None, + pack: false, + type_of: TypeId::from_raw(0), + }, + ] + .into_boxed_slice()]), declarations: vec![ DeclFact { enumerator: false, @@ -2382,7 +2413,6 @@ fn a_cooked_reading_round_trips() { requires_clause: Some("sizeof(T) > 0".into()), parameter_defaults: Vec::new(), parameter_list: None, - parameter_facts: Box::default(), pattern: Some("Widget".into()), in_namespace: Some("std".into()), reflection: Some(summary::ReflectionFact { @@ -2398,7 +2428,7 @@ fn a_cooked_reading_round_trips() { kind: DeclKind::Function, type_of: DeclaredType::Stored(TypeId::from_raw(0)), returns: DeclaredType::Stored(TypeId::from_raw(1)), - parameters: crate::index::params::ParamsId::NONE, + parameters: crate::index::params::ParamsId::from_raw(0), range: SourceRange::new(40, 30), name_range: SourceRange::new(44, 1), local: true, @@ -2419,7 +2449,6 @@ fn a_cooked_reading_round_trips() { requires_clause: None, parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), - parameter_facts: Box::default(), pattern: None, in_namespace: None, reflection: None, @@ -2478,6 +2507,18 @@ fn a_cooked_reading_round_trips() { // **The handles and the table travel together.** A decoded fact's ID is the reading's own, and the table that // gives it meaning came back too — that is what `ProjectIndex::insert_cooked` imports. assert_eq!(back.types, reading.types); + 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_id(), Some(TypeId::from_raw(0)), diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 765ce65f..3c3c801e 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -54,7 +54,11 @@ const MAGIC: [u8; 4] = *b"UNIT"; /// 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. -pub const UNIT_CODEC_VERSION: u32 = 6; +/// +/// 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. +pub const UNIT_CODEC_VERSION: u32 = 7; #[derive(Debug)] pub enum DecodeError { @@ -458,6 +462,7 @@ pub fn decode_indexed_unit(bytes: &[u8]) -> Result { CookedFile { declarations: summary.declarations, types: summary.types, + parameters: summary.parameters, macros: summary.macros, diagnostics, unplaced, @@ -496,7 +501,7 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), types: cooked.types.clone(), - parameters: crate::index::params::ParamsStore::default(), + parameters: cooked.parameters.clone(), macros: cooked.macros.clone(), includes: Vec::new(), guards: SummaryGuards::default(), @@ -521,6 +526,7 @@ mod index_tests { CookedFile { declarations: Vec::new(), types: crate::index::types::TypeTable::default(), + parameters: crate::index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: vec![CookedDiagnostic { range: SourceRange::new(3, 4), diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index ce2e4037..20e3d18b 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -99,7 +99,14 @@ impl ParamsStore { } pub fn parameters(&self, id: ParamsId) -> &[ParameterFact] { - self.entries.get(id.index()).map_or(&[], |facts| facts) + 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]>] { diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 893ddb98..3c870237 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -46,7 +46,8 @@ pub(crate) fn direct_member( root, class, binding, - ), + ) + .fact, path.to_path_buf(), )); } @@ -244,6 +245,20 @@ 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, no interning, and +/// every parameter's `type_of` is [`crate::index::types::TypeId::NONE`] because a view path has no type store to lower +/// into. 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. +pub(crate) struct SynthesizedFact { + pub fact: DeclFact, + pub parameters: Box<[crate::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 @@ -266,7 +281,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, @@ -284,12 +303,20 @@ 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; // **The two types this path can state, and the one place their spellings exist.** This builder has no // `TypeStore` — it runs on the query side, against a buffer — so it converts the written spelling **once** into @@ -322,7 +349,13 @@ pub(crate) fn fact_from_binding_with( }; let type_of = computed(written_type_of); let returns = computed(written_returns.clone()); - DeclFact { + // **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`]). Its + // parameter types stay [`crate::index::types::TypeId::NONE`]: lowering them needs the file's `TypeStore`, and a + // view path has none — the display and name readers of these facts do not need a type. + let parameters = sema::declarations::declared_parameter_facts_with(shapes, binding) + .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`. @@ -374,6 +407,9 @@ pub(crate) fn fact_from_binding_with( // 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. 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: crate::index::params::ParamsId::NONE, // **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`]. @@ -430,8 +466,6 @@ pub(crate) fn fact_from_binding_with( } _ => None, }, - parameter_facts: sema::declarations::declared_parameter_facts_with(shapes, binding) - .into_boxed_slice(), }), // **Who may name it**, read the same way and for the same reason: a member list built from the buffer is // what a completion after `.` offers, and a `private:` member must not be in it. See [DeclFact::access]. @@ -446,7 +480,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. diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 02eede33..fc0bf5d6 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1097,7 +1097,8 @@ pub(crate) fn declaration_of_a_callee( root, "", binding, - ), + ) + .fact, path.to_path_buf(), ) }) diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index 74599d4f..932e90af 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -539,8 +539,10 @@ pub fn name_completions_at( // [`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) { - Some(file) => index.intern_synthetic_fact(file, declaration), - None => index.intern_a_view_fact(written_in, declaration), + // 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 { @@ -1145,7 +1147,8 @@ pub(crate) fn bindings_of( bindings .iter() .filter_map(|binding| { - let mut fact = fact_from_binding(root, spelling, binding); + let synthesized = fact_from_binding(root, spelling, binding); + let mut fact = synthesized.fact; fact.local = local; // **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 @@ -1158,11 +1161,11 @@ pub(crate) fn bindings_of( // **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 in its view table instead of - // dropping the name. See [`ProjectIndex::intern_a_view_fact`]. + // 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), + None => index.intern_a_view_fact(path, fact, synthesized.parameters), }; Some(Candidate::new(reference, NameProvenance::Scope)) }) 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 21af001d..ed69bf96 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -385,32 +385,101 @@ impl ProjectIndex { &self.types } - /// The index's parameter arena; facts reach it by `DeclFact::parameters` after the side table lands. + /// **The index-wide parameter arena**, append-only like [`ProjectIndex::types`]. 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. pub fn parameters(&self) -> &ParamsStore { &self.parameters } - /// **The parameter facts a fact names, through the summary that owns its local `ParamsId`.** No text fallback. + /// **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] { - let Some(summary) = self.summaries.get(&normalize(file)) else { + // **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; + } + // `NONE` is the whole answer — no list was ever written — and returning here is what keeps a zero-parameter + // function from being matched to another declaration's list below. + if fact.parameters.is_none() { + return &[]; + } + let key = normalize(file); + let Some(summary) = self.summaries.get(&key) else { return &[]; }; - let direct = summary.parameter_facts(fact); - if !direct.is_empty() { - return direct; + 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; + } + } } - // **A cooked fact carries its own reading's local id.** The source summary is a different arena, so find the - // declaration the two readings are both about by its name range and use *that* handle. A macro-only - // declaration is absent from the source summary and stays empty; the caller then falls back to its text path. summary .declarations .iter() - .find(|candidate| { - candidate.name == fact.name && candidate.name_range == fact.name_range - }) + .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) + } + + /// **The id a view fact's file was given, without minting one** — the read-only half of + /// [`ProjectIndex::view_paths`], paired with the summary sequence so one lookup answers for both kinds of file. + fn view_file_id(&self, path: &Path) -> Option { + let key = normalize(path); + if let Some(id) = self.sequence.get(&key) { + return Some(*id); + } + self.view_paths.lock().ok()?.get(path) + } + /// **The runtime file id the index assigned this path.** The numbering is the index's insertion sequence; a /// session that owns a VFS will pass its own [`crate::FileId`] here once the two tables are unified. pub fn file_id_of(&self, path: &Path) -> Option { @@ -630,7 +699,7 @@ impl ProjectIndex { .lock() .ok()? .get(reference.fact.index()) - .copied(); + .map(|entry| entry.fact); } let path = self.order.get(&(reference.file.index() as u32))?; let key = normalize(Path::new(path)); @@ -652,23 +721,39 @@ impl ProjectIndex { /// /// 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 share one entry, so a query that regenerates the same member on every - /// keystroke does not grow the arena. - pub fn intern_synthetic_fact(&self, file: crate::FileId, fact: DeclFact) -> FactRef { + /// 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: crate::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 == fact) { + 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()` answers with a borrow, 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 generated members, - // not with its queries. - let leaked: &'static DeclFact = Box::leak(Box::new(fact)); - arena.push(leaked); + // **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 } }; @@ -684,10 +769,16 @@ impl ProjectIndex { /// /// Such a file has no summary, so it has no ordinary [`crate::FileId`]; the index mints one in the view table /// ([`ProjectIndex::view_paths`]) and keeps the path with it, so the row still answers "which file" and "which - /// declaration". The fact is stored in the synthetic arena. A file the index *has* read goes through + /// 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) -> FactRef { + pub fn intern_a_view_fact( + &self, + path: &Path, + fact: DeclFact, + parameters: Box<[ParameterFact]>, + ) -> FactRef { let file = { let mut paths = self .view_paths @@ -695,7 +786,7 @@ impl ProjectIndex { .expect("the view fact table is not poisoned"); crate::FileId::new(paths.id_of(path)) }; - self.intern_synthetic_fact(file, fact) + self.intern_synthetic_fact(file, fact, parameters) } /// **The declaration a [`ProjectDefinition`] answers with.** @@ -864,17 +955,45 @@ impl ProjectIndex { } } - /// **The parameter facts of the declaration whose name starts at `offset`**, through its source summary. This is - /// what a fact-only signature fallback uses when it has a file and an offset rather than a `DeclFact`. + /// **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 Some(summary) = self.summaries.get(&normalize(file)) else { - return &[]; - }; - summary - .declarations - .iter() - .find(|fact| fact.name_range.start_offset == offset) - .map_or(&[], |fact| summary.parameter_facts(fact)) + 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); + } + if let Some(id) = self.view_file_id(file) + && let Ok(arena) = self.synthetic_facts.lock() + && let Some(entry) = arena.iter().find(|entry| { + entry.file.index() as u32 == id && 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 written type spelling of a fact**, for a display consumer — an owned string produced at this edge. @@ -935,8 +1054,10 @@ impl ProjectIndex { /// /// A summary built from syntax carries a local `TypeTable` — the IDs its facts hold are indices into that table, /// not into this store. Importing rewrites them to this store's IDs, so a stored fact's handle can be resolved by - /// [`ProjectIndex::computed_type_of`] with no second store and no spelling in between. A summary read back from - /// the cache takes the same path; a synthesized fact carries no ID and is untouched. + /// [`ProjectIndex::computed_type_of`] with no second store and no spelling in between. The summary's parameter + /// table holds handles into the same table, so [`ParamsStore::remap_types`] is the other half of the same step — + /// and it is the only half now that a declaration no longer carries parameter facts of its own. A summary read + /// back from the cache takes the same path; a synthesized fact carries no ID and is untouched. fn intern_the_types_of(&mut self, summary: &mut FileSummary) { if !summary.types.is_empty() { let mapping = self.types.import(&summary.types); @@ -952,13 +1073,6 @@ impl ProjectIndex { { *id = *store_id; } - if let Some(detail) = fact.detail.as_mut() { - for parameter in &mut detail.parameter_facts { - if let Some(store_id) = mapping.get(¶meter.type_of.raw()) { - parameter.type_of = *store_id; - } - } - } } } let ids: Vec<_> = summary @@ -979,6 +1093,10 @@ impl ProjectIndex { fn intern_the_types_of_a_reading(&mut self, reading: &mut CookedFile) { if !reading.types.is_empty() { let mapping = self.types.import(&reading.types); + // **The parameter table's handles are local to the same table**, so they are rewritten by the same + // mapping the declarations' handles are. Doing it here is what lets a cooked fact's `ParamsId` resolve + // against its own reading later (see [`ProjectIndex::parameter_facts_of`]). + reading.parameters.remap_types(&mapping); for fact in &mut reading.declarations { if let DeclaredType::Stored(id) = &mut fact.type_of && let Some(store_id) = mapping.get(&(id.index() as u32)) @@ -990,13 +1108,6 @@ impl ProjectIndex { { *id = *store_id; } - if let Some(detail) = fact.detail.as_mut() { - for parameter in &mut detail.parameter_facts { - if let Some(store_id) = mapping.get(¶meter.type_of.raw()) { - parameter.type_of = *store_id; - } - } - } } } // **The reading's table is rewritten alongside the handles**, exactly as a summary's is. Without this the 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 65d7a522..73ffced9 100644 --- a/crates/cpp_code_analysis/src/index/project/member_candidates.rs +++ b/crates/cpp_code_analysis/src/index/project/member_candidates.rs @@ -64,7 +64,8 @@ pub(crate) fn member_candidates( root, class, binding, - ), + ) + .fact, path.to_path_buf(), ) }) diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 1d582876..352a29db 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -2069,15 +2069,18 @@ pub(crate) fn direct_members( .map(|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. - let fact = fact_from_binding_with(shapes, root, class, binding); - match index.fact_ref_matching(path, &fact) { + // 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, fact), + None => { + index.intern_a_view_fact(path, synthesized.fact, synthesized.parameters) + } } }) .collect(), @@ -2109,10 +2112,12 @@ pub(crate) fn direct_members( data.bindings .iter() .map(|binding| { - let fact = fact_from_binding_with(shapes, root, &qualified, binding); - match index.fact_ref_matching(path, &fact) { + 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, fact), + None => { + index.intern_a_view_fact(path, synthesized.fact, synthesized.parameters) + } } }) .collect(), diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 5eeb356c..e84a1ae5 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -117,6 +117,16 @@ pub struct CookedFile { /// with it so the ID can be rewritten once at insertion. A reading built by hand (a test, a caller with facts and /// no parse) leaves it empty and uses the facts' synthetic computed types instead. pub types: crate::index::types::TypeTable, + /// **The reading's local parameter table**, indexed by [`DeclFact::parameters`] — the same contract + /// [`CookedFile::types`] 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 and remaps this + /// table once, exactly as it does the type table. + /// + /// 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: crate::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. /// @@ -151,6 +161,7 @@ impl CookedFile { CookedFile { declarations, types: crate::index::types::TypeTable::default(), + parameters: crate::index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: Vec::new(), unplaced: 0, @@ -166,6 +177,7 @@ impl CookedFile { .map(DeclFact::heap_bytes) .sum::() + self.types.heap_bytes() + + self.parameters.accounting() + self.macros.iter().map(MacroFact::heap_bytes).sum::() + self.diagnostics.len() * size_of::() } @@ -183,6 +195,7 @@ impl From for CookedFile { CookedFile { declarations: indexed.summary.declarations, types: indexed.summary.types, + parameters: indexed.summary.parameters, macros: indexed.summary.macros, diagnostics: indexed.diagnostics, unplaced: indexed.unplaced, @@ -573,10 +586,21 @@ pub struct ProjectIndex { /// **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 the one case — 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 only a configured Unreal project generates such members. - synthetic_facts: std::sync::Mutex>, + /// 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. /// @@ -615,6 +639,22 @@ impl ViewFactPaths { 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: crate::FileId, + fact: &'static DeclFact, + parameters: &'static [crate::index::params::ParameterFact], } /// One entry of [`ProjectIndex::member_lists`]: the members, and **what the answer was made of**. diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 28336c8d..d289e17e 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -4551,3 +4551,89 @@ 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 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 + .types() + .type_ref(parameters[0].type_of) + .expect("the parameter's type was imported with the reading") + .display(), + "double" + ); +} diff --git a/crates/cpp_code_analysis/src/index/store.rs b/crates/cpp_code_analysis/src/index/store.rs index f96d8319..a9453606 100644 --- a/crates/cpp_code_analysis/src/index/store.rs +++ b/crates/cpp_code_analysis/src/index/store.rs @@ -1300,6 +1300,8 @@ impl SummaryStore { // **The same local table the summary holds.** Both records index the same handles; each is imported into // the index's one store at its own insertion edge, and hash-consing makes the two imports agree. types: indexed.summary.types.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/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index 2f259592..af22dd5c 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -41,17 +41,15 @@ pub(crate) fn parameter_list_has_a_pack(list: &CppParamList) -> bool { }) } -/// The names of a declaration's parameters, from its CST-derived facts. -/// **The names from the summary arena, else from the raw fact's build-time copy.** The latter exists only for a -/// fact that has not been inserted through `ProjectIndex`; it is removed with that copy. +/// The names of a declaration's parameters, from the **index-resolved** CST facts. +/// +/// 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( - fact: &crate::DeclFact, indexed: &[crate::index::params::ParameterFact], ) -> Option>> { - if !indexed.is_empty() { - return parameter_names_of_facts(indexed); - } - parameter_names_of_facts(fact.parameter_facts()) + parameter_names_of_facts(indexed) } pub(crate) fn parameter_names_of_facts( 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 987e171c..a4dd8e13 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -397,12 +397,9 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec let Some(parameters) = fact.parameter_list() else { continue; }; - let indexed = context.index().parameter_facts_of(&file, fact); - let facts = if indexed.is_empty() { - fact.parameter_facts() - } else { - indexed - }; + // **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); let Some(callee) = the_callee_in_facts(facts, context.index().types(), parameters) .or_else(|| the_callee_in_text(parameters)) else { @@ -609,12 +606,7 @@ fn judge_a_member_call( let fact = context.index().member_fact(member)?; let parameters = context.index().member_parameter_list(member)?; let file = context.index().member_path(member)?; - let indexed = context.index().parameter_facts_of(file, fact); - let facts = if indexed.is_empty() { - fact.parameter_facts() - } else { - indexed - }; + let facts = context.index().parameter_facts_of(file, fact); the_callee_in_facts(facts, context.index().types(), ¶meters) .or_else(|| the_callee_in_text(¶meters)) }) diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index f80280a7..06a4a65c 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -95,17 +95,23 @@ use cpp_parser::{CppSyntaxNode, SourceRange}; 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: crate::index::params::ParamsStore, pub types: crate::index::types::TypeStore, } /// **A freshly built fact set for a caller that keeps no store**: each type handle is materialized and kept as the -/// fact's computed value, and the handle is cleared. +/// fact's computed value, and the handles are cleared. /// -/// [`build_facts`] returns a **local** `TypeStore`; 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 handles on those facts would let a query resolve an index into a store that was -/// dropped — another store's `TypeId(3)` — so they are bound here, once, into the computation layer. +/// [`build_facts`] returns a **local** `TypeStore` and a local `ParamsStore`; a caller that files the facts in a +/// summary hands the tables 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 them. Leaving the local handles on those facts would let a query resolve an +/// index into a store that was dropped — another store's `TypeId(3)` — so the type handles are bound here, once, into +/// the computation layer, and the parameter handle is cleared. pub fn facts_with_their_types(built: BuiltFacts) -> Vec { let BuiltFacts { mut facts, types, .. @@ -123,6 +129,11 @@ pub fn facts_with_their_types(built: BuiltFacts) -> Vec { .map_or(DeclaredType::None, |computed| { DeclaredType::Computed(std::sync::Arc::new(computed)) }); + // **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 — + // the same reason the two type handles above are materialized. A caller that needs a declaration's parameters + // asks the index (`ProjectIndex::parameter_facts_of`), which resolves through the summary that owns them. + fact.parameters = crate::index::params::ParamsId::NONE; } facts } @@ -138,34 +149,7 @@ pub fn build_facts( // half of the standard library's facts are those locals (measured on `import std;`: 29 067 of 61 337). keep_locals: bool, ) -> BuiltFacts { - let file = DeclarationFacts::new(scopes, preprocessing, root, errors, keep_locals); - let (mut facts, guards, mut types) = file.build(); - let mut parameters = crate::index::params::ParamsStore::new(); - for fact in &mut facts { - // The declaration's template parameters, so a parameter written `T&&` is stored as a parameter rather than a - // class called `T` — see [`TypeStore::intern_a_declared_type`]. - let template_parameters = fact.parameters().to_vec(); - let Some(detail) = fact.detail.as_mut() else { - continue; - }; - for parameter in &mut detail.parameter_facts { - if let Some(node) = parameter.declaration.to_node_from_root(root) - && let Some(cpp) = CppParam::cast(node) - { - parameter.type_of = - types.intern_a_declared_type(&cpp.get_type_text(), &template_parameters); - } - } - if !detail.parameter_facts.is_empty() { - fact.parameters = parameters.intern(detail.parameter_facts.to_vec()); - } - } - BuiltFacts { - facts, - guards, - parameters, - types, - } + 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. @@ -3595,7 +3579,9 @@ pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option } /// **Parameters as CST facts**, from the declarator the shape table already found. This is the only builder a fact -/// uses; [`DeclDetail::parameter_list`] is display fallback. +/// 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. pub(crate) fn declared_parameter_facts_with( shapes: &DeclarationShapes, binding: &Binding, @@ -3960,6 +3946,11 @@ fn fact_for( // interned **once**, here, at the construction edge — never on a query. `ProjectIndex::insert_at` imports this // table into the one global store and rewrites the handles; a query then materializes without parsing anything. types: &mut crate::index::types::TypeStore, + // **The summary's local parameter arena.** Each parameter's type is interned into `types` and the list itself 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 crate::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 @@ -4151,6 +4142,23 @@ 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.** The lowering of each parameter's type is + // done here, at the construction edge, so that the fact carries a `ParamsId` and the arena carries the list — no + // second copy of the list survives on the fact (see `DeclDetail`). The declaration's template parameters are + // passed to the interner so a parameter written `T&&` is stored as a parameter rather than as a class called `T` + // — see [`TypeStore::intern_a_declared_type`]. + let parameter_facts = { + let mut declared = declared_parameter_facts_with(shapes, binding); + for parameter in &mut declared { + if let Some(node) = parameter.declaration.to_node_from_root(root) + && let Some(cpp) = CppParam::cast(node) + { + parameter.type_of = types.intern_a_declared_type(&cpp.get_type_text(), ¶meters); + } + } + parameter_arena.intern(declared) + }; + // **The type handles, interned at the construction edge.** The two spellings above are the only place this fact // ever sees the text of a type; storing a handle here is what lets every later query materialize a // `ComputedType` without parsing. An empty spelling means "no type to name", which is the handle `NONE` — the @@ -4194,7 +4202,7 @@ fn fact_for( local, type_of: DeclaredType::from_stored(type_of_id), returns: DeclaredType::from_stored(returns_id), - parameters: crate::index::params::ParamsId::NONE, + parameters: parameter_facts, split_by_a_directive, detail: summary::DeclDetail::in_a_box(summary::DeclDetail { in_namespace: in_namespace.map(Into::into), @@ -4209,7 +4217,6 @@ fn fact_for( parameter_defaults: parameter_defaults.into_iter().map(SmolStr::from).collect(), pattern: pattern.map(Into::into), parameter_list: parameter_list.map(Into::into), - parameter_facts: declared_parameter_facts_with(shapes, binding).into_boxed_slice(), }), access, exported, @@ -4830,6 +4837,10 @@ struct DeclarationFacts<'a> { /// with the facts so that [`crate::FileIndexer::index_tree`] can put it in the summary and the index can import /// it once, at insertion. types: crate::index::types::TypeStore, + /// **The summary's local parameter arena**, filled by [`fact_for`] as each declaration's parameters are interned. + /// Returned beside the facts for the same reason the type table is, and this is the only place the parameter list + /// is stored — a fact holds a `ParamsId`, never the list itself. + parameters: crate::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, @@ -4853,10 +4864,11 @@ impl<'a> DeclarationFacts<'a> { guards: SummaryGuards::default(), facts: Vec::new(), types: crate::index::types::TypeStore::new(), + parameters: crate::index::params::ParamsStore::new(), } } - fn build(self) -> (Vec, SummaryGuards, crate::index::types::TypeStore) { + 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 { @@ -4869,6 +4881,7 @@ impl<'a> DeclarationFacts<'a> { mut guards, mut facts, mut types, + mut parameters, } = self; // per declaration copies the whole file each time. @@ -4948,6 +4961,7 @@ impl<'a> DeclarationFacts<'a> { in_namespace.clone(), &declarations, &mut types, + &mut parameters, ) { facts.push(fact); } @@ -4989,7 +5003,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 @@ -5017,12 +5031,13 @@ impl<'a> DeclarationFacts<'a> { None, &declarations, &mut types, + &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) @@ -5067,7 +5082,12 @@ 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, types) + BuiltFacts { + facts, + guards, + parameters, + types, + } } } diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index e4b286a3..f5a8032a 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -1482,8 +1482,9 @@ impl Session { // 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. - let reference = index.intern_synthetic_fact(declared.file, fact); + // 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 { fact: reference, substitution: None, diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index efd7171d..604a5d72 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2027,7 +2027,6 @@ fn doc_comments( .map(ToString::to_string) .collect(); if let Some(found) = sema::call_syntax::parameter_names_of_fact( - fact, index.parameter_facts_of(path, fact), ) { names.extend(found.into_iter().flatten()); diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index f8dd866e..6d9ce465 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -1095,10 +1095,10 @@ impl Session { 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_of_fact( + let name = sema::call_syntax::parameter_names_of_fact(index.parameter_facts_of( + &chosen_file, &chosen_fact, - index.parameter_facts_of(&chosen_file, &chosen_fact), - )? + ))? .get(at) .cloned() .flatten()?; diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index c3c75ef2..81dc4b45 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -584,10 +584,10 @@ fn callable_object_parameter_names( if fact.name != "operator()" { continue; } - let Some(names) = parameter_names_of_fact( + let Some(names) = parameter_names_of_fact(index.parameter_facts_of( + index.member_path(member)?, fact, - index.parameter_facts_of(index.member_path(member)?, fact), - ) else { + )) else { continue; }; if names.len() != passed { @@ -702,8 +702,7 @@ fn constructor_parameter_names( let Some(file) = index.definition_path(declaration) else { continue; }; - let Some(names) = parameter_names_of_fact(fact, index.parameter_facts_of(file, fact)) - else { + let Some(names) = parameter_names_of_fact(index.parameter_facts_of(file, fact)) else { continue; }; if names.len() < passed { diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 7eed5dc6..6a31f768 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -273,6 +273,15 @@ struct ParameterFact { `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` beside its own `TypeTable`, imported at `insert_cooked`, because the +rendering's facts name handles in the rendering's table. 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 From 99c4053741d037d0a3f6d940c018560416056154 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 17:32:22 +0800 Subject: [PATCH 074/102] feat(files): use session VFS file ids at runtime ProjectIndex keeps a registered path<->FileId table; the session registers the id Vfs::load returns before indexing or inserting a buffer. file_id_of prefers it, with a high-bit fallback namespace for hand-built indexes/tests and the existing downward view namespace kept separate. path_of resolves VFS, view and fallback tables in that order; fact/member/definition/offered refs all work with both origins. Persisted records stay path-keyed. Tests cover namespace separation, conflict refusal, cache-load registration and open-buffer registration. Workspace tests (3606 passed) and clippy pass. --- .../src/index/project/macro_walk.rs | 150 +++++++++++---- .../src/index/project/mod.rs | 105 ++++++++++ .../src/index/project/tests.rs | 179 +++++++++++++++++- crates/cpp_code_analysis/src/session/edits.rs | 8 + .../cpp_code_analysis/src/session/indexing.rs | 11 +- .../src/session/tests/buffers.rs | 66 +++++++ crates/cpp_code_analysis/src/session/units.rs | 9 +- 7 files changed, 487 insertions(+), 41 deletions(-) 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 ed69bf96..6597ea7d 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -470,40 +470,76 @@ impl ProjectIndex { .map(|entry| entry.parameters) } - /// **The id a view fact's file was given, without minting one** — the read-only half of - /// [`ProjectIndex::view_paths`], paired with the summary sequence so one lookup answers for both kinds of file. - fn view_file_id(&self, path: &Path) -> Option { - let key = normalize(path); - if let Some(id) = self.sequence.get(&key) { - return Some(*id); - } - self.view_paths.lock().ok()?.get(path) + /// **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: crate::FileId) { + self.file_ids.register(path, id); } - /// **The runtime file id the index assigned this path.** The numbering is the index's insertion sequence; a - /// session that owns a VFS will pass its own [`crate::FileId`] here once the two tables are unified. + /// **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 { - self.sequence - .get(&normalize(path)) - .copied() - .map(crate::FileId::new) + 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 the index assigned this file id**, in the spelling every other query keys on. + /// **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: crate::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; - let Some(key) = self.order.get(&number) else { - // **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. - return self.view_paths.lock().ok()?.by_id.get(&number).copied(); - }; + 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())), @@ -686,8 +722,9 @@ impl ProjectIndex { }) } - /// **Resolve a `FactRef` to the immutable declaration.** The path is recovered from the index's sequence, - /// never from the fact itself. + /// **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 @@ -701,8 +738,7 @@ impl ProjectIndex { .get(reference.fact.index()) .map(|entry| entry.fact); } - let path = self.order.get(&(reference.file.index() as u32))?; - let key = normalize(Path::new(path)); + let key = normalize(self.path_of(reference.file)?); if reference.reading == 0 { return self .summaries @@ -767,10 +803,13 @@ impl ProjectIndex { /// **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 it has no ordinary [`crate::FileId`]; the index mints one in the view table - /// ([`ProjectIndex::view_paths`]) and keeps the path with 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 + /// 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( @@ -779,12 +818,15 @@ impl ProjectIndex { fact: DeclFact, parameters: Box<[ParameterFact]>, ) -> FactRef { - let file = { - let mut paths = self - .view_paths - .lock() - .expect("the view fact table is not poisoned"); - crate::FileId::new(paths.id_of(path)) + 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"); + crate::FileId::new(paths.id_of(path)) + } }; self.intern_synthetic_fact(file, fact, parameters) } @@ -973,10 +1015,24 @@ impl ProjectIndex { { return summary.parameter_facts(fact); } - if let Some(id) = self.view_file_id(file) + // **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(crate::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| { - entry.file.index() as u32 == id && entry.fact.name_range.start_offset == offset + ids.contains(&entry.file) && entry.fact.name_range.start_offset == offset }) { return entry.parameters; @@ -1962,6 +2018,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() @@ -1971,6 +2029,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 { @@ -2933,12 +3003,18 @@ impl ProjectIndex { ), }; + // **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: crate::FileId::new(file), + file: visible_file, reading, fact: DeclFactId::from_index(at), }, diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index e84a1ae5..eb08c640 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -287,12 +287,117 @@ 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(|| crate::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: crate::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: crate::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: crate::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 diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index d289e17e..f3d7aa28 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -16,11 +16,12 @@ 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; @@ -105,6 +106,182 @@ fn the_file<'a>(index: &'a ProjectIndex, definition: &ProjectDefinition) -> &'a .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: super::FactRef) -> ProjectMember { + ProjectMember { + fact, + substitution: None, + declared_in: "One".to_string(), + depth: 0, + ambiguous: false, + } +} + /// **The index interns a summary's type spellings once**, and two declarations of one type share the handle. /// /// The string fields are still the source a query may read during the transition; this test pins the store's side 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/tests/buffers.rs b/crates/cpp_code_analysis/src/session/tests/buffers.rs index 397353c3..9de4ed35 100644 --- a/crates/cpp_code_analysis/src/session/tests/buffers.rs +++ b/crates/cpp_code_analysis/src/session/tests/buffers.rs @@ -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/units.rs b/crates/cpp_code_analysis/src/session/units.rs index 9180f8c1..81e47390 100644 --- a/crates/cpp_code_analysis/src/session/units.rs +++ b/crates/cpp_code_analysis/src/session/units.rs @@ -115,9 +115,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. From 61d76cd0d6e9806a6e6792bbc0d42d65f7d17974 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 18:10:08 +0800 Subject: [PATCH 075/102] refactor(constraint): evaluate typed conditions Constraint evaluation now takes CppSyntaxNode conditions and ComputedType bindings; operators, is_same and traits are read from CST/token structure, and the string splitter/substituter/trait-call parser/declaration-text template-parameter parser are deleted. RequiresClause exposes its typed condition. Constant declaration detection reads token kinds; value_of(&str) remains only as the documented lexer boundary for non-CST macro bodies/tests. Workspace tests (3606 passed) and clippy pass. --- .../src/index/project/queries.rs | 168 ++-- crates/cpp_code_analysis/src/sema/constant.rs | 129 ++- .../cpp_code_analysis/src/sema/constraint.rs | 904 ++++++++++-------- crates/cpp_code_analysis/src/sema/types.rs | 51 + crates/cpp_code_analysis/tests/suite/types.rs | 307 ++++-- crates/cpp_parser/src/syntax/node/cpp/mod.rs | 30 +- 6 files changed, 945 insertions(+), 644 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 8ea3d20b..bf63b294 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -9,9 +9,16 @@ 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::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. @@ -578,62 +585,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; + return false; } - 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; - } - // **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. @@ -683,11 +676,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(ComputedType::from(&found)), _ => None, } }) @@ -711,33 +704,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_map(::cast) + .find_map(::cast) .and_then(|clause| sema::constraint::a_requires_clause_node(&clause)); - let condition_owned = requires_clause - .as_deref() - .map(str::to_string) - .or_else(|| sema::constraint::the_condition_of_node(&declaration_node)); + 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()?))) @@ -746,9 +736,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) => {} @@ -760,42 +750,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/sema/constant.rs b/crates/cpp_code_analysis/src/sema/constant.rs index 0b173763..1d1eba48 100644 --- a/crates/cpp_code_analysis/src/sema/constant.rs +++ b/crates/cpp_code_analysis/src/sema/constant.rs @@ -55,45 +55,46 @@ 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** — the public boundary. The analysis path uses -/// [`value_of_tokens`] with the CST's own tokens; this is for callers that only hold a spelling (a macro body, or a -/// test). +/// **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) @@ -171,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) }); @@ -198,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 @@ -210,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(), ); } } @@ -462,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 bf2d1a06..6f288b7e 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; +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,160 @@ 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; + match current { + ComputedType::Reference { to, .. } => { + reference = true; + current = to; + } + ComputedType::Qualified(qualified) => { + topmost_const |= qualified.is_const; + topmost_volatile |= qualified.is_volatile; + current = &qualified.of; + } + _ => break, } - if let Some(rest) = bare.strip_prefix("volatile ") { - bare = rest.trim(); - continue; + } + // **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; + } + ComputedType::Array { of, .. } => { + array = true; + current = of; + } + ComputedType::Function(_) => function = true, + ComputedType::Pack(of) => { + pack = true; + current = of; } - break; + _ => {} } - let mut pointers_start = bare; - while let Some(rest) = pointers_start.strip_suffix('*') { - pointers_start = rest.trim(); + // **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, + _ => break, + } } - 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"; + let scalar = match base { + ComputedType::Builtin(spelling) => Some(spelling.as_str()), + // **A name with no arguments is a scalar this layer can place** — `size_t`, `std::size_t`, `ptrdiff_t` + // are the standard's names for builtin types. A name *with* arguments is a class template, which is not. + ComputedType::Named(named) if named.arguments.is_empty() => Some(named.name.as_str()), + _ => 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::TemplateParameter(_) + | ComputedType::Auto + | ComputedType::DecltypeAuto => true, + ComputedType::Named(named) if named.arguments.is_empty() => { + a_parameter_by_convention(&named.name) + } + ComputedType::Named(_) => false, + ComputedType::Builtin(name) => name.starts_with("decltype") || name == "auto", + _ => false, + }; - // The decorators answer for **any** type, known or not: `std::string&` is a reference whichever class `string` is. + // The scalar shape, read once, for the traits that are a property of it. + let integral = scalar.is_some_and(|scalar| { + !array + && !function + && !pack + && matches!( + scalar, + "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 = scalar.is_some_and(|scalar| { + !array && !function && !pack && matches!(scalar, "float" | "double" | "long double") + }); + let signed = integral + && scalar.is_some_and(|scalar| { + !scalar.starts_with("unsigned") && !matches!(scalar, "bool" | "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 => { - if unknown { - return None; - } - return Some(qualified_const); - } - Trait::Volatile => { - if unknown { - return None; - } - return Some(qualified_volatile); - } - Trait::Array => { - if unknown { - return None; - } - return Some(array); - } - Trait::Function => { - if unknown { - return None; - } - return Some(function); - } + 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 == Some("void") && !pointer && !reference && !array && !function, Trait::Signed => signed, Trait::Unsigned => integral && !signed, // Answered above, before the scalar was needed. @@ -200,289 +268,147 @@ 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 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) - }); - } - } - 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()); - } - - // **`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()); - } - - // **`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; - } - Trait::named(&trait_call.name)?.of(&argument) +/// `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<…>`; no declaration text is scanned. -pub fn the_condition_of_node(declaration: &cpp_parser::CppSyntaxNode) -> Option { - use cpp_parser::CppAstNode; +/// template argument of `enable_if<…>`/`enable_if_t<…>`, handed over as the typed expression node it was written as. +/// +/// 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 = cpp_parser::CppNameExpr::cast(node)?; - name.get_qualified_name() - .contains("enable_if") - .then_some(name) + 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(cpp_parser::CppTemplateArgList::cast)?; + .find_map(CppTemplateArgList::cast)?; let first = list.get_args().next()?; - let text = first.syntax().text().to_string(); - let text = text.trim(); - (!text.is_empty()).then(|| text.to_string()) + the_condition_in_a_template_argument(&first) +} + +/// **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()); + } + 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. +/// 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. -/// **The condition a `CppRequiresClause` states**, read from its own tokens. This is the CST entry point; the text -/// form remains for callers that only hold a spelling. -pub fn a_requires_clause_node(clause: &cpp_parser::CppRequiresClause) -> Option { - clause.get_condition_text() -} - -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`. -/// -/// 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) } @@ -492,74 +418,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(ComputedType::from(&marked).substituted(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/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 3ba4204d..76acf30c 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -2031,6 +2031,57 @@ pub fn type_of_declaration_named( wrapped } +/// **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; + } + 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 = Type::Array { + of: Arc::new(wrapped), + extent: array_extent(&child), + }; + } else if CppParamList::can_cast(child.kind().into()) { + wrapped = Type::Function { + returns: Arc::new(wrapped), + parameters: read_parameters(&child), + }; + } + } + Some(wrapped) +} + /// **The range of the identifier a declarator declares** — its first `NameExpr`, which is the name. /// /// First and not last, and the order is the opposite of the one `parameters_of` uses for a good reason: a diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index a7d5dde1..2bd888df 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2755,120 +2755,313 @@ std::string f() { } /// **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_node}; + use cpp_code_analysis::index::types::ComputedType; + use cpp_code_analysis::sema::constraint::{ + a_requires_clause_node, satisfies, the_condition_of_node, + }; + use cpp_code_analysis::sema::types::{Qualifiers, Type}; + 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" + )) + } + + /// The deducer's binding: `T` stands for one structured type. + fn bind(written: Type) -> Vec<(SmolStr, ComputedType)> { + vec![(SmolStr::new("T"), ComputedType::from(&written))] + } - let bind = |spelling: &str| vec![("T".to_string(), spelling.to_string())]; - let condition = |written: &str| { - let tree = cpp_parser::CppParser::parse(written, cpp_parser::ParserConfig::default()); - the_condition_of_node(&tree.get_red_root()) + let a_reference = |of: Type| Type::Reference { + to: Arc::new(of), + rvalue: false, + }; + let an_rvalue_reference = |of: Type| Type::Reference { + to: Arc::new(of), + rvalue: true, + }; + let a_const = |of: Type| Type::Qualified { + of: Arc::new(of), + qualifiers: Qualifiers::CONST, + }; + let a_volatile = |of: Type| Type::Qualified { + of: Arc::new(of), + qualifiers: Qualifiers::VOLATILE, + }; + let a_pointer = |of: Type| Type::Pointer { to: Arc::new(of) }; + let an_array = |of: Type, extent: Option| Type::Array { + of: Arc::new(of), + extent, + }; + let a_function = |returns: Type, parameters: Vec| Type::Function { + returns: Arc::new(returns), + parameters, }; // The two declarations of `describe`, verbatim. - let integral = condition( + 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(Type::builtin("int"))), + Some(true) + ); + assert_eq!( + satisfies(&integral, &bind(Type::builtin("double"))), + Some(false) + ); assert_eq!( - satisfies(&integral, &bind("std::string")), + satisfies(&integral, &bind(Type::named("std::string"))), Some(false), "a class is not integral" ); - let floating = condition( + 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(Type::builtin("double"))), + Some(true) + ); + assert_eq!( + satisfies(&floating, &bind(Type::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(Type::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(Type::builtin("double")) + ), + Some(true) + ); + assert_eq!( + satisfies( + &with_requires("std::is_integral::value && !std::is_same::value"), + &bind(Type::builtin("int")) + ), + Some(true) + ); + assert_eq!( + satisfies( + &with_requires("std::is_integral::value || std::is_floating_point::value"), + &bind(Type::builtin("float")) + ), Some(true) ); assert_eq!( satisfies( - "std::is_integral::value && !std::is_same::value", - &bind("int") + &with_requires("std::is_same"), + &bind(Type::builtin("char")) ), Some(true) ); assert_eq!( satisfies( - "std::is_integral::value || std::is_floating_point::value", - &bind("float") + &with_requires("std::is_same_v"), + &bind(Type::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(Type::builtin("int")) + ), + Some(true), + "the same class template with the same argument" + ); + assert_eq!( + satisfies( + &with_requires("std::is_same"), + &bind(a_reference(Type::builtin("int"))) ), Some(true) ); + assert_eq!( - satisfies("std::is_user_defined::value", &bind("int")), + satisfies( + &with_requires("std::is_user_defined::value"), + &bind(Type::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(Type::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(Type::builtin("int")), + true, + ), + ( + "std::is_reference_v", + an_rvalue_reference(Type::builtin("int")), + true, + ), + ("std::is_reference_v", Type::builtin("int"), false), + ( + "std::is_reference_v", + a_reference(Type::named("std::string")), + true, + ), + ("std::is_const_v", a_const(Type::builtin("int")), true), + ("std::is_const_v", Type::builtin("int"), false), + ( + "std::is_const_v", + a_pointer(a_const(Type::builtin("int"))), + false, + ), + ( + "std::is_volatile_v", + a_volatile(Type::builtin("int")), + true, + ), + ("std::is_volatile_v", Type::builtin("int"), false), + ( + "std::is_array_v", + an_array(Type::builtin("int"), Some(4)), + true, + ), + ( + "std::is_array_v", + an_array(Type::builtin("int"), None), + true, + ), + ("std::is_array_v", Type::builtin("int"), false), + ( + "std::is_function_v", + a_function(Type::builtin("int"), vec![Type::builtin("int")]), + true, + ), + ("std::is_function_v", Type::builtin("int"), false), + ( + "std::is_pointer_v", + a_pointer(Type::builtin("int")), + true, + ), + ("std::is_pointer_v", Type::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(Type::named("std::string")) + ), 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!( - condition("void plain(int value)"), + satisfies( + &with_requires("std::is_const_v"), + &bind(Type::named("U")) + ), + None + ); + assert_eq!( + satisfies( + &with_requires("std::is_class_v"), + &bind(Type::named("std::string")) + ), 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. diff --git a/crates/cpp_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 4cc81143..d66e04af 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -1369,25 +1369,17 @@ impl CppRequiresClause { syntax::node::traits::subtree_text_spaced(self.syntax()) } - /// **The condition the clause states**, without the `requires` keyword — `None` for a requires-expression - /// (`requires { … }`), which states no condition this layer can decide. Token-based, so a comment or a newline - /// between the keyword and the condition does not change the answer. - pub fn get_condition_text(&self) -> Option { - let mut tokens = self - .syntax() - .descendants_with_tokens() - .filter_map(|element| element.into_token()) - .filter(|token| !syntax::node::traits::is_trivia(token.kind().into())) - .map(|token| token.text().to_string()); - let keyword = tokens.next()?; - if keyword != "requires" { - return None; - } - let rest: Vec = tokens.collect(); - if rest.first().is_some_and(|token| token == "{") { - return None; - } - (!rest.is_empty()).then(|| rest.join(" ")) + /// **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) } } From b508d0c4b4c71c51a8ff907c0dc93a758618fd6f Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 18:50:30 +0800 Subject: [PATCH 076/102] refactor(convert): take parsed target types The conversion core is now conversion_to(from: &Type, target: &Type, tagged_record, family, class_question); it never parses a spelling. strip_references and the string-target conversion are removed. Callers parse their written declaration once at the boundary (assign/param/return/concept/overload) and pass Type plus explicit C tag metadata; parameter candidates are parsed once when built rather than per comparison. Conversion tests use Type values and keep the C record, pointer-bool, class and template-parameter cases. Workspace tests (3606 passed) and clippy pass. --- .../src/index/project/calls.rs | 11 +- .../src/sema/check/assign_type_check.rs | 18 +- .../src/sema/check/concept_not_satisfied.rs | 18 +- .../src/sema/check/param_type_check.rs | 159 ++++++++++++------ .../src/sema/check/return_type_mismatch.rs | 22 ++- crates/cpp_code_analysis/src/sema/convert.rs | 142 +++++++++------- .../cpp_code_analysis/tests/suite/checks.rs | 2 +- crates/cpp_code_analysis/tests/suite/types.rs | 75 ++++++++- 8 files changed, 308 insertions(+), 139 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index fc0bf5d6..82e0c396 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -699,7 +699,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`). @@ -842,7 +842,14 @@ 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 crosses from spelling to type once, here** — the declaration layer records parameters + // as text (`parameters_in` split them for the arity check), and the conversion question takes `Type`s. + // Doing it in this closure parses each parameter exactly once per candidate rather than once per + // comparison, and the C tag (`struct point`) is read from the same spelling as boundary metadata. + let target = parse_type_spelling(parameter); + let tagged_record = sema::convert::tagged_record_in(parameter); + !sema::convert::conversion_to(argument, &target, tagged_record, None, |_| None) + .is_refused() }) } 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 ff55126b..67ec8ff2 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 @@ -414,19 +414,25 @@ fn report_if_it_does_not_convert( } let known_from = context.type_of(expression); let target = sema::types::parse_type_spelling(written); + let tagged_record = sema::convert::tagged_record_in(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 parsed + // **here**, once, and the conversion question takes that `Type`; the C tag (`struct point`) is metadata the + // parsed type cannot carry, read from the same spelling at this boundary. // **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) { return; } - if sema::convert::conversion(&from, written, context.language.family(), |class| { - a_class_can_be_built_from(context, class, &from) - }) == sema::convert::Conversion::Refused + if sema::convert::conversion_to( + &from, + &target, + tagged_record, + context.language.family(), + |class| a_class_can_be_built_from(context, class, &from), + ) == sema::convert::Conversion::Refused { report(context, expression, name, how, written); return; 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 e3834425..14d85f9d 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 @@ -94,8 +94,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 `Type` — 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) { @@ -276,15 +278,21 @@ impl Concept { _ => Some(true), } } - Concept::ConvertibleTo(target) => { - let target = sema::types::parse_type_spelling(target); + Concept::ConvertibleTo(written) => { + // **The concept's argument, parsed once here.** The conversion below takes the `Type`, not a + // spelling: the old form wrote the parsed shape back out and parsed it again, which is a second + // reader of the same question. The tag is the written metadata a parsed type cannot carry. + let tagged_record = sema::convert::tagged_record_in(written); + let target = sema::types::parse_type_spelling(written); 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, tagged_record, None, |_| { + None + }), sema::convert::Conversion::Refused )), } 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 f5d6e0d0..81817c5e 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 @@ -68,8 +68,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() @@ -83,7 +85,12 @@ impl Check for ParamTypeCheck { // `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 declaration layer records parameters as spellings; this is the boundary where + // they become the parsed types the conversion question takes, so the conversion itself never parses. + let parameters: Vec = parameter_spellings_of(&function) + .into_iter() + .map(|written| CandidateParameter::from_spelling(&written)) + .collect(); let namespaces = enclosing_namespaces(&function); match by_name.entry(name) { std::collections::hash_map::Entry::Occupied(mut e) => { @@ -135,7 +142,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 +157,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 `Type`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; @@ -192,7 +199,7 @@ impl Check for ParamTypeCheck { 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(); }; @@ -206,10 +213,54 @@ fn member_parameter_lists( .iter() .filter(|member| context.model.member_name(member) == access.member) .filter_map(|member| context.model.member_parameter_list(member)) - .map(|written| sema::overload::parameters_in(&written).0) + .map(|written| { + sema::overload::parameters_in(&written) + .0 + .iter() + .map(|parameter| CandidateParameter::from_spelling(parameter)) + .collect() + }) .collect() } +/// **One candidate parameter, read once at this boundary** — the spelling the declaring file wrote (the finding +/// quotes it, and C's string-literal rule reads it) and the [`Type`](sema::types::Type) the conversion question +/// takes. +/// +/// The declaration layer records parameters as spellings (`DeclFact::parameter_list`), so this is where a candidate +/// crosses from text into structure. Parsing happens **once per candidate**, before any argument is compared, rather +/// than once per comparison; the conversion core never parses. `tagged_record` is the C tag the spelling carries +/// (`struct point`), the one piece of written metadata a `Type` cannot keep. +#[derive(Clone)] +struct CandidateParameter { + written: String, + type_of: sema::types::Type, + tagged_record: Option, +} + +impl CandidateParameter { + /// **From the spelling a declaration records** — parsed exactly once. + fn from_spelling(written: &str) -> Self { + Self { + written: written.to_string(), + type_of: sema::types::parse_type_spelling(written), + tagged_record: sema::convert::tagged_record_in(written).map(str::to_string), + } + } + + /// **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 + /// never writes a C tag; so there is no tag metadata to carry here. + fn from_type(type_of: &sema::types::Type) -> Option { + Some(Self { + written: a_spelling_of(type_of)?, + type_of: type_of.clone(), + tagged_record: None, + }) + } +} + /// **One call's arguments against every declaration the name has** — the comparison both paths make. /// /// # The rule for more than one declaration @@ -223,7 +274,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` @@ -246,60 +297,48 @@ 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 (`Type::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) { + if context + .a_string_literal_in_a_char_pointer_position(argument.syntax(), ¶meter.written) + { 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 the C tag is the metadata read from the same spelling at that boundary. + if !sema::convert::conversion_to( + &from, + ¶meter.type_of, + parameter.tagged_record.as_deref(), + 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; @@ -362,7 +401,10 @@ 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. @@ -391,8 +433,15 @@ fn the_index_declares_one(context: &CheckContext<'_>, name: &str) -> Option { - if !sema::types::parse_type_spelling(&declared).is_void() { + if !declared_type.is_void() { context.add( DiagnosticCode::ReturnTypeMismatch, source_range(returned.get_range()), @@ -125,14 +130,15 @@ impl Check for ReturnTypeMismatch { ) { 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, + declared_tag, context.language.family(), |class| a_class_can_be_built_from(context, class, &from), ); diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index 0ca22421..35be9082 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -4,6 +4,12 @@ //! 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 [`Type`](sema::types::Type); this module never parses the same spelling again. The one +//! piece of written evidence a parsed type cannot carry is C's tag (`struct point`), which crosses the boundary as +//! explicit metadata ([`tagged_record_in`]) rather than as a second reading of the text. +//! //! # 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, @@ -46,51 +52,56 @@ fn a_pointer(type_of: &sema::types::Type) -> bool { } } -/// **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: &sema::types::Type) -> &sema::types::Type { + match type_of { + sema::types::Type::Reference { to, .. } | sema::types::Type::Qualified { of: to, .. } => { + the_referent(to) + } + 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 [`Type`](sema::types::Type), 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. +/// +/// `tagged_record` is the one piece of **written metadata** a `Type` does not carry: the name after `struct`/`union` +/// when the target was written with C's tag syntax (`struct point *` answers `Some("point")`). It is read from the +/// CST or the written spelling at the caller's boundary — [`tagged_record_in`] is that reader — because a `Named` +/// type cannot say whether its name was tagged, and `typedef int point;` makes the tag the only evidence that the +/// name is a record. A C++ target passes whatever it read; this function consults the metadata only in C. /// /// `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( +/// `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: &sema::types::Type, - written: &str, + target: &sema::types::Type, + tagged_record: Option<&str>, 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, + target, sema::types::Type::Builtin { spelling } if spelling == "bool" || spelling == "_Bool" ) && a_pointer(from) @@ -100,42 +111,49 @@ 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*, which is why it arrives as metadata: + // 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. // // 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(record) = tagged_record + && !the_value_is_that_record(from, 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.** `Type::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, sema::types::Type::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 [`Type::class_name`](sema::types::Type::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; } @@ -149,15 +167,20 @@ pub fn conversion( /// **The record a spelling writes with its tag** — `struct point *` and `union value` answer the name; everything /// else answers `None`. /// -/// 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 { +/// This is **boundary metadata**, not part of [`Type`](sema::types::Type): C's own syntax writes `struct`/`union` +/// before a name as a tag, and no typedef can write one, so the word is the evidence the type algebra cannot keep. +/// A caller reads it here **once**, from the CST or from the written spelling it already holds, and hands it to +/// [`conversion_to`]; the conversion core never scans a string. +/// +/// `enum` is deliberately not here — an enumeration *is* an arithmetic type in C, and `enum colour c = 3;` is +/// ordinary code. +pub(crate) fn tagged_record_in(written: &str) -> Option<&str> { 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); + return words.next(); } } None @@ -182,17 +205,22 @@ fn the_value_is_that_record(type_of: &sema::types::Type, record: &str) -> bool { _ => 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 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* 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) +/// `_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. +/// +/// [`Type::TemplateParameter`](sema::types::Type::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: &sema::types::Type) -> bool { + match type_of { + sema::types::Type::TemplateParameter { .. } => true, + sema::types::Type::Pointer { to } + | sema::types::Type::Reference { to, .. } + | sema::types::Type::Qualified { of: to, .. } => names_a_template_parameter_for_a_check(to), + 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/tests/suite/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 96dc5582..80dbb454 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -4257,7 +4257,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() { diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 2bd888df..2595901c 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -3439,33 +3439,98 @@ 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**: a caller parses the written target once at its own boundary, and +/// the C tag (`struct point`) is metadata read from that spelling there, because a `Named` type cannot say whether its +/// name was written with one. 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::convert::{Conversion, conversion_to}; use cpp_code_analysis::sema::types::{Type, parse_type_spelling}; + use cpp_parser::features::Family; let an_int = Type::builtin("int"); assert_eq!( - conversion(&an_int, "_Ty2&&", None, |_| None), + conversion_to(&an_int, &parse_type_spelling("_Ty2&&"), None, 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, |_| 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 = Type::TemplateParameter { + name: "T".to_string(), + }; + assert_eq!( + conversion_to(&an_int, &a_parameter, None, None, |_| None), + Conversion::Unknown, + "`Type::TemplateParameter` 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, + 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, &Type::builtin("int"), None, None, |_| None), Conversion::Unknown ); + // **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, &Type::builtin("bool"), None, None, |_| None), + Conversion::Implicit, + ); + // **In C, a tagged record is nobody else's type** — the tag is metadata the `Type` cannot carry, so the caller + // passes it from the written spelling (`struct point *`) and the core stays structural. + let a_record_pointer = parse_type_spelling("struct point *"); + assert_eq!( + conversion_to( + &parse_type_spelling("int *"), + &a_record_pointer, + Some("point"), + 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("point"), + Some(Family::C), + |_| None + ), + Conversion::Implicit, + "and the record itself converts to the same record" + ); + // **The gate matters**: the same pair without the C tag metadata is `Unknown`, not a refusal — the type algebra + // cannot tell the name is a record, and the safe direction is silence. + assert_eq!( + conversion_to( + &parse_type_spelling("int *"), + &a_record_pointer, + None, + Some(Family::C), + |_| None + ), + Conversion::Unknown, + ); } /// **A member's deduced return type, through the header that declares it** — `auto copy_of() const { return value_; }`. From 05462eeaab2a3e12f2dbaa6a1088da2eb462d210 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Thu, 3 Dec 2026 20:18:08 +0800 Subject: [PATCH 077/102] refactor(params): lower parameter and return types structurally ParameterFact.type_of is now DeclaredType (None/Stored/Computed); parameter types are lowered from CppParam CST via type_of_a_parameter + with_template_parameters + TypeStore::intern_type, with the written spelling only for display. Parameter and return consumers (overload ranking, deduction, param/assign/return checks, argument count, completion hints, signature help, call declaration resolution) use ComputedType/Type through ProjectIndex resolvers. View/display facts carry ComputedType, never a second store. The overload parameter-list parsers (parameters_in, a_type_without_its_name, defaults_in) are deleted. Workspace tests (3608 passed) and clippy pass. Remaining spelling boundaries are list-level '...' detection and C struct/union tag metadata, documented. --- crates/cpp_code_analysis/src/cache/summary.rs | 2 +- .../src/cache/summary_codec.rs | 16 +- crates/cpp_code_analysis/src/index/params.rs | 45 +- .../src/index/project/bases.rs | 42 +- .../src/index/project/calls.rs | 301 +++++---- .../src/index/project/macro_environment.rs | 8 + .../src/index/project/macro_walk.rs | 68 +- .../src/index/project/member_candidates.rs | 38 +- .../src/index/project/substituted.rs | 43 +- .../src/index/project/tests.rs | 40 +- .../src/index/project/type_of.rs | 19 +- .../src/index/types/compute.rs | 72 +++ .../cpp_code_analysis/src/index/types/mod.rs | 9 +- .../src/sema/check/argument_count.rs | 116 ++-- .../src/sema/check/assign_type_check.rs | 142 +++-- .../src/sema/check/missing_include.rs | 4 +- .../cpp_code_analysis/src/sema/check/mod.rs | 250 ++++---- .../src/sema/check/param_type_check.rs | 214 +++++-- .../src/sema/check/return_type_mismatch.rs | 41 +- .../src/sema/declarations.rs | 27 +- .../cpp_code_analysis/src/sema/deduction.rs | 317 ++++++---- crates/cpp_code_analysis/src/sema/overload.rs | 583 +++++++----------- crates/cpp_code_analysis/src/sema/types.rs | 26 + crates/cpp_code_analysis/src/session/calls.rs | 87 ++- .../src/session/completion/request.rs | 49 +- .../src/session/signature.rs | 65 +- crates/cpp_code_analysis/tests/params.rs | 125 +++- .../cpp_code_analysis/tests/suite/checks.rs | 15 +- crates/cpp_ls/src/handlers/definition/mod.rs | 17 +- crates/cpp_ls/src/handlers/hover/mod.rs | 47 +- docs/type-system-redesign.md | 8 +- 31 files changed, 1692 insertions(+), 1144 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 768cf8d1..f8405ba3 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -146,7 +146,7 @@ impl DeclModifiers { /// global store, and [`DeclaredType::Computed`] is a value for which no `TypeId` exists at all. /// /// [`TypeStore`]: crate::index::types::TypeStore -#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub enum DeclaredType { /// The declaration states no type, or none this reading could reach. #[default] diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 7d7db319..d1b414d2 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1149,7 +1149,16 @@ fn put_parameter_facts(out: &mut Vec, facts: &[crate::index::params::Paramet None => put_u8(out, 0), } put_u8(out, u8::from(fact.pack)); - put_u32(out, fact.type_of.raw()); + // **Only a stored handle is written.** A parameter fact filed in a summary or a cooked reading holds + // `DeclaredType::Stored`; `Computed` is a query-synthesized value with no `TypeId` to invent, and `None` is + // the empty answer — both are the `NONE` sentinel on disk, which is also what an older reader expects here. + put_u32( + out, + fact.type_of + .stored_id() + .unwrap_or(TypeId::NONE) + .raw(), + ); } } @@ -1180,7 +1189,8 @@ fn get_parameter_facts( _ => return Err(DecodeError::BadDiscriminant), }; let pack = reader.u8()? != 0; - let type_of = TypeId::from_raw(reader.u32()?); + // The on-disk form is the handle, or `NONE`; a record never carries a computed value (see `put_parameter_facts`). + let type_of = DeclaredType::from_stored(TypeId::from_raw(reader.u32()?)); facts.push(crate::index::params::ParameterFact { name, declaration, @@ -2380,7 +2390,7 @@ fn a_cooked_reading_round_trips() { .expect("a syntax id"), default_value: None, pack: false, - type_of: TypeId::from_raw(0), + type_of: DeclaredType::Stored(TypeId::from_raw(0)), }, ] .into_boxed_slice()]), diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index 20e3d18b..ba3c3243 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -4,9 +4,15 @@ //! 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 type of a parameter is a [`TypeId`] in the target schema. Until the CST type-lowering lands it is -//! [`TypeId::NONE`]; the field is deliberately an ID rather than a spelling, so adding the lowering is not a schema -//! change to every consumer. +//! **The type is a [`DeclaredType`], the same enum a [`DeclFact`](crate::DeclFact)'s own types use.** A parameter a +//! summary or a cooked reading filed holds [`DeclaredType::Stored`] — a handle into the one global +//! [`TypeStore`](crate::index::types::TypeStore), lowered from the parameter's own `CppParam` node by +//! [`crate::sema::declarations`] at construction. A parameter fact a query synthesized from a view has no arena to +//! intern into, so it holds [`DeclaredType::Computed`], the value the builder already has. There is **no spelling +//! field**: [`crate::ProjectIndex::parameter_type`] resolves either kind to a +//! [`ComputedType`](crate::index::types::ComputedType), and nothing re-parses a type on the way. +//! +//! [`DeclFact`]: crate::DeclFact use cpp_parser::CppAstNode; use cpp_parser::CppInitializer; use cpp_parser::CppParam; @@ -16,6 +22,7 @@ use cpp_parser::CppTokenKind; use smol_str::SmolStr; use super::types::TypeId; +use crate::cache::summary::DeclaredType; use rustc_hash::FxHashMap; use std::mem::size_of; @@ -30,8 +37,9 @@ pub struct ParameterFact { pub default_value: Option, /// A parameter pack / ellipsis parameter. pub pack: bool, - /// Filled by the CST type lowering; `NONE` until that phase lands. - pub type_of: TypeId, + /// **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. @@ -124,17 +132,26 @@ impl ParamsStore { /// **Rewrite the parameter type handles after a summary's type table is imported.** The keys are the local /// `TypeId` values the summary was encoded with. + /// + /// Only [`DeclaredType::Stored`] moves: a view fact's [`DeclaredType::Computed`] names no arena, and + /// [`DeclaredType::None`] is not a handle at all. pub fn remap_types(&mut self, mapping: &FxHashMap) { for facts in &mut self.entries { for fact in facts.iter_mut() { - if let Some(store_id) = mapping.get(&fact.type_of.raw()) { - fact.type_of = *store_id; + if let DeclaredType::Stored(id) = fact.type_of + && let Some(store_id) = mapping.get(&id.raw()) + { + fact.type_of = DeclaredType::Stored(*store_id); } } } } /// **Import another store's local handles**, deduplicating against this one. + /// + /// A [`DeclaredType::Stored`] handle travels as it is: it is valid only after the type table it names has been + /// imported into the one global store, which is [`ParamsStore::remap_types`]'s job and happens at the same edge + /// that imports a summary's or a reading's types. pub fn import(&mut self, from: &ParamsStore) -> FxHashMap { let mut mapping = FxHashMap::default(); for (at, facts) in from.entries.iter().enumerate() { @@ -169,7 +186,10 @@ fn fact_of(parameter: CppParam) -> ParameterFact { .descendants_with_tokens() .filter_map(|element| element.into_token()) .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Ellipsis), - type_of: TypeId::NONE, + // **No type yet.** Lowering it needs a `TypeStore` (or the computation layer, for a view), so the two + // builders that own one fill this in — see `crate::sema::declarations::fact_for` and + // `crate::index::project::fact_from_binding_with`. This reader is the CST half only. + type_of: DeclaredType::None, } } @@ -206,11 +226,10 @@ mod tests { ); assert_eq!(facts[2].name.as_deref(), Some("rest")); assert!(facts[2].pack); - assert_eq!( - facts[2].type_of, - TypeId::NONE, - "until the type lowering lands" - ); + // **The CST reader states no type** — lowering needs a store (or the computation layer, for a view), and both + // builders that own one 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] diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 3c870237..106400ed 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -12,8 +12,12 @@ use crate::ScopeTree; 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, @@ -247,13 +251,14 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { /// **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, no interning, and -/// every parameter's `type_of` is [`crate::index::types::TypeId::NONE`] because a view path has no type store to lower -/// into. 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. +/// 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`, because a view path has no store to intern into and inventing a `TypeId` from a +/// 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. pub(crate) struct SynthesizedFact { pub fact: DeclFact, pub parameters: Box<[crate::index::params::ParameterFact]>, @@ -350,11 +355,24 @@ pub(crate) fn fact_from_binding_with( let type_of = computed(written_type_of); let returns = computed(written_returns.clone()); // **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`]). Its - // parameter types stay [`crate::index::types::TypeId::NONE`]: lowering them needs the file's `TypeStore`, and a - // view path has none — the display and name readers of these facts do not need a type. - let parameters = sema::declarations::declared_parameter_facts_with(shapes, binding) - .into_boxed_slice(); + // 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 `TypeId` is invented and no spelling is parsed. + let parameters = { + let mut parameters = sema::declarations::declared_parameter_facts_with(shapes, binding); + 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(ComputedType::from(&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), diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 82e0c396..1395ef16 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -758,8 +758,20 @@ 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 variadic = candidate_fact + .parameter_list() + .is_some_and(|list| list.contains("...")); + let parameters = candidate_fact + .parameter_list() + .is_some() + .then(|| index.parameter_types_of(file, candidate_fact)); if !a_candidate_that_can_be_called_this_way( - candidate_fact.parameter_list(), + parameters.as_deref(), + variadic, argument_types, how_many_arguments, ) { @@ -804,27 +816,30 @@ 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 converts the parameter structurally (no spelling, no parse) +/// and passes no C tag: the tag rule only applies when the caller knows the language is C, and this one does not. pub(crate) fn a_candidate_that_can_be_called_this_way( - parameter_list: Option<&str>, + parameters: Option<&[crate::index::types::ComputedType]>, + variadic: bool, argument_types: &[Type], 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 { @@ -842,14 +857,10 @@ pub(crate) fn a_candidate_that_can_be_called_this_way( .iter() .zip(argument_types) .all(|(parameter, argument)| { - // **The parameter crosses from spelling to type once, here** — the declaration layer records parameters - // as text (`parameters_in` split them for the arity check), and the conversion question takes `Type`s. - // Doing it in this closure parses each parameter exactly once per candidate rather than once per - // comparison, and the C tag (`struct point`) is read from the same spelling as boundary metadata. - let target = parse_type_spelling(parameter); - let tagged_record = sema::convert::tagged_record_in(parameter); - !sema::convert::conversion_to(argument, &target, tagged_record, 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.to_sema_type(); + !sema::convert::conversion_to(argument, &target, None, None, |_| None).is_refused() }) } @@ -1050,20 +1061,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(index, &types, &callable, &[]) - && let Some((fact, file)) = callable.get(chosen) + && let Some(chosen) = the_one_the_arguments_select(&types, &callable, &[]) + && let Some(candidate) = callable.get(chosen) { return Known::Yes(NamedDeclaration::Indexed( - fact.clone(), - file.clone(), + candidate.fact.clone(), + candidate.file.clone(), bindings, )); } @@ -1095,31 +1110,36 @@ 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, - ) - .fact, - 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) + .map(crate::index::types::ComputedType::from) .collect(); if let Some(chosen) = - the_one_the_arguments_select(index, &types, &candidates, &explicit_arguments) + the_one_the_arguments_select(&types, &candidates, &explicit_arguments) && let Some(binding) = bindings.get(chosen) { return Known::Yes(NamedDeclaration::Here(binding.clone())); @@ -1400,25 +1420,26 @@ 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() .filter_map(|definition| { let (fact, file) = index.definition_parts(definition)?; - Some((fact.clone(), file.to_path_buf())) + 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) + .map(crate::index::types::ComputedType::from) .collect(); - let chosen = the_one_the_arguments_select(index, &types, &candidates, &explicit_arguments)?; - candidates.get(chosen).cloned() + let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?; + 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. @@ -1451,7 +1472,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 `Type`; this converts the representation and parses nothing. pub(crate) fn the_types_of_the_arguments( memo: &TypeMemo, index: &ProjectIndex, @@ -1460,7 +1482,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 @@ -1477,7 +1499,9 @@ 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( + crate::index::types::ComputedType::from(&type_of), + ), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), } @@ -1486,6 +1510,54 @@ 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 { + CandidateDeclaration { + fact: fact.clone(), + file: file.to_path_buf(), + parameters: sema::overload::DeclaredParameters::new( + index.parameter_types_of(file, fact), + fact.parameter_list().is_some_and(|list| list.contains("...")), + ), + } + } + + /// **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: &[crate::index::params::ParameterFact], + index: &ProjectIndex, + ) -> Self { + let types = parameters + .iter() + .filter_map(|parameter| index.parameter_type(parameter)) + .collect(); + let variadic = fact.parameter_list().is_some_and(|list| list.contains("...")) + || 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 @@ -1499,17 +1571,16 @@ 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( - index: &ProjectIndex, - types: &[Known], - candidates: &[(DeclFact, PathBuf)], - explicit_arguments: &[String], + types: &[Known], + candidates: &[CandidateDeclaration], + explicit_arguments: &[crate::index::types::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 @@ -1519,13 +1590,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: Vec = fact.parameters().iter().map(ToString::to_string).collect(); + .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`. @@ -1538,10 +1614,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()), @@ -1552,10 +1626,7 @@ pub(crate) fn the_one_the_arguments_select( format!("declaration {at}"), ); if substituted.1 { - candidate.with_declaration( - declared_for_ordering, - names.iter().map(ToString::to_string).collect(), - ) + candidate.with_declaration(declared_for_ordering, names) } else { candidate } @@ -1569,34 +1640,20 @@ 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, file) = &candidates[**at]; - { - let facts = index.parameter_facts_of(file, fact); - let parameters = if facts.is_empty() { - fact.parameter_list() - .map(|list| sema::overload::parameters_in(list).0) - .unwrap_or_default() - } else { - sema::overload::parameters_in_facts( - facts, - index.types(), - fact.parameter_list() - .is_some_and(|list| list.contains("...")), - ) - .0 - }; - parameters - .into_iter() - .next() - .and_then(|first| the_character_width(&first)) - == Some(written) - } + // **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() .collect(); @@ -1608,23 +1665,59 @@ 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: &crate::index::types::ComputedType) -> Option { + let mut wide = false; + let mut narrow = false; + let mut pending = vec![type_of]; + while let Some(current) = pending.pop() { + match current { + crate::index::types::ComputedType::Builtin(name) + | crate::index::types::ComputedType::TemplateParameter(name) => { + width_of_a_name(name, &mut wide, &mut narrow); + } + crate::index::types::ComputedType::Named(named) => { + width_of_a_name(&named.name, &mut wide, &mut narrow); + pending.extend(named.arguments.iter()); + } + crate::index::types::ComputedType::Pointer(to) + | crate::index::types::ComputedType::Pack(to) => pending.push(to), + crate::index::types::ComputedType::Reference { to, .. } + | crate::index::types::ComputedType::Array { of: to, .. } => pending.push(to), + crate::index::types::ComputedType::Function(function) => { + pending.push(&function.returns); + pending.extend(function.parameters.iter()); + } + crate::index::types::ComputedType::Qualified(qualified) => pending.push(&qualified.of), + crate::index::types::ComputedType::Auto + | crate::index::types::ComputedType::DecltypeAuto => {} + } + } + if wide { + Some(true) + } else if narrow { + Some(false) + } else { + None } - if spelling.contains("char") || spelling.contains("string") { - return Some(false); +} + +/// 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`]. /// 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 71776bba..595c4407 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -532,6 +532,14 @@ 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, } 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 6597ea7d..158ea5c9 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -416,13 +416,28 @@ impl ProjectIndex { if let Some(parameters) = self.synthetic_parameter_facts(fact) { return parameters; } - // `NONE` is the whole answer — no list was ever written — and returning here is what keeps a zero-parameter - // function from being matched to another declaration's list below. + 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() { - return &[]; + 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 key = normalize(file); - let Some(summary) = self.summaries.get(&key) else { + let Some(summary) = summary else { return &[]; }; if summary @@ -1106,6 +1121,49 @@ impl ProjectIndex { fact.returns.as_computed(&self.types) } + /// **One parameter's type as computation sees it.** A summary's or a cooked reading's parameter holds + /// [`DeclaredType::Stored`] and is materialized from the one global store; a view-synthesized parameter holds + /// [`DeclaredType::Computed`] and is cloned. Neither path interns anything, 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(&self.types) + } + + /// **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 spelling of one parameter's type**, for the display edge — a message quotes it and C's tag metadata + /// (`struct point`) is read from it; **nothing parses it**. A synthesized parameter prints its computed value; a + /// stored one answers the spelling the store recorded (the file's own words). + pub fn parameter_spelling( + &self, + parameter: &ParameterFact, + ) -> Option { + if let Some(computed) = parameter.type_of.computed() { + return Some(smol_str::SmolStr::new(computed.to_string())); + } + let id = parameter.type_of.stored_id()?; + self.types + .spelling(id) + .map(smol_str::SmolStr::new) + .or_else(|| { + self.types + .materialize(id) + .map(|computed| smol_str::SmolStr::new(computed.to_string())) + }) + } + /// **Import every type a summary carries into the index's one store**, once, before the summary is filed. /// /// A summary built from syntax carries a local `TypeTable` — the IDs its facts hold are indices into that table, 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 73ffced9..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,20 +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, - ) - .fact, - 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(); @@ -90,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 @@ -100,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; @@ -111,7 +121,7 @@ pub(crate) fn member_candidates( match index.definition(&format!("{class}::{member}"), path) { Known::Yes(found) => index .definition_parts(&found) - .map(|(fact, file)| (fact.clone(), file.to_path_buf())) + .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/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 5f7ede5c..acdf93a6 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -257,6 +257,10 @@ fn substituted_members_with( // 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(); + // **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; @@ -274,6 +278,9 @@ fn substituted_members_with( } 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)); + } } // **The per-member substitution context** — the class's parameters paired with this use's arguments, plus the @@ -314,7 +321,7 @@ fn substituted_members_with( Some(class) => names .iter() .zip(class.arguments().iter()) - .map(|(name, argument)| (name.clone(), argument.clone())) + .map(|(name, argument)| (name.clone(), an_argument_as_a_type(argument))) .collect(), None => { let mut bindings = Vec::with_capacity(names.len()); @@ -338,12 +345,13 @@ fn substituted_members_with( }; let parsed = parse_type_spelling(&written); let parsed = sema::types::with_template_parameters(parsed, &names); - bindings.push((name.clone(), ComputedType::from(&parsed))); + bindings.push((name.clone(), an_argument_as_a_type(&ComputedType::from(&parsed)))); } bindings } }; let substitution = MemberSubstitution { + alias_bindings, bindings, stages: vec![stage], }; @@ -361,11 +369,29 @@ fn substituted_members_with( Known::Yes(list) } +/// **One structured template argument as the type it names.** +/// +/// `read_template_arguments` answers [`ComputedType::Named`] 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 builtin type. +fn an_argument_as_a_type(argument: &ComputedType) -> ComputedType { + match argument { + ComputedType::Named(named) + if named.arguments.is_empty() && sema::types::is_a_builtin(&named.name) => + { + ComputedType::Builtin(named.name.clone()) + } + 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], } } @@ -380,9 +406,20 @@ impl MemberSubstitution { } bindings.push((name.clone(), value.substituted(&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(&new.bindings))); + } let mut stages = existing.stages.clone(); stages.extend(new.stages.iter().cloned()); - MemberSubstitution { bindings, stages } + MemberSubstitution { + bindings, + alias_bindings, + stages, + } } /// **A written spelling with this instantiation applied**, stage by stage — aliases first, then the parameters, diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index f3d7aa28..16a8cb02 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -369,16 +369,9 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { let parameter = second .parameter_facts_of(path, function) .first() - .map(|parameter| parameter.type_of) + .and_then(|parameter| second.parameter_type(parameter)) .expect("a parameter"); - assert_eq!( - second - .types() - .type_ref(parameter) - .expect("the imported parameter") - .display(), - "double" - ); + assert_eq!(parameter.to_string(), "double"); } #[test] @@ -414,18 +407,16 @@ fn a_function_detail_interns_its_parameter_types() { assert_eq!(parameters.len(), 2, "both parameters are CST facts"); assert_eq!( index - .types() - .type_ref(parameters[0].type_of) + .parameter_type(¶meters[0]) .expect("the parameter type was lowered") - .display(), + .to_string(), "double" ); assert_eq!( index - .types() - .type_ref(parameters[1].type_of) + .parameter_type(¶meters[1]) .expect("the parameter type was lowered") - .display(), + .to_string(), "const char*" ); assert_eq!(parameters[0].name.as_deref(), Some("value")); @@ -434,17 +425,11 @@ fn a_function_detail_interns_its_parameter_types() { let types: Vec<_> = index .parameter_facts_of(path, function) .iter() - .map(|parameter| parameter.type_of) + .filter_map(|parameter| index.parameter_type(parameter)) .collect(); - assert_eq!(types.len(), 2, "both parameters got a handle"); - assert_eq!( - index.types().type_ref(types[0]).unwrap().display(), - "double" - ); - assert_eq!( - index.types().type_ref(types[1]).unwrap().display(), - "const char*" - ); + 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 one node, not one per declaration.** This is the memory contract of the store: a header @@ -4807,10 +4792,9 @@ fn a_cooked_facts_parameters_resolve_through_its_own_reading() { ); assert_eq!( index - .types() - .type_ref(parameters[0].type_of) + .parameter_type(¶meters[0]) .expect("the parameter's type was imported with the reading") - .display(), + .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 0d87e429..bef6d439 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -2159,26 +2159,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(ComputedType::from(argument))) .collect(); - let at = the_one_the_arguments_select(index, &types, &callable, &[])?; + 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) { diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 68b8bd09..949b161e 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -84,6 +84,24 @@ impl ComputedType { } } + /// **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 builtin answers its 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 { + ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => Some(name.as_str()), + ComputedType::Named(named) => Some(named.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::Auto | ComputedType::DecltypeAuto | ComputedType::Function(_) => None, + } + } + /// The template arguments written on the type, looking through a reference or a qualifier. pub fn arguments(&self) -> &[ComputedType] { match self { @@ -216,6 +234,60 @@ impl ComputedType { } } + /// **This type with one name in it replaced** — the structural twin of + /// [`crate::sema::types::Type::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 `Type` version follows. + pub fn replacing(&self, name: &str, with: &ComputedType) -> ComputedType { + match self { + ComputedType::Named(found) if found.arguments.is_empty() && found.name == name => { + with.clone() + } + ComputedType::Named(found) => ComputedType::named( + found.name.clone(), + found + .arguments + .iter() + .map(|argument| argument.replacing(name, with)) + .collect(), + ), + ComputedType::Builtin(_) + | ComputedType::TemplateParameter(_) + | ComputedType::Auto + | ComputedType::DecltypeAuto => self.clone(), + 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, + }, + 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. diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 15bf3174..d6744c1b 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -270,13 +270,18 @@ impl TypeStore { self.intern_type_written_as(written, None) } - /// [`TypeStore::intern_type`] with **the source text kept as the node's display spelling**. + /// [`TypeStore::intern_type`] with **the source spelling kept as the node's display spelling**. /// /// A file writes `const char *` and a hover is owed those characters; rendering the parsed shape instead answers /// `const char*`. The structure is the same either way, and only the top node's spelling is kept — children are /// reached from the source spelling when it is printed, so the canonical spelling of each child is what a /// synthesized child would show anyway. - fn intern_type_written_as(&mut self, written: &Type, source: Option<&str>) -> TypeId { + /// + /// `source` is a **spelling, never a parse**: a construction edge that already has the structured [`Type`] — a + /// parameter read from its own `CppParam`, for instance — passes the written form it printed from the same node so + /// that a display consumer quotes the file, while computation reads the structure. No consumer below this edge + /// parses the spelling back. + pub fn intern_type_written_as(&mut self, written: &Type, source: Option<&str>) -> TypeId { let spelling = source.map_or_else(|| written.to_string(), str::to_string); let kind = match written { Type::Builtin { spelling } if spelling.trim() == "auto" => TypeKind::Auto, 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 a4dd8e13..2e3d4e8e 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,12 @@ use crate::BindingKind; use crate::DeclKind; use crate::Known; use crate::file; +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 +65,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 +174,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 `Type` 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(ComputedType::from(&a_type)), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -189,7 +192,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 +261,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 +283,17 @@ 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.map_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()), + |written| ComputedType::from(&written), + )); } // **A `...` is a token of the list, not a parameter *node*.** `int count, ...` has one child (`int count`) and @@ -300,21 +313,27 @@ 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 + && matches!(¶meters_written[0], ComputedType::Builtin(name) if name == "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, }); } } @@ -400,8 +419,8 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec // **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); - let Some(callee) = the_callee_in_facts(facts, context.index().types(), parameters) - .or_else(|| the_callee_in_text(parameters)) + let Some(callee) = + the_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) else { continue; }; @@ -412,55 +431,47 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec callees } -/// **The last-resort text candidate** for a fact whose parameter type handles are not in this index. This is a -/// top-level comma walk, not a parser; the indexed path above is the ordinary one. -fn the_callee_in_text(parameter_list: &str) -> Option { - let (spellings, variadic) = sema::overload::parameters_in(parameter_list); - let written = spellings.len(); - let required = written.saturating_sub(parameter_list.matches('=').count()); - Some(Callee { - required, - written, - variadic, - parameters: spellings, - }) -} - -/// **One candidate out of the CST parameter facts.** Type spellings come from the type store; nothing is parsed. +/// **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 recorded list. +/// +/// [`DeclaredType`]: crate::cache::summary::DeclaredType fn the_callee_in_facts( facts: &[crate::index::params::ParameterFact], types: &crate::index::types::TypeStore, - parameter_list: &str, + mut variadic: bool, ) -> Option { let mut written = 0usize; let mut required = 0usize; - let mut variadic = has_an_ellipsis(parameter_list); - let mut spellings: Vec = Vec::new(); + let mut parameters: Vec = Vec::new(); for parameter in facts { if parameter.pack { variadic = true; continue; } - let spelling = types.spelling(parameter.type_of)?; - if spelling.trim().is_empty() { - return None; - } + let type_of = parameter.type_of.as_computed(types)?; written += 1; if parameter.default_value.is_none() { required += 1; } - spellings.push(spelling.to_string()); + parameters.push(type_of); } - if written == 1 && spellings.len() == 1 && spellings[0].trim() == "void" { + if written == 1 + && parameters.len() == 1 + && matches!(¶meters[0], ComputedType::Builtin(name) if name == "void") + { written = 0; required = 0; - spellings.clear(); + parameters.clear(); } Some(Callee { required, written, variadic, - parameters: spellings, + parameters, }) } @@ -589,7 +600,9 @@ fn judge_a_member_call( continue; }; let facts = context.index().parameter_facts_of(file, fact); - if let Some(callee) = the_callee_in_facts(facts, context.index().types(), parameters) { + if let Some(callee) = + the_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) + { members.push(callee); } } @@ -604,11 +617,10 @@ fn judge_a_member_call( .filter(|member| context.index().member_name(member) == access.member) .filter_map(|member| { let fact = context.index().member_fact(member)?; - let parameters = context.index().member_parameter_list(member)?; + let parameters = fact.parameter_list()?; let file = context.index().member_path(member)?; let facts = context.index().parameter_facts_of(file, fact); - the_callee_in_facts(facts, context.index().types(), ¶meters) - .or_else(|| the_callee_in_text(¶meters)) + the_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) }) .collect(); } 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 67ec8ff2..28389c76 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 @@ -99,21 +99,30 @@ impl Check for AssignTypeCheck { let declarations = context .declarations(DeclarationSource::Cooked) .unwrap_or_default(); - let mut declared: HashMap<&str, Option> = HashMap::new(); + let mut declared: HashMap<&str, Option> = HashMap::new(); for fact in declarations { if fact.kind != DeclKind::Variable { continue; } - let Some(written) = context.index().type_spelling_of(fact) 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())) + }); + 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 +192,7 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).cloned() else { + let Some(Some(target)) = declared.get(name.as_str()).cloned() else { continue; }; @@ -211,7 +220,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 +236,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 +278,11 @@ impl Check for AssignTypeCheck { else { continue; }; - let Some(Some(written)) = declared.get(name.as_str()).cloned() 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 +306,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| context.index().member_name(found) == name) - .and_then(|found| context.index().member_type_spelling(found)) 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* @@ -380,16 +399,47 @@ fn not_assignable(type_of: &sema::types::Type) -> Option { } } -/// **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 and the C tag (`struct point`) that a `Type` cannot carry. /// -/// 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: sema::types::Type, + written: smol_str::SmolStr, + /// The name after `struct`/`union` when the declaration wrote C's tag syntax — boundary metadata read from the + /// spelling, as [`sema::convert::conversion_to`] documents. + tagged_record: Option, +} + +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: &crate::index::types::ComputedType, written: &str) -> Option { + if written.trim().is_empty() { + return None; + } + Some(Target { + type_of: computed.to_sema_type(), + written: smol_str::SmolStr::new(written.trim()), + tagged_record: sema::convert::tagged_record_in(written).map(str::to_string), + }) + } } /// **One place a value enters an object whose type is written down**, reported when it does not convert. @@ -399,7 +449,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,28 +463,25 @@ fn report_if_it_does_not_convert( return; } let known_from = context.type_of(expression); - let target = sema::types::parse_type_spelling(written); - let tagged_record = sema::convert::tagged_record_in(written); let Known::Yes((from, _)) = known_from else { return; }; // **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 parsed - // **here**, once, and the conversion question takes that `Type`; the C tag (`struct point`) is metadata the - // parsed type cannot carry, read from the same spelling at this boundary. + // only for the class question, and answers `Unknown` — silence — when neither can speak. The target is the fact's + // own **type**, resolved once above; the C tag is metadata read from the spelling at that same construction edge. // **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_to( &from, - &target, - tagged_record, + &target.type_of, + target.tagged_record.as_deref(), 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; } @@ -442,15 +489,14 @@ 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) + // 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); } } @@ -477,8 +523,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; }; @@ -488,8 +536,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/missing_include.rs b/crates/cpp_code_analysis/src/sema/check/missing_include.rs index 02e936d6..757539f2 100644 --- a/crates/cpp_code_analysis/src/sema/check/missing_include.rs +++ b/crates/cpp_code_analysis/src/sema/check/missing_include.rs @@ -318,7 +318,9 @@ pub(super) fn types_this_declaration_uses( spellings.push(returns.to_string()); } for parameter in index.parameter_facts_of(file, fact) { - if let Some(spelling) = index.types().spelling(parameter.type_of) + // **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()); diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index 27b1c360..edf590f7 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -510,15 +510,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: &sema::types::Type, ) -> 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 +585,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, @@ -1537,24 +1553,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 +1600,31 @@ 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: &sema::types::Type) -> bool { + use sema::types::Type; + let type_of = match type_of { + Type::Qualified { of, .. } => &**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 Type::Pointer { to } = type_of else { + return false; + }; + let pointee = match &**to { + Type::Qualified { of, .. } => &**of, + other => other, + }; + matches!(pointee, Type::Builtin { spelling } if spelling == "char" || spelling == "void") } /// **A type written back as a spelling** — for a message, and only for the shapes a call's parameter list holds. @@ -1740,12 +1746,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. @@ -1761,41 +1773,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: &[crate::index::params::ParameterFact], + value: &sema::types::Type, +) -> 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) @@ -1804,7 +1807,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; }; @@ -1816,30 +1820,12 @@ 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: &crate::index::types::ComputedType) -> Option { + use crate::index::types::ComputedType; let arithmetic = |word: &str| { let word = word.trim_start_matches("const").trim(); @@ -1869,46 +1855,58 @@ fn could_take_an_arithmetic_value(parameter: &str) -> Option { | "std::uint64_t" ) }; + // **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 ") + }; - // 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); + Some(match type_of { + ComputedType::Builtin(name) => arithmetic(name), + // **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(named) if named.arguments.is_empty() => { + if arithmetic(&named.name) { + true + } else if looks_like_a_template_parameter(&named.name) { + return None; + } else { + false + } } - 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) + ComputedType::Named(_) => false, + ComputedType::TemplateParameter(_) + | ComputedType::Auto + | ComputedType::DecltypeAuto => 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::Builtin(name) => arithmetic(name), + ComputedType::Named(named) if named.arguments.is_empty() => { + if arithmetic(&named.name) { + true + } else if looks_like_a_template_parameter(&named.name) { + return None; + } else { + false + } + } + ComputedType::Qualified(qualified) => { + return could_take_an_arithmetic_value(&qualified.of); + } + _ => return None, + }, + ComputedType::Qualified(qualified) => { + return could_take_an_arithmetic_value(&qualified.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/param_type_check.rs b/crates/cpp_code_analysis/src/sema/check/param_type_check.rs index 81817c5e..43faa62e 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 two display-only jobs: the message quotes it, and C's tag metadata +//! (`struct point`) is read from it, since a `Type` cannot say whether its name was tagged. +//! +//! [`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 @@ -40,16 +49,19 @@ 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::DeclKind; use crate::Known; 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}; @@ -81,16 +93,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.) - // **Read once, here.** The declaration layer records parameters as spellings; this is the boundary where - // they become the parsed types the conversion question takes, so the conversion itself never parses. - let parameters: Vec = parameter_spellings_of(&function) - .into_iter() - .map(|written| CandidateParameter::from_spelling(&written)) - .collect(); + // **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 and where C's tag metadata is read. + 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) => { @@ -118,10 +124,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() { @@ -194,8 +201,9 @@ 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, @@ -209,28 +217,49 @@ fn member_parameter_lists( else { return Vec::new(); }; + let index = context.index(); list.members .iter() .filter(|member| context.model.member_name(member) == access.member) - .filter_map(|member| context.model.member_parameter_list(member)) - .map(|written| { - sema::overload::parameters_in(&written) - .0 + .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() - .map(|parameter| CandidateParameter::from_spelling(parameter)) - .collect() + .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 C's string-literal rule reads it) and the [`Type`](sema::types::Type) the conversion question -/// takes. +/// quotes it, and C's tag metadata reads it) and the [`Type`](sema::types::Type) the conversion question takes. /// -/// The declaration layer records parameters as spellings (`DeclFact::parameter_list`), so this is where a candidate -/// crosses from text into structure. Parsing happens **once per candidate**, before any argument is compared, rather -/// than once per comparison; the conversion core never parses. `tagged_record` is the C tag the spelling carries -/// (`struct point`), the one piece of written metadata a `Type` cannot keep. +/// 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 and for the C tag (`struct point`), the one piece of written evidence a `Type` +/// cannot carry. #[derive(Clone)] struct CandidateParameter { written: String, @@ -239,13 +268,63 @@ struct CandidateParameter { } impl CandidateParameter { - /// **From the spelling a declaration records** — parsed exactly once. - fn from_spelling(written: &str) -> Self { - Self { + /// **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 { + tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), + 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 the metadata read from that spelling. + fn from_fact( + index: &crate::ProjectIndex, + parameter: &crate::index::params::ParameterFact, + ) -> Option { + let type_of = index.parameter_type(parameter)?.to_sema_type(); + let written = index.parameter_spelling(parameter)?; + Some(Self { + tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), written: written.to_string(), - type_of: sema::types::parse_type_spelling(written), - tagged_record: sema::convert::tagged_record_in(written).map(str::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 and the C tag 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: &crate::ProjectIndex, + member: &crate::ProjectMember, + fact: &crate::DeclFact, + parameter: &crate::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(&substitution.bindings)); + } + type_of = type_of.substituted(&substitution.bindings); + written = smol_str::SmolStr::new(substitution.applied_to_spelling(&written, fact)); } + Some(Self { + tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), + written: written.to_string(), + type_of: type_of.to_sema_type(), + }) } /// **From a type the model already holds** — the function-pointer signature's parameters. @@ -314,9 +393,8 @@ fn check_the_arguments( } // **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(), ¶meter.written) + // `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; @@ -408,38 +486,54 @@ fn the_index_declares_one( // **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, &crate::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_map(|definition| { - let fact = context.index().definition_fact(definition)?; - (fact.kind == DeclKind::Function) - .then(|| fact.parameter_list().map(str::to_string)) - .flatten() - }) - .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)); + } + } + // **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<&[crate::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); + } } - written.dedup(); - if written.len() != 1 { + if lists.len() != 1 { return None; } - // **Read once, at this boundary** — the same crossing from the recorded spelling to the conversion's input as - // the file's own parameters. `parameters_in` strips each parameter's name. Some( - sema::overload::parameters_in(&written[0]) - .0 + lists[0] .iter() - .map(|parameter| CandidateParameter::from_spelling(parameter)) + .filter_map(|parameter| CandidateParameter::from_fact(index, parameter)) .collect(), ) } 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 c2bea579..af1725fd 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 @@ -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,17 +52,34 @@ 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, parsed once at this boundary.** It is the `Type` both the `return;` test and the - // conversion question take, and the C tag (`struct point`) is the written metadata the parsed type - // cannot carry — read here, from the same spelling. - let declared_type = sema::types::parse_type_spelling(&declared); + // **The return type as the conversion question takes it**, and the spelling the message quotes. The two + // come from the same fact; the C tag (`struct point`) is the written metadata a `Type` cannot carry. + let declared = context + .index() + .returns_spelling_of(fact) + .map_or_else(|| computed.to_string(), |written| written.to_string()); + let declared_type = computed.to_sema_type(); let declared_tag = sema::convert::tagged_record_in(&declared); for returned in the_returns_in(&function) { @@ -102,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. } @@ -123,10 +141,11 @@ 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; } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 06a4a65c..afcb9bb5 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -112,6 +112,14 @@ pub struct BuiltFacts { /// view, an outline) has nowhere to keep them. Leaving the local handles on those facts would let a query resolve an /// index into a store that was dropped — another store's `TypeId(3)` — so the type handles are bound here, once, into /// the computation layer, and the parameter handle is cleared. +/// +/// **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, types, .. @@ -4142,18 +4150,25 @@ 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.** The lowering of each parameter's type is - // done here, at the construction edge, so that the fact carries a `ParamsId` and the arena carries the list — no - // second copy of the list survives on the fact (see `DeclDetail`). The declaration's template parameters are - // passed to the interner so a parameter written `T&&` is stored as a parameter rather than as a class called `T` - // — see [`TypeStore::intern_a_declared_type`]. + // **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. let parameter_facts = { let mut declared = declared_parameter_facts_with(shapes, binding); 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) { - parameter.type_of = types.intern_a_declared_type(&cpp.get_type_text(), ¶meters); + let written = sema::types::with_template_parameters(written, ¶meters); + let source = cpp.get_type_text(); + parameter.type_of = DeclaredType::Stored( + types.intern_type_written_as(&written, Some(source.trim())), + ); } } parameter_arena.intern(declared) diff --git a/crates/cpp_code_analysis/src/sema/deduction.rs b/crates/cpp_code_analysis/src/sema/deduction.rs index 57cf5949..27d1b10c 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(&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,126 @@ fn deduce_seeded( Some(deduced) } +/// **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); + } + + match (parameter, argument) { + ( + ComputedType::Named(written), + ComputedType::Named(found), + ) => { + // A name is not a shape: two different class templates are not unified, and the arguments are paired + // positionally only when the names agree. + 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) + } + } + (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), + } +} + /// 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 { +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.to_string()); + bound.insert(name.to_string(), argument.clone()); 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(), - )); - } - from = end; - } - } - None -} - -/// A spelling without the reference and cv-qualifiers a call does not choose on — the same normalisation the resolver +/// 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. -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; - } - } +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 + } + 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 +321,33 @@ 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); + let parsed = + sema::types::with_template_parameters(parsed, &["T", "U", "N", "_Tp", "_Args"]); + ComputedType::from(&parsed) + } + + 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 +359,7 @@ mod tests { ¶meters(&["const T&"]), &[yes("std::string")] ), - Some(names(&["std::string"])) + Some(vec![a_type("std::string")]) ); } @@ -318,7 +367,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 +379,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 +404,7 @@ mod tests { yes("int") ], ), - Some(names(&["int"])), + Some(vec![a_type("int")]), "the second parameter still fixes T" ); } @@ -376,16 +425,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 +448,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 +460,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 +476,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/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index d98d6697..f595569a 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -35,9 +35,9 @@ //! 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::types::ComputedType; 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 +55,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 +89,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 +115,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 +128,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 +144,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 +173,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 +191,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 +305,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 +322,35 @@ 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 + .to_sema_type() + .convertible_to(¶meter.to_sema_type()) + { 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 + } + other => return other, + }; } - text.split_whitespace().collect::>().join(" ") } /// The promotions a compiler ranks above a conversion, and only those. @@ -346,7 +359,7 @@ 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 { +fn is_a_promotion(from: &ComputedType, to: &ComputedType) -> bool { const NARROW: [&str; 6] = [ "char", "signed char", @@ -357,7 +370,12 @@ fn is_a_promotion(from: &str, to: &str) -> bool { ]; const TO_INT: [&str; 2] = ["int", "unsigned int"]; - (NARROW.contains(&from) && TO_INT.contains(&to)) || (from == "float" && to == "double") + let (ComputedType::Builtin(from), ComputedType::Builtin(to)) = (from, to) else { + return false; + }; + + (NARROW.contains(&from.as_str()) && TO_INT.contains(&to.as_str())) + || (from == "float" && to == "double") } #[cfg(test)] @@ -365,15 +383,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(ComputedType::from(&sema::types::parse_type_spelling(spelling))) } fn candidate(parameters: &[&str]) -> Candidate { Candidate::new( parameters .iter() - .map(|parameter| (*parameter).to_string()) + .map(|parameter| ComputedType::from(&sema::types::parse_type_spelling(parameter))) .collect(), false, parameters.join(", "), @@ -494,7 +515,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,257 +525,40 @@ mod tests { } } -/// **A parameter's type without its name.** +/// **The parameter types from CST facts**, with no parameter list parsing and no spelling in sight. /// -/// `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]`. -/// -/// `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. -/// -/// 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 { - '<' if inner[..].contains('>') => depth += 1, - '<' => {} - '(' | '[' => 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 `...`. +/// Each fact's type is resolved to the computation layer by the same rule as +/// [`crate::ProjectIndex::parameter_type`]: a summary's or a cooked reading's parameter holds a handle into the one +/// global store and is materialized; a view-synthesized one carries its value and is cloned. `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. /// -/// `(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. -/// **The parameter types from CST facts**, with no parameter list parsing. The type spelling comes from the type -/// store; a pack is one parameter whose `...` is already gone. +/// 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: &[crate::index::params::ParameterFact], types: &crate::index::types::TypeStore, c_style_variadic: bool, -) -> (Vec, bool) { +) -> (Vec, bool) { let mut parameters = Vec::new(); let mut variadic = c_style_variadic; for fact in facts { - let Some(spelling) = types.spelling(fact.type_of) else { + let Some(type_of) = fact.type_of.as_computed(types) else { continue; }; if fact.pack { variadic = true; - let element = spelling.trim().trim_end_matches("...").trim(); - if !element.is_empty() { - parameters.push(element.to_string()); - } - } else { - parameters.push(spelling.to_string()); - } - } - (parameters, variadic) -} - -pub fn parameters_in(parameter_list: &str) -> (Vec, bool) { - let inner = parameter_list - .trim() - .trim_start_matches('(') - .trim_end_matches(')'); - - 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 - }; - if outside_the_arguments.contains("...") { - *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)); - }; - - // **No synthetic parameter-list parse.** This text path is only reached by a caller that has no `ParamsStore` - // entry; it splits at top-level commas, which is the old reader's rule. - variadic |= parameter_list.contains("..."); - let characters: Vec = inner.chars().collect(); - let closes_an_angle = |rest: &[char]| { - let mut depth = 0i32; - for character in rest { - match character { - '<' => depth += 1, - '>' if depth == 0 => return true, - '>' => depth -= 1, - _ => {} - } - } - false - }; - let mut at = 0usize; - while at < characters.len() { - let character = characters[at]; - match character { - // **A comparison is not a template bracket.** `bool ok = 1 < 2` has no closing `>`, so it must not - // raise the depth and swallow the parameters after its default. - '<' if closes_an_angle(&characters[at + 1..]) => depth += 1, - '<' => {} - '(' | '[' => depth += 1, - '>' | ')' | ']' => depth -= 1, - ',' if depth == 0 => { - take(¤t, &mut parameters, &mut variadic); - current.clear(); - at += 1; - continue; - } - _ => {} + // 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); } - current.push(character); - at += 1; } - take(¤t, &mut parameters, &mut variadic); - (parameters, variadic) } @@ -775,11 +579,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() }) @@ -790,98 +594,133 @@ 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 crate::index::types::TypeStore; + 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); + let mut types = TypeStore::new(); + 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::Stored(types.intern_type(&written)); + } + parameters_in_facts(&facts, &types, 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.len(), 3, "a comparison in a default is not a bracket"); 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, ...)") - ); - 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)" - ); - 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 *)" + parameters, + vec![ + ComputedType::Builtin("int".into()), + ComputedType::Builtin("bool".into()), + ComputedType::Builtin("int".into()), + ] ); - // **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::index::params::parameter_facts_of; + use crate::index::types::TypeStore; + 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()]); + let mut types = TypeStore::new(); + facts[0].type_of = crate::cache::summary::DeclaredType::Stored(types.intern_type(&written)); + + let (parameters, _) = parameters_in_facts(&facts, &types, 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); + let parsed = sema::types::with_template_parameters(parsed, &["T".to_string()]); + ComputedType::from(&parsed) + }; + let an_argument = |spelling: &str| { + Known::Yes(ComputedType::from( + &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), @@ -893,7 +732,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!( @@ -906,7 +745,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/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 76acf30c..baa09b8e 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -2031,6 +2031,32 @@ pub fn type_of_declaration_named( wrapped } +/// **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 diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index f5a8032a..bc24ab30 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -406,10 +406,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 @@ -422,11 +426,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, @@ -444,33 +448,56 @@ 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 list-level `...` the fact recorded. The one step every caller of the two methods above needs, in one + /// place. + /// + /// The list-level ellipsis is read from the declaration's recorded parameter list because no field stores it: the + /// fact's `pack` bit describes a *parameter*, and a C-style `...` is a token of the list rather than a parameter. + /// That is the one property this boundary still takes from the display spelling; the types themselves never + /// pass through text. + pub fn declared_parameters_of( + &self, + file: &Path, + fact: &DeclFact, + ) -> sema::overload::DeclaredParameters { + let index = self.store.index(); + sema::overload::DeclaredParameters::new( + index.parameter_types_of(file, fact), + fact.parameter_list().is_some_and(|list| list.contains("...")), + ) + } + /// **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 `Type` 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 = @@ -483,23 +510,22 @@ 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(crate::index::types::ComputedType::from( + &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`. @@ -509,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 { @@ -588,7 +617,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( @@ -596,8 +627,8 @@ impl Session { view: &FileView, offset: ReadingOffset, template_parameters: &[String], - parameters: &[String], - ) -> Option> { + parameters: &[crate::index::types::ComputedType], + ) -> Option> { if template_parameters.is_empty() { return None; } @@ -619,10 +650,12 @@ 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(crate::index::types::ComputedType::from( + &a_type, + )), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 6d9ce465..1a366e43 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -841,21 +841,16 @@ impl Session { if fact.kind != DeclKind::Function || fact.parameters().is_empty() { return None; } - // **The inserted summary already has parameter types.** Parse the written list only for a fact that predates - // the store; a stored handle is materialized read-only, so a template-argument hint costs no parse and no - // write to the type store. + // **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() - .types() - .materialize(parameter.type_of) - .map(|computed| computed.to_string()) - }) + .filter_map(|parameter| self.store.index().parameter_type(parameter)) + .map(|computed| computed.to_string()) .collect(); if parameter_types.is_empty() { return None; @@ -1025,32 +1020,22 @@ impl Session { let Some(fact) = index.member_fact(member) else { return false; }; - let Some(list) = index.member_parameter_list(member) else { - return false; - }; - let facts = index.parameter_facts_of( - index.member_path(member).unwrap_or(Path::new("")), - fact, + // **The parameter's own type, structurally.** A member's list is a fact like any other; the type + // resolves through the one store, 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), + index.types(), + false, ); - let types = if facts.is_empty() { - sema::overload::parameters_in(&list).0 - } else { - sema::overload::parameters_in_facts(facts, index.types(), list.contains("...")).0 + let Some(parameter) = parameters.get(at) else { + return false; }; - let Some(written) = types.get(at) else { + let Some(core) = parameter.bare_name() 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(['&', '*']); - fact.parameters() - .iter() - .any(|parameter| parameter == core) + fact.parameters().iter().any(|name| name == core) }) // Rule 1: a `const` object reaches only the `const` members. .filter(|member| { diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index d8f49eaf..4cde3147 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -32,7 +32,9 @@ use crate::sema; use std::ops::Range; use std::path::{Path, PathBuf}; -use cpp_parser::{CppDocComment, CppSyntaxElement, CppSyntaxKind, CppSyntaxNode, CppTokenKind}; +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 +152,11 @@ 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. + let mut rankable: Vec<(Vec, Vec)> = 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 @@ -222,30 +225,29 @@ where // 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(); - let written: Vec = parameters_of(&list) - .into_iter() - .map(|(parameter, _)| { - let mut text = parameter.text().to_string(); - text = text.split_whitespace().collect::>().join(" "); - text - }) - .collect(); - for (at, text) in written.iter().enumerate() { + // **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); + label.push_str(&text); parameters.push((start..label.len(), text.clone())); - } + let written = cpp_parser::CppParam::cast(parameter) + .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); + plain.push(written.map_or_else( + || crate::index::types::ComputedType::named(text, Vec::new()), + |written| crate::index::types::ComputedType::from(&written), + )); } label.push(')'); - // The declaration's own parameter texts, names dropped, and the template header it owns — the last read + // 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, @@ -293,18 +295,21 @@ 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(crate::index::types::ComputedType::from( + &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() @@ -312,10 +317,10 @@ where let (plain, templates) = 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, @@ -743,7 +748,9 @@ fn constructors_in_the_index( let mut label = format!("{class}("); let mut parameters: Vec<(Range, String)> = Vec::new(); for (at, parameter) in facts.iter().enumerate() { - let Some(spelling) = index.types().spelling(parameter.type_of) else { + // **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; }; diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs index fc1fe3ef..1f473c2e 100644 --- a/crates/cpp_code_analysis/tests/params.rs +++ b/crates/cpp_code_analysis/tests/params.rs @@ -1,49 +1,122 @@ //! 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 interned as a `Type`, and is resolved back +//! to a `ComputedType` 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::TypeStore; +use cpp_code_analysis::index::types::{ComputedType, TypeStore}; +use cpp_code_analysis::sema; use cpp_code_analysis::sema::overload::parameters_in_facts; use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; -fn facts( - source: &str, -) -> ( - cpp_parser::CppSyntaxTree, - Vec, -) { +/// One declaration's parameter list, lowered into a fresh store — the way +/// `sema::declarations::DeclarationFacts::fact_for` lowers it. +fn lowered(source: &str) -> (TypeStore, Vec, bool) { let tree = CppParser::parse(source, ParserConfig::default()); - let list = tree - .get_red_root() + let root = tree.get_red_root(); + let list = root .descendants() .find_map(CppParamList::cast) .expect("a parameter list"); - (tree, parameter_facts_of(&list)) -} - -#[test] -fn parameter_types_come_from_each_cpp_param() { - let (tree, mut facts) = facts("void f(int a, std::pair p, double... rest);\n"); + let mut facts = parameter_facts_of(&list); let mut types = TypeStore::new(); for fact in &mut facts { let node = fact .declaration - .to_node_from_root(&tree.get_red_root()) + .to_node_from_root(&root) .expect("the parameter node"); let parameter = CppParam::cast(node).expect("typed parameter"); - fact.type_of = types.intern_spelling(¶meter.get_type_text()); + let written = sema::types::type_of_a_parameter(¶meter) + .expect("a parameter has a type this layer can read"); + fact.type_of = DeclaredType::Stored(types.intern_type(&written)); } - let (parameters, variadic) = parameters_in_facts(&facts, &types, false); - assert_eq!(parameters, vec!["int", "std::pair", "double"]); - assert!(variadic); + let (parameters, variadic) = parameters_in_facts(&facts, &types, list.is_variadic()); + (types, parameters, variadic) +} + +#[test] +fn parameter_types_come_from_each_cpp_param() { + let (_types, 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::Builtin(name) if name == "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::Builtin(name) if name == "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 (_tree, facts) = facts("void f(const char* format, ...);\n"); + let (_types, 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 interning, 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()]); let mut types = TypeStore::new(); - let mut facts = facts; - facts[0].type_of = types.intern_spelling("const char*"); - let (parameters, variadic) = parameters_in_facts(&facts, &types, true); - assert_eq!(parameters, vec!["const char*"]); - assert!(variadic); + facts[0].type_of = DeclaredType::Stored(types.intern_type(&written)); + + let (parameters, variadic) = parameters_in_facts(&facts, &types, 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/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 80dbb454..8f17c560 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -2097,14 +2097,13 @@ void f() { ); } -/// **A named parameter is not checked, and that is a gap rather than a rule.** -/// -/// `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. +/// **A named parameter is checked like an unnamed one**, because the type is read from the parameter's own node. +/// +/// 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 = "\ diff --git a/crates/cpp_ls/src/handlers/definition/mod.rs b/crates/cpp_ls/src/handlers/definition/mod.rs index 55b75641..3a271116 100644 --- a/crates/cpp_ls/src/handlers/definition/mod.rs +++ b/crates/cpp_ls/src/handlers/definition/mod.rs @@ -444,14 +444,19 @@ 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| { - session - .definition_fact(declaration) - .and_then(|fact| fact.parameter_list()) - .map(str::to_string) + 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 @@ -472,7 +477,7 @@ fn chosen_definition( .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)] diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 0077ee3d..89583ccc 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1228,9 +1228,19 @@ 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| session.index().member_parameter_list(candidate)) + .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() @@ -1254,7 +1264,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, ) }) @@ -1427,14 +1437,20 @@ 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| { - session - .definition_fact(declaration) - .and_then(|fact| fact.parameter_list()) - .map(str::to_string) + 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. @@ -1463,7 +1479,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) @@ -1523,19 +1539,20 @@ fn overloads_markdown( { // **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, ); - 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); } } diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 6a31f768..45c05e4a 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -265,10 +265,16 @@ struct ParameterFact { declaration: SyntaxId, default_value: Option, pack: bool, - type_of: TypeId, + type_of: DeclaredType, } ``` +A parameter's type is the same [`DeclaredType`](#3-declfact) a fact's own types use: a summary's or a cooked +reading's parameter holds `Stored` (lowered from its own `CppParam` node at construction), and a parameter a query +synthesized from a view holds `Computed` — no `TypeId` is invented and no second store is minted. +`ProjectIndex::parameter_type` is the resolver both kinds share; it answers a `ComputedType`, 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. From 1475a0fdb09d1a6c3b772036a6894b0d082708bc Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 10:09:14 +0800 Subject: [PATCH 078/102] refactor(params): store the C variadic list bit DeclFact now records variadic_parameters from CppParamList::is_variadic (including '(...)' with no params); the list-level ellipsis is no longer detected by scanning parameter_list text. Overload candidates, argument_count, signature help and call resolution read the stored bit; packs remain ParameterFact::pack. Codec persists the bit and COOKED/UNIT versions move with it. Tests cover int+..., pure (...), packs and non-variadic lists. Workspace tests (3615 passed) and clippy pass. --- crates/cpp_code_analysis/src/cache/summary.rs | 32 ++- .../src/cache/summary_codec.rs | 44 +++- .../cpp_code_analysis/src/cache/unit_codec.rs | 6 +- crates/cpp_code_analysis/src/index/params.rs | 82 +++++++- .../src/index/project/bases.rs | 17 +- .../src/index/project/calls.rs | 25 ++- .../src/index/project/completions.rs | 1 + .../src/index/project/macro_environment.rs | 9 + .../src/index/project/tests.rs | 59 ++++++ .../src/sema/check/argument_count.rs | 76 +++---- .../src/sema/check/test/argument_count.rs | 47 +++++ .../src/sema/declarations.rs | 192 ++++++++++++++---- crates/cpp_code_analysis/src/session/calls.rs | 20 +- .../src/session/completion/mod.rs | 3 + .../src/session/signature.rs | 38 +++- .../cpp_code_analysis/tests/suite/checks.rs | 3 + .../tests/suite/modifiers.rs | 30 ++- .../tests/suite/signature.rs | 50 +++++ crates/cpp_parser/src/syntax/node/cpp/mod.rs | 8 +- docs/type-system-redesign.md | 10 + 20 files changed, 615 insertions(+), 137 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index f8405ba3..092da41c 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -94,8 +94,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 @@ -331,6 +334,31 @@ pub struct DeclFact { /// `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 diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index d1b414d2..72aa1052 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -307,7 +307,17 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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. -pub const CODEC_VERSION: u32 = 44; +/// +/// # 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). +pub const CODEC_VERSION: u32 = 45; /// Write a summary as bytes. /// @@ -1487,6 +1497,10 @@ mod tests { // A class returns nothing either, so `None` — and the second fact below covers the other value. returns: DeclaredType::None, parameters: crate::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), @@ -1548,6 +1562,8 @@ mod tests { // The table's second node, so a fact's handle is part of what the round trip carries. returns: DeclaredType::Stored(TypeId::from_raw(1)), parameters: crate::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, @@ -1577,6 +1593,9 @@ mod tests { type_of: DeclaredType::None, returns: DeclaredType::None, parameters: crate::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. @@ -1920,6 +1939,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. @@ -1997,6 +2019,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, @@ -2009,6 +2034,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { type_of, returns, parameters: parameters_id, + variadic_parameters, split_by_a_directive, range, name_range, @@ -2103,7 +2129,11 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// 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. -const COOKED_VERSION: u32 = 8; +/// +/// 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. +const COOKED_VERSION: u32 = 9; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -2403,6 +2433,9 @@ fn a_cooked_reading_round_trips() { type_of: DeclaredType::None, returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, + // The class is not variadic; the function below is, which is how both values of the byte are + // covered by the record that carries them. + variadic_parameters: false, range: SourceRange::new(10, 20), name_range: SourceRange::new(16, 6), local: false, @@ -2439,6 +2472,9 @@ fn a_cooked_reading_round_trips() { type_of: DeclaredType::Stored(TypeId::from_raw(0)), returns: DeclaredType::Stored(TypeId::from_raw(1)), parameters: crate::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, @@ -2507,6 +2543,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))); diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 3c3c801e..83e46566 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -58,7 +58,11 @@ const MAGIC: [u8; 4] = *b"UNIT"; /// 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. -pub const UNIT_CODEC_VERSION: u32 = 7; +/// +/// 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. +pub const UNIT_CODEC_VERSION: u32 = 8; #[derive(Debug)] pub enum DecodeError { diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index ba3c3243..125f826e 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -4,15 +4,21 @@ //! 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 type is a [`DeclaredType`], the same enum a [`DeclFact`](crate::DeclFact)'s own types use.** A parameter a -//! summary or a cooked reading filed holds [`DeclaredType::Stored`] — a handle into the one global +//! **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 enum a [`DeclFact`](crate::summary::DeclFact)'s own types use.** A +//! parameter a summary or a cooked reading filed holds [`DeclaredType::Stored`] — a handle into the one global //! [`TypeStore`](crate::index::types::TypeStore), lowered from the parameter's own `CppParam` node by //! [`crate::sema::declarations`] at construction. A parameter fact a query synthesized from a view has no arena to //! intern into, so it holds [`DeclaredType::Computed`], the value the builder already has. There is **no spelling //! field**: [`crate::ProjectIndex::parameter_type`] resolves either kind to a //! [`ComputedType`](crate::index::types::ComputedType), and nothing re-parses a type on the way. -//! -//! [`DeclFact`]: crate::DeclFact use cpp_parser::CppAstNode; use cpp_parser::CppInitializer; use cpp_parser::CppParam; @@ -35,7 +41,9 @@ pub struct ParameterFact { pub declaration: CppSyntaxId, /// The initializer expression after `=`, when one is written. pub default_value: Option, - /// A parameter pack / ellipsis parameter. + /// **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. @@ -198,14 +206,68 @@ mod tests { use super::*; use cpp_parser::{CppParser, ParserConfig}; - fn parameters(source: &str) -> Vec { + fn parameter_list(source: &str) -> CppParamList { let tree = CppParser::parse(source, ParserConfig::default()); - let list = tree - .get_red_root() + tree.get_red_root() .descendants() .find_map(CppParamList::cast) - .expect("a parameter list"); - parameter_facts_of(&list) + .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] diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 106400ed..45aa015f 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -259,6 +259,10 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { /// lowered from its own `CppParam`, because a view path has no store to intern into and inventing a `TypeId` from a /// 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<[crate::index::params::ParameterFact]>, @@ -359,8 +363,15 @@ pub(crate) fn fact_from_binding_with( // 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 `TypeId` is invented and 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 = sema::declarations::declared_parameter_facts_with(shapes, binding); + 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) @@ -429,6 +440,10 @@ pub(crate) fn fact_from_binding_with( // files it in the synthetic arena; `ProjectIndex::parameter_facts_of` resolves it from there. See // [`SynthesizedFact`]. parameters: crate::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`]. // diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 1395ef16..8ead59a0 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -762,13 +762,16 @@ pub(crate) fn the_return_the_overloads_agree_on( // (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 variadic = candidate_fact - .parameter_list() - .is_some_and(|list| list.contains("...")); 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( parameters.as_deref(), variadic, @@ -1527,13 +1530,19 @@ 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( - index.parameter_types_of(file, fact), - fact.parameter_list().is_some_and(|list| list.contains("...")), - ), + parameters: sema::overload::DeclaredParameters::new(types, variadic), } } @@ -1548,7 +1557,7 @@ impl CandidateDeclaration { .iter() .filter_map(|parameter| index.parameter_type(parameter)) .collect(); - let variadic = fact.parameter_list().is_some_and(|list| list.contains("...")) + let variadic = fact.variadic_parameters || parameters.iter().any(|parameter| parameter.pack); CandidateDeclaration { fact, diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index 932e90af..fba7aae7 100644 --- a/crates/cpp_code_analysis/src/index/project/completions.rs +++ b/crates/cpp_code_analysis/src/index/project/completions.rs @@ -517,6 +517,7 @@ pub fn name_completions_at( // parameters of its own and no bases, and a `#define` is never local. 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; 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 595c4407..400d1c15 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_environment.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_environment.rs @@ -682,6 +682,10 @@ fn fact_from_a_binding(binding: Binding, scope: Option, local: bool) -> type_of: DeclaredType::None, returns: DeclaredType::None, parameters: crate::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`]. @@ -911,6 +915,10 @@ pub(crate) fn rank_of(qualified: &str, name: &str, wanted: &str) -> Option bool { one.name == other.name && one.scope == other.scope @@ -921,6 +929,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? diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 16a8cb02..9a71a4d2 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -4763,6 +4763,65 @@ fn a_view_facts_parameters_resolve_through_the_synthetic_arena() { 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 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 2e3d4e8e..1baa7eca 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -413,15 +413,20 @@ 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; - }; + } // **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); - let Some(callee) = - the_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) - else { + // **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, + context.index().types(), + fact.variadic_parameters, + ) else { continue; }; // **The same signature declared twice is one candidate at the most permissive arity** — see @@ -436,7 +441,8 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec /// 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 recorded list. +/// 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( @@ -495,44 +501,6 @@ 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 { @@ -596,13 +564,15 @@ fn judge_a_member_call( re_exposed = true; continue; } - let Some(parameters) = fact.parameter_list() else { + if fact.parameter_list().is_none() { continue; - }; + } let facts = context.index().parameter_facts_of(file, fact); - if let Some(callee) = - the_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) - { + if let Some(callee) = the_callee_in_facts( + facts, + context.index().types(), + fact.variadic_parameters, + ) { members.push(callee); } } @@ -617,10 +587,14 @@ fn judge_a_member_call( .filter(|member| context.index().member_name(member) == access.member) .filter_map(|member| { let fact = context.index().member_fact(member)?; - let parameters = fact.parameter_list()?; + // **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_callee_in_facts(facts, context.index().types(), has_an_ellipsis(parameters)) + // **The list's `...` from the fact; a pack from the parameters.** See + // [`crate::DeclFact::variadic_parameters`]. + the_callee_in_facts(facts, context.index().types(), fact.variadic_parameters) }) .collect(); } 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/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index afcb9bb5..79ed2f93 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -141,6 +141,9 @@ pub fn facts_with_their_types(built: BuiltFacts) -> Vec { // clearing the handle is what keeps a caller from resolving a local id through an arena that was dropped — // the same reason the two type handles above are materialized. 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 = crate::index::params::ParamsId::NONE; } facts @@ -747,8 +750,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(); @@ -771,22 +774,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!( @@ -796,8 +791,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); } } @@ -3586,41 +3580,47 @@ pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option sema::call_syntax::parameter_list_text(declarator.syntax()) } +/// **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. +/// +/// 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, -) -> Vec { - let mut found = None; - shapes.on_the_path(binding.name_range.start_offset, |shape| { - if let Some(declarator) = &shape.declarator - && names_the_binding(declarator, binding.name_range.start_offset) - { - found = Some(declarator.clone()); - } - }); - found - .and_then(|declarator| sema::call_syntax::parameter_list_node(&declarator)) - .map(|list| crate::index::params::parameter_facts_of(&list)) - .unwrap_or_default() +) -> ParameterListFacts { + let Some(list) = declared_parameter_list_with(shapes, binding) else { + return ParameterListFacts::default(); + }; + ParameterListFacts { + facts: crate::index::params::parameter_facts_of(&list), + variadic: list.is_variadic(), + } } -/// **The parameter list as the file spells it, read from the shape table** — `"(int a, int b)"`. +/// **The parameter list node the declarator that names this binding owns**, from the shape table. /// -/// [`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( +/// 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. @@ -3647,7 +3647,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`? @@ -4157,8 +4175,14 @@ fn fact_for( // 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_parameter_facts_with(shapes, binding); + 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) @@ -4218,6 +4242,9 @@ fn fact_for( type_of: DeclaredType::from_stored(type_of_id), returns: DeclaredType::from_stored(returns_id), 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), @@ -6497,6 +6524,25 @@ int Box::Inner::deep = 0; (built.facts, built.guards, built.types) } + /// 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, crate::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**, from the local table — the display edge a consumer uses. fn type_spelling_of( types: &crate::index::types::TypeStore, @@ -6563,6 +6609,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, + crate::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 diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index bc24ab30..9ecb76f0 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -460,22 +460,26 @@ impl Session { } /// **A declaration's parameters as the resolver takes them** — the structured types materialized from its facts, - /// and the list-level `...` the fact recorded. The one step every caller of the two methods above needs, in one - /// place. + /// 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 list-level ellipsis is read from the declaration's recorded parameter list because no field stores it: the - /// fact's `pack` bit describes a *parameter*, and a C-style `...` is a token of the list rather than a parameter. - /// That is the one property this boundary still takes from the display spelling; the types themselves never - /// pass through text. + /// 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( - index.parameter_types_of(file, fact), - fact.parameter_list().is_some_and(|list| list.contains("...")), + types, + fact.variadic_parameters || parameters.iter().any(|parameter| parameter.pack), ) } diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 604a5d72..e4e3fa1a 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2591,6 +2591,9 @@ mod tests { 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, diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index 4cde3147..7003a755 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -155,8 +155,9 @@ where // **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. - let mut rankable: Vec<(Vec, Vec)> = Vec::new(); + // 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 @@ -201,7 +202,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,7 +244,20 @@ where plain.push(written.map_or_else( || crate::index::types::ComputedType::named(text, Vec::new()), |written| crate::index::types::ComputedType::from(&written), - )); } + )); + } + // **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 = cpp_parser::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 @@ -261,7 +275,7 @@ where declared_at: source.name_offset, documentation: None, }); - rankable.push((plain, templates)); + rankable.push((plain, templates, variadic)); } } @@ -314,7 +328,7 @@ where .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(deduced) => plain @@ -325,11 +339,8 @@ where .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(); @@ -769,6 +780,11 @@ fn constructors_in_the_index( 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, diff --git a/crates/cpp_code_analysis/tests/suite/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 8f17c560..5d2c2baf 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); 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/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_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index d66e04af..20d4db5f 100644 --- a/crates/cpp_parser/src/syntax/node/cpp/mod.rs +++ b/crates/cpp_parser/src/syntax/node/cpp/mod.rs @@ -1451,7 +1451,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() diff --git a/docs/type-system-redesign.md b/docs/type-system-redesign.md index 45c05e4a..0ffccf17 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -110,6 +110,7 @@ struct DeclFact { type_of: DeclaredType, returns: DeclaredType, parameters: ParamsId, + variadic_parameters: bool, template_parameters: Box<[SmolStr]>, parameter_defaults: Box<[SmolStr]>, requires_clause: Option, @@ -269,6 +270,15 @@ struct ParameterFact { } ``` +**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: a summary's or a cooked reading's parameter holds `Stored` (lowered from its own `CppParam` node at construction), and a parameter a query synthesized from a view holds `Computed` — no `TypeId` is invented and no second store is minted. From be26c88f92d89edca228199165c9b03e7a379a9d Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 11:05:09 +0800 Subject: [PATCH 079/102] refactor(types): represent C elaborated record tags Type/ComputedType/TypeKind/EncodedTypeKind carry ElaboratedRecord { tag: Struct|Union, of } from CST struct/union specifiers; conversion derives the C record tag structurally and no longer takes written tag metadata. Display/messages keep the tag spelling. Workspace tests (3618 passed) and clippy pass. This is an intermediate green boundary before the single-type-model collapse. --- .../src/cache/summary_codec.rs | 63 +++- .../src/index/project/calls.rs | 12 +- .../src/index/project/macro_walk.rs | 7 +- .../src/index/types/compute.rs | 34 +- .../cpp_code_analysis/src/index/types/mod.rs | 100 +++++- .../src/sema/check/assign_type_check.rs | 9 +- .../src/sema/check/concept_not_satisfied.rs | 7 +- .../cpp_code_analysis/src/sema/check/mod.rs | 5 + .../src/sema/check/param_type_check.rs | 30 +- .../src/sema/check/return_type_mismatch.rs | 5 +- .../cpp_code_analysis/src/sema/constraint.rs | 3 + crates/cpp_code_analysis/src/sema/convert.rs | 137 ++++---- .../cpp_code_analysis/src/sema/deduction.rs | 15 +- crates/cpp_code_analysis/src/sema/overload.rs | 4 + crates/cpp_code_analysis/src/sema/types.rs | 332 ++++++++++++++++-- .../cpp_code_analysis/tests/suite/checks.rs | 45 ++- .../tests/suite/macro_member_types.rs | 4 +- crates/cpp_code_analysis/tests/suite/types.rs | 103 ++++-- 18 files changed, 748 insertions(+), 167 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 72aa1052..37682cc6 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -29,6 +29,7 @@ use crate::READING_FINGERPRINT; use crate::index::types::{EncodedType, EncodedTypeKind, TypeId, TypeTable}; use crate::macros; use crate::preprocess; +use crate::sema::types::RecordTag; use crate::summary; use smol_str::SmolStr; use std::path::PathBuf; @@ -317,7 +318,15 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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). -pub const CODEC_VERSION: u32 = 45; +/// +/// # 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). +pub const CODEC_VERSION: u32 = 46; /// Write a summary as bytes. /// @@ -1017,6 +1026,24 @@ 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 type table**, as a count-prefixed list of nodes. The IDs are the summary's local handles; they are /// meaningful only beside this table and are rewritten when the summary is inserted into an index. fn put_type_table(out: &mut Vec, table: &TypeTable) { @@ -1043,6 +1070,11 @@ fn put_type_table(out: &mut Vec, table: &TypeTable) { } EncodedTypeKind::Auto => put_u8(out, 3), EncodedTypeKind::DecltypeAuto => put_u8(out, 4), + EncodedTypeKind::ElaboratedRecord { tag, of } => { + put_u8(out, 11); + put_u8(out, encoded_record_tag(*tag)); + put_u32(out, *of); + } EncodedTypeKind::Pointer(to) => { put_u8(out, 5); put_u32(out, *to); @@ -1133,6 +1165,10 @@ fn get_type_table(reader: &mut Reader<'_>) -> Result { is_const: reader.u8()? != 0, is_volatile: reader.u8()? != 0, }, + 11 => EncodedTypeKind::ElaboratedRecord { + tag: decoded_record_tag(reader.u8()?).ok_or(DecodeError::BadDiscriminant)?, + of: reader.u32()?, + }, _ => return Err(DecodeError::BadDiscriminant), }; entries.push(EncodedType { id, spelling, kind }); @@ -1480,6 +1516,24 @@ mod tests { arguments: vec![0, 0], }, }, + // **C's record tags, one of each keyword** — the new discriminant, and both of its tag bytes, so + // that the round trip covers the encoding rather than a sample of it. + EncodedType { + id: 2, + spelling: Some("struct point".to_string()), + kind: EncodedTypeKind::ElaboratedRecord { + tag: crate::sema::types::RecordTag::Struct, + of: 0, + }, + }, + EncodedType { + id: 3, + spelling: Some("union value".to_string()), + kind: EncodedTypeKind::ElaboratedRecord { + tag: crate::sema::types::RecordTag::Union, + of: 0, + }, + }, ], }, declarations: vec![ @@ -2133,7 +2187,12 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// 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. -const COOKED_VERSION: u32 = 9; +/// +/// 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. +const COOKED_VERSION: u32 = 10; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 8ead59a0..e40bfd5c 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -826,8 +826,9 @@ pub(crate) fn the_return_the_overloads_agree_on( /// `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 converts the parameter structurally (no spelling, no parse) -/// and passes no C tag: the tag rule only applies when the caller knows the language is C, and this one does not. +/// 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( parameters: Option<&[crate::index::types::ComputedType]>, variadic: bool, @@ -863,7 +864,7 @@ pub(crate) fn a_candidate_that_can_be_called_this_way( // **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.to_sema_type(); - !sema::convert::conversion_to(argument, &target, None, None, |_| None).is_refused() + !sema::convert::conversion_to(argument, &target, None, |_| None).is_refused() }) } @@ -1695,7 +1696,10 @@ pub(crate) fn the_character_width(type_of: &crate::index::types::ComputedType) - pending.extend(named.arguments.iter()); } crate::index::types::ComputedType::Pointer(to) - | crate::index::types::ComputedType::Pack(to) => pending.push(to), + | crate::index::types::ComputedType::Pack(to) + | crate::index::types::ComputedType::ElaboratedRecord { of: to, .. } => { + pending.push(to) + } crate::index::types::ComputedType::Reference { to, .. } | crate::index::types::ComputedType::Array { of: to, .. } => pending.push(to), crate::index::types::ComputedType::Function(function) => { 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 158ea5c9..bd13ae00 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -1143,9 +1143,10 @@ impl ProjectIndex { .collect() } - /// **The spelling of one parameter's type**, for the display edge — a message quotes it and C's tag metadata - /// (`struct point`) is read from it; **nothing parses it**. A synthesized parameter prints its computed value; a - /// stored one answers the spelling the store recorded (the file's own words). + /// **The spelling of one parameter's type**, for the display edge — a message quotes it, and **nothing parses + /// it**. A synthesized parameter prints its computed value; a stored one answers the spelling the store recorded + /// (the file's own words, C's tag included). Every computation consumer asks [`ProjectIndex::parameter_type`], + /// whose `ComputedType` carries the tag structurally. pub fn parameter_spelling( &self, parameter: &ParameterFact, diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 949b161e..adfe0e95 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use smol_str::SmolStr; -use crate::sema::types::{Qualifiers, Type}; +use crate::sema::types::{Qualifiers, RecordTag, Type}; /// A name and its arguments — boxed inside [`ComputedType::Named`] so the enum's inline size stays small. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -52,6 +52,12 @@ pub enum ComputedType { TemplateParameter(SmolStr), Auto, DecltypeAuto, + /// **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, @@ -80,6 +86,8 @@ impl ComputedType { ComputedType::Named(named) => Some(named.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, } } @@ -98,6 +106,7 @@ impl ComputedType { 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::Auto | ComputedType::DecltypeAuto | ComputedType::Function(_) => None, } } @@ -108,6 +117,7 @@ impl ComputedType { ComputedType::Named(named) => &named.arguments, ComputedType::Reference { to, .. } => to.arguments(), ComputedType::Qualified(qualified) => qualified.of.arguments(), + ComputedType::ElaboratedRecord { of, .. } => of.arguments(), _ => &[], } } @@ -116,6 +126,7 @@ impl ComputedType { match self { ComputedType::Qualified(qualified) => qualified.is_const, ComputedType::Reference { to, .. } => to.is_const(), + ComputedType::ElaboratedRecord { of, .. } => of.is_const(), _ => false, } } @@ -137,6 +148,7 @@ impl ComputedType { 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, } } @@ -164,6 +176,7 @@ impl ComputedType { ComputedType::Pointer(to) | ComputedType::Pack(to) => to.heap_bytes(), ComputedType::Reference { to, .. } => to.heap_bytes(), ComputedType::Array { of, .. } => of.heap_bytes(), + ComputedType::ElaboratedRecord { of, .. } => of.heap_bytes(), ComputedType::Function(function) => { size_of::() + function.returns.heap_bytes() @@ -200,6 +213,10 @@ impl ComputedType { ComputedType::DecltypeAuto => Type::Builtin { spelling: "decltype(auto)".to_string(), }, + ComputedType::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.to_sema_type()), + }, ComputedType::Pointer(to) => Type::Pointer { to: Arc::new(to.to_sema_type()), }, @@ -258,6 +275,10 @@ impl ComputedType { | ComputedType::TemplateParameter(_) | ComputedType::Auto | ComputedType::DecltypeAuto => 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))) } @@ -300,6 +321,10 @@ impl ComputedType { ComputedType::Builtin(_) | ComputedType::Auto | ComputedType::DecltypeAuto => { self.clone() } + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.substituted(bindings)), + }, ComputedType::Named(named) => ComputedType::named( named.name.clone(), named @@ -348,6 +373,10 @@ impl From<&Type> for ComputedType { arguments.iter().map(ComputedType::from).collect(), ), Type::TemplateParameter { name } => ComputedType::TemplateParameter(name.into()), + Type::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(ComputedType::from(&**of)), + }, Type::Pointer { to } => ComputedType::Pointer(Arc::new(ComputedType::from(&**to))), Type::Reference { to, rvalue } => ComputedType::Reference { to: Arc::new(ComputedType::from(&**to)), @@ -398,6 +427,9 @@ impl fmt::Display for ComputedType { } ComputedType::Auto => write!(out, "auto"), ComputedType::DecltypeAuto => write!(out, "decltype(auto)"), + // **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 { "&" }) diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index d6744c1b..96bdb220 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -25,7 +25,7 @@ use std::fmt; use rustc_hash::FxHashMap; use smol_str::SmolStr; -use crate::sema::types::Type; +use crate::sema::types::{RecordTag, Type}; pub mod compute; pub use compute::{ComputedType, FunctionType, NamedType, QualifiedType}; @@ -131,6 +131,12 @@ pub enum TypeKind { Auto, /// `decltype(auto)`, which is a placeholder with different deduction rules from `auto`. DecltypeAuto, + /// **A C record written with its tag** — `struct point`, `union value`. The tag is what tells a record's name + /// from a `typedef` of something else; see [`crate::sema::types::RecordTag`]. + ElaboratedRecord { + tag: RecordTag, + of: TypeId, + }, Pointer(TypeId), Reference { to: TypeId, @@ -303,6 +309,10 @@ impl TypeStore { Type::TemplateParameter { name } => { TypeKind::TemplateParameter(self.names.intern(name)) } + Type::ElaboratedRecord { tag, of } => TypeKind::ElaboratedRecord { + tag: *tag, + of: self.intern_type(of), + }, Type::Pointer { to } => TypeKind::Pointer(self.intern_type(to)), Type::Reference { to, rvalue } => TypeKind::Reference { to: self.intern_type(to), @@ -422,6 +432,10 @@ impl TypeStore { } TypeKind::Auto => ComputedType::Auto, TypeKind::DecltypeAuto => ComputedType::DecltypeAuto, + TypeKind::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: std::sync::Arc::new(self.materialize(*of)?), + }, TypeKind::Pointer(to) => { ComputedType::Pointer(std::sync::Arc::new(self.materialize(*to)?)) } @@ -487,6 +501,13 @@ impl TypeStore { ), TypeKind::Auto => EncodedTypeKind::Auto, TypeKind::DecltypeAuto => EncodedTypeKind::DecltypeAuto, + TypeKind::ElaboratedRecord { tag, of } => { + pending.push(*of); + EncodedTypeKind::ElaboratedRecord { + tag: *tag, + of: of.0, + } + } TypeKind::Pointer(to) => { pending.push(*to); EncodedTypeKind::Pointer(to.0) @@ -564,6 +585,10 @@ impl TypeStore { } EncodedTypeKind::Auto => TypeKind::Auto, EncodedTypeKind::DecltypeAuto => TypeKind::DecltypeAuto, + EncodedTypeKind::ElaboratedRecord { tag, of } => TypeKind::ElaboratedRecord { + tag: *tag, + of: child(&map, *of), + }, EncodedTypeKind::Pointer(to) => TypeKind::Pointer(child(&map, *to)), EncodedTypeKind::Reference { to, rvalue } => TypeKind::Reference { to: child(&map, *to), @@ -661,6 +686,10 @@ pub enum EncodedTypeKind { TemplateParameter(String), Auto, DecltypeAuto, + ElaboratedRecord { + tag: RecordTag, + of: u32, + }, Pointer(u32), Reference { to: u32, @@ -718,6 +747,7 @@ impl TypeTable { EncodedTypeKind::Named { arguments, .. } => pending.extend(arguments.iter().copied()), EncodedTypeKind::Pointer(to) | EncodedTypeKind::Pack(to) + | EncodedTypeKind::ElaboratedRecord { of: to, .. } | EncodedTypeKind::Qualified { of: to, .. } | EncodedTypeKind::Reference { to, .. } | EncodedTypeKind::Array { of: to, .. } => pending.push(*to), @@ -810,6 +840,8 @@ impl<'a> TypeRef<'a> { TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { self.store.type_ref(*to)?.class_name() } + // **C's tag is transparent to a class question** — `struct point` names the record `point`. + TypeKind::ElaboratedRecord { of, .. } => self.store.type_ref(*of)?.class_name(), _ => None, } } @@ -818,7 +850,9 @@ impl<'a> TypeRef<'a> { pub fn arguments(self) -> &'a [TypeId] { match self.kind() { TypeKind::Named { arguments, .. } => self.store.arguments(*arguments), - TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { + TypeKind::Reference { to, .. } + | TypeKind::Qualified { of: to, .. } + | TypeKind::ElaboratedRecord { of: to, .. } => { self.store.type_ref(*to).map_or(&[], TypeRef::arguments) } _ => &[], @@ -871,6 +905,12 @@ impl<'a> TypeRef<'a> { } TypeKind::Auto => "auto".to_string(), TypeKind::DecltypeAuto => "decltype(auto)".to_string(), + // **The tag is written back** for a node that has no source spelling of its own; one that has a spelling + // is displayed from it, so the file's own characters win. + TypeKind::ElaboratedRecord { tag, of } => self.store.type_ref(*of).map_or_else( + || format!("{} ", tag.word()), + |inner| format!("{} {}", tag.word(), inner.render()), + ), TypeKind::Pointer(to) => self.store.type_ref(*to).map_or_else( || "*".to_string(), |inner| format!("{}*", inner.render()), @@ -918,7 +958,7 @@ impl<'a> TypeRef<'a> { #[cfg(test)] mod tests { use super::*; - use crate::sema::types::{Qualifiers, Type}; + use crate::sema::types::{Qualifiers, RecordTag, Type}; use std::mem::size_of; use std::sync::Arc; @@ -991,6 +1031,60 @@ mod tests { ); } + /// **C's record tag crosses the store and the record that carries it.** The tag is written on the declaration, so + /// a fact's handle has to materialize it back — a `ComputedType` for the queries and a `Type` for the conversion + /// question — and the table a summary exports has to bring it along. Dropping it at either boundary is what would + /// turn `struct point *` into a name a `typedef` could also spell. + #[test] + fn a_c_record_tag_survives_the_store_and_the_table() { + let mut store = TypeStore::new(); + let written = store.intern_spelling("struct point *"); + let computed = store.materialize(written).expect("materialized"); + assert_eq!(computed.to_string(), "struct point*"); + let parser = computed.to_sema_type(); + assert!( + matches!( + parser, + Type::Pointer { ref to } + if matches!( + **to, + Type::ElaboratedRecord { + tag: RecordTag::Struct, + .. + } + ) + ), + "the tag survives materialization: {parser:?}" + ); + + let value = store.intern_spelling("union value"); + assert_eq!( + store.materialize(value).expect("materialized").to_string(), + "union value", + "a union writes its own keyword" + ); + + // **The table a summary writes is the same shape.** Export, import into a fresh store, and read it back: + // both records must answer their tag from the imported nodes. + let table = store.export([written, value]); + let mut loaded = TypeStore::new(); + let mapping = loaded.import(&table); + assert_eq!( + loaded + .materialize(mapping[&written.raw()]) + .expect("restored") + .to_string(), + "struct point*" + ); + assert_eq!( + loaded + .materialize(mapping[&value.raw()]) + .expect("restored") + .to_string(), + "union value" + ); + } + #[test] fn a_type_kind_is_sixteen_bytes() { assert_eq!(size_of::(), 16); 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 28389c76..f7cd7652 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 @@ -412,7 +412,7 @@ fn not_assignable(type_of: &sema::types::Type) -> Option { // 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 and the C tag (`struct point`) that a `Type` cannot carry. +/// quotes. /// /// 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 @@ -422,9 +422,6 @@ fn not_assignable(type_of: &sema::types::Type) -> Option { struct Target { type_of: sema::types::Type, written: smol_str::SmolStr, - /// The name after `struct`/`union` when the declaration wrote C's tag syntax — boundary metadata read from the - /// spelling, as [`sema::convert::conversion_to`] documents. - tagged_record: Option, } impl Target { @@ -437,7 +434,6 @@ impl Target { Some(Target { type_of: computed.to_sema_type(), written: smol_str::SmolStr::new(written.trim()), - tagged_record: sema::convert::tagged_record_in(written).map(str::to_string), }) } } @@ -468,7 +464,7 @@ fn report_if_it_does_not_convert( }; // **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; the C tag is metadata read from the spelling at that same construction edge. + // 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, &target.type_of) { return; @@ -476,7 +472,6 @@ fn report_if_it_does_not_convert( if sema::convert::conversion_to( &from, &target.type_of, - target.tagged_record.as_deref(), context.language.family(), |class| a_class_can_be_built_from(context, class, &from), ) == sema::convert::Conversion::Refused 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 14d85f9d..abfdf6e1 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 @@ -281,8 +281,7 @@ impl Concept { Concept::ConvertibleTo(written) => { // **The concept's argument, parsed once here.** The conversion below takes the `Type`, not a // spelling: the old form wrote the parsed shape back out and parsed it again, which is a second - // reader of the same question. The tag is the written metadata a parsed type cannot carry. - let tagged_record = sema::convert::tagged_record_in(written); + // reader of the same question. C's tag is part of the parsed type now, so nothing is read beside it. let target = sema::types::parse_type_spelling(written); match passed.convertible_to(&target) { // The class case goes through the shared facility, exactly as `param-type-check` asks it — a @@ -290,9 +289,7 @@ impl Concept { Known::No => Some(false), Known::Yes(()) => Some(true), Known::Unknown(_) => Some(!matches!( - sema::convert::conversion_to(passed, &target, tagged_record, None, |_| { - None - }), + sema::convert::conversion_to(passed, &target, None, |_| None), sema::convert::Conversion::Refused )), } diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index edf590f7..9dacdd6c 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -1644,6 +1644,9 @@ pub fn a_spelling_of(type_of: &sema::types::Type) -> Option { | Type::TemplateParameter { .. } | Type::Pack { .. } | Type::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. + Type::ElaboratedRecord { tag, of } => format!("{} {}", tag.word(), a_spelling_of(of)?), Type::Pointer { to } => format!("{} *", a_spelling_of(to)?), Type::Reference { to, rvalue } => format!( "{} {}", @@ -1904,6 +1907,8 @@ fn could_take_an_arithmetic_value(type_of: &crate::index::types::ComputedType) - 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), }) 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 43faa62e..0e76aacf 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 @@ -23,8 +23,8 @@ //! **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 two display-only jobs: the message quotes it, and C's tag metadata -//! (`struct point`) is read from it, since a `Type` cannot say whether its name was tagged. +//! spelling. The written form survives for one display-only job: the message quotes it. C's tag (`struct point`) is +//! part of the `Type` (`Type::ElaboratedRecord`), not a second reading of that text. //! //! [`ParameterFact`]: crate::index::params::ParameterFact //! @@ -95,7 +95,7 @@ impl Check for ParamTypeCheck { }; // **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 and where C's tag metadata is read. + // 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) { @@ -253,18 +253,16 @@ fn candidates_of_a_list(parameters: &CppParamList) -> Vec { } /// **One candidate parameter, read once at this boundary** — the spelling the declaring file wrote (the finding -/// quotes it, and C's tag metadata reads it) and the [`Type`](sema::types::Type) the conversion question takes. +/// quotes it) and the [`Type`](sema::types::Type) 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 and for the C tag (`struct point`), the one piece of written evidence a `Type` -/// cannot carry. +/// `written` exists for the message alone. #[derive(Clone)] struct CandidateParameter { written: String, type_of: sema::types::Type, - tagged_record: Option, } impl CandidateParameter { @@ -273,16 +271,12 @@ impl CandidateParameter { 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 { - tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), - written, - type_of, - }) + 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 the metadata read from that spelling. + /// [`crate::ProjectIndex::parameter_spelling`], both read-only; the C tag is part of the resolved type. fn from_fact( index: &crate::ProjectIndex, parameter: &crate::index::params::ParameterFact, @@ -290,7 +284,6 @@ impl CandidateParameter { let type_of = index.parameter_type(parameter)?.to_sema_type(); let written = index.parameter_spelling(parameter)?; Some(Self { - tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), written: written.to_string(), type_of, }) @@ -300,7 +293,7 @@ impl CandidateParameter { /// /// `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 and the C tag only, to the spelling as text. That is the computation twin of + /// 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: &crate::ProjectIndex, @@ -321,7 +314,6 @@ impl CandidateParameter { written = smol_str::SmolStr::new(substitution.applied_to_spelling(&written, fact)); } Some(Self { - tagged_record: sema::convert::tagged_record_in(&written).map(str::to_string), written: written.to_string(), type_of: type_of.to_sema_type(), }) @@ -330,12 +322,11 @@ impl CandidateParameter { /// **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 - /// never writes a C tag; so there is no tag metadata to carry here. + /// writes C's tag from the type when there is one. fn from_type(type_of: &sema::types::Type) -> Option { Some(Self { written: a_spelling_of(type_of)?, type_of: type_of.clone(), - tagged_record: None, }) } } @@ -403,11 +394,10 @@ fn check_the_arguments( // 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 the C tag is the metadata read from the same spelling at that boundary. + // built, and its type carries C's tag, which the shared facility reads structurally. if !sema::convert::conversion_to( &from, ¶meter.type_of, - parameter.tagged_record.as_deref(), context.language.family(), |class| a_class_can_be_built_from(context, class, &from), ) 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 af1725fd..80aa7e4d 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 @@ -74,13 +74,13 @@ impl Check for ReturnTypeMismatch { continue; } // **The return type as the conversion question takes it**, and the spelling the message quotes. The two - // come from the same fact; the C tag (`struct point`) is the written metadata a `Type` cannot carry. + // 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.to_sema_type(); - let declared_tag = sema::convert::tagged_record_in(&declared); for returned in the_returns_in(&function) { // **A `co_return` is the coroutine promise`s business, not a conversion.** The parser files @@ -157,7 +157,6 @@ impl Check for ReturnTypeMismatch { let conversion = sema::convert::conversion_to( &from, &declared_type, - declared_tag, context.language.family(), |class| a_class_can_be_built_from(context, class, &from), ); diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index 6f288b7e..ea74a03b 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -168,6 +168,9 @@ impl Trait { 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, } } diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index 35be9082..d9852463 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -6,9 +6,9 @@ //! //! **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 [`Type`](sema::types::Type); this module never parses the same spelling again. The one -//! piece of written evidence a parsed type cannot carry is C's tag (`struct point`), which crosses the boundary as -//! explicit metadata ([`tagged_record_in`]) rather than as a second reading of the text. +//! boundary and passes the [`Type`]; this module never parses the same spelling again. C's tag +//! (`struct point`) is not an exception: the type carries it as [`Type::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 //! @@ -16,7 +16,7 @@ //! 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::sema::types::{RecordTag, Type}; use cpp_parser::features; /// **What it takes to use a value of one type where another is expected.** @@ -42,12 +42,12 @@ 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: &Type) -> bool { match type_of { - sema::types::Type::Pointer { .. } => true, - sema::types::Type::Qualified { of, .. } => a_pointer(of), + Type::Pointer { .. } => true, + Type::Qualified { of, .. } => a_pointer(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, + Type::Array { .. } => true, _ => false, } } @@ -58,26 +58,24 @@ fn a_pointer(type_of: &sema::types::Type) -> bool { /// 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: &sema::types::Type) -> &sema::types::Type { +fn the_referent(type_of: &Type) -> &Type { match type_of { - sema::types::Type::Reference { to, .. } | sema::types::Type::Qualified { of: to, .. } => { - the_referent(to) - } + Type::Reference { to, .. } | Type::Qualified { of: to, .. } => the_referent(to), other => other, } } /// **Can a value of `from` be used where the parsed `target` is expected?** /// -/// `target` is a [`Type`](sema::types::Type), not a spelling: nothing in this function parses a string, and the +/// `target` is a [`Type`], 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. /// -/// `tagged_record` is the one piece of **written metadata** a `Type` does not carry: the name after `struct`/`union` -/// when the target was written with C's tag syntax (`struct point *` answers `Some("point")`). It is read from the -/// CST or the written spelling at the caller's boundary — [`tagged_record_in`] is that reader — because a `Named` -/// type cannot say whether its name was tagged, and `typedef int point;` makes the tag the only evidence that the -/// name is a record. A C++ target passes whatever it read; this function consults the metadata only in C. +/// **C's tag is part of the type.** `struct point *` is a [`Type::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 @@ -90,9 +88,8 @@ fn the_referent(type_of: &sema::types::Type) -> &sema::types::Type { /// `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: &sema::types::Type, - target: &sema::types::Type, - tagged_record: Option<&str>, + from: &Type, + target: &Type, family: Option, answer_the_class_question: impl FnOnce(&str) -> Option, ) -> Conversion { @@ -102,7 +99,7 @@ pub fn conversion_to( // capability lookup of that shape. if matches!( target, - sema::types::Type::Builtin { spelling } + Type::Builtin { spelling } if spelling == "bool" || spelling == "_Bool" ) && a_pointer(from) { @@ -111,16 +108,17 @@ pub fn conversion_to( // **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 *tag*, which is why it arrives as metadata: - // 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** + // ([`Type::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) = tagged_record - && !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; } @@ -141,7 +139,7 @@ pub fn conversion_to( // 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, sema::types::Type::TemplateParameter { .. }) { + if matches!(bare, Type::TemplateParameter { .. }) { return Conversion::Unknown; } let Some(class) = bare.class_name() else { @@ -150,7 +148,7 @@ pub fn conversion_to( // **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 [`Type::class_name`](sema::types::Type::class_name)**, never a type + // read as one. This is a **name check on [`Type::class_name`](Type::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. @@ -164,26 +162,33 @@ pub fn conversion_to( } } -/// **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** ([`Type::ElaboratedRecord`]), which the declaration reader and +/// `parse_type_spelling` produce from the written keyword and which the index's `TypeStore` keeps. No caller hands +/// this function a spelling, and nothing here scans one: a type that crossed a fact boundary still carries its tag. /// -/// This is **boundary metadata**, not part of [`Type`](sema::types::Type): C's own syntax writes `struct`/`union` -/// before a name as a tag, and no typedef can write one, so the word is the evidence the type algebra cannot keep. -/// A caller reads it here **once**, from the CST or from the written spelling it already holds, and hands it to -/// [`conversion_to`]; the conversion core never scans a string. +/// 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. /// /// `enum` is deliberately not here — an enumeration *is* an arithmetic type in C, and `enum colour c = 3;` is -/// ordinary code. -pub(crate) fn tagged_record_in(written: &str) -> Option<&str> { - 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(); - } +/// ordinary code. See [`RecordTag`]. +fn a_tagged_record_in(type_of: &Type) -> Option<(RecordTag, &str)> { + match type_of { + Type::ElaboratedRecord { tag, of } => of.class_name().map(|name| (*tag, name)), + Type::Pointer { to } + | Type::Reference { to, .. } + | Type::Pack { of: to } + | Type::Qualified { of: to, .. } + | Type::Array { of: to, .. } => a_tagged_record_in(to), + Type::Function { + returns, + parameters, + } => a_tagged_record_in(returns).or_else(|| parameters.iter().find_map(a_tagged_record_in)), + Type::Named { arguments, .. } => arguments.iter().find_map(a_tagged_record_in), + Type::Builtin { .. } | Type::TemplateParameter { .. } => None, } - None } /// **Is this value that record?** — through any qualifiers, pointers and array bounds, because `struct point **` and @@ -191,34 +196,46 @@ pub(crate) fn tagged_record_in(written: &str) -> Option<&str> { /// /// 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: &Type, 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) + Type::Qualified { of, .. } => the_value_is_that_record(of, tag, record), + Type::ElaboratedRecord { tag: written, of } => { + *written == tag && of.class_name().is_some_and(|name| names_the_record(name, record)) } - sema::types::Type::Pointer { to } => { - matches!(&**to, sema::types::Type::Builtin { spelling } if spelling == "void") - || the_value_is_that_record(to, record) + Type::Named { name, .. } => names_the_record(name, record), + Type::Pointer { to } => { + matches!(&**to, Type::Builtin { spelling } if spelling == "void") + || the_value_is_that_record(to, tag, record) } - sema::types::Type::Array { of, .. } => the_value_is_that_record(of, record), + Type::Array { of, .. } => the_value_is_that_record(of, tag, record), _ => false, } } + +/// 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. /// -/// [`Type::TemplateParameter`](sema::types::Type::TemplateParameter) is the structural answer — the declaration's own +/// [`Type::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: &sema::types::Type) -> bool { +pub(crate) fn names_a_template_parameter_for_a_check(type_of: &Type) -> bool { match type_of { - sema::types::Type::TemplateParameter { .. } => true, - sema::types::Type::Pointer { to } - | sema::types::Type::Reference { to, .. } - | sema::types::Type::Qualified { of: to, .. } => names_a_template_parameter_for_a_check(to), + Type::TemplateParameter { .. } => true, + Type::Pointer { to } + | Type::Reference { to, .. } + | Type::Qualified { of: to, .. } => names_a_template_parameter_for_a_check(to), other => other.class_name().is_some_and(names_a_template_parameter), } } diff --git a/crates/cpp_code_analysis/src/sema/deduction.rs b/crates/cpp_code_analysis/src/sema/deduction.rs index 27d1b10c..22d5a5ff 100644 --- a/crates/cpp_code_analysis/src/sema/deduction.rs +++ b/crates/cpp_code_analysis/src/sema/deduction.rs @@ -168,6 +168,16 @@ fn bind_inside( return bind(bound, name, argument).then_some(true); } + // **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) { ( ComputedType::Named(written), @@ -246,7 +256,9 @@ fn bind(bound: &mut HashMap, name: &str, argument: &Comput } /// 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. +/// 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 { @@ -255,6 +267,7 @@ fn the_shape_of(type_of: &ComputedType) -> &ComputedType { ComputedType::Qualified(qualified) if qualified.is_const || qualified.is_volatile => { &qualified.of } + ComputedType::ElaboratedRecord { of, .. } => of, other => return other, }; } diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index f595569a..6c13b39e 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -348,6 +348,10 @@ fn the_shape_of(type_of: &ComputedType) -> &ComputedType { 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, }; } diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index baa09b8e..914b99a3 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -18,6 +18,7 @@ //! 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::ElaboratedRecord { tag, of } `struct point`, `union value` — C's tag, kept on the type //! Type::Pointer { to } `Widget*` //! Type::Reference { to, rvalue } `Widget&`, `Widget&&` //! Type::Array { of, extent } `int[4]`, `int[]` @@ -226,6 +227,45 @@ impl Qualifiers { } } +/// **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 +/// ([`Type::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, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Type { /// A builtin: `int`, `void`, `unsigned long long`, `decltype(auto)`. @@ -246,6 +286,19 @@ pub enum Type { TemplateParameter { name: String, }, + /// **A C record written with its tag**: `struct point`, `union value`. + /// + /// The keyword is the evidence that a name denotes a record rather than a `typedef` of something else, and that + /// evidence is not recoverable from [`Type::Named`] — `typedef int point;` writes one. The wrapper is + /// **transparent to the type relation and to class questions** (`struct point` and `point` are one shape to + /// everything except display), and the one consumer that reads the tag is the C conversion rule in + /// [`crate::sema::convert`]. + /// + /// `enum` is not one of these: see [`RecordTag`]. + ElaboratedRecord { + tag: RecordTag, + of: TypeOf, + }, Pointer { to: TypeOf, }, @@ -296,6 +349,68 @@ fn a_pointee_without_its_qualifiers(type_of: &TypeOf) -> (&Type, bool) { (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: &Type) -> bool { + match type_of { + Type::ElaboratedRecord { .. } => true, + Type::Named { arguments, .. } => arguments.iter().any(has_an_elaborated_record), + Type::Pointer { to } | Type::Pack { of: to } => has_an_elaborated_record(to), + Type::Reference { to, .. } | Type::Qualified { of: to, .. } => has_an_elaborated_record(to), + Type::Array { of, .. } => has_an_elaborated_record(of), + Type::Function { + returns, + parameters, + } => has_an_elaborated_record(returns) || parameters.iter().any(has_an_elaborated_record), + Type::Builtin { .. } | Type::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. Before [`Type::ElaboratedRecord`] +/// existed the declaration reader dropped the keyword before a type ever reached the algebra, so the relation is kept +/// exactly as it was by removing the wrapper here rather than teaching every arm about it. 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: &Type) -> Type { + match type_of { + Type::ElaboratedRecord { of, .. } => without_elaborated_records(of), + Type::Named { name, arguments } => Type::Named { + name: name.clone(), + arguments: arguments.iter().map(without_elaborated_records).collect(), + }, + Type::Pointer { to } => Type::Pointer { + to: Arc::new(without_elaborated_records(to)), + }, + Type::Reference { to, rvalue } => Type::Reference { + to: Arc::new(without_elaborated_records(to)), + rvalue: *rvalue, + }, + Type::Array { of, extent } => Type::Array { + of: Arc::new(without_elaborated_records(of)), + extent: *extent, + }, + Type::Function { + returns, + parameters, + } => Type::Function { + returns: Arc::new(without_elaborated_records(returns)), + parameters: parameters.iter().map(without_elaborated_records).collect(), + }, + Type::Pack { of } => Type::Pack { + of: Arc::new(without_elaborated_records(of)), + }, + Type::Qualified { of, qualifiers } => Type::Qualified { + of: Arc::new(without_elaborated_records(of)), + qualifiers: *qualifiers, + }, + Type::Builtin { .. } | Type::TemplateParameter { .. } => type_of.clone(), + } +} + impl Type { pub fn builtin(spelling: impl Into) -> Type { Type::Builtin { @@ -327,6 +442,10 @@ impl Type { // `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(), + // **C's tag is transparent too.** `struct point` and `point` name one record, and a member question goes + // to the name; the tag is evidence about what the name *is*, which `sema::convert` reads, not a + // different class. + Type::ElaboratedRecord { of, .. } => of.class_name(), _ => None, } } @@ -336,6 +455,7 @@ impl Type { match self { Type::Named { arguments, .. } => arguments, Type::Reference { to, .. } | Type::Qualified { of: to, .. } => to.arguments(), + Type::ElaboratedRecord { of, .. } => of.arguments(), _ => &[], } } @@ -450,7 +570,25 @@ impl Type { pub fn convertible_to(&self, target: &Type) -> sema::symbol::Known<()> { use crate::sema::symbol::Known; - let from = self.decay(); + // **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 @@ -667,7 +805,8 @@ impl Type { Type::Pointer { to } | Type::Reference { to, .. } | Type::Pack { of: to } - | Type::Qualified { of: to, .. } => to.depends_on_a_parameter(), + | Type::Qualified { of: to, .. } + | Type::ElaboratedRecord { of: to, .. } => to.depends_on_a_parameter(), Type::Array { of, .. } => of.depends_on_a_parameter(), Type::Function { returns, @@ -756,6 +895,13 @@ impl Type { of: Arc::new(of.substituted(substitutions)), qualifiers: *qualifiers, }, + // **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: + // the keyword is part of how the type was written, not of the name it was written on. + Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.substituted(substitutions)), + }, Type::Builtin { .. } => self.clone(), } } @@ -821,6 +967,11 @@ impl Type { of: Arc::new(of.replacing(name, with)), qualifiers: *qualifiers, }, + // The tag travels with the name it was written on — see [`Type::substituted`]. + Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.replacing(name, with)), + }, } } } @@ -850,6 +1001,10 @@ impl fmt::Display for Type { } Ok(()) } + // **The tag is written back**, because that is what the file wrote: the relation treats `struct point` + // and `point` as one shape, while a hover or a message is owed the file's own spelling. `of` is a base, + // so a pointer written around it (`struct point*`) comes out as the same words in the same order. + Type::ElaboratedRecord { tag, of } => write!(out, "{} {of}", tag.word()), Type::Pointer { to } => write!(out, "{to}*"), Type::Reference { to, rvalue } => { if *rvalue { @@ -1185,6 +1340,12 @@ pub fn without_placeholders_written_as_names(written: Type) -> Type { of: Arc::new(without_placeholders_written_as_names((*of).clone())), qualifiers, }, + // A tag is not a placeholder: `struct auto` is not a spelling, and what it wraps is normalized like any + // other name. + Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + tag, + of: Arc::new(without_placeholders_written_as_names((*of).clone())), + }, builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, } } @@ -1241,6 +1402,11 @@ pub fn with_template_parameters>(written: Type, parameters: &[N]) of: Arc::new(with_template_parameters_of(&of, parameters)), qualifiers, }, + // See [`Type::substituted`]: a tag written before a name stays before whatever that name became. + Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + tag, + of: Arc::new(with_template_parameters_of(&of, parameters)), + }, builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, } } @@ -1396,7 +1562,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { // 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"); } @@ -1425,6 +1591,16 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { }, }; + // **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) => Type::ElaboratedRecord { + tag, + of: Arc::new(qualified), + }, + None => qualified, + }; + match qualifier.is_none() { true => qualified, false => Type::Qualified { @@ -1565,15 +1741,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() { @@ -1583,15 +1761,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. @@ -2125,9 +2309,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 /// @@ -2172,9 +2356,10 @@ 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 `Type::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 { @@ -2250,6 +2435,9 @@ pub(crate) fn read_specifiers_named( 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; @@ -2279,7 +2467,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 @@ -2398,7 +2593,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(Type::named(tag)); + } None => an_unnamed_body = true, } } @@ -2437,7 +2643,16 @@ pub(crate) fn read_specifiers_named( let answer = if !builtin.is_empty() { Type::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) => Type::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 @@ -3218,6 +3433,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 `Type::ElaboratedRecord` — rather than + /// dropping it, so a fact that crosses the `TypeStore` 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 Type::Pointer { to } = &pointed else { + panic!("`struct point *p` is a pointer: {pointed:?}"); + }; + assert!( + matches!( + &**to, + Type::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, + Type::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"), + Type::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, Type::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. /// @@ -3791,7 +4071,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/tests/suite/checks.rs b/crates/cpp_code_analysis/tests/suite/checks.rs index 5d2c2baf..fb34fdd5 100644 --- a/crates/cpp_code_analysis/tests/suite/checks.rs +++ b/crates/cpp_code_analysis/tests/suite/checks.rs @@ -4415,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. @@ -4450,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/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/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 2595901c..612bcb8e 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2151,11 +2151,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(), @@ -2226,12 +2228,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" ); } @@ -3440,9 +3444,10 @@ 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**: a caller parses the written target once at its own boundary, and -/// the C tag (`struct point`) is metadata read from that spelling there, because a `Named` type cannot say whether its -/// name was written with one. This pins the rules the checks rely on at that seam. +/// 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_to}; @@ -3451,14 +3456,12 @@ fn a_template_parameter_target_is_not_a_refusal() { let an_int = Type::builtin("int"); assert_eq!( - conversion_to(&an_int, &parse_type_spelling("_Ty2&&"), None, 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_to(&an_int, &parse_type_spelling("T"), None, None, |_| None), + conversion_to(&an_int, &parse_type_spelling("T"), None, |_| None), Conversion::Unknown, "and so is a bare `T`" ); @@ -3467,7 +3470,7 @@ fn a_template_parameter_target_is_not_a_refusal() { name: "T".to_string(), }; assert_eq!( - conversion_to(&an_int, &a_parameter, None, None, |_| None), + conversion_to(&an_int, &a_parameter, None, |_| None), Conversion::Unknown, "`Type::TemplateParameter` is a template parameter, structurally" ); @@ -3477,7 +3480,6 @@ fn a_template_parameter_target_is_not_a_refusal() { &an_int, &parse_type_spelling("const Widget&"), None, - None, |_| Some(false) ), Conversion::Refused, @@ -3485,23 +3487,18 @@ fn a_template_parameter_target_is_not_a_refusal() { // **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_to(&a_string, &Type::builtin("int"), None, None, |_| None), + conversion_to(&a_string, &Type::builtin("int"), None, |_| None), Conversion::Unknown ); - // **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, &Type::builtin("bool"), None, None, |_| None), - Conversion::Implicit, - ); - // **In C, a tagged record is nobody else's type** — the tag is metadata the `Type` cannot carry, so the caller - // passes it from the written spelling (`struct point *`) and the core stays structural. + + // **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("point"), Some(Family::C), |_| None ), @@ -3512,25 +3509,69 @@ fn a_template_parameter_target_is_not_a_refusal() { conversion_to( &a_record_pointer, &a_record_pointer, - Some("point"), Some(Family::C), |_| None ), Conversion::Implicit, "and the record itself converts to the same record" ); - // **The gate matters**: the same pair without the C tag metadata is `Unknown`, not a refusal — the type algebra - // cannot tell the name is a record, and the safe direction is silence. + // **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 *"), - &a_record_pointer, - None, + &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, &Type::builtin("bool"), None, |_| None), + Conversion::Implicit, + ); } /// **A member's deduced return type, through the header that declares it** — `auto copy_of() const { return value_; }`. From 701458ddd7354645d621e5ca870bb94699788afb Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 11:29:18 +0800 Subject: [PATCH 080/102] refactor(types): reshape ComputedType into primary forms ComputedType is now Primary(PrimaryType), Named(SmolStr), Generic(name+arguments), TemplateParameter, ElaboratedRecord, and the structural pointer/reference/array/function/pack/qualified variants. Builtin and old Named(Arc) are gone; Generic carries template instantiations, Named is argument-less. The 32-byte size is preserved. Materialize maps stored TypeKind into the new shape; display/codec behavior is unchanged. Tests (3627 passed) and clippy pass. This is the shape step before removing TypeStore/Type. --- crates/cpp_code_analysis/src/cache/summary.rs | 4 +- .../src/cache/summary_codec.rs | 4 +- .../src/index/project/calls.rs | 17 +- .../src/index/project/substituted.rs | 10 +- .../src/index/project/type_of.rs | 10 +- .../src/index/types/compute.rs | 598 +++++++++++++++--- .../cpp_code_analysis/src/index/types/mod.rs | 48 +- .../src/sema/check/argument_count.rs | 7 +- .../cpp_code_analysis/src/sema/check/mod.rs | 36 +- .../cpp_code_analysis/src/sema/constraint.rs | 100 +-- crates/cpp_code_analysis/src/sema/deduce.rs | 20 +- .../cpp_code_analysis/src/sema/deduction.rs | 12 +- crates/cpp_code_analysis/src/sema/overload.rs | 31 +- .../src/session/completion/mod.rs | 7 +- crates/cpp_code_analysis/tests/params.rs | 12 +- 15 files changed, 694 insertions(+), 222 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 092da41c..0f2dbb21 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -1614,8 +1614,8 @@ mod declared_type_tests { "a stored handle is materialized through the store it names" ); - let computed = DeclaredType::Computed(std::sync::Arc::new(ComputedType::Builtin( - "unsigned long".into(), + let computed = DeclaredType::Computed(std::sync::Arc::new(ComputedType::Primary( + crate::index::types::PrimaryType::UnsignedLong, ))); assert!(!computed.is_none()); assert!(computed.has_value()); diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 37682cc6..d51da6f2 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -1795,10 +1795,10 @@ mod tests { // `Stored(NONE)` in the process. let mut original = every_field(); original.declarations[1].type_of = DeclaredType::Computed(std::sync::Arc::new( - crate::index::types::ComputedType::Builtin("int".into()), + crate::index::types::ComputedType::Primary(crate::index::types::PrimaryType::Int), )); original.declarations[1].returns = DeclaredType::Computed(std::sync::Arc::new( - crate::index::types::ComputedType::Builtin("void".into()), + crate::index::types::ComputedType::Primary(crate::index::types::PrimaryType::Void), )); let decoded = diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index e40bfd5c..76a8e267 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1687,13 +1687,18 @@ pub(crate) fn the_character_width(type_of: &crate::index::types::ComputedType) - let mut pending = vec![type_of]; while let Some(current) = pending.pop() { match current { - crate::index::types::ComputedType::Builtin(name) - | crate::index::types::ComputedType::TemplateParameter(name) => { + crate::index::types::ComputedType::Primary(primary) => { + width_of_a_name(primary.spelling(), &mut wide, &mut narrow); + } + crate::index::types::ComputedType::TemplateParameter(name) => { + width_of_a_name(name, &mut wide, &mut narrow); + } + crate::index::types::ComputedType::Named(name) => { width_of_a_name(name, &mut wide, &mut narrow); } - crate::index::types::ComputedType::Named(named) => { - width_of_a_name(&named.name, &mut wide, &mut narrow); - pending.extend(named.arguments.iter()); + crate::index::types::ComputedType::Generic(generic) => { + width_of_a_name(&generic.name, &mut wide, &mut narrow); + pending.extend(generic.arguments.iter()); } crate::index::types::ComputedType::Pointer(to) | crate::index::types::ComputedType::Pack(to) @@ -1707,8 +1712,6 @@ pub(crate) fn the_character_width(type_of: &crate::index::types::ComputedType) - pending.extend(function.parameters.iter()); } crate::index::types::ComputedType::Qualified(qualified) => pending.push(&qualified.of), - crate::index::types::ComputedType::Auto - | crate::index::types::ComputedType::DecltypeAuto => {} } } if wide { diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index acdf93a6..d31e3207 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -374,14 +374,12 @@ fn substituted_members_with( /// `read_template_arguments` answers [`ComputedType::Named`] 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 builtin type. +/// `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(named) - if named.arguments.is_empty() && sema::types::is_a_builtin(&named.name) => - { - ComputedType::Builtin(named.name.clone()) - } + ComputedType::Named(name) => index::types::PrimaryType::from_spelling(name) + .map_or_else(|| argument.clone(), ComputedType::Primary), other => other.clone(), } } 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 bef6d439..ecccc9e0 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -2033,9 +2033,13 @@ pub(crate) fn operator_returns_of_with_arguments( target.class_name(), ) { (Some(qualifier), Some(bare)) if !bare.contains("::") => match &target { - ComputedType::Named(named) => Some(ComputedType::named( - format!("{qualifier}::{bare}"), - named.arguments.to_vec(), + 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. diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index adfe0e95..4c1a6f3f 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -13,9 +13,19 @@ //! immutable after indexing owned by the request / SemanticModel //! ``` //! -//! The large variants are boxed (`Named`, `Function`, `Qualified`) so the enum stays 32 bytes. A `SmolStr` is a small -//! copy from the store's name table; a long name shares its `Arc` with the store. The result is cheap to build -//! and cheap to clone, and it owns no borrow of the index. +//! # 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. The store still keeps the written spelling for display; the mapping happens once, at the storage boundary. +//! +//! 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` is a +//! small copy from the store's name table; a long name shares its `Arc` with the store. The result is cheap to +//! build and cheap to clone, and it owns no borrow of the index. use std::fmt; use std::sync::Arc; @@ -23,9 +33,168 @@ use smol_str::SmolStr; use crate::sema::types::{Qualifiers, RecordTag, Type}; -/// A name and its arguments — boxed inside [`ComputedType::Named`] so the enum's inline size stays small. +/// **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 NamedType { +pub struct GenericType { pub name: SmolStr, pub arguments: Box<[ComputedType]>, } @@ -47,11 +216,14 @@ pub struct QualifiedType { /// 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 { - Builtin(SmolStr), - Named(Arc), + /// 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), - Auto, - DecltypeAuto, /// **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 { @@ -73,17 +245,37 @@ pub enum ComputedType { } 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 { - ComputedType::Named(Arc::new(NamedType { - name: name.into(), - arguments: arguments.into_boxed_slice(), - })) + 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. pub fn class_name(&self) -> Option<&str> { match self { - ComputedType::Named(named) => Some(named.name.as_str()), + ComputedType::Named(name) => 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`. @@ -93,28 +285,31 @@ impl ComputedType { } /// **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 builtin answers its spelling. + /// `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 { - ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => Some(name.as_str()), - ComputedType::Named(named) => Some(named.name.as_str()), + // **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::Auto | ComputedType::DecltypeAuto | ComputedType::Function(_) => None, + 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::Named(named) => &named.arguments, + ComputedType::Generic(generic) => &generic.arguments, ComputedType::Reference { to, .. } => to.arguments(), ComputedType::Qualified(qualified) => qualified.of.arguments(), ComputedType::ElaboratedRecord { of, .. } => of.arguments(), @@ -138,13 +333,19 @@ impl ComputedType { } } - /// **Is this the `auto` placeholder**, however it was written around — `auto`, `auto&`, `const auto*`? + /// Is this exactly `void`? The C spelling of an empty parameter list, and the answer to "is there a value here". + pub fn is_void(&self) -> bool { + matches!(self, ComputedType::Primary(PrimaryType::Void)) + } + + /// **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::Auto | ComputedType::DecltypeAuto => true, + 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(), @@ -162,17 +363,17 @@ impl ComputedType { let text = |name: &SmolStr| name.len(); size_of::() + match self { - ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => text(name), - ComputedType::Named(named) => { - size_of::() - + text(&named.name) - + named + 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::Auto | ComputedType::DecltypeAuto => 0, ComputedType::Pointer(to) | ComputedType::Pack(to) => to.heap_bytes(), ComputedType::Reference { to, .. } => to.heap_bytes(), ComputedType::Array { of, .. } => of.heap_bytes(), @@ -197,21 +398,19 @@ impl ComputedType { /// exists because the current type engine still speaks `sema::types::Type`. pub fn to_sema_type(&self) -> Type { match self { - ComputedType::Builtin(spelling) => Type::Builtin { - spelling: spelling.to_string(), - }, - ComputedType::Named(named) => Type::Named { - name: named.name.to_string(), - arguments: named.arguments.iter().map(Self::to_sema_type).collect(), + ComputedType::Primary(primary) => Type::Builtin { + spelling: primary.spelling().to_string(), }, - ComputedType::TemplateParameter(name) => Type::TemplateParameter { + ComputedType::Named(name) => Type::Named { name: name.to_string(), + arguments: Vec::new(), }, - ComputedType::Auto => Type::Builtin { - spelling: "auto".to_string(), + ComputedType::Generic(generic) => Type::Named { + name: generic.name.to_string(), + arguments: generic.arguments.iter().map(Self::to_sema_type).collect(), }, - ComputedType::DecltypeAuto => Type::Builtin { - spelling: "decltype(auto)".to_string(), + ComputedType::TemplateParameter(name) => Type::TemplateParameter { + name: name.to_string(), }, ComputedType::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { tag: *tag, @@ -260,21 +459,17 @@ impl ComputedType { /// the same rule the `Type` version follows. pub fn replacing(&self, name: &str, with: &ComputedType) -> ComputedType { match self { - ComputedType::Named(found) if found.arguments.is_empty() && found.name == name => { - with.clone() - } - ComputedType::Named(found) => ComputedType::named( - found.name.clone(), - found + 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::Builtin(_) - | ComputedType::TemplateParameter(_) - | ComputedType::Auto - | ComputedType::DecltypeAuto => self.clone(), + })), + ComputedType::Primary(_) | ComputedType::TemplateParameter(_) => self.clone(), ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { tag: *tag, of: Arc::new(of.replacing(name, with)), @@ -318,21 +513,19 @@ impl ComputedType { .iter() .find(|(parameter, _)| parameter == name) .map_or_else(|| self.clone(), |(_, concrete)| concrete.clone()), - ComputedType::Builtin(_) | ComputedType::Auto | ComputedType::DecltypeAuto => { - self.clone() - } - ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { - tag: *tag, - of: Arc::new(of.substituted(bindings)), - }, - ComputedType::Named(named) => ComputedType::named( - named.name.clone(), - named + 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(bindings)) .collect(), - ), + })), + ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { + tag: *tag, + of: Arc::new(of.substituted(bindings)), + }, ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.substituted(bindings))), ComputedType::Reference { to, rvalue } => ComputedType::Reference { to: Arc::new(to.substituted(bindings)), @@ -367,7 +560,7 @@ impl From<&Type> for ComputedType { /// converted from the structure the query already holds. fn from(value: &Type) -> ComputedType { match value { - Type::Builtin { spelling } => ComputedType::Builtin(spelling.into()), + Type::Builtin { spelling } => ComputedType::from_builtin_spelling(spelling), Type::Named { name, arguments } => ComputedType::named( name.as_str(), arguments.iter().map(ComputedType::from).collect(), @@ -405,28 +598,35 @@ impl From<&Type> for ComputedType { } } +impl ComputedType { + /// **A 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. + fn from_builtin_spelling(spelling: &str) -> ComputedType { + match PrimaryType::from_spelling(spelling) { + Some(primary) => ComputedType::Primary(primary), + None => ComputedType::Named(SmolStr::new(spelling.trim())), + } + } +} + impl fmt::Display for ComputedType { fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ComputedType::Builtin(name) | ComputedType::TemplateParameter(name) => { + ComputedType::Primary(primary) => write!(out, "{}", primary.spelling()), + ComputedType::Named(name) | ComputedType::TemplateParameter(name) => { write!(out, "{name}") } - ComputedType::Named(named) => { - if named.arguments.is_empty() { - write!(out, "{}", named.name) - } else { - write!(out, "{}<", named.name)?; - for (at, argument) in named.arguments.iter().enumerate() { - if at > 0 { - write!(out, ", ")?; - } - write!(out, "{argument}")?; + ComputedType::Generic(generic) => { + write!(out, "{}<", generic.name)?; + for (at, argument) in generic.arguments.iter().enumerate() { + if at > 0 { + write!(out, ", ")?; } - write!(out, ">") + write!(out, "{argument}")?; } + write!(out, ">") } - ComputedType::Auto => write!(out, "auto"), - ComputedType::DecltypeAuto => write!(out, "decltype(auto)"), // **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()), @@ -484,12 +684,233 @@ mod tests { ); } + /// 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(&[(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: Some(4), + } + .to_string(), + "int[4]" + ); + assert_eq!( + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: None, + } + .to_string(), + "int[]" + ); + 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 store keeps + /// the written spelling; the computation layer 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::from(&Type::builtin("short int")); + assert_eq!(short_int, ComputedType::Primary(PrimaryType::Short)); + assert_eq!(short_int.to_string(), "short", "the canonical spelling"); + + assert_eq!( + ComputedType::from(&Type::builtin("unsigned")), + ComputedType::Primary(PrimaryType::UnsignedInt) + ); + assert_eq!( + ComputedType::from(&Type::builtin("decltype(auto)")), + ComputedType::Primary(PrimaryType::DecltypeAuto) + ); + assert_eq!( + ComputedType::from(&Type::builtin("auto")), + ComputedType::Primary(PrimaryType::Auto) + ); + + let extension = ComputedType::from(&Type::builtin("__int128")); + assert_eq!(extension, ComputedType::Named(SmolStr::new("__int128"))); + assert_eq!(extension.to_string(), "__int128", "the spelling survives"); + assert_eq!( + ComputedType::from(&Type::builtin("")), + ComputedType::Named(SmolStr::new("")) + ); + } + #[test] fn the_parser_bridge_preserves_the_shape() { let value = ComputedType::Pointer(Arc::new(ComputedType::Reference { to: Arc::new(ComputedType::named( "std::vector", - vec![ComputedType::Builtin(SmolStr::new("int"))], + vec![ComputedType::Primary(PrimaryType::Int)], )), rvalue: false, })); @@ -505,7 +926,7 @@ mod tests { fn a_boxed_named_type_renders_and_answers_members() { let value = ComputedType::named( "std::vector", - vec![ComputedType::Builtin(SmolStr::new("int"))], + vec![ComputedType::Primary(PrimaryType::Int)], ); assert_eq!(value.to_string(), "std::vector"); assert_eq!(value.class_name(), Some("std::vector")); @@ -518,9 +939,7 @@ mod tests { let value = Type::Named { name: "std::vector".to_string(), arguments: vec![Type::Pointer { - to: Arc::new(Type::Builtin { - spelling: "int".to_string(), - }), + to: Arc::new(Type::builtin("int")), }], }; assert_eq!(ComputedType::from(&value).to_string(), "std::vector"); @@ -537,8 +956,25 @@ mod tests { ); let concretely = value.substituted(&[( SmolStr::new("T"), - ComputedType::Builtin(SmolStr::new("int")), + 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 96bdb220..817751d5 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -28,7 +28,7 @@ use smol_str::SmolStr; use crate::sema::types::{RecordTag, Type}; pub mod compute; -pub use compute::{ComputedType, FunctionType, NamedType, QualifiedType}; +pub use compute::{ComputedType, FunctionType, GenericType, PrimaryType, QualifiedType}; /// A handle to one node in a [`TypeStore`]. /// @@ -290,11 +290,14 @@ impl TypeStore { pub fn intern_type_written_as(&mut self, written: &Type, source: Option<&str>) -> TypeId { let spelling = source.map_or_else(|| written.to_string(), str::to_string); let kind = match written { - Type::Builtin { spelling } if spelling.trim() == "auto" => TypeKind::Auto, - Type::Builtin { spelling } if spelling.trim() == "decltype(auto)" => { - TypeKind::DecltypeAuto - } - Type::Builtin { spelling } => TypeKind::Builtin(self.names.intern(spelling.trim())), + // **The placeholders are storage kinds of their own** — the computation layer folds them back into + // [`PrimaryType::Auto`]/[`PrimaryType::DecltypeAuto`]. The one spelling-to-primary table lives in + // `compute`; this is a construction-edge lookup, not a parse. + Type::Builtin { spelling } => match PrimaryType::from_spelling(spelling) { + Some(PrimaryType::Auto) => TypeKind::Auto, + Some(PrimaryType::DecltypeAuto) => TypeKind::DecltypeAuto, + _ => TypeKind::Builtin(self.names.intern(spelling.trim())), + }, Type::Named { name, arguments } => { let name = self.names.intern(name); let arguments = arguments @@ -415,23 +418,30 @@ impl TypeStore { pub fn materialize(&self, id: TypeId) -> Option { let node = self.node(id)?; Some(match &node.kind { - TypeKind::Builtin(name) => ComputedType::Builtin(self.names.smol(*name)?), + // **A stored builtin is the primary it spells.** The node keeps the file's spelling for `TypeRef::display`; + // the computation layer works with the primary identity, and a spelling outside the language's primary set + // (a compiler extension) has no primary to answer, so it stays a name. + TypeKind::Builtin(name) => { + let name = self.names.smol(*name)?; + match PrimaryType::from_spelling(&name) { + Some(primary) => ComputedType::Primary(primary), + None => ComputedType::Named(name), + } + } TypeKind::Named { name, arguments } => { - ComputedType::Named(std::sync::Arc::new(NamedType { - name: self.names.smol(*name)?, - arguments: self - .arguments(*arguments) - .iter() - .filter_map(|argument| self.materialize(*argument)) - .collect::>() - .into_boxed_slice(), - })) + let name = self.names.smol(*name)?; + let arguments = self + .arguments(*arguments) + .iter() + .filter_map(|argument| self.materialize(*argument)) + .collect::>(); + ComputedType::named(name, arguments) } TypeKind::TemplateParameter(name) => { ComputedType::TemplateParameter(self.names.smol(*name)?) } - TypeKind::Auto => ComputedType::Auto, - TypeKind::DecltypeAuto => ComputedType::DecltypeAuto, + TypeKind::Auto => ComputedType::Primary(PrimaryType::Auto), + TypeKind::DecltypeAuto => ComputedType::Primary(PrimaryType::DecltypeAuto), TypeKind::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { tag: *tag, of: std::sync::Arc::new(self.materialize(*of)?), @@ -1006,7 +1016,7 @@ mod tests { assert_eq!(computed.to_string(), "const T&"); let substituted = computed.substituted(&[( SmolStr::new("T"), - ComputedType::Builtin(SmolStr::new("int")), + ComputedType::Primary(PrimaryType::Int), )]); assert_eq!(substituted.to_string(), "const int&"); } 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 1baa7eca..82c568d9 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -315,7 +315,7 @@ fn callees_in_this_file( // parameter list of exactly one unnamed `void` declares nothing. if written == 1 && parameters_written.len() == 1 - && matches!(¶meters_written[0], ComputedType::Builtin(name) if name == "void") + && parameters_written[0].is_void() { written = 0; required = 0; @@ -465,10 +465,7 @@ fn the_callee_in_facts( } parameters.push(type_of); } - if written == 1 - && parameters.len() == 1 - && matches!(¶meters[0], ComputedType::Builtin(name) if name == "void") - { + if written == 1 && parameters.len() == 1 && parameters[0].is_void() { written = 0; required = 0; parameters.clear(); diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index 9dacdd6c..706ee533 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -1828,8 +1828,13 @@ fn parameters_that_could_accept( /// `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: &crate::index::types::ComputedType) -> Option { - use crate::index::types::ComputedType; + 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!( @@ -1867,33 +1872,38 @@ fn could_take_an_arithmetic_value(type_of: &crate::index::types::ComputedType) - || name.starts_with("class ") || name.starts_with("typename ") }; + let a_primary = |primary: PrimaryType| { + if primary.is_a_placeholder() { + None + } else { + Some(primary.is_arithmetic()) + } + }; Some(match type_of { - ComputedType::Builtin(name) => arithmetic(name), + 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(named) if named.arguments.is_empty() => { - if arithmetic(&named.name) { + ComputedType::Named(name) => { + if arithmetic(name) { true - } else if looks_like_a_template_parameter(&named.name) { + } else if looks_like_a_template_parameter(name) { return None; } else { false } } - ComputedType::Named(_) => false, - ComputedType::TemplateParameter(_) - | ComputedType::Auto - | ComputedType::DecltypeAuto => return None, + 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::Builtin(name) => arithmetic(name), - ComputedType::Named(named) if named.arguments.is_empty() => { - if arithmetic(&named.name) { + ComputedType::Primary(primary) => return a_primary(*primary), + ComputedType::Named(name) => { + if arithmetic(name) { true - } else if looks_like_a_template_parameter(&named.name) { + } else if looks_like_a_template_parameter(name) { return None; } else { false diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index ea74a03b..62633011 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -30,7 +30,7 @@ //! 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. -use crate::index::types::ComputedType; +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; @@ -174,11 +174,11 @@ impl Trait { _ => 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::Builtin(spelling) => Some(spelling.as_str()), - // **A name with no arguments is a scalar this layer can place** — `size_t`, `std::size_t`, `ptrdiff_t` - // are the standard's names for builtin types. A name *with* arguments is a class template, which is not. - ComputedType::Named(named) if named.arguments.is_empty() => Some(named.name.as_str()), + 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 @@ -192,53 +192,16 @@ impl Trait { && !function && !pack && match base { - ComputedType::TemplateParameter(_) - | ComputedType::Auto - | ComputedType::DecltypeAuto => true, - ComputedType::Named(named) if named.arguments.is_empty() => { - a_parameter_by_convention(&named.name) - } - ComputedType::Named(_) => false, - ComputedType::Builtin(name) => name.starts_with("decltype") || name == "auto", + 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| { - !array - && !function - && !pack - && matches!( - scalar, - "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 = scalar.is_some_and(|scalar| { - !array && !function && !pack && matches!(scalar, "float" | "double" | "long double") - }); - let signed = integral - && scalar.is_some_and(|scalar| { - !scalar.starts_with("unsigned") && !matches!(scalar, "bool" | "unsigned") - }); + 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. @@ -258,7 +221,13 @@ impl Trait { Trait::FloatingPoint => floating && !pointer && !reference, Trait::Arithmetic => (integral || floating) && !pointer && !reference, Trait::Pointer => pointer && !reference, - Trait::Void => scalar == Some("void") && !pointer && !reference && !array && !function, + 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. @@ -269,6 +238,39 @@ impl Trait { } } +/// **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), +} + +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"), + } + } + + fn is_floating_point(self) -> bool { + matches!(self, Scalar::Primary(primary) if primary.is_floating_point()) + } + + fn is_unsigned(self) -> bool { + match self { + Scalar::Primary(primary) => primary.is_unsigned(), + Scalar::Named(name) => name.starts_with("unsigned") || name == "uint64_t", + } + } + + fn is_void(self) -> bool { + matches!(self, Scalar::Primary(PrimaryType::Void)) + } +} + /// **Decide a condition**, with the template parameters bound to the types a call deduced. /// /// `condition` is the typed expression node a caller got from [`the_condition_of_node`] or diff --git a/crates/cpp_code_analysis/src/sema/deduce.rs b/crates/cpp_code_analysis/src/sema/deduce.rs index 8bc05131..ab657e35 100644 --- a/crates/cpp_code_analysis/src/sema/deduce.rs +++ b/crates/cpp_code_analysis/src/sema/deduce.rs @@ -64,19 +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 index - .computed_returns_of(fact) - .is_some_and(|returns| matches!(returns, index::types::ComputedType::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 !index - .computed_type_of(fact) - .is_some_and(|type_of| matches!(type_of, index::types::ComputedType::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 22d5a5ff..699289fa 100644 --- a/crates/cpp_code_analysis/src/sema/deduction.rs +++ b/crates/cpp_code_analysis/src/sema/deduction.rs @@ -179,12 +179,12 @@ fn bind_inside( } match (parameter, argument) { - ( - ComputedType::Named(written), - ComputedType::Named(found), - ) => { - // A name is not a shape: two different class templates are not unified, and the arguments are paired - // positionally only when the names agree. + // **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 { diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 6c13b39e..f83de661 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -35,7 +35,7 @@ //! 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::types::ComputedType; +use crate::index::types::{ComputedType, PrimaryType}; use crate::sema; use crate::sema::symbol::Known; @@ -364,22 +364,19 @@ fn the_shape_of(type_of: &ComputedType) -> &ComputedType { /// 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: &ComputedType, to: &ComputedType) -> bool { - const NARROW: [&str; 6] = [ - "char", - "signed char", - "unsigned char", - "short", - "short int", - "unsigned short", - ]; - const TO_INT: [&str; 2] = ["int", "unsigned int"]; - - let (ComputedType::Builtin(from), ComputedType::Builtin(to)) = (from, to) else { + let (ComputedType::Primary(from), ComputedType::Primary(to)) = (from, to) else { return false; }; - (NARROW.contains(&from.as_str()) && TO_INT.contains(&to.as_str())) - || (from == "float" && to == "double") + (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)] @@ -649,9 +646,9 @@ fn a_template_argument_pack_inside_a_parameter_is_not_the_parameter_pack() { assert_eq!( parameters, vec![ - ComputedType::Builtin("int".into()), - ComputedType::Builtin("bool".into()), - ComputedType::Builtin("int".into()), + ComputedType::Primary(PrimaryType::Int), + ComputedType::Primary(PrimaryType::Bool), + ComputedType::Primary(PrimaryType::Int), ] ); assert!(!variadic); diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index e4e3fa1a..1d3c1520 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -2577,7 +2577,12 @@ mod tests { fn a_functions_detail_line_is_what_it_takes() { use crate::index::types::ComputedType; - let builtin = |name: &str| ComputedType::Builtin(name.into()); + // **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, diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs index 1f473c2e..8649b55d 100644 --- a/crates/cpp_code_analysis/tests/params.rs +++ b/crates/cpp_code_analysis/tests/params.rs @@ -7,7 +7,7 @@ use cpp_code_analysis::cache::summary::DeclaredType; use cpp_code_analysis::index::params::parameter_facts_of; -use cpp_code_analysis::index::types::{ComputedType, TypeStore}; +use cpp_code_analysis::index::types::{ComputedType, PrimaryType, TypeStore}; use cpp_code_analysis::sema; use cpp_code_analysis::sema::overload::parameters_in_facts; use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; @@ -43,7 +43,10 @@ fn parameter_types_come_from_each_cpp_param() { 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::Builtin(name) if name == "int"), + matches!( + ¶meters[0], + ComputedType::Primary(PrimaryType::Int) + ), "`int a` is an `int`, and the name is not part of it: {:?}", parameters[0] ); @@ -59,7 +62,10 @@ fn parameter_types_come_from_each_cpp_param() { "neither the name nor the comma split the arguments" ); assert!( - matches!(¶meters[2], ComputedType::Builtin(name) if name == "double"), + matches!( + ¶meters[2], + ComputedType::Primary(PrimaryType::Double) + ), "a pack is ranked by its element type: {:?}", parameters[2] ); From 2968d721523461a86813e7768d3a3e612f006fd4 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 13:04:31 +0800 Subject: [PATCH 081/102] refactor(types): delete the stored type arena DeclFact and ParameterFact now carry DeclaredType::{None, Computed(Arc)} directly. Builders lower CST types structurally and never intern. TypeStore, TypeId, TypeTable, TypeKind, EncodedTypeKind, TypeNode/TypeRef and their codec tables are deleted; facts encode ComputedType values directly with versioned tagged encoding (CODEC_VERSION 47, COOKED_VERSION 11, UNIT_CODEC_VERSION 9). Canonical display replaces stored written-spelling aliases. ComputedType remaining semantic Type bridge is the next batch. Workspace tests (3615 passed) and clippy pass. --- crates/cpp_code_analysis/src/cache/memory.rs | 13 - crates/cpp_code_analysis/src/cache/summary.rs | 223 ++- .../src/cache/summary_codec.rs | 639 +++++---- .../cpp_code_analysis/src/cache/unit_codec.rs | 10 +- crates/cpp_code_analysis/src/index/mod.rs | 24 - crates/cpp_code_analysis/src/index/params.rs | 46 +- .../src/index/project/bases.rs | 65 +- .../src/index/project/macro_walk.rs | 209 +-- .../src/index/project/member_facts.rs | 2 +- .../src/index/project/mod.rs | 26 +- .../src/index/project/tests.rs | 109 +- .../src/index/project/type_of.rs | 22 +- crates/cpp_code_analysis/src/index/store.rs | 3 - .../src/index/types/compute.rs | 26 +- .../cpp_code_analysis/src/index/types/mod.rs | 1208 +---------------- .../src/sema/check/argument_count.rs | 22 +- .../src/sema/check/assign_type_check.rs | 23 +- crates/cpp_code_analysis/src/sema/convert.rs | 2 +- .../src/sema/declarations.rs | 1016 +++++++------- crates/cpp_code_analysis/src/sema/model.rs | 33 +- crates/cpp_code_analysis/src/sema/overload.rs | 49 +- crates/cpp_code_analysis/src/sema/render.rs | 15 +- crates/cpp_code_analysis/src/sema/types.rs | 337 ++--- crates/cpp_code_analysis/src/session/calls.rs | 86 +- .../src/session/completion/mod.rs | 71 +- .../src/session/completion/request.rs | 27 +- crates/cpp_code_analysis/src/session/cook.rs | 23 +- .../cpp_code_analysis/src/session/memory.rs | 5 - .../cpp_code_analysis/src/session/semantic.rs | 15 +- crates/cpp_code_analysis/tests/params.rs | 42 +- .../tests/suite/reported_defects.rs | 8 +- crates/cpp_ls/src/handlers/completion/mod.rs | 4 +- crates/cpp_ls/src/handlers/hover/mod.rs | 16 +- .../tests/suite/handshake/diagnostics.rs | 4 +- docs/type-system-redesign.md | 71 +- 35 files changed, 1480 insertions(+), 3014 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/memory.rs b/crates/cpp_code_analysis/src/cache/memory.rs index fea6841f..43efbfa1 100644 --- a/crates/cpp_code_analysis/src/cache/memory.rs +++ b/crates/cpp_code_analysis/src/cache/memory.rs @@ -48,11 +48,6 @@ pub struct MemoryReport { pub declarations: usize, pub declarations_with_detail: usize, pub declaration_detail_bytes: usize, - /// **The interned type store** — distinct types, names and argument lists, plus the store's estimated bytes. - pub types: usize, - pub type_names: usize, - pub type_argument_lists: usize, - pub type_store_bytes: usize, /// The cooked reading: how many files have one, and their estimated bytes. pub cooked_files: usize, pub cooked_bytes: usize, @@ -231,14 +226,6 @@ impl std::fmt::Display for MemoryReport { mb(self.walks_by_content_bytes), mb(self.shared_timeline_bytes), )?; - write!( - formatter, - " | types {} ({} name(s), {} argument list(s), {})", - thousands(self.types), - thousands(self.type_names), - thousands(self.type_argument_lists), - mb(self.type_store_bytes), - )?; write!( formatter, " | index tables {} ({} name(s) / {} name posting(s), {} scope(s) / {} scope posting(s), \ diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 0f2dbb21..c587d7f2 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -33,7 +33,7 @@ use crate::cache; use crate::condition; use crate::index; use crate::index::params::{ParameterFact, ParamsId, ParamsStore}; -use crate::index::types::{ComputedType, TypeId, TypeTable}; +use crate::index::types::ComputedType; use crate::macros; use crate::paths; use crate::preprocess; @@ -55,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; @@ -137,73 +138,57 @@ impl DeclModifiers { } } -/// **The type a declaration carries** — the one value that answers "stored, synthesized, or absent?". +/// **The type a declaration carries** — the value itself, or the honest absence of one. /// -/// A [`DeclFact`] moves between arenas. A fact filed in a summary holds a [`TypeId`] into the one global -/// [`TypeStore`], while a fact a query synthesized — a view fact built from a buffer the index has not read, a -/// generated member, a substituted display copy — has no arena to intern into. Storing an `Option` and an -/// `Option>` side by side made that a pair of fields that had to agree with each other; this enum -/// is the choice itself. +/// 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. /// -/// There is **no second `TypeStore` and no arena tag**: [`DeclaredType::Stored`] is always a handle into the one -/// global store, and [`DeclaredType::Computed`] is a value for which no `TypeId` exists at all. +/// 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. /// -/// [`TypeStore`]: crate::index::types::TypeStore +/// 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, - /// A handle into the one global [`TypeStore`]; valid only after the summary or reading is filed in an index. - Stored(TypeId), - /// A query-synthesized type. No [`TypeId`] exists for it and none is invented: an ID from a second store would - /// silently alias the global one. - Computed(std::sync::Arc), + /// The type itself, lowered from the declaration's syntax once at the construction edge. + Computed(Arc), } impl DeclaredType { - /// Is there no type at all — neither stored nor computed? + /// Is there no type at all? pub fn is_none(&self) -> bool { matches!(self, Self::None) } - /// The handle this value holds, when it is stored. - pub fn stored_id(&self) -> Option { - match self { - Self::Stored(id) => Some(*id), - _ => None, - } - } - - /// The synthesized value this type holds, when it is computed. - pub fn computed(&self) -> Option<&std::sync::Arc> { + /// The value this type holds, when there is one. + pub fn computed(&self) -> Option<&Arc> { match self { Self::Computed(computed) => Some(computed), - _ => None, - } - } - - /// **The type as the computation layer works on it.** A stored handle is materialized from `store` — the one - /// global store, never a local one — and a synthesized value is cloned. Nothing is parsed. - pub fn as_computed(&self, store: &index::types::TypeStore) -> Option { - match self { Self::None => None, - Self::Stored(id) => store.materialize(*id), - Self::Computed(computed) => Some((**computed).clone()), } } - /// Does this value carry a type at all, stored or computed? + /// Does this value carry a type at all? pub fn has_value(&self) -> bool { !self.is_none() } - /// A stored handle, or [`DeclaredType::None`] for the [`TypeId::NONE`] sentinel. - /// - /// A summary built from syntax marks "no type" with the sentinel, so the builder funnels the two through here - /// rather than letting a `Stored(NONE)` into the vocabulary. - pub(crate) fn from_stored(id: TypeId) -> Self { - if id.is_none() { Self::None } else { Self::Stored(id) } + /// **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))) } } @@ -303,12 +288,10 @@ pub struct DeclFact { /// /// Three limits, all deliberate: /// - /// * **A value, not a spelling.** A stored fact holds a [`DeclaredType::Stored`] handle into the one global - /// [`TypeStore`], which keeps the source spelling beside the structure, so a display edge can print what the - /// file wrote and a computation edge can materialize a [`ComputedType`] without parsing anything. A fact a - /// query synthesized — a view fact built from a buffer the index has not read, a generated member, a - /// substituted display copy — carries a [`DeclaredType::Computed`] value instead: minting a `TypeId` for it - /// would need a second store, and an ID from a second store would silently alias the global one. + /// * **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. /// [`DeclaredType::None`] is the honest answer for them. @@ -316,7 +299,6 @@ pub struct DeclFact { /// 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. /// - /// [`TypeStore`]: crate::index::types::TypeStore pub type_of: DeclaredType, /// The type a **function** returns, by the same rule as [`DeclFact::type_of`] — see [`DeclaredType`]. /// @@ -592,18 +574,10 @@ impl DeclarationAccounting { } impl DeclFact { - /// The interned form of [`DeclFact::type_of`], when the summary has been inserted into an index. - pub fn type_of_id(&self) -> Option { - self.type_of.stored_id() - } - - /// The interned form of [`DeclFact::returns`], when the summary has been inserted into an index. - pub fn returns_id(&self) -> Option { - self.returns.stored_id() - } - - /// **Does this fact carry a type at all** — stored or computed? A consumer deciding "is this a typedef" - /// asks this; one that wants the type itself asks [`crate::ProjectIndex::computed_type_of`]. + /// **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() } @@ -613,22 +587,13 @@ impl DeclFact { self.returns.has_value() } - /// **Take another fact's computed types**, for a display copy that was rebuilt from a second reading. + /// **Take another fact's types**, for a display copy that was rebuilt from a second reading. /// - /// The copy has no arena of its own, so it cannot keep the other fact's handles: they would index a table that - /// does not travel with it. It keeps the computed values instead, and an ordinary stored type becomes - /// [`DeclaredType::None`] — the same shape a synthesized fact has. + /// 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 - .computed() - .cloned() - .map_or(DeclaredType::None, DeclaredType::Computed); - self.returns = other - .returns - .computed() - .cloned() - .map_or(DeclaredType::None, DeclaredType::Computed); + 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. @@ -1460,7 +1425,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, @@ -1468,7 +1433,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 { @@ -1503,8 +1468,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, @@ -1594,35 +1558,20 @@ mod fact_size_tests { #[cfg(test)] mod declared_type_tests { use super::{ComputedType, DeclaredType}; - use crate::index::types::{TypeId, TypeStore}; + use crate::index::types::PrimaryType; + use std::sync::Arc; - /// **One enum, three answers** — the accessors a consumer uses to tell stored, computed and absent apart, and - /// `as_computed` as the single materialization edge. + /// **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_three_states_are_distinguishable() { - let mut store = TypeStore::new(); - let id = store.intern_spelling("int"); - - let stored = DeclaredType::Stored(id); - assert!(!stored.is_none()); - assert!(stored.has_value()); - assert_eq!(stored.stored_id(), Some(id)); - assert!(stored.computed().is_none()); - assert_eq!( - stored.as_computed(&store).map(|computed| computed.to_string()), - Some("int".to_string()), - "a stored handle is materialized through the store it names" - ); - - let computed = DeclaredType::Computed(std::sync::Arc::new(ComputedType::Primary( - crate::index::types::PrimaryType::UnsignedLong, - ))); + 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_eq!(computed.stored_id(), None); assert!(computed.computed().is_some()); assert_eq!( - computed.as_computed(&store).map(|computed| computed.to_string()), + computed.as_computed().map(|computed| computed.to_string()), Some("unsigned long".to_string()), "a computed value is already materialized and is cloned, not interned" ); @@ -1630,15 +1579,18 @@ mod declared_type_tests { let absent = DeclaredType::None; assert!(absent.is_none()); assert!(!absent.has_value()); - assert_eq!(absent.stored_id(), None); assert!(absent.computed().is_none()); - assert!(absent.as_computed(&store).is_none()); + assert!(absent.as_computed().is_none()); assert_eq!(DeclaredType::default(), DeclaredType::None); assert_eq!( - DeclaredType::from_stored(TypeId::NONE), + DeclaredType::from_computed(None), DeclaredType::None, - "the sentinel is an absence, never `Stored(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))) ); } } @@ -1670,7 +1622,6 @@ impl FileSummary { .iter() .map(DeclFact::heap_bytes) .sum::() - + self.types.heap_bytes() + self.macros.iter().map(MacroFact::heap_bytes).sum::() + self .includes @@ -1708,10 +1659,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(); @@ -1736,8 +1684,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 @@ -1747,7 +1695,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 @@ -1756,10 +1704,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(); @@ -1799,7 +1744,7 @@ impl MacroDefinitions { path: &Path, source: &str, fact: &MacroFact, - ) -> Option> { + ) -> Option> { self.definition_of(path, source, fact) } } @@ -2142,7 +2087,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. /// @@ -2194,14 +2139,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 @@ -2286,14 +2231,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, @@ -2418,13 +2363,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); } @@ -2501,7 +2446,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; @@ -2982,7 +2927,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, @@ -3000,7 +2945,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; @@ -3018,12 +2963,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); @@ -3550,7 +3495,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(), @@ -5527,9 +5472,6 @@ 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 type table.** Facts hold local IDs on disk; inserting into a `ProjectIndex` imports - /// this table and rewrites them to process-local handles. Empty for a summary built directly from syntax. - pub types: TypeTable, /// The summary's local parameter arena, indexed by `DeclFact::parameters`. pub parameters: ParamsStore, pub macros: Vec, @@ -5717,7 +5659,6 @@ impl FileSummary { path: path.into(), key, declarations: Vec::new(), - types: TypeTable::default(), parameters: ParamsStore::default(), macros: Vec::new(), includes: Vec::new(), @@ -6056,7 +5997,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. @@ -6124,7 +6065,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 d51da6f2..f7a7a6dd 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -23,16 +23,18 @@ //! 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::types::{EncodedType, EncodedTypeKind, TypeId, TypeTable}; +use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::macros; use crate::preprocess; use crate::sema::types::RecordTag; use crate::summary; use smol_str::SmolStr; use std::path::PathBuf; +use std::sync::Arc; use cpp_parser::SymbolKind; use cpp_parser::{MacroBody, SourceRange}; @@ -42,7 +44,7 @@ use crate::index::CookedFile; use crate::preprocess::directive::IncludeForm; use crate::summary::CookedDiagnostic; use crate::summary::{ - Access, ConditionalRegion, DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, GuardBranch, + Access, ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, IncludeFact, MacroFact, MacroKind, MacroScopeReading, ModuleReading, SummaryGuards, TranslationUnit, TuEvent, TuFrame, }; @@ -321,12 +323,29 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// /// # Version 46 /// -/// **The type table can hold a C record's tag** — see [`EncodedTypeKind::ElaboratedRecord`]. The tag was previously +/// **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). -pub const CODEC_VERSION: u32 = 46; +/// +/// # 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). +pub const CODEC_VERSION: u32 = 47; + +/// **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; /// Write a summary as bytes. /// @@ -442,10 +461,6 @@ pub fn encode(summary: &FileSummary) -> Vec { put_u32(&mut out, summary.use_filter.len() as u32); out.extend_from_slice(&summary.use_filter); - // **The local type table**, last for the same reason the filter is: the decoder reads the sections in the - // order they were written. A fact's IDs are local to this table; `ProjectIndex::insert_at` imports the table - // and rewrites them, so a process-local handle is never written to disk. - put_type_table(&mut out, &summary.types); put_params_store(&mut out, &summary.parameters); out @@ -592,7 +607,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), @@ -604,8 +619,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( @@ -836,7 +851,6 @@ pub fn decode(bytes: &[u8]) -> Result { bytes }; - let types = get_type_table(&mut reader)?; 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, @@ -850,7 +864,6 @@ pub fn decode(bytes: &[u8]) -> Result { path, key, declarations, - types, parameters, macros, includes, @@ -1044,136 +1057,222 @@ fn decoded_record_tag(byte: u8) -> Option { } } -/// **The type table**, as a count-prefixed list of nodes. The IDs are the summary's local handles; they are -/// meaningful only beside this table and are rewritten when the summary is inserted into an index. -fn put_type_table(out: &mut Vec, table: &TypeTable) { - put_u32(out, table.entries.len() as u32); - for entry in &table.entries { - put_u32(out, entry.id); - put_opt_str(out, entry.spelling.as_deref()); - match &entry.kind { - EncodedTypeKind::Builtin(name) => { - put_u8(out, 0); - put_str(out, name); - } - EncodedTypeKind::Named { name, arguments } => { - put_u8(out, 1); - put_str(out, name); - put_u32(out, arguments.len() as u32); - for argument in arguments { - put_u32(out, *argument); - } - } - EncodedTypeKind::TemplateParameter(name) => { - put_u8(out, 2); - put_str(out, name); - } - EncodedTypeKind::Auto => put_u8(out, 3), - EncodedTypeKind::DecltypeAuto => put_u8(out, 4), - EncodedTypeKind::ElaboratedRecord { tag, of } => { - put_u8(out, 11); - put_u8(out, encoded_record_tag(*tag)); - put_u32(out, *of); - } - EncodedTypeKind::Pointer(to) => { - put_u8(out, 5); - put_u32(out, *to); - } - EncodedTypeKind::Reference { to, rvalue } => { - put_u8(out, 6); - put_u32(out, *to); - put_u8(out, u8::from(*rvalue)); - } - EncodedTypeKind::Array { of, extent } => { - put_u8(out, 7); - put_u32(out, *of); - put_u64(out, *extent); +/// **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); } - EncodedTypeKind::Function { - returns, - parameters, - } => { - put_u8(out, 8); - put_u32(out, *returns); - put_u32(out, parameters.len() as u32); - for parameter in parameters { - put_u32(out, *parameter); + } + 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); + match extent { + Some(extent) => { + put_u8(out, 1); + put_u64(out, *extent); } + None => put_u8(out, 0), } - EncodedTypeKind::Pack(of) => { - put_u8(out, 9); - put_u32(out, *of); - } - EncodedTypeKind::Qualified { - of, - is_const, - is_volatile, - } => { - put_u8(out, 10); - put_u32(out, *of); - put_u8(out, u8::from(*is_const)); - put_u8(out, u8::from(*is_volatile)); + } + 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)); + } } } -fn get_type_table(reader: &mut Reader<'_>) -> Result { - let count = reader.count()?; - let mut entries = Vec::with_capacity(count.min(64 * 1024)); - for _ in 0..count { - let id = reader.u32()?; - let spelling = reader.optional_string()?; - let kind = match reader.u8()? { - 0 => EncodedTypeKind::Builtin(reader.string()?), - 1 => { - let name = reader.string()?; - let count = reader.count()?; - let mut arguments = Vec::with_capacity(count.min(64 * 1024)); - for _ in 0..count { - arguments.push(reader.u32()?); - } - EncodedTypeKind::Named { name, arguments } +/// 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)?); } - 2 => EncodedTypeKind::TemplateParameter(reader.string()?), - 3 => EncodedTypeKind::Auto, - 4 => EncodedTypeKind::DecltypeAuto, - 5 => EncodedTypeKind::Pointer(reader.u32()?), - 6 => EncodedTypeKind::Reference { - to: reader.u32()?, - rvalue: reader.u8()? != 0, - }, - 7 => EncodedTypeKind::Array { - of: reader.u32()?, - extent: reader.u64()?, - }, - 8 => { - let returns = reader.u32()?; - let count = reader.count()?; - let mut parameters = Vec::with_capacity(count.min(64 * 1024)); - for _ in 0..count { - parameters.push(reader.u32()?); - } - EncodedTypeKind::Function { - returns, - parameters, - } + 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 => None, + 1 => Some(reader.u64()?), + _ => 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)?); } - 9 => EncodedTypeKind::Pack(reader.u32()?), - 10 => EncodedTypeKind::Qualified { - of: reader.u32()?, - is_const: reader.u8()? != 0, - is_volatile: reader.u8()? != 0, - }, - 11 => EncodedTypeKind::ElaboratedRecord { - tag: decoded_record_tag(reader.u8()?).ok_or(DecodeError::BadDiscriminant)?, - of: reader.u32()?, - }, - _ => return Err(DecodeError::BadDiscriminant), - }; - entries.push(EncodedType { id, spelling, kind }); - } - Ok(TypeTable { entries }) + 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: &[crate::index::params::ParameterFact]) { @@ -1195,16 +1294,9 @@ fn put_parameter_facts(out: &mut Vec, facts: &[crate::index::params::Paramet None => put_u8(out, 0), } put_u8(out, u8::from(fact.pack)); - // **Only a stored handle is written.** A parameter fact filed in a summary or a cooked reading holds - // `DeclaredType::Stored`; `Computed` is a query-synthesized value with no `TypeId` to invent, and `None` is - // the empty answer — both are the `NONE` sentinel on disk, which is also what an older reader expects here. - put_u32( - out, - fact.type_of - .stored_id() - .unwrap_or(TypeId::NONE) - .raw(), - ); + // **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); } } @@ -1235,8 +1327,7 @@ fn get_parameter_facts( _ => return Err(DecodeError::BadDiscriminant), }; let pack = reader.u8()? != 0; - // The on-disk form is the handle, or `NONE`; a record never carries a computed value (see `put_parameter_facts`). - let type_of = DeclaredType::from_stored(TypeId::from_raw(reader.u32()?)); + let type_of = get_declared_type(reader)?; facts.push(crate::index::params::ParameterFact { name, declaration, @@ -1470,19 +1561,22 @@ fn symbol_kind_code(kind: SymbolKind) -> u8 { #[cfg(test)] mod tests { + use std::sync::Arc; + use super::Access; use super::ModuleReading; use super::{CODEC_VERSION, DecodeError, MAGIC, decl_kind_code, decode, encode}; use crate::DeclModifiers; use crate::DirectiveKind; use crate::cache::SummaryKey; - use crate::index::types::{EncodedType, EncodedTypeKind, TypeId, TypeTable}; + use crate::index::types::{ComputedType, PrimaryType}; use crate::preprocess::directive::IncludeForm; use crate::summary; + use crate::summary::DeclaredType; use crate::summary::MacroKind; use crate::summary::{ - ConditionalRegion, DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, GuardBranch, - IncludeFact, MacroFact, MacroScopeReading, SummaryGuards, + ConditionalRegion, DeclFact, DeclKind, FactGuard, FileSummary, GuardBranch, IncludeFact, + MacroFact, MacroScopeReading, SummaryGuards, }; use cpp_parser::{MacroBody, SourceRange}; use smol_str::SmolStr; @@ -1491,6 +1585,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 { @@ -1501,41 +1600,6 @@ mod tests { // 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: crate::index::params::ParamsStore::default(), - types: TypeTable { - entries: vec![ - EncodedType { - id: 0, - spelling: Some("int".to_string()), - kind: EncodedTypeKind::Builtin("int".to_string()), - }, - EncodedType { - id: 1, - spelling: Some("std::pair".to_string()), - kind: EncodedTypeKind::Named { - name: "std::pair".to_string(), - arguments: vec![0, 0], - }, - }, - // **C's record tags, one of each keyword** — the new discriminant, and both of its tag bytes, so - // that the round trip covers the encoding rather than a sample of it. - EncodedType { - id: 2, - spelling: Some("struct point".to_string()), - kind: EncodedTypeKind::ElaboratedRecord { - tag: crate::sema::types::RecordTag::Struct, - of: 0, - }, - }, - EncodedType { - id: 3, - spelling: Some("union value".to_string()), - kind: EncodedTypeKind::ElaboratedRecord { - tag: crate::sema::types::RecordTag::Union, - of: 0, - }, - }, - ], - }, declarations: vec![ DeclFact { // **The flag at `true`**, on this of the three declarations, so the byte is covered at both ends — the @@ -1613,8 +1677,14 @@ mod tests { // 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: DeclaredType::None, - // The table's second node, so a fact's handle is part of what the round trip carries. - returns: DeclaredType::Stored(TypeId::from_raw(1)), + // 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: crate::index::params::ParamsId::NONE, // The `false` side of the list-level `...`, which the class above covers the other way round. variadic_parameters: false, @@ -1644,7 +1714,26 @@ mod tests { scope: None, kind: DeclKind::Other, modifiers: DeclModifiers::default(), - type_of: DeclaredType::None, + type_of: computed(ComputedType::Qualified(Arc::new( + crate::index::types::QualifiedType { + of: Arc::new(ComputedType::Pointer(Arc::new(ComputedType::named( + "std::vector", + vec![ + ComputedType::ElaboratedRecord { + tag: crate::sema::types::RecordTag::Union, + of: Arc::new(ComputedType::Named(SmolStr::new("value"))), + }, + ComputedType::Array { + of: Arc::new(ComputedType::Primary(PrimaryType::Int)), + extent: Some(4), + }, + ComputedType::TemplateParameter(SmolStr::new("T")), + ], + )))), + is_const: true, + is_volatile: false, + }, + ))), returns: DeclaredType::None, parameters: crate::index::params::ParamsId::NONE, // The third fact has no list at all, so the flag is `false` — the value a decoded fact from an @@ -1789,30 +1878,79 @@ mod tests { } #[test] - fn a_synthesized_type_is_not_persisted() { - // A `Computed` type has no handle into the record's type table, so the codec writes `NONE` for it — the same - // bytes an absent type writes. Decoding it back therefore answers `None`, and the fact keeps no - // `Stored(NONE)` in the process. - let mut original = every_field(); - original.declarations[1].type_of = DeclaredType::Computed(std::sync::Arc::new( - crate::index::types::ComputedType::Primary(crate::index::types::PrimaryType::Int), - )); - original.declarations[1].returns = DeclaredType::Computed(std::sync::Arc::new( - crate::index::types::ComputedType::Primary(crate::index::types::PrimaryType::Void), - )); - + 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].type_of, DeclaredType::None); - assert_eq!(decoded.declarations[1].returns, DeclaredType::None); assert_eq!( - decoded.declarations[1].type_of_id(), - None, - "a decoded fact never holds the `NONE` sentinel as a stored handle" + 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: crate::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: None, + }, + ComputedType::Function(Arc::new(crate::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(crate::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)); @@ -1933,10 +2071,10 @@ 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)); - // **One stored handle per type, and no spelling** — the record's type table carries every spelling, and a fact - // that was synthesized has no handle to write (`NONE`) because it carries its computed type in memory only. - put_u32(out, fact.type_of.stored_id().unwrap_or(TypeId::NONE).raw()); - put_u32(out, fact.returns.stored_id().unwrap_or(TypeId::NONE).raw()); + // **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. @@ -2018,15 +2156,6 @@ fn put_macro(out: &mut Vec, fact: &MacroFact) { put_u8(out, u8::from(fact.settles_the_name)); } -/// A fact's type as the codec can carry it: a stored handle, or [`DeclaredType::None`]. -/// -/// A synthesized type is **not persisted** — it belongs to the query that built the fact and has no `TypeId` — so -/// [`DeclaredType::Computed`] writes the same `NONE` an absent type does. Neither is the sentinel ever wrapped: a -/// decoded fact holds `Stored` only for a real handle, which keeps `Stored(NONE)` out of the vocabulary. -fn declared_type_from_raw(raw: u32) -> DeclaredType { - DeclaredType::from_stored(TypeId::from_raw(raw)) -} - /// Read one declaration fact — the reader half of [`put_declaration`]. fn get_declaration(reader: &mut Reader<'_>) -> Result { // **Read in the order the bytes are written, then assemble** — the rare fields are boxed as a group (see @@ -2034,8 +2163,8 @@ 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 = declared_type_from_raw(reader.u32()?); - let returns = declared_type_from_raw(reader.u32()?); + let type_of = get_declared_type(reader)?; + let returns = get_declared_type(reader)?; let parameters_id = crate::index::params::ParamsId::from_raw(reader.u32()?); let returns_in_the_class = reader.optional_string()?; let bases = get_strings(reader)?; @@ -2188,11 +2317,15 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// [`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`] +/// 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. -const COOKED_VERSION: u32 = 10; +/// +/// 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. +const COOKED_VERSION: u32 = 11; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -2261,10 +2394,6 @@ fn put_cooked_body(out: &mut Vec, reading: &CookedFile) { put_str(out, &diagnostic.message); } put_u32(out, reading.unplaced as u32); - // **The reading's local type table**, for the same reason a summary writes one: the facts hold handles, and - // `ProjectIndex::insert_cooked` imports this table into the index's one store. A reading with no types writes an - // empty table, which is what a decoded reading from a caller that built one by hand has too. - put_type_table(out, &reading.types); // **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 @@ -2352,13 +2481,10 @@ pub fn decode_the_cooked_record( }); } let unplaced = reader.u32()? as usize; - // The reading's local type table, written by [`put_cooked_body`] before the optional rendering, then its - // parameter table. - let types = get_type_table(&mut reader)?; + // 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, - types, parameters, macros, diagnostics, @@ -2454,35 +2580,19 @@ fn get_origin(reader: &mut Reader<'_>) -> Result Result { path, CookedFile { declarations: summary.declarations, - types: summary.types, parameters: summary.parameters, macros: summary.macros, diagnostics, unplaced, }, - )); } + )); + } let unplaced = reader.u32()? as usize; let tokens = reader.u32()? as usize; @@ -504,7 +504,6 @@ fn as_a_summary(path: &Path, cooked: &CookedFile) -> FileSummary { path: path.to_path_buf(), key: SummaryKey::new(0, 0), declarations: cooked.declarations.clone(), - types: cooked.types.clone(), parameters: cooked.parameters.clone(), macros: cooked.macros.clone(), includes: Vec::new(), @@ -529,7 +528,6 @@ mod index_tests { PathBuf::from("/p/a.h"), CookedFile { declarations: Vec::new(), - types: crate::index::types::TypeTable::default(), parameters: crate::index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: vec![CookedDiagnostic { diff --git a/crates/cpp_code_analysis/src/index/mod.rs b/crates/cpp_code_analysis/src/index/mod.rs index 76ef3405..fc3957e0 100644 --- a/crates/cpp_code_analysis/src/index/mod.rs +++ b/crates/cpp_code_analysis/src/index/mod.rs @@ -45,7 +45,6 @@ use crate::RenderedUnit; use crate::directive; use crate::guards; use crate::index::params::ParamsStore; -use crate::index::types::{TypeId, TypeTable}; use crate::preprocess; use crate::sema; use crate::summary; @@ -690,7 +689,6 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { file_what_was_found( summary.declarations, - &summary.types, &tree, stream, &mut files, @@ -835,10 +833,6 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { let mut declarations = built.facts; let mut guards = built.guards; let parameters = built.parameters; - let parameter_types = built.types; - let parameter_type_ids: Vec<_> = - (0..parameter_types.len()).map(TypeId::from_index).collect(); - 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); @@ -969,7 +963,6 @@ impl<'a, F: FileProvider> FileIndexer<'a, F> { path: path.to_path_buf(), key, declarations, - types: parameter_types.export(parameter_type_ids), parameters, macros, includes, @@ -1105,7 +1098,6 @@ 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(), - types: TypeTable::default(), parameters: ParamsStore::default(), macros, includes, @@ -1655,7 +1647,6 @@ fn is_one_parenthesised_group(tokens: &[cpp_parser::CppTokenKind]) -> bool { /// gone there is one parse of one stream, and every fact from it belongs to the file the fact was written in. fn file_what_was_found( declarations: Vec, - types: &TypeTable, tree: &CppSyntaxTree, stream: &RenderedUnit, files: &mut [(PathBuf, CookedFile)], @@ -1690,21 +1681,6 @@ fn file_what_was_found( } } - // **Each file's own slice of the unit's type table.** A declaration's handle indexes the *unit's* local table, - // because every file was read by the one parse; the table travels with the reading so that - // `ProjectIndex::insert_cooked` can rewrite the handles once, at the insertion edge (`CookedFile::types`). A - // per-file export keeps one header's record from carrying every other file's types, and `TypeTable::export` - // pulls in each node's children, so a fact's handle is resolvable from its own file's table alone. - for (_, cooked) in files.iter_mut() { - let ids: Vec<_> = cooked - .declarations - .iter() - .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) - .flatten() - .collect(); - cooked.types = types.export(ids); - } - // **A stream's parse error is the program's, not a file's — so it is counted, not placed.** // // The loop that stood here asked `stream.written_span(range)` and pushed the answer into the file the error's diff --git a/crates/cpp_code_analysis/src/index/params.rs b/crates/cpp_code_analysis/src/index/params.rs index 125f826e..94302533 100644 --- a/crates/cpp_code_analysis/src/index/params.rs +++ b/crates/cpp_code_analysis/src/index/params.rs @@ -12,13 +12,10 @@ //! [`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 enum a [`DeclFact`](crate::summary::DeclFact)'s own types use.** A -//! parameter a summary or a cooked reading filed holds [`DeclaredType::Stored`] — a handle into the one global -//! [`TypeStore`](crate::index::types::TypeStore), lowered from the parameter's own `CppParam` node by -//! [`crate::sema::declarations`] at construction. A parameter fact a query synthesized from a view has no arena to -//! intern into, so it holds [`DeclaredType::Computed`], the value the builder already has. There is **no spelling -//! field**: [`crate::ProjectIndex::parameter_type`] resolves either kind to a -//! [`ComputedType`](crate::index::types::ComputedType), and nothing re-parses a type on the way. +//! **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; @@ -27,7 +24,6 @@ use cpp_parser::CppSyntaxId; use cpp_parser::CppTokenKind; use smol_str::SmolStr; -use super::types::TypeId; use crate::cache::summary::DeclaredType; use rustc_hash::FxHashMap; use std::mem::size_of; @@ -138,28 +134,7 @@ impl ParamsStore { store } - /// **Rewrite the parameter type handles after a summary's type table is imported.** The keys are the local - /// `TypeId` values the summary was encoded with. - /// - /// Only [`DeclaredType::Stored`] moves: a view fact's [`DeclaredType::Computed`] names no arena, and - /// [`DeclaredType::None`] is not a handle at all. - pub fn remap_types(&mut self, mapping: &FxHashMap) { - for facts in &mut self.entries { - for fact in facts.iter_mut() { - if let DeclaredType::Stored(id) = fact.type_of - && let Some(store_id) = mapping.get(&id.raw()) - { - fact.type_of = DeclaredType::Stored(*store_id); - } - } - } - } - /// **Import another store's local handles**, deduplicating against this one. - /// - /// A [`DeclaredType::Stored`] handle travels as it is: it is valid only after the type table it names has been - /// imported into the one global store, which is [`ParamsStore::remap_types`]'s job and happens at the same edge - /// that imports a summary's or a reading's types. pub fn import(&mut self, from: &ParamsStore) -> FxHashMap { let mut mapping = FxHashMap::default(); for (at, facts) in from.entries.iter().enumerate() { @@ -194,9 +169,10 @@ fn fact_of(parameter: CppParam) -> ParameterFact { .descendants_with_tokens() .filter_map(|element| element.into_token()) .any(|token| CppTokenKind::from(token.kind()) == CppTokenKind::Ellipsis), - // **No type yet.** Lowering it needs a `TypeStore` (or the computation layer, for a view), so the two - // builders that own one fill this in — see `crate::sema::declarations::fact_for` and - // `crate::index::project::fact_from_binding_with`. This reader is the CST half only. + // **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, } } @@ -288,9 +264,9 @@ mod tests { ); assert_eq!(facts[2].name.as_deref(), Some("rest")); assert!(facts[2].pack); - // **The CST reader states no type** — lowering needs a store (or the computation layer, for a view), and both - // builders that own one 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. + // **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); } diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 45aa015f..97d17145 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -256,7 +256,7 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { /// [`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`, because a view path has no store to intern into and inventing a `TypeId` from a +/// 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. /// @@ -327,42 +327,46 @@ pub(crate) fn fact_from_binding_with( binding: &Binding, ) -> SynthesizedFact { let _ = root; - // **The two types this path can state, and the one place their spellings exist.** This builder has no - // `TypeStore` — it runs on the query side, against a buffer — so it converts the written spelling **once** into - // the computation layer and stores the value on the fact. No second store is minted, no `TypeId` is invented, and - // no consumer parses the spelling again. - 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, - ) - }); + // **The two types this path can state, lowered structurally once.** The readers below answer a + // [`crate::sema::types::Type`] 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 computed = |written: Option| { + let template_parameters = + sema::declarations::declared_template_parameters_with(shapes, binding); + let lower = |written: Option| { written.map_or(DeclaredType::None, |written| { - let parsed = parse_type_spelling(&written); - let parsed = sema::types::without_placeholders_written_as_names(parsed); - let parsed = sema::types::with_template_parameters(parsed, &template_parameters); - DeclaredType::Computed(Arc::new(ComputedType::from(&parsed))) + let written = sema::types::with_template_parameters(written, &template_parameters); + DeclaredType::Computed(Arc::new(ComputedType::from(&written))) }) }; - let type_of = computed(written_type_of); - let returns = computed(written_returns.clone()); + 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 `TypeId` is invented and no spelling is parsed. + // [`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: @@ -378,8 +382,7 @@ pub(crate) fn fact_from_binding_with( && 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(ComputedType::from(&written))); + parameter.type_of = DeclaredType::Computed(Arc::new(ComputedType::from(&written))); } } parameters.into_boxed_slice() @@ -454,7 +457,7 @@ 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: { - if written_returns.is_some() { + if returns_written { None } else { sema::declarations::the_returns_the_class_has_to_resolve(shapes, root, binding) @@ -472,7 +475,11 @@ 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: template_parameters.iter().cloned().map(SmolStr::from).collect(), + parameters: template_parameters + .iter() + .cloned() + .map(SmolStr::from) + .collect(), constraints: 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. 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 bd13ae00..7f8af514 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -379,16 +379,12 @@ impl ProjectIndex { } } - /// **The interned types this index has built.** Append-only with the index; a summary's string fields remain - /// the transition source until the codec carries a local type table. - pub fn types(&self) -> &TypeStore { - &self.types - } - - /// **The index-wide parameter arena**, append-only like [`ProjectIndex::types`]. 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. + /// **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 } @@ -465,7 +461,9 @@ impl ProjectIndex { summary .declarations .iter() - .find(|candidate| candidate.name == fact.name && candidate.name_range == fact.name_range) + .find(|candidate| { + candidate.name == fact.name && candidate.name_range == fact.name_range + }) .map_or(&[], |candidate| summary.parameter_facts(candidate)) } @@ -943,7 +941,7 @@ impl ProjectIndex { /// **[`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 and no `TypeId` is interned. + /// is parsed. pub fn member_computed_type(&self, member: &ProjectMember) -> Option { let fact = self.member_fact(member)?; let base = self.computed_type_of(fact)?; @@ -974,7 +972,7 @@ impl ProjectIndex { /// /// **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 `TypeId` is minted and no + /// 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)?; @@ -982,6 +980,9 @@ impl ProjectIndex { return Some(fact.clone()); } let mut shown = fact.clone(); + if shown.name == "second" { + eprintln!("[display] sub={:?} base={:?}", member.substitution, fact.type_of); + } shown.type_of = self .member_computed_type(member) .map_or(DeclaredType::None, |computed| { @@ -1067,70 +1068,43 @@ impl ProjectIndex { &[] } - /// **The written type spelling of a fact**, for a display consumer — an owned string produced at this edge. + /// **The canonical display spelling of a fact's type**, for a display consumer — an owned string produced at + /// this edge. /// - /// A synthesized fact answers its `ComputedType` printed; a stored fact answers the spelling the store recorded - /// for its handle (the file's own words), because that is the display form a reader is owed. If the store has a - /// node with no recorded spelling — a node a substitution synthesized — the materialized value is printed instead. - /// **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`]. + /// [`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 { - if let Some(computed) = fact.type_of.computed() { - return Some(smol_str::SmolStr::new(computed.to_string())); - } - let id = fact.type_of.stored_id()?; - let spelled = self - .types - .spelling(id) - .map(smol_str::SmolStr::new) - .or_else(|| { - self.types - .materialize(id) - .map(|computed| smol_str::SmolStr::new(computed.to_string())) - })?; - Some(spelled) + fact.type_of + .computed() + .map(|computed| smol_str::SmolStr::new(computed.to_string())) } - /// The written return spelling of a fact, by the same rule as [`ProjectIndex::type_spelling_of`]. + /// 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 { - if let Some(computed) = fact.returns.computed() { - return Some(smol_str::SmolStr::new(computed.to_string())); - } - let id = fact.returns.stored_id()?; - let spelled = self - .types - .spelling(id) - .map(smol_str::SmolStr::new) - .or_else(|| { - self.types - .materialize(id) - .map(|computed| smol_str::SmolStr::new(computed.to_string())) - })?; - Some(spelled) + fact.returns + .computed() + .map(|computed| smol_str::SmolStr::new(computed.to_string())) } - /// **The computation-side type of a declaration's `type_of`.** A synthesized fact carries its value directly; - /// an ordinary fact's handle is materialized from the one global store. Neither path interns anything. + /// **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(&self.types) + 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(&self.types) + fact.returns.as_computed() } - /// **One parameter's type as computation sees it.** A summary's or a cooked reading's parameter holds - /// [`DeclaredType::Stored`] and is materialized from the one global store; a view-synthesized parameter holds - /// [`DeclaredType::Computed`] and is cloned. Neither path interns anything, 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(&self.types) + /// **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 @@ -1143,100 +1117,14 @@ impl ProjectIndex { .collect() } - /// **The spelling of one parameter's type**, for the display edge — a message quotes it, and **nothing parses - /// it**. A synthesized parameter prints its computed value; a stored one answers the spelling the store recorded - /// (the file's own words, C's tag included). Every computation consumer asks [`ProjectIndex::parameter_type`], - /// whose `ComputedType` carries the tag structurally. - pub fn parameter_spelling( - &self, - parameter: &ParameterFact, - ) -> Option { - if let Some(computed) = parameter.type_of.computed() { - return Some(smol_str::SmolStr::new(computed.to_string())); - } - let id = parameter.type_of.stored_id()?; - self.types - .spelling(id) - .map(smol_str::SmolStr::new) - .or_else(|| { - self.types - .materialize(id) - .map(|computed| smol_str::SmolStr::new(computed.to_string())) - }) - } - - /// **Import every type a summary carries into the index's one store**, once, before the summary is filed. - /// - /// A summary built from syntax carries a local `TypeTable` — the IDs its facts hold are indices into that table, - /// not into this store. Importing rewrites them to this store's IDs, so a stored fact's handle can be resolved by - /// [`ProjectIndex::computed_type_of`] with no second store and no spelling in between. The summary's parameter - /// table holds handles into the same table, so [`ParamsStore::remap_types`] is the other half of the same step — - /// and it is the only half now that a declaration no longer carries parameter facts of its own. A summary read - /// back from the cache takes the same path; a synthesized fact carries no ID and is untouched. - fn intern_the_types_of(&mut self, summary: &mut FileSummary) { - if !summary.types.is_empty() { - let mapping = self.types.import(&summary.types); - summary.parameters.remap_types(&mapping); - for fact in &mut summary.declarations { - if let DeclaredType::Stored(id) = &mut fact.type_of - && let Some(store_id) = mapping.get(&(id.index() as u32)) - { - *id = *store_id; - } - if let DeclaredType::Stored(id) = &mut fact.returns - && let Some(store_id) = mapping.get(&(id.index() as u32)) - { - *id = *store_id; - } - } - } - let ids: Vec<_> = summary - .declarations - .iter() - .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) - .flatten() - .collect(); - summary.types = self.types.export(ids); - } - - /// **Import a cooked reading's types into the index's one store**, rewriting the facts' local IDs to store IDs. - /// - /// A cooked reading is built from a syntax pass of a whole translation unit, so its facts carry indices into - /// that pass's `TypeTable` exactly as a summary's do. The table travels with the reading (in memory and in the - /// cache record) and is imported here, at the moment the reading is filed — the same edge that binds a - /// summary's handles, so there is still one store that ever resolves a stored [`TypeId`]. - fn intern_the_types_of_a_reading(&mut self, reading: &mut CookedFile) { - if !reading.types.is_empty() { - let mapping = self.types.import(&reading.types); - // **The parameter table's handles are local to the same table**, so they are rewritten by the same - // mapping the declarations' handles are. Doing it here is what lets a cooked fact's `ParamsId` resolve - // against its own reading later (see [`ProjectIndex::parameter_facts_of`]). - reading.parameters.remap_types(&mapping); - for fact in &mut reading.declarations { - if let DeclaredType::Stored(id) = &mut fact.type_of - && let Some(store_id) = mapping.get(&(id.index() as u32)) - { - *id = *store_id; - } - if let DeclaredType::Stored(id) = &mut fact.returns - && let Some(store_id) = mapping.get(&(id.index() as u32)) - { - *id = *store_id; - } - } - } - // **The reading's table is rewritten alongside the handles**, exactly as a summary's is. Without this the - // stored reading would hold store handles beside a table in another ID space: harmless while nothing encoded - // it, but `Session::persist_cooked` writes the *live* reading, and the next session would decode that pair and - // resolve every handle through the wrong nodes. A re-import of this store-ID table is a no-op (hash-consing - // answers the same IDs), so a reading that is filed twice keeps meaning the same types. - let ids: Vec<_> = reading - .declarations - .iter() - .flat_map(|fact| [fact.type_of.stored_id(), fact.returns.stored_id()]) - .flatten() - .collect(); - reading.types = self.types.export(ids); + /// **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. @@ -1303,7 +1191,6 @@ impl ProjectIndex { self.forget_macro_walks(path, known_to_the_index); let mut summary = summary; summary.path = path.to_path_buf(); - self.intern_the_types_of(&mut summary); let path = normalize(path); @@ -1684,12 +1571,11 @@ impl ProjectIndex { &mut self, path: &Path, program: Option, - mut reading: CookedFile, + 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. - self.intern_the_types_of_a_reading(&mut reading); // **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 @@ -2016,7 +1902,10 @@ impl ProjectIndex { .map(|member| { size_of::() + member.declared_in.len() - + member.substitution.as_ref().map_or(0, |held| held.heap_bytes()) + + member + .substitution + .as_ref() + .map_or(0, |held| held.heap_bytes()) }) .sum(); let unlisted = held.list.unlisted.len() * size_of::(); 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 773fd05c..59723b8d 100644 --- a/crates/cpp_code_analysis/src/index/project/member_facts.rs +++ b/crates/cpp_code_analysis/src/index/project/member_facts.rs @@ -892,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, diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index eb08c640..f5072de4 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -32,7 +32,6 @@ //! **guarded** include is reported as [`Known::Unknown`] rather than as visible or invisible — the same rule the //! rest of the crate follows, and the reason [`IncludeFact`](crate::summary::IncludeFact) carries a guard at all. -use super::types::TypeStore; use crate::CookedDiagnostic; use crate::IndexedRendering; use cpp_parser::SourceRange; @@ -109,19 +108,11 @@ 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 local type table the declarations' handles index**, imported into the index's one global - /// [`crate::index::types::TypeStore`] when the reading is filed — see - /// [`crate::ProjectIndex::insert_cooked`]. - /// - /// The same contract a [`crate::FileSummary`]'s table has: a fact holds a local [`TypeId`], and the table travels - /// with it so the ID can be rewritten once at insertion. A reading built by hand (a test, a caller with facts and - /// no parse) leaves it empty and uses the facts' synthetic computed types instead. - pub types: crate::index::types::TypeTable, - /// **The reading's local parameter table**, indexed by [`DeclFact::parameters`] — the same contract - /// [`CookedFile::types`] 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 and remaps this - /// table once, exactly as it does the type table. + /// **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 @@ -160,7 +151,6 @@ impl CookedFile { pub fn declarations(declarations: Vec) -> Self { CookedFile { declarations, - types: crate::index::types::TypeTable::default(), parameters: crate::index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: Vec::new(), @@ -176,7 +166,6 @@ impl CookedFile { .iter() .map(DeclFact::heap_bytes) .sum::() - + self.types.heap_bytes() + self.parameters.accounting() + self.macros.iter().map(MacroFact::heap_bytes).sum::() + self.diagnostics.len() * size_of::() @@ -184,7 +173,7 @@ impl CookedFile { } impl From for CookedFile { - /// What the index keeps of a rendering's reading: the declarations, **the type table their handles index**, the + /// 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 @@ -194,7 +183,6 @@ impl From for CookedFile { fn from(indexed: IndexedRendering) -> Self { CookedFile { declarations: indexed.summary.declarations, - types: indexed.summary.types, parameters: indexed.summary.parameters, macros: indexed.summary.macros, diagnostics: indexed.diagnostics, @@ -473,8 +461,6 @@ 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 types of every declaration this index has inserted. - types: TypeStore, /// The interned parameter lists of every declaration this index has inserted. parameters: crate::index::params::ParamsStore, /// **What the cooked reading found**, by normalized path — the declarations a compiler sees, and the errors the diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 9a71a4d2..405ee00b 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -282,12 +282,12 @@ fn member_row(fact: super::FactRef) -> ProjectMember { } } -/// **The index interns a summary's type spellings once**, and two declarations of one type share the handle. +/// **A summary's fact carries its type as a value**, so inserting it needs no type store and no handle rewrite. /// -/// The string fields are still the source a query may read during the transition; this test pins the store's side -/// of the contract: insert fills `type_of`, and `int` is one node rather than one per declaration. +/// 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 the_index_interns_the_types_a_summary_declares_once() { +fn a_summary_stores_each_declaration_type_as_a_value() { let mut index = ProjectIndex::new(); let summary = summarize( Path::new("/p/a.cpp"), @@ -297,33 +297,26 @@ fn the_index_interns_the_types_a_summary_declares_once() { index.insert(summary); let stored = index.summary(Path::new("/p/a.cpp")).expect("inserted"); - let ids: Vec<_> = stored + let types: Vec<_> = stored .declarations .iter() - .filter_map(|fact| fact.type_of_id()) + .filter_map(|fact| fact.type_of.computed().map(|computed| computed.to_string())) .collect(); assert_eq!( - ids.len(), + types.len(), 3, - "every declaration with a written type got a handle" - ); - assert_eq!(ids[0], ids[1], "`int` is one interned type"); - assert_ne!(ids[0], ids[2], "`double` is another"); - assert_eq!(index.types().len(), 2, "int and double, once each"); - assert_eq!( - index - .types() - .type_ref(ids[0]) - .expect("the handle belongs to the store") - .display(), - "int" + "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 summary's local type table is imported, not trusted.** Encode/decode a real inserted summary, then insert the -/// decoded copy into a fresh index: the IDs are rewritten to the new store and the display survives. +/// **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_remaps_its_type_ids_on_insert() { +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(); @@ -338,10 +331,11 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { .expect("the vector"); assert_eq!( restored - .type_of_id() - .and_then(|id| decoded.types.spelling_for(id.raw())), - Some("std::vector"), - "the decoder restores the spelling from the type table through the fact's handle" + .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(); @@ -351,15 +345,13 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { .declarations .iter() .find(|fact| fact.name == "items") - .and_then(|fact| fact.type_of_id()) - .expect("the vector declaration kept a type"); + .expect("the vector declaration"); assert_eq!( - second - .types() - .type_ref(vector) - .expect("the imported handle") - .display(), - "std::vector" + vector + .type_of + .computed() + .map(|computed| computed.to_string()), + Some("std::vector".to_string()) ); let function = stored .declarations @@ -375,7 +367,7 @@ fn a_cached_summary_remaps_its_type_ids_on_insert() { } #[test] -fn a_function_detail_interns_its_parameter_types() { +fn a_function_detail_stores_its_parameter_types() { let path = Path::new("/p/params.cpp"); let mut index = ProjectIndex::new(); index.insert(summarize( @@ -432,11 +424,9 @@ fn a_function_detail_interns_its_parameter_types() { assert_eq!(types[1].to_string(), "const char*"); } -/// **A repeated type is one node, not one per declaration.** This is the memory contract of the store: a header -/// with a hundred `std::vector` members must not carry a hundred type records. The check is on the store and on -/// the summary's exported table, because both are counted by the memory report. +/// **A repeated type is the same value on every fact**, and no table or intern count stands behind it. #[test] -fn repeated_declarations_share_one_type_node() { +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")) @@ -445,19 +435,18 @@ fn repeated_declarations_share_one_type_node() { index.insert(summarize(path, &source, SummaryKey::new(0, 0))); let stored = index.summary(path).expect("inserted"); assert_eq!(stored.declarations.len(), 100); - assert_eq!( - index.types().len(), - 2, - "`std::vector` and `int`, once each" - ); - assert_eq!( - stored.types.entries.len(), - 2, - "the exported table is deduplicated too" + 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" ); - let accounting = index.types().accounting(); - assert!(accounting.types >= 2); - assert!(accounting.bytes > 0); } #[test] @@ -1696,9 +1685,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(); @@ -1708,8 +1697,8 @@ fn a_function_pointer_typedef_records_the_whole_type() { }; assert_eq!( index.type_spelling_of(the_fact(&index, &fact)).as_deref(), - Some("void (*)(int)"), - "specifiers plus declarator minus the name" + 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. @@ -2415,7 +2404,9 @@ impl ResolvedList { } fn at_depth(&self, depth: usize) -> impl Iterator { - self.members.iter().filter(move |member| member.depth == depth) + self.members + .iter() + .filter(move |member| member.depth == depth) } } @@ -4738,7 +4729,9 @@ fn a_view_facts_parameters_resolve_through_the_synthetic_arena() { .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"); + let fact = index + .member_fact(member) + .expect("the row names an arena entry"); assert_eq!( fact.parameters, crate::index::params::ParamsId::NONE, 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 ecccc9e0..52a04bf0 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -939,6 +939,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, @@ -2493,10 +2501,7 @@ fn a_member_with_that_arity( // **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(), - )) + Some((index.member_display_fact(found)?, found.declared_in.clone())) } /// **What a member whose return type is `auto` returns**, read from its body. @@ -3102,9 +3107,9 @@ impl NamedDeclaration { sema::declarations::shapes_from(shapes, root), binding, ) - .filter(|returns| !is_a_placeholder(returns)) + .filter(|returns| !ComputedType::from(returns).is_a_placeholder()) { - Some(returns) => parse_type_spelling(&returns), + Some(returns) => returns, None => { let substitutions = sema::types::TypeSubstitutions::new( &names_for_the_call, @@ -3210,6 +3215,7 @@ 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 { @@ -3631,9 +3637,7 @@ pub(crate) fn a_trait_alias_resolved( .get(at) .map(|default| default.trim()) .filter(|default| !default.is_empty() && *default != parameter.as_str()) - .map(|default| { - sema::types::substituted_spelling(default, ¶meters, &arguments) - }); + .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()), diff --git a/crates/cpp_code_analysis/src/index/store.rs b/crates/cpp_code_analysis/src/index/store.rs index a9453606..6b6edf3e 100644 --- a/crates/cpp_code_analysis/src/index/store.rs +++ b/crates/cpp_code_analysis/src/index/store.rs @@ -1297,9 +1297,6 @@ 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(), - // **The same local table the summary holds.** Both records index the same handles; each is imported into - // the index's one store at its own insertion edge, and hash-consing makes the two imports agree. - types: indexed.summary.types.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(), diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 4c1a6f3f..8d9fabbf 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -1,31 +1,29 @@ -//! **The computed type** — what a query works on, separate from the index's compact storage. +//! **The computed type** — the immutable value a fact carries and a query works on. //! -//! [`TypeStore`](super::TypeStore) is append-only and written only by the indexing side. A query must not intern a -//! temporary type into it: that would put a write lock on the path every hover, completion and inlay request takes, -//! and the whole point of the read side is that many readers can run at once. -//! -//! So a fact stores a [`TypeId`](super::TypeId), and a query materializes the small amount it needs into this type: +//! 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 -//! storage computation -//! TypeKind, 16 bytes ComputedType, 32 bytes -//! IDs, arena-owned names SmolStr names, Arc children -//! immutable after indexing owned by the request / SemanticModel +//! 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. The store still keeps the written spelling for display; the mapping happens once, at the storage boundary. +//! 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` is a -//! small copy from the store's name table; a long name shares its `Arc` with the store. The result is cheap to -//! build and cheap to clone, and it owns no borrow of the index. +//! 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::sync::Arc; diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 817751d5..9acd5b25 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -1,1207 +1,19 @@ -//! **Types as the index stores them**: a hash-consed graph of handles, not a spelling per declaration. +//! **Types as the index stores them** — as values, not as handles into an arena. //! -//! [`sema::types::Type`](crate::sema::types::Type) is the parser-facing shape. This module is the *storage* shape: -//! the same information, but shared through an append-only store, so a declaration can hold an eight-byte -//! `Option` instead of a 24-byte `SmolStr` that every consumer has to parse again. +//! 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 -//! one source spelling -> TypeStore -> TypeId -//! std::vector one node, one name, one ID 0x0000_0017 -//! std::vector the same node and ID 0x0000_0017 +//! a declaration's syntax -> Type (the parser's shape) -> ComputedType (the value a fact carries) //! ``` //! -//! # What is shared, and what is not +//! There is no `TypeId`, no interning and no source-spelling side table. 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. //! -//! [`TypeId`] is a **process-local handle**, not a durable identifier. A summary that is written to disk keeps its -//! own local type table; importing that summary into a store rewrites the local IDs to store IDs. The design and -//! the migration order are in `docs/type-system-redesign.md`. -//! -//! The store interns the *shape* and the *source spelling*. It deliberately does not resolve aliases or instantiate -//! templates: those are index queries, and doing them here would make the cache depend on the whole project while -//! it is still being built. - -use std::fmt; - -use rustc_hash::FxHashMap; -use smol_str::SmolStr; - -use crate::sema::types::{RecordTag, Type}; +//! The design and the migration order are in `docs/type-system-redesign.md`. pub mod compute; pub use compute::{ComputedType, FunctionType, GenericType, PrimaryType, QualifiedType}; - -/// A handle to one node in a [`TypeStore`]. -/// -/// Four bytes, `Copy`, and meaningful only with the store that produced it. A [`TypeRef`] keeps the two together. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct TypeId(u32); - -impl TypeId { - /// The sentinel a fact uses for "no type". Zero is a valid node, so the reserved value is the top of the - /// `u32` range and a store never hands it out. - pub const NONE: TypeId = TypeId(u32::MAX); - - /// The index into the store's node vector. Public for diagnostics and tests; consumers should prefer - /// [`TypeRef`]. - pub fn index(self) -> usize { - self.0 as usize - } - - /// The raw value, for a codec that writes it beside the summary's type table. - pub fn raw(self) -> u32 { - self.0 - } - - /// A value read back from a codec; `u32::MAX` is [`TypeId::NONE`]. - pub fn from_raw(raw: u32) -> TypeId { - TypeId(raw) - } - - /// The handle for the `index`th node, used by a decoder that is rebuilding a store. - pub fn from_index(index: usize) -> TypeId { - assert!( - index < u32::MAX as usize, - "a type store with more than u32::MAX - 1 nodes" - ); - TypeId(u32::try_from(index).expect("a type index that fits in u32")) - } - - /// Is this the sentinel rather than a node? - pub fn is_none(self) -> bool { - self == TypeId::NONE - } -} - -impl fmt::Display for TypeId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "#{}", self.0) - } -} - -/// A handle to one interned spelling in a [`TypeStore`]. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct NameId(u32); - -impl NameId { - pub fn index(self) -> usize { - self.0 as usize - } - - pub fn from_index(index: usize) -> NameId { - NameId(u32::try_from(index).expect("a name store with more than u32::MAX names")) - } -} - -/// A handle to one interned argument list. Keeping the list out of [`TypeKind`] is what makes a named type fit in -/// eight payload bytes — see the size assertion in the tests. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct ArgsId(u32); - -impl ArgsId { - /// The empty list, which every argument-free type shares. - pub const EMPTY: ArgsId = ArgsId(u32::MAX); - - pub fn index(self) -> Option { - (self != ArgsId::EMPTY).then_some(self.0 as usize) - } - - pub fn from_index(index: usize) -> ArgsId { - assert!( - index < u32::MAX as usize, - "more argument lists than u32 can hold" - ); - ArgsId(index as u32) - } -} - -/// **The structural shape of one type.** The spelling lives on [`TypeNode`], because the same shape may have been -/// written two ways and a reader is owed the one in their file. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub enum TypeKind { - /// `int`, `unsigned long long`, `bool` — the spelling is the name ID. - Builtin(NameId), - /// `Widget`, `std::vector`, `T` before the context says it is a parameter. - Named { - name: NameId, - arguments: ArgsId, - }, - /// `T` inside a template body. - TemplateParameter(NameId), - /// `auto` as a placeholder. Deduced types are interned as their result, not as this. - Auto, - /// `decltype(auto)`, which is a placeholder with different deduction rules from `auto`. - DecltypeAuto, - /// **A C record written with its tag** — `struct point`, `union value`. The tag is what tells a record's name - /// from a `typedef` of something else; see [`crate::sema::types::RecordTag`]. - ElaboratedRecord { - tag: RecordTag, - of: TypeId, - }, - Pointer(TypeId), - Reference { - to: TypeId, - /// `&&` rather than `&`; a forwarding reference is a deduction question, not a display detail. - rvalue: bool, - }, - Array { - of: TypeId, - /// The extent, or [`UNKNOWN_EXTENT`] for `int[]`. A sentinel rather than `Option` keeps this variant - /// inside the same eight payload bytes as the others. - extent: u64, - }, - Function { - returns: TypeId, - parameters: ArgsId, - }, - Pack(TypeId), - Qualified { - of: TypeId, - qualifiers: crate::sema::types::Qualifiers, - }, -} - -/// The extent written for `int[]`, and the value [`TypeKind::Array`] uses when the source wrote no bound. -pub const UNKNOWN_EXTENT: u64 = u64::MAX; - -/// One node: the shape of the type. The spelling is a parallel table in [`TypeStore`], so this stays 16 bytes. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct TypeNode { - pub kind: TypeKind, -} - -/// The interning key. Two nodes with the same shape **and** the same spelling are one node; two spellings of one -/// structural type stay distinct so a hover can show what the file wrote. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -struct TypeKey { - kind: TypeKind, - spelling: Option, -} - -/// **An append-only name table.** `NameId` is four bytes and a lookup is one hash; the strings live here once. -/// -/// The table is deliberately small: no removal, no refcount, no generation. A `TypeStore` is rebuilt with the index -/// generation it belongs to, and a summary's names are imported into it once. -#[derive(Debug, Default)] -pub struct NameInterner { - names: Vec, - ids: FxHashMap, -} - -impl NameInterner { - pub fn intern(&mut self, spelling: &str) -> NameId { - if let Some(id) = self.ids.get(spelling) { - return *id; - } - let id = NameId::from_index(self.names.len()); - let name = SmolStr::new(spelling); - self.names.push(name.clone()); - self.ids.insert(name, id); - id - } - - pub fn name(&self, id: NameId) -> Option<&str> { - self.names.get(id.index()).map(|name| &**name) - } - - /// A `SmolStr` copy for a computed type: short names are inline, long names share the `Arc`. - pub fn smol(&self, id: NameId) -> Option { - self.name(id).map(SmolStr::new) - } - - pub fn len(&self) -> usize { - self.names.len() - } - - pub fn is_empty(&self) -> bool { - self.names.is_empty() - } -} - -/// **The type graph of one index generation**, hash-consed and append-only. -#[derive(Debug, Default)] -pub struct TypeStore { - nodes: Vec, - spellings: Vec>, - arguments: Vec>, - argument_ids: FxHashMap, ArgsId>, - interned: FxHashMap, - names: NameInterner, -} - -impl TypeStore { - pub fn new() -> TypeStore { - TypeStore::default() - } - - /// The number of distinct types interned so far. - pub fn len(&self) -> usize { - self.nodes.len() - } - - pub fn is_empty(&self) -> bool { - self.nodes.is_empty() - } - - /// The name table, for a consumer that has to print a `name` field or build a new node. - pub fn names(&self) -> &NameInterner { - &self.names - } - - /// The name table, mutably — the entry point for a decoder or a synthetic node. - pub fn names_mut(&mut self) -> &mut NameInterner { - &mut self.names - } - - /// **Intern one already-structured node.** `spelling` is the source spelling when there is one; `None` asks - /// [`TypeRef::display`] to reconstruct it. - pub fn intern(&mut self, kind: TypeKind, spelling: Option<&str>) -> TypeId { - let spelling = spelling.map(|spelling| self.names.intern(spelling)); - let key = TypeKey { - kind: kind.clone(), - spelling, - }; - if let Some(id) = self.interned.get(&key) { - return *id; - } - let id = TypeId::from_index(self.nodes.len()); - self.nodes.push(TypeNode { kind }); - self.spellings.push(spelling); - self.interned.insert(key, id); - id - } - - /// **Convert the parser's type into the store.** Every child is interned first, so the graph is a DAG rather - /// than a tree with repeated spellings. - pub fn intern_type(&mut self, written: &Type) -> TypeId { - self.intern_type_written_as(written, None) - } - - /// [`TypeStore::intern_type`] with **the source spelling kept as the node's display spelling**. - /// - /// A file writes `const char *` and a hover is owed those characters; rendering the parsed shape instead answers - /// `const char*`. The structure is the same either way, and only the top node's spelling is kept — children are - /// reached from the source spelling when it is printed, so the canonical spelling of each child is what a - /// synthesized child would show anyway. - /// - /// `source` is a **spelling, never a parse**: a construction edge that already has the structured [`Type`] — a - /// parameter read from its own `CppParam`, for instance — passes the written form it printed from the same node so - /// that a display consumer quotes the file, while computation reads the structure. No consumer below this edge - /// parses the spelling back. - pub fn intern_type_written_as(&mut self, written: &Type, source: Option<&str>) -> TypeId { - let spelling = source.map_or_else(|| written.to_string(), str::to_string); - let kind = match written { - // **The placeholders are storage kinds of their own** — the computation layer folds them back into - // [`PrimaryType::Auto`]/[`PrimaryType::DecltypeAuto`]. The one spelling-to-primary table lives in - // `compute`; this is a construction-edge lookup, not a parse. - Type::Builtin { spelling } => match PrimaryType::from_spelling(spelling) { - Some(PrimaryType::Auto) => TypeKind::Auto, - Some(PrimaryType::DecltypeAuto) => TypeKind::DecltypeAuto, - _ => TypeKind::Builtin(self.names.intern(spelling.trim())), - }, - Type::Named { name, arguments } => { - let name = self.names.intern(name); - let arguments = arguments - .iter() - .map(|argument| self.intern_type(argument)) - .collect(); - TypeKind::Named { - name, - arguments: self.intern_arguments(arguments), - } - } - Type::TemplateParameter { name } => { - TypeKind::TemplateParameter(self.names.intern(name)) - } - Type::ElaboratedRecord { tag, of } => TypeKind::ElaboratedRecord { - tag: *tag, - of: self.intern_type(of), - }, - Type::Pointer { to } => TypeKind::Pointer(self.intern_type(to)), - Type::Reference { to, rvalue } => TypeKind::Reference { - to: self.intern_type(to), - rvalue: *rvalue, - }, - Type::Array { of, extent } => TypeKind::Array { - of: self.intern_type(of), - extent: extent.map_or(UNKNOWN_EXTENT, |extent| extent as u64), - }, - Type::Function { - returns, - parameters, - } => { - let returns = self.intern_type(returns); - let parameters = parameters - .iter() - .map(|parameter| self.intern_type(parameter)) - .collect(); - TypeKind::Function { - returns, - parameters: self.intern_arguments(parameters), - } - } - Type::Pack { of } => TypeKind::Pack(self.intern_type(of)), - Type::Qualified { of, qualifiers } => TypeKind::Qualified { - of: self.intern_type(of), - qualifiers: *qualifiers, - }, - }; - self.intern(kind, Some(&spelling)) - } - - /// **Intern one argument sequence**, so two `std::vector` nodes share the same argument list as well as the - /// same name. An empty sequence is [`ArgsId::EMPTY`] and costs no arena slot. - pub fn intern_arguments(&mut self, arguments: Vec) -> ArgsId { - if arguments.is_empty() { - return ArgsId::EMPTY; - } - let arguments: Box<[TypeId]> = arguments.into_boxed_slice(); - if let Some(id) = self.argument_ids.get(&arguments) { - return *id; - } - let id = ArgsId::from_index(self.arguments.len()); - self.arguments.push(arguments.clone()); - self.argument_ids.insert(arguments, id); - id - } - - pub fn arguments(&self, id: ArgsId) -> &[TypeId] { - id.index() - .and_then(|at| self.arguments.get(at)) - .map_or(&[], |arguments| arguments) - } - - /// **The entry point for a spelling that came from outside the syntax** — a cache record, a CLI argument, a - /// test. Parsing remains one call, at this boundary; consumers below use [`TypeId`]. The spelling itself is kept - /// as the node's display value, so a caller that recorded `const char *` is shown those characters. - pub fn intern_spelling(&mut self, spelling: &str) -> TypeId { - let parsed = crate::sema::types::parse_type_spelling(spelling); - let parsed = crate::sema::types::without_placeholders_written_as_names(parsed); - self.intern_type_written_as(&parsed, Some(spelling)) - } - - /// **Intern a type a declaration wrote**, with the declaration's own template parameter names marked as - /// [`TypeKind::TemplateParameter`], and the written spelling kept for display. - /// - /// The spelling is the file's, so this is a construction-edge parse — the one place the fact builder hands a - /// written type to the store. `parameters` is the fact's own template-parameter list: without it a member written - /// `T&` would be stored as a class *named* `T`, and instantiating the class would never substitute it. - pub fn intern_a_declared_type>( - &mut self, - spelling: &str, - parameters: &[N], - ) -> TypeId { - let parsed = crate::sema::types::parse_type_spelling(spelling); - let parsed = crate::sema::types::without_placeholders_written_as_names(parsed); - let parsed = crate::sema::types::with_template_parameters(parsed, parameters); - self.intern_type_written_as(&parsed, Some(spelling)) - } - - /// The node a handle names, or `None` for a handle from a different store. - pub fn node(&self, id: TypeId) -> Option<&TypeNode> { - self.nodes.get(id.index()) - } - - /// A store-plus-handle pair, the read API used by everything above this module. - pub fn type_ref(&self, id: TypeId) -> Option> { - self.node(id).map(|_| TypeRef { store: self, id }) - } - - pub fn spelling(&self, id: TypeId) -> Option<&str> { - self.spellings - .get(id.index()) - .and_then(|spelling| *spelling) - .and_then(|spelling| self.names.name(spelling)) - } - - /// **Build the computation-side type for one handle.** No mutation: a query can call this while other readers - /// use the same store, and the result owns its names (or shares their long backing strings) and its children. - pub fn materialize(&self, id: TypeId) -> Option { - let node = self.node(id)?; - Some(match &node.kind { - // **A stored builtin is the primary it spells.** The node keeps the file's spelling for `TypeRef::display`; - // the computation layer works with the primary identity, and a spelling outside the language's primary set - // (a compiler extension) has no primary to answer, so it stays a name. - TypeKind::Builtin(name) => { - let name = self.names.smol(*name)?; - match PrimaryType::from_spelling(&name) { - Some(primary) => ComputedType::Primary(primary), - None => ComputedType::Named(name), - } - } - TypeKind::Named { name, arguments } => { - let name = self.names.smol(*name)?; - let arguments = self - .arguments(*arguments) - .iter() - .filter_map(|argument| self.materialize(*argument)) - .collect::>(); - ComputedType::named(name, arguments) - } - TypeKind::TemplateParameter(name) => { - ComputedType::TemplateParameter(self.names.smol(*name)?) - } - TypeKind::Auto => ComputedType::Primary(PrimaryType::Auto), - TypeKind::DecltypeAuto => ComputedType::Primary(PrimaryType::DecltypeAuto), - TypeKind::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { - tag: *tag, - of: std::sync::Arc::new(self.materialize(*of)?), - }, - TypeKind::Pointer(to) => { - ComputedType::Pointer(std::sync::Arc::new(self.materialize(*to)?)) - } - TypeKind::Reference { to, rvalue } => ComputedType::Reference { - to: std::sync::Arc::new(self.materialize(*to)?), - rvalue: *rvalue, - }, - TypeKind::Array { of, extent } => ComputedType::Array { - of: std::sync::Arc::new(self.materialize(*of)?), - extent: (*extent != UNKNOWN_EXTENT).then_some(*extent), - }, - TypeKind::Function { - returns, - parameters, - } => ComputedType::Function(std::sync::Arc::new(FunctionType { - returns: std::sync::Arc::new(self.materialize(*returns)?), - parameters: self - .arguments(*parameters) - .iter() - .filter_map(|parameter| self.materialize(*parameter)) - .collect::>() - .into_boxed_slice(), - })), - TypeKind::Pack(of) => ComputedType::Pack(std::sync::Arc::new(self.materialize(*of)?)), - TypeKind::Qualified { of, qualifiers } => { - ComputedType::Qualified(std::sync::Arc::new(QualifiedType { - of: std::sync::Arc::new(self.materialize(*of)?), - is_const: qualifiers.is_const(), - is_volatile: qualifiers.is_volatile(), - })) - } - }) - } - - /// **Collect every node reachable from `ids` into a self-contained table.** Children always have lower IDs than - /// the nodes that name them, because interning is post-order, so a decoder can import entries in ascending ID - /// order without a second topological sort. - pub fn export(&self, ids: impl IntoIterator) -> TypeTable { - let mut seen = FxHashMap::::default(); - let mut pending: Vec = ids.into_iter().collect(); - let mut entries: Vec = Vec::new(); - while let Some(id) = pending.pop() { - if id.is_none() || seen.insert(id.0, ()).is_some() { - continue; - } - let Some(node) = self.node(id) else { - continue; - }; - let kind = match &node.kind { - TypeKind::Builtin(name) => { - EncodedTypeKind::Builtin(self.names.name(*name).unwrap_or_default().to_string()) - } - TypeKind::Named { name, arguments } => { - let arguments = self.arguments(*arguments).to_vec(); - pending.extend(arguments.iter().copied()); - EncodedTypeKind::Named { - name: self.names.name(*name).unwrap_or_default().to_string(), - arguments: arguments.iter().map(|id| id.0).collect(), - } - } - TypeKind::TemplateParameter(name) => EncodedTypeKind::TemplateParameter( - self.names.name(*name).unwrap_or_default().to_string(), - ), - TypeKind::Auto => EncodedTypeKind::Auto, - TypeKind::DecltypeAuto => EncodedTypeKind::DecltypeAuto, - TypeKind::ElaboratedRecord { tag, of } => { - pending.push(*of); - EncodedTypeKind::ElaboratedRecord { - tag: *tag, - of: of.0, - } - } - TypeKind::Pointer(to) => { - pending.push(*to); - EncodedTypeKind::Pointer(to.0) - } - TypeKind::Reference { to, rvalue } => { - pending.push(*to); - EncodedTypeKind::Reference { - to: to.0, - rvalue: *rvalue, - } - } - TypeKind::Array { of, extent } => { - pending.push(*of); - EncodedTypeKind::Array { - of: of.0, - extent: *extent, - } - } - TypeKind::Function { - returns, - parameters, - } => { - let parameters = self.arguments(*parameters).to_vec(); - pending.push(*returns); - pending.extend(parameters.iter().copied()); - EncodedTypeKind::Function { - returns: returns.0, - parameters: parameters.iter().map(|id| id.0).collect(), - } - } - TypeKind::Pack(of) => { - pending.push(*of); - EncodedTypeKind::Pack(of.0) - } - TypeKind::Qualified { of, qualifiers } => { - pending.push(*of); - EncodedTypeKind::Qualified { - of: of.0, - is_const: qualifiers.is_const(), - is_volatile: qualifiers.is_volatile(), - } - } - }; - entries.push(EncodedType { - id: id.0, - spelling: self.spelling(id).map(str::to_string), - kind, - }); - } - entries.sort_by_key(|entry| entry.id); - TypeTable { entries } - } - - /// **Import a summary's local table into this store**, returning the old-ID to store-ID map. - /// - /// Entries are sorted by their local ID; a child therefore always precedes the node that names it. - pub fn import(&mut self, table: &TypeTable) -> FxHashMap { - use crate::sema::types::Qualifiers; - let mut map = FxHashMap::::default(); - for entry in &table.entries { - let child = |map: &FxHashMap, id: u32| { - map.get(&id).copied().unwrap_or(TypeId::NONE) - }; - let kind = match &entry.kind { - EncodedTypeKind::Builtin(name) => TypeKind::Builtin(self.names.intern(name)), - EncodedTypeKind::Named { name, arguments } => { - let arguments = arguments.iter().map(|id| child(&map, *id)).collect(); - TypeKind::Named { - name: self.names.intern(name), - arguments: self.intern_arguments(arguments), - } - } - EncodedTypeKind::TemplateParameter(name) => { - TypeKind::TemplateParameter(self.names.intern(name)) - } - EncodedTypeKind::Auto => TypeKind::Auto, - EncodedTypeKind::DecltypeAuto => TypeKind::DecltypeAuto, - EncodedTypeKind::ElaboratedRecord { tag, of } => TypeKind::ElaboratedRecord { - tag: *tag, - of: child(&map, *of), - }, - EncodedTypeKind::Pointer(to) => TypeKind::Pointer(child(&map, *to)), - EncodedTypeKind::Reference { to, rvalue } => TypeKind::Reference { - to: child(&map, *to), - rvalue: *rvalue, - }, - EncodedTypeKind::Array { of, extent } => TypeKind::Array { - of: child(&map, *of), - extent: *extent, - }, - EncodedTypeKind::Function { - returns, - parameters, - } => { - let parameters = parameters.iter().map(|id| child(&map, *id)).collect(); - TypeKind::Function { - returns: child(&map, *returns), - parameters: self.intern_arguments(parameters), - } - } - EncodedTypeKind::Pack(of) => TypeKind::Pack(child(&map, *of)), - EncodedTypeKind::Qualified { - of, - is_const, - is_volatile, - } => { - let mut qualifiers = Qualifiers::NONE; - if *is_const { - qualifiers = qualifiers.with(Qualifiers::CONST); - } - if *is_volatile { - qualifiers = qualifiers.with(Qualifiers::VOLATILE); - } - TypeKind::Qualified { - of: child(&map, *of), - qualifiers, - } - } - }; - let id = self.intern(kind, entry.spelling.as_deref()); - map.insert(entry.id, id); - } - map - } - - /// **What the store costs**, in the same lower-bound style as [`crate::MemoryReport`]: live nodes, live names, - /// argument-list payloads, and the maps' table entries. Spare capacity is not counted. - pub fn accounting(&self) -> TypeAccounting { - let argument_payload = self - .arguments - .iter() - .map(|arguments| arguments.len() * size_of::()) - .sum::(); - TypeAccounting { - types: self.nodes.len(), - names: self.names.len(), - argument_lists: self.arguments.len(), - bytes: self.nodes.len() * size_of::() - + self.spellings.len() * size_of::>() - + self.arguments.len() * size_of::>() - + argument_payload - + self.argument_ids.len() * size_of::<(Box<[TypeId]>, ArgsId)>() - + self.interned.len() * size_of::<(TypeKey, TypeId)>() - + self - .names - .names - .iter() - .map(|name| name.len()) - .sum::() - + self.names.ids.len() * size_of::<(SmolStr, NameId)>(), - } - } -} - -/// **One type as a summary writes it** — local IDs, names as strings, argument lists inline. The process-local -/// [`TypeStore`] is rebuilt from a table when the summary is loaded. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct TypeTable { - pub entries: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct EncodedType { - pub id: u32, - pub spelling: Option, - pub kind: EncodedTypeKind, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum EncodedTypeKind { - Builtin(String), - Named { - name: String, - arguments: Vec, - }, - TemplateParameter(String), - Auto, - DecltypeAuto, - ElaboratedRecord { - tag: RecordTag, - of: u32, - }, - Pointer(u32), - Reference { - to: u32, - rvalue: bool, - }, - Array { - of: u32, - extent: u64, - }, - Function { - returns: u32, - parameters: Vec, - }, - Pack(u32), - Qualified { - of: u32, - is_const: bool, - is_volatile: bool, - }, -} - -impl TypeTable { - pub fn is_empty(&self) -> bool { - self.entries.is_empty() - } - - /// The written spelling of a local table entry, when the encoder kept one. - pub fn spelling_for(&self, id: u32) -> Option<&str> { - self.entries - .iter() - .find(|entry| entry.id == id) - .and_then(|entry| entry.spelling.as_deref()) - } - - /// **A self-contained table for the nodes reachable from `ids`.** Children are pulled in, so a decoder importing - /// the result can resolve every handle a fact holds; IDs keep their local values, because the importer builds its - /// own map from them. - /// - /// Used when one parse's table is split across the files it read: a cooked reading travels and is cached per - /// file, so each file's record carries only its own facts' types. - pub fn export(&self, ids: impl IntoIterator) -> TypeTable { - let by_id: FxHashMap = - self.entries.iter().map(|entry| (entry.id, entry)).collect(); - let mut seen = FxHashMap::::default(); - let mut pending: Vec = ids.into_iter().map(TypeId::raw).collect(); - let mut entries = Vec::new(); - while let Some(id) = pending.pop() { - if id == TypeId::NONE.raw() || seen.insert(id, ()).is_some() { - continue; - } - let Some(entry) = by_id.get(&id) else { - continue; - }; - match &entry.kind { - EncodedTypeKind::Named { arguments, .. } => pending.extend(arguments.iter().copied()), - EncodedTypeKind::Pointer(to) - | EncodedTypeKind::Pack(to) - | EncodedTypeKind::ElaboratedRecord { of: to, .. } - | EncodedTypeKind::Qualified { of: to, .. } - | EncodedTypeKind::Reference { to, .. } - | EncodedTypeKind::Array { of: to, .. } => pending.push(*to), - EncodedTypeKind::Function { - returns, - parameters, - } => { - pending.push(*returns); - pending.extend(parameters.iter().copied()); - } - EncodedTypeKind::Builtin(_) - | EncodedTypeKind::TemplateParameter(_) - | EncodedTypeKind::Auto - | EncodedTypeKind::DecltypeAuto => {} - } - entries.push((*entry).clone()); - } - entries.sort_by_key(|entry| entry.id); - TypeTable { entries } - } - - /// The encoded table's heap cost: entries, spelling strings, named and function argument vectors. - pub fn heap_bytes(&self) -> usize { - self.entries.len() * size_of::() - + self - .entries - .iter() - .map(|entry| { - entry.spelling.as_ref().map_or(0, String::len) - + match &entry.kind { - EncodedTypeKind::Named { name, arguments } => { - name.len() + arguments.len() * size_of::() - } - EncodedTypeKind::Function { parameters, .. } => { - parameters.len() * size_of::() - } - EncodedTypeKind::Builtin(name) - | EncodedTypeKind::TemplateParameter(name) => name.len(), - _ => 0, - } - }) - .sum::() - } -} - -/// The store's contribution to the session's memory report. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct TypeAccounting { - pub types: usize, - pub names: usize, - pub argument_lists: usize, - pub bytes: usize, -} - -/// **A type handle with the store that gives it meaning.** The borrow is what makes it impossible to use an ID -/// from one generation in another. -#[derive(Clone, Copy)] -pub struct TypeRef<'a> { - store: &'a TypeStore, - id: TypeId, -} - -impl<'a> TypeRef<'a> { - pub fn id(self) -> TypeId { - self.id - } - - pub fn kind(self) -> &'a TypeKind { - &self.store.nodes[self.id.index()].kind - } - - /// The spelling the file wrote, if this node has one. - pub fn spelling(self) -> Option<&'a str> { - self.store.spelling(self.id) - } - - /// **How a reader sees the type.** The source spelling when there is one; otherwise a rendering of the shape, - /// used for a node a substitution or a test synthesized. - pub fn display(self) -> String { - if let Some(spelling) = self.spelling() { - return spelling.to_string(); - } - self.render() - } - - /// The class this type names, if it names one. A reference and a qualifier are transparent; a pointer is not. - pub fn class_name(self) -> Option<&'a str> { - match self.kind() { - TypeKind::Named { name, .. } => self.store.names.name(*name), - TypeKind::Reference { to, .. } | TypeKind::Qualified { of: to, .. } => { - self.store.type_ref(*to)?.class_name() - } - // **C's tag is transparent to a class question** — `struct point` names the record `point`. - TypeKind::ElaboratedRecord { of, .. } => self.store.type_ref(*of)?.class_name(), - _ => None, - } - } - - /// The template arguments written on the type, looking through a reference or a qualifier. - pub fn arguments(self) -> &'a [TypeId] { - match self.kind() { - TypeKind::Named { arguments, .. } => self.store.arguments(*arguments), - TypeKind::Reference { to, .. } - | TypeKind::Qualified { of: to, .. } - | TypeKind::ElaboratedRecord { of: to, .. } => { - self.store.type_ref(*to).map_or(&[], TypeRef::arguments) - } - _ => &[], - } - } - - /// The pointee of a pointer. A reference is a binding, not a pointer; a caller that wants through either asks - /// [`TypeRef::decay`] first. - pub fn pointee(self) -> Option> { - match self.kind() { - TypeKind::Pointer(to) => self.store.type_ref(*to), - _ => None, - } - } - - /// Is the object this type describes `const`? A qualifier and a reference are looked through; a pointer is not. - pub fn is_const(self) -> bool { - match self.kind() { - TypeKind::Qualified { qualifiers, .. } => qualifiers.is_const(), - TypeKind::Reference { to, .. } => self - .store - .type_ref(*to) - .is_some_and(|inner| inner.is_const()), - _ => false, - } - } - - fn render(self) -> String { - match self.kind() { - TypeKind::Builtin(name) | TypeKind::TemplateParameter(name) => self - .store - .names - .name(*name) - .unwrap_or("") - .to_string(), - TypeKind::Named { name, arguments } => { - let name = self.store.names.name(*name).unwrap_or(""); - let arguments = self.store.arguments(*arguments); - if arguments.is_empty() { - name.to_string() - } else { - let arguments = arguments - .iter() - .filter_map(|argument| self.store.type_ref(*argument)) - .map(TypeRef::render) - .collect::>() - .join(", "); - format!("{name}<{arguments}>") - } - } - TypeKind::Auto => "auto".to_string(), - TypeKind::DecltypeAuto => "decltype(auto)".to_string(), - // **The tag is written back** for a node that has no source spelling of its own; one that has a spelling - // is displayed from it, so the file's own characters win. - TypeKind::ElaboratedRecord { tag, of } => self.store.type_ref(*of).map_or_else( - || format!("{} ", tag.word()), - |inner| format!("{} {}", tag.word(), inner.render()), - ), - TypeKind::Pointer(to) => self.store.type_ref(*to).map_or_else( - || "*".to_string(), - |inner| format!("{}*", inner.render()), - ), - TypeKind::Reference { to, rvalue } => self.store.type_ref(*to).map_or_else( - || "&".to_string(), - |inner| format!("{}{}", inner.render(), if *rvalue { "&&" } else { "&" }), - ), - TypeKind::Array { of, extent } => self.store.type_ref(*of).map_or_else( - || "[]".to_string(), - |inner| match *extent { - UNKNOWN_EXTENT => format!("{}[]", inner.render()), - extent => format!("{}[{extent}]", inner.render()), - }, - ), - TypeKind::Function { - returns, - parameters, - } => { - let returns = self - .store - .type_ref(*returns) - .map_or_else(|| "".to_string(), TypeRef::render); - let parameters = self.store.arguments(*parameters); - let parameters = parameters - .iter() - .filter_map(|parameter| self.store.type_ref(*parameter)) - .map(TypeRef::render) - .collect::>() - .join(", "); - format!("{returns}({parameters})") - } - TypeKind::Pack(of) => self.store.type_ref(*of).map_or_else( - || "...".to_string(), - |inner| format!("{}...", inner.render()), - ), - TypeKind::Qualified { of, qualifiers } => self.store.type_ref(*of).map_or_else( - || "".to_string(), - |inner| format!("{}{}", qualifiers.leading_words(), inner.render()), - ), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::sema::types::{Qualifiers, RecordTag, Type}; - use std::mem::size_of; - use std::sync::Arc; - - /// **The storage shape stays small.** `Named` is the variant that used to push `TypeKind` to 32 bytes; its - /// argument list lives in the store's arena, so the enum is one tag plus eight payload bytes. - #[test] - fn a_stored_type_materializes_without_touching_the_store() { - let mut store = TypeStore::new(); - let stored = store.intern_spelling("std::vector"); - let before = store.len(); - let computed = store.materialize(stored).expect("materialized"); - assert_eq!(computed.to_string(), "std::vector"); - assert_eq!(computed.class_name(), Some("std::vector")); - assert_eq!(store.len(), before, "materializing interned nothing"); - } - - #[test] - fn a_type_table_exports_the_nodes_one_fact_needs() { - // The unit read parses every file as one program and then splits the facts per file; each file's record has - // to carry the nodes its own handles reach, children included, and nothing else. - let mut store = TypeStore::new(); - let int = store.intern_spelling("int"); - let vector = store.intern_spelling("std::vector"); - let full = store.export([vector]); - assert_eq!(full.entries.len(), 2, "the node and its argument"); - - let subset = full.export([vector]); - assert_eq!( - subset.entries.len(), - 2, - "a subset by a parent still brings its children" - ); - let only_the_argument = full.export([int]); - assert_eq!(only_the_argument.entries.len(), 1); - assert_eq!(only_the_argument.entries[0].id, int.raw()); - } - - #[test] - fn a_declared_template_parameter_is_stored_as_one() { - // A fact's type is written by a declaration that also lists its template parameters; without that list a - // member's `const T&` is a class called `T` and instantiating the class would never substitute it. - let mut store = TypeStore::new(); - let written = store.intern_a_declared_type("const T&", &[SmolStr::new("T")]); - let computed = store.materialize(written).expect("materialized"); - assert_eq!(computed.to_string(), "const T&"); - let substituted = computed.substituted(&[( - SmolStr::new("T"), - ComputedType::Primary(PrimaryType::Int), - )]); - assert_eq!(substituted.to_string(), "const int&"); - } - - #[test] - fn a_type_table_round_trips_every_node_a_fact_needs() { - let mut store = TypeStore::new(); - let written = store.intern_spelling("std::vector"); - let table = store.export([written]); - assert!(!table.is_empty()); - - let mut loaded = TypeStore::new(); - let mapping = loaded.import(&table); - let restored = mapping[&written.0]; - assert_eq!( - loaded.type_ref(restored).unwrap().display(), - "std::vector" - ); - assert_eq!( - loaded.type_ref(restored).unwrap().class_name(), - Some("std::vector") - ); - } - - /// **C's record tag crosses the store and the record that carries it.** The tag is written on the declaration, so - /// a fact's handle has to materialize it back — a `ComputedType` for the queries and a `Type` for the conversion - /// question — and the table a summary exports has to bring it along. Dropping it at either boundary is what would - /// turn `struct point *` into a name a `typedef` could also spell. - #[test] - fn a_c_record_tag_survives_the_store_and_the_table() { - let mut store = TypeStore::new(); - let written = store.intern_spelling("struct point *"); - let computed = store.materialize(written).expect("materialized"); - assert_eq!(computed.to_string(), "struct point*"); - let parser = computed.to_sema_type(); - assert!( - matches!( - parser, - Type::Pointer { ref to } - if matches!( - **to, - Type::ElaboratedRecord { - tag: RecordTag::Struct, - .. - } - ) - ), - "the tag survives materialization: {parser:?}" - ); - - let value = store.intern_spelling("union value"); - assert_eq!( - store.materialize(value).expect("materialized").to_string(), - "union value", - "a union writes its own keyword" - ); - - // **The table a summary writes is the same shape.** Export, import into a fresh store, and read it back: - // both records must answer their tag from the imported nodes. - let table = store.export([written, value]); - let mut loaded = TypeStore::new(); - let mapping = loaded.import(&table); - assert_eq!( - loaded - .materialize(mapping[&written.raw()]) - .expect("restored") - .to_string(), - "struct point*" - ); - assert_eq!( - loaded - .materialize(mapping[&value.raw()]) - .expect("restored") - .to_string(), - "union value" - ); - } - - #[test] - fn a_type_kind_is_sixteen_bytes() { - assert_eq!(size_of::(), 16); - assert_eq!(size_of::(), 16); - } - - #[test] - fn the_same_spelling_is_one_node() { - let mut store = TypeStore::new(); - let first = store.intern_spelling("std::vector"); - let second = store.intern_spelling("std::vector"); - - assert_eq!(first, second); - assert_eq!( - store.len(), - 2, - "int and the vector node; vector itself is not a separate node" - ); - } - - #[test] - fn two_spellings_of_one_shape_are_two_nodes() { - let mut store = TypeStore::new(); - let size_t = store.intern_spelling("std::size_t"); - let unsigned = store.intern_spelling("unsigned long long"); - - assert_ne!(size_t, unsigned); - assert_eq!(store.type_ref(size_t).unwrap().display(), "std::size_t"); - assert_eq!( - store.type_ref(unsigned).unwrap().display(), - "unsigned long long" - ); - } - - #[test] - fn a_named_type_keeps_its_class_and_arguments() { - let mut store = TypeStore::new(); - let vector = store.intern_spelling("std::vector"); - let reference = store.type_ref(vector).expect("interned"); - - assert_eq!(reference.class_name(), Some("std::vector")); - assert_eq!(reference.arguments().len(), 1); - assert_eq!( - store - .type_ref(reference.arguments()[0]) - .expect("argument") - .display(), - "int" - ); - } - - #[test] - fn a_qualified_pointer_keeps_the_qualifier_where_it_was_written() { - let mut store = TypeStore::new(); - let pointer_to_const = store.intern_spelling("const Widget*"); - let const_pointer = store.intern_spelling("Widget* const"); - - assert_ne!(pointer_to_const, const_pointer); - assert!( - !store.type_ref(pointer_to_const).unwrap().is_const(), - "the pointee is const, not the pointer" - ); - assert!( - store.type_ref(const_pointer).unwrap().is_const(), - "the pointer itself is const" - ); - } - - #[test] - fn a_synthetic_node_renders_without_a_spelling() { - let mut store = TypeStore::new(); - let int = store.intern_spelling("int"); - let pointer = store.intern(TypeKind::Pointer(int), None); - - assert_eq!(store.type_ref(pointer).unwrap().display(), "int*"); - } - - #[test] - fn a_source_spelling_is_displayed_even_when_the_shape_is_synthetic() { - let mut store = TypeStore::new(); - let int = store.intern_spelling("int"); - let alias = store.intern( - TypeKind::Qualified { - of: int, - qualifiers: Qualifiers::CONST, - }, - Some("cint"), - ); - - assert_eq!(store.type_ref(alias).unwrap().display(), "cint"); - assert!(store.type_ref(alias).unwrap().is_const()); - } - - #[test] - fn converting_a_parser_type_returns_the_same_id_as_the_spelling_entry() { - let parsed = Type::Function { - returns: Arc::new(Type::builtin("int")), - parameters: vec![Type::builtin("int"), Type::builtin("double")], - }; - let mut store = TypeStore::new(); - let from_syntax = store.intern_type(&parsed); - let from_spelling = store.intern_spelling("int(int, double)"); - - assert_eq!(from_syntax, from_spelling); - assert_eq!( - store.type_ref(from_syntax).unwrap().display(), - "int(int, double)" - ); - } -} 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 82c568d9..0f5fc4db 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -313,10 +313,7 @@ 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 - && parameters_written.len() == 1 - && parameters_written[0].is_void() - { + if written == 1 && parameters_written.len() == 1 && parameters_written[0].is_void() { written = 0; required = 0; parameters_written.clear(); @@ -422,11 +419,7 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec // **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, - context.index().types(), - fact.variadic_parameters, - ) else { + 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 @@ -447,7 +440,6 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec /// [`DeclaredType`]: crate::cache::summary::DeclaredType fn the_callee_in_facts( facts: &[crate::index::params::ParameterFact], - types: &crate::index::types::TypeStore, mut variadic: bool, ) -> Option { let mut written = 0usize; @@ -458,7 +450,7 @@ fn the_callee_in_facts( variadic = true; continue; } - let type_of = parameter.type_of.as_computed(types)?; + let type_of = parameter.type_of.as_computed()?; written += 1; if parameter.default_value.is_none() { required += 1; @@ -565,11 +557,7 @@ fn judge_a_member_call( continue; } let facts = context.index().parameter_facts_of(file, fact); - if let Some(callee) = the_callee_in_facts( - facts, - context.index().types(), - fact.variadic_parameters, - ) { + if let Some(callee) = the_callee_in_facts(facts, fact.variadic_parameters) { members.push(callee); } } @@ -591,7 +579,7 @@ fn judge_a_member_call( 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, context.index().types(), fact.variadic_parameters) + the_callee_in_facts(facts, fact.variadic_parameters) }) .collect(); } 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 f7cd7652..ce741826 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 @@ -116,6 +116,12 @@ impl Check for AssignTypeCheck { .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) => { @@ -469,12 +475,10 @@ fn report_if_it_does_not_convert( if context.a_string_literal_in_a_char_pointer_position(expression, &target.type_of) { return; } - 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 + 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, &target.written); return; @@ -488,8 +492,11 @@ fn report_if_it_does_not_convert( // **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) + if a_class_can_be_built_from( + context, + target.type_of.class_name().unwrap_or_default(), + &from, + ) == Some(false) { report(context, expression, name, how, &target.written); } diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index d9852463..b62d5ef4 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -166,7 +166,7 @@ pub fn conversion_to( /// name; a type written without one answers `None`. /// /// The evidence is **on the type** ([`Type::ElaboratedRecord`]), which the declaration reader and -/// `parse_type_spelling` produce from the written keyword and which the index's `TypeStore` keeps. No caller hands +/// `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 diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 79ed2f93..5ad9fa69 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -30,7 +30,6 @@ use crate::DeclModifiers; use crate::Name; -use crate::index::types::TypeId; use crate::scopes; use crate::sema; use crate::summary; @@ -101,17 +100,15 @@ pub struct BuiltFacts { /// 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: crate::index::params::ParamsStore, - pub types: crate::index::types::TypeStore, } -/// **A freshly built fact set for a caller that keeps no store**: each type handle is materialized and kept as the -/// fact's computed value, and the handles are cleared. +/// **A freshly built fact set for a caller that keeps no parameter store**: the parameter handle is cleared. /// -/// [`build_facts`] returns a **local** `TypeStore` and a local `ParamsStore`; a caller that files the facts in a -/// summary hands the tables 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 them. Leaving the local handles on those facts would let a query resolve an -/// index into a store that was dropped — another store's `TypeId(3)` — so the type handles are bound here, once, into -/// the computation layer, and 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 @@ -121,26 +118,12 @@ pub struct BuiltFacts { /// /// [`SynthesizedFact`]: crate::index::project::SynthesizedFact pub fn facts_with_their_types(built: BuiltFacts) -> Vec { - let BuiltFacts { - mut facts, types, .. - } = built; + let BuiltFacts { mut facts, .. } = built; for fact in &mut facts { - fact.type_of = fact - .type_of - .as_computed(&types) - .map_or(DeclaredType::None, |computed| { - DeclaredType::Computed(std::sync::Arc::new(computed)) - }); - fact.returns = fact - .returns - .as_computed(&types) - .map_or(DeclaredType::None, |computed| { - DeclaredType::Computed(std::sync::Arc::new(computed)) - }); // **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 — - // the same reason the two type handles above are materialized. A caller that needs a declaration's parameters - // asks the index (`ProjectIndex::parameter_facts_of`), which resolves through the summary that owns them. + // 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. @@ -188,7 +171,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) } @@ -239,18 +222,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 @@ -282,7 +267,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; @@ -295,7 +280,10 @@ pub(crate) fn an_unnamed_class_body_named( unnamed = a_class_body_without_a_tag(specifiers); } }); - unnamed.then(|| format!("{scope}::{name}")) + unnamed.then(|| sema::types::Type::Named { + name: format!("{scope}::{name}"), + arguments: Vec::new(), + }) } /// Does this specifier sequence hold an **unnamed class body** — `struct { … }` with no tag of its own? @@ -324,7 +312,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 @@ -434,6 +422,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 `Type` already. let found = sema::types::type_of_declaration_named( &specifiers, declarator.as_ref(), @@ -446,33 +439,174 @@ 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), ); + // **An empty spelling is "no type"**, which is what a declaration specifier sequence the reader could not + // place produces; `Type::Builtin { spelling: "" }` is the shape that means it. + (!found.to_string().trim().is_empty()).then_some(found) +} - // **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}") +/// **The written spelling of a declaration's type**, for a consumer that must evaluate what the structure cannot +/// carry — an array dimension that is a macro or an enumerator (`Point points[COUNT]`). +/// +/// The fact carries the *structural* type, and a dimension that is not a literal is deliberately not part of it +/// (`Type::Array.extent` is `None`). A layout question still has to size such a member, so this is the one query that +/// reassembles the file's own spelling: the specifiers read as syntax, plus the declarator with the declared name cut +/// out — and, for a type's parameter list, with the parameter *names* cut out too (`int (*)(int)` is the type; +/// `int (*)(int left)` is the declaration). It is a **query over the tree**, used for display/evaluation only; no +/// fact stores it. +pub(crate) fn declared_type_spelling_with( + shapes: &DeclarationShapes, + binding: &Binding, +) -> Option { + if !matches!( + binding.kind, + BindingKind::Variable | BindingKind::Typedef | BindingKind::Alias + ) { + return None; + } + let mut specifiers = None; + let mut declarator: Option = None; + let name_is_a_parameter = shapes.names_a_parameter(binding.name_range.start_offset); + shapes.on_the_path(the_offset_to_descend_by(binding), |shape| { + if let Some(node) = &shape.specifiers { + specifiers = Some(node.clone()); + } + if declarator.is_none() + && let Some(node) = &shape.declarator + && reaches_the_name(node, binding.name_range) + && !(name_is_a_parameter && is_a_function_declarator(node)) + { + declarator = Some(node.clone()); } - None => found.to_string(), + }); + let specifiers = specifiers?; + let spelled = match binding.kind { + BindingKind::Typedef => None, + _ => Some(binding.name.spelled()), + }; + let base = sema::types::read_specifiers_named( + &specifiers, + spelled.as_deref(), + source_range(specifiers.text_range()), + ); + let base = strip_declaration_specifiers(&base.to_string()); + let Some(declarator) = declarator else { + return (!base.is_empty()).then_some(base); }; - let written = written.split_whitespace().collect::>().join(" "); - (!written.is_empty()).then_some(written) + let operators = the_operators_around_the_name(&declarator, binding.name_range); + let writing = format!("{base} {operators}"); + let writing = writing.split_whitespace().collect::>().join(" "); + (!writing.is_empty()).then_some(writing) +} + +/// **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** and a **parameter list +/// that belongs to the name** of an object (a constructor call). Everything else is the type's. This is a written +/// spelling for the layout edge only — see [`declared_type_spelling_with`] — not a stored representation. +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(); + 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)); + } + 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()) + }); + 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; + 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]); + } + 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 specifier keywords that can precede a type without being part of it. +const DECLARATION_SPECIFIERS: &[&str] = &[ + "static", + "extern", + "inline", + "virtual", + "explicit", + "friend", + "mutable", + "register", + "thread_local", + "constexpr", + "consteval", + "constinit", + "typedef", + "const", + "volatile", + "struct", + "class", + "union", + "enum", +]; + +/// 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(); + } } /// **The modifiers a declaration is written with**, from the tokens the shape table already holds. @@ -1429,7 +1563,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) } @@ -1437,7 +1571,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; } @@ -1462,15 +1596,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.** // @@ -1479,35 +1609,45 @@ 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(sema::types::Type::Named { + name: named, + arguments: 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 @@ -1538,99 +1678,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 @@ -1646,12 +1693,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()`. @@ -2988,20 +3037,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`]. @@ -3018,7 +3068,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?** @@ -3032,7 +3083,11 @@ 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 an_operator_return_is_usable( + root: &CppSyntaxNode, + binding: &Binding, + written: &sema::types::Type, +) -> bool { fn means_the_same_everywhere(kind: &sema::types::Type) -> bool { use crate::sema::types::Type; match kind { @@ -3048,13 +3103,10 @@ fn an_operator_return_is_usable(root: &CppSyntaxNode, binding: &Binding, spellin } } - 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) @@ -3108,8 +3160,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 @@ -3134,11 +3186,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 `Type` 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!( @@ -3150,10 +3206,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 { @@ -3162,10 +3218,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 @@ -3177,95 +3230,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('*'), @@ -3275,61 +3282,82 @@ 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 sema::types::Type::Builtin { spelling } = &written + && matches!(spelling.trim(), "auto" | "decltype(auto)") + { 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: sema::types::Type, operators: &str) -> sema::types::Type { + 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 = sema::types::Type::Pointer { + to: Arc::new(written), + }; + at += 1; + } + '&' => { + let rvalue = operators.get(at + 1) == Some(&'&'); + written = sema::types::Type::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*. @@ -3350,8 +3378,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: &sema::types::Type, +) -> 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(); @@ -3377,8 +3410,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()) @@ -3387,14 +3420,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() @@ -3403,13 +3437,38 @@ 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 = sema::types::Type::Function { + returns: Arc::new(wrapped), + parameters: sema::types::read_parameters(suffix), + }; + } else { + wrapped = sema::types::Type::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 { + '*' => sema::types::Type::Pointer { + to: Arc::new(wrapped), + }, + _ => sema::types::Type::Reference { + to: Arc::new(wrapped), + rvalue: false, + }, + }; + } + Some(wrapped) } fn before(text: &str, node: &CppSyntaxNode, name: SourceRange) -> String { @@ -3900,59 +3959,6 @@ 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 @@ -3968,14 +3974,10 @@ fn fact_for( // scope in the file per declaration. in_namespace: Option, declarations: &Declarations<'_>, - // **The summary's local type table.** A fact stores a handle, so the two spellings this declaration states are - // interned **once**, here, at the construction edge — never on a query. `ProjectIndex::insert_at` imports this - // table into the one global store and rewrites the handles; a query then materializes without parsing anything. - types: &mut crate::index::types::TypeStore, - // **The summary's local parameter arena.** Each parameter's type is interned into `types` and the list itself 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`]. + // **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 crate::index::params::ParamsStore, // than the macro table, because the answer is the same for every declaration in the file and asking per ) -> Option { @@ -4036,6 +4038,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 `Type`; 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 { @@ -4043,8 +4048,16 @@ 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 `Type::Named`. + .or_else(|| { + declared_namespace_alias_target_with(root, binding).map(|name| { + sema::types::Type::Named { + name, + arguments: 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 @@ -4064,15 +4077,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 @@ -4080,10 +4100,12 @@ 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 @@ -4188,34 +4210,37 @@ fn fact_for( && 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); - let source = cpp.get_type_text(); - parameter.type_of = DeclaredType::Stored( - types.intern_type_written_as(&written, Some(source.trim())), - ); + parameter.type_of = DeclaredType::Computed(std::sync::Arc::new( + crate::index::types::ComputedType::from(&written), + )); } } parameter_arena.intern(declared) }; - // **The type handles, interned at the construction edge.** The two spellings above are the only place this fact - // ever sees the text of a type; storing a handle here is what lets every later query materialize a - // `ComputedType` without parsing. An empty spelling means "no type to name", which is the handle `NONE` — the - // same answer as a declaration that declares no type. - let type_of_id = type_of.as_deref().map_or(TypeId::NONE, |spelling| { - if spelling.trim().is_empty() { - TypeId::NONE - } else { - types.intern_a_declared_type(spelling, ¶meters) - } - }); - let returns_id = returns.as_deref().map_or(TypeId::NONE, |spelling| { - if spelling.trim().is_empty() { - TypeId::NONE - } else { - types.intern_a_declared_type(spelling, ¶meters) - } - }); + // **The type values, lowered at the construction edge.** The two `Type`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( + crate::index::types::ComputedType::from(&written), + )) + }) + }; + if name.as_ref() == "pointer" { + eprintln!("[fact] {} -> {:?}", name, type_of); + } + if name.as_ref() == "priority" { eprintln!("[fact] {} -> {:?}", name, type_of); } + if name.as_ref() == "find" { eprintln!("[fact find] params={:?} returns={:?}", parameters, returns); } + let type_of = lower(type_of); + let returns = lower(returns); Some(DeclFact { kind: DeclKind::from_binding_kind(binding.kind), @@ -4239,8 +4264,8 @@ 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: DeclaredType::from_stored(type_of_id), - returns: DeclaredType::from_stored(returns_id), + 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`. @@ -4875,13 +4900,10 @@ 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 type table**, filled by [`fact_for`] as each fact's spellings are interned. Returned - /// with the facts so that [`crate::FileIndexer::index_tree`] can put it in the summary and the index can import - /// it once, at insertion. - types: crate::index::types::TypeStore, /// **The summary's local parameter arena**, filled by [`fact_for`] as each declaration's parameters are interned. - /// Returned beside the facts for the same reason the type table is, and this is the only place the parameter list - /// is stored — a fact holds a `ParamsId`, never the list itself. + /// 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: crate::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. @@ -4905,7 +4927,6 @@ impl<'a> DeclarationFacts<'a> { declarations: Declarations::of(root, errors), guards: SummaryGuards::default(), facts: Vec::new(), - types: crate::index::types::TypeStore::new(), parameters: crate::index::params::ParamsStore::new(), } } @@ -4922,7 +4943,6 @@ impl<'a> DeclarationFacts<'a> { declarations, mut guards, mut facts, - mut types, mut parameters, } = self; @@ -5002,7 +5022,6 @@ impl<'a> DeclarationFacts<'a> { local, in_namespace.clone(), &declarations, - &mut types, &mut parameters, ) { facts.push(fact); @@ -5072,7 +5091,6 @@ impl<'a> DeclarationFacts<'a> { false, None, &declarations, - &mut types, &mut parameters, ) { // **The walker answered `None` for a definition's list**, because the shape it reads the declarator @@ -5128,7 +5146,6 @@ impl<'a> DeclarationFacts<'a> { facts, guards, parameters, - types, } } } @@ -6346,22 +6363,22 @@ mod tests { typedef basic_string B;\n\ typedef void (*F)(int);\n\ typedef int int32_t;\n"; - let (facts, _, types) = facts_and_types(source); + let (facts, _) = facts(source); let type_of = |name: &str| { let fact = facts .iter() .find(|fact| fact.name == name) .unwrap_or_else(|| panic!("{name} must be a fact")); - type_spelling_of(&types, 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")); } @@ -6498,18 +6515,6 @@ int Box::Inner::deep = 0; } fn facts(source: &str) -> (Vec, summary::SummaryGuards) { - let (facts, guards, _) = facts_and_types(source); - (facts, guards) - } - - /// The same facts, with the local type table their handles index — what a test that prints a fact's type needs. - fn facts_and_types( - source: &str, - ) -> ( - Vec, - summary::SummaryGuards, - crate::index::types::TypeStore, - ) { let tree = CppParser::parse(source, ParserConfig::default()); assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); @@ -6521,14 +6526,12 @@ int Box::Inner::deep = 0; &[], true, ); - (built.facts, built.guards, built.types) + (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, crate::index::params::ParamsStore) { + fn facts_with_parameters(source: &str) -> (Vec, crate::index::params::ParamsStore) { let tree = CppParser::parse(source, ParserConfig::default()); assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); @@ -6543,33 +6546,13 @@ int Box::Inner::deep = 0; (built.facts, built.parameters) } - /// **A fact's written type or return spelling**, from the local table — the display edge a consumer uses. - fn type_spelling_of( - types: &crate::index::types::TypeStore, - fact: &DeclFact, - ) -> Option { - spelled_at_the_edge(types, fact.type_of_id()) + /// **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( - types: &crate::index::types::TypeStore, - fact: &DeclFact, - ) -> Option { - spelled_at_the_edge(types, fact.returns_id()) - } - - fn spelled_at_the_edge( - types: &crate::index::types::TypeStore, - id: Option, - ) -> Option { - let id = id?; - Some( - types - .spelling(id) - .map(str::to_string) - .or_else(|| types.materialize(id).map(|computed| computed.to_string())) - .unwrap_or_default(), - ) + 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 @@ -7117,7 +7100,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, _, types) = facts_and_types( + let (declared_facts, _) = facts( "Widget make();\n\ Widget w;\n\ struct C { Widget member(); };\n\ @@ -7132,29 +7115,28 @@ 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")) }; - let type_of = |name: &str| type_spelling_of(&types, of(name)); - let returns_of = |name: &str| returns_spelling_of(&types, of(name)); - - // **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, _, returning_types) = { - let source = "int (*maker(int a))(int b);\nvoid (*signal(int, void (*)(int)))(int);\n"; - facts_and_types(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!( - returns_spelling_of(&returning_types, fact).as_deref(), + returns_spelling_of(fact).as_deref(), Some(expected), - "`{name}` returns" + "`{name}` returns a pointer to a function — the canonical display of that shape" ); } assert_eq!(returns_of("make").as_deref(), Some("Widget")); @@ -7166,19 +7148,15 @@ void f(int value); // declarator's, so only a `(` **after** the operators is a parenthesized name. assert_eq!( returns_of("paren_name").as_deref(), - Some("const char *"), + Some("const char*"), "a parenthesized declarator name is not a function pointer" ); assert_eq!( type_of("through_pointer").as_deref(), - Some("int (*)(int)"), + 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!(type_of("make"), None, "a function has no type of its own"); assert_eq!( type_of("w").as_deref(), Some("Widget"), @@ -7218,7 +7196,7 @@ void f(int value); // the convention is a word beside the `*` rather than part of it. assert_eq!( returns_of("conventional").as_deref(), - Some("char *"), + Some("char*"), "a pointer whose calling convention stands before the name is still a pointer" ); } diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index 26f097ab..ddc42d58 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -52,9 +52,8 @@ use std::path::{Path, PathBuf}; use cpp_parser::CppSyntaxNode; use crate::index::project::{self, MemberList, ProjectIndex}; -use crate::index::types::{ComputedType, TypeId}; +use crate::index::types::ComputedType; use crate::sema::types::Type; -use crate::summary::DeclaredType; use crate::{Known, ScopeTree}; /// **A file, the index, and a way to read another file** — see the module documentation. @@ -75,10 +74,6 @@ pub struct SemanticModel<'a> { /// shared model is the ordinary case, and a check that had to hold `&mut` would not be able to ask two questions /// while iterating the file. types: project::TypeMemo, - /// **The computed form of the storage handles this request has already materialized.** Materializing copies names - /// and shares children; one member walk asks the same handle many times, and the request, not the index, is the - /// right owner of that cache. - computed: RefCell>, /// **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>>, @@ -117,7 +112,6 @@ impl<'a> SemanticModel<'a> { path, resolver: RefCell::new(resolver), types: project::TypeMemo::default(), - computed: RefCell::new(BTreeMap::new()), members: RefCell::new(BTreeMap::new()), computed_members: RefCell::new(HashMap::new()), shapes: sema::declarations::ShapeTable::new(), @@ -158,26 +152,11 @@ impl<'a> SemanticModel<'a> { ) } - /// **Materialize a stored handle once per request.** The store stays read-only; this is the computation-side - /// cache the query is allowed to own. - pub fn computed_type(&self, id: TypeId) -> Option { - if let Some(found) = self.computed.borrow().get(&id) { - return Some(found.clone()); - } - let found = self.index.types().materialize(id)?; - self.computed.borrow_mut().insert(id, found.clone()); - Some(found) - } - /// **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 new `TypeId` is interned. + /// instantiation bindings applied structurally. No spelling is parsed and no type is interned. pub fn computed_type_of_member(&self, member: &crate::ProjectMember) -> Option { let fact = self.index.member_fact(member)?; - let base = match &fact.type_of { - DeclaredType::Stored(id) => self.computed_type(*id)?, - DeclaredType::Computed(computed) => (**computed).clone(), - DeclaredType::None => return None, - }; + let base = fact.type_of.as_computed()?; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, @@ -188,11 +167,7 @@ impl<'a> SemanticModel<'a> { /// half, for the member functions whose declared type is the one they return. pub fn member_returns(&self, member: &crate::ProjectMember) -> Option { let fact = self.index.member_fact(member)?; - let base = match &fact.returns { - DeclaredType::Stored(id) => self.computed_type(*id)?, - DeclaredType::Computed(computed) => (**computed).clone(), - DeclaredType::None => return None, - }; + let base = fact.returns.as_computed()?; Some(match &member.substitution { Some(substitution) => base.substituted(&substitution.bindings), None => base, diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index f83de661..f9e89b58 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -388,7 +388,9 @@ mod tests { /// `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(ComputedType::from(&sema::types::parse_type_spelling(spelling))) + Known::Yes(ComputedType::from(&sema::types::parse_type_spelling( + spelling, + ))) } fn candidate(parameters: &[&str]) -> Candidate { @@ -528,23 +530,20 @@ mod tests { /// **The parameter types from CST facts**, with no parameter list parsing and no spelling in sight. /// -/// Each fact's type is resolved to the computation layer by the same rule as -/// [`crate::ProjectIndex::parameter_type`]: a summary's or a cooked reading's parameter holds a handle into the one -/// global store and is materialized; a view-synthesized one carries its value and is cloned. `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. +/// 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. /// /// 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: &[crate::index::params::ParameterFact], - types: &crate::index::types::TypeStore, c_style_variadic: bool, ) -> (Vec, bool) { let mut parameters = Vec::new(); let mut variadic = c_style_variadic; for fact in facts { - let Some(type_of) = fact.type_of.as_computed(types) else { + let Some(type_of) = fact.type_of.as_computed() else { continue; }; if fact.pack { @@ -598,7 +597,6 @@ pub(crate) fn more_specialized(mine: &Candidate, theirs: &Candidate) -> bool { fn lowered(source: &str) -> (Vec, bool) { use crate::cache::summary::DeclaredType; use crate::index::params::parameter_facts_of; - use crate::index::types::TypeStore; use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; let tree = CppParser::parse(source, ParserConfig::default()); @@ -608,7 +606,6 @@ fn lowered(source: &str) -> (Vec, bool) { .find_map(CppParamList::cast) .expect("a parameter list"); let mut facts = parameter_facts_of(&list); - let mut types = TypeStore::new(); for fact in &mut facts { let node = fact .declaration @@ -616,9 +613,9 @@ fn lowered(source: &str) -> (Vec, bool) { .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::Stored(types.intern_type(&written)); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(ComputedType::from(&written))); } - parameters_in_facts(&facts, &types, list.is_variadic()) + parameters_in_facts(&facts, list.is_variadic()) } #[test] @@ -642,7 +639,11 @@ fn a_template_argument_pack_inside_a_parameter_is_not_the_parameter_pack() { // **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.len(), 3, "a comparison in a default is not a bracket"); + assert_eq!( + parameters.len(), + 3, + "a comparison in a default is not a bracket" + ); assert_eq!( parameters, vec![ @@ -665,7 +666,6 @@ fn a_template_argument_pack_inside_a_parameter_is_not_the_parameter_pack() { #[test] fn a_parameter_written_with_the_declarations_template_parameter_is_a_parameter() { use crate::index::params::parameter_facts_of; - use crate::index::types::TypeStore; use cpp_parser::{CppAstNode, CppParam, CppParamList, CppParser, ParserConfig}; // The declaration's own template parameter names applied to the **structured** type — the structural form of @@ -684,10 +684,11 @@ fn a_parameter_written_with_the_declarations_template_parameter_is_a_parameter() 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()]); - let mut types = TypeStore::new(); - facts[0].type_of = crate::cache::summary::DeclaredType::Stored(types.intern_type(&written)); + facts[0].type_of = crate::cache::summary::DeclaredType::Computed(std::sync::Arc::new( + ComputedType::from(&written), + )); - let (parameters, _) = parameters_in_facts(&facts, &types, false); + let (parameters, _) = parameters_in_facts(&facts, false); assert_eq!(parameters.len(), 1); assert!( matches!( @@ -708,18 +709,14 @@ fn the_more_specialized_of_two_templates_wins() { ComputedType::from(&parsed) }; let an_argument = |spelling: &str| { - Known::Yes(ComputedType::from( - &sema::types::parse_type_spelling(spelling), - )) + Known::Yes(ComputedType::from(&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![a_written_type("int*")], - false, - "take(T*)".to_string(), - ) - .with_declaration(vec![a_written_type("T*")], 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()]); diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index 680899ac..309b9bf2 100644 --- a/crates/cpp_code_analysis/src/sema/render.rs +++ b/crates/cpp_code_analysis/src/sema/render.rs @@ -96,7 +96,7 @@ 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*. -/// **The renderer with its type spellings supplied by the caller.** A summary fact has `TypeId`s; the caller owns the +/// **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, @@ -1049,7 +1049,6 @@ mod tests { true, ); let facts = built.facts; - let types = built.types; let fact = facts .iter() .find(|fact| fact.name == name) @@ -1062,16 +1061,8 @@ mod tests { fact, declaration.as_ref(), None, - &|fact: &DeclFact| { - fact.type_of_id() - .and_then(|id| types.materialize(id)) - .map(|computed| computed.to_string()) - }, - &|fact: &DeclFact| { - fact.returns_id() - .and_then(|id| types.materialize(id)) - .map(|computed| computed.to_string()) - }, + &|fact: &DeclFact| fact.type_of.computed().map(|computed| computed.to_string()), + &|fact: &DeclFact| fact.returns.computed().map(|computed| computed.to_string()), ) } diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 914b99a3..09f1e1d2 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -79,7 +79,6 @@ use cpp_parser::CppInitDeclarator; use cpp_parser::CppNameExpr; use cpp_parser::CppParam; use cpp_parser::CppParamList; -use cpp_parser::CppPointerType; use cpp_parser::CppTemplateParam; use cpp_parser::CppTypeId; use cpp_parser::SourceRange; @@ -92,29 +91,6 @@ 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 { @@ -1279,9 +1255,9 @@ impl TypeBindings { /// **`auto` and `decltype(auto)` are placeholders, not names.** /// /// [`parse_type_spelling`] has no context for them: `auto` is not one of the language's builtin words it knows, so a -/// spelling `auto&` becomes a reference to a class *named* `auto`. The storage layer has kinds for the placeholders -/// ([`crate::index::types::TypeKind::Auto`]), and `auto` is never a class a file can declare, so the name is rewritten -/// here before a fact's type is interned. This is the same normalization [`crate::index::types::TypeStore::intern_type`] +/// spelling `auto&` becomes a reference to a class *named* `auto`. The computation layer has a primary for each +/// placeholder (`ComputedType::Primary(PrimaryType::Auto)`), and `auto` is never a class a file can declare, so the +/// name is rewritten here before a fact's type is lowered. This is the same normalization `ComputedType::from(&Type)` /// applies to a parser-built `Type::Builtin { spelling: "auto" }`. pub fn without_placeholders_written_as_names(written: Type) -> Type { match written { @@ -2179,40 +2155,7 @@ 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), - } - }; - } - wrapped + wrap(base, declarator, &inner, name, declares_an_object) } /// **The structured type a parameter declares** — `int n` → `int`, `const std::string& name` → `const std::string&`, @@ -2826,6 +2769,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 => { @@ -2884,190 +2836,143 @@ 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, 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(), + /// One operator the declarator wrote, in reading order. + enum Step { + Pointer, + Reference { rvalue: bool }, + Array { extent: Option }, + 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() { + 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() { - // **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) { + 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 => Type::Pointer { + to: Arc::new(written), + }, + Step::Reference { rvalue } => Type::Reference { + to: Arc::new(written), + rvalue, + }, + Step::Array { extent } => Type::Array { + of: Arc::new(written), + extent, + }, + Step::Parameters(parameters) => Type::Function { + returns: Arc::new(written), + parameters, + }, + }; } - - wrapped.unwrap_or(base) + written } /// The `[4]` of an array declarator, when it is a number this layer can read. @@ -3075,7 +2980,7 @@ fn wrap( /// `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 { +pub(crate) fn array_extent(node: &CppSyntaxNode) -> Option { let text = node.text().to_string(); let inside = text .trim() @@ -3435,7 +3340,7 @@ mod tests { /// **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 `Type::ElaboratedRecord` — rather than - /// dropping it, so a fact that crosses the `TypeStore` and the conversion question both have it and neither reads + /// 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() { diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 9ecb76f0..d14f1cce 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -517,9 +517,9 @@ impl Session { let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(crate::index::types::ComputedType::from( - &a_type, - )), + Known::Yes((a_type, _)) => { + Known::Yes(crate::index::types::ComputedType::from(&a_type)) + } Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -582,7 +582,13 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - facts_with_their_types(build_facts(&view.scopes, &preprocessing, &view.root, &errors, true)) + 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. @@ -657,9 +663,9 @@ impl Session { let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(crate::index::types::ComputedType::from( - &a_type, - )), + Known::Yes((a_type, _)) => { + Known::Yes(crate::index::types::ComputedType::from(&a_type)) + } Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -844,22 +850,15 @@ impl Session { .cmp(&right.fact.file) .then(at(left).cmp(&at(right))) }); - // **The written type of a member built from the buffer's own bindings.** Such a fact carries a - // `ComputedType` rather than a handle, and a rendered array whose extent is a macro or an enumerator prints as - // `int[]` — the dimension is an *expression*, not part of the type. Layout sizes that expression (needs its - // width), so it reads the member's writing back out of the view's tree, once per request. A fact from the - // index keeps the file's spelling in its store, so this is only for the asking file's own members. - let written_types = as_written.as_ref().and_then(|_| { - list.members - .iter() - .any(|member| { - index.member_fact(member).is_some_and(|fact| { - fact.type_of.computed().is_some() - && index.member_path(member) == Some(view.path.as_path()) - }) - }) - .then(|| sema::declarations::DeclarationShapes::of(&view.root)) - }); + // **The written type of a member of the asking file.** A dimension that is a macro or an enumerator is not + // part of the structural type a fact carries (`Point points[COUNT]` is `Point[]` structurally), and layout + // has to evaluate it — so for the file's own members the declaration's written type is read from the tree it + // came from, once per request. A fact from another file falls back to its canonical spelling. + let written_types = list + .members + .iter() + .any(|member| index.member_path(member) == Some(view.path.as_path())) + .then(|| sema::declarations::DeclarationShapes::of(&view.root)); for member in own { let Some(fact) = index.member_fact(member) else { continue; @@ -876,17 +875,21 @@ impl Session { // **The spelling the file wrote**, for a member of the asking file — see `written_types`. let type_of = match (&written_types, fact.type_of.computed().is_some()) { (Some(shapes), true) if index.member_path(member) == Some(view.path.as_path()) => { - sema::resolve::definition_at( - &view.scopes, - &view.root, - fact.name_range.start_offset, - ) - .value() - .filter(|binding| binding.name.text() == fact.name.as_str()) - .and_then(|binding| { - sema::declarations::declared_type_of_with(shapes, &binding) - }) - .unwrap_or(type_of) + // **By name and scope, not by offset.** A fact read from the index holds *file* offsets, and + // this view's tree is the rendering — the two need not agree once a macro has been expanded. + // The scope tree is keyed by the same qualified names the fact carries. + view.scopes + .scope_with_qualified_name(&member.declared_in) + .and_then(|scope| view.scopes.scope(scope)) + .and_then(|data| { + data.bindings.iter().find(|binding| { + binding.name.identifier_text() == Some(fact.name.as_str()) + }) + }) + .and_then(|binding| { + sema::declarations::declared_type_spelling_with(shapes, binding) + }) + .unwrap_or(type_of) } _ => type_of, }; @@ -1510,11 +1513,10 @@ impl Session { // 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 = crate::DeclaredType::Computed(Arc::new( - crate::index::types::ComputedType::from( + fact.type_of = + crate::DeclaredType::Computed(Arc::new(crate::index::types::ComputedType::from( &crate::sema::types::parse_type_spelling(&type_of), - ), - )); + ))); fact.returns = crate::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()); @@ -1677,7 +1679,13 @@ impl Session { .iter() .map(|error| source_range(error.range)) .collect(); - let facts = facts_with_their_types(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 1d3c1520..b1779dad 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -63,7 +63,6 @@ use crate::cuda; use crate::file; use crate::include; use crate::index; -use crate::index::types::TypeStore; use crate::sema; use cpp_parser::every_command; pub mod context; @@ -88,7 +87,7 @@ pub use table::{ }; use crate::sema::symbol::{Known, ScopeKind, ScopeTree}; -use crate::summary::{DeclFact, DeclKind, DeclaredType}; +use crate::summary::{DeclFact, DeclKind}; use crate::{ProjectIndex, ProjectMember}; /// What an item is, in the vocabulary every consumer understands. @@ -235,7 +234,7 @@ pub fn the_include_spelling( impl CompletionItem { /// A declaration, as an item. - fn declared(fact: &DeclFact, file: &Path, types: Option<&TypeStore>) -> CompletionItem { + fn declared(fact: &DeclFact, file: &Path) -> CompletionItem { // An item with no name — a destructor the index could not spell — has nothing to resolve *to*, and an // identity pointing at an empty range would fetch another declaration's documentation. let identity = @@ -252,7 +251,7 @@ impl CompletionItem { _ => fact.name.to_string(), }, snippet: false, - detail: detail_of_with_types(fact, types), + detail: detail_of_with_types(fact), identity, filter: None, fact: Some(fact.clone()), @@ -295,13 +294,8 @@ impl CompletionItem { } /// **A declaration from a header this file does not include**, with the include that would make it usable. - fn unincluded( - fact: &DeclFact, - file: &Path, - inclusion: Inclusion, - types: Option<&TypeStore>, - ) -> CompletionItem { - let mut item = CompletionItem::declared(fact, file, types); + fn unincluded(fact: &DeclFact, file: &Path, inclusion: Inclusion) -> CompletionItem { + let mut item = CompletionItem::declared(fact, file); let line = inclusion.line(); item.detail = Some(format!( "not included — accepting this adds `{}`", @@ -357,30 +351,11 @@ 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. -/// **The row's detail, preferring the stored type handles.** A completion is built from a summary that has been -/// inserted, so its type/return IDs are available; a synthesized fact (a generated member, a display copy) carries its -/// computed value instead. Both are printed here, at the display edge — nothing is parsed. -pub fn detail_of_with_types(fact: &DeclFact, types: Option<&TypeStore>) -> Option { - let displayed = |id| { - types.and_then(|types| { - types - .spelling(id) - .map(str::to_string) - .or_else(|| types.materialize(id).map(|computed| computed.to_string())) - }) - }; - // **The written spelling wins when it exists**, because it is what the reader sees in the declaration; a synthetic - // value is printed as its computed type. - let returns = match &fact.returns { - DeclaredType::Computed(returns) => Some(returns.to_string()), - DeclaredType::Stored(id) => displayed(*id), - DeclaredType::None => None, - }; - let type_of = match &fact.type_of { - DeclaredType::Computed(type_of) => Some(type_of.to_string()), - DeclaredType::Stored(id) => displayed(*id), - DeclaredType::None => None, - }; +/// **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 (returns, fact.parameter_list()) { (Some(returns), Some(parameters)) => Some(format!("{returns} {parameters}")), @@ -817,6 +792,7 @@ pub(crate) fn the_type_after_the_operator( 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 @@ -893,6 +869,7 @@ 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. @@ -1282,10 +1259,11 @@ fn members_of_a_type( continue; } - let (Some(fact), Some(file)) = (index.member_fact(member), index.member_path(member)) else { + let (Some(fact), Some(file)) = (index.member_fact(member), index.member_path(member)) + else { continue; }; - let mut item = CompletionItem::declared(fact, file, Some(index.types())); + let mut item = CompletionItem::declared(fact, file); item.kind = member_kind(index, member, &class); item.replace = replace; @@ -1682,7 +1660,7 @@ fn names( continue; } - let mut item = CompletionItem::declared(fact, file, Some(index.types())); + 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 @@ -1906,7 +1884,6 @@ fn names( fact, &related.file, related.inclusion.clone(), - Some(index.types()), ), }); } @@ -2026,9 +2003,9 @@ fn doc_comments( .filter(|name| !name.is_empty()) .map(ToString::to_string) .collect(); - if let Some(found) = sema::call_syntax::parameter_names_of_fact( - index.parameter_facts_of(path, fact), - ) { + if let Some(found) = + sema::call_syntax::parameter_names_of_fact(index.parameter_facts_of(path, fact)) + { names.extend(found.into_iter().flatten()); } @@ -2519,6 +2496,8 @@ pub fn header_index( #[cfg(test)] mod tests { + use crate::summary::DeclaredType; + use super::*; use crate::DeclModifiers; use crate::FactGuard; @@ -2614,22 +2593,22 @@ mod tests { }), }; assert_eq!( - detail_of_with_types(&fact(Some(builtin("string")), Some("()")), None).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_with_types(&fact(Some(builtin("string")), None), 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_with_types(&fact(None, Some("(int)")), None).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_with_types(&fact(None, None), None), + 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 1a366e43..7c76b55b 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -886,15 +886,10 @@ impl Session { indexed .and_then(|found| { let fact = self.definition_fact(&found)?; - fact.returns_id() - .and_then(|id| self.store.index().types().materialize(id)) - .map(|computed| computed.to_string()) - .or_else(|| { - self.store - .index() - .returns_spelling_of(fact) - .map(|spelled| spelled.to_string()) - }) + self.store + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()) }) .or_else(|| { local.and_then(|found| { @@ -1020,13 +1015,12 @@ impl Session { let Some(fact) = index.member_fact(member) else { return false; }; - // **The parameter's own type, structurally.** A member's list is a fact like any other; the type - // resolves through the one store, 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. + // **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), - index.types(), false, ); let Some(parameter) = parameters.get(at) else { @@ -1080,10 +1074,9 @@ impl Session { 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_of_fact(index.parameter_facts_of( - &chosen_file, - &chosen_fact, - ))? + let name = sema::call_syntax::parameter_names_of_fact( + index.parameter_facts_of(&chosen_file, &chosen_fact), + )? .get(at) .cloned() .flatten()?; diff --git a/crates/cpp_code_analysis/src/session/cook.rs b/crates/cpp_code_analysis/src/session/cook.rs index eeeb25cb..b836c80b 100644 --- a/crates/cpp_code_analysis/src/session/cook.rs +++ b/crates/cpp_code_analysis/src/session/cook.rs @@ -956,32 +956,15 @@ impl Session { built } }; - // **The fact is synthesized for the caller**, so its types cannot stay as handles into this temporary - // summary's local table: the table does not travel with it. The table's written spelling is the one thing the - // caller can still read, so each is converted **once, here**, into the computation layer — the construction - // edge this path is — and the fact keeps the computed value instead. No store is minted and no handle leaks - // out of the summary. - let mut fact = 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 })? .clone(); - let template_parameters = fact.parameters().to_vec(); - let computed = |id: Option| { - id.and_then(|id| summary.types.spelling_for(id.raw())) - .map(|written| { - let parsed = sema::types::parse_type_spelling(written); - let parsed = sema::types::without_placeholders_written_as_names(parsed); - let parsed = sema::types::with_template_parameters(parsed, &template_parameters); - Arc::new(index::types::ComputedType::from(&parsed)) - }) - }; - fact.type_of = computed(fact.type_of.stored_id()) - .map_or(crate::DeclaredType::None, crate::DeclaredType::Computed); - fact.returns = computed(fact.returns.stored_id()) - .map_or(crate::DeclaredType::None, crate::DeclaredType::Computed); Some(fact) } diff --git a/crates/cpp_code_analysis/src/session/memory.rs b/crates/cpp_code_analysis/src/session/memory.rs index d032abb7..fa476f71 100644 --- a/crates/cpp_code_analysis/src/session/memory.rs +++ b/crates/cpp_code_analysis/src/session/memory.rs @@ -139,7 +139,6 @@ impl Session { let (summaries, summary_bytes, cooked_files, cooked_bytes) = self.store.index().accounting(); let declarations = self.store.index().declaration_accounting(); - let types = self.store.index().types().accounting(); let (definitions, definition_bytes) = self .definitions .lock() @@ -222,10 +221,6 @@ impl Session { declarations: declarations.declarations, declarations_with_detail: declarations.with_detail, declaration_detail_bytes: declarations.detail_bytes, - types: types.types, - type_names: types.names, - type_argument_lists: types.argument_lists, - type_store_bytes: types.bytes, cooked_files, cooked_bytes, cooked_budget_bytes: self.store.index().cooked_budget_bytes(), diff --git a/crates/cpp_code_analysis/src/session/semantic.rs b/crates/cpp_code_analysis/src/session/semantic.rs index a893d019..32e4cdaf 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -1052,9 +1052,13 @@ 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 sema::types::Type::Pointer { to } = sema::types::parse_type_spelling(&spelling) + && matches!(*to, sema::types::Type::Function { .. }) + { return true; } let Known::Yes(found) = index.definition(&spelling, declaring) else { @@ -1144,8 +1148,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/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs index 8649b55d..445f8c3f 100644 --- a/crates/cpp_code_analysis/tests/params.rs +++ b/crates/cpp_code_analysis/tests/params.rs @@ -1,20 +1,20 @@ //! 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 interned as a `Type`, and is resolved back -//! to a `ComputedType` 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. +//! 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, TypeStore}; +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 into a fresh store — the way -/// `sema::declarations::DeclarationFacts::fact_for` lowers it. -fn lowered(source: &str) -> (TypeStore, Vec, bool) { +/// 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 @@ -22,7 +22,6 @@ fn lowered(source: &str) -> (TypeStore, Vec, bool) { .find_map(CppParamList::cast) .expect("a parameter list"); let mut facts = parameter_facts_of(&list); - let mut types = TypeStore::new(); for fact in &mut facts { let node = fact .declaration @@ -31,22 +30,17 @@ fn lowered(source: &str) -> (TypeStore, Vec, bool) { 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::Stored(types.intern_type(&written)); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(ComputedType::from(&written))); } - let (parameters, variadic) = parameters_in_facts(&facts, &types, list.is_variadic()); - (types, parameters, variadic) + parameters_in_facts(&facts, list.is_variadic()) } #[test] fn parameter_types_come_from_each_cpp_param() { - let (_types, parameters, variadic) = - lowered("void f(int a, std::pair p, double... rest);\n"); + 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) - ), + matches!(¶meters[0], ComputedType::Primary(PrimaryType::Int)), "`int a` is an `int`, and the name is not part of it: {:?}", parameters[0] ); @@ -62,10 +56,7 @@ fn parameter_types_come_from_each_cpp_param() { "neither the name nor the comma split the arguments" ); assert!( - matches!( - ¶meters[2], - ComputedType::Primary(PrimaryType::Double) - ), + matches!(¶meters[2], ComputedType::Primary(PrimaryType::Double)), "a pack is ranked by its element type: {:?}", parameters[2] ); @@ -74,7 +65,7 @@ fn parameter_types_come_from_each_cpp_param() { #[test] fn a_c_style_ellipsis_is_reported_by_the_list_flag() { - let (_types, parameters, variadic) = lowered("void f(const char* format, ...);\n"); + let (parameters, variadic) = lowered("void f(const char* format, ...);\n"); assert_eq!( parameters.len(), 1, @@ -93,7 +84,7 @@ fn a_c_style_ellipsis_is_reported_by_the_list_flag() { } /// **A parameter written with the declaration's template parameter is structured as one** — the step -/// `sema::declarations::fact_for` performs before interning, pinned on the computation side. +/// `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()); @@ -110,10 +101,9 @@ fn a_parameter_written_with_a_template_parameter_is_structured_as_one() { 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()]); - let mut types = TypeStore::new(); - facts[0].type_of = DeclaredType::Stored(types.intern_type(&written)); + facts[0].type_of = DeclaredType::Computed(std::sync::Arc::new(ComputedType::from(&written))); - let (parameters, variadic) = parameters_in_facts(&facts, &types, false); + let (parameters, variadic) = parameters_in_facts(&facts, false); assert_eq!(parameters.len(), 1); assert!( matches!( diff --git a/crates/cpp_code_analysis/tests/suite/reported_defects.rs b/crates/cpp_code_analysis/tests/suite/reported_defects.rs index d355220c..7de695da 100644 --- a/crates/cpp_code_analysis/tests/suite/reported_defects.rs +++ b/crates/cpp_code_analysis/tests/suite/reported_defects.rs @@ -113,7 +113,9 @@ fn an_anonymous_structs_variable_is_not_a_void() { .map(|fact| { ( &*fact.name, - index.type_spelling_of(fact).map(|spelled| spelled.to_string()), + index + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()), ) }) .collect(); @@ -609,8 +611,8 @@ fn a_member_of_a_template_base_is_substituted_with_the_base_arguments() { .expect("the member comes through the base walk"); assert_eq!( session.index().member_returns_spelling(member).as_deref(), - Some("Node *"), - "the base's `T` is the class it was instantiated with: {member:?}" + 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", diff --git a/crates/cpp_ls/src/handlers/completion/mod.rs b/crates/cpp_ls/src/handlers/completion/mod.rs index 1394a9b3..7e045136 100644 --- a/crates/cpp_ls/src/handlers/completion/mod.rs +++ b/crates/cpp_ls/src/handlers/completion/mod.rs @@ -503,9 +503,7 @@ pub async fn on_completion_resolve( let fact = declaration_in(session, &looked_up, offset, &label); // 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(|fact| detail_of_with_types(fact, Some(session.index().types()))); + 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/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 89583ccc..6e218e19 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1407,6 +1407,9 @@ fn member_markdown( fact: member.fact, }; let displayed = session.index().member_display_fact(member); + if session.index().member_name(member) == "second" { + eprintln!("[member] sub={:?} raw={:?} shown={:?}", member.substitution, session.index().member_fact(member).map(|f| &f.type_of), displayed.as_ref().map(|f| &f.type_of)); + } declaration_markdown_with(session, view, &definition, displayed.as_ref(), None) } @@ -1812,9 +1815,11 @@ fn a_line(session: &Session, fact: &DeclFact) -> String { /// **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 + let shown = index .type_spelling_of(fact) - .map(|spelled| spelled.to_string()) + .map(|spelled| spelled.to_string()); + if fact.name == "priority" { eprintln!("[hover] priority {:?} {:?}", fact.type_of, shown); } + shown } /// [`shown_type_of`] for a function's return type. @@ -2149,6 +2154,9 @@ fn declaration_markdown_with( return code_block("the answer names a file the index does not hold"); }; let found_fact = &found_fact; + if found_fact.name == "second" { + eprintln!("[card] substituted={} type={:?}", substituted.is_some(), found_fact.type_of); + } // **A return type read as a macro's name is corrected here.** `wincon.h` writes // // ```c @@ -2285,6 +2293,10 @@ fn declaration_markdown_with( 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. 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/docs/type-system-redesign.md b/docs/type-system-redesign.md index 0ffccf17..5807f80e 100644 --- a/docs/type-system-redesign.md +++ b/docs/type-system-redesign.md @@ -15,7 +15,6 @@ The storage layer owns immutable data and small handles into it: 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 -TypeId an identity for one type in one TypeStore ParamsId an identity for one parameter list in one ParamsStore SyntaxId a CST node identity, valid with the tree it came from ``` @@ -23,12 +22,11 @@ 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 `TypeId` is never useful on its own. It must be resolved through its owning `TypeStore`. - A `DeclFactId` is never useful on its own. It must be resolved through its owning fact arena. -- No second/local `TypeStore` is created for a computed result. A local store would make - `TypeId(3)` alias the global `TypeId(3)`. -- Persisted records never store run-local `FileId`/`DeclFactId`/`TypeId` as if they were stable - across runs. They store their own relative keys and are rebound on load. +- **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 @@ -39,14 +37,9 @@ ComputedType an owned, structured type; names are cooked, children are shar ResolvedMember a member row whose types are computed, not spelled ``` -`ComputedType` is produced from storage exactly once per request: - -```text -TypeId + TypeStore -> ComputedType -``` - -It is then passed through inference, overload ranking, conversion checks, member lookup, alias -substitution, and so on. There is **no** `TypeId -> spelling -> parse` step in this layer. +`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 @@ -126,25 +119,23 @@ The two type fields are one enum, because a fact holds either kind of answer: ```rust enum DeclaredType { None, - Stored(TypeId), // valid only in the one global TypeStore - Computed(Arc), // a query-synthesized value; NO TypeId exists + Computed(Arc), // the value itself; no id, no arena } ``` -There is no `type_of: Option>` and no `returns: Option>`. There is also **no second -`TypeStore` and no arena tag**: `Stored` is always a handle into the one global store, and `Computed` is a -value for which no `TypeId` is invented — an ID from a second store would silently alias the global one. +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 type that is needed for display is materialized: +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 +index.computed_type_of(fact) // -> Option (a clone of the value) +index.type_spelling_of(fact) // -> canonical display ``` -A fact with no written type has `DeclaredType::None`. A fact built from a temporary/view arena or synthesized -by a query carries `DeclaredType::Computed` — the value the query already has — rather than a handle into a -store that does not travel with it; it never gets a local store. - ## 4. `ProjectMember` `ProjectMember` is a small row: @@ -189,14 +180,13 @@ impl SemanticModel<'_> { } ``` -The base type is materialized from the fact arena's `TypeStore`, then the member substitution is -applied structurally: +The base type is the value on the member's fact, cloned and then substituted structurally: ```rust -base.substituted(&substitution.bindings) +fact.type_of.as_computed()?.substituted(&substitution.bindings) ``` -No spelling is parsed. +No spelling is parsed and no table is consulted. ### 4.2 Substitution @@ -226,13 +216,12 @@ the substitution cannot be a field on `MemberList`. `SemanticModel` owns the per-request caches: ```text -computed_types: BTreeMap<(FileId, TypeId), ComputedType> member_types: HashMap<(FactRef, SubstitutionId?), ComputedType> members: HashMap ``` -Keys use `FileId`/`TypeId` pairs so two files' local handles cannot collide. The index owns no -substituted member cache and no recomputation cache. +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 @@ -279,19 +268,19 @@ in the index's synthetic arena, and `facts_with_their_types` clears the handle), 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: a summary's or a cooked -reading's parameter holds `Stored` (lowered from its own `CppParam` node at construction), and a parameter a query -synthesized from a view holds `Computed` — no `TypeId` is invented and no second store is minted. -`ProjectIndex::parameter_type` is the resolver both kinds share; it answers a `ComputedType`, and nothing below it -parses a parameter list. +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` beside its own `TypeTable`, imported at `insert_cooked`, because the -rendering's facts name handles in the rendering's table. A fact a query synthesized — a buffer's member +`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. @@ -341,7 +330,7 @@ list-level substitution applying to members from different bases - `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 materialized `ComputedType`s by `(FileId, TypeId)`. +- `SemanticModel` caches substituted member types by `FactRef`; the fact already holds a `ComputedType`. ### Phase 3: types @@ -369,7 +358,7 @@ plus static guards: no ParserConfig::default() parse outside whole-file entry points no `DeclFact.type_of` / `DeclFact.returns` strings no `PathBuf` in ProjectMember/ProjectDefinition/Candidate -no second TypeStore +no TypeStore/TypeId/TypeTable interning for facts or parameters ``` Each phase boundary must be green. Within a phase, intermediate commits may be red. From 80b109e26d2cd898a5a1ca1b5e5686a62da0fb80 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 13:50:23 +0800 Subject: [PATCH 082/102] refactor(types): delete the duplicate semantic Type enum ComputedType is now the only type definition. sema/types.rs keeps only the CST/spelling reader; parse_type_spelling returns ComputedType, and semantics (convertible_to, decay, qualifiers, substitution, class_name, display) moved onto ComputedType in index/types/semantics.rs and compute.rs. TypeOf/to_sema_type/From<&Type> are gone; TypeIds were already gone. All callers migrated. ComputedType remains 32 bytes. Workspace tests (3615 passed) and clippy pass. Remaining parse_type_spelling sites consume text that entered as text (syntax/display/macro/config), not a second type model. --- .../src/index/project/aliases.rs | 10 +- .../src/index/project/bases.rs | 10 +- .../src/index/project/calls.rs | 111 +- .../src/index/project/deductions.rs | 89 +- .../src/index/project/macro_walk.rs | 14 +- .../src/index/project/member_facts.rs | 12 +- .../src/index/project/members.rs | 66 +- .../src/index/project/mod.rs | 5 +- .../src/index/project/queries.rs | 2 +- .../src/index/project/substituted.rs | 23 +- .../src/index/project/type_of.rs | 185 +- .../src/index/types/compute.rs | 357 ++-- .../cpp_code_analysis/src/index/types/mod.rs | 9 +- .../src/index/types/semantics.rs | 577 ++++++ crates/cpp_code_analysis/src/lib.rs | 2 +- .../src/sema/builtins/mod.rs | 4 +- .../src/sema/builtins/traits.rs | 11 +- .../src/sema/builtins/transforms.rs | 2 +- .../src/sema/check/argument_count.rs | 11 +- .../src/sema/check/assign_type_check.rs | 15 +- .../src/sema/check/concept_not_satisfied.rs | 41 +- .../src/sema/check/deref_type_check.rs | 14 +- .../cpp_code_analysis/src/sema/check/mod.rs | 59 +- .../src/sema/check/param_type_check.rs | 35 +- .../src/sema/check/return_type_mismatch.rs | 4 +- .../src/sema/check/test/undefined_field.rs | 2 +- .../src/sema/check/undefined_name.rs | 18 +- .../cpp_code_analysis/src/sema/constraint.rs | 2 +- crates/cpp_code_analysis/src/sema/convert.rs | 97 +- .../src/sema/declarations.rs | 150 +- .../cpp_code_analysis/src/sema/deduction.rs | 6 +- crates/cpp_code_analysis/src/sema/model.rs | 9 +- crates/cpp_code_analysis/src/sema/overload.rs | 22 +- crates/cpp_code_analysis/src/sema/render.rs | 10 +- crates/cpp_code_analysis/src/sema/types.rs | 1621 +++-------------- crates/cpp_code_analysis/src/session/calls.rs | 13 +- .../src/session/completion/mod.rs | 11 +- crates/cpp_code_analysis/src/session/inlay.rs | 2 +- .../cpp_code_analysis/src/session/semantic.rs | 5 +- .../src/session/signature.rs | 11 +- crates/cpp_code_analysis/src/session/units.rs | 14 +- crates/cpp_code_analysis/tests/params.rs | 4 +- crates/cpp_code_analysis/tests/suite/types.rs | 124 +- crates/cpp_ls/src/handlers/hover/mod.rs | 12 +- 44 files changed, 1664 insertions(+), 2137 deletions(-) create mode 100644 crates/cpp_code_analysis/src/index/types/semantics.rs diff --git a/crates/cpp_code_analysis/src/index/project/aliases.rs b/crates/cpp_code_analysis/src/index/project/aliases.rs index 9265a0d6..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, diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 97d17145..fefaf05c 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -328,7 +328,7 @@ pub(crate) fn fact_from_binding_with( ) -> SynthesizedFact { let _ = root; // **The two types this path can state, lowered structurally once.** The readers below answer a - // [`crate::sema::types::Type`] from the buffer's own syntax; the fact then carries the immutable + // [`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 = @@ -350,10 +350,10 @@ pub(crate) fn fact_from_binding_with( // 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| { + let lower = |written: Option| { written.map_or(DeclaredType::None, |written| { let written = sema::types::with_template_parameters(written, &template_parameters); - DeclaredType::Computed(Arc::new(ComputedType::from(&written))) + DeclaredType::Computed(Arc::new(written)) }) }; let returns_written = written_returns.is_some(); @@ -382,7 +382,7 @@ pub(crate) fn fact_from_binding_with( && 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(ComputedType::from(&written))); + parameter.type_of = DeclaredType::Computed(Arc::new(written)); } } parameters.into_boxed_slice() @@ -711,7 +711,7 @@ pub(crate) fn lookup_names>(bases: &[B]) -> 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 76a8e267..5145dbbd 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -183,12 +183,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, @@ -207,7 +207,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()) @@ -242,7 +242,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(); @@ -301,7 +301,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() @@ -374,7 +374,7 @@ 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, @@ -400,7 +400,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(), )); } @@ -428,16 +428,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( + crate::index::types::QualifiedType { + of: Arc::new(element), + is_const: true, + is_volatile: false, + }, + ))); + let array = Arc::new(ComputedType::Array { of: element, extent: None, }); return Known::Yes(( - Type::Reference { + ComputedType::Reference { to: array, rvalue: false, }, @@ -714,8 +717,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, @@ -830,9 +833,9 @@ pub(crate) fn the_return_the_overloads_agree_on( /// 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( - parameters: Option<&[crate::index::types::ComputedType]>, + parameters: Option<&[ComputedType]>, variadic: bool, - argument_types: &[Type], + argument_types: &[ComputedType], how_many_arguments: usize, ) -> bool { // **A declaration with nothing recorded has no vote.** It cannot be refused either, so it is skipped rather @@ -863,8 +866,8 @@ pub(crate) fn a_candidate_that_can_be_called_this_way( .all(|(parameter, argument)| { // **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.to_sema_type(); - !sema::convert::conversion_to(argument, &target, None, |_| None).is_refused() + let target = parameter; + !sema::convert::conversion_to(argument, target, None, |_| None).is_refused() }) } @@ -896,7 +899,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(), @@ -931,7 +934,7 @@ pub(crate) fn iterator_element_type( Some(Known::Yes((parse_type_spelling(&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) @@ -1134,14 +1137,12 @@ pub(crate) fn declaration_of_a_callee( ) }) .collect(); - let explicit_arguments: Vec = call + let explicit_arguments: Vec = call .children() .next() .map(|callee| written_template_arguments(&callee)) .unwrap_or_default() - .iter() - .map(crate::index::types::ComputedType::from) - .collect(); + .to_vec(); if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments) && let Some(binding) = bindings.get(chosen) @@ -1433,14 +1434,12 @@ pub(crate) fn the_declaration_the_arguments_pick( }) .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(crate::index::types::ComputedType::from) - .collect(); + .to_vec(); let chosen = the_one_the_arguments_select(&types, &candidates, &explicit_arguments)?; let candidate = candidates.get(chosen)?; Some((candidate.fact.clone(), candidate.file.clone())) @@ -1477,7 +1476,7 @@ pub(crate) fn the_name_without_its_arguments(written: &str) -> &str { written } /// **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 `Type`; this converts the representation and parses nothing. +/// 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, @@ -1486,7 +1485,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 @@ -1503,9 +1502,7 @@ pub(crate) fn the_types_of_the_arguments( argument, 0, ) { - Known::Yes((type_of, _)) => Known::Yes( - crate::index::types::ComputedType::from(&type_of), - ), + Known::Yes((type_of, _)) => Known::Yes(type_of), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), } @@ -1581,9 +1578,9 @@ impl CandidateDeclaration { /// 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], + types: &[Known], candidates: &[CandidateDeclaration], - explicit_arguments: &[crate::index::types::ComputedType], + 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 @@ -1681,37 +1678,37 @@ pub(crate) fn the_one_the_arguments_select( /// `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: &crate::index::types::ComputedType) -> Option { +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 { - crate::index::types::ComputedType::Primary(primary) => { + ComputedType::Primary(primary) => { width_of_a_name(primary.spelling(), &mut wide, &mut narrow); } - crate::index::types::ComputedType::TemplateParameter(name) => { + ComputedType::TemplateParameter(name) => { width_of_a_name(name, &mut wide, &mut narrow); } - crate::index::types::ComputedType::Named(name) => { + ComputedType::Named(name) => { width_of_a_name(name, &mut wide, &mut narrow); } - crate::index::types::ComputedType::Generic(generic) => { + ComputedType::Generic(generic) => { width_of_a_name(&generic.name, &mut wide, &mut narrow); pending.extend(generic.arguments.iter()); } - crate::index::types::ComputedType::Pointer(to) - | crate::index::types::ComputedType::Pack(to) - | crate::index::types::ComputedType::ElaboratedRecord { of: to, .. } => { + ComputedType::Pointer(to) + | ComputedType::Pack(to) + | ComputedType::ElaboratedRecord { of: to, .. } => { pending.push(to) } - crate::index::types::ComputedType::Reference { to, .. } - | crate::index::types::ComputedType::Array { of: to, .. } => pending.push(to), - crate::index::types::ComputedType::Function(function) => { + ComputedType::Reference { to, .. } + | ComputedType::Array { of: to, .. } => pending.push(to), + ComputedType::Function(function) => { pending.push(&function.returns); pending.extend(function.parameters.iter()); } - crate::index::types::ComputedType::Qualified(qualified) => pending.push(&qualified.of), + ComputedType::Qualified(qualified) => pending.push(&qualified.of), } } if wide { @@ -1878,7 +1875,7 @@ pub(crate) fn a_members_answer_as_a_type( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, + class_type: &ComputedType, returns: &str, ) -> String { // **An alias has no parameters of its own; its target has them.** `std::string` is @@ -1916,16 +1913,16 @@ pub(crate) fn a_members_answer_as_a_type( // **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 = crate::index::types::ComputedType::named( + let resolved = ComputedType::named( qualified, target.arguments().to_vec(), - ) - .to_sema_type(); + ); class_type = match class_type.is_const() && !resolved.is_const() { - true => Type::Qualified { + true => ComputedType::Qualified(Arc::new(crate::index::types::QualifiedType { of: Arc::new(resolved), - qualifiers: sema::types::Qualifiers::CONST, - }, + is_const: true, + is_volatile: false, + })), false => resolved, }; } @@ -2040,7 +2037,7 @@ fn a_reference_resolved_through_its_value_type( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, + class_type: &ComputedType, member: &str, target: &str, parameters: &[String], diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index eed30b77..ae73f5b5 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -34,7 +34,7 @@ pub(crate) fn range_for_element_type( path: &Path, named: &NamedDeclaration, depth: usize, -) -> Option> { +) -> Option> { let NamedDeclaration::Here(binding) = named else { return None; }; @@ -111,7 +111,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 +125,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. @@ -284,7 +284,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 +422,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 { @@ -604,7 +604,7 @@ fn the_alternatives_a_visit_hands( // 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 = crate::index::types::ComputedType::from(&type_of); + let mut resolved = type_of.clone(); for _ in 0..4 { let Some(name) = resolved.class_name().map(str::to_string) else { break; @@ -672,13 +672,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 { @@ -756,7 +756,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, @@ -814,9 +814,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" { @@ -828,7 +830,7 @@ 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 { +pub(crate) fn strip_a_leading_const(type_of: &ComputedType) -> ComputedType { let written = type_of.to_string(); match written.strip_prefix("const ") { Some(rest) => parse_type_spelling(rest), @@ -837,7 +839,7 @@ pub(crate) fn strip_a_leading_const(type_of: &Type) -> Type { } /// **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 { +pub(crate) fn element_of_the_element(element: &ComputedType) -> Option { let written = element_of(element, 0)?; Some(parse_type_spelling(&written)) } @@ -855,7 +857,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(); @@ -909,10 +911,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, } } @@ -921,17 +923,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.to_string()), _ => None, }; }; @@ -998,7 +1000,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 @@ -1214,7 +1216,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 @@ -1360,18 +1362,17 @@ pub(crate) fn is_a_placeholder(written: &str) -> bool { ) } -pub(crate) fn what_a_call_has_in(index: &ProjectIndex, 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())), + 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()) - .map(|returns| returns.to_sema_type()), + .filter(|returns| !returns.is_a_placeholder()), } } @@ -1420,7 +1421,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 { @@ -1490,8 +1491,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", @@ -1624,13 +1627,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.to_string()), + _ => None, + }; + } }; let plain = name.rsplit("::").next().unwrap_or(name); @@ -1763,11 +1770,11 @@ pub(crate) fn is_an_identifier(segment: &str) -> bool { pub(crate) fn deduce_the_parameters>( names: &[N], written_list: Option<&str>, - argument_types: &[Type], -) -> Vec { - let mut deduced: Vec = names + argument_types: &[ComputedType], +) -> Vec { + let mut deduced: Vec = names .iter() - .map(|name| Type::named(name.as_ref())) + .map(|name| ComputedType::named(name.as_ref(), Vec::new())) .collect(); if names.is_empty() || argument_types.is_empty() { return deduced; 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 7f8af514..560ae9a6 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -946,7 +946,7 @@ impl ProjectIndex { let fact = self.member_fact(member)?; let base = self.computed_type_of(fact)?; Some(match &member.substitution { - Some(substitution) => base.substituted(&substitution.bindings), + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), None => base, }) } @@ -957,7 +957,7 @@ impl ProjectIndex { let fact = self.member_fact(member)?; let base = self.computed_returns_of(fact)?; Some(match &member.substitution { - Some(substitution) => base.substituted(&substitution.bindings), + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), None => base, }) } @@ -1391,7 +1391,7 @@ impl ProjectIndex { &self, path: &Path, expression: &CppSyntaxNode, - ) -> Option> { + ) -> Option> { let key = the_type_key(path, expression); let remembered = self .type_answers @@ -1422,7 +1422,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() { @@ -2388,8 +2388,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 /// @@ -3862,7 +3862,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( 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 59723b8d..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 { diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 352a29db..e45888bf 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -161,7 +161,7 @@ pub(crate) fn member_across_files_with( /// /// `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 @@ -367,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() @@ -437,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( @@ -499,8 +496,8 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( let class_as_written = match &declared { Some(declaration) => index .definition_fact(declaration) - .map_or_else(|| name.clone(), |fact| fact.qualified_name()), - None => name.clone(), + .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 @@ -516,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("::") @@ -553,7 +547,7 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( return None; } - let mut agreed: Option> = None; + let mut agreed: Option> = None; for constructor in listed .members .iter() @@ -567,8 +561,8 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( ); // 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; @@ -580,10 +574,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. @@ -601,8 +592,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()) @@ -621,9 +612,7 @@ pub(crate) fn the_pointee_of_a_handle( }; // **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) - .map(|computed| computed.to_sema_type())?; + let written_type = index.computed_type_of(&fact)?; let bindings = member_bindings(index, scopes, root, path, class, arguments); let finished = bindings.applied_to(&written_type); // **A nested spelling is followed**, which is the ordinary shape in the standard library: `shared_ptr` inherits @@ -648,18 +637,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()); } @@ -681,10 +677,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(), } } @@ -707,8 +703,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); diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index f5072de4..1dae2589 100644 --- a/crates/cpp_code_analysis/src/index/project/mod.rs +++ b/crates/cpp_code_analysis/src/index/project/mod.rs @@ -46,7 +46,8 @@ use crate::Visibility; use crate::file::paths::normalize_path; use crate::include::graph::Marked; use crate::preprocess::directive::IncludeForm; -use crate::sema::types::{Type, TypeBindings, parse_type_spelling}; +use crate::index::types::ComputedType; +use crate::sema::types::{TypeBindings, parse_type_spelling}; use crate::summary::{DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, MacroFact}; use crate::symbol::{Known, UnknownReason}; @@ -586,7 +587,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, diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index bf63b294..71f214f5 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -680,7 +680,7 @@ pub(crate) fn the_overload_a_call_names( .iter() .map(|argument| { match type_of_expression(index, declaring, scopes, root, path, argument, 0) { - Known::Yes((found, _)) => Some(ComputedType::from(&found)), + Known::Yes((found, _)) => Some(found), _ => None, } }) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index d31e3207..60fa300e 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -4,6 +4,7 @@ //! `names_define_static_array`) that the member and call walks rely on. use super::*; +use crate::sema::types::TypeSubstitutions; use crate::DeclFact; use crate::DeclKind; use crate::FileView; @@ -39,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; @@ -63,22 +64,22 @@ 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( + defaults.push(parsed.substituted(&TypeSubstitutions::new( &names, &written_arguments, ))); } let substitutions = - sema::types::TypeSubstitutions::with_defaults(&names, &written_arguments, &defaults); + 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. @@ -345,7 +346,7 @@ fn substituted_members_with( }; let parsed = parse_type_spelling(&written); let parsed = sema::types::with_template_parameters(parsed, &names); - bindings.push((name.clone(), an_argument_as_a_type(&ComputedType::from(&parsed)))); + bindings.push((name.clone(), an_argument_as_a_type(&parsed))); } bindings } @@ -371,7 +372,7 @@ fn substituted_members_with( /// **One structured template argument as the type it names.** /// -/// `read_template_arguments` answers [`ComputedType::Named`] for an argument the tree gave no typed node — in some +/// `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 @@ -402,14 +403,14 @@ impl MemberSubstitution { if bindings.iter().any(|(taken, _)| taken == name) { continue; } - bindings.push((name.clone(), value.substituted(&new.bindings))); + 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(&new.bindings))); + alias_bindings.push((name.clone(), value.substituted_by_bindings(&new.bindings))); } let mut stages = existing.stages.clone(); stages.extend(new.stages.iter().cloned()); 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 52a04bf0..7cb2b7fa 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -5,6 +5,7 @@ //! expensive so that a completion or a diagnostic asking twice pays once. use super::*; +use crate::sema::types::TypeSubstitutions; use crate::Binding; use crate::BindingKind; use crate::DeclFact; @@ -54,13 +55,11 @@ 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 parser-facing type of a fact**, from its stored handle or its synthetic computed value. This is the -/// transition bridge for the inference engine: the fact's type is materialized once (no spelling, no store write) and -/// converted structurally to the shape the engine speaks. There is no spelling parse on this path. -pub(crate) fn the_type_of_a_fact(index: &ProjectIndex, fact: &DeclFact) -> Option { - index - .computed_type_of(fact) - .map(|computed| computed.to_sema_type()) +/// **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. @@ -141,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`. @@ -166,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>, @@ -175,7 +174,7 @@ 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() } @@ -242,7 +241,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), @@ -306,7 +305,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(); @@ -445,12 +444,12 @@ pub(crate) fn type_of_expression_inner( .find(|declared| declared.fact.kind == DeclKind::Function) && let Some(returns) = index.computed_returns_of(declared.fact) { - return Known::Yes((returns.to_sema_type(), path.to_path_buf())); + 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. @@ -523,7 +522,7 @@ 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 @@ -532,7 +531,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))), }; } @@ -550,7 +549,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))), @@ -663,7 +662,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 @@ -893,7 +892,7 @@ pub(crate) fn type_of_expression_inner( path, &left, depth + 1, - ) && matches!(left_class, Type::Named { .. }) + ) && matches!(left_class, ComputedType::Named(_) | ComputedType::Generic(_)) && let Some(returns) = operator_returns_of( index, declaring, @@ -911,7 +910,7 @@ pub(crate) fn type_of_expression_inner( 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( @@ -1012,7 +1011,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)) } @@ -1033,7 +1037,9 @@ pub(crate) fn type_of_expression_inner( // **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 { .. } => { + 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 @@ -1069,13 +1075,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), @@ -1111,7 +1112,12 @@ pub(crate) fn type_of_expression_inner( ); return match operand_type { Known::Yes((type_of, file)) => { - if matches!(type_of, Type::Named { .. } | Type::TemplateParameter { .. }) + if matches!( + type_of, + ComputedType::Named(_) + | ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) + ) && let Some(returns) = operator_returns_of( index, declaring, @@ -1125,7 +1131,7 @@ pub(crate) fn type_of_expression_inner( return Known::Yes((parse_type_spelling(&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)) } @@ -1213,10 +1219,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 @@ -1228,7 +1234,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, @@ -1508,7 +1514,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 @@ -1517,7 +1523,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(); @@ -1680,11 +1686,11 @@ pub(crate) fn declared_class( .map(|(parameter, argument)| { ( parameter.clone(), - ComputedType::from(&parse_type_spelling(argument)), + parse_type_spelling(argument), ) }) .collect(); - let target = target.substituted(&bindings); + let target = target.substituted_by_bindings(&bindings); if let Some(named) = target.class_name() { return Some(named.to_string()); } @@ -1782,7 +1788,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). @@ -1816,23 +1822,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 @@ -1843,7 +1840,7 @@ 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 { @@ -1905,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<…>`. @@ -1934,7 +1931,7 @@ pub(crate) fn operator_returns_of( scopes: &ScopeTree, root: &CppSyntaxNode, path: &Path, - class_type: &Type, + class_type: &ComputedType, operator: &str, ) -> Option { operator_returns_of_with_arguments( @@ -1959,9 +1956,9 @@ 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, @@ -1994,19 +1991,19 @@ pub(crate) fn operator_returns_of_with_arguments( // 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 `Type`s, converted to the + // 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(), ComputedType::from(argument))) + .map(|(parameter, argument)| (parameter.clone(), argument.clone())) .collect(); let target = if bindings.is_empty() { target } else { - target.substituted(&bindings) + 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 @@ -2068,7 +2065,7 @@ pub(crate) fn operator_returns_of_with_arguments( scopes, root, path, - &candidate.to_sema_type(), + candidate, operator, argument_types, argument_count, @@ -2144,7 +2141,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.** // @@ -2185,7 +2182,7 @@ pub(crate) fn operator_returns_of_with_arguments( } let types: Vec> = argument_types .iter() - .map(|argument| Known::Yes(ComputedType::from(argument))) + .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 @@ -2397,7 +2394,7 @@ fn the_members_return( member_file: &Path, parameter_names: &[String], written_arguments: &[String], - argument_types: &[Type], + argument_types: &[ComputedType], ) -> Option { let _ = (index, scopes, root, path); let returns = index @@ -2531,7 +2528,7 @@ fn deduced_returns_of_the_member( file: &Path, parameter_names: &[String], written_arguments: &[String], - argument_types: &[Type], + 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 @@ -2594,7 +2591,7 @@ fn deduced_returns_of_the_member( 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); + TypeSubstitutions::new(fact.parameters(), &deduced_from_the_call); let deduced = sema::declarations::deduced_returns_of_substituted( &declared_in.root, binding, @@ -2953,7 +2950,7 @@ impl NamedDeclaration { index: &ProjectIndex, root: &CppSyntaxNode, scopes: &ScopeTree, - ) -> Option { + ) -> 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 @@ -2983,7 +2980,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| { @@ -3027,7 +3024,7 @@ impl NamedDeclaration { an_unnamed_class_body(&specifiers), ) { (true, Some(_)) if keyed_by_the_declarator => { - Some(Type::named(binding.name.identifier_text()?)) + Some(ComputedType::named(binding.name.identifier_text()?, Vec::new())) } _ => Some(written), } @@ -3038,7 +3035,7 @@ impl NamedDeclaration { let _ = scopes; index .computed_type_of(fact) - .map(|computed| bindings.applied_to(&computed.to_sema_type())) + .map(|computed| bindings.applied_to(&computed)) } } } @@ -3061,9 +3058,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 @@ -3090,7 +3087,7 @@ 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.** // @@ -3107,11 +3104,11 @@ impl NamedDeclaration { sema::declarations::shapes_from(shapes, root), binding, ) - .filter(|returns| !ComputedType::from(returns).is_a_placeholder()) + .filter(|returns| !returns.is_a_placeholder()) { Some(returns) => returns, None => { - let substitutions = sema::types::TypeSubstitutions::new( + let substitutions = TypeSubstitutions::new( &names_for_the_call, written_arguments, ); @@ -3140,7 +3137,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 @@ -3161,7 +3158,7 @@ impl NamedDeclaration { let returns = match what_a_call_has_in(index, fact) { Some(returns) => returns, None => { - let substitutions = sema::types::TypeSubstitutions::new( + let substitutions = TypeSubstitutions::new( fact.parameters(), written_arguments, ); @@ -3226,7 +3223,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) }; @@ -3244,12 +3241,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, }; @@ -3374,12 +3366,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 @@ -3394,10 +3386,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, …>>` — @@ -3595,8 +3587,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; @@ -3641,11 +3633,11 @@ pub(crate) fn a_trait_alias_resolved( if let Some(written) = argument.or(default) { bindings.push(( smol_str::SmolStr::new(parameter.as_str()), - ComputedType::from(&parse_type_spelling(&written)), + parse_type_spelling(&written), )); } } - Some(target.substituted(&bindings).to_sema_type()) + Some(target.substituted_by_bindings(&bindings)) } /// The type a declaration was written with — or, where it wrote `auto`, the type its **initializer** has. /// @@ -3683,7 +3675,7 @@ 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 @@ -3700,7 +3692,7 @@ pub(crate) fn declared_type( .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(index, root, scopes); @@ -3732,8 +3724,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 @@ -3796,7 +3787,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/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 8d9fabbf..208193cb 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -29,7 +29,7 @@ use std::sync::Arc; use smol_str::SmolStr; -use crate::sema::types::{Qualifiers, RecordTag, Type}; +use super::semantics::RecordTag; /// **One of the language's own fundamental types.** /// @@ -270,9 +270,12 @@ impl ComputedType { } /// 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) => Some(name.as_str()), + 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(), @@ -324,16 +327,28 @@ impl ComputedType { } } + /// 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) => Some(to), + 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 exactly `void`? The C spelling of an empty parameter list, and the answer to "is there a value here". + /// Is this `void` — the incomplete type no object can have? A qualifier is looked through; nothing else is. pub fn is_void(&self) -> bool { - matches!(self, ComputedType::Primary(PrimaryType::Void)) + 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&`, @@ -391,70 +406,13 @@ impl ComputedType { } } - /// **The parser-facing form**, for the transition period. This is a conversion, not a parse: the structure is - /// already known and only its representation changes. Queries should prefer the `ComputedType` methods; this - /// exists because the current type engine still speaks `sema::types::Type`. - pub fn to_sema_type(&self) -> Type { - match self { - ComputedType::Primary(primary) => Type::Builtin { - spelling: primary.spelling().to_string(), - }, - ComputedType::Named(name) => Type::Named { - name: name.to_string(), - arguments: Vec::new(), - }, - ComputedType::Generic(generic) => Type::Named { - name: generic.name.to_string(), - arguments: generic.arguments.iter().map(Self::to_sema_type).collect(), - }, - ComputedType::TemplateParameter(name) => Type::TemplateParameter { - name: name.to_string(), - }, - ComputedType::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { - tag: *tag, - of: Arc::new(of.to_sema_type()), - }, - ComputedType::Pointer(to) => Type::Pointer { - to: Arc::new(to.to_sema_type()), - }, - ComputedType::Reference { to, rvalue } => Type::Reference { - to: Arc::new(to.to_sema_type()), - rvalue: *rvalue, - }, - ComputedType::Array { of, extent } => Type::Array { - of: Arc::new(of.to_sema_type()), - extent: extent.map(|extent| extent as usize), - }, - ComputedType::Function(function) => Type::Function { - returns: Arc::new(function.returns.to_sema_type()), - parameters: function.parameters.iter().map(Self::to_sema_type).collect(), - }, - ComputedType::Pack(of) => Type::Pack { - of: Arc::new(of.to_sema_type()), - }, - 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); - } - Type::Qualified { - of: Arc::new(qualified.of.to_sema_type()), - qualifiers, - } - } - } - } - /// **This type with one name in it replaced** — the structural twin of - /// [`crate::sema::types::Type::replacing`], and the computation layer's step for a class's own **aliases**. + /// [`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 `Type` version follows. + /// 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(), @@ -505,7 +463,7 @@ impl ComputedType { /// **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(&self, bindings: &[(SmolStr, ComputedType)]) -> ComputedType { + pub fn substituted_by_bindings(&self, bindings: &[(SmolStr, ComputedType)]) -> ComputedType { match self { ComputedType::TemplateParameter(name) => bindings .iter() @@ -517,34 +475,34 @@ impl ComputedType { arguments: generic .arguments .iter() - .map(|argument| argument.substituted(bindings)) + .map(|argument| argument.substituted_by_bindings(bindings)) .collect(), })), ComputedType::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { tag: *tag, - of: Arc::new(of.substituted(bindings)), + of: Arc::new(of.substituted_by_bindings(bindings)), }, - ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.substituted(bindings))), + ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.substituted_by_bindings(bindings))), ComputedType::Reference { to, rvalue } => ComputedType::Reference { - to: Arc::new(to.substituted(bindings)), + to: Arc::new(to.substituted_by_bindings(bindings)), rvalue: *rvalue, }, ComputedType::Array { of, extent } => ComputedType::Array { - of: Arc::new(of.substituted(bindings)), + of: Arc::new(of.substituted_by_bindings(bindings)), extent: *extent, }, ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { - returns: Arc::new(function.returns.substituted(bindings)), + returns: Arc::new(function.returns.substituted_by_bindings(bindings)), parameters: function .parameters .iter() - .map(|parameter| parameter.substituted(bindings)) + .map(|parameter| parameter.substituted_by_bindings(bindings)) .collect(), })), - ComputedType::Pack(of) => ComputedType::Pack(Arc::new(of.substituted(bindings))), + 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(bindings)), + of: Arc::new(qualified.of.substituted_by_bindings(bindings)), is_const: qualified.is_const, is_volatile: qualified.is_volatile, })) @@ -553,62 +511,16 @@ impl ComputedType { } } -impl From<&Type> for ComputedType { - /// **The computation-layer form of a semantic `Type`.** No store lookup and no spelling parse: every variant is - /// converted from the structure the query already holds. - fn from(value: &Type) -> ComputedType { - match value { - Type::Builtin { spelling } => ComputedType::from_builtin_spelling(spelling), - Type::Named { name, arguments } => ComputedType::named( - name.as_str(), - arguments.iter().map(ComputedType::from).collect(), - ), - Type::TemplateParameter { name } => ComputedType::TemplateParameter(name.into()), - Type::ElaboratedRecord { tag, of } => ComputedType::ElaboratedRecord { - tag: *tag, - of: Arc::new(ComputedType::from(&**of)), - }, - Type::Pointer { to } => ComputedType::Pointer(Arc::new(ComputedType::from(&**to))), - Type::Reference { to, rvalue } => ComputedType::Reference { - to: Arc::new(ComputedType::from(&**to)), - rvalue: *rvalue, - }, - Type::Array { of, extent } => ComputedType::Array { - of: Arc::new(ComputedType::from(&**of)), - extent: extent.map(|extent| extent as u64), - }, - Type::Function { - returns, - parameters, - } => ComputedType::Function(Arc::new(FunctionType { - returns: Arc::new(ComputedType::from(&**returns)), - parameters: parameters.iter().map(ComputedType::from).collect(), - })), - Type::Pack { of } => ComputedType::Pack(Arc::new(ComputedType::from(&**of))), - Type::Qualified { of, qualifiers } => { - ComputedType::Qualified(Arc::new(QualifiedType { - of: Arc::new(ComputedType::from(&**of)), - is_const: qualifiers.is_const(), - is_volatile: qualifiers.is_volatile(), - })) - } - } - } -} - -impl ComputedType { - /// **A 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. - fn from_builtin_spelling(spelling: &str) -> ComputedType { - match PrimaryType::from_spelling(spelling) { - Some(primary) => ComputedType::Primary(primary), - None => ComputedType::Named(SmolStr::new(spelling.trim())), - } - } -} 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()), @@ -639,8 +551,16 @@ impl fmt::Display for ComputedType { } write!(out, "]") } + // **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) => { - write!(out, "{}(", function.returns)?; + 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, ", ")?; @@ -650,21 +570,83 @@ impl fmt::Display for ComputedType { 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 separators = Vec::new(); + let mut words = Vec::new(); if qualified.is_const { - separators.push("const"); + words.push("const"); } if qualified.is_volatile { - separators.push("volatile"); + words.push("volatile"); } - if separators.is_empty() { + if words.is_empty() { write!(out, "{}", qualified.of) } else { - write!(out, "{} {}", separators.join(" "), qualified.of) + 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('['); + 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. + 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 { "" } + ) } } @@ -767,7 +749,7 @@ mod tests { assert!(parameter.class_name().is_none()); assert_eq!( parameter - .substituted(&[(SmolStr::new("T"), ComputedType::Primary(PrimaryType::Int))]) + .substituted_by_bindings(&[(SmolStr::new("T"), ComputedType::Primary(PrimaryType::Int))]) .to_string(), "int" ); @@ -872,52 +854,93 @@ mod tests { ); } - /// **The builtin aliases fold into their primary, and the ambiguous spellings are recorded here.** The store keeps - /// the written spelling; the computation layer carries the identity. An implementation-specific word is not a - /// primary and is kept as a name so its display survives. + /// **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::from(&Type::builtin("short int")); + 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::from(&Type::builtin("unsigned")), + ComputedType::builtin("unsigned"), ComputedType::Primary(PrimaryType::UnsignedInt) ); assert_eq!( - ComputedType::from(&Type::builtin("decltype(auto)")), + ComputedType::builtin("decltype(auto)"), ComputedType::Primary(PrimaryType::DecltypeAuto) ); assert_eq!( - ComputedType::from(&Type::builtin("auto")), + ComputedType::builtin("auto"), ComputedType::Primary(PrimaryType::Auto) ); - let extension = ComputedType::from(&Type::builtin("__int128")); + 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::from(&Type::builtin("")), + 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 the_parser_bridge_preserves_the_shape() { - let value = ComputedType::Pointer(Arc::new(ComputedType::Reference { - to: Arc::new(ComputedType::named( - "std::vector", - vec![ComputedType::Primary(PrimaryType::Int)], - )), - rvalue: false, - })); - let parser = value.to_sema_type(); - assert_eq!(parser.to_string(), value.to_string()); - assert!( - matches!(parser, Type::Pointer { .. }), - "the outer operator is kept" - ); + 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: Some(4), + }, + 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] @@ -933,14 +956,14 @@ mod tests { } #[test] - fn a_semantic_type_converts_without_the_store() { - let value = Type::Named { - name: "std::vector".to_string(), - arguments: vec![Type::Pointer { - to: Arc::new(Type::builtin("int")), - }], - }; - assert_eq!(ComputedType::from(&value).to_string(), "std::vector"); + 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] @@ -952,7 +975,7 @@ mod tests { ComputedType::Pointer(Arc::new(ComputedType::TemplateParameter(SmolStr::new("T")))), ], ); - let concretely = value.substituted(&[( + let concretely = value.substituted_by_bindings(&[( SmolStr::new("T"), ComputedType::Primary(PrimaryType::Int), )]); diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index 9acd5b25..f45c008a 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -6,14 +6,17 @@ //! query's display copy, or a decoded cache record — without a process-local id beside it. //! //! ```text -//! a declaration's syntax -> Type (the parser's shape) -> ComputedType (the value a fact carries) +//! a declaration's syntax -> ComputedType (the one type definition, built at the parser boundary) //! ``` //! -//! There is no `TypeId`, no interning and no source-spelling side table. Display is +//! 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. +//! `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::{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..228229d1 --- /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 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(super::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, + }, + 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(super::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, + }, + 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 cd5cf164..4611567d 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] 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..ccb55bf2 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,13 @@ 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 }, + ComputedType::Array { extent, .. } => Shape::Array(extent.is_some()), + 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/check/argument_count.rs b/crates/cpp_code_analysis/src/sema/check/argument_count.rs index 0f5fc4db..b30739a1 100644 --- a/crates/cpp_code_analysis/src/sema/check/argument_count.rs +++ b/crates/cpp_code_analysis/src/sema/check/argument_count.rs @@ -174,14 +174,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 + // 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(ComputedType::from(&a_type)), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -288,12 +288,11 @@ fn callees_in_this_file( // 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.map_or_else( + 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()), - |written| ComputedType::from(&written), - )); + 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 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 ce741826..a8fb9630 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 //! @@ -42,6 +42,7 @@ //! 396 ms**, 94% of the layer, paid per keystroke. One walk is what makes this version linear in the file. use super::a_class_can_be_built_from; +use crate::index::types::ComputedType; use super::a_literal_zero; use super::callee_name_of; use crate::DeclKind; @@ -395,12 +396,12 @@ 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() => { + ComputedType::Qualified(qualified) if qualified.is_const => { Some(NotAssignable::Const) } - sema::types::Type::Array { .. } => Some(NotAssignable::AnArray), + ComputedType::Array { .. } => Some(NotAssignable::AnArray), _ => None, } } @@ -426,19 +427,19 @@ fn not_assignable(type_of: &sema::types::Type) -> Option { /// two ways. #[derive(Clone, PartialEq, Eq)] struct Target { - type_of: sema::types::Type, + 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: &crate::index::types::ComputedType, written: &str) -> Option { + fn of(computed: &ComputedType, written: &str) -> Option { if written.trim().is_empty() { return None; } Some(Target { - type_of: computed.to_sema_type(), + type_of: computed.clone(), written: smol_str::SmolStr::new(written.trim()), }) } 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 abfdf6e1..a1def6f5 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 @@ -37,6 +37,7 @@ //! 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::index::types::ComputedType; use crate::DeclKind; use crate::Known; use crate::sema; @@ -95,7 +96,7 @@ 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`. The question is asked of - // the `Type` — structurally for `TemplateParameter`, by the naming convention on a `Named` — not of a + // 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; @@ -249,7 +250,7 @@ impl Concept { /// check quiet, and `None` is what every type the analysis cannot work out answers. fn is_satisfied_by( &self, - passed: &sema::types::Type, + passed: &ComputedType, context: &CheckContext<'_>, ) -> Option { match self { @@ -267,19 +268,19 @@ 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(written) => { - // **The concept's argument, parsed once here.** The conversion below takes the `Type`, not a + // **The concept's argument, parsed once here.** The conversion below takes the `ComputedType`, not a // spelling: the old form wrote the parsed shape back out and parsed it again, which is a second // reader of the same question. C's tag is part of the parsed type now, so nothing is read beside it. let target = sema::types::parse_type_spelling(written); @@ -298,16 +299,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, } } @@ -317,7 +318,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; }; @@ -370,7 +371,7 @@ 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; }; @@ -403,14 +404,14 @@ fn split_at_top_level_commas(text: &str) -> Vec { /// pointer a definite `false` without asking anything. fn derives_from( context: &CheckContext<'_>, - derived: &sema::types::Type, + derived: &ComputedType, base: &str, ) -> 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 @@ -421,7 +422,7 @@ fn derives_from( let index = context.model.index(); let base = the_class_name(base); - let mut waiting = vec![name.clone()]; + let mut waiting = vec![name.to_string()]; let mut seen = std::collections::HashSet::new(); let mut answered = 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/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index 706ee533..ceb8be85 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -94,6 +94,7 @@ use crate::IncludeForm; use crate::Known; use crate::ScopeTree; use crate::file; +use crate::index::types::ComputedType; use crate::sema; use cpp_parser::CppAttributeList; use cpp_parser::CppDeclarator; @@ -517,7 +518,7 @@ impl<'a> CheckContext<'a> { pub fn a_string_literal_in_a_char_pointer_position( &self, expression: &CppSyntaxNode, - target: &sema::types::Type, + target: &ComputedType, ) -> bool { self.is_c() && is_a_string_literal(expression) && is_a_char_pointer(target) } @@ -701,7 +702,7 @@ impl<'a> CheckContext<'a> { pub fn type_of( &self, expression: &CppSyntaxNode, - ) -> Known<(sema::types::Type, std::path::PathBuf)> { + ) -> Known<(ComputedType, std::path::PathBuf)> { self.model.type_of(expression) } @@ -1610,21 +1611,25 @@ fn is_a_string_literal(expression: &CppSyntaxNode) -> bool { /// 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: &sema::types::Type) -> bool { - use sema::types::Type; +fn is_a_char_pointer(type_of: &ComputedType) -> bool { let type_of = match type_of { - Type::Qualified { of, .. } => &**of, + ComputedType::Qualified(qualified) => &qualified.of, other => other, }; // A reference or an array is not a pointer target: `char *&` and `char[]` are different questions. - let Type::Pointer { to } = type_of else { + let ComputedType::Pointer(to) = type_of else { return false; }; let pointee = match &**to { - Type::Qualified { of, .. } => &**of, + ComputedType::Qualified(qualified) => &qualified.of, other => other, }; - matches!(pointee, Type::Builtin { spelling } if spelling == "char" || spelling == "void") + matches!( + pointee, + ComputedType::Primary( + crate::index::types::PrimaryType::Char | crate::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. @@ -1635,36 +1640,35 @@ fn is_a_char_pointer(type_of: &sema::types::Type) -> 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, + 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. - Type::ElaboratedRecord { tag, of } => format!("{} {}", tag.word(), a_spelling_of(of)?), - Type::Pointer { to } => format!("{} *", a_spelling_of(to)?), - Type::Reference { to, rvalue } => format!( + 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 { + ComputedType::Array { of, extent } => match extent { Some(extent) => format!("{}[{extent}]", a_spelling_of(of)?), None => format!("{}[]", a_spelling_of(of)?), }, @@ -1679,7 +1683,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 @@ -1785,7 +1789,7 @@ pub fn a_class_can_be_built_from( fn parameters_that_could_accept( index: &ProjectIndex, parameters: &[crate::index::params::ParameterFact], - value: &sema::types::Type, + 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. @@ -1827,7 +1831,7 @@ fn parameters_that_could_accept( /// /// `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: &crate::index::types::ComputedType) -> Option { +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 @@ -1912,6 +1916,7 @@ fn could_take_an_arithmetic_value(type_of: &crate::index::types::ComputedType) - ComputedType::Qualified(qualified) => { return could_take_an_arithmetic_value(&qualified.of); } + ComputedType::Generic(_) => false, _ => return None, }, ComputedType::Qualified(qualified) => { 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 0e76aacf..0b5cd170 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 @@ -24,7 +24,7 @@ //! `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 `Type` (`Type::ElaboratedRecord`), not a second reading of that text. +//! part of the `ComputedType` (`ComputedType::ElaboratedRecord`), not a second reading of that text. //! //! [`ParameterFact`]: crate::index::params::ParameterFact //! @@ -37,12 +37,13 @@ //! //! # `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. use super::a_class_can_be_built_from; +use crate::index::types::ComputedType; use super::a_literal_zero; use super::a_spelling_of; use super::callee_name_of; @@ -164,7 +165,7 @@ 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 already `Type`s: they are the conversion question's + // 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 @@ -213,7 +214,7 @@ fn member_parameter_lists( }; let Known::Yes(list) = context .model - .members_of_computed(&crate::index::types::ComputedType::from(&a_type)) + .members_of_computed(&a_type) else { return Vec::new(); }; @@ -253,7 +254,7 @@ fn candidates_of_a_list(parameters: &CppParamList) -> Vec { } /// **One candidate parameter, read once at this boundary** — the spelling the declaring file wrote (the finding -/// quotes it) and the [`Type`](sema::types::Type) the conversion question takes, which carries C's tag. +/// 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 @@ -262,7 +263,7 @@ fn candidates_of_a_list(parameters: &CppParamList) -> Vec { #[derive(Clone)] struct CandidateParameter { written: String, - type_of: sema::types::Type, + type_of: ComputedType, } impl CandidateParameter { @@ -281,7 +282,7 @@ impl CandidateParameter { index: &crate::ProjectIndex, parameter: &crate::index::params::ParameterFact, ) -> Option { - let type_of = index.parameter_type(parameter)?.to_sema_type(); + let type_of = index.parameter_type(parameter)?; let written = index.parameter_spelling(parameter)?; Some(Self { written: written.to_string(), @@ -308,14 +309,14 @@ impl CandidateParameter { // `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(&substitution.bindings)); + type_of = type_of.replacing(name, &target.substituted_by_bindings(&substitution.bindings)); } - type_of = type_of.substituted(&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: type_of.to_sema_type(), + type_of, }) } @@ -323,7 +324,7 @@ impl CandidateParameter { /// /// 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: &sema::types::Type) -> Option { + fn from_type(type_of: &ComputedType) -> Option { Some(Self { written: a_spelling_of(type_of)?, type_of: type_of.clone(), @@ -376,7 +377,7 @@ fn check_the_arguments( // **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 (`Type::TemplateParameter`) plus the + // 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; @@ -536,23 +537,23 @@ fn the_index_declares_one( fn a_function_pointer_signature( context: &CheckContext<'_>, 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/return_type_mismatch.rs b/crates/cpp_code_analysis/src/sema/check/return_type_mismatch.rs index 80aa7e4d..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 @@ -80,7 +80,7 @@ impl Check for ReturnTypeMismatch { .index() .returns_spelling_of(fact) .map_or_else(|| computed.to_string(), |written| written.to_string()); - let declared_type = computed.to_sema_type(); + 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 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_name.rs b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs index 0f3390fc..7cc2fb7d 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs @@ -54,12 +54,12 @@ //! coordinate systems, the rendering's and the file's, are not comparable offset by offset). use super::member_access_above; +use crate::index::types::ComputedType; use crate::Known; use crate::ScopeKind; use crate::UnknownReason; use crate::file::coordinates::ReadingOffset; use crate::index; -use crate::sema; use cpp_parser::CppCallExpr; use cpp_parser::CppDeclSpecifierSeq; use cpp_parser::CppDeclaration; @@ -382,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, } } diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index 62633011..63352e74 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -648,7 +648,7 @@ fn the_type_of_a_trait_argument( 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(ComputedType::from(&marked).substituted(bindings)) + Some(marked.substituted_by_bindings(bindings)) } /// An identifier as this layer spells one: letters, digits and `_`, starting with a letter or `_`. diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index b62d5ef4..f08021d3 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -6,8 +6,8 @@ //! //! **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 [`Type`]; this module never parses the same spelling again. C's tag -//! (`struct point`) is not an exception: the type carries it as [`Type::ElaboratedRecord`] (see +//! 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 @@ -16,7 +16,8 @@ //! a template parameter, a dependent type — all of those are `Unknown`, and all of them are silent. use crate::Known; -use crate::sema::types::{RecordTag, Type}; +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.** @@ -42,12 +43,12 @@ impl Conversion { } /// **Is this a pointer, through any qualifiers?** — `const char*`, `T* const`, `T*`. -fn a_pointer(type_of: &Type) -> bool { +fn a_pointer(type_of: &ComputedType) -> bool { match type_of { - Type::Pointer { .. } => true, - 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. - Type::Array { .. } => true, + ComputedType::Array { .. } => true, _ => false, } } @@ -58,20 +59,21 @@ fn a_pointer(type_of: &Type) -> bool { /// 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: &Type) -> &Type { +fn the_referent(type_of: &ComputedType) -> &ComputedType { match type_of { - Type::Reference { to, .. } | Type::Qualified { of: to, .. } => the_referent(to), + ComputedType::Reference { to, .. } => the_referent(to), + ComputedType::Qualified(qualified) => the_referent(&qualified.of), other => other, } } /// **Can a value of `from` be used where the parsed `target` is expected?** /// -/// `target` is a [`Type`], not a spelling: nothing in this function parses a string, and the +/// `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 [`Type::ElaboratedRecord`] reached through a pointer, +/// **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 @@ -88,8 +90,8 @@ fn the_referent(type_of: &Type) -> &Type { /// `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: &Type, - target: &Type, + from: &ComputedType, + target: &ComputedType, family: Option, answer_the_class_question: impl FnOnce(&str) -> Option, ) -> Conversion { @@ -99,8 +101,7 @@ pub fn conversion_to( // capability lookup of that shape. if matches!( target, - Type::Builtin { spelling } - if spelling == "bool" || spelling == "_Bool" + ComputedType::Primary(crate::index::types::PrimaryType::Bool) ) && a_pointer(from) { return Conversion::Implicit; @@ -109,7 +110,7 @@ pub fn conversion_to( // **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 **tag on the target type** - // ([`Type::ElaboratedRecord`]), not a spelling beside it: a name alone is not a type — `typedef int point;` + // ([`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. @@ -133,13 +134,13 @@ pub fn conversion_to( // **The class case**, which the relation cannot answer: it lives in the type algebra and never sees a constructor. let bare = the_referent(target); - // **A template parameter is not a class to ask about.** `Type::TemplateParameter` is the structural answer: the + // **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, Type::TemplateParameter { .. }) { + if matches!(bare, ComputedType::TemplateParameter(_)) { return Conversion::Unknown; } let Some(class) = bare.class_name() else { @@ -148,7 +149,7 @@ pub fn conversion_to( // **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 [`Type::class_name`](Type::class_name)**, never a type + // 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. @@ -165,7 +166,7 @@ pub fn conversion_to( /// **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** ([`Type::ElaboratedRecord`]), which the declaration reader and +/// 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. /// @@ -174,20 +175,20 @@ pub fn conversion_to( /// /// `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: &Type) -> Option<(RecordTag, &str)> { +fn a_tagged_record_in(type_of: &ComputedType) -> Option<(RecordTag, &str)> { match type_of { - Type::ElaboratedRecord { tag, of } => of.class_name().map(|name| (*tag, name)), - Type::Pointer { to } - | Type::Reference { to, .. } - | Type::Pack { of: to } - | Type::Qualified { of: to, .. } - | Type::Array { of: to, .. } => a_tagged_record_in(to), - Type::Function { - returns, - parameters, - } => a_tagged_record_in(returns).or_else(|| parameters.iter().find_map(a_tagged_record_in)), - Type::Named { arguments, .. } => arguments.iter().find_map(a_tagged_record_in), - Type::Builtin { .. } | Type::TemplateParameter { .. } => None, + 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, } } @@ -201,18 +202,18 @@ fn a_tagged_record_in(type_of: &Type) -> Option<(RecordTag, &str)> { /// 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: &Type, tag: RecordTag, record: &str) -> bool { +fn the_value_is_that_record(type_of: &ComputedType, tag: RecordTag, record: &str) -> bool { match type_of { - Type::Qualified { of, .. } => the_value_is_that_record(of, tag, record), - Type::ElaboratedRecord { tag: written, of } => { + 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)) } - Type::Named { name, .. } => names_the_record(name, record), - Type::Pointer { to } => { - matches!(&**to, Type::Builtin { spelling } if spelling == "void") - || the_value_is_that_record(to, tag, 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) } - Type::Array { of, .. } => the_value_is_that_record(of, tag, record), + ComputedType::Array { of, .. } => the_value_is_that_record(of, tag, record), _ => false, } } @@ -227,15 +228,17 @@ fn names_the_record(name: &str, record: &str) -> bool { /// `_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. /// -/// [`Type::TemplateParameter`] is the structural answer — the declaration's own +/// [`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: &Type) -> bool { +pub(crate) fn names_a_template_parameter_for_a_check(type_of: &ComputedType) -> bool { match type_of { - Type::TemplateParameter { .. } => true, - Type::Pointer { to } - | Type::Reference { to, .. } - | Type::Qualified { of: to, .. } => names_a_template_parameter_for_a_check(to), + 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), } } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 5ad9fa69..07393267 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -29,6 +29,8 @@ //! the work, and it is the reason this module rather than `summary` owns the walk. use crate::DeclModifiers; +use crate::sema::types::TypeSubstitutions; +use crate::index::types::ComputedType; use crate::Name; use crate::scopes; use crate::sema; @@ -171,7 +173,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) } @@ -226,7 +228,7 @@ pub fn declared_type_of(root: &CppSyntaxNode, binding: &Binding) -> Option Option { +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; @@ -267,7 +269,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; @@ -280,10 +282,7 @@ pub(crate) fn an_unnamed_class_body_named( unnamed = a_class_body_without_a_tag(specifiers); } }); - unnamed.then(|| sema::types::Type::Named { - name: format!("{scope}::{name}"), - arguments: Vec::new(), - }) + 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? @@ -312,7 +311,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 @@ -426,7 +425,7 @@ pub(crate) fn declared_type_of_with( // 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 `Type` already. + // operators the shape knows about are in `ComputedType` already. let found = sema::types::type_of_declaration_named( &specifiers, declarator.as_ref(), @@ -440,7 +439,7 @@ pub(crate) fn declared_type_of_with( matches!(binding.kind, BindingKind::Variable), ); // **An empty spelling is "no type"**, which is what a declaration specifier sequence the reader could not - // place produces; `Type::Builtin { spelling: "" }` is the shape that means it. + // place produces; `ComputedType::Named("")` is the shape that means it. (!found.to_string().trim().is_empty()).then_some(found) } @@ -448,7 +447,7 @@ pub(crate) fn declared_type_of_with( /// carry — an array dimension that is a macro or an enumerator (`Point points[COUNT]`). /// /// The fact carries the *structural* type, and a dimension that is not a literal is deliberately not part of it -/// (`Type::Array.extent` is `None`). A layout question still has to size such a member, so this is the one query that +/// (`ComputedType::Array.extent` is `None`). A layout question still has to size such a member, so this is the one query that /// reassembles the file's own spelling: the specifiers read as syntax, plus the declarator with the declared name cut /// out — and, for a type's parameter list, with the parameter *names* cut out too (`int (*)(int)` is the type; /// `int (*)(int left)` is the declaration). It is a **query over the tree**, used for display/evaluation only; no @@ -1563,7 +1562,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) } @@ -1571,7 +1570,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; } @@ -1616,10 +1615,7 @@ pub(crate) fn declared_alias_target_with( // 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(sema::types::Type::Named { - name: named, - arguments: Vec::new(), - }); + 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 @@ -1693,7 +1689,7 @@ fn the_class_a_typedef_body_names( /// `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; @@ -1746,10 +1742,10 @@ pub fn declared_returns_of(root: &CppSyntaxNode, binding: &Binding) -> Option>( root: &CppSyntaxNode, binding: Binding, - substitutions: &sema::types::TypeSubstitutions<'_, N>, + 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; @@ -1787,7 +1783,7 @@ pub fn deduced_returns_of_substituted>( fn a_branch_that_is_taken>( expression: &cpp_parser::CppExpr, body: &cpp_parser::CppCompoundStat, - substitutions: &sema::types::TypeSubstitutions<'_, N>, + 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 @@ -1852,7 +1848,7 @@ fn constexpr_condition_of(statement: &cpp_parser::CppIfStat) -> Option { /// ``` fn evaluate_a_trait>( condition: &str, - substitutions: &sema::types::TypeSubstitutions<'_, N>, + substitutions: &TypeSubstitutions<'_, N>, ) -> Option { let condition = condition.trim(); @@ -1922,7 +1918,7 @@ fn evaluate_a_trait>( /// A spelling with `decay_t<…>` applied and the template parameters substituted — see [`evaluate_a_trait`]. fn substituted_spelling>( written: &str, - substitutions: &sema::types::TypeSubstitutions<'_, N>, + substitutions: &TypeSubstitutions<'_, N>, ) -> String { let mut text = written.trim(); while let Some(inner) = text @@ -2500,7 +2496,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 @@ -2516,7 +2512,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 { @@ -2553,8 +2549,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() @@ -2603,7 +2599,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 { @@ -2706,7 +2702,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(); @@ -2784,8 +2780,8 @@ fn a_data_member_type(expression: &CppSyntaxNode, declaration: &CppSyntaxNode) - fn type_a_return_states_with>( expression: &cpp_parser::CppExpr, declaration: &CppSyntaxNode, - substitutions: &sema::types::TypeSubstitutions<'_, N>, - argument_types: &[sema::types::Type], + substitutions: &TypeSubstitutions<'_, N>, + argument_types: &[ComputedType], ) -> Option { use cpp_parser::{CppAstNode, CppExpr}; match expression { @@ -2975,7 +2971,7 @@ fn a_captures_type(expression: &CppSyntaxNode) -> Option { type_a_return_states_with( &initializer, enclosing.syntax(), - &sema::types::TypeSubstitutions::::new(&[], &[]), + &TypeSubstitutions::::new(&[], &[]), &[], ) } @@ -3037,7 +3033,7 @@ 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(written) = written { // **An operator's return type, when the fact's readers can resolve the shape.** See @@ -3086,19 +3082,23 @@ pub(crate) fn the_returns_the_class_has_to_resolve( fn an_operator_return_is_usable( root: &CppSyntaxNode, binding: &Binding, - written: &sema::types::Type, + written: &ComputedType, ) -> bool { - fn means_the_same_everywhere(kind: &sema::types::Type) -> bool { - use crate::sema::types::Type; + 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, } } @@ -3160,7 +3160,7 @@ fn the_enclosing_body_declares(root: &CppSyntaxNode, binding: &Binding, name: &s pub(crate) fn declared_returns_of_with( shapes: &DeclarationShapes, binding: &Binding, -) -> Option { +) -> 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: @@ -3188,7 +3188,7 @@ pub(crate) fn declared_returns_of_with( // 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 `Type` here + // 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) @@ -3322,8 +3322,8 @@ pub(crate) fn declared_returns_of_with( // 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 sema::types::Type::Builtin { spelling } = &written - && matches!(spelling.trim(), "auto" | "decltype(auto)") + && let ComputedType::Primary(primary) = &written + && primary.is_a_placeholder() { return None; } @@ -3333,7 +3333,7 @@ pub(crate) fn declared_returns_of_with( /// **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: sema::types::Type, operators: &str) -> sema::types::Type { +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; @@ -3341,14 +3341,12 @@ fn with_operators(base: sema::types::Type, operators: &str) -> sema::types::Type while at < operators.len() { match operators[at] { '*' => { - written = sema::types::Type::Pointer { - to: Arc::new(written), - }; + written = ComputedType::Pointer(Arc::new(written)); at += 1; } '&' => { let rvalue = operators.get(at + 1) == Some(&'&'); - written = sema::types::Type::Reference { + written = ComputedType::Reference { to: Arc::new(written), rvalue, }; @@ -3381,8 +3379,8 @@ fn with_operators(base: sema::types::Type, operators: &str) -> sema::types::Type fn a_parenthesised_return_type( declarator: &CppSyntaxNode, name: SourceRange, - base: &sema::types::Type, -) -> Option { + base: &ComputedType, +) -> Option { use cpp_parser::CppAstNode; use std::sync::Arc; @@ -3444,12 +3442,12 @@ fn a_parenthesised_return_type( let mut wrapped = base.clone(); for suffix in &suffixes { if CppParamList::can_cast(suffix.kind().into()) { - wrapped = sema::types::Type::Function { + wrapped = ComputedType::Function(Arc::new(crate::index::types::FunctionType { returns: Arc::new(wrapped), - parameters: sema::types::read_parameters(suffix), - }; + parameters: sema::types::read_parameters(suffix).into_boxed_slice(), + })); } else { - wrapped = sema::types::Type::Array { + wrapped = ComputedType::Array { of: Arc::new(wrapped), extent: sema::types::array_extent(suffix), }; @@ -3459,10 +3457,8 @@ fn a_parenthesised_return_type( // suffix chain last. for operator in operators { wrapped = match operator { - '*' => sema::types::Type::Pointer { - to: Arc::new(wrapped), - }, - _ => sema::types::Type::Reference { + '*' => ComputedType::Pointer(Arc::new(wrapped)), + _ => ComputedType::Reference { to: Arc::new(wrapped), rvalue: false, }, @@ -4039,7 +4035,7 @@ fn fact_for( // 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 `Type`; the fact then stores the immutable `ComputedType` that value denotes. No spelling is + // 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 @@ -4049,14 +4045,10 @@ fn fact_for( // **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. A namespace name is - // a name as far as the type layer is concerned, so it is a `Type::Named`. + // 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| { - sema::types::Type::Named { - name, - arguments: Vec::new(), - } - }) + 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 @@ -4214,24 +4206,20 @@ fn fact_for( // `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( - crate::index::types::ComputedType::from(&written), - )); + parameter.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); } } parameter_arena.intern(declared) }; - // **The type values, lowered at the construction edge.** The two `Type`s above are the only place this fact ever + // **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| { + 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( - crate::index::types::ComputedType::from(&written), - )) + DeclaredType::Computed(std::sync::Arc::new(written)) }) }; if name.as_ref() == "pointer" { @@ -5938,9 +5926,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 @@ -6080,7 +6068,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. /// diff --git a/crates/cpp_code_analysis/src/sema/deduction.rs b/crates/cpp_code_analysis/src/sema/deduction.rs index 699289fa..1827d1d5 100644 --- a/crates/cpp_code_analysis/src/sema/deduction.rs +++ b/crates/cpp_code_analysis/src/sema/deduction.rs @@ -100,7 +100,7 @@ pub(crate) fn substituted( .map(smol_str::SmolStr::from) .zip(deduced.iter().cloned()) .collect(); - type_of.substituted(&bindings) + type_of.substituted_by_bindings(&bindings) } /// The deduction itself, with a set of names already fixed. @@ -339,9 +339,7 @@ mod tests { /// 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); - let parsed = - sema::types::with_template_parameters(parsed, &["T", "U", "N", "_Tp", "_Args"]); - ComputedType::from(&parsed) + sema::types::with_template_parameters(parsed, &["T", "U", "N", "_Tp", "_Args"]) } fn yes(spelling: &str) -> Known { diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index ddc42d58..4cbb8781 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -53,7 +53,6 @@ use cpp_parser::CppSyntaxNode; use crate::index::project::{self, MemberList, ProjectIndex}; use crate::index::types::ComputedType; -use crate::sema::types::Type; use crate::{Known, ScopeTree}; /// **A file, the index, and a way to read another file** — see the module documentation. @@ -128,7 +127,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 @@ -158,7 +157,7 @@ impl<'a> SemanticModel<'a> { let fact = self.index.member_fact(member)?; let base = fact.type_of.as_computed()?; Some(match &member.substitution { - Some(substitution) => base.substituted(&substitution.bindings), + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), None => base, }) } @@ -169,7 +168,7 @@ impl<'a> SemanticModel<'a> { let fact = self.index.member_fact(member)?; let base = fact.returns.as_computed()?; Some(match &member.substitution { - Some(substitution) => base.substituted(&substitution.bindings), + Some(substitution) => base.substituted_by_bindings(&substitution.bindings), None => base, }) } @@ -262,7 +261,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, diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index f9e89b58..7ce50211 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -328,10 +328,7 @@ pub(crate) fn rank(parameter: &ComputedType, argument: &Known) -> // 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 - .to_sema_type() - .convertible_to(¶meter.to_sema_type()) - { + match argument.convertible_to(parameter) { Known::Yes(()) => Match::Conversion, Known::No => Match::NotViable, Known::Unknown(_) => Match::Unranked, @@ -388,16 +385,14 @@ mod tests { /// `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(ComputedType::from(&sema::types::parse_type_spelling( - spelling, - ))) + Known::Yes(sema::types::parse_type_spelling(spelling)) } fn candidate(parameters: &[&str]) -> Candidate { Candidate::new( parameters .iter() - .map(|parameter| ComputedType::from(&sema::types::parse_type_spelling(parameter))) + .map(|parameter| sema::types::parse_type_spelling(parameter)) .collect(), false, parameters.join(", "), @@ -613,7 +608,7 @@ fn lowered(source: &str) -> (Vec, bool) { .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(ComputedType::from(&written))); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); } parameters_in_facts(&facts, list.is_variadic()) } @@ -685,7 +680,7 @@ fn a_parameter_written_with_the_declarations_template_parameter_is_a_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 = crate::cache::summary::DeclaredType::Computed(std::sync::Arc::new( - ComputedType::from(&written), + written, )); let (parameters, _) = parameters_in_facts(&facts, false); @@ -705,13 +700,10 @@ fn the_more_specialized_of_two_templates_wins() { // `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); - let parsed = sema::types::with_template_parameters(parsed, &["T".to_string()]); - ComputedType::from(&parsed) + sema::types::with_template_parameters(parsed, &["T".to_string()]) }; let an_argument = |spelling: &str| { - Known::Yes(ComputedType::from(&sema::types::parse_type_spelling( - spelling, - ))) + 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. diff --git a/crates/cpp_code_analysis/src/sema/render.rs b/crates/cpp_code_analysis/src/sema/render.rs index 309b9bf2..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. //! @@ -581,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, @@ -617,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`. @@ -1151,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 09f1e1d2..0f7dc367 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -12,65 +12,64 @@ //! 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::ElaboratedRecord { tag, of } `struct point`, `union value` — C's tag, kept on the type -//! 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[]` +//! 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::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; use cpp_parser::CppArrayType; use cpp_parser::CppDeclaration; @@ -85,7 +84,6 @@ use cpp_parser::SourceRange; use cpp_parser::source_range; use cpp_parser::subtree_text_spaced; use cpp_parser::typed_descendants; -use std::fmt; use std::sync::Arc; use cpp_parser::CppAstNode; @@ -103,991 +101,11 @@ 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) => "", - } - } -} - -/// **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 -/// ([`Type::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, - } - } -} - -#[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, - }, - /// **A C record written with its tag**: `struct point`, `union value`. - /// - /// The keyword is the evidence that a name denotes a record rather than a `typedef` of something else, and that - /// evidence is not recoverable from [`Type::Named`] — `typedef int point;` writes one. The wrapper is - /// **transparent to the type relation and to class questions** (`struct point` and `point` are one shape to - /// everything except display), and the one consumer that reads the tag is the C conversion rule in - /// [`crate::sema::convert`]. - /// - /// `enum` is not one of these: see [`RecordTag`]. - ElaboratedRecord { - tag: RecordTag, - of: TypeOf, - }, - 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, - }, -} +/// **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}; -/// **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) -} - -/// **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: &Type) -> bool { - match type_of { - Type::ElaboratedRecord { .. } => true, - Type::Named { arguments, .. } => arguments.iter().any(has_an_elaborated_record), - Type::Pointer { to } | Type::Pack { of: to } => has_an_elaborated_record(to), - Type::Reference { to, .. } | Type::Qualified { of: to, .. } => has_an_elaborated_record(to), - Type::Array { of, .. } => has_an_elaborated_record(of), - Type::Function { - returns, - parameters, - } => has_an_elaborated_record(returns) || parameters.iter().any(has_an_elaborated_record), - Type::Builtin { .. } | Type::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. Before [`Type::ElaboratedRecord`] -/// existed the declaration reader dropped the keyword before a type ever reached the algebra, so the relation is kept -/// exactly as it was by removing the wrapper here rather than teaching every arm about it. 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: &Type) -> Type { - match type_of { - Type::ElaboratedRecord { of, .. } => without_elaborated_records(of), - Type::Named { name, arguments } => Type::Named { - name: name.clone(), - arguments: arguments.iter().map(without_elaborated_records).collect(), - }, - Type::Pointer { to } => Type::Pointer { - to: Arc::new(without_elaborated_records(to)), - }, - Type::Reference { to, rvalue } => Type::Reference { - to: Arc::new(without_elaborated_records(to)), - rvalue: *rvalue, - }, - Type::Array { of, extent } => Type::Array { - of: Arc::new(without_elaborated_records(of)), - extent: *extent, - }, - Type::Function { - returns, - parameters, - } => Type::Function { - returns: Arc::new(without_elaborated_records(returns)), - parameters: parameters.iter().map(without_elaborated_records).collect(), - }, - Type::Pack { of } => Type::Pack { - of: Arc::new(without_elaborated_records(of)), - }, - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(without_elaborated_records(of)), - qualifiers: *qualifiers, - }, - Type::Builtin { .. } | Type::TemplateParameter { .. } => type_of.clone(), - } -} - -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(), - // **C's tag is transparent too.** `struct point` and `point` name one record, and a member question goes - // to the name; the tag is evidence about what the name *is*, which `sema::convert` reads, not a - // different class. - Type::ElaboratedRecord { of, .. } => of.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(), - Type::ElaboratedRecord { of, .. } => of.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; - - // **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. 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, .. } - | Type::ElaboratedRecord { 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<'_, N>) -> 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, - }, - // **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: - // the keyword is part of how the type was written, not of the name it was written on. - Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { - tag: *tag, - of: Arc::new(of.substituted(substitutions)), - }, - 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, - }, - // The tag travels with the name it was written on — see [`Type::substituted`]. - Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { - tag: *tag, - of: Arc::new(of.replacing(name, with)), - }, - } - } -} - -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(()) - } - // **The tag is written back**, because that is what the file wrote: the relation treats `struct point` - // and `point` as one shape, while a hover or a message is owed the file's own spelling. `of` is a base, - // so a pointer written around it (`struct point*`) comes out as the same words in the same order. - Type::ElaboratedRecord { tag, of } => write!(out, "{} {of}", tag.word()), - 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 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 @@ -1096,16 +114,16 @@ impl Type { #[derive(Debug, Clone, Copy)] pub struct TypeSubstitutions<'a, N: AsRef = String> { names: &'a [N], - arguments: &'a [Type], + 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, N: AsRef> TypeSubstitutions<'a, N> { - pub fn new(names: &'a [N], arguments: &'a [Type]) -> TypeSubstitutions<'a, N> { + pub fn new(names: &'a [N], arguments: &'a [ComputedType]) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, arguments, @@ -1118,8 +136,8 @@ impl<'a, N: AsRef> TypeSubstitutions<'a, N> { /// defaulted, and `twice` writes one argument for two. pub fn with_defaults( names: &'a [N], - arguments: &'a [Type], - defaults: &'a [Type], + arguments: &'a [ComputedType], + defaults: &'a [ComputedType], ) -> TypeSubstitutions<'a, N> { TypeSubstitutions { names, @@ -1134,7 +152,7 @@ impl<'a, N: AsRef> TypeSubstitutions<'a, N> { /// 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> { + 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 @@ -1154,7 +172,7 @@ impl<'a, N: AsRef> TypeSubstitutions<'a, N> { /// 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 } } @@ -1170,7 +188,7 @@ impl<'a, N: AsRef> TypeSubstitutions<'a, N> { #[derive(Debug, Clone, Default)] pub struct TypeBindings { names: Vec, - arguments: Vec, + arguments: Vec, } impl TypeBindings { @@ -1179,7 +197,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 } } @@ -1198,7 +216,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 } @@ -1208,11 +226,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(); } @@ -1221,178 +239,105 @@ impl TypeBindings { } } -/// **Read a type out of the spelling a `DeclFact` records.** -/// -/// # Why a spelling parser exists at all, when the syntax is the better source -/// -/// Because two layers of this crate do not have the syntax, and cannot get it cheaply: -/// -/// ```text -/// a declaration the index holds `DeclFact::type_of` is a handle into the global type store; the class it -/// names is materialized without a tree, because the declaring file need not be open -/// a type written as a template arg `std::map` arrives as text inside a name node -/// ``` -/// -/// 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. -/// -/// # 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. -/// **`auto` and `decltype(auto)` are placeholders, not names.** -/// -/// [`parse_type_spelling`] has no context for them: `auto` is not one of the language's builtin words it knows, so a -/// spelling `auto&` becomes a reference to a class *named* `auto`. The computation layer has a primary for each -/// placeholder (`ComputedType::Primary(PrimaryType::Auto)`), and `auto` is never a class a file can declare, so the -/// name is rewritten here before a fact's type is lowered. This is the same normalization `ComputedType::from(&Type)` -/// applies to a parser-built `Type::Builtin { spelling: "auto" }`. -pub fn without_placeholders_written_as_names(written: Type) -> Type { - match written { - Type::Named { name, arguments } if arguments.is_empty() && name.trim() == "auto" => { - Type::builtin("auto") - } - Type::Named { name, arguments } - if arguments.is_empty() && name.trim() == "decltype(auto)" => - { - Type::builtin("decltype(auto)") - } - // **`decltype(auto)` reads as a function type to the spelling parser** — it ends in `)`, and - // `split_trailing_parameters` sees `decltype` with one parameter, `auto`. It is the other placeholder, not a - // function, so the shape the parser produced is put back. - Type::Function { - returns, - parameters, - } if parameters.len() == 1 - && matches!(&*returns, Type::Builtin { spelling } if spelling.trim() == "decltype") - && matches!(¶meters[0], Type::Builtin { spelling } if spelling.trim() == "auto") => - { - Type::builtin("decltype(auto)") - } - Type::Named { name, arguments } => Type::Named { - name, - arguments: arguments - .into_iter() - .map(without_placeholders_written_as_names) - .collect(), - }, - Type::Pointer { to } => Type::Pointer { - to: Arc::new(without_placeholders_written_as_names((*to).clone())), - }, - Type::Reference { to, rvalue } => Type::Reference { - to: Arc::new(without_placeholders_written_as_names((*to).clone())), - rvalue, - }, - Type::Array { of, extent } => Type::Array { - of: Arc::new(without_placeholders_written_as_names((*of).clone())), - extent, - }, - Type::Function { - returns, - parameters, - } => Type::Function { - returns: Arc::new(without_placeholders_written_as_names((*returns).clone())), - parameters: parameters - .into_iter() - .map(without_placeholders_written_as_names) - .collect(), - }, - Type::Pack { of } => Type::Pack { - of: Arc::new(without_placeholders_written_as_names((*of).clone())), - }, - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(without_placeholders_written_as_names((*of).clone())), - qualifiers, - }, - // A tag is not a placeholder: `struct auto` is not a spelling, and what it wraps is normalized like any - // other name. - Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { - tag, - of: Arc::new(without_placeholders_written_as_names((*of).clone())), - }, - builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, - } -} - /// **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 -/// [`Type::substituted`] only replaces [`Type::TemplateParameter`] — so the names the declaration itself lists are -/// rewritten here, before the type is interned or converted to [`crate::index::types::ComputedType`]. +/// [`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: Type, parameters: &[N]) -> Type { +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 { - Type::Named { name, arguments } if arguments.is_empty() && names_a_parameter(&name) => { - Type::TemplateParameter { name } - } - Type::Named { name, arguments } => Type::Named { - name, - arguments: arguments - .into_iter() - .map(|argument| with_template_parameters(argument, parameters)) - .collect(), - }, - Type::Pointer { to } => Type::Pointer { - to: Arc::new(with_template_parameters_of(&to, parameters)), - }, - Type::Reference { to, rvalue } => Type::Reference { - to: Arc::new(with_template_parameters_of(&to, parameters)), + 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( + crate::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, }, - Type::Array { of, extent } => Type::Array { - of: Arc::new(with_template_parameters_of(&of, parameters)), + ComputedType::Array { of, extent } => ComputedType::Array { + of: Arc::new(with_template_parameters((*of).clone(), parameters)), extent, }, - Type::Function { - returns, - parameters: written_parameters, - } => Type::Function { - returns: Arc::new(with_template_parameters_of(&returns, parameters)), - parameters: written_parameters - .into_iter() - .map(|parameter| with_template_parameters(parameter, parameters)) + 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(), - }, - Type::Pack { of } => Type::Pack { - of: Arc::new(with_template_parameters_of(&of, parameters)), - }, - Type::Qualified { of, qualifiers } => Type::Qualified { - of: Arc::new(with_template_parameters_of(&of, parameters)), - qualifiers, - }, - // See [`Type::substituted`]: a tag written before a name stays before whatever that name became. - Type::ElaboratedRecord { tag, of } => Type::ElaboratedRecord { + })), + 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(&of, parameters)), + of: Arc::new(with_template_parameters((*of).clone(), parameters)), }, - builtin @ (Type::Builtin { .. } | Type::TemplateParameter { .. }) => builtin, + ComputedType::TemplateParameter(_) => written, } } -/// [`with_template_parameters`] through a shared child. -fn with_template_parameters_of>(written: &Type, parameters: &[N]) -> Type { - with_template_parameters(written.clone(), parameters) -} - -pub fn parse_type_spelling(written: &str) -> Type { +/// **Read a type out of a spelling.** +/// +/// 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. +/// +/// # 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 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 +/// ``` +/// +/// 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. +/// +/// **`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 @@ -1411,19 +356,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 @@ -1437,14 +399,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.** @@ -1470,9 +432,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}")))); } } @@ -1482,7 +442,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, }; @@ -1500,7 +460,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, }; @@ -1510,9 +470,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 @@ -1523,7 +481,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(',') @@ -1531,7 +489,7 @@ 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 @@ -1540,7 +498,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { // declaration was written to add. 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('<') { @@ -1551,38 +509,34 @@ 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), }; - // **C's tag is kept on the type.** `struct point` and `union value` wrote a record's keyword, and a `Type` that + // **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) => Type::ElaboratedRecord { + Some(tag) => ComputedType::ElaboratedRecord { tag, of: Arc::new(qualified), }, None => qualified, }; - match qualifier.is_none() { - true => qualified, - false => Type::Qualified { + if qualifier.is_none() { + qualified + } else { + ComputedType::Qualified(Arc::new(QualifiedType { of: Arc::new(qualified), - qualifiers: qualifier, - }, + is_const: qualifier.is_const(), + is_volatile: qualifier.is_volatile(), + })) } } @@ -1590,7 +544,7 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> Type { /// /// 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)> { +fn split_trailing_extent(written: &str) -> Option<(&str, Option)> { let mut depth = 0isize; for (index, character) in written.char_indices().rev() { @@ -1795,7 +749,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 @@ -2090,10 +1044,11 @@ pub fn declarator_declaring(root: &CppSyntaxNode, name: SourceRange) -> Option, @@ -2101,7 +1056,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) } @@ -2131,7 +1086,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 @@ -2172,7 +1127,7 @@ pub fn type_of_declaration_named( /// `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 { +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( @@ -2202,7 +1157,7 @@ pub fn type_of_a_parameter(parameter: &CppParam) -> Option { /// /// `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 { +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()))?; @@ -2221,15 +1176,15 @@ pub fn type_of_a_type_id(type_id: &CppSyntaxNode) -> Option { false, ); } else if CppArrayType::can_cast(child.kind().into()) { - wrapped = Type::Array { + wrapped = ComputedType::Array { of: Arc::new(wrapped), extent: array_extent(&child), }; } else if CppParamList::can_cast(child.kind().into()) { - wrapped = Type::Function { + wrapped = ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(wrapped), - parameters: read_parameters(&child), - }; + parameters: read_parameters(&child).into_boxed_slice(), + })); } } Some(wrapped) @@ -2262,7 +1217,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? @@ -2284,7 +1239,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| { @@ -2300,12 +1255,12 @@ fn the_type_a_typeof_names(node: &CppSyntaxNode) -> Option { }; let read = read_specifiers_named(&specifiers, None, source_range(specifiers.text_range())); // 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 `Type::ElaboratedRecord` around `point` + // 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())) } @@ -2350,7 +1305,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`. // @@ -2365,14 +1320,12 @@ 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; @@ -2471,7 +1424,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`, @@ -2546,7 +1502,7 @@ pub(crate) fn read_specifiers_named( CppSyntaxKind::UnionDef => Some(RecordTag::Union), _ => record_tag, }; - named = Some(Type::named(tag)); + named = Some(ComputedType::named(tag, Vec::new())); } None => an_unnamed_body = true, } @@ -2560,7 +1516,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())); } } } @@ -2568,7 +1524,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 @@ -2584,13 +1540,13 @@ 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 { // **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) => Type::ElaboratedRecord { + Some(tag) => ComputedType::ElaboratedRecord { tag, of: Arc::new(named), }, @@ -2606,16 +1562,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(), + })) } } @@ -2672,17 +1630,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; @@ -2717,7 +1675,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. @@ -2730,7 +1688,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() { @@ -2742,9 +1700,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; } @@ -2752,7 +1711,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())), } } @@ -2760,7 +1719,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() { @@ -2786,13 +1745,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? @@ -2862,18 +1821,18 @@ fn declarator_holding_the_name(declarator: &CppSyntaxNode, name: SourceRange) -> /// 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, declares_an_object: bool, -) -> Type { +) -> ComputedType { /// One operator the declarator wrote, in reading order. enum Step { Pointer, Reference { rvalue: bool }, - Array { extent: Option }, - Parameters(Vec), + Array { extent: Option }, + Parameters(Vec), } /// The pointer/reference wrappers inside a declarator that does **not** reach the name — a prefix operator. @@ -2955,21 +1914,19 @@ fn wrap( let mut written = base; for step in steps.into_iter().rev() { written = match step { - Step::Pointer => Type::Pointer { - to: Arc::new(written), - }, - Step::Reference { rvalue } => Type::Reference { + Step::Pointer => ComputedType::Pointer(Arc::new(written)), + Step::Reference { rvalue } => ComputedType::Reference { to: Arc::new(written), rvalue, }, - Step::Array { extent } => Type::Array { + Step::Array { extent } => ComputedType::Array { of: Arc::new(written), extent, }, - Step::Parameters(parameters) => Type::Function { + Step::Parameters(parameters) => ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(written), - parameters, - }, + parameters: parameters.into_boxed_slice(), + })), }; } written @@ -2980,7 +1937,7 @@ fn wrap( /// `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. -pub(crate) fn array_extent(node: &CppSyntaxNode) -> Option { +pub(crate) fn array_extent(node: &CppSyntaxNode) -> Option { let text = node.text().to_string(); let inside = text .trim() @@ -2991,7 +1948,7 @@ pub(crate) fn array_extent(node: &CppSyntaxNode) -> Option { } /// 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() { @@ -3071,7 +2028,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 — @@ -3280,7 +2237,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) } @@ -3294,7 +2251,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(); @@ -3339,20 +2296,20 @@ mod tests { } /// **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 `Type::ElaboratedRecord` — rather than + /// `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 Type::Pointer { to } = &pointed else { + let ComputedType::Pointer(to) = &pointed else { panic!("`struct point *p` is a pointer: {pointed:?}"); }; assert!( matches!( &**to, - Type::ElaboratedRecord { tag: RecordTag::Struct, of } + ComputedType::ElaboratedRecord { tag: RecordTag::Struct, of } if of.class_name() == Some("point") ), "the pointer's pointee is the elaborated record: {to:?}" @@ -3364,7 +2321,7 @@ mod tests { assert!( matches!( value, - Type::ElaboratedRecord { + ComputedType::ElaboratedRecord { tag: RecordTag::Union, .. } @@ -3387,13 +2344,13 @@ mod tests { assert_eq!(written("enum colour c = 3;", "c"), "colour"); assert!(!matches!( parse_type_spelling("colour"), - Type::ElaboratedRecord { .. } + 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, Type::Named { .. }), + matches!(typedef_use, ComputedType::Named(_)), "a typedef use writes no keyword: {typedef_use:?}" ); assert_eq!( @@ -3410,7 +2367,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*"); @@ -3498,11 +2455,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.** @@ -3537,28 +2492,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>" @@ -3568,11 +2520,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" ); } @@ -3582,25 +2532,21 @@ mod tests { #[test] fn a_type_that_holds_a_parameter_says_so() { assert!( - Type::Pointer { - to: Arc::new(Type::TemplateParameter { - name: "T".to_string() - }) - } + 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 @@ -3640,7 +2586,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() { @@ -3688,7 +2634,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*"); @@ -3700,7 +2646,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 @@ -3735,15 +2681,12 @@ mod tests { let found = parse_type_spelling("int(int, double)"); assert_eq!(found.to_string(), "int(int, double)"); - let Type::Function { - returns, - parameters, - } = &found + 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 @@ -3754,20 +2697,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)); diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index d14f1cce..75b3fd91 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -500,7 +500,7 @@ impl Session { .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 structures, which is + // 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(); @@ -518,7 +518,7 @@ impl Session { .iter() .map(|argument| match model.type_of(argument) { Known::Yes((a_type, _)) => { - Known::Yes(crate::index::types::ComputedType::from(&a_type)) + Known::Yes(a_type) } Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), @@ -664,7 +664,7 @@ impl Session { .iter() .map(|argument| match model.type_of(argument) { Known::Yes((a_type, _)) => { - Known::Yes(crate::index::types::ComputedType::from(&a_type)) + Known::Yes(a_type) } Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), @@ -1513,10 +1513,9 @@ impl Session { // 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 = - crate::DeclaredType::Computed(Arc::new(crate::index::types::ComputedType::from( - &crate::sema::types::parse_type_spelling(&type_of), - ))); + fact.type_of = crate::DeclaredType::Computed(Arc::new( + crate::sema::types::parse_type_spelling(&type_of), + )); fact.returns = crate::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()); diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index b1779dad..9f43e21a 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}; @@ -760,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) = @@ -785,9 +786,9 @@ 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(); @@ -922,7 +923,7 @@ 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; @@ -1104,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, diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index 81dc4b45..d6f2040b 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -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(); diff --git a/crates/cpp_code_analysis/src/session/semantic.rs b/crates/cpp_code_analysis/src/session/semantic.rs index 32e4cdaf..7450e6ba 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -88,6 +88,7 @@ //! ``` use crate::FactGuard; +use crate::index::types::ComputedType; use crate::ProjectLanguage; use crate::Visibility; use crate::ascend; @@ -1056,8 +1057,8 @@ fn denotes_a_function_pointer(index: &ProjectIndex, declaring: &Path, written: & // 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 sema::types::Type::Pointer { to } = sema::types::parse_type_spelling(&spelling) - && matches!(*to, sema::types::Type::Function { .. }) + if let ComputedType::Pointer(to) = sema::types::parse_type_spelling(&spelling) + && matches!(&*to, ComputedType::Function(_)) { return true; } diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index 7003a755..29a8b841 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -241,10 +241,9 @@ where parameters.push((start..label.len(), text.clone())); let written = cpp_parser::CppParam::cast(parameter) .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); - plain.push(written.map_or_else( - || crate::index::types::ComputedType::named(text, Vec::new()), - |written| crate::index::types::ComputedType::from(&written), - )); + plain.push(written.unwrap_or_else(|| { + crate::index::types::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 @@ -312,9 +311,7 @@ where let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => Known::Yes(crate::index::types::ComputedType::from( - &a_type, - )), + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) diff --git a/crates/cpp_code_analysis/src/session/units.rs b/crates/cpp_code_analysis/src/session/units.rs index 81e47390..ec89dac6 100644 --- a/crates/cpp_code_analysis/src/session/units.rs +++ b/crates/cpp_code_analysis/src/session/units.rs @@ -5,6 +5,7 @@ //! the flags), which is what makes a cached unit reusable across runs and what makes a stale one detectable. use super::*; +use crate::index::types::ComputedType; use crate::CookedFile; use crate::FileId; use crate::FileView; @@ -1617,15 +1618,22 @@ impl Session { // `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( diff --git a/crates/cpp_code_analysis/tests/params.rs b/crates/cpp_code_analysis/tests/params.rs index 445f8c3f..f35b67e8 100644 --- a/crates/cpp_code_analysis/tests/params.rs +++ b/crates/cpp_code_analysis/tests/params.rs @@ -30,7 +30,7 @@ fn lowered(source: &str) -> (Vec, bool) { 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(ComputedType::from(&written))); + fact.type_of = DeclaredType::Computed(std::sync::Arc::new(written)); } parameters_in_facts(&facts, list.is_variadic()) } @@ -101,7 +101,7 @@ fn a_parameter_written_with_a_template_parameter_is_structured_as_one() { 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(ComputedType::from(&written))); + facts[0].type_of = DeclaredType::Computed(std::sync::Arc::new(written)); let (parameters, variadic) = parameters_in_facts(&facts, false); assert_eq!(parameters.len(), 1); diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 612bcb8e..5caa650c 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2765,11 +2765,10 @@ std::string f() { /// call deduces, so no assertion hands the evaluator a condition spelling. #[test] fn the_constraint_evaluator_decides_the_fundamental_traits() { - use cpp_code_analysis::index::types::ComputedType; + use cpp_code_analysis::index::types::{ComputedType, FunctionType, QualifiedType}; use cpp_code_analysis::sema::constraint::{ a_requires_clause_node, satisfies, the_condition_of_node, }; - use cpp_code_analysis::sema::types::{Qualifiers, Type}; use cpp_parser::{CppAstNode, CppParser, CppRequiresClause, CppSyntaxNode, ParserConfig}; use smol_str::SmolStr; use std::sync::Arc; @@ -2799,34 +2798,42 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { } /// The deducer's binding: `T` stands for one structured type. - fn bind(written: Type) -> Vec<(SmolStr, ComputedType)> { - vec![(SmolStr::new("T"), ComputedType::from(&written))] + fn bind(written: ComputedType) -> Vec<(SmolStr, ComputedType)> { + vec![(SmolStr::new("T"), written)] } - let a_reference = |of: Type| Type::Reference { + let a_reference = |of: ComputedType| ComputedType::Reference { to: Arc::new(of), rvalue: false, }; - let an_rvalue_reference = |of: Type| Type::Reference { + let an_rvalue_reference = |of: ComputedType| ComputedType::Reference { to: Arc::new(of), rvalue: true, }; - let a_const = |of: Type| Type::Qualified { - of: Arc::new(of), - qualifiers: Qualifiers::CONST, + let a_const = |of: ComputedType| { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(of), + is_const: true, + is_volatile: false, + })) }; - let a_volatile = |of: Type| Type::Qualified { - of: Arc::new(of), - qualifiers: Qualifiers::VOLATILE, + let a_volatile = |of: ComputedType| { + ComputedType::Qualified(Arc::new(QualifiedType { + of: Arc::new(of), + is_const: false, + is_volatile: true, + })) }; - let a_pointer = |of: Type| Type::Pointer { to: Arc::new(of) }; - let an_array = |of: Type, extent: Option| Type::Array { + let a_pointer = |of: ComputedType| ComputedType::Pointer(Arc::new(of)); + let an_array = |of: ComputedType, extent: Option| ComputedType::Array { of: Arc::new(of), extent, }; - let a_function = |returns: Type, parameters: Vec| Type::Function { - returns: Arc::new(returns), - parameters, + 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. @@ -2839,15 +2846,15 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { "the entry point answers the condition node, not the declaration" ); assert_eq!( - satisfies(&integral, &bind(Type::builtin("int"))), + satisfies(&integral, &bind(ComputedType::builtin("int"))), Some(true) ); assert_eq!( - satisfies(&integral, &bind(Type::builtin("double"))), + satisfies(&integral, &bind(ComputedType::builtin("double"))), Some(false) ); assert_eq!( - satisfies(&integral, &bind(Type::named("std::string"))), + satisfies(&integral, &bind(ComputedType::named("std::string", Vec::new()))), Some(false), "a class is not integral" ); @@ -2856,11 +2863,11 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { "typename std::enable_if::value, int>::type describe(T value)", ); assert_eq!( - satisfies(&floating, &bind(Type::builtin("double"))), + satisfies(&floating, &bind(ComputedType::builtin("double"))), Some(true) ); assert_eq!( - satisfies(&floating, &bind(Type::builtin("int"))), + satisfies(&floating, &bind(ComputedType::builtin("int"))), Some(false) ); @@ -2883,7 +2890,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { ("()", with_requires("std::is_integral()")), ] { assert_eq!( - satisfies(&condition, &bind(Type::builtin("long"))), + satisfies(&condition, &bind(ComputedType::builtin("long"))), Some(true), "{spelling} says a `long` is integral" ); @@ -2894,35 +2901,35 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("!std::is_integral::value"), - &bind(Type::builtin("double")) + &bind(ComputedType::builtin("double")) ), Some(true) ); assert_eq!( satisfies( &with_requires("std::is_integral::value && !std::is_same::value"), - &bind(Type::builtin("int")) + &bind(ComputedType::builtin("int")) ), Some(true) ); assert_eq!( satisfies( &with_requires("std::is_integral::value || std::is_floating_point::value"), - &bind(Type::builtin("float")) + &bind(ComputedType::builtin("float")) ), Some(true) ); assert_eq!( satisfies( &with_requires("std::is_same"), - &bind(Type::builtin("char")) + &bind(ComputedType::builtin("char")) ), Some(true) ); assert_eq!( satisfies( &with_requires("std::is_same_v"), - &bind(Type::builtin("int")) + &bind(ComputedType::builtin("int")) ), Some(false) ); @@ -2932,7 +2939,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("std::is_same, std::vector>"), - &bind(Type::builtin("int")) + &bind(ComputedType::builtin("int")) ), Some(true), "the same class template with the same argument" @@ -2940,7 +2947,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("std::is_same"), - &bind(a_reference(Type::builtin("int"))) + &bind(a_reference(ComputedType::builtin("int"))) ), Some(true) ); @@ -2948,7 +2955,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("std::is_user_defined::value"), - &bind(Type::builtin("int")) + &bind(ComputedType::builtin("int")) ), None, "a trait this layer does not know is *cannot tell*, never `false`" @@ -2956,7 +2963,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("std::is_integral::value"), - &bind(Type::builtin("int")) + &bind(ComputedType::builtin("int")) ), None, "an unbound parameter is cannot-tell as well" @@ -2966,56 +2973,56 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { for (condition, spelling, expected) in [ ( "std::is_reference_v", - a_reference(Type::builtin("int")), + a_reference(ComputedType::builtin("int")), true, ), ( "std::is_reference_v", - an_rvalue_reference(Type::builtin("int")), + an_rvalue_reference(ComputedType::builtin("int")), true, ), - ("std::is_reference_v", Type::builtin("int"), false), + ("std::is_reference_v", ComputedType::builtin("int"), false), ( "std::is_reference_v", - a_reference(Type::named("std::string")), + a_reference(ComputedType::named("std::string", Vec::new())), true, ), - ("std::is_const_v", a_const(Type::builtin("int")), true), - ("std::is_const_v", Type::builtin("int"), false), + ("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(Type::builtin("int"))), + a_pointer(a_const(ComputedType::builtin("int"))), false, ), ( "std::is_volatile_v", - a_volatile(Type::builtin("int")), + a_volatile(ComputedType::builtin("int")), true, ), - ("std::is_volatile_v", Type::builtin("int"), false), + ("std::is_volatile_v", ComputedType::builtin("int"), false), ( "std::is_array_v", - an_array(Type::builtin("int"), Some(4)), + an_array(ComputedType::builtin("int"), Some(4)), true, ), ( "std::is_array_v", - an_array(Type::builtin("int"), None), + an_array(ComputedType::builtin("int"), None), true, ), - ("std::is_array_v", Type::builtin("int"), false), + ("std::is_array_v", ComputedType::builtin("int"), false), ( "std::is_function_v", - a_function(Type::builtin("int"), vec![Type::builtin("int")]), + a_function(ComputedType::builtin("int"), vec![ComputedType::builtin("int")]), true, ), - ("std::is_function_v", Type::builtin("int"), false), + ("std::is_function_v", ComputedType::builtin("int"), false), ( "std::is_pointer_v", - a_pointer(Type::builtin("int")), + a_pointer(ComputedType::builtin("int")), true, ), - ("std::is_pointer_v", Type::builtin("int"), false), + ("std::is_pointer_v", ComputedType::builtin("int"), false), ] { assert_eq!( satisfies(&with_requires(condition), &bind(spelling)), @@ -3028,21 +3035,21 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { assert_eq!( satisfies( &with_requires("std::is_integral_v"), - &bind(Type::named("std::string")) + &bind(ComputedType::named("std::string", Vec::new())) ), Some(false) ); assert_eq!( satisfies( &with_requires("std::is_const_v"), - &bind(Type::named("U")) + &bind(ComputedType::named("U", Vec::new())) ), None ); assert_eq!( satisfies( &with_requires("std::is_class_v"), - &bind(Type::named("std::string")) + &bind(ComputedType::named("std::string", Vec::new())) ), None, "`is_class` is a symbol-table question" @@ -3451,10 +3458,11 @@ std::string f() { #[test] fn a_template_parameter_target_is_not_a_refusal() { use cpp_code_analysis::sema::convert::{Conversion, conversion_to}; - use cpp_code_analysis::sema::types::{Type, parse_type_spelling}; + use cpp_code_analysis::sema::types::parse_type_spelling; + use cpp_code_analysis::index::types::ComputedType; use cpp_parser::features::Family; - let an_int = Type::builtin("int"); + let an_int = ComputedType::builtin("int"); assert_eq!( conversion_to(&an_int, &parse_type_spelling("_Ty2&&"), None, |_| None), Conversion::Unknown, @@ -3466,13 +3474,11 @@ fn a_template_parameter_target_is_not_a_refusal() { "and so is a bare `T`" ); // **The structural answer**, when the declaration's template parameter list was in hand. - let a_parameter = Type::TemplateParameter { - name: "T".to_string(), - }; + let a_parameter = ComputedType::TemplateParameter("T".into()); assert_eq!( conversion_to(&an_int, &a_parameter, None, |_| None), Conversion::Unknown, - "`Type::TemplateParameter` is a template parameter, structurally" + "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!( @@ -3487,7 +3493,7 @@ fn a_template_parameter_target_is_not_a_refusal() { // **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_to(&a_string, &Type::builtin("int"), None, |_| None), + conversion_to(&a_string, &ComputedType::builtin("int"), None, |_| None), Conversion::Unknown ); @@ -3569,7 +3575,7 @@ fn a_template_parameter_target_is_not_a_refusal() { // **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, &Type::builtin("bool"), None, |_| None), + conversion_to(&a_pointer, &ComputedType::builtin("bool"), None, |_| None), Conversion::Implicit, ); } diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 6e218e19..284d09b3 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1836,18 +1836,14 @@ fn shown_returns_of(index: &ProjectIndex, fact: &DeclFact) -> Option { /// 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( - cpp_code_analysis::index::types::ComputedType::from( - &sema::types::parse_type_spelling(&written), - ), + 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( - cpp_code_analysis::index::types::ComputedType::from( - &sema::types::parse_type_spelling(&written), - ), + sema::types::parse_type_spelling(&written), )); } @@ -3536,9 +3532,7 @@ mod tests { // its return type is the computed value — exactly the shape `set_the_written_returns` produces. let other = DeclFact { returns: DeclaredType::Computed(std::sync::Arc::new( - cpp_code_analysis::index::types::ComputedType::from( - &sema::types::parse_type_spelling("std::size_t"), - ), + sema::types::parse_type_spelling("std::size_t"), )), ..fact.clone() }; From 69bb7ea571d4e9ff17e35d826079b0567e556583 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 14:14:46 +0800 Subject: [PATCH 083/102] refactor(constraints): store structured concept facts DeclDetail carries ConstraintFact { concept, arguments: Box<[ComputedType]> } aligned with the template parameters; the CST template-head reader lowers the concept node and its type arguments structurally, with the display string derived from the same value. concept_not_satisfied builds SameAs/ConvertibleTo/DerivedFrom from the fact and compares ComputedType directly; from_constraint and comma splitting are deleted. Codec versions move (CODEC 48, COOKED 12, UNIT 10). Workspace tests (3618 passed) and clippy pass. Remaining unstructurable forms: constrained non-type parameters and value template arguments, reported. --- crates/cpp_code_analysis/src/cache/summary.rs | 70 ++++++- .../src/cache/summary_codec.rs | 81 +++++++- .../cpp_code_analysis/src/cache/unit_codec.rs | 10 +- .../src/index/project/bases.rs | 3 + crates/cpp_code_analysis/src/lib.rs | 13 +- .../src/sema/check/concept_not_satisfied.rs | 175 ++++++++---------- .../sema/check/test/concept_not_satisfied.rs | 38 ++++ .../src/sema/declarations.rs | 136 +++++++++++--- crates/cpp_code_analysis/src/sema/types.rs | 154 +++++++++++---- 9 files changed, 508 insertions(+), 172 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index c587d7f2..191791f8 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -465,6 +465,8 @@ pub struct DeclFact { /// 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 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 [`ComputedType`] +/// values, because the alternative was storing a spelling a consumer would have to parse back into 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. @@ -477,8 +479,19 @@ pub struct DeclDetail { 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. + /// 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 them back into a type was the round trip this field removes. + 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. @@ -509,6 +522,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() @@ -516,6 +530,31 @@ 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 type arguments: `std::same_as`, `std::convertible_to` (and the two-argument spellings a file may +/// write, which are kept whole). 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 +/// [`ComputedType`], exactly the way every other type answer in this crate does, 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 type argument the concept wrote**, in the order it wrote them, lowered structurally. + /// + /// 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. + pub arguments: Box<[ComputedType]>, +} + 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 @@ -534,6 +573,7 @@ impl DeclDetail { + 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) @@ -548,6 +588,26 @@ 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 +/// trees that fell out of line. Each argument's [`ComputedType::heap_bytes`] already counts its own inline slot, the +/// same convention the type model uses; the slot array is counted here for the same reason [`strings_bytes`] counts +/// its element array, because the detail's own `size_of` covers 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(ComputedType::heap_bytes) + .sum::() + }) + .sum::() +} + /// 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) @@ -633,10 +693,18 @@ impl DeclFact { self.detail().map_or(&[], |detail| &detail.parameters) } + /// 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()) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index f7a7a6dd..adfaf6e1 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -337,7 +337,18 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// `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). -pub const CODEC_VERSION: u32 = 47; +/// +/// # 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). +pub const CODEC_VERSION: u32 = 48; /// **The version of the `ComputedType` grammar written inside a fact or parameter record.** /// @@ -1655,6 +1666,20 @@ mod tests { parameters: vec!["_Ty".into(), "_Alloc".into()], // The constraint in front of each parameter — empty here, and carried by the round trip. constraints: vec![SmolStr::default(), "Integral".into()], + // **The same constraints structurally**, in the same slots: the second parameter's concept + // carries a type argument, so the round trip exercises a nested type value and not only a + // name. The first slot is `None`, the shape an unconstrained parameter has. + constraint_facts: vec![ + None, + Some(summary::ConstraintFact { + concept: "same_as".into(), + arguments: vec![ComputedType::named( + "std::vector", + vec![ComputedType::Primary(PrimaryType::Int)], + )] + .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(), @@ -2091,6 +2116,24 @@ 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. A concept is a name and its + // arguments are type values, so this is written with the same [`ENCODED_COMPUTED_TYPE`] grammar the declaration's + // own types use — 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 { + put_u8(out, ENCODED_COMPUTED_TYPE); + put_computed_type(out, argument); + } + } + 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() { @@ -2170,6 +2213,29 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { 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 { + if reader.u8()? != ENCODED_COMPUTED_TYPE { + return Err(DecodeError::BadDiscriminant); + } + arguments.push(get_computed_type(reader, 0)?); + } + 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()?; @@ -2233,6 +2299,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), @@ -2325,7 +2392,12 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// 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. -const COOKED_VERSION: u32 = 11; +/// +/// 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. +const COOKED_VERSION: u32 = 12; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; @@ -2622,6 +2694,7 @@ fn a_cooked_reading_round_trips() { bases: vec!["Base".into()], parameters: vec!["T".into()], constraints: Vec::new(), + constraint_facts: Vec::new(), requires_clause: Some("sizeof(T) > 0".into()), parameter_defaults: Vec::new(), parameter_list: None, @@ -2661,6 +2734,10 @@ fn a_cooked_reading_round_trips() { bases: Vec::new(), parameters: Vec::new(), constraints: vec!["Copyable".into()], + constraint_facts: vec![Some(summary::ConstraintFact { + concept: "Copyable".into(), + arguments: Vec::new().into_boxed_slice(), + })], requires_clause: None, parameter_defaults: vec!["0".into()], parameter_list: Some("(int a)".into()), diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index e419eb93..6a8ebb6e 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -62,7 +62,15 @@ const MAGIC: [u8; 4] = *b"UNIT"; /// 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. -pub const UNIT_CODEC_VERSION: u32 = 9; +/// +/// 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. +pub const UNIT_CODEC_VERSION: u32 = 10; #[derive(Debug)] pub enum DecodeError { diff --git a/crates/cpp_code_analysis/src/index/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index fefaf05c..550973dd 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -481,6 +481,9 @@ pub(crate) fn fact_from_binding_with( .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) diff --git a/crates/cpp_code_analysis/src/lib.rs b/crates/cpp_code_analysis/src/lib.rs index 4611567d..e626afb2 100644 --- a/crates/cpp_code_analysis/src/lib.rs +++ b/crates/cpp_code_analysis/src/lib.rs @@ -146,12 +146,13 @@ pub use sema::{check, module_info, modules, parser_symbols, scopes, symbol}; pub use memory::MemoryReport; pub use summary::ConditionalBody; pub use summary::{ - ClosureEvidence, ConditionAt, ConditionalRegion, 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, + ClosureEvidence, ConditionAt, ConditionalRegion, 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/check/concept_not_satisfied.rs b/crates/cpp_code_analysis/src/sema/check/concept_not_satisfied.rs index a1def6f5..30b221e3 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,18 +28,21 @@ //! # 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 type arguments, lowered from the head's own `CppTemplateParam` nodes when the fact was built. 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::index::types::ComputedType; +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}; @@ -56,9 +59,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. @@ -69,25 +72,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(|constraints| { - constraints - .iter() - .map(ToString::to_string) - .collect::>() - }) - 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 { @@ -128,8 +126,8 @@ impl Check for ConceptNotSatisfied { fn constraints_of_a_declaration<'a>( context: &'a CheckContext<'_>, name: &str, -) -> Option<&'a [smol_str::SmolStr]> { - let mut own: Option<&[smol_str::SmolStr]> = None; +) -> Option<&'a [Option]> { + let mut own: Option<&[Option]> = None; let mut own_declarations = 0; for fact in context .declarations(DeclarationSource::Cooked) @@ -139,7 +137,7 @@ fn constraints_of_a_declaration<'a>( continue; } own_declarations += 1; - own = Some(fact.constraints()); + own = Some(fact.constraint_facts()); } match own_declarations { 0 => {} @@ -149,14 +147,14 @@ fn constraints_of_a_declaration<'a>( let index = context.model.index(); let declared = index.files_declaring(name, context.path); - let mut elsewhere: Option<&[smol_str::SmolStr]> = 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, @@ -171,12 +169,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`. /// @@ -187,50 +185,39 @@ 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), - }; - let name = head.rsplit("::").next().unwrap_or(head).trim(); + /// The fact is already the head's own answer: `sema::types` lowered the constrained parameter's `NamedType` or + /// `TemplateType` into a [`ComputedType`] 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. + fn from_fact(constraint: &ConstraintFact) -> Option { + let first_argument = || constraint.arguments.first().cloned(); - 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_argument()?)), + "convertible_to" => Some(Concept::ConvertibleTo(first_argument()?)), + "derived_from" => Some(Concept::DerivedFrom(first_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, } } @@ -257,10 +244,12 @@ impl Concept { 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, } } @@ -279,18 +268,18 @@ impl Concept { _ => Some(true), } } - Concept::ConvertibleTo(written) => { - // **The concept's argument, parsed once here.** The conversion below takes the `ComputedType`, not a - // spelling: the old form wrote the parsed shape back out and parsed it again, which is a second - // reader of the same question. C's tag is part of the parsed type now, so nothing is read beside it. - let target = sema::types::parse_type_spelling(written); - match passed.convertible_to(&target) { + Concept::ConvertibleTo(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_to(passed, &target, None, |_| None), + sema::convert::conversion_to(passed, target, None, |_| None), sema::convert::Conversion::Refused )), } @@ -377,35 +366,21 @@ fn is_a_floating_point(passed: &ComputedType) -> bool { }; 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: &ComputedType, - base: &str, + base: &ComputedType, ) -> Option { let (name, arguments): (&str, &[ComputedType]) = match derived { ComputedType::Named(name) => (name.as_str(), &[]), @@ -420,7 +395,9 @@ 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.to_string()]; let mut seen = std::collections::HashSet::new(); @@ -430,7 +407,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/test/concept_not_satisfied.rs b/crates/cpp_code_analysis/src/sema/check/test/concept_not_satisfied.rs index 5d0d0390..d73de037 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] diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 07393267..763af1bb 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -965,9 +965,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 { @@ -3843,32 +3843,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 @@ -3880,17 +3895,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` @@ -3901,13 +3916,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. /// @@ -4104,9 +4124,9 @@ fn fact_for( // 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`]. @@ -4267,7 +4287,12 @@ fn fact_for( // text once for the whole file rather than once per declaration. reflection: None, parameters: parameters.into_iter().map(SmolStr::from).collect(), - constraints: constraints.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.into_iter().map(SmolStr::from).collect(), pattern: pattern.map(Into::into), @@ -4314,10 +4339,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() @@ -6502,6 +6527,65 @@ 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 type 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::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], + ComputedType::Primary(PrimaryType::Int) + ); + assert_eq!( + structured.arguments[1], + 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" + ); + } + fn facts(source: &str) -> (Vec, summary::SummaryGuards) { let tree = CppParser::parse(source, ParserConfig::default()); assert_eq!(tree.get_errors(), [], "the input must parse cleanly"); diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 0f7dc367..6355216c 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -71,6 +71,7 @@ use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; +use crate::summary::ConstraintFact; use cpp_parser::CppArrayType; use cpp_parser::CppDeclaration; use cpp_parser::CppDeclarator; @@ -84,6 +85,7 @@ use cpp_parser::SourceRange; use cpp_parser::source_range; use cpp_parser::subtree_text_spaced; use cpp_parser::typed_descendants; +use smol_str::SmolStr; use std::sync::Arc; use cpp_parser::CppAstNode; @@ -769,9 +771,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() } @@ -782,12 +784,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() } @@ -797,10 +803,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 [`ComputedType`]-shaped 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 @@ -815,18 +842,23 @@ 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 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. Nothing here takes the constraint apart as text. +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 @@ -836,6 +868,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()) { @@ -857,38 +890,85 @@ 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; - } - constraint = trimmed; - } - - // A pack whose name came first (`Ts...`) leaves nothing in front, and so does an unconstrained parameter. - found.push((name, constraint, default)); + // **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 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`. +/// +/// The concept node is then lowered with [`read_specifiers`], the one reader a declaration's type goes through, so +/// its arguments are [`ComputedType`]s: `std::same_as` answers the concept `same_as` with *both* +/// arguments, and the display is the same value's canonical `Display`. No spelling is split here. +/// +/// [`CppDeclSpecifierSeq`]: cpp_parser::CppDeclSpecifierSeq +fn constrained_by(parameter: &CppTemplateParam) -> Option<(ConstraintFact, String)> { + let specifiers = parameter.get_decl_specifiers()?; + let node = specifiers.syntax(); + + 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; + } + + let lowered = read_specifiers(node); + // **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. + let display = lowered.to_string(); + let (name, arguments) = match lowered { + ComputedType::Named(name) => (name, Vec::new()), + ComputedType::Generic(generic) => (generic.name.clone(), generic.arguments.to_vec()), + _ => return None, + }; + let concept = name.rsplit("::").next().unwrap_or(&name).trim(); + if concept.is_empty() { + return None; + } + Some(( + ConstraintFact { + concept: SmolStr::from(concept), + arguments: arguments.into_boxed_slice(), + }, + display, + )) +} + /// **The default argument written for a template parameter**, if one is — `allocator<_Ty>` for /// `class _Alloc = allocator<_Ty>`. /// From 0eb0e9b069d7a3b1dd9099199ca8bb868f914d49 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 14:22:23 +0800 Subject: [PATCH 084/102] refactor(members): split alias targets structurally The alias fallback in substituted_members no longer prints a ComputedType and re-parses the display spelling: it takes the class name and arguments from the structured target. The primary string entry remains for callers that only hold a written spelling. --- .../src/index/project/substituted.rs | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/substituted.rs b/crates/cpp_code_analysis/src/index/project/substituted.rs index 60fa300e..333446f1 100644 --- a/crates/cpp_code_analysis/src/index/project/substituted.rs +++ b/crates/cpp_code_analysis/src/index/project/substituted.rs @@ -4,7 +4,6 @@ //! `names_define_static_array`) that the member and call walks rely on. use super::*; -use crate::sema::types::TypeSubstitutions; use crate::DeclFact; use crate::DeclKind; use crate::FileView; @@ -12,6 +11,7 @@ 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; @@ -72,14 +72,10 @@ pub(crate) fn substituted_at_the_use( continue; } let parsed = parse_type_spelling(default); - defaults.push(parsed.substituted(&TypeSubstitutions::new( - &names, - &written_arguments, - ))); + defaults.push(parsed.substituted(&TypeSubstitutions::new(&names, &written_arguments))); } - let substitutions = - 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. @@ -207,15 +203,19 @@ fn substituted_members_with( (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)) - .map(|computed| computed.to_string())?; - split_template_arguments(&target) + .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); }; @@ -463,8 +463,11 @@ impl MemberSubstitutionStage { { break; } - let next = - sema::types::substituted_spelling(&spelling, &self.alias_names, &self.alias_targets); + let next = sema::types::substituted_spelling( + &spelling, + &self.alias_names, + &self.alias_targets, + ); if next == spelling { break; } From 1d5238154f9bea9f8b31097b2e39a1eb3585243f Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 14:38:49 +0800 Subject: [PATCH 085/102] refactor(session): carry expression types structurally ExpressionType now carries type_value: Option beside the display spelling. Session::members_of_type and project::members_of_computed use the structured class directly (no split/reparse), and completion/hover member lookup prefers it. Removed leftover debug eprintln! calls in hover. Workspace tests (3618 passed) and clippy pass. --- .../src/index/project/members.rs | 20 ++++++++++++++ crates/cpp_code_analysis/src/session/calls.rs | 27 +++++++++++++++---- .../src/session/completion/request.rs | 14 ++++++++-- crates/cpp_code_analysis/src/session/mod.rs | 4 +++ crates/cpp_ls/src/handlers/hover/mod.rs | 12 ++------- 5 files changed, 60 insertions(+), 17 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index e45888bf..4f0f4a7b 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -961,6 +961,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 diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index 75b3fd91..c04e975f 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -491,7 +491,7 @@ impl Session { parameters: &[sema::overload::DeclaredParameters], template_parameters: &[Vec], ) -> Option<( - Vec>, + Vec>, Vec, )> { let token = token_at(&view.root, offset.get())?; @@ -514,7 +514,7 @@ 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, _)) => { @@ -637,8 +637,8 @@ impl Session { view: &FileView, offset: ReadingOffset, template_parameters: &[String], - parameters: &[crate::index::types::ComputedType], - ) -> Option> { + parameters: &[ComputedType], + ) -> Option> { if template_parameters.is_empty() { return None; } @@ -660,7 +660,7 @@ 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, _)) => { @@ -690,6 +690,23 @@ 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, diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 7c76b55b..7629fb63 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -560,6 +560,7 @@ impl Session { Known::Yes((type_of, file)) => Known::Yes(ExpressionType { expression: written, type_of: type_of.to_string(), + type_value: Some(type_of), file, }), Known::Unknown(reason) => Known::Unknown(reason), @@ -591,6 +592,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 +654,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), @@ -674,7 +677,10 @@ 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() @@ -689,6 +695,7 @@ impl Session { return Known::Yes(ExpressionType { expression: written, type_of: spelled.to_string(), + type_value: None, file, }); } @@ -995,7 +1002,10 @@ 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; }; diff --git a/crates/cpp_code_analysis/src/session/mod.rs b/crates/cpp_code_analysis/src/session/mod.rs index 6874364d..8f399faf 100644 --- a/crates/cpp_code_analysis/src/session/mod.rs +++ b/crates/cpp_code_analysis/src/session/mod.rs @@ -70,6 +70,7 @@ //! representable and simply not implemented. The store is what carries the single configuration today. use crate::IndexedRendering; +use crate::index::types::ComputedType; use crate::IndexedUnit; use crate::MacroDefinitions; use crate::MapReport; @@ -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_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 284d09b3..d5133091 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1407,9 +1407,6 @@ fn member_markdown( fact: member.fact, }; let displayed = session.index().member_display_fact(member); - if session.index().member_name(member) == "second" { - eprintln!("[member] sub={:?} raw={:?} shown={:?}", member.substitution, session.index().member_fact(member).map(|f| &f.type_of), displayed.as_ref().map(|f| &f.type_of)); - } declaration_markdown_with(session, view, &definition, displayed.as_ref(), None) } @@ -1815,11 +1812,9 @@ fn a_line(session: &Session, fact: &DeclFact) -> String { /// **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 { - let shown = index + index .type_spelling_of(fact) - .map(|spelled| spelled.to_string()); - if fact.name == "priority" { eprintln!("[hover] priority {:?} {:?}", fact.type_of, shown); } - shown + .map(|spelled| spelled.to_string()) } /// [`shown_type_of`] for a function's return type. @@ -2150,9 +2145,6 @@ fn declaration_markdown_with( return code_block("the answer names a file the index does not hold"); }; let found_fact = &found_fact; - if found_fact.name == "second" { - eprintln!("[card] substituted={} type={:?}", substituted.is_some(), found_fact.type_of); - } // **A return type read as a macro's name is corrected here.** `wincon.h` writes // // ```c From f1ab0b230d764734d16935b04d39dbf825fa161d Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 14:49:20 +0800 Subject: [PATCH 086/102] refactor(handlers): use structured expression types references and type-definition use ExpressionType.type_value when present instead of parsing the display spelling; type_definition looks up declarations by the structured class name. The string path remains only as a fallback for results that do not carry a type value. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_ls/src/handlers/references/mod.rs | 8 ++++- .../src/handlers/type_definition/mod.rs | 34 ++++++++++++++++--- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/crates/cpp_ls/src/handlers/references/mod.rs b/crates/cpp_ls/src/handlers/references/mod.rs index 1f4c43df..2e25de3b 100644 --- a/crates/cpp_ls/src/handlers/references/mod.rs +++ b/crates/cpp_ls/src/handlers/references/mod.rs @@ -1023,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, diff --git a/crates/cpp_ls/src/handlers/type_definition/mod.rs b/crates/cpp_ls/src/handlers/type_definition/mod.rs index 63e068ba..79498dca 100644 --- a/crates/cpp_ls/src/handlers/type_definition/mod.rs +++ b/crates/cpp_ls/src/handlers/type_definition/mod.rs @@ -130,8 +130,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 +159,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; } } @@ -189,16 +197,32 @@ 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: &cpp_code_analysis::index::types::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 { From 1434495a8167c1ef468898c66961dce5db885e21 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 14:56:23 +0800 Subject: [PATCH 087/102] refactor(inference): construct static types directly The remaining parse_type_spelling calls for the fixed std::ptrdiff_t, std::size_t and std::meta::info names now construct ComputedType::Named directly; no spelling is parsed for a type the compiler fixes. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_code_analysis/src/index/project/calls.rs | 4 ++-- crates/cpp_code_analysis/src/index/project/type_of.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 5145dbbd..62c1075a 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -465,10 +465,10 @@ 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() 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 7cb2b7fa..fa28403c 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -387,7 +387,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())); } From 3cf6b316b6b71de64d969609e3e3c5b1ff4366fd Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 15:08:49 +0800 Subject: [PATCH 088/102] refactor(deduction): read parameter and const structure Range deduction lowers a parameter's type with type_of_a_parameter instead of parsing get_type_text, and strip_a_leading_const peels ComputedType::Qualified structurally instead of printing and reparsing. The string fallback remains only for a parameter whose CST type cannot be lowered. Workspace tests (3618 passed) and clippy pass. --- .../src/index/project/deductions.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index ae73f5b5..485d572a 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -786,7 +786,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(); @@ -831,10 +832,11 @@ pub(crate) fn pair_component(element: &ComputedType, 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: &ComputedType) -> ComputedType { - let written = type_of.to_string(); - match written.strip_prefix("const ") { - Some(rest) => parse_type_spelling(rest), - None => type_of.clone(), + match type_of { + ComputedType::Qualified(qualified) if qualified.is_const && !qualified.is_volatile => { + (*qualified.of).clone() + } + _ => type_of.clone(), } } From 503bc3a24c4696ec7495d6f1c00b429284db4d8b Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 15:23:54 +0800 Subject: [PATCH 089/102] refactor(ranges): return element types structurally range_element_of and element_of now return ComputedType instead of a spelling: map elements construct std::pair directly, array elements clone their structured element, and member fallback uses member_computed_type. Callers no longer print and reparse the element. Workspace tests (3618 passed) and clippy pass. --- .../src/index/project/calls.rs | 3 +- .../src/index/project/deductions.rs | 58 +++++++++++-------- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 62c1075a..673b4324 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -427,7 +427,6 @@ 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(ComputedType::Qualified(Arc::new( crate::index::types::QualifiedType { of: Arc::new(element), @@ -931,7 +930,7 @@ 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 { diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index 485d572a..d8d0312a 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -92,7 +92,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()))), }) } @@ -169,7 +169,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 @@ -842,8 +842,7 @@ pub(crate) fn strip_a_leading_const(type_of: &ComputedType) -> ComputedType { /// **The element of the element** — `join`'s rule, for the shapes this layer can read. pub(crate) fn element_of_the_element(element: &ComputedType) -> Option { - let written = element_of(element, 0)?; - Some(parse_type_spelling(&written)) + element_of(element, 0) } /// **The element of the range an iterator expression came from** — `numbers.begin()`, `numbers.begin() + 3`. @@ -878,7 +877,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. @@ -925,7 +924,7 @@ pub(crate) fn as_a_range(type_of: &ComputedType) -> &ComputedType { /// /// 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: &ComputedType) -> 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 `ComputedType::Named` alone answered "this container has no element" for every @@ -935,7 +934,7 @@ pub(crate) fn range_element_of(container: &ComputedType) -> Option { // questions the member walk asks, and both see through `Reference` and `Qualified`. let Some(name) = container.class_name() else { return match container { - ComputedType::Array { of, .. } => Some(of.to_string()), + ComputedType::Array { of, .. } => Some((**of).clone()), _ => None, }; }; @@ -952,10 +951,19 @@ pub(crate) fn range_element_of(container: &ComputedType) -> 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( + crate::index::types::QualifiedType { + of: Arc::new(arguments[0].clone()), + is_const: true, + is_volatile: false, + }, )); + return Some(ComputedType::Generic(Arc::new( + crate::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 @@ -978,11 +986,11 @@ pub(crate) fn range_element_of(container: &ComputedType) -> 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 @@ -1521,11 +1529,11 @@ pub(crate) fn structured_binding_type( index.member_name(member) == wanted && index.member_kind(member) == Some(DeclKind::Variable) }) - .and_then(|member| index.member_type_spelling(member)) + .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,14 +1637,14 @@ pub(crate) fn initializer_of_the_pattern(pattern: &CppSyntaxNode) -> Option Option { +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 { - ComputedType::Array { of, .. } => Some(of.to_string()), + ComputedType::Array { of, .. } => Some((**of).clone()), _ => None, }; } @@ -1654,13 +1662,19 @@ pub(crate) fn element_of(container: &ComputedType, position: usize) -> Option`; 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( + crate::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. @@ -1682,14 +1696,12 @@ pub(crate) fn element_of(container: &ComputedType, position: usize) -> Option Date: Fri, 4 Dec 2026 15:28:08 +0800 Subject: [PATCH 090/102] refactor(hover): prefer structured object members The member hover asks Session::members_of_type with the expression's ComputedType first and falls back to the written spelling and arrow class only when the structured answer finds no member. Display still uses the written spelling. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_ls/src/handlers/hover/mod.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index d5133091..6661fef9 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1145,6 +1145,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 @@ -1168,8 +1169,15 @@ 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(view, class))) + { + if let Known::Yes(candidates) = candidates { if candidates .members .iter() From 195483e3e601521cec065b90c4258ff4fc619759 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 15:34:01 +0800 Subject: [PATCH 091/102] refactor(casts): lower cast targets structurally A named cast's TypeId node is lowered with type_of_a_type_id directly; the cast target text is no longer printed and reparsed. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_code_analysis/src/index/project/type_of.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) 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 fa28403c..a778c203 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -731,11 +731,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))), From ac5c88f16393ab3a2531d3cac021f3beb9ab9693 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 15:40:15 +0800 Subject: [PATCH 092/102] refactor(arrow): return reached types structurally Session::the_type_after_the_operator returns ComputedType; the class-after-operator helper reads class_name directly, and hover asks members_of_type for both the object and the reached arrow class. The standard-library pointee is reconstructed from its structured name and arguments rather than reparsed. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_code_analysis/src/session/units.rs | 25 ++++++++++--------- crates/cpp_ls/src/handlers/hover/mod.rs | 2 +- 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/crates/cpp_code_analysis/src/session/units.rs b/crates/cpp_code_analysis/src/session/units.rs index ec89dac6..ff1d26e2 100644 --- a/crates/cpp_code_analysis/src/session/units.rs +++ b/crates/cpp_code_analysis/src/session/units.rs @@ -1587,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 @@ -1612,7 +1611,7 @@ 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 @@ -1636,15 +1635,17 @@ impl Session { .unwrap_or_else(|| name.to_string()) } }; - if let Some((pointee, _)) = index::project::the_pointee_of_a_handle( - self.store.index(), - &view.scopes, - &view.root, - &view.path, - &class, - arguments, - ) { - return Some(pointee); + if let Some((pointee, pointee_arguments)) = + index::project::the_pointee_of_a_handle( + self.store.index(), + &view.scopes, + &view.root, + &view.path, + &class, + arguments, + ) + { + return Some(ComputedType::named(pointee, pointee_arguments)); } } completion::the_type_after_the_operator( @@ -1655,7 +1656,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_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 6661fef9..7256a325 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1175,7 +1175,7 @@ fn member_markdown( for candidates in own .into_iter() .chain(std::iter::once_with(|| session.members_of(view, &written))) - .chain(reached.iter().map(|class| session.members_of(view, class))) + .chain(reached.iter().map(|class| session.members_of_type(view, class))) { if let Known::Yes(candidates) = candidates { if candidates From 4dc3bd01fb37e422565b4a0f125b77504cc8bb05 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 15:45:30 +0800 Subject: [PATCH 093/102] refactor(inference): construct size_t directly The fixed size_t result is a ComputedType::Named construction, not a spelling parse. Workspace tests (3618 passed) and clippy pass. --- crates/cpp_code_analysis/src/index/project/type_of.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 a778c203..ccf8a56b 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -793,7 +793,7 @@ 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())); } } From 33ecf70155a381aec7971fc8cecb752001c63989 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 16:16:22 +0800 Subject: [PATCH 094/102] refactor(operators): return operator types structurally operator_returns_of, operator_returns_of_with_arguments and the_members_return now return ComputedType. The direct member path reads computed_returns_of and substitutes class_type.arguments() structurally; callers (co_await, binary/unary operators, deref, subscript, call-of-object, completion arrow) consume the value without reparsing. String-only fallbacks (base clause, deduced body, returns_in_the_class) parse once at their own boundary. New test pins T&/T* substitution for Box. Workspace tests (3619 passed) and clippy pass. --- .../src/index/project/calls.rs | 39 +++++- .../src/index/project/deductions.rs | 8 -- .../src/index/project/type_of.rs | 132 ++++++++++++------ .../src/session/completion/mod.rs | 2 +- crates/cpp_code_analysis/tests/suite/types.rs | 61 ++++++++ 5 files changed, 188 insertions(+), 54 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 673b4324..a7add8a7 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -387,7 +387,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 @@ -1869,7 +1869,44 @@ 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. +/// +/// # Why the walk itself is spelling-level +/// +/// An operator's return type is a value ([`crate::index::types::ComputedType`]), but the chain this follows is not: +/// `typename some_allocator::value_type&` is a **dependent name** — a template's argument list inside a qualified +/// name — and the model has no structural form for one, so the alias has to be read by the spelling the declaration +/// wrote. The one conversion happens here, at this fallback's boundary, and the answer is parsed once at the end: +/// a caller gets a type and never a spelling. pub(crate) fn a_members_answer_as_a_type( + index: &ProjectIndex, + scopes: &ScopeTree, + root: &CppSyntaxNode, + path: &Path, + 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 crate::index::types::PrimaryType::from_spelling(name).is_some() { + return returns.clone(); + } + let written = + a_members_answer_as_a_spelling(index, scopes, root, path, class_type, &returns.to_string()); + parse_type_spelling(&written) +} + +/// [`a_members_answer_as_a_type`]'s spelling-level half — see the note there on why this walk is a spelling one. +fn a_members_answer_as_a_spelling( index: &ProjectIndex, scopes: &ScopeTree, root: &CppSyntaxNode, diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index d8d0312a..6efbcd4f 100644 --- a/crates/cpp_code_analysis/src/index/project/deductions.rs +++ b/crates/cpp_code_analysis/src/index/project/deductions.rs @@ -1364,14 +1364,6 @@ 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(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 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 ccf8a56b..1d0bfca8 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -361,7 +361,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, @@ -370,9 +370,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))); @@ -902,7 +900,7 @@ pub(crate) fn type_of_expression_inner( &format!("operator{operator}"), ) { - return Known::Yes((parse_type_spelling(&returns), file)); + return Known::Yes((returns, file)); } if matches!( @@ -1031,7 +1029,7 @@ 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. @@ -1127,7 +1125,7 @@ pub(crate) fn type_of_expression_inner( &format!("operator{symbol}"), ) { - return Known::Yes((parse_type_spelling(&returns), file)); + return Known::Yes((returns, file)); } if symbol == "!" { Known::Yes((ComputedType::named("bool", Vec::new()), path.to_path_buf())) @@ -1267,11 +1265,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))), @@ -1921,9 +1919,11 @@ 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, @@ -1932,7 +1932,7 @@ pub(crate) fn operator_returns_of( path: &Path, class_type: &ComputedType, operator: &str, -) -> Option { +) -> Option { operator_returns_of_with_arguments( index, declaring, @@ -1961,7 +1961,7 @@ pub(crate) fn operator_returns_of_with_arguments( // **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 @@ -2251,6 +2251,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, ) @@ -2298,6 +2299,7 @@ pub(crate) fn operator_returns_of_with_arguments( &fact, member_file.as_path(), parameter_names, + class_type.arguments(), &written_arguments, argument_types, ) { @@ -2342,9 +2344,12 @@ pub(crate) fn operator_returns_of_with_arguments( != object_is_const })?; 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 - .member_returns_spelling(found) - .or_else(|| found_fact.returns_in_the_class().map(str::to_string))?; + .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->`, @@ -2353,7 +2358,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, @@ -2361,7 +2374,7 @@ pub(crate) fn operator_returns_of_with_arguments( path, &class, &found.declared_in, - &returns, + &written, parameter_names, &written_arguments, ) @@ -2369,19 +2382,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, @@ -2392,15 +2433,17 @@ fn the_members_return( fact: &DeclFact, member_file: &Path, parameter_names: &[String], + class_arguments: &[ComputedType], written_arguments: &[String], argument_types: &[ComputedType], -) -> Option { +) -> Option { let _ = (index, scopes, root, path); + // **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 - .returns_spelling_of(fact) - .map(|spelled| spelled.to_string()) - .or_else(|| fact.returns_in_the_class().map(str::to_string)); - if returns.as_deref().is_none_or(is_a_placeholder) + .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, @@ -2413,11 +2456,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. @@ -2528,7 +2567,7 @@ fn deduced_returns_of_the_member( parameter_names: &[String], written_arguments: &[String], argument_types: &[ComputedType], -) -> Option { +) -> 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 @@ -2605,11 +2644,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.** @@ -2657,8 +2698,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, @@ -2669,7 +2713,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 { @@ -2714,14 +2758,14 @@ pub(crate) fn a_base_operators_return( && 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 diff --git a/crates/cpp_code_analysis/src/session/completion/mod.rs b/crates/cpp_code_analysis/src/session/completion/mod.rs index 9f43e21a..5e0a5c58 100644 --- a/crates/cpp_code_analysis/src/session/completion/mod.rs +++ b/crates/cpp_code_analysis/src/session/completion/mod.rs @@ -876,7 +876,7 @@ pub(crate) fn the_type_after_the_operator( // 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; } diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 5caa650c..42c300ee 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2098,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: From a570ad496ae954cff99f3977c75ec261aa796eb3 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 16:22:07 +0800 Subject: [PATCH 095/102] refactor(subscript): keep concrete class answers structured a_members_answer_as_a_type returns the structural type directly for a non-dependent name declared as a class; only aliases and dependent members use the spelling walk. This keeps the common subscript path off the string round trip. Workspace tests (3619 passed) and clippy pass. --- .../cpp_code_analysis/src/index/project/calls.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index a7add8a7..175236a3 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1900,6 +1900,21 @@ pub(crate) fn a_members_answer_as_a_type( if crate::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 spelling walk. This keeps the common subscript answer off the string path. + 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(); + } + } let written = a_members_answer_as_a_spelling(index, scopes, root, path, class_type, &returns.to_string()); parse_type_spelling(&written) From d0e73a1b880945918ade1e2cd7b3221dd87f832b Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 16:28:19 +0800 Subject: [PATCH 096/102] clean code --- .../src/cache/summary_codec.rs | 45 +++---- .../cpp_code_analysis/src/cache/unit_codec.rs | 3 +- .../src/index/project/bases.rs | 5 +- .../src/index/project/calls.rs | 60 +++++---- .../src/index/project/completions.rs | 5 +- .../src/index/project/deductions.rs | 35 +++-- .../src/index/project/macro_environment.rs | 14 +- .../src/index/project/macro_walk.rs | 24 ++-- .../src/index/project/members.rs | 23 +--- .../src/index/project/mod.rs | 31 ++--- .../src/index/project/tests.rs | 9 +- .../src/index/project/type_of.rs | 123 ++++++++++-------- .../src/index/types/compute.rs | 73 ++++++----- .../src/index/types/semantics.rs | 66 +++++----- .../cpp_code_analysis/src/sema/call_syntax.rs | 5 +- .../src/sema/check/argument_count.rs | 3 +- .../src/sema/check/assign_type_check.rs | 6 +- .../src/sema/check/concept_not_satisfied.rs | 6 +- .../src/sema/check/missing_include.rs | 3 +- .../cpp_code_analysis/src/sema/check/mod.rs | 16 +-- .../src/sema/check/param_type_check.rs | 44 ++++--- .../sema/check/pure_virtual_not_overridden.rs | 12 +- .../src/sema/check/undefined_name.rs | 2 +- .../src/sema/check/use_override.rs | 10 +- .../cpp_code_analysis/src/sema/constraint.rs | 9 +- crates/cpp_code_analysis/src/sema/convert.rs | 25 ++-- .../src/sema/declarations.rs | 42 +++--- .../cpp_code_analysis/src/sema/deduction.rs | 14 +- crates/cpp_code_analysis/src/sema/model.rs | 16 ++- crates/cpp_code_analysis/src/sema/overload.rs | 12 +- crates/cpp_code_analysis/src/sema/types.rs | 37 +++--- crates/cpp_code_analysis/src/session/calls.rs | 27 ++-- .../src/session/completion/request.rs | 7 +- .../src/session/definition.rs | 16 ++- crates/cpp_code_analysis/src/session/inlay.rs | 7 +- crates/cpp_code_analysis/src/session/mod.rs | 2 +- .../cpp_code_analysis/src/session/queries.rs | 9 +- .../cpp_code_analysis/src/session/semantic.rs | 2 +- .../src/session/signature.rs | 21 ++- crates/cpp_code_analysis/src/session/units.rs | 24 ++-- .../cpp_code_analysis/tests/suite/semantic.rs | 25 +++- crates/cpp_code_analysis/tests/suite/types.rs | 41 ++++-- .../tests/suite/ue_engine.rs | 5 +- crates/cpp_inspect/src/questions.rs | 12 +- crates/cpp_ls/src/handlers/hover/mod.rs | 53 ++++---- 45 files changed, 556 insertions(+), 473 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index adfaf6e1..f1956e2c 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -27,6 +27,7 @@ use crate::DeclaredType; use crate::DirectiveKind; use crate::FORMAT_VERSION; use crate::READING_FINGERPRINT; +use crate::index; use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::macros; use crate::preprocess; @@ -1286,7 +1287,7 @@ fn get_computed_type(reader: &mut Reader<'_>, depth: u32) -> Result, facts: &[crate::index::params::ParameterFact]) { +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()); @@ -1313,7 +1314,7 @@ fn put_parameter_facts(out: &mut Vec, facts: &[crate::index::params::Paramet fn get_parameter_facts( reader: &mut Reader<'_>, -) -> Result, DecodeError> { +) -> Result, DecodeError> { let count = reader.count()?; let mut facts = Vec::with_capacity(count.min(64 * 1024)); for _ in 0..count { @@ -1339,7 +1340,7 @@ fn get_parameter_facts( }; let pack = reader.u8()? != 0; let type_of = get_declared_type(reader)?; - facts.push(crate::index::params::ParameterFact { + facts.push(index::params::ParameterFact { name, declaration, default_value, @@ -1350,22 +1351,20 @@ fn get_parameter_facts( Ok(facts) } -fn put_params_store(out: &mut Vec, store: &crate::index::params::ParamsStore) { +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 { +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(crate::index::params::ParamsStore::from_entries(entries)) + Ok(index::params::ParamsStore::from_entries(entries)) } fn put_opt_str(out: &mut Vec, value: Option<&str>) { @@ -1572,6 +1571,8 @@ fn symbol_kind_code(kind: SymbolKind) -> u8 { #[cfg(test)] mod tests { + use crate::index; + use crate::sema; use std::sync::Arc; use super::Access; @@ -1610,7 +1611,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: crate::index::params::ParamsStore::default(), + 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 @@ -1625,7 +1626,7 @@ mod tests { type_of: DeclaredType::None, // A class returns nothing either, so `None` — and the second fact below covers the other value. returns: DeclaredType::None, - parameters: crate::index::params::ParamsId::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. @@ -1710,7 +1711,7 @@ mod tests { ComputedType::Primary(PrimaryType::Int), ], )), - parameters: crate::index::params::ParamsId::NONE, + 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 @@ -1740,12 +1741,12 @@ mod tests { kind: DeclKind::Other, modifiers: DeclModifiers::default(), type_of: computed(ComputedType::Qualified(Arc::new( - crate::index::types::QualifiedType { + index::types::QualifiedType { of: Arc::new(ComputedType::Pointer(Arc::new(ComputedType::named( "std::vector", vec![ ComputedType::ElaboratedRecord { - tag: crate::sema::types::RecordTag::Union, + tag: sema::types::RecordTag::Union, of: Arc::new(ComputedType::Named(SmolStr::new("value"))), }, ComputedType::Array { @@ -1760,7 +1761,7 @@ mod tests { }, ))), returns: DeclaredType::None, - parameters: crate::index::params::ParamsId::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, @@ -1938,7 +1939,7 @@ mod tests { ComputedType::named("std::vector", vec![ComputedType::Primary(PrimaryType::Int)]), ComputedType::TemplateParameter(SmolStr::new("T")), ComputedType::ElaboratedRecord { - tag: crate::sema::types::RecordTag::Struct, + tag: sema::types::RecordTag::Struct, of: Arc::new(ComputedType::Named(SmolStr::new("point"))), }, ComputedType::Pointer(Arc::new(ComputedType::Primary(PrimaryType::Int))), @@ -1950,14 +1951,14 @@ mod tests { of: Arc::new(ComputedType::Primary(PrimaryType::Char)), extent: None, }, - ComputedType::Function(Arc::new(crate::index::types::FunctionType { + 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(crate::index::types::QualifiedType { + ComputedType::Qualified(Arc::new(index::types::QualifiedType { of: Arc::new(ComputedType::Named(SmolStr::new("Widget"))), is_const: true, is_volatile: true, @@ -2208,7 +2209,7 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let kind = decl_kind_from(reader.u8()?)?; let type_of = get_declared_type(reader)?; let returns = get_declared_type(reader)?; - let parameters_id = crate::index::params::ParamsId::from_raw(reader.u32()?); + 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)?; @@ -2655,8 +2656,8 @@ fn a_cooked_reading_round_trips() { // **The reading's own parameter table**: a fact's `ParamsId` is local to the reading, so the table travels // with the record and `ProjectIndex::insert_cooked` imports it. Types need no table — each fact carries its // value. - parameters: crate::index::params::ParamsStore::from_entries(vec![ - vec![crate::index::params::ParameterFact { + parameters: index::params::ParamsStore::from_entries(vec![ + vec![index::params::ParameterFact { name: Some("value".into()), declaration: cpp_parser::CppSyntaxId::from_raw_parts(0, 0, 1).expect("a syntax id"), default_value: None, @@ -2673,7 +2674,7 @@ fn a_cooked_reading_round_trips() { kind: DeclKind::Type, type_of: DeclaredType::None, returns: DeclaredType::None, - parameters: crate::index::params::ParamsId::NONE, + parameters: index::params::ParamsId::NONE, // The class is not variadic; the function below is, which is how both values of the byte are // covered by the record that carries them. variadic_parameters: false, @@ -2713,7 +2714,7 @@ fn a_cooked_reading_round_trips() { kind: DeclKind::Function, type_of: DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Int))), returns: DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Void))), - parameters: crate::index::params::ParamsId::from_raw(0), + 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, diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 6a8ebb6e..effb247b 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -528,6 +528,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() { @@ -536,7 +537,7 @@ mod index_tests { PathBuf::from("/p/a.h"), CookedFile { declarations: Vec::new(), - parameters: crate::index::params::ParamsStore::default(), + 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/project/bases.rs b/crates/cpp_code_analysis/src/index/project/bases.rs index 550973dd..56878261 100644 --- a/crates/cpp_code_analysis/src/index/project/bases.rs +++ b/crates/cpp_code_analysis/src/index/project/bases.rs @@ -9,6 +9,7 @@ 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; @@ -265,7 +266,7 @@ pub(crate) fn arguments_in_a_spelling(written: &str) -> Option> { /// 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<[crate::index::params::ParameterFact]>, + pub parameters: Box<[index::params::ParameterFact]>, } /// One binding as a [`DeclFact`], under the qualified name of the scope it was written in. @@ -442,7 +443,7 @@ pub(crate) fn fact_from_binding_with( // **`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: crate::index::params::ParamsId::NONE, + 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`]. diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 175236a3..6f31b37a 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; @@ -374,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, ComputedType::Named(_) | ComputedType::Generic(_)) + && matches!( + callee_type, + ComputedType::Named(_) | ComputedType::Generic(_) + ) && let Some(returns) = operator_returns_of_with_arguments( index, declaring, @@ -428,7 +432,7 @@ pub(crate) fn type_of_a_call( && let Some(element) = range_element_of(as_a_range(&argument)) { let element = Arc::new(ComputedType::Qualified(Arc::new( - crate::index::types::QualifiedType { + index::types::QualifiedType { of: Arc::new(element), is_const: true, is_volatile: false, @@ -464,10 +468,16 @@ pub(crate) fn type_of_a_call( } } "count" | "count_if" | "distance" | "ssize" => { - return Known::Yes((ComputedType::named("std::ptrdiff_t", Vec::new()), path.to_path_buf())); + return Known::Yes(( + ComputedType::named("std::ptrdiff_t", Vec::new()), + path.to_path_buf(), + )); } "size" => { - return Known::Yes((ComputedType::named("std::size_t", Vec::new()), 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() @@ -772,8 +782,8 @@ pub(crate) fn the_return_the_overloads_agree_on( // 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); + let variadic = + candidate_fact.variadic_parameters || list.iter().any(|parameter| parameter.pack); if !a_candidate_that_can_be_called_this_way( parameters.as_deref(), variadic, @@ -1142,8 +1152,7 @@ pub(crate) fn declaration_of_a_callee( .map(|callee| written_template_arguments(&callee)) .unwrap_or_default() .to_vec(); - if let Some(chosen) = - the_one_the_arguments_select(&types, &candidates, &explicit_arguments) + if let Some(chosen) = the_one_the_arguments_select(&types, &candidates, &explicit_arguments) && let Some(binding) = bindings.get(chosen) { return Known::Yes(NamedDeclaration::Here(binding.clone())); @@ -1547,15 +1556,15 @@ impl CandidateDeclaration { pub(crate) fn with_parameters( file: &Path, fact: DeclFact, - parameters: &[crate::index::params::ParameterFact], + 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); + let variadic = + fact.variadic_parameters || parameters.iter().any(|parameter| parameter.pack); CandidateDeclaration { fact, file: file.to_path_buf(), @@ -1586,7 +1595,12 @@ pub(crate) fn the_one_the_arguments_select( // 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].fact.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 @@ -1698,11 +1712,10 @@ pub(crate) fn the_character_width(type_of: &ComputedType) -> Option { } ComputedType::Pointer(to) | ComputedType::Pack(to) - | ComputedType::ElaboratedRecord { of: to, .. } => { + | ComputedType::ElaboratedRecord { of: to, .. } => pending.push(to), + ComputedType::Reference { to, .. } | ComputedType::Array { 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()); @@ -1897,7 +1910,7 @@ pub(crate) fn a_members_answer_as_a_type( let Some(name) = returns.bare_name() else { return returns.clone(); }; - if crate::index::types::PrimaryType::from_spelling(name).is_some() { + 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 @@ -1964,12 +1977,9 @@ fn a_members_answer_as_a_spelling( // **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 = ComputedType::named( - qualified, - target.arguments().to_vec(), - ); + let resolved = ComputedType::named(qualified, target.arguments().to_vec()); class_type = match class_type.is_const() && !resolved.is_const() { - true => ComputedType::Qualified(Arc::new(crate::index::types::QualifiedType { + true => ComputedType::Qualified(Arc::new(index::types::QualifiedType { of: Arc::new(resolved), is_const: true, is_volatile: false, @@ -2024,8 +2034,12 @@ fn a_members_answer_as_a_spelling( let Some(target) = index.type_spelling_of(&fact) else { return substituted; }; - let target = - sema::types::substituted_spelling_with_defaults(&target, ¶meters, &defaults, &arguments); + 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`. diff --git a/crates/cpp_code_analysis/src/index/project/completions.rs b/crates/cpp_code_analysis/src/index/project/completions.rs index fba7aae7..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; @@ -222,7 +223,7 @@ pub(crate) fn written_before_the_cursor( pub struct OfferedName { /// 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: crate::FileId, + 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 @@ -1057,7 +1058,7 @@ pub(crate) fn declared_above(fact: &DeclFact, offset: usize) -> bool { pub(crate) struct Candidate { /// 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: crate::FileId, + 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. diff --git a/crates/cpp_code_analysis/src/index/project/deductions.rs b/crates/cpp_code_analysis/src/index/project/deductions.rs index 6efbcd4f..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; @@ -615,9 +616,7 @@ fn the_alternatives_a_visit_hands( let target = index .files_declaring(&name, path) .into_iter() - .find(|declared| { - declared.fact.kind == DeclKind::Type && declared.fact.has_type_of() - }) + .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, @@ -628,7 +627,11 @@ fn the_alternatives_a_visit_hands( if !(class == "std::variant" || class == "variant") { return None; } - let alternatives: Vec = resolved.arguments().iter().map(ToString::to_string).collect(); + let alternatives: Vec = resolved + .arguments() + .iter() + .map(ToString::to_string) + .collect(); (!alternatives.is_empty()).then_some(alternatives) } @@ -951,19 +954,15 @@ pub(crate) fn range_element_of(container: &ComputedType) -> Option "map" | "unordered_map" | "multimap" | "unordered_multimap" ) && arguments.len() >= 2 { - let first = ComputedType::Qualified(Arc::new( - crate::index::types::QualifiedType { - of: Arc::new(arguments[0].clone()), - is_const: true, - is_volatile: false, - }, - )); - return Some(ComputedType::Generic(Arc::new( - crate::index::types::GenericType { - name: smol_str::SmolStr::new("std::pair"), - arguments: Box::new([first, arguments[1].clone()]), - }, - ))); + 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 @@ -1655,7 +1654,7 @@ pub(crate) fn element_of(container: &ComputedType, position: usize) -> Option Some(ComputedType::Qualified(Arc::new( - crate::index::types::QualifiedType { + index::types::QualifiedType { of: Arc::new(arguments[0].clone()), is_const: true, is_volatile: false, 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 400d1c15..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,6 +7,8 @@ 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; @@ -40,7 +42,7 @@ impl DeclFactId { /// is local to it, exactly as [`DeclFactId`] documents. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct FactRef { - pub file: crate::FileId, + 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, @@ -392,7 +394,7 @@ impl IndexedKind { /// [`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: crate::FileId, + pub file: FileId, pub fact: FactRef, } @@ -595,7 +597,11 @@ impl MemberSubstitution { .map(|(name, _)| name.len().saturating_sub(22)) .sum::() + self.stages.len() * size_of::() - + self.stages.iter().map(MemberSubstitutionStage::heap_bytes).sum::() + + self + .stages + .iter() + .map(MemberSubstitutionStage::heap_bytes) + .sum::() } } @@ -681,7 +687,7 @@ fn fact_from_a_binding(binding: Binding, scope: Option, local: bool) -> // is never answered with — [`ProjectDefinition`] answers with the reference to the arena entry. type_of: DeclaredType::None, returns: DeclaredType::None, - parameters: crate::index::params::ParamsId::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. 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 560ae9a6..c14c498a 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -7,6 +7,7 @@ use super::*; use crate::DeclModifiers; use crate::FactGuard; +use crate::FileId; use crate::MacroKind; use crate::ProjectMember; use crate::UnlistedBase; @@ -496,7 +497,7 @@ impl ProjectIndex { /// (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: crate::FileId) { + pub fn register_file_id(&mut self, path: &Path, id: FileId) { self.file_ids.register(path, id); } @@ -512,7 +513,7 @@ impl ProjectIndex { /// 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 { + pub fn file_id_of(&self, path: &Path) -> Option { if let Some(id) = self.file_ids.id_of(path) { return Some(id); } @@ -534,7 +535,7 @@ impl ProjectIndex { /// 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: crate::FileId) -> Option<&Path> { + 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) { @@ -778,7 +779,7 @@ impl ProjectIndex { /// no list (a macro, a generated member) passes the empty one. pub fn intern_synthetic_fact( &self, - file: crate::FileId, + file: FileId, fact: DeclFact, parameters: Box<[ParameterFact]>, ) -> FactRef { @@ -838,7 +839,7 @@ impl ProjectIndex { .view_paths .lock() .expect("the view fact table is not poisoned"); - crate::FileId::new(paths.id_of(path)) + FileId::new(paths.id_of(path)) } }; self.intern_synthetic_fact(file, fact, parameters) @@ -981,7 +982,10 @@ impl ProjectIndex { } let mut shown = fact.clone(); if shown.name == "second" { - eprintln!("[display] sub={:?} base={:?}", member.substitution, fact.type_of); + eprintln!( + "[display] sub={:?} base={:?}", + member.substitution, fact.type_of + ); } shown.type_of = self .member_computed_type(member) @@ -1035,12 +1039,12 @@ impl ProjectIndex { // 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(); + 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(crate::FileId::new) + && let Some(id) = viewed.get(file).map(FileId::new) && !ids.contains(&id) { ids.push(id); @@ -1982,13 +1986,13 @@ impl ProjectIndex { .file_ids .by_path .keys() - .map(|path| path.len() + size_of::() + size_of::()) + .map(|path| path.len() + size_of::() + size_of::()) .sum::() + self .file_ids .by_id .values() - .map(|path| path.len() + size_of::() + size_of::()) + .map(|path| path.len() + size_of::() + size_of::()) .sum::(); TableCost { diff --git a/crates/cpp_code_analysis/src/index/project/members.rs b/crates/cpp_code_analysis/src/index/project/members.rs index 4f0f4a7b..6d5d1777 100644 --- a/crates/cpp_code_analysis/src/index/project/members.rs +++ b/crates/cpp_code_analysis/src/index/project/members.rs @@ -534,13 +534,10 @@ pub(crate) fn the_arguments_a_braced_initialisation_deduces( .map(|fact| fact.parameters().to_vec()) .unwrap_or_default() } - _ => listed - .members - .iter() - .find_map(|member| { - let parameters = index.member_fact(member)?.parameters(); - (!parameters.is_empty()).then(|| 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() { @@ -1403,11 +1400,7 @@ pub(crate) fn members_of_inner( ambiguous: false, }) .collect(); - own.sort_by(|one, other| { - index - .member_name(one) - .cmp(index.member_name(other)) - }); + 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); @@ -1636,11 +1629,7 @@ pub(crate) fn members_of_inner( !hidden.contains(index.member_name(member)) || re_exposed.contains(index.member_name(member)) }); - found.sort_by(|one, other| { - index - .member_name(one) - .cmp(index.member_name(other)) - }); + 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); diff --git a/crates/cpp_code_analysis/src/index/project/mod.rs b/crates/cpp_code_analysis/src/index/project/mod.rs index 1dae2589..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,8 +47,8 @@ use super::names::{NameIndex, Posting}; use crate::Visibility; use crate::file::paths::normalize_path; use crate::include::graph::Marked; -use crate::preprocess::directive::IncludeForm; use crate::index::types::ComputedType; +use crate::preprocess::directive::IncludeForm; use crate::sema::types::{TypeBindings, parse_type_spelling}; use crate::summary::{DeclFact, DeclKind, DeclaredType, FactGuard, FileSummary, MacroFact}; use crate::symbol::{Known, UnknownReason}; @@ -118,7 +120,7 @@ pub struct CookedFile { /// 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: crate::index::params::ParamsStore, + 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. /// @@ -152,7 +154,7 @@ impl CookedFile { pub fn declarations(declarations: Vec) -> Self { CookedFile { declarations, - parameters: crate::index::params::ParamsStore::default(), + parameters: index::params::ParamsStore::default(), macros: Vec::new(), diagnostics: Vec::new(), unplaced: 0, @@ -303,16 +305,15 @@ const FALLBACK_FILE_ID_BIT: u32 = 0x8000_0000; 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(|| crate::FileId::new(FALLBACK_FILE_ID_BIT | sequence)) +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: crate::FileId) -> Option { +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) } @@ -330,18 +331,18 @@ fn fallback_sequence(file: crate::FileId) -> Option { /// the table already gave true. #[derive(Debug, Default)] struct FileIdTable { - by_path: HashMap, - by_id: HashMap, + 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 { + 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: crate::FileId) -> Option<&str> { + fn key_of(&self, id: FileId) -> Option<&str> { self.by_id.get(&id).map(String::as_str) } @@ -357,7 +358,7 @@ impl FileIdTable { /// /// 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: crate::FileId) -> bool { + fn register(&mut self, path: &Path, id: FileId) -> bool { if fallback_sequence(id).is_some() { return false; } @@ -463,7 +464,7 @@ pub struct ProjectIndex { /// is complete about and what it deliberately is not. macros: Marked, /// The interned parameter lists of every declaration this index has inserted. - parameters: crate::index::params::ParamsStore, + 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. /// @@ -744,9 +745,9 @@ impl ViewFactPaths { /// [`ProjectIndex`]'s `synthetic_facts` field for why this is an arena and not a second store. #[derive(Debug)] struct SyntheticFactEntry { - file: crate::FileId, + file: FileId, fact: &'static DeclFact, - parameters: &'static [crate::index::params::ParameterFact], + parameters: &'static [index::params::ParameterFact], } /// One entry of [`ProjectIndex::member_lists`]: the members, and **what the answer was made of**. diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 405ee00b..14fc6d96 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,6 +11,7 @@ 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; @@ -30,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; @@ -272,7 +275,7 @@ fn a_vfs_id_registered_before_the_summary_resolves_the_path_and_the_facts() { } /// A row whose only content is a fact reference, for asking the resolvers that take a `ProjectMember`. -fn member_row(fact: super::FactRef) -> ProjectMember { +fn member_row(fact: FactRef) -> ProjectMember { ProjectMember { fact, substitution: None, @@ -322,7 +325,7 @@ fn a_cached_summary_keeps_its_type_values() { let mut first = ProjectIndex::new(); first.insert(summarize(path, source, SummaryKey::new(0, 0))); let stored = first.summary(path).expect("inserted"); - let decoded = crate::cache::summary_codec::decode(&crate::cache::summary_codec::encode(stored)) + let decoded = cache::summary_codec::decode(&cache::summary_codec::encode(stored)) .expect("the summary round-trips"); let restored = decoded .declarations @@ -2384,7 +2387,7 @@ impl ResolvedMember { #[derive(Debug)] struct ResolvedList { members: Vec, - unlisted: Vec, + unlisted: Vec, } impl ResolvedList { 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 1d0bfca8..51df53cb 100644 --- a/crates/cpp_code_analysis/src/index/project/type_of.rs +++ b/crates/cpp_code_analysis/src/index/project/type_of.rs @@ -5,7 +5,6 @@ //! expensive so that a completion or a diagnostic asking twice pays once. use super::*; -use crate::sema::types::TypeSubstitutions; use crate::Binding; use crate::BindingKind; use crate::DeclFact; @@ -19,6 +18,7 @@ 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; @@ -174,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() } @@ -520,7 +523,10 @@ pub(crate) fn type_of_expression_inner( .chars() .all(|character| !character.is_ascii_lowercase()) { - return Known::Yes((ComputedType::named(callee.trim(), Vec::new()), 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 @@ -791,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((ComputedType::named("size_t", Vec::new()), path.to_path_buf())); + return Known::Yes(( + ComputedType::named("size_t", Vec::new()), + path.to_path_buf(), + )); } } @@ -889,17 +898,18 @@ pub(crate) fn type_of_expression_inner( path, &left, depth + 1, - ) && matches!(left_class, ComputedType::Named(_) | ComputedType::Generic(_)) - && let Some(returns) = operator_returns_of( - index, - declaring, - scopes, - root, - path, - &left_class, - &format!("operator{operator}"), - ) - { + ) && 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)); } @@ -1009,11 +1019,11 @@ pub(crate) fn type_of_expression_inner( // declared, and a class that declared nothing is the iterator model's case. Some(pointee) if !matches!( - type_of, - ComputedType::Named(_) - | ComputedType::Generic(_) - | ComputedType::TemplateParameter(_) - ) => + type_of, + ComputedType::Named(_) + | ComputedType::Generic(_) + | ComputedType::TemplateParameter(_) + ) => { Known::Yes(((*pointee).clone(), file)) } @@ -1036,9 +1046,7 @@ pub(crate) fn type_of_expression_inner( match &type_of { ComputedType::Named(_) | ComputedType::Generic(_) - | ComputedType::TemplateParameter(_) => { - Known::Yes((type_of, file)) - } + | 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))), @@ -1114,17 +1122,15 @@ pub(crate) fn type_of_expression_inner( ComputedType::Named(_) | ComputedType::Generic(_) | ComputedType::TemplateParameter(_) - ) - && let Some(returns) = operator_returns_of( - index, - declaring, - scopes, - root, - path, - &type_of, - &format!("operator{symbol}"), - ) - { + ) && let Some(returns) = operator_returns_of( + index, + declaring, + scopes, + root, + path, + &type_of, + &format!("operator{symbol}"), + ) { return Known::Yes((returns, file)); } if symbol == "!" { @@ -1680,12 +1686,7 @@ pub(crate) fn declared_class( .parameters() .iter() .zip(written.iter()) - .map(|(parameter, argument)| { - ( - parameter.clone(), - parse_type_spelling(argument), - ) - }) + .map(|(parameter, argument)| (parameter.clone(), parse_type_spelling(argument))) .collect(); let target = target.substituted_by_bindings(&bindings); if let Some(named) = target.class_name() { @@ -1837,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 { @@ -2628,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 = - 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, @@ -3066,9 +3068,10 @@ impl NamedDeclaration { written.to_string().is_empty(), an_unnamed_class_body(&specifiers), ) { - (true, Some(_)) if keyed_by_the_declarator => { - Some(ComputedType::named(binding.name.identifier_text()?, Vec::new())) - } + (true, Some(_)) if keyed_by_the_declarator => Some(ComputedType::named( + binding.name.identifier_text()?, + Vec::new(), + )), _ => Some(written), } } @@ -3130,7 +3133,10 @@ impl NamedDeclaration { match self { NamedDeclaration::Here(binding) => { if binding.kind == BindingKind::Class { - return binding.name.identifier_text().map(|name| ComputedType::named(name, Vec::new())); + 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.** // @@ -3151,10 +3157,8 @@ impl NamedDeclaration { { Some(returns) => returns, None => { - let substitutions = 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(), @@ -3201,10 +3205,8 @@ impl NamedDeclaration { let returns = match what_a_call_has_in(index, fact) { Some(returns) => returns, None => { - let substitutions = 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*.** // @@ -3255,7 +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::>()); } + 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 { diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 208193cb..8cfa0593 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -296,7 +296,9 @@ impl ComputedType { // **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::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(), @@ -430,9 +432,7 @@ impl ComputedType { tag: *tag, of: Arc::new(of.replacing(name, with)), }, - ComputedType::Pointer(to) => { - ComputedType::Pointer(Arc::new(to.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, @@ -482,7 +482,9 @@ impl ComputedType { tag: *tag, of: Arc::new(of.substituted_by_bindings(bindings)), }, - ComputedType::Pointer(to) => ComputedType::Pointer(Arc::new(to.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, @@ -499,7 +501,9 @@ impl ComputedType { .map(|parameter| parameter.substituted_by_bindings(bindings)) .collect(), })), - ComputedType::Pack(of) => ComputedType::Pack(Arc::new(of.substituted_by_bindings(bindings))), + 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)), @@ -511,7 +515,6 @@ impl ComputedType { } } - 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. @@ -556,8 +559,12 @@ impl fmt::Display for ComputedType { // `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())?, + pointer @ ComputedType::Pointer(_) => { + write!(out, "{}", pointer.as_a_declarator())? + } + array @ ComputedType::Array { .. } => { + write!(out, "{}", array.as_a_declarator())? + } other => write!(out, "{other}")?, } write!(out, "(")?; @@ -573,7 +580,10 @@ impl fmt::Display for ComputedType { // `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 { .. }) => + if matches!( + &*qualified.of, + ComputedType::Pointer(_) | ComputedType::Array { .. } + ) => { let mut words = Vec::new(); if qualified.is_const { @@ -668,10 +678,7 @@ mod tests { /// 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::Int).to_string(), "int"); assert_eq!( ComputedType::Primary(PrimaryType::UnsignedLongLong).to_string(), "unsigned long long" @@ -680,7 +687,11 @@ mod tests { ComputedType::Primary(PrimaryType::DecltypeAuto).to_string(), "decltype(auto)" ); - assert!(ComputedType::Primary(PrimaryType::Void).class_name().is_none()); + assert!( + ComputedType::Primary(PrimaryType::Void) + .class_name() + .is_none() + ); assert_eq!( ComputedType::Primary(PrimaryType::Float).bare_name(), Some("float") @@ -728,10 +739,8 @@ mod tests { #[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)], - ); + 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); @@ -749,7 +758,10 @@ mod tests { assert!(parameter.class_name().is_none()); assert_eq!( parameter - .substituted_by_bindings(&[(SmolStr::new("T"), ComputedType::Primary(PrimaryType::Int))]) + .substituted_by_bindings(&[( + SmolStr::new("T"), + ComputedType::Primary(PrimaryType::Int) + )]) .to_string(), "int" ); @@ -846,10 +858,12 @@ mod tests { "T" ); assert_eq!( - spelling(ComputedType::Pointer(Arc::new(ComputedType::ElaboratedRecord { - tag: RecordTag::Struct, - of: Arc::new(ComputedType::named("point", Vec::new())), - }))), + spelling(ComputedType::Pointer(Arc::new( + ComputedType::ElaboratedRecord { + tag: RecordTag::Struct, + of: Arc::new(ComputedType::named("point", Vec::new())), + } + ))), "struct point*" ); } @@ -945,10 +959,8 @@ mod tests { #[test] fn a_boxed_named_type_renders_and_answers_members() { - let value = ComputedType::named( - "std::vector", - vec![ComputedType::Primary(PrimaryType::Int)], - ); + 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); @@ -992,10 +1004,7 @@ mod tests { )), rvalue: false, }; - let replaced = value.replacing( - "value_type", - &ComputedType::Primary(PrimaryType::Int), - ); + 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/semantics.rs b/crates/cpp_code_analysis/src/index/types/semantics.rs index 228229d1..e7cd8bf9 100644 --- a/crates/cpp_code_analysis/src/index/types/semantics.rs +++ b/crates/cpp_code_analysis/src/index/types/semantics.rs @@ -16,6 +16,7 @@ //! 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}; @@ -157,22 +158,18 @@ fn a_pointee_without_its_qualifiers(type_of: &ComputedType) -> (&ComputedType, b 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::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) + || function.parameters.iter().any(has_an_elaborated_record) + } + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + false } - ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => false, } } @@ -186,7 +183,7 @@ fn has_an_elaborated_record(type_of: &ComputedType) -> bool { 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(super::GenericType { + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { name: generic.name.clone(), arguments: generic .arguments @@ -219,9 +216,9 @@ fn without_elaborated_records(type_of: &ComputedType) -> ComputedType { is_const: qualified.is_const, is_volatile: qualified.is_volatile, })), - ComputedType::Primary(_) - | ComputedType::Named(_) - | ComputedType::TemplateParameter(_) => type_of.clone(), + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + type_of.clone() + } } } @@ -294,11 +291,13 @@ impl 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, - })), + 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(), } } @@ -356,7 +355,10 @@ impl ComputedType { rvalue: false, } = target && matches!(from, ComputedType::Pointer(_)) - && matches!(&**referent, ComputedType::Named(_) | ComputedType::Generic(_)) + && matches!( + &**referent, + ComputedType::Named(_) | ComputedType::Generic(_) + ) { return Known::No; } @@ -387,10 +389,9 @@ impl ComputedType { // 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(()), + (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, @@ -398,10 +399,7 @@ impl ComputedType { // **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), - ) => { + (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| { @@ -528,7 +526,7 @@ impl ComputedType { .get(name) .cloned() .unwrap_or_else(|| self.clone()), - ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(super::GenericType { + ComputedType::Generic(generic) => ComputedType::Generic(Arc::new(GenericType { name: generic.name.clone(), arguments: generic .arguments @@ -560,11 +558,13 @@ impl ComputedType { .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, - })), + 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 { diff --git a/crates/cpp_code_analysis/src/sema/call_syntax.rs b/crates/cpp_code_analysis/src/sema/call_syntax.rs index af22dd5c..db9ec3de 100644 --- a/crates/cpp_code_analysis/src/sema/call_syntax.rs +++ b/crates/cpp_code_analysis/src/sema/call_syntax.rs @@ -14,6 +14,7 @@ //! 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; @@ -47,13 +48,13 @@ pub(crate) fn parameter_list_has_a_pack(list: &CppParamList) -> bool { /// 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: &[crate::index::params::ParameterFact], + indexed: &[index::params::ParameterFact], ) -> Option>> { parameter_names_of_facts(indexed) } pub(crate) fn parameter_names_of_facts( - facts: &[crate::index::params::ParameterFact], + facts: &[index::params::ParameterFact], ) -> Option>> { if facts.is_empty() { return None; 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 b30739a1..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,6 +41,7 @@ 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; @@ -438,7 +439,7 @@ fn callees_from_the_index(context: &CheckContext<'_>, name: &str) -> Vec /// /// [`DeclaredType`]: crate::cache::summary::DeclaredType fn the_callee_in_facts( - facts: &[crate::index::params::ParameterFact], + facts: &[index::params::ParameterFact], mut variadic: bool, ) -> Option { let mut written = 0usize; 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 a8fb9630..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 @@ -42,11 +42,11 @@ //! 396 ms**, 94% of the layer, paid per keystroke. One walk is what makes this version linear in the file. use super::a_class_can_be_built_from; -use crate::index::types::ComputedType; 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; @@ -398,9 +398,7 @@ enum NotAssignable { fn not_assignable(type_of: &ComputedType) -> Option { match type_of { - ComputedType::Qualified(qualified) if qualified.is_const => { - Some(NotAssignable::Const) - } + ComputedType::Qualified(qualified) if qualified.is_const => Some(NotAssignable::Const), ComputedType::Array { .. } => Some(NotAssignable::AnArray), _ => None, } 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 30b221e3..8cace628 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 @@ -235,11 +235,7 @@ 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: &ComputedType, - 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)), 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 757539f2..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,6 +66,7 @@ //! turned the channel off; the switch makes that a decision rather than a habit. use crate::DeclFact; +use crate::ProjectIndex; use crate::file; use std::path::Path; @@ -306,7 +307,7 @@ 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( - index: &crate::ProjectIndex, + index: &ProjectIndex, file: &Path, fact: &DeclFact, ) -> Vec { diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index ceb8be85..9b7275f5 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -94,6 +94,7 @@ 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; @@ -699,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<(ComputedType, std::path::PathBuf)> { + pub fn type_of(&self, expression: &CppSyntaxNode) -> Known<(ComputedType, std::path::PathBuf)> { self.model.type_of(expression) } @@ -1626,9 +1624,7 @@ fn is_a_char_pointer(type_of: &ComputedType) -> bool { }; matches!( pointee, - ComputedType::Primary( - crate::index::types::PrimaryType::Char | crate::index::types::PrimaryType::Void - ) + ComputedType::Primary(index::types::PrimaryType::Char | index::types::PrimaryType::Void) ) } @@ -1650,7 +1646,9 @@ pub fn a_spelling_of(type_of: &ComputedType) -> Option { | 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::ElaboratedRecord { tag, of } => { + format!("{} {}", tag.word(), a_spelling_of(of)?) + } ComputedType::Pointer(to) => format!("{} *", a_spelling_of(to)?), ComputedType::Reference { to, rvalue } => format!( "{} {}", @@ -1788,7 +1786,7 @@ pub fn a_class_can_be_built_from( /// declaration rather than guessed from commas and `=`. fn parameters_that_could_accept( index: &ProjectIndex, - parameters: &[crate::index::params::ParameterFact], + 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 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 0b5cd170..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 @@ -43,15 +43,19 @@ //! nothing**. A conversion this layer cannot see is not a conversion the program does not have. use super::a_class_can_be_built_from; -use crate::index::types::ComputedType; use super::a_literal_zero; use super::a_spelling_of; use super::callee_name_of; use super::is_a_function_definition; use super::member_access_above; use super::name_declared_by; +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; @@ -212,10 +216,7 @@ fn member_parameter_lists( let Known::Yes((a_type, _)) = context.type_of(&access.object) else { return Vec::new(); }; - let Known::Yes(list) = context - .model - .members_of_computed(&a_type) - else { + let Known::Yes(list) = context.model.members_of_computed(&a_type) else { return Vec::new(); }; let index = context.index(); @@ -228,7 +229,9 @@ fn member_parameter_lists( let parameters: Vec = index .parameter_facts_of(file, fact) .iter() - .filter_map(|parameter| CandidateParameter::from_a_member(index, member, fact, parameter)) + .filter_map(|parameter| { + CandidateParameter::from_a_member(index, member, fact, parameter) + }) .collect(); (!parameters.is_empty()).then_some(parameters) }) @@ -237,8 +240,8 @@ fn member_parameter_lists( /// **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()) + let Some(parameters) = + CppDeclaration::cast(function.clone()).and_then(|declaration| declaration.get_param_list()) else { return Vec::new(); }; @@ -278,10 +281,7 @@ impl CandidateParameter { /// **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: &crate::ProjectIndex, - parameter: &crate::index::params::ParameterFact, - ) -> Option { + 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 { @@ -297,10 +297,10 @@ impl CandidateParameter { /// 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: &crate::ProjectIndex, - member: &crate::ProjectMember, - fact: &crate::DeclFact, - parameter: &crate::index::params::ParameterFact, + 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)?; @@ -309,7 +309,10 @@ impl CandidateParameter { // `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.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)); @@ -386,7 +389,8 @@ fn check_the_arguments( // **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. The target is the candidate's **type**, asked structurally. - if context.a_string_literal_in_a_char_pointer_position(argument.syntax(), ¶meter.type_of) + if context + .a_string_literal_in_a_char_pointer_position(argument.syntax(), ¶meter.type_of) { every_candidate_disagrees = false; break; @@ -482,7 +486,7 @@ fn the_index_declares_one( // 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, &crate::DeclFact)> = context + let mut found: Vec<(&Path, &DeclFact)> = context .summary .declarations .iter() @@ -511,7 +515,7 @@ fn the_index_declares_one( } // **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<&[crate::index::params::ParameterFact]> = Vec::new(); + 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) { 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 f2230fc2..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 @@ -79,9 +79,9 @@ impl Check for PureVirtualNotOverridden { for member in &list.members { if context.index().member_kind(member) != Some(DeclKind::Function) || !context - .index() - .member_modifiers(member) - .is_some_and(|modifiers| modifiers.contains(DeclModifiers::PURE)) + .index() + .member_modifiers(member) + .is_some_and(|modifiers| modifiers.contains(DeclModifiers::PURE)) { continue; } @@ -94,7 +94,11 @@ impl Check for PureVirtualNotOverridden { .member_modifiers(other) .is_some_and(|modifiers| !modifiers.contains(DeclModifiers::PURE)) }); - if !overridden && !missing.iter().any(|name| name == context.index().member_name(member)) { + if !overridden + && !missing + .iter() + .any(|name| name == context.index().member_name(member)) + { missing.push(context.index().member_name(member).to_string()); } } 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 7cc2fb7d..4f9650db 100644 --- a/crates/cpp_code_analysis/src/sema/check/undefined_name.rs +++ b/crates/cpp_code_analysis/src/sema/check/undefined_name.rs @@ -54,12 +54,12 @@ //! coordinate systems, the rendering's and the file's, are not comparable offset by offset). use super::member_access_above; -use crate::index::types::ComputedType; use crate::Known; use crate::ScopeKind; use crate::UnknownReason; use crate::file::coordinates::ReadingOffset; use crate::index; +use crate::index::types::ComputedType; use cpp_parser::CppCallExpr; use cpp_parser::CppDeclSpecifierSeq; use cpp_parser::CppDeclaration; 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 3b0aca5c..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,12 @@ impl Check for UseOverride { .members .iter() .filter(|member| { - context.index().member_modifiers(member).is_some_and(|modifiers| { - modifiers.contains(DeclModifiers::VIRTUAL) - || modifiers.contains(DeclModifiers::OVERRIDE) - }) + context.index().member_modifiers(member).is_some_and( + |modifiers| { + modifiers.contains(DeclModifiers::VIRTUAL) + || modifiers.contains(DeclModifiers::OVERRIDE) + }, + ) }) .map(|member| context.index().member_name(member).to_string()) .collect(), diff --git a/crates/cpp_code_analysis/src/sema/constraint.rs b/crates/cpp_code_analysis/src/sema/constraint.rs index 63352e74..8eff3be3 100644 --- a/crates/cpp_code_analysis/src/sema/constraint.rs +++ b/crates/cpp_code_analysis/src/sema/constraint.rs @@ -200,7 +200,8 @@ impl Trait { // 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 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 @@ -222,11 +223,7 @@ impl Trait { Trait::Arithmetic => (integral || floating) && !pointer && !reference, Trait::Pointer => pointer && !reference, Trait::Void => { - scalar.is_some_and(Scalar::is_void) - && !pointer - && !reference - && !array - && !function + scalar.is_some_and(Scalar::is_void) && !pointer && !reference && !array && !function } Trait::Signed => signed, Trait::Unsigned => integral && !signed, diff --git a/crates/cpp_code_analysis/src/sema/convert.rs b/crates/cpp_code_analysis/src/sema/convert.rs index f08021d3..63678eb8 100644 --- a/crates/cpp_code_analysis/src/sema/convert.rs +++ b/crates/cpp_code_analysis/src/sema/convert.rs @@ -16,6 +16,7 @@ //! a template parameter, a dependent type — all of those are `Unknown`, and all of them are silent. use crate::Known; +use crate::index; use crate::index::types::ComputedType; use crate::sema::types::RecordTag; use cpp_parser::features; @@ -101,7 +102,7 @@ pub fn conversion_to( // capability lookup of that shape. if matches!( target, - ComputedType::Primary(crate::index::types::PrimaryType::Bool) + ComputedType::Primary(index::types::PrimaryType::Bool) ) && a_pointer(from) { return Conversion::Implicit; @@ -186,9 +187,9 @@ fn a_tagged_record_in(type_of: &ComputedType) -> Option<(RecordTag, &str)> { 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, + ComputedType::Primary(_) | ComputedType::Named(_) | ComputedType::TemplateParameter(_) => { + None + } } } @@ -206,13 +207,14 @@ fn the_value_is_that_record(type_of: &ComputedType, tag: RecordTag, record: &str match type_of { 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)) + *written == tag + && of + .class_name() + .is_some_and(|name| names_the_record(name, 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::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, } @@ -234,11 +236,10 @@ fn names_the_record(name: &str, record: &str) -> bool { 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) + 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), } } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 763af1bb..a5b7e153 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -28,12 +28,14 @@ //! 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::sema::types::TypeSubstitutions; -use crate::index::types::ComputedType; 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; @@ -101,7 +103,7 @@ pub struct BuiltFacts { /// 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: crate::index::params::ParamsStore, + pub parameters: index::params::ParamsStore, } /// **A freshly built fact set for a caller that keeps no parameter store**: the parameter handle is cleared. @@ -129,7 +131,7 @@ pub fn facts_with_their_types(built: BuiltFacts) -> Vec { // **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 = crate::index::params::ParamsId::NONE; + fact.parameters = index::params::ParamsId::NONE; } facts } @@ -3090,10 +3092,7 @@ fn an_operator_return_is_usable( ComputedType::Named(name) => name.contains("::"), ComputedType::Generic(generic) => { generic.name.contains("::") - && generic - .arguments - .iter() - .all(means_the_same_everywhere) + && generic.arguments.iter().all(means_the_same_everywhere) } ComputedType::Pointer(to) | ComputedType::Reference { to, .. } @@ -3442,7 +3441,7 @@ fn a_parenthesised_return_type( let mut wrapped = base.clone(); for suffix in &suffixes { if CppParamList::can_cast(suffix.kind().into()) { - wrapped = ComputedType::Function(Arc::new(crate::index::types::FunctionType { + wrapped = ComputedType::Function(Arc::new(index::types::FunctionType { returns: Arc::new(wrapped), parameters: sema::types::read_parameters(suffix).into_boxed_slice(), })); @@ -3644,7 +3643,7 @@ pub fn parameter_list_at(root: &CppSyntaxNode, offset: usize) -> Option /// **not** a parameter (`void f(int, ...)` has one parameter, `void f(...)` has none). #[derive(Debug, Default)] pub(crate) struct ParameterListFacts { - pub facts: Vec, + pub facts: Vec, pub variadic: bool, } @@ -3663,7 +3662,7 @@ pub(crate) fn declared_parameter_facts_with( return ParameterListFacts::default(); }; ParameterListFacts { - facts: crate::index::params::parameter_facts_of(&list), + facts: index::params::parameter_facts_of(&list), variadic: list.is_variadic(), } } @@ -3868,7 +3867,7 @@ 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>, + pub facts: Vec>, } fn declared_constraints_with(shapes: &DeclarationShapes, binding: &Binding) -> DeclaredConstraints { @@ -3994,7 +3993,7 @@ fn fact_for( // (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 crate::index::params::ParamsStore, + 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 @@ -4245,8 +4244,12 @@ fn fact_for( if name.as_ref() == "pointer" { eprintln!("[fact] {} -> {:?}", name, type_of); } - if name.as_ref() == "priority" { eprintln!("[fact] {} -> {:?}", name, type_of); } - if name.as_ref() == "find" { eprintln!("[fact find] params={:?} returns={:?}", parameters, returns); } + if name.as_ref() == "priority" { + eprintln!("[fact] {} -> {:?}", name, type_of); + } + if name.as_ref() == "find" { + eprintln!("[fact find] params={:?} returns={:?}", parameters, returns); + } let type_of = lower(type_of); let returns = lower(returns); @@ -4917,7 +4920,7 @@ struct DeclarationFacts<'a> { /// 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: crate::index::params::ParamsStore, + 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, @@ -4940,7 +4943,7 @@ impl<'a> DeclarationFacts<'a> { declarations: Declarations::of(root, errors), guards: SummaryGuards::default(), facts: Vec::new(), - parameters: crate::index::params::ParamsStore::new(), + parameters: index::params::ParamsStore::new(), } } @@ -6043,6 +6046,7 @@ pub fn split_by_a_directive_with(shapes: &DeclarationShapes, binding: &Binding) mod 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; @@ -6603,7 +6607,7 @@ int Box::Inner::deep = 0; /// 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, crate::index::params::ParamsStore) { + 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"); @@ -6709,7 +6713,7 @@ void dots(const char* text = \"...\"); ); assert_eq!( only_ellipsis.parameters, - crate::index::params::ParamsId::NONE, + 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()); diff --git a/crates/cpp_code_analysis/src/sema/deduction.rs b/crates/cpp_code_analysis/src/sema/deduction.rs index 1827d1d5..dc4efe0b 100644 --- a/crates/cpp_code_analysis/src/sema/deduction.rs +++ b/crates/cpp_code_analysis/src/sema/deduction.rs @@ -221,16 +221,14 @@ fn bind_inside( (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 => { + (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() => { + (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)?; diff --git a/crates/cpp_code_analysis/src/sema/model.rs b/crates/cpp_code_analysis/src/sema/model.rs index 4cbb8781..30dc4fe7 100644 --- a/crates/cpp_code_analysis/src/sema/model.rs +++ b/crates/cpp_code_analysis/src/sema/model.rs @@ -42,7 +42,9 @@ //! 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::DeclKind; use crate::FileView; +use crate::ProjectMember; use crate::completion; use crate::sema; use std::cell::RefCell; @@ -153,7 +155,7 @@ 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: &crate::ProjectMember) -> Option { + 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 { @@ -164,7 +166,7 @@ impl<'a> SemanticModel<'a> { /// **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: &crate::ProjectMember) -> Option { + 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 { @@ -175,28 +177,28 @@ impl<'a> SemanticModel<'a> { /// **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 crate::ProjectMember) -> &'m str { + 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: &crate::ProjectMember) -> Option { + 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: &crate::ProjectMember) -> Option { + 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: &crate::ProjectMember) -> Option { + 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: &crate::ProjectMember) -> Option { + pub fn member_parameter_list(&self, member: &ProjectMember) -> Option { self.index.member_parameter_list(member) } diff --git a/crates/cpp_code_analysis/src/sema/overload.rs b/crates/cpp_code_analysis/src/sema/overload.rs index 7ce50211..79c42e03 100644 --- a/crates/cpp_code_analysis/src/sema/overload.rs +++ b/crates/cpp_code_analysis/src/sema/overload.rs @@ -35,6 +35,7 @@ //! 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; @@ -532,7 +533,7 @@ mod tests { /// 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: &[crate::index::params::ParameterFact], + facts: &[index::params::ParameterFact], c_style_variadic: bool, ) -> (Vec, bool) { let mut parameters = Vec::new(); @@ -660,6 +661,7 @@ fn a_template_argument_pack_inside_a_parameter_is_not_the_parameter_pack() { #[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}; @@ -679,9 +681,7 @@ fn a_parameter_written_with_the_declarations_template_parameter_is_a_parameter() 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 = crate::cache::summary::DeclaredType::Computed(std::sync::Arc::new( - written, - )); + facts[0].type_of = DeclaredType::Computed(std::sync::Arc::new(written)); let (parameters, _) = parameters_in_facts(&facts, false); assert_eq!(parameters.len(), 1); @@ -702,9 +702,7 @@ fn the_more_specialized_of_two_templates_wins() { 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)) - }; + 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![a_written_type("int*")], false, "take(T*)".to_string()) diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 6355216c..0fbc29e5 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -69,6 +69,7 @@ //! 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::{ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; use crate::summary::ConstraintFact; @@ -262,19 +263,20 @@ pub fn with_template_parameters>( ComputedType::TemplateParameter(name) } ComputedType::Named(_) | ComputedType::Primary(_) => written, - ComputedType::Generic(generic) => ComputedType::Generic(Arc::new( - crate::index::types::GenericType { + 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::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, @@ -294,9 +296,10 @@ pub fn with_template_parameters>( .map(|parameter| with_template_parameters(parameter.clone(), parameters)) .collect(), })), - ComputedType::Pack(of) => { - ComputedType::Pack(Arc::new(with_template_parameters((*of).clone(), parameters))) - } + 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(), @@ -2612,10 +2615,8 @@ mod tests { #[test] fn a_type_that_holds_a_parameter_says_so() { assert!( - ComputedType::Pointer(Arc::new(ComputedType::TemplateParameter( - "T".into() - ))) - .depends_on_a_parameter() + ComputedType::Pointer(Arc::new(ComputedType::TemplateParameter("T".into()))) + .depends_on_a_parameter() ); assert!( @@ -2626,7 +2627,10 @@ mod tests { .depends_on_a_parameter() ); - assert!(!ComputedType::named("std::vector", vec![ComputedType::builtin("int")]).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 @@ -2761,8 +2765,7 @@ mod tests { let found = parse_type_spelling("int(int, double)"); assert_eq!(found.to_string(), "int(int, double)"); - let ComputedType::Function(function) = &found - else { + let ComputedType::Function(function) = &found else { panic!("a parameter list at the end is a function type: {found:?}"); }; assert_eq!(function.returns.to_string(), "int"); diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index c04e975f..e915aaad 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -6,6 +6,7 @@ use super::*; use crate::DeclFact; use crate::DeclKind; use crate::DeclModifiers; +use crate::DeclaredType; use crate::Known; use crate::ProjectIndex; use crate::build_facts; @@ -490,10 +491,7 @@ impl Session { offset: ReadingOffset, 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() @@ -517,9 +515,7 @@ impl Session { let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => { - Known::Yes(a_type) - } + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -663,9 +659,7 @@ impl Session { let types: Vec> = arguments .iter() .map(|argument| match model.type_of(argument) { - Known::Yes((a_type, _)) => { - Known::Yes(a_type) - } + Known::Yes((a_type, _)) => Known::Yes(a_type), Known::No => Known::No, Known::Unknown(reason) => Known::Unknown(reason), }) @@ -692,11 +686,7 @@ impl Session { /// [`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 { + pub fn members_of_type(&self, view: &FileView, class: &ComputedType) -> Known { let listed = crate::index::project::members_of_computed( self.store.index(), &view.scopes, @@ -1530,10 +1520,9 @@ impl Session { // 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 = crate::DeclaredType::Computed(Arc::new( - crate::sema::types::parse_type_spelling(&type_of), - )); - fact.returns = crate::DeclaredType::None; + 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 diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 7629fb63..c351377a 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; @@ -744,7 +745,7 @@ impl Session { &self, view: &FileView, offset: ReadingOffset, - ) -> Option { + ) -> Option { let callee = sema::resolve::name_node_at(&view.root, offset.get())?; index::project::a_member_row_of_the_enclosing_class( self.store.index(), @@ -1010,7 +1011,7 @@ impl Session { return None; }; let index = self.store.index(); - let mut candidates: Vec<&index::project::ProjectMember> = list + let mut candidates: Vec<&ProjectMember> = list .members .iter() .filter(|member| index.member_kind(member) == Some(DeclKind::Function)) @@ -1053,7 +1054,7 @@ impl Session { 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| { + let constrained = |member: &&ProjectMember| { index .member_fact(member) .and_then(|fact| fact.requires_clause()) diff --git a/crates/cpp_code_analysis/src/session/definition.rs b/crates/cpp_code_analysis/src/session/definition.rs index 65c3db93..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: self.index().returns_spelling_of(fact).map(|spelled| spelled.to_string()), + returns: self + .index() + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template, @@ -169,9 +172,7 @@ impl Session { let Some(fact) = index.member_fact(member) else { continue; }; - if fact.kind != DeclKind::Function - || !fact.modifiers.contains(DeclModifiers::PURE) - { + if fact.kind != DeclKind::Function || !fact.modifiers.contains(DeclModifiers::PURE) { continue; } let overridden = list.members.iter().any(|other| { @@ -189,8 +190,7 @@ impl Session { let Some(file) = index.member_path(member) else { continue; }; - let Some((parameters, qualifiers)) = - signature_of(self, file, fact, written.as_deref()) + let Some((parameters, qualifiers)) = signature_of(self, file, fact, written.as_deref()) else { continue; }; @@ -198,7 +198,9 @@ impl Session { qualified_name: format!("{class}::{}", fact.name), class: class.to_string(), name: fact.name.to_string(), - returns: index.returns_spelling_of(fact).map(|spelled| spelled.to_string()), + returns: index + .returns_spelling_of(fact) + .map(|spelled| spelled.to_string()), parameters, qualifiers, is_a_template: false, diff --git a/crates/cpp_code_analysis/src/session/inlay.rs b/crates/cpp_code_analysis/src/session/inlay.rs index d6f2040b..3907f50c 100644 --- a/crates/cpp_code_analysis/src/session/inlay.rs +++ b/crates/cpp_code_analysis/src/session/inlay.rs @@ -584,10 +584,9 @@ fn callable_object_parameter_names( if fact.name != "operator()" { continue; } - let Some(names) = parameter_names_of_fact(index.parameter_facts_of( - index.member_path(member)?, - fact, - )) else { + let Some(names) = + parameter_names_of_fact(index.parameter_facts_of(index.member_path(member)?, fact)) + else { continue; }; if names.len() != passed { diff --git a/crates/cpp_code_analysis/src/session/mod.rs b/crates/cpp_code_analysis/src/session/mod.rs index 8f399faf..3a0ccc7b 100644 --- a/crates/cpp_code_analysis/src/session/mod.rs +++ b/crates/cpp_code_analysis/src/session/mod.rs @@ -70,7 +70,6 @@ //! representable and simply not implemented. The store is what carries the single configuration today. use crate::IndexedRendering; -use crate::index::types::ComputedType; use crate::IndexedUnit; use crate::MacroDefinitions; use crate::MapReport; @@ -85,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; diff --git a/crates/cpp_code_analysis/src/session/queries.rs b/crates/cpp_code_analysis/src/session/queries.rs index 79a54949..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; @@ -257,7 +260,7 @@ impl Session { let index = self.store.index(); let alias = definitions.found.iter().find(|definition| { index.definition_fact(definition).is_some_and(|fact| { - fact.kind == crate::DeclKind::Type && index.type_spelling_of(fact).is_some() + fact.kind == DeclKind::Type && index.type_spelling_of(fact).is_some() }) })?; @@ -464,7 +467,7 @@ impl Session { pub fn reflection_of_definition( &self, definition: &ProjectDefinition, - ) -> Option { + ) -> Option { let found = self.store.index().definition_fact(definition)?; if let Some(reflection) = found.reflection() { return Some(reflection.clone()); @@ -487,7 +490,7 @@ impl Session { /// 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: crate::FileId) -> Option { + pub fn path_of_file(&self, file: FileId) -> Option { let path = self.store.index().path_of(file)?; Some( self.project_paths diff --git a/crates/cpp_code_analysis/src/session/semantic.rs b/crates/cpp_code_analysis/src/session/semantic.rs index 7450e6ba..0bdba749 100644 --- a/crates/cpp_code_analysis/src/session/semantic.rs +++ b/crates/cpp_code_analysis/src/session/semantic.rs @@ -88,11 +88,11 @@ //! ``` use crate::FactGuard; -use crate::index::types::ComputedType; 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; diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index 29a8b841..c63946f3 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -28,6 +28,7 @@ //! [`Ambiguous`]: crate::UnknownReason::Ambiguous use crate::DeclKind; +use crate::index; use crate::sema; use std::ops::Range; use std::path::{Path, PathBuf}; @@ -157,7 +158,7 @@ where // 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(); + 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 @@ -229,7 +230,7 @@ where // **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(); + 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(" "); @@ -241,16 +242,16 @@ where parameters.push((start..label.len(), text.clone())); let written = cpp_parser::CppParam::cast(parameter) .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); - plain.push(written.unwrap_or_else(|| { - crate::index::types::ComputedType::named(text, Vec::new()) - })); + plain.push( + written.unwrap_or_else(|| index::types::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 = cpp_parser::CppParamList::cast(list.clone()) - .is_some_and(|list| list.is_variadic()); + let variadic = + cpp_parser::CppParamList::cast(list.clone()).is_some_and(|list| list.is_variadic()); if variadic { if !parameters.is_empty() { label.push_str(", "); @@ -308,7 +309,7 @@ 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), @@ -330,9 +331,7 @@ where let parameters = match sema::deduction::deduce(&templates, &plain, &types) { Some(deduced) => plain .iter() - .map(|type_of| { - sema::deduction::substituted(type_of, &templates, &deduced) - }) + .map(|type_of| sema::deduction::substituted(type_of, &templates, &deduced)) .collect(), None => plain, }; diff --git a/crates/cpp_code_analysis/src/session/units.rs b/crates/cpp_code_analysis/src/session/units.rs index ff1d26e2..cbcc1e78 100644 --- a/crates/cpp_code_analysis/src/session/units.rs +++ b/crates/cpp_code_analysis/src/session/units.rs @@ -5,7 +5,6 @@ //! the flags), which is what makes a cached unit reusable across runs and what makes a stale one detectable. use super::*; -use crate::index::types::ComputedType; use crate::CookedFile; use crate::FileId; use crate::FileView; @@ -18,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; @@ -1619,9 +1619,7 @@ impl Session { // `operator->` whose return type is a class. let parts: Option<(&str, &[ComputedType])> = match &written { ComputedType::Named(name) => Some((name.as_str(), &[])), - ComputedType::Generic(generic) => { - Some((generic.name.as_str(), &generic.arguments)) - } + ComputedType::Generic(generic) => Some((generic.name.as_str(), &generic.arguments)), _ => None, }; if arrow && let Some((name, arguments)) = parts { @@ -1635,16 +1633,14 @@ impl Session { .unwrap_or_else(|| name.to_string()) } }; - if let Some((pointee, pointee_arguments)) = - index::project::the_pointee_of_a_handle( - self.store.index(), - &view.scopes, - &view.root, - &view.path, - &class, - arguments, - ) - { + if let Some((pointee, pointee_arguments)) = index::project::the_pointee_of_a_handle( + self.store.index(), + &view.scopes, + &view.root, + &view.path, + &class, + arguments, + ) { return Some(ComputedType::named(pointee, pointee_arguments)); } } diff --git a/crates/cpp_code_analysis/tests/suite/semantic.rs b/crates/cpp_code_analysis/tests/suite/semantic.rs index a9f26f00..033158ad 100644 --- a/crates/cpp_code_analysis/tests/suite/semantic.rs +++ b/crates/cpp_code_analysis/tests/suite/semantic.rs @@ -1015,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 && session.index().type_spelling_of(fact).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)) { @@ -1067,7 +1070,10 @@ fn an_auto_is_deduced_from_its_initializer() { let deduced = |name: &str| -> String { let fact = facts .iter() - .find(|fact| fact.name == name && session.index().type_spelling_of(fact).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`: {:?}", @@ -1114,7 +1120,10 @@ fn an_auto_is_deduced_from_its_initializer() { let name = "no_initializer"; let fact = facts .iter() - .find(|fact| fact.name == name && session.index().type_spelling_of(fact).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!( @@ -1319,7 +1328,10 @@ fn an_auto_written_through_a_macro_is_still_deduced() { ] { let fact = facts .iter() - .find(|fact| fact.name == name && session.index().type_spelling_of(fact).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`: {:?}", @@ -1566,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 && session.index().type_spelling_of(fact).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, diff --git a/crates/cpp_code_analysis/tests/suite/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index 42c300ee..b9302106 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2915,7 +2915,10 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { Some(false) ); assert_eq!( - satisfies(&integral, &bind(ComputedType::named("std::string", Vec::new()))), + satisfies( + &integral, + &bind(ComputedType::named("std::string", Vec::new())) + ), Some(false), "a class is not integral" ); @@ -3042,13 +3045,21 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { an_rvalue_reference(ComputedType::builtin("int")), true, ), - ("std::is_reference_v", ComputedType::builtin("int"), false), + ( + "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", + a_const(ComputedType::builtin("int")), + true, + ), ("std::is_const_v", ComputedType::builtin("int"), false), ( "std::is_const_v", @@ -3074,7 +3085,10 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { ("std::is_array_v", ComputedType::builtin("int"), false), ( "std::is_function_v", - a_function(ComputedType::builtin("int"), vec![ComputedType::builtin("int")]), + a_function( + ComputedType::builtin("int"), + vec![ComputedType::builtin("int")], + ), true, ), ("std::is_function_v", ComputedType::builtin("int"), false), @@ -3518,9 +3532,9 @@ std::string f() { /// rely on at that seam. #[test] fn a_template_parameter_target_is_not_a_refusal() { + 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_code_analysis::index::types::ComputedType; use cpp_parser::features::Family; let an_int = ComputedType::builtin("int"); @@ -3543,12 +3557,9 @@ fn a_template_parameter_target_is_not_a_refusal() { ); // **A class the index knows still refuses**: `int` cannot be built into a `Widget` that has no such constructor. assert_eq!( - conversion_to( - &an_int, - &parse_type_spelling("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. @@ -3595,7 +3606,9 @@ fn a_template_parameter_target_is_not_a_refusal() { "a `struct value` is not a `union value`" ); assert_eq!( - conversion_to(&a_union_pointer, &a_union_pointer, Some(Family::C), |_| None), + conversion_to(&a_union_pointer, &a_union_pointer, Some(Family::C), |_| { + None + }), Conversion::Implicit, "a `union value *` converts to itself" ); @@ -4661,7 +4674,9 @@ void f() { panic!("a class this file declares answers a member list: {bare:?}"); }; assert!( - bare.members.iter().any(|member| session.index().member_name(member) == "own"), + bare.members + .iter() + .any(|member| session.index().member_name(member) == "own"), "the class's own members are listed: {:?}", bare.members .iter() diff --git a/crates/cpp_code_analysis/tests/suite/ue_engine.rs b/crates/cpp_code_analysis/tests/suite/ue_engine.rs index 6d6bdf97..42b917d2 100644 --- a/crates/cpp_code_analysis/tests/suite/ue_engine.rs +++ b/crates/cpp_code_analysis/tests/suite/ue_engine.rs @@ -311,7 +311,10 @@ public: .find(|member| session.index().member_name(member) == "Super") .expect("the generated `Super`"); assert_eq!( - session.index().member_type_spelling(super_member).as_deref(), + session + .index() + .member_type_spelling(super_member) + .as_deref(), Some("AActor") ); let this_class = list diff --git a/crates/cpp_inspect/src/questions.rs b/crates/cpp_inspect/src/questions.rs index f4366ed7..b1e795de 100644 --- a/crates/cpp_inspect/src/questions.rs +++ b/crates/cpp_inspect/src/questions.rs @@ -220,7 +220,10 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { text.push_str(&format!( " picked {:<40} {}\n", where_a_declaration(session, definition), - fact.map_or_else(|| "(unresolved)".to_string(), |fact| a_fact_and_what_it_says(session, 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")), @@ -232,9 +235,10 @@ pub fn what_it_names(opened: &Opened, place: &Place) -> Result { text.push_str(&format!( " found {:<40} {}\n", where_a_declaration(session, definition), - session - .definition_fact(definition) - .map_or_else(|| "(unresolved)".to_string(), |fact| a_fact_and_what_it_says(session, 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() { diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 7256a325..6998dca1 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1175,7 +1175,11 @@ fn member_markdown( 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))) + .chain( + reached + .iter() + .map(|class| session.members_of_type(view, class)), + ) { if let Known::Yes(candidates) = candidates { if candidates @@ -1261,9 +1265,9 @@ fn member_markdown( sema::deduction::template_parameters_before( &text, session - .index() - .member_fact(candidate) - .map_or(0, |fact| fact.name_range.start_offset), + .index() + .member_fact(candidate) + .map_or(0, |fact| fact.name_range.start_offset), ) }) .unwrap_or_default() @@ -1321,10 +1325,12 @@ fn member_markdown( let const_ones: Vec<&ProjectMember> = shown .iter() .copied() - .filter(|candidate| session - .index() - .member_modifiers(candidate) - .is_some_and(|modifiers| 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 @@ -1559,8 +1565,7 @@ fn overloads_markdown( if let Some(arguments) = session.the_deduced_arguments(view, offset, &names, ¶meters) { - let arguments: Vec = - arguments.iter().map(ToString::to_string).collect(); + let arguments: Vec = arguments.iter().map(ToString::to_string).collect(); line = sema::types::substituted_spelling(&line, &names, &arguments); } } @@ -1808,7 +1813,11 @@ fn a_line(session: &Session, fact: &DeclFact) -> String { fact, None, None, - &|fact| index.type_spelling_of(fact).map(|spelled| spelled.to_string()), + &|fact| { + index + .type_spelling_of(fact) + .map(|spelled| spelled.to_string()) + }, &|fact| { index .returns_spelling_of(fact) @@ -1838,16 +1847,16 @@ fn shown_returns_of(index: &ProjectIndex, fact: &DeclFact) -> Option { /// 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), - )); + 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), - )); + fact.returns = DeclaredType::Computed(std::sync::Arc::new(sema::types::parse_type_spelling( + &written, + ))); } pub(crate) fn markdown(value: String) -> Hover { @@ -2460,8 +2469,8 @@ fn declaration_markdown_with( 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) = shown_type_of(session.index(), fact) - .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") { @@ -3531,9 +3540,9 @@ mod tests { // 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 { - returns: DeclaredType::Computed(std::sync::Arc::new( - sema::types::parse_type_spelling("std::size_t"), - )), + returns: DeclaredType::Computed(std::sync::Arc::new(sema::types::parse_type_spelling( + "std::size_t", + ))), ..fact.clone() }; assert_eq!( From e4b399075cc53f0f09c07b9ad6a5a07af5200985 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 17:16:20 +0800 Subject: [PATCH 097/102] refactor(subscript): resolve dependent members structurally a_members_answer_as_a_type follows class aliases, member lists and member_computed_type structurally, replacing the named core of Pointer/Reference/Array/Qualified wrappers and resolving reference/const_reference to value_type without printing and parsing a spelling. a_members_answer_as_a_spelling and a_reference_resolved_through_its_value_type are deleted; the pre-existing debug print in member_display_fact is removed. Adds a focused standard reference-chain test. Workspace tests (3620 passed) and clippy pass. --- .../src/index/project/calls.rs | 871 ++++++++++++++---- .../src/index/project/macro_walk.rs | 6 - .../tests/suite/subscript_overloads.rs | 100 +- 3 files changed, 783 insertions(+), 194 deletions(-) diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index 6f31b37a..ea34d6e1 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -1869,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: @@ -1883,13 +1883,16 @@ pub(crate) fn callee_of_a_call( /// `std::vector` answered `Unknown(NotDeclaredHere("_Ty"))`: the alias was followed to a *different* class's /// `reference`, whose `_Ty` nothing substitutes. /// -/// # Why the walk itself is spelling-level +/// # The walk is structural /// -/// An operator's return type is a value ([`crate::index::types::ComputedType`]), but the chain this follows is not: -/// `typename some_allocator::value_type&` is a **dependent name** — a template's argument list inside a qualified -/// name — and the model has no structural form for one, so the alias has to be read by the spelling the declaration -/// wrote. The one conversion happens here, at this fallback's boundary, and the answer is parsed once at the end: -/// a caller gets a type and never a spelling. +/// 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, @@ -1913,9 +1916,12 @@ pub(crate) fn a_members_answer_as_a_type( 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 spelling walk. This keeps the common subscript answer off the string path. + // **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 @@ -1928,215 +1934,716 @@ pub(crate) fn a_members_answer_as_a_type( return returns.clone(); } } - let written = - a_members_answer_as_a_spelling(index, scopes, root, path, class_type, &returns.to_string()); - parse_type_spelling(&written) + // **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, + }; + 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, + } } -/// [`a_members_answer_as_a_type`]'s spelling-level half — see the note there on why this walk is a spelling one. -fn a_members_answer_as_a_spelling( +/// **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, - scopes: &ScopeTree, - root: &CppSyntaxNode, path: &Path, class_type: &ComputedType, - 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(); - }; - // **The alias's target is the declaration's computed type**, materialized rather than parsed. - let Some(target) = index - .files_declaring(&name, path) - .into_iter() - .find(|declared| declared.fact.kind == DeclKind::Type && declared.fact.has_type_of()) - .and_then(|declared| index.computed_type_of(declared.fact)) - else { +) -> 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 Some(resolved_name) = target.class_name().map(str::to_string) 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.clone()); - 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; } - // **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 = ComputedType::named(qualified, target.arguments().to_vec()); - class_type = match class_type.is_const() && !resolved.is_const() { - true => ComputedType::Qualified(Arc::new(index::types::QualifiedType { - of: Arc::new(resolved), - is_const: true, - is_volatile: false, - })), - 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), + }) +} + +/// **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, + }, + 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, + })) + } + } +} - // **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 == '_') +/// **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 substituted; + 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 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) = index.type_spelling_of(&fact) 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. +/// **One member of `class`, with the class's substitution already applied** — the step both the name and qualifier +/// readers are made of. /// -/// 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. -/// -/// 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: &ComputedType, - 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, + }, + 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 = index.type_spelling_of(&fact)?; - 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/macro_walk.rs b/crates/cpp_code_analysis/src/index/project/macro_walk.rs index c14c498a..2c1db817 100644 --- a/crates/cpp_code_analysis/src/index/project/macro_walk.rs +++ b/crates/cpp_code_analysis/src/index/project/macro_walk.rs @@ -981,12 +981,6 @@ impl ProjectIndex { return Some(fact.clone()); } let mut shown = fact.clone(); - if shown.name == "second" { - eprintln!( - "[display] sub={:?} base={:?}", - member.substitution, fact.type_of - ); - } shown.type_of = self .member_computed_type(member) .map_or(DeclaredType::None, |computed| { 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&`" + ); +} From edc650b93a8cb58ef0848f85a6cb4bf8d506ee63 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 17:55:15 +0800 Subject: [PATCH 098/102] refactor(arrays): carry structural extents and size layout from them ComputedType::Array.extent is now ArrayExtent::{Unspecified, Literal, Written}; the declaration/type-id/parse readers preserve COUNT and expression dimensions instead of dropping them. Layout sizes an array member from its structural type (Unspecified=0, Literal, Written evaluated through the existing macro/enumerator reader) and recurses on the element; declared_type_spelling_with and its declaration-text reassembly helpers are deleted. Codec versions move (CODEC 49, COOKED 13, UNIT 11) with an append-only array tag. Tests cover structural extents, layout with COUNT, display/parse round-trips and codec variants. Workspace tests (3624 passed) and clippy pass. --- .../src/cache/summary_codec.rs | 47 +++-- .../cpp_code_analysis/src/cache/unit_codec.rs | 6 +- .../src/index/project/calls.rs | 6 +- .../src/index/types/compute.rs | 121 ++++++++++--- .../cpp_code_analysis/src/index/types/mod.rs | 4 +- .../src/index/types/semantics.rs | 4 +- .../src/sema/builtins/traits.rs | 4 +- .../cpp_code_analysis/src/sema/check/mod.rs | 5 +- .../src/sema/declarations.rs | 165 ------------------ crates/cpp_code_analysis/src/sema/types.rs | 99 +++++++++-- crates/cpp_code_analysis/src/session/calls.rs | 141 +++++++++++---- .../cpp_code_analysis/tests/suite/layout.rs | 61 +++++++ crates/cpp_code_analysis/tests/suite/types.rs | 13 +- 13 files changed, 418 insertions(+), 258 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index f1956e2c..706cb12b 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -28,7 +28,7 @@ use crate::DirectiveKind; use crate::FORMAT_VERSION; use crate::READING_FINGERPRINT; use crate::index; -use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; +use crate::index::types::{ArrayExtent, ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::macros; use crate::preprocess; use crate::sema::types::RecordTag; @@ -349,7 +349,17 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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). -pub const CODEC_VERSION: u32 = 48; +/// # 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). +pub const CODEC_VERSION: u32 = 49; /// **The version of the `ComputedType` grammar written inside a fact or parameter record.** /// @@ -1194,12 +1204,18 @@ fn put_computed_type(out: &mut Vec, value: &ComputedType) { 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 { - Some(extent) => { + ArrayExtent::Unspecified => put_u8(out, 0), + ArrayExtent::Literal(extent) => { put_u8(out, 1); put_u64(out, *extent); } - None => put_u8(out, 0), + ArrayExtent::Written(written) => { + put_u8(out, 2); + put_str(out, written); + } } } ComputedType::Function(function) => { @@ -1259,8 +1275,9 @@ fn get_computed_type(reader: &mut Reader<'_>, depth: u32) -> Result { let of = Arc::new(get_computed_type(reader, depth + 1)?); let extent = match reader.u8()? { - 0 => None, - 1 => Some(reader.u64()?), + 0 => ArrayExtent::Unspecified, + 1 => ArrayExtent::Literal(reader.u64()?), + 2 => ArrayExtent::written(reader.string()?), _ => return Err(DecodeError::BadDiscriminant), }; ComputedType::Array { of, extent } @@ -1581,7 +1598,7 @@ mod tests { use crate::DeclModifiers; use crate::DirectiveKind; use crate::cache::SummaryKey; - use crate::index::types::{ComputedType, PrimaryType}; + use crate::index::types::{ArrayExtent, ComputedType, PrimaryType}; use crate::preprocess::directive::IncludeForm; use crate::summary; use crate::summary::DeclaredType; @@ -1751,7 +1768,7 @@ mod tests { }, ComputedType::Array { of: Arc::new(ComputedType::Primary(PrimaryType::Int)), - extent: Some(4), + extent: ArrayExtent::Literal(4), }, ComputedType::TemplateParameter(SmolStr::new("T")), ], @@ -1949,7 +1966,13 @@ mod tests { }, ComputedType::Array { of: Arc::new(ComputedType::Primary(PrimaryType::Char)), - extent: None, + 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)), @@ -2398,7 +2421,11 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// — 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. -const COOKED_VERSION: u32 = 12; +/// +/// 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. +const COOKED_VERSION: u32 = 13; /// **The record has its rendering with it** — see [`COOKED_VERSION`]. const COOKED_HAS_A_RENDERING: u8 = 1; diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index effb247b..394a6fa5 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -70,7 +70,11 @@ const MAGIC: [u8; 4] = *b"UNIT"; /// 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. -pub const UNIT_CODEC_VERSION: u32 = 10; +/// +/// 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. +pub const UNIT_CODEC_VERSION: u32 = 11; #[derive(Debug)] pub enum DecodeError { diff --git a/crates/cpp_code_analysis/src/index/project/calls.rs b/crates/cpp_code_analysis/src/index/project/calls.rs index ea34d6e1..9cb0b38c 100644 --- a/crates/cpp_code_analysis/src/index/project/calls.rs +++ b/crates/cpp_code_analysis/src/index/project/calls.rs @@ -440,7 +440,7 @@ pub(crate) fn type_of_a_call( ))); let array = Arc::new(ComputedType::Array { of: element, - extent: None, + extent: index::types::ArrayExtent::Unspecified, }); return Known::Yes(( ComputedType::Reference { @@ -2179,7 +2179,7 @@ fn a_type_through_the_members( of: Arc::new(a_type_through_the_members( index, scopes, root, path, class, of, visited, bindings, depth, )), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => { ComputedType::Function(Arc::new(index::types::FunctionType { @@ -2586,7 +2586,7 @@ fn replace_bare_core( }, ComputedType::Array { of, extent } => ComputedType::Array { of: Arc::new(replace_bare_core(of, matches, with)), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => { ComputedType::Function(Arc::new(index::types::FunctionType { diff --git a/crates/cpp_code_analysis/src/index/types/compute.rs b/crates/cpp_code_analysis/src/index/types/compute.rs index 8cfa0593..daadb8e9 100644 --- a/crates/cpp_code_analysis/src/index/types/compute.rs +++ b/crates/cpp_code_analysis/src/index/types/compute.rs @@ -25,6 +25,7 @@ //! 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; @@ -210,6 +211,71 @@ pub struct QualifiedType { 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)] @@ -233,9 +299,12 @@ pub enum ComputedType { 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: Option, + extent: ArrayExtent, }, Function(Arc), Pack(Arc), @@ -374,7 +443,6 @@ impl ComputedType { /// /// An estimate in the same style as [`crate::MemoryReport`]: live bytes, not the allocator's high-water mark. pub fn heap_bytes(&self) -> usize { - use std::mem::size_of; let text = |name: &SmolStr| name.len(); size_of::() + match self { @@ -391,7 +459,7 @@ impl ComputedType { } ComputedType::Pointer(to) | ComputedType::Pack(to) => to.heap_bytes(), ComputedType::Reference { to, .. } => to.heap_bytes(), - ComputedType::Array { of, .. } => of.heap_bytes(), + ComputedType::Array { of, extent } => of.heap_bytes() + extent.heap_bytes(), ComputedType::ElaboratedRecord { of, .. } => of.heap_bytes(), ComputedType::Function(function) => { size_of::() @@ -439,7 +507,7 @@ impl ComputedType { }, ComputedType::Array { of, extent } => ComputedType::Array { of: Arc::new(of.replacing(name, with)), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(function.returns.replacing(name, with)), @@ -491,7 +559,7 @@ impl ComputedType { }, ComputedType::Array { of, extent } => ComputedType::Array { of: Arc::new(of.substituted_by_bindings(bindings)), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(function.returns.substituted_by_bindings(bindings)), @@ -547,13 +615,7 @@ impl fmt::Display for ComputedType { ComputedType::Reference { to, rvalue } => { write!(out, "{to}{}", if *rvalue { "&&" } else { "&" }) } - ComputedType::Array { of, extent } => { - write!(out, "{of}[")?; - if let Some(extent) = extent { - write!(out, "{extent}")?; - } - write!(out, "]") - } + 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. @@ -631,11 +693,7 @@ impl ComputedType { current = to; } ComputedType::Array { of, extent } => { - suffix.push('['); - if let Some(size) = extent { - suffix.push_str(&size.to_string()); - } - suffix.push(']'); + 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 @@ -790,7 +848,7 @@ mod tests { assert_eq!( ComputedType::Array { of: Arc::new(ComputedType::Primary(PrimaryType::Int)), - extent: Some(4), + extent: ArrayExtent::Literal(4), } .to_string(), "int[4]" @@ -798,11 +856,20 @@ mod tests { assert_eq!( ComputedType::Array { of: Arc::new(ComputedType::Primary(PrimaryType::Int)), - extent: None, + 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)), @@ -925,7 +992,21 @@ mod tests { }, ComputedType::Array { of: Arc::new(ComputedType::Primary(PrimaryType::Int)), - extent: Some(4), + 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)), diff --git a/crates/cpp_code_analysis/src/index/types/mod.rs b/crates/cpp_code_analysis/src/index/types/mod.rs index f45c008a..0cbb19f9 100644 --- a/crates/cpp_code_analysis/src/index/types/mod.rs +++ b/crates/cpp_code_analysis/src/index/types/mod.rs @@ -18,5 +18,7 @@ pub mod compute; pub mod semantics; -pub use compute::{ComputedType, FunctionType, GenericType, PrimaryType, QualifiedType}; +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 index e7cd8bf9..4cf2f411 100644 --- a/crates/cpp_code_analysis/src/index/types/semantics.rs +++ b/crates/cpp_code_analysis/src/index/types/semantics.rs @@ -200,7 +200,7 @@ fn without_elaborated_records(type_of: &ComputedType) -> ComputedType { }, ComputedType::Array { of, extent } => ComputedType::Array { of: Arc::new(without_elaborated_records(of)), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(without_elaborated_records(&function.returns)), @@ -547,7 +547,7 @@ impl ComputedType { }, ComputedType::Array { of, extent } => ComputedType::Array { of: Arc::new(of.substituted(substitutions)), - extent: *extent, + extent: extent.clone(), }, ComputedType::Function(function) => ComputedType::Function(Arc::new(FunctionType { returns: Arc::new(function.returns.substituted(substitutions)), diff --git a/crates/cpp_code_analysis/src/sema/builtins/traits.rs b/crates/cpp_code_analysis/src/sema/builtins/traits.rs index ccb55bf2..ae1936a3 100644 --- a/crates/cpp_code_analysis/src/sema/builtins/traits.rs +++ b/crates/cpp_code_analysis/src/sema/builtins/traits.rs @@ -287,7 +287,9 @@ fn shape(written: &str) -> Shape<'_> { match sema::types::parse_type_spelling(written) { ComputedType::Pointer(_) => Shape::Pointer, ComputedType::Reference { rvalue, .. } => Shape::Reference { rvalue }, - ComputedType::Array { extent, .. } => Shape::Array(extent.is_some()), + // **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. diff --git a/crates/cpp_code_analysis/src/sema/check/mod.rs b/crates/cpp_code_analysis/src/sema/check/mod.rs index 9b7275f5..f2c8d00b 100644 --- a/crates/cpp_code_analysis/src/sema/check/mod.rs +++ b/crates/cpp_code_analysis/src/sema/check/mod.rs @@ -1666,10 +1666,7 @@ pub fn a_spelling_of(type_of: &ComputedType) -> Option { spelling.push_str(&a_spelling_of(&qualified.of)?); spelling } - ComputedType::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)?), }) } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index a5b7e153..fce5eabd 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -445,171 +445,6 @@ pub(crate) fn declared_type_of_with( (!found.to_string().trim().is_empty()).then_some(found) } -/// **The written spelling of a declaration's type**, for a consumer that must evaluate what the structure cannot -/// carry — an array dimension that is a macro or an enumerator (`Point points[COUNT]`). -/// -/// The fact carries the *structural* type, and a dimension that is not a literal is deliberately not part of it -/// (`ComputedType::Array.extent` is `None`). A layout question still has to size such a member, so this is the one query that -/// reassembles the file's own spelling: the specifiers read as syntax, plus the declarator with the declared name cut -/// out — and, for a type's parameter list, with the parameter *names* cut out too (`int (*)(int)` is the type; -/// `int (*)(int left)` is the declaration). It is a **query over the tree**, used for display/evaluation only; no -/// fact stores it. -pub(crate) fn declared_type_spelling_with( - shapes: &DeclarationShapes, - binding: &Binding, -) -> Option { - if !matches!( - binding.kind, - BindingKind::Variable | BindingKind::Typedef | BindingKind::Alias - ) { - return None; - } - let mut specifiers = None; - let mut declarator: Option = None; - let name_is_a_parameter = shapes.names_a_parameter(binding.name_range.start_offset); - shapes.on_the_path(the_offset_to_descend_by(binding), |shape| { - if let Some(node) = &shape.specifiers { - specifiers = Some(node.clone()); - } - if declarator.is_none() - && let Some(node) = &shape.declarator - && reaches_the_name(node, binding.name_range) - && !(name_is_a_parameter && is_a_function_declarator(node)) - { - declarator = Some(node.clone()); - } - }); - let specifiers = specifiers?; - let spelled = match binding.kind { - BindingKind::Typedef => None, - _ => Some(binding.name.spelled()), - }; - let base = sema::types::read_specifiers_named( - &specifiers, - spelled.as_deref(), - source_range(specifiers.text_range()), - ); - let base = strip_declaration_specifiers(&base.to_string()); - let Some(declarator) = declarator else { - return (!base.is_empty()).then_some(base); - }; - let operators = the_operators_around_the_name(&declarator, binding.name_range); - let writing = format!("{base} {operators}"); - let writing = writing.split_whitespace().collect::>().join(" "); - (!writing.is_empty()).then_some(writing) -} - -/// **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** and a **parameter list -/// that belongs to the name** of an object (a constructor call). Everything else is the type's. This is a written -/// spelling for the layout edge only — see [`declared_type_spelling_with`] — not a stored representation. -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(); - 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)); - } - 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()) - }); - 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; - 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]); - } - 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 specifier keywords that can precede a type without being part of it. -const DECLARATION_SPECIFIERS: &[&str] = &[ - "static", - "extern", - "inline", - "virtual", - "explicit", - "friend", - "mutable", - "register", - "thread_local", - "constexpr", - "consteval", - "constinit", - "typedef", - "const", - "volatile", - "struct", - "class", - "union", - "enum", -]; - -/// 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(); - } -} - /// **The modifiers a declaration is written with**, from the tokens the shape table already holds. /// /// `override` and `final` are contextual identifiers, `[[maybe_unused]]` is an attribute and `virtual`/`constexpr` are diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index 0fbc29e5..e2fc62fa 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -25,7 +25,7 @@ //! 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[]` +//! 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` @@ -70,7 +70,7 @@ //! `std::vector::size_type` answerable once `T` is known. use crate::index; -use crate::index::types::{ComputedType, FunctionType, PrimaryType, QualifiedType}; +use crate::index::types::{ArrayExtent, ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; use crate::summary::ConstraintFact; use cpp_parser::CppArrayType; @@ -545,11 +545,17 @@ fn parse_type_spelling_without_a_trailing_qualifier(written: &str) -> ComputedTy } } -/// `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() { @@ -563,7 +569,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)); } } _ => {} @@ -1914,7 +1928,7 @@ fn wrap( enum Step { Pointer, Reference { rvalue: bool }, - Array { extent: Option }, + Array { extent: ArrayExtent }, Parameters(Vec), } @@ -2015,19 +2029,27 @@ fn wrap( 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. -pub(crate) 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. @@ -2482,15 +2504,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`. diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index e915aaad..ea329ddf 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -857,15 +857,6 @@ impl Session { .cmp(&right.fact.file) .then(at(left).cmp(&at(right))) }); - // **The written type of a member of the asking file.** A dimension that is a macro or an enumerator is not - // part of the structural type a fact carries (`Point points[COUNT]` is `Point[]` structurally), and layout - // has to evaluate it — so for the file's own members the declaration's written type is read from the tree it - // came from, once per request. A fact from another file falls back to its canonical spelling. - let written_types = list - .members - .iter() - .any(|member| index.member_path(member) == Some(view.path.as_path())) - .then(|| sema::declarations::DeclarationShapes::of(&view.root)); for member in own { let Some(fact) = index.member_fact(member) else { continue; @@ -875,31 +866,14 @@ impl Session { if fact.kind != DeclKind::Variable || fact.modifiers.contains(DeclModifiers::STATIC) { continue; } - let Some(type_of) = index.member_type_spelling(member) 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; }; - // **The spelling the file wrote**, for a member of the asking file — see `written_types`. - let type_of = match (&written_types, fact.type_of.computed().is_some()) { - (Some(shapes), true) if index.member_path(member) == Some(view.path.as_path()) => { - // **By name and scope, not by offset.** A fact read from the index holds *file* offsets, and - // this view's tree is the rendering — the two need not agree once a macro has been expanded. - // The scope tree is keyed by the same qualified names the fact carries. - view.scopes - .scope_with_qualified_name(&member.declared_in) - .and_then(|scope| view.scopes.scope(scope)) - .and_then(|data| { - data.bindings.iter().find(|binding| { - binding.name.identifier_text() == Some(fact.name.as_str()) - }) - }) - .and_then(|binding| { - sema::declarations::declared_type_spelling_with(shapes, binding) - }) - .unwrap_or(type_of) - } - _ => type_of, - }; // **A bitfield's width is in the file's text, not in its fact.** It is read at the member's own file // offset, which is why the class was read out of its summary above: a member fact that came from a cooked // reading carries the rendering's offsets instead. A width that is not a literal (`: BITS`) stays @@ -924,21 +898,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( 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)) @@ -1201,6 +1180,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 diff --git a/crates/cpp_code_analysis/tests/suite/layout.rs b/crates/cpp_code_analysis/tests/suite/layout.rs index 6679dff9..095f2cdc 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 { @@ -550,6 +552,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/types.rs b/crates/cpp_code_analysis/tests/suite/types.rs index b9302106..ce739e42 100644 --- a/crates/cpp_code_analysis/tests/suite/types.rs +++ b/crates/cpp_code_analysis/tests/suite/types.rs @@ -2826,7 +2826,7 @@ std::string f() { /// call deduces, so no assertion hands the evaluator a condition spelling. #[test] fn the_constraint_evaluator_decides_the_fundamental_traits() { - use cpp_code_analysis::index::types::{ComputedType, FunctionType, QualifiedType}; + 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, }; @@ -2886,7 +2886,7 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { })) }; let a_pointer = |of: ComputedType| ComputedType::Pointer(Arc::new(of)); - let an_array = |of: ComputedType, extent: Option| ComputedType::Array { + let an_array = |of: ComputedType, extent: ArrayExtent| ComputedType::Array { of: Arc::new(of), extent, }; @@ -3074,12 +3074,17 @@ fn the_constraint_evaluator_decides_the_fundamental_traits() { ("std::is_volatile_v", ComputedType::builtin("int"), false), ( "std::is_array_v", - an_array(ComputedType::builtin("int"), Some(4)), + an_array(ComputedType::builtin("int"), ArrayExtent::Literal(4)), true, ), ( "std::is_array_v", - an_array(ComputedType::builtin("int"), None), + 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), From 90d546f74a276f7a4c497ee8951915fb5f31ef83 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 18:21:46 +0800 Subject: [PATCH 099/102] refactor(constraints): distinguish type and value arguments ConstraintFact arguments are ConstraintArgument::{Type(ComputedType), Value(SmolStr)}; value arguments are no longer wrapped as ComputedType::Named. The reader classifies by the direct TemplateArgument child, constrained non-type parameters read their type-constraint through CppDeclSpecifierSeq::get_type_constraint, and concept_not_satisfied only compares type arguments (values stay Unknown/silent). Codec versions move (CODEC 50, COOKED 14, UNIT 12) with per-argument tags. Tests cover value arguments, constrained auto parameters, parser accessor and codec round-trips. Workspace tests (3625 passed) and clippy pass. --- crates/cpp_code_analysis/src/cache/summary.rs | 74 ++++- .../src/cache/summary_codec.rs | 100 +++++-- .../cpp_code_analysis/src/cache/unit_codec.rs | 7 +- crates/cpp_code_analysis/src/lib.rs | 10 +- .../src/sema/check/concept_not_satisfied.rs | 37 ++- .../sema/check/test/concept_not_satisfied.rs | 20 ++ .../src/sema/declarations.rs | 55 +++- crates/cpp_code_analysis/src/sema/types.rs | 261 ++++++++++++++++-- crates/cpp_parser/src/syntax/node/cpp/mod.rs | 54 ++++ crates/cpp_parser/tests/suite/concepts.rs | 72 ++++- 10 files changed, 612 insertions(+), 78 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary.rs b/crates/cpp_code_analysis/src/cache/summary.rs index 191791f8..5a871c2b 100644 --- a/crates/cpp_code_analysis/src/cache/summary.rs +++ b/crates/cpp_code_analysis/src/cache/summary.rs @@ -465,8 +465,10 @@ pub struct DeclFact { /// 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 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 [`ComputedType`] -/// values, because the alternative was storing a spelling a consumer would have to parse back into a type. +/// [`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. @@ -490,7 +492,8 @@ pub struct DeclDetail { /// 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 them back into a type was the round trip this field removes. + /// 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, @@ -534,10 +537,10 @@ impl DeclDetail { /// [`DeclDetail::constraints`]. /// /// A `template ` head writes a **concept** in front of the parameter's name, and the concept may -/// carry type arguments: `std::same_as`, `std::convertible_to` (and the two-argument spellings a file may -/// write, which are kept whole). 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 -/// [`ComputedType`], exactly the way every other type answer in this crate does, instead of splitting a spelling. +/// 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)] @@ -546,13 +549,56 @@ pub struct ConstraintFact { /// `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 type argument the concept wrote**, in the order it wrote them, lowered structurally. + /// **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. - pub arguments: Box<[ComputedType]>, + /// 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 { @@ -589,9 +635,9 @@ fn strings_bytes(values: &[SmolStr]) -> usize { } /// **The bytes the structured constraints own** — their optional slots, each concept's payload, and the argument -/// trees that fell out of line. Each argument's [`ComputedType::heap_bytes`] already counts its own inline slot, the -/// same convention the type model uses; the slot array is counted here for the same reason [`strings_bytes`] counts -/// its element array, because the detail's own `size_of` covers only the `Vec` header. +/// 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 @@ -602,7 +648,7 @@ fn constraint_facts_bytes(values: &[Option]) -> usize { + constraint .arguments .iter() - .map(ComputedType::heap_bytes) + .map(ConstraintArgument::heap_bytes) .sum::() }) .sum::() diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 706cb12b..870c8d92 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -45,9 +45,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. @@ -359,7 +359,17 @@ const MAGIC: &[u8; 8] = b"CPPLSSUM"; /// 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). -pub const CODEC_VERSION: u32 = 49; +/// +/// # 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.** /// @@ -369,6 +379,14 @@ pub const CODEC_VERSION: u32 = 49; /// 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. /// /// The encoding is little-endian throughout, which is what every target this runs on uses in practice; the @@ -1595,6 +1613,7 @@ mod tests { 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; @@ -1685,16 +1704,20 @@ mod tests { // The constraint in front of each parameter — empty here, and carried by the round trip. constraints: vec![SmolStr::default(), "Integral".into()], // **The same constraints structurally**, in the same slots: the second parameter's concept - // carries a type argument, so the round trip exercises a nested type value and not only a - // name. The first slot is `None`, the shape an unconstrained parameter has. + // 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![ComputedType::named( - "std::vector", - vec![ComputedType::Primary(PrimaryType::Int)], - )] + arguments: vec![ + ConstraintArgument::Type(ComputedType::named( + "std::vector", + vec![ComputedType::Primary(PrimaryType::Int)], + )), + ConstraintArgument::Value("42".into()), + ] .into_boxed_slice(), }), ], @@ -2140,9 +2163,10 @@ 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. A concept is a name and its - // arguments are type values, so this is written with the same [`ENCODED_COMPUTED_TYPE`] grammar the declaration's - // own types use — no spelling is parsed on the way back in. + // **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 { @@ -2151,8 +2175,16 @@ fn put_declaration(out: &mut Vec, fact: &DeclFact) { put_str(out, &constraint.concept); put_u32(out, constraint.arguments.len() as u32); for argument in &constraint.arguments { - put_u8(out, ENCODED_COMPUTED_TYPE); - put_computed_type(out, argument); + 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), @@ -2247,10 +2279,15 @@ fn get_declaration(reader: &mut Reader<'_>) -> Result { let count = reader.count()?; let mut arguments = Vec::with_capacity(count.min(64 * 1024)); for _ in 0..count { - if reader.u8()? != ENCODED_COMPUTED_TYPE { - return Err(DecodeError::BadDiscriminant); - } - arguments.push(get_computed_type(reader, 0)?); + 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, @@ -2425,7 +2462,12 @@ const COOKED_MAGIC: &[u8; 8] = b"CPPLSCKR"; /// 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. -const COOKED_VERSION: u32 = 13; +/// +/// 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; @@ -2761,10 +2803,13 @@ fn a_cooked_reading_round_trips() { returns_in_the_class: None, bases: Vec::new(), parameters: Vec::new(), - constraints: vec!["Copyable".into()], + 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: "Copyable".into(), - arguments: Vec::new().into_boxed_slice(), + concept: "SomeConcept".into(), + arguments: vec![ConstraintArgument::Value("42".into())].into_boxed_slice(), })], requires_clause: None, parameter_defaults: vec!["0".into()], @@ -2806,6 +2851,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!( diff --git a/crates/cpp_code_analysis/src/cache/unit_codec.rs b/crates/cpp_code_analysis/src/cache/unit_codec.rs index 394a6fa5..925c6c1c 100644 --- a/crates/cpp_code_analysis/src/cache/unit_codec.rs +++ b/crates/cpp_code_analysis/src/cache/unit_codec.rs @@ -74,7 +74,12 @@ const MAGIC: [u8; 4] = *b"UNIT"; /// 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. -pub const UNIT_CODEC_VERSION: u32 = 11; +/// +/// 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 { diff --git a/crates/cpp_code_analysis/src/lib.rs b/crates/cpp_code_analysis/src/lib.rs index e626afb2..dcfc64ab 100644 --- a/crates/cpp_code_analysis/src/lib.rs +++ b/crates/cpp_code_analysis/src/lib.rs @@ -146,11 +146,11 @@ pub use sema::{check, module_info, modules, parser_symbols, scopes, symbol}; pub use memory::MemoryReport; pub use summary::ConditionalBody; pub use summary::{ - ClosureEvidence, ConditionAt, ConditionalRegion, 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, + 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, }; 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 8cace628..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 @@ -30,15 +30,18 @@ //! 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::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 type arguments, lowered from the head's own `CppTemplateParam` nodes when the fact was built. 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". +//! 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; @@ -188,19 +191,29 @@ impl Concept { /// **Which concept a [`ConstraintFact`] names** — the last segment the head read, with or without `std::`. /// /// The fact is already the head's own answer: `sema::types` lowered the constrained parameter's `NamedType` or - /// `TemplateType` into a [`ComputedType`] 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. + /// `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_argument = || constraint.arguments.first().cloned(); + let first_type_argument = || match constraint.arguments.first()? { + ConstraintArgument::Type(argument) => Some(argument.clone()), + ConstraintArgument::Value(_) => None, + }; match constraint.concept.as_str() { "integral" | "signed_integral" | "unsigned_integral" => Some(Concept::Integral), "floating_point" => Some(Concept::FloatingPoint), - "same_as" => Some(Concept::SameAs(first_argument()?)), - "convertible_to" => Some(Concept::ConvertibleTo(first_argument()?)), - "derived_from" => Some(Concept::DerivedFrom(first_argument()?)), + "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" 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 d73de037..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 @@ -144,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/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index fce5eabd..6ac077fa 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -6367,11 +6367,12 @@ 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 type 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. + /// 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( @@ -6399,11 +6400,11 @@ int Box::Inner::deep = 0; ); assert_eq!( structured.arguments[0], - ComputedType::Primary(PrimaryType::Int) + ConstraintArgument::Type(ComputedType::Primary(PrimaryType::Int)) ); assert_eq!( structured.arguments[1], - ComputedType::Primary(PrimaryType::Long) + ConstraintArgument::Type(ComputedType::Primary(PrimaryType::Long)) ); let g = fact_of("g"); @@ -6425,6 +6426,50 @@ int Box::Inner::deep = 0; ); } + /// **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"); diff --git a/crates/cpp_code_analysis/src/sema/types.rs b/crates/cpp_code_analysis/src/sema/types.rs index e2fc62fa..14fa8f0f 100644 --- a/crates/cpp_code_analysis/src/sema/types.rs +++ b/crates/cpp_code_analysis/src/sema/types.rs @@ -72,14 +72,16 @@ use crate::index; use crate::index::types::{ArrayExtent, ComputedType, FunctionType, PrimaryType, QualifiedType}; use crate::sema; -use crate::summary::ConstraintFact; +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::CppTemplateArg; use cpp_parser::CppTemplateParam; use cpp_parser::CppTypeId; use cpp_parser::SourceRange; @@ -89,7 +91,6 @@ use cpp_parser::typed_descendants; use smol_str::SmolStr; use std::sync::Arc; -use cpp_parser::CppAstNode; use cpp_parser::{CppSyntaxKind, CppSyntaxNode}; /// **The node's text, trimmed, in one allocation.** `text().to_string().trim().to_string()` copied the node twice for @@ -828,8 +829,8 @@ pub fn template_parameter_defaults(list: &CppSyntaxNode) -> Vec { /// 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 [`ComputedType`]-shaped value a check -/// reads, so no consumer has to split a spelling back into a concept name and arguments. +/// 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 @@ -862,11 +863,13 @@ pub struct TemplateParameter { /// /// # The constraint's structured half /// -/// A constrained 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`, +/// 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. Nothing here takes the constraint apart as text. +/// 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(); @@ -937,22 +940,35 @@ pub fn template_parameters_with_defaults(list: &CppSyntaxNode) -> Vec 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`. /// -/// The concept node is then lowered with [`read_specifiers`], the one reader a declaration's type goes through, so -/// its arguments are [`ComputedType`]s: `std::same_as` answers the concept `same_as` with *both* -/// arguments, and the display is the same value's canonical `Display`. No spelling is split here. +/// 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()) @@ -964,19 +980,61 @@ fn constrained_by(parameter: &CppTemplateParam) -> Option<(ConstraintFact, Strin return None; } - let lowered = read_specifiers(node); // **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. - let display = lowered.to_string(); - let (name, arguments) = match lowered { - ComputedType::Named(name) => (name, Vec::new()), - ComputedType::Generic(generic) => (generic.name.clone(), generic.arguments.to_vec()), + // 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(", "); + } + display.push_str(&argument.to_string()); + } + display.push('>'); + } + Some(( ConstraintFact { concept: SmolStr::from(concept), @@ -986,6 +1044,81 @@ fn constrained_by(parameter: &CppTemplateParam) -> Option<(ConstraintFact, Strin )) } +/// **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 +} + +/// **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 /// `class _Alloc = allocator<_Ty>`. /// @@ -3015,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)] diff --git a/crates/cpp_parser/src/syntax/node/cpp/mod.rs b/crates/cpp_parser/src/syntax/node/cpp/mod.rs index 20d4db5f..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 { 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 From a7248b43ec43fa6a983fd30fb78d825c93aa5d4e Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 19:55:14 +0800 Subject: [PATCH 100/102] fix(layout): size enums as their underlying integer Enum enumerators are Variable facts, so the class-layout walk tried to size each and std::errc answered 'not computed' listing all 78. A type whose own members are all enumerators is now sized as int/4 (the default underlying type), and enumerators are skipped by the data-member walk. Also removes leftover debug prints in fact construction. Hover's rendering fallback is now limited to expressions containing a MacroCall: for an ordinary expression a failed answer is honest, while crossing offsets into an inlined header could answer an unrelated expression (measured: maybe(5).transform(...) answered divide(6,2)'s int). --- .../src/sema/declarations.rs | 9 ------ crates/cpp_code_analysis/src/session/calls.rs | 21 ++++++++++++- .../src/session/completion/request.rs | 31 ++++++++++++++----- .../cpp_code_analysis/tests/suite/layout.rs | 26 +++++++++++++--- crates/cpp_ls/src/handlers/hover/mod.rs | 14 ++++++++- 5 files changed, 79 insertions(+), 22 deletions(-) diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 6ac077fa..53d902da 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -4076,15 +4076,6 @@ fn fact_for( DeclaredType::Computed(std::sync::Arc::new(written)) }) }; - if name.as_ref() == "pointer" { - eprintln!("[fact] {} -> {:?}", name, type_of); - } - if name.as_ref() == "priority" { - eprintln!("[fact] {} -> {:?}", name, type_of); - } - if name.as_ref() == "find" { - eprintln!("[fact find] params={:?} returns={:?}", parameters, returns); - } let type_of = lower(type_of); let returns = lower(returns); diff --git a/crates/cpp_code_analysis/src/session/calls.rs b/crates/cpp_code_analysis/src/session/calls.rs index ea329ddf..2cb9ee88 100644 --- a/crates/cpp_code_analysis/src/session/calls.rs +++ b/crates/cpp_code_analysis/src/session/calls.rs @@ -766,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))) => { @@ -863,7 +879,10 @@ impl Session { }; // **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; } // **The member's type as its fact carries it, structurally.** An array dimension that is a macro or an diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index c351377a..1da9a4d8 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -558,12 +558,17 @@ impl Session { expression, 0, ) { - Known::Yes((type_of, file)) => Known::Yes(ExpressionType { - expression: written, - type_of: type_of.to_string(), - type_value: Some(type_of), - 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, } @@ -669,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 @@ -1205,3 +1210,15 @@ 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/tests/suite/layout.rs b/crates/cpp_code_analysis/tests/suite/layout.rs index 095f2cdc..79597b17 100644 --- a/crates/cpp_code_analysis/tests/suite/layout.rs +++ b/crates/cpp_code_analysis/tests/suite/layout.rs @@ -23,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:?}"), } } @@ -66,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() { diff --git a/crates/cpp_ls/src/handlers/hover/mod.rs b/crates/cpp_ls/src/handlers/hover/mod.rs index 6998dca1..6696ff0b 100644 --- a/crates/cpp_ls/src/handlers/hover/mod.rs +++ b/crates/cpp_ls/src/handlers/hover/mod.rs @@ -1128,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 @@ -1826,6 +1829,15 @@ fn a_line(session: &Session, fact: &DeclFact) -> 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 { From 35b2959789effb6d08ef210a307139480c351be9 Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 20:35:40 +0800 Subject: [PATCH 101/102] fix(facts): deduce pair and tuple arguments from braced literals A variable fact now applies the standard's pair/tuple braced deduction when every initializer element is a literal the syntax states: std::pair pair{1, 2} records std::pair instead of the bare class name, so the hover card shows the instantiation and downstream members have arguments to substitute. Non-literal elements leave the written type alone. Uses typed CppInitializer/CppInitListExpr checks. --- .../src/sema/declarations.rs | 57 ++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 53d902da..10d4432c 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -39,7 +39,7 @@ use crate::sema::types::TypeSubstitutions; use crate::summary; use crate::token; use cpp_parser::CppBinaryExpr; -use cpp_parser::CppInitializer; +use cpp_parser::{CppInitListExpr, CppInitializer}; use cpp_parser::CppParam; use cpp_parser::CppParamList; use cpp_parser::CppPreprocessorDirective; @@ -3813,6 +3813,54 @@ pub(crate) fn declared_bases_of_with(shapes: &DeclarationShapes, binding: &Bindi /// /// 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, @@ -4076,6 +4124,13 @@ fn fact_for( 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); From 06138dc2698181ed7bc5dec1ba3def51d816421b Mon Sep 17 00:00:00 2001 From: CppCXY <812125110@qq.com> Date: Fri, 4 Dec 2026 20:52:27 +0800 Subject: [PATCH 102/102] clean code --- .../src/cache/summary_codec.rs | 9 +++++---- .../src/index/project/queries.rs | 3 ++- .../src/index/project/tests.rs | 3 ++- .../src/sema/declarations.rs | 2 +- .../src/session/completion/request.rs | 1 - .../src/session/signature.rs | 19 +++++++++---------- .../src/handlers/type_definition/mod.rs | 3 ++- 7 files changed, 21 insertions(+), 19 deletions(-) diff --git a/crates/cpp_code_analysis/src/cache/summary_codec.rs b/crates/cpp_code_analysis/src/cache/summary_codec.rs index 870c8d92..a4bf5c8e 100644 --- a/crates/cpp_code_analysis/src/cache/summary_codec.rs +++ b/crates/cpp_code_analysis/src/cache/summary_codec.rs @@ -33,6 +33,7 @@ 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; @@ -1357,8 +1358,8 @@ fn get_parameter_facts( let kind = u16::try_from(reader.u32()?).map_err(|_| DecodeError::BadDiscriminant)?; let start = reader.u32()?; let end = reader.u32()?; - let declaration = cpp_parser::CppSyntaxId::from_raw_parts(kind, start, end) - .ok_or(DecodeError::BadDiscriminant)?; + let declaration = + CppSyntaxId::from_raw_parts(kind, start, end).ok_or(DecodeError::BadDiscriminant)?; let default_value = match reader.u8()? { 0 => None, 1 => { @@ -1367,7 +1368,7 @@ fn get_parameter_facts( let start = reader.u32()?; let end = reader.u32()?; Some( - cpp_parser::CppSyntaxId::from_raw_parts(kind, start, end) + CppSyntaxId::from_raw_parts(kind, start, end) .ok_or(DecodeError::BadDiscriminant)?, ) } @@ -2728,7 +2729,7 @@ fn a_cooked_reading_round_trips() { parameters: index::params::ParamsStore::from_entries(vec![ vec![index::params::ParameterFact { name: Some("value".into()), - declaration: cpp_parser::CppSyntaxId::from_raw_parts(0, 0, 1).expect("a syntax id"), + declaration: CppSyntaxId::from_raw_parts(0, 0, 1).expect("a syntax id"), default_value: None, pack: false, type_of: DeclaredType::Computed(Arc::new(ComputedType::Primary(PrimaryType::Int))), diff --git a/crates/cpp_code_analysis/src/index/project/queries.rs b/crates/cpp_code_analysis/src/index/project/queries.rs index 71f214f5..943fdb65 100644 --- a/crates/cpp_code_analysis/src/index/project/queries.rs +++ b/crates/cpp_code_analysis/src/index/project/queries.rs @@ -14,6 +14,7 @@ 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; @@ -710,7 +711,7 @@ pub(crate) fn the_overload_a_call_names( // template argument is the condition. Both answers are **typed CST nodes** — nothing here is a spelling. let requires_clause = declaration_node .descendants() - .find_map(::cast) + .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)); diff --git a/crates/cpp_code_analysis/src/index/project/tests.rs b/crates/cpp_code_analysis/src/index/project/tests.rs index 14fc6d96..81b4ba18 100644 --- a/crates/cpp_code_analysis/src/index/project/tests.rs +++ b/crates/cpp_code_analysis/src/index/project/tests.rs @@ -41,6 +41,7 @@ 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, PathBuf}; @@ -3156,7 +3157,7 @@ fn after(source: &str, needle: &str) -> usize { struct ResolvedCompletions { class: String, members: ResolvedList, - member_range: cpp_parser::SourceRange, + member_range: SourceRange, prefix: String, hidden_by_access: usize, } diff --git a/crates/cpp_code_analysis/src/sema/declarations.rs b/crates/cpp_code_analysis/src/sema/declarations.rs index 10d4432c..94789ccd 100644 --- a/crates/cpp_code_analysis/src/sema/declarations.rs +++ b/crates/cpp_code_analysis/src/sema/declarations.rs @@ -39,7 +39,6 @@ use crate::sema::types::TypeSubstitutions; use crate::summary; use crate::token; use cpp_parser::CppBinaryExpr; -use cpp_parser::{CppInitListExpr, CppInitializer}; use cpp_parser::CppParam; use cpp_parser::CppParamList; use cpp_parser::CppPreprocessorDirective; @@ -56,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}; diff --git a/crates/cpp_code_analysis/src/session/completion/request.rs b/crates/cpp_code_analysis/src/session/completion/request.rs index 1da9a4d8..0f2fe9ce 100644 --- a/crates/cpp_code_analysis/src/session/completion/request.rs +++ b/crates/cpp_code_analysis/src/session/completion/request.rs @@ -1211,7 +1211,6 @@ fn is_a_name_expression(argument: &CppSyntaxNode) -> bool { ) } - /// **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 diff --git a/crates/cpp_code_analysis/src/session/signature.rs b/crates/cpp_code_analysis/src/session/signature.rs index c63946f3..1fe39198 100644 --- a/crates/cpp_code_analysis/src/session/signature.rs +++ b/crates/cpp_code_analysis/src/session/signature.rs @@ -28,11 +28,13 @@ //! [`Ambiguous`]: crate::UnknownReason::Ambiguous use crate::DeclKind; -use crate::index; +use crate::index::types::ComputedType; use crate::sema; use std::ops::Range; use std::path::{Path, PathBuf}; +use cpp_parser::CppParam; +use cpp_parser::CppParamList; use cpp_parser::{ CppAstNode, CppDocComment, CppSyntaxElement, CppSyntaxKind, CppSyntaxNode, CppTokenKind, }; @@ -158,7 +160,7 @@ where // 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(); + 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 @@ -230,7 +232,7 @@ where // **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(); + 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(" "); @@ -240,18 +242,15 @@ where let start = label.len(); label.push_str(&text); parameters.push((start..label.len(), text.clone())); - let written = cpp_parser::CppParam::cast(parameter) + let written = CppParam::cast(parameter) .and_then(|parameter| sema::types::type_of_a_parameter(¶meter)); - plain.push( - written.unwrap_or_else(|| index::types::ComputedType::named(text, Vec::new())), - ); + 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 = - cpp_parser::CppParamList::cast(list.clone()).is_some_and(|list| list.is_variadic()); + let variadic = CppParamList::cast(list.clone()).is_some_and(|list| list.is_variadic()); if variadic { if !parameters.is_empty() { label.push_str(", "); @@ -309,7 +308,7 @@ 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), diff --git a/crates/cpp_ls/src/handlers/type_definition/mod.rs b/crates/cpp_ls/src/handlers/type_definition/mod.rs index 79498dca..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; @@ -200,7 +201,7 @@ pub fn type_definitions_of( fn declarations_of_a_type_value( session: &Session, view: &FileView, - type_of: &cpp_code_analysis::index::types::ComputedType, + type_of: &ComputedType, ) -> Option> { declarations_of_a_type_name(session, view, type_of.class_name()?) }