use super::{Check, CheckContext, DiagnosticCode};
pub struct AbstractClassInstantiated;
impl Check for AbstractClassInstantiated {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::AbstractClassInstantiated];
fn check(context: &mut CheckContext<'_>) {
let mut known: std::collections::BTreeMap<String, Option<bool>> =
std::collections::BTreeMap::new();
let variables: Vec<(String, String, cpp_parser::SourceRange)> = context
.summary
.declarations
.iter()
.filter(|fact| fact.kind == crate::DeclKind::Variable)
.filter_map(|fact| {
let class = a_class_name(fact.type_of.as_deref()?)?;
Some((class, fact.name.to_string(), fact.name_range))
})
.collect();
for (class, name, name_range) in variables {
let is_abstract = *known.entry(class.clone()).or_insert_with(|| {
let crate::Known::Yes(list) = context.model.members_of(&class) else {
return None;
};
let mut every_pure_is_overridden = true;
for member in list.members.iter().filter(|member| {
member.fact.kind == crate::DeclKind::Function
&& member.fact.modifiers.contains(crate::DeclModifiers::PURE)
}) {
let overridden = list.members.iter().any(|other| {
other.fact.kind == crate::DeclKind::Function
&& other.fact.name == member.fact.name
&& other.depth < member.depth
&& !other.fact.modifiers.contains(crate::DeclModifiers::PURE)
});
if !overridden {
every_pure_is_overridden = false;
break;
}
}
Some(!every_pure_is_overridden)
});
if is_abstract == Some(true) {
context.add_in_the_file(
DiagnosticCode::AbstractClassInstantiated,
name_range,
name.clone(),
t!(
"`%{name}` has type `%{class}`, which is abstract — a pure virtual function of it is declared `= 0` and nothing overrides it, so the class cannot be instantiated",
name = name,
class = class
),
);
}
}
}
}
fn a_class_name(spelling: &str) -> Option<String> {
let spelling = spelling.trim();
if spelling.is_empty() || spelling.contains(['*', '&', '[', '(', ')', '<', '>', ',', '.']) {
return None;
}
let name = spelling.rsplit("::").next()?.trim();
if name.is_empty()
|| !name.starts_with(|first: char| first.is_ascii_alphabetic() || first == '_')
{
return None;
}
(!spelling.contains(' ')).then(|| name.to_string())
}