use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
};
use schemars::JsonSchema;
use serde::Serialize;
use tramlines_md::{check::Counts, derive};
use crate::{
Cache, CacheMode, Document, Error, Model, RepoPath, RepoRoot, Result, config,
grammar::{self, Label, LimitKind, Section, Shape, SokfSchema, States, Text, squash},
graph,
model::{ParseMode, parse_source},
scaffold, source,
};
#[derive(Debug, Clone)]
pub struct GuideOptions {
pub documents: Vec<String>,
pub states: Vec<(String, String)>,
pub cwd: PathBuf,
pub cache: CacheMode,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[schemars(title = "sokf guide report")]
pub struct GuideReport {
pub documents: Vec<DocumentGuide>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct DocumentGuide {
pub path: RepoPath,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub id: Option<String>,
#[serde(rename = "type")]
pub type_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "RepoPath")]
pub schema: Option<RepoPath>,
#[schemars(with = "BTreeMap<String, String>")]
pub states: serde_json::Map<String, serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub guidance: Option<String>,
pub bans: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
pub labels: Vec<LabelGuide>,
pub frontmatter: Vec<KeyGuide>,
pub links: Vec<LinkGuide>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "PreambleGuide")]
pub preamble: Option<PreambleGuide>,
pub sections: Vec<SectionGuide>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct LabelGuide {
pub key: String,
pub words: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub meaning: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct KeyGuide {
pub key: String,
pub lifecycle: bool,
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub guidance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "GuideLimit")]
pub limit: Option<GuideLimit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct LinkGuide {
pub rel: String,
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "GuideLimit")]
pub limit: Option<GuideLimit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct PreambleGuide {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub guidance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct SectionGuide {
pub heading: String,
pub level: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub rule_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub parent: Option<String>,
pub optional: bool,
pub repeat: bool,
pub held: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub guidance: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct BlockGuide {
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub rule_id: Option<String>,
pub pos: usize,
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub guidance: Option<String>,
pub limits: Vec<RuleLimit>,
pub labels: Vec<RuleLabel>,
pub bans: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct RuleLimit {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "usize")]
pub rule: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub format: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub rule_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "GuideCounts")]
pub counts: Option<GuideCounts>,
pub line: usize,
#[serde(flatten)]
pub limit: GuideLimit,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct RuleLabel {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "usize")]
pub rule: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
#[schemars(with = "String")]
pub rule_id: Option<String>,
pub line: usize,
pub label: GuideLabel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum GuideLabel {
Required,
Optional,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
pub struct GuideLimit {
pub kind: GuideLimitKind,
pub count: usize,
pub when_at_limit: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum GuideCounts {
Units,
Lines,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum GuideLimitKind {
Soft,
Hard,
}
pub fn guide(root: &RepoRoot, opts: &GuideOptions) -> Result<GuideReport> {
let config = config::load_config(root)?;
let (grammar, repo) = super::load::load_formats(root)?;
let cache = Cache::open(root, opts.cache);
let (mut model, keys) = if opts.documents.iter().any(|d| graph::is_key_reference(d)) {
let slugs = super::locate::key_slugs(&opts.documents, graph::is_key_reference);
let (model, keys) = super::load_keys_for(root, &config, &cache, &slugs)?;
(model, Some(keys))
} else {
(super::load_for_lookup(root, &config, &cache)?, None)
};
let mut documents = Vec::new();
for arg in &opts.documents {
let path = graph::resolve_document(&model, keys.as_ref(), &opts.cwd, arg)?;
documents.push(read(root, &path)?);
}
let types: BTreeSet<&str> = documents.iter().map(|(_, t)| t.as_str()).collect();
for type_name in types {
if type_name != "Schema" {
super::admit_schemas_of_type(&mut model, root, &cache, type_name)?;
}
}
let texts = config::load_texts(root)?;
let compiled = grammar::compile_all(&model, grammar, &repo, texts);
let mut guides = Vec::new();
for (doc, type_name) in &documents {
let (schema, schema_path, k) = schema_of(&model, &compiled, doc, type_name)?;
let language = scaffold::language(&model, &compiled, schema, type_name, Some(k), Some(k));
let words = scaffold::Words::new(&compiled.texts, language);
let mut states = schema.core.states(doc.frontmatter.as_ref());
let given = scaffold::given_states(schema, &opts.states)
.map_err(|e| Error::Guide(format!("{}: {e}", doc.path)))?;
states.0.extend(given.0);
own_states(doc, schema, &states)?;
guides.push(document_guide(
doc,
type_name,
schema,
schema_path,
&states,
&words,
));
}
Ok(GuideReport { documents: guides })
}
fn read(root: &RepoRoot, path: &RepoPath) -> Result<(Document, String)> {
let src = source::load(root, path)?;
let parsed = parse_source(&src, ParseMode::Document);
let doc = Document::new(src, parsed);
let Some(type_name) = doc.type_name().map(str::to_string) else {
return Err(Error::Guide(format!(
"{path} has no `type`, or its frontmatter does not parse, so it has no schema"
)));
};
Ok((doc, type_name))
}
fn schema_of<'a>(
model: &Model,
compiled: &'a grammar::Compiled,
doc: &Document,
type_name: &str,
) -> Result<(&'a SokfSchema, Option<RepoPath>, usize)> {
let path = &doc.path;
let Some(k) = model.knowledge_of(path) else {
return Err(Error::Guide(format!("{path} lies in no knowledge store")));
};
let (_, schema) =
scaffold::schema_for(model, compiled, type_name, Some(k)).map_err(|e| match e {
Error::New(why) => Error::Guide(format!("{path}: {why}")),
e => e,
})?;
let schema_path = compiled
.for_type(model, k, type_name)
.filter(|_| type_name != "Schema")
.map(|(r, _)| model.schema(r).doc.path.clone());
Ok((schema, schema_path, k))
}
fn own_states(doc: &Document, schema: &SokfSchema, states: &States) -> Result<()> {
for dim in &schema.core.core.lifecycle {
let key = &dim.key;
let why = match states.0.get(key).and_then(|v| v.first()) {
Some(state) if dim.states.contains(state) => continue,
Some(state) => format!(
"`{key}: {state}` is not a state of `{key}`. The states are {}",
dim.states.join(", ")
),
None => format!("the frontmatter sets no `{key}`"),
};
return Err(Error::Guide(format!(
"{}: {why}, so give `--state {key}=STATE`",
doc.path
)));
}
Ok(())
}
fn document_guide(
doc: &Document,
type_name: &str,
schema: &SokfSchema,
schema_path: Option<RepoPath>,
states: &States,
words: &scaffold::Words<'_>,
) -> DocumentGuide {
let host = scaffold::SokfScaffold::with_words(schema, words);
let g = derive::guide(&schema.core, states, &host);
let admitted: Vec<&Section> = schema
.core
.sections
.iter()
.filter(|s| s.common.only.admits(states))
.collect();
let opening: Vec<String> = g
.guidance
.iter()
.chain(&g.bans)
.map(|t| squash(t))
.filter(|t| !t.is_empty())
.collect();
DocumentGuide {
path: doc.path.clone(),
id: doc.id().map(str::to_string),
type_name: type_name.to_string(),
schema: schema_path,
states: schema
.core
.core
.lifecycle
.iter()
.filter_map(|d| {
let state = states.0.get(&d.key)?.first()?;
Some((d.key.clone(), state.clone().into()))
})
.collect(),
guidance: g.guidance,
bans: g.bans,
text: (!opening.is_empty()).then(|| opening.join(" ")),
labels: g
.labels
.into_iter()
.map(|l| LabelGuide {
meaning: words.attribution(&l.key),
key: l.key,
words: l.words,
})
.collect(),
frontmatter: g
.frontmatter
.into_iter()
.map(|k| key_guide(k, words))
.collect(),
links: schema
.written_links(states)
.map(|r| LinkGuide {
rel: r.rel.clone(),
optional: r.min == 0,
limit: r.max.clone().map(limit),
text: scaffold::link_text(r, Some(words)),
})
.collect(),
preamble: g.preamble.map(|p| PreambleGuide {
guidance: p.guidance,
text: p.text,
blocks: p.blocks.into_iter().map(block_guide).collect(),
line: p.line,
}),
sections: g
.sections
.into_iter()
.enumerate()
.map(|(i, s)| {
debug_assert_eq!(admitted[i].common.line, s.line);
let held = holds(doc, &admitted, i);
SectionGuide {
heading: s.heading,
level: s.level,
rule_id: s.rule_id,
parent: s.parent,
optional: s.optional,
repeat: s.repeat,
held,
guidance: s.guidance,
text: s.text,
blocks: s.blocks.into_iter().map(block_guide).collect(),
line: s.line,
}
})
.collect(),
}
}
fn key_guide(k: derive::KeyGuide, words: &scaffold::Words<'_>) -> KeyGuide {
let text = match (host_text(&k.key, words), k.text) {
(Some(host), Some(own)) => Some(format!("{host} {own}")),
(host, own) => host.or(own),
};
KeyGuide {
lifecycle: k.lifecycle,
optional: k.optional,
guidance: k.guidance,
limit: k.limit.map(limit),
text,
line: k.line,
key: k.key,
}
}
fn host_text(key: &str, words: &scaffold::Words<'_>) -> Option<String> {
(key == "description")
.then(|| words.description())
.flatten()
}
fn block_guide(b: derive::BlockGuide) -> BlockGuide {
BlockGuide {
kind: b.kind.name().to_string(),
rule_id: b.rule_id,
pos: b.pos,
optional: b.optional,
guidance: b.guidance,
limits: b
.limits
.into_iter()
.map(|l| RuleLimit {
rule: l.rule,
format: l.format,
rule_id: l.rule_id,
counts: l.counts.map(|c| match c {
Counts::Units => GuideCounts::Units,
Counts::Lines => GuideCounts::Lines,
}),
line: l.line,
limit: limit(l.limit),
})
.collect(),
labels: b
.labels
.into_iter()
.map(|l| RuleLabel {
rule: l.rule,
rule_id: l.rule_id,
line: l.line,
label: match l.label {
Label::Required => GuideLabel::Required,
Label::Optional => GuideLabel::Optional,
},
})
.collect(),
bans: b.bans,
text: b.text,
blocks: b.blocks.into_iter().map(block_guide).collect(),
line: b.line,
}
}
fn limit(l: grammar::Limit) -> GuideLimit {
GuideLimit {
kind: match l.kind {
LimitKind::Soft => GuideLimitKind::Soft,
LimitKind::Hard => GuideLimitKind::Hard,
},
count: l.count,
when_at_limit: l.when_at_limit,
}
}
fn holds(doc: &Document, sections: &[&Section], i: usize) -> bool {
(0..doc.body.headings.len()).any(|h| takes(doc, sections, i, h))
}
fn takes(doc: &Document, sections: &[&Section], i: usize, h: usize) -> bool {
let section = sections[i];
let headings = &doc.body.headings;
let heading = &headings[h];
if heading.level != section.level {
return false;
}
let exact = |s: &Section| match &s.heading.shape {
Shape::Text(Text::Literal(t)) => t == &heading.text,
Shape::Text(Text::From(key)) => doc
.frontmatter
.as_ref()
.and_then(|f| f.get(key))
.and_then(crate::Spanned::scalar_text)
.is_some_and(|v| v == heading.text),
_ => false,
};
let text = squash(&heading.text);
let shaped = |s: &Section| {
!s.is_exact() && s.level == heading.level && s.heading.shape.matches(&text, |_| None)
};
let named = if section.is_exact() {
exact(section)
} else {
shaped(section) && !sections.iter().any(|s| exact(s))
};
let renamed = section.renamed_from.iter().any(|r| r == &heading.text)
&& !sections.iter().any(|s| exact(s) || shaped(s));
if !(named || renamed) {
return false;
}
let Some(parent) = §ion.parent else {
return true;
};
let Some(p) = sections
.iter()
.position(|s| s.rule_id.as_deref() == Some(parent.as_str()))
else {
return false;
};
let level = sections[p].level;
(0..h)
.rev()
.find(|&j| headings[j].level <= level)
.is_some_and(|j| takes(doc, sections, p, j))
}