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
.get_expr()
.map(|expression| expression.syntax().clone())
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 let Some(paren) = cpp_parser::CppParenExpr::cast(node.clone()) {
match paren.get_expr() {
Some(inner) => node = inner.syntax().clone(),
None => return false,
}
}
if let Some(binary) = cpp_parser::CppBinaryExpr::cast(node.clone()) {
return matches!(
binary.get_operator_text().as_deref(),
Some("==" | "!=" | "<" | ">" | "<=" | ">=" | "&&" | "||")
);
}
if let Some(unary) = cpp_parser::CppUnaryExpr::cast(node.clone()) {
return unary.get_operator_text().as_deref() == Some("!");
}
false
}