use cpp_code_analysis::{
CompilerConfig, FileProvider, MemoryFiles, ModuleInfo, PathInterner, scan_imports, walk,
};
use cpp_parser::{CppParser, ParserConfig};
use std::path::Path;
fn info(source: &str) -> ModuleInfo {
let tree = CppParser::parse(source, ParserConfig::default());
ModuleInfo::from_tree(&tree.get_red_root())
}
fn include_walk(files: &MemoryFiles, root: &str) -> (cpp_code_analysis::FileGraph, PathInterner) {
let source = files.read(Path::new(root)).expect("the root");
let tree = CppParser::parse(&source, ParserConfig::default());
let mut interner = PathInterner::new(files.is_case_insensitive());
let graph = walk(
&source,
&tree,
Path::new(root),
files,
&CompilerConfig::new(),
&mut interner,
);
(graph, interner)
}
fn import_scan(files: &MemoryFiles, root: &str) -> (cpp_code_analysis::ModuleGraph, PathInterner) {
let source = files.read(Path::new(root)).expect("the root");
let tree = CppParser::parse(&source, ParserConfig::default());
let mut interner = PathInterner::new(files.is_case_insensitive());
let graph = scan_imports(
&tree,
Path::new(root),
files,
&CompilerConfig::new(),
&mut interner,
);
(graph, interner)
}
fn macros_at(
graph: &cpp_code_analysis::FileGraph,
interner: &PathInterner,
file: &str,
) -> Vec<String> {
let id = interner
.get(Path::new(file))
.unwrap_or_else(|| panic!("{file} was not reached"));
graph
.entry(id)
.unwrap_or_else(|| panic!("{file} has no entry"))
.macros
.iter()
.map(|name| name.to_string())
.collect()
}
#[test]
fn every_module_unit_owns_its_macro_environment() {
let sources = [
"export module m;\n",
"module m;\n",
"export module m:part;\n",
"module m:part;\n",
"module;\n#include <vector>\nexport module m;\n",
"export module m;\nmodule : private;\n",
];
for source in sources {
assert!(
info(source).macros_are_self_contained(),
"{source:?} is a module unit and so owns its macros"
);
}
}
#[test]
fn a_plain_translation_unit_is_not_a_module_unit() {
for source in ["int x;\n", "#include <vector>\n", "import std;\n"] {
assert!(!info(source).macros_are_self_contained(), "{source:?}");
assert!(!info(source).is_module_unit(), "{source:?}");
}
}
#[test]
fn an_include_does_carry_the_includers_macros() {
let files = MemoryFiles::new()
.with_file(
"main.cpp",
"#define OPTION 1\n#include \"body.h\"\n#include \"later.h\"\n",
)
.with_file("body.h", "#ifdef OPTION\nint body_sees_it;\n#endif\n")
.with_file("later.h", "int later;\n");
let (graph, interner) = include_walk(&files, "main.cpp");
assert_eq!(
macros_at(&graph, &interner, "body.h"),
vec!["OPTION".to_string()],
"the header is entered with the includer's macro"
);
assert_eq!(
macros_at(&graph, &interner, "later.h"),
vec!["OPTION".to_string()],
"and the macro outlives the header it was defined for"
);
}
#[test]
fn a_header_define_reaches_the_includer() {
let files = MemoryFiles::new()
.with_file("main.cpp", "#include \"sets.h\"\n#include \"uses.h\"\n")
.with_file("sets.h", "#define FROM_HEADER 1\n")
.with_file("uses.h", "int after;\n");
let (graph, interner) = include_walk(&files, "main.cpp");
assert_eq!(
macros_at(&graph, &interner, "uses.h"),
vec!["FROM_HEADER".to_string()],
"the definition propagated past the include point"
);
}
#[test]
fn an_import_does_not_carry_the_importers_macros() {
let files = MemoryFiles::new()
.with_file("main.cpp", "#define OPTION 1\nimport body;\n")
.with_file(
"body.cppm",
"export module body;\n#ifdef OPTION\nint body_sees_it;\n#endif\n",
);
let (modules, interner) = import_scan(&files, "main.cpp");
let main = interner.get(Path::new("main.cpp")).expect("main.cpp");
let edge = modules
.imports_of(main)
.next()
.expect("the import was recorded");
assert!(edge.outcome.is_resolved(), "{:?}", edge.outcome);
let body = interner.get(Path::new("body.cppm")).expect("body.cppm");
assert!(
modules.analysed.contains(&body),
"the resolved module was followed: {:?}",
modules.analysed
);
let cpp_code_analysis::ImportEdge {
from: _,
from_module: _,
target: _,
is_reexport: _,
outcome: _,
range: _,
} = edge;
}
#[test]
fn the_two_graphs_answer_the_macro_question_differently() {
let body = "#ifdef OPTION\nint conditional;\n#endif\n";
let via_include = MemoryFiles::new()
.with_file("main.cpp", "#define OPTION 1\n#include \"body.h\"\n")
.with_file("body.h", body);
let via_import = MemoryFiles::new()
.with_file("main.cpp", "#define OPTION 1\nimport body;\n")
.with_file("body.cppm", format!("export module body;\n{body}"));
let (includes, interner) = include_walk(&via_include, "main.cpp");
let header = macros_at(&includes, &interner, "body.h");
assert_eq!(
header,
vec!["OPTION".to_string()],
"the include walk has an answer, and carries it"
);
let (modules, interner) = import_scan(&via_import, "main.cpp");
let main = interner.get(Path::new("main.cpp")).expect("main.cpp");
assert!(
modules
.imports_of(main)
.all(|edge| edge.outcome.is_resolved()),
"the module resolved: {:?}",
modules.edges
);
assert!(
modules
.units
.iter()
.all(|unit| unit.module_name.as_ref() == "body"),
"and what the graph records about the second file is its *module*, not a macro state: {:?}",
modules.units
);
}
#[test]
fn a_global_module_fragment_keeps_ordinary_include_semantics() {
let files = MemoryFiles::new()
.with_file(
"unit.cppm",
"#define CONFIG 1\nmodule;\n#include \"global.h\"\nexport module m;\nimport dep;\n",
)
.with_file(
"global.h",
"#ifdef CONFIG\nint header_sees_config;\n#endif\n",
)
.with_file("dep.cppm", "export module dep;\n");
let source = files.read(Path::new("unit.cppm")).expect("unit.cppm");
let shape = info(&source);
assert!(shape.has_global_fragment);
assert!(shape.macros_are_self_contained());
assert_eq!(shape.module_name.as_deref(), Some("m"));
let (includes, interner) = include_walk(&files, "unit.cppm");
let header = macros_at(&includes, &interner, "global.h");
assert!(
header.iter().any(|name| name == "CONFIG"),
"the fragment's `#include` is an ordinary include: {header:?}"
);
let (modules, interner) = import_scan(&files, "unit.cppm");
let unit = interner.get(Path::new("unit.cppm")).expect("unit.cppm");
let edge = modules.imports_of(unit).next().expect("the import");
assert!(edge.outcome.is_resolved(), "{:?}", edge.outcome);
assert_eq!(
edge.from_module.as_deref(),
Some("m"),
"and it is attributed to the named module, not to the fragment"
);
}
#[test]
fn the_fragment_flags_are_independent_of_the_unit_kind() {
let with_fragment = info("module;\n#include <vector>\nexport module m;\n");
let without = info("export module m;\n");
assert!(with_fragment.has_global_fragment);
assert!(!without.has_global_fragment);
assert_eq!(with_fragment.unit, without.unit, "both are interface units");
assert_eq!(with_fragment.module_name, without.module_name);
assert!(!with_fragment.has_private_fragment);
assert!(!without.has_private_fragment);
let private = info("export module m;\nmodule : private;\n");
assert!(private.has_private_fragment);
assert!(!private.has_global_fragment);
}
#[test]
fn only_a_re_export_extends_the_module_interface() {
let files = MemoryFiles::new()
.with_file(
"m.cppm",
"export module m;\nexport import public_dep;\nimport private_dep;\n",
)
.with_file("public_dep.cppm", "export module public_dep;\n")
.with_file("private_dep.cppm", "export module private_dep;\n");
let (graph, interner) = import_scan(&files, "m.cppm");
let m = interner.get(Path::new("m.cppm")).expect("m.cppm");
let reexported: Vec<String> = graph
.imports_of(m)
.filter(|edge| edge.is_reexport)
.map(|edge| edge.target.describe())
.collect();
let private: Vec<String> = graph
.imports_of(m)
.filter(|edge| !edge.is_reexport)
.map(|edge| edge.target.describe())
.collect();
assert_eq!(reexported, vec!["module `public_dep`".to_string()]);
assert_eq!(private, vec!["module `private_dep`".to_string()]);
}