#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
use super::notation::{Step, flush, walk};
use super::{Drawable, Form};
use crate::Error;
use crate::linear::proofs::style::{Drawn, Part, parts};
use crate::linear::proofs::{Labels, OpenGoal};
use crate::linear::sequents::Sequent;
use crate::linear::sequents::notation::{Atoms, Notation};
use crate::ordinary::Symbols;
use std::fmt::Write;
const NOTATION: Notation = Notation {
tensor: r"\otimes",
par: r"\parr",
with: r"\with",
plus: r"\oplus",
lollipop: r"\multimap",
under: r"\mathbin{\backslash}",
over: r"\mathbin{/}",
bang: r"\oc ",
quest: r"\wn ",
one: r"\mathbf{1}",
bot: r"\bot",
top: r"\top",
zero: "0",
dual_prefix: "",
dual: r"^\bot",
turnstile: r"\vdash",
align: "&",
atom: Atoms::Latex,
forall: r"\forall ",
exists: r"\exists ",
dot: r".\,",
ordinary: Symbols {
not: r"\lnot ",
and: r"\land",
or: r"\lor",
implies: r"\to",
iff: r"\leftrightarrow",
truth: r"\top",
falsity: r"\bot",
},
};
const PREAMBLE: &str = r"\documentclass[border=5pt]{standalone}
\usepackage{amssymb}
\usepackage{cmll}
";
fn greek(c: char) -> Option<&'static str> {
Some(match c {
'α' => r"\alpha",
'β' => r"\beta",
'γ' => r"\gamma",
'δ' => r"\delta",
'ε' => r"\varepsilon",
'ϵ' => r"\epsilon",
'ζ' => r"\zeta",
'η' => r"\eta",
'θ' => r"\theta",
'ϑ' => r"\vartheta",
'ι' => r"\iota",
'κ' => r"\kappa",
'λ' => r"\lambda",
'μ' => r"\mu",
'ν' => r"\nu",
'ξ' => r"\xi",
'ο' => "o",
'π' => r"\pi",
'ϖ' => r"\varpi",
'ρ' => r"\rho",
'ϱ' => r"\varrho",
'σ' => r"\sigma",
'ς' => r"\varsigma",
'τ' => r"\tau",
'υ' => r"\upsilon",
'φ' => r"\varphi",
'ϕ' => r"\phi",
'χ' => r"\chi",
'ψ' => r"\psi",
'ω' => r"\omega",
'Γ' => r"\Gamma",
'Δ' => r"\Delta",
'Θ' => r"\Theta",
'Λ' => r"\Lambda",
'Ξ' => r"\Xi",
'Π' => r"\Pi",
'Σ' => r"\Sigma",
'Υ' => r"\Upsilon",
'Φ' => r"\Phi",
'Ψ' => r"\Psi",
'Ω' => r"\Omega",
'Α' => "A",
'Β' => "B",
'Ε' => "E",
'Ζ' => "Z",
'Η' => "H",
'Ι' => "I",
'Κ' => "K",
'Μ' => "M",
'Ν' => "N",
'Ο' => "O",
'Ρ' => "P",
'Τ' => "T",
'Χ' => "X",
_ => return None,
})
}
pub(crate) fn atom<W: Write + ?Sized>(out: &mut W, name: &str) -> std::fmt::Result {
let mut chars = name.chars();
if let (Some(c), None) = (chars.next(), chars.next()) {
if c.is_ascii_alphabetic() {
return out.write_char(c);
}
if let Some(letter) = greek(c) {
return out.write_str(letter);
}
}
out.write_str(r"\mathit{")?;
for c in name.chars() {
escape(out, c)?;
}
out.write_char('}')
}
fn escape(out: &mut (impl Write + ?Sized), c: char) -> std::fmt::Result {
match c {
'\\' => out.write_str(r"\mbox{\textbackslash}"),
'{' | '}' | '$' | '#' | '%' | '&' | '_' => {
out.write_char('\\')?;
out.write_char(c)
}
'^' => out.write_str(r"\mbox{\textasciicircum}"),
'~' => out.write_str(r"\mbox{\textasciitilde}"),
' ' => out.write_str(r"\ "),
'‿' => out.write_str(r"{\smallsmile}"),
'·' => out.write_str(r"{\cdotp}"),
c => match greek(c) {
Some(letter) if letter.starts_with('\\') => write!(out, "{{{letter}}}"),
Some(letter) => out.write_str(letter),
None => out.write_char(c),
},
}
}
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
pub form: Form,
pub labels: Labels,
pub open: OpenGoal,
pub align: bool,
pub ebproof: String,
pub preamble: Option<String>,
pub lambda: Option<crate::lambda::Options>,
}
impl Default for Options {
fn default() -> Self {
Self {
form: Form::Fragment,
labels: Labels::Upright,
open: OpenGoal::Dots,
align: true,
ebproof: String::new(),
preamble: None,
lambda: None,
}
}
}
impl Options {
#[must_use]
pub fn with_form(self, form: Form) -> Self {
Self { form, ..self }
}
#[must_use]
pub fn with_labels(self, labels: Labels) -> Self {
Self { labels, ..self }
}
#[must_use]
pub fn with_open(self, open: OpenGoal) -> Self {
Self { open, ..self }
}
#[must_use]
pub fn with_align(self, align: bool) -> Self {
Self { align, ..self }
}
#[must_use]
pub fn with_ebproof(self, ebproof: String) -> Self {
Self { ebproof, ..self }
}
#[must_use]
pub fn with_preamble(self, preamble: Option<String>) -> Self {
Self { preamble, ..self }
}
#[must_use]
pub fn with_lambda(self, lambda: Option<crate::lambda::Options>) -> Self {
Self { lambda, ..self }
}
}
fn label(out: &mut String, markup: &str) {
let text = |out: &mut String, text: &str| {
out.push_str(r"\mathrm{");
for c in text.chars() {
escape(out, c).unwrap();
}
out.push('}');
};
for part in parts(markup) {
match part {
Part::Symbol(c) => out.push_str(match c {
'⊗' => NOTATION.tensor,
'⅋' => NOTATION.par,
'&' => NOTATION.with,
'⊕' => NOTATION.plus,
'⊸' => NOTATION.lollipop,
'\\' => r"\backslash",
'/' => "/",
'!' => r"\oc",
'?' => r"\wn",
'⊤' => NOTATION.top,
'⊥' => NOTATION.bot,
'1' => NOTATION.one,
'*' => "^{*}",
'∧' => NOTATION.ordinary.and,
'∨' => NOTATION.ordinary.or,
'→' => NOTATION.ordinary.implies,
'¬' => r"\lnot",
'↔' => NOTATION.ordinary.iff,
'∀' => r"\forall",
'∃' => r"\exists",
_ => NOTATION.zero,
}),
Part::Text(t) => text(out, t),
Part::Sub(t) if t.len() == 1 && t.chars().all(|c| c.is_ascii_digit()) => {
out.push('_');
out.push_str(t);
}
Part::Sub(t) => {
out.push_str("_{");
text(out, t);
out.push('}');
}
}
}
}
fn begin(out: &mut impl Write, options: &Options, tree: bool) -> std::fmt::Result {
match &options.preamble {
Some(preamble) => writeln!(out, "{}", preamble.trim_end())?,
None => {
out.write_str(PREAMBLE)?;
if tree {
out.write_str("\\usepackage{ebproof}\n")?;
}
}
}
out.write_str("\\begin{document}\n")
}
fn formed(math: String, options: &Options) -> String {
match options.form {
Form::Fragment => math,
Form::Standalone => {
let mut out = String::new();
begin(&mut out, options, false).expect("a string takes any text");
out.push_str(&math);
out.push_str("\n\\end{document}");
out
}
}
}
const PER_OCCURRENCE: u64 = 32;
pub fn sequent(
sequent: &Sequent,
mode: crate::linear::Mode,
options: &Options,
limits: &crate::Limits,
) -> Result<String, Error> {
super::math(sequent, mode, PER_OCCURRENCE, limits, &NOTATION).map(|out| formed(out, options))
}
pub fn write<'a>(
derivation: impl Into<Drawable<'a>>,
options: &Options,
out: &mut impl Write,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<(), Error> {
let mut stop = stop;
let drawable = derivation.into();
let judgement = super::judgement(
drawable,
options.lambda.as_ref(),
&crate::lambda::print::LATEX,
&mut stop,
)?;
let judgement = judgement.as_deref();
let stop = crate::limits::counting(stop, crate::limits::Phase::Write);
match drawable {
Drawable::Linear(derivation) => tree(derivation, options, judgement, out, stop),
Drawable::Ordinary(derivation) => tree(derivation, options, judgement, out, stop),
Drawable::Classical(view) => tree(view, options, judgement, out, stop),
}
}
pub fn to_string<'a>(
derivation: impl Into<Drawable<'a>>,
options: &Options,
) -> Result<String, Error> {
let mut out = String::new();
write(derivation, options, &mut out, |_| false)?;
Ok(out)
}
fn tree<T: Drawn>(
derivation: &T,
options: &Options,
judgement: Option<&str>,
out: &mut impl Write,
mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
let standalone = options.form == Form::Standalone;
if standalone {
begin(out, options, true)?;
}
out.write_str("\\begin{prooftree}")?;
if !options.ebproof.is_empty() {
write!(out, "[{}]", options.ebproof)?;
}
out.write_char('\n')?;
let mut buffer = String::new();
walk(derivation, |step| {
let Step::Exit(id, _) = step else {
return Ok(());
};
let markup = derivation.label(id, &options.labels);
let markup = markup.as_deref();
match (derivation.is_open(id), &options.open) {
(true, OpenGoal::Dots) => buffer.push_str("\\hypo{\\vdots}\n\\infer[no rule]1"),
(true, OpenGoal::Bare) => buffer.push_str("\\hypo"),
(true, OpenGoal::Dashed) => buffer.push_str("\\infer[dashed]0"),
(true, OpenGoal::Mark(mark)) => {
buffer.push_str("\\infer0[$");
label(&mut buffer, mark);
buffer.push_str("$]");
}
_ => {
buffer.push_str("\\infer");
buffer.push_str(&derivation.premises(id).len().to_string());
if let Some(markup) = markup {
buffer.push_str("[$");
label(&mut buffer, markup);
buffer.push_str("$]");
}
}
}
buffer.push('{');
derivation.sequent(&mut buffer, &NOTATION, id, options.align, false);
buffer.push_str("}\n");
flush(out, &mut buffer, &mut stop)
})?;
if let Some(judgement) = judgement {
writeln!(out, "\\infer[no rule]1{{{judgement}}}")?;
}
out.write_str("\\end{prooftree}")?;
if standalone {
out.write_str("\n\\end{document}")?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn escaped(name: &str) -> String {
let mut out = String::new();
atom(&mut out, name).unwrap();
out
}
#[test]
fn names_are_escaped() {
for (name, expected) in [
("A", "A"),
("p", "p"),
("foo", r"\mathit{foo}"),
("x_1", r"\mathit{x\_1}"),
("α", r"\alpha"),
("Γ", r"\Gamma"),
("Α", "A"),
("αβ", r"\mathit{{\alpha}{\beta}}"),
("Οx", r"\mathit{Ox}"),
("P‿a·b", r"\mathit{P{\smallsmile}a{\cdotp}b}"),
("é", r"\mathit{é}"),
(
r"a{b}$#%&^~\ c",
r"\mathit{a\{b\}\$\#\%\&\mbox{\textasciicircum}\mbox{\textasciitilde}\mbox{\textbackslash}\ c}",
),
] {
assert_eq!(escaped(name), expected, "{name:?}");
}
}
}