use std::collections::HashMap;
use super::{Check, CheckContext, DiagnosticCode};
pub struct Redefinition;
impl Check for Redefinition {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::Redefinition];
fn check(context: &mut CheckContext<'_>) {
let mut repeated: Vec<(cpp_parser::SourceRange, String)> = Vec::new();
for scope in context.model.scopes().scopes() {
if !matches!(
scope.kind,
crate::ScopeKind::Function | crate::ScopeKind::Block | crate::ScopeKind::Lambda
) {
continue;
}
let mut declared: HashMap<&str, cpp_parser::SourceRange> = HashMap::new();
for binding in &scope.bindings {
let Some(name) = binding.name.identifier_text() else {
continue;
};
if !a_kind_that_cannot_be_repeated(binding.kind) {
continue;
}
if binding.origin.is_some() {
continue;
}
let declarator: &str = context
.source
.get(binding.range.start_offset..binding.range.end_offset())
.unwrap_or("");
let specifier = context
.source
.get(..binding.range.start_offset)
.unwrap_or("")
.trim_end()
.rsplit(|character: char| !(character.is_alphanumeric() || character == '_'))
.next()
.unwrap_or("");
if declarator.trim_start().starts_with('*') && specifier == name {
continue;
}
match declared.get(name) {
Some(first) if first.start_offset == binding.name_range.start_offset => {}
Some(_) => {
repeated.push((binding.name_range, name.to_string()));
}
None => {
declared.insert(name, binding.name_range);
}
}
}
}
for (range, name) in repeated {
context.add(
DiagnosticCode::Redefinition,
range,
name.clone(),
t!("`%{name}` is already declared in this scope", name = name),
);
}
}
}
fn a_kind_that_cannot_be_repeated(kind: crate::BindingKind) -> bool {
matches!(kind, crate::BindingKind::Variable)
}