use super::{OpenDocuments, Session, SessionFiles, queue_key};
use crate::file::coordinates::ReadingOffset;
use crate::file::paths::{DiskFiles, FileProvider, MemoryFiles};
use crate::include::config::{CommandLineMacro, CompilerConfig};
use crate::include::toolchain::{Toolchain, ToolchainSource};
use crate::index::watch::{FileEvent, WatchFilter};
use crate::index::{Priority, StepOutcome};
use crate::symbol::Known;
use std::path::{Path, PathBuf};
struct Memory<'a> {
files: &'a MemoryFiles,
documents: OpenDocuments,
providers: SessionFiles<MemoryFiles>,
root: PathBuf,
}
impl<'a> Memory<'a> {
fn new(name: &str, files: &'a MemoryFiles) -> Self {
let root = std::env::temp_dir().join("cppls-session-tests").join(name);
let _ = std::fs::remove_dir_all(&root);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents.clone(), files.clone());
Memory {
files,
documents,
providers,
root,
}
}
fn session(&self) -> Session<MemoryFiles> {
self.session_with(CompilerConfig::default())
}
fn session_with(&self, config: CompilerConfig) -> Session<MemoryFiles> {
Session::with_config(
&self.root,
self.providers.clone(),
WatchFilter::new(&self.root),
config,
)
}
fn text(&self, path: &str) -> Option<String> {
self.documents
.text(path)
.or_else(|| self.files.read(Path::new(path)))
}
}
impl Drop for Memory<'_> {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
fn paths(steps: &[crate::index::Step]) -> Vec<String> {
steps
.iter()
.map(|step| step.path.to_string_lossy().replace('\\', "/"))
.collect()
}
#[test]
fn a_rendering_is_not_left_in_the_cache_for_the_next_session() {
let api = "#ifdef FROM_THE_SOURCE\nstruct Live { int a; };\n#else\nstruct Live { long b; };\n#endif\n";
let main = "#define FROM_THE_SOURCE 1\n#include \"api.h\"\nLive live;\n";
let files = MemoryFiles::new()
.with_file("/p/api.h", api)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-rendering-is-not-cached", &files);
{
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let reading = session
.read_a_looked_at_unit()
.expect("the program is read");
assert!(reading.files >= 2, "two files: {reading:?}");
assert!(
session
.index()
.cooked_declarations(Path::new("/p/api.h"))
.is_some_and(|facts| facts.iter().any(|fact| fact.name == "Live")),
"the program's reading of the header is in this session"
);
}
let mut session = fixture.session();
session.add_project_files([std::path::PathBuf::from("/p/api.h")]);
session.index_everything();
let summary = session
.index()
.summary(Path::new("/p/api.h"))
.expect("the header is read")
.clone();
let live: Vec<_> = summary
.declarations
.iter()
.filter(|fact| fact.name == "Live")
.collect();
assert_eq!(
live.len(),
1,
"the file declares `Live` once when it is read on its own: {live:?}"
);
assert_eq!(
live[0].range.start_offset,
api.find("struct Live { long b; }").expect("the fixture"),
"and it is the branch that file has when nothing defines `FROM_THE_SOURCE`"
);
}
#[test]
fn the_sharing_cache_survives_a_restart() {
let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; };\n";
let source = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
let files = MemoryFiles::new()
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", source);
let fixture = Memory::new("the-sharing-cache-survives-a-restart", &files);
let written = {
let mut session = fixture.session();
session.did_open("/p/api.h", source);
session.index_everything();
session
.save_the_sharing()
.expect("the cache directory is the fixture's")
};
assert!(
written > 0,
"a run that walked files must have something to write"
);
let empty = fixture.session();
assert_eq!(
empty.walk_contributions_held(),
0,
"a new store holds nothing"
);
let session = fixture.session();
let restored = session.load_the_sharing();
assert_eq!(restored, written, "what was written is what is read back");
assert_eq!(
session.walk_contributions_held(),
restored,
"and it is in the cache the walk consults, not merely counted"
);
}
#[test]
fn a_declaration_only_a_macro_makes_is_found_once_the_session_has_cooked_the_file() {
let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let source = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
let files = MemoryFiles::new()
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", source);
let fixture = Memory::new("cooked-reading-is-indexed", &files);
let mut session = fixture.session();
session.did_open("/p/api.h", source);
session.advance(1);
let before = session.index().definition("HWND__", Path::new("/p/api.h"));
assert!(
matches!(before, Known::Unknown(_)),
"the file's own text does not declare what the macro declares: {before:?}"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/api.h"))
.is_none(),
"and nothing has cooked it yet"
);
session.index_everything();
let after = session.index().definition("HWND__", Path::new("/p/api.h"));
let Known::Yes(found) = after else {
panic!("the cooked reading declares it: {after:?}");
};
assert_eq!(found.file, Path::new("/p/api.h"));
let at = found.fact.range;
let written = &source[at.start_offset..at.end_offset()];
assert!(
written.contains("DECLARE_HANDLE"),
"the declaration is reported at the invocation: {written:?}"
);
let cooked = session.cook_the_open_files();
assert_eq!(cooked.len(), 1, "api.h is the open file");
let (path, reading) = &cooked[0];
assert_eq!(path, Path::new("/p/api.h"));
assert!(
reading.declarations >= 2,
"the struct, its member and the typedef are declarations here: {reading:?}"
);
assert!(
reading.only_after_expansion >= 2,
"`HWND__` and `HWND` exist only after expansion: {reading:?}"
);
assert_eq!(reading.mapped.dropped, 0, "every range landed in the file");
}
#[test]
fn a_header_the_user_never_opened_is_cooked_when_a_request_names_it() {
let handle = "#include \"deep.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let api = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
let main = "#include \"api.h\"\nHWND h;\n";
let files = MemoryFiles::new()
.with_file("/p/deep.h", "#define DEEP 1\n")
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", api)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-named-file-is-cooked", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let after = session
.index()
.definition("HWND__", Path::new("/p/main.cpp"));
let Known::Yes(found) = after else {
panic!("`api.h`'s cooked reading declares it: {after:?}");
};
assert_eq!(
found.file,
Path::new("/p/api.h"),
"the file that invoked the macro, which nobody opened"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/handle.h"))
.is_some(),
"the level under a direct include is where the library keeps what a reader asks for"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/deep.h"))
.is_some(),
"the third level is where a header's own class is declared, and it is cooked"
);
session.want_cooked_reading(Path::new("/p/handle.h"));
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/handle.h"))
.is_some(),
"and then it has one"
);
}
#[test]
fn a_file_that_does_not_balance_its_braces_is_named_and_still_read() {
let files = MemoryFiles::new()
.with_file(
"/p/broken.h",
"namespace vc_attributes {\nstruct NotAClosure { int x; };\n",
)
.with_file(
"/p/good.h",
"namespace good {\nstruct Inside { int y; };\n}\n",
)
.with_file(
"/p/main.cpp",
"#include \"broken.h\"\n#include \"good.h\"\nInside i;\n",
);
let fixture = Memory::new("a-unit-that-does-not-balance", &files);
let mut session = fixture.session();
session.did_open(
"/p/main.cpp",
"#include \"broken.h\"\n#include \"good.h\"\nInside i;\n",
);
session.index_everything();
let reading = session
.read_the_unit(Path::new("/p/main.cpp"))
.expect("the unit reads");
assert_eq!(
reading.unbalanced.len(),
1,
"one file does not balance: {reading:?}"
);
assert!(
reading.unbalanced[0].ends_with("broken.h"),
"and it is the one that opens a brace it never closes: {reading:?}"
);
let inside = session
.index()
.cooked_declarations(Path::new("/p/good.h"))
.expect("good.h is part of the program");
let inside = inside
.iter()
.find(|fact| fact.name == "Inside")
.expect("the class is declared there");
assert_eq!(
inside.scope.as_deref(),
Some("good"),
"a scope does not cross a file boundary, so `good.h` is scoped by its own namespace"
);
let broken = session
.index()
.cooked_declarations(Path::new("/p/broken.h"))
.expect("the unbalanced file's own reading is filed too");
let struct_fact = broken
.iter()
.find(|fact| fact.name == "NotAClosure")
.expect("the struct is declared in the file that does not balance");
assert_eq!(
struct_fact.scope.as_deref(),
Some("vc_attributes"),
"and at the scope its own text gives it: {broken:?}"
);
}
#[test]
fn a_single_bracket_attribute_no_longer_props_the_program_open() {
let leaky = "REPEATABLE\n[source_annotation_attribute( 1 )]\nstruct Pre\n{\n int Deref;\n};\n";
let main = "#include \"broken.h\"\n#include \"good.h\"\nInside i;\n";
let files = MemoryFiles::new()
.with_file("/p/broken.h", leaky)
.with_file(
"/p/good.h",
"namespace good {\nstruct Inside { int y; };\n}\n",
)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-scope-that-used-to-leak", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let reading = session
.read_the_unit(Path::new("/p/main.cpp"))
.expect("the unit reads");
assert!(
reading.unbalanced.is_empty(),
"the text balances, and now the parse does too: {reading:?}"
);
assert!(
reading.unbalanced.is_empty(),
"nothing leaked and nothing is out of balance: {reading:?}"
);
let pre = session
.index()
.cooked_declarations(Path::new("/p/broken.h"))
.expect("the reading was filed")
.iter()
.find(|fact| fact.name == "Pre")
.expect("the struct the attribute precedes is declared there");
assert_eq!(
pre.scope, None,
"and it is at file scope, not inside anything"
);
let inside = session
.index()
.cooked_declarations(Path::new("/p/good.h"))
.expect("the reading was filed")
.iter()
.find(|fact| fact.name == "Inside")
.expect("the class is declared there")
.scope
.clone();
assert_eq!(
inside.as_deref(),
Some("good"),
"the file after it is read as itself"
);
}
#[test]
fn a_file_that_does_not_balance_costs_nothing_but_a_name() {
let good = "namespace good {\nstruct Good { int x; };\n";
let other = "struct Other { int y; };\n";
let main = "#include \"good.h\"\n#include \"other.h\"\nOther o;\n";
let files = MemoryFiles::new()
.with_file("/p/good.h", good)
.with_file("/p/other.h", other)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-scope-that-really-leaks", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let reading = session
.read_the_unit(Path::new("/p/main.cpp"))
.expect("the unit reads");
assert_eq!(
reading.unbalanced.len(),
1,
"one file does not balance, and it is reported: {reading:?}"
);
let other_fact = session
.index()
.cooked_declarations(Path::new("/p/other.h"))
.expect("other.h is part of the program")
.iter()
.find(|fact| fact.name == "Other")
.map(|fact| fact.scope.clone())
.expect("the struct is declared there");
assert_eq!(
other_fact, None,
"the file after the unbalanced one is at file scope, not inside `good::`: {reading:?}"
);
let good_facts = session
.index()
.cooked_declarations(Path::new("/p/good.h"))
.expect("the leaking file's own reading is filed too");
assert!(
good_facts.iter().any(|fact| fact.name == "Good"),
"the struct is declared in the file that does not balance: {good_facts:?}"
);
}
#[test]
fn a_program_whose_files_keep_their_scopes_quarantines_nothing() {
let main = "#include \"a.h\"\n#include \"b.h\"\nint main_variable;\n";
let files = MemoryFiles::new()
.with_file("/p/a.h", "namespace a {\nstruct A { int x; };\n}\n")
.with_file("/p/b.h", "namespace b {\n#include \"c.h\"\n}\n")
.with_file("/p/c.h", "struct C { int z; };\n")
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-program-that-does-not-leak", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let reading = session
.read_the_unit(Path::new("/p/main.cpp"))
.expect("the unit reads");
assert!(
reading.unbalanced.is_empty(),
"a scope that closes around an `#include` is in balance: {reading:?}"
);
let c = session
.index()
.cooked_declarations(Path::new("/p/c.h"))
.expect("filed")
.iter()
.find(|fact| fact.name == "C")
.expect("declared")
.scope
.clone();
assert_eq!(
c.as_deref(),
Some("b"),
"the namespace `b.h` opens around its include still holds `C`"
);
}
#[test]
fn a_unit_read_reads_the_whole_program_once() {
let handle = "#include \"deep.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let api = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n";
let main = "#include \"api.h\"\nHWND h;\n";
let files = MemoryFiles::new()
.with_file("/p/deep.h", "#define DEEP 1\n")
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", api)
.with_file("/p/main.cpp", main)
.with_file("/p/other.cpp", "#include \"other.h\"\nvoid g() { }\n")
.with_file("/p/other.h", "struct Unrelated { int y; };\n");
let fixture = Memory::new("a-unit-read", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/handle.h"))
.is_some(),
"the level under a direct include is cooked"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/deep.h"))
.is_some(),
"and the level under that is cooked too — the bound moved when `std::string` needed it"
);
let reading = session
.read_the_unit(Path::new("/p/main.cpp"))
.expect("the unit reads");
assert_eq!(reading.root, Path::new("/p/main.cpp"));
assert!(
reading.files >= 3,
"the program is three files: {reading:?}"
);
assert_eq!(
reading.files_with_tokens, 2,
"two of them write tokens; a file of directives writes none: {reading:?}"
);
assert_eq!(reading.missing, 0, "every file had text: {reading:?}");
for (file, why) in [
(
"/p/handle.h",
"a file the program is made of is read with it",
),
("/p/deep.h", "including the one the per-file bound left out"),
] {
assert!(
session
.index()
.cooked_declarations(Path::new(file))
.is_some(),
"{why}"
);
}
let after = session
.index()
.definition("HWND__", Path::new("/p/main.cpp"));
let Known::Yes(found) = after else {
panic!("`api.h`'s cooked reading declares it: {after:?}");
};
assert_eq!(found.file, Path::new("/p/api.h"));
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_none(),
"a file no program reads and nobody opens has no reading"
);
}
#[test]
fn a_program_is_read_when_the_reader_stops_editing() {
let handle = "#include \"mid.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let main = "#include \"api.h\"\nHWND h;\n";
let files = MemoryFiles::new()
.with_file("/p/deep.h", "#define DEEP 1\n")
.with_file("/p/mid.h", "#include \"deep.h\"\nstruct Mid { int x; };\n")
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-program-when-the-typing-stops", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let steps = session.advance(4);
assert!(
!session
.index()
.cooked_declarations(Path::new("/p/deep.h"))
.is_some(),
"nothing read the program while the reader was typing: {:?}",
paths(&steps)
);
std::thread::sleep(super::UNTIL_A_UNIT_MAY_BE_READ + std::time::Duration::from_millis(100));
session.advance(1);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/deep.h"))
.is_some(),
"the program's own files are read with it, two includes below the file the reader opened"
);
let found = session
.index()
.definition("HWND__", Path::new("/p/main.cpp"));
let Known::Yes(found) = found else {
panic!("the macro's declaration is in the index after the program was read: {found:?}");
};
assert_eq!(
found.file,
Path::new("/p/api.h"),
"filed under the file that invoked the macro"
);
}
#[test]
fn a_program_too_large_to_read_at_once_is_left_alone() {
let line = "// padding padding padding padding\n";
let big = line.repeat(super::THE_LARGEST_PROGRAM_READ_AT_ONCE / line.len() + 1);
assert!(big.len() > super::THE_LARGEST_PROGRAM_READ_AT_ONCE);
let handle = "#include \"big.h\"\n#include \"mid.h\"\n#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let main = "#include \"api.h\"\nHWND h;\n";
let files = MemoryFiles::new()
.with_file("/p/big.h", big)
.with_file("/p/deep.h", "#define DEEP 1\n")
.with_file("/p/mid.h", "#include \"deep.h\"\nstruct Mid { int x; };\n")
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-program-too-large", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
std::thread::sleep(super::UNTIL_A_UNIT_MAY_BE_READ + std::time::Duration::from_millis(100));
session.advance(1);
assert!(
!session
.index()
.cooked_declarations(Path::new("/p/deep.h"))
.is_some(),
"the program is over the budget, so it is not read in one piece"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/api.h"))
.is_some(),
"the per-file reading is unaffected by the budget"
);
}
#[test]
fn a_private_namespaced_alias_still_resolves_in_a_return_type() {
let text = "namespace std {\n\
template <typename T> struct _Tree_base { using iterator = T *; };\n\
template <typename T> struct _Tree {\n\
public:\n\
\x20 _Mybase::iterator find(int key) const;\n\
private:\n\
\x20 using _Mybase = _Tree_base<T>;\n\
};\n\
}\n\
void f(std::_Tree<int> &t) {\n\
\x20 t.find(1);\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-private-namespaced-alias", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("find(1)").expect("the fixture") + "find".len();
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(typed) = typed else {
panic!("`t.find(1)` must have a type: {typed:?}");
};
assert_eq!(
typed.type_of, "int*",
"`_Mybase::iterator` is `_Tree_base<int>::iterator` — a private alias still names a type here"
);
}
#[test]
fn a_calls_return_type_is_a_qualified_alias_of_its_own_class() {
let text = "template <typename T> struct base { using iterator = T *; };\n\
template <typename T> struct tree {\n\
\x20 using _Mybase = base<T>;\n\
\x20 _Mybase::iterator find(int key) const;\n\
};\n\
void f(tree<int> &t) {\n\
\x20 t.find(1);\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-qualified-alias-return", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("find(1)").expect("the fixture") + "find".len();
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(typed) = typed else {
panic!("`t.find(1)` must have a type: {typed:?}");
};
assert_eq!(
typed.type_of, "int*",
"`_Mybase::iterator` is `base<int>::iterator`, which is `int*`"
);
}
#[test]
fn a_maps_find_reaches_the_element_when_the_comparator_is_written() {
let text = "template <typename A, typename B> struct pair { A first; B second; };\n\
template <typename K, typename V, typename C> struct map_like {\n\
\x20 pair<const K, V> find(const K &key) const;\n\
};\n\
void f(map_like<int, float, int> &m) {\n\
\x20 m.find(1)->second;\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-maps-find-with-a-comparator", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("find(1)").expect("the fixture") + "find".len();
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(typed) = typed else {
panic!("`m.find(1)` must have a type: {typed:?}");
};
assert!(
typed.type_of.contains("pair") && typed.type_of.contains("float"),
"the element of the map, not the iterator: {:?}",
typed.type_of
);
let second = text.find("->second").expect("the fixture") + "->".len();
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(second));
let Known::Yes(found) = found else {
panic!("`find(1)->second` must resolve: {found:?}");
};
assert_eq!(found.found[0].fact.name, "second");
}
#[test]
fn a_calls_iterator_answer_reaches_the_element_through_a_trait_alias() {
let text = "template <bool B, class T, class F> struct conditional {};\n\
template <class T, class F> struct conditional<false, T, F> { using type = F; };\n\
template <bool B, class T, class F>\n\
using conditional_t = typename conditional<B, T, F>::type;\n\
struct element { int first; int second; };\n\
template <typename T> struct tree_iterator {\n\
\x20 using pointer = conditional_t<false, void, T> *;\n\
\x20 pointer operator->() const;\n\
};\n\
struct map_like {\n\
\x20 using value_type = element;\n\
\x20 tree_iterator<value_type> find(int key) const;\n\
};\n\
void f(map_like &m) {\n\
\x20 m.find(1)->second = 2;\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-calls-iterator-through-a-trait", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("->second").expect("the fixture") + "->".len();
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("`m.find(1)->second` must resolve: {found:?}");
};
assert_eq!(
(
found.found[0].fact.name.as_str(),
found.found[0].fact.scope.as_deref()
),
("second", Some("element")),
"the call's iterator, its `pointer` alias, and the trait alias in it"
);
}
#[test]
fn a_constants_value_is_folded_and_an_enumerators_initialiser_reads_it() {
let text = "#define UCHAR_MAX 0xff\n\
const int FIRST_RESERVED = UCHAR_MAX + 1;\n\
enum Kind { TK_AND = FIRST_RESERVED, TK_BREAK, TK_SHIFT = 1 << 4 };\n\
int plain = 5;\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-folded-constant", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let value_at = |written: &str| {
let at = text.find(written).expect("the fixture");
session.constant_value_at(&view, crate::file::coordinates::ReadingOffset::new(at))
};
assert_eq!(
value_at("FIRST_RESERVED = "),
Some(256),
"`UCHAR_MAX + 1` folds: `0xff` + 1"
);
assert_eq!(
value_at("TK_AND"),
Some(256),
"the enumerator names the constant"
);
assert_eq!(
value_at("TK_BREAK"),
Some(257),
"and the next one counts on"
);
assert_eq!(value_at("TK_SHIFT"), Some(16), "`1 << 4` folds");
assert_eq!(
value_at("plain = 5"),
None,
"a non-const variable has a value but not a constant one"
);
}
#[test]
fn a_member_list_is_reached_through_an_alias_written_absolutely() {
let text = "namespace std {\n\
template <class T> struct basic_string {\n\
\x20 void append(const T &value);\n\
\x20 int size() const;\n\
};\n\
using string = ::std::basic_string<char>;\n\
}\n\
void g() {\n\
\x20 std::string s;\n\
\x20 s.\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("an-absolute-alias-target", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("s.\n").expect("the fixture") + "s.".len();
let completions =
session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
let Known::Yes(completions) = completions else {
panic!("`s.` must list `basic_string`'s members: {completions:?}");
};
let mut names: Vec<&str> = completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
names.sort_unstable();
names.dedup();
assert_eq!(
names,
vec!["append", "size"],
"the alias's absolute target names a class the index has"
);
}
#[test]
fn a_calls_overload_is_the_one_its_arguments_select() {
let text = "namespace std {\n\
struct string { };\n\
struct wstring { };\n\
template <class... T> struct format_string { };\n\
template <class... T> struct wformat_string { };\n\
template <class... T> string format(const format_string<T...>, T &&...);\n\
template <class... T> wstring format(const wformat_string<T...>, T &&...);\n\
}\n\
void g() {\n\
\x20 auto narrow = std::format(\"x {}\", 1);\n\
\x20 auto wide = std::format(L\"x {}\", 1);\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-calls-selected-overload", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
for (written, expected) in [("auto narrow", "string"), ("auto wide", "wstring")] {
let at = text.find(written).expect("the fixture") + "auto ".len();
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(typed) = typed else {
panic!("`{written} = std::format(…)` must have a type: {typed:?}");
};
assert_eq!(
typed.type_of, expected,
"the arguments select the overload — {written}"
);
}
}
#[test]
fn a_name_whose_declarations_disagree_answers_with_the_disagreement() {
let header = "int f();\n";
let other = "double f();\n";
let text = "#include \"a.h\"\n#include \"b.h\"\nvoid g() {\n auto x = f();\n}\n";
let files = MemoryFiles::new()
.with_file("/p/a.h", header)
.with_file("/p/b.h", other)
.with_file("/p/a.cpp", text);
let fixture = Memory::new("a-disagreeing-name", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("auto x").expect("the fixture") + "auto ".len();
let typed = session.type_at(&view, crate::file::coordinates::ReadingOffset::new(at));
match typed {
Known::Unknown(crate::UnknownReason::Ambiguous(name)) => assert_eq!(&*name, "f"),
other => panic!("`int f()` and `double f()` agree on no type: {other:?}"),
}
}
#[test]
fn an_unscoped_enumerations_member_is_visible_in_the_enclosing_scope() {
let text = "enum { MyClass = 123, AnotherClass };\n\
enum class Scoped { Hidden };\n\
int main() {\n\
\x20 int a = AnotherClass;\n\
\x20 int b = Hidden;\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("an-unscoped-enum", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("= AnotherClass").expect("the fixture") + 2;
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("a bare `AnotherClass` must resolve: {found:?}");
};
assert_eq!(
found.found[0].fact.name, "AnotherClass",
"the enumerator, not the enumeration"
);
let classified: Vec<(String, crate::semantic::NameKind)> = session
.classified_names(&view)
.into_iter()
.map(|name| {
(
text[name.range.start_offset..]
.chars()
.take(12)
.collect::<String>(),
name.kind,
)
})
.collect();
let kinds: Vec<&crate::semantic::NameKind> = classified
.iter()
.filter(|(spelled, _)| spelled.starts_with("AnotherClass"))
.map(|(_, kind)| kind)
.collect();
assert!(
kinds.contains(&&crate::semantic::NameKind::EnumMember),
"the use is an enum member too, not just the declaration: {classified:?}"
);
assert!(
kinds.len() >= 2,
"both the declaration and the use are coloured: {classified:?}"
);
let declaration = text.find("AnotherClass }").expect("the fixture");
let found = session.definitions(
&view,
crate::file::coordinates::ReadingOffset::new(declaration),
);
let Known::Yes(found) = found else {
panic!("the declaration of `AnotherClass` must answer: {found:?}");
};
assert_eq!(found.found[0].fact.name, "AnotherClass");
let hidden = text.find("= Hidden").expect("the fixture") + 2;
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(hidden));
assert!(
!matches!(&found, Known::Yes(found) if found.found[0].fact.name == "Hidden"),
"a scoped enumeration's member is not visible here: {found:?}"
);
}
#[test]
fn a_trait_alias_selects_the_specialization_its_arguments_name() {
let text = "struct Item { int value; void grow(); };\n\
template <bool B, class T, class F> struct conditional {};\n\
template <class T, class F> struct conditional<false, T, F> { using type = F; };\n\
template <bool B, class T, class F>\n\
using conditional_t = typename conditional<B, T, F>::type;\n\
template <typename T> struct handle {\n\
\x20 using value_type = conditional_t<false, void, T>;\n\
\x20 value_type *operator->() const;\n\
};\n\
void g(handle<Item> h) {\n\
\x20 h->\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("a-trait-alias-selects", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let written = "h->";
let at = text.find(written).expect("the fixture") + written.len();
let completions =
session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
let Known::Yes(completions) = completions else {
panic!("`{written}` must reach `Item`: {completions:?}");
};
let names: Vec<&str> = completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(
completions.class, "Item",
"`conditional_t<false, void, T>` is `T`, and the arrow reaches it ({names:?})"
);
}
#[test]
fn an_arrow_through_an_alias_reaches_the_pointee() {
let text = "template <typename K, typename V> struct pair {\n\
\x20 K first;\n\
\x20 V second;\n\
};\n\
template <typename T> struct iterator {\n\
\x20 using pointer = T *;\n\
\x20 pointer operator->() const;\n\
};\n\
template <typename K, typename V> struct map {\n\
\x20 using value_type = pair<const K, V>;\n\
\x20 iterator<value_type> find(const K &key) const;\n\
};\n\
void f(map<int, float> &m) {\n\
\x20 m.find(1)->second = 2;\n\
}\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("an-arrow-through-an-alias", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("->second").expect("the fixture") + "->".len();
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("`find()->second` must resolve through `pointer`: {found:?}");
};
assert_eq!(
(
found.found[0].fact.name.as_str(),
found.found[0].fact.scope.as_deref()
),
("second", Some("pair")),
"the arrow's `pointer` is the value type, and `second` is its member"
);
}
#[test]
fn an_out_of_line_definition_records_the_type_it_writes() {
let text = "namespace std {\n\
template <typename K, typename V> struct map { V &at(const K &key); };\n\
}\n\
struct Lexer {\n\
\x20 static std::map<int, int> Reserved;\n\
\x20 std::size_t GetLine(std::size_t offset) const;\n\
};\n\
std::map<int, int> Lexer::Reserved = {};\n\
std::size_t Lexer::GetLine(std::size_t offset) const { return offset; }\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("an-out-of-line-definition", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let summary = session.index().summary(&path).expect("the file is read");
for (name, expected) in [
("Reserved", "std::map<int, int>"),
("GetLine", "std::size_t"),
] {
let written: Vec<Option<&str>> = summary
.declarations
.iter()
.filter(|fact| fact.name == name)
.map(|fact| fact.type_of.as_deref().or(fact.returns.as_deref()))
.collect();
assert!(
written.contains(&Some(expected)),
"`{name}` declares `{expected}`, and one of its facts must say so: {written:?}"
);
let qualified = format!("::{name}");
assert!(
!written
.iter()
.any(|found| found.is_some_and(|found| found.ends_with(&qualified))),
"and none of them may record the declarator's own qualified name (`…{qualified}`): {written:?}"
);
}
}
#[test]
fn a_class_templates_members_are_read_through_the_uses_arguments() {
let text = "template <typename T> struct Box {\n\
\x20 T &operator[](int index);\n\
\x20 T *operator->();\n\
};\n\
template <typename T> struct AliasBox {\n\
\x20 using reference = T &;\n\
\x20 reference operator[](int index);\n\
};\n\
struct Item { int value; void grow(); };\n\
void f(Box<Item> box) {\n\
\x20 box[0].value;\n\
\x20 box->grow();\n\
}\n\
void g(AliasBox<Item> box) {\n\
\x20 alias[0].value;\n\
}\n";
let text = text.replace("alias[0]", "box[0]");
let files = MemoryFiles::new().with_file("/p/a.cpp", &text);
let fixture = Memory::new("a-class-templates-members", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", &text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let mut searched = 0usize;
for (written, expected) in [
("box[0].value", ("value", Some("Item"))),
("box->grow", ("grow", Some("Item"))),
("box[0].value", ("value", Some("Item"))),
] {
let found_at = text[searched..]
.find(written)
.map(|at| searched + at)
.expect("the fixture writes it");
searched = found_at + written.len();
let at = found_at + written.len() - expected.0.len();
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("`{written}` must resolve to the element's member: {found:?}");
};
assert_eq!(
(
found.found[0].fact.name.as_str(),
found.found[0].fact.scope.as_deref()
),
expected,
"`{written}` is the element's member"
);
}
}
#[test]
fn an_arrow_through_a_member_template_reaches_the_element_type() {
let header = "template <typename T> struct Holder {\n\
\x20 using element_type = T;\n\
};\n\
template <typename T> struct Handle {\n\
\x20 private:\n\
\x20 using _Mybase = Holder<T>;\n\
\x20 public:\n\
\x20 using typename _Mybase::element_type;\n\
\x20 template <typename U = T, int = 0>\n\
\x20 U *operator->() const;\n\
};\n";
let source = "#include \"handle.h\"\n\
struct Item { int value; void grow(); };\n\
void g(Handle<Item> file) {\n\
\x20 file->\n\
}\n";
let files = MemoryFiles::new()
.with_file("/p/handle.h", header)
.with_file("/p/a.cpp", source);
let fixture = Memory::new("an-arrow-through-a-member-template", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", source);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let written = "file->";
let at = source.find(written).expect("the fixture") + written.len();
let completions =
session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
let Known::Yes(completions) = completions else {
panic!("`{written}` must list the element's members: {completions:?}");
};
let names: Vec<&str> = completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(
completions.class, "Item",
"the arrow reaches `element_type`, not the member template's parameter name ({names:?})"
);
}
#[test]
fn an_arrow_through_a_base_named_by_a_member_alias_in_another_file() {
let base = "namespace std {\n\
template <typename T> class _Ptr_base;\n\
template <typename T> struct remove_extent { using type = T; };\n\
template <typename T> using remove_extent_t = typename remove_extent<T>::type;\n\
template <typename T> class _Ptr_base {\n\
public:\n\
\x20 using element_type = remove_extent_t<T>;\n\
};\n\
}\n";
let memory = "#include \"ptr_base.h\"\nnamespace std {\n\
template <typename T> class shared_ptr {\n\
private:\n\
\x20 using _Mybase = _Ptr_base<T>;\n\
public:\n\
\x20 using typename _Mybase::element_type;\n\
\x20 template <typename U = T, int = 0>\n\
\x20 U *operator->() const;\n\
\x20 element_type *get() const;\n\
};\n\
}\n";
let source = "#include \"memory.h\"\n\
struct Item { int value; void grow(); };\n\
void g(std::shared_ptr<Item> file) {\n\
\x20 file->\n\
}\n";
let files = MemoryFiles::new()
.with_file("/p/ptr_base.h", base)
.with_file("/p/memory.h", memory)
.with_file("/p/a.cpp", source);
let fixture = Memory::new("an-arrow-through-a-real-shape", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", source);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let written = "file->";
let at = source.find(written).expect("the fixture") + written.len();
let completions =
session.member_completions(&view, crate::file::coordinates::FileOffset::new(at));
let Known::Yes(completions) = completions else {
panic!("`{written}` must list the element's members: {completions:?}");
};
let names: Vec<&str> = completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(
completions.class, "Item",
"the arrow reaches the base alias's `element_type` ({names:?})"
);
}
#[test]
fn a_class_templates_alias_return_is_substituted_too() {
let header = "template <typename T> struct AliasBox {\n\
\x20 using reference = T &;\n\
\x20 reference operator[](int index);\n\
};\n";
let source = "#include \"box.h\"\n\
struct Item { int value; void grow(); };\n\
void g(AliasBox<Item> box) {\n\
\x20 box[0].value;\n\
}\n";
let files = MemoryFiles::new()
.with_file("/p/box.h", header)
.with_file("/p/a.cpp", source);
let fixture = Memory::new("a-class-templates-alias", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", source);
session.add_project_files([std::path::PathBuf::from("/p/a.cpp")]);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let written = "box[0].value";
let at = source.find(written).expect("the fixture") + written.len() - "value".len();
let found = session.definitions(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("`{written}` must resolve to the element's member: {found:?}");
};
assert_eq!(
(
found.found[0].fact.name.as_str(),
found.found[0].fact.scope.as_deref()
),
("value", Some("Item")),
"the alias's target is the use's argument, not the class's parameter name"
);
}
#[test]
fn an_anonymous_enum_declares_its_enumerators() {
let text = "enum { LAJF, LBJF };\nvoid f() { int x = LAJF; }\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("an-anonymous-enum", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
for name in ["LAJF", "LBJF"] {
let found = session.index().definitions(name, &path);
let Known::Yes(found) = found else {
panic!("`{name}` is declared by the anonymous enum: {found:?}");
};
assert_eq!(
found.found[0].fact.scope, None,
"an unnamed enum has no scope name"
);
}
let view = session.view_of_the_file(&path).expect("a view");
let names = session.classified_names(&view);
let lajf = names
.iter()
.find(|name| name.range.start_offset == text.find("LAJF").expect("the fixture"))
.expect("`LAJF` is a name");
assert_eq!(lajf.kind, crate::semantic::NameKind::EnumMember);
}
#[test]
fn a_member_through_an_operator_arrow_is_the_pointees() {
let text = "template <typename T> struct handle { T *operator->(); void reset(); };\n\
struct Config { int Generate(int uri); };\n\
void g(handle<Config> config) { config->Generate(1); }\n";
let files = MemoryFiles::new().with_file("/p/a.cpp", text);
let fixture = Memory::new("through-an-arrow", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", text);
session.index_everything();
let path = std::path::PathBuf::from("/p/a.cpp");
let view = session.view_of_the_file(&path).expect("a view");
let at = text.find("Generate(1)").expect("the fixture") + 1;
let found = session.definition(&view, crate::file::coordinates::ReadingOffset::new(at));
let Known::Yes(found) = found else {
panic!("`config->Generate` must resolve through `operator->`: {found:?}");
};
assert_eq!(
(found.fact.name.as_str(), found.fact.scope.as_deref()),
("Generate", Some("Config")),
"the member is the pointee's"
);
let after = text.find("config->Generate").expect("the fixture") + "config->".len();
let completions =
session.member_completions(&view, crate::file::coordinates::FileOffset::new(after));
let Known::Yes(completions) = completions else {
panic!("`config->` must list the pointee's members: {completions:?}");
};
assert_eq!(completions.class, "Config");
let names: Vec<&str> = completions
.members
.members
.iter()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(names, ["Generate"], "and not the handle's own list");
}
#[test]
fn a_project_can_decline_to_read_its_other_roots() {
let shared = "struct Shared { int size; };\n";
let a = "#include \"shared.h\"\n";
let b = "#include \"shared.h\"\nint from_b = 1;\n";
let files = MemoryFiles::new()
.with_file("/p/shared.h", shared)
.with_file("/p/a.cpp", a)
.with_file("/p/b.cpp", b)
.with_file(
"/p/.cppls.toml",
"[index]\nread_the_whole_project = false\n",
);
let fixture = Memory::new("a-project-declines", &files);
let mut session = crate::Session::with_config(
"/p",
fixture.providers.clone(),
crate::WatchFilter::new("/p"),
crate::CompilerConfig::default(),
);
session.add_project_files([
std::path::PathBuf::from("/p/a.cpp"),
std::path::PathBuf::from("/p/b.cpp"),
]);
session.did_open("/p/a.cpp", a);
session.index_everything();
session.pretend_a_pause(std::time::Duration::from_millis(1_100));
let first = session
.read_a_program_now()
.expect("the reader's own program");
assert_eq!(first.root, std::path::Path::new("/p/a.cpp"));
session.pretend_a_pause(std::time::Duration::from_secs(60));
assert!(
session.read_a_program_now().is_none(),
"the project declined its unopened roots"
);
assert!(
session.the_wait_before_a_program_may_be_read().is_none(),
"so the pump has nothing to wait for"
);
assert!(
!session
.index()
.the_program_that_read(std::path::Path::new("/p/b.cpp"))
.is_some(),
"and `b.cpp` was not read"
);
}
#[test]
fn a_body_edit_does_not_cost_the_program_again() {
let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let main = "#include \"api.h\"\nHWND h;\n";
let body_edit = "#include \"api.h\"\nHWND h;\nint padding;\n";
let directive_edit = "#include \"api.h\"\nHWND h;\nint padding;\n#define PAD 1\n";
let files = MemoryFiles::new()
.with_file("/p/handle.h", handle)
.with_file("/p/api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n")
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-body-edit-keeps-the-program", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let reading = session
.read_a_looked_at_unit()
.expect("the reader has a file open, so there is a program to read");
assert!(
reading.files >= 3,
"the program is three files: {reading:?}"
);
assert!(
session.the_wait_before_a_program_may_be_read().is_none(),
"one program per root, until something changes its shape"
);
session.did_change("/p/main.cpp", body_edit);
assert!(
session.the_wait_before_a_program_may_be_read().is_none(),
"a declaration added to a body does not make the program owed again"
);
session.advance(4);
assert!(
session
.index()
.summary(Path::new("/p/main.cpp"))
.is_some_and(|summary| summary
.declarations
.iter()
.any(|fact| fact.name == "padding")),
"the keystroke's own file is read again, by the per-file path"
);
session.did_change("/p/main.cpp", directive_edit);
assert!(
session.the_wait_before_a_program_may_be_read().is_some(),
"a directive that moved makes the program worth reading again"
);
}
#[test]
fn a_file_read_as_a_program_needs_no_guard_filter() {
let cfg = "#define ON 1\n";
let api = "#include \"cfg.h\"\n#if 0\nstruct Dead { int gone; };\n#endif\nstruct Live { int kept; };\n";
let main = "#include \"api.h\"\nLive live;\n";
let files = MemoryFiles::new()
.with_file("/p/cfg.h", cfg)
.with_file("/p/api.h", api)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("no-guard-filter-needed", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
session
.read_a_looked_at_unit()
.expect("the reader has a file open, so there is a program to read");
let ask = |session: &Session<_>| {
let mut answers: Vec<String> = Vec::new();
for name in ["Dead", "gone", "Live", "kept"] {
let answer = match session.index().definitions(name, Path::new("/p/main.cpp")) {
Known::Yes(found) => format!(
"{:?}",
found
.found
.iter()
.map(|one| (
one.file.to_string_lossy().to_string(),
one.fact.name.clone()
))
.collect::<Vec<_>>()
),
Known::Unknown(reason) => format!("unknown:{reason:?}"),
Known::No => String::from("no"),
};
answers.push(format!("{name} = {answer}"));
}
answers
};
let with = ask(&session);
session.index().forget_the_name_answers();
crate::probes::set_no_guard_filter(true);
let without = ask(&session);
crate::probes::set_no_guard_filter(false);
assert_eq!(
with, without,
"the filter changed an answer, so this file's reading is not the rendering: {with:?}"
);
assert!(
!with.iter().any(|answer| answer.starts_with("Dead = yes")),
"and the branch nobody takes is not an answer at all: {with:?}"
);
}
#[test]
fn a_files_rendering_is_its_reading_and_not_one_answer_beside_another() {
let api = "#ifdef FROM_THE_SOURCE\n\
struct Live { int a; };\n\
#else\n\
struct Live { long b; };\n\
#endif\n";
let main = "#define FROM_THE_SOURCE 1\n#include \"api.h\"\nLive live;\n";
let files = MemoryFiles::new()
.with_file("/p/api.h", api)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("the-rendering-is-the-reading", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let taken = api.find("struct Live { int a; }").expect("the fixture");
let not_taken = api.find("struct Live { long b; }").expect("the fixture");
let before = session
.index()
.definitions("Live", Path::new("/p/main.cpp"));
println!("before the program read: {before:?}");
session
.read_a_looked_at_unit()
.expect("the reader has a file open, so there is a program to read");
let found = session
.index()
.definitions("Live", Path::new("/p/main.cpp"));
let Known::Yes(found) = found else {
panic!("`Live` is declared in a header the source includes: {found:?}");
};
assert_eq!(
found.found.len(),
1,
"the file has been read as a program, so its reading is the reading: {:?}",
found
.found
.iter()
.map(|one| one.fact.range)
.collect::<Vec<_>>()
);
assert_eq!(
found.found[0].fact.range.start_offset, taken,
"the answer is the branch `FROM_THE_SOURCE` selects: {:?}",
found.found[0].fact.range
);
assert_ne!(
found.found[0].fact.range.start_offset, not_taken,
"and not the one the file has when it is read on its own"
);
}
#[test]
fn a_header_read_in_two_programs_answers_each_its_own_way() {
let cfg = "#ifdef A\nstruct X { int from_a; };\n#else\nstruct X { long from_b; };\n#endif\n";
let a = "#define A 1\n#include \"cfg.h\"\n";
let b = "#include \"cfg.h\"\n";
let files = MemoryFiles::new()
.with_file("/p/cfg.h", cfg)
.with_file("/p/a.cpp", a)
.with_file("/p/b.cpp", b);
let fixture = Memory::new("a-header-in-two-programs", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", a);
session.did_open("/p/b.cpp", b);
session.index_everything();
let mut read = Vec::new();
while let Some(reading) = session.read_a_looked_at_unit() {
read.push(reading.root.clone());
}
assert!(read.len() >= 2, "both translation units are read: {read:?}");
let from_a = session.index().definitions("X", Path::new("/p/a.cpp"));
let from_b = session.index().definitions("X", Path::new("/p/b.cpp"));
let offset = |known: &Known<crate::ProjectDefinitions>| match known {
Known::Yes(found) => found.found.first().map(|one| one.fact.range.start_offset),
_ => None,
};
assert_eq!(
offset(&from_a),
Some(cfg.find("struct X { int from_a; }").expect("the fixture")),
"`a.cpp` defines `A`, so it sees the `int` branch: {from_a:?}"
);
assert_eq!(
offset(&from_b),
Some(cfg.find("struct X { long from_b; }").expect("the fixture")),
"`b.cpp` does not, so it sees the `long` one: {from_b:?}"
);
}
#[test]
fn a_branch_nobody_takes_reports_nothing_once_the_file_is_cooked() {
let main = "#include \"cfg.h\"\n#if OFF\nstruct Unclosed { int x;\n#endif\nint ok;\n";
let files = MemoryFiles::new()
.with_file("/p/cfg.h", "#define OFF 0\n")
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-branch-nobody-takes", &files);
let mut session = fixture.session();
session.load("/p/main.cpp");
assert!(
session.diagnostics("/p/main.cpp").is_none(),
"nothing has read this file as a compiler reads it, so there is nothing to say about it"
);
session.did_open("/p/main.cpp", main);
session.index_everything();
let cooked = session.diagnostics("/p/main.cpp").expect("the file reads");
assert_eq!(
cooked.reading,
super::DiagnosticReading::Cooked,
"the index holds a reading of this file now"
);
assert!(
cooked.errors.is_empty(),
"and the branch it complained about is not in it: {cooked:?}"
);
assert_eq!(
cooked.unplaced, 0,
"nothing was hidden from the reader either"
);
}
#[test]
fn a_cooked_error_is_placed_in_the_file_not_in_the_rendering() {
let handle = "#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \
typedef struct name##__ *name\n";
let main = "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\nstruct Unclosed { int x;\n";
let files = MemoryFiles::new()
.with_file("/p/handle.h", handle)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("cooked-errors-are-file-offsets", &files);
let mut session = fixture.session();
session.did_open("/p/main.cpp", main);
session.index_everything();
let declarations = session
.index()
.cooked_declarations(Path::new("/p/main.cpp"))
.expect("the file was cooked");
assert!(
declarations.iter().any(|fact| fact.name == "HWND__"),
"the rendering is not the file's text: the macro declared a struct this file never wrote: {:?}",
declarations
.iter()
.map(|fact| &fact.name)
.collect::<Vec<_>>()
);
let found = session.diagnostics("/p/main.cpp").expect("the file reads");
assert_eq!(found.reading, super::DiagnosticReading::Cooked);
assert_eq!(found.errors.len(), 1, "{found:?}");
let error = &found.errors[0];
let unclosed = main.find("struct Unclosed").expect("the fixture writes it");
assert!(
error.start >= unclosed,
"the error is about the line that is still unclosed: {error:?}"
);
assert!(
error.end <= main.len(),
"and it is a position in the file — a rendering offset would be past its end: {error:?}"
);
assert_eq!(found.unplaced, 0, "nothing had to be hidden: {found:?}");
}
#[test]
fn a_file_nobody_looked_at_is_not_cooked_and_one_a_request_names_is() {
let main = "#include \"a.h\"\n#include \"b.h\"\n#include \"c.h\"\nA a; B b; C c;\n";
let files = MemoryFiles::new()
.with_file("/p/a.h", "struct A { int x; };\n")
.with_file("/p/b.h", "struct B { int x; };\n")
.with_file("/p/c.h", "struct C { int x; };\n")
.with_file("/p/main.cpp", main)
.with_file("/p/other.cpp", "#include \"a.h\"\nvoid g() { }\n");
let fixture = Memory::new("only-what-is-looked-at-is-cooked", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/other.cpp")]);
session.did_open("/p/main.cpp", main);
session.index_everything();
assert_eq!(session.pending_work(), 0, "both kinds of work are done");
for looked_at in ["/p/main.cpp", "/p/a.h", "/p/b.h", "/p/c.h"] {
assert!(
session
.index()
.cooked_declarations(Path::new(looked_at))
.is_some(),
"{looked_at} is what the reader is looking at"
);
}
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_none(),
"and a file nobody opened, nobody included and no request named has no reading"
);
session.want_cooked_reading(Path::new("/p/other.cpp"));
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_some(),
"the file a request is about is read the way a compiler reads it"
);
}
#[test]
fn editing_a_header_invalidates_the_readings_that_depend_on_it() {
let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
let other = "#include \"api.h\"\nWidget w;\n";
let files = MemoryFiles::new()
.with_file("/p/ns.h", ns)
.with_file("/p/api.h", api)
.with_file("/p/other.cpp", other);
let fixture = Memory::new("a-cooked-file-goes-stale", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/other.cpp")]);
session.did_open("/p/api.h", api);
session.want_cooked_reading(Path::new("/p/other.cpp"));
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_some(),
"the fixture starts with the dependent cooked"
);
let changed = "#define BEGIN_NS namespace two {\n#define END_NS }\n";
session.did_open("/p/ns.h", changed);
for stale in ["/p/other.cpp", "/p/api.h"] {
assert!(
session
.index()
.cooked_declarations(Path::new(stale))
.is_none(),
"{stale} was read as the namespace the macro used to open"
);
}
session.index_everything();
assert!(
matches!(
session
.index()
.definition("two::Widget", Path::new("/p/other.cpp")),
Known::Yes(_)
),
"and it is read again, as the new macro says: {:?}",
session
.index()
.definition("two::Widget", Path::new("/p/other.cpp"))
);
}
#[test]
fn editing_a_file_that_defines_no_macros_keeps_its_dependents_readings() {
let api = "struct Widget { int size; };\n";
let other = "#include \"api.h\"\nWidget w;\n";
let files = MemoryFiles::new()
.with_file("/p/api.h", api)
.with_file("/p/other.cpp", other);
let fixture = Memory::new("a-declaration-is-not-an-environment", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/other.cpp")]);
session.did_open("/p/api.h", api);
session.want_cooked_reading(Path::new("/p/other.cpp"));
session.index_everything();
session.did_open("/p/api.h", "struct Widget { int size; int weight; };\n");
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_some(),
"nothing in this file is part of anyone's environment"
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/api.h"))
.is_none(),
"…while the file itself is re-read, which is not a question about macros"
);
}
#[test]
fn the_first_macro_a_header_defines_invalidates_the_readings_that_include_it() {
let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
let other = "#include \"api.h\"\nWidget w;\n";
let files = MemoryFiles::new()
.with_file("/p/ns.h", "// nothing to say yet\n")
.with_file("/p/api.h", api)
.with_file("/p/other.cpp", other);
let fixture = Memory::new("the-first-macro-of-a-header", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/other.cpp")]);
session.want_cooked_reading(Path::new("/p/other.cpp"));
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_some(),
"the fixture starts with the dependent cooked"
);
session.did_open(
"/p/ns.h",
"#define BEGIN_NS namespace one {\n#define END_NS }\n",
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_none(),
"the reading was built when `BEGIN_NS` meant nothing"
);
}
#[test]
fn typing_in_a_body_does_not_cost_the_walk_a_translation_unit_is() {
let main = "#include \"b.h\"\nint main() { return A; }\n";
let files = MemoryFiles::new()
.with_file("/p/a.h", "#pragma once\n#define A 1\n")
.with_file(
"/p/b.h",
"#pragma once\n#include \"a.h\"\nstruct B { int b; };\n",
)
.with_file("/p/main.cpp", main);
let fixture = Memory::new("a-body-edit-is-not-a-walk", &files);
let mut first = fixture.session();
first.add_project_files([PathBuf::from("/p/main.cpp")]);
first.did_open("/p/main.cpp", main);
first.index_everything();
assert!(
first
.index()
.cooked_declarations(Path::new("/p/main.cpp"))
.is_some(),
"the fixture cooked the file, which is what walks its unit"
);
assert!(
first.unit_stats().walked > 0,
"…and nothing was on disk to serve it: {:?}",
first.unit_stats()
);
let over_a_fresh_session = |what: &str, text: &str| {
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/main.cpp")]);
session.did_open("/p/main.cpp", text);
session.index_everything();
let stats = session.unit_stats();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/main.cpp"))
.is_some(),
"{what}: the fixture cooked the file"
);
stats
};
let unedited = over_a_fresh_session("unedited", main);
let walked_baseline = unedited.walked;
assert_eq!(
unedited.walked, walked_baseline,
"the entry the first session wrote answers for the text it was walked from: {unedited:?}"
);
assert!(
unedited.walked > 0,
"…and the fresh session walked, because no timeline survives a session any more: {unedited:?}"
);
let typed = format!("{main}\nint more() {{ return A; }}\n");
let edited = over_a_fresh_session("a body edit", &typed);
assert_eq!(
edited.walked, walked_baseline,
"a body edit must not cost more walks than a fresh session already pays: {edited:?}"
);
assert!(
edited.walked > 0,
"…and the body edit walked, as every fresh session now does: {edited:?}"
);
let with_an_include = "#include \"a.h\"\n#include \"b.h\"\nint main() { return A; }\n";
let moved = over_a_fresh_session("an include above the body", with_an_include);
assert!(
moved.walked > 0,
"an edit above the bound is an edit to what the walk reads: {moved:?}"
);
}
#[test]
fn a_file_read_back_through_its_own_unit_is_not_read_again_by_the_second_pass() {
let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
let typed = format!("{api}void body() {{ int inside; }}\n");
let files = MemoryFiles::new()
.with_file("/p/ns.h", ns)
.with_file("/p/api.h", api);
let fixture = Memory::new("a-file-is-read-with-its-environment", &files);
let second_pass_has = |session: &Session<MemoryFiles>| {
session
.parsed_since_the_last_pass
.iter()
.any(|queued| queued.ends_with("api.h"))
};
let mut cold = fixture.session();
cold.did_open("/p/api.h", api);
cold.advance(1);
assert!(
second_pass_has(&cold),
"with no unit in memory the file is read the way it always was, and the pass still has it: {:?}",
cold.parsed_since_the_last_pass
);
let mut warm = fixture.session();
warm.did_open("/p/api.h", api);
warm.index_everything();
assert!(
holds_a_unit_for(&warm, "/p/api.h"),
"the fixture walked a unit for the file"
);
warm.did_change("/p/api.h", &typed);
warm.advance(64);
assert!(
!second_pass_has(&warm),
"read with the environment of its own closure, so the pass has nothing to repair: {:?}",
warm.parsed_since_the_last_pass
);
}
#[test]
fn a_wave_with_nothing_to_parse_still_carries_the_drains_timelines() {
let count = crate::session::RE_READ_SLICE + 4;
let files = (0..count).fold(MemoryFiles::new(), |files, at| {
files.with_file(format!("/p/f{at}.cpp"), format!("int value_{at} = {at};\n"))
});
let fixture = Memory::new("a-wave-carries-its-drain-timelines", &files);
let mut session = fixture.session();
session.add_project_files((0..count).map(|at| PathBuf::from(format!("/p/f{at}.cpp"))));
let wave = session.prepare_a_wave(count);
session.commit_a_wave(wave, count);
assert_eq!(
session.pending(),
0,
"the fixture is the drain phase: nothing left to index"
);
assert!(
!session.parsed_since_the_last_pass.is_empty(),
"and the second pass still has files: {:?}",
session.parsed_since_the_last_pass
);
let next = session.prepare_a_wave(8);
assert!(
next.prepared.is_empty(),
"there is nothing to parse, which is the state this test is about"
);
assert_eq!(
next.units.len(),
session.parsed_since_the_last_pass.len().min(4),
"and the drain's timelines are still prepared, one per file it will re-read"
);
}
#[test]
fn a_quoted_include_is_verified_in_the_directory_it_is_asked_from() {
let files = MemoryFiles::new()
.with_file("/p/a/x.h", "int from_a;\n")
.with_file("/p/b/x.h", "int from_b;\n")
.with_file("/p/a/one.cpp", "#include \"x.h\"\n")
.with_file("/p/b/two.cpp", "#include \"x.h\"\n");
let fixture = Memory::new("a-quoted-include-is-per-directory", &files);
let roots = [PathBuf::from("/p/a/one.cpp"), PathBuf::from("/p/b/two.cpp")];
let mut first = fixture.session();
first.add_project_files(roots.iter().cloned());
first.index_everything();
assert!(
first.stats().rebuilt >= 2,
"the fixture starts cold: {:?}",
first.stats()
);
let mut second = fixture.session();
second.add_project_files(roots.iter().cloned());
let steps = second.advance(16);
let outcomes: Vec<String> = steps
.iter()
.map(|step| {
format!(
"{}: {:?}",
step.path.file_name().unwrap_or_default().to_string_lossy(),
step.outcome
)
})
.collect();
assert!(
steps.iter().all(|step| step.outcome == StepOutcome::Reused),
"nothing may be rebuilt from a cache that holds every one of these files: {outcomes:?}"
);
}
#[test]
fn an_include_added_to_a_header_invalidates_the_readings_that_include_it() {
let files = MemoryFiles::new()
.with_file("/p/macros.h", "#define ANSWER 42\n")
.with_file("/p/api.h", "int declared;\n")
.with_file("/p/other.cpp", "#include \"api.h\"\nint x = ANSWER;\n");
let fixture = Memory::new("an-include-is-an-environment", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/other.cpp")]);
session.want_cooked_reading(Path::new("/p/other.cpp"));
session.index_everything();
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_some()
);
session.did_open("/p/api.h", "#include \"macros.h\"\nint declared;\n");
assert!(
session
.index()
.cooked_declarations(Path::new("/p/other.cpp"))
.is_none(),
"`ANSWER` is now in force where it was not"
);
}
#[test]
fn a_unit_survives_typing_in_a_body_and_not_a_change_to_a_directive() {
let ns = "#define BEGIN_NS namespace one {\n#define END_NS }\n";
let api = "#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n";
let files = MemoryFiles::new()
.with_file("/p/ns.h", ns)
.with_file("/p/api.h", api);
let fixture = Memory::new("a-unit-survives-a-body", &files);
let mut session = fixture.session();
session.did_open("/p/api.h", api);
session.index_everything();
assert!(
holds_a_unit_for(&session, "/p/api.h"),
"the fixture cooked the file, which walked a unit"
);
assert!(
holds_a_unit_for(&session, "/p/ns.h"),
"…and the header it includes, whose closure does not contain `api.h`"
);
let typed = format!("{api}void body() {{ int inside; }}\n");
session.did_change("/p/api.h", &typed);
assert!(
holds_a_unit_for(&session, "/p/api.h"),
"a body was typed below the last directive"
);
let typed_more = format!("{api}void body() {{ int inside; int more; }}\n");
session.did_change("/p/api.h", &typed_more);
assert!(holds_a_unit_for(&session, "/p/api.h"), "and again");
session.did_change(
"/p/api.h",
&format!("#include \"ns.h\"\n#define EXTRA 1\n{typed_more}"),
);
assert!(
!holds_a_unit_for(&session, "/p/api.h"),
"a directive appeared, so `api.h`'s timeline is out of date"
);
assert!(
holds_a_unit_for(&session, "/p/ns.h"),
"…and `ns.h`'s is not: nothing in its closure moved, and dropping it would be a walk bought for nothing"
);
}
fn holds_a_unit_for(session: &Session<MemoryFiles>, path: &str) -> bool {
session
.units
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.held
.contains_key(&queue_key(Path::new(path)))
}
#[test]
fn a_cook_that_cannot_succeed_is_not_queued_again_by_a_request() {
let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
let fixture = Memory::new("a-refused-cook-is-not-requeued", &files);
let mut session = fixture.session();
session.index_everything();
session.want_cooked_reading(Path::new("/p/absent.cpp"));
let claimed = session.claim_cooking(4);
assert_eq!(claimed.len(), 1, "the request queued it once");
let built = session.materials_for(claimed.clone());
assert!(
built.is_empty(),
"a file the index cannot describe has no materials to cook"
);
session.refuse_the_cooks_that_built_nothing(&claimed, &[]);
assert_eq!(
session.pending_cooking(),
0,
"the refused file left the queue"
);
session.want_cooked_reading(Path::new("/p/absent.cpp"));
assert_eq!(
session.pending_cooking(),
0,
"a request does not resurrect a refusal — that was the loop"
);
session.did_change(Path::new("/p/absent.cpp"), "int b;\n");
assert_eq!(
session.pending_cooking(),
1,
"an edit is what makes a refusal worth retrying"
);
}
#[test]
fn editing_a_header_stales_the_cooked_reading_of_a_file_that_includes_it() {
let files = MemoryFiles::new()
.with_file(
"/p/ns.h",
"#define BEGIN_NS namespace one {\n#define END_NS }\n",
)
.with_file(
"/p/api.h",
"#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n",
);
let fixture = Memory::new("a-header-edit-stales-readings", &files);
let mut session = fixture.session();
session.did_open(
"/p/api.h",
"#include \"ns.h\"\nBEGIN_NS struct Widget { int size; }; END_NS\n",
);
session.index_everything();
assert!(
matches!(
session
.index()
.definition("one::Widget", Path::new("/p/api.h")),
Known::Yes(_)
),
"the fixture reads as the header says: {:?}",
session
.index()
.definition("one::Widget", Path::new("/p/api.h"))
);
session.did_change(
"/p/ns.h",
"#define BEGIN_NS namespace two {\n#define END_NS }\n",
);
assert!(
session.pending_cooking() > 0,
"the open file that includes it is marked for cooking again"
);
session.index_everything();
assert!(
matches!(
session
.index()
.definition("two::Widget", Path::new("/p/api.h")),
Known::Yes(_)
),
"and the new reading is the one in the index: {:?}",
session
.index()
.definition("two::Widget", Path::new("/p/api.h"))
);
assert!(
session
.index()
.cooked_declarations(Path::new("/p/api.h"))
.is_some_and(|facts| facts
.iter()
.any(|fact| fact.qualified_name() == "two::Widget")),
"the stale reading was replaced, not kept beside it"
);
}
#[test]
fn a_buffer_is_the_text_the_analysis_reads() {
let files = MemoryFiles::new()
.with_file("/p/widget.h", "struct Widget { int old; };\n")
.with_file(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
let fixture = Memory::new("buffer-is-the-text", &files);
let mut session = fixture.session();
session.did_open("/p/widget.h", "struct Widget { int fresh; };\n");
session.did_open(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
session.index_everything();
let view = session.view("/p/main.cpp").expect("the file reads");
let at = view
.source
.find("Widget w")
.expect("the use is in the text");
match session.definition(&view, ReadingOffset::new(at)) {
Known::Yes(found) => {
assert_eq!(found.file, Path::new("/p/widget.h"));
assert_eq!(found.fact.name, "Widget");
}
other => panic!("the buffer's declaration should be found, got {other:?}"),
}
match session.members_of(&view, "Widget") {
Known::Yes(members) => {
let names: Vec<&str> = members
.own()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(
names,
["fresh"],
"the disk says `old` and the disk is not the text"
);
}
other => panic!("the buffer's class should have members, got {other:?}"),
}
assert_eq!(
fixture.text("/p/widget.h").as_deref(),
Some("struct Widget { int fresh; };\n")
);
}
#[test]
fn a_buffer_that_has_never_been_saved_is_a_file_like_any_other() {
let files = MemoryFiles::new().with_file(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
let fixture = Memory::new("unsaved", &files);
let mut session = fixture.session();
session.did_open("/p/widget.h", "struct Widget { int size; };\n");
session.did_open(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
assert!(
session.index_everything() >= 2,
"both the buffer and its includer"
);
let view = session.view("/p/main.cpp").expect("the file reads");
let at = view
.source
.find("Widget w")
.expect("the use is in the text");
assert!(
matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")),
"a buffer no file has answers as the declaration's file"
);
}
#[test]
fn an_edit_replaces_what_the_index_knew_and_the_gap_is_visible() {
let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int before; };\n");
let fixture = Memory::new("edit", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/widget.h")]);
session.index_everything();
assert!(session.is_indexed("/p/widget.h"));
assert!(session.is_idle());
session.did_change("/p/widget.h", "struct Widget { int after; };\n");
assert!(
!session.is_indexed("/p/widget.h"),
"the summary describes text the user has replaced"
);
assert_eq!(session.pending(), 1, "and the file is queued again");
let steps = session.advance(4);
assert_eq!(paths(&steps), ["/p/widget.h"]);
assert!(
matches!(steps[0].outcome, StepOutcome::Built | StepOutcome::Unstored),
"the summary was dropped, so this is a parse and not a cache hit: {:?}",
steps[0].outcome
);
assert_eq!(session.stats().rebuilt, 2, "the first index and this one");
session.index_everything();
let view = session.view("/p/widget.h").expect("the file reads");
match session.members_of(&view, "Widget") {
Known::Yes(members) => {
let names: Vec<&str> = members
.own()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(names, ["after"]);
}
other => panic!("the edited buffer's class should have members, got {other:?}"),
}
}
#[test]
fn closing_a_document_goes_back_to_the_file() {
let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int on_disk; };\n");
let fixture = Memory::new("close", &files);
let mut session = fixture.session();
session.did_open("/p/widget.h", "struct Widget { int in_the_buffer; };\n");
session.index_everything();
session.did_close("/p/widget.h");
assert!(!fixture.documents.is_open("/p/widget.h"));
assert!(!session.is_indexed("/p/widget.h"));
let steps = session.advance(4);
assert_eq!(paths(&steps), ["/p/widget.h"]);
assert_eq!(
steps[0].priority,
Priority::Rest,
"the user has stopped looking at it, so it is not urgent"
);
assert!(
session.view("/p/widget.h").is_none(),
"a buffer's rendering was made of the buffer, and the buffer is closed"
);
session.index_everything();
let view = session
.view("/p/widget.h")
.expect("the file has been read again");
match session.members_of(&view, "Widget") {
Known::Yes(members) => {
let names: Vec<&str> = members
.own()
.map(|member| member.fact.name.as_str())
.collect();
assert_eq!(names, ["on_disk"]);
}
other => panic!("the file's own class should have members, got {other:?}"),
}
}
#[test]
fn the_open_file_is_worked_first_and_its_includes_next() {
let files = MemoryFiles::new()
.with_file("/p/open.cpp", "#include \"deep.h\"\nvoid f() { }\n")
.with_file("/p/deep.h", "int deep;\n")
.with_file("/p/one.cpp", "int one;\n")
.with_file("/p/two.cpp", "int two;\n");
let fixture = Memory::new("order", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/one.cpp"), PathBuf::from("/p/two.cpp")]);
session.did_open("/p/open.cpp", "#include \"deep.h\"\nvoid f() { }\n");
let steps = session.advance(8);
assert_eq!(
paths(&steps),
["/p/open.cpp", "/p/deep.h", "/p/one.cpp", "/p/two.cpp"]
);
assert_eq!(steps[0].priority, Priority::Open);
assert_eq!(steps[0].depth, 0);
assert_eq!(
(steps[1].priority, steps[1].depth),
(Priority::Open, 1),
"a header an open file includes is worth reading before the project"
);
assert_eq!((steps[2].priority, steps[2].depth), (Priority::Rest, 0));
}
#[test]
fn a_project_file_that_is_opened_moves_to_the_open_half() {
let files = MemoryFiles::new()
.with_file("/p/widget.h", "struct Widget { int size; };\n")
.with_file("/p/one.cpp", "int one;\n");
let fixture = Memory::new("upgrade", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/one.cpp"), PathBuf::from("/p/widget.h")]);
session.did_open("/p/widget.h", "struct Widget { int size; };\n");
let steps = session.advance(1);
assert_eq!(paths(&steps), ["/p/widget.h"]);
assert_eq!(steps[0].priority, Priority::Open);
let rest = session.advance(4);
assert_eq!(paths(&rest), ["/p/one.cpp"]);
assert!(session.is_idle());
assert_eq!(session.pending(), 0);
}
#[test]
fn a_file_that_was_worked_is_queued_again_when_its_answer_changes() {
let files = MemoryFiles::new().with_file("/p/widget.h", "struct Widget { int a; };\n");
let fixture = Memory::new("again", &files);
let mut session = fixture.session();
session.did_open("/p/widget.h", "struct Widget { int a; };\n");
session.index_everything();
assert!(session.is_idle());
let before = session.stats();
session.did_change("/p/widget.h", "struct Widget { int b; };\n");
assert_eq!(session.pending(), 1);
let steps = session.advance(4);
assert_eq!(paths(&steps), ["/p/widget.h"]);
assert_eq!(session.stats().since(before).rebuilt, 1);
}
#[test]
fn a_reported_change_is_read_again_and_a_reported_removal_is_forgotten() {
let files = MemoryFiles::new()
.with_file("/p/widget.h", "struct Widget { int size; };\n")
.with_file(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
let fixture = Memory::new("client-events", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/main.cpp")]);
session.index_everything();
assert!(
session.is_indexed("/p/widget.h"),
"the closure was followed"
);
let modified = session.changed([FileEvent::modified("/p/widget.h")]);
assert_eq!(modified.reindex, [PathBuf::from("/p/widget.h")]);
assert!(modified.forgotten.is_empty());
assert!(!modified.everything);
assert_eq!(
session.pending(),
2,
"the change and the file whose reading depends on it are both queued"
);
let steps = session.advance(4);
assert_eq!(paths(&steps), ["/p/widget.h", "/p/main.cpp"]);
assert_eq!(
steps[0].outcome,
StepOutcome::Reused,
"the text did not change, so the key still names the stored summary"
);
let removed = session.changed([FileEvent::removed("/p/widget.h")]);
assert_eq!(removed.forgotten, [PathBuf::from("/p/widget.h")]);
assert_eq!(
removed.reindex,
[PathBuf::from("/p/main.cpp")],
"the file that resolved to it records a search that would now fail"
);
assert!(
!session.is_indexed("/p/widget.h"),
"and the declarations are out of the index before anything is re-read"
);
}
#[test]
fn a_change_the_client_does_not_care_about_is_no_work() {
let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
let fixture = Memory::new("ignored-events", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/a.cpp")]);
session.index_everything();
let root = fixture.root.clone();
let quiet = session.changed([
FileEvent::modified(root.join(".git/index.lock")),
FileEvent::modified(root.join(".cppls/summaries/ab/cdef.bin")),
FileEvent::modified(root.join("notes.md")),
]);
assert!(quiet.is_empty(), "{quiet:?}");
assert!(session.is_idle());
let configuration = session.changed([FileEvent::modified(root.join("compile_commands.json"))]);
assert!(configuration.everything);
}
#[test]
fn a_configuration_change_re_seeds_the_project_and_the_open_buffers() {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", "int a;\n")
.with_file("/p/b.cpp", "int b;\n")
.with_file("/p/open.cpp", "int open;\n");
let fixture = Memory::new("configuration", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/a.cpp"), PathBuf::from("/p/b.cpp")]);
session.did_open("/p/open.cpp", "int open;\n");
session.index_everything();
assert!(session.is_idle());
let response = session.changed([FileEvent::modified(
fixture.root.join("compile_commands.json"),
)]);
assert!(response.everything);
assert_eq!(
session.pending(),
3,
"the project list and the buffer are all work again"
);
let steps = session.advance(8);
assert_eq!(paths(&steps), ["/p/open.cpp", "/p/a.cpp", "/p/b.cpp"]);
}
#[test]
fn a_configuration_change_re_arms_a_worked_file_and_it_is_rebuilt() {
let files = MemoryFiles::new().with_file("/p/a.cpp", "int a;\n");
let fixture = Memory::new("rearm", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/a.cpp")]);
session.index_everything();
assert_eq!(session.index().summaries().count(), 1);
let before = session.stats();
session.changed([FileEvent::modified(
fixture.root.join("compile_commands.json"),
)]);
let steps = session.advance(4);
assert_eq!(paths(&steps), ["/p/a.cpp"], "the file is work again");
assert!(
matches!(steps[0].outcome, StepOutcome::Built | StepOutcome::Unstored),
"a different configuration is a different reading, so the text alone cannot answer for it: {:?}",
steps[0].outcome
);
assert_eq!(session.stats().since(before).rebuilt, 1);
assert_eq!(
session.index().summaries().count(),
1,
"and the index is the same size: a rebuild is not a second file"
);
}
#[test]
fn a_name_in_a_file_that_has_not_been_read_is_unknown_and_the_queue_says_so() {
let files = MemoryFiles::new()
.with_file("/p/widget.h", "struct Widget { int size; };\n")
.with_file(
"/p/main.cpp",
"#include \"widget.h\"\nvoid f() { Widget w; }\n",
);
let fixture = Memory::new("not-read-yet", &files);
let mut session = fixture.session();
session.add_project_files([PathBuf::from("/p/main.cpp")]);
session.load("/p/main.cpp");
assert!(
session.view("/p/main.cpp").is_none(),
"a file nothing has read as a compiler reads it has no semantic view"
);
session.index_everything();
let view = session.view("/p/main.cpp").expect("the pump has read it");
let at = view
.source
.find("Widget w")
.expect("the use is in the text");
assert!(session.is_idle());
assert!(
matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/widget.h")),
"the same question, answered once the file has been read"
);
}
#[test]
fn a_view_is_the_buffer_parsed_and_maps_a_position_onto_an_offset() {
let files =
MemoryFiles::new().with_file("/p/a.cpp", "int on_disk;\nvoid f() { on_disk = 1; }\n");
let fixture = Memory::new("view", &files);
let mut session = fixture.session();
session.did_open("/p/a.cpp", "int in_buffer;\nvoid f() { in_buffer = 1; }\n");
let tokens = session.tokens_of("/p/a.cpp").expect("the buffer is held");
assert!(
tokens.open,
"the reading says which of the two texts it read"
);
let at = tokens
.source
.find("in_buffer = 1")
.expect("the use is in the text");
assert_eq!(
tokens.offset_at(1, 11),
Some(ReadingOffset::new(at)),
"line 1, column 11 is where `in_buffer` is written on the second line"
);
assert_eq!(
tokens.offset_at(99, 0),
None,
"a line past the end is not an offset"
);
session.index_everything();
let view = session.view("/p/a.cpp").expect("the pump has read it");
assert!(
view.source.contains("in_buffer"),
"the reading is the buffer's"
);
let at = view
.source
.find("in_buffer = 1")
.expect("the use is in the text");
assert!(
matches!(session.definition(&view, ReadingOffset::new(at)), Known::Yes(found) if found.file == Path::new("/p/a.cpp")),
"a local declaration is resolved by the file's scopes"
);
assert!(session.view("/p/not_there.cpp").is_none());
}
#[test]
fn a_position_maps_back_onto_the_offset_it_came_from() {
let files = MemoryFiles::new()
.with_file("/p/a.cpp", "// é comment\nint x = 1;\n")
.with_file("/p/crlf.cpp", "int a;\r\nint b;\r\n");
let fixture = Memory::new("position", &files);
let mut session = fixture.session();
session.load("/p/a.cpp");
session.load("/p/crlf.cpp");
let view = session.tokens_of("/p/a.cpp").expect("the file reads");
let at = view
.source
.find("x = 1")
.expect("the statement is in the text");
assert_eq!(
view.position_at(ReadingOffset::new(at)),
Some((1, 4)),
"the offset of `x` is line 1, column 4"
);
let (line, column) = view
.position_at(ReadingOffset::new(at))
.expect("the offset is in the file");
assert_eq!(view.offset_at(line, column), Some(ReadingOffset::new(at)));
let comment = view.source.find('é').expect("the character is in the text");
assert_eq!(
view.position_at(ReadingOffset::new(comment)),
Some((0, 3)),
"a character counts as one column, whatever it costs in bytes"
);
let crlf = session.tokens_of("/p/crlf.cpp").expect("the file reads");
let second = crlf
.source
.find("int b")
.expect("the second line is in the text");
assert_eq!(crlf.position_at(ReadingOffset::new(second)), Some((1, 0)));
assert_eq!(
crlf.position_at(ReadingOffset::new(crlf.source.len())),
Some((2, 0)),
"the end of the text is a position: it is where a range at EOF sits"
);
assert_eq!(
crlf.position_at(ReadingOffset::new(crlf.source.len() + 1)),
None,
"an offset past the end is not a position"
);
}
struct Project {
root: PathBuf,
}
impl Project {
fn new(name: &str) -> Self {
let root = std::env::temp_dir().join("cppls-session-disk").join(name);
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).expect("the fixture directory");
Project { root }
}
fn write(&self, name: &str, text: &str) -> PathBuf {
let path = self.root.join(name);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("the fixture directory");
}
std::fs::write(&path, text).expect("the fixture writes");
path
}
fn relative(&self, paths: &[PathBuf]) -> Vec<String> {
paths
.iter()
.filter_map(|path| path.strip_prefix(&self.root).ok())
.map(|path| path.to_string_lossy().replace('\\', "/"))
.collect()
}
}
impl Drop for Project {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn the_scan_finds_the_projects_sources_and_leaves_the_rest() {
let project = Project::new("scan");
project.write("main.cpp", "int main() { return 0; }\n");
project.write("include/widget.hpp", "struct Widget { int size; };\n");
project.write("notes.md", "# notes\n");
project.write("build/generated.cpp", "int generated;\n");
project.write(".git/hooks/thing.cpp", "int hook;\n");
project.write("extensionless", "int nothing;\n");
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let filter = WatchFilter::new(&project.root).ignore(project.root.join("build"));
let session = Session::with_config(
&project.root,
providers.clone(),
filter,
CompilerConfig::default(),
);
assert_eq!(
project.relative(session.project_files()),
["include/widget.hpp", "main.cpp"]
);
assert_eq!(
session.pending(),
2,
"and the list is the queue's seed, so the work is ready before the first query"
);
}
#[test]
fn a_class_scoped_by_another_files_macro_body_is_scoped_through_the_session() {
let project = Project::new("body-pass");
let open = project.write(
"open.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
);
let widget = project.write(
"widget.h",
"#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
);
let main = project.write("main.cpp", "#include \"widget.h\"\n");
let mut session = Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
session.index_everything();
let found = session.index().definition("std::Widget", &main);
let Known::Yes(found) = found else {
panic!("`Widget` is declared behind a macro body written in `open.h`: {found:?}");
};
assert_eq!(found.file, widget);
assert_eq!(found.fact.scope.as_deref(), Some("std"));
assert_eq!(
session.index().dependents_of(&open).len(),
2,
"`widget.h` includes it and `main.cpp` includes that: the index knows both"
);
session.did_change(
&open,
"#pragma once\n#define _STD_BEGIN namespace studio {\n#define _STD_END }\n",
);
assert!(
!session.is_indexed(&widget),
"the body moved, so the file that rendered through it has to be read again"
);
session.index_everything();
assert!(
matches!(
session.index().definition("std::Widget", &main),
Known::No | Known::Unknown(_)
),
"the body no longer opens `std`, so nothing may still answer `std::Widget`"
);
let moved = session.index().definition("studio::Widget", &main);
let Known::Yes(moved) = moved else {
panic!("`Widget` is behind `namespace studio` now: {moved:?}");
};
assert_eq!(
moved.file.file_name(),
widget.file_name(),
"the declaration is still `widget.h`'s"
);
}
#[test]
fn a_keystroke_in_a_body_reads_the_file_through_its_timeline() {
let project = Project::new("keystroke-renders");
project.write(
"open.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
);
let widget = project.write(
"widget.h",
"#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
);
let mut session = Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
session.add_project_files([widget.clone()]);
session.index_everything();
assert!(
session.index().summary(&widget).is_some_and(|summary| {
summary
.declarations
.iter()
.any(|fact| fact.name == "Widget" && fact.scope.as_deref() == Some("std"))
}),
"the first reading is the timeline's, from the second pass"
);
session.did_change(
&widget,
"#include \"open.h\"\nint padding;\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
);
let steps = session.advance(4);
let step = steps
.iter()
.find(|step| step.path == widget)
.unwrap_or_else(|| panic!("the edited file is read: {:?}", paths(&steps)));
assert!(
step.with_the_environment,
"the rebuild was taken through the file's timeline, so the second pass has nothing to repair: {step:?}"
);
let summary = session.index().summary(&widget).expect("indexed again");
let widget_fact = summary
.declarations
.iter()
.find(|fact| fact.name == "Widget")
.expect("the class is declared");
assert_eq!(
widget_fact.scope.as_deref(),
Some("std"),
"a rendering, not the file's own bytes"
);
}
#[test]
fn a_file_opened_after_the_index_was_built_is_read_through_a_walked_timeline() {
let project = Project::new("opened-renders");
project.write(
"open.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
);
let widget = project.write(
"widget.h",
"#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
);
let mut session = Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
session.add_project_files([widget.clone()]);
session.index_everything();
let edited = format!(
"{}#define PAD 1\n",
std::fs::read_to_string(&widget).expect("the fixture reads")
);
session.did_change(&widget, &edited);
assert!(
session.index().summary(&widget).is_none(),
"the edit drops the reading: the buffer is the text now"
);
let walked_before = session.unit_stats().walked;
let steps = session.advance(4);
let step = steps
.iter()
.find(|step| step.path == widget)
.unwrap_or_else(|| panic!("the opened file is read: {:?}", paths(&steps)));
assert!(
session.unit_stats().walked > walked_before,
"the timeline was walked for this file: {:?}",
session.unit_stats()
);
assert!(
step.with_the_environment,
"and the reading taken through it is the program's, so the second pass has nothing to repair: {step:?}"
);
let summary = session.index().summary(&widget).expect("indexed again");
let widget_fact = summary
.declarations
.iter()
.find(|fact| fact.name == "Widget")
.expect("the class is declared");
assert_eq!(
widget_fact.scope.as_deref(),
Some("std"),
"the scope comes from another file's macro body, so the timeline is what answered"
);
}
#[test]
fn a_file_whose_program_has_not_been_read_yet_is_still_read_as_text() {
let project = Project::new("opened-before-the-program");
project.write(
"open.h",
"#pragma once\n#define _STD_BEGIN namespace std {\n#define _STD_END }\n",
);
let widget = project.write(
"widget.h",
"#include \"open.h\"\n_STD_BEGIN\nstruct Widget { int size; };\n_STD_END\n",
);
let text = std::fs::read_to_string(&widget).expect("the fixture reads");
let mut session = Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
session.add_project_files([widget.clone()]);
session.did_open(&widget, &text);
let steps = session.advance(4);
let step = steps
.iter()
.find(|step| step.path == widget)
.unwrap_or_else(|| panic!("the opened file is read: {:?}", paths(&steps)));
assert!(
!step.with_the_environment,
"`open.h` has not been read, so there is no timeline to read this file through: {step:?}"
);
assert_eq!(
step.outcome,
StepOutcome::Built,
"and the file's own text is what was read: {step:?}"
);
}
#[test]
fn a_project_configuration_narrows_the_scan_and_widens_the_source_list() {
let project = Project::new("config-scan");
project.write("main.cpp", "int main() { return 0; }\n");
project.write("vendor/third_party.cpp", "int vendored;\n");
project.write("kernels/vector.cuh", "struct FromCuda { int x; };\n");
project.write(
".cppls.toml",
"[workspace]\nexclude = [\"vendor/**\"]\nsource_extensions = [\"cuh\"]\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::with_config(
&project.root,
providers,
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
assert_eq!(
project.relative(session.project_files()),
["kernels/vector.cuh", "main.cpp"],
"the excluded tree is not scanned, and the project's own extension is"
);
assert!(
session.project_config().found(),
"the file was read: {:?}",
session.project_config()
);
assert!(session.project_config().problems.is_empty());
}
#[test]
fn the_projects_flags_win_over_the_databases_and_extra_args_add_to_the_winner() {
let project = Project::new("config-flags");
project.write("main.cpp", "int main() { return 0; }\n");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write(
"compile_commands.json",
&format!(
"[\n {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-std=c++17\", \"-Werror\", \
\"-c\", \"{root}/main.cpp\"]}}\n]\n"
),
);
project.write(
".cppls.toml",
"[compile]\nargs = [\"-DFROM_THE_CONFIG\", \"-std=c++20\"]\nextra_args = [\"-DEXTRA\"]\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));
let defines: Vec<&str> = session
.config()
.defines
.iter()
.map(|define| define.name.as_ref())
.collect();
assert_eq!(
defines,
["FROM_THE_CONFIG", "EXTRA"],
"the file's flags are the compilation, and `extra_args` joins them"
);
assert_eq!(
session.config().standard.as_deref(),
Some("c++20"),
"the database's `-std=c++17` is not in effect"
);
}
#[test]
fn removing_and_adding_a_flag_is_one_pass_in_that_order() {
let project = Project::new("config-remove");
project.write("main.cpp", "int main() { return 0; }\n");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write(
"compile_commands.json",
&format!(
"[\n {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-std=c++17\", \"-DKEEP\", \"-Werror\", \"-c\", \"{root}/main.cpp\"]}}\n]\n"
),
);
project.write(
".cppls.toml",
"[compile]\nremove_args = [\"-Werror\", \"-std=c++17\"]\nextra_args = [\"-std=c++20\"]\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));
assert_eq!(
session
.config_for(&project.root.join("main.cpp"))
.standard
.as_deref(),
Some("c++20")
);
let per_file = session.config_for(&project.root.join("main.cpp"));
let defines: Vec<&str> = per_file
.defines
.iter()
.map(|define| define.name.as_ref())
.collect();
assert_eq!(defines, ["KEEP"], "a flag nobody removed still applies");
}
#[test]
fn the_database_can_be_somewhere_no_convention_predicts() {
let project = Project::new("config-database");
project.write("main.cpp", "int main() { return 0; }\n");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write(
"out/compile_commands.json",
&format!(
"[\n {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-DFROM_ELSEWHERE\", \"-c\", \"{root}/main.cpp\"]}}\n]\n"
),
);
project.write(
".cppls.toml",
"[compile]\ndatabase = \"out/compile_commands.json\"\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));
assert_eq!(
session.compile_database().map(crate::CompileCommands::len),
Some(1)
);
let defines: Vec<&str> = session
.config()
.defines
.iter()
.map(|define| define.name.as_ref())
.collect();
assert_eq!(defines, ["FROM_ELSEWHERE"]);
assert_eq!(project.relative(session.project_files()), ["main.cpp"]);
}
#[test]
fn the_cache_goes_where_the_project_says_and_the_filter_follows_it() {
let project = Project::new("config-cache");
project.write("main.cpp", "int main() { return 0; }\n");
project.write(".cppls.toml", "[index]\ncache_dir = \".cppls-cache\"\n");
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let mut session = Session::with_config(
&project.root,
providers,
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
session.index_everything();
assert_eq!(session.stats().rebuilt, 1, "the file was read");
assert!(
project.root.join(".cppls-cache").is_dir(),
"the cache is under the configured directory, not the default: {}",
project.root.join(".cppls-cache").display()
);
assert!(
!project.root.join(crate::CACHE_DIRECTORY).exists(),
"and the default directory was not created at all"
);
}
#[test]
fn the_sections_a_language_server_reads_come_from_the_same_parse() {
let project = Project::new("config-server-keys");
project.write("main.cpp", "int main() { return 0; }\n");
project.write(
".cppls.toml",
"[diagnostics]\non_change_ms = 250\n\n[hover]\nenable = false\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::with_config(
&project.root,
providers,
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
let config = &session.project_config().config;
assert_eq!(config.diagnostics.on_change_ms, Some(250));
assert_eq!(config.hover.enable, Some(false));
}
#[test]
fn a_configuration_file_with_a_typo_still_analyses_the_project() {
let project = Project::new("config-typo");
project.write("main.cpp", "int main() { return 0; }\n");
project.write("vendor/third_party.cpp", "int vendored;\n");
project.write(
".cppls.toml",
"[workspace]\nexclude = [\"vendor/**\"]\n\n[index]\ncache_dir = 5\n",
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::with_config(
&project.root,
providers,
WatchFilter::new(&project.root),
CompilerConfig::default(),
);
assert_eq!(
project.relative(session.project_files()),
["main.cpp"],
"the exclusions are in effect"
);
assert_eq!(session.project_config().problems.len(), 1);
assert!(
session.project_config().problems[0]
.message
.contains("[index]")
);
assert_eq!(session.project_config().errors().count(), 1);
}
#[test]
fn a_database_in_a_build_directory_is_found_and_its_flags_reach_the_session() {
let project = Project::new("build-directory-database");
project.write("main.cpp", "int main() { return 0; }\n");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write(
"build/compile_commands.json",
&format!(
"[\n {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-DFROM_THE_BUILD_DIRECTORY\", \"-std=c++20\", \
\"-c\", \"{root}/main.cpp\"]}}\n]\n"
),
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));
assert_eq!(
session.compile_database().map(crate::CompileCommands::len),
Some(1),
"the database in the build directory was read"
);
assert_eq!(
session
.discovery()
.database
.as_ref()
.map(|found| found.origin),
Some(crate::DatabaseOrigin::BuildDirectory),
"and the report says where it was found"
);
let per_file = session.config_for(&project.root.join("main.cpp"));
let defines: Vec<&str> = per_file
.defines
.iter()
.map(|define| define.name.as_ref())
.collect();
assert_eq!(defines, ["FROM_THE_BUILD_DIRECTORY"]);
assert_eq!(
session
.config_for(&project.root.join("main.cpp"))
.standard
.as_deref(),
Some("c++20")
);
assert!(
session
.discovery()
.problems
.iter()
.any(|problem| problem.message.contains("build directory")),
"and a user reading the report is told: {:?}",
session.discovery().problems
);
}
#[test]
fn a_project_without_a_database_is_analysed_against_the_compilers_defaults() {
let project = Project::new("without-a-database");
project.write("main.cpp", "int main() { return 0; }\n");
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(&project.root, providers, WatchFilter::new(&project.root));
assert!(session.compile_database().is_none());
assert!(
session
.discovery()
.problems
.iter()
.any(|problem| problem.message.contains("no compile database")),
"the way to do better is spelled out: {:?}",
session.discovery().problems
);
}
#[test]
fn a_compile_database_names_the_files_that_are_here_and_the_flags_they_are_built_with() {
let project = Project::new("database");
project.write("main.cpp", "int main() { return 0; }\n");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write(
"compile_commands.json",
&format!(
"[\n {{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-I{root}/include\", \"-std=c++20\", \
\"-c\", \"{root}/main.cpp\"]}},\n \
{{\"directory\": \"{root}\", \"file\": \"{root}/elsewhere.cpp\", \
\"arguments\": [\"g++\", \"-c\", \"{root}/elsewhere.cpp\"]}}\n]\n"
),
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let session = Session::open(
&project.root,
providers.clone(),
WatchFilter::new(&project.root),
);
let database = session.compile_database().expect("the database is read");
assert_eq!(database.len(), 2);
let per_file = session.config_for(&project.root.join("main.cpp"));
let defines: Vec<&str> = per_file
.defines
.iter()
.map(|define| define.name.as_ref())
.collect();
assert_eq!(defines, ["FROM_THE_DATABASE"]);
assert_eq!(
session
.config_for(&project.root.join("main.cpp"))
.standard
.as_deref(),
Some("c++20")
);
assert_eq!(project.relative(session.project_files()), ["main.cpp"]);
assert_eq!(
session.pending(),
1,
"the entry for a file that is not here is not work"
);
}
#[test]
fn a_define_the_compile_database_carries_decides_a_condition_in_a_file() {
let project = Project::new("conditional-include");
let root = project.root.to_string_lossy().replace('\\', "/");
project.write("feature.h", "#define FEATURE_ONLY int\n");
project.write(
"main.cpp",
"#ifdef FROM_THE_DATABASE\n#include \"feature.h\"\n#endif\nFEATURE_ONLY x;\n",
);
project.write(
"compile_commands.json",
&format!(
"[{{\"directory\": \"{root}\", \"file\": \"{root}/main.cpp\", \
\"arguments\": [\"g++\", \"-DFROM_THE_DATABASE\", \"-c\", \"{root}/main.cpp\"]}}]\n"
),
);
let documents = OpenDocuments::new();
let providers = SessionFiles::new(documents, DiskFiles);
let mut session = Session::open(
&project.root,
providers.clone(),
WatchFilter::new(&project.root),
);
session.advance(64);
let path = project.root.join("main.cpp");
let _source = std::fs::read_to_string(&path).expect("the fixture reads");
assert!(
session.view(&path).is_none(),
"nothing has read this file as a compiler reads it, and that is what the ask is for"
);
session.index_everything();
let view = session
.view(&path)
.expect("the ask queued it and the pump cooked it");
assert_eq!(
view.source.as_ref(),
"int x;",
"the -D took the branch, the branch included feature.h, and FEATURE_ONLY became int"
);
}
#[test]
fn the_compilation_is_known_only_when_the_compiler_answered_with_its_macros() {
assert!(
!super::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!(
!super::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!(
super::the_compilation_is_known(Some(&asked)),
"a compiler that answered is the only witness there is to the names no file defines"
);
}
#[test]
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]
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]
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]
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]
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]
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
);
}