use super::noad::*;
use crate::catcode::Cat;
use crate::expand::{Engine, NumericCs, TexError};
use crate::lexer::Lexer;
use crate::token::{CsId, Token};
type R<T> = Result<T, TexError>;
const VAR_CLASS: i64 = 7;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Stop {
Brace,
MathShift,
Cs(&'static str),
}
#[derive(Clone, Debug, Default)]
pub struct Formula {
pub rows: Vec<Vec<Vec<Noad>>>,
pub number: Option<Vec<Noad>>,
pub number_left: bool,
pub labels: Vec<(usize, Vec<Token>)>,
pub unnumbered: Vec<usize>,
pub tags: Vec<(usize, Vec<Token>, bool)>,
}
impl Formula {
pub fn flat(&self) -> Vec<Noad> {
self.rows.iter().flatten().flatten().cloned().collect()
}
pub fn is_single(&self) -> bool {
self.rows.len() == 1 && self.rows[0].len() == 1
}
pub fn single(&self) -> Option<&[Noad]> {
match self.is_single() {
true => Some(&self.rows[0][0]),
false => None,
}
}
}
pub fn formula(eng: &mut Engine, lx: &mut Lexer, stop: Stop) -> R<Formula> {
let mut scanner = Scanner {
eng,
depth: 0,
rows: Vec::new(),
cells: Vec::new(),
number: None,
number_left: false,
labels: Vec::new(),
unnumbered: Vec::new(),
tags: Vec::new(),
};
let last = scanner.mlist(lx, stop)?;
scanner.cells.push(last);
scanner.rows.push(std::mem::take(&mut scanner.cells));
Ok(Formula {
rows: scanner.rows,
number: scanner.number,
number_left: scanner.number_left,
labels: scanner.labels,
unnumbered: scanner.unnumbered,
tags: scanner.tags,
})
}
struct Scanner<'a> {
eng: &'a mut Engine,
depth: usize,
rows: Vec<Vec<Vec<Noad>>>,
cells: Vec<Vec<Noad>>,
number: Option<Vec<Noad>>,
number_left: bool,
labels: Vec<(usize, Vec<Token>)>,
unnumbered: Vec<usize>,
tags: Vec<(usize, Vec<Token>, bool)>,
}
const MAX_DEPTH: usize = 48;
impl Scanner<'_> {
fn mlist(&mut self, lx: &mut Lexer, stop: Stop) -> R<Vec<Noad>> {
self.depth += 1;
if self.depth > MAX_DEPTH {
self.depth -= 1;
return Err(TexError(
"TeX capacity exceeded, sorry [math nesting]".into(),
));
}
let out = self.mlist_inner(lx, stop);
self.depth -= 1;
out
}
fn mlist_inner(&mut self, lx: &mut Lexer, stop: Stop) -> R<Vec<Noad>> {
let mut list: Vec<Noad> = Vec::new();
let mut incompleat: Option<Fraction> = None;
while let Some(tok) = lx.next_token(&self.eng.cats) {
match tok {
Token::Char(_, Cat::EndGroup) => {
if stop == Stop::Brace {
return Ok(self.finish(list, incompleat));
}
return Ok(self.finish(list, incompleat));
}
Token::Char(_, Cat::MathShift) => {
if stop == Stop::MathShift {
return Ok(self.finish(list, incompleat));
}
return Ok(self.finish(list, incompleat));
}
Token::Char(_, Cat::BeginGroup) => {
let inner = self.mlist(lx, Stop::Brace)?;
list.push(Noad::Atom(Atom::new(Class::Ord, Field::List(inner))));
}
Token::Char(_, Cat::Space) => {}
Token::Char('^', _) => {
let field = self.field(lx)?;
self.attach(&mut list, field, true);
}
Token::Char('_', _) => {
let field = self.field(lx)?;
self.attach(&mut list, field, false);
}
Token::Char(_, Cat::AlignTab) if self.depth == 1 => {
let cell = self.finish(std::mem::take(&mut list), incompleat.take());
self.cells.push(cell);
}
Token::Char(_, Cat::AlignTab) => {}
Token::Char(c, _) => {
let code = mathcode(c);
if let Some(atom) = atom_for_code(code) {
list.push(Noad::Atom(atom));
}
}
Token::Cs(name) => {
let n = name.name();
if n == "par" {
lx.push_back(&[Token::Cs(name)]);
return Ok(self.finish(list, incompleat));
}
if n == "right" || n == "end" {
lx.push_back(&[Token::Cs(name)]);
return Ok(self.finish(list, incompleat));
}
if let Stop::Cs(want) = stop {
if n == want {
return Ok(self.finish(list, incompleat));
}
}
if self.depth == 1 && matches!(n, "\\" | "cr" | "crcr") {
let _ = self.eng.skip_optional_star(lx);
let cell = self.finish(std::mem::take(&mut list), incompleat.take());
self.cells.push(cell);
self.rows.push(std::mem::take(&mut self.cells));
continue;
}
if self.depth == 1 && matches!(n, "eqno" | "leqno") {
self.number_left = n == "leqno";
let number = self.mlist(lx, stop)?;
self.number = Some(number);
return Ok(self.finish(list, incompleat));
}
if let Some(f) = self.generalized_fraction(lx, n)? {
if incompleat.is_none() {
incompleat = Some(Fraction {
numerator: std::mem::take(&mut list),
..f
});
}
continue;
}
self.control_sequence(lx, name, &mut list)?;
}
}
}
Ok(self.finish(list, incompleat))
}
fn finish(&mut self, list: Vec<Noad>, incompleat: Option<Fraction>) -> Vec<Noad> {
match incompleat {
None => list,
Some(f) => vec![Noad::Fraction(Fraction {
denominator: list,
..f
})],
}
}
fn generalized_fraction(&mut self, lx: &mut Lexer, name: &str) -> R<Option<Fraction>> {
let (thickness, delims) = match name {
"over" => (None, false),
"atop" => (Some(0), false),
"above" => (Some(self.eng.scan_dimen(lx, false)?), false),
"overwithdelims" => (None, true),
"atopwithdelims" => (Some(0), true),
"abovewithdelims" => (Some(i64::MIN), true),
_ => return Ok(None),
};
let (left, right) = match delims {
true => (self.delimiter(lx)?, self.delimiter(lx)?),
false => (Delimiter::null(), Delimiter::null()),
};
let thickness = match thickness {
Some(t) if t == i64::MIN => Some(self.eng.scan_dimen(lx, false)?),
other => other,
};
Ok(Some(Fraction {
thickness,
numerator: Vec::new(),
denominator: Vec::new(),
left_delimiter: left,
right_delimiter: right,
}))
}
fn attach(&mut self, list: &mut Vec<Noad>, field: Field, superscript: bool) {
fn slot(item: &mut Noad) -> Option<&mut Atom> {
match item {
Noad::Atom(a) | Noad::Over(a) | Noad::Under(a) | Noad::VCenter(a) => Some(a),
Noad::Radical(r) => Some(&mut r.nucleus),
Noad::Accent(acc) => Some(&mut acc.atom),
_ => None,
}
}
let free = match list.last_mut().and_then(slot) {
Some(a) => match superscript {
true => a.supscr.is_empty(),
false => a.subscr.is_empty(),
},
None => false,
};
if !free {
list.push(Noad::Atom(Atom::default()));
}
if let Some(a) = list.last_mut().and_then(slot) {
match superscript {
true => a.supscr = field,
false => a.subscr = field,
}
}
}
fn field(&mut self, lx: &mut Lexer) -> R<Field> {
while let Some(tok) = lx.next_token(&self.eng.cats) {
match tok {
Token::Char(_, Cat::Space) => continue,
Token::Char(_, Cat::BeginGroup) => {
return Ok(Field::List(self.mlist(lx, Stop::Brace)?));
}
Token::Char(c, _) => {
let code = mathcode(c);
return Ok(match char_field(code) {
Some(f) => f,
None => Field::Empty,
});
}
Token::Cs(name) => {
if let Some(code) = self.math_code_of(name) {
return Ok(char_field(code).unwrap_or(Field::Empty));
}
let mut one = Vec::new();
self.control_sequence(lx, name, &mut one)?;
return Ok(Field::List(one));
}
}
}
Ok(Field::Empty)
}
fn math_code_of(&mut self, name: CsId) -> Option<i64> {
if let Some(NumericCs::Value(v)) = self.eng.numeric_cs(name) {
if v >= 256 {
return Some(v);
}
if (0..256).contains(&v) {
return Some(mathcode(v as u8 as char));
}
}
plain_math_symbol(name.name())
}
fn delimiter(&mut self, lx: &mut Lexer) -> R<Delimiter> {
while let Some(tok) = lx.next_token(&self.eng.cats) {
match tok {
Token::Char(_, Cat::Space) => continue,
Token::Char('.', _) => return Ok(Delimiter::null()),
Token::Char(c, _) => {
return Ok(delcode(c)
.map(Delimiter::from_code)
.unwrap_or_else(Delimiter::null))
}
Token::Cs(name) => {
return Ok(match delimiter_code(name.name()) {
Some(code) => Delimiter::from_code(code & 0xFF_FFFF),
None => Delimiter::null(),
})
}
}
}
Ok(Delimiter::null())
}
fn argument(&mut self, lx: &mut Lexer) -> R<Vec<Noad>> {
match self.field(lx)? {
Field::List(l) => Ok(l),
Field::Char(c) => Ok(vec![Noad::Atom(Atom::new(Class::Ord, Field::Char(c)))]),
Field::Literal(c) => Ok(vec![Noad::Atom(Atom::new(Class::Ord, Field::Literal(c)))]),
_ => Ok(Vec::new()),
}
}
fn raw_argument(&mut self, lx: &mut Lexer) -> Vec<Token> {
let first = loop {
match lx.next_token(&self.eng.cats) {
Some(Token::Char(_, Cat::Space)) => continue,
Some(t) => break t,
None => return Vec::new(),
}
};
if !matches!(first, Token::Char(_, Cat::BeginGroup)) {
return vec![first];
}
let mut body = Vec::new();
let mut depth = 1usize;
while let Some(t) = lx.next_token(&self.eng.cats) {
match t {
Token::Char(_, Cat::BeginGroup) => depth += 1,
Token::Char(_, Cat::EndGroup) => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
body.push(t);
}
body
}
fn accent_noad(&mut self, lx: &mut Lexer, code: i64) -> R<Noad> {
let accent = MathChar {
fam: ((code / 256) % 16) as usize,
character: (code % 256) as u8,
};
let nucleus = self.field(lx)?;
Ok(Noad::Accent(Accent {
accent,
atom: Atom::new(Class::Ord, nucleus),
}))
}
fn mu_dimen(&mut self, lx: &mut Lexer) -> R<Scaled> {
Ok(self.mu_glue_amount(lx)?.natural)
}
fn mu_glue(&mut self, lx: &mut Lexer) -> R<MuGlue> {
let mut glue = self.mu_glue_amount(lx)?;
if self.eng.scan_keyword(lx, "plus", false)? {
glue.stretch = self.mu_glue_amount(lx)?.natural;
}
if self.eng.scan_keyword(lx, "minus", false)? {
glue.shrink = self.mu_glue_amount(lx)?.natural;
}
Ok(glue)
}
fn mu_glue_amount(&mut self, lx: &mut Lexer) -> R<MuGlue> {
let mut negative = false;
let mut digits: Vec<u8> = Vec::new();
let mut fraction: Vec<u8> = Vec::new();
loop {
let Some(tok) = lx.next_token(&self.eng.cats) else {
return Ok(MuGlue::default());
};
match tok {
Token::Char(_, Cat::Space) => continue,
Token::Char('-', _) => negative = !negative,
Token::Char('+', _) => {}
Token::Char(c, _) if c.is_ascii_digit() || c == '.' || c == ',' => {
lx.push_back(&[tok]);
break;
}
Token::Cs(name) => {
let spec = match name.name() {
"thinmuskip" => THIN_MU_SKIP,
"medmuskip" => MED_MU_SKIP,
"thickmuskip" => THICK_MU_SKIP,
_ => return Ok(MuGlue::default()),
};
let glue = MuGlue::of(spec);
return Ok(match negative {
true => glue.negated(),
false => glue,
});
}
other => {
lx.push_back(&[other]);
break;
}
}
}
let mut past_point = false;
while let Some(tok) = lx.next_token(&self.eng.cats) {
match tok {
Token::Char(c, _) if c.is_ascii_digit() => match past_point {
true => fraction.push(c as u8 - b'0'),
false => digits.push(c as u8 - b'0'),
},
Token::Char('.', _) | Token::Char(',', _) if !past_point => past_point = true,
other => {
lx.push_back(&[other]);
break;
}
}
}
if !self.eng.scan_keyword(lx, "mu", false)? {
return Err(TexError("Illegal unit of measure (mu inserted)".into()));
}
let whole: i64 = digits.iter().fold(0i64, |a, d| a * 10 + *d as i64);
fraction.truncate(17);
let amount = whole * 65536 + round_decimals(&fraction);
Ok(MuGlue::fixed(match negative {
true => -amount,
false => amount,
}))
}
fn control_sequence(&mut self, lx: &mut Lexer, name: CsId, out: &mut Vec<Noad>) -> R<()> {
let n = name.name();
if let Some(code) = self.math_code_of(name) {
if let Some(atom) = atom_for_code(code) {
out.push(Noad::Atom(atom));
}
return Ok(());
}
if let Some(code) = delimiter_code(n) {
if let Some(atom) = atom_for_code(code / 0x10000) {
out.push(Noad::Atom(atom));
}
return Ok(());
}
match n {
"mathord" | "mathop" | "mathbin" | "mathrel" | "mathopen" | "mathclose"
| "mathpunct" | "mathinner" => {
let class = match n {
"mathop" => Class::Op,
"mathbin" => Class::Bin,
"mathrel" => Class::Rel,
"mathopen" => Class::Open,
"mathclose" => Class::Close,
"mathpunct" => Class::Punct,
"mathinner" => Class::Inner,
_ => Class::Ord,
};
let field = self.field(lx)?;
out.push(Noad::Atom(Atom::new(class, field)));
}
"overline" => {
let field = self.field(lx)?;
out.push(Noad::Over(Atom::new(Class::Ord, field)));
}
"underline" => {
let field = self.field(lx)?;
out.push(Noad::Under(Atom::new(Class::Ord, field)));
}
"limits" | "nolimits" | "displaylimits" => {
if let Some(Noad::Atom(a)) = out.last_mut() {
a.limits = match n {
"limits" => Limits::Above,
"nolimits" => Limits::Beside,
_ => Limits::Normal,
};
}
}
"label" => {
let key = self.raw_argument(lx);
self.labels.push((self.rows.len(), key));
}
"nonumber" | "notag" => self.unnumbered.push(self.rows.len()),
"tag" => {
let starred = self.eng.skip_optional_star(lx);
let tag = self.raw_argument(lx);
self.tags.push((self.rows.len(), tag, starred));
}
"displaystyle" => out.push(Noad::Style(DISPLAY_STYLE)),
"textstyle" => out.push(Noad::Style(TEXT_STYLE)),
"scriptstyle" => out.push(Noad::Style(SCRIPT_STYLE)),
"scriptscriptstyle" => out.push(Noad::Style(SCRIPT_SCRIPT_STYLE)),
"sqrt" | "radical" => {
let delim = match n {
"radical" => {
Delimiter::from_code(self.eng.scan_number_pending(lx)? & 0xFF_FFFF)
}
_ => Delimiter::from_code(0x270370),
};
let index = match self.eng.read_optional_bracket(lx)? {
Some(tokens) => {
let mut back = tokens;
back.push(Token::Char('}', Cat::EndGroup));
lx.push_back(&back);
Some(self.mlist(lx, Stop::Brace)?)
}
None => None,
};
let body = self.argument(lx)?;
out.push(Noad::Radical(Radical {
left_delimiter: delim,
nucleus: Atom::new(Class::Ord, Field::List(body)),
index,
}));
}
"frac" | "dfrac" | "tfrac" => {
let numerator = self.argument(lx)?;
let denominator = self.argument(lx)?;
out.push(Noad::Fraction(Fraction {
thickness: None,
numerator,
denominator,
left_delimiter: Delimiter::null(),
right_delimiter: Delimiter::null(),
}));
}
"binom" => {
let numerator = self.argument(lx)?;
let denominator = self.argument(lx)?;
out.push(Noad::Fraction(Fraction {
thickness: Some(0),
numerator,
denominator,
left_delimiter: Delimiter::from_code(0x028300),
right_delimiter: Delimiter::from_code(0x029301),
}));
}
"left" => {
let left = self.delimiter(lx)?;
let mut inner = self.mlist(lx, Stop::Cs("right"))?;
let right = match lx.next_token(&self.eng.cats) {
Some(Token::Cs(c)) if c.name() == "right" => self.delimiter(lx)?,
Some(t) => {
lx.push_back(&[t]);
Delimiter::null()
}
None => Delimiter::null(),
};
let mut whole = vec![Noad::Left(left)];
whole.append(&mut inner);
whole.push(Noad::Right(right));
out.push(Noad::Atom(Atom::new(Class::Inner, Field::List(whole))));
}
"," => out.push(Noad::MuGlue(MuGlue::of(THIN_MU_SKIP))),
">" => out.push(Noad::MuGlue(MuGlue::of(MED_MU_SKIP))),
";" => out.push(Noad::MuGlue(MuGlue::of(THICK_MU_SKIP))),
"!" => out.push(Noad::MuGlue(MuGlue::of(THIN_MU_SKIP).negated())),
"thinspace" => out.push(Noad::MuGlue(MuGlue::of(THIN_MU_SKIP))),
"quad" => out.push(Noad::Glue(mu(18 * 65536))),
"qquad" => out.push(Noad::Glue(mu(36 * 65536))),
" " | "enspace" => out.push(Noad::Glue(mu(9 * 65536))),
"ldots" | "dots" | "cdots" => {
let code = match n == "cdots" {
true => 0x6201,
false => 0x613A,
};
let dots: Vec<Noad> = (0..3)
.filter_map(|_| atom_for_code(code).map(Noad::Atom))
.collect();
out.push(Noad::Atom(Atom::new(Class::Inner, Field::List(dots))));
}
"mathaccent" => {
let code = self.eng.scan_number_pending(lx)?;
out.push(self.accent_noad(lx, code)?);
}
_ if MATH_ACCENTS.iter().any(|(a, _)| *a == n) => {
let code = MATH_ACCENTS
.iter()
.find(|(a, _)| *a == n)
.map(|(_, c)| *c)
.unwrap_or(0);
out.push(self.accent_noad(lx, code)?);
}
"vcenter" => {
let body = self.argument(lx)?;
out.push(Noad::VCenter(Atom::new(Class::Ord, Field::List(body))));
}
"mathchoice" => {
out.push(Noad::Choice(Box::new(Choice {
display: self.argument(lx)?,
text: self.argument(lx)?,
script: self.argument(lx)?,
script_script: self.argument(lx)?,
})));
}
"mkern" => {
let amount = self.mu_dimen(lx)?;
out.push(Noad::MuKern(amount));
}
"mskip" => {
let glue = self.mu_glue(lx)?;
out.push(Noad::MuGlue(glue));
}
"mathrm" | "mathbf" | "mathsf" | "mathtt" | "mathnormal" | "mathit" | "text"
| "textrm" | "mbox" | "operatorname" => {
let fam = match n {
"mathit" | "mathnormal" => 1,
_ => 0,
};
let body = self.argument(lx)?;
let body = in_family(body, fam);
let class = match n == "operatorname" {
true => Class::Op,
false => Class::Ord,
};
let mut atom = Atom::new(class, Field::List(body));
if n == "operatorname" {
atom.limits = Limits::Beside;
}
out.push(Noad::Atom(atom));
}
_ if OPERATOR_NAMES.contains(&n) => {
let letters: Vec<Noad> = n
.bytes()
.map(|b| {
Noad::Atom(Atom::new(
Class::Ord,
Field::Char(MathChar {
fam: 0,
character: b,
}),
))
})
.collect();
out.push(Noad::Atom(Atom {
class: ClassOrOrd(Class::Op),
nucleus: Field::List(letters),
limits: match OPERATOR_LIMITS.contains(&n) {
true => Limits::Normal,
false => Limits::Beside,
},
..Atom::default()
}));
}
_ => {
if self.eng.is_macro(name) {
self.eng.expand_macro_file(lx, name)?;
return Ok(());
}
if let Some(c) = crate::typeset::symbol_char(n) {
out.push(Noad::Atom(Atom::new(Class::Ord, Field::Literal(c))));
}
}
}
Ok(())
}
}
fn mu(amount: i64) -> Scaled {
amount / 18
}
fn round_decimals(digits: &[u8]) -> Scaled {
let mut a: i64 = 0;
for d in digits.iter().rev() {
a = (a + *d as i64 * 131_072) / 10;
}
(a + 1) / 2
}
pub const MATH_ACCENTS: &[(&str, i64)] = &[
("acute", 0x7013),
("grave", 0x7012),
("ddot", 0x707F),
("tilde", 0x707E),
("bar", 0x7016),
("breve", 0x7015),
("check", 0x7014),
("hat", 0x705E),
("vec", 0x017E),
("dot", 0x705F),
("widetilde", 0x0365),
("widehat", 0x0362),
];
fn in_family(list: Vec<Noad>, fam: usize) -> Vec<Noad> {
fn field(f: Field, fam: usize) -> Field {
match f {
Field::Char(c) => Field::Char(MathChar { fam, ..c }),
Field::List(l) => Field::List(in_family(l, fam)),
other => other,
}
}
list.into_iter()
.map(|item| match item {
Noad::Atom(a) => Noad::Atom(Atom {
nucleus: field(a.nucleus, fam),
supscr: field(a.supscr, fam),
subscr: field(a.subscr, fam),
..a
}),
other => other,
})
.collect()
}
fn atom_for_code(code: i64) -> Option<Atom> {
if code >= 0o100000 {
return None;
}
let class = code / 0o10000;
let fam = ((code / 256) % 16) as usize;
let character = (code % 256) as u8;
let atom = Atom::new(
match class == VAR_CLASS {
true => Class::Ord,
false => Class::from_code(class),
},
Field::Char(MathChar { fam, character }),
);
Some(atom)
}
fn char_field(code: i64) -> Option<Field> {
if code >= 0o100000 {
return None;
}
Some(Field::Char(MathChar {
fam: ((code / 256) % 16) as usize,
character: (code % 256) as u8,
}))
}
pub fn mathcode(c: char) -> i64 {
let b = match u32::from(c) {
n if n < 256 => n as u8,
_ => return c as i64,
};
match b {
b'A'..=b'Z' | b'a'..=b'z' => 0x7100 + b as i64,
b'0'..=b'9' => 0x7000 + b as i64,
b'!' => 0x5021,
b'(' => 0x4028,
b')' => 0x5029,
b'*' => 0x2203,
b'+' => 0x202B,
b',' => 0x613B,
b'-' => 0x2200,
b'.' => 0x013A,
b'/' => 0x013D,
b':' => 0x303A,
b';' => 0x603B,
b'<' => 0x313C,
b'=' => 0x303D,
b'>' => 0x313E,
b'?' => 0x503F,
b'[' => 0x405B,
b'\\' => 0x026E,
b']' => 0x505D,
b'{' => 0x4266,
b'|' => 0x026A,
b'}' => 0x5267,
_ => b as i64,
}
}
pub fn delcode(c: char) -> Option<i64> {
Some(match c {
'(' => 0x028300,
')' => 0x029301,
'[' => 0x05B302,
']' => 0x05D303,
'<' => 0x26830A,
'>' => 0x26930B,
'/' => 0x02F30E,
'|' => 0x26A30C,
'\\' => 0x26E30F,
_ => return None,
})
}
pub fn delimiter_code(name: &str) -> Option<i64> {
Some(match name {
"lmoustache" => 0x437A340,
"rmoustache" => 0x537B341,
"lgroup" => 0x462833A,
"rgroup" => 0x562933B,
"arrowvert" => 0x26A33C,
"Arrowvert" => 0x26B33D,
"bracevert" => 0x77C33E,
"Vert" | "|" => 0x26B30D,
"vert" => 0x26A30C,
"uparrow" => 0x3222378,
"downarrow" => 0x3223379,
"updownarrow" => 0x326C33F,
"Uparrow" => 0x322A37E,
"Downarrow" => 0x322B37F,
"Updownarrow" => 0x326D377,
"backslash" => 0x26E30F,
"rangle" => 0x526930B,
"langle" => 0x426830A,
"rbrace" | "}" => 0x5267309,
"lbrace" | "{" => 0x4266308,
"rceil" => 0x5265307,
"lceil" => 0x4264306,
"rfloor" => 0x5263305,
"lfloor" => 0x4262304,
_ => return None,
})
}
const OPERATOR_NAMES: &[&str] = &[
"log", "lg", "ln", "lim", "limsup", "liminf", "sin", "arcsin", "sinh", "cos", "arccos", "cosh",
"tan", "arctan", "tanh", "cot", "coth", "sec", "csc", "max", "min", "sup", "inf", "arg", "ker",
"dim", "hom", "det", "exp", "Pr", "gcd", "deg",
];
const OPERATOR_LIMITS: &[&str] = &[
"lim", "limsup", "liminf", "max", "min", "sup", "inf", "det", "Pr", "gcd",
];
fn plain_math_symbol(name: &str) -> Option<i64> {
static BY_NAME: once_cell::sync::Lazy<rustc_hash::FxHashMap<&str, i64>> =
once_cell::sync::Lazy::new(|| MATH_SYMBOLS.iter().copied().collect());
BY_NAME.get(name).copied()
}
pub const MATH_SYMBOLS: &[(&str, i64)] = &[
("alpha", 0x010B),
("beta", 0x010C),
("gamma", 0x010D),
("delta", 0x010E),
("epsilon", 0x010F),
("zeta", 0x0110),
("eta", 0x0111),
("theta", 0x0112),
("iota", 0x0113),
("kappa", 0x0114),
("lambda", 0x0115),
("mu", 0x0116),
("nu", 0x0117),
("xi", 0x0118),
("pi", 0x0119),
("rho", 0x011A),
("sigma", 0x011B),
("tau", 0x011C),
("upsilon", 0x011D),
("phi", 0x011E),
("chi", 0x011F),
("psi", 0x0120),
("omega", 0x0121),
("varepsilon", 0x0122),
("vartheta", 0x0123),
("varpi", 0x0124),
("varrho", 0x0125),
("varsigma", 0x0126),
("varphi", 0x0127),
("Gamma", 0x7000),
("Delta", 0x7001),
("Theta", 0x7002),
("Lambda", 0x7003),
("Xi", 0x7004),
("Pi", 0x7005),
("Sigma", 0x7006),
("Upsilon", 0x7007),
("Phi", 0x7008),
("Psi", 0x7009),
("Omega", 0x700A),
("aleph", 0x0240),
("imath", 0x017B),
("jmath", 0x017C),
("ell", 0x0160),
("wp", 0x017D),
("Re", 0x023C),
("Im", 0x023D),
("partial", 0x0140),
("infty", 0x0231),
("prime", 0x0230),
("emptyset", 0x023B),
("varnothing", 0x023B),
("nabla", 0x0272),
("top", 0x023E),
("bot", 0x023F),
("triangle", 0x0234),
("forall", 0x0238),
("exists", 0x0239),
("neg", 0x023A),
("lnot", 0x023A),
("flat", 0x015B),
("natural", 0x015C),
("sharp", 0x015D),
("clubsuit", 0x027C),
("diamondsuit", 0x027D),
("heartsuit", 0x027E),
("spadesuit", 0x027F),
("coprod", 0x1360),
("bigvee", 0x1357),
("bigwedge", 0x1356),
("biguplus", 0x1355),
("bigcap", 0x1354),
("bigcup", 0x1353),
("intop", 0x1352),
("prod", 0x1351),
("sum", 0x1350),
("bigotimes", 0x134E),
("bigoplus", 0x134C),
("bigodot", 0x134A),
("ointop", 0x1348),
("bigsqcup", 0x1346),
("smallint", 0x1273),
("triangleleft", 0x212F),
("triangleright", 0x212E),
("bigtriangleup", 0x2234),
("bigtriangledown", 0x2235),
("wedge", 0x225E),
("land", 0x225E),
("vee", 0x225F),
("lor", 0x225F),
("cap", 0x225C),
("cup", 0x225B),
("ddagger", 0x227A),
("dagger", 0x2279),
("sqcap", 0x2275),
("sqcup", 0x2274),
("uplus", 0x225D),
("amalg", 0x2271),
("diamond", 0x2205),
("bullet", 0x220F),
("wr", 0x226F),
("div", 0x2204),
("odot", 0x220C),
("oslash", 0x220B),
("otimes", 0x220A),
("ominus", 0x2209),
("oplus", 0x2208),
("mp", 0x2207),
("pm", 0x2206),
("circ", 0x220E),
("bigcirc", 0x220D),
("setminus", 0x226E),
("cdot", 0x2201),
("ast", 0x2203),
("times", 0x2202),
("star", 0x213F),
("propto", 0x322F),
("sqsubseteq", 0x3276),
("sqsupseteq", 0x3277),
("parallel", 0x326B),
("mid", 0x326A),
("dashv", 0x3261),
("vdash", 0x3260),
("nearrow", 0x3225),
("searrow", 0x3226),
("nwarrow", 0x322D),
("swarrow", 0x322E),
("Leftrightarrow", 0x322C),
("Leftarrow", 0x3228),
("Rightarrow", 0x3229),
("leq", 0x3214),
("le", 0x3214),
("geq", 0x3215),
("ge", 0x3215),
("succ", 0x321F),
("prec", 0x321E),
("approx", 0x3219),
("succeq", 0x3217),
("preceq", 0x3216),
("supset", 0x321B),
("subset", 0x321A),
("supseteq", 0x3213),
("subseteq", 0x3212),
("in", 0x3232),
("ni", 0x3233),
("owns", 0x3233),
("gg", 0x321D),
("ll", 0x321C),
("not", 0x3236),
("leftrightarrow", 0x3224),
("leftarrow", 0x3220),
("gets", 0x3220),
("rightarrow", 0x3221),
("to", 0x3221),
("mapstochar", 0x3237),
("sim", 0x3218),
("simeq", 0x3227),
("perp", 0x323F),
("equiv", 0x3211),
("asymp", 0x3210),
("smile", 0x315E),
("frown", 0x315F),
("leftharpoonup", 0x3128),
("leftharpoondown", 0x3129),
("rightharpoonup", 0x312A),
("rightharpoondown", 0x312B),
("lhook", 0x312C),
("rhook", 0x312D),
("ldotp", 0x613A),
("cdotp", 0x6201),
("colon", 0x603A),
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_letter_is_family_one_and_a_digit_family_zero() {
assert_eq!(mathcode('A'), 0x7141);
assert_eq!(mathcode('x'), 0x7178);
assert_eq!(mathcode('0'), 0x7030);
assert_eq!(mathcode('+'), 0x202B);
assert_eq!(mathcode('='), 0x303D);
assert_eq!(mathcode('('), 0x4028);
assert_eq!(mathcode(')'), 0x5029);
assert_eq!(mathcode(','), 0x613B);
}
#[test]
fn a_math_code_unpacks_the_way_section_1155_unpacks_it() {
let x = atom_for_code(mathcode('x')).unwrap();
assert_eq!(x.class(), Class::Ord, "a letter is an Ord, not a class 7");
assert!(matches!(
x.nucleus,
Field::Char(MathChar {
fam: 1,
character: b'x'
})
));
let plus = atom_for_code(mathcode('+')).unwrap();
assert_eq!(plus.class(), Class::Bin);
assert!(matches!(
plus.nucleus,
Field::Char(MathChar {
fam: 0,
character: b'+'
})
));
let sum = atom_for_code(0x1350).unwrap();
assert_eq!(sum.class(), Class::Op);
assert!(matches!(
sum.nucleus,
Field::Char(MathChar {
fam: 3,
character: 0x50
})
));
}
#[test]
fn a_delimiter_code_names_both_variants() {
let d = Delimiter::from_code(0x028300);
assert_eq!((d.small_fam, d.small_char), (0, b'('));
assert_eq!((d.large_fam, d.large_char), (3, 0x00));
let r = Delimiter::from_code(0x270370);
assert_eq!((r.small_fam, r.small_char), (2, 0x70));
assert_eq!((r.large_fam, r.large_char), (3, 0x70));
assert!(Delimiter::null().is_null());
}
}