use cpp_code_analysis::signature::CallSignature;
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 signature_where_marked(source: &str) -> (String, Option<CallSignature>) {
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let signature = {
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
session
.signatures_at(&view, in_the_reading)
.into_iter()
.next()
};
(without_marker, signature)
}
#[test]
fn a_constructor_call_offers_its_parameters() {
let source = "\
class Widget {
public:
Widget(int size, int extra);
};
int main() {
Widget w = Widget(|);
return 0;
}
";
let (_, signature) = signature_where_marked(source);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
assert!(
label.contains("size"),
"the constructor's own parameters, or nothing: {label:?}"
);
}
#[test]
fn a_direct_initialization_offers_the_constructors() {
let source = "\
class Widget {
public:
Widget(int size, int extra);
};
void f() {
Widget w(|);
}
";
let (_, signature) = signature_where_marked(source);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
println!("direct initialization: {label:?}");
assert!(
label.contains("size") && label.contains("extra"),
"the constructor's own parameters: {label:?}"
);
}
#[test]
fn the_overload_the_arguments_select_is_the_first_signature() {
let integer = "\
void print(int value);
void print(const char* text);
void g() {
print(|1);
}
";
let (_, signature) = signature_where_marked(integer);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
assert!(
label.starts_with("print(int"),
"an `int` argument selects the `int` overload: {label:?}"
);
let text = "\
void print(int value);
void print(const char* text);
void g() {
print(|\"x\");
}
";
let (_, signature) = signature_where_marked(text);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
assert!(
label.starts_with("print(const char*"),
"a string literal selects the `const char*` overload: {label:?}"
);
}
#[test]
fn a_template_candidate_is_ranked_as_the_function_the_call_instantiates() {
let source = "\
template <typename T> void take(T* value);
template <typename T> void take(T value);
int g() { int n = 0; int* p = &n; take(|p); return 0; }
";
let (_, signature) = signature_where_marked(source);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
assert!(
label.contains("T*"),
"an `int*` argument selects the `T*` overload: {label:?}"
);
}
#[test]
fn an_ordinary_function_beats_a_template_that_is_equally_good() {
let source = "\
template <typename T> void pick(T value);
void pick(int value);
int g() { pick(|5); return 0; }
";
let (_, signature) = signature_where_marked(source);
let label = signature
.map(|signature| signature.label)
.unwrap_or_default();
assert!(
label.starts_with("pick(int"),
"the ordinary function comes first, not the template: {label:?}"
);
}
fn label_where_marked(source: &str) -> (String, Vec<String>, Option<usize>) {
let (_, signature) = signature_where_marked(source);
let signature = signature.unwrap_or_else(|| panic!("no signature at the cursor in {source:?}"));
let spans: Vec<String> = signature
.parameters
.iter()
.map(|(range, _)| signature.label[range.clone()].to_string())
.collect();
(signature.label, spans, signature.active_parameter)
}
const SCALE: &str = "double scale(int count, double factor);\ndouble f() { return scale(|); }\n";
#[test]
fn a_call_reports_the_declarations_own_signature() {
let (label, spans, active) = label_where_marked(SCALE);
assert_eq!(label, "scale(int count, double factor)");
assert_eq!(
spans,
vec!["int count".to_string(), "double factor".to_string()]
);
assert_eq!(active, Some(0), "the cursor is in the first parameter");
}
#[test]
fn the_active_parameter_follows_the_arguments() {
let cases = [
("scale(|)", 0),
("scale(1|)", 0),
("scale(1,|)", 1),
("scale(1, |)", 1),
("scale(1, 2|)", 1),
("scale(1, 2, |)", 2),
];
for (call, expected) in cases {
let source =
format!("double scale(int count, double factor);\ndouble f() {{ return {call}; }}\n");
let (_, _, active) = label_where_marked(&source);
assert_eq!(active, Some(expected), "in `{call}`");
}
}
#[test]
fn a_declaration_in_an_uncooked_file_still_answers() {
let files = [
(
"/p/math.cppm",
"export module math;\nexport namespace math {\nint add(int lhs, int rhs);\n}\n",
),
(
"/p/a.cpp",
"import math;\nint f() { return math::add(|1, 2); }\n",
),
];
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([
std::path::PathBuf::from("/p/math.cppm"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.want_cooked_reading(std::path::Path::new("/p/a.cpp"));
session.index_everything();
let view = session.view("/p/a.cpp").expect("the caller is held");
assert!(
session.view("/p/math.cppm").is_none(),
"the fixture is only meaningful while the declaration's file has no rendering"
);
let cursor = view
.source
.find("math::add(")
.expect("the fixture writes the call")
+ "math::add(".len();
let signatures = session.signatures_at(
&view,
cpp_code_analysis::file::coordinates::ReadingOffset::new(cursor),
);
assert_eq!(
signatures.len(),
1,
"the fact is enough to write the label: {signatures:?}"
);
assert_eq!(signatures[0].label, "math::add(int lhs, int rhs)");
assert_eq!(
signatures[0].active_parameter,
Some(0),
"the count and the active parameter do not need a tree"
);
assert!(
signatures[0].parameters.is_empty(),
"the spans do need one, and are honestly absent rather than wrong"
);
}
#[test]
fn a_cursor_on_the_callee_has_no_signature() {
let (_, signature) =
signature_where_marked("double scale(int count);\ndouble f() { return sca|le(1); }\n");
assert!(signature.is_none());
}
#[test]
fn a_nested_call_reports_the_innermost_signature() {
let (label, _, _) = label_where_marked(
"int inner(int depth);\nint outer(int width);\nint f() { return outer(inner(|)); }\n",
);
assert_eq!(label, "inner(int depth)");
}
#[test]
fn a_member_call_reports_the_members_signature() {
let (label, spans, _) = label_where_marked(
"struct Widget { int scaled(int factor) const; };\nint f(Widget& w) { return w.scaled(|); }\n",
);
assert_eq!(label, "scaled(int factor)");
assert_eq!(spans, vec!["int factor".to_string()]);
}
#[test]
fn a_callee_in_another_file_reports_its_signature() {
let header = "double scale(int count, double factor);\n";
let source = "#include \"b.h\"\ndouble f() { return scale(|); }\n";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker), ("/p/b.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signature = session
.signatures_at(&view, in_the_reading)
.into_iter()
.next()
.expect("the header declares the callee");
assert_eq!(signature.label, "scale(int count, double factor)");
assert_eq!(signature.declared_in, std::path::Path::new("/p/b.h"));
}
#[test]
fn a_call_to_an_overloaded_function_answers_every_overload() {
let source = "\
int scale(int count);
double scale(double factor, int places);
int f() { return scale(1, |); }
";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signatures = session.signatures_at(&view, in_the_reading);
let labels: Vec<&str> = signatures
.iter()
.map(|found| found.label.as_str())
.collect();
assert_eq!(
labels,
["scale(int count)", "scale(double factor, int places)"],
"both declarations, in the order they are written"
);
assert_eq!(
signatures[0].active_parameter,
Some(1),
"the cursor is past one comma, which is the *second* parameter — and the first overload has no second one"
);
assert_eq!(
signatures[1].active_parameter,
Some(1),
"the count is the call's, and each signature reports it against its own list"
);
}
#[test]
fn a_member_call_answers_every_overload_of_the_member() {
let source = "\
struct Widget {
void scaled(int factor);
void scaled(double factor, int places);
void grow();
};
int f(Widget& w) { return w.scaled(|); }
";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signatures = session.signatures_at(&view, in_the_reading);
let labels: Vec<&str> = signatures
.iter()
.map(|found| found.label.as_str())
.collect();
assert_eq!(
labels,
["scaled(int factor)", "scaled(double factor, int places)"],
"both member overloads, and not the one that is not called"
);
}
#[test]
fn a_member_call_answers_an_inherited_overload() {
let source = "\
struct Base { void scaled(int factor); };
struct Widget : Base { };
int f(Widget& w) { return w.scaled(|); }
";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signatures = session.signatures_at(&view, in_the_reading);
assert_eq!(
signatures
.iter()
.map(|found| found.label.as_str())
.collect::<Vec<_>>(),
["scaled(int factor)"],
"the base declares it, and the derived class inherits it"
);
}
#[test]
fn a_wrapped_parameter_list_is_one_line_and_the_spans_follow_it() {
let (label, spans, active) = label_where_marked(
"int scale(int count,\n double factor);\nint f() { return scale(|); }\n",
);
assert_eq!(
label, "scale(int count, double factor)",
"the declaration's newline and indentation are the file's layout, not the signature"
);
assert_eq!(
spans,
vec!["int count".to_string(), "double factor".to_string()]
);
assert_eq!(active, Some(0));
}
#[test]
fn overloads_in_one_header_are_read_from_it_once() {
let header = "int scale(int count);\ndouble scale(double factor, int places);\n";
let source = "#include \"b.h\"\nint f() { return scale(|); }\n";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker), ("/p/b.h", header)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signatures = session.signatures_at(&view, in_the_reading);
assert_eq!(signatures.len(), 2);
assert!(
signatures
.iter()
.all(|found| found.declared_in == std::path::Path::new("/p/b.h")),
"both are the header's declarations"
);
}
#[test]
fn an_unresolvable_callee_has_no_signature() {
let (_, signature) = signature_where_marked("int f() { return mystery(|); }\n");
assert!(signature.is_none());
}
#[test]
fn a_call_of_a_class_offers_its_constructors() {
let source = "\
struct Widget {
Widget();
Widget(int width, int height);
};
Widget f() { return Widget(|); }
";
let offset = source.find('|').expect("the fixture marks the cursor");
let without_marker = source.replace('|', "");
let session = session_with(&[("/p/a.cpp", &without_marker)]);
let view = session.view("/p/a.cpp").expect("the file is held");
let in_the_reading = view
.reading_offset_of(cpp_code_analysis::file::coordinates::FileOffset::new(
offset,
))
.expect("the cursor is in the rendering");
let signatures = session.signatures_at(&view, in_the_reading);
let labels: Vec<&str> = signatures
.iter()
.map(|found| found.label.as_str())
.collect();
assert_eq!(
labels,
["Widget()", "Widget(int width, int height)"],
"every constructor the class declares, in the order they are written"
);
}
#[test]
fn the_declarations_documentation_travels_with_the_signature() {
let (_, signature) = signature_where_marked(
"/// Scales a count.\n/// @param count the count\nint scale(int count);\nint f() { return scale(|); }\n",
);
let signature = signature.expect("the callee resolves");
let documentation = signature.documentation.expect("the file documents it");
assert!(documentation.get_comment_text().contains("Scales a count."));
assert!(documentation.get_comment_text().contains("@param count"));
}
#[test]
fn an_empty_argument_list_is_answered() {
let (label, _, active) =
label_where_marked("int make(int count);\nint f() { return make(|); }\n");
assert_eq!(label, "make(int count)");
assert_eq!(active, Some(0));
}
#[test]
fn a_call_inside_a_macros_argument_answers_its_own_signature() {
let source = "\
#define PICK(first, second) pick_impl((first), (second))
/// Scales a count.
int scale(int count, double factor);
int pick_impl(int first, int second);
int f() {
return PICK(1, scale(2, |));
}
";
let (label, spans, active) = label_where_marked(source);
assert!(
label.contains("scale") && label.contains("double factor"),
"the call inside the macro argument is the one asked about: {label:?}"
);
assert_eq!(spans.len(), 2, "two parameters: {spans:?}");
assert_eq!(active, Some(1), "and the cursor is on the second");
}