use std::collections::BTreeSet;
use super::{
admit::{admit_for_check, admit_full, admit_indexes, needed_slugs, unit_paths},
dirty::{additional_rows, changed_queries, key_query, schema_rows, scope_name},
markers::{is_checked_unit, scan_outside},
};
use crate::{
Cache, Compiled, Config, Document, Error, Expected, Model, RepoPath, RepoRoot, Result, Source,
Tree,
cache::DocRow,
check,
config::{self, RepoFormats},
grammar::{self, Grammar, RegexCache},
include,
model::{self, KeyIndex, Loader, ParseMode, PlanIndex, Query},
source, walk,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Working {
All,
Changed,
}
#[derive(Debug)]
pub struct CachedLoader<'a> {
root: &'a RepoRoot,
cache: &'a Cache,
working: Working,
}
impl<'a> CachedLoader<'a> {
pub fn new(root: &'a RepoRoot, cache: &'a Cache) -> Self {
CachedLoader {
root,
cache,
working: Working::All,
}
}
pub fn changed_only(root: &'a RepoRoot, cache: &'a Cache) -> Self {
CachedLoader {
root,
cache,
working: Working::Changed,
}
}
fn stands_in(&self, path: &RepoPath) -> bool {
self.working == Working::Changed && !self.cache.must_read(path)
}
}
impl Loader for CachedLoader<'_> {
fn load(&mut self, path: &RepoPath) -> Result<Source> {
let source = source::load(self.root, path).inspect_err(|e| {
if is_not_found(e) {
self.cache.note_missing();
}
})?;
self.cache.observe(path, &source.key);
Ok(source)
}
fn document(&mut self, path: &RepoPath) -> Result<Option<Document>> {
if self.stands_in(path) {
return Ok(None);
}
self.full_document(path).map(Some)
}
fn schema(&mut self, path: &RepoPath) -> Result<Option<Document>> {
if self.stands_in(path) {
return Ok(None);
}
self.full_document(path).map(Some)
}
fn additional(&mut self, path: &RepoPath) -> Result<Option<Source>> {
if self.stands_in(path) {
return Ok(None);
}
self.load(path).map(Some)
}
fn index(&mut self, path: &RepoPath) -> Result<Option<crate::model::IndexFile>> {
if self.stands_in(path) {
return Ok(None);
}
let source = self.load(path)?;
Ok(Some(crate::model::IndexFile {
path: path.clone(),
source,
}))
}
fn full_document(&mut self, path: &RepoPath) -> Result<Document> {
let source = self.load(path)?;
let parsed = self.parse(&source, ParseMode::Document);
let doc = Document::new(source, parsed);
let knowledge = self.cache.knowledge_of(path).unwrap_or(0);
self.cache.record_row(path, DocRow::of(knowledge, &doc));
Ok(doc)
}
}
pub struct Loaded {
pub model: Model,
pub compiled: Compiled,
pub keys: KeyIndex,
pub expected: Expected,
pub dirty: BTreeSet<RepoPath>,
pub touched: Option<BTreeSet<RepoPath>>,
pub full: bool,
}
pub fn load_model(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
let tree = walk_tree(root, config, cache)?;
cache.sync(&tree);
model::build(tree, &mut CachedLoader::new(root, cache))
}
fn walk_tree(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Tree> {
cache.begin_run();
match cache.hint() {
Some(changed) => cache.tree_from_store(root, config, &changed),
None => walk::collect(root, config),
}
}
pub fn load_working(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
let tree = walk_tree(root, config, cache)?;
cache.sync(&tree);
match cache.view() {
Some(view) => model::build_with(
tree,
&mut CachedLoader::changed_only(root, cache),
Some(view),
),
None => model::build(tree, &mut CachedLoader::new(root, cache)),
}
}
pub fn load_with_keys(
root: &RepoRoot,
config: &Config,
cache: &Cache,
) -> Result<(Model, KeyIndex)> {
let (grammar, repo_formats) = load_formats(root)?;
let model = load_model(root, config, cache)?;
let texts = config::load_texts(root)?;
let compiled = grammar::compile_all(&model, grammar, &repo_formats, texts);
let keys = check::capture_keys_of(&model, &compiled, None);
Ok((model, keys))
}
pub(super) fn load_formats(root: &RepoRoot) -> Result<(Grammar, RepoFormats)> {
let grammar = grammar::load_grammar()?;
let repo_formats = config::load_repo_formats(root, &grammar, &RegexCache::new())?;
Ok((grammar, repo_formats))
}
pub fn load_checked(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Option<Loaded>> {
if !cache.is_on() {
return Ok(None);
}
let (grammar, repo_formats) = load_formats(root)?;
let (loaded, _) = super::validate::check_and_keep(
root,
config,
&grammar,
&repo_formats,
cache,
false,
false,
)?;
Ok(Some(loaded))
}
pub fn load_for_lookup(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
match load_checked(root, config, cache)? {
Some(loaded) => Ok(loaded.model),
None => load_model(root, config, cache),
}
}
pub fn load_keys_for(
root: &RepoRoot,
config: &Config,
cache: &Cache,
slugs: &BTreeSet<String>,
) -> Result<(Model, KeyIndex)> {
let Some(loaded) = load_checked(root, config, cache)? else {
return load_with_keys(root, config, cache);
};
Ok((loaded.model, cache.stored_keys_for(slugs, &BTreeSet::new())))
}
pub fn load_repository(
root: &RepoRoot,
config: &Config,
grammar: &Grammar,
repo_formats: &RepoFormats,
cache: &Cache,
) -> Result<Loaded> {
load_for_check(root, config, grammar, repo_formats, cache, true)
}
pub(super) fn load_for_check(
root: &RepoRoot,
config: &Config,
grammar: &Grammar,
repo_formats: &RepoFormats,
cache: &Cache,
want_full: bool,
) -> Result<Loaded> {
let mut model = if want_full {
load_model(root, config, cache)?
} else {
load_working(root, config, cache)?
};
let mut loader = CachedLoader::new(root, cache);
let identities_changed = cache.identities_changed(model.identity_rows());
let full = want_full || cache.is_fresh();
model.marker_check = config.markers;
let scanned = scan_outside(&mut model, cache, root, full);
let texts = config::load_texts(root)?;
let mut compiled = grammar::compile_all(&model, grammar.clone(), repo_formats, texts);
let changes = Changes {
identities: identities_changed,
scanned,
formats: cache.formats_changed(repo_formats.hash, || {
grammar::fingerprint(&compiled.registry)
}),
schemas: cache.schemas_changed(schema_rows(&model, cache)),
additional: cache.additional_changed(additional_rows(&model)),
};
let mut touched: Option<BTreeSet<RepoPath>> = None;
let (dirty, keys) = if full {
let all = unit_paths(&model);
admit_full(&mut model, &mut loader, cache, &all)?;
ensure_not_missed(cache)?;
let keys = check::capture_keys_of(&model, &compiled, None);
model.plans = check::capture_plans_of(&model, &compiled, None);
(all, keys)
} else {
let (mut queries, dirs) = dirty_queries(&model, cache, root, &changes);
admit_indexes(&mut model, &mut loader, cache, &dirs);
touched = Some(dirs);
let mut dirty = first_dirty(&model, cache, changes, &mut queries);
let (mut captured, mut planned) =
spread_dirty(&mut model, &mut loader, cache, &mut compiled, &mut dirty)?;
let stored_plans = cache.stored_plans(&dirty);
for target in stored_plans.targets() {
for planner in stored_plans.planners(&target) {
planned.add(&planner, &target);
}
}
model.plans = planned;
let slugs = needed_slugs(&model, &captured);
captured.merge(cache.stored_keys_for(&slugs, &dirty));
(dirty, captured)
};
let expected = if full {
include::expected(&model, &keys)
} else {
include::expected_for(&model, &keys, Some(&dirty))
};
Ok(Loaded {
model,
compiled,
keys,
expected,
dirty,
touched,
full,
})
}
struct Changes {
identities: bool,
scanned: Vec<RepoPath>,
formats: Option<BTreeSet<String>>,
schemas: BTreeSet<(usize, String)>,
additional: BTreeSet<RepoPath>,
}
fn dirty_queries(
model: &Model,
cache: &Cache,
root: &RepoRoot,
changes: &Changes,
) -> (BTreeSet<String>, BTreeSet<RepoPath>) {
let mut dirs: BTreeSet<RepoPath> = BTreeSet::new();
let mut queries = changed_queries(model, cache, root, &mut dirs);
for (knowledge, key) in &changes.schemas {
queries.insert(
Query::Schema {
knowledge: *knowledge,
key: key.clone(),
}
.key(),
);
}
if changes.identities {
queries.insert(Query::Identities.key());
}
if let Some(names) = &changes.formats {
for (k, knowledge) in model.knowledges.iter().enumerate() {
for (i, schema) in knowledge.schemas.iter().enumerate() {
if schema.uses.iter().any(|u| names.contains(u)) {
queries.insert(
Query::Schema {
knowledge: k,
key: knowledge.schema_key(i),
}
.key(),
);
}
}
}
}
(queries, dirs)
}
fn first_dirty(
model: &Model,
cache: &Cache,
changes: Changes,
queries: &mut BTreeSet<String>,
) -> BTreeSet<RepoPath> {
let changed = cache.changed_set();
let mut dirty: BTreeSet<RepoPath> = model
.documents_and_schemas()
.map(|(_, d)| &d.path)
.chain(model.additional.iter().map(|a| &a.path))
.filter(|p| changed.contains(*p))
.cloned()
.collect();
dirty.extend(changes.scanned);
for path in changes.additional {
queries.insert(Query::Path(path.clone()).key());
if model.is_additional(&path) {
dirty.insert(path);
} else if model.tree.file(&path).is_some() {
cache.record_output(&path, Vec::new());
cache.record_edges(&path, Vec::new());
}
}
dirty.extend(
cache
.readers_of(queries)
.into_iter()
.filter(|p| is_checked_unit(model, cache, p)),
);
if changes
.formats
.as_ref()
.is_some_and(|names| names.iter().any(|n| n.starts_with("f:")))
{
dirty.extend(
model
.knowledges
.iter()
.flat_map(|k| k.schemas.iter().map(|s| s.doc.path.clone()))
.filter(|p| is_checked_unit(model, cache, p)),
);
}
dirty
}
fn spread_dirty(
model: &mut Model,
loader: &mut CachedLoader,
cache: &Cache,
compiled: &mut Compiled,
dirty: &mut BTreeSet<RepoPath>,
) -> Result<(KeyIndex, PlanIndex)> {
let mut captured = KeyIndex::default();
let mut planned = PlanIndex::default();
let mut seen: BTreeSet<RepoPath> = BTreeSet::new();
loop {
let wave: BTreeSet<RepoPath> = dirty.difference(&seen).cloned().collect();
if wave.is_empty() {
break;
}
admit_for_check(model, loader, cache, compiled, &wave)?;
let fresh = check::capture_keys_of(model, compiled, Some(&wave));
let mut moved: BTreeSet<String> = BTreeSet::new();
for path in &wave {
let old = cache.old_keys_of(path);
let new: BTreeSet<(String, String, usize)> = fresh
.of_document(path)
.map(|e| (scope_name(&e.scope), e.id.clone(), e.knowledge))
.collect();
for (scope, slug, k) in old.symmetric_difference(&new) {
moved.insert(key_query(scope, slug, *k));
}
let mut was = cache.old_anchors_of(path);
was.extend(old.iter().map(|(_, slug, _)| slug.clone()));
let mut is: BTreeSet<String> = fresh.anchors_of(path).map(str::to_string).collect();
is.extend(new.iter().map(|(_, slug, _)| slug.clone()));
if was != is
&& let Some(crate::Located::Document(k, doc)) = model.by_path(path)
&& let Some(id) = doc.id()
{
moved.insert(
Query::Doc {
knowledge: k,
id: id.to_string(),
}
.key(),
);
}
}
captured.merge(fresh);
let plans = check::capture_plans_of(model, compiled, Some(&wave));
for path in &wave {
let new = plans.of(path);
for target in cache.old_plans_of(path).symmetric_difference(&new) {
moved.insert(Query::Planned(target.path.clone()).key());
}
for target in &new {
planned.add(path, target);
}
}
seen.extend(wave);
let more: BTreeSet<RepoPath> = cache
.readers_of(&moved)
.into_iter()
.filter(|p| is_checked_unit(model, cache, p) && !dirty.contains(p))
.collect();
dirty.extend(more);
}
Ok((captured, planned))
}
pub(super) fn is_not_found(e: &crate::Error) -> bool {
matches!(e, crate::Error::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
}
pub(super) fn ensure_not_missed(cache: &Cache) -> Result<()> {
if cache.missed() {
return Err(Error::Internal("the hint left out a removed file".into()));
}
Ok(())
}