Skip to main content

sokf_core/grammar/
compile.rs

1//! `compile_all` checks the schema of every Schema document against the
2//! grammar and turns it into the form that the checks use. It does this once
3//! per run.
4//!
5//! Check, Fix, and Scaffold share the compiled schemas.
6
7use super::{FormatRegistry, Grammar, RegexCache, SokfSchema, compile, embedded_formats};
8use crate::{
9    Finding, Model, RepoPath,
10    config::{RepoFormats, Texts},
11    model::SchemaRef,
12};
13
14/// `Compiled` holds the grammar and the compiled schemas of one run.
15#[derive(Debug)]
16pub struct Compiled {
17    /// `grammar` holds the grammar that each schema is checked against.
18    pub grammar: Grammar,
19    /// `registry` holds the formats that schemas can use: the embedded
20    /// formats, then the layer `formats.d`, then the repository's formats, each
21    /// layer replacing a format of the same name in the layers under it.
22    pub registry: FormatRegistry,
23    /// `regexes` holds each regular expression that the schemas use, so that
24    /// each one is compiled only once.
25    pub regexes: RegexCache,
26    /// `schema_document` is the schema that Schema documents follow, compiled
27    /// from the grammar's `schema-document` section.
28    pub schema_document: SokfSchema,
29    /// `schemas` holds the schema of each Schema document. An entry is `None`
30    /// when the schema doesn't conform to the grammar, or when the run hasn't
31    /// read the document.
32    pub schemas: Vec<(SchemaRef, Option<SokfSchema>)>,
33    /// `texts` holds sokf's own texts, from which each host takes the words
34    /// of a label in the language of a schema, so that a check, a scaffold,
35    /// and a guide give a label the same words (`SOKF_SCHEMA_107`).
36    pub texts: Texts,
37    /// `problems` holds the findings that compiling the schemas produced.
38    pub problems: Vec<Finding>,
39    /// `done` holds every schema compiled so far, including those that failed.
40    done: std::collections::HashSet<SchemaRef>,
41    /// `rebased` holds, for each store and each schema that the store
42    /// inherits and that declares a `root` or `asset-files` globs, a copy
43    /// of the compiled schema whose paths lie under the inheriting store
44    /// (`SOKF_SCHEMA_98`).
45    rebased: std::collections::HashMap<(usize, SchemaRef), SokfSchema>,
46}
47
48impl Compiled {
49    /// `compile_more` compiles every schema that the model has read since the
50    /// last call. Those are the schemas that a check looked up for a
51    /// document's type (CACHE-1_AC-25).
52    pub fn compile_more(&mut self, model: &Model) {
53        for (k, knowledge) in model.knowledges.iter().enumerate() {
54            for (i, schema) in knowledge.schemas.iter().enumerate() {
55                let r = SchemaRef {
56                    knowledge: k,
57                    index: i,
58                };
59                if !schema.loaded || self.done.contains(&r) {
60                    continue;
61                }
62                let compiled = compile_one(
63                    schema,
64                    &knowledge.root,
65                    &self.grammar,
66                    &self.registry,
67                    &self.regexes,
68                    &mut self.problems,
69                );
70                match self.schemas.iter_mut().find(|(s, _)| *s == r) {
71                    Some(slot) => slot.1 = compiled,
72                    None => self.schemas.push((r, compiled)),
73                }
74                self.done.insert(r);
75            }
76        }
77        self.rebase_inherited(model);
78    }
79
80    /// `rebase_inherited` adds a rebased copy of each compiled schema that a
81    /// store inherits, where the schema declares a `root` or `asset-files`
82    /// globs and the run holds no copy for that store yet.
83    // sokf-implements: SOKF_SCHEMA_98
84    // sokf-implements: FORMAT-5_AC-6
85    fn rebase_inherited(&mut self, model: &Model) {
86        for k in 0..model.knowledges.len() {
87            for r in model.inherited(k) {
88                if self.rebased.contains_key(&(k, r)) {
89                    continue;
90                }
91                let Some(source) = self.schema(r) else {
92                    continue;
93                };
94                if source.root.is_none() && source.asset_files.is_empty() {
95                    continue;
96                }
97                let (from, to) = (
98                    &model.knowledges[r.knowledge].root,
99                    &model.knowledges[k].root,
100                );
101                let mut copy = source.clone();
102                copy.root = copy
103                    .root
104                    .as_deref()
105                    .map(|root| crate::model::extends::rebase(root, from, to));
106                copy.asset_files = copy
107                    .asset_files
108                    .iter()
109                    .map(|g| crate::model::extends::rebase(g, from, to))
110                    .collect();
111                self.rebased.insert((k, r), copy);
112            }
113        }
114    }
115    /// `schema` returns the schema of Schema document `r`, or `None` when the
116    /// schema hasn't compiled.
117    pub fn schema(&self, r: SchemaRef) -> Option<&SokfSchema> {
118        self.schemas
119            .iter()
120            .find(|(s, _)| *s == r)
121            .and_then(|(_, c)| c.as_ref())
122    }
123
124    /// `for_type` returns the schema that governs `type_name` in `knowledge`,
125    /// its own or an inherited one, when exactly one schema declares the type
126    /// and that schema compiled. An inherited schema comes as its copy for
127    /// `knowledge`, where it has one. It records that the caller asked for
128    /// the type's schema in each store of the chain that it read
129    /// (CACHE-1_AC-25).
130    // sokf-implements: SOKF_SCHEMA_96
131    // sokf-implements: SOKF_SCHEMA_97
132    // sokf-implements: FORMAT-5_AC-5
133    pub fn for_type(
134        &self,
135        model: &Model,
136        knowledge: usize,
137        type_name: &str,
138    ) -> Option<(SchemaRef, &SokfSchema)> {
139        match model.claimants(knowledge, type_name).as_slice() {
140            [r] => self.for_ref(knowledge, *r).map(|s| (*r, s)),
141            _ => None,
142        }
143    }
144
145    /// `for_ref` returns the compiled schema `r` as it governs the documents
146    /// of `knowledge`: its copy for `knowledge` when `knowledge` inherits it
147    /// and its paths move, and the schema itself otherwise.
148    pub fn for_ref(&self, knowledge: usize, r: SchemaRef) -> Option<&SokfSchema> {
149        self.rebased.get(&(knowledge, r)).or_else(|| self.schema(r))
150    }
151
152    /// `for_doc` returns the schema that governs the type of `doc` in
153    /// `knowledge`, as `for_type` does, or `None` for a document without a
154    /// type.
155    pub fn for_doc(
156        &self,
157        model: &Model,
158        knowledge: usize,
159        doc: &crate::Document,
160    ) -> Option<(SchemaRef, &SokfSchema)> {
161        doc.type_name()
162            .and_then(|t| self.for_type(model, knowledge, t))
163    }
164
165    /// `broken_for_doc` returns whether exactly one schema declares the type
166    /// of `doc` in `knowledge` and that schema hasn't compiled. The check
167    /// reports such a document under `SOKF_VALIDATION_41`.
168    pub fn broken_for_doc(&self, model: &Model, knowledge: usize, doc: &crate::Document) -> bool {
169        doc.type_name()
170            .is_some_and(|t| match model.claimants(knowledge, t).as_slice() {
171                [r] => self.for_ref(knowledge, *r).is_none(),
172                _ => false,
173            })
174    }
175}
176
177/// `compile_all` compiles the grammar's `schema-document` schema and every
178/// schema that the model has read, with `texts`, sokf's own texts, for the
179/// hosts that read them.
180// sokf-implements: SOKF_SCHEMA_15
181// sokf-implements: SOKF_SCHEMA_43
182// sokf-implements: SOKF_SCHEMA_107
183pub fn compile_all(
184    model: &Model,
185    grammar: Grammar,
186    formats: &RepoFormats,
187    texts: Texts,
188) -> Compiled {
189    let regexes = RegexCache::new();
190    let mut problems = Vec::new();
191    let embedded = embedded_formats(&grammar, &regexes).unwrap_or_default();
192    let registry = formats.effective(&embedded);
193    // The schema extension is embedded, and a test checks that it has a
194    // `schema-document` section.
195    let written = grammar
196        .section("schema-document")
197        .expect("SOKF's schema extension has a `schema-document` section");
198    let (schema_document, findings) = compile(
199        written,
200        &grammar,
201        &registry,
202        &regexes,
203        &RepoPath::root(),
204        "grammar",
205    )
206    .unwrap_or_else(|findings| {
207        (
208            SokfSchema::of_schema_document(super::Schema::demand_nothing()),
209            findings,
210        )
211    });
212    problems.extend(findings);
213
214    let mut compiled = Compiled {
215        grammar,
216        registry,
217        regexes,
218        schema_document,
219        schemas: Vec::new(),
220        texts,
221        problems,
222        done: std::collections::HashSet::new(),
223        rebased: std::collections::HashMap::new(),
224    };
225    // Every schema gets an entry, so that each reference to a schema resolves.
226    // `compile_more` compiles the schemas that the run has read, and the rest
227    // wait for a later call.
228    for (k, knowledge) in model.knowledges.iter().enumerate() {
229        for i in 0..knowledge.schemas.len() {
230            compiled.schemas.push((
231                SchemaRef {
232                    knowledge: k,
233                    index: i,
234                },
235                None,
236            ));
237        }
238    }
239    compiled.compile_more(model);
240    compiled
241}
242
243/// `compile_one` compiles one Schema document and pushes its problems onto
244/// `problems`.
245fn compile_one(
246    schema: &crate::model::SchemaDocument,
247    knowledge_root: &RepoPath,
248    grammar: &Grammar,
249    registry: &FormatRegistry,
250    regexes: &RegexCache,
251    problems: &mut Vec<Finding>,
252) -> Option<SokfSchema> {
253    if let Some(p) = &schema.schema_problem {
254        problems.push(p.clone());
255    }
256    let yaml = schema.schema_yaml.as_ref()?;
257    match compile(
258        yaml,
259        grammar,
260        registry,
261        regexes,
262        &schema.doc.path,
263        &schema.id(),
264    ) {
265        Ok((c, warnings)) => {
266            // A warning leaves the schema in force, and the run reports it on
267            // the Schema document (`EXT-1_AC-5`).
268            problems.extend(warnings);
269            if let Some(root) = &c.root {
270                let inside = RepoPath::parse(root).is_some_and(|r| r.starts_with(knowledge_root));
271                if !inside {
272                    problems.push(Finding::error(
273                        schema.doc.path.clone(),
274                        yaml.key_line("root"),
275                        "SOKF_SCHEMA_27",
276                        format!("`root` {root} lies outside the knowledge {knowledge_root}"),
277                    ));
278                }
279            }
280            Some(c)
281        }
282        Err(findings) => {
283            problems.extend(findings);
284            None
285        }
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use std::{fs, path::PathBuf};
292
293    use super::*;
294    use crate::{Config, FsLoader, RepoRoot, build, collect, grammar::Dispatch, load_grammar};
295
296    fn temp(name: &str) -> PathBuf {
297        let dir = crate::test_support::fresh_dir(&format!("compile-{name}"));
298        fs::create_dir_all(dir.join("knowledge/schemas")).unwrap();
299        fs::write(
300            dir.join("knowledge/manifest.sokf.yaml"),
301            "sokf: \"0.7\"\nname: k\nscope: test\n",
302        )
303        .unwrap();
304        fs::write(
305            dir.join("knowledge/schemas/note.md"),
306            "---\ntype: Schema\nid: schema-note\n---\n\n````yaml\nline-limit: 0\nfrontmatter:\n  type:\n    const: Note\nsections: []\n````\n",
307        )
308        .unwrap();
309        fs::write(
310            dir.join("knowledge/schemas/bad.md"),
311            "---\ntype: Schema\nid: schema-bad\n---\n\n````yaml\nbogus: 1\n````\n",
312        )
313        .unwrap();
314        fs::write(
315            dir.join("knowledge/schemas/outside.md"),
316            "---\ntype: Schema\nid: schema-outside\n---\n\n````yaml\nline-limit: 0\nroot: /elsewhere\nlifecycle:\n  - {key: s, states: [a], path: true}\nfrontmatter:\n  type:\n    const: Issue\nsections: []\n````\n",
317        )
318        .unwrap();
319        fs::write(
320            dir.join("knowledge/schemas/none.md"),
321            "---\ntype: Schema\nid: schema-none\n---\n\nno fence\n",
322        )
323        .unwrap();
324        dir
325    }
326
327    #[test]
328    fn compiles_every_schema_and_the_grammar_schema_document() {
329        let dir = temp("compile");
330        let root = RepoRoot::new(dir.clone());
331        let tree = collect(&root, &Config::default()).unwrap();
332        let model = build(tree, &mut FsLoader::new(&root)).unwrap();
333        let compiled = compile_all(
334            &model,
335            load_grammar().unwrap(),
336            &RepoFormats::default(),
337            Texts::english(),
338        );
339        assert_eq!(
340            compiled.schema_document.dispatch,
341            Dispatch::Type("Schema".into())
342        );
343        assert!(compiled.schema_document.core.preamble.is_some());
344        assert_eq!(compiled.schemas.len(), 4);
345        // The schemas sort by path: bad, none, note, outside.
346        assert!(
347            compiled
348                .schema(SchemaRef {
349                    knowledge: 0,
350                    index: 2
351                })
352                .is_some()
353        );
354        assert!(
355            compiled
356                .schema(SchemaRef {
357                    knowledge: 0,
358                    index: 0
359                })
360                .is_none()
361        );
362        assert!(
363            compiled
364                .schema(SchemaRef {
365                    knowledge: 0,
366                    index: 1
367                })
368                .is_none()
369        );
370        assert!(compiled.for_type(&model, 0, "Note").is_some());
371        assert!(compiled.for_type(&model, 0, "Nope").is_none());
372        assert!(compiled.for_type(&model, 1, "Note").is_none());
373        let messages: Vec<&str> = compiled
374            .problems
375            .iter()
376            .map(|f| f.message.as_str())
377            .collect();
378        assert!(
379            messages.iter().any(|m| m.contains("unknown key `bogus`")),
380            "{messages:?}"
381        );
382        assert!(
383            messages
384                .iter()
385                .any(|m| m.contains("lies outside the knowledge")),
386            "{messages:?}"
387        );
388        assert!(
389            messages.iter().any(|m| m.contains("no YAML fence")),
390            "{messages:?}"
391        );
392        assert!(compiled.registry.types_seen().get("ref").is_some());
393        fs::remove_dir_all(&dir).unwrap();
394    }
395}