use super::{Check, CheckContext, DiagnosticCode};
pub struct MacroParentheses;
impl Check for MacroParentheses {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::MacroParentheses];
fn check(context: &mut CheckContext<'_>) {
let bodies: Vec<(String, usize, usize)> = context
.summary
.macros
.iter()
.filter_map(|fact| {
let range = fact.body_range?;
context
.written
.get(range.start_offset..range.end_offset())?;
Some((fact.name.clone(), range.start_offset, range.end_offset()))
})
.collect();
for (name, start, end) in bodies {
let body = context.written.get(start..end).unwrap_or("").trim();
if body.is_empty()
|| body.starts_with('(')
|| body.starts_with('{')
|| body.starts_with("do") && !has_a_loose_operator(body)
{
continue;
}
if !has_a_loose_operator(body) {
continue;
}
context.add(
DiagnosticCode::MacroParentheses,
cpp_parser::SourceRange::new(start, end - start),
name.clone(),
t!(
"`%{name}`'s replacement list is not parenthesised, so a caller's expression is spliced in without its precedence — write `#define %{name}(…) (…)`", name = name
),
);
}
}
}
fn has_a_loose_operator(body: &str) -> bool {
let mut depth = 0i32;
for (index, character) in body.char_indices() {
match character {
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth -= 1,
'+' | '-' | '*' | '/' | '%' | '&' | '|' | '^' | '?' | '<' | '>' | '=' | '!'
if depth == 0 =>
{
let before = body[..index].chars().last();
let after = body[index + 1..].chars().next();
let is_unary = before.is_none()
|| before.is_some_and(|previous| {
matches!(
previous,
'(' | '[' | '{' | ',' | '=' | '+' | '-' | '*' | '/' | '!' | '?' | ':'
)
});
let is_a_suffix = matches!(
(character, after),
('-', Some('>')) | ('>', Some('>')) | (':', Some(':'))
);
if !is_unary && !is_a_suffix {
return true;
}
}
_ => {}
}
}
false
}