use cpp_parser::{
CppParser, CppSyntaxKind, CppSyntaxTree, NoSymbols, ParserConfig, SymbolKind, SymbolMap,
SymbolTable,
};
fn shape(
source: &str,
config: ParserConfig<'_>,
) -> (Vec<(CppSyntaxKind, usize, usize)>, Vec<String>, String) {
let tree = CppParser::parse(source, config);
let nodes = tree
.get_red_root()
.descendants()
.map(|node| {
let range = node.text_range();
(
CppSyntaxKind::from(node.kind()),
u32::from(range.start()) as usize,
u32::from(range.end()) as usize,
)
})
.collect();
let errors = tree
.get_errors()
.iter()
.map(|error| error.message.to_string())
.collect();
(nodes, errors, tree.to_source_text())
}
fn sources() -> Vec<String> {
let mut sources: Vec<String> = [
"Widget w(1, 2);\ng(1, 2);\n",
"#define MY_API __declspec(dllexport)\n#define NUMBER_OPTION(op) if (Get(op)) { }\n#define IF_EXIST(op) if (Get(op))\nMY_API Widget *p;\nvoid f() {\n NUMBER_OPTION(a)\n IF_EXIST(b) { g(); }\n}\n",
"void f(void* p) { auto x = (Widget*)p; auto y = (a) - b; auto z = (::a); }\n",
"std::vector<int> v;\nA<B> x;\na < b > c;\n",
"static void Widget::draw(T t) { }\nstruct S { int bits : 3; void f() { for (auto &v: vec) { } } };\n",
"enum E { A = 0, B };\nstatic const struct { int a; } table[] = { { 1 } };\n",
]
.into_iter()
.map(str::to_string)
.collect();
sources.push(include_str!("real_world.cpp").to_string());
sources
}
#[test]
fn an_empty_table_parses_exactly_like_no_table() {
for source in sources() {
let without = shape(&source, ParserConfig::default());
let nothing = shape(
&source,
ParserConfig::default().with_symbol_table(&NoSymbols),
);
let empty = shape(
&source,
ParserConfig::default().with_symbol_table(&SymbolMap::new()),
);
assert_eq!(
without, nothing,
"`NoSymbols` must be indistinguishable from no table at all"
);
assert_eq!(
without, empty,
"an empty `SymbolMap` must be indistinguishable from no table at all"
);
}
}
struct EverythingIsAMacro;
impl SymbolTable for EverythingIsAMacro {
fn kind_of(&self, _name: &str) -> Option<SymbolKind> {
Some(SymbolKind::Macro {
function_like: true,
body: cpp_parser::MacroBody::Statement,
})
}
}
struct EverythingIsAType;
impl SymbolTable for EverythingIsAType {
fn kind_of(&self, _name: &str) -> Option<SymbolKind> {
Some(SymbolKind::Type)
}
}
#[test]
fn a_hostile_table_cannot_break_the_tree() {
for source in sources() {
for table in [
&EverythingIsAMacro as &dyn SymbolTable,
&EverythingIsAType as &dyn SymbolTable,
] {
let tree: CppSyntaxTree =
CppParser::parse(&source, ParserConfig::default().with_symbol_table(table));
assert_eq!(
tree.to_source_text(),
source,
"a table must never cost a token, whoever is answering"
);
for node in tree.get_red_root().descendants() {
if let Some(parent) = node.parent() {
let (inner, outer) = (node.text_range(), parent.text_range());
assert!(
outer.contains_range(inner),
"{:?} escapes its parent {:?}",
inner,
outer
);
}
}
}
}
}
#[test]
fn a_table_described_type_settles_the_declaration_question() {
let symbols = SymbolMap::new()
.with("Widget", SymbolKind::Type)
.with("g", SymbolKind::Function)
.with("Vec", SymbolKind::Template);
let source = "Widget w(a, b);\n";
let tree = CppParser::parse(source, ParserConfig::default().with_symbol_table(&symbols));
assert_eq!(tree.get_errors(), []);
assert_eq!(
tree.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer)
.count(),
1,
"the table's `Type` answer makes it a declaration"
);
let source = "g(a, b);\n";
let tree = CppParser::parse(source, ParserConfig::default().with_symbol_table(&symbols));
assert_eq!(tree.get_errors(), []);
assert_eq!(
tree.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr)
.count(),
1,
"the table's `Function` answer refuses the declaration reading"
);
let source = "void f(void* p) { auto x = (Widget)p; }\n";
let tree = CppParser::parse(source, ParserConfig::default().with_symbol_table(&symbols));
assert_eq!(
tree.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CastExpr)
.count(),
1,
"`(Widget)p` is a cast when the table says `Widget` is a type"
);
}
#[test]
fn a_table_can_be_built_and_shared_from_outside_the_crate() {
let mut symbols = SymbolMap::new();
symbols.insert("Widget", SymbolKind::Type);
symbols.insert("Vec", SymbolKind::Template);
symbols.insert("g", SymbolKind::Function);
symbols.insert("count", SymbolKind::Variable);
symbols.insert("ns", SymbolKind::Namespace);
let config = ParserConfig::default().with_symbol_table(&symbols);
let table = config.symbol_table().expect("the table is in force");
assert_eq!(table.kind_of("Widget"), Some(SymbolKind::Type));
assert_eq!(table.kind_of("Vec"), Some(SymbolKind::Template));
assert_eq!(table.kind_of("g"), Some(SymbolKind::Function));
assert_eq!(
table.kind_of("unknown_to_the_index"),
None,
"an unresolved name is unknown — never a `no`"
);
let source = "Widget w(1, 2);\n";
let with = shape(source, ParserConfig::default().with_symbol_table(&symbols));
let without = shape(source, ParserConfig::default());
assert_eq!(with, without);
assert!(ParserConfig::default().symbol_table().is_none());
}
#[test]
fn a_namespace_behind_a_linkage_specification_opens_it() {
use cpp_parser::{BodyShape, NothingAtAll, shape_of_a_body};
assert_eq!(
shape_of_a_body("namespace std {"),
BodyShape::OpensANamespace(vec!["std".to_string()])
);
assert_eq!(
shape_of_a_body("inline namespace __p2286 {"),
BodyShape::OpensANamespace(vec!["__p2286".to_string()])
);
let _ = NothingAtAll;
assert_eq!(
shape_of_a_body("extern \"C++\" { namespace std {"),
BodyShape::OpensANamespace(vec!["std".to_string()]),
"`_STD_BEGIN` under `c++latest` is a linkage block in front of the namespace"
);
assert_eq!(
shape_of_a_body("extern \"C\" { inline namespace v1 {"),
BodyShape::OpensANamespace(vec!["v1".to_string()])
);
assert_eq!(
shape_of_a_body("extern \"C\" {"),
BodyShape::OpensABlock,
"a linkage block is a block, not a namespace"
);
assert_ne!(
shape_of_a_body("extern \"C\" int f();"),
BodyShape::OpensANamespace(vec!["f".to_string()])
);
}
#[test]
fn an_unexpanded_word_in_a_body_keeps_the_shape_out_of_reach() {
use cpp_parser::{BodyShape, shape_of_a_body};
assert_eq!(
shape_of_a_body("_EXTERN_CXX_WORKAROUND namespace std {"),
BodyShape::Other,
"an unexpanded name is kept, so the reader cannot see past it"
);
assert_eq!(
shape_of_a_body("extern \"C++\" { namespace std {"),
BodyShape::OpensANamespace(vec!["std".to_string()]),
"resolved, the same body is a namespace head"
);
}