use std::collections::{BTreeMap, HashMap};
use super::Refusal;
use crate::{
check::Host,
grammar::{Block, KeyText, RuleCommon, Schema, Section, Shape, States, Text, Unit, Words},
markdown::{BlockKind, Dialect},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Mode {
Scaffold,
Plain,
Skeleton,
}
#[derive(Debug, Clone, Default)]
pub(super) struct Examples {
pub(super) keys: BTreeMap<String, String>,
pub(super) preamble: Option<String>,
pub(super) sections: HashMap<usize, String>,
pub(super) blocks: HashMap<usize, String>,
}
pub(super) fn address<T>(rule: &T) -> usize {
std::ptr::from_ref(rule) as usize
}
pub(super) fn text_of(lines: &[String]) -> Option<String> {
let start = lines.iter().position(|l| !l.trim().is_empty())?;
let end = lines.iter().rposition(|l| !l.trim().is_empty())?;
Some(lines[start..=end].join("\n"))
}
pub(crate) struct Deriver<'a> {
pub(super) schema: &'a Schema,
pub(super) host: &'a dyn Host,
pub(super) dialect: Dialect,
pub(super) states: &'a States,
pub(super) keys: BTreeMap<String, Vec<KeyText>>,
pub(super) kinds: Vec<BlockKind>,
pub(super) values: BTreeMap<String, String>,
pub(super) section_rule: Option<String>,
pub(super) group_rule: Option<String>,
pub(super) refusals: Vec<Refusal>,
pub(super) omitted: Vec<Refusal>,
pub(super) in_optional: bool,
pub(super) scope: Option<BTreeMap<String, usize>>,
pub(super) labels: Words,
pub(super) named_label: Option<String>,
pub(super) mode: Mode,
pub(super) given: &'a BTreeMap<String, String>,
pub(super) examples: Option<Examples>,
}
struct Trial {
pub(super) lines: usize,
pub(super) refusals: usize,
pub(super) keys: BTreeMap<String, Vec<KeyText>>,
pub(super) kinds: usize,
pub(super) examples: Option<Examples>,
}
impl Deriver<'_> {
pub(super) fn plain(&self) -> bool {
self.mode != Mode::Scaffold
}
pub(super) fn skeleton(&self) -> bool {
self.mode == Mode::Skeleton
}
pub(super) fn keeps(&self, rule: Option<&Unit>) -> bool {
if !self.skeleton() {
return true;
}
match rule.and_then(|r| r.shape.as_ref()) {
Some(Shape::Text(Text::Literal(_))) => true,
Some(Shape::Text(Text::From(key))) => self.values.contains_key(key),
_ => false,
}
}
pub(super) fn record_section(&mut self, rule: &Section, lines: &[String]) {
if let Some(ex) = &mut self.examples
&& let Some(text) = text_of(lines)
{
ex.sections.entry(address(rule)).or_insert(text);
}
}
pub(super) fn record_block(&mut self, rule: &Block, lines: &[String]) {
if let Some(ex) = &mut self.examples
&& let Some(text) = text_of(lines)
{
ex.blocks.entry(address(rule)).or_insert(text);
}
}
pub(super) fn attempt(
&mut self,
optional: bool,
out: &mut Vec<String>,
write: impl FnOnce(&mut Self, &mut Vec<String>),
) {
if !optional {
return write(self, out);
}
let at = self.save(out);
write(self, out);
if self.refusals.len() > at.refusals {
self.undo(at, out);
}
}
fn save(&self, out: &[String]) -> Trial {
Trial {
lines: out.len(),
refusals: self.refusals.len(),
examples: self.examples.clone(),
keys: self.keys.clone(),
kinds: self.kinds.len(),
}
}
fn undo(&mut self, at: Trial, out: &mut Vec<String>) {
out.truncate(at.lines);
let stopped: Vec<Refusal> = self.refusals.split_off(at.refusals);
self.keys = at.keys;
self.kinds.truncate(at.kinds);
self.examples = at.examples;
push_unique(&mut self.omitted, stopped);
}
pub(super) fn optional_region(
&mut self,
out: &mut Vec<String>,
write: impl FnOnce(&mut Self, &mut Vec<String>),
) {
let start = out.len();
let held = std::mem::replace(&mut self.in_optional, true);
write(self, out);
self.in_optional = held;
if !self.plain() {
wrap(&self.dialect, start, out);
}
}
pub(super) fn gate_text(&self, common: &RuleCommon) -> Option<String> {
(!self.plain() && common.only.is_gated())
.then(|| format!("{} {}", self.dialect.spell("only"), common.only.render()))
}
pub(super) fn refuse(&mut self, line: usize, what: impl Into<String>) {
self.refuse_on(line, "TLMD_116", what);
}
pub(super) fn refuse_on(
&mut self,
line: usize,
criterion: &'static str,
what: impl Into<String>,
) {
let what = what.into();
if !self
.refusals
.iter()
.any(|r| r.line == line && r.what == what)
{
self.refusals.push(Refusal {
line,
criterion,
what,
});
}
}
}
pub(super) fn push_unique<T: PartialEq>(into: &mut Vec<T>, from: impl IntoIterator<Item = T>) {
for one in from {
if !into.contains(&one) {
into.push(one);
}
}
}
fn wrap(dialect: &Dialect, start: usize, out: &mut Vec<String>) {
while out.len() > start && out.last().is_some_and(String::is_empty) {
out.pop();
}
if out.len() == start {
return;
}
out.insert(start, String::new());
out.insert(start, format!("<!-- {} -->", dialect.spell("optional")));
out.push(String::new());
out.push(format!("<!-- /{} -->", dialect.spell("optional")));
out.push(String::new());
}