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 the_declaration_is_really_a_call(context, binding.range) {
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)
}
fn the_declaration_is_really_a_call(
context: &CheckContext<'_>,
range: cpp_parser::SourceRange,
) -> bool {
let Some(token) = cpp_parser::token_at(context.model.tree(), range.start_offset) else {
return false;
};
let Some(declaration) = token.parent_ancestors().find(|node| {
cpp_parser::CppSyntaxKind::from(node.kind()) == cpp_parser::CppSyntaxKind::Declaration
}) else {
return false;
};
let Some(first) = declaration
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())))
else {
return false;
};
if cpp_parser::CppTokenKind::from(first.kind()) != cpp_parser::CppTokenKind::Identifier {
return false;
}
let name = first.text().to_string();
matches!(
context.model.index().definition(name.as_str(), context.path),
crate::Known::Yes(found) if found.fact.kind == crate::DeclKind::Function
)
}