//! Owned token-derived noads and math-to-horizontal conversion. No text parser. use super::*; use crate::provenance::{Derivation, PaintSource}; use crate::{ HorizontalBox, math::MathBox, math_engine_tex::{MathGeometry, MathItem, MathParams, MathStyle, PositionedItem}, math_font::MathFontId, }; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[repr(u8)] pub enum NoadClass { Ord, Op, Bin, Rel, Open, Close, Punct, Inner, } impl NoadClass { pub(super) fn from_code(c: u8) -> Self { [ Self::Ord, Self::Op, Self::Bin, Self::Rel, Self::Open, Self::Close, Self::Punct, Self::Inner, ][c as usize] } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MathChar { pub family: u8, pub slot: u8, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Delimiter { pub small: MathChar, pub large: MathChar, } /// None selects the live extension font's default rule thickness at conversion. /// Explicit dimensions, including zero and negative values, remain distinct. #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct FractionSpec { pub thickness: Option, pub left: Delimiter, pub right: Delimiter, pub left_source: PaintSource, pub right_source: PaintSource, } impl Default for FractionSpec { fn default() -> Self { Self { thickness: None, left: Delimiter::from_code(0), right: Delimiter::from_code(0), left_source: PaintSource::default(), right_source: PaintSource::default(), } } } impl Delimiter { pub(super) fn from_code(code: u32) -> Self { Self { small: MathChar { family: ((code >> 20) & 15) as u8, slot: (code >> 12) as u8, }, large: MathChar { family: ((code >> 8) & 15) as u8, slot: code as u8, }, } } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathField { Empty, Char(MathChar), /// A make_ord character whose italic correction depends on font space. TextChar(MathChar), List(Vec), Box(Box), Radical(Delimiter, Box), } /// Provenance follows fields without changing TeX's character addresses or /// field kinds. Lists/boxes retain their children's sources; a radical has an /// operator source and an independently sourced operand. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct FieldSource { pub paint: PaintSource, pub radical: Option>, } impl FieldSource { pub const UNKNOWN: Self = Self { paint: PaintSource { tokens: Vec::new(), derivations: Vec::new(), }, radical: None, }; pub fn paint(paint: PaintSource) -> Self { Self { paint, radical: None, } } pub fn token(origin: TokenOrigin) -> Self { Self::paint(PaintSource::token(origin)) } } #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct NoadSource { pub nucleus: FieldSource, pub sub: FieldSource, pub sup: FieldSource, pub operator: PaintSource, } #[derive( Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, )] pub enum OperatorLimits { #[default] Display, AboveBelow, Side, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathRulePosition { Over, Under, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Noad { pub source: NoadSource, pub class: NoadClass, pub limits: OperatorLimits, pub accent: Option, pub rule: Option, /// A vcenter noad retains its natural vertical box until math conversion, /// when the current style selects the symbol font's mathematical axis. pub vcenter: bool, pub nucleus: MathField, pub sub: Option, pub sup: Option, pub span: Span, } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum MathNode { Noad(Noad), Delimiter { value: Delimiter, opening: bool, source: PaintSource, }, Style(MathStyle), /// Display, text, script, and scriptscript lists, in scanning order. Choice(Box<[Vec; 4]>), Glue(Glue), /// Normal-unit glue, including explicit spaces and horizontal skip commands. ExplicitSpace(Glue, Option), Leaders(LeaderGlue), Kern { amount: i32, mu: bool, explicit: bool, }, Penalty(i32), Discretionary(Box), Rule(NativeRule), Mark(NativeMark), Adjustment(NativeAdjustment), Insertion(NativeInsertion), Output(OutputNode), Fraction { numerator: Vec, denominator: Vec, specification: FractionSpec, span: Span, source: PaintSource, }, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NativeMath { pub noads: Vec, pub effective_classes: Vec>, pub parameters: std::collections::BTreeMap, pub horizontal: Vec, pub penalties_enabled: bool, pub display: bool, pub horizontal_packs: usize, pub last_pack_badness: Option, pub span: Span, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct NativeDisplay { pub parameters: std::collections::BTreeMap, pub box_: NativeBox, pub short_skips: bool, pub previous_lines: usize, pub span: Span, } #[derive(Clone, Copy, Debug)] pub(super) enum FieldTarget { Nucleus(usize), Radical(usize, Delimiter), Sub(usize), Sup(usize), } #[derive(Clone, Copy, Debug)] pub(super) enum MathGroupTarget { Field(FieldTarget), Choice { node: usize, branch: usize }, } #[derive(Clone)] pub(super) struct MathBuilder { pub nodes: Vec, pub numerator: Option, pub pending: Option, pub depth: usize, pub target: Option, pub left: Option<(Delimiter, PaintSource)>, pub span: Span, } #[derive(Clone)] pub(super) struct PendingFraction { pub numerator: Vec, pub specification: FractionSpec, pub origin: TokenOrigin, } impl MathBuilder { pub fn new(depth: usize, target: Option, span: Span) -> Self { Self { nodes: Vec::new(), numerator: None, pending: None, depth, target, left: None, span, } } pub fn finish(self) -> Vec { let mut nodes = if let Some(fraction) = self.numerator { vec![MathNode::Fraction { numerator: fraction.numerator, denominator: self.nodes, specification: fraction.specification, span: fraction.origin.span, source: PaintSource::token(fraction.origin).derived(Derivation::Fraction), }] } else { self.nodes }; if let Some((value, source)) = self.left { nodes.insert( 0, MathNode::Delimiter { value, opening: true, source, }, ); } nodes } } pub(super) fn field(mut nodes: Vec) -> (MathField, FieldSource) { if nodes.len() == 1 && let MathNode::Noad(n) = &nodes[0] && n.class == NoadClass::Ord && n.accent.is_none() && n.rule.is_none() && !n.vcenter && n.sub.is_none() && n.sup.is_none() && !matches!(n.nucleus, MathField::Radical(..)) { let Some(MathNode::Noad(n)) = nodes.pop() else { unreachable!(); }; return (n.nucleus, n.source.nucleus); } (MathField::List(nodes), FieldSource::default()) } pub(super) fn put_field( nodes: &mut [MathNode], target: FieldTarget, mut value: MathField, mut source: FieldSource, ) { let (i, part) = match target { FieldTarget::Nucleus(i) => (i, 0), FieldTarget::Sub(i) => (i, 1), FieldTarget::Sup(i) => (i, 2), FieldTarget::Radical(i, _) => (i, 0), }; let MathNode::Noad(n) = &mut nodes[i] else { unreachable!() }; if let FieldTarget::Radical(_, delimiter) = target { value = MathField::Radical(delimiter, Box::new(value)); source = FieldSource { paint: n.source.operator.clone().derived(Derivation::Radical), radical: Some(Box::new(source)), }; } match part { 0 => { n.nucleus = value; n.source.nucleus = source; } 1 => { n.sub = Some(value); n.source.sub = source; } _ => { n.sup = Some(value); n.source.sup = source; } } } fn class(n: &MathNode) -> Option { match n { MathNode::Noad(n) => Some(n.class), MathNode::Fraction { .. } => Some(NoadClass::Ord), MathNode::Delimiter { opening, .. } => Some(if *opening { NoadClass::Open } else { NoadClass::Close }), _ => None, } } pub(super) struct Converter<'a> { pub state: &'a State, pub horizontal_packs: std::cell::Cell, pub last_pack_badness: std::cell::Cell>, pub missing: std::cell::RefCell>, pub delimiter_glyphs: std::cell::Cell, pub delimiter_glyph_limit: usize, pub steps: std::cell::Cell, pub step_limit: usize, pub node_limit: usize, } impl Converter<'_> { pub(super) fn font( &self, family: u8, style: MathStyle, ) -> Result<&std::sync::Arc, String> { let id = self.state.math_font(style.size_index() as u8, family); self.state.fonts.glyph_font(id).map_err(|_| { format!( "native math family {family} size {} is nullfont", style.size_index() ) }) } pub fn validate(&self) -> Result<(), String> { for s in [MathStyle::Text, MathStyle::Script, MathStyle::ScriptScript] { if self .state .fonts .font(self.font(2, s)?.id)? .parameters() .len() < 22 || self .state .fonts .font(self.font(3, s)?.id)? .parameters() .len() < 13 { return Err("insufficient native symbol/extension font parameters".into()); } } Ok(()) } pub(super) fn params(&self, style: MathStyle) -> Result { let symbol = self.state.fonts.font(self.font(2, style)?.id)?.parameters(); let extension = self.state.fonts.font(self.font(3, style)?.id)?.parameters(); Ok(MathParams::from_parameters( |n| i64::from(symbol[n]), |n| i64::from(extension[n]), )) } pub(super) fn glyph( &self, c: MathChar, style: MathStyle, source: &PaintSource, ) -> Result<(MathGeometry, i64), String> { let id = self.font(c.family, style)?; let f = id.metrics(); let slot = char::from(c.slot); let font = self.state.math_font(style.size_index() as u8, c.family); if !self.state.font_has_slot(font, c.slot) { self.missing.borrow_mut().push((font, c.slot)); return Ok((MathGeometry::default(), 0)); } let italic = f.italic(slot); Ok(( MathGeometry { metrics: MathBox { width: f.width(slot) + italic, height: f.height(slot), depth: f.depth(slot), }, items: vec![PositionedItem { source: source.clone(), x: 0, y: 0, item: MathItem::NativeGlyph { character: char::from(c.slot), font: id.clone(), slot: c.slot, size: id.size_sp(), }, }], }, italic, )) } pub(super) fn measure(&self, nodes: &[TextNode]) -> Result { let b = super::boxes::hpack( nodes.to_vec(), super::boxes::PackSpec::Natural, Span::default(), self.state, )?; self.horizontal_packs.set(self.horizontal_packs.get() + 1); self.last_pack_badness.set(Some(b.badness)); Ok(b) } pub(super) fn clean(&self, nodes: &[TextNode]) -> Result { let b = self.measure(nodes)?; if b.contains_output()? { return Err("deferred output in flattened native math fields requires retained semantic math boxes".into()); } b.geometry() } pub(super) fn field( &self, field: &MathField, style: MathStyle, source: &FieldSource, ) -> Result { match field { MathField::Empty => Ok(MathGeometry::default()), MathField::Radical(delimiter, nucleus) => { self.radical(*delimiter, nucleus, style, source) } MathField::Char(c) | MathField::TextChar(c) => { let (g, _) = self.glyph(*c, style, &source.paint)?; self.clean(&[TextNode::Box(math_box(g))]) } MathField::Box(b) => { if b.contains_output()? { return Err("deferred output in flattened native math fields requires retained semantic math boxes".into()); } if b.shift == 0 { b.geometry() } else { self.clean(&[TextNode::Box((**b).clone().horizontal_item())]) } } MathField::List(nodes) => { let (out, _, _) = self.convert(nodes, style, false)?; self.clean(&out) } } } pub(super) fn noad( &self, n: &Noad, style: MathStyle, suppress_italic: bool, ) -> Result { if n.accent.is_some() { return self.accent(n, style); } if n.class == NoadClass::Op { return self.operator(n, style); } let (mut body, italic) = if let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { self.glyph(c, style, &n.source.nucleus.paint)? } else { (self.field(&n.nucleus, style, &n.source.nucleus)?, 0) }; if suppress_italic { body.metrics.width -= italic; } Ok(body) } fn mu(&self, n: i32, style: MathStyle) -> Result { let m = self.params(style)?.quad; let whole = m / 18; // TeX cur_mu truncates quad/18 before fixed-point math_glue. i32::try_from(n as i64 * whole / 65536).map_err(|_| "native mu dimension overflow".into()) } fn glue(&self, g: Glue, style: MathStyle) -> Result { Ok(Glue { canonical_zero: false, width: self.mu(g.width, style)?, stretch: Flex { amount: if g.stretch.order == 0 { self.mu(g.stretch.amount, style)? } else { g.stretch.amount }, order: g.stretch.order, }, shrink: Flex { amount: if g.shrink.order == 0 { self.mu(g.shrink.amount, style)? } else { g.shrink.amount }, order: g.shrink.order, }, }) } fn translate_noad(&self, original: &Noad, style: MathStyle) -> Result, String> { let mut n = original.clone(); if let Some(position) = n.rule.take() { n.nucleus = MathField::Box(Box::new(self.rule_noad(&n, position, style)?)); } if n.vcenter { let MathField::Box(b) = &mut n.nucleus else { return Err("native vcenter noad requires an owned vertical box".into()); }; if b.kind != BoxKind::Vertical { return Err("native vcenter nucleus must be a vertical box".into()); } let extent = b.height + b.depth; b.height = self.params(style)?.axis_height + (extent + 1).div_euclid(2); b.depth = extent - b.height; } // A missing accent leaves an ordinary fetched nucleus, // including its character/trailing-kern visibility. if let Some(accent) = n.accent { self.font(accent.family, style)?; let font = self .state .math_font(style.size_index() as u8, accent.family); if !self.state.font_has_slot(font, accent.slot) { self.missing.borrow_mut().push((font, accent.slot)); n.accent = None; } } // fetch clears a nonexistent nucleus; scripts still execute. if n.accent.is_none() && n.class != NoadClass::Op && let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { let _ = self.font(c.family, style)?; let font = self.state.math_font(style.size_index() as u8, c.family); if !self.state.font_has_slot(font, c.slot) { self.missing.borrow_mut().push((font, c.slot)); n.nucleus = MathField::Empty; } } let n = &n; if n.class == NoadClass::Op && n.accent.is_none() { let nodes = self.operator_nodes(n, style)?; self.measure(&nodes)?; return Ok(nodes); } let suppress = if let MathField::TextChar(c) = n.nucleus { self.state .fonts .font(self.font(c.family, style)?.id)? .space() .width != 0 } else { false }; if n.class != NoadClass::Op && n.accent.is_none() && (n.sub.is_some() || n.sup.is_some()) { let nodes = self.script_noad(n, style, suppress, 0)?; // This is only the first-pass extent check. The returned owned // nodes keep deferred effects; no geometry replaces their boxes. self.measure(&nodes)?; return Ok(nodes); } if n.class != NoadClass::Op && n.accent.is_none() && n.sub.is_none() && n.sup.is_none() { if let MathField::Box(b) = &n.nucleus { let nodes = vec![TextNode::Box((**b).clone().horizontal_item())]; self.measure(&nodes)?; return Ok(nodes); } if let MathField::List(list) = &n.nucleus { // A sub-mlist nucleus is hpacked as an owned list. This differs // from clean_box's single-box optimization for script fields. let material = self.convert(list, style, false)?.0; let b = self.measure(&material)?; let nodes = vec![TextNode::Box(b.horizontal_item())]; self.measure(&nodes)?; return Ok(nodes); } } let mut g = self.noad(n, style, suppress)?; let mut noad_nodes = Vec::new(); if n.class != NoadClass::Op && n.accent.is_none() && n.sub.is_none() && n.sup.is_none() && let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { let italic = g.metrics.width - self .font(c.family, style)? .metrics() .width(char::from(c.slot)); g.metrics.width -= italic; noad_nodes.push(TextNode::MathChar(math_box(g))); if italic != 0 { noad_nodes.push(TextNode::Kern { width: italic as i32, explicit: false, }); } } else if !matches!(n.nucleus, MathField::Empty) || n.sub.is_some() || n.sup.is_some() { noad_nodes.push(TextNode::Box(math_box(g))); } // The first-pass extent check packs the translated noad. // Preserve a character and its trailing italic kern as // separate semantic nodes for pre_display_size scanning. self.clean(&noad_nodes)?; Ok(noad_nodes) } pub fn convert( &self, nodes: &[MathNode], mut style: MathStyle, penalties: bool, ) -> Result<(Vec, Vec>, Vec), String> { use NoadClass::*; let original_style = style; let mut pending: std::collections::VecDeque<_> = nodes.to_vec().into(); let mut prepared: Vec = Vec::new(); let mut translated = Vec::new(); let mut previous = None; // First pass follows the actual mutable mlist. Rendering each noad // here preserves fetch/missing-character and recursive pack order. while let Some(mut node) = pending.pop_front() { if let MathNode::Choice(mut branches) = node { let selected = std::mem::take(&mut branches[usize::from(style as u8 / 2)]); for item in selected.into_iter().rev() { pending.push_front(item); } // TeX splices the choice into this list. An explicit style in // the selected branch can therefore affect later parent nodes. node = MathNode::Style(style); } if let MathNode::Style(s) = &node { style = *s; } let prior = previous.and_then(|i| prepared.get(i)).and_then(class); if let MathNode::Noad(n) = &mut node { if n.class == Bin && prior.is_none_or(|p| matches!(p, Bin | Op | Rel | Open | Punct)) { n.class = Ord; } } if matches!(class(&node), Some(Rel | Close | Punct)) && prior == Some(Bin) { if let Some(MathNode::Noad(n)) = previous.and_then(|i| prepared.get_mut(i)) { n.class = Ord; } } if let MathNode::Noad(n) = &mut node { if n.class == Ord && n.accent.is_none() && n.rule.is_none() { self.make_ord(n, &mut pending, prepared.len(), style)?; } } let list = match &node { MathNode::Noad(n) => self.translate_noad(n, style)?, MathNode::Delimiter { .. } => vec![TextNode::Box(HorizontalBox::default())], MathNode::Fraction { numerator, denominator, specification, span, source, } => { let node = TextNode::Box( self.fraction(numerator, denominator, specification, style, *span, source)? .horizontal_item(), ); self.measure(std::slice::from_ref(&node))?; vec![node] } MathNode::ExplicitSpace(glue, parameter) => vec![match parameter { Some(parameter) => TextNode::NamedGlue(*glue, *parameter), None => TextNode::Glue(*glue), }], MathNode::Leaders(leader) => vec![TextNode::Leaders(leader.clone())], MathNode::Glue(g) => vec![TextNode::Glue(self.glue(*g, style)?)], MathNode::Kern { amount, mu, explicit, } => vec![TextNode::Kern { width: if *mu { self.mu(*amount, style)? } else { *amount }, explicit: *explicit, }], MathNode::Penalty(n) => vec![TextNode::Penalty(*n)], MathNode::Discretionary(n) => vec![*n.clone()], MathNode::Rule(r) => vec![TextNode::Rule(*r)], MathNode::Mark(m) => vec![TextNode::Mark(m.clone())], MathNode::Adjustment(adjustment) => vec![TextNode::Adjustment(adjustment.clone())], MathNode::Insertion(insertion) => vec![TextNode::Insertion(insertion.clone())], MathNode::Output(n) => vec![TextNode::Output(n.clone())], MathNode::Style(_) => Vec::new(), MathNode::Choice(_) => unreachable!("choice was spliced before conversion"), }; if class(&node).is_some() { previous = Some(prepared.len()); } prepared.push(node); translated.push(list); } if let Some(MathNode::Noad(n)) = previous.and_then(|i| prepared.get_mut(i)) { if n.class == Bin { n.class = Ord; } } let cls: Vec<_> = prepared.iter().map(class).collect(); style = original_style; previous = None; let mut delimiters = Vec::new(); let mut out = Vec::new(); // Second pass consumes the classes and translated lists that survived // make_ord. Collapsed relation/bin noads cannot leave stale glue. for (i, node) in prepared.iter().enumerate() { if let MathNode::Style(s) = node { style = *s; continue; } if let Some(current) = cls[i] { if let Some(left) = previous { let level = b"0234000122*4000133**3**344*0400400*000000234000111*1111112341011" [left as usize * 8 + current as usize]; let parameter = match level { b'2' => Some(Parameter::Thinmuskip), b'1' if style.size_index() == 0 => Some(Parameter::Thinmuskip), b'3' if style.size_index() == 0 => Some(Parameter::Medmuskip), b'4' if style.size_index() == 0 => Some(Parameter::Thickmuskip), _ => None, }; if let Some(p) = parameter { let ParameterValue::Quantity(RegisterValue::Glue(g)) = self.state.parameter(p) else { unreachable!() }; out.push(TextNode::NamedGlue(self.glue(g, style)?, p)); } } previous = Some(current as usize); } if let MathNode::Delimiter { value, source, .. } = node { delimiters.push((out.len(), *value, source)); } out.append(&mut translated[i]); if penalties && i + 1 < prepared.len() && !matches!( prepared[i + 1], MathNode::Penalty(_) | MathNode::Noad(Noad { class: Rel, .. }) ) { if let Some(p) = match cls[i] { Some(Bin) => Some(Parameter::Binoppenalty), Some(Rel) => Some(Parameter::Relpenalty), _ => None, } { let n = self.state.parameter(p).width(); if n < 10000 { out.push(TextNode::Penalty(n)); } } } } if !delimiters.is_empty() { let (mut height, mut depth) = (0, 0); for n in &out { if let TextNode::Box(b) | TextNode::MathChar(b) = n { let shift = b.native_box.as_ref().map_or(0, |b| b.shift); height = height.max(b.height - shift); depth = depth.max(b.depth + shift); } else if let TextNode::Rule(r) = n { let (_, h, d) = r.dimensions(); height = height.max(h); depth = depth.max(d); } } let axis = self.params(original_style)?.axis_height; let delta = (height - axis).max(depth + axis); let factor = self.state.parameter(Parameter::Delimiterfactor).width() as i64; let shortfall = self.state.parameter(Parameter::Delimitershortfall).width() as i64; let target = ((delta / 500) * factor).max(2 * delta - shortfall); if target > 1073741823 { return Err("native delimiter dimension capacity exceeded".into()); } for (index, value, source) in delimiters { out[index] = TextNode::Box( self.delimiter(value, original_style, target, source)? .horizontal_item(), ); } } Ok((out, cls, prepared)) } } pub(super) fn math_box(g: MathGeometry) -> HorizontalBox { HorizontalBox { width: g.metrics.width, height: g.metrics.height, depth: g.metrics.depth, math_geometry: Some(Box::new(g)), ..HorizontalBox::default() } } pub(crate) fn paint_native_math( g: &MathGeometry, x: i64, y: i64, out: &mut Vec, ) { paint_geometry(g, 0, 0, x, y, out) } pub(crate) fn paint_geometry( g: &MathGeometry, x: i64, y: i64, ox: i64, oy: i64, out: &mut Vec, ) { use super::boxes::bp; use crate::render::DisplayItem; for p in &g.items { out.push(match &p.item { MathItem::NativeGlyph { font, slot, size, character, } => DisplayItem::NativeGlyph { x: ox + bp(x + p.x), y: oy + bp(y + p.y), size: bp(*size), character: *character, slot: *slot, font: font.clone(), paint: None, }, MathItem::Glyph { character, font, slot, size, } => DisplayItem::MathGlyph { x: ox + bp(x + p.x), y: oy + bp(y + p.y), size: bp(*size), character: *character, slot: *slot, face: MathFontId::new(*font, *size), }, MathItem::Rule { width, height } => DisplayItem::Rule { x: ox + bp(x + p.x), y: oy + bp(y + p.y), width: bp(*width), height: bp(*height), }, MathItem::PdfImage(image) => DisplayItem::PdfImage { x: ox + bp(x + p.x), y: oy + bp(y + p.y - image.height), width: bp(image.width), height: bp(image.height + image.depth), image: image.clone(), }, }) } }