use super::{IncludeVisibility, ProjectIndex};
use crate::cache::SummaryKey;
use crate::index::summarize;
use crate::symbol::{Known, UnknownReason};
use std::path::Path;
#[test]
fn a_member_named_like_its_class_does_not_hide_the_class() {
let index = index(&[
(
"/p/LSPHandle.h",
"class LSPHandle {\npublic:\n LSPHandle(int server);\n void RefreshDiagnostic();\n};\n",
),
(
"/p/LSPHandle.cpp",
"#include \"LSPHandle.h\"\nLSPHandle::LSPHandle(int server) {\n}\n",
),
]);
let found = index.definition("LSPHandle", Path::new("/p/LSPHandle.cpp"));
let Known::Yes(definition) = found else {
panic!("the class must resolve, not fall to its constructor: {found:?}");
};
assert_eq!(
definition.fact.kind,
crate::DeclKind::Type,
"the name `LSPHandle` resolved to {:?} in {}",
definition.fact.kind,
definition.file.display()
);
}
fn index(files: &[(&str, &str)]) -> ProjectIndex {
let mut index = ProjectIndex::new();
for (path, source) in files {
let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
}
index
}
#[test]
fn a_declaration_in_an_included_header_is_found() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the class in the included header must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert_eq!(definition.fact.name, "Widget");
}
#[test]
fn a_declaration_a_macro_makes_is_found_once_the_file_is_cooked() {
let files = [
(
"/p/decl.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n",
),
("/p/api.h", "#include \"decl.h\"\nDECLARE_HANDLE(HWND);\n"),
];
let mut index = ProjectIndex::new();
let mut definitions = crate::MacroDefinitions::default();
for (path, source) in files {
let mut summary = summarize(Path::new(path), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
let _ = source;
index.insert(summary);
}
let api = Path::new("/p/api.h");
let source = files[1].1;
let before = index.definition("HWND__", api);
assert!(
matches!(before, Known::Unknown(_)),
"the raw reading cannot see a declaration inside a macro body: {before:?}"
);
let text_of = |wanted: &Path| {
files
.iter()
.find(|(path, _)| Path::new(path) == wanted)
.map(|(_, source)| *source)
.unwrap_or("")
};
let unit = crate::TranslationUnit::walk(
index.summary(api).expect("indexed"),
|wanted| {
index
.summary(wanted)
.map(|summary| (summary, text_of(wanted)))
},
&crate::Marked::default(),
&mut definitions,
false,
&crate::WalkCache::new(),
);
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let unit_definitions = unit.definitions();
let view = unit.environment_of(api).expect("the unit reaches api.h");
let macros = crate::preprocess::cooked::FileMacros::new(&view, &unit_definitions, None, true);
let rendered = crate::preprocess::cooked::cook_with(source, &tokens, ¯os).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
let indexed = indexer.index_rendering(api, &rendered, SummaryKey::new(0, 0));
assert_eq!(indexed.mapped.dropped, 0, "every range landed in the file");
index.insert_cooked(api, indexed.into());
let after = index.definition("HWND__", api);
let Known::Yes(definition) = after else {
panic!("the cooked reading declares it: {after:?}");
};
assert_eq!(definition.file, api);
let written = &source[definition.fact.range.start_offset..definition.fact.range.end_offset()];
assert!(
written.contains("DECLARE_HANDLE"),
"the declaration is reported at the invocation: {written:?}"
);
assert!(
matches!(index.definition("HWND", api), Known::Yes(_)),
"and the typedef with it: {:?}",
index.definition("HWND", api)
);
}
#[test]
fn a_declaration_both_readings_found_is_one_candidate() {
let source = "struct Plain { int size; };\n";
let mut index = index(&[("/p/a.h", source)]);
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
let indexed = indexer.index_rendering(Path::new("/p/a.h"), &rendered, SummaryKey::new(0, 0));
assert_eq!(indexed.mapped.dropped, 0);
index.insert_cooked(Path::new("/p/a.h"), indexed.into());
let found = index.definition("Plain", Path::new("/p/a.h"));
assert!(matches!(found, Known::Yes(_)), "one candidate: {found:?}");
}
fn cooked_reading_of(path: &str, source: &str) -> crate::CookedFile {
let (tokens, _) = cpp_parser::lex(source, &cpp_parser::LexerConfig::default());
let rendered = crate::preprocess::cooked::cook(source, &tokens).render();
let provider = crate::MemoryFiles::new();
let config = crate::CompilerConfig::default();
let indexer = crate::FileIndexer::new(&provider, &config);
indexer
.index_rendering(Path::new(path), &rendered, SummaryKey::new(0, 0))
.into()
}
#[test]
fn a_workspace_search_finds_symbols_across_the_project() {
let mut index = index(&[
(
"/p/widget.h",
"namespace ns {\nstruct Widget { int size; };\n}\n",
),
(
"/p/other.cpp",
"void f() {\n int widget_local;\n}\nstruct Widest { int y; };\n",
),
(
"/p/handle.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);\n",
),
]);
let names = |found: &[super::ProjectSymbol]| -> Vec<String> {
found
.iter()
.map(|symbol| symbol.fact.name.to_string())
.collect()
};
let found = index.symbols_matching("wid", 100);
assert_eq!(
names(&found),
vec!["Widest", "Widget"],
"one rank, alphabetical by name: {found:?}"
);
assert_eq!(
found[1].fact.scope.as_deref(),
Some("ns"),
"and the fact says which scope it was written in: {found:?}"
);
let found = index.symbols_matching("widget", 100);
assert_eq!(names(&found), vec!["Widget"], "{found:?}");
let found = index.symbols_matching("idg", 100);
assert_eq!(
names(&found),
vec!["Widget"],
"a substring finds the name it is inside: {found:?}"
);
assert_eq!(
names(&index.symbols_matching("widget_local", 100)),
Vec::<String>::new(),
"a variable inside a body is not something the project has"
);
assert_eq!(
names(&index.symbols_matching("ns::widget", 100)),
vec!["Widget"]
);
assert_eq!(
names(&index.symbols_matching("Widget::si", 100)),
vec!["size"],
"a query with `::` is about a qualified name"
);
assert_eq!(index.symbols_matching("wid", 1).len(), 1);
index.insert_cooked(
Path::new("/p/handle.h"),
cooked_reading_of(
"/p/handle.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; };\nDECLARE_HANDLE(HWND);",
),
);
assert!(
names(&index.symbols_matching("HWND__", 100)).contains(&"HWND__".to_string()),
"the macro-declared type is a symbol a compiler knows"
);
}
#[test]
fn re_indexing_different_text_takes_the_cooked_reading_with_it() {
let source = "struct Plain { int size; };\n";
let mut index = index(&[("/p/a.h", source)]);
index.insert_cooked(Path::new("/p/a.h"), cooked_reading_of("/p/a.h", source));
assert!(index.cooked_declarations(Path::new("/p/a.h")).is_some());
let same = summarize(Path::new("/p/a.h"), source, SummaryKey::new(0, 0));
index.insert(same);
assert!(
index.cooked_declarations(Path::new("/p/a.h")).is_some(),
"an unchanged file keeps its reading"
);
let changed = summarize(
Path::new("/p/a.h"),
"struct Other { int size; };\n",
SummaryKey::new(0, 0),
);
index.insert(changed);
assert!(
index.cooked_reading(Path::new("/p/a.h")).is_none(),
"the reading goes with the text it was built from"
);
}
#[test]
fn a_declaration_in_a_header_the_file_does_not_include_is_not_found() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
("/p/other.cpp", "void g() { }\n"),
]);
let found = index.definition("Widget", Path::new("/p/other.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"a name that is not in scope is not a definition: {found:?}"
);
}
#[test]
fn visibility_follows_a_chain_of_includes() {
let index = index(&[
("/p/deep.h", "struct Deep { int x; };\n"),
("/p/middle.h", "#include \"deep.h\"\n"),
(
"/p/main.cpp",
"#include \"middle.h\"\nvoid f() { Deep d; }\n",
),
]);
let found = index.definition("Deep", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("a transitively included declaration is visible: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/deep.h"));
}
#[test]
fn the_files_own_declaration_wins_over_an_included_one() {
let index = index(&[
("/p/widget.h", "struct Widget { int from_header; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nstruct Widget { int from_this_file; };\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the local declaration wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
}
#[test]
fn a_name_declared_in_two_visible_headers_is_ambiguous_rather_than_guessed() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
),
]);
let found = index.definition("count", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
"two declarations and nothing to choose between them: {found:?}"
);
}
#[test]
fn two_declarations_of_one_name_are_a_list_for_a_consumer_that_shows_one() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#include \"two.h\"\nvoid f() { count = 1; }\n",
),
]);
let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
panic!("two declarations, both of them answers");
};
assert_eq!(found.found.len(), 2);
assert_eq!(found.conditional, 0);
assert_eq!(
found.found[0].file,
Path::new("/p/one.h"),
"the order is imposed (by file, then offset), so a client's peek list cannot reorder itself between \
two identical requests"
);
assert_eq!(found.found[1].file, Path::new("/p/two.h"));
}
#[test]
fn a_bare_name_does_not_reach_a_class_member() {
let index = index(&[
(
"/p/name.h",
"struct Name {\n void printf(int i);\n};\nvoid Name::printf(int i) { }\n",
),
("/p/stdio.h", "void printf(const char* format, ...);\n"),
(
"/p/main.cpp",
"#include \"name.h\"\n#include \"stdio.h\"\nvoid f() { printf(\"x\"); }\n",
),
]);
let found = index.definitions_in_scope("printf", Path::new("/p/main.cpp"));
let Known::Yes(found) = found else {
panic!("the file can name the global `printf`: {found:?}");
};
assert_eq!(
found.found.len(),
1,
"one declaration, the only one an unqualified `printf` can denote: {:?}",
found
.found
.iter()
.map(|definition| definition.file.display().to_string())
.collect::<Vec<_>>()
);
assert_eq!(found.found[0].file, Path::new("/p/stdio.h"));
let Known::Yes(every) = index.definitions("printf", Path::new("/p/main.cpp")) else {
panic!("the index holds the spelling");
};
assert_eq!(
every.found.len(),
2,
"a member access whose object's type is unknown still asks this one"
);
let Known::Yes(qualified) =
index.definitions_in_scope("Name::printf", Path::new("/p/main.cpp"))
else {
panic!("a qualified name is a member's own question");
};
assert_eq!(
qualified.found.len(),
1,
"the member, addressed through its qualifier: {qualified:?}"
);
}
#[test]
fn an_overload_set_is_a_list_and_a_namespace_is_one_entity() {
let index = index(&[
(
"/p/lib.h",
"namespace ns {\n void f(int);\n void f(double);\n}\n",
),
("/p/other.h", "namespace ns {\n void f(char);\n}\n"),
(
"/p/main.cpp",
"#include \"lib.h\"\n#include \"other.h\"\nvoid h() { ns::f(1); }\n",
),
]);
let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/main.cpp")) else {
panic!("an overload set is three declarations, not an ambiguity");
};
assert_eq!(found.found.len(), 3);
let Known::Yes(found) = index.definitions("ns", Path::new("/p/main.cpp")) else {
panic!("the namespace is declared in both headers");
};
assert_eq!(
found.found.len(),
1,
"one namespace, however many files reopen it: a peek list of fifty-eight entries answers a question \
nobody asked"
);
}
#[test]
fn one_function_declared_twice_is_one_entity_and_an_overload_is_two() {
let index = index(&[(
"/p/lib.h",
"namespace ns {\n void f(int);\n void f(int);\n void f(double);\n}\n",
)]);
let Known::Yes(found) = index.definitions("ns::f", Path::new("/p/lib.h")) else {
panic!("three declarations of `ns::f`, and two entities among them");
};
assert_eq!(
found.found.len(),
2,
"the twice-declared `(int)` is one entity; `(double)` is an overload: {found:?}"
);
}
#[test]
fn the_walk_that_carries_the_state_sees_what_asking_each_condition_saw() {
let index = index(&[
("/p/one.h", "#define ONE 1\n"),
("/p/two.h", "int count;\n"),
("/p/three.h", "int three;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\n#include \"three.h\"\n",
),
("/p/four.h", "#include \"two.h\"\n"),
("/p/other.cpp", "#include \"four.h\"\n"),
]);
for root in ["/p/main.cpp", "/p/other.cpp"] {
let walked = index.visible_files(Path::new(root));
let asked = index.visible_files_by_asking_each_condition(Path::new(root));
let mut walked = walked.clone();
let mut asked = asked.clone();
walked.sort_by(|left, right| left.0.cmp(&right.0));
asked.sort_by(|left, right| left.0.cmp(&right.0));
assert_eq!(
walked, asked,
"the two walks disagree about {root}: the completion list is built from this set"
);
}
}
#[test]
fn a_declaration_behind_a_conditional_include_is_counted_not_offered() {
let index = index(&[
("/p/one.h", "int count;\n"),
("/p/two.h", "int count;\n"),
(
"/p/main.cpp",
"#include \"one.h\"\n#ifdef FEATURE\n#include \"two.h\"\n#endif\nvoid f() { count = 1; }\n",
),
]);
let Known::Yes(found) = index.definitions("count", Path::new("/p/main.cpp")) else {
panic!("the unguarded header declares it");
};
assert_eq!(found.found.len(), 1);
assert_eq!(found.found[0].file, Path::new("/p/one.h"));
assert_eq!(
found.conditional, 1,
"and the one that might also be there is counted, so the answer does not claim there is nothing else"
);
}
#[test]
fn an_include_inside_a_condition_that_is_decided_and_false_is_not_visible() {
let index = index(&[
("/p/arm.h", "int arm_intrinsic;\n"),
(
"/p/main.cpp",
"#if 0\n#include \"arm.h\"\n#endif\nvoid f() { }\n",
),
]);
let found = index.definition("arm_intrinsic", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the branch was not taken, so the file is not in this translation unit at all: {found:?}"
);
}
#[test]
fn a_qualified_name_prefers_the_declaration_that_matches_it() {
let index = index(&[
("/p/a.h", "namespace a {\n struct Widget { int x; };\n}\n"),
("/p/b.h", "namespace b {\n struct Widget { int y; };\n}\n"),
(
"/p/main.cpp",
"#include \"a.h\"\n#include \"b.h\"\nvoid f() { a::Widget w; }\n",
),
]);
let found = index.definition("a::Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the qualified name must select one of them: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/a.h"));
assert_eq!(definition.fact.qualified_name(), "a::Widget");
}
#[test]
fn a_guarded_include_makes_the_answer_unknown() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#if defined(USE_WIDGET)\n#include \"widget.h\"\n#endif\nvoid f() { Widget w; }\n",
),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"a conditional include cannot be decided here: {found:?}"
);
}
#[test]
fn an_unconditional_include_beats_a_guarded_one() {
let index = index(&[
("/p/real.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"real.h\"\n#if defined(X)\n#include \"other.h\"\n#endif\nvoid f() { Widget w; }\n",
),
("/p/other.h", "struct Widget { int other; };\n"),
]);
let found = index.definition("Widget", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("the unconditional path wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/real.h"));
}
#[test]
fn a_file_that_includes_nothing_sees_only_itself() {
let index = index(&[("/p/a.cpp", "int count;\n"), ("/p/b.cpp", "int count;\n")]);
for path in ["/p/a.cpp", "/p/b.cpp"] {
let found = index.definition("count", Path::new(path));
let Known::Yes(definition) = found else {
panic!("{path} must find its own count: {found:?}");
};
assert_eq!(definition.file, Path::new(path));
}
}
#[test]
fn a_cycle_of_includes_does_not_hang_the_visibility_walk() {
let index = index(&[
("/p/a.h", "#include \"b.h\"\nstruct A { int x; };\n"),
("/p/b.h", "#include \"a.h\"\nstruct B { int y; };\n"),
("/p/main.cpp", "#include \"a.h\"\nvoid f() { B b; }\n"),
]);
let found = index.definition("B", Path::new("/p/main.cpp"));
let Known::Yes(definition) = found else {
panic!("a cycle must not stop a name being found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/b.h"));
}
#[test]
fn the_reverse_edges_are_derived_from_the_summaries() {
let index = index(&[
("/p/header.h", "int x;\n"),
("/p/one.cpp", "#include \"header.h\"\n"),
("/p/two.cpp", "#include \"header.h\"\n"),
]);
let mut includers = index.includers_of(Path::new("/p/header.h"));
includers.sort();
assert_eq!(
includers,
[Path::new("/p/one.cpp"), Path::new("/p/two.cpp")],
"an edit to the header invalidates exactly these"
);
}
#[test]
fn reindexing_a_file_removes_the_edges_its_old_text_had() {
let mut index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
),
]);
assert!(index.includers_of(Path::new("/p/widget.h")).len() == 1);
let mut edited = summarize(
Path::new("/p/main.cpp"),
"void f() { }\n",
SummaryKey::new(1, 0),
);
for include in &mut edited.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(edited);
assert!(
index.includers_of(Path::new("/p/widget.h")).is_empty(),
"the edge must go with the line that wrote it"
);
assert!(
matches!(
index.definition("Widget", Path::new("/p/main.cpp")),
Known::Unknown(_)
),
"and the name is no longer visible there"
);
}
#[test]
fn visibility_is_reported_so_a_caller_can_downgrade() {
let index = index(&[
("/p/widget.h", "struct Widget { int size; };\n"),
("/p/main.cpp", "#include \"widget.h\"\n"),
]);
let found = index.files_declaring("Widget", Path::new("/p/main.cpp"));
assert_eq!(found.len(), 1);
assert_eq!(found[0].visibility, IncludeVisibility::Unconditional);
}
fn at(source: &str, needle: &str) -> usize {
source
.rfind(needle)
.unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
}
fn analysed(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
let (index, tree) = analysed_while_typing(files, from, source);
assert!(
tree.get_errors().is_empty(),
"the fixture must parse cleanly: {source:?}"
);
(index, tree)
}
fn analysed_while_typing(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> (ProjectIndex, cpp_parser::CppSyntaxTree) {
let mut index = index(files);
let tree = cpp_parser::CppParser::parse(source, cpp_parser::ParserConfig::default());
let mut summary = summarize(Path::new(from), source, SummaryKey::new(0, 0));
for include in &mut summary.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(summary);
(index, tree)
}
#[test]
fn a_local_declaration_is_answered_without_looking_in_the_index() {
let source = "#include \"widget.h\"\nvoid f() {\n int count = 0;\n count = 1;\n}\n";
let (index, tree) = analysed(&[("/p/widget.h", "int count;\n")], "/p/main.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "count = 1;"),
);
let Known::Yes(definition) = found else {
panic!("the local must win: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
assert!(
definition.fact.range.start_offset > at(source, "void f"),
"the jump goes to the local, not to the header"
);
}
#[test]
fn another_files_local_is_never_the_answer() {
let source = "#include \"widget.h\"\nvoid f() {\n helper();\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"void g() {\n int helper = 0;\n}\nstruct Widget { int size; };\n",
)],
"/p/main.cpp",
source,
);
let header = index.summary(Path::new("/p/widget.h")).expect("indexed");
let helper = header
.declarations
.iter()
.find(|fact| fact.name == "helper")
.expect("the header declares `helper`");
assert!(helper.local, "declared inside `g`'s body");
assert_eq!(helper.scope, None, "…which is why the scope cannot say so");
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "helper();"),
);
assert!(
matches!(
found,
Known::Unknown(UnknownReason::NotDeclaredHere(_)) | Known::No
),
"the header's local is not a declaration of the name this file writes: {found:?}"
);
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"void g() {\n int helper = 0;\n}\nstruct Widget { int size; };\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("`Widget` is at file scope in the header: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert!(!definition.fact.local);
}
#[test]
fn a_call_resolves_through_the_return_type_of_a_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.inner().size = 1;\n}\n";
let (index, tree) = analysed(
&[(
"/p/widget.h",
"struct Inner {\n int size;\n};\nstruct Widget {\n Inner inner();\n};\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(definition) = found else {
panic!("`w.inner()` returns an `Inner`, which declares `size`: {found:?}");
};
assert_eq!(definition.fact.name, "size");
assert_eq!(
definition.file,
Path::new("/p/widget.h"),
"the member is in the header, like everything else on this chain"
);
}
#[test]
fn a_name_only_a_header_declares_is_found_through_the_index() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "struct Widget { int size; };\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the header's class must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/widget.h"));
assert_eq!(definition.fact.name, "Widget");
}
#[test]
fn a_qualified_name_resolves_into_an_included_header() {
let source = "#include \"a.h\"\nvoid f() {\n a::Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/a.h", "namespace a {\n struct Widget { int x; };\n}\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the header's `a::Widget` must be found: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/a.h"));
assert_eq!(definition.fact.qualified_name(), "a::Widget");
}
#[test]
fn a_qualified_name_is_not_answered_by_a_same_named_declaration_elsewhere() {
let source = "#include \"b.h\"\nvoid f() {\n a::Widget w;\n}\n";
let (index, tree) = analysed(
&[("/p/b.h", "namespace b {\n struct Widget { int y; };\n}\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`a::Widget` is not declared anywhere this file can see: {found:?}"
);
}
#[test]
fn a_global_spelling_does_not_match_a_namespaced_declaration() {
let source = "#include \"both.h\"\nvoid f() {\n ::Widget w;\n}\n";
let (index, tree) = analysed(
&[(
"/p/both.h",
"struct Widget { int global; };\nnamespace ns {\n struct Widget { int nested; };\n}\n",
)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "Widget w;"),
);
let Known::Yes(definition) = found else {
panic!("the global `Widget` is the one asked for: {found:?}");
};
assert_eq!(definition.fact.scope, None);
assert_eq!(definition.fact.name, "Widget");
}
fn member_of(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::ProjectDefinition> {
let (index, tree) = analysed(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new(from),
at(source, needle),
)
}
#[test]
fn a_member_of_an_alias_resolves_through_it() {
let source = "struct Widget {\n int size;\n};\nusing Alias = Widget;\n\
void f() {\n Alias w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Alias` names `Widget`, so `size` is `Widget::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn a_member_of_the_standard_library_string_resolves_into_basic_string() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n \
int find(int);\n };\n typedef basic_string<char> string;\n}\n\
void f() {\n std::string s;\n s.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`std::string::size` is `std::basic_string::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(
member.fact.scope.as_deref(),
Some("std::basic_string"),
"the member is declared in the class the alias points at, and its scope says so"
);
}
#[test]
fn an_alias_written_with_using_resolves_the_same_way() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n };\n \
using string = basic_string<char>;\n}\n\
void f() {\n std::string s;\n s.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the `using` form is the same declaration shape: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("std::basic_string"));
}
#[test]
fn an_alias_target_written_with_a_qualifier_is_taken_as_it_stands() {
let source = "namespace other {\n struct Thing {\n int size;\n };\n}\n\
namespace ns {\n using Alias = other::Thing;\n}\n\
void f() {\n ns::Alias t;\n t.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the qualified target is the class: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("other::Thing"));
}
#[test]
fn an_alias_to_an_alias_is_followed_to_the_class() {
let source = "struct Widget {\n int size;\n};\nusing B = Widget;\nusing A = B;\n\
void f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("two aliases deep is still a class at the end: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn a_cycle_of_aliases_terminates_and_says_nothing_was_declared() {
let source = "using A = B;\nusing B = A;\nvoid f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(_)),
"a cycle of aliases names no class: {found:?}"
);
}
#[test]
fn an_alias_to_itself_terminates() {
let source = "using A = A;\nvoid f() {\n A w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(_)),
"`using A = A;` names no class: {found:?}"
);
}
#[test]
fn an_alias_whose_target_is_not_indexed_reports_the_target() {
let source = "using Alias = Widget;\nvoid f() {\n Alias w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Unknown(UnknownReason::NotDeclaredHere(written)) = found else {
panic!("the target is what was looked for: {found:?}");
};
assert_eq!(&*written, "Widget::size");
}
#[test]
fn an_alias_to_a_non_class_is_not_a_member_lookup() {
let source = "typedef int MyInt;\nvoid f() {\n MyInt x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`int` declares no members: {found:?}"
);
}
#[test]
fn a_function_pointer_typedef_records_the_whole_type() {
let source = "typedef void (*F)(int);\nvoid f() {\n F callback;\n callback();\n}\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let Known::Yes(fact) = index.definition("F", Path::new("/p/a.cpp")) else {
panic!("the alias is a fact")
};
assert_eq!(
fact.fact.type_of.as_deref(),
Some("void (*)(int)"),
"specifiers plus declarator minus the name"
);
let plain = "typedef basic_string<char> String;\n";
let (index, tree) = analysed(&[], "/p/b.cpp", plain);
let Known::Yes(fact) = index.definition("String", Path::new("/p/b.cpp")) else {
panic!("the alias is a fact")
};
assert_eq!(fact.fact.type_of.as_deref(), Some("basic_string<char>"));
let _ = (root, tree);
}
#[test]
fn a_member_list_of_an_alias_is_the_member_list_of_its_target() {
let source = "namespace std {\n template<typename T> struct basic_string {\n int size;\n \
int find(int);\n };\n typedef basic_string<char> string;\n}\n";
let list = members_of_class(&[], "/p/a.cpp", source, "std::string");
let Known::Yes(list) = list else {
panic!("the alias's target is a class with members: {list:?}");
};
assert!(
names(&list).contains(&"size") && names(&list).contains(&"find"),
"the members are `basic_string`'s: {:?}",
names(&list)
);
}
#[test]
fn a_member_access_resolves_through_the_objects_type() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Widget::size` is declared in this file: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
assert!(
member.fact.range.start_offset < at(source, "void f"),
"the jump goes to the member's declaration, not to the use"
);
}
#[test]
fn a_member_of_another_class_with_the_same_name_is_not_the_answer() {
let source = "struct Other {\n int size;\n};\nstruct Widget {\n int size;\n};\n\
void f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Widget::size` is the one the object names: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
assert!(
member.fact.range.start_offset > at(source, "struct Widget"),
"the jump lands in `Widget`, not in `Other`"
);
}
#[test]
fn a_member_access_reads_a_pointer_the_same_way() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n p->size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the pointee's member is the answer: {found:?}");
};
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_access_reaches_a_class_in_an_included_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "struct Widget {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(member) = found else {
panic!("the member declared in the header is the answer: {found:?}");
};
assert_eq!(member.file, Path::new("/p/widget.h"));
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_access_through_a_qualified_type_resolves() {
let source = "namespace ns {\n struct Widget {\n int size;\n };\n}\n\
void f() {\n ns::Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`ns::Widget::size` is in this file: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("ns::Widget"));
}
#[test]
fn a_member_of_a_class_that_does_not_have_it_is_not_declared_here() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.nope = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the class is known and the member is not in it: {found:?}"
);
}
#[test]
fn a_member_access_on_a_call_is_the_callees_return_type() {
let source = "struct Widget {\n int size;\n};\nWidget make();\n\
void f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(definition) = found else {
panic!("`make()` returns a `Widget`, so `size` is its member: {found:?}");
};
assert_eq!(definition.fact.name, "size");
assert_eq!(definition.fact.type_of.as_deref(), Some("int"));
let constructed = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget().size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(constructed, Known::Yes(_)),
"a temporary of a known class has the class's members: {constructed:?}"
);
}
#[test]
fn a_member_access_through_a_dereference_resolves() {
let through_a_call = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nWidget* make();\nvoid f() {\n (*make()).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_call else {
panic!("`make()` returns a `Widget*`, so `(*make())` is a `Widget`: {through_a_call:?}");
};
assert_eq!(found.fact.name, "size");
let through_a_pointer = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n (*p).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_pointer else {
panic!("`p` points at a `Widget`: {through_a_pointer:?}");
};
assert_eq!(found.fact.name, "size");
let through_a_parameter = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f(Widget* p) {\n (*p).size = 1;\n}\n",
"size = 1;",
);
let Known::Yes(found) = through_a_parameter else {
panic!("`p` points at a `Widget`: {through_a_parameter:?}");
};
assert_eq!(found.fact.name, "size");
let through_a_reference = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget& r = w;\n (&r)->size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(through_a_reference, Known::Yes(_)),
"`&r` is a `Widget*`: {through_a_reference:?}"
);
}
#[test]
fn a_dereference_of_something_that_is_not_a_pointer_is_an_unknown_type() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n int* q;\n (*q).size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"an `int` is not a class, and saying so beats inventing one: {found:?}"
);
let vector = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\ntemplate<typename T> struct Box { T first; };\n\
void f() {\n Box<Widget> box;\n box[0].size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(vector, Known::Unknown(UnknownReason::UnknownType(_))),
"a class subscript needs the template instantiated: {vector:?}"
);
}
#[test]
fn a_member_access_through_a_subscript_of_an_array_resolves() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget arr[4];\n arr[0].size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(found) = found else {
panic!("`arr[0]` is a `Widget`: {found:?}");
};
assert_eq!(found.fact.name, "size");
let two_dimensional = member_of(
&[],
"/p/a.cpp",
"struct Widget {\n int size;\n};\nvoid f() {\n Widget grid[2][3];\n grid[i][j].size = 1;\n}\n",
"size = 1;",
);
assert!(
matches!(two_dimensional, Known::Yes(_)),
"`grid[i][j]` is a `Widget`: {two_dimensional:?}"
);
}
#[test]
fn a_call_of_something_with_no_return_type_is_an_unknown_type() {
let source = "struct Widget {\n int size;\n};\nauto make() { return Widget{}; }\n\
void f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(found) = found else {
panic!("`return Widget{{}}` states the type it returns: {found:?}");
};
assert_eq!(found.fact.name, "size");
let called = "struct Widget {\n int size;\n};\nWidget source();\n\
auto make() { return source(); }\nvoid f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", called, "size = 1;");
assert!(
matches!(found, Known::Yes(_)),
"`source()` is a `Widget`, so `make().size` names the member: {found:?}"
);
let bodiless =
"struct Widget {\n int size;\n};\nauto make();\nvoid f() {\n make().size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", bodiless, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"the file does not state what this call has: {found:?}"
);
}
#[test]
fn a_member_access_on_an_unknown_object_is_an_unknown_type() {
let source = "void f() {\n widget.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"nothing says what `widget` is: {found:?}"
);
}
#[test]
fn a_cursor_that_is_not_on_a_member_access_has_nothing_to_look_up() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "= 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is not on a member name: {found:?}"
);
}
#[test]
fn a_nested_member_access_follows_the_types_down() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n};\n\
void f() {\n Outer a;\n a.b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Inner::size` is what `a.b.size` names: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
assert!(
member.fact.range.start_offset < at(source, "struct Outer"),
"the jump lands in `Inner`, not in `Outer`"
);
}
#[test]
fn a_nested_member_access_that_disagrees_with_the_outer_class_is_not_answered_by_it() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n int size;\n};\n\
void f() {\n Outer a;\n a.b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the member of `a.b`'s type is the answer: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Inner"));
}
#[test]
fn this_resolves_to_the_enclosing_class() {
let source = "struct Widget {\n int size;\n void grow() {\n this->size = 1;\n }\n};\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`this->size` is `Widget::size`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Widget"));
}
#[test]
fn this_resolves_to_the_nearest_class_when_classes_are_nested() {
let source = "struct Outer {\n int size;\n struct Inner {\n int size;\n void f() {\n \
this->size = 1;\n }\n };\n};\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`this` inside `Inner` is `Inner`: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Outer::Inner"));
}
#[test]
fn a_nested_access_propagates_why_the_inner_one_failed() {
let source = "struct Inner {\n int size;\n};\nstruct Outer {\n Inner b;\n};\n\
void f() {\n Outer a;\n a.nope.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"there is no `nope` to type, and that is the answer worth keeping: {found:?}"
);
}
#[test]
fn a_member_inherited_from_a_base_class_resolves() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int other;\n};\n\
void f() {\n Derived d;\n d.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("`Base::size` is inherited by `Derived`: {found:?}");
};
assert_eq!(member.fact.name, "size");
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
assert!(
member.fact.range.start_offset < at(source, "struct Derived"),
"the jump lands in the base, not in the derived class"
);
}
#[test]
fn a_member_of_the_class_itself_hides_one_in_a_base() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int size;\n};\n\
void f() {\n Derived d;\n d.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the class's own member hides the one it inherits: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Derived"));
}
#[test]
fn a_member_inherited_through_another_base_resolves() {
let source = "struct Base {\n int size;\n};\nstruct Middle : public Base {\n int m;\n};\n\
struct Derived : public Middle {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("a member two bases down is still inherited: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
}
#[test]
fn a_member_declared_in_two_bases_at_once_is_ambiguous_rather_than_picked() {
let source = "struct Left {\n int size;\n};\nstruct Right {\n int size;\n};\n\
struct Both : public Left, public Right {\n int own;\n};\n\
void f() {\n Both b;\n b.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::Ambiguous(_))),
"two bases declare it and nothing chooses: {found:?}"
);
}
#[test]
fn a_member_inherited_across_a_header_resolves() {
let source = "#include \"base.h\"\nstruct Derived : public Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/base.h", "struct Base {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "size = 1;"),
);
let Known::Yes(member) = found else {
panic!("the inherited member is declared in the header: {found:?}");
};
assert_eq!(member.file, Path::new("/p/base.h"));
assert_eq!(member.fact.name, "size");
}
#[test]
fn a_member_nobody_declares_is_still_not_declared() {
let source = "struct Base {\n int size;\n};\nstruct Derived : public Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.nope = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "nope = 1;");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"neither the class nor its base declares it: {found:?}"
);
}
#[test]
fn a_base_list_is_read_without_its_access_keywords() {
let source = "struct Base {\n int size;\n};\nstruct Derived : private virtual Base {\n int d;\n};\n\
void f() {\n Derived x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("the access and `virtual` are not part of the base's name: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("Base"));
}
#[test]
fn a_base_that_inherits_from_itself_terminates() {
let source = "struct A : public B {\n int a;\n};\nstruct B : public A {\n int size;\n};\n\
void f() {\n A x;\n x.size = 1;\n}\n";
let found = member_of(&[], "/p/a.cpp", source, "size = 1;");
let Known::Yes(member) = found else {
panic!("a cycle must not stop the member being found: {found:?}");
};
assert_eq!(member.fact.scope.as_deref(), Some("B"));
}
#[test]
fn a_local_declaration_still_wins_when_the_header_also_has_the_name() {
let source = "#include \"widget.h\"\nint count = 0;\nvoid f() {\n count = 1;\n}\n";
let (index, tree) = analysed(
&[("/p/widget.h", "int count = 7;\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::definition_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
at(source, "count = 1;"),
);
let Known::Yes(definition) = found else {
panic!("the file's own declaration wins: {found:?}");
};
assert_eq!(definition.file, Path::new("/p/main.cpp"));
}
fn members_of_class(
files: &[(&str, &str)],
from: &str,
source: &str,
class: &str,
) -> Known<super::MemberList> {
let (index, tree) = analysed(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::members_of(&index, &scopes, &root, Path::new(from), class)
}
fn names(list: &super::MemberList) -> Vec<&str> {
list.members
.iter()
.map(|member| member.fact.name.as_str())
.collect()
}
#[test]
fn an_anonymous_unions_members_belong_to_the_struct() {
let source = "struct point { int x; int y; };\n\
struct line {\n\
struct point from;\n\
union { long integer; double real; };\n\
char colour;\n\
};\n";
let found = members_of_class(&[], "/p/a.c", source, "line");
let Known::Yes(list) = found else {
panic!("`line` is declared here: {found:?}");
};
assert!(
names(&list).contains(&"integer"),
"the union is anonymous, so its members are `line`'s: {:?}",
names(&list)
);
assert!(
names(&list).contains(&"real"),
"and so is `real`: {:?}",
names(&list)
);
}
#[test]
fn a_class_declared_more_than_once_still_reports_the_bases_it_could_not_read() {
let source = "template <class E>\nstruct Stream : Base {\n int read;\n};\ntemplate struct Stream<char>;\n";
let found = members_of_class(
&[("/p/base.h", "struct Base { int eof; };\n")],
"/p/a.cpp",
source,
"Stream",
);
let Known::Yes(list) = found else {
panic!("`Stream` is declared here: {found:?}");
};
assert_eq!(names(&list), ["read"], "its own member is listed");
assert_eq!(
list.unlisted
.iter()
.map(|base| base.spelling.as_str())
.collect::<Vec<_>>(),
["Base"],
"and the base the walk could not follow is named, so the list does not claim completeness"
);
}
#[test]
fn a_class_lists_the_members_written_in_it() {
let source = "struct Widget {\n void grow();\n int size;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(list) = found else {
panic!("`Widget` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["grow", "size"]);
assert!(
list.unlisted.is_empty(),
"a class with no bases has nothing left unread: {:?}",
list.unlisted
);
let size = &list.members[1];
assert_eq!(size.declared_in, "Widget");
assert_eq!(size.depth, 0, "its own member, not an inherited one");
assert!(!size.ambiguous);
assert_eq!(size.file, Path::new("/p/a.cpp"));
assert_eq!(
size.fact.type_of.as_deref(),
Some("int"),
"the type a completion shows beside the name"
);
assert_eq!(
list.own().count(),
2,
"every member here is the class's own"
);
}
#[test]
fn a_derived_class_lists_its_own_members_before_the_ones_it_inherits() {
let source = "struct Base {\n int inherited_count;\n};\n\
struct Derived : public Base {\n int own_count;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(
names(&list),
["own_count", "inherited_count"],
"the class's own members come first, and the inherited one is last"
);
assert_eq!(list.members[0].declared_in, "Derived");
assert_eq!(list.members[0].depth, 0);
assert_eq!(
list.members[1].declared_in, "Base",
"the member is the base's, not the derived class's"
);
assert_eq!(list.members[1].depth, 1);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("int"),
"and it carries its own declaration's type"
);
assert_eq!(list.at_depth(1).count(), 1);
}
#[test]
fn a_member_the_class_redeclares_hides_the_one_in_its_base() {
let source = "struct Base {\n int size;\n};\n\
struct Derived : public Base {\n double size;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(
names(&list),
["size"],
"one `size`, and it is the derived class's"
);
assert_eq!(list.members[0].declared_in, "Derived");
assert_eq!(list.members[0].fact.type_of.as_deref(), Some("double"));
}
#[test]
fn a_name_two_bases_declare_is_listed_twice_and_marked_ambiguous() {
let source = "struct Left {\n int value;\n};\nstruct Right {\n int value;\n};\n\
struct Both : public Left, public Right {\n int own;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Both");
let Known::Yes(list) = found else {
panic!("`Both` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["own", "value", "value"]);
let values: Vec<&super::ProjectMember> = list
.members
.iter()
.filter(|member| member.fact.name == "value")
.collect();
assert_eq!(values.len(), 2, "both declarations survive into the list");
assert!(
values.iter().all(|member| member.ambiguous),
"both are contested: {values:?}"
);
let mut declaring: Vec<&str> = values
.iter()
.map(|member| member.declared_in.as_str())
.collect();
declaring.sort_unstable();
assert_eq!(declaring, ["Left", "Right"]);
assert!(
!list.members[0].ambiguous,
"`own` is declared once, in one class"
);
}
#[test]
fn a_destructor_hides_nothing_in_a_base_because_its_spelling_is_its_own() {
let source = "struct Base {\n virtual ~Base();\n int size;\n};\n\
struct Derived : public Base {\n virtual ~Derived();\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
let destructors: Vec<&super::ProjectMember> = list
.members
.iter()
.filter(|member| member.fact.name.starts_with('~'))
.collect();
assert_eq!(
destructors.len(),
2,
"both destructors are declarations that exist, and dropping one would be a silent omission: {:?}",
names(&list)
);
let mut classes: Vec<&str> = destructors
.iter()
.map(|member| member.declared_in.as_str())
.collect();
classes.sort_unstable();
assert_eq!(classes, ["Base", "Derived"]);
let mut spellings: Vec<&str> = destructors
.iter()
.map(|member| member.fact.name.as_str())
.collect();
spellings.sort_unstable();
assert_eq!(
spellings,
["~Base", "~Derived"],
"a destructor's name is the class it destroys, so the two are not one name"
);
assert!(
destructors.iter().all(|member| !member.ambiguous),
"two different spellings are not one contested name: {destructors:?}"
);
assert!(
list.members
.iter()
.any(|member| member.fact.name == "size" && member.declared_in == "Base"),
"and the named members still cross the inheritance boundary: {:?}",
names(&list)
);
}
#[test]
fn a_destructor_without_a_specifier_is_a_member() {
let source = "struct Derived {\n ~Derived();\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("the class must be found by its own name: {found:?}");
};
assert_eq!(names(&list), ["d", "~Derived"]);
}
#[test]
fn overloads_in_one_class_are_not_ambiguous() {
let source = "struct Widget {\n void f();\n void f(int);\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(list) = found else {
panic!("`Widget` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["f", "f"], "both overloads are listed");
assert!(
list.members.iter().all(|member| !member.ambiguous),
"one class declaring a name twice is an overload set, not an ambiguity: {:?}",
list.members
);
}
#[test]
fn a_cycle_of_bases_terminates_and_each_class_contributes_once() {
let source =
"struct A : public B {\n int a_member;\n};\nstruct B : public A {\n int b_member;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "A");
let Known::Yes(list) = found else {
panic!("`A` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["a_member", "b_member"]);
assert_eq!(list.members[0].depth, 0);
assert_eq!(
list.members[1].depth, 1,
"`A` is reached again as `B`'s base and is not listed a second time"
);
}
#[test]
fn a_template_class_lists_the_members_it_was_written_with() {
let source = "template <typename T>\nstruct Holder {\n T value;\n int count;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Holder");
let Known::Yes(list) = found else {
panic!("`Holder` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["count", "value"]);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("T"),
"the parameter as written, not an instantiated type"
);
assert!(
!list.members.iter().any(|member| member.fact.name == "T"),
"the template parameter is declared in the parameter list, not in the class: {:?}",
names(&list)
);
}
#[test]
fn a_type_nothing_declares_has_no_member_list_rather_than_an_empty_one() {
let source = "void f() { }\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Nowhere");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`Nowhere` is not a type this analysis has seen: {found:?}"
);
}
#[test]
fn a_class_that_is_empty_has_an_empty_member_list() {
let source = "struct Empty { };\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Empty");
let Known::Yes(list) = found else {
panic!("`Empty` is declared in this file and has no members: {found:?}");
};
assert!(list.members.is_empty());
}
#[test]
fn a_member_declared_in_a_nested_class_is_not_a_member_of_the_outer_one() {
let source = "struct Outer {\n struct Inner {\n int x;\n };\n int y;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Outer");
let Known::Yes(list) = found else {
panic!("`Outer` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["Inner", "y"]);
assert_eq!(list.members[0].fact.qualified_name(), "Outer::Inner");
}
#[test]
fn a_member_list_crosses_a_header_and_keeps_the_base_tagged() {
let source = "#include \"base.h\"\nstruct Derived : public Base {\n int d;\n};\n";
let (index, tree) = analysed(
&[("/p/base.h", "struct Base {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::members_of(&index, &scopes, &root, Path::new("/p/main.cpp"), "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in the buffer: {found:?}");
};
assert_eq!(names(&list), ["d", "size"]);
assert_eq!(list.members[1].file, Path::new("/p/base.h"));
assert_eq!(list.members[1].declared_in, "Base");
}
#[test]
fn a_base_that_resolves_to_a_template_is_listed_without_instantiating_it() {
let source = "template <typename T>\nstruct Base {\n T size;\n};\n\
struct Derived : public Base<int> {\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` is declared in this file: {found:?}");
};
assert_eq!(names(&list), ["d", "size"]);
assert_eq!(
list.members[1].fact.type_of.as_deref(),
Some("int"),
"the base's parameter is substituted: {list:?}"
);
assert_eq!(list.members[1].declared_in, "Base<int>");
}
#[test]
fn a_base_nothing_declares_is_reported_as_a_gap_rather_than_dropped() {
let source = "#include \"missing.h\"\nstruct Derived : public Base {\n int d;\n};\n";
let found = members_of_class(&[], "/p/a.cpp", source, "Derived");
let Known::Yes(list) = found else {
panic!("`Derived` itself is in the buffer: {found:?}");
};
assert_eq!(names(&list), ["d"], "what could be listed is listed");
assert_eq!(list.unlisted.len(), 1, "and what could not is named");
assert_eq!(list.unlisted[0].spelling, "Base");
assert!(
matches!(list.unlisted[0].reason, UnknownReason::NotDeclaredHere(_)),
"the reason has to say that the base is not here, not that the list ended: {:?}",
list.unlisted[0].reason
);
}
#[test]
fn a_base_of_a_class_in_a_namespace_is_looked_up_in_that_namespace() {
let lib = "namespace std {\nstruct _Tree {\n void find();\n};\nstruct map : _Tree {\n int count;\n};\n}\n";
let source = "#include \"lib.h\"\nstruct _Tree {\n void wrong();\n};\nvoid f() {\n std::map m;\n m.find();\n m.wrong();\n}\n";
let files: &[(&str, &str)] = &[("/p/lib.h", lib)];
let Known::Yes(list) = members_of_class(files, "/p/a.cpp", source, "std::map") else {
panic!("`std::map` is in the indexed header");
};
assert_eq!(
names(&list),
["count", "find"],
"`find` comes from the base, and `wrong` is not a member of anything this class inherits"
);
assert!(
list.unlisted.is_empty(),
"the base was found, so nothing here is a gap: {:?}",
list.unlisted
);
assert_eq!(
list.members[1].declared_in, "std::_Tree",
"the answer names the scope the base was found in, not the spelling the class wrote"
);
assert_eq!(list.members[1].depth, 1);
let found = member_of(files, "/p/a.cpp", source, "find();");
let Known::Yes(found) = found else {
panic!("`m.find` is `std::_Tree::find`: {found:?}");
};
assert_eq!(found.file, Path::new("/p/lib.h"));
assert_eq!(found.fact.qualified_name(), "std::_Tree::find");
assert!(
matches!(
member_of(files, "/p/a.cpp", source, "wrong();"),
Known::Unknown(UnknownReason::NotDeclaredHere(_))
),
"a base name that a nearer scope has does not fall through to the file-scope `_Tree`"
);
}
#[test]
fn a_type_spelled_from_the_global_name_space_lists_the_same_members() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n ::Widget w;\n}\n";
let found = members_of_class(&[], "/p/a.cpp", source, "::Widget");
let Known::Yes(list) = found else {
panic!("`::Widget` is the file-scope `Widget`: {found:?}");
};
assert_eq!(names(&list), ["size"]);
assert_eq!(list.members[0].declared_in, "Widget");
}
#[test]
fn a_member_added_to_a_base_appears_without_reindexing_the_derived_class() {
let a_header = "#include \"b.h\"\nstruct A : public B {\n int a_member;\n};\n";
let before = "struct B {\n int old_member;\n};\n";
let after = "struct B {\n int new_member;\n};\n";
let main = "#include \"a.h\"\n";
let mut index = index(&[
("/p/main.cpp", main),
("/p/a.h", a_header),
("/p/b.h", before),
]);
let tree = cpp_parser::CppParser::parse(main, cpp_parser::ParserConfig::default());
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let listed = |index: &ProjectIndex| match super::members_of(
index,
&scopes,
&root,
Path::new("/p/main.cpp"),
"A",
) {
Known::Yes(list) => list
.members
.iter()
.map(|member| member.fact.name.to_string())
.collect::<Vec<_>>(),
other => panic!("`A` is declared in an included header: {other:?}"),
};
assert_eq!(listed(&index), ["a_member", "old_member"]);
let mut rebuilt = summarize(Path::new("/p/b.h"), after, SummaryKey::new(1, 0));
for include in &mut rebuilt.includes {
include.resolved = Some(std::path::PathBuf::from(format!("/p/{}", include.spelling)));
}
index.insert(rebuilt);
assert_eq!(
listed(&index),
["a_member", "new_member"],
"the derived class's members are read from its bases at query time, so the edit is seen without \
anything of `A`'s being rebuilt"
);
let a = index
.summary(Path::new("/p/a.h"))
.expect("`a.h` is indexed");
let a_members: Vec<&str> = a
.declarations
.iter()
.filter(|fact| fact.scope.as_deref() == Some("A"))
.map(|fact| fact.name.as_str())
.collect();
assert_eq!(
a_members,
["a_member"],
"a fact stores the spelling `B`, never the members `B` happens to have"
);
}
fn after(source: &str, needle: &str) -> usize {
source
.rfind(needle)
.unwrap_or_else(|| panic!("{needle:?} is not in {source:?}"))
+ needle.len()
}
fn completions_at(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::MemberCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new(from),
after(source, needle),
)
}
#[test]
fn a_private_member_is_offered_inside_the_class_and_not_outside_it() {
let outside = "\
class Widget {
int hidden;
public:
int shown;
};
void f() {
Widget w;
w.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", outside, "w.") else {
panic!("`w` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["shown"],
"`hidden` is private and the cursor is not in `Widget`"
);
assert_eq!(
found.hidden_by_access, 1,
"and the answer says how many it kept out"
);
let inside = "\
class Widget {
int hidden;
public:
int shown;
void grow(Widget& other) {
other.
}
};
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", inside, "other.") else {
panic!("`other` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["grow", "hidden", "shown"],
"inside the class both are nameable, so both are offered"
);
}
#[test]
fn a_member_defined_outside_its_class_keeps_its_access() {
let source = "\
class Widget {
int hidden;
public:
int shown;
void set(int value);
void grow(Widget& other);
};
void Widget::set(int value) {
hidden = value;
}
void Widget::grow(Widget& other) {
other.
}
void f(Widget& w) {
w.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
panic!("`other` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert!(
offered.contains(&"hidden"),
"the cursor is inside a member of `Widget`, so `hidden` is nameable there: {offered:?}"
);
assert!(
offered.contains(&"set") && offered.contains(&"shown") && offered.contains(&"grow"),
"and so is everything else the class declares: {offered:?}"
);
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "w.") else {
panic!("`w` is a `Widget`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert!(
!offered.contains(&"hidden"),
"and from outside the class the same member is not: {offered:?}"
);
}
#[test]
fn a_protected_member_is_offered_in_a_derived_class() {
let source = "\
class Base {
protected:
int guarded;
public:
int open;
};
class Derived : public Base {
void grow(Derived& other) {
other.
}
};
void f(Derived& d) {
d.
}
";
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "other.") else {
panic!("`other` is a `Derived`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["grow", "guarded", "open"],
"`guarded` is protected and the cursor is in a class derived from the one that declares it"
);
let Known::Yes(found) = completions_at(&[], "/p/a.cpp", source, "d.") else {
panic!("`d` is a `Derived`");
};
let offered: Vec<&str> = found
.members
.members
.iter()
.map(|m| m.fact.name.as_str())
.collect();
assert_eq!(
offered,
["open"],
"and from a free function the same member is not nameable"
);
}
#[test]
fn a_member_access_with_nothing_typed_offers_the_types_members() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.");
let Known::Yes(completions) = found else {
panic!("`w` is a `Widget` declared two lines up: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
assert_eq!(completions.prefix, "", "nothing of the name is written yet");
assert_eq!(
completions.member_range.start_offset,
after(source, "w."),
"the empty range sits just past the operator, which is where the name goes"
);
assert_eq!(completions.member_range.length, 0);
}
#[test]
fn a_half_typed_member_offers_the_same_members_and_names_the_prefix() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.si\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.si");
let Known::Yes(completions) = found else {
panic!("the cursor is on the member being typed: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(completions.prefix, "si");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"si",
"the range covers what is written, so replacing it does not leave a doubled name"
);
}
#[test]
fn a_pointer_member_access_offers_the_pointees_members() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget* p;\n p->\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "p->");
let Known::Yes(completions) = found else {
panic!("`Widget* p` is a pointer to a `Widget`: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(completions.members.members.len(), 1);
}
#[test]
fn a_completion_on_this_offers_the_enclosing_class_members() {
let source = "struct Widget {\n int size;\n void grow() {\n this->\n }\n};\n";
let found = completions_at(&[], "/p/a.cpp", source, "this->");
let Known::Yes(completions) = found else {
panic!("`this` is the enclosing `Widget`: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
}
#[test]
fn the_members_offered_include_the_ones_the_bases_declare() {
let source = "struct Base {\n int inherited_size;\n};\n\
struct Derived : public Base {\n int own_size;\n};\n\
void f() {\n Derived d;\n d.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "d.");
let Known::Yes(completions) = found else {
panic!("`d` is a `Derived`: {found:?}");
};
let listed: Vec<(&str, &str)> = completions
.members
.members
.iter()
.map(|member| (member.fact.name.as_str(), member.declared_in.as_str()))
.collect();
assert_eq!(
listed,
[("own_size", "Derived"), ("inherited_size", "Base")],
"the class's own member first, then the inherited one, tagged with where it is declared"
);
}
#[test]
fn the_members_offered_cross_a_header() {
let source = "#include \"widget.h\"\nvoid f() {\n Widget w;\n w.\n}\n";
let (index, tree) = analysed_while_typing(
&[("/p/widget.h", "struct Widget {\n int size;\n};\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/main.cpp"),
after(source, "w."),
);
let Known::Yes(completions) = found else {
panic!("the class is in the included header: {found:?}");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions.members.members[0].file,
Path::new("/p/widget.h")
);
}
#[test]
fn a_completion_after_a_call_offers_what_the_call_returns() {
let source = "struct Widget {\n int size;\n void grow();\n};\nWidget make();\n\
void f() {\n make().\n}\n";
let Known::Yes(completions) = completions_at(&[], "/p/a.cpp", source, "make().") else {
panic!("`make()` returns a `Widget`");
};
assert_eq!(completions.class, "Widget");
assert_eq!(
completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>(),
["grow", "size"]
);
}
#[test]
fn a_completion_after_a_dereference_offers_the_pointees_members() {
let source = "struct Widget {\n int size;\n};\nWidget* make();\n\
void f() {\n (*make()).\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "(*make()).");
let Known::Yes(completions) = found else {
panic!("`(*make())` is a `Widget`, so its members are the answer: {found:?}");
};
assert_eq!(completions.class, "Widget");
}
#[test]
fn a_completion_on_an_expression_with_no_type_offers_nothing_and_says_why() {
let source =
"struct Widget {\n int size;\n};\nvoid f() {\n Widget a;\n (a.size + a.size).\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "(a.size + a.size).");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnknownType(_))),
"an arithmetic expression's type is not read off a declaration: {found:?}"
);
}
#[test]
fn a_completion_on_an_object_of_an_unknown_type_offers_nothing() {
let source = "void f() {\n Nowhere w;\n w.\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"`Nowhere` is a type nothing here declares: {found:?}"
);
let Known::Unknown(UnknownReason::NotDeclaredHere(name)) = found else {
unreachable!("just checked")
};
assert_eq!(
&*name, "Nowhere",
"and the reason names the type, not the object"
);
}
#[test]
fn a_cursor_that_is_not_on_a_member_access_offers_nothing() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "Widget w;");
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"a declaration is not a member access: {found:?}"
);
}
#[test]
fn a_cursor_on_the_object_asks_about_the_object() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size;\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
at(source, "w.size"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is on the object, before the operator: {found:?}"
);
}
#[test]
fn a_cursor_inside_a_name_filters_by_the_part_before_it() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.size;\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let cursor = at(source, "w.size") + 2 + 2;
let found = super::member_completions_at(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
cursor,
);
let Known::Yes(completions) = found else {
panic!("the cursor is inside the member's name: {found:?}");
};
assert_eq!(completions.prefix, "si", "what has been typed so far");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"size",
"and the whole name is what gets replaced"
);
}
#[test]
fn a_completed_member_access_still_answers_with_its_own_prefix() {
let source = "struct Widget {\n int size;\n void grow();\n};\n\
void f() {\n Widget w;\n w.size\n}\n";
let found = completions_at(&[], "/p/a.cpp", source, "w.size");
let Known::Yes(completions) = found else {
panic!("the cursor is at the end of `size`: {found:?}");
};
assert_eq!(completions.prefix, "size");
assert_eq!(
&source[completions.member_range.start_offset..completions.member_range.end_offset()],
"size"
);
}
#[test]
fn a_jump_on_a_member_that_is_not_written_yet_has_nothing_to_jump_to() {
let source = "struct Widget {\n int size;\n};\nvoid f() {\n Widget w;\n w.\n}\n";
let (index, tree) = analysed_while_typing(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let found = super::member_across_files(
&index,
&mut |_: &Path| None,
&scopes,
&root,
Path::new("/p/a.cpp"),
after(source, "w."),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"there is no written name to resolve: {found:?}"
);
}
fn names_at(
files: &[(&str, &str)],
from: &str,
source: &str,
needle: &str,
) -> Known<super::NameCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
super::name_completions_at(
&index,
&scopes,
&root,
Path::new(from),
after(source, needle),
)
}
fn names_at_blank(
files: &[(&str, &str)],
from: &str,
source: &str,
) -> Known<super::NameCompletions> {
let (index, tree) = analysed_while_typing(files, from, source);
let root = tree.get_red_root();
let scopes = crate::build_scopes(&root, &crate::NoMacroBodies);
let at = source
.find("void f()")
.and_then(|body| source[body..].find('{').map(|brace| body + brace + 1))
.expect("the fixture has a body");
super::name_completions_at(&index, &scopes, &root, Path::new(from), at)
}
#[track_caller]
fn offered(found: &Known<super::NameCompletions>) -> Vec<String> {
match found {
Known::Yes(completions) => completions
.names
.iter()
.map(|name| name.fact.name.to_string())
.collect(),
other => panic!("expected names: {other:?}"),
}
}
#[test]
fn a_name_in_a_late_file_of_a_namespace_is_still_offered() {
let mut big = String::from("namespace ns {\n");
for index in 0..(super::MAX_COLLECTED_NAMES + 20) {
big.push_str(&format!(" int filler{index};\n"));
}
big.push_str("}\n");
let late = "namespace ns {\n int zebra;\n}\n";
let big_with_include = format!("#include \"late.h\"\n{big}");
let source = "#include \"big.h\"\nvoid f() {\n ns::\n}\n";
let files = [
("/p/big.h", big_with_include.as_str()),
("/p/late.h", late),
("/p/a.cpp", source),
];
let found = names_at(&files, "/p/a.cpp", source, "ns::");
let names = offered(&found);
assert!(
names.iter().any(|name| name == "zebra"),
"the name is declared in a file the cursor can see, and the list must not stop before it: \
{} names offered, none of them `zebra`",
names.len()
);
}
#[test]
fn the_members_of_a_class_template_reached_through_an_alias_are_offered() {
let header = "namespace ns {\n\
template <class _Ty>\n\
struct Basic {\n\
unsigned long size() const;\n\
_Ty* data();\n\
};\n\
using String = Basic<char>;\n\
}\n";
let source = "#include \"basic.h\"\nvoid f() {\n ns::String::\n}\n";
let files = [("/p/basic.h", header), ("/p/a.cpp", source)];
let found = names_at(&files, "/p/a.cpp", source, "ns::String::");
let names = offered(&found);
assert!(
names.iter().any(|name| name == "size") && names.iter().any(|name| name == "data"),
"`ns::String` is `ns::Basic<char>`, and its members are the answer: {names:?}"
);
}
#[test]
fn a_qualified_scope_offers_the_names_written_in_it() {
let source =
"namespace ns {\n struct Widget { };\n int helper();\n}\nvoid f() {\n ns::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "ns::");
assert_eq!(
offered(&found),
["Widget", "helper"],
"sorted within the scope"
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "ns", "the scope as a lookup key");
assert_eq!(completions.prefix, "", "nothing of the name is typed yet");
assert_eq!(
completions.name_range.start_offset,
after(source, "ns::"),
"the empty range sits just past the `::`, where the name goes"
);
assert_eq!(completions.name_range.length, 0);
}
#[test]
fn a_half_typed_name_keeps_the_prefix_and_replaces_the_whole_segment() {
let source = "namespace ns {\n struct Widget { };\n}\nvoid f() {\n ns::Wid\n}\n";
let Known::Yes(completions) = names_at(&[], "/p/a.cpp", source, "ns::Wid") else {
panic!("the cursor is on the name being typed");
};
assert_eq!(completions.scope, "ns");
assert_eq!(completions.prefix, "Wid");
assert_eq!(
completions.name_range.start_offset,
at(source, "Wid"),
"the range is the written segment, not the point"
);
assert_eq!(completions.name_range.length, 3);
}
#[test]
fn a_class_scope_offers_its_members_and_the_ones_its_bases_declare() {
let source = "struct Base {\n typedef int size_type;\n};\n\
struct Derived : Base {\n typedef int value_type;\n};\n\
void f() {\n Derived::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "Derived::");
assert_eq!(
offered(&found),
["value_type", "size_type"],
"the class's own names first, then the ones a base declares"
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "Derived");
assert_eq!(
completions
.names
.iter()
.map(|name| name.depth)
.collect::<Vec<_>>(),
[0, 1],
"the base's name is one step further out, which is the order lookup walks in"
);
}
#[test]
fn a_global_scope_offers_only_what_is_declared_at_file_scope() {
let source =
"int global;\nnamespace ns {\n int inner;\n}\nvoid f() {\n int local;\n ::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "::");
assert_eq!(offered(&found), ["f", "global", "ns"]);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "::", "the global name space, as spelled");
let names = offered(&Known::Yes(completions.clone()));
assert!(
!names.contains(&"inner".to_string()) && !names.contains(&"local".to_string()),
"a namespace member and a local are not in the global name space: {names:?}"
);
}
#[test]
fn a_bare_name_offers_the_scopes_the_cursor_is_inside_innermost_first() {
let source = "int at_file_scope;\nnamespace ns {\n int in_a_namespace;\n struct C {\n int member;\n \
void g() {\n int local;\n loc\n }\n };\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "loc");
assert_eq!(
offered(&found),
[
"local",
"g",
"member",
"C",
"in_a_namespace",
"at_file_scope",
"ns"
]
);
let Known::Yes(completions) = found else {
unreachable!("asserted above")
};
assert_eq!(completions.scope, "", "no qualifier was written");
assert_eq!(completions.prefix, "loc");
let depths: Vec<usize> = completions.names.iter().map(|name| name.depth).collect();
let mut sorted = depths.clone();
sorted.sort_unstable();
assert_eq!(depths, sorted, "nearer scopes come first");
assert_eq!(depths[0], 0, "the local is in the scope the cursor is in");
}
#[test]
fn another_files_local_is_not_offered_by_a_bare_name() {
let header = "/p/widget.h";
let declaration = "void g() {\n int __first = 0;\n int helper;\n}\nint global_name;\n";
let source = "#include \"widget.h\"\nvoid f() {\n int mine;\n min\n}\n";
let found = names_at(&[(header, declaration)], "/p/main.cpp", source, "min");
let names = offered(&found);
assert!(
names.contains(&"mine".to_string()),
"the local of *this* file is offered, from its own scopes: {names:?}"
);
assert!(
!names.contains(&"__first".to_string()) && !names.contains(&"helper".to_string()),
"another file's locals are not names this file can write: {names:?}"
);
let at_a_blank = names_at_blank(&[(header, declaration)], "/p/main.cpp", source);
let names = offered(&at_a_blank);
assert!(
names.contains(&"global_name".to_string()),
"…while a file-scope name in the same header is offered where nothing is typed: {names:?}"
);
}
#[test]
fn a_namespace_is_merged_across_the_buffer_and_the_header() {
let source =
"#include \"ns.h\"\nnamespace ns {\n int in_the_buffer;\n}\nvoid f() {\n ns::\n}\n";
let found = names_at(
&[("/p/ns.h", "namespace ns {\n int in_the_header;\n}\n")],
"/p/main.cpp",
source,
"ns::",
);
assert_eq!(offered(&found), ["in_the_buffer", "in_the_header"]);
}
#[test]
fn a_scope_nothing_declares_is_not_an_empty_list() {
let source = "void f() {\n nowhere::\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "nowhere::");
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"nothing declares `nowhere`: {found:?}"
);
}
#[test]
fn a_cursor_where_a_name_can_be_written_offers_the_visible_names() {
let source = "struct Widget { int size; };\nvoid f() {\n Widget w;\n}\n";
let found = names_at(&[], "/p/a.cpp", source, "Widget");
let Known::Yes(found) = found else {
panic!("a name can be written here: {found:?}");
};
let names: Vec<&str> = found
.names
.iter()
.map(|offered| offered.fact.name.as_str())
.collect();
assert!(
names.contains(&"Widget") && names.contains(&"f"),
"the names in scope: {names:?}"
);
assert_eq!(found.prefix, "Widget", "what is written filters the list");
assert_eq!(
found.name_range.length,
"Widget".len(),
"and the chosen name replaces it rather than being inserted beside it"
);
}
fn line_of(source: &str, offset: usize) -> usize {
source[..offset].matches('\n').count()
}
#[test]
fn a_macro_defined_above_its_use_resolves_to_the_define() {
let source = "#define MAX 1\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the define above the use is the answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/a.cpp"));
assert_eq!(found.fact.name, "MAX");
assert!(found.fact.kind.is_definition());
assert_eq!(
&source[found.fact.range.start_offset..found.fact.range.end_offset()],
"MAX",
"and the range is the name a user would be sent to"
);
}
#[test]
fn a_macro_defined_below_its_use_is_not_in_force_yet() {
let source = "int x = MAX;\n#define MAX 1\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"nothing above the use defines it: {found:?}"
);
}
#[test]
fn a_macro_in_an_included_header_resolves_into_that_header() {
let source = "#include \"config.h\"\nint x = FEATURE;\n";
let header = "#define FEATURE 1\n";
let (index, tree) = analysed(&[("/p/config.h", header)], "/p/main.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the header's define must be found: {found:?}");
};
assert_eq!(found.file, Path::new("/p/config.h"));
assert_eq!(line_of(header, found.fact.range.start_offset), 0);
}
#[test]
fn a_header_included_after_the_use_does_not_define_it_yet() {
let source = "int x = FEATURE;\n#include \"config.h\"\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the include is below the use: {found:?}"
);
}
#[test]
fn the_later_of_two_headers_that_define_it_wins() {
let source = "#include \"one.h\"\n#include \"two.h\"\nint x = FLAG;\n";
let one = "#define FLAG 1\n";
let two = "#define FLAG 2\n";
let (index, tree) = analysed(
&[("/p/one.h", one), ("/p/two.h", two)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));
let Known::Yes(found) = found else {
panic!("the last define gone past is the answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/two.h"));
}
#[test]
fn swapping_the_two_includes_swaps_the_answer() {
let source = "#include \"two.h\"\n#include \"one.h\"\nint x = FLAG;\n";
let one = "#define FLAG 1\n";
let two = "#define FLAG 2\n";
let (index, tree) = analysed(
&[("/p/one.h", one), ("/p/two.h", two)],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "FLAG;"));
let Known::Yes(found) = found else {
panic!("order is the whole answer: {found:?}");
};
assert_eq!(found.file, Path::new("/p/one.h"));
}
#[test]
fn a_local_define_after_an_include_wins_over_the_header() {
let source = "#include \"config.h\"\n#define FEATURE 2\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the file's own later define is what is in force: {found:?}");
};
assert_eq!(found.file, Path::new("/p/main.cpp"));
}
#[test]
fn a_local_define_before_an_include_loses_to_the_header() {
let source = "#define FEATURE 2\n#include \"config.h\"\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
let Known::Yes(found) = found else {
panic!("the header was pasted after the local define: {found:?}");
};
assert_eq!(found.file, Path::new("/p/config.h"));
}
#[test]
fn a_nested_include_is_reached() {
let source = "#include \"middle.h\"\nint x = DEEP;\n";
let (index, tree) = analysed(
&[
("/p/middle.h", "#include \"leaf.h\"\n"),
("/p/leaf.h", "#define DEEP 1\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found =
super::macro_across_files(&index, &root, Path::new("/p/main.cpp"), at(source, "DEEP;"));
let Known::Yes(found) = found else {
panic!("a define two includes down is still in force: {found:?}");
};
assert_eq!(found.file, Path::new("/p/leaf.h"));
}
#[test]
fn an_undef_of_a_local_define_leaves_an_ordinary_identifier() {
let source = "#define MAX 1\n#undef MAX\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"an `#undef` above the use settles it: {found:?}"
);
}
#[test]
fn an_undef_of_a_headers_define_also_counts() {
let source = "#include \"config.h\"\n#undef FEATURE\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"the header's define is ended by the file's own `#undef`: {found:?}"
);
}
#[test]
fn a_define_after_an_undef_is_in_force_again() {
let source = "#define MAX 1\n#undef MAX\n#define MAX 2\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the last fact is a define: {found:?}");
};
assert_eq!(line_of(source, found.fact.range.start_offset), 2);
}
#[test]
fn a_define_inside_a_conditional_is_unknown_rather_than_guessed() {
let source = "#if defined(USE_MAX)\n#define MAX 1\n#endif\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"whether that branch was taken is not knowable here: {found:?}"
);
}
#[test]
fn an_unconditional_define_beats_a_guarded_one_after_it() {
let source = "#define MAX 1\n#if defined(OTHER)\n#define MAX 3\n#endif\nint x = MAX;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "MAX;"));
let Known::Yes(found) = found else {
panic!("the unconditional define is what is certain: {found:?}");
};
assert_eq!(line_of(source, found.fact.range.start_offset), 0);
}
#[test]
fn a_guarded_include_makes_the_answer_conditional() {
let source = "#if defined(USE_CONFIG)\n#include \"config.h\"\n#endif\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[("/p/config.h", "#define FEATURE 1\n")],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::ConditionalCompilation)),
"the only path to the define goes through an `#if`: {found:?}"
);
}
#[test]
fn a_name_no_one_defines_is_not_declared_here() {
let source = "int x = NOT_A_MACRO;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/a.cpp"),
at(source, "NOT_A_MACRO;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::NotDeclaredHere(_))),
"the index is a subset of the translation unit, so this is not a definite no: {found:?}"
);
}
#[test]
fn a_cursor_that_is_not_on_a_name_has_nothing_to_look_up() {
let source = "#define MAX 1\nint x = MAX + 1;\n";
let (index, tree) = analysed(&[], "/p/a.cpp", source);
let root = tree.get_red_root();
let found = super::macro_across_files(&index, &root, Path::new("/p/a.cpp"), at(source, "+ 1;"));
assert!(
matches!(found, Known::Unknown(UnknownReason::UnparsableName)),
"the cursor is on an operator: {found:?}"
);
}
#[test]
fn a_cycle_of_includes_terminates() {
let source = "#include \"a.h\"\nint x = SHARED;\n";
let (index, tree) = analysed(
&[
("/p/a.h", "#include \"b.h\"\n#define SHARED 1\n"),
("/p/b.h", "#include \"a.h\"\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "SHARED;"),
);
let Known::Yes(found) = found else {
panic!("a cycle must not stop the define being found: {found:?}");
};
assert_eq!(found.file, Path::new("/p/a.h"));
}
#[test]
fn an_undef_in_a_header_is_reached_like_a_define() {
let source = "#include \"config.h\"\n#include \"cleanup.h\"\nint x = FEATURE;\n";
let (index, tree) = analysed(
&[
("/p/config.h", "#define FEATURE 1\n"),
("/p/cleanup.h", "#undef FEATURE\n"),
],
"/p/main.cpp",
source,
);
let root = tree.get_red_root();
let found = super::macro_across_files(
&index,
&root,
Path::new("/p/main.cpp"),
at(source, "FEATURE;"),
);
assert!(
matches!(found, Known::Unknown(UnknownReason::UndefinedHere(_))),
"the later header undefines it: {found:?}"
);
}
#[test]
fn an_empty_program_reading_does_not_hide_the_one_with_declarations() {
let mut index = index(&[
(
"/p/a.h",
"struct Widget {\n int size;\n int area();\n};\n",
),
(
"/p/main.cpp",
"#include \"a.h\"\nint main() { return 0; }\n",
),
]);
let cooked_of = |index: &ProjectIndex, path: &str| {
let summary = index
.summary(Path::new(path))
.expect("the fixture is summarized");
crate::index::CookedFile::declarations(summary.declarations.clone())
};
index.insert_cooked(Path::new("/p/a.h"), cooked_of(&index, "/p/a.h"));
index.insert_cooked_in_a_program(
Path::new("/p/main.cpp"),
7,
cooked_of(&index, "/p/main.cpp"),
);
index.insert_cooked_in_a_program(Path::new("/p/a.h"), 7, crate::index::CookedFile::default());
let members = index
.declarations_in("Widget", Path::new("/p/main.cpp"))
.len();
assert!(
members >= 2,
"the class's members are still visible from the program that read the header: {members}"
);
let found = index.definition("Widget::size", Path::new("/p/main.cpp"));
assert!(
matches!(found, Known::Yes(_)),
"and a member resolves: {found:?}"
);
}