Skip to content

Commit c13f01e

Browse files
committed
scopes: a namespace body is not a function body — the parameters of a .cpp's definitions are declared again
Two reports from a reader, both in a body written inside a namespace: ```text archive.cpp void Archive::put(const Entry& entry) { _counts[entry.key] += entry.count; } `entry` is not declared: nothing this file can see names it report.cpp void Report::add(std::string line) { lines.push_back(std::move(line)); } hovering `line` answered std::source_location::line ``` # One rule, one line of the grammar `ScopeWalker::declaration` skips a `::`-qualified declaration nested in a `CompoundStat`, because the most-vexing-parse reading of a *call statement* is exactly that shape (`std::iter_swap(__result, __b);` bound a phantom function in `std`). The test was `ancestors().any(CppCompoundStat)` — and **a namespace's body is a `CompoundStat` too**, so every out-of-class member definition written inside `namespace archive { … }`, the layout of every `.cpp` there is, was dropped whole: no function scope, no parameter bindings, and every name in the body looked up as if it had been written at namespace scope. `line` then found `std::source_location::line`, which is exactly the hover that was reported. The rule is about the *parent* of the compound: a function's body hangs off the declaration, a branch's off the `if`, and a namespace's off the `NamespaceDecl` — a scope, not a body. # The second rule the report exposed With the declaration read again, the qualifier had to be found. `scope_of_a_qualifier` matches the name **as written** against the table's absolute qualified names, so `Archive` inside `namespace report` matched nothing (the class is `report::Archive`) and the definition took the "the class is in a header" path anyway. The lookup now tries the enclosing scopes first and the absolute name second, which is the order the language uses. # Verified on the reported project `tests/reported_parameters.rs` (ignored; skips without the fixture) opens both files and asks the reader's questions: ```text before archive.cpp: "_counts[entry.key]" → Unknown(NotDeclaredHere("entry")) archive.cpp: 7 check(s) UndefinedName: `entry` is not declared: nothing this file can see names it report.cpp: "std::move(line)" → Unknown(NotDeclaredHere("line")) after archive.cpp: "_counts[entry.key]" → entry in archive.cpp report.cpp: "std::move(line)" → line in report.cpp archive.cpp: 0 error(s), 0 check(s) report.cpp: 0 error(s), 0 check(s) ``` `tests/session/tests.rs::a_parameter_of_an_out_of_class_definition_is_declared` is the same shape in memory, so the regression runs without the fixture. # What did *not* reproduce The second image's `param-type-check` — *"this passes `std::move(line)` where `const _Ty&` is declared for `push_back`"* — did not appear in this reading, before the fix or after it (`report.cpp: 0 check(s)` in both). A rule was tried for it (a template parameter is `Unknown` before the relation is asked) and **reverted**, because no test could make it differ from the existing behaviour: the class-case guard already answers `Unknown` for `_Ty`, `T`, `_Tp` and their reference spellings. The hover and the "not declared" errors were the same unresolved-parameter defect and are fixed; if the type check comes back it is a separate report with its own reproduction. `cargo test --workspace`: 146 suites, 0 failures.
1 parent fc169a6 commit c13f01e

3 files changed

Lines changed: 285 additions & 8 deletions

File tree

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

Lines changed: 110 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1329,16 +1329,33 @@ impl ScopeWalker<'_> {
13291329
// arguments and so cannot be told from a return type). One question, asked once, for the three rules below
13301330
// and for [`ScopeWalker::declarator_as`], which reads the same pair.
13311331
let qualified_name = the_qualified_name_of_a_declaration(node);
1332-
// **A statement that looks like one of these declares nothing, and a definition never nests inside a body.**
1333-
// The most-vexing-parse reading of a call with a qualified callee is exactly this shape —
1332+
// **A statement that looks like one of these declares nothing, and a definition never nests inside a
1333+
// *function body*.** The most-vexing-parse reading of a call with a qualified callee is exactly this shape —
13341334
// `std::iter_swap(__result, __b);` is a `Declaration` naming `std::iter_swap` with a parameter list — and
13351335
// inside a body it bound a **function** named `iter_swap` in scope `std`, taking the enclosing function's
13361336
// template parameters with it. Measured on libstdc++: `bits/stl_algo.h` alone had 22 `std::iter_swap` facts at
13371337
// namespace scope, `local: false`, all of them call statements.
1338+
//
1339+
// **A namespace body is a `CompoundStat` too**, and asking only for that kind rejected every out-of-class
1340+
// member definition written inside a namespace — the layout of every `.cpp` there is:
1341+
//
1342+
// ```text
1343+
// namespace archive {
1344+
// void Archive::put(const Entry& entry) { _counts[entry.key] += entry.count; }
1345+
// }
1346+
// ```
1347+
//
1348+
// The whole declaration was dropped: no function scope, no parameter bindings, and `entry` reported as
1349+
// "not declared" in the body it is declared in. What makes a statement a statement is the *parent* of the
1350+
// compound: a function's body hangs off the declaration, a branch's off the `if`, and a namespace's off the
1351+
// `NamespaceDecl` — which is a scope, not a body, so it is allowed through here.
13381352
if qualified_name.is_some()
1339-
&& node
1340-
.ancestors()
1341-
.any(|ancestor| cpp_parser::CppCompoundStat::can_cast(ancestor.kind().into()))
1353+
&& node.ancestors().any(|ancestor| {
1354+
ancestor.parent().is_some_and(|parent| {
1355+
cpp_parser::CppCompoundStat::can_cast(ancestor.kind().into())
1356+
&& !cpp_parser::CppNamespaceDecl::can_cast(parent.kind().into())
1357+
})
1358+
})
13421359
{
13431360
return;
13441361
}
@@ -1364,7 +1381,7 @@ impl ScopeWalker<'_> {
13641381
.is_some_and(|parent| cpp_parser::CppFriendDecl::can_cast(parent.kind().into()));
13651382

13661383
if let Some((qualifier, _)) = &qualified_name
1367-
&& self.scope_of_a_qualifier(qualifier).is_none()
1384+
&& self.scope_of_the_qualifier(qualifier, outer).is_none()
13681385
{
13691386
// **The name is not this file's — the body is.** `size_t LuaSource::GetLine(size_t offset) const
13701387
// { … }` declares nothing at file scope: the class is in a header this file only includes. That
@@ -1715,6 +1732,90 @@ impl ScopeWalker<'_> {
17151732

17161733
found
17171734
}
1735+
1736+
/// **A qualifier read the way C++ reads it: from the scope it was written in, then from the file.**
1737+
///
1738+
/// `scope_of_a_qualifier` matches the name as written against the qualified names the table records, which are
1739+
/// absolute. A definition inside a namespace writes only the part that is relative to it —
1740+
///
1741+
/// ```text
1742+
/// namespace report {
1743+
/// class Archive { void put(const Entry& entry); };
1744+
/// void Archive::put(const Entry& entry) { … }
1745+
/// }
1746+
/// ```
1747+
///
1748+
/// — so `Archive` matched nothing while the class's qualified name is `report::Archive`, and that one miss sent a
1749+
/// **same-file** definition down the "the class is in a header" path, where it bound nothing and opened no function
1750+
/// scope: reported from a reader as `entry` and `line` "not declared" in their own bodies.
1751+
///
1752+
/// The order is the language's: the qualifier is looked up in the enclosing scope first (which is what makes a name
1753+
/// inside a namespace find that namespace's class), and only then as an absolute name. Namespaces, classes and the
1754+
/// translation unit only — a function scope contributes no prefix, because its name is not part of any qualified
1755+
/// name.
1756+
fn scope_of_the_qualifier(&self, qualifier: &str, from: ScopeId) -> Option<ScopeId> {
1757+
let mut ancestor = Some(from);
1758+
let mut seen = std::collections::HashSet::new();
1759+
while let Some(scope) = ancestor {
1760+
if !seen.insert(scope) {
1761+
break;
1762+
}
1763+
let Some(data) = self.table.scope(scope) else {
1764+
break;
1765+
};
1766+
let usable = matches!(
1767+
data.kind,
1768+
ScopeKind::TranslationUnit
1769+
| ScopeKind::Namespace
1770+
| ScopeKind::Class
1771+
| ScopeKind::Enum
1772+
);
1773+
if usable && let Some(found) = self.scope_of_a_qualifier_inside(qualifier, scope) {
1774+
return Some(found);
1775+
}
1776+
ancestor = data.parent;
1777+
}
1778+
self.scope_of_a_qualifier(qualifier)
1779+
}
1780+
1781+
/// [`ScopeWalker::scope_of_a_qualifier`] with `prefix` — the enclosing scope's qualified name — in front.
1782+
fn scope_of_a_qualifier_inside(&self, qualifier: &str, prefix: ScopeId) -> Option<ScopeId> {
1783+
let base = self.table.qualified_name_of(prefix);
1784+
let mut segments: Vec<String> = Vec::new();
1785+
let mut depth = 0usize;
1786+
let mut letters = String::new();
1787+
for character in qualifier.chars() {
1788+
match character {
1789+
'<' => depth += 1,
1790+
'>' => depth = depth.saturating_sub(1),
1791+
':' if depth == 0 => {
1792+
if !letters.is_empty() {
1793+
segments.push(std::mem::take(&mut letters));
1794+
}
1795+
}
1796+
_ if depth == 0 => letters.push(character),
1797+
_ => {}
1798+
}
1799+
}
1800+
if !letters.is_empty() {
1801+
segments.push(letters);
1802+
}
1803+
if segments.is_empty() {
1804+
return None;
1805+
}
1806+
1807+
let mut walked = base.unwrap_or_default();
1808+
let mut found = None;
1809+
for segment in segments {
1810+
if !walked.is_empty() {
1811+
walked.push_str("::");
1812+
}
1813+
walked.push_str(&segment);
1814+
found = self.table.scope_with_qualified_name(&walked);
1815+
found?;
1816+
}
1817+
found
1818+
}
17181819
/// One declarator: a name, possibly a function, possibly with a body.
17191820
///
17201821
/// `as_kind` overrides what the declarator would otherwise declare, for the case where a class-like
@@ -1767,7 +1868,7 @@ impl ScopeWalker<'_> {
17671868
// a scope this file built, that scope is the parent.
17681869
let qualifier = spelled.rsplit_once("::").map(|(qualifier, _)| qualifier);
17691870
let parent = qualifier
1770-
.and_then(|qualifier| self.scope_of_a_qualifier(qualifier))
1871+
.and_then(|qualifier| self.scope_of_the_qualifier(qualifier, outer))
17711872
.unwrap_or(outer);
17721873
self.table.create_named_scope(
17731874
ScopeKind::Function,
@@ -1866,7 +1967,8 @@ impl ScopeWalker<'_> {
18661967
.identifier_text()
18671968
.map(|name| format!("{qualifier}::{name}"));
18681969
(
1869-
self.scope_of_a_qualifier(&qualifier).unwrap_or(outer),
1970+
self.scope_of_the_qualifier(&qualifier, outer)
1971+
.unwrap_or(outer),
18701972
name.0,
18711973
name.1,
18721974
)

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4949,3 +4949,54 @@ fn a_second_pull_reuses_the_inference_of_the_first() {
49494949
{misses_before} -> {misses_after} computed"
49504950
);
49514951
}
4952+
4953+
/// **A parameter of an out-of-class member definition is a declaration in its body** — two reports, one root cause.
4954+
///
4955+
/// `void Archive::put(const Entry& entry) { counts += entry.key; }` and `void Report::add(int line) { lines(…) }` are
4956+
/// the shapes a real project writes, and both were reported by a reader: `entry` and `line` "are not declared", and
4957+
/// hovering `line` answered `std::source_location::line` — a *namespace* member found because the parameter had no
4958+
/// binding of its own.
4959+
///
4960+
/// The qualified declarator is the common factor: `declared_name` refuses a qualified name on purpose (a `count` bound
4961+
/// in this file's scope would be a name that cannot be used unqualified), and the question this test asks is whether
4962+
/// that refusal also dropped the **parameters**, which are in scope in the body regardless of how the function is
4963+
/// spelled.
4964+
#[test]
4965+
fn a_parameter_of_an_out_of_class_definition_is_declared() {
4966+
let text = "namespace report {\n\
4967+
\x20 struct Entry { int key; int count; };\n\
4968+
\x20 class Archive {\n\
4969+
\x20 public:\n\
4970+
\x20 void put(const Entry& entry);\n\
4971+
\x20 private:\n\
4972+
\x20 int counts;\n\
4973+
\x20 };\n\
4974+
\x20 void Archive::put(const Entry& entry) {\n\
4975+
\x20 counts += entry.key;\n\
4976+
\x20 }\n\
4977+
}\n";
4978+
let files = MemoryFiles::new().with_file("/p/archive.cpp", text);
4979+
let fixture = Memory::new("a-parameter-of-an-out-of-class-definition", &files);
4980+
let mut session = fixture.session();
4981+
session.did_open("/p/archive.cpp", text);
4982+
session.index_everything();
4983+
let path = std::path::PathBuf::from("/p/archive.cpp");
4984+
let view = session.view_of_the_file(&path).expect("a view");
4985+
4986+
// **The use, not the declaration**: `entry` in `entry.key`, inside the body.
4987+
let at = text.find("entry.key").expect("the fixture") + 1;
4988+
let found = session.definition(&view, ReadingOffset::new(at));
4989+
assert!(
4990+
matches!(found, Known::Yes(_)),
4991+
"the body's `entry` is the parameter: {found:?}"
4992+
);
4993+
let Known::Yes(found) = found else {
4994+
unreachable!()
4995+
};
4996+
assert_eq!(
4997+
found.fact.name.as_str(),
4998+
"entry",
4999+
"and it is the parameter, not a type or a namespace member: {:?}",
5000+
found.fact
5001+
);
5002+
}
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
//! **A reader's two reports, checked against their own project** — the fixture at `CPPLS_MODULES_PROJECT`.
2+
//!
3+
//! Both were about a body inside a namespace: `entry` in `Archive::put` and `line` in `Report::add` "are not declared",
4+
//! and hovering `line` answered `std::source_location::line`. The cause was one rule: a qualified declaration nested in
5+
//! a `CompoundStat` was skipped, and a namespace body is a `CompoundStat`.
6+
//!
7+
//! Skipped when the fixture is absent, like every other probe.
8+
9+
use std::path::PathBuf;
10+
11+
use cpp_code_analysis::{DiskFiles, Known, OpenDocuments, Session, SessionFiles, WatchFilter};
12+
13+
fn project() -> Option<PathBuf> {
14+
let named = std::env::var_os("CPPLS_MODULES_PROJECT")
15+
.map(PathBuf::from)
16+
.unwrap_or_else(|| PathBuf::from(r"C:\Users\zc\Desktop\cpp_modules"));
17+
named
18+
.join("src")
19+
.join("archive.cpp")
20+
.is_file()
21+
.then_some(named)
22+
}
23+
24+
#[test]
25+
#[ignore = "a probe: needs the external fixture"]
26+
fn a_body_inside_a_namespace_names_its_parameters() {
27+
let Some(root) = project() else {
28+
eprintln!("no fixture: set CPPLS_MODULES_PROJECT");
29+
return;
30+
};
31+
let mut session = Session::open(
32+
root.clone(),
33+
SessionFiles::new(OpenDocuments::new(), DiskFiles),
34+
WatchFilter::new(&root),
35+
);
36+
let archive = root.join("src").join("archive.cpp");
37+
let report = root.join("src").join("report.cpp");
38+
let archive_text = std::fs::read_to_string(&archive).expect("archive.cpp");
39+
let report_text = std::fs::read_to_string(&report).expect("report.cpp");
40+
session.did_open(&archive, &archive_text);
41+
session.did_open(&report, &report_text);
42+
session.add_project_files([archive.clone(), report.clone()]);
43+
session.index_everything();
44+
45+
for (path, text, needle) in [
46+
(&archive, &archive_text, "_counts[entry.key]"),
47+
(&report, &report_text, "std::move(line)"),
48+
] {
49+
let at = text.find(needle).expect("the reported line");
50+
let name = if needle.contains("entry") {
51+
at + "_counts[".len() + 1
52+
} else {
53+
at + "std::move(".len() + 1
54+
};
55+
let view = session.view_of_the_file(path).expect("a view");
56+
let found = session.definition(
57+
&view,
58+
cpp_code_analysis::file::coordinates::ReadingOffset::new(name),
59+
);
60+
let rendered = match &found {
61+
Known::Yes(definition) => format!(
62+
"{} in {:?}",
63+
definition.fact.name,
64+
definition.file.file_name()
65+
),
66+
other => format!("{other:?}"),
67+
};
68+
println!(
69+
"{}: {needle:?} → {rendered}",
70+
path.file_name().unwrap().to_string_lossy()
71+
);
72+
}
73+
74+
for path in [&archive, &report] {
75+
if let Some(diagnostics) = session.diagnostics(path) {
76+
let messages: Vec<String> = diagnostics
77+
.checks
78+
.iter()
79+
.map(|entry| format!("{:?}: {}", entry.code, entry.message))
80+
.collect();
81+
let errors: usize = diagnostics.errors.len();
82+
println!(
83+
"{}: {} error(s), {} check(s) {}",
84+
path.file_name().unwrap().to_string_lossy(),
85+
errors,
86+
messages.len(),
87+
messages.join(" | ")
88+
);
89+
}
90+
}
91+
92+
// **The answer**: the parameters are declared, so no entry says otherwise.
93+
if let Some(diagnostics) = session.diagnostics(&archive) {
94+
assert!(
95+
!diagnostics
96+
.errors
97+
.iter()
98+
.any(|error| error.message.contains("entry"))
99+
&& !diagnostics
100+
.checks
101+
.iter()
102+
.any(|check| check.message.contains("entry")),
103+
"`entry` is the parameter of the definition it is written in: {:?}",
104+
diagnostics
105+
.errors
106+
.iter()
107+
.map(|error| error.message.clone())
108+
.collect::<Vec<_>>()
109+
);
110+
}
111+
if let Some(diagnostics) = session.diagnostics(&report) {
112+
assert!(
113+
!diagnostics.checks.iter().any(|check| {
114+
check.message.contains("push_back") || check.message.contains("_Ty")
115+
}),
116+
"`push_back(const _Ty&)` takes a moved string: {:?}",
117+
diagnostics
118+
.checks
119+
.iter()
120+
.map(|check| check.message.clone())
121+
.collect::<Vec<_>>()
122+
);
123+
}
124+
}

0 commit comments

Comments
 (0)