#![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;
pub const CURRYST: &str = "0.6.0";
const NOTATION: Notation = Notation {
tensor: "⊗",
par: "⅋",
with: r#"class("binary", \&)"#,
plus: "⊕",
lollipop: "⊸",
under: r#"class("binary", backslash)"#,
over: r#"class("binary", slash)"#,
bang: "!",
quest: r#"class("normal", ?)"#,
one: "bold(1)",
bot: "⊥",
top: "⊤",
zero: "0",
dual_prefix: "",
dual: "^⊥",
turnstile: "⊢",
align: "",
atom: Atoms::Typst,
forall: "forall ",
exists: "exists ",
dot: ". ",
ordinary: Symbols::UNICODE,
};
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())
&& c.is_alphabetic()
{
return out.write_char(c);
}
out.write_str("italic(\"")?;
for c in name.chars() {
if c == '"' || c == '\\' {
out.write_char('\\')?;
}
out.write_char(c)?;
}
out.write_str("\")")
}
pub const PAGE: &str = "#set page(width: auto, height: auto, margin: 5pt)";
pub const CURRYST_HEIGHT: usize = 9;
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Layout {
#[default]
Auto,
Curryst,
#[cfg_attr(feature = "serialize", serde(alias = "linlog"))]
Deduxit,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Length(Box<str>);
impl Length {
pub const UNITS: [&'static str; 5] = ["pt", "mm", "cm", "in", "em"];
pub fn new(text: &str) -> Result<Self, Error> {
let number = text.trim_end_matches(|c: char| c.is_ascii_alphabetic());
let (whole, fraction) = number.split_once('.').unwrap_or((number, "0"));
let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
if digits(whole) && digits(fraction) && Self::UNITS.contains(&&text[number.len()..]) {
Ok(Self(text.into()))
} else {
Err(Error::InvalidOption {
key: "typst",
message: format!(
"`{text}` is no Typst length: digits, a fraction or not, and one of {}",
Self::UNITS.join(", ")
),
})
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::str::FromStr for Length {
type Err = Error;
fn from_str(text: &str) -> Result<Self, Error> {
Self::new(text)
}
}
impl std::fmt::Display for Length {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[cfg(feature = "serialize")]
impl serde::Serialize for Length {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
#[cfg(feature = "serialize")]
impl<'a> serde::Deserialize<'a> for Length {
fn deserialize<D: serde::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
let text = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
Self::new(&text).map_err(serde::de::Error::custom)
}
}
#[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 import: String,
pub page: String,
pub layout: Layout,
pub premise_gap: Length,
pub label_gap: Length,
pub band: Length,
pub stroke: Length,
pub lambda: Option<crate::lambda::Options>,
}
impl Default for Options {
fn default() -> Self {
Self {
form: Form::Fragment,
labels: Labels::Upright,
open: OpenGoal::Dots,
import: format!("#import \"@preview/curryst:{CURRYST}\": prooftree, rule"),
page: PAGE.to_owned(),
layout: Layout::Auto,
premise_gap: Length("1.5em".into()),
label_gap: Length("0.2em".into()),
band: Length("0.8em".into()),
stroke: Length("0.05em".into()),
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_import(self, import: String) -> Self {
Self { import, ..self }
}
#[must_use]
pub fn with_page(self, page: String) -> Self {
Self { page, ..self }
}
#[must_use]
pub fn with_layout(self, layout: Layout) -> Self {
Self { layout, ..self }
}
#[must_use]
pub fn with_premise_gap(self, premise_gap: Length) -> Self {
Self {
premise_gap,
..self
}
}
#[must_use]
pub fn with_label_gap(self, label_gap: Length) -> Self {
Self { label_gap, ..self }
}
#[must_use]
pub fn with_band(self, band: Length) -> Self {
Self { band, ..self }
}
#[must_use]
pub fn with_stroke(self, stroke: Length) -> Self {
Self { stroke, ..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| {
let mut chars = text.chars();
if let (Some(c), None) = (chars.next(), chars.next())
&& c.is_alphabetic()
{
out.push_str("upright(");
out.push(c);
out.push(')');
return;
}
out.push('"');
for c in text.chars() {
if c == '"' || c == '\\' {
out.push('\\');
}
out.push(c);
}
out.push('"');
};
let start = out.len();
for part in parts(markup) {
match part {
Part::Symbol(c) => out.push_str(match c {
'&' => r"\&",
'?' => NOTATION.quest,
'1' => NOTATION.one,
'⊗' => "⊗",
'⅋' => "⅋",
'⊕' => "⊕",
'⊸' => "⊸",
'\\' => "backslash",
'/' => "slash",
'!' => "!",
'⊤' => "⊤",
'⊥' => "⊥",
'*' => "^*",
'∧' => "∧",
'∨' => "∨",
'→' => "→",
'¬' => "¬",
'↔' => "↔",
'∀' => "forall",
'∃' => "exists",
_ => "0",
}),
Part::Text(t) => {
if out.len() > start {
out.push(' ');
}
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 formed(math: String, options: &Options) -> String {
match options.form {
Form::Fragment => math,
Form::Standalone => format!("{}\n\n{math}", options.page.trim_end()),
}
}
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::TYPST,
&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,
stop: impl FnMut() -> bool,
) -> Result<(), Error> {
let own = match options.layout {
Layout::Curryst => false,
Layout::Deduxit => true,
Layout::Auto => height(derivation) > CURRYST_HEIGHT,
};
if own {
laid_out(derivation, options, judgement, out, stop)
} else {
curryst(derivation, options, judgement, out, stop)
}
}
fn height<T: Drawn>(derivation: &T) -> usize {
let mut heights = vec![0; derivation.len()];
for i in 0..heights.len() {
let premises = derivation.premises(crate::linear::InfId::new(i as u32));
let above = premises.iter().map(|p| heights[p.index()]);
heights[i] = 1 + above.max().unwrap_or(0);
}
heights.last().copied().unwrap_or(0)
}
const LAYOUT: &str = r#" let n = nodes.len()
let tall = (3em).to-absolute()
let metrics(c) = {
let size = measure(box(c))
let low = measure(box[#box(height: tall, width: 0pt)#c]).height - tall
(size.width, size.height - low, low)
}
let (dots-width, dots-up, dots-down) = metrics(dots)
let (width, up, down, wide, left, offset) = ((0pt,) * n,) * 6
let bar = (none,) * n
let names = (none,) * n
let stack = ()
for i in range(n - 1, -1, step: -1) {
let (k, name, c) = nodes.at(i)
let (w, a, d) = metrics(c)
width.at(i) = w
up.at(i) = a
down.at(i) = d
if k == none {
let reach = if open == "dots" { dots-width } else { 0pt }
wide.at(i) = calc.max(w, reach)
left.at(i) = calc.max(reach - w, 0pt) / 2
if open == "dashed" { bar.at(i) = (left.at(i), left.at(i) + w) }
stack.push(i)
continue
}
let kids = ()
for _ in range(k) { kids.push(stack.pop()) }
let x = 0pt
let span = none
for p in kids {
offset.at(p) = x
let s = x + left.at(p)
span = (if span == none { s } else { span.at(0 ) }, s + width.at(p))
x += wide.at(p) + gap
}
let (l, b) = if span == none { (0pt, (0pt, w)) } else {
let l = (span.at(0) + span.at(1) - w) / 2
(l, (calc.min(span.at(0), l), calc.max(span.at(1), l + w)))
}
let shift = calc.max(-l, 0pt)
for p in kids { offset.at(p) += shift }
let named = 0pt
if name != none {
let size = measure(box(name))
names.at(i) = (size.width, size.height)
named = name-gap + size.width
}
let row = if k == 0 { 0pt } else { x - gap }
wide.at(i) = calc.max(row, b.at(1) + named) + shift
left.at(i) = l + shift
bar.at(i) = (b.at(0) + shift, b.at(1) + shift)
stack.push(i)
}
let (x, depth) = ((0pt,) * n, (0,) * n)
let parents = ()
for i in range(n) {
if parents.len() > 0 {
let (p, r) = parents.last()
x.at(i) = x.at(p) + offset.at(i)
depth.at(i) = depth.at(p) + 1
if r == 1 { let _ = parents.pop() } else { parents.at(-1) = (p, r - 1) }
}
let k = nodes.at(i).at(0)
if k != none and k > 0 { parents.push((i, k)) }
}
let rows = calc.max(..depth) + 2
let (row-up, row-down, between) = ((0pt,) * rows,) * 3
for i in range(n) {
let j = depth.at(i)
row-up.at(j) = calc.max(row-up.at(j), up.at(i))
row-down.at(j) = calc.max(row-down.at(j), down.at(i))
if bar.at(i) != none {
let tall = if names.at(i) == none { 0pt } else { names.at(i).at(1) }
between.at(j) = calc.max(between.at(j), band, tall)
}
if nodes.at(i).at(0) == none and open == "dots" {
between.at(j) = calc.max(between.at(j), band / 2)
row-up.at(j + 1) = calc.max(row-up.at(j + 1), dots-up)
row-down.at(j + 1) = calc.max(row-down.at(j + 1), dots-down)
}
}
let base = (0pt,) * rows
base.at(rows - 1) = row-up.at(rows - 1)
for j in range(rows - 2, -1, step: -1) {
base.at(j) = base.at(j + 1) + row-down.at(j + 1) + between.at(j) + row-up.at(j)
}
box(width: wide.at(0), height: base.at(0) + row-down.at(0), baseline: row-down.at(0), {
for i in range(n) {
let (k, name, c) = nodes.at(i)
let (j, at) = (depth.at(i), x.at(i))
place(dx: at + left.at(i), dy: base.at(j) - up.at(i), box(c))
if k == none and open == "dots" {
let dx = at + (wide.at(i) - dots-width) / 2
place(dx: dx, dy: base.at(j + 1) - dots-up, box(dots))
}
if bar.at(i) != none {
let (start, end) = bar.at(i)
let y = base.at(j) - row-up.at(j) - between.at(j) / 2
let dash = if k == none { "dashed" } else { none }
place(dx: at + start, dy: y, line(length: end - start, stroke: (thickness: stroke, dash: dash)))
if names.at(i) != none {
let (w, h) = names.at(i)
place(dx: at + end + name-gap, dy: y - h / 2, box(name))
}
}
}
})
}
"#;
fn laid_out<T: Drawn>(
derivation: &T,
options: &Options,
judgement: Option<&str>,
out: &mut impl Write,
mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
if options.form == Form::Standalone {
write!(out, "{}\n\n", options.page.trim_end())?;
}
if judgement.is_some() {
out.write_str(STACK)?;
} else {
out.write_char('#')?;
}
let open = match options.open {
OpenGoal::Dots => "dots",
OpenGoal::Dashed => "dashed",
OpenGoal::Bare | OpenGoal::Mark(_) => "bare",
};
write!(
out,
"context {{\n let open = \"{open}\"\n let gap = ({}).to-absolute()\n \
let name-gap = ({}).to-absolute()\n let band = ({}).to-absolute()\n \
let stroke = {}\n let dots = $dots.v$\n let nodes = (\n",
options.premise_gap, options.label_gap, options.band, options.stroke
)?;
let mut buffer = String::new();
walk(derivation, |step| {
let Step::Enter(id, _) = step else {
return Ok(());
};
let markup = derivation.label(id, &options.labels);
let (premises, name) = match (derivation.is_open(id), &options.open) {
(true, OpenGoal::Mark(mark)) => ("0".to_owned(), Some(mark.as_str())),
(true, _) => ("none".to_owned(), None),
_ => (derivation.premises(id).len().to_string(), markup.as_deref()),
};
write!(buffer, " ({premises}, ")?;
match name {
Some(name) => {
buffer.push('$');
label(&mut buffer, name);
buffer.push('$');
}
None => buffer.push_str("none"),
}
buffer.push_str(", $");
derivation.sequent(&mut buffer, &NOTATION, id, false, false);
buffer.push_str("$),\n");
flush(out, &mut buffer, &mut stop)
})?;
out.write_str(" )\n")?;
out.write_str(LAYOUT.trim_end())?;
under(out, judgement)
}
const STACK: &str = "#stack(spacing: 0.8em, align(center, ";
fn under(out: &mut impl Write, judgement: Option<&str>) -> Result<(), Error> {
if let Some(judgement) = judgement {
write!(out, "), align(center, ${judgement}$))")?;
}
Ok(())
}
fn curryst<T: Drawn>(
derivation: &T,
options: &Options,
judgement: Option<&str>,
out: &mut impl Write,
mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
if options.form == Form::Standalone {
write!(
out,
"{}\n{}\n\n",
options.import.trim_end(),
options.page.trim_end()
)?;
}
out.write_str(if judgement.is_some() { STACK } else { "#" })?;
out.write_str("prooftree(\n")?;
let indent = |out: &mut String, depth: usize| {
for _ in 0..depth {
out.push_str(" ");
}
};
let conclusion = |out: &mut String, id| {
out.push('$');
derivation.sequent(out, &NOTATION, id, false, false);
out.push('$');
};
let mut buffer = String::new();
walk(derivation, |step| {
match step {
Step::Enter(id, depth) => {
let premises = derivation.premises(id);
indent(&mut buffer, depth + 1);
let open = |out: &mut String, grid: &str| {
out.push_str(grid);
conclusion(out, id);
out.push_str("),\n");
};
match (derivation.is_open(id), &options.open) {
(true, OpenGoal::Dots) => open(
&mut buffer,
"grid(align: center, row-gutter: 0.4em, $dots.v$, ",
),
(true, OpenGoal::Dashed) => open(
&mut buffer,
"grid(align: center, inset: (top: 0.3em), \
grid.hline(stroke: (dash: \"dashed\")), ",
),
(true, OpenGoal::Bare) => {
conclusion(&mut buffer, id);
buffer.push_str(",\n");
}
(true, OpenGoal::Mark(mark)) => {
buffer.push_str("rule(name: $");
label(&mut buffer, mark);
buffer.push_str("$, ");
conclusion(&mut buffer, id);
buffer.push_str("),\n");
}
_ => {
let markup = derivation.label(id, &options.labels);
let markup = markup.as_deref();
let name = |out: &mut String| {
if let Some(markup) = markup {
out.push_str("name: $");
label(out, markup);
out.push('$');
}
};
buffer.push_str("rule(");
if premises.is_empty() {
name(&mut buffer);
if markup.is_some() {
buffer.push_str(", ");
}
conclusion(&mut buffer, id);
buffer.push_str("),\n");
} else if markup.is_some() {
buffer.push('\n');
indent(&mut buffer, depth + 2);
name(&mut buffer);
buffer.push_str(",\n");
} else {
buffer.push('\n');
}
}
}
}
Step::Exit(id, depth) => {
if !derivation.premises(id).is_empty() {
indent(&mut buffer, depth + 2);
conclusion(&mut buffer, id);
buffer.push_str(",\n");
indent(&mut buffer, depth + 1);
buffer.push_str("),\n");
}
}
}
flush(out, &mut buffer, &mut stop)
})?;
out.write_char(')')?;
under(out, judgement)
}
#[cfg(test)]
mod tests {
use super::*;
fn escaped(name: &str) -> String {
let mut out = String::new();
atom(&mut out, name).unwrap();
out
}
#[test]
fn lengths_are_numbers_and_units() {
for text in ["1.5em", "0pt", "12mm", "2.25in", "3cm"] {
assert_eq!(Length::new(text).unwrap().as_str(), text);
}
for text in [
"", "em", "1", "1.em", ".5em", "1.5 em", "-1em", "1em)", "1fr", "1em+2pt",
] {
assert!(
matches!(
Length::new(text),
Err(Error::InvalidOption { key: "typst", .. })
),
"{text:?}"
);
}
}
#[test]
fn names_are_escaped() {
for (name, expected) in [
("A", "A"),
("α", "α"),
("foo", r#"italic("foo")"#),
("x_1", r#"italic("x_1")"#),
(r#"a"b\c"#, r#"italic("a\"b\\c")"#),
] {
assert_eq!(escaped(name), expected, "{name:?}");
}
}
}