use super::derivation::{Derivation, InfId};
use super::{Named, Rule};
#[cfg(any(feature = "latex", feature = "typst"))]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Write;
#[non_exhaustive]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Labels {
#[default]
Upright,
Subscript,
Off,
Table(BTreeMap<Named, String>),
}
const LABELLED: usize = Named::ALL.len() + Named::DIVISIONS.len();
const UPRIGHT: [&str; LABELLED] = [
"ax", "⊗", "⅋", "1", "⊥", "&", "⊕_1", "⊕_2", "⊤", "!", "?d", "?c", "?w", "mix", "wk", "cut",
"∀", "∃", "⊸L", "⊸R", "⊗L", "⊗R", "&L_1", "&L_2", "&R", "⊕L", "⊕R_1", "⊕R_2", "1L", "1R", "0L",
"⊤R", "!L", "!R", "!c", "!w", "∀R", "∃L", "∃R", "∀L", "", "\\L", "\\R", "/L", "/R",
];
const SUBSCRIPT: [&str; LABELLED] = [
"ax", "⊗", "⅋", "1", "⊥", "&", "⊕_1", "⊕_2", "⊤", "!", "?_d", "?_c", "?_w", "mix", "wk", "cut",
"∀", "∃", "⊸_L", "⊸_R", "⊗_L", "⊗_R", "&_{L1}", "&_{L2}", "&_R", "⊕_L", "⊕_{R1}", "⊕_{R2}",
"1_L", "1_R", "0_L", "⊤_R", "!_L", "!_R", "!_c", "!_w", "∀_R", "∃_L", "∃_R", "∀_L", "", "\\_L",
"\\_R", "/_L", "/_R",
];
impl Labels {
pub fn markup(&self, rule: Named) -> Option<&str> {
let index = rule.index();
let label = match self {
Self::Upright => UPRIGHT[index],
Self::Subscript => SUBSCRIPT[index],
Self::Off => return None,
Self::Table(table) => table.get(&rule).map_or(UPRIGHT[index], String::as_str),
};
(rule.rule != Rule::Open && !label.is_empty()).then_some(label)
}
}
pub(crate) const RUN: &str = "*";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Part<'a> {
Symbol(char),
Text(&'a str),
Sub(&'a str),
Sup(&'a str),
}
pub(crate) const LITERAL: char = '\u{7}';
pub(crate) const RAISED: char = '\u{8}';
fn symbol(c: char) -> bool {
matches!(
c,
'⊗' | '⅋'
| '&'
| '⊕'
| '⊸'
| '\\'
| '/'
| '!'
| '?'
| '⊤'
| '⊥'
| '0'
| '1'
| '*'
| '∧'
| '∨'
| '→'
| '¬'
| '↔'
| '∀'
| '∃'
)
}
pub(crate) fn parts(markup: &str) -> Vec<Part<'_>> {
let mut parts = Vec::new();
let mut rest = markup;
while let Some(c) = rest.chars().next() {
if c == RAISED {
let after = &rest[c.len_utf8()..];
let (group, next) = match after.strip_prefix('{') {
Some(group) => group.split_once('}').unwrap_or((group, "")),
None => ("", after),
};
parts.push(Part::Sup(group));
rest = next;
} else if c == LITERAL {
let after = &rest[c.len_utf8()..];
let next = after.chars().next().map_or(0, char::len_utf8);
if next > 0 {
parts.push(Part::Text(&after[..next]));
}
rest = &after[next..];
} else if c == '_' {
let after = &rest[1..];
let (sub, next) = match after.strip_prefix('{') {
Some(group) => group.split_once('}').unwrap_or((group, "")),
None => after.split_at(after.chars().next().map_or(0, char::len_utf8)),
};
parts.push(Part::Sub(sub));
rest = next;
} else if symbol(c) {
parts.push(Part::Symbol(c));
rest = &rest[c.len_utf8()..];
} else {
let end = rest
.find(|c: char| c == '_' || c == LITERAL || c == RAISED || symbol(c))
.unwrap_or(rest.len());
parts.push(Part::Text(&rest[..end]));
rest = &rest[end..];
}
}
parts
}
pub(crate) fn superscript(c: char) -> char {
match c {
'1' => '¹',
'2' => '²',
'3' => '³',
'0' | '4'..='9' => c
.to_digit(10)
.and_then(|d| char::from_u32(0x2070 + d))
.unwrap_or(c),
c => c,
}
}
pub(crate) fn plain(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.extend(text.chars().map(|c| match c.to_digit(10) {
Some(d) => char::from_u32(0x2080 + d).unwrap(),
None => c,
})),
Part::Sup(text) => out.extend(text.chars().map(superscript)),
}
}
out
}
pub(crate) trait Drawn {
fn rules(&self) -> usize;
fn open(&self) -> Option<usize>;
fn markup<'a>(&'a self, rule: usize, labels: &'a Labels) -> Option<&'a str>;
fn len(&self) -> usize;
fn root(&self) -> InfId;
fn premises(&self, id: InfId) -> &[InfId];
fn rule(&self, id: InfId) -> usize;
fn name(&self, id: InfId) -> &str;
fn times(&self, id: InfId) -> u32;
fn write_sequent(&self, out: &mut impl Write, id: InfId) -> std::fmt::Result;
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
fn sequent(
&self,
out: &mut String,
notation: &crate::linear::sequents::notation::Notation,
id: InfId,
aligned: bool,
marks: bool,
);
#[cfg(feature = "svg")]
fn positions(&self, id: InfId) -> Vec<usize>;
fn is_open(&self, id: InfId) -> bool {
self.open() == Some(self.rule(id))
}
fn bare(&self) -> Option<usize> {
None
}
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
fn is_bare(&self, id: InfId) -> bool {
self.bare() == Some(self.rule(id))
}
#[cfg(any(feature = "latex", feature = "typst"))]
fn label<'l>(&'l self, id: InfId, labels: &'l Labels) -> Option<Cow<'l, str>> {
let markup = self.markup(self.rule(id), labels)?;
Some(match self.times(id) {
1 => Cow::Borrowed(markup),
_ => Cow::Owned(format!("{markup}{RUN}")),
})
}
}
impl Drawn for Derivation<'_> {
fn rules(&self) -> usize {
LABELLED
}
fn open(&self) -> Option<usize> {
Some(Named::new(Rule::Open, None).index())
}
fn markup<'a>(&'a self, rule: usize, labels: &'a Labels) -> Option<&'a str> {
labels.markup(Named::at(rule))
}
fn len(&self) -> usize {
self.inferences().len()
}
fn root(&self) -> InfId {
Derivation::root(self)
}
fn premises(&self, id: InfId) -> &[InfId] {
&self.inference(id).premises
}
fn rule(&self, id: InfId) -> usize {
self.inference(id).rule.index()
}
fn name(&self, id: InfId) -> &'static str {
self.inference(id).rule.name()
}
fn times(&self, id: InfId) -> u32 {
self.inference(id).times
}
fn write_sequent(&self, out: &mut impl Write, id: InfId) -> std::fmt::Result {
super::fmt::write_sequent(
out,
self.forest(),
self.reading(),
self.framing(),
&self.inference(id).sequent,
)
}
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
fn sequent(
&self,
out: &mut String,
notation: &crate::linear::sequents::notation::Notation,
id: InfId,
aligned: bool,
marks: bool,
) {
let sequent = &self.inference(id).sequent;
notation
.sequent(
out,
self.forest(),
self.reading(),
self.framing(),
sequent,
aligned,
marks,
)
.unwrap();
}
#[cfg(feature = "svg")]
fn positions(&self, id: InfId) -> Vec<usize> {
let sequent = &self.inference(id).sequent;
match (self.reading(), self.framing()) {
(Some(reading), Some(framing)) => reading
.written_by(sequent, |m| framing.occurrence(m))
.collect(),
(Some(reading), None) => reading.written(sequent).collect(),
(None, _) => (0..sequent.len()).collect(),
}
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum OpenGoal {
Dots,
Bare,
Mark(String),
Dashed,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_round_trip() {
for rule in Named::ALL.into_iter().chain(Named::DIVISIONS) {
assert_eq!(rule.name().parse::<Named>().unwrap(), rule, "{rule:?}");
if rule.rule != Rule::Open {
let label = Labels::Upright.markup(rule).unwrap();
assert_eq!(plain(label), rule.name(), "{rule:?}");
}
}
}
#[test]
fn markup_parts() {
use Part::*;
assert_eq!(
parts("&L_1"),
[Symbol('&'), Text("L"), Sub("1")],
"a subscript of one character"
);
assert_eq!(parts("⊕_{R2}x"), [Symbol('⊕'), Sub("R2"), Text("x")]);
assert_eq!(parts("ax"), [Text("ax")]);
assert_eq!(parts("a_"), [Text("a"), Sub("")]);
}
}