use std::path::Path;
use super::{Check, CheckContext, DiagnosticCode};
use crate::DeclKind;
pub struct MissingInclude;
impl Check for MissingInclude {
const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::MissingInclude];
fn check(context: &mut CheckContext<'_>) {
let path = context.path.to_path_buf();
let own: std::collections::HashSet<String> = context
.summary
.declarations
.iter()
.map(|fact| fact.name.clone())
.collect();
let bound: std::collections::HashSet<&str> = context
.view
.scopes
.scopes()
.iter()
.flat_map(|scope| scope.bindings.iter())
.filter_map(|binding| binding.name.identifier_text())
.collect();
let reached = context.index().include_closure(&path);
let mut reported: std::collections::HashSet<String> = std::collections::HashSet::new();
for fact in &context.summary.declarations {
if fact.local || matches!(fact.kind, DeclKind::MacroLike | DeclKind::Other) {
continue;
}
for spelling in types_this_declaration_uses(fact) {
if is_a_qualified_spelling(&spelling) {
continue;
}
for name in type_names_in(&spelling) {
if name == fact.name
|| own.contains(&name)
|| bound.contains(name.as_str())
|| is_a_qualified_spelling(&name)
|| !reported.insert(name.clone())
{
continue;
}
let Some(header) = the_candidate(context, &name, &path, &reached) else {
continue;
};
let message = format!(
"`{name}` is declared in {header}, which this file does not include"
);
context.add_in_the_file(
DiagnosticCode::MissingInclude,
fact.range,
name,
message,
);
}
}
}
}
}
fn the_candidate(
context: &CheckContext<'_>,
name: &str,
path: &Path,
reached: &std::collections::HashSet<String>,
) -> Option<String> {
let mut best: Option<(u8, String)> = None;
for (declaring, fact) in context.index().every_fact_named(name) {
if declaring == path || !is_ours(context, &declaring) {
continue;
}
if fact.kind != DeclKind::Type {
continue;
}
if reached.contains(&crate::file::paths::normalize_path(
&declaring,
cfg!(windows),
)) {
continue;
}
let rank = how_strongly_it_answers(&declaring, name, path);
if best.as_ref().is_none_or(|(known, _)| rank < *known) {
let file = declaring
.file_name()
.map(|file| file.to_string_lossy().to_string())
.unwrap_or_else(|| declaring.display().to_string());
best = Some((rank, file));
}
}
best.map(|(_, file)| file)
}
fn how_strongly_it_answers(declaring: &Path, name: &str, asking: &Path) -> u8 {
let same_directory = declaring.parent() == asking.parent();
let named_after_it = declaring.file_stem().is_some_and(|stem| {
let stem = stem.to_string_lossy().to_lowercase();
let name = name.to_lowercase();
stem == name || stem.strip_suffix('s') == Some(name.as_str())
});
match (same_directory, named_after_it) {
(true, true) => 0,
(true, false) => 1,
(false, true) => 2,
(false, false) => 3,
}
}
fn is_ours(context: &CheckContext<'_>, file: &Path) -> bool {
let file = file.to_string_lossy().to_lowercase().replace('\\', "/");
context.inside.iter().any(|root| {
let root = root.to_string_lossy().to_lowercase().replace('\\', "/");
let root = root.trim_end_matches('/');
!root.is_empty() && file.starts_with(root)
})
}
fn types_this_declaration_uses(fact: &crate::DeclFact) -> Vec<String> {
let mut spellings: Vec<String> = Vec::new();
if let Some(of) = &fact.type_of {
spellings.push(of.clone());
}
if let Some(parameters) = &fact.parameter_list {
spellings.extend(parameters.split(',').map(|one| one.trim().to_string()));
}
spellings
}
fn type_names_in(spelling: &str) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut word = String::new();
for character in spelling.chars().chain(std::iter::once(' ')) {
if character.is_alphanumeric() || character == '_' {
word.push(character);
continue;
}
if !word.is_empty() {
if !is_a_keyword(&word) {
names.push(word.clone());
}
word.clear();
}
}
names
}
fn is_a_keyword(word: &str) -> bool {
matches!(
word,
"const"
| "volatile"
| "static"
| "inline"
| "mutable"
| "explicit"
| "virtual"
| "constexpr"
| "consteval"
| "constinit"
| "extern"
| "register"
| "thread_local"
| "signed"
| "unsigned"
| "short"
| "long"
| "int"
| "char"
| "bool"
| "float"
| "double"
| "void"
| "auto"
| "wchar_t"
| "char8_t"
| "char16_t"
| "char32_t"
| "struct"
| "class"
| "union"
| "enum"
| "typename"
| "template"
| "noexcept"
| "override"
| "final"
| "and"
| "or"
| "not"
)
}
fn is_a_qualified_spelling(spelling: &str) -> bool {
spelling.contains("::")
}