Skip to main content

sokf_core/api/
guide.rs

1//! This module implements `sokf guide` (CLI-17), which prints the guidance that
2//! a document's schema gives for the document's parts at the document's
3//! lifecycle states, with each part's example. The engine's
4//! `derive::guide_for` returns that guidance, and the example that the
5//! schema's scaffold writes for each part with the document's own values,
6//! and `sokf new` prints the guide of the document that it creates.
7
8use std::{
9    collections::{BTreeMap, BTreeSet},
10    path::PathBuf,
11};
12
13use tramlines_md::{
14    check::{self, Counts, HeadingMatch},
15    derive,
16};
17
18use crate::{
19    Cache, CacheMode, Document, Error, Model, RepoPath, RepoRoot, Result, Spanned, Yaml, config,
20    grammar::{self, Label, LimitKind, Section, SokfSchema, States, squash},
21    graph,
22    model::{ParseMode, parse_source},
23    scaffold, source,
24};
25
26/// `GuideOptions` holds the options of `sokf guide`.
27#[derive(Debug, Clone)]
28pub struct GuideOptions {
29    /// `documents` holds the arguments, each an id or a path of a document.
30    pub documents: Vec<String>,
31    /// `states` holds the values of `--state`, each a key and a state, in the
32    /// order of the arguments.
33    pub states: Vec<(String, String)>,
34    /// `cwd` is the current directory, from which a relative path resolves.
35    pub cwd: PathBuf,
36    /// `cache` is the cache mode.
37    pub cache: CacheMode,
38}
39
40mod report;
41
42pub use report::*;
43
44/// `guide` returns the guide of each document that `opts.documents` names,
45/// in the order of the arguments. It reads the tree as a lookup does, reads
46/// each document from its file, and compiles the schemas of their types.
47/// It refuses an argument that names no document of a store, a document
48/// without a `type` or without a schema that passes the grammar, and a
49/// `--state` that the document's lifecycle doesn't declare, before it
50/// returns anything. `guide` writes only the cache.
51// sokf-implements: CLI-9_AC-3
52// sokf-implements: CLI-17_AC-5
53// sokf-implements: CACHE-1_AC-27
54pub fn guide(root: &RepoRoot, opts: &GuideOptions) -> Result<GuideReport> {
55    let config = config::load_config(root)?;
56    let (grammar, repo) = super::load::load_formats(root)?;
57    let cache = Cache::open(root, opts.cache);
58    // Only a reference to a key alone needs the keys that the schemas
59    // capture, as for `locate`.
60    let (mut model, keys) = if opts.documents.iter().any(|d| graph::is_key_reference(d)) {
61        let slugs = super::locate::key_slugs(&opts.documents, graph::is_key_reference);
62        let (model, keys) = super::load_keys_for(root, &config, &cache, &slugs)?;
63        (model, Some(keys))
64    } else {
65        (super::load_for_lookup(root, &config, &cache)?, None)
66    };
67    let mut documents = Vec::new();
68    for arg in &opts.documents {
69        let path = graph::resolve_document(&model, keys.as_ref(), &opts.cwd, arg)?;
70        documents.push(read(root, &path)?);
71    }
72    let types: BTreeSet<&str> = documents.iter().map(|(_, t)| t.as_str()).collect();
73    for type_name in types {
74        if type_name != "Schema" {
75            super::admit_schemas_of_type(&mut model, root, &cache, type_name)?;
76        }
77    }
78    // sokf-implements: CONF-12_AC-7
79    let texts = config::load_texts(root)?;
80    let compiled = grammar::compile_all(&model, grammar, &repo, texts);
81    let mut guides = Vec::new();
82    for (doc, type_name) in &documents {
83        let (schema, schema_path, k) = schema_of(&model, &compiled, doc, type_name)?;
84        let language = scaffold::language(&model, &compiled, schema, type_name, Some(k), Some(k));
85        let words = scaffold::Words::new(&compiled.texts, language);
86        let mut states = schema.core.states(doc.frontmatter.as_ref());
87        // sokf-implements: CLI-17_AC-11
88        let given = scaffold::given_states(schema, &opts.states)
89            .map_err(|e| Error::Guide(format!("{}: {e}", doc.path)))?;
90        states.0.extend(given.0);
91        own_states(doc, schema, &states)?;
92        guides.push(document_guide(
93            doc,
94            type_name,
95            schema,
96            schema_path,
97            &states,
98            &words,
99        ));
100    }
101    Ok(GuideReport { documents: guides })
102}
103
104/// `read` reads the document at `path` from its file, with its type. It
105/// refuses a document whose frontmatter gives no `type`.
106// sokf-implements: CLI-17_AC-4
107fn read(root: &RepoRoot, path: &RepoPath) -> Result<(Document, String)> {
108    let src = source::load(root, path)?;
109    let parsed = parse_source(&src, ParseMode::Document);
110    let doc = Document::new(src, parsed);
111    let Some(type_name) = doc.type_name().map(str::to_string) else {
112        return Err(Error::Guide(format!(
113            "{path} has no `type`, or its frontmatter does not parse, so it has no schema"
114        )));
115    };
116    Ok((doc, type_name))
117}
118
119/// `schema_of` returns the compiled schema of the document's type in the
120/// document's store, as `sokf new` chooses it for a type of that store, with
121/// the path of the schema, or the grammar's schema of a schema document,
122/// with no path (CLI-17_AC-21), and the document's store. It refuses what
123/// `scaffold::schema_for` refuses, with the document's path.
124// sokf-implements: CLI-17_AC-4
125// sokf-implements: CLI-17_AC-21
126fn schema_of<'a>(
127    model: &Model,
128    compiled: &'a grammar::Compiled,
129    doc: &Document,
130    type_name: &str,
131) -> Result<(&'a SokfSchema, Option<RepoPath>, usize)> {
132    let path = &doc.path;
133    let Some(k) = model.knowledge_of(path) else {
134        return Err(Error::Guide(format!("{path} lies in no knowledge store")));
135    };
136    let (_, schema) =
137        scaffold::schema_for(model, compiled, type_name, Some(k)).map_err(|e| match e {
138            Error::New(why) => Error::Guide(format!("{path}: {why}")),
139            e => e,
140        })?;
141    let schema_path = compiled
142        .for_type(model, k, type_name)
143        .filter(|_| type_name != "Schema")
144        .map(|(r, _)| model.schema(r).doc.path.clone());
145    Ok((schema, schema_path, k))
146}
147
148/// `own_states` refuses a document whose frontmatter sets no state, or a
149/// state that the lifecycle doesn't declare, for a dimension that `--state`
150/// doesn't give, because the guide would then leave out each part that the
151/// dimension gates.
152// sokf-implements: CLI-17_AC-24
153fn own_states(doc: &Document, schema: &SokfSchema, states: &States) -> Result<()> {
154    for dim in &schema.core.core.lifecycle {
155        let key = &dim.key;
156        let why = match states.0.get(key).and_then(|v| v.first()) {
157            Some(state) if dim.states.contains(state) => continue,
158            Some(state) => format!(
159                "`{key}: {state}` is not a state of `{key}`. The states are {}",
160                dim.states.join(", ")
161            ),
162            None => format!("the frontmatter sets no `{key}`"),
163        };
164        return Err(Error::Guide(format!(
165            "{}: {why}, so give `--state {key}=STATE`",
166            doc.path
167        )));
168    }
169    Ok(())
170}
171
172/// `document_guide` builds the guide of `doc` from the engine's guide of its
173/// schema at `states`, with `words`, sokf's texts in the language of the
174/// schema, through the host that derives the scaffold.
175// sokf-implements: CLI-17_AC-6
176// sokf-implements: CLI-17_AC-7
177// sokf-implements: CLI-17_AC-8
178// sokf-implements: CLI-17_AC-9
179// sokf-implements: CLI-17_AC-10
180// sokf-implements: CLI-17_AC-29
181// sokf-implements: CLI-17_AC-38
182fn document_guide(
183    doc: &Document,
184    type_name: &str,
185    schema: &SokfSchema,
186    schema_path: Option<RepoPath>,
187    states: &States,
188    words: &scaffold::Words<'_>,
189) -> DocumentGuide {
190    // The engine's guide holds each part that the states admit, each with
191    // the words of the scaffold's guidance line for it, and the example that
192    // the scaffold writes for it with the document's own values, and no rule
193    // or pattern.
194    let host = scaffold::SokfScaffold::with_words(schema, words);
195    let (g, plain) = guides(doc, schema, states, &host);
196    let (frontmatter_text, body_text) = texts(doc);
197    let key_example = |key: &str| {
198        plain
199            .frontmatter
200            .iter()
201            .find(|k| k.key == key)
202            .and_then(|k| k.example.clone())
203    };
204    let admitted: Vec<usize> = (0..schema.core.sections.len())
205        .filter(|&i| schema.core.sections[i].common.only.admits(states))
206        .collect();
207    // The check's own match of each heading to its section.
208    let matches = check::match_headings(crate::check::doc_view(doc).engine(), &schema.core, states);
209    // The scaffold opens its body with the schema's guidance, then the
210    // message of each ban of the whole body, on one line.
211    let opening: Vec<String> = g
212        .guidance
213        .iter()
214        .chain(&g.bans)
215        .map(|t| squash(t))
216        .filter(|t| !t.is_empty())
217        .collect();
218    DocumentGuide {
219        path: doc.path.clone(),
220        id: doc.id().map(str::to_string),
221        type_name: type_name.to_string(),
222        schema: schema_path,
223        states: schema
224            .core
225            .core
226            .lifecycle
227            .iter()
228            .filter_map(|d| {
229                let state = states.0.get(&d.key)?.first()?;
230                Some((d.key.clone(), state.clone().into()))
231            })
232            .collect(),
233        guidance: g.guidance,
234        bans: g.bans,
235        text: (!opening.is_empty()).then(|| opening.join(" ")),
236        // sokf-implements: CLI-17_AC-35
237        // sokf-implements: CLI-17_AC-36
238        labels: g
239            .labels
240            .into_iter()
241            .map(|l| LabelGuide {
242                meaning: words.attribution(&l.key),
243                key: l.key,
244                words: l.words,
245            })
246            .collect(),
247        frontmatter: g
248            .frontmatter
249            .into_iter()
250            .map(|mut k| {
251                k.example = key_example(&k.key);
252                key_guide(k, words)
253            })
254            .collect(),
255        // The scaffold writes the guidance of each `links` rule that the
256        // states admit before the rule's entries, as one line, and leaves
257        // out a rule that a hard limit of 0 bans.
258        links: schema
259            .written_links(states)
260            // sokf-implements: CLI-17_AC-33
261            // sokf-implements: CLI-17_AC-34
262            .map(|r| LinkGuide {
263                rel: r.rel.clone(),
264                optional: r.min == 0,
265                limit: r.max.clone().map(limit),
266                text: scaffold::link_text(r, Some(words)),
267                example: scaffold::link_example(r),
268            })
269            .collect(),
270        preamble: g.preamble.map(|p| PreambleGuide {
271            guidance: p.guidance,
272            text: p.text,
273            example: p.example,
274            blocks: p.blocks.into_iter().map(block_guide).collect(),
275            line: p.line,
276        }),
277        // The engine's guide holds the sections that the states admit, in
278        // the schema's order, so the guide of a section and its rule share an
279        // index in `admitted`.
280        sections: g
281            .sections
282            .into_iter()
283            .enumerate()
284            .map(|(i, s)| {
285                let section = admitted[i];
286                debug_assert_eq!(schema.core.sections[section].common.line, s.line);
287                let held = holds(doc, &schema.core.sections, &matches, section);
288                SectionGuide {
289                    heading: s.heading,
290                    level: s.level,
291                    rule_id: s.rule_id,
292                    parent: s.parent,
293                    optional: s.optional,
294                    repeat: s.repeat,
295                    held,
296                    guidance: s.guidance,
297                    text: s.text,
298                    example: s.example,
299                    blocks: s.blocks.into_iter().map(block_guide).collect(),
300                    line: s.line,
301                }
302            })
303            .collect(),
304        frontmatter_text,
305        body_text,
306    }
307}
308
309/// `texts` returns the YAML of the frontmatter of `doc` and its body, as the
310/// source's split gives them.
311fn texts(doc: &Document) -> (String, String) {
312    let split = source::split(&doc.source);
313    let front = split.frontmatter.map_or("", |(yaml, _)| yaml);
314    (front.to_string(), split.body.to_string())
315}
316
317/// `guides` returns the engine's guide of `doc` at `states` twice: with each
318/// scalar frontmatter value of the document, and with its id and its title
319/// alone, from which the example of each other frontmatter key comes, because
320/// the writer's own value, right or wrong, is no example of the key. A value
321/// of the document that no scaffold can hold, such as a title that a
322/// paragraph bound to it can't hold, would leave every part without an
323/// example, so both then carry the schema's values.
324fn guides(
325    doc: &Document,
326    schema: &SokfSchema,
327    states: &States,
328    host: &scaffold::SokfScaffold<'_>,
329) -> (derive::Guide, derive::Guide) {
330    let mut values = scalar_values(doc);
331    if derive::derive_for(&schema.core, states, host, &values).is_err() {
332        values.clear();
333    }
334    let own: BTreeMap<String, String> = values
335        .iter()
336        .filter(|(k, _)| matches!(k.as_str(), "id" | "title"))
337        .map(|(k, v)| (k.clone(), v.clone()))
338        .collect();
339    (
340        derive::guide_for(&schema.core, states, host, &values),
341        derive::guide_for(&schema.core, states, host, &own),
342    )
343}
344
345/// `scalar_values` returns each top-level frontmatter key of `doc` whose
346/// value is a scalar that holds text, with that text, which the engine
347/// splices into each example in place of the schema's, so that an example
348/// carries the document's own values.
349// sokf-implements: CLI-17_AC-39
350fn scalar_values(doc: &Document) -> BTreeMap<String, String> {
351    let Some(Spanned {
352        value: Yaml::Map(entries),
353        ..
354    }) = &doc.frontmatter
355    else {
356        return BTreeMap::new();
357    };
358    entries
359        .iter()
360        .filter(|(_, v)| !matches!(v.value, Yaml::Null | Yaml::Seq(_) | Yaml::Map(_)))
361        .filter_map(|(k, v)| Some((k.value.clone(), v.scalar_text()?)))
362        .filter(|(_, v)| !v.trim().is_empty())
363        .collect()
364}
365
366/// `new_guide` returns the guide of the new document `text`, which `sokf new`
367/// builds at `path` of the type `type_name` at `states`, as `sokf guide`
368/// returns it for the document once written, with `words`, sokf's texts in
369/// the language of the schema.
370// sokf-implements: CLI-6_AC-127
371#[expect(
372    clippy::too_many_arguments,
373    reason = "the guide of a new document needs what `new` resolved, field by field"
374)]
375pub(super) fn new_guide(
376    path: &RepoPath,
377    text: &str,
378    type_name: &str,
379    schema: &SokfSchema,
380    model: &Model,
381    compiled: &grammar::Compiled,
382    knowledge: Option<usize>,
383    states: &States,
384    words: &scaffold::Words<'_>,
385) -> DocumentGuide {
386    let source = crate::Source::from_text(path.clone(), text);
387    let parsed = parse_source(&source, ParseMode::Document);
388    let doc = Document::new(source, parsed);
389    // The store that holds the path chooses the schema's path, as `guide`
390    // chooses it for the document once written.
391    let schema_path = model
392        .knowledge_of(path)
393        .or(knowledge)
394        .and_then(|k| compiled.for_type(model, k, type_name))
395        .filter(|_| type_name != "Schema")
396        .map(|(r, _)| model.schema(r).doc.path.clone());
397    document_guide(&doc, type_name, schema, schema_path, states, words)
398}
399
400/// `key_guide` copies the engine's guide of one frontmatter key, with sokf's
401/// own text for the key before the schema's, as the scaffold writes them on
402/// one line.
403fn key_guide(k: derive::KeyGuide, words: &scaffold::Words<'_>) -> KeyGuide {
404    let text = match (host_text(&k.key, words), k.text) {
405        (Some(host), Some(own)) => Some(format!("{host} {own}")),
406        (host, own) => host.or(own),
407    };
408    KeyGuide {
409        lifecycle: k.lifecycle,
410        optional: k.optional,
411        guidance: k.guidance,
412        limit: k.limit.map(limit),
413        text,
414        example: k.example,
415        line: k.line,
416        key: k.key,
417    }
418}
419
420/// `host_text` returns sokf's own text for the frontmatter key `key`, which
421/// the guide puts before the schema's text for the key, as the scaffold puts
422/// it at the start of the guidance line before the key: the rule for
423/// writing a description, in the language of the schema.
424// sokf-implements: CLI-17_AC-32
425// sokf-implements: CLI-6_AC-118
426// sokf-implements: CLI-6_AC-119
427// sokf-implements: CLI-6_AC-123
428fn host_text(key: &str, words: &scaffold::Words<'_>) -> Option<String> {
429    (key == "description")
430        .then(|| words.description())
431        .flatten()
432}
433
434/// `block_guide` copies the engine's guide of one block, with the format,
435/// the `rule-id`, and what each rule's limit counts, and the `label` of the
436/// block and of each of its unit rules.
437// sokf-implements: CLI-17_AC-31
438// sokf-implements: CLI-17_AC-37
439fn block_guide(b: derive::BlockGuide) -> BlockGuide {
440    BlockGuide {
441        kind: b.kind.name().to_string(),
442        rule_id: b.rule_id,
443        pos: b.pos,
444        optional: b.optional,
445        guidance: b.guidance,
446        limits: b
447            .limits
448            .into_iter()
449            .map(|l| RuleLimit {
450                rule: l.rule,
451                format: l.format,
452                rule_id: l.rule_id,
453                counts: l.counts.map(|c| match c {
454                    Counts::Units => GuideCounts::Units,
455                    Counts::Lines => GuideCounts::Lines,
456                }),
457                line: l.line,
458                limit: limit(l.limit),
459            })
460            .collect(),
461        labels: b
462            .labels
463            .into_iter()
464            .map(|l| RuleLabel {
465                rule: l.rule,
466                rule_id: l.rule_id,
467                line: l.line,
468                label: match l.label {
469                    Label::Required => GuideLabel::Required,
470                    Label::Optional => GuideLabel::Optional,
471                },
472            })
473            .collect(),
474        bans: b.bans,
475        text: b.text,
476        example: b.example,
477        blocks: b.blocks.into_iter().map(block_guide).collect(),
478        line: b.line,
479    }
480}
481
482fn limit(l: grammar::Limit) -> GuideLimit {
483    GuideLimit {
484        kind: match l.kind {
485            LimitKind::Soft => GuideLimitKind::Soft,
486            LimitKind::Hard => GuideLimitKind::Hard,
487        },
488        count: l.count,
489        when_at_limit: l.when_at_limit,
490    }
491}
492
493/// `holds` reports whether `doc` has a heading of the section `i` of the
494/// schema's sections, as `takes` reads a heading, given `matches`, the
495/// section that the check matches each heading to.
496// sokf-implements: CLI-17_AC-15
497fn holds(doc: &Document, sections: &[Section], matches: &[Option<HeadingMatch>], i: usize) -> bool {
498    (0..doc.body.headings.len()).any(|h| takes(doc, sections, matches, i, h))
499}
500
501/// `takes` reports whether the heading `h` of `doc` is a heading of the
502/// section `i` of `sections`, the schema's sections: the check matches the
503/// heading to the section, the heading stands at the section's level, and
504/// a heading bound to the frontmatter reads as the value. The match reads
505/// each heading in tramlines' fixed spelling of its markup, gives a heading
506/// whose text another section gives exactly to that section, and gives a
507/// heading to a section by a `renamed-from` text only where no section
508/// takes it by its text or its shape. A section inside a parent takes only
509/// a heading that lies under a heading of the parent, which the match
510/// doesn't read.
511// sokf-implements: CLI-17_AC-25
512// sokf-implements: CLI-17_AC-26
513// sokf-implements: CLI-17_AC-27
514fn takes(
515    doc: &Document,
516    sections: &[Section],
517    matches: &[Option<HeadingMatch>],
518    i: usize,
519    h: usize,
520) -> bool {
521    if !crate::check::headings::opens(doc, sections, matches, h, i) {
522        return false;
523    }
524    let headings = &doc.body.headings;
525    let Some(parent) = &sections[i].parent else {
526        return true;
527    };
528    // The heading lies under the nearest heading above it at the parent's
529    // level or above, as the check finds the parent of a heading. Only a
530    // parent that the states admit takes a heading.
531    (0..sections.len())
532        .filter(|&p| sections[p].rule_id.as_deref() == Some(parent.as_str()))
533        .any(|p| {
534            let level = sections[p].level;
535            (0..h)
536                .rev()
537                .find(|&j| headings[j].level <= level)
538                .is_some_and(|j| takes(doc, sections, matches, p, j))
539        })
540}
541
542#[cfg(test)]
543mod tests;