use cpp_parser::{CppParser, CppSyntaxKind, CppSyntaxNode, CppSyntaxTree, ParserConfig};
const DEFINITION: &str =
"int main(argc, argv)\n int argc;\n char *argv[];\n{ return argc; }\n";
const HEAD_WITHOUT_A_BODY: &str = "int main(argc, argv)\nint argc;\nchar *argv[];\n";
const SPLIT_BRANCHES: &str = "\
#if defined(__CLASSIC_C__)\n\
int main(argc, argv)\n\
int argc;\n\
char* argv[];\n\
#else\n\
int main(int argc, char* argv[])\n\
#endif\n\
{\n\
return 0;\n\
}\n";
fn tree(source: &str) -> CppSyntaxTree {
CppParser::parse(source, ParserConfig::default())
}
fn parses(source: &str) {
let parsed = tree(source);
assert_eq!(
parsed.get_errors(),
[],
"{source:?} must parse cleanly, got {:?}",
parsed.get_errors()
);
let unclaimed = parsed.get_red_root().descendants().any(|node| {
matches!(
CppSyntaxKind::from(node.kind()),
CppSyntaxKind::ErrorNode | CppSyntaxKind::MissingNode
)
});
assert!(!unclaimed, "{source:?} leaves an ErrorNode behind");
assert_eq!(parsed.to_source_text(), source, "{source:?} stays lossless");
}
fn node(source: &str, kind: CppSyntaxKind) -> CppSyntaxNode {
tree(source)
.get_red_root()
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == kind)
.unwrap_or_else(|| panic!("no {kind:?} in {source:?}"))
}
fn count(source: &str, kind: CppSyntaxKind) -> usize {
tree(source)
.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == kind)
.count()
}
fn children_of(node: &CppSyntaxNode) -> Vec<CppSyntaxKind> {
node.children()
.map(|child| CppSyntaxKind::from(child.kind()))
.collect()
}
fn file_scope_declarations(source: &str) -> Vec<CppSyntaxNode> {
tree(source)
.get_red_root()
.children()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declaration)
.collect()
}
#[test]
fn an_old_style_definition_is_one_declaration_with_its_body() {
parses(DEFINITION);
let declaration = node(DEFINITION, CppSyntaxKind::Declaration);
assert_eq!(
children_of(&declaration),
vec![
CppSyntaxKind::DeclSpecifierSeq,
CppSyntaxKind::InitDeclarator,
CppSyntaxKind::CompoundStat,
],
"the definition is one declaration, body included"
);
assert_eq!(
declaration
.parent()
.map(|parent| CppSyntaxKind::from(parent.kind())),
Some(CppSyntaxKind::TranslationUnit),
"and it is the only thing at file scope"
);
let declarator = node(DEFINITION, CppSyntaxKind::Declarator);
assert_eq!(
children_of(&declarator),
vec![CppSyntaxKind::NameExpr, CppSyntaxKind::ParameterList]
);
assert_eq!(
children_of(&node(DEFINITION, CppSyntaxKind::InitDeclarator)),
vec![
CppSyntaxKind::Declarator,
CppSyntaxKind::OldStyleParameterList,
]
);
let list = node(DEFINITION, CppSyntaxKind::OldStyleParameterList);
assert_eq!(
children_of(&list),
vec![CppSyntaxKind::Declaration, CppSyntaxKind::Declaration]
);
assert_eq!(list.text().to_string(), "int argc;\n char *argv[];");
}
#[test]
fn the_names_are_read_as_parameters_and_the_truth_as_a_second_list() {
parses(DEFINITION);
assert_eq!(
node(DEFINITION, CppSyntaxKind::ParameterList)
.text()
.to_string(),
"(argc, argv)",
"`argc` and `argv` are read as the parameter list, because a parameter's type may be a name"
);
assert_eq!(
count(DEFINITION, CppSyntaxKind::Parameter),
2,
"which makes them two unnamed parameters of type `argc` and `argv`"
);
let declarations: Vec<String> = node(DEFINITION, CppSyntaxKind::OldStyleParameterList)
.children()
.map(|declaration| declaration.text().to_string())
.collect();
assert_eq!(declarations, ["int argc;", "char *argv[];"]);
}
#[test]
fn an_old_style_definition_after_another_declaration_is_still_a_definition() {
let source = format!("int x;\n{DEFINITION}");
parses(&source);
assert_eq!(
file_scope_declarations(&source).len(),
2,
"`x`, then the function"
);
assert_eq!(count(&source, CppSyntaxKind::CompoundStat), 1, "one body");
assert_eq!(
count(&source, CppSyntaxKind::OldStyleParameterList),
1,
"and one old-style list — `int x;` is not part of it"
);
}
#[test]
fn a_head_without_a_body_is_still_one_declaration() {
parses(HEAD_WITHOUT_A_BODY);
let declaration = node(HEAD_WITHOUT_A_BODY, CppSyntaxKind::Declaration);
assert_eq!(
children_of(&declaration),
vec![
CppSyntaxKind::DeclSpecifierSeq,
CppSyntaxKind::InitDeclarator
],
"the declaration is complete at the last parameter's `;`"
);
assert_eq!(
children_of(&declaration.parent().expect("file scope")),
vec![CppSyntaxKind::Declaration],
"and nothing is left over beside it"
);
assert_eq!(
count(HEAD_WITHOUT_A_BODY, CppSyntaxKind::CompoundStat),
0,
"there is no body to find"
);
}
#[test]
fn the_head_and_the_body_may_sit_in_different_conditional_branches() {
parses(SPLIT_BRANCHES);
assert_eq!(file_scope_declarations(SPLIT_BRANCHES).len(), 2);
assert_eq!(count(SPLIT_BRANCHES, CppSyntaxKind::CompoundStat), 1);
let old_style = tree(SPLIT_BRANCHES)
.get_red_root()
.descendants()
.find(|node| {
CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declaration
&& node.descendants().any(|child| {
CppSyntaxKind::from(child.kind()) == CppSyntaxKind::OldStyleParameterList
})
})
.expect("the old-style branch is a declaration");
assert_eq!(
old_style.text().to_string(),
"int main(argc, argv)\nint argc;\nchar* argv[];"
);
let body = node(SPLIT_BRANCHES, CppSyntaxKind::CompoundStat);
let owner = body.parent().expect("the body has an owner");
assert_eq!(
CppSyntaxKind::from(owner.kind()),
CppSyntaxKind::Declaration
);
assert!(
owner
.text()
.to_string()
.starts_with("int main(int argc, char* argv[])"),
"the body belongs to the modern head, got {:?}",
owner.text().to_string()
);
}
#[test]
fn a_modern_function_declarator_is_not_read_as_an_old_style_one() {
for source in [
"void f(int a) { }",
"void g();",
"static void A::f<int>(int);",
"struct S { void f() const; void g() noexcept; virtual void h() override; };",
"struct S { S() : a(1) { } int a; };",
"template <typename T> void f(T t) requires C<T>;",
"auto l = [](int a) { return a; };",
] {
parses(source);
assert_eq!(
count(source, CppSyntaxKind::OldStyleParameterList),
0,
"{source:?} is not an old-style definition"
);
}
}
#[test]
fn the_list_holds_declarations_and_stops_at_anything_else() {
let source = "int f(a)\nint a;\nx = 1;\n";
assert_eq!(
children_of(&node(source, CppSyntaxKind::OldStyleParameterList)),
vec![CppSyntaxKind::Declaration],
"one declaration in the list"
);
assert_eq!(
node(source, CppSyntaxKind::OldStyleParameterList)
.text()
.to_string(),
"int a;",
"and the statement after it is not part of it"
);
}