use crate::file::paths::DiskFiles;
use crate::include::config::CompilerConfig;
use crate::index::StepOutcome;
use crate::index::watch::WatchFilter;
use crate::session::{OpenDocuments, Session, SessionFiles};
use crate::symbol::Known;
use std::path::PathBuf;
use super::*;
pub(crate) struct Project {
pub(crate) root: PathBuf,
}
impl Project {
pub(crate) fn new(name: &str) -> Self {
let root = a_fresh_fixture_directory("cppls-session-disk", name);
std::fs::create_dir_all(&root).expect("the fixture directory");
Project { root }
}
pub(crate) 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
}
pub(crate) 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]
pub(crate) 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]
pub(crate) fn a_fixture_directory_is_unique_to_its_run() {
let first = a_fresh_fixture_directory("cppls-session-tests", "shared-name");
let second = a_fresh_fixture_directory("cppls-session-tests", "shared-name");
assert_ne!(
first, second,
"two fixtures of one name never share a directory"
);
std::fs::create_dir_all(first.join(".cppls")).expect("the stale cache");
std::fs::write(first.join(".cppls").join("stale"), b"an older reading")
.expect("the stale cache");
let third = a_fresh_fixture_directory("cppls-session-tests", "shared-name");
assert_ne!(third, first, "a stale directory is not reused");
assert!(
!third.join(".cppls").exists(),
"and its cache is not handed over"
);
let _ = std::fs::remove_dir_all(&first);
let _ = std::fs::remove_dir_all(&third);
}
#[test]
pub(crate) 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 first = session.index().definition("std::Widget", &main);
assert!(
!matches!(first, Known::Yes(_)),
"the first request cannot answer from a header read without its macro body: {first:?}"
);
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 first = session.index().definition("studio::Widget", &main);
assert!(
!matches!(first, Known::Yes(_)),
"the re-read file is not scoped yet: {first:?}"
);
session.index_everything();
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]
pub(crate) 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.want_refinement(&widget);
session.index_everything();
assert!(
session
.index()
.cooked_reading(&widget)
.is_some_and(|cooked| {
cooked
.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 cooked = session
.index()
.cooked_reading(&widget)
.expect("read again, in its program");
let widget_fact = cooked
.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]
pub(crate) 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.want_refinement(&widget);
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]
pub(crate) 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]
pub(crate) fn a_program_read_files_each_files_reading_on_the_disk() {
let project = Project::new("program-writes-per-file");
project.write("main.cpp", "#include \"api.h\"\nHWND h;\n");
project.write("api.h", "#include \"handle.h\"\nDECLARE_HANDLE(HWND);\n");
project.write(
"handle.h",
"#define DECLARE_HANDLE(name) struct name##__ { int unused; }; \\\n\
typedef struct name##__ *name\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.add_project_files([project.root.join("main.cpp")]);
session.index_everything();
let reading = session
.read_the_unit(&project.root.join("main.cpp"))
.expect("the program reads");
assert_eq!(
reading.files, 3,
"the program is main.cpp, api.h and handle.h"
);
let api = project.root.join("api.h");
let stored = session
.store
.the_stored_cooked_reading(&api)
.expect("the program's reading of api.h is filed under api.h");
let in_the_index = session
.index()
.cooked_declarations(&api)
.expect("and in the index, under the program");
assert_eq!(
stored.declarations.len(),
in_the_index.len(),
"the disk record and the index hold one reading"
);
assert!(
!stored.declarations.is_empty(),
"the reading is the program's, so it has the macro's declaration"
);
}
#[test]
pub(crate) fn a_stored_cook_answers_the_next_session() {
let project = Project::new("a-stored-cook-answers");
let source = "#include \"b.h\"\nint main() { return B; }\n";
let main = project.write("main.cpp", source);
project.write("b.h", "#define B 1\n");
let open = || {
Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
)
};
let mut first = open();
first.add_project_files([main.clone()]);
first.did_open(&main, source);
first.index_everything();
assert!(
first.index().cooked_declarations(&main).is_some(),
"the first session cooked the file"
);
assert_eq!(
first.unit_stats().walked,
0,
"and it composed the environment instead of walking one: {:?}",
first.unit_stats()
);
let mut second = open();
second.add_project_files([main.clone()]);
second.did_open(&main, source);
second.index_everything();
assert!(
second.index().cooked_declarations(&main).is_some(),
"the file is read in the second session"
);
assert_eq!(
second.unit_stats().walked,
0,
"and no timeline was walked: the record answered with its rendering: {:?}",
second.unit_stats()
);
assert!(
second.view_of_the_file(&main).is_some(),
"and the rendering is there for a view, which is what a facts-only record could not give"
);
assert!(
second.cooks_served_from_disk() > 0,
"and the counter the budget is read from says so: {} served",
second.cooks_served_from_disk()
);
}
#[test]
pub(crate) fn a_comment_edit_to_a_header_keeps_the_cook_record() {
let project = Project::new("a-comment-edit-keeps-the-record");
let source = "#include \"api.h\"\nLive live;\n";
let main = project.write("main.cpp", source);
project.write("api.h", "// the first comment\nstruct Live { int a; };\n");
let open = || {
Session::with_config(
&project.root,
SessionFiles::new(OpenDocuments::new(), DiskFiles),
WatchFilter::new(&project.root),
CompilerConfig::default(),
)
};
{
let mut first = open();
first.add_project_files([main.clone()]);
first.did_open(&main, source);
first.index_everything();
assert!(
first.index().cooked_declarations(&main).is_some(),
"the first session cooked the file"
);
}
project.write(
"api.h",
"// a longer comment, and the same declaration\nstruct Live { int a; };\n",
);
let mut second = open();
second.add_project_files([main.clone()]);
second.did_open(&main, source);
second.index_everything();
assert!(
second.cooks_served_from_disk() > 0,
"a comment is not a change to the macros in force, so the record still answers: {} served",
second.cooks_served_from_disk()
);
}