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.to_string(),
range.start_offset,
range.end_offset(),
))
})
.collect();
for (name, start, end) in bodies {
let body = context.written.get(start..end).unwrap_or("");
let body = the_code_of(body);
if body.is_empty()
|| is_one_group(&body)
|| 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 is_one_group(body: &str) -> bool {
if !body.starts_with('(') {
return false;
}
let mut depth = 0i32;
for (at, character) in body.char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return body[at + 1..].trim().is_empty();
}
}
_ => {}
}
}
false
}
fn the_code_of(body: &str) -> String {
let mut code = String::with_capacity(body.len());
let mut characters = body.chars().peekable();
while let Some(character) = characters.next() {
match character {
'\\' if characters.peek() == Some(&'\n') => {
characters.next();
}
'\\' if characters.peek() == Some(&'\r') => {
characters.next();
if characters.peek() == Some(&'\n') {
characters.next();
}
}
'/' if characters.peek() == Some(&'*') => {
characters.next();
let mut previous = '\0';
for inside in characters.by_ref() {
if previous == '*' && inside == '/' {
break;
}
previous = inside;
}
code.push(' ');
}
'/' if characters.peek() == Some(&'/') => {
characters.next();
while let Some(inside) = characters.peek() {
if *inside == '\n' {
break;
}
characters.next();
}
code.push(' ');
}
quote @ ('"' | '\'') => {
let mut closed = false;
while let Some(inside) = characters.next() {
if inside == '\\' {
characters.next();
continue;
}
if inside == quote {
closed = true;
break;
}
}
code.push(quote);
if closed {
code.push(quote);
}
}
other => code.push(other),
}
}
code.trim().to_string()
}
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",
"typename",
"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;
let mut skip_until = 0usize;
for (index, character) in body.char_indices() {
if index < skip_until {
continue;
}
match character {
'(' | '[' | '{' => depth += 1,
')' | ']' | '}' => depth -= 1,
'+' | '-' | '*' | '/' | '%' | '&' | '|' | '^' | '?' | '<' | '>' | '=' | '!'
if depth == 0 =>
{
if character == '<'
&& let Some(end) = template_id_end(body, index)
{
skip_until = end;
continue;
}
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
}
fn template_id_end(body: &str, open: usize) -> Option<usize> {
let mut depth = 0i32;
for (at, character) in body[open..].char_indices() {
match character {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
return (at > 1).then_some(open + at + 1);
}
}
_ if depth > 0 => {
let allowed = character.is_alphanumeric()
|| matches!(
character,
'_' | ':'
| ','
| '.'
| '*'
| '&'
| '('
| ')'
| '['
| ']'
| '-'
| '\''
| ' '
);
if !allowed {
return None;
}
}
_ => return None,
}
}
None
}