use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
file::coordinates::FileOffset,
};
fn expanded(source: &str, at: &str) -> String {
let memory = MemoryFiles::new().with_file("/p/a.cpp", source);
let providers = SessionFiles::new(OpenDocuments::new(), memory);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the file is cooked");
let offset = source.find(at).expect("the fixture uses the marker") + 1;
session
.the_expansion_of_a_macro(&view, FileOffset::new(offset))
.unwrap_or_else(|| panic!("`{at}` at {offset} has no expansion"))
}
#[test]
fn a_macro_expansion_applies_the_paste_operator() {
let source = "\
#define PASTE(a, b) a ## b
int PASTE(foo, bar) = 1;
";
let expansion = expanded(source, "PASTE(foo");
assert_eq!(expansion.trim(), "foobar", "`a ## b` is one token");
}
#[test]
fn a_macro_expansion_expands_the_macros_in_its_body() {
let source = "\
#define ORIGIN 3
#define WRAPPED (ORIGIN + 1)
int x = WRAPPED;
";
let expansion = expanded(source, "WRAPPED;");
assert!(
expansion.contains('3'),
"`ORIGIN` is a macro and its value is what the compiler sees: {expansion}"
);
assert!(
!expansion.contains("ORIGIN"),
"the name is substituted: {expansion}"
);
}
#[test]
fn a_macro_expansion_applies_the_stringize_operator() {
let source = "\
#define STR(x) #x
const char *s = STR(hello);
";
let expansion = expanded(source, "STR(hello)");
assert!(
expansion.contains("\"hello\""),
"`#x` is a string literal: {expansion}"
);
}
#[test]
fn a_macro_expansion_is_formatted() {
let source = "\
#define ADD(a,b) ((a)+(b))
int n = ADD(1, 2);
";
let expansion = expanded(source, "ADD(1");
assert_eq!(
expansion.trim(),
"((1) + (2))",
"the formatter puts the operators where a reader expects them"
);
}