use serde::{Serialize, Serializer};
use super::deriver::push_unique;
use crate::{
check::{self, Counts, Host, LimitFacts, LimitSubject, RuleName},
grammar::{
Block, FrontmatterConstraint, Label, Limit, LimitKind, Schema, Section, States, Unit,
squash,
},
markdown::BlockKind,
};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Guide {
pub guidance: Option<String>,
pub bans: Vec<String>,
pub labels: Vec<LabelGuide>,
pub frontmatter: Vec<KeyGuide>,
pub preamble: Option<PreambleGuide>,
pub sections: Vec<SectionGuide>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LabelGuide {
pub key: String,
pub words: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct KeyGuide {
pub key: String,
pub lifecycle: bool,
pub optional: bool,
pub guidance: Option<String>,
pub limit: Option<Limit>,
pub text: Option<String>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PreambleGuide {
pub guidance: Option<String>,
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SectionGuide {
pub heading: String,
pub level: u8,
pub rule_id: Option<String>,
pub parent: Option<String>,
pub optional: bool,
pub repeat: bool,
pub guidance: Option<String>,
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct BlockGuide {
#[serde(serialize_with = "kind_name")]
pub kind: BlockKind,
pub rule_id: Option<String>,
pub pos: usize,
pub optional: bool,
pub guidance: Option<String>,
pub limits: Vec<RuleLimit>,
pub labels: Vec<RuleLabel>,
pub bans: Vec<String>,
pub text: Option<String>,
pub blocks: Vec<BlockGuide>,
pub line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RuleLabel {
pub rule: Option<usize>,
pub rule_id: Option<String>,
pub line: usize,
pub label: Label,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RuleLimit {
pub rule: Option<usize>,
pub format: Option<String>,
pub rule_id: Option<String>,
pub counts: Option<Counts>,
pub line: usize,
pub limit: Limit,
}
fn kind_name<S: Serializer>(kind: &BlockKind, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(kind.name())
}
pub fn guide(schema: &Schema, states: &States, host: &dyn Host) -> Guide {
let mut frontmatter: Vec<KeyGuide> = schema
.core
.frontmatter
.iter()
.filter(|(_, c)| c.common.only.admits(states))
.map(|(key, c)| KeyGuide {
key: key.clone(),
lifecycle: false,
optional: c.optional,
guidance: c.guidance.clone(),
limit: c.max.clone(),
text: key_text(host, schema.core.language.as_deref(), key, c),
line: c.common.line,
})
.collect();
frontmatter.extend(schema.core.lifecycle.iter().map(|d| KeyGuide {
key: d.key.clone(),
lifecycle: true,
optional: false,
guidance: d.guidance.clone(),
limit: None,
text: d.guidance.as_deref().map(own_line),
line: d.line,
}));
Guide {
guidance: schema.core.guidance.clone(),
bans: schema
.core
.prohibited_patterns
.iter()
.map(|b| b.message.clone())
.collect(),
labels: check::words_of(schema, host)
.iter()
.map(|(key, words)| LabelGuide {
key: key.to_string(),
words: words.to_string(),
})
.collect(),
frontmatter,
preamble: schema
.preamble
.as_ref()
.filter(|p| p.common.only.admits(states))
.map(|p| PreambleGuide {
guidance: p.guidance.clone(),
text: p.guidance.as_deref().map(own_line),
blocks: blocks(schema, p.blocks.as_deref(), states, host),
line: p.common.line,
}),
sections: schema
.sections
.iter()
.filter(|s| s.common.only.admits(states))
.map(|s| section(schema, s, states, host))
.collect(),
}
}
fn section(schema: &Schema, s: &Section, states: &States, host: &dyn Host) -> SectionGuide {
SectionGuide {
heading: s.label(),
level: s.level,
rule_id: s.rule_id.clone(),
parent: s.parent.clone(),
optional: s.optional_at(states, &schema.core.lifecycle),
repeat: s.repeat,
guidance: s.guidance.clone(),
text: s.guidance.as_deref().map(own_line),
blocks: blocks(schema, s.blocks.as_deref(), states, host),
line: s.common.line,
}
}
fn blocks(
schema: &Schema,
list: Option<&[Block]>,
states: &States,
host: &dyn Host,
) -> Vec<BlockGuide> {
list.unwrap_or(&[])
.iter()
.filter(|b| b.common.only.admits(states) && b.hard_max() != Some(0))
.map(|b| block(schema, b, states, host))
.collect()
}
fn block(schema: &Schema, b: &Block, states: &States, host: &dyn Host) -> BlockGuide {
let mut inner = blocks(schema, b.blocks.as_deref(), states, host);
for unit in b.units() {
inner.extend(blocks(schema, unit.blocks.as_deref(), states, host));
}
let limits = block_limits(b);
let bans = block_bans(schema, b);
BlockGuide {
kind: b.kind,
rule_id: b.rule_id.clone(),
pos: b.pos,
optional: b.optional_at(states, &schema.core.lifecycle),
guidance: b.guidance.clone(),
text: line_text(host, schema.core.language.as_deref(), b, &limits, &bans),
limits,
labels: block_labels(b),
bans,
blocks: inner,
line: b.common.line,
}
}
fn block_labels(b: &Block) -> Vec<RuleLabel> {
let own = b.label.map(|label| RuleLabel {
rule: None,
rule_id: None,
line: b.common.line,
label,
});
own.into_iter()
.chain(b.units().filter_map(|u| {
Some(RuleLabel {
rule: Some(u.index),
rule_id: u.rule_id.clone(),
line: u.common.line,
label: u.label?,
})
}))
.collect()
}
fn block_limits(b: &Block) -> Vec<RuleLimit> {
fn unit_limits(u: &Unit, counts: Counts, out: &mut Vec<RuleLimit>) {
if let Some(limit) = &u.max {
out.push(RuleLimit {
rule: Some(u.index),
format: u.format.clone(),
rule_id: u.rule_id.clone(),
counts: Some(counts),
line: u.common.line,
limit: limit.clone(),
});
}
for line in u.lines.iter().flatten() {
unit_limits(line, Counts::Lines, out);
}
}
let mut out: Vec<RuleLimit> = b
.max
.iter()
.map(|limit| RuleLimit {
rule: None,
format: None,
rule_id: None,
counts: None,
line: b.common.line,
limit: limit.clone(),
})
.collect();
for u in b.units() {
unit_limits(u, Counts::Units, &mut out);
}
out
}
pub(super) fn block_bans(schema: &Schema, b: &Block) -> Vec<String> {
fn unit_bans(schema: &Schema, u: &Unit, out: &mut Vec<String>) {
let format = u.format_in(&schema.core.formats);
let bans = u
.prohibited_patterns
.iter()
.chain(format.into_iter().flat_map(|f| f.prohibited.iter()));
push_unique(out, bans.map(|ban| ban.message.clone()));
for line in u.lines.iter().flatten() {
unit_bans(schema, line, out);
}
}
let mut out = Vec::new();
for u in b.units() {
unit_bans(schema, u, &mut out);
}
out
}
pub(super) fn block_text(schema: &Schema, host: &dyn Host, b: &Block) -> Option<String> {
line_text(
host,
schema.core.language.as_deref(),
b,
&block_limits(b),
&block_bans(schema, b),
)
}
fn line_text(
host: &dyn Host,
language: Option<&str>,
b: &Block,
limits: &[RuleLimit],
bans: &[String],
) -> Option<String> {
joined(
b.guidance
.iter()
.cloned()
.chain(
limits
.iter()
.flat_map(|l| limit_texts(host, &l.limit, subject(b, l), language)),
)
.chain(bans.iter().cloned()),
)
}
pub(super) fn key_text(
host: &dyn Host,
language: Option<&str>,
key: &str,
c: &FrontmatterConstraint,
) -> Option<String> {
joined(
c.guidance.iter().cloned().chain(
c.max
.iter()
.flat_map(|l| limit_texts(host, l, LimitSubject::Key(key), language)),
),
)
}
fn subject<'a>(b: &Block, l: &'a RuleLimit) -> LimitSubject<'a> {
let Some(counts) = l.counts else {
return LimitSubject::Block(b.kind);
};
let name = match (&l.format, &l.rule_id) {
(Some(format), _) => Some(RuleName::Format(format)),
(None, Some(id)) => Some(RuleName::RuleId(id)),
(None, None) => None,
};
LimitSubject::Rule {
block: b.kind,
counts,
name,
}
}
fn limit_texts(
host: &dyn Host,
limit: &Limit,
subject: LimitSubject<'_>,
language: Option<&str>,
) -> impl Iterator<Item = String> {
let facts = LimitFacts::new(limit.kind, limit.count, subject, language);
let lead = host
.limit_lead(&facts)
.filter(|words| !squash(words).is_empty())
.unwrap_or_else(|| {
let kind = match limit.kind {
LimitKind::Soft => "soft",
LimitKind::Hard => "hard",
};
format!("`{kind}: {}`, `when-at-limit`:", limit.count)
});
[lead, limit.when_at_limit.clone()].into_iter()
}
fn own_line(guidance: &str) -> String {
squash(guidance).to_string()
}
fn joined(texts: impl Iterator<Item = String>) -> Option<String> {
let texts: Vec<String> = texts
.map(|t| squash(&t).to_string())
.filter(|t| !t.is_empty())
.collect();
(!texts.is_empty()).then(|| texts.join(" "))
}