use cpp_parser::{CppAstNode, CppSyntaxKind, CppTokenKind};
use super::{Check, CheckContext, DiagnosticCode};
pub struct UndefinedName;
impl Check for UndefinedName {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::UndefinedName];
fn check(context: &mut CheckContext<'_>) {
for (node, access) in context.member_accesses() {
let Some(token) = a_bare_name(&access.object) else {
continue;
};
let name = token.text().to_string();
let at = usize::from(token.text_range().start());
if matches!(CppTokenKind::from(token.kind()), CppTokenKind::ThisKeyword) {
continue;
}
if CppTokenKind::from(token.kind()) != CppTokenKind::Identifier {
continue;
}
if in_a_template(&node) || in_a_lambda(context, at) {
continue;
}
if context
.summary
.macros
.iter()
.any(|macro_fact| macro_fact.name == name)
{
continue;
}
if context.model.names_a_template_parameter(&name, at) {
continue;
}
if a_declaration_is_visible(context, &name, at) {
continue;
}
context.add(
DiagnosticCode::UndefinedName,
cpp_parser::source_range(token.text_range()),
name.clone(),
t!(
"`%{name}` is not declared: nothing this file can see names it",
name = name
),
);
}
for call in context.own::<cpp_parser::CppCallExpr>().collect::<Vec<_>>() {
let Some(callee) = call.get_callee() else {
continue;
};
let callee = callee.syntax().clone();
let call_node = call.syntax().clone();
let Some(token) = a_bare_name(&callee) else {
continue;
};
if super::member_access_above(&callee).is_some() {
continue;
}
if CppTokenKind::from(token.kind()) != CppTokenKind::Identifier {
continue;
}
let name = token.text().to_string();
let at = usize::from(token.text_range().start());
if in_a_template(&call_node) || in_a_lambda(context, at) {
continue;
}
if context
.summary
.macros
.iter()
.any(|macro_fact| macro_fact.name == name)
{
continue;
}
if context.model.names_a_template_parameter(&name, at) {
continue;
}
if is_a_keyword_construct(&name) || is_the_implementations_builtin(&name) {
continue;
}
if a_declaration_is_visible(context, &name, at) {
continue;
}
if an_argument_may_take_part_in_adl(context, &call_node) {
continue;
}
context.add(
DiagnosticCode::UndefinedName,
cpp_parser::source_range(token.text_range()),
name.clone(),
t!(
"`%{name}` is not declared: nothing this file can see names it",
name = name
),
);
}
}
}
fn an_argument_may_take_part_in_adl(
context: &CheckContext<'_>,
call: &cpp_parser::CppSyntaxNode,
) -> bool {
let Some(call_expression) = cpp_parser::CppCallExpr::cast(call.clone()) else {
return true;
};
call_expression.get_args().iter().any(|argument| {
!matches!(
context.type_of(argument.syntax()),
crate::Known::Yes((type_of, _)) if is_a_builtin_spelling(&type_of.to_string())
)
})
}
fn is_a_keyword_construct(name: &str) -> bool {
matches!(
name,
"_Static_assert"
| "static_assert"
| "_Generic"
| "_Atomic"
| "_Alignas"
| "alignas"
| "_Alignof"
| "alignof"
| "_Noreturn"
| "_Thread_local"
| "thread_local"
| "typeof"
| "typeof_unqual"
| "__typeof__"
| "__typeof"
| "_BitInt"
| "noexcept"
| "decltype"
| "sizeof"
| "offsetof"
| "_Pragma"
| "__pragma"
)
}
fn is_the_implementations_builtin(name: &str) -> bool {
name.starts_with("__builtin_")
|| name.starts_with("__sync_")
|| name.starts_with("__atomic_")
|| name.starts_with("__builtin")
|| name.starts_with("_Interlocked")
|| name.starts_with("_mm")
}
pub(super) fn is_a_builtin_spelling(written: &str) -> bool {
const BUILTIN: &[&str] = &[
"void", "bool", "char", "char8_t", "char16_t", "char32_t", "wchar_t", "short", "int",
"long", "float", "double", "signed", "unsigned",
];
written
.split(|character: char| !character.is_alphanumeric() && character != '_')
.filter(|word| !word.is_empty())
.all(|word| BUILTIN.contains(&word) || matches!(word, "const" | "volatile" | "constexpr"))
}
fn a_bare_name(object: &cpp_parser::CppSyntaxNode) -> Option<cpp_parser::CppSyntaxToken> {
let mut tokens = object
.descendants_with_tokens()
.filter_map(|element| element.into_token())
.filter(|token| {
!matches!(
CppTokenKind::from(token.kind()),
CppTokenKind::Whitespace | CppTokenKind::Newline
)
});
let token = tokens.next()?;
if tokens.next().is_some() {
return None;
}
Some(token)
}
fn in_a_template(node: &cpp_parser::CppSyntaxNode) -> bool {
for ancestor in node.ancestors() {
if CppSyntaxKind::from(ancestor.kind()) == CppSyntaxKind::TemplateDecl {
return true;
}
let Some(parent) = ancestor.parent() else {
continue;
};
if cpp_parser::CppDeclaration::can_cast(parent.kind().into())
&& parent
.children()
.any(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::TemplateDecl)
{
return true;
}
}
false
}
fn in_a_lambda(context: &CheckContext<'_>, at: usize) -> bool {
let Some(scope) = context.model.scopes().scope_at(at) else {
return false;
};
context.model.scopes().scope_chain(scope).iter().any(|id| {
context
.model
.scopes()
.scope(*id)
.is_some_and(|data| data.kind == crate::ScopeKind::Lambda)
})
}
fn a_declaration_is_visible(context: &CheckContext<'_>, name: &str, at: usize) -> bool {
let scopes = context.model.scopes();
if let Some(scope) = scopes.scope_at(at) {
for id in scopes.scopes_visible_from(scope) {
let Some(data) = scopes.scope(id) else {
continue;
};
let from_anywhere =
matches!(data.kind, crate::ScopeKind::Class | crate::ScopeKind::Enum);
for binding in &data.bindings {
if binding.name.identifier_text() != Some(name) {
continue;
}
if from_anywhere || binding.name_range.start_offset <= at {
return true;
}
}
}
}
if let Some(class) = crate::index::project::class_of_the_enclosing_definition(scopes, at)
&& let crate::Known::Yes(found) = context
.model
.index()
.definitions_in_scope(&format!("{class}::{name}"), context.path)
&& !found.found.is_empty()
{
return true;
}
match context.model.index().definitions(name, context.path) {
crate::Known::Yes(found) => found
.found
.iter()
.any(|declaration| declaration.file != context.path),
crate::Known::Unknown(crate::UnknownReason::NotDeclaredHere(_)) => false,
crate::Known::Unknown(_) => true,
crate::Known::No => false,
}
}