Repository navigation
Refactor type - #3
Merged
Merged
Conversation
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
A hundred std::vector<int> 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.
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.
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.
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.
DeclFact.type_of and returns use Option<Arc<str>>: 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.
DeclDetail's base, parameter, constraint and default vectors are Vec<SmolStr>, so a short name no longer allocates. TypeSubstitutions, substituted_spelling, deduction and pattern matching are generic over AsRef<str>; call sites that still need Vec<String> convert at the boundary.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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<NamedType>) 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.
DeclFact and ParameterFact now carry DeclaredType::{None, Computed(Arc<ComputedType>)} 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.
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.
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.
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.
ExpressionType now carries type_value: Option<ComputedType> 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.
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.
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.
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.
range_element_of and element_of now return ComputedType instead of a spelling: map elements construct std::pair<const K, V> 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.
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.
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.
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.
The fixed size_t result is a ComputedType::Named construction, not a spelling parse. Workspace tests (3618 passed) and clippy pass.
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<Widget>. Workspace tests (3619 passed) and clippy pass.
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.
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.
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.
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.
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).
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<int, int> 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.