use crate::index::environment::fact_in_force;
use crate::summary::MacroFact;
use super::{Check, CheckContext, DiagnosticCode};
pub struct MacroRedefined;
impl Check for MacroRedefined {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::MacroRedefined];
fn check(context: &mut CheckContext<'_>) {
let seed = context.index().macros();
let live: Vec<&MacroFact> = context
.summary
.macros
.iter()
.filter(|fact| fact.kind.is_definition())
.filter(|fact| fact_in_force(seed, context.summary, fact))
.collect();
for (at, fact) in live.iter().enumerate() {
let Some(first) = live[..at].iter().find(|earlier| earlier.name == fact.name) else {
continue;
};
let undefined_between = context.summary.macros.iter().any(|other| {
!other.kind.is_definition()
&& other.name == first.name
&& other.range.start_offset > first.range.start_offset
&& other.range.start_offset < fact.range.start_offset
});
if undefined_between {
continue;
}
if first.function_like == fact.function_like && bodies_are_equal(context, first, fact) {
continue;
}
context.add_in_the_file(
DiagnosticCode::MacroRedefined,
fact.range,
fact.name.to_string(),
format!(
"`{}` is redefined here with a different body; the definition that was in force is at offset {}",
fact.name, first.range.start_offset
),
);
}
}
}
fn bodies_are_equal(context: &CheckContext<'_>, first: &MacroFact, second: &MacroFact) -> bool {
let text = |fact: &MacroFact| {
fact.body_range
.and_then(|range| context.written.get(range.start_offset..range.end_offset()))
.unwrap_or("")
.trim()
};
text(first) == text(second)
}