#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
mod font;
mod mell;
mod net;
mod tree;
use super::Drawable;
use crate::Error;
use crate::linear::nets::{MellStructure, ProofStructure};
use crate::linear::occurrences::Reading;
use crate::linear::proofs::style::{Part, parts};
use crate::linear::proofs::{Labels, OpenGoal};
use crate::linear::sequents::Sequent;
use crate::linear::sequents::notation::{Atoms, Notation};
use crate::ordinary::Symbols;
pub use font::{Advances, Font, MONOSPACE, MathFont};
use font::{DEPTH, HEIGHT, LOWER, RAISE, SCRIPT};
use std::fmt::Write;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Style {
pub font: Font,
pub labels: Labels,
pub open: OpenGoal,
pub ids: bool,
pub description: bool,
pub font_size: u32,
pub label_size: u32,
pub line_height: u32,
pub premise_gap: u32,
pub literal_gap: u32,
pub label_gap: u32,
pub margin: u32,
pub stroke_width: u32,
pub link_height: u32,
pub link_cap: Option<u32>,
pub node_radius: u32,
pub text: String,
pub line: String,
pub par: String,
pub link: String,
pub highlight: String,
pub background: Option<String>,
pub essential: bool,
pub net: NetDrawing,
pub net_look: NetLook,
pub input: String,
pub dominator: String,
pub lambda: Option<crate::lambda::Options>,
}
impl Default for Style {
fn default() -> Self {
Self {
font: Font::euler(),
labels: Labels::Upright,
open: OpenGoal::Dots,
ids: false,
description: true,
font_size: 16,
label_size: 800,
line_height: 1500,
premise_gap: 1500,
literal_gap: 1000,
label_gap: 200,
margin: 300,
stroke_width: 40,
link_height: 600,
link_cap: Some(8000),
node_radius: 380,
text: "black".into(),
line: "black".into(),
par: "#0072b2".into(),
link: "black".into(),
highlight: "#d55e00".into(),
background: None,
essential: false,
input: "#0072b2".into(),
dominator: "#cc79a7".into(),
net: NetDrawing::Formulas,
net_look: NetLook::DEDUXIT,
lambda: None,
}
}
}
#[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 NetDrawing {
#[default]
Formulas,
Compact,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
pub struct NetLook {
pub premises: Premises,
pub conclusions: Conclusions,
pub why_not: WhyNot,
}
impl NetLook {
pub const DEDUXIT: Self = Self {
premises: Premises::Dashed,
conclusions: Conclusions::Raised,
why_not: WhyNot::Node,
};
pub const TEXTBOOK: Self = Self {
premises: Premises::Plain,
conclusions: Conclusions::Bottom,
why_not: WhyNot::Rules,
};
#[must_use]
pub const fn with_premises(self, premises: Premises) -> Self {
Self { premises, ..self }
}
#[must_use]
pub const fn with_conclusions(self, conclusions: Conclusions) -> Self {
Self {
conclusions,
..self
}
}
#[must_use]
pub const fn with_why_not(self, why_not: WhyNot) -> Self {
Self { why_not, ..self }
}
}
#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for NetLook {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
struct Fields {
premises: Premises,
conclusions: Conclusions,
why_not: WhyNot,
}
impl Default for Fields {
fn default() -> Self {
let NetLook {
premises,
conclusions,
why_not,
} = NetLook::default();
Self {
premises,
conclusions,
why_not,
}
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = NetLook;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a net's premises, conclusions and why_not, or the name of a preset")
}
fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<NetLook, E> {
use serde::Deserialize;
use serde::de::IntoDeserializer;
NetPreset::deserialize(name.into_deserializer()).map(NetPreset::look)
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<NetLook, A::Error> {
use serde::Deserialize;
let Fields {
premises,
conclusions,
why_not,
} = Fields::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
Ok(NetLook {
premises,
conclusions,
why_not,
})
}
}
deserializer.deserialize_any(Visitor)
}
}
#[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 NetPreset {
#[default]
#[cfg_attr(feature = "serialize", serde(alias = "linlog"))]
Deduxit,
Textbook,
}
impl NetPreset {
#[must_use]
pub const fn look(self) -> NetLook {
match self {
Self::Deduxit => NetLook::DEDUXIT,
Self::Textbook => NetLook::TEXTBOOK,
}
}
}
#[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 Premises {
#[default]
Dashed,
Plain,
}
#[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 Conclusions {
#[default]
Raised,
Bottom,
}
#[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 WhyNot {
#[default]
Node,
Rules,
}
impl Style {
#[must_use]
pub fn with_font(self, font: Font) -> Self {
Self { font, ..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_ids(self, ids: bool) -> Self {
Self { ids, ..self }
}
#[must_use]
pub fn with_description(self, description: bool) -> Self {
Self {
description,
..self
}
}
#[must_use]
pub fn with_font_size(self, font_size: u32) -> Self {
Self { font_size, ..self }
}
#[must_use]
pub fn with_label_size(self, label_size: u32) -> Self {
Self { label_size, ..self }
}
#[must_use]
pub fn with_line_height(self, line_height: u32) -> Self {
Self {
line_height,
..self
}
}
#[must_use]
pub fn with_premise_gap(self, premise_gap: u32) -> Self {
Self {
premise_gap,
..self
}
}
#[must_use]
pub fn with_literal_gap(self, literal_gap: u32) -> Self {
Self {
literal_gap,
..self
}
}
#[must_use]
pub fn with_label_gap(self, label_gap: u32) -> Self {
Self { label_gap, ..self }
}
#[must_use]
pub fn with_margin(self, margin: u32) -> Self {
Self { margin, ..self }
}
#[must_use]
pub fn with_stroke_width(self, stroke_width: u32) -> Self {
Self {
stroke_width,
..self
}
}
#[must_use]
pub fn with_link_height(self, link_height: u32) -> Self {
Self {
link_height,
..self
}
}
#[must_use]
pub fn with_link_cap(self, link_cap: Option<u32>) -> Self {
Self { link_cap, ..self }
}
#[must_use]
pub fn with_node_radius(self, node_radius: u32) -> Self {
Self {
node_radius,
..self
}
}
#[must_use]
pub fn with_text(self, text: String) -> Self {
Self { text, ..self }
}
#[must_use]
pub fn with_line(self, line: String) -> Self {
Self { line, ..self }
}
#[must_use]
pub fn with_par(self, par: String) -> Self {
Self { par, ..self }
}
#[must_use]
pub fn with_link(self, link: String) -> Self {
Self { link, ..self }
}
#[must_use]
pub fn with_highlight(self, highlight: String) -> Self {
Self { highlight, ..self }
}
#[must_use]
pub fn with_background(self, background: Option<String>) -> Self {
Self { background, ..self }
}
#[must_use]
pub fn with_essential(self, essential: bool) -> Self {
Self { essential, ..self }
}
#[must_use]
pub fn with_input(self, input: String) -> Self {
Self { input, ..self }
}
#[must_use]
pub fn with_dominator(self, dominator: String) -> Self {
Self { dominator, ..self }
}
#[must_use]
pub fn with_net(self, net: NetDrawing) -> Self {
Self { net, ..self }
}
#[must_use]
pub fn with_net_look(self, net_look: NetLook) -> Self {
Self { net_look, ..self }
}
}
impl Style {
pub fn dark() -> Self {
Self {
text: "#e6e6e6".into(),
line: "#e6e6e6".into(),
par: "#56b4e9".into(),
link: "#e6e6e6".into(),
highlight: "#e69f00".into(),
background: Some("#1e1e1e".into()),
input: "#56b4e9".into(),
dominator: "#cc79a7".into(),
..Self::default()
}
}
pub fn monospace() -> Self {
Self {
font: Font::monospace(),
..Self::default()
}
}
pub const MOST_LENGTH: u32 = 1_000_000;
pub const MOST_SIZE: u32 = 10_000;
pub const MOST_FONT_SIZE: u32 = 10_000;
pub fn check(&self) -> Result<(), Error> {
let advances: u32 = match &self.font.advances {
Advances::Euler
| Advances::StixTwo
| Advances::Garamond
| Advances::Asana
| Advances::NewComputerModern => 0,
Advances::Fixed(advance) => *advance,
Advances::Table { table, fallback } => {
table.values().copied().fold(*fallback, u32::max)
}
};
let numbers = [
("svg.font_size", self.font_size, Self::MOST_FONT_SIZE),
("svg.label_size", self.label_size, Self::MOST_SIZE),
("svg.font.advances", advances, Self::MOST_SIZE),
("svg.line_height", self.line_height, Self::MOST_LENGTH),
("svg.premise_gap", self.premise_gap, Self::MOST_LENGTH),
("svg.literal_gap", self.literal_gap, Self::MOST_LENGTH),
("svg.label_gap", self.label_gap, Self::MOST_LENGTH),
("svg.margin", self.margin, Self::MOST_LENGTH),
("svg.stroke_width", self.stroke_width, Self::MOST_LENGTH),
("svg.link_height", self.link_height, Self::MOST_LENGTH),
(
"svg.link_cap",
self.link_cap.unwrap_or(0),
Self::MOST_LENGTH,
),
("svg.node_radius", self.node_radius, Self::MOST_LENGTH),
];
match numbers.into_iter().find(|&(_, value, most)| value > most) {
Some((key, value, most)) => Err(Error::InvalidOption {
key,
message: format!("{value} is more than the most it may be, {most}"),
}),
None => Ok(()),
}
}
}
const FORMULA: (char, char) = ('\u{2}', '\u{3}');
const SUBSCRIPT: (char, char) = ('\u{4}', '\u{5}');
fn label(markup: &str) -> String {
let mut out = String::new();
for part in parts(markup) {
match part {
Part::Symbol(c) => out.push(c),
Part::Text(text) => out.push_str(text),
Part::Sub(text) => {
out.push(SUBSCRIPT.0);
out.push_str(text);
out.push(SUBSCRIPT.1);
}
}
}
out
}
const RAISED_BOT: char = '\u{1}';
const NOTATION: Notation = Notation {
tensor: "⊗",
par: "⅋",
with: "&",
plus: "⊕",
lollipop: "⊸",
under: "\\",
over: "/",
bang: "!",
quest: "?",
one: "1",
bot: "⊥",
top: "⊤",
zero: "0",
dual_prefix: "",
dual: "\u{1}",
turnstile: "⊢",
align: "",
atom: Atoms::Italic,
forall: "∀",
exists: "∃",
dot: ". ",
ordinary: Symbols::UNICODE,
};
const PLAIN: Notation = Notation {
dual: "⊥",
atom: Atoms::Plain,
..NOTATION
};
pub(crate) fn italic<W: Write + ?Sized>(out: &mut W, name: &str) -> std::fmt::Result {
for c in name.chars() {
out.write_char(match c {
'h' => 'ℎ',
'A'..='Z' => char::from_u32(0x1D434 + (c as u32 - 'A' as u32)).unwrap(),
'a'..='z' => char::from_u32(0x1D44E + (c as u32 - 'a' as u32)).unwrap(),
c => c,
})?;
}
Ok(())
}
fn escape(out: &mut String, c: char) {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\t' | '\n' | '\r' => out.push(c),
'\0'..='\u{1F}' | '\u{FFFE}' | '\u{FFFF}' => out.push('\u{FFFD}'),
c => out.push(c),
}
}
fn escaped(text: &str) -> String {
let mut out = String::with_capacity(text.len());
text.chars().for_each(|c| escape(&mut out, c));
out
}
#[derive(Clone, Debug, Default)]
struct Piece {
text: String,
offset: i64,
raise: i64,
size: Option<i64>,
width: i64,
formula: Option<usize>,
}
#[derive(Clone, Debug, Default)]
struct Run {
pieces: Vec<Piece>,
width: i64,
}
fn run(text: &str, size: i64, font: &Font) -> Run {
let mut pieces = Vec::new();
let width = lay(text, size, font, |piece| pieces.push(piece));
Run { pieces, width }
}
fn lay(text: &str, size: i64, font: &Font, mut emit: impl FnMut(Piece)) -> i64 {
let scale = |millionths: i64| match millionths.checked_mul(size) {
Some(product) => product / 1_000_000,
None => {
let scaled = i128::from(millionths) * i128::from(size) / 1_000_000;
i64::try_from(scaled).unwrap_or(i64::MAX)
}
};
let (mut position, mut start, mut end) = (0, 0, 0);
let mut current = (0, 1000);
let (mut lowered, mut formula, mut formulas) = (false, None, 0);
let mut piece = String::new();
let mut close = |piece: &mut String, shape: (i64, i64), formula, start, end| {
piece.truncate(piece.trim_end_matches(' ').len());
if !piece.is_empty() {
emit(Piece {
text: std::mem::take(piece),
offset: scale(start),
raise: shape.0,
size: (shape.1 != 1000).then_some(size * shape.1 / 1000),
width: scale(end) - scale(start),
formula,
});
}
};
for c in text.chars() {
if c == FORMULA.0 || c == FORMULA.1 {
close(&mut piece, current, formula, start, end);
formula = (c == FORMULA.0).then_some(formulas);
formulas += usize::from(c == FORMULA.0);
continue;
}
if c == SUBSCRIPT.0 || c == SUBSCRIPT.1 {
lowered = c == SUBSCRIPT.0;
continue;
}
let (c, shape) = match c {
RAISED_BOT => ('⊥', (RAISE * size / 1000, SCRIPT)),
c if lowered => (c, (-LOWER * size / 1000, SCRIPT)),
c => (c, (0, 1000)),
};
if shape != current {
close(&mut piece, current, formula, start, end);
current = shape;
}
let advance = i64::from(font.advances.advance(c)) * shape.1;
if c == ' ' {
if !piece.is_empty() {
piece.push(' ');
}
position += advance;
continue;
}
if piece.is_empty() {
start = position;
}
position += advance;
end = position;
escape(&mut piece, c);
}
close(&mut piece, current, formula, start, end);
scale(position)
}
fn text(
out: &mut String,
x: i64,
y: i64,
run: &Run,
attributes: &str,
ids: Option<(u32, &[usize])>,
) {
let group = run.pieces.len() > 1 || ids.is_some();
if group {
writeln!(out, "<g{attributes}>").unwrap();
}
let mut open = None;
for piece in &run.pieces {
if let Some((id, positions)) = ids
&& piece.formula != open
{
if open.is_some() {
out.push_str("</g>\n");
}
if let Some(k) = piece.formula {
writeln!(out, r#"<g id="i{id}-{}">"#, positions[k]).unwrap();
}
open = piece.formula;
}
write_piece(out, x, y, piece, if group { "" } else { attributes });
}
if open.is_some() {
out.push_str("</g>\n");
}
if group {
out.push_str("</g>\n");
}
}
fn write_piece(out: &mut String, x: i64, y: i64, piece: &Piece, attributes: &str) {
write!(
out,
r#"<text x="{}" y="{}" textLength="{}" lengthAdjust="spacing""#,
x + piece.offset,
y - piece.raise,
piece.width
)
.unwrap();
if let Some(size) = piece.size {
write!(out, r#" font-size="{size}""#).unwrap();
}
out.push_str(attributes);
writeln!(out, ">{}</text>", piece.text).unwrap();
}
fn decimal(thousandths: i128) -> String {
let sign = if thousandths < 0 { "-" } else { "" };
let magnitude = thousandths.unsigned_abs();
let text = format!("{sign}{}.{:03}", magnitude / 1000, magnitude % 1000);
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
fn head(out: &mut impl Write, style: &Style, title: &str, size: (i64, i64)) -> std::fmt::Result {
let (width, height) = size;
let px = |length: i64| decimal(i128::from(length) * i128::from(style.font_size));
write!(
out,
r#"<svg xmlns="http://www.w3.org/2000/svg" role="img" width="{}" height="{}" viewBox="0 0 {width} {height}" font-family="{}" font-size="1000" fill="{}">"#,
px(width),
px(height),
escaped(&style.font.family),
escaped(&style.text),
)?;
write!(out, "\n<title>{}</title>\n", escaped(title))
}
struct Escaping<'a, W>(&'a mut W);
impl<W: Write> Write for Escaping<'_, W> {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
let mut text = String::with_capacity(s.len());
s.chars().for_each(|c| escape(&mut text, c));
self.0.write_str(&text)
}
}
fn backdrop(out: &mut impl Write, style: &Style, size: (i64, i64)) -> std::fmt::Result {
let (width, height) = size;
if let Some(background) = &style.background {
writeln!(
out,
r#"<rect width="{width}" height="{height}" fill="{}"/>"#,
escaped(background)
)?;
}
Ok(())
}
fn document(
style: &Style,
title: &str,
description: Option<&str>,
size: (i64, i64),
body: impl FnOnce(&mut String),
) -> String {
let mut out = String::new();
head(&mut out, style, title, size).unwrap();
if let Some(description) = description {
writeln!(out, "<desc>{}</desc>", escaped(description)).unwrap();
}
backdrop(&mut out, style, size).unwrap();
body(&mut out);
out.push_str("</svg>");
out
}
fn line(style: &Style, title: &str, content: &str) -> String {
let margin = i64::from(style.margin);
let mut pieces = 0usize;
let width = lay(content, 1000, &style.font, |_| pieces += 1);
let size = (width + 2 * margin, HEIGHT + DEPTH + 2 * margin);
document(style, title, None, size, |out| {
let group = pieces > 1;
if group {
out.push_str("<g>\n");
}
lay(content, 1000, &style.font, |piece| {
write_piece(out, margin, margin + HEIGHT, &piece, "");
});
if group {
out.push_str("</g>\n");
}
})
}
const PER_OCCURRENCE: u64 = 128;
pub fn sequent(
sequent: &Sequent,
mode: crate::linear::Mode,
style: &Style,
limits: &crate::Limits,
) -> Result<String, Error> {
style.check()?;
Ok(
match super::printed(sequent, mode, PER_OCCURRENCE, limits)? {
None => one_sided(sequent, style),
Some(forest) => {
let reading = Reading::of_mode(&forest, mode).map_err(Error::NotIntuitionistic)?;
two_sided(&reading, style)
}
},
)
}
fn one_sided(sequent: &Sequent, style: &Style) -> String {
let (mut drawn, mut title) = (String::new(), String::new());
NOTATION.one_sided(&mut drawn, sequent).unwrap();
PLAIN.one_sided(&mut title, sequent).unwrap();
line(style, &title, &drawn)
}
fn two_sided(reading: &Reading, style: &Style) -> String {
let forest = reading.forest();
let (mut drawn, mut title) = (String::new(), String::new());
NOTATION
.sequent(
&mut drawn,
forest,
Some(reading),
None,
&forest.root_members(),
false,
false,
)
.unwrap();
PLAIN
.sequent(
&mut title,
forest,
Some(reading),
None,
&forest.root_members(),
false,
false,
)
.unwrap();
line(style, &title, &drawn)
}
pub fn write<'a>(
derivation: impl Into<Drawable<'a>>,
style: &Style,
out: &mut impl Write,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<(), Error> {
style.check()?;
let mut stop = stop;
let drawable = derivation.into();
let judgement = super::judgement(
drawable,
style.lambda.as_ref(),
&crate::lambda::print::SVG,
&mut stop,
)?;
let judgement = judgement.as_deref();
let stop = crate::limits::counting(stop, crate::limits::Phase::Write);
match drawable {
Drawable::Linear(derivation) => tree::draw(derivation, style, judgement, out, stop),
Drawable::Ordinary(derivation) => tree::draw(derivation, style, judgement, out, stop),
Drawable::Classical(view) => tree::draw(view, style, judgement, out, stop),
}
}
pub fn net(
net: &ProofStructure,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
net_marked(net, &Marks::default(), style, limits, stop)
}
pub fn net_step(
net: &ProofStructure,
step: &crate::linear::nets::cut::Step,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
net_marked(net, &Marks::of_mll(net, step), style, limits, stop)
}
fn net_marked(
net: &ProofStructure,
marks: &Marks,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
style.check()?;
let reading = net.reading().ok().filter(|_| style.essential);
if let Some(limit) = limits.derivation_bytes {
let estimate = net::estimate(net, style, reading.is_some(), limit);
if estimate > limit {
return Err(Error::Refused(crate::limits::Refusal::Output {
what: "drawing",
estimate_bytes: estimate,
limit_bytes: limit,
least_bytes: None,
}));
}
}
let mut stop = stop;
let verdict = match &reading {
Some(_) => net.is_essential(&mut stop),
None => net.is_correct(&mut stop),
};
if let Err(refused @ crate::linear::nets::NetError::Refused { .. }) = verdict {
return Err(refused.into());
}
Ok(net::draw(net, style, &verdict, reading.as_ref(), marks))
}
pub fn mell_net(
net: &MellStructure,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
mell_net_marked(net, &Marks::default(), style, limits, stop)
}
pub fn mell_net_step(
net: &MellStructure,
step: &crate::linear::nets::cut::Step,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
mell_net_marked(net, &Marks::of_mell(net, step), style, limits, stop)
}
fn mell_net_marked(
net: &MellStructure,
marks: &Marks,
style: &Style,
limits: &crate::Limits,
stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
style.check()?;
let reading = net.reading().ok().filter(|_| style.essential);
if let Some(limit) = limits.derivation_bytes {
let estimate = mell::estimate(net, style, reading.is_some(), limit);
if estimate > limit {
return Err(Error::Refused(crate::limits::Refusal::Output {
what: "drawing",
estimate_bytes: estimate,
limit_bytes: limit,
least_bytes: None,
}));
}
}
let verdict = net.is_correct(stop);
if let Err(refused @ crate::linear::nets::NetError::Refused { .. }) = verdict {
return Err(refused.into());
}
Ok(mell::draw(net, style, &verdict, reading.as_ref(), marks))
}
#[derive(Default)]
struct Marks {
cut: Option<(u32, u32)>,
pairs: Vec<(u32, u32)>,
boxes: Vec<u32>,
}
impl Marks {
fn of_mll(net: &ProofStructure, step: &crate::linear::nets::cut::Step) -> Self {
let (x, y) = step.cut;
let forest = net.forest();
let mut pairs = Vec::new();
for v in [x, y] {
match step.case {
crate::linear::proofs::cut::Case::TensorPar => {
pairs.extend(forest.children(v.occ()).map(|c| (v.get(), c.get())));
}
crate::linear::proofs::cut::Case::Axiom
| crate::linear::proofs::cut::Case::OneBot
| crate::linear::proofs::cut::Case::WithPlus
| crate::linear::proofs::cut::Case::Weakening
| crate::linear::proofs::cut::Case::Dereliction
| crate::linear::proofs::cut::Case::Contraction
| crate::linear::proofs::cut::Case::BoxIntoBox
| crate::linear::proofs::cut::Case::ForallExists
| crate::linear::proofs::cut::Case::Commutative => {
pairs.extend(net.partner(v).map(|p| (v.get(), p.get())));
}
}
}
Self::new(step, pairs, Vec::new())
}
fn of_mell(net: &MellStructure, step: &crate::linear::nets::cut::Step) -> Self {
use crate::linear::proofs::cut::Case;
let (x, y) = step.cut;
let (mut pairs, mut boxes) = (Vec::new(), Vec::new());
let bang = |v: crate::linear::nets::VertexId| {
net.occurrence(v)
.is_some_and(|o| net.forest().kind(o) == crate::linear::Kind::Bang)
};
let (b, q) = if bang(x) { (x, y) } else { (y, x) };
match step.case {
Case::Axiom => {
for v in [x, y] {
pairs.extend(net.partner(v).map(|p| (v.get(), p.get())));
}
}
Case::TensorPar => {
for v in [x, y] {
pairs.extend(net.premises(v).map(|c| (v.get(), c.get())));
}
}
Case::BoxIntoBox => {
boxes.push(b.get());
boxes.extend(step.above.map(crate::linear::nets::VertexId::get));
}
Case::Weakening
| Case::Dereliction
| Case::Contraction
| Case::OneBot
| Case::WithPlus
| Case::ForallExists
| Case::Commutative => {
boxes.push(b.get());
pairs.extend(step.above.map(|c| (q.get(), c.get())));
}
}
Self::new(step, pairs, boxes)
}
fn new(step: &crate::linear::nets::cut::Step, pairs: Vec<(u32, u32)>, boxes: Vec<u32>) -> Self {
let mut pairs: Vec<(u32, u32)> = pairs
.into_iter()
.map(|(a, b)| (a.min(b), a.max(b)))
.collect();
pairs.sort_unstable();
Self {
cut: Some((step.cut.0.get(), step.cut.1.get())),
pairs,
boxes,
}
}
fn has(&self, a: u32, b: u32) -> bool {
self.pairs.binary_search(&(a.min(b), a.max(b))).is_ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scripts_are_pieces() {
let pieces = |r: &Run| {
r.pieces
.iter()
.map(|p| (p.text.clone(), p.offset, p.raise, p.size, p.width))
.collect::<Vec<_>>()
};
let (a, bot, comma, space) = (770, 611, 277, 333);
let r = run("A\u{1} ⊗ A", 1000, &Font::euler());
assert_eq!(
pieces(&r),
[
("A".into(), 0, 0, None, a),
("⊥".into(), a, 400, Some(700), bot),
("⊗ A".into(), a + bot + space, 0, None, 668 + space + a),
]
);
assert_eq!(r.width, a + bot + space + 668 + space + a);
let r = run("&L\u{4}1\u{5}, ", 800, &Font::euler());
assert_eq!(
pieces(&r),
[
("&L".into(), 0, 0, None, 1036),
("1".into(), 1036, -120, Some(560), 280),
(",".into(), 1316, 0, None, comma * 8 / 10),
]
);
}
#[cfg(feature = "parse")]
#[test]
fn styles_are_within_their_maxima() {
let s: Sequent = "A * B |- B * A".parse().unwrap();
let limits = crate::Limits::default();
let drawn = |style: &Style| sequent(&s, crate::linear::Mode::CLASSICAL, style, &limits);
let past = Style {
font_size: Style::MOST_FONT_SIZE + 1,
..Style::default()
};
assert!(matches!(
drawn(&past),
Err(Error::InvalidOption {
key: "svg.font_size",
..
})
));
let most = Style {
font: Font {
advances: Advances::Fixed(Style::MOST_SIZE),
..Font::euler()
},
font_size: Style::MOST_FONT_SIZE,
label_size: Style::MOST_SIZE,
margin: Style::MOST_LENGTH,
..Style::default()
};
let svg = drawn(&most).unwrap();
let width = svg
.split("width=\"")
.nth(1)
.unwrap()
.split('"')
.next()
.unwrap();
assert!(width.parse::<f64>().unwrap() > 0.0, "{width}");
assert_eq!(decimal(-1500), "-1.5");
}
#[test]
fn names_are_italic() {
let mut out = String::new();
italic(&mut out, "Ah_1α").unwrap();
assert_eq!(out, "𝐴ℎ_1α");
}
#[test]
fn text_is_xml() {
assert_eq!(
escaped("a\u{7}<b>\t\n\r&\"\u{FFFE}\u{FFFF}\u{0}"),
"a\u{FFFD}<b>\t\n\r&"\u{FFFD}\u{FFFD}\u{FFFD}"
);
}
}