Files
texrra-engine/crates/texrra-tex-core/src/execution/engine/math.rs
T

932 lines
39 KiB
Rust

use super::super::boxes::{PackSpec, hpack};
use super::super::math::{self, FieldTarget, MathBuilder, MathGroupTarget};
use super::*;
use crate::math_engine_tex::MathStyle;
use crate::provenance::PaintSource;
impl Executor {
pub(super) fn accept_box_math_field(&mut self, b: NativeBox) -> Result<(), Error> {
if self.math.last().unwrap().pending.is_some() {
return self.fail("expected a grouped native math box field");
}
self.new_noad(NoadClass::Ord, MathField::Box(Box::new(b)), self.current);
Ok(())
}
pub(super) fn scan_delimiter_code_index(
&mut self,
files: &mut impl SourceProvider,
) -> Result<u32, Error> {
let maximum = if self.state.input_profile() == InputProfile::XeTeX {
0x10_ffff
} else {
255
};
self.character_number("delcode index", maximum, files)
}
pub(super) fn read_delimiter_code(&mut self, c: u32) -> i32 {
self.reads.insert(match u8::try_from(c) {
Ok(slot) => Dependency::DelCode(slot),
Err(_) => Dependency::UnicodeDelCode(c),
});
self.state.delimiter_code(c)
}
fn scan_extended_delimiter_code(&mut self, files: &mut impl SourceProvider) -> Result<i32, Error> {
let family = self.scan_math_family(files)?;
let slot = self.scan_delimiter_code_index(files)?;
Ok(math::Delimiter::EXTENDED | (i32::from(family) << 21) | slot as i32)
}
pub(super) fn scan_delimiter_code_assignment(
&mut self,
primitive: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let slot = self.scan_delimiter_code_index(files)?;
self.optional_equals(files)?;
let word = if primitive == Primitive::Udelcode {
self.scan_extended_delimiter_code(files)?
} else {
self.integer(files)?
};
if primitive == Primitive::Delcode && word >= 1 << 24 {
return self.fail("delcode must be at most 16777215");
}
let equivalent = self.state.delimiter_code(slot) == word;
self.assign_equivalence(Key::Delcode(slot), global, equivalent, files, |state| {
state.assign_delcode(slot, word, global);
})
}
fn scan_delimiter(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(super::super::math::Delimiter, PaintSource), Error> {
let (code, origin) = loop {
let t = self.expanded_non_space(files)?.token;
match self.meaning(&t) {
Meaning::Primitive(Primitive::Relax) => continue,
Meaning::Primitive(Primitive::Delimiter) => {
let n = self.integer(files)?;
if !(0..1 << 27).contains(&n) {
return self.fail("delimiter must be in 0..134217727");
}
break (n, TokenOrigin::from(&t));
}
Meaning::Primitive(Primitive::Udelimiter) => {
let class = self.integer(files)?;
if !(0..=7).contains(&class) {
return self.fail("Bad math class");
}
break (self.scan_extended_delimiter_code(files)?, TokenOrigin::from(&t));
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
if self.state.input_profile() != InputProfile::XeTeX && c as u32 > 255 {
return Err(self.error("delimiter character must be in 0..255", t.span));
}
break (self.read_delimiter_code(c as u32), TokenOrigin::from(&t));
}
_ => return self.fail("expected native delimiter character or delimiter code"),
}
};
if code < 0 {
return self.fail("missing native delimiter: character has negative delcode");
}
Ok((
super::super::math::Delimiter::from_code(code as u32),
PaintSource::token(origin),
))
}
fn math_delimiter(
&mut self,
command: Primitive,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if command == Primitive::Left {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
}
let left = self.scan_delimiter(files)?;
self.begin_group(GroupKind::MathLeft, files)?;
let mut b = MathBuilder::new(self.state.group_depth(), None, span);
b.left = Some(left);
self.math.push(b);
} else {
let b = self.math.last().unwrap();
if b.left.is_none() || b.depth != self.state.group_depth() {
if command == Primitive::Middle {
return self.fail(r"Extra \middle.");
}
return self.fail("unmatched native right delimiter");
}
let (value, source) = self.scan_delimiter(files)?;
if command == Primitive::Middle {
let b = self.math.last_mut().unwrap();
b.finish_segment();
b.nodes.push(MathNode::MiddleDelimiter { value, source });
// Middle ends the current delimiter group and starts another.
// The math list survives, while local assignments and delayed
// tokens follow the ordinary rules for closing a group.
self.finish_group(GroupKind::MathLeft, span, files)?;
self.begin_group(GroupKind::MathLeft, files)?;
return Ok(());
}
let b = self.math.pop().unwrap();
let span = b.span;
let mut nodes = b.finish();
nodes.push(MathNode::Delimiter {
value,
opening: false,
source,
});
self.finish_group(GroupKind::MathLeft, span, files)?;
self.new_noad(NoadClass::Inner, MathField::List(nodes), span);
}
Ok(())
}
pub(super) fn math_font_assignment(
&mut self,
p: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let family = self.scan_math_family(files)?;
self.optional_equals(files)?;
let font = self.font_identifier(files)?;
let size = match p {
Primitive::Textfont => 0,
Primitive::Scriptfont => 1,
_ => 2,
};
let equivalent = self.state.math_font(size, family) == font;
self.assign_equivalence(
Key::Mathfont(size, family),
global,
equivalent,
files,
|state| {
state.assign_mathfont(size, family, font, global);
},
)?;
Ok(())
}
fn math_code_char(
&mut self,
c: u32,
token: &Token,
) -> Result<Option<(NoadClass, MathChar)>, Error> {
let code = self.read_math_code(c);
if code.is_active() {
let c = self.scalar_character(c, token.span)?;
let mut t = token.clone();
t.kind = TokenKind::Command(CommandName::Active(c));
self.unread(t.into())?;
return Ok(None);
}
Ok(Some(self.decode_math_code(code)))
}
fn decode_math_char(&mut self, code: u16) -> (NoadClass, MathChar) {
self.decode_math_code(MathCode::from_legacy(code))
}
fn decode_math_code(&mut self, code: MathCode) -> (NoadClass, MathChar) {
let class = code.class();
let mut family = code.family();
if class == 7 {
let current = self.read_parameter(Parameter::Fam).width();
if (0..self.state.math_family_count()).contains(&current) {
family = current as u8;
}
}
if family >= 16 {
for size in 0..3 {
self.reads.insert(Dependency::MathFamily { size, family });
}
}
(
NoadClass::from_code(if class == 7 { 0 } else { class }),
MathChar { family, slot: code.slot() },
)
}
fn explicit_math_code(&mut self, code: MathCode) -> Result<(NoadClass, MathChar), Error> {
if code.is_active() {
return self.fail("active math code requires a character table entry");
}
Ok(self.decode_math_code(code))
}
pub(super) fn start_math(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
// vmode math_shift first starts an indented paragraph in TeX.
if self.paragraph.is_none() {
self.begin_paragraph(token.span, true)?;
}
// init_math peeks raw, so ifmmode immediately after $ sees math mode.
let next = self.raw(files)?;
if !self.restricted()
&& next.as_ref().is_some_and(|t| {
matches!(
self.meaning(&t.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
)
})
{
return self.start_display(token.span, files);
};
if let Some(t) = next {
self.unread(t)?;
}
self.finish_text(true)?;
self.begin_group(GroupKind::MathShift, files)?;
self.assign_traced_parameter(Parameter::Fam, ParameterValue::Integer(-1), false, files)?;
self.math
.push(MathBuilder::new(self.state.group_depth(), None, token.span));
self.push_mode_hook(TokenParameter::Everymath)
}
fn new_noad(&mut self, class: NoadClass, nucleus: MathField, span: Span) {
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Noad(Noad {
source: NoadSource::default(),
class,
limits: OperatorLimits::Display,
accent: None,
accent_style: AccentStyle::default(),
rule: None,
vcenter: false,
nucleus,
sub: None,
sup: None,
span,
}));
}
fn accept_math_field(&mut self, value: MathField, class: NoadClass, origin: TokenOrigin) {
let source = FieldSource::token(origin);
let b = self.math.last_mut().unwrap();
if let Some(target) = b.pending.take() {
math::put_field(&mut b.nodes, target, value, source)
} else {
self.new_noad(class, value, origin.span);
let Some(MathNode::Noad(n)) = self.math.last_mut().unwrap().nodes.last_mut() else {
unreachable!()
};
n.source.nucleus = source;
}
}
fn math_group(&mut self, span: Span, files: &mut impl SourceProvider) -> Result<(), Error> {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
};
let target = if let Some(p) = self.math.last_mut().unwrap().pending.take() {
p
} else {
self.new_noad(NoadClass::Ord, MathField::Empty, span);
FieldTarget::Nucleus(self.math.last().unwrap().nodes.len() - 1)
};
self.begin_group(GroupKind::MathGroup, files)?;
self.math.push(MathBuilder::new(
self.state.group_depth(),
Some(MathGroupTarget::Field(target)),
span,
));
Ok(())
}
fn start_math_choice(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let parent = self.math.last_mut().unwrap();
let node = parent.nodes.len();
parent.nodes.push(MathNode::Choice(Box::default()));
self.open_math_choice_branch(node, 0, span, files)
}
fn open_math_choice_branch(
&mut self,
node: usize,
branch: usize,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
}
self.begin_group(GroupKind::MathChoice, files)?;
self.math.push(MathBuilder::new(
self.state.group_depth(),
Some(MathGroupTarget::Choice { node, branch }),
span,
));
loop {
let open = self.expanded_non_space(files)?;
let meaning = self.meaning(&open.token);
if matches!(meaning, Meaning::Primitive(Primitive::Relax))
|| Self::suppresses_meaning(&open, &meaning)
{
continue;
}
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return Ok(());
}
return self.fail("expected opening brace for native math choice");
}
}
fn close_math_group(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let b = self.math.last().unwrap();
let Some(target) = b.target else {
return self.fail("unbalanced native math group");
};
if self.state.group_depth() != b.depth || b.left.is_some() {
return self.fail("unbalanced native math group");
}
if b.pending.is_some() {
return self.fail("missing native math field");
}
match target {
MathGroupTarget::Field(target) => {
let b = self.math.pop().unwrap();
let (value, source) = math::field(b.finish());
self.finish_group(GroupKind::MathGroup, span, files)?;
math::put_field(
&mut self.math.last_mut().unwrap().nodes,
target,
value,
source,
);
}
MathGroupTarget::Choice { node, branch } => {
self.finish_group(GroupKind::MathChoice, span, files)?;
let b = self.math.pop().unwrap();
let origin = b.span;
let MathNode::Choice(branches) = &mut self.math.last_mut().unwrap().nodes[node]
else {
unreachable!("math choice stays owned by the parent list during scanning");
};
branches[branch] = b.finish();
if branch + 1 < branches.len() {
self.open_math_choice_branch(node, branch + 1, origin, files)?;
}
}
}
Ok(())
}
fn close_math(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let side = self.display.as_ref().and_then(|frame| frame.number_side);
let layers = if side.is_some() { 2 } else { 1 };
if self.math.len() != layers || self.state.group_depth() != self.math[layers - 1].depth {
return self.fail("math shift closes an unfinished native math group");
}
let mut b = self.math.pop().unwrap();
let display = self.display.is_some();
if display {
let close = self.required_expanded(files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
return self.fail("native display math must end with a second math shift");
}
}
let number = if let Some(side) = side {
let tag = self.convert_math(b, MathStyle::Text, false, files)?;
let mut box_ = hpack(
tag.horizontal.clone(),
PackSpec::Natural,
tag.span,
&self.state,
)
.map_err(|e| self.error(e, tag.span))?;
box_.display = true;
self.state.last_badness = box_.badness;
let span = tag.span;
self.events.push(Event::BuiltMath(Box::new(tag)));
self.finish_group(GroupKind::MathShift, span, files)?;
b = self.math.pop().unwrap();
Some(display::EquationNumber { side, box_ })
} else {
None
};
let style = if display {
MathStyle::Display
} else {
MathStyle::Text
};
let enabled = !display && !self.restricted();
let material = self.convert_math(b, style, enabled, files)?;
let span = material.span;
if display {
let horizontal = material.horizontal.clone();
self.events.push(Event::BuiltMath(Box::new(material)));
return self.finish_display(&horizontal, number, span, files);
}
let surround = self.read_parameter(Parameter::Mathsurround).width();
let p = self.paragraph.as_mut().unwrap();
p.nodes.push(TextNode::MathBoundary {
width: surround,
after: false,
});
p.nodes.extend(material.horizontal.iter().cloned());
p.nodes.push(TextNode::MathBoundary {
width: surround,
after: true,
});
p.space_factor = 1000;
self.events.push(Event::BuiltMath(Box::new(material)));
self.finish_group(GroupKind::MathShift, span, files)?;
Ok(())
}
fn convert_math(
&mut self,
b: MathBuilder,
style: MathStyle,
enabled: bool,
files: &mut impl SourceProvider,
) -> Result<NativeMath, Error> {
let span = b.span;
let nodes = b.finish();
self.reads.insert(Dependency::FontResources);
for p in [
Parameter::Delimiterfactor,
Parameter::Delimitershortfall,
Parameter::Nulldelimiterspace,
] {
self.reads.insert(Dependency::Parameter(p));
}
let converter = math::Converter {
state: &self.state,
horizontal_packs: std::cell::Cell::new(0),
last_pack_badness: std::cell::Cell::new(None),
missing: std::cell::RefCell::new(Vec::new()),
current_math_font: std::cell::Cell::new(FontId::NULL),
delimiter_glyphs: std::cell::Cell::new(0),
delimiter_glyph_limit: self.limits.tokens,
steps: std::cell::Cell::new(self.steps),
step_limit: self.limits.steps,
node_limit: self.limits.tokens,
};
converter.validate().map_err(|e| self.error(e, span))?;
let converted = converter.convert(&nodes, style, enabled);
let missing = converter.missing.take();
let horizontal_packs = converter.horizontal_packs.get();
let last_pack_badness = converter.last_pack_badness.get();
self.steps = converter.steps.get();
for (font, slot) in missing {
self.missing_glyph(font, slot, span, files)?;
}
let (horizontal, effective_classes, nodes) = converted.map_err(|e| self.error(e, span))?;
if let Some(badness) = last_pack_badness {
self.state.last_badness = badness;
}
for size in 0..3 {
for family in 0..16 {
self.reads.insert(Dependency::MathFamily { size, family });
}
}
let parameters = Parameter::ALL
.iter()
.map(|p| (*p, self.state.parameter(*p)))
.collect();
Ok(NativeMath {
noads: nodes,
effective_classes,
parameters,
horizontal,
penalties_enabled: enabled,
display: style == MathStyle::Display,
horizontal_packs,
last_pack_badness,
span,
})
}
pub(super) fn math_token(
&mut self,
token: &Token,
meaning: &Meaning,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
use Primitive::*;
self.reads.insert(Dependency::MathState);
if !self.math.is_empty() {
self.math_tokens_processed += 1;
if self.math_tokens_processed > self.limits.tokens {
return self.fail("native math token/list capacity exceeded");
}
}
if self.math.is_empty() {
if matches!(meaning, Meaning::Primitive(Eqno | Leqno)) {
return self.fail("native equation number requires outer display math");
}
if matches!(meaning, Meaning::Primitive(Mathchoice)) {
return self.fail("native math choice requires math mode");
}
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
self.start_math(token, files)?;
return Ok(true);
}
return Ok(false);
}
if self.math.last().unwrap().pending.is_some() {
match meaning {
Meaning::Character(TokenKind::Character(_, CatCode::Space))
| Meaning::Primitive(Relax) => return Ok(true),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup)) => {
self.math_group(token.span, files)?;
return Ok(true);
}
Meaning::Character(TokenKind::Character(_, CatCode::Letter | CatCode::Other))
| Meaning::CharGiven(_)
| Meaning::MathCharGiven(_)
| Meaning::UnicodeMathCharGiven(_)
| Meaning::Primitive(Mathchar | Umathchar | Umathcharnum | Char | Delimiter) => {}
_ => return self.fail("expected a native math field character or group"),
}
}
match meaning {
Meaning::Character(TokenKind::Character(c, code)) => match code {
CatCode::MathShift => self.close_math(files)?,
CatCode::Space => {}
CatCode::BeginGroup => self.math_group(token.span, files)?,
CatCode::EndGroup => self.close_math_group(token.span, files)?,
CatCode::Superscript | CatCode::Subscript => {
let b = self.math.last_mut().unwrap();
if !matches!(b.nodes.last(), Some(MathNode::Noad(_))) {
self.new_noad(NoadClass::Ord, MathField::Empty, token.span)
}
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &b.nodes[i] else {
unreachable!()
};
let sup = *code == CatCode::Superscript;
if if sup {
n.sup.is_some()
} else {
n.sub.is_some()
} {
return self.fail("double native math script");
};
b.pending = Some(if sup {
FieldTarget::Sup(i)
} else {
FieldTarget::Sub(i)
});
}
CatCode::Letter | CatCode::Other => {
if let Some((class, c)) = self.math_code_char(*c as u32, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
_ => return self.fail("unsupported native math category"),
},
Meaning::CharGiven(c) => {
if let Some((class, c)) = self.math_code_char(*c, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
Meaning::MathCharGiven(code) => {
let (class, c) = self.decode_math_char(*code);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
Meaning::UnicodeMathCharGiven(code) => {
let (class, c) = self.explicit_math_code(*code)?;
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
}
Meaning::Primitive(p) => match p {
Halign => self.start_alignment(*p, token.span, files)?,
Mathchoice => self.start_math_choice(token.span, files)?,
Eqno | Leqno => self.start_equation_number(
if *p == Eqno {
display::EquationSide::Right
} else {
display::EquationSide::Left
},
token.span,
files,
)?,
Vcenter => self.box_command(*p, boxes::Destination::Append, token.span, files)?,
Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise
| Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout
| Ignorespaces | Unskip | Unkern | Unpenalty => {
return Ok(false);
}
Unhbox | Unhcopy => {
self.unpackage(*p, files)?;
}
Vrule => {
let r = self.scan_rule(false, TokenOrigin::from(token), files)?;
self.math.last_mut().unwrap().nodes.push(MathNode::Rule(r));
}
Left | Middle | Right => self.math_delimiter(*p, token.span, files)?,
Umathchar | Umathcharnum | Udelimiter => {
let code = self.scan_unicode_math_code(*p != Umathcharnum, files)?;
let (class, c) = self.explicit_math_code(code)?;
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
}
Mathchar | Char | Delimiter => {
if *p == Char {
let c = self.character_number("char", 0xFFFF, files)?;
if let Some((class, c)) = self.math_code_char(c, token)? {
self.accept_math_field(
MathField::Char(c),
class,
TokenOrigin::from(token),
)
}
} else if *p == Delimiter {
let n = self.integer(files)?;
if !(0..1 << 27).contains(&n) {
return self.fail("delimiter must be in 0..134217727");
}
let (class, c) = self.decode_math_char((n >> 12) as u16);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
} else {
let n = self.integer(files)?;
if !(0..32768).contains(&n) {
return self.fail("mathchar must be in 0..32767");
};
let (class, c) = self.decode_math_char(n as u16);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
Mathord | Mathop | Mathbin | Mathrel | Mathopen | Mathclose | Mathpunct
| Mathinner => {
let class = match p {
Mathord => 0,
Mathop => 1,
Mathbin => 2,
Mathrel => 3,
Mathopen => 4,
Mathclose => 5,
Mathpunct => 6,
_ => 7,
};
self.new_noad(NoadClass::from_code(class), MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
b.pending = Some(FieldTarget::Nucleus(b.nodes.len() - 1));
}
Radical | Uradical => {
let code = if *p == Uradical {
self.scan_extended_delimiter_code(files)?
} else {
let code = self.integer(files)?;
if !(0..1 << 27).contains(&code) {
return self.fail("radical must be in 0..134217727");
}
code
};
let delimiter = math::Delimiter::from_code(code as u32);
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let builder = self.math.last_mut().unwrap();
let Some(MathNode::Noad(n)) = builder.nodes.last_mut() else {
unreachable!()
};
n.source.operator = PaintSource::token(TokenOrigin::from(token));
builder.pending =
Some(FieldTarget::Radical(builder.nodes.len() - 1, delimiter));
}
Overline | Underline => {
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &mut b.nodes[i] else {
unreachable!()
};
n.rule = Some(if *p == Overline {
MathRulePosition::Over
} else {
MathRulePosition::Under
});
n.source.operator = PaintSource::token(TokenOrigin::from(token));
b.pending = Some(FieldTarget::Nucleus(i));
}
Mathaccent | Umathaccent => {
let (accent, accent_style) = if *p == Umathaccent {
let mode = if self.keyword("fixed", files)? {
AccentStyle::Fixed
} else if self.keyword("bottom", files)? {
if self.keyword("fixed", files)? {
AccentStyle::BottomFixed
} else {
AccentStyle::Bottom
}
} else {
AccentStyle::Top
};
let code = self.scan_unicode_math_code(true, files)?;
(self.explicit_math_code(code)?.1, mode)
} else {
let code = self.integer(files)?;
if !(0..32768).contains(&code) {
return self.fail("mathaccent must be in 0..32767");
}
(self.decode_math_char(code as u16).1, AccentStyle::Top)
};
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &mut b.nodes[i] else {
unreachable!()
};
n.accent = Some(accent);
n.accent_style = accent_style;
n.source.operator = PaintSource::token(TokenOrigin::from(token));
b.pending = Some(FieldTarget::Nucleus(i));
}
Limits | Nolimits | Displaylimits => {
let Some(MathNode::Noad(n)) = self.math.last_mut().unwrap().nodes.last_mut()
else {
return self.fail("native limits switch requires an operator noad");
};
if n.class != NoadClass::Op {
return self.fail("native limits switch requires an operator noad");
}
n.limits = match p {
Limits => OperatorLimits::AboveBelow,
Nolimits => OperatorLimits::Side,
_ => OperatorLimits::Display,
};
}
Displaystyle | Textstyle | Scriptstyle | Scriptscriptstyle => self
.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Style(match p {
Displaystyle => MathStyle::Display,
Textstyle => MathStyle::Text,
Scriptstyle => MathStyle::Script,
_ => MathStyle::ScriptScript,
})),
Explicitspace => {
let space = match self.explicit_space(None)? {
TextNode::NamedGlue(glue, parameter) => {
MathNode::ExplicitSpace(glue, Some(parameter))
}
TextNode::Glue(glue) => MathNode::ExplicitSpace(glue, None),
_ => unreachable!(),
};
self.math.last_mut().unwrap().nodes.push(space);
}
Hskip | Hfil | Hfill | Hss | Hfilneg => {
let g = self.skip_glue(*p, files)?;
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::ExplicitSpace(g, None));
}
Leaders | Cleaders | Xleaders => self.scan_leaders(*p, files)?,
Nonscript => {
self.math.last_mut().unwrap().nodes.push(MathNode::ConditionalMathGlue);
}
Mskip => {
let g = self.skip_glue(*p, files)?;
self.math.last_mut().unwrap().nodes.push(MathNode::Glue(g));
}
Mkern | Kern => {
let n = self.dimension(*p == Mkern, false, files)?.amount;
self.math.last_mut().unwrap().nodes.push(MathNode::Kern {
amount: n,
mu: *p == Mkern,
explicit: true,
})
}
ItalicCorrection => {
self.math.last_mut().unwrap().nodes.push(MathNode::Kern {
amount: 0,
mu: false,
explicit: false,
});
}
Penalty => {
let n = self.integer(files)?;
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Penalty(n));
}
Over | Atop | Above | Overwithdelims | Atopwithdelims | Abovewithdelims => {
let b = self.math.last_mut().unwrap();
let ambiguous = b.numerator.is_some();
// Own the suspended numerator before scanning delimiter/dimension
// input, so a real scanner error or cancellation retains it.
if !ambiguous {
b.numerator = Some(math::PendingFraction {
numerator: std::mem::take(&mut b.nodes),
specification: FractionSpec::default(),
origin: TokenOrigin::from(token),
});
}
if matches!(p, Overwithdelims | Atopwithdelims | Abovewithdelims) {
let (left, source) = self.scan_delimiter(files)?;
if !ambiguous {
let spec = &mut self
.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification;
spec.left = left;
spec.left_source = source;
}
let (right, source) = self.scan_delimiter(files)?;
if !ambiguous {
let spec = &mut self
.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification;
spec.right = right;
spec.right_source = source;
}
}
let thickness = match p {
Above | Abovewithdelims => {
Some(self.dimension(false, false, files)?.amount)
}
Atop | Atopwithdelims => Some(0),
_ => None,
};
if ambiguous {
return self.fail("ambiguous native generalized fraction");
}
self.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification
.thickness = thickness;
}
Noboundary => {}
Global | Long | Outer | Protected | Def | Gdef | Edef | Xdef | Let | Futurelet
| Afterassignment | Aftergroup | Immediate | Chardef | Mathchardef
| Umathchardef | Umathcharnumdef | Catcode
| Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode
| Umathcode | Umathcodenum
| Delcode | Udelcode | Udelcodenum | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand | Pdfnoligatures | Tagcode
| Knbccode | Knaccode | Letterspacefont | Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | DeferredPrimitive | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Showtokens | Showlists | Showifs | Showgroups
| Discretionary | DiscretionaryHyphen
| Parshape | LinePenalties(_) | Partokenname => {
return Ok(false);
}
_ if self.execute_output_extension(*p, token, files)? => {}
_ => return self.fail(format!("unsupported native math primitive: {p:?}")),
},
Meaning::Count(_)
| Meaning::Toks(_)
| Meaning::TokenParameter(_)
| Meaning::Register(_)
| Meaning::Parameter(_)
| Meaning::Font(_) => return Ok(false),
Meaning::Undefined => return Ok(false),
_ => return self.fail("unsupported native math meaning"),
}
if self
.math
.iter()
.map(|b| b.nodes.len() + b.numerator.as_ref().map_or(0, |n| n.numerator.len()))
.sum::<usize>()
> self.limits.tokens
{
return self.fail("native math node capacity exceeded");
}
Ok(true)
}
}