use std::path::{Path, PathBuf};
use crate::{
config::CompilerConfig,
directive::{Include, IncludeForm},
paths::{FileId, FileProvider, PathInterner, join_normalized, normalize_path},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolved {
pub file: FileId,
pub path: PathBuf,
pub found_in: FoundIn,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FoundIn {
LocalDirectory,
SearchPath(usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unresolved {
pub name: Box<str>,
pub searched: Vec<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
Resolved(Resolved),
Unresolved(Unresolved),
}
impl Resolution {
pub fn resolved(&self) -> Option<&Resolved> {
match self {
Resolution::Resolved(resolved) => Some(resolved),
Resolution::Unresolved(_) => None,
}
}
pub fn is_resolved(&self) -> bool {
matches!(self, Resolution::Resolved(_))
}
}
fn include_roots_above<F: FileProvider>(directory: &Path, files: &F) -> Vec<PathBuf> {
const LEVELS: usize = 6;
let mut roots = Vec::new();
let mut at = Some(directory);
for _ in 0..LEVELS {
let Some(current) = at else { break };
let candidate = current.join("include");
if files.exists(&candidate) {
roots.push(candidate);
}
at = current.parent();
}
roots
}
pub struct IncludeResolver<'a, F: FileProvider> {
files: &'a F,
config: &'a CompilerConfig,
}
impl<'a, F: FileProvider> IncludeResolver<'a, F> {
pub fn new(files: &'a F, config: &'a CompilerConfig) -> Self {
IncludeResolver { files, config }
}
pub fn files(&self) -> &'a F {
self.files
}
pub fn config(&self) -> &'a CompilerConfig {
self.config
}
pub fn resolve(
&self,
include: &Include,
including: &Path,
origin: Option<&FoundIn>,
interner: &mut PathInterner,
) -> Resolution {
let name = Path::new(&*include.target);
let mut searched = Vec::new();
if include.form == IncludeForm::Macro {
return Resolution::Unresolved(Unresolved {
name: include.target.clone(),
searched,
});
}
if name.is_absolute() {
if let Some(path) = self.existing(name) {
return Resolution::Resolved(self.resolved(
path,
FoundIn::LocalDirectory,
interner,
));
}
searched.push(name.to_path_buf());
return Resolution::Unresolved(Unresolved {
name: include.target.clone(),
searched,
});
}
let mut candidates: Vec<(PathBuf, FoundIn)> = Vec::new();
let skip_through = if include.is_next {
origin.map(|origin| match origin {
FoundIn::LocalDirectory => 0usize,
FoundIn::SearchPath(index) => index + 1,
})
} else {
None
};
if include.form == IncludeForm::Quote && skip_through.is_none() {
candidates.push((
join_normalized(including, name, self.case_insensitive()),
FoundIn::LocalDirectory,
));
}
for root in include_roots_above(including, self.files) {
candidates.push((
join_normalized(&root, name, self.case_insensitive()),
FoundIn::LocalDirectory,
));
}
for (index, include_path) in self.config.include_paths.iter().enumerate() {
if skip_through.is_some_and(|skip| index < skip) {
continue;
}
let directory = self
.config
.resolve_against_working_directory(&include_path.directory);
candidates.push((
join_normalized(&directory, name, self.case_insensitive()),
FoundIn::SearchPath(index),
));
}
for (candidate, found_in) in candidates {
if let Some(path) = self.existing(&candidate) {
return Resolution::Resolved(self.resolved(path, found_in, interner));
}
searched.push(candidate);
}
if self.config.fuzzy_includes
&& let Some(root) = &self.config.root
&& let Some(index) = fuzzy::index_for(root)
{
let matches = index.matching(&include.target);
if let Some(chosen) = matches.first() {
return Resolution::Resolved(self.resolved(
chosen.clone(),
FoundIn::LocalDirectory,
interner,
));
}
}
Resolution::Unresolved(Unresolved {
name: include.target.clone(),
searched,
})
}
fn existing(&self, candidate: &Path) -> Option<PathBuf> {
if self.files.exists(candidate) {
return Some(candidate.to_path_buf());
}
if self.case_insensitive() {
let lowered = normalize_path(candidate, true);
let lowered = Path::new(&lowered);
if self.files.exists(lowered) {
return Some(lowered.to_path_buf());
}
}
None
}
fn resolved(&self, path: PathBuf, found_in: FoundIn, interner: &mut PathInterner) -> Resolved {
let file = interner.intern(&path);
Resolved {
file,
path,
found_in,
}
}
fn case_insensitive(&self) -> bool {
self.files.is_case_insensitive()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{config::IncludePath, paths::MemoryFiles};
fn project() -> MemoryFiles {
MemoryFiles::new()
.with_case_insensitive(false)
.with_file("src/main.cpp", "")
.with_file("src/local.h", "local")
.with_file("user/vector", "user's vector")
.with_file("system/vector", "system's vector")
.with_file("system/stdio.h", "stdio")
}
fn config() -> CompilerConfig {
CompilerConfig::new()
.with_include_path("user")
.with_system_include_path("system")
}
fn resolve(
name: &str,
form: IncludeForm,
including: &str,
case_insensitive: bool,
) -> Resolution {
let files = project().with_case_insensitive(case_insensitive);
let config = config();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(case_insensitive);
let include = Include {
form,
target: name.into(),
is_next: false,
};
let mut resolution = resolver.resolve(&include, Path::new(including), None, &mut interner);
if let Resolution::Resolved(resolved) = &mut resolution {
resolved.path = PathBuf::from(normalize_path(&resolved.path, case_insensitive));
}
resolution
}
mod fuzzy_fallback {
use crate::include::fuzzy;
use crate::{CompilerConfig, DiskFiles, IncludeResolver};
use super::{Include, IncludeForm, PathInterner, Resolution};
fn project(name: &str, files: &[&str]) -> (std::path::PathBuf, CompilerConfig) {
let root = std::env::temp_dir().join("cppls-include-fuzzy").join(name);
let _ = std::fs::remove_dir_all(&root);
for file in files {
let path = root.join(file);
std::fs::create_dir_all(path.parent().expect("a parent")).expect("a directory");
std::fs::write(&path, "// a header\n").expect("a file");
}
fuzzy::forget_everything();
let config = CompilerConfig {
root: Some(root.clone()),
fuzzy_includes: true,
..CompilerConfig::new()
};
(root, config)
}
fn resolve(name: &str, config: &CompilerConfig) -> Option<std::path::PathBuf> {
let resolver = IncludeResolver::new(&DiskFiles, config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Quote,
target: name.into(),
is_next: false,
};
match resolver.resolve(
&include,
std::path::Path::new("/nowhere"),
None,
&mut interner,
) {
Resolution::Resolved(resolved) => Some(resolved.path),
Resolution::Unresolved(_) => None,
}
}
#[test]
fn a_header_nothing_could_place_is_found_by_its_tail() {
let (root, config) = project(
"tail",
&["CodeFormatServer/include/Session/StandardIOSession.h"],
);
let found = resolve("Session/StandardIOSession.h", &config).expect("found by its tail");
assert_eq!(
found,
root.join("CodeFormatServer/include/Session/StandardIOSession.h")
);
}
#[test]
fn an_exact_include_directory_is_never_shadowed() {
let (root, mut config) =
project("shadow", &["named/Widget.h", "elsewhere/named/Widget.h"]);
config
.include_paths
.push(crate::config::IncludePath::user(root.join("named")));
let found = resolve("Widget.h", &config).expect("the search path found it");
assert!(
found.to_string_lossy().to_lowercase().replace('\\', "/")
== root
.join("named/Widget.h")
.to_string_lossy()
.to_lowercase()
.replace('\\', "/"),
"the search path placed it: {found:?}"
);
let strict = CompilerConfig {
include_paths: config.include_paths.clone(),
..CompilerConfig::new()
};
assert_eq!(resolve("Session/Absent.h", &strict), None);
}
#[test]
fn a_bare_name_is_left_to_the_search_path() {
let (_, config) = project("bare", &["a/vector", "b/vector", "c/stdio.h"]);
assert_eq!(resolve("vector", &config), None);
assert_eq!(resolve("stdio.h", &config), None);
}
#[test]
fn the_flag_off_means_no_fallback_at_all() {
let (_root, config) = project("off", &["include/Session/IOSession.h"]);
let strict = CompilerConfig {
root: config.root.clone(),
fuzzy_includes: false,
..CompilerConfig::new()
};
assert_eq!(resolve("Session/IOSession.h", &strict), None);
assert!(resolve("Session/IOSession.h", &config).is_some());
}
}
#[test]
fn a_quoted_include_prefers_the_files_own_directory() {
let resolution = resolve("local.h", IncludeForm::Quote, "src", false);
assert_eq!(
resolution.resolved().map(|it| it.path.as_path()),
Some(Path::new("src/local.h"))
);
assert_eq!(
resolution.resolved().map(|it| &it.found_in),
Some(&FoundIn::LocalDirectory)
);
}
#[test]
fn a_quoted_include_falls_back_to_the_search_paths() {
let resolution = resolve("stdio.h", IncludeForm::Quote, "src", false);
assert_eq!(
resolution.resolved().map(|it| it.path.as_path()),
Some(Path::new("system/stdio.h"))
);
assert_eq!(
resolution.resolved().map(|it| &it.found_in),
Some(&FoundIn::SearchPath(1))
);
}
#[test]
fn an_angled_include_does_not_search_the_files_own_directory() {
let resolution = resolve("local.h", IncludeForm::Angle, "src", false);
assert!(
!resolution.is_resolved(),
"`src/local.h` exists but must not be found: {resolution:?}"
);
assert_eq!(
resolution,
Resolution::Unresolved(Unresolved {
name: "local.h".into(),
searched: vec![
PathBuf::from("user/local.h"),
PathBuf::from("system/local.h")
],
})
);
}
#[test]
fn a_user_path_shadows_a_system_path() {
let resolution = resolve("vector", IncludeForm::Angle, "src", false);
assert_eq!(
resolution.resolved().map(|it| it.path.as_path()),
Some(Path::new("user/vector"))
);
assert_eq!(
resolution.resolved().map(|it| &it.found_in),
Some(&FoundIn::SearchPath(0))
);
}
#[test]
fn an_unresolved_include_lists_what_was_searched() {
let resolution = resolve("missing.h", IncludeForm::Quote, "src", false);
match resolution {
Resolution::Unresolved(unresolved) => {
assert_eq!(&*unresolved.name, "missing.h");
assert_eq!(
unresolved.searched,
vec![
PathBuf::from("src/missing.h"),
PathBuf::from("user/missing.h"),
PathBuf::from("system/missing.h"),
]
);
}
Resolution::Resolved(resolved) => panic!("expected a failure, got {resolved:?}"),
}
}
#[test]
fn a_macro_include_is_unresolved_and_searches_nothing() {
let resolution = resolve("BOOST_HEADER", IncludeForm::Macro, "src", false);
assert_eq!(
resolution,
Resolution::Unresolved(Unresolved {
name: "BOOST_HEADER".into(),
searched: Vec::new(),
})
);
}
#[test]
fn include_next_continues_past_the_current_file() {
let files = MemoryFiles::new()
.with_file("user/vector", "the wrapper")
.with_file("system/vector", "the real one");
let config = config();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Angle,
target: "vector".into(),
is_next: true,
};
let resolution = resolver.resolve(
&include,
Path::new("src"),
Some(&FoundIn::SearchPath(0)),
&mut interner,
);
assert_eq!(
resolution
.resolved()
.map(|it| normalize_path(&it.path, false)),
Some("system/vector".to_string())
);
}
#[test]
fn an_ordinary_include_finds_the_wrapper() {
let files = MemoryFiles::new()
.with_file("user/vector", "the wrapper")
.with_file("system/vector", "the real one");
let config = config();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Angle,
target: "vector".into(),
is_next: false,
};
let resolution = resolver.resolve(
&include,
Path::new("src"),
Some(&FoundIn::SearchPath(0)),
&mut interner,
);
assert_eq!(
resolution
.resolved()
.map(|it| normalize_path(&it.path, false)),
Some("user/vector".to_string())
);
}
#[test]
fn two_routes_to_one_file_produce_one_id() {
let files = project();
let config = config();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let quoted = Include {
form: IncludeForm::Quote,
target: "stdio.h".into(),
is_next: false,
};
let angled = Include {
form: IncludeForm::Angle,
target: "stdio.h".into(),
is_next: false,
};
let first = resolver.resolve("ed, Path::new("src"), None, &mut interner);
let second = resolver.resolve(&angled, Path::new("src"), None, &mut interner);
assert_eq!(
first.resolved().map(|it| it.file),
second.resolved().map(|it| it.file)
);
assert_eq!(interner.len(), 1);
}
#[test]
fn a_relative_search_path_resolves_against_the_working_directory() {
let files = MemoryFiles::new().with_file("build/inc/a.h", "found");
let config = CompilerConfig::new()
.with_include_path("inc")
.with_working_directory("build");
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Angle,
target: "a.h".into(),
is_next: false,
};
let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
assert_eq!(
resolution
.resolved()
.map(|it| normalize_path(&it.path, false)),
Some("build/inc/a.h".to_string())
);
}
#[test]
fn an_absolute_target_is_tried_only_as_written() {
let files = project();
let config = config();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let absolute = std::env::temp_dir().join("definitely-not-here-a1b2c3.h");
let name: Box<str> = absolute.to_string_lossy().into_owned().into();
let include = Include {
form: IncludeForm::Angle,
target: name.clone(),
is_next: false,
};
let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
assert_eq!(
resolution,
Resolution::Unresolved(Unresolved {
name,
searched: vec![absolute],
}),
"the target was tried as written and nothing else was"
);
}
#[test]
fn a_relative_target_is_searched_for() {
let resolution = resolve("nope.h", IncludeForm::Angle, "src", false);
match resolution {
Resolution::Unresolved(unresolved) => assert_eq!(
unresolved.searched,
vec![PathBuf::from("user/nope.h"), PathBuf::from("system/nope.h")],
"every search directory was tried"
),
Resolution::Resolved(resolved) => panic!("expected a failure, got {resolved:?}"),
}
}
#[test]
fn an_empty_configuration_still_finds_neighbours() {
let files = MemoryFiles::new().with_file("src/a.h", "found");
let config = CompilerConfig::new();
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Quote,
target: "a.h".into(),
is_next: false,
};
let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
assert!(resolution.is_resolved(), "{resolution:?}");
}
#[test]
fn an_include_path_with_a_trailing_separator_still_matches() {
let files = MemoryFiles::new().with_file("user/a.h", "found");
let config = CompilerConfig {
include_paths: vec![IncludePath::user("user/")],
..CompilerConfig::default()
};
let resolver = IncludeResolver::new(&files, &config);
let mut interner = PathInterner::new(false);
let include = Include {
form: IncludeForm::Angle,
target: "a.h".into(),
is_next: false,
};
let resolution = resolver.resolve(&include, Path::new("src"), None, &mut interner);
assert!(resolution.is_resolved(), "{resolution:?}");
}
}
pub mod config;
pub mod fuzzy;
pub mod graph;
pub mod msvc;
pub mod system_headers;
pub mod toolchain;
pub use crate::file::paths;