sokf_core/model/loader.rs
1//! The `loader` module reads files and parses them for the model.
2
3use super::{Document, IndexFile, ParseMode, Parsed, parse_source};
4use crate::{RepoPath, RepoRoot, Result, Source, source};
5
6// sokf:begin loader
7/// A `Loader` reads files and parses them. An implementation can put a cache
8/// behind it.
9pub trait Loader {
10 /// `load` reads one file.
11 fn load(&mut self, path: &RepoPath) -> Result<Source>;
12
13 /// `parse` parses one source.
14 fn parse(&mut self, source: &Source, mode: ParseMode) -> Parsed {
15 parse_source(source, mode)
16 }
17
18 /// `document` reads and parses one document. When a cache is behind the
19 /// loader, `document` returns `None` for an unchanged document whose
20 /// results the cache already holds, until a check needs the document
21 /// (CACHE-1_AC-20).
22 fn document(&mut self, path: &RepoPath) -> Result<Option<Document>> {
23 self.full_document(path).map(Some)
24 }
25
26 /// `full_document` reads and parses one document, whatever the cache holds.
27 fn full_document(&mut self, path: &RepoPath) -> Result<Document> {
28 let source = self.load(path)?;
29 let parsed = self.parse(&source, ParseMode::Document);
30 Ok(Document::new(source, parsed))
31 }
32
33 /// `additional` reads the text of one additional file. When a cache is
34 /// behind the loader, `additional` returns `None` for an unchanged file
35 /// until a check needs the file (CACHE-1_AC-20).
36 fn additional(&mut self, path: &RepoPath) -> Result<Option<Source>> {
37 self.load(path).map(Some)
38 }
39
40 /// `schema` reads and parses one schema document. When a cache is behind
41 /// the loader, `schema` returns `None` for an unchanged schema until a
42 /// check needs the schema compiled (CACHE-1_AC-25).
43 fn schema(&mut self, path: &RepoPath) -> Result<Option<Document>> {
44 self.full_document(path).map(Some)
45 }
46
47 /// `index` reads one index file. When a cache is behind the loader, `index`
48 /// returns `None` for an unchanged index file until the check of the
49 /// file's directory needs the file (CACHE-1_AC-19).
50 fn index(&mut self, path: &RepoPath) -> Result<Option<IndexFile>> {
51 let source = self.load(path)?;
52 Ok(Some(IndexFile {
53 path: path.clone(),
54 source,
55 }))
56 }
57}
58// sokf:end loader
59
60/// `FsLoader` is a loader without a cache: it reads every file from disk.
61#[derive(Debug, Clone)]
62pub struct FsLoader<'a> {
63 root: &'a RepoRoot,
64}
65
66impl<'a> FsLoader<'a> {
67 /// `new` makes a loader that reads files under `root`.
68 pub fn new(root: &'a RepoRoot) -> Self {
69 FsLoader { root }
70 }
71}
72
73impl Loader for FsLoader<'_> {
74 fn load(&mut self, path: &RepoPath) -> Result<Source> {
75 source::load(self.root, path)
76 }
77}