use cpp_parser::{
CppAstNode, CppDeclaration, CppParser, CppSyntaxKind, CppSyntaxNode, ParserConfig,
};
fn declaration(source: &str) -> CppDeclaration {
let tree = CppParser::parse(source, ParserConfig::default());
let root = cpp_parser::CppTranslationUnit::cast(tree.get_red_root())
.expect("the root is a translation unit");
root.descendants::<CppDeclaration>()
.next()
.expect("a declaration")
}
fn child_chain(node: &CppSyntaxNode) -> String {
let children: Vec<String> = node
.children()
.map(|child| {
let kind = format!("{:?}", CppSyntaxKind::from(child.kind()));
let text = child.text().to_string();
let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
let text = if text.len() > 34 {
format!("{}…", &text[..34])
} else {
text
};
format!("{kind}[{text}]")
})
.collect();
children.join(" ")
}
struct Row {
written: &'static str,
shape: String,
list: String,
declarator: String,
}
fn survey() -> Vec<Row> {
let cases: &[(&str, &str)] = &[
("simple", "void simple(int a);"),
("function pointer", "int (*fp)(int);"),
("pointer to function pointer", "int (**ppf)(int);"),
("function returning pointer", "int *ret(int);"),
("parenthesised name", "void (named) (int a, char *b);"),
(
"function returning function pointer",
"int (*maker(int a))(int b);",
),
("pointer to member function", "void (Widget::*pm)(int);"),
("array of function pointers", "int (*table[3])(int);"),
("reference to array (C++)", "void takes(int (&arr)[3]);"),
(
"unnamed function pointer parameter",
"void takes2(int (*)(int));",
),
(
"the classic signal()",
"void (*signal(int, void (*)(int)))(int);",
),
("typedef of a function pointer", "typedef int (*Fn)(int);"),
(
"using of a function pointer (C++)",
"using Fn2 = int (*)(int);",
),
("trailing return (C++)", "auto trailing(int a) -> int;"),
(
"function pointer member in a class",
"struct S { int (*m)(int); };",
),
("two lists on one declaration", "int (*two(int a))(int b);"),
];
cases
.iter()
.map(|(_name, source)| {
let declaration = declaration(source);
let declarator = declaration.get_init_declarator();
let shape = declarator
.as_ref()
.map(|init| child_chain(init.syntax()))
.unwrap_or_else(|| child_chain(declaration.syntax()));
let list = declaration.get_param_list().map(|list| {
let parent = list
.syntax()
.parent()
.map(|parent| {
format!(
"{:?}[{}]",
CppSyntaxKind::from(parent.kind()),
parent
.text()
.to_string()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
)
})
.unwrap_or_else(|| "no parent".to_string());
format!("{} in {parent}", list.syntax().text())
});
let declarator_text = declarator
.as_ref()
.map(|init| {
init.child::<cpp_parser::CppDeclarator>()
.map(|declarator| declarator.syntax().text().to_string())
.unwrap_or_else(|| "(no declarator)".to_string())
})
.unwrap_or_else(|| "(no init declarator)".to_string());
Row {
written: source,
shape,
list: list.unwrap_or_else(|| "None".to_string()),
declarator: declarator_text,
}
})
.collect()
}
#[test]
fn the_survey() {
for row in survey() {
println!(
"\n{:<44}\n shape {}\n list {}\n declarator {}",
row.written, row.shape, row.list, row.declarator
);
}
}
#[test]
fn every_declarator_keeps_its_suffixes_to_itself() {
let shapes = [
"void simple(int a);",
"int *ret(int);",
"int (*fp)(int);",
"int (**ppf)(int);",
"void (named) (int a, char *b);",
"int (*maker(int a))(int b);",
"void (Widget::*pm)(int);",
"int (*table[3])(int);",
"void takes(int (&arr)[3]);",
"void takes2(int (*)(int));",
"void (*signal(int, void (*)(int)))(int);",
"int (*two(int a))(int b);",
];
for source in shapes {
let declaration = declaration(source);
let init = declaration
.get_init_declarator()
.expect("an init declarator");
let kinds: Vec<CppSyntaxKind> = init
.syntax()
.children()
.map(|child| CppSyntaxKind::from(child.kind()))
.collect();
assert_eq!(
kinds,
vec![CppSyntaxKind::Declarator],
"{source}: the list is the declarator's child, and there is no sibling: {}",
child_chain(init.syntax())
);
let declarator = init
.child::<cpp_parser::CppDeclarator>()
.expect("a declarator");
let spelled = declarator.syntax().text().to_string();
assert!(
spelled.ends_with(')') && (spelled.contains('(') || spelled.contains('[')),
"{source}: the declarator spells its own suffixes: {spelled:?}"
);
}
}
#[test]
fn a_parenthesised_declarator_is_one_declarator() {
let declaration = declaration("void (named) (int a, char *b);");
let init = declaration
.get_init_declarator()
.expect("an init declarator");
assert_eq!(
child_chain(init.syntax()),
"Declarator[(named) (int a, char *b)]",
"one declarator, its suffixes inside"
);
}
#[test]
fn the_two_lists_of_a_function_returning_a_function_pointer() {
let declaration = declaration("int (*maker(int a))(int b);");
let outer = declaration
.get_init_declarator()
.and_then(|init| init.child::<cpp_parser::CppDeclarator>())
.expect("a declarator");
let lists: Vec<(String, String)> = outer
.syntax()
.descendants()
.filter(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::ParameterList)
.map(|node| {
let owner = node
.parent()
.map(|parent| parent.text().to_string())
.unwrap_or_default();
(node.text().to_string(), owner)
})
.collect();
assert!(
lists
.iter()
.any(|(list, owner)| list == "(int a)" && owner.contains("maker")),
"`maker`'s own list is inside the parentheses: {lists:?}"
);
assert!(
lists
.iter()
.any(|(list, owner)| list == "(int b)" && owner.starts_with("(*maker")),
"and the pointer's list is the outer declarator's: {lists:?}"
);
}
#[test]
fn debug_initialised_variable() {
let declaration = declaration("std::unique_lock<M> lock(mutex, 1);");
let declarator = declaration
.get_init_declarator()
.and_then(|init| init.child::<cpp_parser::CppDeclarator>());
fn dump(node: &cpp_parser::CppSyntaxNode, depth: usize) {
println!(
"{:indent$}{:?} {:?}",
"",
cpp_parser::CppSyntaxKind::from(node.kind()),
node.text().to_string(),
indent = depth * 2
);
for child in node.children() {
dump(&child, depth + 1);
}
}
match declarator {
Some(declarator) => dump(declarator.syntax(), 0),
None => println!("no declarator"),
}
}