use std::sync::Arc;
use techy::core::node::{BuildId, GroupData, NodeKind, NodeRef, NodeTree};
use techy::core::Lang;
use techy::error::Diagnostic;
use techy::source::SourceSpan;
use techy::transform::{Restage, RestageContext, RestageVisitor};
use crate::core::lowering::{
DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
spelling_at_lowering,
};
use crate::core::registry::{BuildError, FeatureBuilder};
use crate::lang::flm::FlmCallableType;
use crate::lang::guard::{self, on_worker_thread, GuardPolicy};
use crate::lang::rewrites::userdefs::{CompiledTemplate, PlaceholderTarget};
use crate::lang::{Flm, FlmGroupType};
use crate::model::aspects::is_whitespace_of;
use crate::model::element::element_value;
use crate::model::names::{ElementName, Name};
use crate::stdlib::backends::latex::construct::{stamp_point, ARG_SLOT, ENVIRONMENT, MACRO, RAW};
use crate::stdlib::backends::latex::packages::ENUMITEM;
use crate::stdlib::backends::latex::{
LatexArgShape, LatexEnvironmentPayload, LatexMacroPayload, LatexRawPayload,
};
use crate::stdlib::backends::latex_recomposed::{LatexRecomposedRenderOptions, BACKEND};
use crate::stdlib::backends::lowering::lower_run;
use crate::stdlib::backends::pres::BODY_SLOT;
use crate::stdlib::features::numbering::{occurrences_of, COUNTERS};
use crate::stdlib::features::refs::{self, SafeLabels, SAFE_LABELS};
use super::diagnostics::{NoEnumitemFormat, NumberReadAsCharacters};
use super::items::{is_item, list_items};
use super::labels::{CompiledLabel, Labels};
use super::lower::{own_label, own_ref, report_no_numbering, report_reading, stage_tag};
use super::{ListElement, ITEM_COMMAND, LABEL_KEY, LIST, OPTIONS_ARG, REF_KEY};
pub const LATEX_RULE: &str = "flm.lists.list.lower.latex-recomposed";
#[derive(Debug)]
pub struct ListLatexRule {
labels: Arc<Labels>,
}
impl ListLatexRule {
pub(super) fn new(labels: Arc<Labels>) -> ListLatexRule {
ListLatexRule { labels }
}
}
const ENUMITEM_FORMATS: [(&str, &str); 5] = [
("arabic", "\\arabic*"),
("alph", "\\alph*"),
("Alph", "\\Alph*"),
("roman", "\\roman*"),
("Roman", "\\Roman*"),
];
fn enumitem_command(name: &str) -> Option<&'static str> {
ENUMITEM_FORMATS.iter().find(|(format, _)| *format == name).map(|(_, command)| *command)
}
struct Braced<'t> {
template: &'t CompiledTemplate,
}
struct Stamp<'t> {
template: &'t CompiledTemplate,
}
impl RestageVisitor<Flm, (), ()> for Stamp<'_> {
type Error = LowerError;
fn restage(
&mut self,
node: NodeRef<'_, Flm>,
cx: &mut RestageContext<'_, Flm, (), ()>,
) -> Result<Restage<()>, LowerError> {
if node.callable_type() != Some(FlmCallableType::Placeholder) {
return Ok(Restage::Descend(()));
}
let command = match self.template.placeholder(node.id()).map(|reference| &reference.target) {
Some(PlaceholderTarget::Extra(format)) => enumitem_command(format),
_ => None,
};
let command = command.ok_or_else(|| {
LowerError::structure("a placeholder of a list's label that is not an enumitem format")
})?;
Ok(Restage::Emit(vec![stamp_point(&node, command, cx)?]))
}
}
impl RestageVisitor<Flm, (), ()> for Braced<'_> {
type Error = LowerError;
fn restage(
&mut self,
root: NodeRef<'_, Flm>,
cx: &mut RestageContext<'_, Flm, (), ()>,
) -> Result<Restage<()>, LowerError> {
let span = SourceSpan::new(root.span().source(), root.span().start()..root.span().start());
let state = Arc::clone(root.parsing_state());
let mut stamp = Stamp { template: self.template };
let mut children = Vec::new();
for node in root.children().iter() {
children.extend(cx.restage_subtree(node, &mut stamp).map_err(copy_failed)?);
}
let mut add = |kind: NodeKind<Flm>, children: Vec<BuildId>| {
let ext =
Flm::make_node_ext(&kind, &span, &state, cx.builder().staged_children(&children))
.map_err(copy_failed)?;
cx.builder()
.add(kind, span.clone(), Arc::clone(&state), children, ext, ())
.map_err(copy_failed)
};
let group = add(NodeKind::group(GroupData::new(FlmGroupType::Content, "{", "}")), children)?;
Ok(Restage::Emit(vec![add(NodeKind::list(), vec![group])?]))
}
}
fn copy_failed(error: impl std::fmt::Display) -> LowerError {
LowerError::other(format!("copying a list's label failed: {error}"))
}
fn label_value(label: &CompiledLabel) -> Result<Arc<NodeTree<Flm>>, LowerError> {
let template = label.template();
on_worker_thread(|| {
guard::restager(&mut Braced { template }, GuardPolicy::StackBudget)
.restage(template.tree())
.map(Arc::new)
.map_err(copy_failed)
})
.map_err(|error| LowerError::other(format!(
"copying a list's label template needs a thread with a large stack, and the \
operating system refused to create one: {error}"
)))?
}
fn raw(cx: &mut LowerCx<'_>, lw: &mut dyn Lowerer, text: &str) -> Result<BuildId, LowerError> {
lw.pres_slots_with(cx, &ElementName::from(RAW), LatexRawPayload::new(text), Vec::new())
}
fn stage_label_key(
node: &NodeRef<'_, Flm>,
key: &str,
template: &str,
label: &CompiledLabel,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Option<Vec<BuildId>>, LowerError> {
let unwritable = occurrences_of(label.template())
.into_iter()
.find(|(format, _)| enumitem_command(format).is_none());
if let Some((format, _)) = unwritable {
lw.diagnose(Diagnostic::error(
NoEnumitemFormat { key: key.to_string(), template: template.to_string(), format },
node.span().clone(),
));
return Ok(None);
}
let value = label_value(label)?;
let content = match lw.splice(cx, &value) {
Err(LowerError::PlaceholderCharacters) => {
let condition =
NumberReadAsCharacters { key: key.to_string(), template: template.to_string() };
lw.diagnose(Diagnostic::error(condition, node.span().clone()));
return Ok(None);
}
other => other?,
};
let mut staged = vec![raw(cx, lw, &format!("{key}="))?];
staged.extend(content);
lw.require(&Name::from(ENUMITEM));
Ok(Some(staged))
}
impl Lower for ListLatexRule {
fn lower(
&self,
node: NodeRef<'_, Flm>,
cx: &mut LowerCx<'_>,
lw: &mut dyn Lowerer,
) -> Result<Lowering, LowerError> {
let value = element_value::<ListElement>(&node)
.ok_or_else(|| LowerError::structure("a list without its element's data"))?;
if let Some(options) = node.argument_content_nodes_named(OPTIONS_ARG).ok().flatten() {
spelling_at_lowering(options.iter())?;
}
let body = list_items(&node);
report_reading(&node, value, &body, lw);
let counted = value.kind.numbered && lw.get(COUNTERS)?.is_some();
let own = own_label(&self.labels, &node, value, &body, counted, lw);
let reference = own_ref(&self.labels, &node, value, &body, counted, lw);
report_no_numbering(&self.labels, &node, value, &body, own.as_ref(), lw)?;
let mut shapes = Vec::new();
let mut slots = Vec::new();
let label_text = body.own_label.as_ref().map(|own| own.template.as_str());
let ref_text = body.own_ref.as_deref().filter(|text| Some(*text) != label_text);
let mut keys = Vec::new();
if let (Some(label), Some(text)) = (&own, label_text) {
keys.extend(stage_label_key(&node, LABEL_KEY, text, label, cx, lw)?);
}
if let (Some(label), Some(text)) = (&reference, ref_text) {
keys.extend(stage_label_key(&node, REF_KEY, text, label, cx, lw)?);
}
if !keys.is_empty() {
let mut staged = Vec::new();
for (index, key) in keys.into_iter().enumerate() {
if index > 0 {
staged.push(raw(cx, lw, ", ")?);
}
staged.extend(key);
}
shapes.push(LatexArgShape::Optional);
slots.push((ARG_SLOT.to_string(), staged));
}
let mut content: Vec<BuildId> = Vec::new();
let before: Vec<NodeRef<'_, Flm>> = node
.body()
.map(|children| children.iter().take_while(|child| !is_item(child)).collect())
.unwrap_or_default();
if body.before.is_empty() {
for run in before.split(is_whitespace_of) {
content.extend(lower_run(cx, lw, run)?);
}
} else {
content.extend(lower_run(cx, lw, &before)?);
}
for item in &body.items {
let (args, item_slots) = match &item.tag {
None => (Vec::new(), Vec::new()),
Some(tag) => {
let staged = stage_tag(cx, lw, tag)?;
(vec![LatexArgShape::Optional], vec![(ARG_SLOT.to_string(), staged)])
}
};
content.push(lw.pres_slots_with(
cx,
&ElementName::from(MACRO),
LatexMacroPayload::new(ITEM_COMMAND, args),
item_slots,
)?);
let mut labels = Vec::new();
for written in &item.labels {
labels.push(refs::stage_label(cx, lw, &written.text, written.label.as_ref())?);
}
content.extend(refs::stage_label_group(cx, lw, labels, false)?);
content.extend(lower_run(cx, lw, &item.content)?);
}
slots.push((BODY_SLOT.to_string(), content));
let environment = lw.pres_slots_with(
cx,
&ElementName::from(ENVIRONMENT),
LatexEnvironmentPayload::new(value.name.as_str(), shapes),
slots,
)?;
Ok(Lowering::Emit(vec![environment]))
}
}
pub(super) fn latex_rule(labels: Arc<Labels>) -> LoweringRule {
LoweringRule::new(
LATEX_RULE,
LIST,
LoweringDecl::new()
.reads_opt(SAFE_LABELS)
.reads_opt(COUNTERS)
.option::<LatexRecomposedRenderOptions>()
.produces(ENVIRONMENT)
.produces(MACRO)
.produces(RAW),
Arc::new(ListLatexRule::new(labels)),
DefaultMark::OnBackends(vec![BACKEND.into()]),
)
.docs(
"a list lowers to its LaTeX environment, its own templates as the `label=` and `ref=` \
keys of the `enumitem` package, each item to `\\item` with its tag as the optional \
argument and its labels in the LaTeX hook `\\flmLabels`, and the items' content through \
the rules",
)
}
pub(super) fn register(b: &mut FeatureBuilder<'_>, labels: Arc<Labels>) -> Result<(), BuildError> {
b.peer_backend(
BACKEND,
"the latex-recomposed backend, on which the recomposition rule of a list is the default",
)?;
b.peer_element::<LatexEnvironmentPayload>(
ENVIRONMENT,
"the LaTeX family's environment construct, which the recomposition rule stages for the list",
)?;
b.peer_element::<LatexMacroPayload>(
MACRO,
"the LaTeX family's macro-call construct, which the recomposition rule stages for `\\item` \
and the LaTeX hook `\\flmLabels`",
)?;
b.peer_element::<LatexRawPayload>(
RAW,
"the LaTeX family's raw construct, in which the recomposition rule stages the keys of a \
list's own templates and a label written as the document wrote it",
)?;
b.peer_table::<SafeLabels>(
SAFE_LABELS.name(),
"the references feature's safe-labels table, which the recomposition rule reads for the \
safe label of each label written after an `\\item`",
)?;
b.lowering_rule(latex_rule(labels))
}