use cpp_code_analysis::{BindingKind, ScopeKind, ScopeTree, build_scopes};
use cpp_parser::{CppParser, CppSyntaxKind, ParserConfig};
fn scopes(source: &str) -> ScopeTree {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(
tree.to_source_text(),
source,
"the parse must stay lossless before anything is read out of it"
);
assert_eq!(
tree.get_errors(),
[],
"the input must parse cleanly for its shape to mean anything: {:?}",
tree.get_errors()
);
build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies)
}
fn shape(table: &ScopeTree) -> String {
fn render(table: &ScopeTree, id: cpp_code_analysis::ScopeId, out: &mut String) {
let scope = table.scope(id).expect("a scope that exists");
let kind = match scope.kind {
ScopeKind::TranslationUnit => "File",
ScopeKind::Namespace => "Ns",
ScopeKind::Class => "Class",
ScopeKind::Enum => "Enum",
ScopeKind::Function => "Fn",
ScopeKind::Block => "Block",
ScopeKind::TemplateParameters => "Params",
ScopeKind::Lambda => "Lambda",
};
out.push_str(kind);
if !scope.bindings.is_empty() {
let names: Vec<String> = scope
.bindings
.iter()
.map(|binding| binding.name.text())
.collect();
out.push('{');
out.push_str(&names.join(","));
out.push('}');
}
if !scope.children.is_empty() {
out.push('(');
for (index, child) in scope.children.iter().enumerate() {
if index > 0 {
out.push(' ');
}
render(table, *child, out);
}
out.push(')');
}
}
let mut out = String::new();
if let Some(root) = table.root() {
render(table, root, &mut out);
}
out
}
fn kind_of(
table: &ScopeTree,
scope: cpp_code_analysis::ScopeId,
name: &str,
) -> Option<BindingKind> {
table
.scope(scope)?
.bindings
.iter()
.find(|binding| binding.name.identifier_text() == Some(name))
.map(|binding| binding.kind)
}
fn qualified_of(table: &ScopeTree, want: ScopeKind, name: Option<&str>) -> Option<String> {
let id = table
.scopes()
.iter()
.position(|scope| scope.kind == want && scope.name.as_deref() == name)?;
table.qualified_name_of(cpp_code_analysis::ScopeId(id))
}
fn bindings_of(
table: &ScopeTree,
scope: cpp_code_analysis::ScopeId,
name: &str,
) -> Vec<(BindingKind, cpp_parser::SourceRange)> {
table
.scope(scope)
.map(|scope| {
scope
.bindings
.iter()
.filter(|binding| binding.name.identifier_text() == Some(name))
.map(|binding| (binding.kind, binding.name_range))
.collect()
})
.unwrap_or_default()
}
#[test]
fn an_empty_file_has_a_file_scope() {
let table = scopes("");
assert_eq!(shape(&table), "File");
assert_eq!(table.len(), 1);
assert!(table.root().is_some());
}
#[test]
fn top_level_declarations_share_the_file_scope() {
let table = scopes("int count;\nvoid f();\nclass Widget {};\n");
assert_eq!(shape(&table), "File{Widget,count,f}");
assert_eq!(
table.len(),
1,
"an empty class body opens no scope, so there is only the file's"
);
}
#[test]
fn a_namespace_opens_a_scope() {
let table = scopes("namespace ns { int x; void f(); }\n");
assert_eq!(shape(&table), "File{ns}(Ns{f,x})");
}
#[test]
fn nested_namespaces_nest() {
let table = scopes("namespace outer { namespace inner { int x; } }\n");
assert_eq!(shape(&table), "File{outer}(Ns{inner}(Ns{x}))");
}
#[test]
fn a_class_declares_its_name_outside_itself() {
let table = scopes("class Widget { int value_; void size(); };\n");
let file = table.root().unwrap();
assert_eq!(
shape(&table),
"File{Widget}(Class{size,value_})",
"the members are inside; the class is outside"
);
assert_eq!(kind_of(&table, file, "Widget"), Some(BindingKind::Class));
let class = table.scope(file).unwrap().children[0];
assert_eq!(
kind_of(&table, class, "Widget"),
None,
"not a member of itself"
);
assert_eq!(
kind_of(&table, class, "value_"),
Some(BindingKind::Variable)
);
assert_eq!(kind_of(&table, class, "size"), Some(BindingKind::Function));
}
#[test]
fn a_nested_class_nests() {
let table = scopes("struct Outer { struct Inner { int x; }; };\n");
assert_eq!(shape(&table), "File{Outer}(Class{Inner}(Class{x}))");
}
#[test]
fn a_class_with_a_destructor_in_its_body_keeps_its_own_name() {
let table = scopes("struct Widget {\n ~Widget();\n int size;\n};\n");
let file = table.root().unwrap();
assert_eq!(
shape(&table),
"File{Widget}(Class{size,~Widget})",
"the class is `Widget`, `size` is its member, and the destructor is a member too — it binds now, where \
the walker used to bind no declarator that was not an `InitDeclarator`"
);
assert_eq!(kind_of(&table, file, "Widget"), Some(BindingKind::Class));
assert_eq!(
qualified_of(&table, ScopeKind::Class, Some("Widget")).as_deref(),
Some("Widget"),
"and the scope it opens is named after it, not after the destructor"
);
}
#[test]
fn a_class_with_an_operator_in_its_body_keeps_its_own_name() {
let table = scopes("struct Widget {\n Widget& operator+(const Widget&);\n int size;\n};\n");
assert_eq!(
shape(&table),
"File{Widget}(Class{size,operator+}(Fn))",
"the class is `Widget`, and the operator is a member of it"
);
}
#[test]
fn a_destructor_without_a_specifier_declares_its_name() {
let table = scopes("struct Widget {\n ~Widget();\n int size;\n};\n");
assert_eq!(shape(&table), "File{Widget}(Class{size,~Widget})");
}
#[test]
fn a_virtual_destructor_is_bound_under_its_tilde_name() {
let table = scopes("struct Widget {\n virtual ~Widget();\n int size;\n};\n");
assert_eq!(shape(&table), "File{Widget}(Class{size,~Widget})");
let class = table.scope(table.root().unwrap()).unwrap().children[0];
let bound = table
.scope(class)
.unwrap()
.bindings
.iter()
.find(|binding| binding.name.identifier_text().is_none())
.expect("the destructor is bound");
assert_eq!(bound.name.text(), "~Widget");
assert_eq!(bound.kind, BindingKind::Destructor);
}
#[test]
fn a_forward_declaration_declares_the_name() {
let table = scopes("class Widget;\nstruct Point;\n");
assert_eq!(shape(&table), "File{Point,Widget}");
assert_eq!(
kind_of(&table, table.root().unwrap(), "Widget"),
Some(BindingKind::Class)
);
}
#[test]
fn an_enum_holds_its_enumerators() {
let table = scopes("enum class Color { Red, Green = 2 };\n");
assert_eq!(shape(&table), "File{Color}(Enum{Green,Red})");
let file = table.root().unwrap();
let enumeration = table.scope(file).unwrap().children[0];
assert_eq!(
table.qualified_name_of(enumeration).as_deref(),
Some("Color"),
"the enumerators belong to `Color`, not to the file"
);
assert_eq!(
kind_of(&table, enumeration, "Red"),
Some(BindingKind::Enumerator)
);
assert_eq!(
kind_of(&table, file, "Red"),
None,
"an enumerator is not in the file scope"
);
let nested = scopes("namespace std { enum class E { Yes }; }\n");
let file = nested.root().unwrap();
let namespace = nested.scope(file).unwrap().children[0];
let enumeration = nested.scope(namespace).unwrap().children[0];
assert_eq!(
nested.qualified_name_of(enumeration).as_deref(),
Some("std::E")
);
}
#[test]
fn an_anonymous_enum_is_not_named_after_an_initializer() {
let table = scopes("enum { A = 1, B = A };\n");
assert_eq!(shape(&table), "File(Enum{A,B})");
let file = table.root().unwrap();
let enumeration = table.scope(file).unwrap().children[0];
assert_eq!(
table.qualified_name_of(enumeration),
None,
"an unnamed enumeration has no qualified name"
);
assert_eq!(
kind_of(&table, enumeration, "A"),
Some(BindingKind::Enumerator)
);
assert_eq!(
kind_of(&table, file, "A"),
None,
"an enumerator is not in the file scope"
);
}
#[test]
fn a_function_binds_its_parameters_in_its_own_scope() {
let table = scopes("int add(int a, int b) { int sum = a + b; return sum; }\n");
assert_eq!(shape(&table), "File{add}(Fn{a,b,sum})");
let file = table.root().unwrap();
let function = table.scope(file).unwrap().children[0];
assert_eq!(kind_of(&table, file, "add"), Some(BindingKind::Function));
assert_eq!(
kind_of(&table, file, "a"),
None,
"a parameter is not in the file scope"
);
assert_eq!(kind_of(&table, function, "a"), Some(BindingKind::Variable));
assert_eq!(
kind_of(&table, function, "sum"),
Some(BindingKind::Variable)
);
}
#[test]
fn a_parameter_is_bound_exactly_once() {
let table = scopes("void f(int value) { value = 1; }\n");
let function = table.scope(table.root().unwrap()).unwrap().children[0];
let bindings = bindings_of(&table, function, "value");
assert_eq!(bindings.len(), 1, "{:?}", table.scope(function).unwrap());
}
#[test]
fn a_declaration_without_a_body_still_binds_its_parameters() {
let table = scopes("void f(int a, double b);\n");
assert_eq!(shape(&table), "File{f}(Fn{a,b})");
}
#[test]
fn a_block_opens_a_nested_scope() {
let table = scopes("void f() { { int inner; } }\n");
assert_eq!(shape(&table), "File{f}(Fn(Block{inner}))");
}
#[test]
fn a_range_for_opens_a_scope_for_its_variable() {
let table = scopes("void f() { for (auto x : items) { } }\n");
assert_eq!(
shape(&table),
"File{f}(Fn(Block{x}(Block)))",
"`x` is in the loop's scope; the body is nested inside it"
);
let function = table.scope(table.root().unwrap()).unwrap().children[0];
let loop_scope = table.scope(function).unwrap().children[0];
assert_eq!(
kind_of(&table, loop_scope, "x"),
Some(BindingKind::Variable),
"the loop variable is declared where the loop can see it"
);
assert_eq!(
kind_of(&table, table.root().unwrap(), "x"),
None,
"and not at file scope"
);
}
#[test]
fn a_range_for_over_a_structured_binding_binds_each_name() {
let table = scopes("void f() { for (auto [key, value] : map) { } }\n");
assert_eq!(shape(&table), "File{f}(Fn(Block{key,value}(Block)))");
}
#[test]
fn a_range_for_over_a_call_binds_only_its_variable() {
let table = scopes("void f() { for (int x : make_items()) { } }\n");
assert_eq!(shape(&table), "File{f}(Fn(Block{x}(Block)))");
}
#[test]
fn a_call_statement_declares_nothing() {
for body in [
"use(x);",
"f();",
"g(a, b);",
"x;",
"a = b;",
"++i;",
"a + b;",
"delete p;",
"return;",
] {
let source = format!("void f() {{ {body} }}\n");
let table = scopes(&source);
let function = table.scope(table.root().unwrap()).unwrap().children[0];
let declared: Vec<String> = table
.scope(function)
.unwrap()
.declared_names()
.iter()
.map(|name| name.text())
.collect();
assert!(
declared.is_empty(),
"{body:?} is a statement, but the walker declared {declared:?}"
);
}
}
#[test]
fn a_real_declaration_is_still_declared() {
let table = scopes(
"void f() {\n\
int local;\n\
int initialised = 1;\n\
const char* name = \"x\";\n\
auto deduced = 2;\n\
Widget widget{1, 2};\n\
int direct(1, 2);\n\
std::vector<int> values;\n\
Foo* pointer = new Foo();\n\
}\n",
);
assert_eq!(
shape(&table),
"File{f}(Fn{deduced,direct,initialised,local,name,pointer,values,widget})",
"every one of these declares a name"
);
}
#[test]
fn direct_initialisation_declares_a_variable() {
for source in [
"void f() { int a(1); }\n",
"void f() { double d(1.5); }\n",
"void f() { char c('x'); }\n",
"void f() { unsigned int u(1); }\n",
] {
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:?} must stay lossless"
);
assert!(
tree.get_red_root()
.descendants()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
"{source:?} declares a variable with an initializer"
);
}
}
#[test]
fn a_call_keeps_its_argument_list() {
for source in [
"void f() { g(1); }\n",
"void f() { g(1, 2); }\n",
"void f() { obj.method(1); }\n",
"void f() { p->method(x); }\n",
"Max(a, 1);\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(
tree.get_errors(),
[],
"{source:?} must parse cleanly, got {:?}",
tree.get_errors()
);
assert!(
tree.get_red_root()
.descendants()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::CallExpr),
"{source:?} is a call, not a declaration"
);
}
}
#[test]
fn direct_initialisation_of_a_user_type_declares_a_variable() {
for source in [
"struct Widget {};\nvoid f() { Widget w(1, 2); }\n",
"class Widget {};\nvoid f() { Widget w(1, 2); }\n",
"union Widget {};\nvoid f() { Widget w(1, 2); }\n",
"enum class Widget {};\nvoid f() { Widget w(1, 2); }\n",
"using Widget = int;\nvoid f() { Widget w(1, 2); }\n",
"typedef int Integer;\nvoid f() { Integer i(1); }\n",
"struct Outer { struct Inner {}; void m() { Inner i(1); } };\n",
"struct Widget {};\nWidget make();\n",
] {
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:?} must stay lossless"
);
}
let table = scopes(
"struct Widget {};\nvoid f() {\n Widget w(1, 2);\n Widget v;\n}\nstruct Outer { Inner i(1); };\n",
);
assert_eq!(
shape(&table),
"File{Outer,Widget,f}(Fn{v,w} Class{i})",
"both direct-initialised variables are declared"
);
}
#[test]
fn a_user_type_declared_later_is_still_a_declaration() {
let source = "void f() { Widget w(1, 2); }\nstruct Widget {};\n";
let tree = CppParser::parse(source, ParserConfig::default());
assert!(
tree.get_red_root()
.descendants()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
"the declarator's name is the evidence, and it is there whether or not the type is"
);
assert_eq!(tree.to_source_text(), source, "and the file stays lossless");
}
#[test]
fn an_undeclared_type_name_is_still_a_declaration() {
for source in [
"void f() { Widget w(1, 2); }\n",
"void f() { std::string s(\"x\"); }\n",
"void f() { Foo bar(1); }\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
assert!(
tree.get_red_root()
.descendants()
.any(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::Initializer),
"{source:?} names a declarator and initialises it"
);
assert_eq!(tree.to_source_text(), source, "{source:?} stays lossless");
}
}
#[test]
fn sizeof_a_builtin_type_parses() {
for source in [
"void f() { sizeof(int); }\n",
"void f() { sizeof(unsigned char); }\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
assert!(
tree.get_errors().is_empty(),
"{source:?} should parse, got {:?}",
tree.get_errors()
);
assert_eq!(tree.to_source_text(), source, "and stays lossless");
}
for source in [
"void f() { sizeof(std::vector<int>); }\n",
"void f() { sizeof(Foo); }\n",
"void f() { sizeof x; }\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(tree.get_errors(), [], "{source:?} parses");
}
}
#[test]
fn assignment_operators_parse() {
for body in [
"a = b;",
"i += 1;",
"i -= 1;",
"i *= 2;",
"i /= 2;",
"i %= 2;",
"flags &= mask;",
"flags |= mask;",
"flags ^= mask;",
"value <<= 2;",
"value >>= 2;",
"a = b = c;",
"arr[0] = 1;",
"arr[0] += 1;",
"p->field = 1;",
"p->next = q;",
"obj.field = obj.other;",
"*p = 5;",
"x = y + z * w;",
] {
let source = format!("void f() {{ {body} }}\n");
let tree = CppParser::parse(&source, ParserConfig::default());
assert_eq!(
tree.get_errors(),
[],
"{body:?} must parse cleanly, got {:?}",
tree.get_errors()
);
assert_eq!(tree.to_source_text(), source, "{body:?} must stay lossless");
}
}
#[test]
fn assignment_is_right_associative() {
let source = "void f() { *p = *q = 5; }\n";
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(tree.get_errors(), [], "must parse cleanly");
let outer = tree
.get_red_root()
.descendants()
.find(|node| CppSyntaxKind::from(node.kind()) == CppSyntaxKind::BinaryExpr)
.expect("a binary expression");
assert_eq!(
outer.text().to_string(),
"*p = *q = 5",
"the outer assignment covers the whole chain"
);
let inner = outer
.children()
.find(|child| CppSyntaxKind::from(child.kind()) == CppSyntaxKind::BinaryExpr)
.expect("the right-hand side is itself an assignment");
assert_eq!(
inner.text().to_string(),
"*q = 5",
"which is what right-associative means here"
);
}
#[test]
fn a_loop_opens_a_scope_for_its_init_declaration() {
let table = scopes("void f() { for (int i = 0; i < 3; ++i) { int body; } }\n");
assert_eq!(
shape(&table),
"File{f}(Fn(Block{i}(Block{body})))",
"`i` is in the loop's scope; `body` is in the body's, nested inside it"
);
}
#[test]
fn sibling_branches_have_separate_scopes() {
let table = scopes("void f() { if (c) { int x; } else { int x; } }\n");
assert_eq!(
shape(&table),
"File{f}(Fn(Block(Block{x} Block{x})))",
"the function's block, then one scope per branch"
);
let function = table.scope(table.root().unwrap()).unwrap().children[0];
let body = table.scope(function).unwrap().children[0];
let branches = &table.scope(body).unwrap().children;
assert_eq!(branches.len(), 2, "one scope per branch");
let first = bindings_of(&table, branches[0], "x");
let second = bindings_of(&table, branches[1], "x");
assert_eq!(first.len(), 1);
assert_eq!(second.len(), 1);
assert_ne!(
first[0].1, second[0].1,
"two declarations of the same name at different offsets"
);
}
#[test]
fn a_switch_opens_one_scope_for_all_its_cases() {
let table = scopes("void f() { switch (n) { case 1: { int a; } case 2: { int b; } } }\n");
assert_eq!(shape(&table), "File{f}(Fn(Block(Block{a} Block{b})))");
}
#[test]
fn a_label_is_bound() {
let table = scopes("void f() { goto done; done: return; }\n");
assert_eq!(shape(&table), "File{f}(Fn{done})");
let function = table.scope(table.root().unwrap()).unwrap().children[0];
assert_eq!(kind_of(&table, function, "done"), Some(BindingKind::Label));
}
#[test]
fn a_typedef_declares_its_name() {
let table = scopes("typedef int Integer;\n");
assert_eq!(shape(&table), "File{Integer}");
assert_eq!(
kind_of(&table, table.root().unwrap(), "Integer"),
Some(BindingKind::Typedef)
);
}
#[test]
fn a_typedef_declares_every_name_it_lists() {
let table = scopes("typedef WCHAR *PWCHAR, *LPWCH, *PWCH;\n");
assert_eq!(shape(&table), "File{LPWCH,PWCH,PWCHAR}");
for name in ["PWCHAR", "LPWCH", "PWCH"] {
assert_eq!(
kind_of(&table, table.root().unwrap(), name),
Some(BindingKind::Typedef),
"`{name}` is one of the declaration's names"
);
}
}
#[test]
fn a_using_declaration_is_told_apart_from_an_alias() {
let table = scopes("using Alias = int;\n");
assert_eq!(
kind_of(&table, table.root().unwrap(), "Alias"),
Some(BindingKind::Alias)
);
let table = scopes("using ns::f;\n");
assert_eq!(
shape(&table),
"File{f}",
"the name is the last component, not the qualifier"
);
assert_eq!(
kind_of(&table, table.root().unwrap(), "f"),
Some(BindingKind::UsingDeclaration)
);
}
#[test]
fn a_using_directive_is_recorded() {
let table = scopes("using namespace std;\n");
assert_eq!(shape(&table), "File{std}");
assert_eq!(
kind_of(&table, table.root().unwrap(), "std"),
Some(BindingKind::UsingDirective)
);
}
#[test]
fn a_template_parameter_scope_wraps_the_declaration() {
let table = scopes("template <typename T, int N> class Array { T data[N]; };\n");
assert_eq!(
shape(&table),
"File{Array}(Params{N,T}(Class{data}))",
"`Array` is outside the parameter scope; `T` and `N` are in it"
);
}
#[test]
fn a_template_parameter_has_its_own_kind() {
let table = scopes("template <typename T> T id(T x) { return x; }\n");
let params = table.scope(table.root().unwrap()).unwrap().children[0];
assert_eq!(
kind_of(&table, params, "T"),
Some(BindingKind::TemplateParameter)
);
assert_eq!(
table.scope(params).unwrap().kind,
ScopeKind::TemplateParameters
);
}
#[test]
fn a_template_parameter_is_not_in_the_file_scope() {
let table = scopes("template <typename T> T id(T x) { return x; }\n");
let shape = shape(&table);
assert!(shape.starts_with("File{id}(Params{T}"), "{shape}");
assert_eq!(
kind_of(&table, table.root().unwrap(), "T"),
None,
"T belongs to the template"
);
}
#[test]
fn a_qualified_declaration_binds_nothing_here() {
let table = scopes("int ns::Widget::count = 0;\n");
assert_eq!(
shape(&table),
"File",
"the name belongs to `ns::Widget`, which this file does not declare"
);
}
#[test]
fn a_qualified_name_in_a_base_clause_does_not_make_the_declaration_qualified() {
for source in [
"struct W : Base<A::B> {};\n",
"struct W : A::B {};\n",
"struct W : public Base<std::vector<int>> {};\n",
"struct W : Base<A::B>, Other<C::D> {};\n",
"template <class T> struct W : conditional_t<A::value, Base> {};\n",
] {
let table = scopes(source);
let file = table.scope(table.root().unwrap()).unwrap();
let names: Vec<String> = file
.bindings
.iter()
.map(|binding| binding.name.text())
.collect();
assert!(
names.iter().any(|name| name == "W"),
"the class is declared here — nothing in its base clause is its own name: {source:?} gave {names:?}"
);
}
let table = scopes("int ns::Widget::count = 0;\n");
assert_eq!(
shape(&table),
"File",
"a genuinely qualified declaration still binds nothing here"
);
}
#[test]
fn a_friend_declaration_binds_nothing() {
let table = scopes("class Widget { friend class Helper; friend void free_fn(); };\n");
let class = table.scope(table.root().unwrap()).unwrap().children[0];
let names: Vec<String> = table
.scope(class)
.unwrap()
.bindings
.iter()
.map(|binding| binding.name.text())
.collect();
assert!(
names.is_empty(),
"a friend declares nothing here, got {names:?}"
);
}
#[test]
fn a_class_whose_members_write_qualified_names_is_still_declared() {
for text in [
"template <class T> class Widget { std::vector<int> values; };\n",
"class Widget { int f(std::size_t n = std::numeric_limits<int>::max()); };\n",
"struct Widget { using type = std::allocator_traits<Alloc>::value_type; };\n",
] {
let table = scopes(text);
let names: Vec<String> = table
.scope(table.root().unwrap())
.unwrap()
.bindings
.iter()
.map(|binding| binding.name.text())
.collect();
assert!(
names.iter().any(|name| name == "Widget"),
"`Widget` is declared in this file, whatever its members write: {names:?} for {text:?}"
);
}
}
#[test]
fn a_qualified_name_with_nested_segments_is_read_without_panicking() {
let table = scopes(
"\
template <class T> struct Outer { struct Inner { void grow(); }; };
template <class T> void Outer<T>::Inner::grow() {}
template <class T> void Outer<T>::grow() {}
template <class T> void Outer<A::B>::grow() {}
void Outer<Box<int>>::grow() {}
void Outer<int>::grow(Outer<int>::Inner* p) {}
int Outer<int>::count = 0;
",
);
let named = |wanted: &str| -> Vec<String> {
(0..table.scopes().len())
.filter(|index| {
table
.qualified_name_of(cpp_code_analysis::ScopeId(*index))
.as_deref()
== Some(wanted)
})
.flat_map(|index| {
table
.scope(cpp_code_analysis::ScopeId(index))
.map(|scope| {
scope
.bindings
.iter()
.map(|binding| binding.name.text())
.collect::<Vec<_>>()
})
.unwrap_or_default()
})
.collect()
};
let in_class = named("Outer");
let in_inner = named("Outer::Inner");
assert!(
in_class.contains(&"grow".to_string()) && in_class.contains(&"count".to_string()),
"the members written through a template argument are members of the class: {in_class:?}"
);
assert!(
in_inner.contains(&"grow".to_string()),
"and the nested one is in the nested class: {in_inner:?}"
);
}
#[test]
fn a_static_assert_declares_nothing() {
let table = scopes("int before;\nstatic_assert(true);\nint after;\n");
assert_eq!(shape(&table), "File{after,before}");
}
#[test]
fn a_static_assert_with_a_comparison_parses() {
let source = "static_assert(sizeof(int) > 0);\n";
let tree = CppParser::parse(source, ParserConfig::default());
assert!(
tree.get_errors().is_empty(),
"the comparison should parse, got {:?}",
tree.get_errors()
);
assert_eq!(
tree.to_source_text(),
source,
"and stays lossless regardless"
);
assert_eq!(shape(&scopes(source)), "File");
}
#[test]
fn a_use_is_not_a_binding() {
let table = scopes("void f() { undeclared_name; other(); }\n");
assert_eq!(
shape(&table),
"File{f}(Fn)",
"nothing is bound for a name that is only used"
);
}
#[test]
fn a_scope_a_macro_body_opens_holds_the_declarations_behind_it() {
use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};
let files = MemoryFiles::new()
.with_file(
"/p/ns.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
)
.with_file(
"/p/main.cpp",
"#include \"ns.h\"\n_STD_BEGIN\nstruct vector { int size; };\n_STD_END\n",
);
let root = std::env::temp_dir().join("cppls-macro-scope-tests");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the test directory");
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
let indexed =
store.index_includes_from(std::path::Path::new("/p/main.cpp"), Default::default());
assert_eq!(
indexed.re_read, 2,
"both files mention a name the closure gives a body to — `main.cpp` invokes it and `ns.h` writes the \
`#define` — which is exactly what the filter's soundness costs: one re-parse of the file that defined \
it, whose summary comes out identical. What matters is that the file which does *not* mention it is not \
re-read, and that nothing that could change is skipped: {:?}",
indexed.indexed
);
let summary = store
.index()
.summary(std::path::Path::new("/p/main.cpp"))
.expect("main.cpp is indexed");
let vector = summary
.declarations
.iter()
.find(|fact| fact.name == "vector")
.expect("the class was read");
assert_eq!(
vector.scope.as_deref(),
Some("std"),
"the body's `namespace std {{` is what puts it there: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
assert_eq!(vector.qualified_name(), "std::vector");
let readings: Vec<(&str, Option<Vec<String>>)> = summary
.macro_readings
.iter()
.map(|reading| (reading.name.as_str(), reading.opens.clone()))
.collect();
assert_eq!(
readings,
vec![
("_STD_BEGIN", Some(vec!["std".to_string()])),
("_STD_END", None),
],
"both invocations are recorded, and the closer is told apart by having no scope"
);
assert_eq!(summary.macro_readings[0].body.trim(), "namespace std {");
assert_eq!(summary.macro_readings[1].body.trim(), "}");
assert!(
summary.declarations.iter().all(|fact| fact.name != "std"),
"no fact is invented for a name the file does not write: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
match store
.index()
.definition("std::vector", std::path::Path::new("/p/main.cpp"))
{
Known::Yes(found) => {
assert_eq!(found.fact.name, "vector");
assert_eq!(found.fact.qualified_name(), "std::vector");
}
other => panic!("`std::vector` must resolve through the scope a body opened: {other:?}"),
}
let files = MemoryFiles::new()
.with_file(
"/q/ns.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n\
#if defined(_BUILD_STD_MODULE)\n#define _EXPORT_STD export\n#else\n#define _EXPORT_STD\n#endif\n",
)
.with_file(
"/q/main.cpp",
"#include \"ns.h\"\n_STD_BEGIN\n_EXPORT_STD template <class _Ty, class _Alloc = allocator<_Ty>>\nclass vector { // varying size array of values\npublic:\n using value_type = _Ty;\n};\n_STD_END\n",
);
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());
let summary = store
.index()
.summary(std::path::Path::new("/q/main.cpp"))
.expect("main.cpp is indexed");
let vector = summary
.declarations
.iter()
.find(|fact| fact.name == "vector")
.unwrap_or_else(|| {
panic!(
"the class was read: {:?}",
summary
.declarations
.iter()
.map(|fact| (fact.qualified_name(), fact.kind))
.collect::<Vec<_>>()
)
});
assert_eq!(
vector.scope.as_deref(),
Some("std"),
"a macro in front of the declaration does not change whose scope it is in: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
}
#[test]
fn a_scope_a_macro_body_opens_is_held_where_the_invocation_is_two_headers_down() {
use cpp_code_analysis::{CompilerConfig, MemoryFiles, SummaryStore};
let files = MemoryFiles::new()
.with_file(
"/q/deep.h",
"#pragma once\n#define NSB namespace deepns {\n#define NSE }\nNSB\nstruct Deep { int d; };\nNSE\n",
)
.with_file("/q/mid.h", "#pragma once\n#include \"deep.h\"\n")
.with_file(
"/q/main.cpp",
"#include \"mid.h\"\nvoid f() { deepns::Deep d; }\n",
);
let root = std::env::temp_dir().join("cppls-macro-scope-deep-tests");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the test directory");
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());
let summary = store
.index()
.summary(std::path::Path::new("/q/deep.h"))
.expect("deep.h is indexed");
let deep = summary
.declarations
.iter()
.find(|fact| fact.name == "Deep")
.unwrap_or_else(|| {
panic!(
"the declaration was read: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
)
});
assert_eq!(
deep.scope.as_deref(),
Some("deepns"),
"the file that writes the `#define` and invokes it keeps the scope it opens, however deep it is: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
}
#[test]
fn a_function_behind_an_export_macro_is_in_the_namespace_the_macro_opened() {
use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};
let files = MemoryFiles::new()
.with_file(
"/q/ns.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n\
#if defined(_BUILD_STD_MODULE)\n#define _EXPORT_STD export\n#else\n#define _EXPORT_STD\n#endif\n",
)
.with_file(
"/q/main.cpp",
"#include \"ns.h\"\n_STD_BEGIN\n_EXPORT_STD template <class _Ty>\n_Ty format(int _Fmt);\n_STD_END\n",
);
let root = std::env::temp_dir().join("cppls-macro-scope-function-tests");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the test directory");
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());
let summary = store
.index()
.summary(std::path::Path::new("/q/main.cpp"))
.expect("main.cpp is indexed");
let format = summary
.declarations
.iter()
.find(|fact| fact.name == "format")
.unwrap_or_else(|| {
panic!(
"the function was read: {:?}",
summary
.declarations
.iter()
.map(|fact| (fact.qualified_name(), fact.kind))
.collect::<Vec<_>>()
)
});
assert_eq!(
format.scope.as_deref(),
Some("std"),
"a function is scoped by the namespace the macro opened, exactly as the class beside it is: {:?}",
summary
.declarations
.iter()
.map(|fact| fact.qualified_name())
.collect::<Vec<_>>()
);
match store
.index()
.definition("std::format", std::path::Path::new("/q/main.cpp"))
{
Known::Yes(found) => assert_eq!(found.fact.qualified_name(), "std::format"),
other => {
panic!("`std::format` must resolve for the same reason `std::vector` does: {other:?}")
}
}
}
#[test]
fn an_inline_namespace_is_transparent_to_a_qualified_name() {
use cpp_code_analysis::{CompilerConfig, DeclFact, MemoryFiles, SummaryStore};
let headers = [
(
"macro, conditional, inline",
"#pragma once\n#if 1\n#define NSB inline namespace deepns {\n#define NSE }\n#else\n#define NSB\n#define NSE\n#endif\n",
"std::Deep",
),
(
"macro, conditional, plain",
"#pragma once\n#if 1\n#define NSB namespace deepns {\n#define NSE }\n#else\n#define NSB\n#define NSE\n#endif\n",
"std::deepns::Deep",
),
(
"macro, plain, inline",
"#pragma once\n#define NSB inline namespace deepns {\n#define NSE }\n",
"std::Deep",
),
(
"macro, plain, plain",
"#pragma once\n#define NSB namespace deepns {\n#define NSE }\n",
"std::deepns::Deep",
),
("written out, inline", "#pragma once\n", "std::Deep"),
];
let sources = [
"#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
"#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
"#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
"#include \"pair.h\"\nnamespace std {\nNSB\nstruct Deep { int d; };\nNSE\nint after(int);\n}\n",
"#include \"pair.h\"\nnamespace std {\ninline namespace deepns {\nstruct Deep { int d; };\n}\nint after(int);\n}\n",
];
let mut readings: Vec<(&str, Vec<String>, Vec<String>)> = Vec::new();
for ((label, header, _), source) in headers.into_iter().zip(sources) {
let files = MemoryFiles::new()
.with_file("/q/pair.h", header)
.with_file("/q/main.cpp", source);
let root = std::env::temp_dir().join(format!(
"cppls-inline-namespace-{}",
label.replace(' ', "-")
));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the test directory");
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());
let summary = store
.index()
.summary(std::path::Path::new("/q/main.cpp"))
.expect("main.cpp is indexed");
let names = |want: &str| -> Vec<String> {
summary
.declarations
.iter()
.filter(|fact| fact.name == want)
.map(DeclFact::qualified_name)
.collect()
};
readings.push((label, names("Deep"), names("after")));
}
for ((label, _, expected), (_, deep, after)) in headers.iter().zip(&readings) {
assert_eq!(
after,
&vec!["std::after".to_string()],
"({label}) the declaration after the closer is in `std`"
);
assert_eq!(
deep,
&vec![expected.to_string()],
"({label}) an inline namespace's members are the enclosing namespace's members, and an ordinary \
namespace's are its own. All five readings: {readings:?}"
);
}
}
#[test]
fn a_member_of_an_aliased_class_resolves_through_the_alias() {
use cpp_code_analysis::{CompilerConfig, Known, MemoryFiles, SummaryStore};
let files = MemoryFiles::new().with_file(
"/q/main.cpp",
"namespace std {\n\
template <class _Ty> struct basic_string { using size_type = unsigned long long; };\n\
using string = basic_string<char>;\n\
}\n\
std::basic_string<char>::size_type a;\n\
std::string::size_type b;\n",
);
let root = std::env::temp_dir().join("cppls-alias-member-tests");
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the test directory");
let mut store = SummaryStore::with_provider(&root, CompilerConfig::default(), files);
store.index_includes_from(std::path::Path::new("/q/main.cpp"), Default::default());
let index = store.index();
let main = std::path::Path::new("/q/main.cpp");
assert!(
matches!(
index.definition("std::basic_string::size_type", main),
Known::Yes(_)
),
"the member under the class that declares it resolves: {:?}",
index.definition("std::basic_string::size_type", main)
);
match index.definition("std::string::size_type", main) {
Known::Yes(found) => assert_eq!(found.fact.name, "size_type"),
other => panic!("a member spelled through an alias must resolve through it: {other:?}"),
}
assert!(
matches!(
index.definition("std::string::not_a_member", main),
Known::Unknown(_)
),
"the fallback rewrites a name, it does not invent a declaration: {:?}",
index.definition("std::string::not_a_member", main)
);
}
#[test]
fn a_word_in_a_body_that_expands_to_nothing_does_not_stop_the_reading() {
use cpp_code_analysis::{MacroBodies, build_scopes};
use cpp_parser::{CppParser, IncludedMacro, MacroEnvironment, ParserConfig};
const STD_BEGIN: &str = " \\\n _EXTERN_CXX_WORKAROUND \\\n namespace std {\n";
const NOTHING: &str = " \n";
const STD_END: &str = " \\\n _END_EXTERN_CXX_WORKAROUND \\\n }\n";
let word = |name: &str, body: &str| IncludedMacro {
name: name.into(),
from_offset: 0,
definition: None,
body_text: Some(body.into()),
parameters: None,
};
let environment = MacroEnvironment::from_included_macros([
word("_STD_BEGIN", STD_BEGIN),
word("_STD_END", STD_END),
word("_EXTERN_CXX_WORKAROUND", NOTHING),
word("_END_EXTERN_CXX_WORKAROUND", NOTHING),
]);
assert!(
MacroBodies::body_at(&environment, "_EXTERN_CXX_WORKAROUND", 0)
.is_some_and(|body| body.trim().is_empty()),
"the fixture's empty word must answer an empty body"
);
assert_eq!(
cpp_parser::shape_of_a_body(STD_BEGIN),
cpp_parser::BodyShape::Other,
"…and without the environment the shape is unreadable, which is the state the bug was found in"
);
const FORMAT: &str = "\
_STD_BEGIN
_EXPORT_STD template <class... _Types>
_NODISCARD string format(const format_string<_Types...> _Fmt, _Types&&... _Args) {
return {};
}
_STD_END
int at_file_scope;
";
let tree = CppParser::parse(FORMAT, ParserConfig::default());
let scopes = build_scopes(&tree.get_red_root(), &environment);
let readings: Vec<(&str, Option<Vec<String>>)> = scopes
.macro_readings
.iter()
.map(|reading| (reading.name.as_str(), reading.opens.clone()))
.collect();
assert_eq!(
readings,
vec![
("_STD_BEGIN", Some(vec!["std".to_string()])),
("_STD_END", None),
],
"the two invocations are read **through** the empty word between their own names and the braces"
);
let scope_of = |wanted: &str| {
cpp_code_analysis::ScopeId(
scopes
.scopes()
.iter()
.position(|scope| {
scope
.bindings
.iter()
.any(|binding| binding.name.text() == wanted)
})
.unwrap_or_else(|| panic!("`{wanted}` was not declared at all")),
)
};
assert_eq!(
scopes
.qualification_prefix_of(scope_of("format"))
.unwrap_or_default(),
"std",
"`format` is a member of `std`"
);
assert_ne!(
scope_of("at_file_scope"),
scope_of("format"),
"and the declaration after `_STD_END` is back at file scope, so the closer was read too"
);
}
#[test]
fn a_recovered_parse_still_declares_what_it_can() {
let tree = CppParser::parse(
"int before;\nstruct { ; \nint after;\n",
ParserConfig::default(),
);
let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);
assert_eq!(
tree.to_source_text(),
"int before;\nstruct { ; \nint after;\n"
);
let names: Vec<String> = table
.scope(table.root().unwrap())
.unwrap()
.bindings
.iter()
.map(|binding| binding.name.text())
.collect();
assert!(
names.contains(&"before".to_string()),
"the declarations before the damage are read: {names:?}"
);
}
#[test]
fn an_anonymous_namespace_opens_a_scope_without_binding_a_name() {
let table = scopes("namespace { int hidden; }\n");
assert_eq!(shape(&table), "File(Ns{hidden})");
}
#[test]
fn an_unnamed_parameter_declares_nothing() {
let table = scopes("void f(int, double named) {}\n");
assert_eq!(shape(&table), "File{f}(Fn{named})");
}
#[test]
fn a_structured_binding_binds_each_name() {
let table = scopes("void f() { auto [first, second] = pair; }\n");
assert_eq!(shape(&table), "File{f}(Fn{first,second})");
let function = table.scope(table.root().unwrap()).unwrap().children[0];
assert_eq!(
kind_of(&table, function, "first"),
Some(BindingKind::Variable)
);
assert_eq!(
kind_of(&table, function, "second"),
Some(BindingKind::Variable)
);
}
#[test]
fn building_scopes_never_panics() {
let sources = [
"",
";",
"{",
"}",
"namespace",
"namespace {",
"class",
"class {",
"template <",
"template <typename> ",
"void f(",
"void f() {",
"enum {",
"using",
"typedef",
"struct A : B {",
"int ns::",
"auto [a, = x;",
"[[nodiscard]]",
"void f(int a = {1, 2}) {}",
"class A { class B { class C { int x; }; }; };",
"void f() { for (;;) { while (1) { if (x) { } } } }",
];
for source in sources {
let tree = CppParser::parse(source, ParserConfig::default());
assert_eq!(
tree.to_source_text(),
source,
"losslessness must hold even here: {source:?}"
);
let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);
if let Some(root) = table.root() {
for offset in 0..source.len().min(64) {
if let Some(scope) = table.scope_at(offset) {
let _ = table.scope_chain(scope);
let _ = table.scope(scope).map(|scope| scope.declared_names());
}
}
let _ = table.scope_chain(root);
}
}
}
#[test]
fn the_scope_at_an_offset_is_the_innermost_on_a_real_file() {
let source = "class Widget {\n void size() {\n int local = 0;\n }\n};\n";
let table = scopes(source);
let keyword_offset = source.find("class").unwrap();
let body_offset = source.find('{').unwrap() + 1;
let method_offset = source.find("void size").unwrap() + 5;
let local_offset = source.find("int local").unwrap() + 5;
let at = |offset: usize| {
let scope = table.scope_at(offset).expect("a scope");
table.scope(scope).unwrap().kind
};
assert_eq!(
at(keyword_offset),
ScopeKind::Class,
"the class node starts at its keyword"
);
assert_eq!(at(body_offset), ScopeKind::Class, "just inside the body");
assert_eq!(at(method_offset), ScopeKind::Function, "inside the method");
assert_eq!(
at(local_offset),
ScopeKind::Function,
"inside the method body"
);
assert_eq!(at(method_offset), ScopeKind::Function, "inside the method");
assert_eq!(
at(local_offset),
ScopeKind::Function,
"inside the method body"
);
}
#[test]
fn a_scope_reports_only_its_own_bindings() {
let table = scopes("namespace ns { int inner; }\nint outer;\n");
let file = table.root().unwrap();
let names: Vec<String> = table
.scope(file)
.unwrap()
.declared_names()
.iter()
.map(|name| name.text())
.collect();
assert_eq!(names, vec!["ns", "outer"], "not `inner`");
}
#[test]
fn a_bindings_name_range_covers_just_the_name() {
let source = "int counter = 42;\n";
let table = scopes(source);
let file = table.root().unwrap();
let binding = &table.scope(file).unwrap().bindings[0];
let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];
assert_eq!(slice(binding.name_range), "counter");
assert!(
binding.name_range.length < binding.range.length,
"the name is a part of the declaration, not the whole of it"
);
}
#[test]
fn a_bindings_range_is_its_declarator() {
let source = "int counter = 42;\n";
let table = scopes(source);
let file = table.root().unwrap();
let binding = &table.scope(file).unwrap().bindings[0];
let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];
assert_eq!(slice(binding.name_range), "counter");
assert_eq!(slice(binding.range), "counter = 42");
assert!(
binding.name_range.length < binding.range.length,
"the name is a part of the declarator, not the whole of it"
);
}
#[test]
fn a_shared_declaration_is_not_attributed_to_one_name() {
let source = "int a = 1, b = 2;\n";
let table = scopes(source);
let file = table.root().unwrap();
let slice = |range: cpp_parser::SourceRange| &source[range.start_offset..range.end_offset()];
let named = |name: &str| {
table
.scope(file)
.unwrap()
.bindings
.iter()
.find(|binding| binding.name.text() == name)
.unwrap_or_else(|| panic!("`{name}` is declared here"))
.range
};
assert_eq!(slice(named("a")), "a = 1");
assert_eq!(slice(named("b")), "b = 2");
}
#[test]
fn a_scope_records_the_name_it_introduces() {
let table = scopes("namespace ns { struct C { int member; }; }\n");
assert_eq!(
qualified_of(&table, ScopeKind::Namespace, Some("ns")).as_deref(),
Some("ns")
);
assert_eq!(
qualified_of(&table, ScopeKind::Class, Some("C")).as_deref(),
Some("ns::C"),
"the class's qualified name includes the namespace it was written in"
);
}
#[test]
fn a_nested_namespace_spelling_is_the_same_name() {
let compact = scopes("namespace a::b { struct C { int member; }; }\n");
let spelled = scopes("namespace a { namespace b { struct C { int member; }; } }\n");
for table in [&compact, &spelled] {
assert_eq!(
qualified_of(table, ScopeKind::Class, Some("C")).as_deref(),
Some("a::b::C"),
"both spellings name the same class"
);
}
}
#[test]
fn an_unnamed_scope_is_transparent() {
let table = scopes("namespace ns { void f() { int local = 0; } }\n");
let function = table
.scopes()
.iter()
.position(|scope| scope.kind == ScopeKind::Function)
.expect("the function body has a scope");
let function = cpp_code_analysis::ScopeId(function);
assert_eq!(
table.qualified_name_of(function).as_deref(),
Some("ns"),
"the function body contributes no segment but does not cut the namespace off"
);
assert_eq!(
table.scope(function).expect("the scope").name,
None,
"and it really is unnamed rather than named `f`"
);
}
#[test]
fn an_unnamed_class_takes_the_name_of_the_variable_it_declares() {
let table = scopes("namespace ns { struct { int member; } value; }\n");
let class = table
.scopes()
.iter()
.position(|scope| scope.kind == ScopeKind::Class)
.expect("the class body has a scope");
assert_eq!(
table.qualified_name_of(cpp_code_analysis::ScopeId(class)),
Some("ns::value".to_string()),
"the declarator's name is the segment, under the namespace it was written in"
);
}
#[test]
fn a_member_is_found_under_its_class() {
let table = scopes("namespace ns { struct C { void method(); int field; }; }\n");
let class = table
.scopes()
.iter()
.position(|scope| scope.kind == ScopeKind::Class)
.expect("the class body has a scope");
let class = cpp_code_analysis::ScopeId(class);
let members: Vec<String> = table
.scope(class)
.expect("the scope")
.bindings
.iter()
.map(|binding| {
format!(
"{}::{}",
table.qualified_name_of(class).expect("the class is named"),
binding.name.text()
)
})
.collect();
assert_eq!(members, ["ns::C::field", "ns::C::method"]);
}
#[test]
fn the_file_scope_has_no_qualified_name() {
let table = scopes("int x;\n");
let root = table.root().expect("a non-empty file has a file scope");
assert_eq!(table.scope(root).expect("the scope").name, None);
assert_eq!(table.qualified_name_of(root), None);
}
#[test]
fn a_linkage_specification_declares_what_it_covers() {
let source = "\
namespace std {
extern \"C++\" template <class _Elem, class _Traits>
class basic_istream {
public:
void read(int n);
int member;
};
extern \"C\" { void c_function(int); }
}
";
let table = scopes(source);
assert_eq!(
shape(&table),
"File{std}(Ns{basic_istream,c_function}(Params{_Elem,_Traits}(Class{member,read}(Fn{n})) Fn))",
"the class and the C function are both declared, in `std`"
);
}
#[test]
fn an_extern_variable_is_a_declaration() {
let table = scopes("struct Widget { int size; };\nextern Widget global;\n");
assert_eq!(shape(&table), "File{Widget,global}(Class{size})");
}
#[test]
fn a_local_declared_with_a_qualified_type_is_bound() {
let table = scopes(
"namespace std { using size_t = unsigned long; }\n\
void f() {\n\
\x20 std::size_t length = 0;\n\
\x20 std::string line;\n\
}\n",
);
let body = shape(&table);
assert!(
body.contains("length"),
"the declaration is the declarator's, wherever its type came from: {body}"
);
assert!(body.contains("line"), "and so is the next one: {body}");
}
#[test]
fn operators_bind_a_name() {
let table = scopes("struct M { int operator*() const; int operator[](int at); int cents; };\n");
let shape = shape(&table);
assert!(shape.contains("operator*"), "{shape}");
assert!(shape.contains("operator[]"), "{shape}");
assert!(shape.contains("cents"), "{shape}");
}
#[test]
fn a_local_whose_extent_is_a_macro_is_placed() {
use cpp_code_analysis::sema::declarations::local_references_of;
for source in [
"void f() {\n int more[4];\n (void)more;\n}\n",
"#define N 4\nvoid f() {\n int more[N];\n (void)more;\n}\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
let root = tree.get_red_root();
let table = build_scopes(&root, &cpp_code_analysis::NoMacroBodies);
let locals = local_references_of(&table, &root);
println!("{source:?} → {locals:?}");
assert!(
locals.iter().any(|entry| {
source[entry.declared_at as usize..].starts_with("more") && !entry.uses.is_empty()
}),
"`more` is a local, declared at one place and used at another: {locals:?}"
);
}
}
#[test]
fn a_nested_class_ends_where_its_brace_ends() {
for source in [
"class C { struct Inner : Base { int x; }; int size() const; };\n",
"class C {\n#if __cplusplus < 201103L\n int old();\n#else\n struct Inner : Base { int x; };\n#endif\n int size() const;\n};\n",
"class C {\n struct Inner : Base {\n#if 1\n Inner() : Base() { }\n#endif\n int x;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base { Inner() : Base() { }\n#if 1\n int y;\n#endif\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base // note\n {\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n#if A\n Inner(p a)\n : Base(a), _M_p(a) { }\n#else\n Inner(p a)\n : Base(a), _M_p(a) { }\n#endif\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n#if A\n Inner(p a) : Base(a), _M_p(a) { }\n#endif\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n Inner(p a) : Base(a), _M_p(a) { }\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n#if A\n Inner(p a)\n : Base(a), _M_p(a) { }\n#else\n Inner(p a)\n : Base(a), _M_p(a) { }\n\n Inner(p a)\n : Base(std::move(a)), _M_p(a) { }\n#endif\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n Inner(p a)\n : Base(a), _M_p(a) { }\n Inner(p a)\n : Base(std::move(a)), _M_p(a) { }\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n Inner(p a)\n : Base(a) { }\n Inner(p a)\n : Base(a) { }\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base\n {\n Inner(p a) : Base(a) { }\n Inner(p a) : Base(a) { }\n int y;\n };\n int size() const;\n};\n",
"class C {\n struct Inner : Base // TODO check __is_final\n {\n#if __cplusplus < 201103L\n\tInner(pointer __dat, const Alloc& __a = Alloc())\n\t: Base(__a), _M_p(__dat) { }\n#else\n\tCONSTEXPR\n\tInner(pointer __dat, const Alloc& __a)\n\t: Base(__a), _M_p(__dat) { }\n\n\tCONSTEXPR\n\tInner(pointer __dat, Alloc&& __a = Alloc())\n\t: Base(std::move(__a)), _M_p(__dat) { }\n#endif\n\n\tpointer _M_p; // The actual data.\n };\n int size() const;\n};\n",
] {
let tree = CppParser::parse(source, ParserConfig::default());
let table = build_scopes(&tree.get_red_root(), &cpp_code_analysis::NoMacroBodies);
let shape = shape(&table);
println!("{source}\n→ {shape}\n");
let size_scope = table.scopes().iter().find(|scope| {
scope
.bindings
.iter()
.any(|binding| binding.name.text() == "size")
});
assert_eq!(
size_scope
.and_then(|scope| scope.name.as_ref())
.map(|name| name.to_string()),
Some("C".to_string()),
"`size` is a member of `C`, whatever the nested class does: {shape}"
);
}
}
#[test]
fn a_lambda_body_is_its_own_scope() {
let source = "int f(int, int);\nvoid g(int);\nvoid h() {\n auto show = [](double a) { if (int inner = 1) { g(inner); } };\n}\n";
let table = scopes(source);
let shape = shape(&table);
println!("{shape}");
let lambda = table
.scopes()
.iter()
.position(|scope| scope.kind == ScopeKind::Lambda)
.expect("a lambda scope");
assert!(
kind_of(&table, cpp_code_analysis::ScopeId(lambda), "a").is_some(),
"the lambda's parameter is bound in its own scope: {shape}"
);
assert!(
shape.contains("inner"),
"and a declaration in its body is a declaration: {shape}"
);
}
#[test]
fn a_lambda_inside_a_statement_is_a_scope_too() {
let source = "void g(int);\nvoid h() {\n auto show = [](double a) { g(1); };\n}\n";
let table = scopes(source);
let shape = shape(&table);
println!("{shape}");
assert!(
table
.scopes()
.iter()
.any(|scope| scope.kind == ScopeKind::Lambda),
"the lambda declares a scope of its own: {shape}"
);
}
#[test]
fn a_call_to_a_qualified_name_in_a_body_binds_nothing() {
let source = "namespace std { }\nvoid f() {\n std::iter_swap(a, b);\n}\n";
let table = scopes(source);
let shape = shape(&table);
println!("{shape}");
assert!(
!shape.contains("iter_swap"),
"the call is not a declaration of anything: {shape}"
);
}
#[test]
fn a_friend_definition_binds_its_parameters() {
let source = "\
struct S {
int x;
friend bool operator==(S const& left, S const& right) { return left.x == right.x; }
};
";
let table = scopes(source);
let shape = shape(&table);
println!("{shape}");
assert!(
shape.contains("left,right"),
"the friend function's parameters are bound in a scope of its own: {shape}"
);
assert!(
shape.contains("Class{x}"),
"the class's own member list is unchanged: {shape}"
);
}
#[test]
fn a_catch_handlers_variable_is_bound() {
let source = "\
void f() {
try { } catch (int const& again) { (void)again; }
}
";
let table = scopes(source);
let shape = shape(&table);
println!("{shape}");
assert!(
shape.contains("again"),
"the handler's variable is bound: {shape}"
);
}
#[test]
fn a_function_pointer_declares_a_variable() {
let table = scopes("void use() {\n int (*fp)(int) = 0;\n (void)fp;\n}\n");
let rendered = shape(&table);
println!("{rendered}");
assert!(rendered.contains("fp"), "`fp` is a binding: {rendered}");
}
#[test]
fn an_out_of_class_definition_is_nested_in_its_class() {
let table = scopes("struct W { int a; void f(); };\n\nvoid W::f() { a = 1; }\n");
let rendered = shape(&table);
println!("{rendered}");
assert!(
rendered.contains("Class{"),
"the class scope is built: {rendered}"
);
assert!(
rendered.contains("}(Fn)"),
"and the definition's function scope is a child of it: {rendered}"
);
}