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 is_deliberately_unused(name: &str) -> bool {
name.starts_with('_')
}
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 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 bodies: Vec<cpp_parser::CppSyntaxNode> = super::function_definitions(context)
.into_iter()
.filter_map(|function| super::body_of(&function))
.collect();
for fact in &context.summary.declarations {
if !fact.local || fact.kind != crate::DeclKind::Variable {
continue;
}
let Some(at) =
context
.view
.reading_offset_of(crate::file::coordinates::FileOffset::new(
fact.range.start_offset,
))
else {
continue;
};
let inside_a_body = bodies.iter().any(|body| {
usize::from(body.text_range().start()) < at.get()
&& at.get() < usize::from(body.text_range().end())
});
if !inside_a_body {
continue;
}
if is_deliberately_unused(&fact.name) || !is_a_candidate(&fact.name) {
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
),
);
}
}
}