use cpp_parser::{
CppAstNode, CppAstToken, CppDeclaration, CppExpr, CppParser, CppStat, CppSyntaxKind,
CppTranslationUnit, ParserConfig,
};
fn unit(source: &str) -> (CppTranslationUnit, cpp_parser::CppSyntaxTree) {
let tree = CppParser::parse(source, ParserConfig::default());
let root = CppTranslationUnit::cast(tree.get_red_root()).expect("root is a translation unit");
(root, tree)
}
#[test]
fn a_directive_can_stand_where_the_right_operand_goes() {
let source = "\
namespace std {
class Impl {
public:
void f() {
if (1 == 2
||
#if A
3 == 4
#else
5 == 6
#endif
)
return;
}
int m;
};
class Following { };
}
";
let (root, tree) = unit(source);
assert_eq!(tree.get_errors(), [], "the fixture parses cleanly");
let following = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppClassDef::cast)
.find(|definition| definition.get_name_text().as_deref() == Some("Following"))
.expect("`Following` is a class");
let enclosing = following
.syntax()
.ancestors()
.skip(1)
.filter(|node| cpp_parser::CppClassDef::cast(node.clone()).is_some())
.count();
assert_eq!(
enclosing, 0,
"a class written after the member is not inside it"
);
}
fn decl_names(source: &str) -> Vec<String> {
let (root, _) = unit(source);
root.get_declarations()
.map(|decl| decl.get_name_text().unwrap_or_else(|| "<anon>".to_string()))
.collect()
}
#[test]
fn finds_top_level_declarations() {
let source = concat!(
"int counter;\n",
"void reset();\n",
"struct Point { int x; int y; };\n",
"namespace ns { int inner; }\n",
);
let (root, _) = unit(source);
let kinds: Vec<&str> = root.get_declarations().map(|it| it.kind_name()).collect();
assert_eq!(kinds, vec!["variable", "function", "class"]);
assert_eq!(root.get_namespaces().count(), 1);
assert_eq!(decl_names(source), vec!["counter", "reset", "Point"]);
}
#[test]
fn an_export_macro_before_the_type_leaves_the_declarator_last() {
assert_eq!(decl_names("MY_API Widget *p;\n"), vec!["p"]);
assert_eq!(decl_names("EMMY_API Result f(int x);\n"), vec!["f"]);
assert_eq!(decl_names("EXPORT std::string g();\n"), vec!["g"]);
assert_eq!(decl_names("MY_API Vector<int> *make();\n"), vec!["make"]);
assert_eq!(decl_names("Widget w;\n"), vec!["w"]);
assert_eq!(decl_names("Widget *p;\n"), vec!["p"]);
assert_eq!(decl_names("MY_API int f();\n"), vec!["f"]);
assert_eq!(decl_names("std::string name;\n"), vec!["name"]);
}
#[test]
fn a_class_definition_leaves_the_name_to_the_declarator() {
assert_eq!(decl_names("struct { int a; } x;\n"), vec!["x"]);
assert_eq!(decl_names("union { int a; } u;\n"), vec!["u"]);
assert_eq!(
decl_names("static const struct { int a; } priority[] = { { 1 } };\n"),
vec!["priority"]
);
}
#[test]
fn variable_declaration_exposes_type_and_initializer() {
let (root, _) = unit("int counter = 42;\n");
let decl = root.get_declarations().next().unwrap();
assert_eq!(decl.get_name_text().as_deref(), Some("counter"));
assert_eq!(
decl.get_decl_specifiers().unwrap().get_type_text(),
"int",
"the specifier sequence should report the written type"
);
let initializer = decl.get_initializer().expect("initializer");
let value = initializer.get_expr().expect("initializer expression");
let literal = match value {
CppExpr::LiteralExpr(literal) => literal,
other => panic!("expected a literal, got {other:?}"),
};
assert_eq!(literal.get_literal_text().as_deref(), Some("42"));
assert!(!root.get_declarations().next().unwrap().is_function_def());
}
#[test]
fn function_definition_exposes_params_and_body() {
let (root, _) = unit("int add(int a, int b) { return a + b; }\n");
let decl = root.get_declarations().next().unwrap();
assert!(
decl.is_function_def(),
"should be recognised as a definition"
);
assert_eq!(decl.get_name_text().as_deref(), Some("add"));
let declarator = decl.get_declarator().expect("declarator");
assert!(declarator.is_function());
let params = declarator.get_param_list().expect("parameter list");
let names: Vec<String> = params
.get_params()
.filter_map(|param| param.get_name().map(|it| it.get_name_text().to_string()))
.collect();
assert_eq!(names, vec!["a", "b"]);
let body = decl.get_body().expect("body");
let stats: Vec<CppStat> = body.get_stats().collect();
assert!(
stats.iter().any(|it| matches!(it, CppStat::ReturnStat(_))),
"body should contain the return statement"
);
}
#[test]
fn a_return_without_a_semicolon_is_an_error() {
for (what, source) in [
("at the end of a body", "int f() { return 0 }\n"),
(
"before another statement",
"int f() { return 0\n int x; }\n",
),
("a `break`", "void f() { while (1) { break } }\n"),
("a `continue`", "void f() { while (1) { continue } }\n"),
("a `goto`", "void f() { goto done }\n"),
] {
let tree = CppParser::parse(source, ParserConfig::default());
assert!(
!tree.get_errors().is_empty(),
"{what}: a missing `;` is an error in {source:?}"
);
}
let tree = CppParser::parse("int f() { return 0; }\n", ParserConfig::default());
assert!(
tree.get_errors().is_empty(),
"and `return 0;` is not an error"
);
}
#[test]
fn function_definition_with_trailing_return_type() {
let (root, _) = unit("auto begin() -> int* { return nullptr; }\n");
let decl = root.get_declarations().next().unwrap();
assert!(decl.is_function_def());
let declarator = decl.get_declarator().unwrap();
let trailing = declarator
.get_trailing_return_type()
.expect("trailing return type");
assert_eq!(trailing.get_type_text(), "int*");
}
#[test]
fn class_definition_exposes_members_and_access() {
let source =
"class Foo : public Base {\npublic:\n void method();\nprivate:\n int value_;\n};\n";
let (root, _) = unit(source);
let decl = root.get_declarations().next().unwrap();
let class = decl.get_class_def().expect("class definition");
assert_eq!(class.get_name_text().as_deref(), Some("Foo"));
assert!(!class.is_struct());
let bases: Vec<String> = class
.get_base_specifiers()
.filter_map(|it| it.get_name().map(|n| n.get_qualified_name()))
.collect();
assert_eq!(bases, vec!["Base"]);
let body = class.get_body().expect("class body");
let members: Vec<String> = body
.get_members()
.filter_map(|it| it.get_name_text())
.collect();
assert_eq!(members, vec!["method", "value_"]);
let access: Vec<&'static str> = body
.get_access_specifiers()
.iter()
.map(|it| match CppSyntaxKind::from(it.syntax().kind()) {
CppSyntaxKind::PublicAccess => "public",
CppSyntaxKind::PrivateAccess => "private",
_ => "protected",
})
.collect();
assert_eq!(access, vec!["public", "private"]);
}
#[test]
fn enum_definition_exposes_enumerators() {
let (root, _) = unit("enum class Color : unsigned char { Red, Green = 2 };\n");
let decl = root.get_declarations().next().unwrap();
let enum_def = decl.get_enum_def().expect("enum definition");
assert_eq!(
enum_def
.get_name()
.map(|it| it.get_name_text().to_string())
.as_deref(),
Some("Color")
);
assert!(enum_def.is_scoped(), "`enum class` is a scoped enum");
let names: Vec<String> = enum_def
.get_enumerators()
.filter_map(|it| it.get_name().map(|n| n.get_name_text().to_string()))
.collect();
assert_eq!(names, vec!["Red", "Green"]);
}
#[test]
fn modules_are_typed() {
let (root, _) = unit("export module my.mod:part;\n");
let module = root.get_module_decl().expect("module declaration");
assert!(
module.is_interface(),
"`export module` is an interface unit"
);
assert_eq!(
module.get_name().map(|it| it.get_name_text()).as_deref(),
Some("my.mod")
);
let partition = module.get_partition().expect("partition");
assert_eq!(
partition.get_name().map(|it| it.get_name_text()).as_deref(),
Some("part")
);
}
#[test]
fn imports_cover_all_three_forms() {
let source = "import std;\nexport import :part;\nimport <iostream>;\n";
let (root, _) = unit(source);
let imports: Vec<_> = root
.get_declarations()
.filter_map(|decl| match CppStat::cast(decl.syntax().clone()) {
Some(CppStat::ImportDecl(node)) => Some(node),
_ => None,
})
.collect();
let tree_imports: Vec<_> = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppImportDecl::cast)
.collect();
assert_eq!(
tree_imports.len(),
3,
"expected three imports, got {imports:?}"
);
assert_eq!(
tree_imports[0]
.get_name()
.map(|it| it.get_name_text())
.as_deref(),
Some("std")
);
assert!(tree_imports[1].is_reexport());
assert!(tree_imports[2].is_header_unit());
assert_eq!(
tree_imports[2]
.get_header_name()
.map(|it| it.get_name_text())
.as_deref(),
Some("iostream")
);
}
#[test]
fn expressions_are_walkable() {
let (root, _) = unit("int x = a + b * c;\n");
let decl = root.get_declarations().next().unwrap();
let initializer = decl.get_initializer().unwrap();
let expr = initializer.get_expr().unwrap();
let binary = match expr {
CppExpr::BinaryExpr(node) => node,
other => panic!("expected a binary expression, got {other:?}"),
};
assert_eq!(binary.get_operator_text().as_deref(), Some("+"));
assert!(matches!(binary.get_lhs(), Some(CppExpr::NameExpr(_))));
let rhs = binary.get_rhs().expect("rhs");
assert!(
matches!(rhs, CppExpr::BinaryExpr(_)),
"`b * c` should bind tighter than `+`"
);
}
#[test]
fn call_expression_exposes_callee_and_args() {
let (root, _) = unit("void f() { g(1, 2); }\n");
let call = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppCallExpr::cast)
.next()
.expect("call expression");
let callee = call.get_callee().expect("callee");
assert!(matches!(callee, CppExpr::NameExpr(_)));
assert_eq!(call.get_args().len(), 2);
}
#[test]
fn a_cast_argument_is_counted() {
let (root, _) = unit("void f(int x) { three((int)x, 2, 3); }\n");
let call = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppCallExpr::cast)
.next()
.expect("call expression");
let args = call.get_args();
assert_eq!(
args.len(),
3,
"three arguments, one of them a cast: {args:?}"
);
assert!(
matches!(args.first(), Some(CppExpr::CastExpr(_))),
"and the cast is the first of them: {args:?}"
);
}
#[test]
fn names_report_qualification() {
let (root, _) = unit("std::vector<int> v;\n");
let decl = root.get_declarations().next().unwrap();
let name = decl
.get_decl_specifiers()
.and_then(|it| it.get_type_name())
.expect("type name");
assert!(name.is_qualified());
assert_eq!(name.get_qualified_name(), "std::vector<int>");
}
#[test]
fn preprocessor_directives_are_typed() {
let (root, _) = unit("#include <vector>\n#define N 3\n");
let directives: Vec<_> = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppPreprocessorDirective::cast)
.collect();
assert_eq!(directives.len(), 2);
assert_eq!(
directives[0].get_directive_name().as_deref(),
Some("include")
);
assert_eq!(
directives[0].get_header_name_text().as_deref(),
Some("vector")
);
assert_eq!(
directives[1].get_directive_name().as_deref(),
Some("define")
);
}
#[test]
fn comments_report_their_kind() {
let source = "// ordinary\n\n/// documented\n/** block doc */\nint x;\n";
let (root, tree) = unit(source);
let comments: Vec<_> = tree
.get_red_root()
.descendants_with_tokens()
.filter_map(|it| it.into_token())
.filter_map(cpp_parser::CppCommentToken::cast)
.collect();
let openers: Vec<_> = comments
.iter()
.filter(|comment| {
matches!(
comment.get_comment_kind(),
cpp_parser::CppCommentKind::Line | cpp_parser::CppCommentKind::Block
)
})
.collect();
assert!(
!openers.is_empty(),
"the comment markers must still be in the tree: {:#?}",
tree.get_red_root()
);
let doc_comments: Vec<_> = tree
.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::DocComment)
.collect();
assert_eq!(
doc_comments.len(),
2,
"the blank line separates the header from the documented declaration: {:#?}",
tree.get_red_root()
);
assert_eq!(root.get_declarations().count(), 1);
}
#[test]
fn accessors_never_panic_on_broken_input() {
let broken = [
"",
"int",
"int x =",
"void f(",
"class {",
"void f() { if (",
"struct S { public:",
"namespace",
"template <",
"export module",
"import",
"int x = a + ;",
"#include",
];
for source in broken {
let (root, _) = unit(source);
for decl in root.get_declarations() {
let _ = decl.kind_name();
let _ = decl.get_name_text();
let _ = decl.get_body();
let _ = decl.get_class_def();
let _ = decl.get_enum_def();
let _ = decl.get_namespace_decl();
let _ = decl.get_initializer();
let _ = decl.is_function_def();
let _ = decl.is_exported();
if let Some(specs) = decl.get_decl_specifiers() {
let _ = specs.get_type_text();
let _ = specs.is_const();
let _ = specs.is_static();
}
if let Some(declarator) = decl.get_declarator() {
let _ = declarator.get_name_text();
let _ = declarator.get_declarator_text();
let _ = declarator.is_function();
let _ = declarator.is_array();
let _ = declarator.get_trailing_return_type();
}
if let Some(body) = decl.get_body() {
for stat in body.get_stats() {
let _ = stat.syntax().text().to_string();
}
}
}
for expr in root.syntax().descendants().filter_map(CppExpr::cast) {
match expr {
CppExpr::BinaryExpr(node) => {
let _ = node.get_lhs();
let _ = node.get_rhs();
let _ = node.get_operator_text();
}
CppExpr::CallExpr(node) => {
let _ = node.get_callee();
let _ = node.get_args();
}
CppExpr::UnaryExpr(node) => {
let _ = node.is_prefix();
let _ = node.get_operand();
}
CppExpr::NameExpr(node) => {
let _ = node.get_qualified_name();
let _ = node.is_qualified();
}
_ => {}
}
}
}
}
#[test]
fn cpp_ast_dispatches_on_node_kind() {
use cpp_parser::CppAst;
let (root, tree) = unit("int x = 1;\n");
let mut seen_declaration = false;
let mut seen_expr = false;
for node in tree.get_red_root().descendants() {
match CppAst::cast(node) {
Some(CppAst::Declaration(_)) => seen_declaration = true,
Some(CppAst::Expr(_)) => seen_expr = true,
_ => {}
}
}
assert!(seen_declaration, "should find a declaration");
assert!(seen_expr, "should find the initializer expression");
assert_eq!(root.get_declarations().count(), 1);
}
#[test]
fn accessors_agree_across_entry_points() {
let (root, tree) = unit("int counter = 1;\n");
let by_child = root.get_declarations().next().unwrap();
let by_descendant = tree
.get_red_root()
.descendants()
.find_map(CppDeclaration::cast)
.unwrap();
assert_eq!(
by_child.get_name_text(),
by_descendant.get_name_text(),
"the same declaration must look the same however it is found"
);
assert_eq!(
by_child.syntax().text_range(),
by_descendant.syntax().text_range()
);
}
#[test]
fn a_realistic_module_unit_yields_its_declarations() {
let source = include_str!("real_world.cpp");
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(
tree.get_errors(),
[],
"the parser reports valid code as broken; the errors are {:?}",
tree.get_errors()
);
assert_eq!(
tree.to_source_text(),
source,
"the tree must reproduce the file exactly"
);
let root = CppTranslationUnit::cast(tree.get_red_root()).unwrap();
let module = root.get_module_decl().expect("module declaration");
assert_eq!(
module.get_name().map(|it| it.get_name_text()),
Some("shapes".to_string())
);
let top_level: Vec<String> = root
.get_declarations()
.map(|decl| {
format!(
"{} {}",
decl.kind_name(),
decl.get_name_text().unwrap_or_default()
)
})
.collect();
assert_eq!(top_level, vec!["alias Point", "function helper"]);
let namespace = root.get_namespaces().next().expect("namespace shapes");
assert_eq!(
namespace.get_name().and_then(|it| it.get_name_text()),
Some("shapes".to_string())
);
let members: Vec<String> = namespace
.get_declarations()
.map(|stat| match stat {
CppStat::Declaration(decl) => {
format!(
"{} {}",
decl.kind_name(),
decl.get_name_text().unwrap_or_default()
)
}
other => format!("{other:?}"),
})
.collect();
assert_eq!(
members,
vec![
"variable kMax",
"enum Kind",
"class Point",
"class Grid",
"class Shape",
"function distance",
]
);
}
fn binding_names(source: &str) -> Vec<Vec<String>> {
let (root, _) = unit(source);
root.get_declarations()
.filter_map(|declaration| declaration.get_init_declarator())
.filter_map(|init| init.get_structured_binding())
.map(|binding| binding.get_name_texts())
.collect()
}
#[test]
fn a_structured_binding_reports_its_names() {
assert_eq!(
binding_names("auto [a, b] = pair;\n"),
vec![vec!["a".to_string(), "b".to_string()]]
);
}
#[test]
fn a_structured_binding_survives_a_reference_prefix() {
for source in [
"auto& [k, v] = map;\n",
"auto&& [k, v] = map;\n",
"const auto& [k, v] = map;\n",
] {
assert_eq!(
binding_names(source),
vec![vec!["k".to_string(), "v".to_string()]],
"{source:?}"
);
}
}
#[test]
fn a_pack_expansion_binding_reports_its_name() {
assert_eq!(
binding_names("auto [... xs] = rest;\n"),
vec![vec!["xs".to_string()]]
);
assert_eq!(
binding_names("auto [a, ...] = rest;\n"),
vec![vec!["a".to_string()]]
);
}
#[test]
fn an_ordinary_declarator_is_not_a_structured_binding() {
let (root, _) = unit("int arr[3];\nauto [a, b] = pair;\n");
let kinds: Vec<bool> = root
.get_declarations()
.filter_map(|declaration| declaration.get_init_declarator())
.map(|init| init.is_structured_binding())
.collect();
assert_eq!(kinds, vec![false, true]);
}
#[test]
fn consteval_if_has_a_body_and_no_condition() {
for source in [
"void f() { if consteval { g(); } }\n",
"void f() { if !consteval { g(); } }\n",
"void f() { if consteval { g(); } else { h(); } }\n",
] {
let (root, tree) = unit(source);
assert_eq!(tree.get_errors(), [], "{source:?} must parse cleanly");
let if_stat = root
.get_declarations()
.filter_map(|declaration| declaration.get_body())
.flat_map(|body| body.get_stats())
.find_map(|stat| match stat {
CppStat::IfStat(if_stat) => Some(if_stat),
_ => None,
})
.unwrap_or_else(|| panic!("{source:?} has an if statement"));
let text = if_stat.syntax().text().to_string();
assert!(
text.contains("consteval"),
"the keyword is part of the statement: {text:?}"
);
}
}
#[test]
fn attribute_lists_consume_both_closing_brackets() {
let sources = [
"[[nodiscard]] int f();\n",
"[[noreturn]] void g();\n",
"class C [[deprecated]] { int x; };\n",
"enum class E [[deprecated]] { A };\n",
"struct S { [[maybe_unused]] int x; };\n",
"[[nodiscard, deprecated]] int i();\n",
"[[gnu::always_inline]] inline void j();\n",
"void k([[maybe_unused]] int x);\n",
"[[nodiscard]] int l() { return 1; }\n",
"int m [[gnu::aligned(16)]];\n",
"struct A { [[nodiscard]] virtual int q() const; };\n",
"export module mod [[deprecated]];\n",
"import std [[deprecated]];\n",
"int h() [[carries_dependency]];\n",
"void r() [[noreturn]] { for (;;) {} }\n",
"void s(int x [[maybe_unused]]);\n",
"void t(int x [[maybe_unused]] = 1);\n",
"using T [[deprecated]] = int;\n",
"template <typename T> [[nodiscard]] T p();\n",
"enum class F { A [[deprecated]] = 1, B };\n",
"namespace [[deprecated]] n { int x; }\n",
"namespace [[deprecated(\"STL4002\")]] tr1 { int x; }\n",
"inline namespace [[deprecated]] v1 { int x; }\n",
];
for source in sources {
let (_, tree) = unit(source);
assert_eq!(tree.get_errors(), [], "{source:?} must parse cleanly");
assert_eq!(
tree.to_source_text(),
source,
"{source:?} must stay lossless"
);
let attribute_text: String = tree
.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::AttributeList)
.map(|node| node.text().to_string())
.collect();
let opened = source.matches("[[").count();
let closed = attribute_text.matches("]]").count();
assert_eq!(
closed, opened,
"{source:?}: {opened} attribute list(s) opened but {closed} closed — got {attribute_text:?}"
);
}
}
#[test]
fn known_unparsed_attribute_positions() {
let still_broken: [&str; 0] = [];
for source in still_broken {
let (_, tree) = unit(source);
assert!(
!tree.get_errors().is_empty(),
"{source:?} now parses cleanly — move it into `attribute_lists_consume_both_closing_brackets`"
);
assert_eq!(
tree.to_source_text(),
source,
"{source:?} must stay lossless even while it does not parse"
);
}
}
#[test]
fn a_nested_attribute_list_balances_its_brackets() {
let source = "[[outer([[inner]])]] int f();\n";
let (_, tree) = unit(source);
assert_eq!(tree.get_errors(), [], "must parse cleanly");
assert_eq!(tree.to_source_text(), source);
let text: String = tree
.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::AttributeList)
.map(|node| node.text().to_string())
.collect();
assert_eq!(text.matches("]]").count(), 2, "both lists closed: {text:?}");
}
#[test]
fn an_unterminated_attribute_list_is_reported_and_consumes_the_rest() {
let source = "[[nodiscard\nint f();\nint g;\n";
let (root, tree) = unit(source);
assert_eq!(tree.to_source_text(), source, "still lossless");
assert!(
!tree.get_errors().is_empty(),
"the input is not silently accepted"
);
let declarations: Vec<String> = root
.get_declarations()
.map(|decl| decl.get_name_text().unwrap_or_default())
.collect();
assert!(
declarations.is_empty(),
"the rest of the file is inside the unclosed construct: {declarations:?}"
);
}
#[test]
fn a_function_definition_holds_its_body() {
for (what, source) in [
("a plain function", "int g() { return 1; }\n"),
(
"a member function",
"struct A {\n void g() { return; }\n};\n",
),
(
"a constructor with an initializer list",
"struct A {\n A(int f) : x(f) { int q = f; }\n int x;\n};\n",
),
] {
let tree = CppParser::parse(source, ParserConfig::default());
let declaration = tree
.get_red_root()
.descendants()
.filter(|node| {
CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declaration
&& node.descendants().any(|inner| {
CppSyntaxKind::from(inner.kind()) == CppSyntaxKind::CompoundStat
})
})
.min_by_key(|node| {
usize::from(node.text_range().end()) - usize::from(node.text_range().start())
})
.unwrap_or_else(|| panic!("{what}: no declaration holds a body in {source:?}"));
let body = declaration
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::CompoundStat)
.unwrap_or_else(|| {
panic!(
"{what}: the body is not a child of the declaration: {:?}",
declaration
.children()
.map(|child| format!("{:?}", CppSyntaxKind::from(child.kind())))
.collect::<Vec<_>>()
)
});
assert!(
body.text().to_string().contains('{'),
"{what}: the body is the `{{ … }}` it was written as"
);
}
}
#[test]
fn a_declaration_after_an_incomplete_member_access_is_still_a_declaration() {
let source = "\
struct Widget { int size; };
int f() {
Widget* a = nullptr;
a->
int second = 1;
second = 2;
}
";
let tree = CppParser::parse(source, ParserConfig::default());
let declarations: Vec<String> = tree
.get_red_root()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Declaration)
.map(|node| node.text().to_string().trim().to_string())
.collect();
assert!(
declarations
.iter()
.any(|declaration| declaration == "int second = 1;"),
"the declaration after the cursor is in the tree: {declarations:?}"
);
assert!(
declarations
.iter()
.any(|declaration| declaration == "Widget* a = nullptr;"),
"and so is the one before it: {declarations:?}"
);
}
#[test]
fn a_parameters_type_is_its_spelling_without_its_name() {
let source =
"void f(int a, int* b, const std::string& c, unsigned char d, int e[3], auto f);\n";
let (root, _) = unit(source);
let declaration = root
.get_declarations()
.next()
.expect("the function declares");
let parameters: Vec<(String, String)> = declaration
.descendants::<cpp_parser::CppParam>()
.filter_map(|parameter| Some((parameter.get_name_text()?, parameter.get_type_text())))
.collect();
assert_eq!(
parameters,
vec![
("a".to_string(), "int".to_string()),
("b".to_string(), "int*".to_string()),
("c".to_string(), "const std::string&".to_string()),
("d".to_string(), "unsigned char".to_string()),
("e".to_string(), "int[3]".to_string()),
("f".to_string(), "auto".to_string()),
],
"every parameter's type, as the file writes it"
);
}
#[test]
fn a_functions_parameters_are_its_own_and_not_a_lambdas() {
let source = "auto f(int a) { auto g = [](int b) { return b; }; return a; }\n";
let (root, _) = unit(source);
let declaration = root.get_declarations().next().expect("f is declared");
let list = declaration
.get_param_list()
.expect("f has a parameter list");
let names: Vec<String> = list
.get_params()
.filter_map(|parameter| parameter.get_name_text())
.collect();
assert_eq!(
names,
vec!["a".to_string()],
"the lambda's belongs to the lambda"
);
}
#[test]
fn a_decorated_constructor_and_destructor_name_themselves() {
let source = "\
struct A {
explicit A(int x) : x_(x) {}
virtual ~A() {}
A() {}
~A() {}
int f() { return 0; }
int x_;
};
template <class T>
struct Box {
Box<T>();
};
";
let (root, tree) = unit(source);
assert_eq!(tree.get_errors(), [], "the fixture parses cleanly");
let declarations: Vec<cpp_parser::CppDeclaration> = root
.syntax()
.descendants()
.filter_map(cpp_parser::CppDeclaration::cast)
.filter(|declaration| declaration.get_body().is_some())
.collect();
let said: Vec<(bool, bool)> = declarations
.iter()
.map(|declaration| {
(
declaration.get_name_text().is_some(),
declaration.promises_no_return(),
)
})
.collect();
assert_eq!(
said,
[
(true, true),
(true, true),
(true, true),
(true, true),
(true, false)
],
"every declaration names itself; the four constructors and destructors promise no return, the function does: \
{said:?}"
);
assert_eq!(
declarations[0].get_name_text().as_deref(),
Some("A"),
"the decorated constructor names itself"
);
}
#[test]
fn a_using_declaration_ends_at_its_own_semicolon() {
let pack = concat!(
"template <typename T> struct Base { void f(); };\n",
"template <typename... T> struct D : Base<T>... {\n",
" using Base<T>::f...;\n",
"};\n",
"void g() { }\n",
);
assert_eq!(
decl_names(pack),
vec!["Base", "D", "g"],
"a pack expansion in a using-declaration does not leave the class body open"
);
let template_id = concat!(
"template <typename T> struct Base { void f(); };\n",
"template <typename T> struct D : Base<T> {\n",
" using Base<T>::f;\n",
"};\n",
"void g() { }\n",
);
assert_eq!(
decl_names(template_id),
vec!["Base", "D", "g"],
"and neither does a template-id in the qualifier"
);
let plain = concat!(
"namespace ns { void f(); }\n",
"struct D {\n",
" using ns::f;\n",
"};\n",
"void g() { }\n",
);
assert_eq!(
decl_names(plain),
vec!["D", "g"],
"and the shape that already worked still does — `ns::f` is one name, so `f` is not a top-level declaration"
);
}
#[test]
fn a_parenthesised_declarator_names_its_parameter_list_as_a_child() {
let (root, _tree) = unit("void (foo) (int a, char *b);\nvoid (*bar)(int a);\n");
let declarations: Vec<CppDeclaration> = root.descendants::<CppDeclaration>().collect();
assert_eq!(declarations.len(), 2, "two declarations");
let list = declarations[0]
.get_param_list()
.expect("a parenthesised declarator declares a function");
assert_eq!(list.syntax().text().to_string(), "(int a, char *b)");
let declarator = declarations[0]
.get_init_declarator()
.and_then(|init| init.child::<cpp_parser::CppDeclarator>())
.expect("a declarator");
assert_eq!(
declarator.syntax().text().to_string(),
"(foo) (int a, char *b)",
"the declarator's own text covers the list"
);
assert_eq!(
declarations[1]
.get_param_list()
.map(|list| list.syntax().text().to_string()),
Some("(int a)".to_string())
);
}