use crate::file::coordinates::ReadingOffset;
use crate::file::paths::MemoryFiles;
use crate::symbol::Known;
use std::path::{Path, PathBuf};
use super::*;
#[test]
pub(crate) fn a_modules_closure_is_visible_to_a_file_that_imports_it() {
let interface = "export module m;\nexport int given();\n";
let implementation = "namespace hidden {\n struct Widget { int weight; };\n}\n";
let importer = "import m;\nvoid f() {}\n";
let files = MemoryFiles::new()
.with_file("/p/m.ixx", interface)
.with_file("/p/hidden.cpp", implementation)
.with_file("/p/user.cpp", importer);
let fixture = Memory::new("a-modules-closure-is-visible", &files);
let mut session = fixture.session();
session.add_project_files([
PathBuf::from("/p/m.ixx"),
PathBuf::from("/p/hidden.cpp"),
PathBuf::from("/p/user.cpp"),
]);
session.index_everything();
let before = session.index().visible_files(Path::new("/p/user.cpp"));
assert!(
!before.iter().any(|(path, _)| path.ends_with("hidden.cpp")),
"the interface's own closure is empty until a unit is read: {before:?}"
);
session.index().remember_the_unit_closure(
"m",
vec!["/p/hidden.cpp".to_string(), "/p/m.ixx".to_string()],
);
let after = session.index().visible_files(Path::new("/p/user.cpp"));
assert!(
after.iter().any(|(path, _)| path.ends_with("hidden.cpp")),
"a file the unit was rendered from is visible to its importer: {after:?}"
);
assert!(
matches!(
session
.index()
.definition("Widget", Path::new("/p/user.cpp")),
Known::Yes(_)
),
"the class the unit saw is nameable from the importer"
);
}
#[test]
pub(crate) fn a_type_used_without_its_include_is_reported_and_std_is_not() {
let header = "struct Widget { int size; };\n";
let source = "void grow(Widget* w) { w->size = 1; }\n";
let files = MemoryFiles::new()
.with_file("/p/widget.h", header)
.with_file("/p/widget.cpp", source)
.with_file("/opt/sdk/strings.h", "struct String { int size; };\n")
.with_file(
"/p/other.cpp",
"#include \"/opt/sdk/strings.h\"\nvoid g(String* s) { s->size = 2; }\n",
)
.with_file("/p/uses_string.cpp", "void f(String* s) { s->size = 1; }\n");
let fixture = Memory::new("missing-include", &files);
let mut session = fixture.session();
session.add_project_files([
PathBuf::from("/p/widget.h"),
PathBuf::from("/p/widget.cpp"),
PathBuf::from("/p/other.cpp"),
PathBuf::from("/p/uses_string.cpp"),
]);
session.want_cooked_reading(Path::new("/p/widget.cpp"));
session.want_cooked_reading(Path::new("/p/uses_string.cpp"));
session.index_everything();
let found = session
.diagnostics("/p/widget.cpp")
.expect("the file reads")
.checks;
let missing: Vec<&crate::sema::check::Finding> = found
.iter()
.filter(|finding| finding.code == crate::sema::check::DiagnosticCode::MissingInclude)
.collect();
assert!(
missing
.iter()
.any(|finding| finding.name == "Widget" && finding.message.contains("widget.h")),
"the header that declares `Widget` is named: {found:?}"
);
let outside = session
.diagnostics("/p/uses_string.cpp")
.expect("the file reads")
.checks;
assert!(
!outside
.iter()
.any(|finding| finding.code == crate::sema::check::DiagnosticCode::MissingInclude),
"`String` is declared outside the workspace, so no include is suggested: {outside:?}"
);
}
#[test]
pub(crate) fn a_name_from_a_nearby_header_is_offered_with_its_include() {
let header = "struct Widget { int size; };\n";
let source = "void f() {\n Wid\n}\n";
let files = MemoryFiles::new()
.with_file("/p/widget.h", header)
.with_file("/p/use.cpp", source);
let fixture = Memory::new("unincluded-completion", &files);
let mut session = fixture.session();
session.did_open("/p/use.cpp", source);
session.add_project_files([PathBuf::from("/p/widget.h"), PathBuf::from("/p/use.cpp")]);
session.index_everything();
let path = PathBuf::from("/p/use.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = source.find("Wid").expect("the fixture") + "Wid".len();
let offered = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let item = offered
.items
.iter()
.find(|item| item.label == "Widget")
.unwrap_or_else(|| {
panic!(
"`Widget` is offered from the header beside the file: {:?}",
offered
.items
.iter()
.map(|item| &item.label)
.collect::<Vec<_>>()
)
});
assert_eq!(
item.inclusion,
Some(crate::completion::Inclusion::Include(
"widget.h".to_string()
)),
"the spelling is the one a compiler searches"
);
let (range, text) = item
.additional_edits
.first()
.expect("the include is carried as an edit");
assert_eq!(text, "#include \"widget.h\"\n");
assert_eq!(
range.start_offset, 0,
"there is no include block, so the edit goes at the top"
);
}
#[test]
pub(crate) fn a_forward_declaration_does_not_shadow_the_definition() {
let header = "struct Widget;\n\nstruct Widget {\n int size;\n};\n";
let source = "#include \"widget.h\"\nvoid f(Widget* widget) { (void)widget; }\n";
let files = MemoryFiles::new()
.with_file("/p/widget.h", header)
.with_file("/p/use.cpp", source);
let fixture = Memory::new("forward-declaration", &files);
let mut session = fixture.session();
session.did_open("/p/use.cpp", source);
session.add_project_files([PathBuf::from("/p/widget.h"), PathBuf::from("/p/use.cpp")]);
session.index_everything();
let definition = header.find("struct Widget {").expect("the fixture");
match session
.index()
.definition("Widget", Path::new("/p/use.cpp"))
{
Known::Yes(found) => {
assert_eq!(
found.fact.range.start_offset, definition,
"the answer is the definition, not the forward declaration written above it"
);
assert!(found.fact.definition, "and the fact says so");
}
other => panic!("`Widget` is defined in the header: {other:?}"),
}
let forward = "struct Gadget;\n";
let body = "struct Gadget {\n int size;\n};\n";
let files = MemoryFiles::new()
.with_file("/p/gadget_forward.h", forward)
.with_file("/p/gadget.h", body)
.with_file(
"/p/use.cpp",
"#include \"gadget_forward.h\"\n#include \"gadget.h\"\n",
);
let fixture = Memory::new("forward-declaration-across-files", &files);
let mut session = fixture.session();
session.add_project_files([
PathBuf::from("/p/gadget_forward.h"),
PathBuf::from("/p/gadget.h"),
PathBuf::from("/p/use.cpp"),
]);
session.index_everything();
match session
.index()
.definition("Gadget", Path::new("/p/use.cpp"))
{
Known::Yes(found) => assert!(
found.file.ends_with("gadget.h") && !found.file.ends_with("gadget_forward.h"),
"the definition wins over the forward declaration in another file: {:?}",
found.file
),
other => panic!("`Gadget` is defined in a header this file includes: {other:?}"),
}
}
#[test]
pub(crate) fn a_class_template_resolves_to_its_primary_definition() {
let forward = "template <class _Ty, class _Alloc>\nclass vector;\n";
let defining = "template <class _Ty, class _Alloc>\nclass vector {\npublic:\n void push_back(const _Ty&);\n};\n\
\ntemplate <class _Alloc>\nclass vector<bool, _Alloc> {\npublic:\n void flip();\n};\n";
let source =
"#include \"forward.h\"\n#include \"vector.h\"\nvoid f(std::vector<int>* v) { (void)v; }\n";
let files = MemoryFiles::new()
.with_file("/p/forward.h", forward)
.with_file("/p/vector.h", defining)
.with_file("/p/use.cpp", source);
let fixture = Memory::new("primary-template", &files);
let mut session = fixture.session();
session.did_open("/p/use.cpp", source);
session.add_project_files([
PathBuf::from("/p/forward.h"),
PathBuf::from("/p/vector.h"),
PathBuf::from("/p/use.cpp"),
]);
session.index_everything();
let primary = defining.find("class vector {").expect("the fixture");
match session
.index()
.definition("vector", Path::new("/p/use.cpp"))
{
Known::Yes(found) => {
assert!(
found.fact.definition,
"a definition, not a forward declaration"
);
assert_eq!(
found.fact.pattern(),
None,
"the primary template, not `vector<bool>`"
);
assert_eq!(
found.fact.range.start_offset, primary,
"and its own declaration"
);
}
other => panic!("`vector` has a primary definition in this closure: {other:?}"),
}
}
#[test]
pub(crate) fn a_class_whose_name_is_also_its_constructor_still_lists_its_members() {
const HEADER: &str = "#pragma once\n\
class LSPHandle {\n\
public:\n\
\x20 LSPHandle(int server);\n\
\x20 void RefreshDiagnostic();\n\
\x20 int connected_;\n\
};\n";
const SOURCE: &str = "#include \"LSPHandle.h\"\n\
LSPHandle::LSPHandle(int server) : connected_(server) {\n\
}\n\
void LSPHandle::RefreshDiagnostic() {\n\
\x20 LSPHandle::RefreshDiagnostic();\n\
}\n";
let files = MemoryFiles::new()
.with_file("/p/LSPHandle.h", HEADER)
.with_file("/p/LSPHandle.cpp", SOURCE);
let fixture = Memory::new("a-class-named-like-its-constructor", &files);
let mut session = fixture.session();
session.did_open("/p/LSPHandle.h", HEADER);
session.did_open("/p/LSPHandle.cpp", SOURCE);
session.index_everything();
let view = session
.view_of_the_file(std::path::Path::new("/p/LSPHandle.cpp"))
.expect("a view of the source");
let at = SOURCE
.rfind("LSPHandle::RefreshDiagnostic")
.expect("the qualified call")
+ "LSPHandle::".len();
let set = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let mut names: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
names.sort_unstable();
names.dedup();
assert!(
names.contains(&"RefreshDiagnostic"),
"`LSPHandle::` from a fresh index must offer the class's members; got {} item(s): {:?}",
names.len(),
names.iter().take(12).collect::<Vec<_>>()
);
let qualifier = SOURCE
.rfind("LSPHandle::RefreshDiagnostic")
.expect("the qualified call")
+ 3;
let typed = session.type_at(
&view,
crate::file::coordinates::ReadingOffset::new(qualifier),
);
let shown = format!("{typed:?}");
assert!(
!shown.contains("LSPHandle(int") && !shown.contains("LSPHandle(int)"),
"the qualifier was read as the constructor, not the class: {shown}"
);
let edited = format!("{SOURCE}// typed\n");
session.did_change("/p/LSPHandle.cpp", &edited);
session.catch_up(std::path::Path::new("/p/LSPHandle.cpp"));
let view = session
.view_of_the_file(std::path::Path::new("/p/LSPHandle.cpp"))
.expect("a view of the edited source");
let set = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let names: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
assert!(
names.contains(&"RefreshDiagnostic"),
"one keystroke later `LSPHandle::` must still offer the class's members; got {:?}",
names.iter().take(12).collect::<Vec<_>>()
);
}
#[test]
pub(crate) fn a_conditional_macros_value_is_folded_when_every_definition_agrees() {
let agreeing = "#ifdef WIDE\n\
#define LIMIT 0x10\n\
#else\n\
#define LIMIT 0x10\n\
#endif\n\
const int VALUE = LIMIT * 2;\n";
let files = MemoryFiles::new().with_file("/p/agree.cpp", agreeing);
let fixture = Memory::new("a-conditional-macro-that-agrees", &files);
let mut session = fixture.session();
session.did_open("/p/agree.cpp", agreeing);
session.index_everything();
let view = session
.view_of_the_file(std::path::Path::new("/p/agree.cpp"))
.expect("a view");
let at = agreeing.find("VALUE = ").expect("the fixture");
assert_eq!(
session.constant_value_at(&view, crate::file::coordinates::ReadingOffset::new(at)),
Some(32),
"both definitions in force say 0x10"
);
}
#[test]
pub(crate) fn a_header_cooked_without_a_unit_is_read_in_its_own_environment() {
let files = MemoryFiles::new()
.with_file("/p/h.h", "KIND\n")
.with_file("/p/b.cpp", "#define KIND int value_b;\n#include \"h.h\"\n")
.with_file("/p/c.cpp", "#define KIND int value_c;\n#include \"h.h\"\n");
let memory = Memory::new("header-own-environment", &files);
let mut session = memory.session();
session.add_project_files([PathBuf::from("/p/b.cpp"), PathBuf::from("/p/c.cpp")]);
session.index_everything();
session.cook("/p/b.cpp").expect("the root is cooked");
session.cook("/p/c.cpp").expect("the root is cooked");
session.cook("/p/h.h").expect("the header is cooked");
let names: Vec<String> = session
.index()
.cooked_declarations(Path::new("/p/h.h"))
.expect("the header has a reading")
.iter()
.map(|fact| fact.name.to_string())
.collect();
assert!(
!names
.iter()
.any(|name| name == "value_b" || name == "value_c"),
"an includer's `#define` is not part of the header's own environment: {names:?}"
);
session
.read_the_unit(Path::new("/p/b.cpp"))
.expect("b.cpp reads as a program");
let names: Vec<String> = session
.index()
.cooked_declarations(Path::new("/p/h.h"))
.expect("the header has a reading")
.iter()
.map(|fact| fact.name.to_string())
.collect();
assert!(
names.iter().any(|name| name == "value_b"),
"the program read gives the header the environment it is included in: {names:?}"
);
}
#[test]
pub(crate) fn a_name_a_macro_writes_is_in_the_index_once_its_header_was_cooked() {
let files = MemoryFiles::new()
.with_file(
"/p/lib.h",
"#define DECL(name) extern int name(void);\nDECL(lib_open);\n",
)
.with_file(
"/p/a.c",
"#include \"lib.h\"\nvoid f(void) { lib_open(); }\n",
);
let fixture = Memory::new("macro-declaration", &files);
let mut alone = fixture.session();
alone.add_project_files([PathBuf::from("/p/a.c")]);
alone.index_everything();
alone.cook("/p/a.c").expect("the file is cooked");
let view = alone.view("/p/a.c").expect("the file reads");
let at = view
.source
.find("lib_open")
.expect("the call is in the text");
assert!(
matches!(
alone.definition(&view, ReadingOffset::new(at)),
Known::Unknown(_)
),
"nothing cooked the header, so the declaration is nowhere in the index"
);
let mut editor = fixture.session();
editor.did_open(
"/p/a.c",
"#include \"lib.h\"\nvoid f(void) { lib_open(); }\n",
);
editor.index_everything();
editor.advance(64);
let view = editor.view("/p/a.c").expect("the file reads");
let at = view
.source
.find("lib_open")
.expect("the call is in the text");
match editor.definition(&view, ReadingOffset::new(at)) {
Known::Yes(found) => {
assert_eq!(found.file, Path::new("/p/lib.h"));
assert_eq!(found.fact.name, "lib_open");
}
other => panic!("the macro's declaration is not in the index: {other:?}"),
}
}
#[test]
pub(crate) fn a_headers_own_guard_does_not_empty_its_rendering() {
let files = MemoryFiles::new()
.with_file(
"/p/guarded.h",
"#ifndef GUARDED_H\n#define GUARDED_H\nstruct Widget { int size; };\n#endif\n",
)
.with_file("/p/a.c", "#include \"guarded.h\"\nvoid f(void) { }\n");
let fixture = Memory::new("own-guard", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/a.c")]);
session.index_everything();
session.cook("/p/guarded.h").expect("the header cooks");
let facts = session
.index()
.cooked_declarations(Path::new("/p/guarded.h"))
.expect("the header has a reading");
assert_eq!(
facts.iter().filter(|fact| fact.name == "Widget").count(),
1,
"the declaration inside the guard is in the rendered reading: {facts:?}"
);
}
#[test]
pub(crate) fn a_rendering_view_survives_twelve_buffer_views() {
let main = "#include \"a.h\"\nint main() { return 0; }\n";
let mut files = MemoryFiles::new().with_file("/p/main.cpp", main);
for index in 0..12 {
files = files.with_file(format!("/p/h{index}.h"), "#define A 1\n");
}
let fixture = Memory::new("a-rendering-view-survives", &files);
let mut session = fixture.session();
let project: Vec<std::path::PathBuf> = (0..12)
.map(|index| std::path::PathBuf::from(format!("/p/h{index}.h")))
.collect();
session.add_project_files(project.iter().cloned());
session.did_open("/p/main.cpp", main);
for _ in 0..8 {
session.index_everything();
session.catch_up(std::path::Path::new("/p/main.cpp"));
if session.pending_work() == 0 {
break;
}
}
let rendered = session.view(std::path::Path::new("/p/main.cpp"));
assert!(rendered.is_some(), "the cook left a rendering to parse");
assert_eq!(
session.rendering_views.lock().expect("not poisoned").len(),
1,
"the rendering view is remembered in its own cache"
);
for header in &project {
let _ = session.view_of_the_file(header);
}
assert!(
session.views.lock().expect("not poisoned").len() <= 8,
"the buffer cache keeps its own cap"
);
assert_eq!(
session.rendering_views.lock().expect("not poisoned").len(),
1,
"and twelve buffer views did not throw it away"
);
assert!(
session.view(std::path::Path::new("/p/main.cpp")).is_some(),
"the second ask is a cache hit, not a re-parse"
);
}
#[test]
pub(crate) fn the_focused_document_gets_its_program() {
let main = "#include \"api.h\"\nApi a;\n";
let second = "#include \"api.h\"\nApi b;\n";
let files = MemoryFiles::new()
.with_file("/p/api.h", "struct Api { int x; };\n")
.with_file("/p/main.cpp", main)
.with_file("/p/second.cpp", second);
let fixture = Memory::new("the-focused-document-gets-its-program", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.did_open("/p/second.cpp", second);
session.index_everything();
session.pretend_a_pause(std::time::Duration::from_millis(1_100));
assert_eq!(
session.the_program_to_read().as_deref(),
Some(Path::new("/p/second.cpp")),
"the document the reader opened last is the one whose program is next"
);
assert!(
session.read_a_program_now().is_some(),
"and it is read when the session gets the chance"
);
assert_eq!(
session.the_program_to_read(),
None,
"the background tab is not a program to read"
);
session.did_change("/p/main.cpp", main);
session.pretend_a_pause(std::time::Duration::from_millis(1_100));
assert_eq!(
session.the_program_to_read().as_deref(),
Some(Path::new("/p/main.cpp")),
"the file that was just typed into is the one whose program is next"
);
}