Skip to content

Commit 114b8c7

Browse files
committed
semantic: a constructor written with a specifier is a member, with its parameters
§30 made `missing-return` silent by asking the parser; the constructor still had no **member**: `declared_name` read names along the declarator path, and `explicit A(int x) : x_(x) {}` keeps its name in the specifier sequence, so the walker bound the parameter and never the function. Measured before: `inspect facts` listed `2:20 x` (the parameter) with no function above it, and `4:5 A` — the plain constructor — while the decorated one was absent, so `A::` offered one of the class's two constructors. After: `2:14 A function in A parameters (int x) modifiers 0x100`, and `members_of("A")` lists both. Three parts, the last two only visible after the first: - `declared_name` asks `CppDeclaration::get_name` when the declarator names nothing — the arm §30 added, now the answer for the *binding* too. - the binding is `BindingKind::Constructor`, not `Function`: the fact's `parameter_list` read is keyed on the kind, and `Function` produced a fact that disagreed with its own declaration about what it was. - `declared_parameters_with` finds a list only when a declarator *names* the binding, which this declarator never does; `fact_for` now falls back to the declaration's own `ParameterList`. Without it the row was `A` with no parameters, which a completion row and a signature help both read as `A()`. Test: `semantic::a_constructor_written_with_a_specifier_is_a_member` (two constructors, the decorated one explicit, scope `A`, `parameter_list == "(int x)"`, the destructor beside them). `docs/buglist.md` §30.1 and `docs/next.md` §5 record it.
1 parent 8eeb6a8 commit 114b8c7

5 files changed

Lines changed: 182 additions & 16 deletions

File tree

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3453,6 +3453,28 @@ fn fact_for(
34533453
| BindingKind::LiteralOperator => declared_parameters_with(shapes, binding),
34543454
_ => None,
34553455
};
3456+
// **A name no declarator holds** — a constructor written with a specifier (`explicit A(int x)`) keeps its name in
3457+
// the specifier sequence, so `names_the_binding` is false for its declarator and the list was lost: measured, the
3458+
// fact came out as `A` with an empty `parameter_list`, which a completion row and a signature help both read as a
3459+
// constructor that takes nothing. The declaration is found from the binding's own range, and its `ParameterList` is
3460+
// the one written there.
3461+
let parameter_list = parameter_list.or_else(|| {
3462+
if !matches!(
3463+
binding.kind,
3464+
BindingKind::Constructor | BindingKind::Destructor | BindingKind::ConversionFunction
3465+
) {
3466+
return None;
3467+
}
3468+
use cpp_parser::CppAstNode;
3469+
let token = cpp_parser::token_at(root, binding.range.start_offset)?;
3470+
let parent = token.parent()?;
3471+
let declaration = std::iter::once(parent.clone())
3472+
.chain(parent.ancestors())
3473+
.find(|node| cpp_parser::CppDeclaration::can_cast(node.kind().into()))?;
3474+
let declaration = cpp_parser::CppDeclaration::cast(declaration)?;
3475+
let list = declaration.get_param_list()?;
3476+
Some(list.syntax().text().to_string())
3477+
});
34563478

34573479
// **Where a local sits, for the names it writes.** A declaration inside a body has no qualified name of
34583480
// its own — see [`DeclFact::local`] — so the namespaces around it are the only place a type it writes can

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

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@
3030
//! binding that cannot be placed is dropped, and the resulting gap is visible to a consumer — which is better
3131
//! than a binding in the wrong scope, and much better than a panic in an editor.
3232
33-
use cpp_parser::{CppAstNode, CppSyntaxKind, CppSyntaxNode, CppTokenKind, MacroBodies};
33+
use cpp_parser::{
34+
CppAstNode, CppAstToken, CppSyntaxKind, CppSyntaxNode, CppTokenKind, MacroBodies,
35+
};
3436

3537
use crate::summary::MacroScopeReading;
3638

@@ -1462,6 +1464,37 @@ impl ScopeWalker<'_> {
14621464
}
14631465
}
14641466

1467+
// **A function whose name the specifier sequence holds** — `explicit A(int x) : x_(x) {}` is the shape:
1468+
// the declarator is `(int x)` and names nothing, so the loop above bound the parameters and never the
1469+
// function. `CppDeclaration::get_name` reads the name (`305a927` added the arm), and this is the binding that
1470+
// makes it a **fact**: measured on `struct A { explicit A(int x) : x_(x) {} A() {} int f(); }`, `inspect facts`
1471+
// listed `A` at 4:5 and nothing at 2:5, so `A::` offered one of the class's two constructors and a hover on the
1472+
// decorated one answered nothing — the decorator was invisible in the member list while `A()` was there.
1473+
//
1474+
// Guarded by "no declarator names anything", which is what keeps every ordinary function away from this: its
1475+
// declarator holds the name, so the loop already bound it.
1476+
if declarators(node)
1477+
.iter()
1478+
.all(|declarator| declared_name(declarator).is_none())
1479+
&& let Some(declaration) = cpp_parser::CppDeclaration::cast(node.clone())
1480+
&& declaration.get_param_list().is_some()
1481+
&& let Some(token) = declaration.get_name()
1482+
{
1483+
let text = token.get_name_text().to_string();
1484+
if let Some(name) = name_from_text(&text, node) {
1485+
// **The kind is the one the declaration is**, not `Function`: a constructor's `DeclKind` and its
1486+
// `parameter_list` read are both decided by this, and `Function` made the fact say `A` with no
1487+
// parameters — the fact existed and disagreed with its own declaration about what it was.
1488+
self.bind(
1489+
inner,
1490+
name,
1491+
BindingKind::Constructor,
1492+
node,
1493+
cpp_parser::source_range(token.get_range()),
1494+
);
1495+
}
1496+
}
1497+
14651498
// The body of a function, which the grammar puts beside the declarator rather than inside it. Walking
14661499
// it into the scope the declarator opened is what makes a local variable local.
14671500
// **A lambda written in a declarator's own subtree.** `declarator_as` reads a declarator for its name
@@ -2815,6 +2848,28 @@ fn declared_name(node: &CppSyntaxNode) -> Option<(Name, cpp_parser::SourceRange)
28152848
}
28162849
}
28172850

2851+
// **A name the declarator does not hold** — a constructor written with a specifier (`explicit A(int x)`) or a
2852+
// destructor (`virtual ~A()`), where the parser keeps the name in the specifier sequence and the declarator is
2853+
// only `(int x)`.
2854+
//
2855+
// [`cpp_parser::CppDeclaration::get_name`] is the reader that knows the arm; asking it here is what makes the
2856+
// **fact** exist, not just the `missing-return` rule that already asks it. Measured before this arm on
2857+
// `struct A { explicit A(int x) : x_(x) {} virtual ~A() {} A() {} }`: the parameter `x` was a fact and the
2858+
// decorated constructor was not, so `A::` offered one of its two constructors and a hover on the declaration
2859+
// answered nothing. The decorator was invisible in the member list while `A()` was there — a difference no reader
2860+
// of the class can explain.
2861+
//
2862+
// Asked **last**, so every declaration whose declarator names it is unchanged, and only for a declaration: a
2863+
// declarator and a parameter reach this function too.
2864+
if let Some(declaration) = cpp_parser::CppDeclaration::cast(node.clone())
2865+
&& let Some(token) = declaration.get_name()
2866+
{
2867+
let text = token.get_name_text().to_string();
2868+
if let Some(name) = name_from_text(&text, node) {
2869+
return Some((name, cpp_parser::source_range(token.get_range())));
2870+
}
2871+
}
2872+
28182873
// A node that names something with a direct token has no `NameExpr` to walk: an enumerator is
28192874
// `EnumeratorDecl["Red"]` and a label is `LabelStat["done" ":"]`. Neither can hold an initializer, so the
28202875
// token is unambiguous here in a way it would not be further down the tree.

‎crates/cpp_code_analysis/tests/semantic.rs‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
//! in the C++ tree at all). Each of them is pinned here, and so is the refusal: a name this analysis cannot place
66
//! gets **no** classification rather than a plausible one.
77
8-
use cpp_code_analysis::Known;
98
use cpp_code_analysis::semantic::{Name, NameKind, Provenance};
109
use cpp_code_analysis::{
1110
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
1211
};
12+
use cpp_code_analysis::{DeclKind, DeclModifiers, Known};
1313

1414
fn session_with(files: &[(&str, &str)]) -> Session<MemoryFiles> {
1515
let mut memory = MemoryFiles::new();
@@ -2136,3 +2136,65 @@ class Following { public: void h(); };
21362136
"the class after the member is a class of the namespace, not of `Impl`"
21372137
);
21382138
}
2139+
2140+
/// **A constructor written with a specifier is a member too** — `explicit A(int x)` keeps its name in the specifier
2141+
/// sequence and its declarator holds only `(int x)`, so the binding path that reads declarators found the parameters
2142+
/// and never the function.
2143+
///
2144+
/// Measured before the fix, on this fixture: `inspect facts` listed `A` at 4:5 (the `A() {}`) and nothing at 2:5, so
2145+
/// `A::` offered one of the class's two constructors and a hover on the decorated declaration answered the *class*
2146+
/// instead of the constructor. After it: `2:14 A function in A modifiers 0x100` (0x100 is `explicit`), beside the
2147+
/// destructor and `A()`.
2148+
#[test]
2149+
fn a_constructor_written_with_a_specifier_is_a_member() {
2150+
let session = session_with(&[(
2151+
"/p/a.cpp",
2152+
"\
2153+
struct A {
2154+
explicit A(int x) : x_(x) {}
2155+
virtual ~A() {}
2156+
A() {}
2157+
int f();
2158+
int x_;
2159+
};
2160+
",
2161+
)]);
2162+
let summary = session
2163+
.index()
2164+
.summary(std::path::Path::new("/p/a.cpp"))
2165+
.expect("the file's summary");
2166+
let constructors: Vec<_> = summary
2167+
.declarations
2168+
.iter()
2169+
.filter(|fact| fact.name == "A" && fact.kind == DeclKind::Function)
2170+
.collect();
2171+
assert_eq!(
2172+
constructors.len(),
2173+
2,
2174+
"both constructors are members: {:?}",
2175+
summary.declarations
2176+
);
2177+
let decorated = constructors
2178+
.iter()
2179+
.find(|fact| fact.modifiers.contains(DeclModifiers::EXPLICIT))
2180+
.expect("the decorated one says it is explicit");
2181+
assert_eq!(
2182+
decorated.scope.as_deref(),
2183+
Some("A"),
2184+
"it is a member of its class"
2185+
);
2186+
assert_eq!(
2187+
decorated.parameter_list.as_deref(),
2188+
Some("(int x)"),
2189+
"**and its parameters**, which the declarator does not hold either: without the fallback the fact read as a \
2190+
constructor that takes nothing, which a completion row and a signature help both believe"
2191+
);
2192+
assert!(
2193+
summary
2194+
.declarations
2195+
.iter()
2196+
.any(|fact| fact.kind == DeclKind::Function && fact.name == "~A"),
2197+
"and the destructor is beside it: {:?}",
2198+
summary.declarations
2199+
);
2200+
}

‎docs/buglist.md‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -798,6 +798,40 @@ has **no fact**: in the fixture the parameter is bound (`2:20 x`) and the constr
798798
completion after `A::` therefore do not show it. `docs/next.md` §5 is the item; the guard that keeps the change safe is
799799
that a call statement (`A(1);`) has no specifier sequence at all.
800800

801+
## 30.1 The constructor's **fact**, not just its diagnostic — fixed
802+
803+
§30 made `missing-return` silent for a decorated constructor by asking the parser
804+
(`CppDeclaration::promises_no_return`). The constructor still had no **member**: `declared_name` read names along the
805+
declarator path, and `explicit A(int x) : x_(x) {}` keeps its name in the specifier sequence, so the scope walker bound
806+
the parameter `x` and never the function.
807+
808+
Measured before (`inspect facts` on `struct A { explicit A(int x) : x_(x) {} virtual ~A() {} A() {} int f(); int x_; };`):
809+
810+
```text
811+
1:8 A type
812+
2:20 x variable type `int` the parameter, with no function above it
813+
3:14 ~A function in A
814+
4:5 A function in A the plain constructor
815+
5:9 f function in A returns `int`
816+
6:9 x_ variable in A type `int`
817+
```
818+
819+
After: `2:14 A function in A parameters (int x) modifiers 0x100`, beside the two it already had, and `members_of("A")`
820+
lists both constructors.
821+
822+
Three parts, and the second and third were only visible after the first:
823+
824+
1. `declared_name` asks `CppDeclaration::get_name` when the declarator names nothing — the same arm §30 added, now also
825+
the answer for the *binding*.
826+
2. The binding's kind is `BindingKind::Constructor`, not `Function`: the fact's `parameter_list` read is keyed on it,
827+
and `Function` produced a fact that disagreed with its own declaration about what it was.
828+
3. `declared_parameters_with` finds a list only when a declarator *names* the binding, which a decorated constructor's
829+
declarator never does. `fact_for` now falls back to the declaration's own `ParameterList` — measured: without it the
830+
row was `A` with no parameters, which a completion and a signature help both read as `A()`.
831+
832+
Test: `semantic::a_constructor_written_with_a_specifier_is_a_member` — two constructors, the decorated one explicit,
833+
scope `A`, `parameter_list == "(int x)"`, and the destructor beside them.
834+
801835
## 31. The parser derails on `bits/shared_ptr_base.h` — and that is what "`shared_ptr` again" has been
802836

803837
Found while measuring the smart pointer's members after `50cf209`. It is not a `sema` bug and not a member-list bug:

‎docs/next.md‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,22 +139,15 @@ the cooked reading is stored and served: 48 → 12.8 ms a file):
139139

140140
---
141141

142-
## 5. The decorated constructor's missing fact
142+
## 5. The decorated constructor's fact — **done**
143143

144-
`docs/buglist.md` §30 fixed the diagnostics by asking the declaration's **name** (`promises_no_return`), and taught
145-
`CppDeclaration::get_name` where `explicit A(int x)` keeps its name. The **scope walker** still uses its own reader
146-
(`declared_name`), so a decorated constructor has **no fact**: the parameter beside it is bound (`2:20 x` in the
147-
fixture), the constructor itself is not. Consequences: member lists do not offer it, completion after `A::` does not,
148-
and `missing-return`'s fix is the only consumer that sees it.
144+
§30 fixed the diagnostic; this fixed the member. `declared_name` now asks `CppDeclaration::get_name` when the declarator
145+
names nothing, the binding is a `Constructor` rather than a `Function` (the fact's parameter list is keyed on the kind),
146+
and `fact_for` falls back to the declaration's own `ParameterList` when no declarator names the binding.
149147

150-
* **5.1** `declared_name` should ask the same reader — or `get_name`'s new arm should be reachable from it — with the
151-
`is_unnamed_declaration` guard checked against call statements (`A(1);` has no specifier sequence, which is what keeps
152-
the fallback safe).
153-
* **5.2** Then a member list includes the decorated constructors, and `signature_help` offers them at a construction.
154-
155-
**What settles it:** `inspect facts` listing the constructor, and a completion test after `A(` offering it.
156-
157-
---
148+
Measured: `2:14 A function in A parameters (int x) modifiers 0x100` beside `4:5 A` and `3:14 ~A`, and
149+
`members_of("A")` lists both constructors. Test: `semantic::a_constructor_written_with_a_specifier_is_a_member`.
150+
The numbers are in `docs/buglist.md` §30.1.
158151

159152
## 6. The hover rendering's small gaps (each self-contained)
160153

0 commit comments

Comments
 (0)