Skip to content

Commit 2d7d09a

Browse files
committed
sema: a qualified *type* is not a qualified declaration, and a hover shows the overloads a call can reach
**The bogus declaration behind the `string`-as-a-method report.** Worked back from the two screenshots: the semantic tokens coloured `string` in `std::map<std::string, std::string, std::less<>> &keyValues` as a `method`, and its hover read ``std::vector<std:: string()``, declared in `FormatContext.h:58:42` — the `string` token of the return type's template argument. Both come from one fact, and `inspect facts` named it: ```text 58:42 string function in std returns `void` parameters `()` 58:51 GetIgnorePattern function in FormatContext returns `std::vector<std::string> &` ``` `qualified_declarations` was reading it as an **out-of-class definition**: `void C::f()` writes the name in the *specifier*, so a declaration whose declarator holds no name takes the last qualified name from the specifiers. It asked `declarator.child::<CppDeclarator>()` — the **first nested** declarator — and for `&f()` that is the `&` wrapper, which holds no name; so the specifiers were consulted, `std::string &f();` declared a function called `string` in namespace `std`, and `std::vector<int> &f();` one called `vector<int>`. The declarator's **own** name is the reader that answers for every spelling (a direct token for `&f()`, a direct `NameExpr` for `C::f`), and it is what decides now. `inspect facts` on the fixtures shows the bogus facts gone, `void C::f() {}` still files `f in C`, and the header keeps only its real declarations. Fix measured back through the tool on the real project: `hover` on that `string` answers "none" rather than the invented function, and there is no `string` function fact left in the file's summary. **A hover on a call prints the declarations that call can reach.** Reported from the same session: hovering `append` in `result_str.append(x)` drew all nine `basic_string::append` declarations. Two cannot accept one argument at all (`append(const _StringViewIsh&, size_type, size_type = npos)`), so the card was showing declarations the call cannot mean. The arity rule was there and too permissive: `Candidate::takes` asked only "no more arguments than parameters", on the reasoning that a longer parameter list may have defaults — true, and it made every two- and three-parameter overload viable for a one-argument call. The defaulted count is not in the type spellings a candidate holds, but it **is** in the declaration's `parameter_list` spelling, which the hover has: `overload::defaults_in` counts it, `Candidate::with_required` records the required count, and `takes` now asks both ends. With that, the viable set is the answer. New `Session::the_declarations_a_call_means` returns one index when the resolution decides and the whole viable set when it does not (it shares `the_candidates_of_a_call` with the older single-answer question), and both hover paths print exactly those: * **one** → that declaration's own card — for a member, with its details and location, as a member that is not overloaded gets; for a free function, the single line with `→`; * **several** → only those, with a sentence that says they fit the call and that the types do not decide between them; * **not on a call** → the old list, which is the honest answer for a name the cursor is merely on. Tested: `a_hover_on_a_call_shows_only_the_declarations_it_can_reach` (a chosen one-parameter overload, and both one-parameter overloads of an unknown argument — with the two-parameter one absent); `overload`'s arity test now pins the required count (`with_required(0)` reaches a zero-argument call, without it the call reaches nothing); the whole `cpp_ls` suite (including the member-overload `reported_hover` tests) and `cpp_code_analysis`'s.
1 parent f0ceb98 commit 2d7d09a

5 files changed

Lines changed: 360 additions & 70 deletions

File tree

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

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4239,15 +4239,20 @@ fn qualified_declarations(root: &CppSyntaxNode) -> Vec<(Binding, String, Option<
42394239
else {
42404240
continue;
42414241
};
4242-
// **`void C::f()` writes the name as part of the type**, so the declarator is `()` and holds no name; a definition written
4243-
// with the name in the declarator (`int C::count = 0`) has one. The outermost declarator's own name is what tells the
4244-
// two apart, and a *parameter's* name is not it.
4245-
let outer = declarator
4246-
.child::<CppDeclarator>()
4247-
.unwrap_or_else(|| declarator.clone());
4248-
let own_name = outer.child::<CppNameExpr>();
4249-
let names_itself = own_name.is_some();
4250-
let from_the_declarator = own_name.filter(|name| name.is_qualified());
4242+
// **`void C::f()` writes the name as part of the type**, so the declarator is `()` and holds no name; a definition
4243+
// written with the name in the declarator (`int C::count = 0`) has one.
4244+
//
4245+
// **The declarator's *own* name decides it**, and `get_name` is the reader that answers for every spelling: a direct
4246+
// token (`&f()` holds `f` as a token), a direct `NameExpr` (`C::count`), and the nested wrappers in between. Taking
4247+
// `child::<CppDeclarator>()` instead — the *first nested* declarator — looked at the `&` wrapper of `&f()`, which
4248+
// holds no name, so the fallback below consulted the **specifiers**, and `std::string &f();` declared a function
4249+
// called `string` in namespace `std` (`std::vector<int> &f();` one called `vector<int>`). Measured with
4250+
// `inspect facts`; that bogus fact is what a hover on the return type's `string` showed, and what the semantic tokens
4251+
// called a method.
4252+
let names_itself = declarator.get_name().is_some();
4253+
let from_the_declarator = declarator
4254+
.child::<CppNameExpr>()
4255+
.filter(CppNameExpr::is_qualified);
42514256
let from_the_specifiers = (!names_itself)
42524257
.then(|| {
42534258
declaration.get_decl_specifiers().and_then(|specifiers| {

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

Lines changed: 89 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,17 @@ pub(crate) struct Candidate {
7373
pub(crate) declared: Vec<String>,
7474
/// The template's parameter names, for deducing one declaration's spellings from another's.
7575
pub(crate) template_parameters: Vec<String>,
76+
/// **How many parameters a call must supply** — the ones without a default argument. Equal to
77+
/// `parameters.len()` until a caller says otherwise, because the defaulted count is not in the type
78+
/// spellings this candidate is built from.
79+
pub(crate) required: usize,
7680
}
7781

7882
impl Candidate {
7983
/// The candidate an ordinary declaration writes: `void f(int, ...)` as `["int"]` and `variadic`.
8084
pub(crate) fn new(parameters: Vec<String>, variadic: bool, signature: String) -> Self {
8185
Self {
86+
required: parameters.len(),
8287
parameters,
8388
variadic,
8489
signature,
@@ -88,6 +93,14 @@ impl Candidate {
8893
}
8994
}
9095

96+
/// **The same candidate, with the parameters a call must supply.** A caller that has the declaration's
97+
/// *spelling* can count the defaulted parameters — see [`defaults_in`] — and a defaulted tail is exactly what
98+
/// makes a two-parameter overload reachable from a one-argument call.
99+
pub(crate) fn with_required(mut self, required: usize) -> Self {
100+
self.required = required.min(self.parameters.len());
101+
self
102+
}
103+
91104
/// **The same candidate, marked as a template** — the one difference a tie is broken on.
92105
pub(crate) fn into_a_template(mut self) -> Self {
93106
self.is_a_template = true;
@@ -114,7 +127,10 @@ impl Candidate {
114127
/// this reads. Treating them as "no" would delete the overload a program chose — `void f(int, int = 0);` is a
115128
/// real candidate for `f(1)`.
116129
fn takes(&self, arguments: usize) -> bool {
117-
self.variadic || arguments <= self.parameters.len()
130+
// **A default argument is a parameter the call may leave off, and the spelling says which ones.** Without the
131+
// count, `append(const _StringViewIsh&, size_type, size_type = npos)` was "viable" for `append(x)` and every
132+
// two- and three-parameter overload survived an arity filter it should not have.
133+
self.variadic || (arguments >= self.required && arguments <= self.parameters.len())
118134
}
119135
}
120136

@@ -133,8 +149,13 @@ pub(crate) enum Choice {
133149
///
134150
/// The arguments are the types the engine already worked out, in source order; `Known::Unknown` is an argument whose
135151
/// type is not known and is handled by [`Match::Unranked`].
136-
pub(crate) fn choose(argument_types: &[Known<String>], candidates: &[Candidate]) -> Choice {
137-
let viable: Vec<usize> = (0..candidates.len())
152+
/// **The declarations a call can reach** — the candidates whose parameter list the arguments fit, in declaration
153+
/// order. The set [`choose`] ranks; a caller that shows a hover wants exactly these when nothing decides between them.
154+
pub(crate) fn viable_candidates(
155+
argument_types: &[Known<String>],
156+
candidates: &[Candidate],
157+
) -> Vec<usize> {
158+
(0..candidates.len())
138159
.filter(|index| candidates[*index].takes(argument_types.len()))
139160
.filter(|index| {
140161
let candidate = &candidates[*index];
@@ -146,7 +167,11 @@ pub(crate) fn choose(argument_types: &[Known<String>], candidates: &[Candidate])
146167
}
147168
})
148169
})
149-
.collect();
170+
.collect()
171+
}
172+
173+
pub(crate) fn choose(argument_types: &[Known<String>], candidates: &[Candidate]) -> Choice {
174+
let viable = viable_candidates(argument_types, candidates);
150175

151176
if viable.is_empty() {
152177
return Choice::None;
@@ -379,9 +404,15 @@ mod tests {
379404
choose(&[a_type("int"), a_type("int")], &candidates),
380405
Choice::One(1)
381406
);
382-
// Both need a default argument for a zero-argument call, so both are viable and the one using fewer defaults
383-
// wins — see `choose`. "None" would be a claim about the program that is not true.
384-
assert_eq!(choose(&[], &candidates), Choice::One(0));
407+
// **A defaulted parameter may be left off, and only the caller knows which ones are.** `with_required` is that
408+
// count: `f(int a = 0)` is `required 0` and reaches a zero-argument call; a candidate that does not say needs all
409+
// of its parameters, so this call reaches neither.
410+
let with_a_default = vec![
411+
candidate(&["int"]).with_required(0),
412+
candidate(&["int", "int"]),
413+
];
414+
assert_eq!(choose(&[], &with_a_default), Choice::One(0));
415+
assert_eq!(choose(&[], &candidates), Choice::None);
385416
}
386417

387418
#[test]
@@ -502,6 +533,57 @@ pub(crate) fn a_type_without_its_name(parameter: &str) -> String {
502533
parameter.to_string()
503534
}
504535

536+
/// **How many parameters of a `parameter_list` spelling have a default argument** — the arguments a call may leave
537+
/// off.
538+
///
539+
/// Counted at the spelling level, at the same top-level commas [`parameters_in`] splits on, because a default value
540+
/// carries commas of its own: `void f(std::map<int, int> m = {})` has one defaulted parameter, not two parameters.
541+
pub fn defaults_in(parameter_list: &str) -> usize {
542+
let inner = parameter_list
543+
.trim()
544+
.trim_start_matches('(')
545+
.trim_end_matches(')');
546+
let mut defaults = 0usize;
547+
let mut depth = 0i32;
548+
let mut current = String::new();
549+
let count = |parameter: &str, defaults: &mut usize| {
550+
let outside = {
551+
let mut without = String::new();
552+
let mut depth = 0i32;
553+
for character in parameter.trim().chars() {
554+
match character {
555+
'<' | '(' | '[' => depth += 1,
556+
'>' | ')' | ']' => depth -= 1,
557+
_ if depth > 0 => continue,
558+
_ => {}
559+
}
560+
without.push(character);
561+
}
562+
without
563+
};
564+
if outside.contains('=') {
565+
*defaults += 1;
566+
}
567+
};
568+
for character in inner.chars() {
569+
match character {
570+
'<' | '(' | '[' => depth += 1,
571+
'>' | ')' | ']' => depth -= 1,
572+
',' if depth == 0 => {
573+
count(&current, &mut defaults);
574+
current.clear();
575+
continue;
576+
}
577+
_ => {}
578+
}
579+
current.push(character);
580+
}
581+
if !current.trim().is_empty() && current.trim() != "..." {
582+
count(&current, &mut defaults);
583+
}
584+
defaults
585+
}
586+
505587
/// **The parameter types in a `parameter_list` spelling**, and whether it ends in `...`.
506588
///
507589
/// `(int a, const char* b = 0)` is `["int", "const char*"]`; `(Args&&... args)` is `([], true)`. The split is at a

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

Lines changed: 54 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8696,21 +8696,67 @@ impl<F: FileProvider + Clone> Session<F> {
86968696
signatures
86978697
}
86988698

8699-
/// **Which of these declarations a call at this offset means** — an index into `parameter_lists`.
8699+
/// **The declarations a call at this offset can reach** — indices into `parameter_lists`.
87008700
///
8701-
/// The same resolution the argument checks and the signature popup use, asked over the
8702-
/// declarations a caller already holds: a hover has the facts of the name under the cursor and
8703-
/// needs to know which of them the call selects.
8701+
/// The same resolution the argument checks and the signature popup use, asked over the declarations a caller already
8702+
/// holds: a hover has the facts of the name under the cursor and needs to know which of them the call can mean.
87048703
///
8705-
/// `None` when the offset is not on a call, when no candidate is viable, or when the choice is ambiguous — the three
8706-
/// answers a reader should see nothing marked for.
8704+
/// ```text
8705+
/// one index the resolution decided (`Choice::One`)
8706+
/// several every one of them can accept the arguments, and nothing decides between them by type
8707+
/// None the offset is not on a call, or no declaration can accept it
8708+
/// ```
8709+
///
8710+
/// The **several** case is the one a hover needs: printing the chosen declaration beside five others that cannot take
8711+
/// this argument list answers a question the reader did not ask.
8712+
pub fn the_declarations_a_call_means(
8713+
&self,
8714+
view: &FileView,
8715+
offset: ReadingOffset,
8716+
parameter_lists: &[Option<String>],
8717+
template_parameters: &[Vec<String>],
8718+
) -> Option<Vec<usize>> {
8719+
let (types, candidates) =
8720+
self.the_candidates_of_a_call(view, offset, parameter_lists, template_parameters)?;
8721+
match crate::sema::overload::choose(&types, &candidates) {
8722+
crate::sema::overload::Choice::One(chosen) => Some(vec![chosen]),
8723+
// **Nothing decides between them**, so the viable set is the answer: every one of them can accept this call,
8724+
// and the ones arity alone rules out are gone.
8725+
crate::sema::overload::Choice::Ambiguous => Some(
8726+
crate::sema::overload::viable_candidates(&types, &candidates),
8727+
),
8728+
crate::sema::overload::Choice::None => None,
8729+
}
8730+
}
8731+
8732+
/// **The one declaration a call at this offset means**, when the resolution decides — see
8733+
/// [`Session::the_declarations_a_call_means`] for the answer that also covers the ambiguous case.
87078734
pub fn the_declaration_a_call_means(
87088735
&self,
87098736
view: &FileView,
87108737
offset: ReadingOffset,
87118738
parameter_lists: &[Option<String>],
87128739
template_parameters: &[Vec<String>],
87138740
) -> Option<usize> {
8741+
let (types, candidates) =
8742+
self.the_candidates_of_a_call(view, offset, parameter_lists, template_parameters)?;
8743+
match crate::sema::overload::choose(&types, &candidates) {
8744+
crate::sema::overload::Choice::One(chosen) => Some(chosen),
8745+
_ => None,
8746+
}
8747+
}
8748+
8749+
/// **The declarations and the argument types of the call at `offset`** — the one walk the two questions above share.
8750+
fn the_candidates_of_a_call(
8751+
&self,
8752+
view: &FileView,
8753+
offset: ReadingOffset,
8754+
parameter_lists: &[Option<String>],
8755+
template_parameters: &[Vec<String>],
8756+
) -> Option<(
8757+
Vec<crate::Known<String>>,
8758+
Vec<crate::sema::overload::Candidate>,
8759+
)> {
87148760
let token = cpp_parser::token_at(&view.root, offset.get())?;
87158761
let call = token.parent_ancestors().find(|node| {
87168762
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::CallExpr
@@ -8783,11 +8829,9 @@ impl<F: FileProvider + Clone> Session<F> {
87838829
})
87848830
.collect();
87858831

8786-
match crate::sema::overload::choose(&types, &candidates) {
8787-
crate::sema::overload::Choice::One(chosen) => Some(chosen),
8788-
_ => None,
8789-
}
8832+
Some((types, candidates))
87908833
}
8834+
87918835
/// **The template arguments a call fixes**, for a declaration the caller already holds.
87928836
///
87938837
/// Deduction needs the call's argument types, which is what a `SemanticModel` is for; the names come from the

0 commit comments

Comments
 (0)