use std::collections::HashMap;
use cpp_parser::CppTokenKind;
use super::{Check, CheckContext, DiagnosticCode};
fn is_a_header(path: &std::path::Path) -> bool {
matches!(
path.extension().and_then(|extension| extension.to_str()),
Some("h" | "hh" | "hpp" | "hxx" | "inl" | "ipp" | "tpp" | "inc")
)
}
fn declares_a_member(context: &CheckContext<'_>, at: usize) -> bool {
let scopes = context.model.scopes();
scopes
.scope_at(at)
.and_then(|scope| scopes.scope(scope))
.is_some_and(|data| data.kind == crate::ScopeKind::Class)
}
fn is_deliberately_unused(name: &str) -> bool {
name.starts_with('_')
}
fn its_type_cannot_have_a_destructor(fact: &crate::DeclFact) -> bool {
fact.type_of
.as_deref()
.is_some_and(super::undefined_name::is_a_builtin_spelling)
}
fn is_a_candidate(name: &str) -> bool {
!name.is_empty()
&& name
.chars()
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_' || first == '$')
&& name.chars().all(|character| {
character.is_ascii_alphanumeric() || character == '_' || character == '$'
})
}
pub struct Unused;
impl Check for Unused {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::Unused];
fn check(context: &mut CheckContext<'_>) {
if is_a_header(context.path) {
return;
}
let started = std::time::Instant::now();
let mut written: HashMap<&str, usize> = HashMap::new();
for token in context.own_tokens() {
if token.kind != CppTokenKind::Identifier {
continue;
}
let text = context
.source
.get(token.range.start_offset..token.range.end_offset())
.unwrap_or_default()
.trim();
*written.entry(text).or_default() += 1;
}
let counted = started.elapsed().as_millis();
let mut bodies: Vec<std::ops::Range<usize>> = super::function_definitions(context)
.into_iter()
.filter_map(|function| super::body_of(&function))
.filter_map(|body| {
let start = context
.view
.file_offset_of(crate::file::coordinates::ReadingOffset::new(usize::from(
body.text_range().start(),
)))?
.get();
let end = context
.view
.file_offset_of_end(crate::file::coordinates::ReadingOffset::new(usize::from(
body.text_range().end(),
)))?
.get();
(start < end).then_some(start..end)
})
.collect();
bodies.sort_by_key(|body| body.start);
let walked = started.elapsed().as_millis();
let mut locals = 0usize;
for fact in &context.summary.declarations {
if !fact.local || fact.kind != crate::DeclKind::Variable {
continue;
}
locals += 1;
let at = fact.range.start_offset;
let before = bodies.partition_point(|body| body.start < at);
let inside_a_body = (0..16).any(|steps_back| {
before
.checked_sub(1 + steps_back)
.and_then(|at_body| bodies.get(at_body))
.is_some_and(|body| at < body.end)
});
if !inside_a_body {
continue;
}
let Some(at) = context
.view
.reading_offset_of(crate::file::coordinates::FileOffset::new(at))
else {
continue;
};
if declares_a_member(context, at.get()) {
continue;
}
if is_deliberately_unused(&fact.name) || !is_a_candidate(&fact.name) {
continue;
}
if fact.modifiers.contains(crate::DeclModifiers::MAYBE_UNUSED) {
continue;
}
if !its_type_cannot_have_a_destructor(fact) {
continue;
}
if written.get(fact.name.as_str()).copied().unwrap_or_default() > 1 {
continue;
}
context.add_in_the_file(
DiagnosticCode::Unused,
fact.name_range,
fact.name.as_str(),
t!(
"`%{name}` is declared here and never used",
name = fact.name
),
);
}
if crate::probes::diagnostics() {
eprintln!(
"[unused] {} declaration(s), {} local(s): counted tokens {} ms | bodies {} ms | loop {} ms",
context.summary.declarations.len(),
locals,
counted,
walked,
started.elapsed().as_millis().saturating_sub(walked)
);
}
}
}