use std::collections::HashMap;
use std::path::PathBuf;
use cpp_code_analysis::summary::MacroDefinitions;
use cpp_code_analysis::{CompilerConfig, FileIndexer, MemoryFiles, SummaryKey, TranslationUnit};
fn unit_of(files: &[(&str, &str)], root: &str) -> TranslationUnit {
let mut provider = MemoryFiles::new();
for (path, text) in files {
provider.insert(*path, *text);
}
let config = CompilerConfig::default().with_include_path(PathBuf::from("/p"));
let indexer = FileIndexer::new(&provider, &config);
let mut summaries: HashMap<PathBuf, cpp_code_analysis::FileSummary> = HashMap::new();
let mut texts: HashMap<PathBuf, String> = HashMap::new();
for (path, text) in files {
let path = PathBuf::from(*path);
summaries.insert(
path.clone(),
indexer.index(&path, text, SummaryKey::new(0, 0)),
);
texts.insert(path, text.to_string());
}
TranslationUnit::walk(
summaries.get(std::path::Path::new(root)).expect("indexed"),
|wanted| {
summaries
.get(wanted)
.map(|summary| (summary, texts.get(wanted).map(String::as_str).unwrap_or("")))
},
&cpp_code_analysis::include::graph::Marked::default(),
&mut MacroDefinitions::default(),
false,
&cpp_code_analysis::WalkCache::new(),
)
}
#[test]
fn a_guarded_define_in_the_same_file_is_in_force_too() {
let unit = unit_of(
&[
(
"/p/same.h",
"#define SAME 1\n#ifdef SAME\n#define OWN_INSIDE 1\n#endif\n",
),
("/p/root.cpp", "#include \"same.h\"\nint x;\n"),
],
"/p/root.cpp",
);
let own = unit.macro_at(std::path::Path::new("/p/same.h"), "OWN_INSIDE", usize::MAX);
assert_eq!(
own.map(|found| found.defined),
Some(true),
"`SAME` is defined one line above the `#ifdef SAME` that asks about it"
);
}
#[test]
fn a_guarded_define_is_in_force_after_the_include_that_defines_its_condition() {
let unit = unit_of(
&[
("/p/base.h", "#define BASE 1\n"),
(
"/p/guarded.h",
"#include \"base.h\"\n#ifdef BASE\n#define INSIDE 1\n#endif\n",
),
("/p/root.cpp", "#include \"guarded.h\"\nint x;\n"),
],
"/p/root.cpp",
);
let base = unit
.macro_at(std::path::Path::new("/p/guarded.h"), "BASE", usize::MAX)
.expect("BASE was reached");
assert!(base.defined, "the include above the guard defined BASE");
let inside = unit
.macro_at(std::path::Path::new("/p/guarded.h"), "INSIDE", usize::MAX)
.expect("INSIDE is in guarded.h");
assert!(
inside.defined,
"a `#ifdef BASE` after `#include \"base.h\"` is in force: {:?}",
inside.defined
);
let inherited = unit
.macro_at(std::path::Path::new("/p/root.cpp"), "INSIDE", usize::MAX)
.expect("root.cpp includes guarded.h");
assert!(
inherited.defined,
"and it reaches the file that includes it"
);
}