use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde::Deserialize;
use crate::file::paths::FileProvider;
pub const PROJECT_CONFIG_FILE: &str = ".cppls.toml";
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProjectConfig {
pub workspace: WorkspaceSection,
pub compile: CompileSection,
pub index: IndexSection,
pub diagnostics: DiagnosticsSection,
pub hover: HoverSection,
pub format: FormatSection,
pub unreal: Option<UnrealSection>,
pub locale: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct UnrealSection {
#[serde(default)]
pub enable: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkspaceSection {
#[serde(default)]
pub exclude: Vec<String>,
#[serde(default)]
pub source_extensions: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CudaSection {
#[serde(default)]
pub enable: bool,
#[serde(default)]
pub toolkit: Option<PathBuf>,
#[serde(default)]
pub host_compiler: Option<String>,
#[serde(default)]
pub include: Vec<PathBuf>,
#[serde(default)]
pub args: Vec<String>,
}
impl CudaSection {
pub fn applied_to(
&self,
mut config: crate::include::config::CompilerConfig,
root: &std::path::Path,
) -> crate::include::config::CompilerConfig {
if self.enable {
config = config.with_cuda(true);
}
if let Some(host) = &self.host_compiler {
let name = host
.rsplit(['/', '\\'])
.next()
.unwrap_or(host)
.trim_end_matches(".exe");
let dialect = if name == "cl" {
cpp_parser::Dialect::Msvc
} else if name.contains("g++")
|| name.contains("gcc")
|| name.contains("clang")
|| name == "cc"
|| name == "c++"
{
cpp_parser::Dialect::Gnu
} else {
config.dialect()
};
config = config.with_dialect(dialect);
}
if let Some(toolkit) = &self.toolkit {
let toolkit = if toolkit.is_absolute() {
toolkit.clone()
} else {
root.join(toolkit)
};
let toolkit = &toolkit;
for relative in ["include", "include/cccl"] {
let directory = toolkit.join(relative);
if relative == "include" || directory.is_dir() {
config
.include_paths
.push(crate::include::config::IncludePath::system(directory));
}
}
}
for directory in &self.include {
let directory = if directory.is_absolute() {
directory.clone()
} else {
root.join(directory)
};
config
.include_paths
.push(crate::include::config::IncludePath::system(directory));
}
config.extra_args.extend(self.args.iter().cloned());
config
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CompileSection {
#[serde(default)]
pub database: Option<PathBuf>,
#[serde(default)]
pub compiler: Option<String>,
#[serde(default)]
pub standard: Option<String>,
#[serde(default)]
pub args: Option<Vec<String>>,
#[serde(default)]
pub extra_args: Vec<String>,
#[serde(default)]
pub remove_args: Vec<String>,
#[serde(default)]
pub cuda: Option<CudaSection>,
#[serde(default)]
pub include: BTreeMap<String, Vec<String>>,
#[serde(default)]
pub fuzzy_includes: Option<bool>,
#[serde(default, rename = "target")]
pub targets: Vec<TargetSection>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetSection {
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub sources: Vec<String>,
#[serde(default)]
pub includes: Vec<String>,
#[serde(default)]
pub defines: Vec<String>,
#[serde(default)]
pub standard: Option<String>,
#[serde(default)]
pub args: Option<Vec<String>>,
#[serde(default)]
pub extra_args: Vec<String>,
#[serde(default)]
pub remove_args: Vec<String>,
}
pub fn targets_for(section: &CompileSection) -> Vec<TargetSection> {
let mut targets: Vec<TargetSection> = section
.include
.iter()
.map(|(directory, includes)| TargetSection {
name: Some(format!("[compile.include] {directory}")),
sources: vec![if directory == "*" {
"**".to_string()
} else {
format!("{directory}/**")
}],
includes: includes.clone(),
..TargetSection::default()
})
.collect();
targets.extend(section.targets.iter().cloned());
targets
}
pub fn target_for<'a>(
targets: &'a [TargetSection],
root: &Path,
file: &Path,
) -> Option<&'a TargetSection> {
targets
.iter()
.enumerate()
.filter_map(|(order, target)| {
target
.describes(root, file)
.map(|specific| (specific, std::cmp::Reverse(order), target))
})
.max_by_key(|(specific, order, _)| (*specific, *order))
.map(|(_, _, target)| target)
}
impl TargetSection {
pub fn label(&self) -> &str {
self.name.as_deref().unwrap_or("an unnamed target")
}
pub fn describes(&self, root: &Path, file: &Path) -> Option<usize> {
let relative = file.strip_prefix(root).ok()?;
let components: Vec<String> = relative
.components()
.map(|component| component.as_os_str().to_string_lossy().to_lowercase())
.collect();
self.sources
.iter()
.filter_map(|pattern| pattern_specificity(pattern, &components))
.max()
}
}
fn pattern_specificity(pattern: &str, path: &[String]) -> Option<usize> {
let parts: Vec<String> = pattern
.split('/')
.filter(|part| !part.is_empty() && *part != ".")
.map(|part| part.to_lowercase())
.collect();
if parts.is_empty() {
return None;
}
fn walk(parts: &[String], path: &[String], fixed: usize) -> Option<usize> {
let Some((head, rest)) = parts.split_first() else {
return path.is_empty().then_some(fixed);
};
if head == "**" {
return (0..=path.len())
.filter_map(|skipped| walk(rest, &path[skipped..], fixed))
.max();
}
let (component, remaining) = path.split_first()?;
if !component_matches(head, component) {
return None;
}
let fixed = if head.contains('*') { fixed } else { fixed + 1 };
walk(rest, remaining, fixed)
}
walk(&parts, path, 0)
}
fn component_matches(pattern: &str, component: &str) -> bool {
let Some(star) = pattern.find('*') else {
return pattern == component;
};
let (before, after) = (&pattern[..star], &pattern[star + 1..]);
component.starts_with(before)
&& component.len() >= before.len() + after.len()
&& component.ends_with(after)
}
impl CompileSection {
pub fn compiler_is_auto(&self) -> bool {
match &self.compiler {
None => true,
Some(named) => named.eq_ignore_ascii_case("auto"),
}
}
pub fn named_compiler(&self) -> Option<&str> {
match self.compiler.as_deref() {
Some(named) if !self.compiler_is_auto() => Some(named),
_ => None,
}
}
pub fn target_for(&self, root: &Path, file: &Path) -> Option<&TargetSection> {
self.targets
.iter()
.enumerate()
.filter_map(|(order, target)| {
target
.describes(root, file)
.map(|specific| (specific, std::cmp::Reverse(order), target))
})
.max_by_key(|(specific, order, _)| (*specific, *order))
.map(|(_, _, target)| target)
}
pub fn includes_for(&self, root: &Path, file: &Path) -> Vec<PathBuf> {
let mut chosen: Vec<(&str, &Vec<String>)> = self
.include
.iter()
.filter(|(directory, _)| {
directory.as_str() == "*" || file.starts_with(root.join(directory))
})
.map(|(directory, paths)| (directory.as_str(), paths))
.collect();
chosen
.sort_by_key(|(directory, _)| (directory == &"*", std::cmp::Reverse(directory.len())));
chosen
.into_iter()
.flat_map(|(_, paths)| paths.iter())
.map(|directory| root.join(directory))
.collect()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IndexSection {
#[serde(default)]
pub cache_dir: Option<String>,
#[serde(default)]
pub max_files: Option<usize>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DiagnosticsSection {
#[serde(default)]
pub on_change_ms: Option<u64>,
#[serde(default)]
pub enable: Vec<String>,
#[serde(default)]
pub disable: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HoverSection {
#[serde(default)]
pub enable: Option<bool>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FormatSection {
#[serde(default)]
pub enable: Option<bool>,
#[serde(default)]
pub std: Option<bool>,
#[serde(default)]
pub printf: Option<bool>,
#[serde(default)]
pub scanf: Option<bool>,
#[serde(default)]
pub functions: BTreeMap<String, FunctionEntry>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum FunctionEntry {
Syntax(String),
Detailed {
syntax: String,
#[serde(default)]
argument: Option<usize>,
},
}
impl FunctionEntry {
pub fn syntax(&self) -> Option<FormatSyntax> {
let written = match self {
FunctionEntry::Syntax(syntax) => syntax,
FunctionEntry::Detailed { syntax, .. } => syntax,
};
match written.trim() {
"std" => Some(FormatSyntax::Std),
"printf" => Some(FormatSyntax::Printf),
"scanf" => Some(FormatSyntax::Scanf),
_ => None,
}
}
pub fn argument(&self) -> usize {
match self {
FunctionEntry::Syntax(_) => 0,
FunctionEntry::Detailed { argument, .. } => argument.unwrap_or(0),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatSyntax {
Std,
Printf,
Scanf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigProblem {
pub severity: Severity,
pub message: String,
}
impl ConfigProblem {
fn error(message: impl Into<String>) -> Self {
ConfigProblem {
severity: Severity::Error,
message: message.into(),
}
}
fn warning(message: impl Into<String>) -> Self {
ConfigProblem {
severity: Severity::Warning,
message: message.into(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ConfigReport {
pub config: ProjectConfig,
pub path: Option<PathBuf>,
pub problems: Vec<ConfigProblem>,
}
impl ConfigReport {
pub fn none() -> Self {
ConfigReport::default()
}
pub fn found(&self) -> bool {
self.path.is_some()
}
pub fn errors(&self) -> impl Iterator<Item = &ConfigProblem> {
self.problems
.iter()
.filter(|problem| problem.severity == Severity::Error)
}
}
pub fn load_config(
files: &impl FileProvider,
root: &Path,
explicit: Option<&Path>,
) -> ConfigReport {
let path = match explicit {
Some(path) => path.to_path_buf(),
None => root.join(PROJECT_CONFIG_FILE),
};
let Some(text) = files.read(&path) else {
if explicit.is_some() {
return ConfigReport {
config: ProjectConfig::default(),
path: None,
problems: vec![ConfigProblem::error(format!(
"the configuration file {} could not be read",
path.display()
))],
};
}
return ConfigReport::none();
};
parse_config(&text, &path)
}
pub fn parse_config(text: &str, path: &Path) -> ConfigReport {
let value: toml::Value = match toml::from_str(text) {
Ok(value) => value,
Err(error) => {
return ConfigReport {
config: ProjectConfig::default(),
path: Some(path.to_path_buf()),
problems: vec![ConfigProblem::error(format!(
"{} is not valid TOML, so none of it is in effect: {error}",
path.display()
))],
};
}
};
let mut report = ConfigReport {
config: ProjectConfig::default(),
path: Some(path.to_path_buf()),
problems: Vec::new(),
};
let Some(table) = value.as_table() else {
report.problems.push(ConfigProblem::error(format!(
"{} does not hold a table of sections",
path.display()
)));
return report;
};
for (name, section) in table {
let section = section.clone();
match name.as_str() {
"workspace" => match decode::<WorkspaceSection>(section, name) {
Ok(decoded) => report.config.workspace = decoded,
Err(problem) => report.problems.push(problem),
},
"compile" => match decode::<CompileSection>(section, name) {
Ok(decoded) => report.config.compile = decoded,
Err(problem) => report.problems.push(problem),
},
"index" => match decode::<IndexSection>(section, name) {
Ok(decoded) => report.config.index = decoded,
Err(problem) => report.problems.push(problem),
},
"diagnostics" => match decode::<DiagnosticsSection>(section, name) {
Ok(decoded) => report.config.diagnostics = decoded,
Err(problem) => report.problems.push(problem),
},
"hover" => match decode::<HoverSection>(section, name) {
Ok(decoded) => report.config.hover = decoded,
Err(problem) => report.problems.push(problem),
},
"format" => match decode::<FormatSection>(section, name) {
Ok(decoded) => report.config.format = decoded,
Err(problem) => report.problems.push(problem),
},
"unreal" => match decode::<UnrealSection>(section, name) {
Ok(decoded) => report.config.unreal = Some(decoded),
Err(problem) => report.problems.push(problem),
},
"locale" => match section.as_str() {
Some(locale) if !locale.trim().is_empty() => {
report.config.locale = Some(locale.trim().to_string());
}
Some(_) => report.problems.push(ConfigProblem::warning(
"`locale` is empty, so the language is the one the client asked for".to_string(),
)),
None => report.problems.push(ConfigProblem::error(
"`locale` holds a language tag written as a string — `locale = \"zh-CN\"` — so the value here \
is not in effect"
.to_string(),
)),
},
unknown => report.problems.push(ConfigProblem::error(format!(
"[{unknown}] is not a section this server reads (workspace, compile, index, diagnostics, hover, \
format), and `locale` is the one key that stands alone, so nothing under it is in effect"
))),
}
}
validate(&mut report);
report
}
fn decode<T>(value: toml::Value, name: &str) -> Result<T, ConfigProblem>
where
T: for<'de> Deserialize<'de>,
{
value.try_into::<T>().map_err(|error| {
ConfigProblem::error(format!(
"[{name}] could not be read, so that section keeps its defaults: {error}"
))
})
}
fn validate(report: &mut ConfigReport) {
if let Some(cache_dir) = &report.config.index.cache_dir {
let path = Path::new(cache_dir);
let one_component = path.components().count() == 1;
let named = matches!(
path.components().next(),
Some(std::path::Component::Normal(_))
);
if !one_component || !named {
report.problems.push(ConfigProblem::warning(format!(
"index.cache_dir = {cache_dir:?} is not a directory name inside the project, so the default \
`{}` is used instead",
crate::CACHE_DIRECTORY
)));
report.config.index.cache_dir = None;
}
}
if report.config.index.max_files == Some(0) {
report.problems.push(ConfigProblem::warning(
"index.max_files = 0 would mean \"index nothing\", so the default is used instead"
.to_string(),
));
report.config.index.max_files = None;
}
let bad_patterns: Vec<&String> = report
.config
.workspace
.exclude
.iter()
.filter(|pattern| crate::PathPattern::new(pattern).is_err())
.collect();
for pattern in bad_patterns {
report.problems.push(ConfigProblem::warning(format!(
"workspace.exclude has {pattern:?}, which is not a path pattern, so it is ignored"
)));
}
report
.config
.workspace
.exclude
.retain(|pattern| crate::PathPattern::new(pattern).is_ok());
for relative in report.config.compile.include.values().flatten() {
if Path::new(relative).is_absolute() {
report.problems.push(ConfigProblem::warning(format!(
"compile.include names the absolute path {relative:?}; absolute paths in a committed file do not \
survive a move, and this one is used as written"
)));
}
}
let broken: Vec<String> = report
.config
.format
.functions
.iter()
.filter(|(_, entry)| entry.syntax().is_none())
.map(|(name, _)| name.clone())
.collect();
for name in broken {
let written = match report.config.format.functions.get(&name) {
Some(FunctionEntry::Syntax(syntax)) | Some(FunctionEntry::Detailed { syntax, .. }) => {
syntax.clone()
}
None => String::new(),
};
report.problems.push(ConfigProblem::warning(format!(
"format.functions names {name:?} with the syntax {written:?}, which is not one this server reads \
(std, printf, scanf), so that function is not read"
)));
report.config.format.functions.remove(&name);
}
for (name, entry) in &report.config.format.functions {
if !name.contains("::") {
report.problems.push(ConfigProblem::warning(format!(
"format.functions has {name:?}, which is not a qualified name; an unqualified entry would claim \
every function of that spelling in the project, including the standard library's"
)));
}
if entry.argument() > 3 {
report.problems.push(ConfigProblem::warning(format!(
"format.functions gives {name:?} the argument {}, which is past the point any format function puts \
its format string",
entry.argument()
)));
}
}
if report
.config
.compile
.database
.as_ref()
.is_some_and(|database| {
Path::new(database)
.components()
.any(|component| matches!(component, std::path::Component::ParentDir))
})
{
report.problems.push(ConfigProblem::warning(
"compile.database walks out of the project with `..`; it is used as written"
.to_string(),
));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(text: &str) -> ConfigReport {
parse_config(text, Path::new("/p/.cppls.toml"))
}
#[test]
fn the_format_section_is_read() {
let report = parse(
"[format]\nenable = true\nstd = false\nprintf = false\n\n[format.functions]\n\
\"mylib::logf\" = \"printf\"\n\
\"mylib::log\" = \"std\"\n\
\"mylib::trace\" = { syntax = \"printf\", argument = 1 }\n",
);
assert_eq!(report.config.format.enable, Some(true));
assert_eq!(report.config.format.std, Some(false));
assert_eq!(report.config.format.printf, Some(false));
assert_eq!(report.config.format.scanf, None);
assert_eq!(
report
.config
.format
.functions
.get("mylib::logf")
.and_then(FunctionEntry::syntax),
Some(FormatSyntax::Printf)
);
assert_eq!(
report
.config
.format
.functions
.get("mylib::trace")
.map(|entry| (entry.syntax(), entry.argument())),
Some((Some(FormatSyntax::Printf), 1)),
"the table form says which argument is the format string"
);
assert_eq!(
report
.config
.format
.functions
.get("mylib::log")
.map(FunctionEntry::argument),
Some(0),
"a bare string means the first argument"
);
assert!(report.problems.is_empty(), "{:?}", problems(&report));
let report = parse("[workspace]\nexclude = [\"build/**\"]\n");
assert_eq!(report.config.format, FormatSection::default());
assert!(report.problems.is_empty());
let report = parse("[format]\nprintff = false\n");
assert_eq!(report.config.format, FormatSection::default());
assert_eq!(report.problems.len(), 1);
assert!(
report.problems[0].message.contains("[format]"),
"{:?}",
problems(&report)
);
let report = parse("[format.functions]\n\"mylib::logf\" = \"printff\"\n");
assert_eq!(report.problems.len(), 1);
assert!(
report.problems[0].message.contains("printff"),
"the message names the value: {:?}",
problems(&report)
);
assert!(report.problems[0].message.contains("std, printf, scanf"));
}
#[test]
fn the_cuda_section_is_read_and_applied() {
let report = parse(
"[compile.cuda]\n\
enable = true\n\
toolkit = '/opt/cuda-12.4'\n\
host_compiler = 'cl.exe'\n\
include = ['third_party/cutlass/include']\n\
args = ['-arch=sm_80']\n\
[compile]\n\
standard = 'c++20'\n",
);
assert_eq!(problems(&report), Vec::<String>::new());
let cuda = report
.config
.compile
.cuda
.as_ref()
.expect("the section is here");
assert!(cuda.enable);
assert_eq!(cuda.toolkit.as_deref(), Some(Path::new("/opt/cuda-12.4")));
assert_eq!(cuda.host_compiler.as_deref(), Some("cl.exe"));
assert_eq!(cuda.args, vec!["-arch=sm_80"]);
let config = cuda.applied_to(
crate::include::config::CompilerConfig::new(),
Path::new("/p"),
);
assert!(config.cuda(), "`enable` is the parser's CUDA switch");
assert_eq!(config.dialect(), cpp_parser::Dialect::Msvc);
assert!(
config
.include_paths
.iter()
.any(|path| path.directory == Path::new("/opt/cuda-12.4/include")),
"the toolkit's include directory is what makes `<cuda_runtime.h>` resolve: {:?}",
config.include_paths
);
assert!(
config
.include_paths
.iter()
.any(|path| path.directory == Path::new("/p/third_party/cutlass/include")),
"and the project's own are relative to the root: {:?}",
config.include_paths
);
assert!(config.extra_args.iter().any(|arg| arg == "-arch=sm_80"));
}
#[test]
fn a_cuda_section_without_enable_does_not_turn_the_reading_on() {
let report = parse("[compile.cuda]\ntoolkit = '/opt/cuda'\n");
assert_eq!(problems(&report), Vec::<String>::new());
let cuda = report.config.compile.cuda.as_ref().expect("the section");
let config = cuda.applied_to(
crate::include::config::CompilerConfig::new(),
Path::new("/p"),
);
assert!(!config.cuda(), "no `enable`, no CUDA reading");
assert!(
config
.include_paths
.iter()
.any(|path| path.directory == Path::new("/opt/cuda/include")),
"…but the headers are still where the project said"
);
}
fn problems(report: &ConfigReport) -> Vec<String> {
report
.problems
.iter()
.map(|problem| problem.message.clone())
.collect()
}
#[test]
fn an_empty_file_is_the_default_configuration() {
let report = parse("");
assert_eq!(report.config, ProjectConfig::default());
assert!(report.problems.is_empty());
assert!(report.found());
}
#[test]
fn every_key_is_read() {
let report = parse(
r#"
[workspace]
exclude = ["**/build/**", "third_party/**"]
source_extensions = ["cuh"]
[compile]
database = "build/compile_commands.json"
compiler = "clang++"
args = ["-std=c++20", "-Iinclude"]
extra_args = ["-DFEATURE=1"]
remove_args = ["-Werror"]
[compile.include]
"src/legacy" = ["include/legacy"]
[index]
cache_dir = ".cache"
max_files = 20000
[diagnostics]
on_change_ms = 250
[hover]
enable = false
"#,
);
assert!(report.problems.is_empty(), "{:?}", problems(&report));
let config = &report.config;
assert_eq!(config.workspace.exclude, ["**/build/**", "third_party/**"]);
assert_eq!(config.workspace.source_extensions, ["cuh"]);
assert_eq!(
config.compile.database.as_deref(),
Some(Path::new("build/compile_commands.json"))
);
assert_eq!(config.compile.named_compiler(), Some("clang++"));
assert_eq!(
config.compile.args.as_deref(),
Some(["-std=c++20".to_string(), "-Iinclude".to_string()].as_slice())
);
assert_eq!(config.compile.extra_args, ["-DFEATURE=1"]);
assert_eq!(config.compile.remove_args, ["-Werror"]);
assert_eq!(
config.compile.include.get("src/legacy").map(Vec::len),
Some(1)
);
assert_eq!(config.index.cache_dir.as_deref(), Some(".cache"));
assert_eq!(config.index.max_files, Some(20000));
assert_eq!(config.diagnostics.on_change_ms, Some(250));
assert_eq!(config.hover.enable, Some(false));
}
#[test]
fn auto_is_not_a_compiler() {
let report = parse("[compile]\ncompiler = \"auto\"\n");
assert!(report.config.compile.compiler_is_auto());
assert_eq!(report.config.compile.named_compiler(), None);
}
#[test]
fn an_unknown_section_does_not_take_the_others_with_it() {
let report =
parse("[workspace]\nexclude = [\"build/**\"]\n\n[compilee]\ncompiler = \"clang++\"\n");
assert_eq!(report.config.workspace.exclude, ["build/**"]);
assert_eq!(report.config.compile.named_compiler(), None);
assert_eq!(report.problems.len(), 1);
assert!(
report.problems[0].message.contains("[compilee]"),
"{:?}",
problems(&report)
);
assert_eq!(report.problems[0].severity, Severity::Error);
}
#[test]
fn an_unknown_key_in_a_section_keeps_that_section_at_its_defaults_and_says_which() {
let report = parse("[workspace]\nexlude = [\"build/**\"]\n");
assert!(report.config.workspace.exclude.is_empty());
assert_eq!(report.problems.len(), 1);
assert_eq!(report.problems[0].severity, Severity::Error);
assert!(
report.problems[0].message.contains("exlude"),
"the problem names the key: {:?}",
problems(&report)
);
}
#[test]
fn a_section_of_the_wrong_shape_is_reported() {
let report = parse("[index]\ncache_dir = 5\n");
assert_eq!(report.config.index.cache_dir, None);
assert_eq!(report.problems.len(), 1);
assert!(report.problems[0].message.contains("[index]"));
}
#[test]
fn a_syntax_error_reports_the_file_and_keeps_nothing() {
let report = parse("[workspace\nexclude = [\n");
assert_eq!(report.config, ProjectConfig::default());
assert_eq!(report.problems.len(), 1);
assert!(report.problems[0].message.contains("not valid TOML"));
}
#[test]
fn a_cache_directory_that_is_not_a_name_is_replaced_by_the_default() {
for written in ["../outside", "/tmp/cppls", "a/b"] {
let report = parse(&format!("[index]\ncache_dir = {written:?}\n"));
assert_eq!(report.config.index.cache_dir, None, "{written}");
assert_eq!(report.problems.len(), 1, "{written}");
assert_eq!(report.problems[0].severity, Severity::Warning);
}
}
#[test]
fn a_pattern_that_is_not_a_pattern_is_dropped_from_the_list() {
let report = parse("[workspace]\nexclude = [\"**/build/**\", \"**/[unclosed\"]\n");
assert_eq!(report.config.workspace.exclude, ["**/build/**"]);
assert_eq!(report.problems.len(), 1);
assert_eq!(report.problems[0].severity, Severity::Warning);
assert!(report.problems[0].message.contains("unclosed"));
}
#[test]
fn an_include_a_project_names_is_relative_to_the_root_and_the_nearest_rule_wins() {
let report = parse(
r#"
[compile.include]
"*" = ["include"]
"src/legacy" = ["include/legacy", "generated"]
"#,
);
let root = Path::new("/p");
let legacy = report
.config
.compile
.includes_for(root, Path::new("/p/src/legacy/old.cpp"));
assert_eq!(
legacy,
[
PathBuf::from("/p/include/legacy"),
PathBuf::from("/p/generated"),
PathBuf::from("/p/include"),
],
"the specific directory first, then the project-wide one"
);
let elsewhere = report
.config
.compile
.includes_for(root, Path::new("/p/src/new/modern.cpp"));
assert_eq!(elsewhere, [PathBuf::from("/p/include")]);
}
#[test]
fn a_file_that_is_not_there_is_not_a_problem() {
let files = crate::MemoryFiles::new();
let report = load_config(&files, Path::new("/p"), None);
assert!(!report.found());
assert!(report.problems.is_empty());
}
#[test]
fn a_file_the_caller_named_must_exist() {
let files = crate::MemoryFiles::new();
let report = load_config(&files, Path::new("/p"), Some(Path::new("/p/other.toml")));
assert!(!report.found());
assert_eq!(report.problems.len(), 1);
assert!(report.problems[0].message.contains("other.toml"));
}
#[test]
fn a_configuration_is_read_from_a_provider() {
let files = crate::MemoryFiles::new()
.with_file("/p/.cppls.toml", "[workspace]\nexclude = [\"build/**\"]\n");
let report = load_config(&files, Path::new("/p"), None);
assert_eq!(report.path.as_deref(), Some(Path::new("/p/.cppls.toml")));
assert_eq!(report.config.workspace.exclude, ["build/**"]);
}
}