Skip to main content

sokf_core/model/
frontmatter.rs

1//! This module parses a document's frontmatter into `CoreFields`, as the
2//! format specification defines them. The module parses each key on its
3//! own: it reports a finding for a bad key and goes on with the rest of the
4//! document.
5
6use std::{collections::HashMap, sync::OnceLock};
7
8use regex::Regex;
9use serde::{Deserialize, Serialize};
10use tramlines_core::frontmatter as engine;
11
12use crate::{Finding, RepoPath, Spanned, Yaml, YamlError, markdown::is_url};
13
14/// The `status` values (`SOKF_FORMAT_28`).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16pub enum Status {
17    /// `draft`.
18    Draft,
19    /// `stable`, the default.
20    Stable,
21    /// `deprecated`.
22    Deprecated,
23}
24
25/// `resource` (`SOKF_FORMAT_29`) is what a document describes: a `/` path or a URL,
26/// or a list of them.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub enum Resource {
29    /// `One` is a resource written as one string, the form that a sidecar's
30    /// `resource` takes (`SOKF_FORMAT_31`).
31    One(String),
32    /// `List` is a resource written as a list.
33    List(Vec<String>),
34}
35
36impl Resource {
37    /// `entries` returns every entry, in the order written.
38    pub fn entries(&self) -> &[String] {
39        match self {
40            Resource::One(r) => std::slice::from_ref(r),
41            Resource::List(rs) => rs,
42        }
43    }
44
45    /// `one` returns the string when the resource is written as one string,
46    /// and `None` when it is written as a list.
47    pub fn one(&self) -> Option<&str> {
48        match self {
49            Resource::One(r) => Some(r),
50            Resource::List(_) => None,
51        }
52    }
53}
54
55/// One `sources` entry (`SOKF_FORMAT_37`, `SOKF_FORMAT_38`).
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct SourceEntry {
58    /// `resource`: a path relative to the repository root, or a URL.
59    pub resource: String,
60    /// `id`: the footnote key.
61    pub id: Option<String>,
62    /// `title`.
63    pub title: Option<String>,
64    /// The entry's line.
65    pub line: usize,
66}
67
68/// One `links` entry (`SOKF_FORMAT_50`, `SOKF_FORMAT_51`).
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct LinkEntry {
71    /// `rel`.
72    pub rel: String,
73    /// `to`: an id or a `/` path.
74    pub to: String,
75    /// `note`.
76    pub note: Option<String>,
77    /// The entry's line.
78    pub line: usize,
79}
80
81/// One `verified` entry (`SOKF_FORMAT_43`, `SOKF_FORMAT_44`).
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct VerifiedEntry {
84    /// `by`: a `human:` or `process:` actor.
85    pub by: String,
86    /// `at`: an ISO 8601 datetime.
87    pub at: String,
88    /// The entry's line.
89    pub line: usize,
90}
91
92/// The core frontmatter fields of the format specification, each optional, plus
93/// the line of each key and the findings that the parser records as it goes on
94/// past each bad key.
95#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
96pub struct CoreFields {
97    /// `type`.
98    pub type_: Option<String>,
99    /// `id`.
100    pub id: Option<String>,
101    /// `title`.
102    pub title: Option<String>,
103    /// `description`.
104    pub description: Option<String>,
105    /// `tags`.
106    pub tags: Option<Vec<String>>,
107    /// `resource`.
108    pub resource: Option<Resource>,
109    /// `status`.
110    pub status: Option<Status>,
111    /// `sources`: the entries that parsed as valid maps. The parser drops any
112    /// other entry.
113    pub sources: Vec<SourceEntry>,
114    /// `links`: the entries that parsed as valid maps. The parser drops any
115    /// other entry.
116    pub links: Vec<LinkEntry>,
117    /// `verified`.
118    pub verified: Vec<VerifiedEntry>,
119    /// Keys that are not core, as written.
120    pub extra: Vec<(String, Spanned)>,
121    /// The line of every present key.
122    pub lines: HashMap<String, usize>,
123    /// The findings about the shape of the fields.
124    pub problems: Vec<Finding>,
125    /// Whether the frontmatter is present and a map.
126    pub present: bool,
127}
128
129/// The core keys of the format specification.
130pub const CORE_KEYS: &[&str] = &[
131    "type",
132    "id",
133    "title",
134    "description",
135    "tags",
136    "resource",
137    "status",
138    "sources",
139    "links",
140    "verified",
141];
142
143/// The stamped keys of documents (`SOKF_FORMAT_24`): keys that sokf writes
144/// itself.
145pub const STAMPED_DOCUMENT_KEYS: &[&str] = &["generated"];
146
147impl CoreFields {
148    /// `extra` returns the value of a non-core key.
149    pub fn extra(&self, key: &str) -> Option<&Spanned> {
150        self.extra.iter().find(|(k, _)| k == key).map(|(_, v)| v)
151    }
152
153    /// `line_of` returns the line of `key`, or `None` when the key is absent.
154    pub fn line_of(&self, key: &str) -> Option<usize> {
155        self.lines.get(key).copied()
156    }
157
158    /// `fail` records an error about the frontmatter of the document at
159    /// `path`.
160    fn fail(
161        &mut self,
162        path: &RepoPath,
163        line: Option<usize>,
164        criterion: &'static str,
165        msg: impl Into<String>,
166    ) {
167        self.problems
168            .push(Finding::error(path.clone(), line, criterion, msg));
169    }
170}
171
172/// `iso_datetime` returns the pattern of an ISO 8601 date or datetime,
173/// compiled once.
174fn iso_datetime() -> &'static Regex {
175    static ISO: OnceLock<Regex> = OnceLock::new();
176    ISO.get_or_init(|| {
177        Regex::new(r"^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$")
178            .expect("literal")
179    })
180}
181
182/// `core_fields` parses the frontmatter into core fields. `yaml` is the parsed
183/// frontmatter, the parse error, or `None` when the document has no frontmatter.
184// sokf-implements: SOKF_FORMAT_17
185pub fn core_fields(yaml: Option<Result<&Spanned, &YamlError>>, path: &RepoPath) -> CoreFields {
186    let mut core = CoreFields::default();
187    let node = match yaml {
188        None => {
189            core.fail(
190                path,
191                None,
192                "SOKF_FORMAT_17",
193                "the document has no frontmatter",
194            );
195            return core;
196        }
197        Some(Err(e)) => {
198            core.fail(
199                path,
200                Some(e.line()),
201                "SOKF_FORMAT_18",
202                format!("frontmatter: {e}"),
203            );
204            return core;
205        }
206        Some(Ok(node)) => node,
207    };
208    let Some(entries) = node.as_map() else {
209        core.fail(
210            path,
211            Some(node.line),
212            "SOKF_FORMAT_18",
213            format!("the frontmatter must be a map, not a {}", node.type_name()),
214        );
215        return core;
216    };
217    core.present = true;
218    for (key, value) in entries {
219        core_key(&mut core, key, value, path);
220    }
221    core
222}
223
224/// `core_key` reads the frontmatter key `key`, with its `value`, into
225/// `core`: a core key into its field, and any other key into `extra`. It
226/// records the key's line, and a finding when the value has the wrong shape.
227// sokf-implements: SOKF_FORMAT_19
228// sokf-implements: SOKF_FORMAT_26
229// sokf-implements: SOKF_FORMAT_27
230// sokf-implements: SOKF_FORMAT_28
231// sokf-implements: SOKF_FORMAT_29
232// sokf-implements: SOKF_FORMAT_32
233// sokf-implements: SOKF_FORMAT_37
234// sokf-implements: SOKF_FORMAT_38
235// sokf-implements: SOKF_FORMAT_42
236// sokf-implements: SOKF_FORMAT_43
237// sokf-implements: SOKF_FORMAT_44
238// sokf-implements: SOKF_FORMAT_50
239// sokf-implements: SOKF_FORMAT_51
240fn core_key(core: &mut CoreFields, key: &Spanned<String>, value: &Spanned, path: &RepoPath) {
241    core.lines.insert(key.value.clone(), key.line);
242    // A core field other than `type`, `id`, and `generated` that holds no value, a null
243    // or a text of only whitespace, is absent, as the engine reads an empty
244    // value of a required key as missing (`TL_143`): the field's own check
245    // then reports nothing beside the engine's one finding.
246    // sokf-implements: SOKF_FORMAT_256
247    let optional =
248        CORE_KEYS.contains(&key.value.as_str()) && !matches!(key.value.as_str(), "type" | "id");
249    if optional && engine::holds_no_value(value) {
250        return;
251    }
252    let line = Some(value.line);
253    match key.value.as_str() {
254        "type" => match value.as_str() {
255            Some(s) if !s.trim().is_empty() => core.type_ = Some(s.to_string()),
256            Some(_) => core.fail(path, line, "SOKF_FORMAT_19", "`type` is empty"),
257            None => core.fail(path, line, "SOKF_FORMAT_19", "`type` must be a string"),
258        },
259        "id" => {
260            // A scalar that isn't a string still gives the document its
261            // id, so that the other checks can name the document.
262            if let Some(s) = value.scalar_text() {
263                core.id = Some(s);
264            }
265            if value.as_str().is_none() {
266                core.fail(path, line, "SOKF_FORMAT_32", "`id` must be a string");
267            }
268        }
269        "title" => match value.as_str() {
270            Some(s) => core.title = Some(s.to_string()),
271            None => core.fail(path, line, "SOKF_FORMAT_26", "`title` must be a string"),
272        },
273        "description" => match value.as_str() {
274            Some(s) => core.description = Some(s.to_string()),
275            None => core.fail(
276                path,
277                line,
278                "SOKF_FORMAT_26",
279                "`description` must be a string",
280            ),
281        },
282        "tags" => match value.as_seq().map(|items| {
283            items
284                .iter()
285                .map(|i| i.as_str().map(str::to_string))
286                .collect::<Option<Vec<_>>>()
287        }) {
288            Some(Some(tags)) => core.tags = Some(tags),
289            _ => core.fail(
290                path,
291                line,
292                "SOKF_FORMAT_27",
293                "`tags` must be a list of strings",
294            ),
295        },
296        "resource" => match resource(value) {
297            Some(r) => core.resource = Some(r),
298            None => core.fail(
299                path,
300                line,
301                "SOKF_FORMAT_29",
302                "`resource` must be a `/` path or a URL, or a list of them",
303            ),
304        },
305        "status" => match value.as_str() {
306            Some("draft") => core.status = Some(Status::Draft),
307            Some("stable") => core.status = Some(Status::Stable),
308            Some("deprecated") => core.status = Some(Status::Deprecated),
309            _ => core.fail(
310                path,
311                line,
312                "SOKF_FORMAT_28",
313                "`status` must be `draft`, `stable`, or `deprecated`",
314            ),
315        },
316        "sources" => sources(core, value, path),
317        "links" => links(core, value, path),
318        "verified" => verified(core, value, path),
319        _ => core.extra.push((key.value.clone(), value.clone())),
320    }
321}
322
323/// `resource` reads `value` as a `resource`, and returns `None` when it isn't
324/// one. A `resource` is a string, or a non-empty list of strings, and each
325/// string is a `/` path or a URL.
326fn resource(value: &Spanned) -> Option<Resource> {
327    let valid = |s: &str| RepoPath::parse(s).is_some() || is_url(s);
328    if let Some(s) = value.as_str() {
329        return valid(s).then(|| Resource::One(s.to_string()));
330    }
331    let entries = value
332        .as_seq()?
333        .iter()
334        .map(|i| i.as_str().filter(|s| valid(s)).map(str::to_string))
335        .collect::<Option<Vec<_>>>()?;
336    (!entries.is_empty()).then_some(Resource::List(entries))
337}
338
339/// `EntryRules` says what a list of entry maps, `sources` or `links`,
340/// allows, and which criterion each finding about it cites.
341struct EntryRules {
342    /// The frontmatter key, such as `sources`.
343    field: &'static str,
344    /// The keys that an entry can have.
345    allowed: &'static [&'static str],
346    /// The allowed keys, as a finding names them.
347    allowed_text: &'static str,
348    /// The criterion of a value that isn't a list of maps.
349    shape: &'static str,
350    /// The criterion of a key that an entry can't have.
351    unknown: &'static str,
352    /// The criterion of a value that isn't a string, by its key.
353    not_string: fn(&str) -> &'static str,
354}
355
356/// `each_entry` checks that `value` is a list of maps that have only the
357/// keys that `rules` allows, each with a string value. It calls `add` for
358/// each map, in order, with whether the map passed. It reports each
359/// problem as it finds it, so the findings of one entry come before those
360/// of the next.
361fn each_entry(
362    core: &mut CoreFields,
363    value: &Spanned,
364    path: &RepoPath,
365    rules: &EntryRules,
366    mut add: impl FnMut(&mut CoreFields, &Spanned, bool),
367) {
368    let field = rules.field;
369    let Some(items) = value.as_seq() else {
370        core.fail(
371            path,
372            Some(value.line),
373            rules.shape,
374            format!("`{field}` must be a list of maps"),
375        );
376        return;
377    };
378    for item in items {
379        let Some(entries) = item.as_map() else {
380            core.fail(
381                path,
382                Some(item.line),
383                rules.shape,
384                format!("each `{field}` entry must be a map"),
385            );
386            continue;
387        };
388        let mut ok = true;
389        for (k, v) in entries {
390            if !rules.allowed.contains(&k.value.as_str()) {
391                core.fail(
392                    path,
393                    Some(k.line),
394                    rules.unknown,
395                    format!(
396                        "a `{field}` entry has `{}`. Only {} are allowed",
397                        k.value, rules.allowed_text
398                    ),
399                );
400                ok = false;
401            } else if v.as_str().is_none() {
402                core.fail(
403                    path,
404                    Some(v.line),
405                    (rules.not_string)(&k.value),
406                    format!("`{field}[].{}` must be a string", k.value),
407                );
408                ok = false;
409            }
410        }
411        add(core, item, ok);
412    }
413}
414
415/// `text_of` returns the string value of `key` in an entry map.
416fn text_of(item: &Spanned, key: &str) -> Option<String> {
417    item.get(key).and_then(|v| v.as_str()).map(str::to_string)
418}
419
420fn sources(core: &mut CoreFields, value: &Spanned, path: &RepoPath) {
421    let rules = EntryRules {
422        field: "sources",
423        allowed: &["resource", "id", "title"],
424        allowed_text: "`resource`, `id`, and `title`",
425        shape: "SOKF_FORMAT_38",
426        unknown: "SOKF_FORMAT_38",
427        not_string: |k| {
428            if k == "resource" {
429                "SOKF_FORMAT_37"
430            } else {
431                "SOKF_FORMAT_38"
432            }
433        },
434    };
435    each_entry(core, value, path, &rules, |core, item, ok| {
436        let Some(resource) = text_of(item, "resource") else {
437            core.fail(
438                path,
439                Some(item.line),
440                "SOKF_FORMAT_37",
441                "a `sources` entry has no `resource`",
442            );
443            return;
444        };
445        if ok {
446            core.sources.push(SourceEntry {
447                resource,
448                id: text_of(item, "id"),
449                title: text_of(item, "title"),
450                line: item.line,
451            });
452        }
453    });
454}
455
456fn links(core: &mut CoreFields, value: &Spanned, path: &RepoPath) {
457    let rules = EntryRules {
458        field: "links",
459        allowed: &["rel", "to", "note"],
460        allowed_text: "`rel`, `to`, and `note`",
461        shape: "SOKF_FORMAT_50",
462        unknown: "SOKF_FORMAT_51",
463        not_string: |k| {
464            if k == "note" {
465                "SOKF_FORMAT_51"
466            } else {
467                "SOKF_FORMAT_50"
468            }
469        },
470    };
471    each_entry(core, value, path, &rules, |core, item, ok| {
472        let (Some(rel), Some(to)) = (text_of(item, "rel"), text_of(item, "to")) else {
473            core.fail(
474                path,
475                Some(item.line),
476                "SOKF_FORMAT_50",
477                "a `links` entry needs `rel` and `to`",
478            );
479            return;
480        };
481        if ok {
482            core.links.push(LinkEntry {
483                rel,
484                to,
485                note: text_of(item, "note"),
486                line: item.line,
487            });
488        }
489    });
490}
491
492fn verified(core: &mut CoreFields, value: &Spanned, path: &RepoPath) {
493    let items: Vec<&Spanned> = match &value.value {
494        Yaml::Seq(items) => items.iter().collect(),
495        Yaml::Map(_) => vec![value],
496        _ => {
497            core.fail(
498                path,
499                Some(value.line),
500                "SOKF_FORMAT_42",
501                "`verified` must be a list of `{ by, at }` maps",
502            );
503            return;
504        }
505    };
506    for item in items {
507        let line = Some(item.line);
508        let by = item.get("by").and_then(|b| b.as_str());
509        let at = item.get("at").and_then(Spanned::scalar_text);
510        let (Some(by), Some(at)) = (by, at) else {
511            let key = if by.is_none() {
512                "SOKF_FORMAT_43"
513            } else {
514                "SOKF_FORMAT_44"
515            };
516            core.fail(path, line, key, "a `verified` entry needs `by` and `at`");
517            continue;
518        };
519        if !(by.starts_with("human:") || by.starts_with("process:")) {
520            core.fail(
521                path,
522                line,
523                "SOKF_FORMAT_43",
524                "`verified[].by` must be a `human:` or `process:` actor",
525            );
526            continue;
527        }
528        if !iso_datetime().is_match(&at) {
529            core.fail(
530                path,
531                line,
532                "SOKF_FORMAT_44",
533                "`verified[].at` must be an ISO 8601 datetime",
534            );
535            continue;
536        }
537        core.verified.push(VerifiedEntry {
538            by: by.to_string(),
539            at,
540            line: item.line,
541        });
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use std::fmt::Write as _;
548
549    use super::*;
550    use crate::yaml;
551
552    fn fields(text: &str) -> CoreFields {
553        let parsed = yaml::parse(text, 2);
554        core_fields(Some(parsed.as_ref()), &RepoPath::parse("/k/a.md").unwrap())
555    }
556
557    // A core field that holds no value is absent, and its own check reports
558    // nothing; an empty `type` still fails, and an empty field that isn't
559    // a core field is kept.
560    // sokf-tests: SOKF_FORMAT_256
561    #[test]
562    fn an_empty_core_field_is_absent() {
563        let c = fields(
564            "type: Note\nid: note-a\ntitle:\ndescription: '  '\nresource:\ntags:\nstatus: ~\nsources:\nlinks:\nverified:\nextra:\n",
565        );
566        assert!(c.problems.is_empty(), "{:?}", c.problems);
567        assert!(c.title.is_none() && c.description.is_none() && c.status.is_none());
568        assert!(c.resource.is_none() && c.tags.is_none());
569        assert!(c.sources.is_empty(), "{:?}", c.sources);
570        assert!(c.links.is_empty(), "{:?}", c.links);
571        assert!(c.verified.is_empty(), "{:?}", c.verified);
572        assert!(c.extra("extra").is_some());
573        assert_eq!(c.line_of("status"), Some(8));
574        let empty_type = fields("type:\nid: note-a\n");
575        assert_eq!(empty_type.problems.len(), 1, "{:?}", empty_type.problems);
576    }
577
578    #[test]
579    fn parses_every_core_field() {
580        let c = fields(
581            "type: Subsystem\nid: subsystem-logging\ntitle: Logging\ndescription: d\nresource: /crates/x.rs\ntags: [core, logging]\nstatus: draft\nsources:\n  - id: log4rs\n    resource: https://crates.io/log4rs\n    title: docs\nlinks:\n  - rel: depends-on\n    to: config\n    note: n\nverified:\n  - { by: human:rs, at: 2026-08-04T09:00:00Z }\nextra: 1\n",
582        );
583        assert!(c.problems.is_empty(), "{:?}", c.problems);
584        assert!(c.present);
585        assert_eq!(c.type_.as_deref(), Some("Subsystem"));
586        assert_eq!(c.id.as_deref(), Some("subsystem-logging"));
587        assert_eq!(
588            c.tags.as_ref().unwrap(),
589            &vec!["core".to_string(), "logging".to_string()]
590        );
591        assert_eq!(c.status, Some(Status::Draft));
592        assert_eq!(c.sources[0].id.as_deref(), Some("log4rs"));
593        assert_eq!(c.links[0].to, "config");
594        assert_eq!(c.verified[0].by, "human:rs");
595        assert_eq!(c.extra("extra").unwrap().as_int(), Some(1));
596        assert_eq!(c.line_of("id"), Some(3));
597        assert!(c.extra("nope").is_none());
598        assert_eq!(c.resource, Some(Resource::One("/crates/x.rs".into())));
599        let bare = fields("verified: { by: process:x, at: 2026-01-01 }\n");
600        assert_eq!(bare.verified.len(), 1);
601    }
602
603    #[test]
604    fn each_bad_shape_is_one_finding_naming_the_field() {
605        let c = fields(
606            "type: [x]\nid: 3\ntitle: 1\ndescription: []\ntags: x\nresource: relative\nstatus: nope\nsources:\n  - resource: /x\n    extra: 1\n  - id: only\n  - 3\nlinks:\n  - rel: x\n  - to: 1\n    rel: r\n  - rel: r\n    to: t\n    other: 1\nverified:\n  - { by: agent/1, at: 2026-01-01 }\n  - { by: human:x, at: soon }\n  - { by: human:x }\n",
607        );
608        let messages: Vec<&str> = c.problems.iter().map(|f| f.message.as_str()).collect();
609        for needle in [
610            "`type` must be a string",
611            "`id` must be a string",
612            "`title` must be a string",
613            "`description` must be a string",
614            "`tags` must be a list of strings",
615            "`resource` must be a `/` path or a URL, or a list of them",
616            "`status` must be",
617            "has `extra`",
618            "no `resource`",
619            "each `sources` entry must be a map",
620            "needs `rel` and `to`",
621            "`links[].to` must be a string",
622            "has `other`",
623            "`human:` or `process:`",
624            "ISO 8601",
625            "needs `by` and `at`",
626        ] {
627            assert!(
628                messages.iter().any(|m| m.contains(needle)),
629                "missing {needle:?} in {messages:?}"
630            );
631        }
632        assert_eq!(c.id.as_deref(), Some("3"));
633        assert_eq!(c.sources, [] as [crate::model::frontmatter::SourceEntry; 0]);
634        assert_eq!(c.links, [] as [crate::model::frontmatter::LinkEntry; 0]);
635        assert_eq!(
636            c.verified,
637            [] as [crate::model::frontmatter::VerifiedEntry; 0]
638        );
639        let e = fields("type: ''\nsources: 1\nlinks: 1\nverified: 1\n");
640        assert!(
641            e.problems
642                .iter()
643                .any(|f| f.message.contains("`type` is empty"))
644        );
645        assert!(
646            e.problems
647                .iter()
648                .any(|f| f.message.contains("`sources` must be a list"))
649        );
650        assert!(
651            e.problems
652                .iter()
653                .any(|f| f.message.contains("`links` must be a list"))
654        );
655        assert!(
656            e.problems
657                .iter()
658                .any(|f| f.message.contains("`verified` must be a list"))
659        );
660    }
661
662    #[test]
663    fn a_resource_is_one_or_a_list() {
664        let list = fields("resource: [/a, https://x.y]\n");
665        let r = list.resource.unwrap();
666        assert_eq!(r.entries(), ["/a", "https://x.y"]);
667        assert_eq!(r.one(), None);
668        assert_eq!(Resource::One("/a".into()).entries(), ["/a"]);
669        for bad in [
670            "resource: []\n",
671            "resource: [/a, rel]\n",
672            "resource: [[/a]]\n",
673        ] {
674            assert!(fields(bad).resource.is_none(), "{bad}");
675            assert_eq!(fields(bad).problems.len(), 1, "{bad}");
676        }
677    }
678
679    #[test]
680    fn missing_and_broken_frontmatter() {
681        let path = RepoPath::parse("/k/a.md").unwrap();
682        let none = core_fields(None, &path);
683        assert!(!none.present);
684        assert!(none.problems[0].message.contains("no frontmatter"));
685        let err = YamlError::Anchor { line: 3 };
686        let bad = core_fields(Some(Err(&err)), &path);
687        assert_eq!(bad.problems[0].line, Some(3));
688        let list = fields("- a\n");
689        assert!(list.problems[0].message.contains("must be a map"));
690    }
691
692    // sokf-tests: FORMAT_P-10
693    proptest::proptest! {
694        #![proptest_config(crate::proptest_cases::cases(256))]
695
696        /// sokf reads frontmatter through the engine's YAML reader, which
697        /// refuses each anchor, alias, and tag with an error at the line of
698        /// that anchor, alias, or tag.
699        #[test]
700        fn anchors_aliases_and_tags_are_errors_on_their_line(
701            before in 0usize..4,
702            name in "[a-z][a-z0-9]{0,5}",
703        ) {
704            let pad = (0..before).fold(String::new(), |mut out, i| {
705                let _ = writeln!(out, "k{i}: v");
706                out
707            });
708            let line = before + 1;
709            proptest::prop_assert_eq!(
710                yaml::parse(&format!("{pad}a: &{name} 1\n"), 1).unwrap_err(),
711                YamlError::Anchor { line }
712            );
713            proptest::prop_assert_eq!(
714                yaml::parse(&format!("{pad}a: *{name}\n"), 1).unwrap_err(),
715                YamlError::Alias { line }
716            );
717            proptest::prop_assert_eq!(
718                yaml::parse(&format!("{pad}a: !{name} 1\n"), 1).unwrap_err(),
719                YamlError::Tag { line }
720            );
721        }
722
723        /// A plain scalar takes its type from the YAML 1.2 core schema, and
724        /// quoting makes any scalar a string.
725        #[test]
726        fn plain_scalars_follow_the_core_schema(
727            n in proptest::prelude::any::<i64>(),
728            b in proptest::prelude::any::<bool>(),
729            s in "[a-z][a-z ]{0,10}[a-z]",
730        ) {
731            let get = |text: String| yaml::parse(&text, 1).unwrap().get("v").cloned().unwrap();
732            proptest::prop_assert_eq!(get(format!("v: {n}\n")).as_int(), Some(n));
733            proptest::prop_assert_eq!(get(format!("v: {b}\n")).as_bool(), Some(b));
734            let plain = get(format!("v: {s}\n"));
735            proptest::prop_assert_eq!(plain.as_str(), Some(s.as_str()));
736            let quoted = get(format!("v: \"{n}\"\n"));
737            let text = n.to_string();
738            proptest::prop_assert_eq!(quoted.as_str(), Some(text.as_str()));
739        }
740    }
741}