use techy::core::node::{BuildId, NodeRef};
use techy::error::Diagnostic;
use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl};
use crate::lang::Flm;
use crate::lang::mint::is_field_named;
use crate::lang::rewrites::blocks::argument_holds_blocks;
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::lowering::{
is_blank, lower_paragraph, lower_run, stage_trimmed, stage_trimmed_runs,
};
use crate::stdlib::backends::pres::{self, BlockPayload, Length, LinePayload, LinesPayload};
use super::config::{QuoteSection, english_list};
use super::diagnostics::{BareContent, IndentMidLine, NestedSection};
use super::html::STYLE;
use super::elements::{QuoteElement, SectionElement, is_in_quote_body, section_position};
use super::{INDENT_COMMAND, LINEBREAK_COMMAND, QUOTE_ROLE};
#[derive(Debug, Default, Clone, Copy)]
pub struct QuoteRule;
impl Lower for QuoteRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
lw.require(&Name::from(STYLE));
let value = element_value::<QuoteElement>(&node)
.ok_or_else(|| LowerError::structure("a quotation without its element's data"))?;
let body: Vec<NodeRef<'_, Flm>> =
node.body().map(|body| body.iter().collect()).unwrap_or_default();
let mut children = Vec::new();
let mut start = 0;
for (at, child) in body.iter().enumerate() {
if let Some(position) = section_position(child) {
bare_run(cx, lw, value, &body[start..at], &mut children)?;
children.push(stage_section_node(cx, lw, position.section, child)?);
start = at + 1;
}
}
bare_run(cx, lw, value, &body[start..], &mut children)?;
let payload = BlockPayload {
role: Some(Name::from(QUOTE_ROLE)),
kinds: vec![Name::from(value.name.as_str())],
anchor: None,
doc_role: None,
};
let block = lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, children)?;
Ok(Lowering::Emit(vec![block]))
}
}
pub(super) fn quote_decl() -> LoweringDecl {
LoweringDecl::new()
.produces(pres::BLOCK)
.produces(pres::PAR)
.produces(pres::LINES)
.produces(pres::LINE)
}
fn bare_run(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
value: &QuoteElement,
run: &[NodeRef<'_, Flm>],
out: &mut Vec<BuildId>,
) -> Result<(), LowerError> {
let is_edge = |node: &NodeRef<'_, Flm>| node.is_comment() || is_blank(node);
let Some(first) = run.iter().position(|node| !is_edge(node)) else { return Ok(()) };
let last = run.iter().rposition(|node| !is_edge(node)).unwrap_or(first);
let run = &run[first..=last];
let holds_blocks = value.environment.holds_blocks();
match value.environment.bare {
Some(kind) => out.push(stage_section(cx, lw, kind, run, holds_blocks)?),
None => {
lw.diagnose(Diagnostic::error(bare_content(value), run[0].span().clone()));
out.extend(lower_blocks(cx, lw, run)?);
}
}
Ok(())
}
pub(super) fn bare_content(value: &QuoteElement) -> BareContent {
let sections =
value.environment.sections.iter().map(|section| format!("‘\\{}’", section.as_str()));
BareContent { environment: value.name.clone(), sections: english_list(sections, "or") }
}
fn stage_section_node(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
section: QuoteSection,
node: &NodeRef<'_, Flm>,
) -> Result<BuildId, LowerError> {
let content: Vec<NodeRef<'_, Flm>> =
node.argument_content_nodes(0).map(|nodes| nodes.iter().collect()).unwrap_or_default();
stage_section(cx, lw, section, &content, argument_holds_blocks(node, 0))
}
fn stage_section(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
section: QuoteSection,
content: &[NodeRef<'_, Flm>],
holds_blocks: bool,
) -> Result<BuildId, LowerError> {
let staged = match section {
QuoteSection::Lines => vec![stage_lines(cx, lw, content)?],
QuoteSection::Block if holds_blocks => lower_blocks(cx, lw, content)?,
QuoteSection::Text | QuoteSection::Attributed | QuoteSection::Block => {
let run = stage_trimmed(cx, lw, content, is_line_command)?;
if run.is_empty() {
Vec::new()
} else {
vec![lower_paragraph(cx, lw, None, run, Vec::new())?]
}
}
};
sub_block(cx, lw, section, staged)
}
fn sub_block(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
section: QuoteSection,
content: Vec<BuildId>,
) -> Result<BuildId, LowerError> {
let payload = BlockPayload {
role: Some(Name::from(section.role())),
kinds: Vec::new(),
anchor: None,
doc_role: None,
};
lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, content)
}
fn lower_blocks(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
content: &[NodeRef<'_, Flm>],
) -> Result<Vec<BuildId>, LowerError> {
let mut out = Vec::new();
for node in content {
if !(node.is_comment() || is_blank(node)) {
out.extend(lower_run(cx, lw, std::slice::from_ref(node))?);
}
}
Ok(out)
}
fn stage_lines(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
content: &[NodeRef<'_, Flm>],
) -> Result<BuildId, LowerError> {
let mut lines = Vec::new();
if content.iter().any(|node| is_content(node) || is_linebreak(node)) {
for line in content.split(is_linebreak) {
lines.push(stage_line(cx, lw, line)?);
}
}
lw.pres_with(cx, &ElementName::from(pres::LINES), LinesPayload, lines)
}
fn stage_line(
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
line: &[NodeRef<'_, Flm>],
) -> Result<BuildId, LowerError> {
let (indent_left, runs) = read_line(lw, line);
let staged = stage_trimmed_runs(cx, lw, &runs, is_line_command)?;
let payload = LinePayload { indent_left, ..LinePayload::default() };
lw.pres_with(cx, &ElementName::from(pres::LINE), payload, staged)
}
pub(super) fn read_line<'l, 't>(
lw: &mut dyn Lowerer,
line: &'l [NodeRef<'t, Flm>],
) -> (Length, Vec<&'l [NodeRef<'t, Flm>]>) {
let mut indents: i32 = 0;
let mut started = false;
let mut runs: Vec<&[NodeRef<'_, Flm>]> = Vec::new();
let mut run_start = 0;
for (at, node) in line.iter().enumerate() {
if is_field_named(node, INDENT_COMMAND) {
if started {
lw.diagnose(Diagnostic::error(IndentMidLine, node.span().clone()));
} else {
indents = indents.saturating_add(1);
}
runs.push(&line[run_start..at]);
run_start = at + 1;
} else if is_content(node) {
started = true;
}
}
runs.push(&line[run_start..]);
(Length::tabs(indents), runs)
}
pub(super) fn is_content(node: &NodeRef<'_, Flm>) -> bool {
!(node.is_comment() || is_blank(node) || is_line_command(node))
}
pub(super) fn is_line_command(node: &NodeRef<'_, Flm>) -> bool {
is_linebreak(node) || is_field_named(node, INDENT_COMMAND)
}
pub(super) fn is_linebreak(node: &NodeRef<'_, Flm>) -> bool {
is_field_named(node, LINEBREAK_COMMAND)
}
#[derive(Debug, Default, Clone, Copy)]
pub struct SectionRule;
impl Lower for SectionRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let section = element_value::<SectionElement>(&node)
.ok_or_else(|| LowerError::structure(
"a quotation-section command without its element's data"
))?
.section;
if !is_in_quote_body(&node) {
lw.diagnose(Diagnostic::error(
NestedSection { section: section.as_str().to_string() },
node.span().clone(),
));
}
let content: Vec<NodeRef<'_, Flm>> =
node.argument_content_nodes(0).map(|nodes| nodes.iter().collect()).unwrap_or_default();
let mut out = Vec::new();
for run in content.split(|node| is_linebreak(node) || is_field_named(node, INDENT_COMMAND)) {
out.extend(lower_run(cx, lw, run)?);
}
Ok(Lowering::Emit(out))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stdlib::features::quote::QuoteEnvironment;
#[test]
fn the_bare_content_report_lists_the_accepted_sections_as_english_does() {
let listed = |sections: Vec<QuoteSection>| {
let environment = QuoteEnvironment::new(sections);
bare_content(&QuoteElement { name: "quote".into(), environment }).sections
};
assert_eq!(listed(vec![QuoteSection::Block]), "‘\\block’");
assert_eq!(listed(vec![QuoteSection::Block, QuoteSection::Text]), "‘\\text’ or ‘\\block’");
assert_eq!(
listed(QuoteSection::ALL.to_vec()),
"‘\\text’, ‘\\lines’, ‘\\attributed’ or ‘\\block’"
);
}
}