use cpp_parser::CppAstNode;
use super::{Check, CheckContext, DiagnosticCode};
pub struct ImplicitBoolConversion;
impl Check for ImplicitBoolConversion {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::ImplicitBoolConversion];
fn check(context: &mut CheckContext<'_>) {
let mut conditions: Vec<(usize, usize)> = Vec::new();
let mut note = |condition: &cpp_parser::CppParenExpr| {
let Some(inner) = condition.syntax().children().next() else {
return;
};
if the_question_answers_itself(&inner) {
return;
}
let crate::Known::Yes((type_of, _)) = context.type_of(&inner) else {
return;
};
if !type_of.is_arithmetic() || type_of.to_string() == "bool" {
return;
}
let range = inner.text_range();
conditions.push((
usize::from(range.start()),
usize::from(range.end()) - usize::from(range.start()),
));
};
for statement in context.own::<cpp_parser::CppIfStat>().collect::<Vec<_>>() {
if let Some(condition) = statement.get_condition() {
note(&condition);
}
}
for statement in context
.own::<cpp_parser::CppWhileStat>()
.collect::<Vec<_>>()
{
if let Some(condition) = statement.get_condition() {
note(&condition);
}
}
for (offset, length) in conditions {
let written = context
.source
.get(offset..offset + length)
.unwrap_or_default()
.trim()
.to_string();
context.add(
DiagnosticCode::ImplicitBoolConversion,
cpp_parser::SourceRange::new(offset, length),
written.clone(),
t!(
"`%{written}` is converted to `bool` here — write the comparison the reader is being asked to make: `%{written} != 0`", written = written
),
);
}
}
}
fn the_question_answers_itself(expression: &cpp_parser::CppSyntaxNode) -> bool {
let mut node = expression.clone();
while cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::ParenExpr {
match node.children().next() {
Some(inner) => node = inner,
None => return false,
}
}
if let Some(binary) = cpp_parser::CppBinaryExpr::cast(node.clone()) {
return matches!(
binary.get_operator_text().as_deref(),
Some("==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||")
);
}
if cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::UnaryExpr {
return node
.children_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| {
!matches!(
cpp_parser::CppTokenKind::from(token.kind()),
cpp_parser::CppTokenKind::Whitespace | cpp_parser::CppTokenKind::Newline
)
})
.is_some_and(|token| token.text() == "!");
}
false
}