Skip to content

Commit 09939af

Browse files
committed
hover: the card is rendered from the model, never sliced from the file
Reported: "most hover results are a copy of the source range, not a reconstructed rendering — no copy-paste display allowed; redo the hover rendering modelled on Rust, especially for generics." **The code block is now generated by one module.** `cpp_code_analysis::sema::render` takes a `DeclFact` (and the declaration's node when the declaring file is at hand) and rebuilds the item: ```text template <typename T, typename Alloc = int> class Box As written here: `Box<int>` ``` * a **type** is parsed from the recorded spelling and printed by `Type`'s own writer — `std::vector<std::string> &` becomes `std::vector<std::string>&`, `char *` becomes `char*`, `typename` disappears; * a **parameter list** is parsed: types canonical, names kept, defaults summarised (`= 2`, `= npos`, `= …` for an expression), a pack's `...` said once; * a **template head** is rebuilt from the declaration's parameters — `class`/`typename` as written, non-type parameters by type, defaults, packs — with the fact's names as the fallback when the syntax is not at hand; * a **class** says the keyword its node kind carries (`class`/`struct`/`union`/`enum`/`enum class`), its bases, and the reflection annotation above it (`UCLASS(Blueprintable)`, from the fact, not the text); * an **alias** is `using X = Y;`, a **variable** keeps `static`/`constexpr`/`const`/`volatile`, an **enumerator** shows the folded number, a **namespace** its name. Deleted from hover: `declaration_text`, `the_template_head_before`, `the_declarations_start`, `slice_lines`, `signature_line`, `the_trailing_clause`, `spells_a_signature`, `MAX_HOVER_LINES`. The card, the overload list and the member list all print `render::an_item` / `render::a_line`, so the three cannot disagree. **Generics.** A member of a known specialization is rendered **instantiated** — the member list substitutes the class's arguments, so `put(const T& value) const &` on a `Box<int>` reads `put(const int& value) const &` (measured). A class template's card shows its own head plus `As written here: \`Box<int>\``. **Parser fixes found while rendering it.** `CppTemplateParam::is_type_param` searched direct tokens only (the keyword lives under the parameter's specifier sequence), so every type parameter was read as a non-type one; `CppTemplateParam::get_name` had no answer for a type parameter (`typename T` has no declarator), so the head rendered `template <typename, typename>`. Both are subtree searches now. **Fact-level repairs the card needed.** `element_type`'s alias target kept its `typename` (`parse_type_spelling`); `qualified_from_the_index` took the first fact *named* like the class — a constructor — giving `std::shared_ptr::shared_ptr`; `members_of` never retried the qualified spelling for a bare name; `finish_a_nested_name` could not follow a head that is another class (`__shared_ptr<T>::element_type`); an unresolved pointee was returned as a class name. Each has a test, and `shared_ptr` on a hand-written fixture now resolves `p->identifier()`. Tests: nine renderer tests (function, template head with kinds/defaults, non-type parameter and pack, class keywords, alias, variable qualifiers, parameter parsing, type printing), the hover integration tests, and the reported hovers. `reported_hover` now expects the canonical `Fn&& fn`; the anonymous-struct card asserts it does **not** echo the struct's body; `a_hover_names_the_instantiation_and_never_invents_a_void` keeps its own names. The remaining work — `type_of` losing its shape match (the `shared_ptr` root cause), the two readings, and the gaps this pass found — is written down in `docs/hover-render.md`.
1 parent 2d7d09a commit 09939af

12 files changed

Lines changed: 1180 additions & 333 deletions

File tree

‎crates/cpp_code_analysis/src/index/project.rs‎

Lines changed: 182 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1689,8 +1689,20 @@ pub(crate) fn the_pointee_of_a_handle(
16891689
file,
16901690
vec![fact.name.clone()],
16911691
);
1692+
// **A name that no class declares is not a pointee.** `std::shared_ptr`'s `element_type` is written
1693+
// `typename __shared_ptr<_Tp>::element_type`, and a walk that cannot finish it answers the spelling it started with —
1694+
// a class called `__shared_ptr<Resource>::element_type`, which nothing declares. Handing that back hides the caller's
1695+
// own fallback (following `operator->`'s declared return type), which is the step that does resolve it: measured on
1696+
// `test_cpp`'s `smart_pointers.cpp`, the hover asked for members of that invented name and said
1697+
// "`shared_ptr<Resource>` has no member `identifier`".
16921698
match finished.0 {
1693-
Type::Named { name, arguments } => Some((name, arguments)),
1699+
Type::Named { name, arguments } => {
1700+
let declared = index.files_declaring(base_type_name(&name), path);
1701+
declared
1702+
.iter()
1703+
.any(|declaration| declaration.fact.kind == crate::DeclKind::Type)
1704+
.then_some((name, arguments))
1705+
}
16941706
_ => None,
16951707
}
16961708
}
@@ -1965,6 +1977,10 @@ pub fn members_of(
19651977
// written as, and the class is `std::shared_ptr`; a member list asked for the bare name answered `NotDeclaredHere`
19661978
// while the completion at the same cursor offered the members (reported: "`shared_ptr<int>` has no member `reset`"
19671979
// with `reset` in the list next to it). Qualified once, only when the first answer held no class.
1980+
// **An empty answer is also a reason to try the qualified spelling.** A bare class name that resolved to an
1981+
// *ambiguous* declaration answers `Known::Yes` with no members (`direct_members`' own rule for `Ambiguous`), so the
1982+
// retry below — which only ran when the first answer held no class at all — never happened: measured,
1983+
// `members_of("shared_ptr")` answered 0 members while `members_of("std::shared_ptr")` answered 39.
19681984
let listed = match &listed {
19691985
Known::No | Known::Unknown(_) => match class.contains("::") {
19701986
true => listed,
@@ -1975,6 +1991,20 @@ pub fn members_of(
19751991
_ => listed,
19761992
},
19771993
},
1994+
Known::Yes(list) if list.members.is_empty() && !class.contains("::") => {
1995+
match qualified_from_the_index(index, path, base_type_name(class)) {
1996+
Some(qualified) if qualified != class => {
1997+
// The arguments the caller wrote are kept: `shared_ptr<Resource>` qualifies to
1998+
// `std::shared_ptr<Resource>`, which is the spelling the members are then substituted with.
1999+
let qualified = match class.find('<') {
2000+
Some(at) => format!("{qualified}{}", &class[at..]),
2001+
None => qualified,
2002+
};
2003+
members_of_inner(index, scopes, root, path, &qualified)
2004+
}
2005+
_ => listed,
2006+
}
2007+
}
19782008
Known::Yes(_) => listed,
19792009
};
19802010
if let Known::Yes(list) = &listed {
@@ -4435,7 +4465,7 @@ fn type_of_expression_inner(
44354465
//
44364466
// Read from the **token**, not the text: `1` and `1.0f` and `"abc"` differ by their kind, and a suffix
44374467
// (`10u`, `1.0L`) is part of the literal rather than a separate thing to interpret. A user-defined literal
4438-
// (`10_km`) is deliberately **not** here: its type is whatever the literal operator returns, which is a lookup.
4468+
// (`10_km`) is a **lookup**: its type is the return type of `operator""_km`, and that is the arm below.
44394469
if let Some((kind, written_as)) = expression
44404470
.children_with_tokens()
44414471
.filter_map(|element| element.into_token())
@@ -4468,8 +4498,36 @@ fn type_of_expression_inner(
44684498
cpp_parser::CppTokenKind::NullptrLiteral | cpp_parser::CppTokenKind::NullptrKeyword => {
44694499
Some("nullptr_t")
44704500
}
4501+
// **A user-defined literal's type is its operator's return type.** `"numbers"sv` is
4502+
// `operator""sv("numbers", 1)`, whose declaration is where the type is written — a lookup, and one the index
4503+
// answers by name. Measured on `test_cpp`'s `strings.cpp`: `"numbers"sv.size()` had no type at all, so the
4504+
// hover on `size` said the type of `"numbers"sv` was not known and go-to-definition reached nothing.
4505+
cpp_parser::CppTokenKind::UserDefinedLiteral => None,
44714506
_ => None,
44724507
};
4508+
// **The one literal kind whose spelling is not its type.** Handled before the arm above so that the
4509+
// `Some("int")`-style answers stay one match, and because this is the only case that needs the index.
4510+
if kind == cpp_parser::CppTokenKind::UserDefinedLiteral {
4511+
// **An unknown answer says what is unknown**: the literal, with its suffix, rather than the whole
4512+
// expression, because the suffix is the part that did not resolve.
4513+
let a_user_defined_literal_is = |returns: String| {
4514+
Known::Yes((
4515+
crate::sema::types::parse_type_spelling(&returns),
4516+
path.to_path_buf(),
4517+
))
4518+
};
4519+
if let Some(suffix) = a_user_defined_literals_suffix(&written_as)
4520+
&& let Some(declared) = index
4521+
.files_declaring(&format!("operator\"\"{suffix}"), path)
4522+
.into_iter()
4523+
.find(|declared| declared.fact.kind == crate::DeclKind::Function)
4524+
&& let Some(returns) = declared.fact.returns.as_deref()
4525+
&& !returns.trim().is_empty()
4526+
{
4527+
return a_user_defined_literal_is(returns.to_string());
4528+
}
4529+
return Known::Unknown(UnknownReason::UnknownType(Box::from(written)));
4530+
}
44734531
if let Some(spelled) = literal {
44744532
// **Parsed, not named.** `Type::named("int")` is a type whose *name* is `int` — a class as far as every
44754533
// later question is concerned — and the same for `const char*`. Measured: a string literal came back as
@@ -4486,6 +4544,30 @@ fn type_of_expression_inner(
44864544
}
44874545
}
44884546

4547+
/// **The suffix of a user-defined literal** — `_kb` for `4_kb`, `sv` for `"numbers"sv`, `_f` for `1.0e5_f`.
4548+
///
4549+
/// The token is one piece of text, so the boundary has to be found in it. The **last** run of identifier characters
4550+
/// is the suffix's neighbourhood; inside it, a suffix begins at its last `_` (a numeric literal's suffix must start
4551+
/// there, and `0x1F_kb`'s `F` is a hexadecimal digit, not a letter of the suffix) and otherwise at its first letter
4552+
/// (`"x"sv`, `1.5s` — the reserved suffixes the standard library declares without an underscore).
4553+
fn a_user_defined_literals_suffix(written: &str) -> Option<&str> {
4554+
let written = written.trim_end();
4555+
let run_start = written
4556+
.rfind(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
4557+
.map(|boundary| boundary + 1)
4558+
.unwrap_or(0);
4559+
let run = &written[run_start..];
4560+
if run.is_empty() {
4561+
return None;
4562+
}
4563+
if let Some(underscore) = run.rfind('_') {
4564+
let suffix = &run[underscore..];
4565+
return (suffix.len() > 1).then_some(suffix);
4566+
}
4567+
run.find(|character: char| character.is_ascii_alphabetic())
4568+
.map(|at| &run[at..])
4569+
}
4570+
44894571
/// **The type of a string literal, from its encoding prefix** — see the literal arm of [`type_of_expression_inner`].
44904572
///
44914573
/// `L` is `wchar_t`, `u8` is `char` (the C++20 `char8_t` is deliberately not introduced: a file that is not compiled as
@@ -6527,9 +6609,42 @@ fn finish_a_nested_name(
65276609
}
65286610
asked.push(nested.clone());
65296611

6530-
let Known::Yes((inner, inner_file)) =
6531-
member_fact(index, scopes, root, path, class, &nested, None)
6532-
else {
6612+
// **A nested name whose head is another class.** `std::shared_ptr`'s `element_type` is
6613+
// `typename __shared_ptr<_Tp>::element_type`: the alias is the **base's**, and the head of the spelling names the
6614+
// base. Asking the outer class for a member spelled `__shared_ptr<Resource>::element_type` finds nothing, and the
6615+
// walk stopped right there — measured on `test_cpp`'s `smart_pointers.cpp`, where `locked->identifier()` answered
6616+
// "`shared_ptr<Resource>` has no member `identifier`" for a `shared_ptr<Resource>` that has one.
6617+
//
6618+
// The step is the same question [`the_pointee_of_a_handle`] asks, so it is the same `member_fact` call: the head
6619+
// resolved in the enclosing scopes (a base name is not a member, so `resolve_aliases` is the reader that knows how
6620+
// it is written) and the tail looked up in it, with the head's own arguments as the pairing.
6621+
let found = match member_fact(index, scopes, root, path, class, &nested, None) {
6622+
Known::Yes(found) => Known::Yes(found),
6623+
miss => match the_head_and_the_member_of(&nested) {
6624+
Some((head, tail)) => {
6625+
let head = resolve_aliases(index, scopes, root, path, head).to_string();
6626+
let arguments: Vec<String> = parse_type_spelling(&head)
6627+
.arguments()
6628+
.iter()
6629+
.map(|argument| argument.to_string())
6630+
.collect();
6631+
match member_fact(
6632+
index,
6633+
scopes,
6634+
root,
6635+
path,
6636+
&head,
6637+
tail,
6638+
(!arguments.is_empty()).then_some(&arguments),
6639+
) {
6640+
Known::Yes(found) => Known::Yes(found),
6641+
_ => miss,
6642+
}
6643+
}
6644+
None => miss,
6645+
},
6646+
};
6647+
let Known::Yes((inner, inner_file)) = found else {
65336648
break;
65346649
};
65356650
let Some(inner_type) = inner.type_of.as_deref() else {
@@ -6544,6 +6659,34 @@ fn finish_a_nested_name(
65446659
(current, current_file)
65456660
}
65466661

6662+
/// **Split `A<B>::C` into its head and its last member** — `("A<B>", "C")` — at the last `::` outside angle brackets.
6663+
///
6664+
/// `None` when there is no `::` to split at, or when either half would be empty. The head keeps its arguments: a base
6665+
/// written `__shared_ptr<_Tp>` is looked up by the name `__shared_ptr` and substituted by `_Tp`'s argument, and the two
6666+
/// halves are what the caller passes on.
6667+
fn the_head_and_the_member_of(nested: &str) -> Option<(&str, &str)> {
6668+
let mut depth = 0usize;
6669+
let mut boundary = None;
6670+
let bytes = nested.as_bytes();
6671+
let mut at = 0usize;
6672+
while at + 1 < bytes.len() {
6673+
match bytes[at] {
6674+
b'<' => depth += 1,
6675+
b'>' => depth = depth.saturating_sub(1),
6676+
b':' if depth == 0 && bytes[at + 1] == b':' => {
6677+
boundary = Some(at);
6678+
at += 1;
6679+
}
6680+
_ => {}
6681+
}
6682+
at += 1;
6683+
}
6684+
let boundary = boundary?;
6685+
let head = nested[..boundary].trim();
6686+
let tail = nested[boundary + 2..].trim();
6687+
(!head.is_empty() && !tail.is_empty()).then_some((head, tail))
6688+
}
6689+
65476690
/// **A declaration's type finished when it is an alias template applied to arguments.**
65486691
///
65496692
/// `enable_if_t<__is_same(int, int), double> when_the_same;` records the *spelling*, and what it stands for is
@@ -8907,8 +9050,17 @@ pub(crate) fn qualified_from_the_index(
89079050
if class.contains("::") {
89089051
return None;
89099052
}
9053+
// **A *type* called that, not the first thing called that.** `files_declaring` is a name lookup, and a class's
9054+
// name is also its constructors': `std::shared_ptr` has a dozen facts named `shared_ptr` whose scope is
9055+
// `std::shared_ptr` itself — qualifying from one of those gives `std::shared_ptr::shared_ptr`, a class nothing
9056+
// declares, and every member query after it answers nothing. Measured: this function is what turned
9057+
// `shared_ptr<Resource>` into a class with **0 members** while `std::shared_ptr<Resource>` answered **39**, and
9058+
// the hover on `locked->identifier()` said "has no member" because of it. The question here is a *class* spelling,
9059+
// so the declaration has to be the class.
89109060
let declared = index.files_declaring(class, from);
8911-
let found = declared.into_iter().next()?;
9061+
let found = declared
9062+
.into_iter()
9063+
.find(|declared| declared.fact.kind == crate::DeclKind::Type)?;
89129064
let scope = found.fact.scope.as_deref()?;
89139065
(!scope.is_empty()).then(|| format!("{scope}::{class}"))
89149066
}
@@ -20826,7 +20978,19 @@ pub fn substituted_members(
2082620978
alias_targets.push(target);
2082720979
}
2082820980

20829-
for member in &mut list.members {
20981+
// **An alias's own target is not an alias to expand.** `std::shared_ptr`'s `element_type` is written
20982+
// `using element_type = typename __shared_ptr<_Tp>::element_type;`, so the target contains its own name and
20983+
// replacing that name with the target doubles the prefix —
20984+
// `typename __shared_ptr<Resource>::typename __shared_ptr<Resource>::element_type`, measured. The member's own
20985+
// `type_of` *is* the target, so the expansion is a step for the other members only.
20986+
let declares_an_alias = |member: &ProjectMember| {
20987+
member.fact.kind == crate::DeclKind::Type && alias_names.contains(&member.fact.name)
20988+
};
20989+
for member in list
20990+
.members
20991+
.iter_mut()
20992+
.filter(|member| !declares_an_alias(member))
20993+
{
2083020994
for spelling in [
2083120995
&mut member.fact.parameter_list,
2083220996
&mut member.fact.returns,
@@ -20842,6 +21006,17 @@ pub fn substituted_members(
2084221006
&alias_targets,
2084321007
);
2084421008
}
21009+
}
21010+
}
21011+
for member in &mut list.members {
21012+
for spelling in [
21013+
&mut member.fact.parameter_list,
21014+
&mut member.fact.returns,
21015+
&mut member.fact.type_of,
21016+
]
21017+
.into_iter()
21018+
.flatten()
21019+
{
2084521020
*spelling = crate::sema::types::substituted_spelling(spelling, &names, &arguments);
2084621021
}
2084721022
}

‎crates/cpp_code_analysis/src/sema/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub mod model;
2222
pub mod module_info;
2323
pub mod modules;
2424
pub mod parser_symbols;
25+
pub mod render;
2526
pub mod resolve;
2627
pub mod scopes;
2728
pub mod symbol;

0 commit comments

Comments
 (0)