use super::{Check, CheckContext, DiagnosticCode};
pub struct ContractPlacement;
impl Check for ContractPlacement {
const CODES: &'static [DiagnosticCode] = &[
DiagnosticCode::ContractOnVirtualFunction,
DiagnosticCode::ContractOnDefaultedFunction,
];
fn check(context: &mut CheckContext<'_>) {
std::fs::write(
"E:/cpp_ls/target/check-ran.txt",
format!("ran with c={}", context.is_c()),
)
.ok();
let mut contracted: Vec<(String, cpp_parser::SourceRange)> = Vec::new();
for node in context.own_syntax_nodes() {
if cpp_parser::CppSyntaxKind::from(node.kind())
!= cpp_parser::CppSyntaxKind::ContractSpecifierSeq
{
continue;
}
let Some(declarator) = node.ancestors().find(|ancestor| {
cpp_parser::CppSyntaxKind::from(ancestor.kind())
== cpp_parser::CppSyntaxKind::Declarator
}) else {
continue;
};
let Some(name) = declarator
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.find(|token| {
cpp_parser::CppTokenKind::from(token.kind())
== cpp_parser::CppTokenKind::Identifier
})
else {
continue;
};
let Some(in_the_file) = context
.view
.file_range_of(cpp_parser::source_range(name.text_range()))
else {
continue;
};
contracted.push((name.text().to_string(), in_the_file));
}
let declarations: Vec<(
String,
crate::DeclModifiers,
cpp_parser::SourceRange,
Option<String>,
)> = context
.summary
.declarations
.iter()
.filter(|fact| fact.kind == crate::DeclKind::Function)
.map(|fact| {
(
fact.name.to_string(),
fact.modifiers,
fact.name_range,
fact.scope.clone().map(|scope| scope.to_string()),
)
})
.collect();
for (name, name_range) in &contracted {
let Some((_, modifiers, _, scope)) =
declarations.iter().find(|(declared, _, range, _)| {
declared == name && range.start_offset == name_range.start_offset
})
else {
continue;
};
if modifiers.contains(crate::DeclModifiers::VIRTUAL) {
context.add(
DiagnosticCode::ContractOnVirtualFunction,
*name_range,
name.clone(),
"a virtual function cannot have a contract specifier (C++26)",
);
continue;
}
if !modifiers.contains(crate::DeclModifiers::DEFAULTED) {
continue;
}
let first = declarations
.iter()
.filter(|(declared, _, _, declared_scope)| {
declared == name && declared_scope == scope
})
.min_by_key(|(_, _, range, _)| range.start_offset);
let is_first =
first.is_some_and(|(_, _, range, _)| range.start_offset == name_range.start_offset);
if is_first {
context.add(
DiagnosticCode::ContractOnDefaultedFunction,
*name_range,
name.clone(),
"a function defaulted on its first declaration cannot have a contract specifier (C++26)",
);
}
}
}
}