use std::collections::BTreeSet;
use std::sync::Arc;
use techy::core::node::{NodeKind, NodeRef, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use crate::lang::guard;
use crate::lang::structural;
use crate::lang::{Flm, FlmDiagnostics, FlmGroupType, FlmOrigin, FlmSpan, nowhere};
use crate::model::addr::TreeId;
use crate::model::element::element_of;
use crate::model::names::Name;
use crate::stdlib::backends::latex::construct::{
self, BEGIN_SLOT, END_SLOT, LatexArgShape, LatexDefinitionKind, LatexDefinitionPayload,
LatexEnvironmentPayload, LatexMacroPayload, LatexRawPayload, arg_slots, slot_named,
};
use crate::stdlib::backends::latex::{EscapeConfig, LatexRaw, LatexSink, UnicodeMode, escape_url};
use crate::stdlib::backends::pres::{
self, BlockPayload, DroppedPayload, GridPosition, HeadingPayload, ImageDisplay,
ImagePayload, Length, LinePayload, LinkPayload, ListPayload, ParPayload, SpanPayload,
SubtreePayload, UnknownKind, UnknownPayload, UnsupportedPayload, VerbatimDisplay,
VerbatimPayload, cells_of, decoration_at, ends_in_sentence_punctuation, holds_text,
is_presentation, list_entries, payload_of, plain_text, recompose_source,
};
use super::contract::{CORE_CHUNK, Form, Row, row};
use super::feature::LatexRenderedRenderOptions;
use super::length::latex_length;
use super::stages::{LatexSegment, StageFailed};
use super::verbatim::escape_verbatim;
mod constructs;
mod elements;
mod keys;
mod walk;
const LEVEL_STACK_ESTIMATE: usize = 12 * 1024;
pub const DEPTH_LIMIT: usize = guard::STACK_BUDGET / LEVEL_STACK_ESTIMATE;
pub const LINE_WIDTH: usize = 100;
pub(crate) const NOWHERE_LABEL: &str = "latex-rendered backend";
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.latex-rendered.too-deep",
message = "the content nests too deeply to be written as LaTeX: {detail}"
)]
pub struct NestingTooDeep {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
id = "flm.latex-rendered.worker-thread",
message = "writing LaTeX needs a thread with a large stack, and the operating system \
refused to create one: {detail}"
)]
pub struct NoWorkerThread {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StagedDefinition {
pub name: String,
pub text: String,
}
#[derive(Debug, Default)]
pub struct Emitted {
pub segments: Vec<LatexSegment>,
pub requires: BTreeSet<Name>,
pub definitions: Vec<StagedDefinition>,
pub placed_at: Vec<FlmSpan>,
pub diags: FlmDiagnostics,
}
pub fn emit_tree(tree: &Arc<NodeTree<Flm>>, options: &LatexRenderedRenderOptions) -> Emitted {
match guard::on_worker_thread(|| emit_on_worker_thread(tree, options)) {
Ok(emitted) => emitted,
Err(error) => {
let mut diags = FlmDiagnostics::new();
diags.push(Diagnostic::error(
NoWorkerThread { detail: error.to_string() },
nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
));
Emitted { diags, ..Emitted::default() }
}
}
}
fn emit_on_worker_thread(tree: &Arc<NodeTree<Flm>>, options: &LatexRenderedRenderOptions) -> Emitted {
let mut emitter = Emitter::new(options);
emitter.require(CORE_CHUNK);
let root = tree.root();
let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
if root.is_list() {
emitter.run(None, &children);
} else {
emitter.run(None, &[root]);
}
emitter.end_flow();
emitter.line_start();
let Emitter { sink, placements, requires, definitions, refused, mut diags, .. } = emitter;
let latex = sink.finish().text;
if refused {
diags.push(Diagnostic::error(
NestingTooDeep { detail: format!("more than {DEPTH_LIMIT} levels") },
root.span().clone(),
));
return Emitted { diags, ..Emitted::default() };
}
let placed_at = placements.iter().map(|(_, _, span)| span.clone()).collect();
Emitted { segments: segments_of(latex, &placements), requires, definitions, placed_at, diags }
}
fn segments_of(latex: String, placements: &[(usize, TreeId, FlmSpan)]) -> Vec<LatexSegment> {
let mut segments = Vec::new();
let mut at = 0usize;
for (offset, tree, _) in placements {
if *offset > at {
segments.push(LatexSegment::Latex(String::from(&latex[at..*offset])));
}
segments.push(LatexSegment::Tree(*tree));
at = *offset;
}
if at < latex.len() {
segments.push(LatexSegment::Latex(String::from(&latex[at..])));
}
segments
}
pub(super) enum KeyValue<'t> {
Name(String),
Words(Vec<String>),
Content(Vec<NodeRef<'t, Flm>>),
Text(String),
Address(String),
Anchor(String),
Length(Length),
Number(u64),
Bool(bool),
Specs(Vec<String>),
}
pub(crate) fn is_bare_name(name: &str) -> bool {
!name.is_empty()
&& name.chars().all(|ch| ch.is_ascii_alphanumeric() || ".-_:/+@*".contains(ch))
}
pub(crate) fn anchor_spelling(address: &str) -> String {
escape_url(address).replace('~', "\\string~")
}
fn is_space(ch: char) -> bool {
matches!(ch, ' ' | '\t' | '\n' | '\r')
}
fn body<'t>(node: &NodeRef<'t, Flm>) -> Vec<NodeRef<'t, Flm>> {
node.body().map(|slice| slice.iter().collect()).unwrap_or_default()
}
fn is_element(node: &NodeRef<'_, Flm>, name: &str) -> bool {
element_of(node).name == name
}
fn shows_nothing(content: &[NodeRef<'_, Flm>]) -> bool {
let mut pending: Vec<NodeRef<'_, Flm>> = content.to_vec();
while let Some(node) = pending.pop() {
if let Some(text) = node.chars() {
if !text.chars().all(is_space) {
return false;
}
} else if node.is_comment() || is_element(&node, structural::PARBREAK) {
continue;
} else if is_presentation(&node) {
return false;
} else {
pending.extend(node.children().iter());
}
}
true
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Pending {
None,
Space,
Newline,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Last {
Nothing,
Paragraph,
Block,
}
pub(super) struct Emitter<'o> {
pub(super) sink: LatexSink,
pub(super) options: &'o LatexRenderedRenderOptions,
pub(super) requires: BTreeSet<Name>,
pub(super) definitions: Vec<StagedDefinition>,
placements: Vec<(usize, TreeId, FlmSpan)>,
depth: usize,
refused: bool,
pub(super) diags: FlmDiagnostics,
col: usize,
pub(super) flow: bool,
opening: bool,
last: Last,
pending: Pending,
pub(super) no_break: u32,
links_open: u32,
lists_open: u32,
control_word: bool,
}
impl<'o> Emitter<'o> {
pub(super) fn new(options: &'o LatexRenderedRenderOptions) -> Emitter<'o> {
Emitter {
sink: LatexSink::new(EscapeConfig::new(UnicodeMode::Declare)),
options,
requires: BTreeSet::new(),
definitions: Vec::new(),
placements: Vec::new(),
depth: 0,
refused: false,
diags: FlmDiagnostics::new(),
col: 0,
flow: false,
opening: false,
last: Last::Nothing,
pending: Pending::None,
no_break: 0,
links_open: 0,
lists_open: 0,
control_word: false,
}
}
fn descend(&mut self) -> bool {
if self.depth >= DEPTH_LIMIT {
self.refused = true;
return false;
}
self.depth += 1;
true
}
fn ascend(&mut self) {
self.depth -= 1;
}
pub(super) fn require(&mut self, id: &str) {
self.requires.insert(Name::from(id));
}
fn require_row(&mut self, row: &Row) {
if let Some(chunk) = row.chunk {
self.require(chunk);
}
}
pub(super) fn unexpected(&mut self, node: &NodeRef<'_, Flm>, what: &str) {
self.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(super::stages::EMIT_STAGE),
detail: format!(
"{what} `{}` reached the latex-rendered emitter, which cannot write it",
element_of(node).name
),
},
node.span().clone(),
));
}
fn advance(&mut self, written: &str) {
match written.rfind('\n') {
Some(at) => self.col = written.len() - at - 1,
None => self.col += written.len(),
}
}
fn flush(&mut self) {
if std::mem::replace(&mut self.opening, false) {
self.newline();
}
let pending = std::mem::replace(&mut self.pending, Pending::None);
let newline = match pending {
Pending::None => return,
Pending::Space => self.no_break == 0 && self.col > LINE_WIDTH,
Pending::Newline => self.no_break == 0,
};
if newline {
self.control_word = false;
self.sink.newline();
self.col = 0;
} else {
self.syntax(" ");
}
}
pub(super) fn put(&mut self, syntax: &str) {
self.flush();
self.syntax(syntax);
}
fn syntax(&mut self, syntax: &str) {
self.end_control_word(syntax);
let raw = LatexRaw::from_raw_payload(&LatexRawPayload::new(syntax));
if self.sink.raw(&raw).is_ok() {
self.advance(syntax);
}
}
pub(super) fn put_raw(&mut self, node: &NodeRef<'_, Flm>, raw: &LatexRaw) {
self.flush();
self.end_control_word(raw.as_str());
match self.sink.raw(raw) {
Ok(()) => self.advance(raw.as_str()),
Err(refused) => self.diags.push(Diagnostic::error(
StageFailed {
stage: String::from(super::stages::EMIT_STAGE),
detail: refused.to_string(),
},
node.span().clone(),
)),
}
}
fn end_control_word(&mut self, next: &str) {
if std::mem::take(&mut self.control_word) && next.starts_with(char::is_alphabetic) {
self.syntax(" ");
}
}
pub(super) fn newline(&mut self) {
self.control_word = false;
self.pending = Pending::None;
self.sink.newline();
self.col = 0;
}
pub(super) fn line_start(&mut self) {
if self.col != 0 {
self.newline();
} else {
self.pending = Pending::None;
}
}
pub(super) fn text(&mut self, text: &str) {
let mut text = text;
if !self.flow {
if text.chars().all(is_space) {
return;
}
self.begin_flow();
text = text.trim_start_matches(is_space);
}
let mut rest = text;
while !rest.is_empty() {
let space = rest.find(|ch: char| !is_space(ch)).unwrap_or(rest.len());
if space > 0 {
let run = &rest[..space];
let wanted = if run.contains('\n') { Pending::Newline } else { Pending::Space };
self.pending = self.pending.max(wanted);
rest = &rest[space..];
continue;
}
let word = rest.find(is_space).unwrap_or(rest.len());
self.flush();
self.end_control_word(&rest[..word]);
let before = self.sink.position();
self.sink.text(&rest[..word]);
self.col += self.sink.position() - before;
rest = &rest[word..];
}
}
pub(super) fn inline(&mut self) {
if !self.flow {
self.begin_flow();
}
}
fn begin_flow(&mut self) {
self.line_start();
self.opening = self.last != Last::Nothing;
self.flow = true;
}
pub(super) fn end_flow(&mut self) {
if self.flow {
self.flow = false;
if !self.opening {
self.last = Last::Paragraph;
}
self.opening = false;
self.pending = Pending::None;
}
}
pub(super) fn begin_block(&mut self) {
let after_paragraph = (self.flow && !self.opening) || self.last == Last::Paragraph;
self.end_flow();
self.line_start();
if after_paragraph {
self.newline();
}
}
pub(super) fn end_block(&mut self) {
self.line_start();
self.flow = false;
self.last = Last::Block;
}
fn container(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) {
let last = std::mem::replace(&mut self.last, Last::Nothing);
self.flow = false;
self.run(carrier, nodes);
self.end_flow();
self.line_start();
self.last = last;
}
pub(super) fn inline_content(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) {
let flow = std::mem::replace(&mut self.flow, true);
self.run(carrier, nodes);
self.flow = flow;
}
}
fn cell_spec(cell: &pres::CellSpec) -> String {
let mut parts = vec![format!("row={}", u64::from(cell.row) + 1), format!("col={}", u64::from(cell.col) + 1)];
if cell.row_span > 1 {
parts.push(format!("row-span={}", cell.row_span));
}
if cell.col_span > 1 {
parts.push(format!("col-span={}", cell.col_span));
}
if let Some(align) = cell.align {
parts.push(format!("align={}", align.as_str()));
}
if let Some(header) = cell.header {
parts.push(format!("header={}", header.as_str()));
}
if !cell.rules.is_empty() {
let rules: Vec<&str> = cell.rules.iter().map(|edge| edge.as_str()).collect();
parts.push(format!("rules={{{}}}", rules.join(" ")));
}
if !cell.styles.is_empty() {
let styles: Vec<String> = cell
.styles
.iter()
.map(|style| {
if is_bare_name(style.as_str()) {
style.to_string()
} else {
format!("{{{}}}", anchor_spelling(style.as_str()))
}
})
.collect();
parts.push(format!("styles={{{}}}", styles.join(" ")));
}
format!("{{{}}}", parts.join(", "))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_name_is_bare_only_when_every_character_may_stand_bare() {
assert!(is_bare_name("flm.theorems.theorem"));
assert!(is_bare_name("sec-intro_2:a"));
assert!(!is_bare_name(""));
assert!(!is_bare_name("a b"));
assert!(!is_bare_name("a,b"));
assert!(!is_bare_name("a]b"));
assert!(!is_bare_name("a%b"));
assert!(!is_bare_name("a#b"));
}
#[test]
fn a_cell_spec_lists_only_what_the_cell_sets() {
let mut cell = pres::CellSpec::at(0, 1);
assert_eq!(cell_spec(&cell), "{row=1, col=2}");
cell.col_span = 2;
cell.rules = vec![pres::CellEdge::Below];
assert_eq!(cell_spec(&cell), "{row=1, col=2, col-span=2, rules={below}}");
cell.styles = vec![Name::from("green"), Name::from("a b")];
assert_eq!(cell_spec(&cell), "{row=1, col=2, col-span=2, rules={below}, styles={green {a b}}}");
}
}