use std::path::Path;
use cpp_code_analysis::{DeclKind, OutlineSymbol, SummaryKey, summarize};
fn outline_of(source: &str) -> Vec<OutlineSymbol> {
summarize(Path::new("/p/a.h"), source, SummaryKey::new(0, 0)).outline()
}
fn names(symbols: &[OutlineSymbol]) -> Vec<&str> {
symbols.iter().map(|symbol| &*symbol.fact.name).collect()
}
#[test]
fn namespaces_and_classes_nest_in_source_order() {
let outline = outline_of(
"namespace ns {\n\
struct Widget { int size; void grow(); };\n\
int free_function();\n\
}\n\
int after;\n",
);
assert_eq!(
names(&outline),
vec!["ns", "after"],
"two roots, in the file's order"
);
let ns = &outline[0];
assert_eq!(ns.fact.kind, DeclKind::Namespace);
assert_eq!(
names(&ns.children),
vec!["Widget", "free_function"],
"the namespace's own contents"
);
let widget = &ns.children[0];
assert_eq!(widget.fact.kind, DeclKind::Type);
assert_eq!(widget.fact.scope.as_deref(), Some("ns"));
assert_eq!(
names(&widget.children),
vec!["size", "grow"],
"and the class's members are one level deeper"
);
assert_eq!(
widget.children[0].fact.scope.as_deref(),
Some("ns::Widget"),
"which is what the scope of a member is"
);
let outer = widget.fact.range;
let inner = widget.fact.name_range;
assert!(
outer.start_offset <= inner.start_offset && inner.end_offset() <= outer.end_offset(),
"the name is inside the declaration: {outer:?} vs {inner:?}"
);
}
#[test]
fn a_branch_nobody_takes_is_still_in_the_outline() {
let outline = outline_of(
"#if 0\n\
struct NeverCompiled { int x; };\n\
#endif\n\
struct Always { int y; };\n",
);
assert_eq!(
names(&outline),
vec!["NeverCompiled", "Always"],
"both classes, in the order they are written"
);
let never = &outline[0];
assert_eq!(
names(&never.children),
vec!["x"],
"with its members, which are in dead text too"
);
}
#[test]
fn a_name_the_file_does_not_write_is_not_in_the_outline() {
let outline = outline_of(
"#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n\
DECLARE_HANDLE(HWND);\n",
);
assert_eq!(
names(&outline),
Vec::<&str>::new(),
"the macro's call is not a declaration here: {outline:?}"
);
}
#[test]
fn locals_are_not_in_the_outline() {
let outline = outline_of(
"void f() {\n\
int local;\n\
struct Inside { int member; };\n\
}\n\
int global;\n",
);
assert_eq!(
names(&outline),
vec!["f", "global"],
"the function and the file-scope variable, and nothing from inside the body"
);
assert!(
outline[0].children.is_empty(),
"not even the class declared in the body, which nothing outside it can name: {:?}",
outline[0].children
);
}