use cpp_code_analysis::{
CompilerConfig, Known, MemoryFiles, OpenDocuments, Session, SessionFiles, WatchFilter,
file::coordinates::FileOffset,
};
const VECTOR: &str = "\
namespace std {
template <class T>
class vector {
public:
void push_back(T value);
T& front();
unsigned long size();
};
}
";
fn session_with(source: &str) -> Session<MemoryFiles> {
let memory = MemoryFiles::new().with_file("/p/a.cpp", 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([std::path::PathBuf::from("/p/a.cpp")]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
session
}
fn members_after(source: &str, marker: &str) -> Vec<String> {
let session = session_with(source);
let view = session.view("/p/a.cpp").expect("the file is cooked");
let at = source.find(marker).expect("the fixture writes the marker") + marker.len();
match session.member_completions(&view, FileOffset::new(at)) {
Known::Yes(found) => found
.members
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect(),
_ => Vec::new(),
}
}
fn type_of_use(source: &str, spelling: &str) -> Option<String> {
let session = session_with(source);
let view = session.view("/p/a.cpp").expect("the file is cooked");
let at = source.rfind(spelling).expect("the fixture names it");
let reading = view.reading_offset_of(FileOffset::new(at))?;
match session.type_at(&view, reading) {
Known::Yes(found) => Some(found.type_of),
_ => None,
}
}
#[test]
fn a_member_list_is_the_instantiated_class() {
let source = format!("{VECTOR}void f() {{\n std::vector<int> z;\n z.\n}}\n");
let offered = members_after(&source, "z.\n");
assert!(
offered.iter().any(|name| name == "push_back"),
"the vector's member is offered: {offered:?}"
);
assert!(
!offered.iter().any(|name| name == "append"),
"and a `basic_string` member is not: {offered:?}"
);
}
#[test]
fn an_alias_to_an_instantiation_offers_that_class_members() {
let source = "\
namespace std {
template <class T>
class basic_string {
public:
void append(T value);
T& back();
};
using string = basic_string<char>;
}
void f() {
std::string s;
s.
}
";
let offered = members_after(source, "s.\n");
assert!(
offered.iter().any(|name| name == "append"),
"the alias's class is `basic_string`, whose members are these: {offered:?}"
);
assert!(
!offered.iter().any(|name| name == "push_back"),
"and not another class's: {offered:?}"
);
}
#[test]
fn a_nested_instantiation_has_its_members_and_its_argument() {
let source = format!(
"{VECTOR}void f() {{\n std::vector<std::vector<int>> grid;\n auto row = grid.front();\n auto &bound = grid.front();\n}}\n"
);
assert_eq!(
type_of_use(&source, "row").as_deref(),
Some("std::vector<int>"),
"`auto row = grid.front();` is the element the outer argument substituted"
);
assert_eq!(
type_of_use(&source, "bound").as_deref(),
Some("std::vector<int>&"),
"and `auto &bound = …` keeps the reference the member returns"
);
}
#[test]
fn an_instantiated_member_list_records_the_arguments() {
let source = format!("{VECTOR}void f() {{\n std::vector<int> z;\n z.push_back(1);\n}}\n");
let session = session_with(&source);
let view = session.view("/p/a.cpp").expect("the file is cooked");
let at = source.find("z.push_back").expect("the fixture calls it");
let reading = view
.reading_offset_of(FileOffset::new(at))
.expect("the offset is in the file");
let Known::Yes(named) = session.type_at(&view, reading) else {
panic!("the receiver's type is known");
};
assert_eq!(named.type_of, "std::vector<int>");
let Known::Yes(list) = session.members_of(&view, &named.type_of) else {
panic!("the instantiated member list answers");
};
let push_back = list
.members
.iter()
.find(|member| member.fact.name == "push_back")
.expect("the member is on the class");
assert_eq!(
push_back.fact.parameter_list(),
Some("(int value)"),
"the class's parameter is substituted with the use's argument"
);
let front = list
.members
.iter()
.find(|member| member.fact.name == "front")
.expect("the member is on the class");
assert_eq!(
front
.fact
.returns
.as_deref()
.map(|written| written.replace(' ', "")),
Some("int&".to_string())
);
}
#[test]
fn an_operator_in_a_template_base_reaches_the_pointee() {
let source = "\
struct S { void c_str(); };
template <class T>
struct Base { T* operator->(); };
template <class T>
struct Ptr : Base<T> {};
void f() {
Ptr<S> p;
p->;
}
";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let mut session = Session::with_config(
"/p",
SessionFiles::new(OpenDocuments::new(), files),
WatchFilter::new("/p"),
CompilerConfig::default().with_standard("c++23"),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let mut rounds = 0;
while session.pending() > 0 && rounds < 200 {
session.advance(16);
rounds += 1;
}
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("a view");
let at = source.find("p->").expect("the fixture") + 3;
let set = session.completions(&view, FileOffset::new(at));
let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
assert!(
labels.contains(&"c_str"),
"`Ptr<S>::operator->` returns `S*`, so the members are `S`'s: {labels:?}"
);
}
#[test]
fn an_operator_two_bases_down_names_a_typedef_of_its_base() {
let source = "\
struct S { void c_str(); };
template <class T, class U>
struct Leaf { using element_type = T; element_type* operator->(); };
template <class T>
struct Mid : Leaf<T, int> {};
template <class T>
struct Ptr : Mid<T> {};
void f() {
Ptr<S> p;
p->;
}
";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let mut session = Session::with_config(
"/p",
SessionFiles::new(OpenDocuments::new(), files),
WatchFilter::new("/p"),
CompilerConfig::default().with_standard("c++23"),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let mut rounds = 0;
while session.pending() > 0 && rounds < 200 {
session.advance(16);
rounds += 1;
}
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("a view");
let at = source.find("p->").expect("the fixture") + 3;
let set = session.completions(&view, FileOffset::new(at));
let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
assert!(
labels.contains(&"c_str"),
"two bases down, `operator->` returns `element_type*` and `element_type` is `S`: {labels:?}"
);
}
#[test]
fn an_alias_target_one_namespace_in_is_found() {
let source = "\
namespace std {
namespace __cxx11 {
struct basic_string {
void push_back();
void clear();
};
}
using string = basic_string;
}
void f() {
std::string text;
text.;
}
";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let mut session = Session::with_config(
"/p",
SessionFiles::new(OpenDocuments::new(), files),
WatchFilter::new("/p"),
CompilerConfig::default().with_standard("c++23"),
);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let mut rounds = 0;
while session.pending() > 0 && rounds < 200 {
session.advance(16);
rounds += 1;
}
let view = session
.view_of_the_file(std::path::Path::new("/p/a.cpp"))
.expect("a view");
let at = source.find("text.").expect("the fixture") + 5;
let set = session.completions(&view, FileOffset::new(at));
let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
assert!(
labels.contains(&"push_back") && labels.contains(&"clear"),
"`std::string` is `std::__cxx11::basic_string`, one namespace in from where its alias says `basic_string`: {labels:?}"
);
}