use cpp_code_analysis::include::config::predefined_macros_of;
use cpp_code_analysis::{
CommandLineMacro, CompilerConfig, IncludePath, parse_compile_commands, split_command_line,
};
use std::path::{Path, PathBuf};
fn from_arguments(arguments: &[&str]) -> CompilerConfig {
let command = cpp_code_analysis::CompileCommand {
file: PathBuf::from("src/main.cpp"),
directory: Some(PathBuf::from("/project")),
arguments: arguments.iter().map(|it| it.to_string()).collect(),
};
command.to_config()
}
#[test]
fn both_spellings_of_an_include_path_are_read() {
let joined = from_arguments(&["-Iinc", "main.cpp"]);
let separate = from_arguments(&["-I", "inc", "main.cpp"]);
assert_eq!(joined.include_paths, vec![IncludePath::user("inc")]);
assert_eq!(joined.include_paths, separate.include_paths);
}
#[test]
fn a_system_include_path_is_marked_as_one() {
let config = from_arguments(&["-isystem", "/usr/include", "-Iinc"]);
assert_eq!(
config.include_paths,
vec![
IncludePath::system("/usr/include"),
IncludePath::user("inc"),
]
);
assert_eq!(
config.user_include_paths().collect::<Vec<_>>(),
vec![Path::new("inc")]
);
assert_eq!(
config.system_include_paths().collect::<Vec<_>>(),
vec![Path::new("/usr/include")]
);
}
#[test]
fn include_path_order_is_preserved() {
let config = from_arguments(&["-I", "first", "-I", "second", "-isystem", "third"]);
assert_eq!(
config.search_order().collect::<Vec<_>>(),
vec![
(Path::new("first"), false),
(Path::new("second"), false),
(Path::new("third"), true),
]
);
}
#[test]
fn a_bare_define_is_one_and_a_valued_define_keeps_its_value() {
let config = from_arguments(&["-DFOO", "-DBAR=2", "-DBAZ="]);
assert_eq!(
config.defines,
vec![
CommandLineMacro::defined("FOO"),
CommandLineMacro::with_value("BAR", "2"),
CommandLineMacro::with_value("BAZ", ""),
]
);
assert_eq!(
config.defines[0].value, None,
"`-DFOO` has no written value"
);
assert_eq!(
config.defines[2].value.as_deref(),
Some(""),
"and `-DBAZ=` is an empty one, which is a different thing"
);
}
#[test]
fn an_undefine_is_read() {
let config = from_arguments(&["-UFOO", "-U", "BAR"]);
assert_eq!(config.undefines, vec!["FOO".into(), "BAR".into()]);
}
#[test]
fn the_standard_and_the_target_are_read() {
let config = from_arguments(&["-std=c++20", "--target=x86_64-linux-gnu", "-m32"]);
assert_eq!(config.standard.as_deref(), Some("c++20"));
assert_eq!(
config.target.as_deref(),
Some("-m32"),
"the later flag wins"
);
}
#[test]
fn a_target_given_as_a_separate_argument_is_read() {
let config = from_arguments(&["--target", "aarch64-none-elf"]);
assert_eq!(config.target.as_deref(), Some("aarch64-none-elf"));
}
#[test]
fn unknown_flags_are_ignored() {
let config = from_arguments(&[
"-O2",
"-Wall",
"-fno-exceptions",
"-c",
"-o",
"build/main.o",
"-Iinc",
]);
assert_eq!(config.include_paths, vec![IncludePath::user("inc")]);
assert!(config.defines.is_empty());
}
#[test]
fn paths_resolve_against_the_working_directory() {
let config = from_arguments(&["-Iinc", "src/main.cpp"]);
assert_eq!(config.working_directory, Some(PathBuf::from("/project")));
assert_eq!(
config.resolve_against_working_directory(Path::new("inc")),
PathBuf::from("/project/inc")
);
assert_eq!(
config.resolve_against_working_directory(Path::new("/absolute/inc")),
PathBuf::from("/absolute/inc"),
"an absolute path is already resolved"
);
}
#[test]
fn a_configuration_with_nothing_supplied_is_empty() {
assert!(CompilerConfig::new().is_empty());
assert!(
!CompilerConfig::new()
.with_define(CommandLineMacro::defined("X"))
.is_empty()
);
assert!(!CompilerConfig::new().with_include_path("inc").is_empty());
assert!(!CompilerConfig::new().with_standard("c++20").is_empty());
assert!(
!CompilerConfig::new()
.with_working_directory("/project")
.is_empty()
);
}
#[test]
fn a_command_line_splits_on_whitespace() {
assert_eq!(
split_command_line("c++ -c src/main.cpp -o build/main.o"),
vec!["c++", "-c", "src/main.cpp", "-o", "build/main.o"]
);
}
#[test]
fn quoting_keeps_an_argument_together() {
assert_eq!(
split_command_line("c++ \"-DFOO=some value\" 'x y'"),
vec!["c++", "-DFOO=some value", "x y"]
);
}
#[test]
fn an_empty_quoted_argument_is_an_argument() {
assert_eq!(split_command_line("a \"\" b"), vec!["a", "", "b"]);
}
#[test]
fn a_backslash_escapes_the_next_character() {
assert_eq!(split_command_line("c++ -I a\\ b"), vec!["c++", "-I", "a b"]);
}
#[test]
fn a_windows_path_keeps_its_separators() {
assert_eq!(
split_command_line(
r#"C:\toolchains\mingw64\bin\c++.exe -std=c++23 -o CMakeFiles\demo.dir\src\main.cpp.obj -c C:\work\demo\src\main.cpp"#
),
vec![
r#"C:\toolchains\mingw64\bin\c++.exe"#,
"-std=c++23",
"-o",
r#"CMakeFiles\demo.dir\src\main.cpp.obj"#,
"-c",
r#"C:\work\demo\src\main.cpp"#,
]
);
assert_eq!(
split_command_line(r#""C:\Program Files\mingw\c++.exe" -I \\server\share\inc"#),
vec![
r#"C:\Program Files\mingw\c++.exe"#,
"-I",
r#"\\server\share\inc"#
]
);
assert_eq!(
split_command_line(r#"-DMSG="say \"hi\"" -I a\ b"#),
vec![r#"-DMSG=say "hi""#, "-I", "a b"]
);
}
#[test]
fn extra_whitespace_produces_no_empty_arguments() {
assert_eq!(split_command_line(" a b "), vec!["a", "b"]);
assert!(split_command_line(" ").is_empty());
assert!(split_command_line("").is_empty());
}
const DATABASE: &str = r#"[
{
"directory": "/home/u/project",
"command": "/usr/bin/c++ -Iinc -DFOO=1 -std=c++20 -c src/main.cpp",
"file": "/home/u/project/src/main.cpp"
},
{
"directory": "/home/u/project",
"arguments": ["/usr/bin/c++", "-isystem", "/usr/include", "-c", "src/other.cpp"],
"file": "/home/u/project/src/other.cpp"
}
]"#;
#[test]
fn both_shapes_of_entry_are_read() {
let database = parse_compile_commands(DATABASE);
assert_eq!(database.len(), 2);
assert_eq!(database.malformed, 0);
let first = database.command_for(Path::new("/home/u/project/src/main.cpp"));
assert!(first.is_some(), "the `command` shape");
let second = database.command_for(Path::new("/home/u/project/src/other.cpp"));
assert!(second.is_some(), "the `arguments` shape");
}
#[test]
fn a_command_string_becomes_a_configuration() {
let database = parse_compile_commands(DATABASE);
let config = database
.command_for(Path::new("/home/u/project/src/main.cpp"))
.expect("an entry")
.to_config();
assert_eq!(config.include_paths, vec![IncludePath::user("inc")]);
assert_eq!(
config.defines,
vec![CommandLineMacro::with_value("FOO", "1")]
);
assert_eq!(config.standard.as_deref(), Some("c++20"));
assert_eq!(
config.working_directory,
Some(PathBuf::from("/home/u/project"))
);
}
#[test]
fn an_arguments_entry_becomes_a_configuration() {
let database = parse_compile_commands(DATABASE);
let config = database
.command_for(Path::new("/home/u/project/src/other.cpp"))
.expect("an entry")
.to_config();
assert_eq!(
config.include_paths,
vec![IncludePath::system("/usr/include")]
);
}
#[test]
fn a_file_is_found_whatever_the_path_prefix_is() {
let database = parse_compile_commands(DATABASE);
assert!(
database
.command_for(Path::new("/somewhere/else/src/main.cpp"))
.is_some()
);
assert!(
database.command_for(Path::new("src/main.cpp")).is_some(),
"and with no prefix at all"
);
assert!(database.command_for(Path::new("src/nothing.cpp")).is_none());
}
#[test]
fn a_file_matches_across_separators_and_case() {
let database = parse_compile_commands(DATABASE);
assert!(
database
.command_for(Path::new("/home/u/project/src/Main.cpp"))
.is_some()
);
assert!(
database
.command_for(Path::new("\\home\\u\\project\\src\\main.cpp"))
.is_some()
);
}
#[test]
fn a_malformed_database_is_reported_not_fatal() {
let database = parse_compile_commands(
r#"[
{ "directory": "/p", "command": "c++ -c a.cpp", "file": "/p/a.cpp" },
{ "directory": "/p", "file": "/p/no-command.cpp" },
{ this is not json at all },
{ "directory": "/p", "arguments": ["c++", "-c", "b.cpp"], "file": "/p/b.cpp" }
]"#,
);
assert_eq!(database.len(), 2, "the two readable entries");
assert_eq!(database.malformed, 2, "and the two that could not be used");
assert!(
database.command_for(Path::new("a.cpp")).is_some(),
"a malformed entry does not lose the good ones"
);
assert!(
database.command_for(Path::new("b.cpp")).is_some(),
"and the good entry after it is still read"
);
}
#[test]
fn an_empty_or_absent_database_is_empty() {
assert!(parse_compile_commands("[]").is_empty());
assert!(parse_compile_commands("").is_empty());
assert!(parse_compile_commands("not json").is_empty());
assert!(
parse_compile_commands("{}").is_empty(),
"an object, not an array"
);
}
#[test]
fn braces_inside_strings_do_not_confuse_the_reader() {
let database = parse_compile_commands(
r#"[{ "directory": "/p", "command": "c++ -DX={a} -c a.cpp", "file": "/p/a.cpp" }]"#,
);
assert_eq!(database.len(), 1);
assert_eq!(database.malformed, 0);
let config = database
.command_for(Path::new("a.cpp"))
.expect("an entry")
.to_config();
assert_eq!(
config.defines,
vec![CommandLineMacro::with_value("X", "{a}")]
);
}
#[test]
fn escaped_separators_in_a_path_are_unescaped() {
let database = parse_compile_commands(
r#"[{ "directory": "C:\\proj", "command": "cl /c a.cpp", "file": "C:\\proj\\a.cpp" }]"#,
);
assert_eq!(database.len(), 1);
let config = database
.command_for(Path::new("a.cpp"))
.expect("an entry")
.to_config();
let directory = config.working_directory.expect("the database names one");
assert_eq!(
cpp_code_analysis::normalize_path(&directory, false),
"C:/proj",
"the doubled separators are folded into the one spelling comparisons are made in"
);
}
#[test]
fn the_reflection_flag_defines_the_feature_macro() {
let with = from_arguments(&["-std=c++26", "-freflection"]);
assert!(with.reflection, "the flag is read");
let macros = predefined_macros_of(&with);
let value = |name: &str| {
macros
.iter()
.find(|macro_| &*macro_.name == name)
.and_then(|macro_| macro_.value.as_deref())
};
assert_eq!(
value("__cplusplus"),
Some("202400L"),
"GCC 16.2's own value"
);
assert_eq!(value("__cpp_impl_reflection"), Some("202603L"));
let without = from_arguments(&["-std=c++26"]);
assert!(!without.reflection);
let macros = predefined_macros_of(&without);
assert!(
!macros
.iter()
.any(|macro_| &*macro_.name == "__cpp_impl_reflection"),
"the macro is the compiler's switch, not the standard's"
);
assert_eq!(
macros
.iter()
.find(|macro_| &*macro_.name == "__cplusplus")
.and_then(|macro_| macro_.value.as_deref()),
Some("202400L"),
"C++26 is settled now: GCC 16.2 says 202400L"
);
}
#[test]
fn the_reflection_flag_can_be_turned_off_again() {
let config = from_arguments(&["-freflection", "-fno-reflection"]);
assert!(!config.reflection);
let macros = predefined_macros_of(&config);
assert!(
!macros
.iter()
.any(|macro_| &*macro_.name == "__cpp_impl_reflection"),
"{macros:?}"
);
}
#[test]
fn the_cxx23_and_cxx26_values_match_the_compiler() {
for (standard, expected) in [
("c++23", "202302L"),
("gnu++23", "202302L"),
("c++26", "202400L"),
] {
let config = from_arguments(&[&format!("-std={standard}")]);
let macros = predefined_macros_of(&config);
assert_eq!(
macros
.iter()
.find(|macro_| &*macro_.name == "__cplusplus")
.and_then(|macro_| macro_.value.as_deref()),
Some(expected),
"{standard}"
);
}
}