use std::path::{Path, PathBuf};
use cpp_parser::Dialect;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludePath {
pub directory: PathBuf,
pub is_system: bool,
}
impl IncludePath {
pub fn user(directory: impl Into<PathBuf>) -> Self {
IncludePath {
directory: directory.into(),
is_system: false,
}
}
pub fn system(directory: impl Into<PathBuf>) -> Self {
IncludePath {
directory: directory.into(),
is_system: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandLineMacro {
pub name: Box<str>,
pub value: Option<Box<str>>,
}
impl CommandLineMacro {
pub fn defined(name: impl Into<Box<str>>) -> Self {
CommandLineMacro {
name: name.into(),
value: None,
}
}
pub fn with_value(name: impl Into<Box<str>>, value: impl Into<Box<str>>) -> Self {
CommandLineMacro {
name: name.into(),
value: Some(value.into()),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompilerConfig {
pub database: Option<std::sync::Arc<CompileCommands>>,
pub remove_args: Vec<String>,
pub extra_args: Vec<String>,
pub targets: Vec<crate::project::TargetSection>,
pub libraries: Vec<crate::project::LibrarySection>,
pub include_paths: Vec<IncludePath>,
pub defines: Vec<CommandLineMacro>,
pub undefines: Vec<Box<str>>,
pub standard: Option<Box<str>>,
pub target: Option<Box<str>>,
pub dialect: Dialect,
pub cuda: bool,
pub working_directory: Option<PathBuf>,
pub root: Option<PathBuf>,
pub fuzzy_includes: bool,
}
impl CompilerConfig {
pub fn language_for(&self, file: &Path) -> cpp_parser::features::LanguageConfig {
let from_the_command = self
.database
.as_ref()
.and_then(|database| database.command_for(file))
.and_then(|command| {
cpp_parser::features::LanguageConfig::from_command_line(command.arguments.iter())
});
let agrees_with_the_file = |language: &cpp_parser::features::LanguageConfig| {
use cpp_parser::features::Family;
match file.extension().and_then(|extension| extension.to_str()) {
Some("c") | Some("i") => language.family() != Some(Family::Cpp),
_ => true,
}
};
from_the_command
.or_else(|| {
self.standard
.as_deref()
.and_then(cpp_parser::features::LanguageConfig::from_standard_spelling)
.filter(agrees_with_the_file)
})
.or_else(|| {
cpp_parser::features::LanguageConfig::from_command_line(self.extra_args.iter())
.filter(agrees_with_the_file)
})
.or_else(|| {
matches!(
file.extension().and_then(|extension| extension.to_str()),
Some("c") | Some("i")
)
.then(cpp_parser::features::LanguageConfig::c)
})
.unwrap_or_else(cpp_parser::features::LanguageConfig::permissive)
}
pub fn for_file(&self, file: &Path) -> CompilerConfig {
self.for_file_with(file, &mut |path| std::fs::read_to_string(path).ok())
}
pub fn for_file_with(
&self,
file: &Path,
read: &mut dyn FnMut(&Path) -> Option<String>,
) -> CompilerConfig {
let Some(root) = self.root.clone() else {
return self.clone();
};
let mut config = self.clone();
let mut ahead: Vec<IncludePath> = Vec::new();
if let Some(command) = self
.database
.as_ref()
.and_then(|database| database.command_for(file))
{
let arguments: Vec<String> = command
.arguments
.iter()
.filter(|argument| !self.remove_args.iter().any(|drop| drop == *argument))
.cloned()
.chain(self.extra_args.iter().cloned())
.collect();
let arguments = expand_response_files(&arguments, command.directory.as_deref(), read);
let own = config_from_arguments(&arguments, command.directory.clone());
let system: Vec<IncludePath> = config
.include_paths
.iter()
.filter(|path| path.is_system)
.cloned()
.collect();
config.include_paths = own.include_paths;
for path in system {
let known = config
.include_paths
.iter()
.any(|held| held.directory == path.directory);
if !known {
config.include_paths.push(path);
}
}
}
let mut describing: Vec<(
usize,
std::cmp::Reverse<usize>,
&crate::project::TargetSection,
)> = self
.targets
.iter()
.enumerate()
.filter_map(|(order, target)| {
target
.describes(&root, file)
.map(|specific| (specific, std::cmp::Reverse(order), target))
})
.collect();
describing.sort_by_key(|(specific, order, _)| (std::cmp::Reverse(*specific), *order));
for (_, _, target) in describing {
for dependency in &target.depends {
let Some(library) = self
.libraries
.iter()
.find(|library| &library.name == dependency)
else {
continue;
};
for directory in library.include_directories(&root) {
if !config
.include_paths
.iter()
.any(|held| held.directory == directory)
&& !ahead.iter().any(|held| held.directory == directory)
{
ahead.push(IncludePath::user(&directory));
}
}
for definition in &library.defines {
if !config.defines.iter().any(|held| {
held.name.as_ref() == definition.split('=').next().unwrap_or("").trim()
}) {
config.defines.push(define_from_a_config_file(definition));
}
}
}
for directory in &target.includes {
let joined = root.join(directory);
if !config
.include_paths
.iter()
.any(|held| held.directory == joined)
&& !ahead.iter().any(|held| held.directory == joined)
{
ahead.push(IncludePath::user(&joined));
}
}
for definition in &target.defines {
if !config.defines.iter().any(|held| {
held.name.as_ref() == definition.split('=').next().unwrap_or("").trim()
}) {
config.defines.push(define_from_a_config_file(definition));
}
}
if config.standard.is_none()
&& let Some(standard) = &target.standard
{
config.standard = Some(standard.as_str().into());
}
}
ahead.extend(config.include_paths);
config.include_paths = ahead;
config
}
pub fn new() -> Self {
Self::default()
}
pub fn with_include_path(mut self, directory: impl Into<PathBuf>) -> Self {
self.include_paths.push(IncludePath::user(directory));
self
}
pub fn with_system_include_path(mut self, directory: impl Into<PathBuf>) -> Self {
self.include_paths.push(IncludePath::system(directory));
self
}
pub fn with_define(mut self, definition: CommandLineMacro) -> Self {
self.defines.push(definition);
self
}
pub fn with_standard(mut self, standard: impl Into<Box<str>>) -> Self {
self.standard = Some(standard.into());
self
}
pub fn with_target(mut self, target: impl Into<Box<str>>) -> Self {
self.target = Some(target.into());
self
}
pub fn with_dialect(mut self, dialect: Dialect) -> Self {
self.dialect = dialect;
self
}
pub fn dialect(&self) -> Dialect {
self.dialect
}
pub fn with_cuda(mut self, cuda: bool) -> Self {
self.cuda = cuda;
self
}
pub fn cuda(&self) -> bool {
self.cuda
}
pub fn with_working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
self.working_directory = Some(directory.into());
self
}
pub fn is_empty(&self) -> bool {
self.include_paths.is_empty()
&& self.defines.is_empty()
&& self.undefines.is_empty()
&& self.standard.is_none()
&& self.target.is_none()
&& self.working_directory.is_none()
}
pub fn user_include_paths(&self) -> impl Iterator<Item = &Path> {
self.include_paths
.iter()
.filter(|path| !path.is_system)
.map(|path| path.directory.as_path())
}
pub fn system_include_paths(&self) -> impl Iterator<Item = &Path> {
self.include_paths
.iter()
.filter(|path| path.is_system)
.map(|path| path.directory.as_path())
}
pub fn resolve_against_working_directory(&self, path: &Path) -> PathBuf {
if path.is_absolute() {
return path.to_path_buf();
}
match &self.working_directory {
Some(directory) => directory.join(path),
None => path.to_path_buf(),
}
}
pub fn search_order(&self) -> impl Iterator<Item = (&Path, bool)> {
self.include_paths
.iter()
.map(|path| (path.directory.as_path(), path.is_system))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileCommand {
pub file: PathBuf,
pub directory: Option<PathBuf>,
pub arguments: Vec<String>,
}
impl CompileCommand {
pub fn to_config(&self) -> CompilerConfig {
config_from_arguments(&self.arguments, self.directory.clone())
}
pub fn to_config_with(&self, read: &mut dyn FnMut(&Path) -> Option<String>) -> CompilerConfig {
let arguments = expand_response_files(&self.arguments, self.directory.as_deref(), read);
config_from_arguments(&arguments, self.directory.clone())
}
}
pub fn expand_response_files(
arguments: &[String],
working_directory: Option<&Path>,
read: &mut dyn FnMut(&Path) -> Option<String>,
) -> Vec<String> {
const DEEPEST: usize = 8;
let mut expanded = Vec::with_capacity(arguments.len());
let mut pending: Vec<(String, usize)> = arguments
.iter()
.rev()
.map(|argument| (argument.clone(), 0usize))
.collect();
while let Some((argument, depth)) = pending.pop() {
let Some(name) = argument.strip_prefix('@').filter(|name| !name.is_empty()) else {
expanded.push(argument);
continue;
};
let named = Path::new(name);
let resolved = match (named.is_absolute(), working_directory) {
(true, _) | (false, None) => named.to_path_buf(),
(false, Some(directory)) => directory.join(named),
};
let Some(text) = read(&resolved).filter(|_| depth < DEEPEST) else {
expanded.push(argument);
continue;
};
for inner in split_command_line(&text).into_iter().rev() {
pending.push((inner, depth + 1));
}
}
expanded
}
pub fn config_from_arguments(
arguments: &[String],
working_directory: Option<PathBuf>,
) -> CompilerConfig {
let mut config = CompilerConfig {
working_directory,
..CompilerConfig::default()
};
let mut index = 0;
while index < arguments.len() {
let argument = arguments[index].as_str();
index += 1;
let take_value = |index: &mut usize| -> Option<&str> {
let value = arguments.get(*index).map(String::as_str);
if value.is_some() {
*index += 1;
}
value
};
if let Some(rest) = argument.strip_prefix("-isystem") {
let directory = if rest.is_empty() {
take_value(&mut index)
} else {
Some(rest)
};
if let Some(directory) = directory {
config.include_paths.push(IncludePath::system(directory));
}
} else if let Some(rest) = argument.strip_prefix("-I") {
let directory = if rest.is_empty() {
take_value(&mut index)
} else {
Some(rest)
};
if let Some(directory) = directory {
config.include_paths.push(IncludePath::user(directory));
}
} else if let Some(rest) = argument.strip_prefix("-D") {
let definition = if rest.is_empty() {
take_value(&mut index)
} else {
Some(rest)
};
if let Some(definition) = definition {
config.defines.push(parse_define_argument(definition));
}
} else if let Some(rest) = argument.strip_prefix("-U") {
let name = if rest.is_empty() {
take_value(&mut index)
} else {
Some(rest)
};
if let Some(name) = name {
config.undefines.push(name.into());
}
} else if let Some(rest) = argument.strip_prefix("-std=") {
config.standard = Some(rest.into());
} else if let Some(rest) = argument.strip_prefix("--target=") {
config.target = Some(rest.into());
} else if argument == "--target" {
if let Some(target) = take_value(&mut index) {
config.target = Some(target.into());
}
} else if argument == "-m32" || argument == "-m64" {
config.target = Some(argument.into());
}
}
config
}
pub fn project_config_from_flags(
flags: &[String],
working_directory: Option<PathBuf>,
section: &crate::project::CompileSection,
) -> CompilerConfig {
let mut arguments: Vec<String> = flags
.iter()
.filter(|argument| !section.remove_args.iter().any(|drop| drop == *argument))
.cloned()
.collect();
arguments.extend(section.extra_args.iter().cloned());
config_from_arguments(&arguments, working_directory)
}
fn parse_define_argument(argument: &str) -> CommandLineMacro {
match argument.split_once('=') {
Some((name, value)) => CommandLineMacro::with_value(name, value),
None => CommandLineMacro::defined(argument),
}
}
pub fn parse_compile_commands(json: &str) -> CompileCommands {
let mut commands = Vec::new();
let mut malformed = 0usize;
for object in top_level_objects(json) {
match parse_command_object(&object) {
Some(command) => commands.push(command),
None => malformed += 1,
}
}
CompileCommands {
commands,
malformed,
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CompileCommands {
pub commands: Vec<CompileCommand>,
pub malformed: usize,
}
impl CompileCommands {
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
pub fn len(&self) -> usize {
self.commands.len()
}
pub fn command_for(&self, file: &Path) -> Option<&CompileCommand> {
let requested = normalize_for_comparison(file);
let request_tails: std::collections::HashSet<&str> =
path_suffixes(&requested).into_iter().collect();
let mut best: Option<(usize, &CompileCommand)> = None;
for command in &self.commands {
let stored = normalize_for_comparison(&command.file);
for tail in path_suffixes(&stored) {
if request_tails.contains(tail) {
let specificity = tail.len();
if best.is_none_or(|(best_len, _)| specificity > best_len) {
best = Some((specificity, command));
}
break;
}
}
}
best.map(|(_, command)| command)
}
}
fn path_suffixes(path: &str) -> Vec<&str> {
let mut suffixes = vec![path];
for (index, character) in path.char_indices() {
if character == '/' {
let rest = &path[index + 1..];
if !rest.is_empty() {
suffixes.push(rest);
}
}
}
if let Some(index) = path.find(":/")
&& index + 2 < path.len()
{
suffixes.push(&path[index + 2..]);
}
suffixes
}
fn normalize_for_comparison(path: &Path) -> String {
let unified: String = path
.to_string_lossy()
.chars()
.map(|character| if character == '\\' { '/' } else { character })
.collect();
crate::paths::normalize_path(Path::new(&unified), true)
}
fn top_level_objects(json: &str) -> Vec<String> {
let mut objects = Vec::new();
let mut depth = 0usize;
let mut start: Option<usize> = None;
let mut in_string = false;
let mut escaped = false;
for (index, character) in json.char_indices() {
if in_string {
if escaped {
escaped = false;
} else if character == '\\' {
escaped = true;
} else if character == '"' {
in_string = false;
}
continue;
}
match character {
'"' => in_string = true,
'{' => {
if depth == 0 {
start = Some(index);
}
depth += 1;
}
'}' => {
depth = depth.saturating_sub(1);
if depth == 0
&& let Some(start) = start.take()
{
objects.push(json[start..=index].to_string());
}
}
_ => {}
}
}
objects
}
fn parse_command_object(object: &str) -> Option<CompileCommand> {
let directory = string_field(object, "directory").map(PathBuf::from);
let file = string_field(object, "file")?;
let arguments = match array_field(object, "arguments") {
Some(arguments) => arguments,
None => split_command_line(&string_field(object, "command")?),
};
Some(CompileCommand {
file: PathBuf::from(file),
directory,
arguments,
})
}
fn string_field(object: &str, name: &str) -> Option<String> {
let key = format!("\"{name}\"");
let after_key = object.find(&key)? + key.len();
let rest = object[after_key..].trim_start();
let rest = rest.strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('"')?;
let mut value = String::new();
let mut escaped = false;
for character in rest.chars() {
if escaped {
value.push(match character {
'n' => '\n',
't' => '\t',
other => other,
});
escaped = false;
continue;
}
match character {
'\\' => escaped = true,
'"' => return Some(value),
other => value.push(other),
}
}
None
}
fn array_field(object: &str, name: &str) -> Option<Vec<String>> {
let key = format!("\"{name}\"");
let after_key = object.find(&key)? + key.len();
let rest = object[after_key..].trim_start();
let rest = rest.strip_prefix(':')?.trim_start();
let rest = rest.strip_prefix('[')?;
let mut values = Vec::new();
let mut current: Option<String> = None;
let mut escaped = false;
for character in rest.chars() {
if escaped {
if let Some(value) = current.as_mut() {
value.push(character);
}
escaped = false;
continue;
}
match character {
'\\' => escaped = true,
'"' => match current.take() {
Some(value) => values.push(value),
None => current = Some(String::new()),
},
']' if current.is_none() => return Some(values),
other => {
if let Some(value) = current.as_mut() {
value.push(other);
}
}
}
}
None
}
pub fn split_command_line(command: &str) -> Vec<String> {
let mut arguments = Vec::new();
let mut current = String::new();
let mut has_current = false;
let mut quote: Option<char> = None;
let mut characters = command.chars().peekable();
while let Some(character) = characters.next() {
match character {
'\\' if quote != Some('\'') => {
let escapes = characters
.peek()
.is_some_and(|next| next.is_whitespace() || *next == '"' || *next == '\'');
if escapes {
current.push(characters.next().expect("peeked"));
} else {
current.push('\\');
}
has_current = true;
}
'"' | '\'' if quote.is_none() => {
quote = Some(character);
has_current = true;
}
character if Some(character) == quote => quote = None,
character if character.is_whitespace() && quote.is_none() => {
if has_current {
arguments.push(std::mem::take(&mut current));
has_current = false;
}
}
other => {
current.push(other);
has_current = true;
}
}
}
if has_current {
arguments.push(current);
}
arguments
}
pub fn predefined_macros_of(config: &CompilerConfig) -> Vec<CommandLineMacro> {
let mut macros = Vec::new();
if let Some(standard) = config.standard.as_deref() {
if let Some(value) = cplusplus_value(standard) {
macros.push(CommandLineMacro::with_value("__cplusplus", value));
if config.dialect() == Dialect::Msvc {
macros.push(CommandLineMacro::with_value("_MSVC_LANG", value));
}
} else if let Some(value) = c_version(standard) {
macros.push(CommandLineMacro::with_value("__STDC__", "1"));
macros.push(CommandLineMacro::with_value("__STDC_VERSION__", value));
}
}
if let Some(target) = config.target.as_deref() {
macros.extend(target_macros(target));
}
macros
}
fn without_the_gnu_prefix(standard: &str) -> &str {
standard.strip_prefix("gnu").unwrap_or(standard)
}
fn cplusplus_value(standard: &str) -> Option<&'static str> {
let rest = without_the_gnu_prefix(standard);
let year = rest
.strip_prefix("c++")
.or_else(|| rest.strip_prefix("++"))?;
Some(match year {
"98" | "03" => "199711L",
"11" => "201103L",
"14" => "201402L",
"17" => "201703L",
"20" | "2a" => "202002L",
"23" | "2b" => "202302L",
_ => return None,
})
}
fn c_version(standard: &str) -> Option<&'static str> {
let rest = without_the_gnu_prefix(standard);
let year = rest.strip_prefix('c').unwrap_or(rest);
Some(match year {
"89" | "90" => "199409L",
"99" => "199901L",
"11" => "201112L",
"17" | "18" => "201710L",
"23" | "2x" => "202311L",
_ => return None,
})
}
fn target_macros(target: &str) -> Vec<CommandLineMacro> {
let lowered = target.to_ascii_lowercase();
let mut macros = Vec::new();
let architecture =
if lowered.contains("x86_64") || lowered.contains("amd64") || lowered == "-m64" {
Some(("__x86_64__", true))
} else if lowered.contains("i686")
|| lowered.contains("i386")
|| lowered.contains("x86")
|| lowered == "-m32"
{
Some(("__i386__", false))
} else if lowered.contains("aarch64") || lowered.contains("arm64") {
Some(("__aarch64__", true))
} else if lowered.contains("arm") {
Some(("__arm__", false))
} else {
None
};
let is_windows =
lowered.contains("windows") || lowered.contains("mingw") || lowered.contains("msvc");
if let Some((name, _)) = architecture {
macros.push(CommandLineMacro::with_value(name, "1"));
}
if is_windows {
macros.push(CommandLineMacro::with_value("_WIN32", "1"));
if architecture.is_some_and(|(_, wide)| wide) {
macros.push(CommandLineMacro::with_value("_WIN64", "1"));
}
}
if lowered.contains("apple") || lowered.contains("darwin") {
macros.push(CommandLineMacro::with_value("__APPLE__", "1"));
}
if lowered.contains("linux") {
macros.push(CommandLineMacro::with_value("__linux__", "1"));
}
macros
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_standard_decides_cplusplus() {
for (standard, expected) in [
("c++98", "199711L"),
("gnu++03", "199711L"),
("c++11", "201103L"),
("gnu++14", "201402L"),
("c++17", "201703L"),
("gnu++20", "202002L"),
("c++2a", "202002L"),
("c++23", "202302L"),
] {
let config = CompilerConfig::default().with_standard(standard);
let macros = predefined_macros_of(&config);
let cplusplus = macros.iter().find(|entry| &*entry.name == "__cplusplus");
assert_eq!(
cplusplus.and_then(|entry| entry.value.as_deref()),
Some(expected),
"{standard} means {expected}"
);
}
for standard in ["c++26", "c++29", "c90", "nonsense"] {
let config = CompilerConfig::default().with_standard(standard);
assert!(
!predefined_macros_of(&config)
.iter()
.any(|entry| &*entry.name == "__cplusplus"),
"{standard} says nothing about `__cplusplus`"
);
}
}
#[test]
fn the_msvc_dialect_gets_the_language_version_too() {
let config = CompilerConfig::default()
.with_standard("c++17")
.with_dialect(Dialect::Msvc);
let macros = predefined_macros_of(&config);
assert_eq!(
macros
.iter()
.find(|entry| &*entry.name == "_MSVC_LANG")
.and_then(|entry| entry.value.as_deref()),
Some("201703L")
);
let config = CompilerConfig::default().with_standard("c++17");
assert!(
!predefined_macros_of(&config)
.iter()
.any(|entry| &*entry.name == "_MSVC_LANG")
);
}
#[test]
fn a_c_standard_decides_the_c_version() {
let config = CompilerConfig::default().with_standard("gnu11");
let macros = predefined_macros_of(&config);
let value = |name: &str| {
macros
.iter()
.find(|entry| &*entry.name == name)
.and_then(|entry| entry.value.as_deref())
};
assert_eq!(value("__STDC_VERSION__"), Some("201112L"));
assert_eq!(value("__STDC__"), Some("1"));
assert_eq!(value("__cplusplus"), None, "C has no `__cplusplus`");
}
#[test]
fn the_target_decides_the_platform_names() {
let names = |target: &str| {
predefined_macros_of(&CompilerConfig::default().with_target(target))
.into_iter()
.map(|entry| entry.name.to_string())
.collect::<Vec<_>>()
};
assert!(names("x86_64-w64-mingw32").contains(&"_WIN32".to_string()));
assert!(names("x86_64-w64-mingw32").contains(&"_WIN64".to_string()));
assert!(names("x86_64-w64-mingw32").contains(&"__x86_64__".to_string()));
assert!(names("x86_64-unknown-linux-gnu").contains(&"__linux__".to_string()));
assert!(!names("x86_64-unknown-linux-gnu").contains(&"_WIN32".to_string()));
assert!(names("i686-w64-mingw32").contains(&"__i386__".to_string()));
assert!(!names("i686-w64-mingw32").contains(&"_WIN64".to_string()));
assert!(names("-m32").contains(&"__i386__".to_string()));
assert!(names("-m64").contains(&"__x86_64__".to_string()));
assert!(names("wasm32-unknown-unknown").is_empty());
}
}
fn define_from_a_config_file(written: &str) -> CommandLineMacro {
match written.split_once('=') {
Some((name, value)) => CommandLineMacro::with_value(name.trim(), value),
None => CommandLineMacro::defined(written.trim()),
}
}
#[cfg(test)]
mod database_search_path_tests {
use super::*;
#[test]
fn the_compilers_own_directories_survive_an_empty_database_entry() {
let root = PathBuf::from("/p");
let file = root.join("src/main.cpp");
let database = CompileCommands {
commands: vec![CompileCommand {
file: file.clone(),
directory: Some(root.clone()),
arguments: vec![
"c++".to_string(),
"-std=c++23".to_string(),
"-c".to_string(),
file.to_string_lossy().into_owned(),
],
}],
malformed: 0,
};
let config = CompilerConfig {
root: Some(root.clone()),
database: Some(std::sync::Arc::new(database)),
include_paths: vec![
IncludePath::user("/project/include"),
IncludePath::system("/gcc/include/c++/15.1.0"),
IncludePath::system("/gcc/include-fixed"),
],
..CompilerConfig::default()
};
let per_file = config.for_file(&file);
let directories: Vec<&Path> = per_file
.include_paths
.iter()
.map(|path| path.directory.as_path())
.collect();
assert!(
!directories.contains(&Path::new("/project/include")),
"the database entry replaces the project's directories: {directories:?}"
);
assert_eq!(
directories,
vec![
Path::new("/gcc/include/c++/15.1.0"),
Path::new("/gcc/include-fixed")
],
"the toolchain's directories are the one part of the search path the entry knows nothing about"
);
assert!(
per_file.include_paths.iter().all(|path| path.is_system),
"and they keep their kind, so `#include <…>` still finds them"
);
}
#[test]
fn the_entries_own_directories_come_before_the_compilers() {
let root = PathBuf::from("/p");
let file = root.join("src/main.cpp");
let database = CompileCommands {
commands: vec![CompileCommand {
file: file.clone(),
directory: Some(root.clone()),
arguments: vec![
"c++".to_string(),
"-I/project/generated".to_string(),
"-c".to_string(),
file.to_string_lossy().into_owned(),
],
}],
malformed: 0,
};
let config = CompilerConfig {
root: Some(root),
database: Some(std::sync::Arc::new(database)),
include_paths: vec![IncludePath::system("/gcc/include")],
..CompilerConfig::default()
};
let directories: Vec<PathBuf> = config
.for_file(&file)
.include_paths
.iter()
.map(|path| path.directory.clone())
.collect();
assert_eq!(
directories,
vec![
PathBuf::from("/project/generated"),
PathBuf::from("/gcc/include")
]
);
}
}