use cpp_code_analysis::{
CompilerConfig, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
};
fn session_with(files: &[(&str, &str)]) -> Session<MemoryFiles> {
let mut memory = MemoryFiles::new();
for (path, source) in files {
memory = memory.with_file(*path, *source);
}
let providers = SessionFiles::new(OpenDocuments::new(), memory);
let mut session = Session::with_config(
"/p",
providers,
WatchFilter::new("/p"),
CompilerConfig::default(),
);
session.add_project_files(
files
.iter()
.map(|(path, _)| std::path::PathBuf::from(*path)),
);
for (path, _) in files {
session.want_cooked_reading(std::path::Path::new(path));
}
session.index_everything();
session
}
fn parameters_of<'a>(
summary: &'a cpp_code_analysis::FileSummary,
name: &str,
) -> Option<&'a [String]> {
summary
.declarations
.iter()
.find(|fact| fact.name == name)
.map(|fact| fact.parameters.as_slice())
}
#[test]
fn a_template_parameter_is_a_name_and_an_unnamed_one_is_a_slot() {
let session = session_with(&[(
"/p/a.cpp",
"template <class A, typename B, int N>\nstruct S {};\n\
template <typename, typename> class an_unnamed_one;\n\
template <typename, class T> struct partial;\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
assert_eq!(
parameters_of(summary, "S"),
Some(&["A".to_string(), "B".to_string(), "N".to_string()][..]),
"a named parameter answers its name"
);
assert_eq!(
parameters_of(summary, "an_unnamed_one"),
Some(&[String::new(), String::new()][..]),
"two slots, and no keyword pretending to be a name"
);
assert_eq!(
parameters_of(summary, "partial"),
Some(&[String::new(), "T".to_string()][..]),
"the second slot keeps its name **and its position**"
);
}
#[test]
fn an_anonymous_structs_variable_is_not_a_void() {
let session = session_with(&[(
"/p/a.cpp",
"static const struct\n{\n unsigned char left;\n unsigned char right;\n} priority[] = { { 1, 2 } };\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let facts: Vec<(&str, Option<&str>)> = summary
.declarations
.iter()
.filter(|fact| fact.name == "priority" || fact.name == "left" || fact.name == "right")
.map(|fact| (&*fact.name, fact.type_of.as_deref()))
.collect();
println!("facts: {facts:?}");
assert!(
!facts.iter().any(|(_, type_of)| *type_of == Some("void")),
"nothing here is a `void`: {facts:?}"
);
assert!(
facts.contains(&("left", Some("unsigned char"))),
"and the members keep their own types: {facts:?}"
);
}
#[test]
fn a_template_id_keeps_the_spelling_that_was_written() {
let session = session_with(&[(
"/p/a.cpp",
"namespace std {\ntemplate <class K, class V, class C>\nstruct map {};\n}\n\
std::map<int, long, int> table = {};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let table = summary
.declarations
.iter()
.find(|fact| fact.name == "table")
.expect("the variable is a fact");
assert_eq!(
table.type_of.as_deref(),
Some("std::map<int, long, int>"),
"the type the file wrote"
);
}
#[test]
fn an_alias_of_a_qualified_type_is_not_a_void() {
let session = session_with(&[(
"/p/a.cpp",
"template <class T> struct Base { typedef T& reference; };\n\
template <class T> struct V {\n\
typedef typename Base<T>::reference reference;\n\
reference at(int i);\n\
};\n",
)]);
let summary = session
.index()
.summary(std::path::Path::new("/p/a.cpp"))
.expect("indexed");
let alias = summary
.declarations
.iter()
.find(|fact| fact.name == "reference" && fact.scope.as_deref() == Some("V"))
.expect("the alias is a fact");
println!("V::reference type_of {:?}", alias.type_of);
assert!(
alias.type_of.as_deref() != Some("void"),
"an alias's type is never `void`: {:?}",
alias.type_of
);
assert!(
alias
.type_of
.as_deref()
.is_some_and(|written| written.contains("Base<T>::reference")),
"the type the typedef wrote: {:?}",
alias.type_of
);
}
#[test]
fn a_braced_initialisation_of_a_class_template_keeps_its_arguments() {
let session = session_with(&[(
"/p/a.cpp",
"template <typename T, typename U = int>\n\
struct Pair {\n\
T first;\n\
U second;\n\
T sum() const { return first + second; }\n\
};\n\
void f() {\n\
int a = Pair<int, int>{1, 2}.sum();\n\
int b = Pair<int, long>{1, 2}.sum();\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let nodes: Vec<cpp_parser::CppSyntaxNode> = view.root.descendants().collect();
let node_at = |at: usize| -> cpp_parser::CppSyntaxNode {
let found = nodes
.iter()
.find(|node| usize::from(node.text_range().start()) == at)
.expect("a node starts here");
found.clone()
};
let used_at = source.find("Pair<int, int>{1, 2}.sum").expect("the use");
let member = used_at + "Pair<int, int>{1, 2}.".len();
let known = session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(member),
);
assert_eq!(
known.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("int".to_string()),
"the member of an instantiation is read with its arguments substituted"
);
let object = nodes
.iter()
.find(|node| node.text() == "Pair<int, int>{1, 2}")
.expect("the object node")
.clone();
let object_type = session.type_of_the_expression(&view, &object);
assert_eq!(
object_type.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("Pair<int, int>".to_string()),
"the object is the instantiation"
);
let list = source[used_at..].find('{').expect("the list") + used_at;
let bare = node_at(list);
let bare_known = session.type_of_the_expression(&view, &bare);
assert!(
matches!(bare_known, cpp_code_analysis::Known::Unknown(_)),
"a braced list of values has no type this layer can name: {bare_known:?}"
);
}
#[test]
fn a_member_function_records_its_qualifiers_and_its_requires_clause() {
let session = session_with(&[(
"/p/a.cpp",
"struct Foo {\n\
template <typename Fn>\n\
void call(Fn &&fn) {}\n\
template <typename Fn>\n\
void call(Fn &&fn) const {}\n\
};\n\
struct Bar {\n\
template <typename Fn>\n\
void call(Fn &&fn) requires requires { fn(*this); } {}\n\
template <typename Fn>\n\
void call(Fn &&fn) const requires requires { fn(*this); } {}\n\
};\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let is_const = |fact: &cpp_code_analysis::DeclFact| {
fact.modifiers.bits() & cpp_code_analysis::DeclModifiers::CONST.bits() != 0
};
let summary = session.index().summary(path).expect("a summary");
let calls: Vec<&cpp_code_analysis::DeclFact> = summary
.declarations
.iter()
.filter(|fact| fact.name == "call")
.collect();
assert_eq!(calls.len(), 4, "four declarations: {calls:?}");
assert_eq!(calls.iter().filter(|fact| is_const(fact)).count(), 2);
for fact in calls
.iter()
.filter(|fact| fact.scope.as_deref() == Some("Bar"))
{
assert_eq!(
fact.requires_clause.as_deref(),
Some("requires requires { fn(*this); }"),
"the clause as the declaration spells it"
);
}
let cpp_code_analysis::Known::Yes(foo) = session.members_of(&view, "Foo") else {
panic!("members of Foo");
};
assert_eq!(
foo.members
.iter()
.filter(|member| member.fact.name == "call")
.filter(|member| is_const(&member.fact))
.count(),
1,
"one const `call` in Foo's member list"
);
let cpp_code_analysis::Known::Yes(bar) = session.members_of(&view, "Bar") else {
panic!("members of Bar");
};
for member in bar
.members
.iter()
.filter(|member| member.fact.name == "call")
{
assert_eq!(
member.fact.requires_clause.as_deref(),
Some("requires requires { fn(*this); }"),
"the member list's facts carry the clause too"
);
}
}
#[test]
fn a_call_of_a_type_and_an_arrow_through_a_handle() {
let session = session_with(&[(
"/p/a.cpp",
"struct Widget {\n\
int size() const { return 1; }\n\
};\n\
struct Node {\n\
int value() const { return 2; }\n\
};\n\
template <typename T>\n\
struct Handle {\n\
using element_type = T;\n\
T* operator->() const;\n\
};\n\
void f() {\n\
int a = Widget(1).size();\n\
int b = Widget().size();\n\
}\n\
void g(Handle<Node> handle, Node* pointer) {\n\
int c = handle->value();\n\
int d = pointer->value();\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let type_of_member = |needle: &str| {
let at = source.find(needle).expect("the use") + needle.len() - 1;
session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at),
)
};
for needle in [
"Widget(1).size",
"Widget().size",
"handle->value",
"pointer->value",
] {
let known = type_of_member(needle);
assert_eq!(
known.clone().map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("int".to_string()),
"{needle:?} must be an `int`: {known:?}"
);
}
}
#[test]
fn a_type_whose_last_segment_is_the_declared_name_is_not_dropped() {
let session = session_with(&[(
"/p/a.cpp",
"void f() {\n\
std::any any = 1;\n\
std::pair pair{1, 2};\n\
std::string string = \"x\";\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
for (declaration, type_of) in [
("std::any any", "std::any"),
("std::pair pair", "std::pair"),
("std::string string", "std::string"),
] {
let at = source.find(declaration).expect("the declaration")
+ declaration.rfind(' ').unwrap()
+ 1;
let known = session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at),
);
assert_eq!(
known.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes(type_of.to_string()),
"`{declaration}` must be a `{type_of}`, not `void`"
);
}
}
#[test]
fn a_braced_initialisation_of_a_class_template_deduces_its_arguments() {
let session = session_with(&[(
"/p/a.cpp",
"template <typename A, typename B>\n\
struct Pair {\n\
A first;\n\
B second;\n\
Pair(A a, B b) : first(a), second(b) {}\n\
};\n\
void f() {\n\
Pair pair{1, 2.5};\n\
int one = pair.first;\n\
double other = pair.second;\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at_of = |needle: &str| {
let at = source.find(needle).expect("the use");
at + needle.len() - 1
};
let known_at = |needle: &str| {
session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at_of(needle)),
)
};
assert_eq!(
known_at("Pair pair").map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("Pair<int, double>".to_string()),
"the braced initialisation deduces `A = int, B = double`"
);
assert_eq!(
known_at("pair.first").map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("int".to_string()),
"`first` is `A`, and `A` is `int` here"
);
assert_eq!(
known_at("pair.second").map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("double".to_string()),
"`second` is `B`, and `B` is `double` here"
);
}
#[test]
fn a_member_of_a_template_base_is_substituted_with_the_base_arguments() {
let session = session_with(&[
(
"/p/base.h",
"namespace std {\n\
template <typename T>\n\
struct enable_shared_from_this {\n\
T* shared_from_this() { return nullptr; }\n\
};\n\
}\n",
),
(
"/p/a.cpp",
"#include \"base.h\"\n\
struct Node : public std::enable_shared_from_this<Node> {\n\
void twin() { auto p = shared_from_this(); }\n\
};\n",
),
]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let cpp_code_analysis::Known::Yes(listed) = session.members_of(&view, "Node") else {
panic!("`Node` is declared in this file");
};
let member = listed
.members
.iter()
.find(|member| member.fact.name == "shared_from_this")
.expect("the member comes through the base walk");
assert_eq!(
member.fact.returns.as_deref(),
Some("Node *"),
"the base's `T` is the class it was instantiated with: {member:?}"
);
assert_eq!(
member.declared_in, "std::enable_shared_from_this<Node>",
"the tag names the instantiation, not just the base's name"
);
let source = view.source.clone();
let at = source.find("auto p").expect("the fixture") + "auto p".len() - 1;
let known = session.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at),
);
assert_eq!(
known.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("Node*".to_string()),
"the call's type is the substituted return type"
);
}
#[test]
fn a_braced_construction_in_an_expression_deduces_its_arguments() {
let session = session_with(&[(
"/p/a.cpp",
"namespace std {\n\
template <typename A, typename B>\n\
struct pair {\n\
A first;\n\
B second;\n\
pair(A a, B b) : first(a), second(b) {}\n\
};\n\
}\n\
void f() {\n\
auto p = std::pair{1, 2.5};\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("auto p").expect("the fixture") + "auto p".len() - 1;
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("std::pair<int, double>".to_string()),
"the construction's arguments come from its elements"
);
}
#[test]
fn a_structured_binding_over_a_project_class_takes_its_members_types() {
let session = session_with(&[(
"/p/a.cpp",
"template <typename A, typename B>\n\
struct Pair {\n\
A first;\n\
B second;\n\
Pair(A a, B b) : first(a), second(b) {}\n\
};\n\
void f() {\n\
Pair<int, double> p{1, 2.5};\n\
auto [a, b] = p;\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = |needle: &str| source.find(needle).expect("the fixture");
for (needle, skip, expected) in [("[a", 1, "int"), ("b]", 0, "double")] {
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at(needle) + skip)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes(expected.to_string()),
"`{needle}` is the member's type with the container's arguments substituted"
);
}
}
#[test]
fn a_braced_construction_of_a_template_id_is_typed() {
let session = session_with(&[(
"/p/a.cpp",
"template <typename T>\n\
struct B {\n\
T v;\n\
int with(int x) { return x; }\n\
};\n\
void f() {\n\
auto x = B<int>{};\n\
auto y = B<int>{}.with(2);\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("x = ").expect("the fixture");
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("B<int>".to_string()),
"a braced construction of a template-id is its class with the arguments it wrote"
);
}
#[test]
fn a_pointer_subscript_is_its_pointee() {
let session = session_with(&[(
"/p/a.cpp",
"int main() {\n int* a;\n a = new int(42);\n auto x = a[0];\n return 0;\n}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("auto x").expect("the fixture") + "auto x".len() - 1;
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("int".to_string())
);
}
#[test]
fn a_returned_local_states_its_type() {
let session = session_with(&[(
"/p/a.cpp",
"auto make() {\n std::vector<int> result;\n return result;\n}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let _ = &source;
let known = session
.index()
.definition("make", path)
.value()
.unwrap_or_else(|| panic!("`make` is in the index"));
assert_eq!(
known.fact.returns.as_deref(),
Some("std::vector<int>"),
"the local's declaration states the type the function returns"
);
}
#[test]
fn a_qualified_name_is_resolved_through_a_namespace_alias() {
let session = session_with(&[
(
"/p/views.h",
"namespace std {\n\
namespace ranges {\n\
namespace views {\n\
inline constexpr int filter = 1;\n\
}\n\
}\n\
namespace views = ranges::views;\n\
}\n",
),
(
"/p/a.cpp",
"#include \"views.h\"\nint main() { return std::views::filter; }\n",
),
]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("std::views::filter").expect("the fixture") + "std::views::".len();
let known = session.definition(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at),
);
let cpp_code_analysis::Known::Yes(found) = known else {
panic!("the alias names a declaration: {known:?}");
};
assert_eq!(
found.fact.qualified_name(),
"std::ranges::views::filter",
"the answer is the target's declaration, under the scope that actually declares it"
);
let session = session_with(&[
(
"/p/views.h",
"namespace std {\n\
namespace ranges {\n\
namespace views {\n\
struct _Filter { int arity; };\n\
}\n\
}\n\
namespace views = ranges::views;\n\
}\n",
),
(
"/p/a.cpp",
"#include \"views.h\"\nint main() { std::views::_Filter value; return value.arity; }\n",
),
]);
let view = session.view_of_the_file(path).expect("the written text");
let known = session.members_of(&view, "std::views::_Filter");
let cpp_code_analysis::Known::Yes(listed) = known else {
panic!("the alias names the class `std::ranges::views::_Filter`: {known:?}");
};
assert_eq!(
listed
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["arity"],
"the member is looked for in the scope that declares it"
);
}
#[test]
fn a_type_name_through_an_inline_namespace_names_the_type() {
let session = session_with(&[(
"/p/a.cpp",
"namespace std {\n\
template <class E> struct basic_string { };\n\
inline namespace __cxx11 { using string = basic_string<char>; }\n\
}\n\
void f() {\n\
auto tuple = std::tuple<int, std::string>{};\n\
std::string s2{\"three\"};\n\
}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("s2{").expect("the fixture");
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("std::string".to_string()),
"the alias's name is what the file wrote, even though the index stores it under `__cxx11`"
);
}
#[test]
fn a_generic_lambda_called_with_an_int_returns_an_int() {
let session = session_with(&[(
"/p/a.cpp",
"int main() {\n auto twice = [](auto v) { return v * 2; };\n auto x = twice(2.5);\n}\n",
)]);
let path = std::path::Path::new("/p/a.cpp");
let view = session.view_of_the_file(path).expect("the written text");
let source = view.source.clone();
let at = source.find("auto x").expect("the fixture") + "auto x".len() - 1;
assert_eq!(
session
.type_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(at)
)
.map(|found| found.type_of.clone()),
cpp_code_analysis::Known::Yes("double".to_string()),
"`v * 2` with `v` a `double` is a `double`"
);
}
#[test]
fn a_declaration_two_includes_away_is_visible() {
let session = session_with(&[
("/p/a.h", "namespace std { void endl(); }\n"),
("/p/b.h", "#include \"a.h\"\nint in_b;\n"),
(
"/p/c.cpp",
"#include \"b.h\"\nvoid f() { std::endl(); }\nvoid g() { in_b = 1; }\n",
),
]);
let from = std::path::Path::new("/p/c.cpp");
assert!(
matches!(
session.index().definition("in_b", from),
cpp_code_analysis::Known::Yes(_)
),
"the direct include's own declaration is visible"
);
let found = session.index().definition("std::endl", from);
assert!(
matches!(found, cpp_code_analysis::Known::Yes(_)),
"the declaration one hop past the direct include is visible too: {found:?}"
);
}