use cpp_parser::{
CppAstNode, CppDeclaration, CppDocComment, CppParser, CppSyntaxKind, CppSyntaxTree,
ParserConfig, documentation_of,
};
fn parse(source: &str) -> CppSyntaxTree {
CppParser::parse(source, ParserConfig::default())
}
fn comments(tree: &CppSyntaxTree) -> Vec<CppDocComment> {
tree.get_red_root()
.descendants()
.filter_map(CppDocComment::cast)
.collect()
}
fn the_comment(source: &str) -> CppDocComment {
let tree = parse(source);
let mut found = comments(&tree);
assert_eq!(
found.len(),
1,
"{source:?} should hold exactly one comment: {:#?}",
tree.get_red_root()
);
found.remove(0)
}
fn documented_name(comment: &CppDocComment) -> Option<String> {
comment.get_documented_name()
}
#[test]
fn a_comment_documents_the_declaration_after_it() {
assert_eq!(
documented_name(&the_comment("/// Doc.\nint x;\n")),
Some("x".to_string())
);
}
#[test]
fn the_owner_is_the_next_node_not_the_parent() {
let comment = the_comment("/// Doc.\nint x;\n");
let owner = comment.get_owner().expect("a following node");
assert_eq!(
CppSyntaxKind::from(owner.kind()),
CppSyntaxKind::Declaration
);
assert_eq!(
comment
.get_parent::<cpp_parser::CppTranslationUnit>()
.map(|unit| unit.syntax().text().to_string()),
Some("/// Doc.\nint x;\n".to_string()),
"the parent is the translation unit, not the declaration"
);
}
#[test]
fn a_comment_documents_a_class_definition() {
assert_eq!(
documented_name(&the_comment("/// A grid.\nclass Grid {\n int n;\n};\n")),
Some("Grid".to_string())
);
}
#[test]
fn the_documented_declaration_is_found_for_every_form() {
let cases = [
("/// Doc.\nint f();\n", "f"),
("/// Doc.\nint x = 1;\n", "x"),
("/// Doc.\nenum class Color { Red };\n", "Color"),
("/// Doc.\nvoid f() { }\n", "f"),
];
for (source, expected) in cases {
assert_eq!(
documented_name(&the_comment(source)),
Some(expected.to_string()),
"{source:?}"
);
}
}
#[test]
fn a_using_alias_is_documented_too() {
assert_eq!(
documented_name(&the_comment("/// Doc.\nusing Point = shapes::Point;\n")),
Some("Point".to_string())
);
}
#[test]
fn a_comment_at_the_end_of_a_file_documents_nothing() {
let comment = the_comment("int x;\n/// Trailing note.\n");
assert!(comment.get_owner().is_none(), "nothing follows the comment");
assert!(comment.get_documented_declaration().is_none());
}
#[test]
fn a_trailing_comment_documents_nothing_forwards() {
let tree = parse("struct S {\n int a; ///< the a\n int b;\n};\n");
let comment = comments(&tree)
.into_iter()
.find(|comment| comment.get_comment_text().contains("the a"))
.expect("the trailing comment");
assert!(comment.is_trailing(), "the `///<` marker is recognised");
assert_eq!(
documented_name(&comment),
None,
"a trailing comment documents the member before it, so the forward walk must decline"
);
let previous = comment
.get_owner()
.and_then(|owner| owner.prev_sibling())
.and_then(|before| {
if CppSyntaxKind::from(before.kind()) == CppSyntaxKind::DocComment {
before.prev_sibling()
} else {
Some(before)
}
})
.and_then(CppDeclaration::cast)
.and_then(|declaration| declaration.get_name_text());
assert_eq!(
previous,
Some("a".to_string()),
"the member it documents is the declaration before it"
);
}
#[test]
fn only_the_trailing_marker_reverses_the_direction() {
for source in [
"/// Doc.\nint x;\n",
"//! Doc.\nint x;\n",
"/** Doc. */\nint x;\n",
] {
let comment = the_comment(source);
assert!(!comment.is_trailing(), "{source:?}");
assert_eq!(
documented_name(&comment),
Some("x".to_string()),
"{source:?}"
);
}
}
#[test]
fn a_directive_between_the_comment_and_the_declaration_is_stepped_over() {
assert_eq!(
documented_name(&the_comment("/// Doc.\n#define N 3\nint x;\n")),
Some("x".to_string())
);
}
#[test]
fn separate_comment_groups_do_not_merge() {
let tree = parse("/// First.\n\n/// Second.\nint x;\n");
let comments = comments(&tree);
assert_eq!(comments.len(), 2, "a blank line ends a group");
assert_eq!(
documented_name(&comments[1]),
Some("x".to_string()),
"the later group documents the declaration"
);
assert_eq!(
documented_name(&comments[0]),
None,
"the earlier group documents the later comment, which is not a declaration"
);
assert_eq!(
comments[0]
.get_owner()
.map(|node| CppSyntaxKind::from(node.kind())),
Some(CppSyntaxKind::DocComment),
"but it does have a following node"
);
}
#[test]
fn a_comment_in_a_class_body_documents_the_member_after_it() {
let tree = parse("struct S {\n /// The n.\n int n;\n int m;\n};\n");
let comment = comments(&tree).into_iter().next().expect("the comment");
assert_eq!(documented_name(&comment), Some("n".to_string()));
assert!(
comment.get_parent::<cpp_parser::CppClassBody>().is_some(),
"the comment belongs to the class body, like the members do"
);
}
#[test]
fn a_comment_between_two_members_belongs_to_the_class_body() {
let tree = parse("struct S {\n int x;\n /// The y.\n int y;\n};\n");
let comment = comments(&tree)
.into_iter()
.find(|comment| comment.get_comment_text().contains("The y"))
.expect("the comment");
assert_eq!(
comment.get_parent::<CppDeclaration>(),
None,
"the comment is beside the members, not inside the one before it"
);
assert_eq!(
comment
.syntax()
.parent()
.map(|parent| CppSyntaxKind::from(parent.kind())),
Some(CppSyntaxKind::ClassBody),
"it is a child of the class body, where a reader sees it"
);
assert_eq!(
documented_name(&comment),
Some("y".to_string()),
"and it still documents the member after it, which is the relationship that matters"
);
}
#[test]
fn a_comment_before_a_namespace_has_an_owner_but_no_declaration() {
let comment = the_comment("/// Doc.\nnamespace ns { }\n");
assert_eq!(
comment
.get_owner()
.map(|node| CppSyntaxKind::from(node.kind())),
Some(CppSyntaxKind::NamespaceDecl)
);
assert!(
comment.get_documented_declaration().is_none(),
"a namespace is not a declaration node, so it is not the documented declaration"
);
}
#[test]
fn a_plain_comment_has_the_same_relationship() {
let comment = the_comment("// plain\nint x;\n");
assert_eq!(documented_name(&comment), Some("x".to_string()));
assert!(
!comment.is_documentation(),
"but it is not documentation, which is a separate question"
);
}
#[test]
fn every_documented_declaration_in_a_file_is_found() {
let source = "\
/// A point.
struct Point {
/// The x.
int x;
/// The y.
int y;
};
/// Distance.
double dist(const Point& a, const Point& b);
";
let tree = parse(source);
let names: Vec<Option<String>> = comments(&tree).iter().map(documented_name).collect();
assert_eq!(
names,
vec![
Some("Point".to_string()),
Some("x".to_string()),
Some("y".to_string()),
Some("dist".to_string()),
],
"every comment that documents something finds it, in source order"
);
}
fn documentation_above(source: &str, name: &str) -> Option<String> {
let tree = parse(source);
let declaration = tree
.get_red_root()
.descendants()
.filter_map(CppDeclaration::cast)
.find(|declaration| declaration.get_name_text().as_deref() == Some(name))
.unwrap_or_else(|| panic!("{source:?} declares no `{name}`"));
documentation_of(declaration.syntax()).map(|comment| comment.get_comment_text())
}
#[test]
fn a_declaration_finds_the_comment_above_it() {
assert_eq!(
documentation_above("/// Doc.\nint x;\n", "x"),
Some("Doc.".to_string())
);
}
#[test]
fn every_form_of_declaration_finds_its_comment() {
let cases = [
("/// Doc.\nint f();\n", "f", "Doc."),
("/// Doc.\nint x = 1;\n", "x", "Doc."),
("/// Doc.\nvoid f() { }\n", "f", "Doc."),
(
"/// A grid.\nclass Grid {\n int n;\n};\n",
"Grid",
"A grid.",
),
];
for (source, name, expected) in cases {
assert_eq!(
documentation_above(source, name),
Some(expected.to_string()),
"{source:?}"
);
}
}
#[test]
fn the_reverse_walk_steps_over_a_directive() {
assert_eq!(
documentation_above("/// Doc.\n#define N 3\nint x;\n", "x"),
Some("Doc.".to_string())
);
}
#[test]
fn a_member_finds_the_comment_above_it() {
let source = "struct S {\n /// The n.\n int n;\n int m;\n};\n";
assert_eq!(documentation_above(source, "n"), Some("The n.".to_string()));
assert_eq!(
documentation_above(source, "m"),
None,
"the comment above `n` is not borrowed by the member after it"
);
}
#[test]
fn a_member_finds_a_comment_nested_in_the_member_before_it() {
assert_eq!(
documentation_above(
"struct S {\n int x;\n /// The y.\n int y;\n};\n",
"y"
),
Some("The y.".to_string())
);
}
#[test]
fn a_trailing_comment_does_not_document_what_follows() {
let source = "struct S {\n int a; ///< the a\n int b;\n};\n";
assert_eq!(documentation_above(source, "b"), None);
assert_eq!(
documentation_above(source, "a"),
None,
"and the member it does document is not reachable forwards either — the parser declines the \
marker rather than following it backwards"
);
}
#[test]
fn a_comment_is_not_borrowed_by_the_second_declaration_after_it() {
let source = "/// First.\nint a;\nint b;\n";
assert_eq!(documentation_above(source, "a"), Some("First.".to_string()));
assert_eq!(documentation_above(source, "b"), None);
}
#[test]
fn a_class_comment_is_not_the_documentation_of_its_first_member() {
let source = "/// The point.\nstruct Point {\n int x;\n};\n";
assert_eq!(
documentation_above(source, "Point"),
Some("The point.".to_string())
);
assert_eq!(documentation_above(source, "x"), None);
}
#[test]
fn the_group_nearest_the_declaration_is_the_one_found() {
assert_eq!(
documentation_above("/// First.\n\n/// Second.\nint x;\n", "x"),
Some("Second.".to_string())
);
}
#[test]
fn every_declaration_in_a_file_finds_its_comment() {
let source = "\
/// A point.
struct Point {
/// The x.
int x;
/// The y.
int y;
};
/// Distance.
double dist(const Point& a, const Point& b);
";
let tree = parse(source);
let found: Vec<(String, Option<String>)> = tree
.get_red_root()
.descendants()
.filter_map(CppDeclaration::cast)
.filter_map(|declaration| {
let name = declaration.get_name_text()?;
let documentation =
documentation_of(declaration.syntax()).map(|comment| comment.get_comment_text());
Some((name, documentation))
})
.collect();
assert_eq!(
found,
vec![
("Point".to_string(), Some("A point.".to_string())),
("x".to_string(), Some("The x.".to_string())),
("y".to_string(), Some("The y.".to_string())),
("dist".to_string(), Some("Distance.".to_string())),
]
);
}