1use 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#[derive(Debug, Clone)]
28pub struct GuideOptions {
29 pub documents: Vec<String>,
31 pub states: Vec<(String, String)>,
34 pub cwd: PathBuf,
36 pub cache: CacheMode,
38}
39
40mod report;
41
42pub use report::*;
43
44pub 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 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 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 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
104fn 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
119fn 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
148fn 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
172fn 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 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 let matches = check::match_headings(crate::check::doc_view(doc).engine(), &schema.core, states);
209 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 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 links: schema
259 .written_links(states)
260 .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 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
309fn 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
317fn 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
345fn 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#[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 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
400fn 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
420fn host_text(key: &str, words: &scaffold::Words<'_>) -> Option<String> {
429 (key == "description")
430 .then(|| words.description())
431 .flatten()
432}
433
434fn 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
493fn 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
501fn 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) = §ions[i].parent else {
526 return true;
527 };
528 (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;