use cpp_parser::CppAstNode;
use super::unreal::{annotated_declarations, the_type_written_before};
use super::{Check, CheckContext, DiagnosticCode};
pub struct UeNaming;
impl Check for UeNaming {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::UeNaming];
fn check(context: &mut CheckContext<'_>) {
for (annotating, prefixes, what) in [
("UCLASS", &["U", "A"][..], "a class"),
("USTRUCT", &["F"][..], "a struct"),
("UENUM", &["E"][..], "an enumeration"),
("UINTERFACE", &["U", "I"][..], "an interface"),
] {
for annotated in annotated_declarations(context, &[annotating]) {
let spelling = annotated.name.clone();
if prefixes.iter().any(|prefix| spelling.starts_with(prefix)) {
continue;
}
context.add_in_the_file(
DiagnosticCode::UeNaming,
annotated.name_in_the_file,
spelling.clone(),
format!(
"`{spelling}` is {what} under `{annotating}`, and Unreal's prefix for one is `{}` — `{}{spelling}` \
is the engine's own convention",
prefixes.join("` or `"),
prefixes[0]
),
);
}
}
let bodies: Vec<cpp_parser::CppSyntaxNode> = context
.own::<cpp_parser::CppClassBody>()
.map(|body| body.syntax().clone())
.collect();
for body in bodies {
for declaration in body.children() {
if !cpp_parser::CppDeclaration::can_cast(declaration.kind().into()) {
continue;
}
let Some((name, spelled)) = bool_member(context, &declaration) else {
continue;
};
if spelled.starts_with('b')
&& spelled.chars().nth(1).is_some_and(char::is_uppercase)
{
continue;
}
let in_the_file = context.in_the_file(cpp_parser::source_range(name.text_range()));
let suggested = spelled
.chars()
.next()
.map(|first| {
format!("b{}{}", first.to_uppercase(), &spelled[first.len_utf8()..])
})
.unwrap_or_default();
context.add_in_the_file(
DiagnosticCode::UeNaming,
in_the_file,
spelled.clone(),
format!(
"`{spelled}` is a boolean member, and Unreal spells one `b` followed by a capital — \
`{suggested}`"
),
);
}
}
}
}
fn bool_member(
context: &CheckContext<'_>,
declaration: &cpp_parser::CppSyntaxNode,
) -> Option<(cpp_parser::CppSyntaxNode, String)> {
let declarator = declaration
.children()
.find(|child| cpp_parser::CppInitDeclarator::can_cast(child.kind().into()))
.and_then(|init| {
init.children()
.find(|child| cpp_parser::CppDeclarator::can_cast(child.kind().into()))
})?;
if declarator
.children()
.any(|child| cpp_parser::CppParamList::can_cast(child.kind().into()))
{
return None;
}
let name = declarator
.children()
.find(|child| cpp_parser::CppNameExpr::can_cast(child.kind().into()))?;
let start = context
.in_the_file(cpp_parser::source_range(declaration.text_range()))
.start_offset;
let name_start = context
.in_the_file(cpp_parser::source_range(name.text_range()))
.start_offset;
let written = the_type_written_before(context.written, start, name_start)?;
let head = written.split('<').next().unwrap_or_default().trim();
let head = head.strip_prefix("const ").unwrap_or(head).trim();
if head != "bool" {
return None;
}
Some((name.clone(), name.text().to_string()))
}