use crate::file::coordinates::ReadingOffset;
use crate::file::paths::MemoryFiles;
use crate::include::config::{CommandLineMacro, CompilerConfig};
use crate::include::toolchain::{Toolchain, ToolchainSource};
use crate::symbol::Known;
use std::path::{Path, PathBuf};
use super::*;
#[test]
pub(crate) fn the_compilation_is_known_only_when_the_compiler_answered_with_its_macros() {
assert!(
!crate::session::the_compilation_is_known(None),
"no compiler answered, so nothing witnesses the built-ins"
);
let unasked = Toolchain {
compiler: None,
version: None,
system_include_paths: vec![PathBuf::from("/usr/include")],
builtin_macros: Vec::new(),
dialect: None,
cuda: false,
standard: None,
source: ToolchainSource::SystemHeaders,
note: Some("no compiler could be asked".to_string()),
};
assert!(
!crate::session::the_compilation_is_known(Some(&unasked)),
"directories without a macro table are half a toolchain, and the missing half is the built-ins"
);
let asked = Toolchain {
compiler: Some(PathBuf::from("cl")),
builtin_macros: vec![CommandLineMacro::defined("_MSC_VER")],
..unasked
};
assert!(
crate::session::the_compilation_is_known(Some(&asked)),
"a compiler that answered is the only witness there is to the names no file defines"
);
}
#[test]
pub(crate) fn a_file_is_closure_ready_only_once_what_it_reaches_is_read() {
let files = MemoryFiles::new()
.with_file("/p/mid.h", "#include \"deep.h\"\n")
.with_file("/p/deep.h", "namespace std { int endl(); }\n")
.with_file(
"/p/a.cpp",
"#include \"mid.h\"\nint main() { return std::endl(); }\n",
);
let fixture = Memory::new("is-closure-ready", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/a.cpp")]);
session.index_everything();
assert!(
session.is_locally_ready(Path::new("/p/a.cpp")),
"the file and its direct includes are read"
);
assert!(
session.is_closure_ready(Path::new("/p/a.cpp")),
"and so is everything they reach"
);
session.store.forget(Path::new("/p/deep.h"));
assert!(
session.is_locally_ready(Path::new("/p/a.cpp")),
"the direct question is unchanged — `catch_up` has nothing left to read"
);
assert!(
!session.is_closure_ready(Path::new("/p/a.cpp")),
"but a name declared in `deep.h` has no classification, which is the question colouring asks"
);
}
#[test]
pub(crate) fn a_keystroke_outside_the_closure_does_not_rerun_another_files_pull() {
let files = MemoryFiles::new()
.with_file("/p/h.h", "struct Widget { int size; };\n")
.with_file(
"/p/a.cpp",
"#include \"h.h\"\nint main() { int count = \"three\"; return 0; }\n",
)
.with_file("/p/b.cpp", "int other() { return 1; }\n");
let memory = Memory::new("pull-key", &files);
let mut session = memory.session();
let a = PathBuf::from("/p/a.cpp");
let b = PathBuf::from("/p/b.cpp");
session.add_project_files([a.clone(), b.clone()]);
session.index_everything();
session.cook(&a).expect("the file is cooked");
session.cook(&b).expect("the file is cooked");
let first = session.diagnostics(&a).expect("a cooked reading");
assert!(
!first.checks.is_empty(),
"the fixture has a finding to remember: {first:?}"
);
let (hits, runs) = session.pull_counts();
session.did_change(&b, "int other() { return 2; }\n");
session.advance(64);
session.cook(&b);
let unchanged = session.diagnostics(&a).expect("a cooked reading");
assert_eq!(
unchanged.checks, first.checks,
"the same findings, because nothing the pull read changed"
);
let (hits_after, runs_after) = session.pull_counts();
assert_eq!(
(hits_after - hits, runs_after - runs),
(1, 0),
"the pull was answered from the memo rather than run again"
);
session.did_change(PathBuf::from("/p/h.h"), "struct Widget { long size; };\n");
session.advance(64);
session.cook(&a);
let _ = session.diagnostics(&a).expect("a cooked reading");
let (hits_last, runs_last) = session.pull_counts();
assert_eq!(
(hits_last - hits_after, runs_last - runs_after),
(0, 1),
"a header in the closure is a different state, so the rules run again"
);
}
#[test]
pub(crate) fn a_cold_closure_is_walked_once_for_everyone_who_asks_at_the_same_time() {
const DEPTH: usize = 40;
let mut files = MemoryFiles::new();
for depth in 0..DEPTH {
let next = match depth + 1 < DEPTH {
true => format!("#include \"h{}.h\"\n", depth + 1),
false => String::new(),
};
files = files.with_file(
format!("/p/h{depth}.h"),
format!("{next}struct S{depth} {{ int field; }};\n"),
);
}
files = files.with_file("/p/a.cpp", "#include \"h0.h\"\nint main() { return 0; }\n");
let memory = Memory::new("one-walk", &files);
let mut session = memory.session();
let path = PathBuf::from("/p/a.cpp");
session.add_project_files([path.clone()]);
session.index_everything();
session
.store
.forget(Path::new(&format!("/p/h{}.h", DEPTH - 1)));
let (built_before, _, _) = session.index().walk_counts();
const THREADS: usize = 8;
let barrier = std::sync::Barrier::new(THREADS);
let answers: Vec<usize> = std::thread::scope(|scope| {
let handles: Vec<_> = (0..THREADS)
.map(|_| {
scope.spawn(|| {
barrier.wait();
session.index().visible_files(&path).len()
})
})
.collect();
handles
.into_iter()
.map(|handle| handle.join().expect("a walker"))
.collect()
});
let (built, hits, met) = session.index().walk_counts();
assert!(
answers.iter().all(|seen| *seen == answers[0]),
"every caller gets the same closure: {answers:?}"
);
assert!(
answers[0] > 1,
"and it is the closure, not just the file: {} file(s)",
answers[0]
);
assert_eq!(
built - built_before,
1,
"one walk for eight callers ({met} met an in-flight walk, {hits} hit the memo)"
);
}
#[test]
pub(crate) fn a_pull_whose_closure_is_unread_withholds_its_checks_and_says_so() {
let files = MemoryFiles::new()
.with_file("/p/mid.h", "#include \"deep.h\"\n")
.with_file("/p/deep.h", "namespace std { int endl(); }\n")
.with_file(
"/p/a.cpp",
"#include \"mid.h\"\nint main() { int count = \"three\"; return 0; }\n",
);
let memory = Memory::new("checks-withheld", &files);
let mut session = memory.session();
let path = PathBuf::from("/p/a.cpp");
session.add_project_files([path.clone()]);
session.index_everything();
session.cook(&path).expect("the file is cooked");
let ready = session.diagnostics(&path).expect("a cooked reading");
assert!(
!ready.checks_withheld,
"every file in the closure is read, so the rules run: {:?}",
ready.checks
);
session.store.forget(Path::new("/p/deep.h"));
assert!(
!session.is_closure_ready(&path),
"the deepest file's summary is gone"
);
let withheld = session
.diagnostics(&path)
.expect("the file's own reading is untouched — it is the closure that is cold");
assert!(
withheld.checks_withheld,
"the pull says why its checks are empty: {withheld:?}"
);
assert!(
withheld.checks.is_empty(),
"and it ran none of them: {:?}",
withheld.checks
);
}
#[test]
pub(crate) fn cuda_words_are_offered_only_by_a_cuda_project() {
let text = "void f() {\n __dev\n}\n";
let files = MemoryFiles::new().with_file("/p/a.cu", text);
let fixture = Memory::new("cuda-completion", &files);
let mut session = fixture.session_with(CompilerConfig::new().with_cuda(true));
session.did_open("/p/a.cu", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cu");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("__dev\n").expect("the fixture") + "__dev".len();
let labels = |set: &crate::CompletionSet| {
set.items
.iter()
.map(|item| item.label.clone())
.collect::<Vec<String>>()
};
let cuda = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let offered = labels(&cuda);
assert!(
offered.iter().any(|label| label == "__device__"),
"a CUDA project completes `__device__`: {offered:?}"
);
let mut session = fixture.session();
session.did_open("/p/a.cu", text);
session.index_everything();
let view = session.view_of_the_file(&path).expect("a view");
let cpp = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let offered = labels(&cpp);
assert!(
!offered.iter().any(|label| label.starts_with("__")),
"a project that is not CUDA is not offered CUDA's vocabulary: {offered:?}"
);
}
#[test]
pub(crate) fn the_built_in_variables_and_vector_types_complete_too() {
let text = "void f() {\n thr\n}\n";
let files = MemoryFiles::new().with_file("/p/a.cu", text);
let fixture = Memory::new("cuda-completion-kinds", &files);
let mut session = fixture.session_with(CompilerConfig::new().with_cuda(true));
session.did_open("/p/a.cu", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cu");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("thr\n").expect("the fixture") + "thr".len();
let set = session.completions(&view, crate::file::coordinates::FileOffset::new(at));
let labels: Vec<&str> = set.items.iter().map(|item| item.label.as_str()).collect();
assert!(
labels.contains(&"threadIdx"),
"a built-in variable completes: {labels:?}"
);
assert!(
labels.contains(&"threadIdx") && !labels.contains(&"ThreadIdx"),
"and it is the spelling that is offered"
);
}
#[test]
pub(crate) fn an_implementation_unit_sees_its_interface_units_declarations() {
let interface_text = "export module math;\n\
export struct Vec2 {\n\
\x20 double x_;\n\
\x20 double square(double value) const { return value * value; }\n\
\x20 double length() const;\n\
};\n";
let unit_text = "module;\n\
#include <cmath>\n\
module math;\n\
double Vec2::length() const { return std::sqrt(square(x_)); }\n";
let files = MemoryFiles::new()
.with_file("/p/math.cppm", interface_text)
.with_file("/p/math.cpp", unit_text);
let fixture = Memory::new("implementation-unit", &files);
let mut session = fixture.session();
session.add_project_files([
std::path::PathBuf::from("/p/math.cppm"),
std::path::PathBuf::from("/p/math.cpp"),
]);
session.did_open("/p/math.cpp", unit_text);
session.index_everything();
session.read_the_modules_a_file_imports(std::path::Path::new("/p/math.cpp"));
session.index_everything();
while session.pending_work() > 0 {
session.advance(64);
}
let path = std::path::PathBuf::from("/p/math.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = unit_text.find("x_)").expect("the fixture") + 1;
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
assert!(
matches!(&typed, Known::Yes(found) if found.type_of.contains("double")),
"`x_` must have the type the interface unit gives it: {typed:?}"
);
let at = unit_text.find("sqrt(").expect("the fixture") + "sqrt(".len();
let members = session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
if let Known::Yes(members) = members {
let names: Vec<&str> = members
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert!(
names.contains(&"x_") || names.contains(&"square"),
"a member of `Vec2` must be offered: {names:?}"
);
}
}
#[test]
pub(crate) fn a_modules_includes_define_what_a_later_condition_asks() {
let interface_text = "module;\n\
#include \"feature.h\"\n\
#include \"library.h\"\n\
export module std;\n\
export namespace std\n\
{\n\
\x20 using std::vector;\n\
}\n";
let consumer_text = "import std;\nvoid f() { std::vector<int> v; v.push_back(1); }\n";
let files = MemoryFiles::new()
.with_file("/p/std.cppm", interface_text)
.with_file("/p/feature.h", "#define FEATURE 1\n")
.with_file(
"/p/library.h",
"#if FEATURE\n#include \"detail.h\"\n#endif\n",
)
.with_file(
"/p/detail.h",
"namespace std { template <class T> struct vector { void push_back(const T &value); }; }\n",
)
.with_file("/p/a.cpp", consumer_text);
let fixture = Memory::new("a-modules-includes", &files);
let mut session = fixture.session();
session.add_project_files([
std::path::PathBuf::from("/p/std.cppm"),
std::path::PathBuf::from("/p/library.h"),
std::path::PathBuf::from("/p/detail.h"),
std::path::PathBuf::from("/p/a.cpp"),
]);
session.did_open("/p/a.cpp", consumer_text);
session.index_everything();
session.read_the_modules_a_file_imports(std::path::Path::new("/p/a.cpp"));
session.index_everything();
while session.pending_work() > 0 {
session.advance(64);
}
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = consumer_text.find("push_back").expect("the fixture") + 2;
let member = session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
let Known::Yes(member) = member else {
panic!("`v.` must be answered: {member:?}");
};
assert_eq!(
member.class, "std::vector",
"the object's type is the class the header declares"
);
assert_eq!(
member.members.members.len(),
1,
"and its member list is the class's: {:?}",
member
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect::<Vec<_>>()
);
}
#[test]
pub(crate) fn a_cook_of_text_that_has_since_changed_is_not_filed() {
let files = MemoryFiles::new().with_file("/p/a.cpp", "int main() { return 0; }\n");
let memory = Memory::new("stale-cook", &files);
let mut session = memory.session();
let path = PathBuf::from("/p/a.cpp");
session.add_project_files([path.clone()]);
session.load(&path);
session.index_everything();
let materials = session
.cooking_materials(&path)
.expect("the file has a summary and a unit");
let rendered = session
.render_a_cooked(&materials)
.expect("the renderer reads the file's own text");
let changed = "int main() { return 0 }\n";
session.did_change(&path, changed);
assert!(
session.commit_a_cooked(rendered).is_none(),
"a rendering of text that has since changed may not be filed under the new text"
);
assert!(
session.diagnostics(&path).is_none(),
"and the file has no cooked reading, so nothing answers with the old text's errors"
);
session.did_change(&path, "int main() { return 0; }\n");
session.advance(64);
assert!(
session.cook(&path).is_some(),
"the pump re-cooks the file it dropped"
);
let found = session
.diagnostics(&path)
.expect("a cooked reading of the current text");
assert_eq!(
found.errors.len(),
0,
"the text has its `;` back: {:?}",
found.errors
);
}
#[test]
pub(crate) fn a_pull_is_remembered_until_the_file_changes() {
let source = "int f() { int *p = 0; return 1; }\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let fixture = Memory::new("pull-memo", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", source);
session.index_everything();
let first = session
.diagnostics("/p/a.cpp")
.expect("the file reads")
.checks
.len();
let again = session
.diagnostics("/p/a.cpp")
.expect("the file reads")
.checks
.len();
assert_eq!(first, again, "the same reading answers the same");
let edited = "int f() { int *p = 0; return 1; }\nint g() { int *q = 0; return 2; }\n";
session.did_change("/p/a.cpp", edited);
session.advance(4);
let _ = session.cook("/p/a.cpp");
let after = session
.diagnostics("/p/a.cpp")
.expect("the edited file reads")
.checks
.len();
assert!(
after > first,
"an edit is seen, not the memory of it: {first} -> {after}"
);
}
#[test]
pub(crate) fn a_second_pull_reuses_the_inference_of_the_first() {
let source = "void f() {\n int count = \"three\";\n (void)count;\n}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", source);
let fixture = Memory::new("type-memo-across-pulls", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", source);
session.index_everything();
let first = session.diagnostics("/p/a.cpp").expect("the file reads");
assert!(!first.checks.is_empty(), "the fixture has a finding");
let (hits_before, misses_before) = session.index().type_cache_stats();
*session
.checks_memo
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
let second = session.diagnostics("/p/a.cpp").expect("the file reads");
let (hits_after, misses_after) = session.index().type_cache_stats();
assert_eq!(
first.checks.len(),
second.checks.len(),
"the same reading answers the same"
);
assert!(
hits_after > hits_before,
"the second pull answered type questions from the memo: {hits_before} -> {hits_after} hit(s), \
{misses_before} -> {misses_after} computed"
);
}
#[test]
pub(crate) fn a_parameter_of_an_out_of_class_definition_is_declared() {
let text = "namespace report {\n\
\x20 struct Entry { int key; int count; };\n\
\x20 class Archive {\n\
\x20 public:\n\
\x20 void put(const Entry& entry);\n\
\x20 private:\n\
\x20 int counts;\n\
\x20 };\n\
\x20 void Archive::put(const Entry& entry) {\n\
\x20 counts += entry.key;\n\
\x20 }\n\
}\n";
let files = MemoryFiles::new().with_file("/p/archive.cpp", text);
let fixture = Memory::new("a-parameter-of-an-out-of-class-definition", &files);
let mut session = fixture.session();
session.did_open("/p/archive.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/archive.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("entry.key").expect("the fixture") + 1;
let found = session.definition(&view, ReadingOffset::new(at));
assert!(
matches!(found, Known::Yes(_)),
"the body's `entry` is the parameter: {found:?}"
);
let Known::Yes(found) = found else {
unreachable!()
};
assert_eq!(
found.fact.name.as_str(),
"entry",
"and it is the parameter, not a type or a namespace member: {:?}",
found.fact
);
}
#[test]
pub(crate) fn a_member_defined_inside_a_namespace_declares_itself() {
let text = "namespace report {\n\
\x20 void Report::add(int line) {\n\
\x20 line = line + 1;\n\
\x20 }\n\
}\n";
let files = MemoryFiles::new().with_file("/p/report.cpp", text);
let fixture = Memory::new("a-member-defined-inside-a-namespace", &files);
let mut session = fixture.session();
session.did_open("/p/report.cpp", text);
session.index_everything();
let summary = session
.parsed_summary(Path::new("/p/report.cpp"))
.expect("the file was read");
let facts: Vec<(String, Option<String>)> = summary
.declarations
.iter()
.filter(|fact| fact.name.as_str() == "add")
.map(|fact| {
(
format!("{:?}", fact.kind),
fact.scope.as_ref().map(|scope| scope.to_string()),
)
})
.collect();
assert!(
facts
.iter()
.any(|(kind, scope)| kind == "Function" && scope.as_deref() == Some("report::Report")),
"the definition is a `Function` in `report::Report`: {facts:?}"
);
let view = session
.view_of_the_file(Path::new("/p/report.cpp"))
.expect("a view");
let at = text.find("line + 1").expect("the fixture");
assert!(
matches!(
session.definition(&view, ReadingOffset::new(at)),
Known::Yes(_)
),
"the parameter is still declared"
);
}