use std::sync::Arc;
use techy::core::node::{BuildId, NodeRef};
use techy::error::Diagnostic;
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
};
use crate::lang::Flm;
use crate::model::element::element_of;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::lowering::{lower_paragraph, stage_trimmed};
use crate::stdlib::backends::pres::{self, CELL_SLOT, DroppedPayload};
use super::diagnostics::OutsideTable;
use super::reader::{CellContent, read_grid};
use super::styles::Styles;
use super::{CELL, COLNAMES, COLUMN, CONTENT_ARG, DATA, DATA_ARG, ENVIRONMENT, MERGE, ROW, ROWNAMES};
pub const RULE: &str = "flm.cells.cells.lower.default";
#[derive(Debug)]
pub struct CellsRule {
styles: Arc<Styles>,
}
impl CellsRule {
pub fn new(styles: Arc<Styles>) -> CellsRule {
CellsRule { styles }
}
}
impl Lower for CellsRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let grid = read_grid(&node, &self.styles)?;
let mut staged = Vec::new();
for problem in grid.problems {
lw.diagnose(problem.diagnostic);
if let Some(mark) = problem.dropped {
staged.push(lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?);
}
}
if grid.payload.cells.is_empty() {
return Ok(Lowering::Emit(staged));
}
let backend = lw.backend().clone();
for name in &grid.styles {
if let Some(style) = self.styles.get(name.as_str()) {
for id in style.requirements_on(backend.as_str()) {
lw.require(id);
}
}
}
let mut slots: Vec<(String, Vec<BuildId>)> = Vec::with_capacity(grid.contents.len());
for content in grid.contents {
let blocks = match content {
CellContent::Blocks(slice) => lw.lower_nodes(cx, slice)?,
CellContent::Inline(slice) => {
let nodes: Vec<NodeRef<'_, Flm>> = slice.iter().collect();
let run = stage_trimmed(cx, lw, &nodes, |_| false)?;
vec![lower_paragraph(cx, lw, None, run, Vec::new())?]
}
};
slots.push((CELL_SLOT.to_string(), blocks));
}
staged.push(lw.pres_slots_with(cx, &ElementName::from(pres::CELLS), grid.payload, slots)?);
Ok(Lowering::Emit(staged))
}
}
#[derive(Debug, Default)]
pub struct OutsideRule;
pub const OUTSIDE_RULES: [(&str, &str, &str, &str); 7] = [
(
CELL,
"flm.cells.cell.lower.default",
"‘\\cell’ must be written directly in the body of a ‘cells’ environment, or as an entry of ‘\\celldata’",
"\\cell",
),
(
DATA,
"flm.cells.data.lower.default",
"‘\\celldata’ must be written directly in the body of a ‘cells’ environment",
"\\celldata",
),
(
ROW,
"flm.cells.row.lower.default",
"‘\\\\’ in a table of cells must be written directly in its body or in the data of ‘\\celldata’",
"\\\\",
),
(
COLUMN,
"flm.cells.column.lower.default",
"‘&’ must be written directly in the data of ‘\\celldata’, between two entries",
"&",
),
(
MERGE,
"flm.cells.merge.lower.default",
"‘\\merge’ must be written in the placement of ‘\\cell’ or the mapping of ‘\\celldata’",
"\\merge",
),
(
ROWNAMES,
"flm.cells.rownames.lower.default",
"‘\\rownames’ must be written directly in the body of a ‘cells’ environment",
"\\rownames",
),
(
COLNAMES,
"flm.cells.colnames.lower.default",
"‘\\colnames’ must be written directly in the body of a ‘cells’ environment",
"\\colnames",
),
];
impl Lower for OutsideRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let element = element_of(&node).name.clone();
let Some(&(_, _, detail, spelling)) =
OUTSIDE_RULES.iter().find(|(name, ..)| *name == element.as_str())
else {
return Err(LowerError::structure("a command of the tables of cells without its rule"));
};
lw.diagnose(Diagnostic::error(OutsideTable { detail: detail.to_string() }, node.span().clone()));
let content = match element.as_str() {
CELL => Some(CONTENT_ARG),
DATA => Some(DATA_ARG),
_ => None,
};
let shown =
content.filter(|argument| matches!(node.argument_content_nodes_named(argument), Ok(Some(_))));
if let Some(argument) = shown {
return Ok(Lowering::Emit(lw.lower_arg_named(cx, &node, argument)?));
}
let mark = DroppedPayload {
condition: Name::from("flm.cells.outside-table"),
detail: format!("{spelling} out of place"),
};
Ok(Lowering::Emit(vec![lw.pres_with(cx, &ElementName::from(pres::DROPPED), mark, Vec::new())?]))
}
}
pub(super) fn rules(styles: Arc<Styles>) -> Vec<LoweringRule> {
let mut rules = vec![
LoweringRule::new(
RULE,
ENVIRONMENT,
LoweringDecl::new().produces(pres::CELLS).produces(pres::PAR).produces(pres::DROPPED),
Arc::new(CellsRule::new(styles)),
DefaultMark::Everywhere,
)
.docs(
"a table of cells lowers to `flm.pres.cells`, its payload the table's model and its \
`cell` content slots the cells' content, after one dropped mark \
(`flm.pres.dropped`) per thing left out",
),
];
for (element, rule, _, _) in OUTSIDE_RULES {
rules.push(
LoweringRule::new(
rule,
element,
LoweringDecl::new().produces(pres::DROPPED),
Arc::new(OutsideRule),
DefaultMark::Everywhere,
)
.docs(
"a command of the tables of cells lowered outside its table is reported; its \
content is shown where the command is written, or a dropped mark is placed there",
),
);
}
rules
}