use cpp_parser::{CppAstNode, CppSyntaxKind};
use super::{Check, CheckContext, DiagnosticCode};
pub struct CStyleCast;
impl Check for CStyleCast {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::CStyleCast];
fn check(context: &mut CheckContext<'_>) {
if context.is_c() {
return;
}
let Some(root) = context.root() else {
return;
};
for node in root.syntax().descendants() {
if CppSyntaxKind::from(node.kind()) != CppSyntaxKind::CastExpr {
continue;
}
let opens_with_a_parenthesis = node
.children_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| !token.text().trim().is_empty())
.is_some_and(|token| token.text() == "(");
if !opens_with_a_parenthesis {
continue;
}
let Some(type_id) = node
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TypeId)
else {
continue;
};
let written = type_id.text().to_string();
let written = written.trim();
if written.is_empty() {
continue;
}
context.add(
DiagnosticCode::CStyleCast,
cpp_parser::source_range(node.text_range()),
t!("(%{written})", written = written),
t!(
"this is a C-style cast to `%{written}` — the four named casts say which conversion is meant, and \
`static_cast<%{written}>(…)` is almost always the one",
written = written
),
);
}
}
}