use cpp_parser::{CppParser, CppSyntaxKind, ParserConfig};
fn parses(source: &str) {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(
tree.get_errors(),
[],
"{source:?} must parse cleanly, got {:?}",
tree.get_errors()
);
assert_eq!(tree.to_source_text(), source, "{source:?} stays lossless");
}
fn count(source: &str, kind: CppSyntaxKind) -> usize {
let tree = CppParser::parse(source, ParserConfig::default());
tree.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == kind)
.count()
}
#[test]
fn a_call_whose_argument_is_an_address_of_expression_is_a_call() {
parses("void g() { int n = 0; take(&n); }");
assert_eq!(
count("void g() { int n = 0; take(&n); }", CppSyntaxKind::CallExpr),
1,
"`take(&n)` is a call"
);
assert_eq!(
count(
"void g() { int n = 0; take(&n, 1); }",
CppSyntaxKind::CallExpr
),
1,
"and it stays one with a second argument"
);
assert_eq!(
count(
"void g() { int n = 0; take(&n); take(n); }",
CppSyntaxKind::CallExpr
),
2,
"and the plain call beside it is still one"
);
}
#[test]
fn sizeof_reads_an_operand_that_is_not_a_bare_name() {
for source in [
"void f() { auto n = sizeof(a[0]); }\n",
"void f() { auto n = sizeof(a.b); }\n",
"void f() { auto n = sizeof(a->b); }\n",
"void f() { auto n = sizeof(a + b); }\n",
"void f() { auto n = sizeof(a()); }\n",
"void f() { auto n = sizeof(*p); }\n",
"void f() { auto n = sizeof(names) / sizeof(names[0]); }\n",
"void f() { auto n = typeid(a[0]); }\n",
"void f() { auto n = sizeof(int); }\n",
"void f() { auto n = sizeof(int*); }\n",
"void f() { auto n = sizeof(const char*); }\n",
"void f() { auto n = sizeof(unsigned long); }\n",
"void f() { auto n = sizeof(std::vector<int>); }\n",
"void f() { auto n = sizeof(struct S); }\n",
"void f() { auto n = sizeof(union U); }\n",
"void f() { auto n = sizeof(enum E); }\n",
"void f() { auto n = sizeof(struct S*); }\n",
"void f() { auto n = (struct S*)p; }\n",
"void f() { struct S* p = 0; p = (struct S*)q; }\n",
"void f() { auto n = sizeof x; }\n",
"void f() { auto n = sizeof...(Ts); }\n",
"void f() { auto n = alignof(a[0]); }\n",
] {
parses(source);
}
assert!(
!CppParser::parse(
"void f() { auto n = sizeof(a +); }\n",
ParserConfig::default()
)
.get_errors()
.is_empty(),
"a truncated operand is still reported"
);
}
#[test]
fn a_directive_inside_a_literal_run_is_read_as_a_directive() {
parses(
"void f() { const char* s = \"a\"\n#if X\n \"b\"\n#else\n \"c\"\n#endif\n \"d\"; }\n",
);
let conditional = "void f() { const char* s = \"a\"\n#if X\n \"b\"\n#endif\n \"c\"; }\n";
assert_eq!(
count(conditional, CppSyntaxKind::LiteralExpr),
1,
"the run is one literal"
);
assert_eq!(
count(conditional, CppSyntaxKind::PreprocessorDirective),
2,
"and both directives are in the tree"
);
assert!(
!CppParser::parse("void f() { x = 1 # 2; }\n", ParserConfig::default())
.get_errors()
.is_empty(),
"a stray `#` in an expression is still reported"
);
}
#[test]
fn an_array_type_is_read_as_a_type_and_an_index_as_an_expression() {
for source in [
"void f() { auto n = sizeof(int[4]); }\n",
"void f() { auto n = sizeof(char[256]); }\n",
"void f() { auto n = sizeof(int[2][3]); }\n",
"void f() { auto n = sizeof(int[]); }\n",
"void f() { auto n = sizeof(int*[4]); }\n",
"void f() { auto n = sizeof(a[0]); }\n",
"void f() { auto n = sizeof(a.b); }\n",
"void f() { auto x = a[b < c]; }\n",
] {
parses(source);
}
for source in [
"void f() { Vec<int[4]> v; }\n",
"void f() { auto v = Vec<int[4]>{}; }\n",
"void f() { g<Vec<int[4]>>(); }\n",
"void f() { Vec<arr[0]> v; }\n",
] {
parses(source);
}
assert_eq!(
count(
"void f() { auto n = sizeof(int[4]); }\n",
CppSyntaxKind::ArrayType
),
1,
"the bound is part of the type"
);
assert_eq!(
count(
"void f() { auto n = sizeof(a[0]); }\n",
CppSyntaxKind::ArrayType
),
0,
"an index is not an array type"
);
assert_eq!(
count(
"void f() { auto n = sizeof(a[0]); }\n",
CppSyntaxKind::IndexExpr
),
1
);
assert_eq!(
count(
"void f() { auto p = new int[4]; }\n",
CppSyntaxKind::ArrayType
),
1
);
let new_expr = "void f() { auto p = new int[4]; }\n";
let tree = CppParser::parse(new_expr, ParserConfig::default());
let type_id = tree
.get_red_root()
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TypeId)
.expect("the allocation names a type");
assert_eq!(
type_id.text().to_string().trim(),
"int",
"the bounds are the new-declarator's, not the type's"
);
}
#[test]
fn adjacent_string_literals_are_one_literal() {
for source in [
"void f() { const char *s = \"a\"; }\n",
"void f() { const char *s = \"a\" \"b\"; }\n",
"void f() { const char *s = \"a\" \"b\" \"c\"; }\n",
"void f() { g(\"a\" \"b\", 1); }\n",
"void f() { auto s = \"a\" \"b\"; }\n",
"void f() { if (s == \"a\" \"b\") { } }\n",
"const char *file_scope = \"a\" \"b\";\n",
"void f() {\n const char *msg =\n \"line one\\n\"\n \"line two\\n\"\n \"line three\\n\";\n}\n",
"void f() { const char *s = \"INFO\" \":\" \"compiler[\" COMPILER_ID \"]\"; }\n",
"void f() { const char *s = \"a\" MACRO \"b\" OTHER \"c\"; }\n",
"void f() { char c = 'a'; auto n = 1 + 2; auto b = true; }\n",
] {
parses(source);
}
assert_eq!(
count(
"const char *s = \"a\" \"b\" \"c\";\n",
CppSyntaxKind::LiteralExpr
),
1
);
parses("void f() { auto x = \"a\"_km; }\n");
assert_eq!(
count(
"void f() { auto x = \"a\"_km; }\n",
CppSyntaxKind::LiteralExpr
),
1
);
assert!(
!CppParser::parse("void f() { auto x = 1 2; }\n", ParserConfig::default())
.get_errors()
.is_empty(),
"`1 2` is not a literal run"
);
}
#[test]
fn a_for_header_reads_its_step_as_an_expression() {
for source in [
"void f() { for (;; i++) { } }\n",
"void f() { for (;; ++i) { } }\n",
"void f() { for (;; i++, k++) { } }\n",
"void f() { for (i = 0; i < n; i++) { } }\n",
"void f() { for (i = 0, k = 0; i < n; i++, k++) { } }\n",
"void f() { for (int i = 0; i < n; i++) { } }\n",
"void f() { for (int i = 0, k = 0; i < n; i++, k++) { } }\n",
"void f() { for (auto x : items) { } }\n",
"void f() { for (v : items) { } }\n",
"void f() { for (;;) { } }\n",
] {
parses(source);
}
let source = "void f() { for (;; i++, k++) { } }\n";
assert_eq!(count(source, CppSyntaxKind::ExpressionStat), 1);
assert_eq!(
count(source, CppSyntaxKind::ForStat),
1,
"the header is still a for statement"
);
assert_eq!(
count(source, CppSyntaxKind::Declaration),
1,
"only the function definition is a declaration"
);
}
#[test]
fn a_parenthesized_expression_is_its_own_node() {
for source in [
"void f() { x = (a); }\n",
"void f() { x = (a + b); }\n",
"void f() { x = (f()); }\n",
"void f() { x = ((a)); }\n",
"void f() { x = a * (b + c); }\n",
"void f() { if ((a)) { } }\n",
"void f() { while ((a && b)) { } }\n",
"void f() { f((a), (b)); }\n",
] {
parses(source);
}
assert_eq!(
count("void f() { x = ((a)); }\n", CppSyntaxKind::ParenExpr),
2,
"nested parentheses are two nodes"
);
}
#[test]
fn the_conditional_operator_parses_around_a_parenthesized_condition() {
for source in [
"void f() { auto x = a ? b : c; }\n",
"void f() { x = (a > b) ? a : b; }\n",
"void f() { auto x = (a > b) ? a : b; }\n",
"void f() { return (a) ? (b) : (c); }\n",
"void f() { x = (a ? b : c) ? d : e; }\n",
"void f() { x = cond ? (a + b) : (c + d); }\n",
"void f() { x = a ? b : c ? d : e; }\n",
"void f() { x = a == b ? 1 : 2; }\n",
] {
parses(source);
}
assert_eq!(
count(
"void f() { x = a ? b : c ? d : e; }\n",
CppSyntaxKind::TernaryExpr
),
2,
"a conditional in the false branch nests"
);
}
#[test]
fn an_assignment_containing_a_conditional_is_an_expression() {
let tree = CppParser::parse("void f() { x = a ? b : c; }\n", ParserConfig::default());
let root = tree.get_red_root();
let ternary = root
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::TernaryExpr)
.expect("the conditional is a ternary expression");
assert!(
ternary
.descendants()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::BinaryExpr),
"the assignment is the conditional's condition"
);
assert_eq!(
count("void f() { x = a ? b : c; }\n", CppSyntaxKind::TernaryExpr),
1
);
assert_eq!(
count("void f() { x = a ? b : c; }\n", CppSyntaxKind::Initializer),
0,
"an assignment has no initialiser"
);
}
#[test]
fn a_lambda_is_its_own_node_with_its_capture_list() {
for source in [
"void f() { auto a = [] {}; }\n",
"void f() { auto b = []() { return 1; }; }\n",
"void f() { auto c = [](int x) { return x; }; }\n",
"void f() { auto d = [&](int x) { return x + 1; }; }\n",
"void f() { auto e = [x](int y) { return x + y; }; }\n",
"void f() { auto g = [&x, y]() { return x + y; }; }\n",
"void f() { auto h = [=]() { return x; }; }\n",
"void f() { auto i = [this]() { return n; }; }\n",
"void f() { auto j = [*this]() { return n; }; }\n",
"void f() { auto k = []() mutable { }; }\n",
"void f() { auto l = []() constexpr { }; }\n",
"void f() { auto m = []() noexcept { }; }\n",
"void f() { auto n = [](int x) -> int { return x; }; }\n",
"void f() { auto o = [p = 1]() { return p; }; }\n",
"void f() { auto q = [n](auto x) { return x; }; }\n",
"void f() { auto r = [x, &y]() { }; }\n",
"auto file_scope = [](int x) { return x; };\n",
"void f() { std::sort(v.begin(), v.end(), [](int i, int j) { return i < j; }); }\n",
"void f() { call([](int i) { return i; }, 1); }\n",
] {
parses(source);
}
assert_eq!(
count(
"void f() { auto g = [&x, y]() { return x + y; }; }\n",
CppSyntaxKind::LambdaCaptureList
),
1
);
assert_eq!(
count(
"void f() { auto g = [&x, y]() { return x + y; }; }\n",
CppSyntaxKind::LambdaCapture
),
2,
"one node per capture"
);
assert_eq!(
count(
"void f() { auto g = [&x, y]() { return x + y; }; }\n",
CppSyntaxKind::LambdaExpr
),
1
);
assert_eq!(
count(
"void f() { auto o = [p = 1]() { return p; }; }\n",
CppSyntaxKind::LambdaCapture
),
1
);
}
#[test]
fn the_index_operator_is_not_stolen_by_the_lambda_rule() {
for source in [
"void f() { arr[i] = 1; }\n",
"void f() { auto x = a[b]; }\n",
"void f() { auto x = a[b + c]; }\n",
"void f() { auto x = m[k][j]; }\n",
"void f() { int a[] = {1, 2}; }\n",
"void f() { f(a[0], b[1]); }\n",
] {
parses(source);
}
assert_eq!(
count("void f() { auto x = a[b]; }\n", CppSyntaxKind::LambdaExpr),
0,
"an index is not a lambda"
);
assert_eq!(
count("void f() { auto x = a[b]; }\n", CppSyntaxKind::IndexExpr),
1
);
}
#[test]
fn a_lambda_body_is_a_compound_statement() {
for source in [
"void f() { auto g = []() { int x = 1; return x; }; }\n",
"void f() { auto g = []() { if (a) { return 1; } return 2; }; }\n",
"void f() { auto g = []() { auto h = []() { return 1; }; return h(); }; }\n",
"void f() { auto g = [](int x) { for (int i = 0; i < x; ++i) { } }; }\n",
] {
parses(source);
}
}
#[test]
fn a_braced_init_list_is_read_where_the_grammar_wants_an_initializer_clause() {
for source in [
"void f() { x = { 1 }; }\n",
"void f() { x = { 1, 2 }; }\n",
"void f() { x = {}; }\n",
"void f() { x += { 1 }; }\n",
"void f() { x = { 1 }, y = { 2 }; }\n",
"void f() { v.push_back({ 1, 2 }); }\n",
"void f() { v.push_back({}); }\n",
"void f() { f({ 1 }); }\n",
"void f() { f(a, { 1 }); }\n",
"void f() { f({ 1 }, { 2 }); }\n",
"void f() { m.insert({ key, value }); }\n",
"void f() { int x = { 1 }; }\n",
"void f() { int a[] = { 1, 2 }; }\n",
"void f() { auto p = Pair{ 1, 2 }; }\n",
"void f() { std::vector<int> v{ 1, 2 }; }\n",
] {
parses(source);
}
assert_eq!(
count("void f() { x = { 1, 2 }; }\n", CppSyntaxKind::InitListExpr),
1
);
assert_eq!(
count("void f() { x = { 1, 2 }; }\n", CppSyntaxKind::Initializer),
0,
"an assignment's right-hand side is not a declaration's initialiser"
);
assert_eq!(
count(
"void f() { v.push_back({ 1, 2 }); }\n",
CppSyntaxKind::InitListExpr
),
1
);
assert_eq!(
count(
"void f() { int xx[] = { 1, 2 }; }\n",
CppSyntaxKind::InitListExpr
),
1,
"a declaration's initialiser is still an InitListExpr, once"
);
assert_eq!(
count(
"template <typename T> void f(T t) requires C<T> { }\n",
CppSyntaxKind::InitListExpr
),
0,
"the brace after a constraint is the body"
);
}
#[test]
fn a_template_id_does_not_claim_the_next_one() {
for source in [
"void f() { C<T> && C2<T>; }\n",
"void f() { C<T> || C2<T>; }\n",
"void f() { C<T> && C2<T> && C3<T>; }\n",
"void f() { T<A>::value < T<B>::value; }\n",
"void f() { auto x = C<T> && C2<T>; }\n",
"void f() { if (C<T> && C2<T>) { } }\n",
"void f() { auto x = f<A>(1) < f<B>(2); }\n",
"void f() { std::vector<std::vector<int>> v; }\n",
"void f() { std::map<int, std::vector<int>> m; }\n",
] {
parses(source);
}
assert_eq!(
count(
"void f() { C<T> && C2<T>; }\n",
CppSyntaxKind::TemplateArgumentList
),
2,
"two template-ids, two argument lists"
);
assert_eq!(
count("void f() { C<T> && C2<T>; }\n", CppSyntaxKind::BinaryExpr),
1,
"the `&&` joins them rather than being absorbed"
);
}
#[test]
fn a_declarator_name_is_never_a_bare_template_id() {
let source = "void f() { C<T> && C2<T>; }\n";
parses(source);
assert_eq!(
count(source, CppSyntaxKind::ExpressionStat),
1,
"the statement is an expression"
);
assert_eq!(
count(source, CppSyntaxKind::Declaration),
1,
"only the function definition is a declaration"
);
assert_eq!(
count(source, CppSyntaxKind::RValueReferenceType),
0,
"`&&` is the logical operator here, not a declarator's rvalue reference"
);
for source in [
"extern template void f<int>(int);\n",
"extern template class C<int>;\n",
"extern template struct S<int>;\n",
"extern template int v<int>;\n",
"template <typename T> struct A<T*> { };\n",
"template <typename T> void S<T>::f() { }\n",
"template <typename T> void S<T>::f() requires C<T> { }\n",
"A<int> x;\n",
"void f() { A<int> x; }\n",
"void f() { std::vector<int> v; }\n",
"void f() { T<A>::value = 1; }\n",
] {
parses(source);
}
let source = "extern template void f<int>(int);\nvoid g() { C<T> && C2<T>; }\n";
parses(source);
assert_eq!(
count(source, CppSyntaxKind::ExpressionStat),
1,
"the declaration after an instantiation is still read by the ordinary rules"
);
}
#[test]
fn a_class_definition_without_its_semicolon_is_reported() {
let errors = |source: &str| -> Vec<String> {
let tree = CppParser::parse(source, ParserConfig::default());
tree.get_errors()
.iter()
.map(|error| error.message.clone())
.collect()
};
for source in [
"struct S { int a; }\nstruct After { int b; };\n",
"struct S { int a; }\nint g;\n",
"class C {}\nint main() { C c; return 0; }\n",
"enum E { A }\nstruct After { int b; };\n",
"struct S { int a; }\n",
] {
let reported = errors(source);
assert!(
reported.iter().any(|message| message.contains(';')),
"the missing `;` has to be said: {source:?} reported {reported:?}"
);
}
for source in [
"struct S { int a; };\nstruct After { int b; };\n",
"struct S { int a; } x;\nstruct After { int b; };\n",
"struct S { int a; } *p;\nstruct After { int b; };\n",
"enum E { A };\nstruct After { int b; };\n",
] {
let reported = errors(source);
assert!(
reported.is_empty(),
"this spelling is legal and must not be refused: {source:?} reported {reported:?}"
);
}
}
#[test]
fn a_comma_expression_inside_a_parenthesised_initializer_parses() {
for text in [
"void f() { const int n(a, std::g<int>(1).p); }\n",
"void f() { const int n(std::g<int>(1)); }\n",
"void f() { static T n(a, std::g<int>(1).p); }\n",
"void f() { const T n = (a, std::g<int>(1).p); }\n",
] {
let tree = cpp_parser::CppParser::parse(text, cpp_parser::ParserConfig::default());
let errors = tree.get_errors();
assert!(errors.is_empty(), "{text}: {errors:?}");
}
}
#[test]
fn a_member_name_is_not_on_the_next_line() {
let source =
"struct Widget { int size; };\nvoid f()\n{\nWidget * p;\np->\n\nWidget w;\nw.size;\n}\n";
let tree = CppParser::parse(source, ParserConfig::default());
let body = tree
.get_red_root()
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CompoundStat)
.expect("the body of `f`");
let shapes: Vec<String> = body
.children()
.map(|node| {
format!(
"{:?} {:?}",
CppSyntaxKind::from(node.kind()),
node.text().to_string().trim()
)
})
.collect();
assert!(
shapes.contains(&"ExpressionStat \"p->\"".to_string()),
"the arrow ends where its line does: {shapes:?}"
);
assert!(
shapes
.iter()
.any(|shape| shape.starts_with("Declaration") && shape.contains("Widget w")),
"the declaration below the arrow is a declaration: {shapes:?}"
);
assert!(
shapes.contains(&"ExpressionStat \"w.size;\"".to_string()),
"and the member expression below it is still its own statement: {shapes:?}"
);
}