use cpp_parser::CppAstNode;
use cpp_parser::CppSyntaxKind;
use super::borrowed::{Borrowed, Origin, origin_of, view_name_of};
use super::{Check, CheckContext, DiagnosticCode};
pub struct DanglingField;
impl Check for DanglingField {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::DanglingField];
fn check(context: &mut CheckContext<'_>) {
let bodies: Vec<cpp_parser::CppSyntaxNode> = context
.own::<cpp_parser::CppClassBody>()
.map(|body| body.syntax().clone())
.collect();
for body in bodies {
let Some(class_name) = the_class_name(&body) else {
continue;
};
let members = borrowing_members(context, &body);
if members.is_empty() {
continue;
}
for declaration in direct_children_of_kind(&body, CppSyntaxKind::Declaration) {
let Some((name, _)) = the_member_type(context, &declaration) else {
continue;
};
let Some(borrowing) = members.get(&name) else {
continue;
};
let Some(initializer) = declaration
.children()
.find(|child| kind(child) == CppSyntaxKind::InitDeclarator)
.and_then(|init| {
init.children()
.find(|child| kind(child) == CppSyntaxKind::Initializer)
})
else {
continue;
};
let Some(expression) = initializer.children().next() else {
continue;
};
let Some(borrowed) = origin_of(context, &expression, &declaration) else {
continue;
};
if let Some(message) = the_message(borrowing, &borrowed, &name, "initialised from")
{
let range = cpp_parser::source_range(expression.text_range());
context.add(DiagnosticCode::DanglingField, range, name, message);
}
}
for constructor in constructors_of(&body, &class_name) {
let Some(body_of_the_constructor) = constructor
.children()
.find(|child| kind(child) == CppSyntaxKind::CompoundStat)
else {
continue;
};
for initializer in member_initialisers_of(&constructor) {
let Some(member_name) = initializer
.children()
.find(|child| kind(child) == CppSyntaxKind::NameExpr)
.map(|name| name.text().to_string())
else {
continue;
};
let Some(borrowing) = members.get(&member_name) else {
continue;
};
let Some(argument) = the_initialiser_expression(&initializer) else {
continue;
};
let Some(borrowed) = origin_of(context, &argument, &body_of_the_constructor)
else {
continue;
};
if let Some(message) =
the_message(borrowing, &borrowed, &member_name, "initialised from")
{
let range = cpp_parser::source_range(argument.text_range());
context.add(DiagnosticCode::DanglingField, range, member_name, message);
}
}
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Borrowing {
View(String),
Reference,
Pointer,
}
fn the_class_name(body: &cpp_parser::CppSyntaxNode) -> Option<String> {
let class = body.parent()?;
if !matches!(
kind(&class),
CppSyntaxKind::ClassDef | CppSyntaxKind::StructDef | CppSyntaxKind::UnionDef
) {
return None;
}
class
.children()
.find(|child| kind(child) == CppSyntaxKind::NameExpr)
.map(|name| name.text().to_string())
}
fn borrowing_members(
context: &CheckContext<'_>,
body: &cpp_parser::CppSyntaxNode,
) -> std::collections::BTreeMap<String, Borrowing> {
let mut members = std::collections::BTreeMap::new();
for declaration in direct_children_of_kind(body, CppSyntaxKind::Declaration) {
if let Some((name, borrowing)) = the_member_type(context, &declaration) {
members.insert(name, borrowing);
}
}
members
}
fn the_member_type(
context: &CheckContext<'_>,
declaration: &cpp_parser::CppSyntaxNode,
) -> Option<(String, Borrowing)> {
let declarator = declaration
.children()
.find(|child| kind(child) == CppSyntaxKind::InitDeclarator)
.and_then(|init| {
init.children()
.find(|child| kind(child) == CppSyntaxKind::Declarator)
})?;
let name = declarator
.children()
.find(|child| kind(child) == CppSyntaxKind::NameExpr)?;
let start = usize::from(declaration.text_range().start());
let name_start = usize::from(name.text_range().start());
let prefix = context.source.get(start..name_start)?;
let head = prefix.split('<').next().unwrap_or_default();
let borrowing = if head.contains('&') {
Borrowing::Reference
} else if head.contains('*') {
Borrowing::Pointer
} else {
Borrowing::View(view_name_of(head)?)
};
Some((name.text().to_string(), borrowing))
}
fn constructors_of(
body: &cpp_parser::CppSyntaxNode,
class_name: &str,
) -> Vec<cpp_parser::CppSyntaxNode> {
direct_children_of_kind(body, CppSyntaxKind::Declaration)
.into_iter()
.filter(|declaration| {
declaration.children().all(|child| {
kind(&child) != CppSyntaxKind::DeclSpecifierSeq
&& kind(&child) != CppSyntaxKind::InitDeclarator
}) && declaration
.children()
.any(|child| kind(&child) == CppSyntaxKind::CompoundStat)
&& declaration.children().any(|child| {
kind(&child) == CppSyntaxKind::Declaration
&& the_declared_name(&child).as_deref() == Some(class_name)
})
})
.collect()
}
fn the_declared_name(declaration: &cpp_parser::CppSyntaxNode) -> Option<String> {
declaration
.children()
.find(|child| kind(child) == CppSyntaxKind::Declarator)
.and_then(|declarator| {
declarator
.children()
.find(|child| kind(child) == CppSyntaxKind::NameExpr)
})
.map(|name| name.text().to_string())
}
fn member_initialisers_of(
constructor: &cpp_parser::CppSyntaxNode,
) -> Vec<cpp_parser::CppSyntaxNode> {
let mut found = Vec::new();
for child in constructor.children() {
if kind(&child) == CppSyntaxKind::Declaration {
found.extend(direct_children_of_kind(
&child,
CppSyntaxKind::MemberInitializer,
));
} else if kind(&child) == CppSyntaxKind::MemberInitializer {
found.push(child);
}
}
found
}
fn the_initialiser_expression(
initializer: &cpp_parser::CppSyntaxNode,
) -> Option<cpp_parser::CppSyntaxNode> {
for child in initializer.children() {
match kind(&child) {
CppSyntaxKind::NameExpr => continue,
_ => {
return match kind(&child) {
CppSyntaxKind::ArgumentList | CppSyntaxKind::Initializer => {
child.children().next()
}
_ => Some(child),
};
}
}
}
None
}
fn the_message(
borrowing: &Borrowing,
borrowed: &Borrowed,
member: &str,
verb: &str,
) -> Option<String> {
if !matches!(borrowed.kind, Origin::ByValueParameter | Origin::Temporary) {
return None;
}
let described = match borrowing {
Borrowing::View(view) => view.as_str(),
Borrowing::Reference => "reference",
Borrowing::Pointer => "pointer",
};
match (borrowing, borrowed.kind) {
(Borrowing::Pointer, Origin::ByValueParameter)
if !borrowed.address_of && borrowed.through.is_none() =>
{
None
}
(Borrowing::Pointer, Origin::Temporary)
if !borrowed.address_of && borrowed.through.is_none() =>
{
None
}
(_, Origin::ByValueParameter) => Some(format!(
"`{member}` is a `{described}` {verb} `{name}`, a parameter that is destroyed when the constructor returns",
name = borrowed.description
)),
(Borrowing::Pointer, Origin::Temporary) => Some(format!(
"`{member}` is a pointer {verb} a temporary, which is destroyed at the end of the statement",
)),
(_, Origin::Temporary) => Some(format!(
"`{member}` is a `{described}` {verb} a temporary, which is destroyed at the end of the statement",
)),
_ => None,
}
}
fn direct_children_of_kind(
node: &cpp_parser::CppSyntaxNode,
wanted: CppSyntaxKind,
) -> Vec<cpp_parser::CppSyntaxNode> {
node.children()
.filter(|child| kind(child) == wanted)
.collect()
}
fn kind(node: &cpp_parser::CppSyntaxNode) -> CppSyntaxKind {
CppSyntaxKind::from(node.kind())
}