Skip to main content

sokf_core/api/
load.rs

1//! The loaders walk the repository, sync the cache, and build the model
2//! that a command works on, and they read every file through the cache. A
3//! load for a check also computes the dirty set, the documents that the
4//! check runs on.
5
6use std::collections::BTreeSet;
7
8use super::{
9    admit::{admit_for_check, admit_full, admit_indexes, needed_slugs, unit_paths},
10    dirty::{additional_rows, changed_queries, key_query, schema_rows, scope_name},
11    markers::{is_checked_unit, scan_outside},
12};
13use crate::{
14    Cache, Compiled, Config, Document, Error, Expected, Model, RepoPath, RepoRoot, Result, Source,
15    Tree,
16    cache::DocRow,
17    check,
18    config::{self, RepoFormats},
19    grammar::{self, Grammar, RegexCache},
20    include,
21    model::{self, KeyIndex, Loader, ParseMode, PlanIndex, Query},
22    source, walk,
23};
24
25/// `Working` selects which documents a cached loader passes to the model
26/// builder.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28enum Working {
29    /// Every document, read in full.
30    All,
31    /// The loader reads only the changed documents, and the store's rows
32    /// stand in for the others until a check needs one.
33    Changed,
34}
35
36/// `CachedLoader` reads files through the cache: on each read, it records
37/// the file's source key in the cache.
38#[derive(Debug)]
39pub struct CachedLoader<'a> {
40    root: &'a RepoRoot,
41    cache: &'a Cache,
42    working: Working,
43}
44
45impl<'a> CachedLoader<'a> {
46    /// `new` makes a loader that reads under `root` through `cache` and
47    /// passes every document to the model builder.
48    pub fn new(root: &'a RepoRoot, cache: &'a Cache) -> Self {
49        CachedLoader {
50            root,
51            cache,
52            working: Working::All,
53        }
54    }
55
56    /// `changed_only` makes a loader that passes only the changed documents
57    /// to the model builder.
58    pub fn changed_only(root: &'a RepoRoot, cache: &'a Cache) -> Self {
59        CachedLoader {
60            root,
61            cache,
62            working: Working::Changed,
63        }
64    }
65
66    /// `stands_in` returns whether the store's row stands in for the file at
67    /// `path`: the loader reads only the changed files, and the file is
68    /// unchanged.
69    fn stands_in(&self, path: &RepoPath) -> bool {
70        self.working == Working::Changed && !self.cache.must_read(path)
71    }
72}
73
74impl Loader for CachedLoader<'_> {
75    // sokf-implements: CACHE-1_AC-2
76    // sokf-implements: CACHE-1_AC-3
77    fn load(&mut self, path: &RepoPath) -> Result<Source> {
78        let source = source::load(self.root, path).inspect_err(|e| {
79            if is_not_found(e) {
80                self.cache.note_missing();
81            }
82        })?;
83        self.cache.observe(path, &source.key);
84        Ok(source)
85    }
86
87    /// `document` returns `None` for an unchanged document when the loader
88    /// reads only the changed documents, because the store's row stands in
89    /// for it.
90    /// Otherwise it reads and parses the document, and records its row for
91    /// the commit.
92    // sokf-implements: CACHE-3_AC-1
93    fn document(&mut self, path: &RepoPath) -> Result<Option<Document>> {
94        if self.stands_in(path) {
95            return Ok(None);
96        }
97        self.full_document(path).map(Some)
98    }
99
100    /// `schema` returns `None` for an unchanged schema when the loader reads
101    /// only the changed files. A check that needs the compiled schema loads
102    /// the schema into the model.
103    // sokf-implements: CACHE-1_AC-25
104    // sokf-implements: CACHE-1_AC-42
105    fn schema(&mut self, path: &RepoPath) -> Result<Option<Document>> {
106        if self.stands_in(path) {
107            return Ok(None);
108        }
109        self.full_document(path).map(Some)
110    }
111
112    /// `additional` returns `None` for an unchanged additional file when the
113    /// loader reads only the changed files. The file's check reads the file
114    /// when the file is dirty.
115    // sokf-implements: CACHE-1_AC-20
116    fn additional(&mut self, path: &RepoPath) -> Result<Option<Source>> {
117        if self.stands_in(path) {
118            return Ok(None);
119        }
120        self.load(path).map(Some)
121    }
122
123    /// `index` returns `None` for an unchanged index file when the loader
124    /// reads only the changed files. The check of its directory reads the
125    /// index file when a change touched the directory.
126    // sokf-implements: CACHE-1_AC-19
127    fn index(&mut self, path: &RepoPath) -> Result<Option<crate::model::IndexFile>> {
128        if self.stands_in(path) {
129            return Ok(None);
130        }
131        let source = self.load(path)?;
132        Ok(Some(crate::model::IndexFile {
133            path: path.clone(),
134            source,
135        }))
136    }
137
138    fn full_document(&mut self, path: &RepoPath) -> Result<Document> {
139        let source = self.load(path)?;
140        let parsed = self.parse(&source, ParseMode::Document);
141        let doc = Document::new(source, parsed);
142        let knowledge = self.cache.knowledge_of(path).unwrap_or(0);
143        self.cache.record_row(path, DocRow::of(knowledge, &doc));
144        Ok(doc)
145    }
146}
147
148// sokf:begin loaded
149/// `Loaded` holds everything that a run derives from the tree before the run
150/// checks any document, and records what the run checks.
151pub struct Loaded {
152    /// The model: the documents to check and the documents that their
153    /// checks read, in full.
154    pub model: Model,
155    /// The compiled schemas.
156    pub compiled: Compiled,
157    /// The captured keys: this run's keys for the documents it checks, and
158    /// the store's keys for the others.
159    pub keys: KeyIndex,
160    /// The expected generated content of the files that the run checks.
161    pub expected: Expected,
162    /// The documents that this run checks: every document in a full run,
163    /// otherwise the dirty set.
164    pub dirty: BTreeSet<RepoPath>,
165    /// The directories whose index this run computes and checks: the
166    /// directories that a change touched, or `None` for every directory.
167    pub touched: Option<BTreeSet<RepoPath>>,
168    /// Whether this run checks every document.
169    pub full: bool,
170}
171// sokf:end loaded
172
173/// `load_model` walks the repository, syncs the cache, and builds the model
174/// through the cache, reading and parsing every document. The caller records
175/// the results that it derives from the model, then commits the cache.
176// sokf-implements: CACHE-1_AC-27
177pub fn load_model(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
178    let tree = walk_tree(root, config, cache)?;
179    cache.sync(&tree);
180    model::build(tree, &mut CachedLoader::new(root, cache))
181}
182
183/// `walk_tree` returns the file tree that this run works on. A hint is the
184/// list of changed paths that a caller passes in. Without a hint,
185/// `walk_tree` walks the repository. With a hint, it starts from the store's
186/// rows and lists each hinted path again by the walk's rules.
187// sokf-implements: CACHE-1_AC-23
188fn walk_tree(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Tree> {
189    cache.begin_run();
190    match cache.hint() {
191        Some(changed) => cache.tree_from_store(root, config, &changed),
192        None => walk::collect(root, config),
193    }
194}
195
196/// `load_working` walks the repository, syncs the cache, and builds the
197/// model from only the changed documents, with the store's rows standing in
198/// for the others. When the store has no rows to stand in for them,
199/// `load_working` reads every document.
200// sokf-implements: CACHE-3_AC-1
201// sokf-implements: CACHE-3_AC-2
202pub fn load_working(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
203    let tree = walk_tree(root, config, cache)?;
204    cache.sync(&tree);
205    match cache.view() {
206        Some(view) => model::build_with(
207            tree,
208            &mut CachedLoader::changed_only(root, cache),
209            Some(view),
210        ),
211        None => model::build(tree, &mut CachedLoader::new(root, cache)),
212    }
213}
214
215/// `load_with_keys` returns the model with every key captured, for a
216/// lookup under `--no-cache`. Such a lookup runs no check.
217pub fn load_with_keys(
218    root: &RepoRoot,
219    config: &Config,
220    cache: &Cache,
221) -> Result<(Model, KeyIndex)> {
222    let (grammar, repo_formats) = load_formats(root)?;
223    let model = load_model(root, config, cache)?;
224    // sokf-implements: CONF-12_AC-7
225    let texts = config::load_texts(root)?;
226    let compiled = grammar::compile_all(&model, grammar, &repo_formats, texts);
227    let keys = check::capture_keys_of(&model, &compiled, None);
228    Ok((model, keys))
229}
230
231/// `load_formats` loads the grammar and the repository's formats file.
232pub(super) fn load_formats(root: &RepoRoot) -> Result<(Grammar, RepoFormats)> {
233    let grammar = grammar::load_grammar()?;
234    let repo_formats = config::load_repo_formats(root, &grammar, &RegexCache::new())?;
235    Ok((grammar, repo_formats))
236}
237
238/// When the cache is on, `load_checked` runs the check that comes before a
239/// lookup. It checks the changes since the last check, as `validate` does,
240/// commits the result, and drops the findings. The store then holds the
241/// results of a check of the current tree, so the next command doesn't
242/// repeat the check. With `--no-cache` it returns `None`, because the run
243/// then uses a new, empty store that no later command reads.
244// sokf-implements: CACHE-1_AC-34
245// sokf-implements: CACHE-1_AC-35
246// sokf-implements: CACHE-1_AC-36
247pub fn load_checked(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Option<Loaded>> {
248    if !cache.is_on() {
249        return Ok(None);
250    }
251    let (grammar, repo_formats) = load_formats(root)?;
252    let (loaded, _) = super::validate::check_and_keep(
253        root,
254        config,
255        &grammar,
256        &repo_formats,
257        cache,
258        false,
259        false,
260    )?;
261    Ok(Some(loaded))
262}
263
264/// `load_for_lookup` returns the model that a lookup reads. With the cache
265/// on, this is the model of the check that `load_checked` ran: it holds the
266/// changed documents, and the store's rows stand in for the others. With
267/// `--no-cache`, `load_for_lookup` reads every document.
268// sokf-implements: CACHE-1_AC-21
269// sokf-implements: CACHE-1_AC-37
270pub fn load_for_lookup(root: &RepoRoot, config: &Config, cache: &Cache) -> Result<Model> {
271    match load_checked(root, config, cache)? {
272        Some(loaded) => Ok(loaded.model),
273        None => load_model(root, config, cache),
274    }
275}
276
277/// `load_keys_for` returns the model that a lookup reads, with the keys that
278/// a command resolves. With the cache on, the model is the one that
279/// `load_checked` checked, and the keys are the store's keys for `slugs`.
280/// Those keys are current, because `load_checked` commits its check before
281/// it returns. With `--no-cache`,
282/// `load_keys_for` captures every key.
283// sokf-implements: CACHE-1_AC-21
284pub fn load_keys_for(
285    root: &RepoRoot,
286    config: &Config,
287    cache: &Cache,
288    slugs: &BTreeSet<String>,
289) -> Result<(Model, KeyIndex)> {
290    let Some(loaded) = load_checked(root, config, cache)? else {
291        return load_with_keys(root, config, cache);
292    };
293    Ok((loaded.model, cache.stored_keys_for(slugs, &BTreeSet::new())))
294}
295
296/// `load_repository` loads everything that a full run needs: it walks the
297/// repository, loads every document, builds the model, compiles the
298/// schemas, captures the keys, and expands the generated content.
299pub fn load_repository(
300    root: &RepoRoot,
301    config: &Config,
302    grammar: &Grammar,
303    repo_formats: &RepoFormats,
304    cache: &Cache,
305) -> Result<Loaded> {
306    load_for_check(root, config, grammar, repo_formats, cache, true)
307}
308
309/// `load_for_check` walks the repository, syncs the cache, builds the
310/// model, and compiles the schemas. Then it loads the documents to check
311/// and captures their keys. A full run checks every document. Any other
312/// run checks the dirty set. A reader of a fact is a document whose check
313/// reads that fact. The changed documents and schemas are dirty. The
314/// readers of each fact, schema, or identity that changed are dirty. The
315/// readers of each schema that uses a format or type that changed in the
316/// formats file are dirty. A pass compares the keys of the new dirty
317/// documents with the store's keys, and the readers of each key that
318/// differs become dirty. Passes repeat until one adds no new document. A
319/// run is full when the caller asks for one or when the store is new.
320// sokf-implements: CLI-4_AC-20
321// sokf-implements: CACHE-1_AC-4
322// sokf-implements: CACHE-1_AC-15
323// sokf-implements: CACHE-1_AC-41
324pub(super) fn load_for_check(
325    root: &RepoRoot,
326    config: &Config,
327    grammar: &Grammar,
328    repo_formats: &RepoFormats,
329    cache: &Cache,
330    want_full: bool,
331) -> Result<Loaded> {
332    let mut model = if want_full {
333        load_model(root, config, cache)?
334    } else {
335        load_working(root, config, cache)?
336    };
337    let mut loader = CachedLoader::new(root, cache);
338    let identities_changed = cache.identities_changed(model.identity_rows());
339    let full = want_full || cache.is_fresh();
340    model.marker_check = config.markers;
341    let scanned = scan_outside(&mut model, cache, root, full);
342    // sokf-implements: CONF-12_AC-7
343    let texts = config::load_texts(root)?;
344    let mut compiled = grammar::compile_all(&model, grammar.clone(), repo_formats, texts);
345    let changes = Changes {
346        identities: identities_changed,
347        scanned,
348        formats: cache.formats_changed(repo_formats.hash, || {
349            grammar::fingerprint(&compiled.registry)
350        }),
351        schemas: cache.schemas_changed(schema_rows(&model, cache)),
352        additional: cache.additional_changed(additional_rows(&model)),
353    };
354    let mut touched: Option<BTreeSet<RepoPath>> = None;
355    let (dirty, keys) = if full {
356        let all = unit_paths(&model);
357        admit_full(&mut model, &mut loader, cache, &all)?;
358        ensure_not_missed(cache)?;
359        let keys = check::capture_keys_of(&model, &compiled, None);
360        model.plans = check::capture_plans_of(&model, &compiled, None);
361        (all, keys)
362    } else {
363        let (mut queries, dirs) = dirty_queries(&model, cache, root, &changes);
364        admit_indexes(&mut model, &mut loader, cache, &dirs);
365        touched = Some(dirs);
366        let mut dirty = first_dirty(&model, cache, changes, &mut queries);
367        let (mut captured, mut planned) =
368            spread_dirty(&mut model, &mut loader, cache, &mut compiled, &mut dirty)?;
369        let stored_plans = cache.stored_plans(&dirty);
370        for target in stored_plans.targets() {
371            for planner in stored_plans.planners(&target) {
372                planned.add(&planner, &target);
373            }
374        }
375        model.plans = planned;
376        let slugs = needed_slugs(&model, &captured);
377        captured.merge(cache.stored_keys_for(&slugs, &dirty));
378        (dirty, captured)
379    };
380    let expected = if full {
381        include::expected(&model, &keys)
382    } else {
383        include::expected_for(&model, &keys, Some(&dirty))
384    };
385    Ok(Loaded {
386        model,
387        compiled,
388        keys,
389        expected,
390        dirty,
391        touched,
392        full,
393    })
394}
395
396/// A `Changes` is what changed since the last run, besides the content of
397/// the files, that `load_for_check` reads to compute the dirty set.
398struct Changes {
399    /// Whether a store's current or former identity changed.
400    identities: bool,
401    /// The files whose markers changed.
402    scanned: Vec<RepoPath>,
403    /// The formats and types that changed in the formats file, or `None`
404    /// when the file is unchanged.
405    formats: Option<BTreeSet<String>>,
406    /// The schemas that changed, by knowledge and key.
407    schemas: BTreeSet<(usize, String)>,
408    /// The files whose status as an additional file changed.
409    additional: BTreeSet<RepoPath>,
410}
411
412/// `dirty_queries` returns the queries whose answers changed since the last
413/// run, and the directories that a change touched: the queries that the
414/// changed files answer, the queries of each changed schema, the query of
415/// the identities when one changed, and the query of each schema that uses
416/// a format or a type that changed in the formats file.
417// sokf-implements: CACHE-1_AC-16
418fn dirty_queries(
419    model: &Model,
420    cache: &Cache,
421    root: &RepoRoot,
422    changes: &Changes,
423) -> (BTreeSet<String>, BTreeSet<RepoPath>) {
424    let mut dirs: BTreeSet<RepoPath> = BTreeSet::new();
425    let mut queries = changed_queries(model, cache, root, &mut dirs);
426    for (knowledge, key) in &changes.schemas {
427        queries.insert(
428            Query::Schema {
429                knowledge: *knowledge,
430                key: key.clone(),
431            }
432            .key(),
433        );
434    }
435    if changes.identities {
436        queries.insert(Query::Identities.key());
437    }
438    // After an edit to the formats file, query the schemas that use a
439    // changed format or type. The documents that those schemas govern
440    // read the schemas, so those documents become dirty too.
441    // sokf-implements: CACHE-1_AC-17
442    if let Some(names) = &changes.formats {
443        for (k, knowledge) in model.knowledges.iter().enumerate() {
444            for (i, schema) in knowledge.schemas.iter().enumerate() {
445                if schema.uses.iter().any(|u| names.contains(u)) {
446                    queries.insert(
447                        Query::Schema {
448                            knowledge: k,
449                            key: knowledge.schema_key(i),
450                        }
451                        .key(),
452                    );
453                }
454            }
455        }
456    }
457    (queries, dirs)
458}
459
460/// `first_dirty` returns the documents that are dirty before any key is
461/// compared: the files whose content or markers changed, the files that a
462/// glob now matches, the readers of `queries`, and every schema document
463/// when a format changed. It adds the query of each file whose status as an
464/// additional file changed to `queries`, and it clears the stored findings
465/// and edges of such a file that is no longer an additional file.
466fn first_dirty(
467    model: &Model,
468    cache: &Cache,
469    changes: Changes,
470    queries: &mut BTreeSet<String>,
471) -> BTreeSet<RepoPath> {
472    // Only the files whose content changed are dirty. The sync reads a
473    // document again when its modification time lies within
474    // `RACY_MARGIN` of the last sync. Such a document stays clean when
475    // its content is the same.
476    let changed = cache.changed_set();
477    let mut dirty: BTreeSet<RepoPath> = model
478        .documents_and_schemas()
479        .map(|(_, d)| &d.path)
480        .chain(model.additional.iter().map(|a| &a.path))
481        .filter(|p| changed.contains(*p))
482        .cloned()
483        .collect();
484    // A file whose markers changed is dirty, so its check runs.
485    dirty.extend(changes.scanned);
486    // A file that a glob now matches is dirty, so its check runs. For a
487    // file that a glob no longer matches, the loader clears its output
488    // and its edges in the cache. The commit deletes every row of a file
489    // that the walk no longer lists, so the loader records nothing for it.
490    // sokf-implements: CACHE-1_AC-52
491    for path in changes.additional {
492        queries.insert(Query::Path(path.clone()).key());
493        if model.is_additional(&path) {
494            dirty.insert(path);
495        } else if model.tree.file(&path).is_some() {
496            cache.record_output(&path, Vec::new());
497            cache.record_edges(&path, Vec::new());
498        }
499    }
500    // The readers of the changed queries are dirty, except a reader that
501    // the walk no longer lists as a unit, because it has no check.
502    dirty.extend(
503        cache
504            .readers_of(queries)
505            .into_iter()
506            .filter(|p| is_checked_unit(model, cache, p)),
507    );
508    // When a format changed, was added, or was removed, every schema
509    // document is dirty, because its own check reads the examples of
510    // the whole registry.
511    // sokf-implements: CACHE-1_AC-40
512    if changes
513        .formats
514        .as_ref()
515        .is_some_and(|names| names.iter().any(|n| n.starts_with("f:")))
516    {
517        dirty.extend(
518            model
519                .knowledges
520                .iter()
521                .flat_map(|k| k.schemas.iter().map(|s| s.doc.path.clone()))
522                .filter(|p| is_checked_unit(model, cache, p)),
523        );
524    }
525    dirty
526}
527
528/// `spread_dirty` loads the documents in `dirty` for their check, captures
529/// their keys, their kept anchors, and their plans, and adds to `dirty` the
530/// readers of each key and each planned path that differs from the store's,
531/// in waves, until a wave adds no new document. A document whose keys or
532/// kept anchors differ from the store's also adds the readers of its id,
533/// because the resolution of a fragment of the document reads only its id.
534/// It returns the captured keys and plans.
535// sokf-implements: CACHE-1_AC-5
536fn spread_dirty(
537    model: &mut Model,
538    loader: &mut CachedLoader,
539    cache: &Cache,
540    compiled: &mut Compiled,
541    dirty: &mut BTreeSet<RepoPath>,
542) -> Result<(KeyIndex, PlanIndex)> {
543    // Compare the keys of the dirty documents with the store's keys: a
544    // key that differs from the store's makes its readers dirty. The
545    // loop repeats until no new document is dirty.
546    let mut captured = KeyIndex::default();
547    let mut planned = PlanIndex::default();
548    let mut seen: BTreeSet<RepoPath> = BTreeSet::new();
549    loop {
550        let wave: BTreeSet<RepoPath> = dirty.difference(&seen).cloned().collect();
551        if wave.is_empty() {
552            break;
553        }
554        admit_for_check(model, loader, cache, compiled, &wave)?;
555        let fresh = check::capture_keys_of(model, compiled, Some(&wave));
556        let mut moved: BTreeSet<String> = BTreeSet::new();
557        for path in &wave {
558            let old = cache.old_keys_of(path);
559            let new: BTreeSet<(String, String, usize)> = fresh
560                .of_document(path)
561                .map(|e| (scope_name(&e.scope), e.id.clone(), e.knowledge))
562                .collect();
563            for (scope, slug, k) in old.symmetric_difference(&new) {
564                moved.insert(key_query(scope, slug, *k));
565            }
566            // The resolution of a fragment of the document reads only its
567            // id. A fragment resolves to a key and to a kept anchor alike, so
568            // the two count as one set of slugs: a key whose unit breaks its
569            // rule and keeps its anchor changes no answer.
570            let mut was = cache.old_anchors_of(path);
571            was.extend(old.iter().map(|(_, slug, _)| slug.clone()));
572            let mut is: BTreeSet<String> = fresh.anchors_of(path).map(str::to_string).collect();
573            is.extend(new.iter().map(|(_, slug, _)| slug.clone()));
574            if was != is
575                && let Some(crate::Located::Document(k, doc)) = model.by_path(path)
576                && let Some(id) = doc.id()
577            {
578                moved.insert(
579                    Query::Doc {
580                        knowledge: k,
581                        id: id.to_string(),
582                    }
583                    .key(),
584                );
585            }
586        }
587        captured.merge(fresh);
588        // A path that a document starts or stops planning makes the
589        // readers of that path dirty (SOKF_SCHEMA_53).
590        let plans = check::capture_plans_of(model, compiled, Some(&wave));
591        for path in &wave {
592            let new = plans.of(path);
593            for target in cache.old_plans_of(path).symmetric_difference(&new) {
594                moved.insert(Query::Planned(target.path.clone()).key());
595            }
596            for target in &new {
597                planned.add(path, target);
598            }
599        }
600        seen.extend(wave);
601        let more: BTreeSet<RepoPath> = cache
602            .readers_of(&moved)
603            .into_iter()
604            .filter(|p| is_checked_unit(model, cache, p) && !dirty.contains(p))
605            .collect();
606        dirty.extend(more);
607    }
608    Ok((captured, planned))
609}
610
611/// `is_not_found` returns whether `e` is the I/O error of a missing file.
612pub(super) fn is_not_found(e: &crate::Error) -> bool {
613    matches!(e, crate::Error::Io { source, .. } if source.kind() == std::io::ErrorKind::NotFound)
614}
615
616/// `ensure_not_missed` stops a run with an error when its hint left out a
617/// removed file that the run read. `check_and_keep` and the fix loop of
618/// `validate` catch the error and run again without the hint, so it never
619/// reaches the caller.
620pub(super) fn ensure_not_missed(cache: &Cache) -> Result<()> {
621    if cache.missed() {
622        return Err(Error::Internal("the hint left out a removed file".into()));
623    }
624    Ok(())
625}