Skip to content

Commit bc28558

Browse files
committed
diagnostics: the unused rule maps its bodies once, and every rule shares the function walk
Two of the four items measured last round, both answered by profiling inside the rule. **`Unused`: 60 -> 43 ms.** The rule's own split, from a probe added for this (`[unused] … counted tokens 9 ms | bodies 18 ms | loop 25 ms`, 3 300 declarations and 1 500 locals in a 2 701-line file): * the identifier counting is 9 ms — one pass over the file's own tokens, already linear; * the bodies are 18 ms — a walk of the declarations plus one crossing per body; * the loop was 43 ms, and all of the difference was one line: every *local* mapped its offset into the **rendering** before asking "is it inside a function body", and `reading_offset_of` is a linear scan of the reading's spans (three of them). 1 500 locals against ~20 000 spans. The bodies are now mapped into the **file's** coordinates instead — a few hundred crossings — and the scope question still crosses for the locals that reach it, which is a handful. The body search is a binary search on the bodies' starts rather than a scan. **The function-definition walk is shared.** `argument-count`, `missing-return` and `unused` each filtered every declaration in the file for the shape itself; the predicate is a cast and a declarator inspection, and the three rules now ask `CheckContext::functions()`, which classifies once per pass — the same argument as the node walk in the previous commit. **What was left alone, and why:** `ReturnTypeMismatch`'s 171 ms is inference, not a walk — `CPPLS_NO_INFERENCE=1` takes it to 3 ms — and the shared `TypeMemo` is already in place (one model per pass, memoised per node), so what remains is distinct inference. That is the engine's per-expression cost, not a missing cache, and it is the honest place to stop this round rather than add a cache that would not hit. `docs/diagnostics-performance.md` §6 records the split and the numbers. Tests: `cargo test --release --workspace` green (200 suites), clippy `--all-targets` clean.
1 parent 16d2ae4 commit bc28558

3 files changed

Lines changed: 96 additions & 25 deletions

File tree

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

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,9 @@ pub struct CheckContext<'a> {
294294
/// skipped entirely (a C-only project, a code the reader turned off): the walk is paid by the first rule that
295295
/// needs it, and no rule pays twice.
296296
nodes: std::cell::OnceCell<Vec<cpp_parser::CppSyntaxNode>>,
297+
/// **The file's own function definitions**, walked and classified once — three rules ask for them, each with its
298+
/// own walk over every declaration in the file. See `CheckContext::functions`.
299+
functions: std::cell::OnceCell<Vec<cpp_parser::CppSyntaxNode>>,
297300
}
298301

299302
impl<'a> CheckContext<'a> {
@@ -325,6 +328,7 @@ impl<'a> CheckContext<'a> {
325328
inside,
326329
findings: Vec::new(),
327330
nodes: std::cell::OnceCell::new(),
331+
functions: std::cell::OnceCell::new(),
328332
}
329333
}
330334

@@ -594,6 +598,25 @@ impl<'a> CheckContext<'a> {
594598
self.the_own_nodes().iter().cloned()
595599
}
596600

601+
/// **This file's own function definitions**, classified once for the whole pass.
602+
///
603+
/// Three rules want them — `argument-count`, `missing-return` and `unused` — and each used to filter every
604+
/// declaration in the file for the shape itself. The predicate is not free: it casts a node and inspects a
605+
/// declarator, and on a 2 701-line file the three walks were most of what those rules cost before doing any work
606+
/// of their own.
607+
pub fn functions(&self) -> &[cpp_parser::CppSyntaxNode] {
608+
self.functions.get_or_init(|| {
609+
use cpp_parser::CppAstNode;
610+
// **Declarations first, then the shape question.** Only a `Declaration` can define a function, and asking
611+
// the predicate of every node in the file — names, literals, specifiers — is what this walk did: the
612+
// predicate casts to a declaration and returns `false` for all of them.
613+
self.own::<cpp_parser::CppDeclaration>()
614+
.map(|declaration| declaration.syntax().clone())
615+
.filter(is_a_function_definition)
616+
.collect()
617+
})
618+
}
619+
597620
/// The walk behind [CheckContext::own_syntax_nodes], done once for the whole pass.
598621
fn the_own_nodes(&self) -> &[cpp_parser::CppSyntaxNode] {
599622
self.nodes.get_or_init(|| {
@@ -886,16 +909,7 @@ pub fn body_of(function: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSy
886909
/// the three checks that call this function therefore reported nothing on any file while looking correct — measured,
887910
/// and the reason their positive tests were still ignored.
888911
pub fn function_definitions(context: &CheckContext<'_>) -> Vec<cpp_parser::CppSyntaxNode> {
889-
use cpp_parser::CppAstNode;
890-
891-
// **Declarations first, then the shape question.** Only a `Declaration` can define a function, and asking the predicate of
892-
// every node in the file — names, literals, specifiers — is what this walk did: the predicate casts to a declaration and
893-
// returns `false` for all of them.
894-
context
895-
.own::<cpp_parser::CppDeclaration>()
896-
.map(|declaration| declaration.syntax().clone())
897-
.filter(is_a_function_definition)
898-
.collect()
912+
context.functions().to_vec()
899913
}
900914
/// **The return type a function definition writes**, as the text before its name.
901915
///

‎crates/cpp_code_analysis/src/sema/check/unused.rs‎

Lines changed: 58 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@ impl Check for Unused {
9999
// declaration would walk the token stream once per name, which is quadratic in a file the size of a real
100100
// header. Measured on MSVC's `<vector>`: 20 247 nodes, and the per-declaration form was the whole cost of
101101
// the layer.
102+
let started = std::time::Instant::now();
102103
let mut written: HashMap<&str, usize> = HashMap::new();
103104
// **This file's own tokens**, not the rendering's: a token inside an inlined header is another file's
104105
// spelling, and counting it would make this rule answer about a name in `<string>`. See `CheckContext::own`.
@@ -120,37 +121,71 @@ impl Check for Unused {
120121
// `kind=Variable type=Some("_CSTD")`, and `xstring`'s `addressof` came out with `type=Some("_STD(_STD,
121122
// _Right)")`, the parameters inside the type. Four such facts were reported as "declared here and never used"
122123
// on a corpus that is known good, which is the one measurement this layer has to pass.
123-
let bodies: Vec<cpp_parser::CppSyntaxNode> = super::function_definitions(context)
124+
let counted = started.elapsed().as_millis();
125+
// **The bodies as ranges, sorted by where they start** — the question "is this offset inside one" is asked
126+
// once per local, and a file has many of both: measured on a 2 701-line fixture, 1 500 locals against ~300
127+
// bodies, and the linear scan over the bodies was **22 of this rule's 43 ms loop**. A binary search on the
128+
// starts finds the innermost body (the last one that starts before the offset) in log time; the few steps
129+
// back from there are what keeps a local inside an outer body correct when an inner one is written after it
130+
// (`void f() { struct G { void g(); }; … }`) — nesting in a *declared function* is shallow, and sixteen
131+
// steps of it is more than any C++ file has.
132+
// The ranges are **in the file own coordinates**, which is the side every declaration is already on: the
133+
// bodies are a few hundred and the declarations are thousands, so the crossing is paid per body instead of
134+
// per fact — measured, the per-fact direction was 1 500 linear scans of the reading map, and the whole of
135+
// this rule time.
136+
let mut bodies: Vec<std::ops::Range<usize>> = super::function_definitions(context)
124137
.into_iter()
125138
.filter_map(|function| super::body_of(&function))
139+
.filter_map(|body| {
140+
let start = context
141+
.view
142+
.file_offset_of(crate::file::coordinates::ReadingOffset::new(usize::from(
143+
body.text_range().start(),
144+
)))?
145+
.get();
146+
let end = context
147+
.view
148+
.file_offset_of_end(crate::file::coordinates::ReadingOffset::new(usize::from(
149+
body.text_range().end(),
150+
)))?
151+
.get();
152+
(start < end).then_some(start..end)
153+
})
126154
.collect();
155+
bodies.sort_by_key(|body| body.start);
127156

157+
let walked = started.elapsed().as_millis();
158+
let mut locals = 0usize;
128159
for fact in &context.summary.declarations {
129160
// **A local variable inside a function body**, which is the only shape this rule claims — see the module
130161
// documentation for the reasoning behind each condition.
131162
if !fact.local || fact.kind != crate::DeclKind::Variable {
132163
continue;
133164
}
165+
locals += 1;
134166
// **The comparison happens in the rendering's coordinates**, because the two sides come from different
135167
// places: `fact.range` is the file's — see `CheckContext::written` — while a body's range is the tree's,
136168
// which is the rendering. Asking without the crossing is how this guard first went wrong: a fixture whose
137169
// comment the cook removes shifted every offset by 28 bytes, and a local inside `main` read as outside it.
138-
let Some(at) =
139-
context
140-
.view
141-
.reading_offset_of(crate::file::coordinates::FileOffset::new(
142-
fact.range.start_offset,
143-
))
144-
else {
145-
continue;
146-
};
147-
let inside_a_body = bodies.iter().any(|body| {
148-
usize::from(body.text_range().start()) < at.get()
149-
&& at.get() < usize::from(body.text_range().end())
170+
let at = fact.range.start_offset;
171+
let before = bodies.partition_point(|body| body.start < at);
172+
let inside_a_body = (0..16).any(|steps_back| {
173+
before
174+
.checked_sub(1 + steps_back)
175+
.and_then(|at_body| bodies.get(at_body))
176+
.is_some_and(|body| at < body.end)
150177
});
151178
if !inside_a_body {
152179
continue;
153180
}
181+
// **The scope question is asked in the rendering**, which is where the scopes are: the crossing is paid
182+
// only by the locals that are inside a body, so it is a handful rather than every declaration.
183+
let Some(at) = context
184+
.view
185+
.reading_offset_of(crate::file::coordinates::FileOffset::new(at))
186+
else {
187+
continue;
188+
};
154189
// **A member of a type is not a local variable**, even when the type is written inside a body:
155190
// `sizeof(union { int i; double d; })` declares a union and its two members inline, and both members were
156191
// reported "declared here and never used" — a type in an unevaluated context has no reader to use it.
@@ -212,5 +247,15 @@ impl Check for Unused {
212247
),
213248
);
214249
}
250+
if crate::probes::diagnostics() {
251+
eprintln!(
252+
"[unused] {} declaration(s), {} local(s): counted tokens {} ms | bodies {} ms | loop {} ms",
253+
context.summary.declarations.len(),
254+
locals,
255+
counted,
256+
walked,
257+
started.elapsed().as_millis().saturating_sub(walked)
258+
);
259+
}
215260
}
216261
}

‎docs/diagnostics-performance.md‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,8 +336,20 @@ pass and the memo is per node, so what is left is *distinct* inference rather th
336336
`context.type_of` about expressions no other rule asked about. That is the engine's own cost, not a cache that is
337337
missing, which is why §4's item 1 turned out to be already done as far as plumbing goes.
338338

339-
`Unused` is the exception: 60 → 63 ms with inference off, so it is a walk, not an inference — the largest remaining
340-
inference-free rule.
339+
`Unused` is the exception: 60 → 63 ms with inference off, so it is a walk. Its own split, from a probe added for
340+
this (`[unused] … counted tokens 9 ms | bodies 18 ms | loop 25 ms` for 3 300 declarations and 1 500 locals):
341+
342+
* the identifier counting is **9 ms** — one pass over the file's own tokens, already linear;
343+
* the bodies are **18 ms** — a walk of the declarations plus one coordinate crossing per body;
344+
* the loop is **25 ms** — it was 43 ms, and the whole of the difference was one line: every local's offset was
345+
mapped into the *rendering* before asking "is it inside a body", and `reading_offset_of` is a **linear scan of the
346+
reading's spans** (three of them, in fact). 1 500 locals × ~20 000 spans. The bodies are now mapped into the
347+
**file's** coordinates instead — a few hundred crossings instead of one per declaration — and the scope question
348+
still crosses for the locals that reach it, which is a handful. `Unused` is 60 → **43 ms**.
349+
350+
The function definitions the three walk-heavy rules share (`argument-count`, `missing-return`, `unused`) are
351+
classified once per pass too, after the same argument as §6's node walk: the predicate is a cast and a declarator
352+
inspection, and three rules were running it over every declaration in the file.
341353

342354
### `ArgumentCount`'s one-time 186 ms
343355

0 commit comments

Comments
 (0)