#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
mod font;
mod kripke;
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 }
}
#[must_use]
pub fn with_lambda(self, lambda: Option<crate::lambda::Options>) -> Self {
Self { lambda, ..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
};
fn net_conclusion(
out: &mut impl Write,
forest: &crate::linear::Forest,
reading: Option<&Reading<'_>>,
) -> std::fmt::Result {
out.write_str("It concludes ")?;
match reading {
Some(reading) => PLAIN.reading(out, reading)?,
None => PLAIN.one_sided(out, forest.sequent())?,
}
out.write_char('.')
}
fn net_formula(
out: &mut impl Write,
noun: &str,
number: u32,
forest: &crate::linear::Forest,
reading: Option<&Reading<'_>>,
o: crate::linear::OccId,
) -> std::fmt::Result {
write!(out, "{noun} {number}, ")?;
match reading {
Some(reading) => PLAIN.ill(out, reading, o, false),
None => PLAIN.term(out, forest.sequent(), forest.term(o), false),
}
}
fn net_link(
out: &mut impl Write,
cut: bool,
ends: [(u32, crate::linear::OccId); 2],
forest: &crate::linear::Forest,
reading: Option<&Reading<'_>>,
) -> std::fmt::Result {
out.write_str(if cut {
"\nA cut link joins "
} else {
"\nAn axiom link joins "
})?;
net_formula(out, "formula", ends[0].0, forest, reading, ends[0].1)?;
out.write_str(", and ")?;
net_formula(out, "formula", ends[1].0, forest, reading, ends[1].1)?;
out.write_char('.')
}
fn net_verdict(
out: &mut impl Write,
criterion: crate::linear::Criterion,
reason: Option<&dyn std::fmt::Display>,
) -> std::fmt::Result {
match reason {
Some(reason) => write!(out, "\nIt is not a proof net: {reason}."),
None if criterion.mix => {
out.write_str("\nIt is a proof net with Mix: the correctness criterion with Mix holds.")
}
None if criterion.order != crate::linear::Order::Commutative => out.write_str(
"\nIt is a planar proof net: the correctness criterion holds, and no two links \
cross.",
),
None => out.write_str("\nIt is a proof net: the correctness criterion holds."),
}
}
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 to_string<'a>(derivation: impl Into<Drawable<'a>>, style: &Style) -> Result<String, Error> {
let mut out = String::new();
write(derivation, style, &mut out, |_| false)?;
Ok(out)
}
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);
let drawn = within(limits, || net::estimate(net, style, reading.is_some()))?;
let mut stop = stop;
let verdict = match &reading {
Some(_) => net.is_essential(&mut stop),
None => net.is_correct(&mut stop),
};
refused(&verdict)?;
let own = (reading.is_some() && style.description).then(|| net.is_correct(&mut stop));
if let Some(own) = &own {
refused(own)?;
}
let described = own.as_ref().unwrap_or(&verdict);
if style.description {
described_within(drawn, |most| {
net::described_bytes(net, described, reading.as_ref(), most)
})?;
}
Ok(net::draw(
net,
style,
&verdict,
described,
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);
let drawn = within(limits, || mell::estimate(net, style, reading.is_some()))?;
let verdict = net.is_correct(stop);
refused(&verdict)?;
if style.description {
described_within(drawn, |most| {
mell::described_bytes(net, &verdict, reading.as_ref(), most)
})?;
}
Ok(mell::draw(net, style, &verdict, reading.as_ref(), marks))
}
fn within(
limits: &crate::Limits,
estimate: impl FnOnce() -> u64,
) -> Result<Option<(u64, u64)>, Error> {
let Some(limit) = limits.derivation_bytes else {
return Ok(None);
};
let bytes = estimate();
if bytes > limit {
return Err(too_large(bytes, limit));
}
Ok(Some((limit, bytes)))
}
fn described_within(
drawn: Option<(u64, u64)>,
described: impl FnOnce(u64) -> u64,
) -> Result<(), Error> {
let Some((limit, bytes)) = drawn else {
return Ok(());
};
let total = bytes.saturating_add(described(limit - bytes));
match total > limit {
true => Err(too_large(total, limit)),
false => Ok(()),
}
}
const fn too_large(estimate: u64, limit: u64) -> Error {
Error::Refused(crate::limits::Refusal::Output {
what: "drawing",
estimate_bytes: estimate,
limit_bytes: limit,
least_bytes: None,
})
}
#[cfg_attr(all(feature = "parse", feature = "sat"), doc = "```")]
#[cfg_attr(not(all(feature = "parse", feature = "sat")), doc = "```ignore")]
pub fn countermodel(
countermodel: &crate::ordinary::Countermodel,
logic: crate::ordinary::Logic,
style: &Style,
limits: &crate::Limits,
mut stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
use crate::ordinary::{Logic, Node, NodeId};
countermodel.check(logic, limits, &mut stop)?;
let sequent = &countermodel.sequent;
within(limits, || {
let formulas = sequent.formulas();
let mut bytes: Vec<u64> = Vec::with_capacity(formulas.len());
for &node in formulas.nodes() {
let of = |k: NodeId| bytes[k.index()];
let b = match node {
Node::Atom(a) => (formulas.atom_names()[a as usize].len() as u64).saturating_add(2),
Node::True | Node::False => 3,
Node::Not(a) => of(a).saturating_add(4),
Node::And(a, b) | Node::Or(a, b) | Node::Implies(a, b) | Node::Iff(a, b) => {
of(a).saturating_add(of(b)).saturating_add(9)
}
};
bytes.push(b);
}
sequent
.left()
.iter()
.chain(sequent.right())
.fold(0u64, |sum, id| sum.saturating_add(bytes[id.index()]))
.saturating_mul(12)
})?;
let title = format!("A countermodel of {sequent}");
let w = countermodel.model.world;
let last = match (logic, sequent.right().is_empty()) {
(Logic::Classical, _) => format!(
"World {w} makes every formula left of ⊢ true and every formula right of it \
false, so {sequent} is not valid in classical logic."
),
(Logic::Intuitionistic | Logic::Minimal, true) => format!(
"World {w} forces each formula left of ⊢ and not ⊥, so {sequent} is not valid in \
{logic} logic."
),
(Logic::Intuitionistic | Logic::Minimal, false) => format!(
"World {w} forces each formula left of ⊢ and not the one right of it, so \
{sequent} is not valid in {logic} logic."
),
};
let mut polls = 0u64;
kripke::draw(&countermodel.model, &title, &last, style, limits, || {
polls += 1;
stop(crate::limits::Progress::new(
crate::limits::Phase::Write,
1,
polls,
))
})
}
fn refused(verdict: &Result<(), crate::linear::nets::NetError>) -> Result<(), Error> {
match verdict {
Err(refused @ crate::linear::nets::NetError::Refused { .. }) => Err(refused.clone().into()),
_ => Ok(()),
}
}
#[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 the_description_writes_formulas_as_the_title_does() {
use crate::linear::{Mode, Options, prove};
let s: Sequent = "A -o B |- ~B -o ~A".parse().unwrap();
let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
let proof = outcome.verdict.proof().unwrap();
let svg = to_string(&proof.derivation().unwrap(), &Style::default()).unwrap();
let desc = &svg[svg.find("<desc>").unwrap()..svg.find("</desc>").unwrap()];
assert!(svg.contains("<title>⊢ A ⊗ B⊥, B ⅋ A⊥</title>"), "{svg}");
assert!(
desc.ends_with("4. ⊢ A ⊗ B⊥, B ⅋ A⊥, by ⅋ from 3."),
"{desc}"
);
assert!(!desc.contains('~'), "{desc}");
}
#[cfg(feature = "parse")]
#[test]
fn a_net_is_described_in_sentences() {
use crate::linear::{Criterion, Mode, Options, ProofStructure, prove};
let s: Sequent = "A * B |- B * A".parse().unwrap();
let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
let proof = outcome.verdict.proof().unwrap();
let limits = crate::Limits::default();
let structure =
ProofStructure::from_proof(proof, Criterion::MLL, &limits, |_| false).unwrap();
let svg = net(&structure, &Style::default(), &limits, |_| false).unwrap();
let desc = &svg[svg.find("<desc>").unwrap() + 6..svg.find("</desc>").unwrap()];
assert_eq!(
desc,
"It concludes ⊢ A⊥ ⅋ B⊥, B ⊗ A.\n\
An axiom link joins formula 1, A⊥, and formula 5, A.\n\
An axiom link joins formula 2, B⊥, and formula 4, B.\n\
It is a proof net: the correctness criterion holds."
);
}
#[cfg(feature = "parse")]
#[test]
fn crossing_links_are_described_as_no_net() {
use crate::linear::nets::VertexId;
use crate::linear::{Criterion, Forest, Order, ProofStructure};
let limits = crate::Limits::default();
let s = Sequent::parse_ordered("a, b |- b * a", Order::Cyclic, &limits).unwrap();
let v = VertexId::new;
let links = [(v(1), v(4)), (v(0), v(3))];
let structure =
ProofStructure::from_links(Forest::new(&s).unwrap(), Criterion::CYCLIC, &links)
.unwrap();
assert_eq!(structure.is_essential(|_| false), Ok(()));
let style = Style::default().with_essential(true);
let svg = net(&structure, &style, &limits, |_| false).unwrap();
let desc = &svg[svg.find("<desc>").unwrap()..svg.find("</desc>").unwrap()];
assert!(desc.contains("\nIt is not a proof net: "), "{desc}");
}
#[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}"
);
}
}