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_start_matches(['\\', ' ', '\t', '\n', '\r']);
if body.is_empty()
|| body.starts_with('(')
|| body.starts_with('{')
|| body.starts_with("do") && !has_a_loose_operator(body)
{
continue;
}
if starts_a_declaration(body) || body.contains("##") || is_a_call(body) {
continue;
}
if !has_a_loose_operator(body) {
continue;
}
context.add_in_the_file(
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 starts_a_declaration(body: &str) -> bool {
const DECLARATION_WORDS: &[&str] = &[
"static",
"extern",
"const",
"volatile",
"inline",
"register",
"typedef",
"using",
"struct",
"class",
"union",
"enum",
"namespace",
"template",
"auto",
"void",
"char",
"short",
"int",
"long",
"float",
"double",
"signed",
"unsigned",
"bool",
"_Bool",
"size_t",
];
body.split_whitespace()
.next()
.is_some_and(|first| DECLARATION_WORDS.contains(&first))
}
fn is_a_call(body: &str) -> bool {
let Some(open) = body.find('(') else {
return false;
};
let callee = body[..open].trim();
if callee.is_empty()
|| !callee
.chars()
.all(|character| character.is_alphanumeric() || character == '_' || character == ':')
{
return false;
}
let mut depth = 0i32;
for (at, character) in body.char_indices().skip(open) {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return body[at + 1..].trim().is_empty();
}
}
_ => {}
}
}
false
}
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
}