Skip to main content

sokf_core/model/
document.rs

1//! This module defines the parsed forms of a knowledge's files: documents,
2//! schema documents, additional files, assets, and index files.
3
4use serde::{Deserialize, Serialize};
5
6use super::{CoreFields, core_fields};
7use crate::{
8    Body, Finding, RepoPath, Segments, Source, Spanned,
9    markdown::{self, BlockKind},
10    source, yaml,
11};
12
13/// `ParseMode` says how to parse a file.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum ParseMode {
16    /// `Document` parses a frontmatter block, then a body.
17    Document,
18    /// `Plain` parses a body only, with no frontmatter.
19    Plain,
20}
21
22/// `Parsed` holds the result of parsing one file.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct Parsed {
25    /// The frontmatter, when the file has one and it parses.
26    pub frontmatter: Option<Spanned>,
27    /// The core fields.
28    pub core: CoreFields,
29    /// The body.
30    pub body: Body,
31    /// The markers.
32    pub segments: Segments,
33    /// The line the body starts on.
34    pub body_line: usize,
35    /// Whether the file opens with a frontmatter block, parsed or not.
36    pub frontmatter_found: bool,
37}
38
39/// `parse_source` parses `source` in the given `mode`.
40pub fn parse_source(source: &Source, mode: ParseMode) -> Parsed {
41    let (frontmatter, text, body_line) = match mode {
42        ParseMode::Document => {
43            let split = source::split(source);
44            (split.frontmatter, split.body, split.body_line)
45        }
46        ParseMode::Plain => (None, source.text.as_str(), 1),
47    };
48    let yaml = frontmatter.map(|(text, line)| yaml::parse(text, line));
49    // A plain file has no frontmatter to miss, so it has no core fields.
50    let core = match mode {
51        ParseMode::Document => core_fields(yaml.as_ref().map(|r| r.as_ref()), &source.path),
52        ParseMode::Plain => CoreFields::default(),
53    };
54    let segments = markdown::segments(text, body_line);
55    let body = markdown::parse(text, body_line, &segments);
56    Parsed {
57        frontmatter: yaml.and_then(Result::ok),
58        core,
59        body,
60        segments,
61        body_line,
62        frontmatter_found: frontmatter.is_some(),
63    }
64}
65
66// sokf:begin document
67/// A `Document` is one parsed document.
68#[derive(Debug, Clone, PartialEq)]
69pub struct Document {
70    /// The file.
71    pub path: RepoPath,
72    /// The text.
73    pub source: Source,
74    /// The frontmatter, when it parses.
75    pub frontmatter: Option<Spanned>,
76    /// The core fields.
77    pub core: CoreFields,
78    /// The body.
79    pub body: Body,
80    /// The markers.
81    pub segments: Segments,
82    /// The line the body starts on.
83    pub body_line: usize,
84    /// The number of lines in the file.
85    pub lines: usize,
86    /// Whether the file opens with a frontmatter block, parsed or not.
87    pub frontmatter_found: bool,
88}
89// sokf:end document
90
91/// `Visible` holds only the parts of a document that the checks of other
92/// documents read. A change anywhere else, such as to a line number or a code
93/// span, therefore leaves the checks of other documents up to date
94/// (CACHE-1_AC-5).
95#[derive(Serialize)]
96struct Visible<'a> {
97    id: Option<&'a str>,
98    type_: Option<&'a str>,
99    title: Option<&'a str>,
100    description: Option<&'a str>,
101    status: Option<super::Status>,
102    resource: Option<&'a super::Resource>,
103    headings: Vec<(u8, &'a str, &'a str)>,
104    anchors: Vec<&'a str>,
105    frontmatter_found: bool,
106}
107
108impl Document {
109    /// `new` assembles a document from its source and the result of parsing it.
110    pub fn new(source: Source, parsed: Parsed) -> Self {
111        Document {
112            path: source.path.clone(),
113            lines: source.line_count(),
114            source,
115            frontmatter: parsed.frontmatter,
116            core: parsed.core,
117            body: parsed.body,
118            segments: parsed.segments,
119            body_line: parsed.body_line,
120            frontmatter_found: parsed.frontmatter_found,
121        }
122    }
123
124    /// `visible_hash` returns the hash of the parts of this document that the
125    /// checks of other documents read: its id, type, title, description,
126    /// status, resource, headings, anchors, and whether it has a frontmatter
127    /// block (CACHE-1_AC-13). The headings include each heading inside a
128    /// quote or a list item, because a link can refer to it.
129    pub fn visible_hash(&self) -> u64 {
130        let headings = crate::markdown::link_headings(&self.body);
131        let visible = Visible {
132            id: self.core.id.as_deref(),
133            type_: self.core.type_.as_deref(),
134            title: self.core.title.as_deref(),
135            description: self.core.description.as_deref(),
136            status: self.core.status,
137            resource: self.core.resource.as_ref(),
138            headings: headings
139                .iter()
140                .map(|h| (h.level, h.text.as_str(), h.slug.as_str()))
141                .collect(),
142            anchors: self.body.anchors.iter().map(|a| a.id.as_str()).collect(),
143            frontmatter_found: self.frontmatter_found,
144        };
145        source::fnv1a64(&serde_json::to_vec(&visible).unwrap_or_default())
146    }
147
148    /// `line_count` returns the number of lines in the file.
149    pub fn line_count(&self) -> usize {
150        self.lines
151    }
152
153    /// `body_text` returns the text of the body: everything after the
154    /// frontmatter.
155    pub fn body_text(&self) -> &str {
156        source::split(&self.source).body
157    }
158
159    /// `id` returns the document's `id`, if it has one.
160    pub fn id(&self) -> Option<&str> {
161        self.core.id.as_deref()
162    }
163
164    /// `type_name` returns the document's `type`, if it has one.
165    pub fn type_name(&self) -> Option<&str> {
166        self.core.type_.as_deref()
167    }
168}
169
170/// A `SchemaDocument` is a schema document together with the schema it holds,
171/// parsed as YAML. When the run has not read the schema file, it is instead a
172/// placeholder that the run builds from the store's record. The placeholder
173/// holds the id, the `type` const, and the globs, but no text. It stays a
174/// placeholder until a check needs the compiled schema (CACHE-1_AC-25).
175#[derive(Debug, Clone, PartialEq)]
176pub struct SchemaDocument {
177    /// The document, or a placeholder with no text when the run has not
178    /// read the file.
179    pub doc: Document,
180    /// The schema, parsed from the four-backtick YAML fence.
181    pub schema_yaml: Option<Spanned>,
182    /// Why the schema is absent, when it is.
183    pub schema_problem: Option<Finding>,
184    /// The `additional-files` globs, read before compilation.
185    pub globs: Vec<String>,
186    /// The `asset-files` globs, read before compilation.
187    pub asset_globs: Vec<String>,
188    /// The `type` const, read before compilation.
189    pub type_const: Option<String>,
190    /// The registry names that the schema's text uses, `t:<type>` and
191    /// `f:<format>`. When the formats change, the run uses these names to
192    /// find the schemas that the change affects (CACHE-1_AC-17).
193    pub uses: Vec<String>,
194    /// Whether and how the schema archives its documents, read before
195    /// compilation.
196    pub archived: super::Archived,
197    /// Whether the run read the file. It is false for a placeholder from the
198    /// store.
199    pub loaded: bool,
200}
201
202impl SchemaDocument {
203    /// `finding` returns an error about the schema, at the line where its
204    /// body starts.
205    pub fn finding(&self, criterion: &'static str, message: impl Into<String>) -> Finding {
206        Finding::error(
207            self.doc.path.clone(),
208            Some(self.doc.body_line),
209            criterion,
210            message,
211        )
212    }
213
214    /// `placeholder` builds a schema document from the store's record of a
215    /// schema file that the run has not read (CACHE-1_AC-25). A check can
216    /// use the placeholder only to dispatch on its type, to match globs, and
217    /// to read its id.
218    pub fn placeholder(path: RepoPath, meta: super::SchemaMeta) -> Self {
219        let source = Source::from_text(path, "");
220        let mut doc = Document::new(source.clone(), parse_source(&source, ParseMode::Document));
221        doc.core.id = meta.id;
222        doc.core.type_ = Some("Schema".to_string());
223        doc.body_line = meta.body_line;
224        SchemaDocument {
225            doc,
226            schema_yaml: None,
227            schema_problem: None,
228            globs: meta.globs,
229            asset_globs: meta.asset_globs,
230            type_const: meta.type_const,
231            uses: meta.uses,
232            archived: meta.archived,
233            loaded: false,
234        }
235    }
236
237    /// `new` extracts the schema from the YAML fence of a parsed schema
238    /// document, and records why the schema is absent when it is.
239    pub fn new(doc: Document) -> Self {
240        let mut schema_yaml = None;
241        let mut schema_problem = None;
242        let fence = doc.body.blocks.iter().find(|b| b.kind == BlockKind::Code);
243        match fence {
244            Some(block) => {
245                let text = block.units.first().map_or("", |u| u.text.as_str());
246                match yaml::parse(text, block.line + 1) {
247                    Ok(y) => schema_yaml = Some(y),
248                    Err(e) => {
249                        schema_problem = Some(Finding::error(
250                            doc.path.clone(),
251                            Some(e.line()),
252                            "SOKF_SCHEMA_2",
253                            format!("schema: {e}"),
254                        ));
255                    }
256                }
257            }
258            None => {
259                schema_problem = Some(Finding::error(
260                    doc.path.clone(),
261                    Some(doc.body_line),
262                    "SOKF_SCHEMA_1",
263                    "the Schema document has no schema because it has no YAML fence",
264                ));
265            }
266        }
267        let list = |key: &str| {
268            schema_yaml
269                .as_ref()
270                .and_then(|c| c.get(key))
271                .and_then(Spanned::as_str_or_list)
272                .unwrap_or_default()
273        };
274        let (globs, asset_globs) = (list("additional-files"), list("asset-files"));
275        let type_const = schema_yaml
276            .as_ref()
277            .and_then(|c| c.get("frontmatter"))
278            .and_then(|f| f.get("type"))
279            .and_then(|t| t.get("const"))
280            .and_then(Spanned::scalar_text);
281        let uses = crate::grammar::schema_uses(&doc.source.text);
282        let archived = schema_yaml
283            .as_ref()
284            .map(super::Archived::of_schema)
285            .unwrap_or_default();
286        SchemaDocument {
287            doc,
288            schema_yaml,
289            schema_problem,
290            globs,
291            asset_globs,
292            type_const,
293            uses,
294            archived,
295            loaded: true,
296        }
297    }
298
299    /// `id` returns the schema's `id`, or its file name without `.md` when it
300    /// has no `id`.
301    pub fn id(&self) -> String {
302        self.doc.id().map_or_else(
303            || {
304                self.doc
305                    .path
306                    .file_name()
307                    .trim_end_matches(".md")
308                    .to_string()
309            },
310            str::to_string,
311        )
312    }
313}
314
315/// A `SchemaRef` identifies a schema by its knowledge and its index in that
316/// knowledge.
317#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
318pub struct SchemaRef {
319    /// The knowledge.
320    pub knowledge: usize,
321    /// The schema's index in the knowledge.
322    pub index: usize,
323}
324
325/// An `AdditionalFile` is a repository file that a schema governs through
326/// its `additional-files` globs.
327#[derive(Debug, Clone, PartialEq)]
328pub struct AdditionalFile {
329    /// The file.
330    pub path: RepoPath,
331    /// The text.
332    pub source: Source,
333    /// The body.
334    pub body: Body,
335    /// The markers.
336    pub segments: Segments,
337    /// The schema whose glob matches, when exactly one schema's glob does.
338    pub schema: Option<SchemaRef>,
339}
340
341/// An `Asset` is a file that a schema's `asset-files` glob matches
342/// (FORMAT-1_AC-1). The tool never reads its content (FORMAT-1_AC-6).
343#[derive(Debug, Clone, PartialEq, Eq)]
344pub struct Asset {
345    /// The file.
346    pub path: RepoPath,
347    /// The schema whose glob matches.
348    pub schema: SchemaRef,
349    /// The sidecar's index in the knowledge's documents, when the `.md` file
350    /// beside the asset exists and the run has read it.
351    pub sidecar: Option<usize>,
352    /// Whether the `.md` file beside the asset is a document that the run
353    /// has read or that the store records.
354    pub has_sidecar: bool,
355}
356
357impl Asset {
358    /// `sidecar_path` returns the path of the asset's sidecar, whether or not
359    /// the sidecar exists: the asset's path with `.md` appended.
360    pub fn sidecar_path(&self) -> RepoPath {
361        sidecar_path(&self.path)
362    }
363}
364
365/// `sidecar_path` returns the path of the sidecar for an asset at `path`
366/// (`SOKF_FORMAT_4`).
367pub fn sidecar_path(path: &RepoPath) -> RepoPath {
368    RepoPath::parse(&format!("{path}.md")).expect("a path plus `.md` is a path")
369}
370
371/// An `IndexFile` is an `index.md` file, held as text only. The tool
372/// generates its whole content (`SOKF_FORMAT_97`), so the tool does not parse
373/// it.
374#[derive(Debug, Clone, PartialEq)]
375pub struct IndexFile {
376    /// The file.
377    pub path: RepoPath,
378    /// The text.
379    pub source: Source,
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    fn src(text: &str) -> Source {
387        Source::from_text(RepoPath::parse("/k/schemas/s.md").unwrap(), text)
388    }
389
390    #[test]
391    fn parses_documents_and_plain_files() {
392        let s = src("---\ntype: A\nid: a\n---\n\n# T\n\n<!-- sokf:links -->\n");
393        let p = parse_source(&s, ParseMode::Document);
394        assert_eq!(p.core.type_.as_deref(), Some("A"));
395        assert_eq!(p.body.headings[0].line, 6);
396        assert_eq!(p.body_line, 5);
397        assert!(p.segments.definition.is_some());
398        let d = Document::new(s.clone(), p);
399        assert_eq!(d.line_count(), 8);
400        assert_eq!(d.body_text(), "\n# T\n\n<!-- sokf:links -->\n");
401        assert_eq!(d.id(), Some("a"));
402        assert_eq!(d.type_name(), Some("A"));
403        let plain = parse_source(&src("---\nnot: fm\n---\n# H\n"), ParseMode::Plain);
404        assert!(plain.frontmatter.is_none());
405        assert_eq!(
406            plain
407                .body
408                .headings
409                .iter()
410                .find(|h| h.text == "H")
411                .unwrap()
412                .line,
413            4
414        );
415        assert!(!plain.core.present);
416        let json = serde_json::to_string(&plain).unwrap();
417        let back: Parsed = serde_json::from_str(&json).unwrap();
418        assert_eq!(back, plain);
419    }
420
421    // sokf-tests: CACHE-1_AC-5
422    #[test]
423    fn a_line_shift_is_not_visible_and_a_title_is() {
424        let text = "---\ntype: A\nid: a\ntitle: T\n---\n\n# T\n\nSee [b][sokf:b].\n";
425        let doc = |t: &str| {
426            let s = Source::from_text(RepoPath::parse("/k/a.md").unwrap(), t);
427            Document::new(s.clone(), parse_source(&s, ParseMode::Document))
428        };
429        let full = doc(text);
430        let shifted = doc(&text.replacen("# T\n", "\n\n# T\n", 1));
431        assert_ne!(shifted.body.headings[0].line, full.body.headings[0].line);
432        assert_eq!(shifted.visible_hash(), full.visible_hash());
433        let renamed = doc(&text.replacen("title: T", "title: U", 1));
434        assert_ne!(renamed.visible_hash(), full.visible_hash());
435        let reheaded = doc(&text.replacen("# T\n", "# U\n", 1));
436        assert_ne!(reheaded.visible_hash(), full.visible_hash());
437    }
438
439    #[test]
440    fn schemas_extract_their_schema() {
441        let s = src(
442            "---\ntype: Schema\nid: schema-x\n---\n\n````yaml\nadditional-files: [/README.md]\nasset-files: '/k/media/**/*.png'\nfrontmatter:\n  type:\n    const: X\n````\n",
443        );
444        let schema = SchemaDocument::new(Document::new(
445            s.clone(),
446            parse_source(&s, ParseMode::Document),
447        ));
448        assert_eq!(schema.globs, vec!["/README.md"]);
449        assert_eq!(schema.asset_globs, vec!["/k/media/**/*.png"]);
450        assert_eq!(schema.type_const.as_deref(), Some("X"));
451        assert_eq!(
452            sidecar_path(&RepoPath::parse("/k/media/a.png").unwrap()).as_str(),
453            "/k/media/a.png.md"
454        );
455        assert_eq!(
456            schema
457                .schema_yaml
458                .as_ref()
459                .unwrap()
460                .get("additional-files")
461                .unwrap()
462                .line,
463            7
464        );
465        assert_eq!(schema.id(), "schema-x");
466        assert!(schema.schema_problem.is_none());
467        let none = src("---\ntype: Schema\n---\n\nno fence\n");
468        let schema = SchemaDocument::new(Document::new(
469            none.clone(),
470            parse_source(&none, ParseMode::Document),
471        ));
472        assert!(schema.schema_yaml.is_none());
473        assert!(
474            schema
475                .schema_problem
476                .as_ref()
477                .unwrap()
478                .message
479                .contains("no YAML fence")
480        );
481        assert_eq!(schema.id(), "s");
482        let bad = src("---\ntype: Schema\n---\n\n````yaml\na: &x 1\n````\n");
483        let schema = SchemaDocument::new(Document::new(
484            bad.clone(),
485            parse_source(&bad, ParseMode::Document),
486        ));
487        let problem = schema.schema_problem.unwrap();
488        assert_eq!(problem.line, Some(6));
489        assert!(problem.message.contains("anchor"));
490    }
491}