Initial texrra engine
Rename the crate, binary, core crate, font families, env vars, and internal commands from texcraft/tex-engine to texrra. Serve the separately versioned texrra-web frontend from TEXRRA_WEB_DIR, ../web, or ./web instead of embedding index.html. Add starred section heading support and an arXiv template conformance fixture.
This commit is contained in:
commit
bb1d9e0561
147 files changed
+66719
No files matched your search
@@ -0,0 +1,85 @@
|
||||
/// Assignment scope selected by TeX prefixes and `\\globaldefs`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum AssignmentScopeKind {
|
||||
Local,
|
||||
Global,
|
||||
}
|
||||
|
||||
impl Default for AssignmentScopeKind {
|
||||
fn default() -> Self {
|
||||
Self::Local
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AssignmentScope {
|
||||
global_defs: i32,
|
||||
global_prefix_pending: bool,
|
||||
long_prefix_pending: bool,
|
||||
outer_prefix_pending: bool,
|
||||
groups: Vec<AssignmentScopeGroup>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
struct AssignmentScopeGroup {
|
||||
global_defs: Option<i32>,
|
||||
}
|
||||
|
||||
impl AssignmentScope {
|
||||
pub fn global_defs(&self) -> &i32 {
|
||||
&self.global_defs
|
||||
}
|
||||
|
||||
pub fn request_prefixes(&mut self, global: bool, long: bool, outer: bool) {
|
||||
self.global_prefix_pending |= global;
|
||||
self.long_prefix_pending |= long;
|
||||
self.outer_prefix_pending |= outer;
|
||||
}
|
||||
|
||||
pub fn take_prefixed_scope(&mut self) -> AssignmentScopeKind {
|
||||
if std::mem::take(&mut self.global_prefix_pending) {
|
||||
AssignmentScopeKind::Global
|
||||
} else {
|
||||
AssignmentScopeKind::Local
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_macro_prefixes(&mut self) -> (bool, bool) {
|
||||
(
|
||||
std::mem::take(&mut self.long_prefix_pending),
|
||||
std::mem::take(&mut self.outer_prefix_pending),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn global_defs_mut(&mut self, global: bool) -> &mut i32 {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.global_defs = None;
|
||||
}
|
||||
} else if let Some(group) = self.groups.last_mut() {
|
||||
group.global_defs.get_or_insert(self.global_defs);
|
||||
}
|
||||
&mut self.global_defs
|
||||
}
|
||||
|
||||
pub fn override_scope(&self, requested: AssignmentScopeKind) -> AssignmentScopeKind {
|
||||
match self.global_defs.cmp(&0) {
|
||||
std::cmp::Ordering::Less => AssignmentScopeKind::Local,
|
||||
std::cmp::Ordering::Equal => requested,
|
||||
std::cmp::Ordering::Greater => AssignmentScopeKind::Global,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(AssignmentScopeGroup::default());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
if let Some(global_defs) = group.global_defs {
|
||||
self.global_defs = global_defs;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::EngineCommandName;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NativePrimitive {
|
||||
ParagraphBreak,
|
||||
LineBreak,
|
||||
PageBreak,
|
||||
Penalty,
|
||||
Kern,
|
||||
HorizontalSkip,
|
||||
VerticalSkip,
|
||||
Advance,
|
||||
Multiply,
|
||||
Divide,
|
||||
Global,
|
||||
Long,
|
||||
Outer,
|
||||
Relax,
|
||||
}
|
||||
|
||||
/// Meaning selected by the Rust engine for a control sequence.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EngineCommandMeaning {
|
||||
Macro,
|
||||
Native(NativePrimitive),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NativeCommandTable {
|
||||
meanings: HashMap<EngineCommandName, NativePrimitive>,
|
||||
groups: Vec<HashMap<EngineCommandName, Option<NativePrimitive>>>,
|
||||
}
|
||||
|
||||
impl Default for NativeCommandTable {
|
||||
fn default() -> Self {
|
||||
let meanings = [
|
||||
("advance", NativePrimitive::Advance),
|
||||
("multiply", NativePrimitive::Multiply),
|
||||
("divide", NativePrimitive::Divide),
|
||||
("global", NativePrimitive::Global),
|
||||
("long", NativePrimitive::Long),
|
||||
("outer", NativePrimitive::Outer),
|
||||
("relax", NativePrimitive::Relax),
|
||||
("par", NativePrimitive::ParagraphBreak),
|
||||
("newline", NativePrimitive::LineBreak),
|
||||
("texrrapagebreak", NativePrimitive::PageBreak),
|
||||
("penalty", NativePrimitive::Penalty),
|
||||
("kern", NativePrimitive::Kern),
|
||||
("hskip", NativePrimitive::HorizontalSkip),
|
||||
("vskip", NativePrimitive::VerticalSkip),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(name, primitive)| {
|
||||
(
|
||||
EngineCommandName::ControlSequence(name.to_string()),
|
||||
primitive,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
meanings,
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeCommandTable {
|
||||
pub fn get(&self, name: &EngineCommandName) -> Option<NativePrimitive> {
|
||||
self.meanings.get(name).copied()
|
||||
}
|
||||
|
||||
pub fn define(&mut self, name: EngineCommandName, primitive: NativePrimitive, global: bool) {
|
||||
self.prepare_assignment(&name, global);
|
||||
self.meanings.insert(name, primitive);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, name: EngineCommandName, global: bool) {
|
||||
self.prepare_assignment(&name, global);
|
||||
self.meanings.remove(&name);
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(HashMap::new());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (name, previous) in group {
|
||||
match previous {
|
||||
Some(primitive) => {
|
||||
self.meanings.insert(name, primitive);
|
||||
}
|
||||
None => {
|
||||
self.meanings.remove(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prepare_assignment(&mut self, name: &EngineCommandName, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.remove(name);
|
||||
}
|
||||
} else if let Some(group) = self.groups.last_mut() {
|
||||
group
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| self.meanings.get(name).copied());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
path::PathBuf,
|
||||
};
|
||||
|
||||
use crate::{TeXGlue, math_expr::MathExpr, source::SourceLocation};
|
||||
|
||||
/// Physical page dimensions in millimetres.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PageSize {
|
||||
pub width_mm: f64,
|
||||
pub height_mm: f64,
|
||||
}
|
||||
|
||||
impl PageSize {
|
||||
pub const A4: Self = Self {
|
||||
width_mm: 210.0,
|
||||
height_mm: 297.0,
|
||||
};
|
||||
pub const A5: Self = Self {
|
||||
width_mm: 148.0,
|
||||
height_mm: 210.0,
|
||||
};
|
||||
pub const B5: Self = Self {
|
||||
width_mm: 176.0,
|
||||
height_mm: 250.0,
|
||||
};
|
||||
/// US letter, 8.5 by 11 inches.
|
||||
pub const LETTER: Self = Self {
|
||||
width_mm: 215.9,
|
||||
height_mm: 279.4,
|
||||
};
|
||||
/// US legal, 8.5 by 14 inches.
|
||||
pub const LEGAL: Self = Self {
|
||||
width_mm: 215.9,
|
||||
height_mm: 355.6,
|
||||
};
|
||||
/// US executive, 7.25 by 10.5 inches.
|
||||
pub const EXECUTIVE: Self = Self {
|
||||
width_mm: 184.15,
|
||||
height_mm: 266.7,
|
||||
};
|
||||
|
||||
pub fn landscape(self) -> Self {
|
||||
Self {
|
||||
width_mm: self.height_mm,
|
||||
height_mm: self.width_mm,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PageSize {
|
||||
fn default() -> Self {
|
||||
Self::A4
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DocumentModel {
|
||||
pub title: String,
|
||||
pub author: String,
|
||||
pub date: String,
|
||||
pub page: PageSize,
|
||||
pub margins: PageMargins,
|
||||
pub show_title: bool,
|
||||
pub blocks: Vec<Block>,
|
||||
pub block_sources: Vec<Option<SourceLocation>>,
|
||||
pub labels: HashMap<String, String>,
|
||||
pub citations: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
pub struct ParsedDocument(pub DocumentModel);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PageMargins {
|
||||
pub top: f64,
|
||||
pub right: f64,
|
||||
pub bottom: f64,
|
||||
pub left: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EquationNumber {
|
||||
pub text: String,
|
||||
pub parenthesized: bool,
|
||||
}
|
||||
|
||||
impl Default for PageMargins {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
top: 25.0,
|
||||
right: 25.0,
|
||||
bottom: 25.0,
|
||||
left: 25.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum Block {
|
||||
Paragraph(Vec<Run>),
|
||||
Heading {
|
||||
level: u8,
|
||||
runs: Vec<Run>,
|
||||
},
|
||||
List(ListBlock),
|
||||
Table {
|
||||
rows: Vec<Vec<Vec<Run>>>,
|
||||
caption: Option<Vec<Run>>,
|
||||
alignments: Vec<ColumnAlignment>,
|
||||
rules: Vec<usize>,
|
||||
},
|
||||
Image {
|
||||
path: String,
|
||||
options: String,
|
||||
caption: Option<Vec<Run>>,
|
||||
},
|
||||
Bibliography(Vec<(String, Vec<Run>)>),
|
||||
/// A box such as `\fbox{...}` (framed) or `\parbox{width}{...}`.
|
||||
FramedBox {
|
||||
runs: Vec<Run>,
|
||||
frame: bool,
|
||||
width: Option<common::Scaled>,
|
||||
},
|
||||
/// Center-aligned content produced by the `center` environment.
|
||||
Centered {
|
||||
runs: Vec<Run>,
|
||||
},
|
||||
/// A horizontal rule such as `\hrule` (full width when `width` is None).
|
||||
HorizontalRule {
|
||||
height: common::Scaled,
|
||||
width: Option<common::Scaled>,
|
||||
},
|
||||
Math {
|
||||
expression: MathExpr,
|
||||
equation_numbers: Vec<Option<EquationNumber>>,
|
||||
},
|
||||
VerticalKern(common::Scaled),
|
||||
VerticalGlue(TeXGlue),
|
||||
Penalty(i32),
|
||||
PageBreak,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ColumnAlignment {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct ListBlock {
|
||||
pub ordered: bool,
|
||||
pub items: Vec<ListItem>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct ListItem {
|
||||
pub runs: Vec<Run>,
|
||||
pub nested: Vec<ListBlock>,
|
||||
pub vertical_glue_after: Vec<TeXGlue>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub enum UnresolvedReference {
|
||||
Label(String),
|
||||
Citation(Vec<String>),
|
||||
}
|
||||
|
||||
/// An unbreakable inline box such as `\mbox{...}` or `\makebox{...}`.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct InlineBox {
|
||||
pub runs: Vec<Run>,
|
||||
}
|
||||
|
||||
/// A filled rectangle produced by `\rule`.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct RuleBox {
|
||||
pub width: common::Scaled,
|
||||
/// Distance from the baseline to the bottom edge of the ink.
|
||||
///
|
||||
/// A positive raise leaves a gap between the baseline and the rule; a
|
||||
/// negative raise moves the rule below the baseline.
|
||||
pub raise: common::Scaled,
|
||||
/// Thickness of the rule.
|
||||
pub height: common::Scaled,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Run {
|
||||
pub text: String,
|
||||
pub math: Option<MathExpr>,
|
||||
pub kern: Option<common::Scaled>,
|
||||
pub glue: Option<TeXGlue>,
|
||||
pub penalty: Option<i32>,
|
||||
pub rule: Option<RuleBox>,
|
||||
pub box_run: Option<InlineBox>,
|
||||
pub unresolved_reference: Option<UnresolvedReference>,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub monospace: bool,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
pub fn plain(text: String) -> Self {
|
||||
Self {
|
||||
text,
|
||||
math: None,
|
||||
kern: None,
|
||||
glue: None,
|
||||
penalty: None,
|
||||
rule: None,
|
||||
box_run: None,
|
||||
unresolved_reference: None,
|
||||
bold: false,
|
||||
italic: false,
|
||||
monospace: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentModel {
|
||||
pub fn math_font_files(&self) -> HashSet<PathBuf> {
|
||||
fn collect_runs(runs: &[Run], files: &mut HashSet<PathBuf>) {
|
||||
for run in runs {
|
||||
if let Some(expression) = &run.math {
|
||||
expression.collect_math_font_files(files);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_list(list: &ListBlock, files: &mut HashSet<PathBuf>) {
|
||||
for item in &list.items {
|
||||
collect_runs(&item.runs, files);
|
||||
for nested in &item.nested {
|
||||
collect_list(nested, files);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut files = HashSet::new();
|
||||
for block in &self.blocks {
|
||||
match block {
|
||||
Block::Paragraph(runs) | Block::Heading { runs, .. } => {
|
||||
collect_runs(runs, &mut files);
|
||||
}
|
||||
Block::List(list) => collect_list(list, &mut files),
|
||||
Block::Table { rows, caption, .. } => {
|
||||
for cell in rows.iter().flatten() {
|
||||
collect_runs(cell, &mut files);
|
||||
}
|
||||
if let Some(caption) = caption {
|
||||
collect_runs(caption, &mut files);
|
||||
}
|
||||
}
|
||||
Block::Image { caption, .. } => {
|
||||
if let Some(caption) = caption {
|
||||
collect_runs(caption, &mut files);
|
||||
}
|
||||
}
|
||||
Block::FramedBox { runs, .. } | Block::Centered { runs } => {
|
||||
collect_runs(runs, &mut files);
|
||||
}
|
||||
Block::Bibliography(items) => {
|
||||
for (_, runs) in items {
|
||||
collect_runs(runs, &mut files);
|
||||
}
|
||||
}
|
||||
Block::Math { expression, .. } => expression.collect_math_font_files(&mut files),
|
||||
Block::HorizontalRule { .. }
|
||||
| Block::VerticalKern(_)
|
||||
| Block::VerticalGlue(_)
|
||||
| Block::Penalty(_)
|
||||
| Block::PageBreak => {}
|
||||
}
|
||||
}
|
||||
files
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,63 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EnvironmentStack {
|
||||
names: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum EndEnvironmentError {
|
||||
Unmatched { requested: String },
|
||||
Mismatched { active: String, requested: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for EndEnvironmentError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Unmatched { requested } => {
|
||||
write!(
|
||||
formatter,
|
||||
"`\\end{{{requested}}}` has no matching `\\begin`"
|
||||
)
|
||||
}
|
||||
Self::Mismatched { active, requested } => write!(
|
||||
formatter,
|
||||
"environment `{active}` was ended by `\\end{{{requested}}}`"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EnvironmentStack {
|
||||
pub fn begin(&mut self, name: String) {
|
||||
self.names.push(name);
|
||||
}
|
||||
|
||||
pub fn opens_tex_group(name: &str) -> bool {
|
||||
name != "document"
|
||||
}
|
||||
|
||||
pub fn current(&self) -> Option<&str> {
|
||||
self.names.last().map(String::as_str)
|
||||
}
|
||||
|
||||
pub fn end(&mut self, requested: &str) -> Result<(), EndEnvironmentError> {
|
||||
match self.current() {
|
||||
Some(active) if active == requested => {
|
||||
self.names.pop();
|
||||
Ok(())
|
||||
}
|
||||
Some(active) => Err(EndEnvironmentError::Mismatched {
|
||||
active: active.to_string(),
|
||||
requested: requested.to_string(),
|
||||
}),
|
||||
None => Err(EndEnvironmentError::Unmatched {
|
||||
requested: requested.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_slice(&self) -> &[String] {
|
||||
&self.names
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
use std::{ops::Range, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
MathClass, MathStyleCommand, TeXGlue,
|
||||
math_code::UnicodeMathCode,
|
||||
math_expr::{
|
||||
MathAccent, MathDelimiterGlyph, MathDelimiterSettings, MathExpr, MathFontFamilies,
|
||||
MathFontStyle, MathFractionStyle, MathInfixFractionKind, MathLimitMode,
|
||||
MathLineBreakPenalties, MathPhantomKind, MathSpacingSettings,
|
||||
},
|
||||
source::SourceLocation,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TextStyle {
|
||||
Bold,
|
||||
Italic,
|
||||
Monospace,
|
||||
SmallCaps,
|
||||
Normal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MetadataField {
|
||||
Title,
|
||||
Author,
|
||||
Date,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SourceSegment {
|
||||
pub output: Range<usize>,
|
||||
pub location: SourceLocation,
|
||||
pub column_advances: bool,
|
||||
pub column_character_starts: Vec<usize>,
|
||||
}
|
||||
|
||||
fn rebased_column_character_starts(
|
||||
segment: &SourceSegment,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> Vec<usize> {
|
||||
let start_offset = start - segment.output.start;
|
||||
let end_offset = end - segment.output.start;
|
||||
segment
|
||||
.column_character_starts
|
||||
.iter()
|
||||
.filter_map(|offset| {
|
||||
(*offset >= start_offset && *offset < end_offset).then_some(*offset - start_offset)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct DisplayMathTag {
|
||||
pub text: String,
|
||||
pub starred: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct DisplayMathRow {
|
||||
pub equation_tag: Option<DisplayMathTag>,
|
||||
pub suppress_number: bool,
|
||||
pub labels: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for DisplayMathRow {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
equation_tag: None,
|
||||
suppress_number: false,
|
||||
labels: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum FrontendEventKind {
|
||||
ParagraphBreak,
|
||||
PageBreak,
|
||||
Kern(common::Scaled),
|
||||
Rule {
|
||||
width: common::Scaled,
|
||||
raise: common::Scaled,
|
||||
height: common::Scaled,
|
||||
},
|
||||
HorizontalGlue(TeXGlue),
|
||||
VerticalGlue(TeXGlue),
|
||||
Penalty(i32),
|
||||
MakeTitle,
|
||||
FramedBoxStart,
|
||||
ParboxStart {
|
||||
width: common::Scaled,
|
||||
},
|
||||
HorizontalRule {
|
||||
height: common::Scaled,
|
||||
width: Option<common::Scaled>,
|
||||
},
|
||||
FramedBoxEnd,
|
||||
InlineBoxStart,
|
||||
InlineBoxEnd,
|
||||
MetadataStart(MetadataField),
|
||||
MetadataEnd(MetadataField),
|
||||
DisplayMathStart,
|
||||
DisplayMathEnd(MathDelimiterSettings),
|
||||
InlineMathStart,
|
||||
InlineMathEnd(MathDelimiterSettings),
|
||||
DisplayMath {
|
||||
expression: MathExpr,
|
||||
environment: Option<String>,
|
||||
rows: Vec<DisplayMathRow>,
|
||||
},
|
||||
SuppressEquationNumber,
|
||||
EquationTag(DisplayMathTag),
|
||||
InlineMath(MathExpr),
|
||||
MathFractionStart {
|
||||
style: MathFractionStyle,
|
||||
has_rule: bool,
|
||||
parentheses: bool,
|
||||
delimiter_settings: MathDelimiterSettings,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathInfixFraction(MathInfixFractionKind, MathFontFamilies),
|
||||
MathCharacter {
|
||||
code: u16,
|
||||
active_family: i32,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathUnicodeCharacter {
|
||||
class: MathClass,
|
||||
family: u8,
|
||||
character: char,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathUnicodeDelimiter {
|
||||
class: MathClass,
|
||||
family: u8,
|
||||
character: char,
|
||||
settings: MathDelimiterSettings,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathStyleChange(MathStyleCommand),
|
||||
MathChoiceStart,
|
||||
MathChoiceBranch(MathStyleCommand),
|
||||
MathChoiceEnd,
|
||||
MathFractionSeparator,
|
||||
MathFractionEnd,
|
||||
MathLimitMode(MathLimitMode),
|
||||
MathSpace(i8),
|
||||
MathAccentStart {
|
||||
accent: MathAccent,
|
||||
family: u8,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathAccentEnd,
|
||||
MathFontStart(MathFontStyle),
|
||||
MathFontEnd,
|
||||
MathPhantomStart(MathPhantomKind),
|
||||
MathPhantomEnd,
|
||||
MathOperatorStart,
|
||||
MathOperatorEnd,
|
||||
MathClassStart(MathClass),
|
||||
MathClassEnd,
|
||||
MathRootStart {
|
||||
has_index: bool,
|
||||
radical: Option<(u8, char)>,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
MathRootSeparator,
|
||||
MathRootEnd,
|
||||
MathDelimiterStart {
|
||||
delimiter: MathDelimiterGlyph,
|
||||
settings: MathDelimiterSettings,
|
||||
},
|
||||
MathDelimiterMiddle {
|
||||
delimiter: MathDelimiterGlyph,
|
||||
settings: MathDelimiterSettings,
|
||||
},
|
||||
MathDelimiterEnd {
|
||||
delimiter: MathDelimiterGlyph,
|
||||
settings: MathDelimiterSettings,
|
||||
},
|
||||
MathManualDelimiter {
|
||||
delimiter: String,
|
||||
half_points: u8,
|
||||
class: MathClass,
|
||||
settings: MathDelimiterSettings,
|
||||
math_fonts: MathFontFamilies,
|
||||
},
|
||||
BeginEnvironment {
|
||||
name: String,
|
||||
math_fonts: MathFontFamilies,
|
||||
jot: common::Scaled,
|
||||
},
|
||||
EnvironmentArgument(String),
|
||||
EndEnvironment {
|
||||
name: String,
|
||||
delimiter_settings: MathDelimiterSettings,
|
||||
},
|
||||
Geometry(String),
|
||||
TextStyleStart(TextStyle),
|
||||
TextStyleEnd(TextStyle),
|
||||
TextStyleDeclare(TextStyle),
|
||||
LiteralAmpersand,
|
||||
LiteralCharacter(char),
|
||||
LineBreak,
|
||||
MathCell,
|
||||
RowBreak,
|
||||
ListItem,
|
||||
TableCell,
|
||||
TableRule,
|
||||
HeadingStart {
|
||||
level: u8,
|
||||
numbered: bool,
|
||||
},
|
||||
HeadingEnd,
|
||||
CaptionStart,
|
||||
CaptionEnd,
|
||||
IncludeGraphics {
|
||||
options: String,
|
||||
path: String,
|
||||
},
|
||||
Label(String),
|
||||
Reference(String),
|
||||
Citation(String),
|
||||
BibliographyItem(String),
|
||||
GroupStart,
|
||||
GroupEnd,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FrontendEvent {
|
||||
pub position: usize,
|
||||
pub kind: FrontendEventKind,
|
||||
pub location: SourceLocation,
|
||||
pub math_line_break_penalties: MathLineBreakPenalties,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ExpandedTokenValue {
|
||||
BeginGroup(char),
|
||||
EndGroup(char),
|
||||
MathShift(char),
|
||||
AlignmentTab(char),
|
||||
Parameter(char),
|
||||
Superscript(char),
|
||||
Subscript(char),
|
||||
Space(char),
|
||||
Letter(char),
|
||||
Other(char),
|
||||
ActiveCharacter(char),
|
||||
ControlSequence(String),
|
||||
}
|
||||
|
||||
impl ExpandedTokenValue {
|
||||
pub fn character(&self) -> Option<char> {
|
||||
match self {
|
||||
Self::BeginGroup(character)
|
||||
| Self::EndGroup(character)
|
||||
| Self::MathShift(character)
|
||||
| Self::AlignmentTab(character)
|
||||
| Self::Parameter(character)
|
||||
| Self::Superscript(character)
|
||||
| Self::Subscript(character)
|
||||
| Self::Space(character)
|
||||
| Self::Letter(character)
|
||||
| Self::Other(character)
|
||||
| Self::ActiveCharacter(character) => Some(*character),
|
||||
Self::ControlSequence(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ExpandedItemKind {
|
||||
Token(ExpandedTokenValue),
|
||||
Event(FrontendEventKind),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct ExpandedItem {
|
||||
pub position: usize,
|
||||
pub end_position: usize,
|
||||
pub kind: ExpandedItemKind,
|
||||
pub location: SourceLocation,
|
||||
pub math_code: Option<u16>,
|
||||
pub math_family: Option<i32>,
|
||||
pub unicode_math_code: Option<UnicodeMathCode>,
|
||||
pub delimiter_settings: Option<MathDelimiterSettings>,
|
||||
pub math_fonts: MathFontFamilies,
|
||||
pub math_spacing: MathSpacingSettings,
|
||||
pub math_line_break_penalties: MathLineBreakPenalties,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ExpandedSource {
|
||||
pub text: String,
|
||||
pub segments: Vec<SourceSegment>,
|
||||
pub events: Vec<FrontendEvent>,
|
||||
pub items: Vec<ExpandedItem>,
|
||||
}
|
||||
|
||||
/// Semantic consumers receive typed items without the VM's serialized text view.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ExpandedTokenStream {
|
||||
pub items: Vec<ExpandedItem>,
|
||||
pub segments: Vec<SourceSegment>,
|
||||
pub events: Vec<FrontendEvent>,
|
||||
}
|
||||
|
||||
impl ExpandedSource {
|
||||
pub fn into_token_stream(self) -> ExpandedTokenStream {
|
||||
ExpandedTokenStream {
|
||||
items: self.items,
|
||||
segments: self.segments,
|
||||
events: self.events,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn source_at(&self, output_offset: usize) -> Option<SourceLocation> {
|
||||
let index = self
|
||||
.segments
|
||||
.partition_point(|segment| segment.output.end <= output_offset);
|
||||
let segment = self
|
||||
.segments
|
||||
.get(index)
|
||||
.filter(|segment| segment.output.contains(&output_offset))?;
|
||||
Some(self.location_at(segment, output_offset))
|
||||
}
|
||||
|
||||
fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation {
|
||||
let mut location = segment.location.clone();
|
||||
if segment.column_advances {
|
||||
let byte_offset = output_offset - segment.output.start;
|
||||
location.column += segment
|
||||
.column_character_starts
|
||||
.partition_point(|start| *start < byte_offset);
|
||||
}
|
||||
location
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpandedTokenStream {
|
||||
pub fn output_len(&self) -> usize {
|
||||
self.items
|
||||
.last()
|
||||
.map(|item| item.end_position)
|
||||
.unwrap_or_default()
|
||||
.max(
|
||||
self.segments
|
||||
.last()
|
||||
.map(|segment| segment.output.end)
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
.max(
|
||||
self.events
|
||||
.last()
|
||||
.map(|event| event.position)
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn token_item_at(&self, output_offset: usize) -> Option<&ExpandedItem> {
|
||||
let item_start = self
|
||||
.items
|
||||
.partition_point(|item| item.position < output_offset);
|
||||
self.items[item_start..]
|
||||
.iter()
|
||||
.take_while(|item| item.position == output_offset)
|
||||
.find(|item| {
|
||||
item.end_position > item.position
|
||||
&& matches!(&item.kind, ExpandedItemKind::Token(_))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn next_token_item_at_or_after(
|
||||
&self,
|
||||
output_offset: usize,
|
||||
limit: usize,
|
||||
) -> Option<&ExpandedItem> {
|
||||
let item_start = self
|
||||
.items
|
||||
.partition_point(|item| item.position < output_offset);
|
||||
self.items[item_start..]
|
||||
.iter()
|
||||
.take_while(|item| item.position < limit)
|
||||
.find(|item| {
|
||||
item.end_position > item.position
|
||||
&& matches!(&item.kind, ExpandedItemKind::Token(_))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn token_value_at(&self, output_offset: usize) -> Option<&ExpandedTokenValue> {
|
||||
let item = self.token_item_at(output_offset)?;
|
||||
match &item.kind {
|
||||
ExpandedItemKind::Token(value) => Some(value),
|
||||
ExpandedItemKind::Event(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn character_tokens_in(&self, range: Range<usize>) -> String {
|
||||
let item_start = self
|
||||
.items
|
||||
.partition_point(|item| item.position < range.start);
|
||||
let mut text = String::new();
|
||||
for item in self.items[item_start..]
|
||||
.iter()
|
||||
.take_while(|item| item.position < range.end)
|
||||
{
|
||||
let ExpandedItemKind::Token(value) = &item.kind else {
|
||||
continue;
|
||||
};
|
||||
if let Some(character) = value.character() {
|
||||
text.push(character);
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
pub fn source_at(&self, output_offset: usize) -> Option<SourceLocation> {
|
||||
let index = self
|
||||
.segments
|
||||
.partition_point(|segment| segment.output.end <= output_offset);
|
||||
let segment = self
|
||||
.segments
|
||||
.get(index)
|
||||
.filter(|segment| segment.output.contains(&output_offset))?;
|
||||
Some(self.location_at(segment, output_offset))
|
||||
}
|
||||
|
||||
fn location_at(&self, segment: &SourceSegment, output_offset: usize) -> SourceLocation {
|
||||
let mut location = segment.location.clone();
|
||||
if segment.column_advances {
|
||||
let byte_offset = output_offset - segment.output.start;
|
||||
location.column += segment
|
||||
.column_character_starts
|
||||
.partition_point(|start| *start < byte_offset);
|
||||
}
|
||||
location
|
||||
}
|
||||
|
||||
pub fn segment_signature(&self, range: Range<usize>) -> Vec<SourceSegment> {
|
||||
self.segments
|
||||
.iter()
|
||||
.filter_map(|segment| {
|
||||
let start = segment.output.start.max(range.start);
|
||||
let end = segment.output.end.min(range.end);
|
||||
(start < end).then(|| SourceSegment {
|
||||
output: start - range.start..end - range.start,
|
||||
location: self.location_at(segment, start),
|
||||
column_advances: segment.column_advances,
|
||||
column_character_starts: rebased_column_character_starts(segment, start, end),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn copy_token_range(&mut self, source: &Self, range: Range<usize>) {
|
||||
if range.is_empty() {
|
||||
return;
|
||||
}
|
||||
let destination_start = self.output_len();
|
||||
self.copy_segments(source, &range, destination_start);
|
||||
self.items.extend(source.items.iter().filter_map(|item| {
|
||||
(range.start <= item.position
|
||||
&& item.position < range.end
|
||||
&& matches!(&item.kind, ExpandedItemKind::Token(_)))
|
||||
.then(|| rebase_expanded_item(item, destination_start, range.start))
|
||||
}));
|
||||
}
|
||||
|
||||
/// Copies a slice of source items onto the current output in item order.
|
||||
///
|
||||
/// Items with zero output width (space tokens and events) share their byte
|
||||
/// position with the next written token; copying by item index keeps those
|
||||
/// items in expansion order instead of splitting them by position.
|
||||
pub fn copy_items(&mut self, source: &Self, items: &[ExpandedItem]) {
|
||||
if items.is_empty() {
|
||||
return;
|
||||
}
|
||||
let destination_start = self.output_len();
|
||||
let position_start = items[0].position;
|
||||
let position_end = items
|
||||
.iter()
|
||||
.map(|item| item.end_position.max(item.position))
|
||||
.max()
|
||||
.unwrap_or(position_start);
|
||||
if position_end > position_start {
|
||||
self.copy_segments(source, &(position_start..position_end), destination_start);
|
||||
}
|
||||
for item in items {
|
||||
let item = rebase_expanded_item(item, destination_start, position_start);
|
||||
if let ExpandedItemKind::Event(kind) = &item.kind {
|
||||
self.events.push(FrontendEvent {
|
||||
position: item.position,
|
||||
kind: kind.clone(),
|
||||
location: item.location.clone(),
|
||||
math_line_break_penalties: item.math_line_break_penalties,
|
||||
});
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn copy_range(&mut self, source: &Self, range: Range<usize>) {
|
||||
if range.is_empty() {
|
||||
return;
|
||||
}
|
||||
let destination_start = self.output_len();
|
||||
self.copy_segments(source, &range, destination_start);
|
||||
for item in source
|
||||
.items
|
||||
.iter()
|
||||
.filter(|item| range.start <= item.position && item.position < range.end)
|
||||
{
|
||||
let item = rebase_expanded_item(item, destination_start, range.start);
|
||||
if let ExpandedItemKind::Event(kind) = &item.kind {
|
||||
self.events.push(FrontendEvent {
|
||||
position: item.position,
|
||||
kind: kind.clone(),
|
||||
location: item.location.clone(),
|
||||
math_line_break_penalties: item.math_line_break_penalties,
|
||||
});
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_segments(&mut self, source: &Self, range: &Range<usize>, destination_start: usize) {
|
||||
for segment in &source.segments {
|
||||
let start = segment.output.start.max(range.start);
|
||||
let end = segment.output.end.min(range.end);
|
||||
if start < end {
|
||||
self.segments.push(SourceSegment {
|
||||
output: destination_start + start - range.start
|
||||
..destination_start + end - range.start,
|
||||
location: source.location_at(segment, start),
|
||||
column_advances: segment.column_advances,
|
||||
column_character_starts: rebased_column_character_starts(segment, start, end),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn copy_events_at(&mut self, source: &Self, source_position: usize) {
|
||||
let destination_position = self.output_len();
|
||||
for item in source.items.iter().filter(|item| {
|
||||
item.position == source_position && matches!(&item.kind, ExpandedItemKind::Event(_))
|
||||
}) {
|
||||
let ExpandedItemKind::Event(kind) = &item.kind else {
|
||||
unreachable!();
|
||||
};
|
||||
self.events.push(FrontendEvent {
|
||||
position: destination_position,
|
||||
kind: kind.clone(),
|
||||
location: item.location.clone(),
|
||||
math_line_break_penalties: item.math_line_break_penalties,
|
||||
});
|
||||
self.items.push(ExpandedItem {
|
||||
position: destination_position,
|
||||
end_position: destination_position,
|
||||
kind: item.kind.clone(),
|
||||
location: item.location.clone(),
|
||||
math_code: None,
|
||||
math_family: None,
|
||||
unicode_math_code: None,
|
||||
delimiter_settings: None,
|
||||
math_fonts: Arc::default(),
|
||||
math_spacing: MathSpacingSettings::default(),
|
||||
math_line_break_penalties: item.math_line_break_penalties,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert_event(&mut self, kind: FrontendEventKind, location: SourceLocation) {
|
||||
let position = self.output_len();
|
||||
self.events.push(FrontendEvent {
|
||||
position,
|
||||
kind: kind.clone(),
|
||||
location: location.clone(),
|
||||
math_line_break_penalties: MathLineBreakPenalties::default(),
|
||||
});
|
||||
self.items.push(ExpandedItem {
|
||||
position,
|
||||
end_position: position,
|
||||
kind: ExpandedItemKind::Event(kind),
|
||||
location,
|
||||
math_code: None,
|
||||
math_family: None,
|
||||
unicode_math_code: None,
|
||||
delimiter_settings: None,
|
||||
math_fonts: Arc::default(),
|
||||
math_spacing: MathSpacingSettings::default(),
|
||||
math_line_break_penalties: MathLineBreakPenalties::default(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn rebase_expanded_item(
|
||||
item: &ExpandedItem,
|
||||
destination_start: usize,
|
||||
source_start: usize,
|
||||
) -> ExpandedItem {
|
||||
ExpandedItem {
|
||||
position: destination_start + item.position - source_start,
|
||||
end_position: destination_start + item.end_position - source_start,
|
||||
kind: item.kind.clone(),
|
||||
location: item.location.clone(),
|
||||
math_code: item.math_code,
|
||||
math_family: item.math_family,
|
||||
unicode_math_code: item.unicode_math_code,
|
||||
delimiter_settings: item.delimiter_settings,
|
||||
math_fonts: Arc::clone(&item.math_fonts),
|
||||
math_spacing: item.math_spacing,
|
||||
math_line_break_penalties: item.math_line_break_penalties,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
use crate::{CatCode as EngineCatCode, EngineToken, EngineTokenValue, macros::MacroDefinition};
|
||||
|
||||
pub trait MacroTokenStream {
|
||||
type Error;
|
||||
|
||||
fn next_unexpanded(&mut self) -> Result<Option<EngineToken>, Self::Error>;
|
||||
fn back_unexpanded(&mut self, token: EngineToken);
|
||||
fn macro_definition(&self, token: &EngineToken) -> Option<MacroDefinition>;
|
||||
fn in_expanded_definition(&self) -> bool;
|
||||
fn is_outer_macro(&self, token: &EngineToken) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum ErrorStream {
|
||||
Input,
|
||||
Unexpanded,
|
||||
}
|
||||
|
||||
pub enum MacroScanError<E> {
|
||||
Stream(E),
|
||||
Macro {
|
||||
token: EngineToken,
|
||||
message: String,
|
||||
stream: ErrorStream,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn expand_macro<S: MacroTokenStream>(
|
||||
stream: &mut S,
|
||||
macro_token: EngineToken,
|
||||
macro_name: &str,
|
||||
) -> Result<Vec<EngineToken>, MacroScanError<S::Error>> {
|
||||
let Some(definition) = stream.macro_definition(¯o_token) else {
|
||||
return Err(macro_error(
|
||||
¯o_token,
|
||||
"macro definition is no longer active",
|
||||
ErrorStream::Input,
|
||||
));
|
||||
};
|
||||
if definition.is_outer && stream.in_expanded_definition() {
|
||||
return Err(macro_error(
|
||||
¯o_token,
|
||||
"outer macro cannot be expanded in an expanded definition",
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
let arguments = scan_arguments(
|
||||
stream,
|
||||
macro_token,
|
||||
macro_name,
|
||||
&definition,
|
||||
definition.optional_first_default.as_deref(),
|
||||
)?;
|
||||
Ok(definition.instantiate(&arguments))
|
||||
}
|
||||
|
||||
pub fn scan_arguments<S: MacroTokenStream>(
|
||||
stream: &mut S,
|
||||
macro_token: EngineToken,
|
||||
macro_name: &str,
|
||||
definition: &MacroDefinition,
|
||||
optional_default: Option<&[EngineToken]>,
|
||||
) -> Result<Vec<Vec<EngineToken>>, MacroScanError<S::Error>> {
|
||||
for expected in &definition.prefix {
|
||||
let actual = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroScanError::Stream)?
|
||||
.ok_or_else(|| {
|
||||
macro_error(
|
||||
¯o_token,
|
||||
"macro prefix does not match its definition",
|
||||
ErrorStream::Unexpanded,
|
||||
)
|
||||
})?;
|
||||
if actual.value != *expected {
|
||||
return Err(macro_error(
|
||||
&actual,
|
||||
"macro prefix does not match its definition",
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut arguments = Vec::with_capacity(definition.parameters.len());
|
||||
for (index, parameter) in definition.parameters.iter().enumerate() {
|
||||
let parameter_number = (index + 1) as u8;
|
||||
let argument = if index == 0 {
|
||||
if let Some(default) = optional_default {
|
||||
read_optional_argument(
|
||||
stream,
|
||||
¯o_token,
|
||||
macro_name,
|
||||
default,
|
||||
definition.is_long,
|
||||
parameter_number,
|
||||
)?
|
||||
} else if parameter.delimiter.is_empty() {
|
||||
read_argument(
|
||||
stream,
|
||||
¯o_token,
|
||||
macro_name,
|
||||
parameter_number,
|
||||
definition.is_long,
|
||||
)?
|
||||
} else {
|
||||
read_delimited_argument(
|
||||
stream,
|
||||
¯o_token,
|
||||
macro_name,
|
||||
¶meter.delimiter,
|
||||
parameter_number,
|
||||
definition.is_long,
|
||||
)?
|
||||
}
|
||||
} else if parameter.delimiter.is_empty() {
|
||||
read_argument(
|
||||
stream,
|
||||
¯o_token,
|
||||
macro_name,
|
||||
parameter_number,
|
||||
definition.is_long,
|
||||
)?
|
||||
} else {
|
||||
read_delimited_argument(
|
||||
stream,
|
||||
¯o_token,
|
||||
macro_name,
|
||||
¶meter.delimiter,
|
||||
parameter_number,
|
||||
definition.is_long,
|
||||
)?
|
||||
};
|
||||
arguments.push(argument);
|
||||
}
|
||||
Ok(arguments)
|
||||
}
|
||||
|
||||
fn read_argument<S: MacroTokenStream>(
|
||||
stream: &mut S,
|
||||
macro_token: &EngineToken,
|
||||
macro_name: &str,
|
||||
parameter_number: u8,
|
||||
is_long: bool,
|
||||
) -> Result<Vec<EngineToken>, MacroScanError<S::Error>> {
|
||||
let first = loop {
|
||||
match stream.next_unexpanded().map_err(MacroScanError::Stream)? {
|
||||
Some(token) if is_space(&token.value) => continue,
|
||||
Some(token) => break token,
|
||||
None => {
|
||||
return Err(macro_error(
|
||||
macro_token,
|
||||
format!("macro is missing parameter #{parameter_number}"),
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
validate_argument_token(stream, &first, macro_name, parameter_number, is_long)?;
|
||||
if !is_begin_group(&first.value) {
|
||||
return Ok(vec![first]);
|
||||
}
|
||||
|
||||
let mut depth = 1usize;
|
||||
let mut argument = Vec::new();
|
||||
while depth > 0 {
|
||||
let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else {
|
||||
return Err(macro_error(
|
||||
macro_token,
|
||||
format!("unterminated braced argument for parameter #{parameter_number}"),
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
validate_argument_token(stream, &next, macro_name, parameter_number, is_long)?;
|
||||
match next.value {
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
} => {
|
||||
depth += 1;
|
||||
argument.push(next);
|
||||
}
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} => {
|
||||
depth -= 1;
|
||||
if depth > 0 {
|
||||
argument.push(next);
|
||||
}
|
||||
}
|
||||
_ => argument.push(next),
|
||||
}
|
||||
}
|
||||
Ok(argument)
|
||||
}
|
||||
|
||||
fn read_delimited_argument<S: MacroTokenStream>(
|
||||
stream: &mut S,
|
||||
macro_token: &EngineToken,
|
||||
macro_name: &str,
|
||||
delimiter: &[EngineTokenValue],
|
||||
parameter_number: u8,
|
||||
is_long: bool,
|
||||
) -> Result<Vec<EngineToken>, MacroScanError<S::Error>> {
|
||||
let closing_scope_depth = usize::from(matches!(
|
||||
delimiter.last(),
|
||||
Some(EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
})
|
||||
));
|
||||
let mut group_depth = 0usize;
|
||||
let mut argument = Vec::new();
|
||||
loop {
|
||||
let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else {
|
||||
return Err(macro_error(
|
||||
macro_token,
|
||||
format!("unterminated delimited argument for parameter #{parameter_number}"),
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
if stream.is_outer_macro(&next) {
|
||||
return Err(macro_error(
|
||||
&next,
|
||||
format!("outer macro cannot appear in an argument to {macro_name}"),
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
match next.value {
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
} => group_depth += 1,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} if group_depth > 0 => group_depth -= 1,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} => {
|
||||
return Err(macro_error(
|
||||
&next,
|
||||
format!("unexpected closing group in parameter #{parameter_number}"),
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
argument.push(next);
|
||||
|
||||
if group_depth == closing_scope_depth && argument.len() >= delimiter.len() {
|
||||
let delimiter_start = argument.len() - delimiter.len();
|
||||
if argument[delimiter_start..]
|
||||
.iter()
|
||||
.zip(delimiter)
|
||||
.all(|(token, expected)| token.value == *expected)
|
||||
{
|
||||
argument.truncate(delimiter_start);
|
||||
return Ok(trim_outer_group(argument));
|
||||
}
|
||||
}
|
||||
|
||||
let last = argument.last().expect("the current token was appended");
|
||||
if !is_long
|
||||
&& is_par_token(last)
|
||||
&& (group_depth != closing_scope_depth
|
||||
|| !matches_delimiter_prefix(&argument, delimiter))
|
||||
{
|
||||
return Err(macro_error(
|
||||
last,
|
||||
format!(
|
||||
"paragraph ended before parameter #{parameter_number} of {macro_name} was complete"
|
||||
),
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_optional_argument<S: MacroTokenStream>(
|
||||
stream: &mut S,
|
||||
macro_token: &EngineToken,
|
||||
macro_name: &str,
|
||||
default: &[EngineToken],
|
||||
is_long: bool,
|
||||
parameter_number: u8,
|
||||
) -> Result<Vec<EngineToken>, MacroScanError<S::Error>> {
|
||||
let opening = loop {
|
||||
match stream.next_unexpanded().map_err(MacroScanError::Stream)? {
|
||||
Some(token) if is_space(&token.value) => continue,
|
||||
token => break token,
|
||||
}
|
||||
};
|
||||
let Some(opening) = opening else {
|
||||
return Ok(default.to_vec());
|
||||
};
|
||||
if !matches!(
|
||||
opening.value,
|
||||
EngineTokenValue::Character {
|
||||
value: '[',
|
||||
catcode: EngineCatCode::Other
|
||||
}
|
||||
) {
|
||||
stream.back_unexpanded(opening);
|
||||
return Ok(default.to_vec());
|
||||
}
|
||||
|
||||
let mut group_depth = 0usize;
|
||||
let mut argument = Vec::new();
|
||||
loop {
|
||||
let Some(next) = stream.next_unexpanded().map_err(MacroScanError::Stream)? else {
|
||||
return Err(macro_error(
|
||||
macro_token,
|
||||
"unterminated optional macro argument; expected `]`",
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
if stream.is_outer_macro(&next) {
|
||||
return Err(macro_error(
|
||||
&next,
|
||||
format!("outer macro cannot appear in an argument to {macro_name}"),
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
validate_long_token(&next, macro_name, parameter_number, is_long)?;
|
||||
match next.value {
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
} => {
|
||||
group_depth += 1;
|
||||
argument.push(next);
|
||||
}
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} if group_depth > 0 => {
|
||||
group_depth -= 1;
|
||||
argument.push(next);
|
||||
}
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} => {
|
||||
return Err(macro_error(
|
||||
&next,
|
||||
"unexpected closing group in optional macro argument",
|
||||
ErrorStream::Unexpanded,
|
||||
));
|
||||
}
|
||||
EngineTokenValue::Character {
|
||||
value: ']',
|
||||
catcode: EngineCatCode::Other,
|
||||
} if group_depth == 0 => return Ok(argument),
|
||||
_ => argument.push(next),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_argument_token<S: MacroTokenStream>(
|
||||
stream: &S,
|
||||
argument_token: &EngineToken,
|
||||
macro_name: &str,
|
||||
parameter_number: u8,
|
||||
is_long: bool,
|
||||
) -> Result<(), MacroScanError<S::Error>> {
|
||||
if stream.is_outer_macro(argument_token) {
|
||||
return Err(macro_error(
|
||||
argument_token,
|
||||
format!("outer macro cannot appear in an argument to {macro_name}"),
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
validate_long_token(argument_token, macro_name, parameter_number, is_long)
|
||||
}
|
||||
|
||||
fn validate_long_token<E>(
|
||||
argument_token: &EngineToken,
|
||||
macro_name: &str,
|
||||
parameter_number: u8,
|
||||
is_long: bool,
|
||||
) -> Result<(), MacroScanError<E>> {
|
||||
if !is_long && is_par_token(argument_token) {
|
||||
return Err(macro_error(
|
||||
argument_token,
|
||||
format!(
|
||||
"paragraph ended before parameter #{parameter_number} of {macro_name} was complete"
|
||||
),
|
||||
ErrorStream::Input,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn matches_delimiter_prefix(argument: &[EngineToken], delimiter: &[EngineTokenValue]) -> bool {
|
||||
let max_prefix = argument.len().min(delimiter.len());
|
||||
(1..=max_prefix).rev().any(|prefix_len| {
|
||||
argument[argument.len() - prefix_len..]
|
||||
.iter()
|
||||
.zip(&delimiter[..prefix_len])
|
||||
.all(|(token, expected)| token.value == *expected)
|
||||
})
|
||||
}
|
||||
|
||||
fn trim_outer_group(mut tokens: Vec<EngineToken>) -> Vec<EngineToken> {
|
||||
if tokens.len() < 2 || !is_begin_group(&tokens[0].value) {
|
||||
return tokens;
|
||||
}
|
||||
let mut depth = 0usize;
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
match token.value {
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
} => depth += 1,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
} => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
if index + 1 == tokens.len() {
|
||||
tokens.remove(0);
|
||||
tokens.pop();
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
tokens
|
||||
}
|
||||
|
||||
fn is_begin_group(value: &EngineTokenValue) -> bool {
|
||||
matches!(
|
||||
value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_space(value: &EngineTokenValue) -> bool {
|
||||
matches!(
|
||||
value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::Space,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_par_token(token: &EngineToken) -> bool {
|
||||
matches!(&token.value, EngineTokenValue::ControlSequence(name) if name == "par")
|
||||
}
|
||||
|
||||
fn macro_error<E>(
|
||||
token: &EngineToken,
|
||||
message: impl Into<String>,
|
||||
stream: ErrorStream,
|
||||
) -> MacroScanError<E> {
|
||||
MacroScanError::Macro {
|
||||
token: token.clone(),
|
||||
message: message.into(),
|
||||
stream,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use common::{Glue, GlueOrder, Scaled};
|
||||
|
||||
/// TeX glue with stretch and shrink orders stored as engine values.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct TeXGlue {
|
||||
pub width: Scaled,
|
||||
pub stretch: Scaled,
|
||||
pub stretch_order: TeXGlueOrder,
|
||||
pub shrink: Scaled,
|
||||
pub shrink_order: TeXGlueOrder,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum TeXGlueOrder {
|
||||
#[default]
|
||||
Normal,
|
||||
Fil,
|
||||
Fill,
|
||||
Filll,
|
||||
}
|
||||
|
||||
impl TeXGlueOrder {
|
||||
pub const fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Normal => 0,
|
||||
Self::Fil => 1,
|
||||
Self::Fill => 2,
|
||||
Self::Filll => 3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Glue> for TeXGlue {
|
||||
fn from(glue: Glue) -> Self {
|
||||
Self {
|
||||
width: glue.width,
|
||||
stretch: glue.stretch,
|
||||
stretch_order: glue.stretch_order.into(),
|
||||
shrink: glue.shrink,
|
||||
shrink_order: glue.shrink_order.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TeXGlue> for Glue {
|
||||
fn from(glue: TeXGlue) -> Self {
|
||||
Self {
|
||||
width: glue.width,
|
||||
stretch: glue.stretch,
|
||||
stretch_order: glue.stretch_order.into(),
|
||||
shrink: glue.shrink,
|
||||
shrink_order: glue.shrink_order.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<GlueOrder> for TeXGlueOrder {
|
||||
fn from(order: GlueOrder) -> Self {
|
||||
match order {
|
||||
GlueOrder::Normal => Self::Normal,
|
||||
GlueOrder::Fil => Self::Fil,
|
||||
GlueOrder::Fill => Self::Fill,
|
||||
GlueOrder::Filll => Self::Filll,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TeXGlueOrder> for GlueOrder {
|
||||
fn from(order: TeXGlueOrder) -> Self {
|
||||
match order {
|
||||
TeXGlueOrder::Normal => Self::Normal,
|
||||
TeXGlueOrder::Fil => Self::Fil,
|
||||
TeXGlueOrder::Fill => Self::Fill,
|
||||
TeXGlueOrder::Filll => Self::Filll,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::{
|
||||
EngineToken,
|
||||
mouth::{CatCodeTable, InvalidCharacter, Mouth, Token},
|
||||
};
|
||||
|
||||
/// Token access required to scan a TeX input file name.
|
||||
pub trait FileNameTokenStream {
|
||||
type Token;
|
||||
type Error;
|
||||
|
||||
fn next_token(&mut self) -> Result<Option<Self::Token>, Self::Error>;
|
||||
fn back_token(&mut self, token: Self::Token);
|
||||
fn is_space(&self, token: &Self::Token) -> bool;
|
||||
fn character(&self, token: &Self::Token) -> Option<char>;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct InputFileLocation {
|
||||
pub path: String,
|
||||
pub extension: Option<String>,
|
||||
pub area: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum InputPathError {
|
||||
UnsupportedArea(String),
|
||||
MissingWorkingDirectory,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for InputPathError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::UnsupportedArea(area) => {
|
||||
write!(formatter, "input file area `{area}` is not supported")
|
||||
}
|
||||
Self::MissingWorkingDirectory => formatter
|
||||
.write_str("cannot resolve a relative input path without a working directory"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputFileLocation {
|
||||
pub fn resolve_path(
|
||||
&self,
|
||||
working_directory: Option<&Path>,
|
||||
default_extension: &str,
|
||||
) -> Result<PathBuf, InputPathError> {
|
||||
if let Some(area) = &self.area {
|
||||
return Err(InputPathError::UnsupportedArea(area.clone()));
|
||||
}
|
||||
|
||||
let mut path = working_directory.map(Path::to_path_buf).unwrap_or_default();
|
||||
path.push(&self.path);
|
||||
path.set_extension(self.extension.as_deref().unwrap_or(default_extension));
|
||||
|
||||
if !path.is_absolute() {
|
||||
return Err(InputPathError::MissingWorkingDirectory);
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan and split an expanded TeX file name into its area, name, and extension.
|
||||
pub fn scan_file_location<S: FileNameTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<InputFileLocation, S::Error> {
|
||||
let mut raw = String::new();
|
||||
let mut area_end = None;
|
||||
let mut extension_start = None;
|
||||
|
||||
loop {
|
||||
let Some(token) = stream.next_token()? else {
|
||||
break;
|
||||
};
|
||||
if stream.is_space(&token) {
|
||||
if raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
stream.back_token(token);
|
||||
break;
|
||||
}
|
||||
let Some(character) = stream.character(&token) else {
|
||||
stream.back_token(token);
|
||||
break;
|
||||
};
|
||||
if character == ' ' {
|
||||
break;
|
||||
}
|
||||
|
||||
if matches!(character, '>' | ':') {
|
||||
area_end = Some(raw.len() + character.len_utf8());
|
||||
extension_start = None;
|
||||
} else if character == '.' && extension_start.is_none() {
|
||||
extension_start = Some(raw.len());
|
||||
}
|
||||
raw.push(character);
|
||||
}
|
||||
|
||||
let name_start = area_end.unwrap_or(0);
|
||||
let name_end = extension_start.unwrap_or(raw.len());
|
||||
Ok(InputFileLocation {
|
||||
path: raw[name_start..name_end].to_string(),
|
||||
extension: extension_start.map(|index| raw[index + 1..].to_string()),
|
||||
area: area_end.map(|end| raw[..end].to_string()),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct InputId(u64);
|
||||
|
||||
pub struct InputFrame {
|
||||
id: InputId,
|
||||
file_name: PathBuf,
|
||||
source: String,
|
||||
line_offset: usize,
|
||||
priority: bool,
|
||||
ended: bool,
|
||||
mouth: Option<Mouth>,
|
||||
expansion_tokens: Option<Vec<EngineToken>>,
|
||||
}
|
||||
|
||||
impl InputFrame {
|
||||
fn new(
|
||||
id: InputId,
|
||||
file_name: impl Into<PathBuf>,
|
||||
source: &str,
|
||||
line_offset: usize,
|
||||
priority: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
file_name: file_name.into(),
|
||||
source: source.to_string(),
|
||||
line_offset,
|
||||
priority,
|
||||
ended: false,
|
||||
mouth: Some(Mouth::new(source)),
|
||||
expansion_tokens: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn new_expansion(id: InputId, tokens: Vec<EngineToken>) -> Self {
|
||||
Self {
|
||||
id,
|
||||
file_name: PathBuf::from("<macro expansion>"),
|
||||
source: String::new(),
|
||||
line_offset: 0,
|
||||
priority: true,
|
||||
ended: false,
|
||||
mouth: None,
|
||||
expansion_tokens: Some(tokens.into_iter().rev().collect()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(&self) -> InputId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn file_name(&self) -> &Path {
|
||||
&self.file_name
|
||||
}
|
||||
|
||||
pub fn source(&self) -> &str {
|
||||
&self.source
|
||||
}
|
||||
|
||||
pub fn line_offset(&self) -> usize {
|
||||
self.line_offset
|
||||
}
|
||||
|
||||
pub fn is_priority(&self) -> bool {
|
||||
self.priority
|
||||
}
|
||||
|
||||
pub fn is_expansion(&self) -> bool {
|
||||
self.expansion_tokens.is_some()
|
||||
}
|
||||
|
||||
pub fn next_expansion_token(&mut self) -> Option<EngineToken> {
|
||||
self.expansion_tokens.as_mut()?.pop()
|
||||
}
|
||||
|
||||
pub fn has_expansion_tokens(&self) -> bool {
|
||||
self.expansion_tokens
|
||||
.as_ref()
|
||||
.is_some_and(|tokens| !tokens.is_empty())
|
||||
}
|
||||
|
||||
pub fn is_source(&self) -> bool {
|
||||
self.mouth.is_some()
|
||||
}
|
||||
|
||||
pub fn is_ended(&self) -> bool {
|
||||
self.ended
|
||||
}
|
||||
|
||||
pub fn end(&mut self) {
|
||||
self.ended = true;
|
||||
}
|
||||
|
||||
pub fn next_token(
|
||||
&mut self,
|
||||
catcodes: &CatCodeTable,
|
||||
) -> Result<Option<Token>, InvalidCharacter> {
|
||||
self.mouth
|
||||
.as_mut()
|
||||
.expect("token expansion frames do not own a mouth")
|
||||
.next_token(catcodes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct InputStack {
|
||||
frames: Vec<InputFrame>,
|
||||
next_id: u64,
|
||||
}
|
||||
|
||||
impl InputStack {
|
||||
pub fn clear(&mut self) {
|
||||
self.frames.clear();
|
||||
}
|
||||
|
||||
pub fn push(
|
||||
&mut self,
|
||||
file_name: impl Into<PathBuf>,
|
||||
source: &str,
|
||||
line_offset: usize,
|
||||
priority: bool,
|
||||
) -> InputId {
|
||||
let id = InputId(self.next_id);
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
self.frames.push(InputFrame::new(
|
||||
id,
|
||||
file_name,
|
||||
source,
|
||||
line_offset,
|
||||
priority,
|
||||
));
|
||||
id
|
||||
}
|
||||
|
||||
/// Push an already-tokenized macro replacement before the current input.
|
||||
/// Tokens are supplied in the order in which TeX should read them.
|
||||
pub fn push_expansion_tokens(&mut self, tokens: Vec<EngineToken>) -> InputId {
|
||||
let id = InputId(self.next_id);
|
||||
self.next_id = self.next_id.wrapping_add(1);
|
||||
if !tokens.is_empty() {
|
||||
self.frames.push(InputFrame::new_expansion(id, tokens));
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Option<InputFrame> {
|
||||
self.frames.pop()
|
||||
}
|
||||
|
||||
pub fn push_frame(&mut self, frame: InputFrame) {
|
||||
self.frames.push(frame);
|
||||
}
|
||||
|
||||
pub fn last(&self) -> Option<&InputFrame> {
|
||||
self.frames.last()
|
||||
}
|
||||
|
||||
pub fn last_mut(&mut self) -> Option<&mut InputFrame> {
|
||||
self.frames.last_mut()
|
||||
}
|
||||
|
||||
pub fn last_source_mut(&mut self) -> Option<&mut InputFrame> {
|
||||
self.frames.iter_mut().rev().find(|frame| frame.is_source())
|
||||
}
|
||||
|
||||
pub fn external_depth(&self) -> usize {
|
||||
self.frames
|
||||
.iter()
|
||||
.filter(|frame| !frame.is_priority())
|
||||
.count()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
use crate::CatCode;
|
||||
|
||||
/// Token access required by TeX's integer scanner.
|
||||
pub trait IntegerTokenStream {
|
||||
type Token: Clone;
|
||||
type Error;
|
||||
|
||||
fn next_token(&mut self) -> Result<Option<Self::Token>, Self::Error>;
|
||||
fn back_token(&mut self, token: Self::Token);
|
||||
fn character(&self, token: &Self::Token) -> Option<(char, CatCode)>;
|
||||
fn is_space(&self, token: &Self::Token) -> bool;
|
||||
fn is_command_reference(&self, token: &Self::Token) -> bool;
|
||||
fn control_sequence_name(&self, token: &Self::Token) -> Option<String>;
|
||||
fn scan_internal_integer(&mut self, token: Self::Token) -> Result<Option<i32>, Self::Error>;
|
||||
}
|
||||
|
||||
/// Failure while scanning an integer from a TeX token stream.
|
||||
#[derive(Debug)]
|
||||
pub enum IntegerScanError<Token, Error> {
|
||||
Stream(Error),
|
||||
CompatibilityRequired,
|
||||
MissingNumber(Option<Token>),
|
||||
TooLarge {
|
||||
token: Option<Token>,
|
||||
negative: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The scanned value and first token, retained for source diagnostics.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScannedInteger<Token> {
|
||||
pub value: i32,
|
||||
pub first_token: Token,
|
||||
}
|
||||
|
||||
pub fn scan_integer<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<i32, IntegerScanError<S::Token, S::Error>> {
|
||||
scan_integer_with_token(stream).map(|scanned| scanned.value)
|
||||
}
|
||||
|
||||
pub fn scan_integer_with_token<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<ScannedInteger<S::Token>, IntegerScanError<S::Token, S::Error>> {
|
||||
let (negative, first) = scan_signs(stream)?;
|
||||
let first_token = first.clone();
|
||||
let (value, scan_optional_space) = match stream.character(&first) {
|
||||
Some(('\'', CatCode::Other)) => (scan_radix_integer(stream, first, 8, negative)?, true),
|
||||
Some(('"', CatCode::Other)) => (scan_radix_integer(stream, first, 16, negative)?, true),
|
||||
Some(('`', CatCode::Other)) => (scan_character_integer(stream, first)?, false),
|
||||
Some((character, CatCode::Other)) if character.is_ascii_digit() => {
|
||||
(scan_decimal_integer(stream, first, negative)?, true)
|
||||
}
|
||||
_ if stream.is_command_reference(&first) => match stream
|
||||
.scan_internal_integer(first)
|
||||
.map_err(IntegerScanError::Stream)?
|
||||
{
|
||||
Some(value) => (value, false),
|
||||
None => return Err(IntegerScanError::CompatibilityRequired),
|
||||
},
|
||||
_ => return Err(IntegerScanError::MissingNumber(Some(first))),
|
||||
};
|
||||
|
||||
if scan_optional_space {
|
||||
consume_optional_space(stream)?;
|
||||
}
|
||||
let value = if negative {
|
||||
value.wrapping_mul(-1)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
Ok(ScannedInteger { value, first_token })
|
||||
}
|
||||
|
||||
fn scan_signs<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<(bool, S::Token), IntegerScanError<S::Token, S::Error>> {
|
||||
let mut negative = false;
|
||||
loop {
|
||||
let Some(token) = next_token(stream)? else {
|
||||
return Err(IntegerScanError::MissingNumber(None));
|
||||
};
|
||||
if stream.is_space(&token) {
|
||||
continue;
|
||||
}
|
||||
if let Some((character, CatCode::Other)) = stream.character(&token) {
|
||||
match character {
|
||||
'+' => continue,
|
||||
'-' => {
|
||||
negative = !negative;
|
||||
continue;
|
||||
}
|
||||
_ => return Ok((negative, token)),
|
||||
}
|
||||
}
|
||||
return Ok((negative, token));
|
||||
}
|
||||
}
|
||||
|
||||
fn scan_decimal_integer<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
first: S::Token,
|
||||
negative: bool,
|
||||
) -> Result<i32, IntegerScanError<S::Token, S::Error>> {
|
||||
let mut value = u64::from(digit(stream, &first).expect("first token is a decimal digit"));
|
||||
loop {
|
||||
let Some(token) = next_token(stream)? else {
|
||||
break;
|
||||
};
|
||||
let Some(digit) = digit(stream, &token) else {
|
||||
stream.back_token(token);
|
||||
break;
|
||||
};
|
||||
value = value
|
||||
.checked_mul(10)
|
||||
.and_then(|value| value.checked_add(u64::from(digit)))
|
||||
.ok_or_else(|| IntegerScanError::TooLarge {
|
||||
token: Some(first.clone()),
|
||||
negative,
|
||||
})?;
|
||||
}
|
||||
i32::try_from(value).map_err(|_| IntegerScanError::TooLarge {
|
||||
token: Some(first),
|
||||
negative,
|
||||
})
|
||||
}
|
||||
|
||||
fn scan_radix_integer<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
first: S::Token,
|
||||
radix: u8,
|
||||
negative: bool,
|
||||
) -> Result<i32, IntegerScanError<S::Token, S::Error>> {
|
||||
let mut value = 0_u64;
|
||||
let mut digit_count = 0;
|
||||
loop {
|
||||
let Some(token) = next_token(stream)? else {
|
||||
break;
|
||||
};
|
||||
let digit = match stream.character(&token) {
|
||||
Some((character, CatCode::Other | CatCode::Letter)) => {
|
||||
character.to_digit(u32::from(radix))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some(digit) = digit else {
|
||||
stream.back_token(token);
|
||||
break;
|
||||
};
|
||||
value = value
|
||||
.checked_mul(u64::from(radix))
|
||||
.and_then(|value| value.checked_add(u64::from(digit)))
|
||||
.ok_or_else(|| IntegerScanError::TooLarge {
|
||||
token: Some(first.clone()),
|
||||
negative,
|
||||
})?;
|
||||
digit_count += 1;
|
||||
}
|
||||
if digit_count == 0 || value > i32::MAX as u64 {
|
||||
return Err(IntegerScanError::TooLarge {
|
||||
token: Some(first),
|
||||
negative,
|
||||
});
|
||||
}
|
||||
Ok(value as i32)
|
||||
}
|
||||
|
||||
fn scan_character_integer<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
first: S::Token,
|
||||
) -> Result<i32, IntegerScanError<S::Token, S::Error>> {
|
||||
let character = next_token(stream)?
|
||||
.and_then(|token| {
|
||||
stream
|
||||
.character(&token)
|
||||
.map(|(character, _)| character)
|
||||
.or_else(|| {
|
||||
stream.control_sequence_name(&token).and_then(|name| {
|
||||
(name.chars().count() == 1)
|
||||
.then(|| name.chars().next())
|
||||
.flatten()
|
||||
})
|
||||
})
|
||||
})
|
||||
.ok_or(IntegerScanError::CompatibilityRequired)?;
|
||||
consume_optional_space(stream)?;
|
||||
i32::try_from(character as u32).map_err(|_| IntegerScanError::TooLarge {
|
||||
token: Some(first),
|
||||
negative: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn consume_optional_space<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<(), IntegerScanError<S::Token, S::Error>> {
|
||||
if let Some(token) = next_token(stream)? {
|
||||
if !stream.is_space(&token) {
|
||||
stream.back_token(token);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn next_token<S: IntegerTokenStream>(
|
||||
stream: &mut S,
|
||||
) -> Result<Option<S::Token>, IntegerScanError<S::Token, S::Error>> {
|
||||
stream.next_token().map_err(IntegerScanError::Stream)
|
||||
}
|
||||
|
||||
fn digit<S: IntegerTokenStream>(stream: &S, token: &S::Token) -> Option<u8> {
|
||||
match stream.character(token) {
|
||||
Some((character, CatCode::Other)) => character.to_digit(10).map(|digit| digit as u8),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/// Layout primitives whose scanning semantics are independent of a runtime VM.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LayoutPrimitive {
|
||||
ParagraphBreak,
|
||||
LineBreak,
|
||||
PageBreak,
|
||||
Penalty,
|
||||
Kern,
|
||||
HorizontalSkip,
|
||||
VerticalSkip,
|
||||
}
|
||||
|
||||
/// Typed effect produced after a layout primitive has scanned its operands.
|
||||
pub enum LayoutEffect<Dimension, Glue> {
|
||||
ParagraphBreak,
|
||||
LineBreak,
|
||||
PageBreak,
|
||||
Penalty(i32),
|
||||
Kern(Dimension),
|
||||
HorizontalGlue(Glue),
|
||||
VerticalGlue(Glue),
|
||||
}
|
||||
|
||||
/// Input and output boundary supplied by a compiler adapter.
|
||||
pub trait LayoutPrimitiveInput {
|
||||
type Error;
|
||||
type Dimension;
|
||||
type Glue;
|
||||
|
||||
fn scan_integer(&mut self) -> Result<i32, Self::Error>;
|
||||
fn scan_dimension(&mut self) -> Result<Self::Dimension, Self::Error>;
|
||||
fn scan_glue(&mut self) -> Result<Self::Glue, Self::Error>;
|
||||
fn emit(
|
||||
&mut self,
|
||||
effect: LayoutEffect<Self::Dimension, Self::Glue>,
|
||||
) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
/// Execute one layout primitive by scanning its operands and emitting one event.
|
||||
pub fn execute<S: LayoutPrimitiveInput>(
|
||||
primitive: LayoutPrimitive,
|
||||
input: &mut S,
|
||||
) -> Result<(), S::Error> {
|
||||
let effect = match primitive {
|
||||
LayoutPrimitive::ParagraphBreak => LayoutEffect::ParagraphBreak,
|
||||
LayoutPrimitive::LineBreak => LayoutEffect::LineBreak,
|
||||
LayoutPrimitive::PageBreak => LayoutEffect::PageBreak,
|
||||
LayoutPrimitive::Penalty => LayoutEffect::Penalty(input.scan_integer()?),
|
||||
LayoutPrimitive::Kern => LayoutEffect::Kern(input.scan_dimension()?),
|
||||
LayoutPrimitive::HorizontalSkip => LayoutEffect::HorizontalGlue(input.scan_glue()?),
|
||||
LayoutPrimitive::VerticalSkip => LayoutEffect::VerticalGlue(input.scan_glue()?),
|
||||
};
|
||||
input.emit(effect)
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
//! Primitive TeX value types shared by the Rust engine and compatibility adapters.
|
||||
|
||||
use CatCode::*;
|
||||
|
||||
pub mod assignment_scope;
|
||||
pub mod command;
|
||||
pub mod document;
|
||||
pub mod document_parser;
|
||||
pub mod environment;
|
||||
pub mod expanded;
|
||||
pub mod expansion;
|
||||
pub mod glue;
|
||||
pub mod input;
|
||||
pub mod integer;
|
||||
pub mod layout_primitive;
|
||||
pub mod macros;
|
||||
pub mod math_alphabet;
|
||||
pub mod math_code;
|
||||
pub mod math_constants;
|
||||
pub mod math_expr;
|
||||
pub mod math_glyph;
|
||||
pub mod math_layout;
|
||||
pub mod math_list;
|
||||
pub mod math_lowering;
|
||||
pub mod math_mode;
|
||||
pub mod math_parser;
|
||||
pub mod math_style;
|
||||
pub mod mouth;
|
||||
pub mod references;
|
||||
pub mod source;
|
||||
pub mod state;
|
||||
|
||||
pub use glue::{TeXGlue, TeXGlueOrder};
|
||||
pub use math_list::{MathBoundary, MathListContext, MathSpacingKind};
|
||||
pub use math_style::{MathStyle, MathStyleCommand};
|
||||
|
||||
/// TeX math atom class, used by noad construction and inter-atom spacing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MathClass {
|
||||
Ordinary,
|
||||
Operator,
|
||||
Binary,
|
||||
Relation,
|
||||
Opening,
|
||||
Closing,
|
||||
Punctuation,
|
||||
Inner,
|
||||
}
|
||||
|
||||
impl MathClass {
|
||||
pub fn index(self) -> usize {
|
||||
match self {
|
||||
Self::Ordinary => 0,
|
||||
Self::Operator => 1,
|
||||
Self::Binary => 2,
|
||||
Self::Relation => 3,
|
||||
Self::Opening => 4,
|
||||
Self::Closing => 5,
|
||||
Self::Punctuation => 6,
|
||||
Self::Inner => 7,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An engine-owned TeX command name, independent of any runtime interner.
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum EngineCommandName {
|
||||
/// A named control sequence such as `\\par`.
|
||||
ControlSequence(String),
|
||||
/// An active character token.
|
||||
ActiveCharacter(char),
|
||||
}
|
||||
|
||||
/// The value and category code of an engine-owned TeX token.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum EngineTokenValue {
|
||||
/// A control sequence that may be expanded or executed.
|
||||
ControlSequence(String),
|
||||
/// A character token with the category code captured by the mouth.
|
||||
Character { value: char, catcode: CatCode },
|
||||
/// An active character, which behaves like a control sequence.
|
||||
Active(char),
|
||||
}
|
||||
|
||||
/// A TeX token with a stable source-trace handle owned by the engine.
|
||||
#[derive(Clone, Debug)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct EngineToken {
|
||||
/// The token's semantic value.
|
||||
pub value: EngineTokenValue,
|
||||
/// Opaque handle used by the application adapter to recover source data.
|
||||
pub trace_id: u32,
|
||||
}
|
||||
|
||||
/// Enum representing all 16 category codes in TeX.
|
||||
///
|
||||
/// Each variant's documentation contains an example character which is mapped to that category code in plainTeX.
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum CatCode {
|
||||
/// Marks the beginning of a control sequence.
|
||||
/// Example: `\`.
|
||||
///
|
||||
/// This category code is never seen outside of the lexer.
|
||||
Escape = 0,
|
||||
/// Begins a new group.
|
||||
/// Example: `{`.
|
||||
BeginGroup = 1,
|
||||
/// Ends an existing new group.
|
||||
/// Example: `}`.
|
||||
EndGroup = 2,
|
||||
/// Starts or ends math mode.
|
||||
/// Example: `$`.
|
||||
MathShift = 3,
|
||||
/// Used in typesetting tables to align cells.
|
||||
/// Example: `&`.
|
||||
AlignmentTab = 4,
|
||||
/// Marks a new line in the input.
|
||||
/// Example: `\n`.
|
||||
///
|
||||
/// This code behaves similarly to [Space], but has two additional properties.
|
||||
/// First, two or more consecutive new lines, modulo intervening [Space] characters, create a `\par` control sequence
|
||||
/// instead of a regular space.
|
||||
/// Second, this code terminates a comment that started with a [Comment] character.
|
||||
///
|
||||
/// This category code is never seen outside of the lexer.
|
||||
EndOfLine = 5,
|
||||
/// Marks the beginning of a parameter number.
|
||||
/// It must generally be followed by a digit.
|
||||
/// Example: `#`.
|
||||
Parameter = 6,
|
||||
/// Puts following character or group in a superscript.
|
||||
/// Example: `^`.
|
||||
Superscript = 7,
|
||||
/// Puts following character or group in a subscript.
|
||||
/// Example: `_`.
|
||||
Subscript = 8,
|
||||
/// Character that is ignored by the lexer.
|
||||
/// Example: ASCII null (0).
|
||||
///
|
||||
/// This category code is never seen outside of the lexer.
|
||||
Ignored = 9,
|
||||
/// Whitespace. Example: ` `.
|
||||
Space = 10,
|
||||
/// A character that can be used as a control sequence name.
|
||||
/// Examples: `[a-zA-z]`.
|
||||
Letter = 11,
|
||||
/// A character than cannot be used as a control sequence name.
|
||||
/// Example: `@`.
|
||||
#[default]
|
||||
Other = 12,
|
||||
/// A single character that behaves like a control sequence.
|
||||
/// Example: `~`.
|
||||
Active = 13,
|
||||
/// Marks the beginning of a comment.
|
||||
/// All characters until the next [EndOfLine] are ignored.
|
||||
/// Example: `%`.
|
||||
///
|
||||
/// This category code is never seen outside of the lexer.
|
||||
Comment = 14,
|
||||
/// An invalid character.
|
||||
/// If this is encountered in the input, the lexer will return an error.
|
||||
/// Example: ASCII delete (127).
|
||||
///
|
||||
/// This category code is never seen outside of the lexer.
|
||||
Invalid = 15,
|
||||
}
|
||||
|
||||
/// A TeX math code value.
|
||||
///
|
||||
/// Its inner value is in the range 0 through 32768. The upper bound represents
|
||||
/// the math-active value used by `\mathcode`.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct MathCode(pub u16);
|
||||
|
||||
impl MathCode {
|
||||
/// The largest value accepted by the TeX `\mathcode` scanner.
|
||||
pub const MAX: usize = 32768;
|
||||
}
|
||||
|
||||
impl TryFrom<u8> for CatCode {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: u8) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
0 => Ok(Escape),
|
||||
1 => Ok(BeginGroup),
|
||||
2 => Ok(EndGroup),
|
||||
3 => Ok(MathShift),
|
||||
4 => Ok(AlignmentTab),
|
||||
5 => Ok(EndOfLine),
|
||||
6 => Ok(Parameter),
|
||||
7 => Ok(Superscript),
|
||||
8 => Ok(Subscript),
|
||||
9 => Ok(Ignored),
|
||||
10 => Ok(Space),
|
||||
11 => Ok(Letter),
|
||||
12 => Ok(Other),
|
||||
13 => Ok(Active),
|
||||
14 => Ok(Comment),
|
||||
15 => Ok(Invalid),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for CatCode {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{} ({})",
|
||||
*self as u8,
|
||||
match self {
|
||||
Escape => "escape",
|
||||
BeginGroup => "begin group",
|
||||
EndGroup => "end group",
|
||||
MathShift => "math shift",
|
||||
AlignmentTab => "alignment tab",
|
||||
EndOfLine => "end of line",
|
||||
Parameter => "parameter",
|
||||
Superscript => "superscript",
|
||||
Subscript => "subscript",
|
||||
Ignored => "ignored",
|
||||
Space => "space",
|
||||
Letter => "letter",
|
||||
Other => "other",
|
||||
Active => "active",
|
||||
Comment => "comment",
|
||||
Invalid => "invalid",
|
||||
}
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl CatCode {
|
||||
/// Default category codes in INITEX for all ASCII characters.
|
||||
///
|
||||
/// To find the category code for an ASCII character,
|
||||
/// convert it to an integer and use it as an index for the array.
|
||||
///
|
||||
/// This list was compiled by reading the source code TeX '82,
|
||||
/// specifically section 232 in the "TeX: the program".
|
||||
/// These defaults are also described in the TeXBook p343.
|
||||
pub const INITEX_DEFAULTS: [CatCode; 128] = [
|
||||
Ignored, // ASCII null
|
||||
Other, Other, Other, Other, Other, Other, Other, Other, Other,
|
||||
EndOfLine, // carriage return
|
||||
Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other,
|
||||
Other, Other, Other, Other, Other, Other, Other, Other, Space, // space
|
||||
Other, Other, Other, Other, Comment, // %
|
||||
Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other,
|
||||
Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other, Other,
|
||||
Other, Letter, // A
|
||||
Letter, // B
|
||||
Letter, // C
|
||||
Letter, // D
|
||||
Letter, // E
|
||||
Letter, // F
|
||||
Letter, // G
|
||||
Letter, // H
|
||||
Letter, // I
|
||||
Letter, // J
|
||||
Letter, // K
|
||||
Letter, // L
|
||||
Letter, // M
|
||||
Letter, // N
|
||||
Letter, // O
|
||||
Letter, // P
|
||||
Letter, // Q
|
||||
Letter, // R
|
||||
Letter, // S
|
||||
Letter, // T
|
||||
Letter, // U
|
||||
Letter, // V
|
||||
Letter, // W
|
||||
Letter, // X
|
||||
Letter, // Y
|
||||
Letter, // Z
|
||||
Other, Escape, // \
|
||||
Other, Other, Other, Other, Letter, // a
|
||||
Letter, // b
|
||||
Letter, // c
|
||||
Letter, // d
|
||||
Letter, // e
|
||||
Letter, // f
|
||||
Letter, // g
|
||||
Letter, // h
|
||||
Letter, // i
|
||||
Letter, // j
|
||||
Letter, // k
|
||||
Letter, // l
|
||||
Letter, // m
|
||||
Letter, // n
|
||||
Letter, // o
|
||||
Letter, // p
|
||||
Letter, // q
|
||||
Letter, // r
|
||||
Letter, // s
|
||||
Letter, // t
|
||||
Letter, // u
|
||||
Letter, // v
|
||||
Letter, // w
|
||||
Letter, // x
|
||||
Letter, // y
|
||||
Letter, // z
|
||||
Other, Other, Other, Other, Invalid, // ASCII delete
|
||||
];
|
||||
|
||||
/// Default category codes in plainTeX for all ASCII characters.
|
||||
///
|
||||
/// To find the category code for an ASCII character,
|
||||
/// convert it to an integer and use it as an index for the array.
|
||||
///
|
||||
/// This list was compiled by starting with [INITEX_DEFAULTS](CatCode::INITEX_DEFAULTS) and then applying
|
||||
/// all category code changes in the plainTeX format.
|
||||
/// These changes are described on p343 of the TeXBook.
|
||||
pub const PLAIN_TEX_DEFAULTS: [CatCode; 128] = [
|
||||
Ignored, // ASCII null
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Space, // horizontal tab (\t)
|
||||
EndOfLine, // line feed (\n)
|
||||
Other,
|
||||
Active, // ASCII form-feed
|
||||
EndOfLine, // carriage return (\r)
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Space, // space
|
||||
Other,
|
||||
Other,
|
||||
Parameter, // #
|
||||
MathShift, // $
|
||||
Comment, // %
|
||||
AlignmentTab, // &
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Other,
|
||||
Letter, // A
|
||||
Letter, // B
|
||||
Letter, // C
|
||||
Letter, // D
|
||||
Letter, // E
|
||||
Letter, // F
|
||||
Letter, // G
|
||||
Letter, // H
|
||||
Letter, // I
|
||||
Letter, // J
|
||||
Letter, // K
|
||||
Letter, // L
|
||||
Letter, // M
|
||||
Letter, // N
|
||||
Letter, // O
|
||||
Letter, // P
|
||||
Letter, // Q
|
||||
Letter, // R
|
||||
Letter, // S
|
||||
Letter, // T
|
||||
Letter, // U
|
||||
Letter, // V
|
||||
Letter, // W
|
||||
Letter, // X
|
||||
Letter, // Y
|
||||
Letter, // Z
|
||||
Other,
|
||||
Escape, // \
|
||||
Other,
|
||||
Superscript, // ^
|
||||
Subscript, // _
|
||||
Other,
|
||||
Letter, // a
|
||||
Letter, // b
|
||||
Letter, // c
|
||||
Letter, // d
|
||||
Letter, // e
|
||||
Letter, // f
|
||||
Letter, // g
|
||||
Letter, // h
|
||||
Letter, // i
|
||||
Letter, // j
|
||||
Letter, // k
|
||||
Letter, // l
|
||||
Letter, // m
|
||||
Letter, // n
|
||||
Letter, // o
|
||||
Letter, // p
|
||||
Letter, // q
|
||||
Letter, // r
|
||||
Letter, // s
|
||||
Letter, // t
|
||||
Letter, // u
|
||||
Letter, // v
|
||||
Letter, // w
|
||||
Letter, // x
|
||||
Letter, // y
|
||||
Letter, // z
|
||||
BeginGroup, // {
|
||||
Other,
|
||||
EndGroup, // }
|
||||
Active, // ~
|
||||
Invalid, // ASCII delete
|
||||
];
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn serialize_and_deserialize_cat_code() {
|
||||
let all_raw_cat_codes = vec![
|
||||
CatCode::BeginGroup,
|
||||
CatCode::EndGroup,
|
||||
CatCode::MathShift,
|
||||
CatCode::AlignmentTab,
|
||||
CatCode::Parameter,
|
||||
CatCode::Superscript,
|
||||
CatCode::Subscript,
|
||||
CatCode::Space,
|
||||
CatCode::Letter,
|
||||
CatCode::Other,
|
||||
CatCode::Active,
|
||||
CatCode::Escape,
|
||||
CatCode::EndOfLine,
|
||||
CatCode::Ignored,
|
||||
CatCode::Comment,
|
||||
CatCode::Invalid,
|
||||
];
|
||||
for cat_code in all_raw_cat_codes {
|
||||
let u: u8 = cat_code as u8;
|
||||
let recovered: CatCode = u.try_into().unwrap();
|
||||
assert_eq!(recovered, cat_code);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{CatCode as EngineCatCode, EngineCommandName, EngineToken, EngineTokenValue};
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MacroDefinition {
|
||||
pub prefix: Vec<EngineTokenValue>,
|
||||
pub parameters: Vec<MacroParameter>,
|
||||
pub optional_first_default: Option<Vec<EngineToken>>,
|
||||
pub replacement: Vec<Replacement>,
|
||||
#[serde(default)]
|
||||
pub is_long: bool,
|
||||
#[serde(default)]
|
||||
pub is_outer: bool,
|
||||
}
|
||||
|
||||
impl MacroDefinition {
|
||||
pub fn instantiate(&self, arguments: &[Vec<EngineToken>]) -> Vec<EngineToken> {
|
||||
let mut expansion = Vec::new();
|
||||
for item in &self.replacement {
|
||||
match item {
|
||||
Replacement::Tokens(tokens) => {
|
||||
expansion.extend(tokens.iter().cloned());
|
||||
}
|
||||
Replacement::Parameter(index) => {
|
||||
expansion.extend(arguments[*index].iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
expansion
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MacroParameter {
|
||||
pub delimiter: Vec<EngineTokenValue>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Replacement {
|
||||
Tokens(Vec<EngineToken>),
|
||||
Parameter(usize),
|
||||
}
|
||||
|
||||
pub trait MacroDefinitionTokenStream {
|
||||
type Error;
|
||||
|
||||
fn next_unexpanded(&mut self) -> Result<Option<EngineToken>, Self::Error>;
|
||||
fn is_outer_macro(&self, token: &EngineToken) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum MacroDefinitionErrorStream {
|
||||
Input,
|
||||
Unexpanded,
|
||||
}
|
||||
|
||||
pub enum MacroDefinitionScanError<E> {
|
||||
Stream(E),
|
||||
Macro {
|
||||
token: EngineToken,
|
||||
message: String,
|
||||
stream: MacroDefinitionErrorStream,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct ScannedMacroDefinition {
|
||||
pub target: EngineToken,
|
||||
pub parameter_text: Vec<EngineToken>,
|
||||
pub replacement_text: Vec<EngineToken>,
|
||||
}
|
||||
|
||||
pub fn scan_tex_macro_definition<S: MacroDefinitionTokenStream>(
|
||||
stream: &mut S,
|
||||
command: &EngineToken,
|
||||
) -> Result<ScannedMacroDefinition, MacroDefinitionScanError<S::Error>> {
|
||||
let target = loop {
|
||||
let Some(token) = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroDefinitionScanError::Stream)?
|
||||
else {
|
||||
return Err(macro_definition_error(
|
||||
command,
|
||||
"macro definition expects a control sequence",
|
||||
MacroDefinitionErrorStream::Input,
|
||||
));
|
||||
};
|
||||
if is_space(&token) {
|
||||
continue;
|
||||
}
|
||||
break token;
|
||||
};
|
||||
|
||||
if !is_command(&target) {
|
||||
return Err(macro_definition_error(
|
||||
&target,
|
||||
"macro definition expects a control sequence or active character",
|
||||
MacroDefinitionErrorStream::Input,
|
||||
));
|
||||
}
|
||||
|
||||
let mut parameter_text = Vec::new();
|
||||
loop {
|
||||
let Some(next) = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroDefinitionScanError::Stream)?
|
||||
else {
|
||||
return Err(macro_definition_error(
|
||||
command,
|
||||
"unterminated macro definition",
|
||||
MacroDefinitionErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
reject_outer_macro(stream, &next)?;
|
||||
|
||||
if is_begin_group(&next) {
|
||||
let replacement_text = read_braced_replacement(stream, command)?;
|
||||
return Ok(ScannedMacroDefinition {
|
||||
target,
|
||||
parameter_text,
|
||||
replacement_text,
|
||||
});
|
||||
}
|
||||
if is_end_group(&next) {
|
||||
return Err(macro_definition_error(
|
||||
&next,
|
||||
"unexpected end group while reading macro parameters",
|
||||
MacroDefinitionErrorStream::Input,
|
||||
));
|
||||
}
|
||||
if is_parameter(&next) {
|
||||
let Some(parameter_part) = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroDefinitionScanError::Stream)?
|
||||
else {
|
||||
return Err(macro_definition_error(
|
||||
command,
|
||||
"unterminated macro parameter text",
|
||||
MacroDefinitionErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
reject_outer_macro(stream, ¶meter_part)?;
|
||||
if is_begin_group(¶meter_part) {
|
||||
parameter_text.push(parameter_part.clone());
|
||||
let mut replacement_text =
|
||||
read_replacement_after_special_open(stream, command, ¶meter_part)?;
|
||||
replacement_text.push(parameter_part);
|
||||
return Ok(ScannedMacroDefinition {
|
||||
target,
|
||||
parameter_text,
|
||||
replacement_text,
|
||||
});
|
||||
}
|
||||
parameter_text.push(next);
|
||||
parameter_text.push(parameter_part);
|
||||
continue;
|
||||
}
|
||||
parameter_text.push(next);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_braced_replacement<S: MacroDefinitionTokenStream>(
|
||||
stream: &mut S,
|
||||
command: &EngineToken,
|
||||
) -> Result<Vec<EngineToken>, MacroDefinitionScanError<S::Error>> {
|
||||
let mut depth = 1usize;
|
||||
let mut replacement = Vec::new();
|
||||
loop {
|
||||
let Some(next) = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroDefinitionScanError::Stream)?
|
||||
else {
|
||||
return Err(macro_definition_error(
|
||||
command,
|
||||
"unterminated braced command argument",
|
||||
MacroDefinitionErrorStream::Input,
|
||||
));
|
||||
};
|
||||
reject_outer_macro(stream, &next)?;
|
||||
if is_begin_group(&next) {
|
||||
depth += 1;
|
||||
replacement.push(next);
|
||||
} else if is_end_group(&next) {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
return Ok(replacement);
|
||||
}
|
||||
replacement.push(next);
|
||||
} else {
|
||||
replacement.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_replacement_after_special_open<S: MacroDefinitionTokenStream>(
|
||||
stream: &mut S,
|
||||
command: &EngineToken,
|
||||
opening: &EngineToken,
|
||||
) -> Result<Vec<EngineToken>, MacroDefinitionScanError<S::Error>> {
|
||||
let mut depth = 0usize;
|
||||
let mut replacement = Vec::new();
|
||||
loop {
|
||||
let Some(next) = stream
|
||||
.next_unexpanded()
|
||||
.map_err(MacroDefinitionScanError::Stream)?
|
||||
else {
|
||||
let delimiter = match opening.value {
|
||||
EngineTokenValue::Character { value, .. } => value,
|
||||
_ => '{',
|
||||
};
|
||||
return Err(macro_definition_error(
|
||||
command,
|
||||
&format!("unterminated macro replacement after special delimiter `{delimiter}`"),
|
||||
MacroDefinitionErrorStream::Unexpanded,
|
||||
));
|
||||
};
|
||||
reject_outer_macro(stream, &next)?;
|
||||
if is_begin_group(&next) {
|
||||
depth += 1;
|
||||
replacement.push(next);
|
||||
} else if is_end_group(&next) {
|
||||
if depth == 0 {
|
||||
return Ok(replacement);
|
||||
}
|
||||
depth -= 1;
|
||||
replacement.push(next);
|
||||
} else {
|
||||
replacement.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reject_outer_macro<S: MacroDefinitionTokenStream>(
|
||||
stream: &S,
|
||||
token: &EngineToken,
|
||||
) -> Result<(), MacroDefinitionScanError<S::Error>> {
|
||||
if stream.is_outer_macro(token) {
|
||||
return Err(macro_definition_error(
|
||||
token,
|
||||
"outer macro is forbidden while scanning a definition or argument",
|
||||
MacroDefinitionErrorStream::Input,
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn macro_definition_error<E>(
|
||||
token: &EngineToken,
|
||||
message: impl Into<String>,
|
||||
stream: MacroDefinitionErrorStream,
|
||||
) -> MacroDefinitionScanError<E> {
|
||||
MacroDefinitionScanError::Macro {
|
||||
token: token.clone(),
|
||||
message: message.into(),
|
||||
stream,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_space(token: &EngineToken) -> bool {
|
||||
matches!(
|
||||
token.value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::Space,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_begin_group(token: &EngineToken) -> bool {
|
||||
matches!(
|
||||
token.value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::BeginGroup,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_end_group(token: &EngineToken) -> bool {
|
||||
matches!(
|
||||
token.value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::EndGroup,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_parameter(token: &EngineToken) -> bool {
|
||||
matches!(
|
||||
token.value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::Parameter,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn is_command(token: &EngineToken) -> bool {
|
||||
matches!(
|
||||
token.value,
|
||||
EngineTokenValue::ControlSequence(_) | EngineTokenValue::Active(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub struct MacroDefinitionParseError {
|
||||
pub token_index: usize,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub fn parse_tex_macro_parameters(
|
||||
parameter_text: &[EngineTokenValue],
|
||||
) -> Result<(Vec<EngineTokenValue>, Vec<MacroParameter>), MacroDefinitionParseError> {
|
||||
let mut prefix = Vec::new();
|
||||
let mut parameters: Vec<MacroParameter> = Vec::new();
|
||||
let mut between = Vec::new();
|
||||
let mut cursor = 0;
|
||||
while cursor < parameter_text.len() {
|
||||
let current = ¶meter_text[cursor];
|
||||
if !is_parameter_value(current) {
|
||||
between.push(current.clone());
|
||||
cursor += 1;
|
||||
continue;
|
||||
}
|
||||
let Some(number_token) = parameter_text.get(cursor + 1) else {
|
||||
return Err(MacroDefinitionParseError {
|
||||
token_index: cursor,
|
||||
message: "parameter marker must be followed by a number from 1 to 9".into(),
|
||||
});
|
||||
};
|
||||
let expected_number = parameters.len() + 1;
|
||||
let valid_number = token_character(number_token)
|
||||
.filter(char::is_ascii_digit)
|
||||
.and_then(|character| character.to_digit(10))
|
||||
.is_some_and(|number| number as usize == expected_number);
|
||||
if expected_number > 9 || !valid_number {
|
||||
return Err(MacroDefinitionParseError {
|
||||
token_index: cursor + 1,
|
||||
message: format!("expected macro parameter #{expected_number}"),
|
||||
});
|
||||
}
|
||||
if let Some(previous) = parameters.last_mut() {
|
||||
previous.delimiter = std::mem::take(&mut between);
|
||||
} else {
|
||||
prefix = std::mem::take(&mut between);
|
||||
}
|
||||
parameters.push(MacroParameter {
|
||||
delimiter: Vec::new(),
|
||||
});
|
||||
cursor += 2;
|
||||
}
|
||||
if let Some(last) = parameters.last_mut() {
|
||||
last.delimiter = between;
|
||||
} else {
|
||||
prefix = between;
|
||||
}
|
||||
Ok((prefix, parameters))
|
||||
}
|
||||
|
||||
pub fn parse_macro_replacement(
|
||||
replacement: &[EngineToken],
|
||||
arity: u8,
|
||||
) -> Result<Vec<Replacement>, MacroDefinitionParseError> {
|
||||
let mut result = Vec::new();
|
||||
let mut literal_tokens = Vec::new();
|
||||
let mut cursor = 0;
|
||||
while cursor < replacement.len() {
|
||||
let current = &replacement[cursor];
|
||||
if !is_parameter_value(¤t.value) {
|
||||
literal_tokens.push(current.clone());
|
||||
cursor += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(next) = replacement.get(cursor + 1) else {
|
||||
return Err(MacroDefinitionParseError {
|
||||
token_index: cursor,
|
||||
message: "parameter marker must be followed by `#` or a parameter number".into(),
|
||||
});
|
||||
};
|
||||
if is_parameter_value(&next.value) {
|
||||
literal_tokens.push(next.clone());
|
||||
cursor += 2;
|
||||
continue;
|
||||
}
|
||||
let parameter_number = token_character(&next.value)
|
||||
.filter(char::is_ascii_digit)
|
||||
.and_then(|character| character.to_digit(10))
|
||||
.and_then(|number| u8::try_from(number).ok())
|
||||
.filter(|number| *number > 0 && *number <= arity)
|
||||
.ok_or_else(|| MacroDefinitionParseError {
|
||||
token_index: cursor + 1,
|
||||
message: format!("parameter number must be between 1 and {arity}"),
|
||||
})?;
|
||||
|
||||
if !literal_tokens.is_empty() {
|
||||
result.push(Replacement::Tokens(std::mem::take(&mut literal_tokens)));
|
||||
}
|
||||
result.push(Replacement::Parameter(usize::from(parameter_number - 1)));
|
||||
cursor += 2;
|
||||
}
|
||||
if !literal_tokens.is_empty() {
|
||||
result.push(Replacement::Tokens(literal_tokens));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn is_parameter_value(value: &EngineTokenValue) -> bool {
|
||||
matches!(
|
||||
value,
|
||||
EngineTokenValue::Character {
|
||||
catcode: EngineCatCode::Parameter,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fn token_character(value: &EngineTokenValue) -> Option<char> {
|
||||
match value {
|
||||
EngineTokenValue::Character { value, .. } => Some(*value),
|
||||
EngineTokenValue::ControlSequence(_) | EngineTokenValue::Active(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MacroTable {
|
||||
definitions: HashMap<EngineCommandName, MacroDefinition>,
|
||||
groups: Vec<HashMap<EngineCommandName, Option<MacroDefinition>>>,
|
||||
}
|
||||
|
||||
impl MacroTable {
|
||||
pub fn get(&self, name: &EngineCommandName) -> Option<&MacroDefinition> {
|
||||
self.definitions.get(name)
|
||||
}
|
||||
|
||||
pub fn define(&mut self, name: EngineCommandName, definition: MacroDefinition, global: bool) {
|
||||
self.prepare_assignment(&name, global);
|
||||
self.definitions.insert(name, definition);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, name: EngineCommandName, global: bool) {
|
||||
self.prepare_assignment(&name, global);
|
||||
self.definitions.remove(&name);
|
||||
}
|
||||
|
||||
fn prepare_assignment(&mut self, name: &EngineCommandName, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.remove(name);
|
||||
}
|
||||
} else if let Some(group) = self.groups.last_mut() {
|
||||
group
|
||||
.entry(name.clone())
|
||||
.or_insert_with(|| self.definitions.get(name).cloned());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(HashMap::new());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (name, previous) in group {
|
||||
match previous {
|
||||
Some(definition) => {
|
||||
self.definitions.insert(name, definition);
|
||||
}
|
||||
None => {
|
||||
self.definitions.remove(&name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
use std::path::Path;
|
||||
|
||||
use crate::math_expr::{MathExpr, MathFontFamilies, MathFontStyle};
|
||||
use crate::{MathClass, MathStyle};
|
||||
|
||||
/// A Unicode mathematical alphabet selected by a TeX math font command.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MathAlphabet {
|
||||
Bold,
|
||||
BoldItalic,
|
||||
BoldScript,
|
||||
BoldFraktur,
|
||||
Italic,
|
||||
Script,
|
||||
Fraktur,
|
||||
DoubleStruck,
|
||||
SansSerif,
|
||||
SansSerifBold,
|
||||
SansSerifItalic,
|
||||
SansSerifBoldItalic,
|
||||
}
|
||||
|
||||
/// Selects a Unicode mathematical alphabet for a TeX math font style.
|
||||
pub fn for_font_style(font: MathFontStyle, bold: bool, italic: bool) -> Option<MathAlphabet> {
|
||||
Some(match font {
|
||||
MathFontStyle::Bold => {
|
||||
if italic {
|
||||
MathAlphabet::BoldItalic
|
||||
} else {
|
||||
MathAlphabet::Bold
|
||||
}
|
||||
}
|
||||
MathFontStyle::BoldRoman => MathAlphabet::Bold,
|
||||
MathFontStyle::Italic => MathAlphabet::Italic,
|
||||
MathFontStyle::Calligraphic => {
|
||||
if bold {
|
||||
MathAlphabet::BoldScript
|
||||
} else {
|
||||
MathAlphabet::Script
|
||||
}
|
||||
}
|
||||
MathFontStyle::Fraktur => {
|
||||
if bold {
|
||||
MathAlphabet::BoldFraktur
|
||||
} else {
|
||||
MathAlphabet::Fraktur
|
||||
}
|
||||
}
|
||||
MathFontStyle::Blackboard => MathAlphabet::DoubleStruck,
|
||||
MathFontStyle::SansSerif => match (bold, italic) {
|
||||
(false, false) => MathAlphabet::SansSerif,
|
||||
(true, false) => MathAlphabet::SansSerifBold,
|
||||
(false, true) => MathAlphabet::SansSerifItalic,
|
||||
(true, true) => MathAlphabet::SansSerifBoldItalic,
|
||||
},
|
||||
MathFontStyle::Monospace | MathFontStyle::Roman | MathFontStyle::Text => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies a Unicode math alphabet to ordinary atoms, consulting the backend
|
||||
/// only for glyph availability in the selected family and default math font.
|
||||
pub fn transform_expression(
|
||||
expression: &MathExpr,
|
||||
alphabet: MathAlphabet,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
math_style: MathStyle,
|
||||
has_selected_font_glyph: impl Fn(&Path, char) -> bool,
|
||||
has_default_math_glyph: impl Fn(char) -> bool,
|
||||
) -> MathExpr {
|
||||
fn transform(
|
||||
expression: &MathExpr,
|
||||
alphabet: MathAlphabet,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
math_style: MathStyle,
|
||||
has_selected_font_glyph: &impl Fn(&Path, char) -> bool,
|
||||
has_default_math_glyph: &impl Fn(char) -> bool,
|
||||
) -> MathExpr {
|
||||
match expression {
|
||||
MathExpr::Spanned {
|
||||
location,
|
||||
expression,
|
||||
} => MathExpr::Spanned {
|
||||
location: location.clone(),
|
||||
expression: Box::new(transform(
|
||||
expression,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
},
|
||||
MathExpr::Styled { .. } => expression.clone(),
|
||||
MathExpr::Classified { class, body } => MathExpr::Classified {
|
||||
class: *class,
|
||||
body: Box::new(transform(
|
||||
body,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
},
|
||||
MathExpr::Phantom { kind, body } => MathExpr::Phantom {
|
||||
kind: *kind,
|
||||
body: Box::new(transform(
|
||||
body,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
},
|
||||
MathExpr::Accent {
|
||||
position,
|
||||
body,
|
||||
family,
|
||||
math_fonts,
|
||||
} => MathExpr::Accent {
|
||||
position: *position,
|
||||
body: Box::new(transform(
|
||||
body,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
family: *family,
|
||||
math_fonts: math_fonts.clone(),
|
||||
},
|
||||
MathExpr::Sequence(items) => MathExpr::Sequence(
|
||||
items
|
||||
.iter()
|
||||
.map(|item| {
|
||||
transform(
|
||||
item,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
MathExpr::Alignment {
|
||||
rows,
|
||||
alignment,
|
||||
baseline,
|
||||
math_fonts,
|
||||
cell_style,
|
||||
row_spacing,
|
||||
} => MathExpr::Alignment {
|
||||
rows: rows
|
||||
.iter()
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(|item| {
|
||||
transform(
|
||||
item,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect(),
|
||||
alignment: alignment.clone(),
|
||||
baseline: *baseline,
|
||||
math_fonts: math_fonts.clone(),
|
||||
cell_style: *cell_style,
|
||||
row_spacing: *row_spacing,
|
||||
},
|
||||
MathExpr::Fraction {
|
||||
numerator,
|
||||
denominator,
|
||||
style,
|
||||
has_rule,
|
||||
rule_thickness,
|
||||
math_fonts,
|
||||
} => MathExpr::Fraction {
|
||||
numerator: Box::new(transform(
|
||||
numerator,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
denominator: Box::new(transform(
|
||||
denominator,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
style: *style,
|
||||
has_rule: *has_rule,
|
||||
rule_thickness: *rule_thickness,
|
||||
math_fonts: math_fonts.clone(),
|
||||
},
|
||||
MathExpr::MathChoice {
|
||||
display,
|
||||
text,
|
||||
script,
|
||||
scriptscript,
|
||||
} => MathExpr::MathChoice {
|
||||
display: Box::new(transform(
|
||||
display,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
text: Box::new(transform(
|
||||
text,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
script: Box::new(transform(
|
||||
script,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
scriptscript: Box::new(transform(
|
||||
scriptscript,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
},
|
||||
MathExpr::Root {
|
||||
index,
|
||||
body,
|
||||
radical,
|
||||
math_fonts,
|
||||
} => MathExpr::Root {
|
||||
index: index.as_deref().map(|index| {
|
||||
Box::new(transform(
|
||||
index,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
))
|
||||
}),
|
||||
body: Box::new(transform(
|
||||
body,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
radical: *radical,
|
||||
math_fonts: math_fonts.clone(),
|
||||
},
|
||||
MathExpr::Delimited {
|
||||
left,
|
||||
body,
|
||||
right,
|
||||
left_settings,
|
||||
right_settings,
|
||||
} => MathExpr::Delimited {
|
||||
left: left.clone(),
|
||||
body: Box::new(transform(
|
||||
body,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
right: right.clone(),
|
||||
left_settings: *left_settings,
|
||||
right_settings: *right_settings,
|
||||
},
|
||||
MathExpr::Fenced {
|
||||
delimiters,
|
||||
delimiter_settings,
|
||||
segments,
|
||||
} => MathExpr::Fenced {
|
||||
delimiters: delimiters.clone(),
|
||||
delimiter_settings: delimiter_settings.clone(),
|
||||
segments: segments
|
||||
.iter()
|
||||
.map(|segment| {
|
||||
transform(
|
||||
segment,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
MathExpr::Script {
|
||||
base,
|
||||
sub,
|
||||
superscript,
|
||||
limits,
|
||||
} => MathExpr::Script {
|
||||
base: Box::new(transform(
|
||||
base,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
)),
|
||||
sub: sub.as_deref().map(|sub| {
|
||||
Box::new(transform(
|
||||
sub,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
))
|
||||
}),
|
||||
superscript: superscript.as_deref().map(|superscript| {
|
||||
Box::new(transform(
|
||||
superscript,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
))
|
||||
}),
|
||||
limits: *limits,
|
||||
},
|
||||
MathExpr::Atom {
|
||||
class: MathClass::Ordinary,
|
||||
text,
|
||||
math_family,
|
||||
math_slots,
|
||||
math_fonts,
|
||||
} => transform_atom(
|
||||
expression,
|
||||
text,
|
||||
*math_family,
|
||||
math_slots,
|
||||
math_fonts,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
has_selected_font_glyph,
|
||||
has_default_math_glyph,
|
||||
),
|
||||
MathExpr::Text(_)
|
||||
| MathExpr::TextStyled { .. }
|
||||
| MathExpr::Atom { .. }
|
||||
| MathExpr::MathSpacingChange(_)
|
||||
| MathExpr::MathLineBreakPenaltiesChange(_)
|
||||
| MathExpr::BreakPenalty(_)
|
||||
| MathExpr::MathStyleChange(_)
|
||||
| MathExpr::Space(_)
|
||||
| MathExpr::Glue(_)
|
||||
| MathExpr::Kern(_)
|
||||
| MathExpr::SizedDelimiter { .. }
|
||||
| MathExpr::UnicodeDelimiter { .. } => expression.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
transform(
|
||||
expression,
|
||||
alphabet,
|
||||
bold,
|
||||
italic,
|
||||
math_style,
|
||||
&has_selected_font_glyph,
|
||||
&has_default_math_glyph,
|
||||
)
|
||||
}
|
||||
|
||||
fn transform_atom(
|
||||
original: &MathExpr,
|
||||
text: &str,
|
||||
math_family: Option<u8>,
|
||||
math_slots: &[u8],
|
||||
math_fonts: &MathFontFamilies,
|
||||
alphabet: MathAlphabet,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
math_style: MathStyle,
|
||||
has_selected_font_glyph: &impl Fn(&Path, char) -> bool,
|
||||
has_default_math_glyph: &impl Fn(char) -> bool,
|
||||
) -> MathExpr {
|
||||
let glyph_text = crate::math_glyph::math_atom_glyph_text(text, math_family, math_slots);
|
||||
let characters = glyph_text.chars().collect::<Vec<_>>();
|
||||
let has_aligned_slots = math_family.is_some() && math_slots.len() == characters.len();
|
||||
let selected_font = math_family
|
||||
.and_then(|family| math_fonts.get(&family))
|
||||
.and_then(|selection| selection.for_style(math_style));
|
||||
let mut transformed = false;
|
||||
let mut items = Vec::with_capacity(characters.len());
|
||||
for (index, character) in characters.into_iter().enumerate() {
|
||||
let alphabet_character = self::character(character, alphabet);
|
||||
let mapped = alphabet_character.and_then(|mapped| {
|
||||
if selected_font.is_some_and(|path| has_selected_font_glyph(path.as_path(), mapped)) {
|
||||
Some((mapped, true))
|
||||
} else if has_default_math_glyph(mapped) {
|
||||
Some((mapped, false))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some((mapped, use_selected_font)) = mapped {
|
||||
transformed = true;
|
||||
items.push(MathExpr::Atom {
|
||||
class: MathClass::Ordinary,
|
||||
text: mapped.to_string(),
|
||||
math_family: use_selected_font.then_some(math_family).flatten(),
|
||||
math_slots: Vec::new(),
|
||||
math_fonts: math_fonts.clone(),
|
||||
});
|
||||
} else if alphabet_character.is_some() {
|
||||
transformed = true;
|
||||
items.push(MathExpr::TextStyled {
|
||||
text: character.to_string(),
|
||||
bold,
|
||||
italic,
|
||||
monospace: false,
|
||||
});
|
||||
} else {
|
||||
items.push(MathExpr::Atom {
|
||||
class: MathClass::Ordinary,
|
||||
text: character.to_string(),
|
||||
math_family,
|
||||
math_slots: if has_aligned_slots {
|
||||
vec![math_slots[index]]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
math_fonts: math_fonts.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
if !transformed {
|
||||
return original.clone();
|
||||
}
|
||||
match items.len() {
|
||||
0 => MathExpr::Sequence(Vec::new()),
|
||||
1 => items.pop().expect("one alphabet atom was built"),
|
||||
_ => MathExpr::Sequence(items),
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a TeX math letter or supported Greek symbol to its Unicode alphabet form.
|
||||
pub fn character(character: char, alphabet: MathAlphabet) -> Option<char> {
|
||||
let codepoint = match character {
|
||||
'A'..='Z' => {
|
||||
let offset = u32::from(character) - u32::from('A');
|
||||
match alphabet {
|
||||
MathAlphabet::Bold => 0x1D400 + offset,
|
||||
MathAlphabet::BoldItalic => 0x1D468 + offset,
|
||||
MathAlphabet::Italic => 0x1D434 + offset,
|
||||
MathAlphabet::Script => match character {
|
||||
'B' => 0x212C,
|
||||
'E' => 0x2130,
|
||||
'F' => 0x2131,
|
||||
'H' => 0x210B,
|
||||
'I' => 0x2110,
|
||||
'L' => 0x2112,
|
||||
'M' => 0x2133,
|
||||
'R' => 0x211B,
|
||||
_ => 0x1D49C + offset,
|
||||
},
|
||||
MathAlphabet::BoldScript => 0x1D4D0 + offset,
|
||||
MathAlphabet::Fraktur => match character {
|
||||
'C' => 0x212D,
|
||||
'H' => 0x210C,
|
||||
'I' => 0x2111,
|
||||
'R' => 0x211C,
|
||||
_ => 0x1D504 + offset,
|
||||
},
|
||||
MathAlphabet::BoldFraktur => 0x1D56C + offset,
|
||||
MathAlphabet::DoubleStruck => match character {
|
||||
'C' => 0x2102,
|
||||
'H' => 0x210D,
|
||||
'N' => 0x2115,
|
||||
'P' => 0x2119,
|
||||
'Q' => 0x211A,
|
||||
'R' => 0x211D,
|
||||
'Z' => 0x2124,
|
||||
_ => 0x1D538 + offset,
|
||||
},
|
||||
MathAlphabet::SansSerif => 0x1D5A0 + offset,
|
||||
MathAlphabet::SansSerifBold => 0x1D5D4 + offset,
|
||||
MathAlphabet::SansSerifItalic => 0x1D608 + offset,
|
||||
MathAlphabet::SansSerifBoldItalic => 0x1D63C + offset,
|
||||
}
|
||||
}
|
||||
'a'..='z' => {
|
||||
let offset = u32::from(character) - u32::from('a');
|
||||
match alphabet {
|
||||
MathAlphabet::Bold => 0x1D41A + offset,
|
||||
MathAlphabet::BoldItalic => 0x1D482 + offset,
|
||||
MathAlphabet::Italic if character == 'h' => 0x210E,
|
||||
MathAlphabet::Italic => 0x1D44E + offset,
|
||||
MathAlphabet::Script => match character {
|
||||
'e' => 0x212F,
|
||||
'g' => 0x210A,
|
||||
'l' => 0x2113,
|
||||
'o' => 0x2134,
|
||||
_ => 0x1D4B6 + offset,
|
||||
},
|
||||
MathAlphabet::BoldScript => 0x1D4EA + offset,
|
||||
MathAlphabet::Fraktur => 0x1D51E + offset,
|
||||
MathAlphabet::BoldFraktur => 0x1D586 + offset,
|
||||
MathAlphabet::DoubleStruck => 0x1D552 + offset,
|
||||
MathAlphabet::SansSerif => 0x1D5BA + offset,
|
||||
MathAlphabet::SansSerifBold => 0x1D5EE + offset,
|
||||
MathAlphabet::SansSerifItalic => 0x1D622 + offset,
|
||||
MathAlphabet::SansSerifBoldItalic => 0x1D656 + offset,
|
||||
}
|
||||
}
|
||||
'0'..='9' => {
|
||||
let offset = u32::from(character) - u32::from('0');
|
||||
match alphabet {
|
||||
MathAlphabet::Bold => 0x1D7CE + offset,
|
||||
MathAlphabet::DoubleStruck => 0x1D7D8 + offset,
|
||||
MathAlphabet::SansSerif => 0x1D7E2 + offset,
|
||||
MathAlphabet::SansSerifBold => 0x1D7EC + offset,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
_ => return greek_math_alphabet_character(character, alphabet),
|
||||
};
|
||||
char::from_u32(codepoint)
|
||||
}
|
||||
|
||||
fn greek_math_alphabet_character(character: char, alphabet: MathAlphabet) -> Option<char> {
|
||||
let style_base = match alphabet {
|
||||
MathAlphabet::Bold => 0x1D6A8,
|
||||
MathAlphabet::Italic => 0x1D6E2,
|
||||
MathAlphabet::BoldItalic => 0x1D71C,
|
||||
MathAlphabet::SansSerifBold => 0x1D756,
|
||||
MathAlphabet::SansSerifBoldItalic => 0x1D790,
|
||||
MathAlphabet::BoldScript
|
||||
| MathAlphabet::BoldFraktur
|
||||
| MathAlphabet::Script
|
||||
| MathAlphabet::Fraktur
|
||||
| MathAlphabet::DoubleStruck
|
||||
| MathAlphabet::SansSerif
|
||||
| MathAlphabet::SansSerifItalic => return None,
|
||||
};
|
||||
|
||||
let offset = match character as u32 {
|
||||
0x0391..=0x03A1 => character as u32 - 0x0391,
|
||||
0x03A3..=0x03A9 => character as u32 - 0x03A3 + 18,
|
||||
0x03F4 => 17,
|
||||
0x2207 => 25,
|
||||
0x03B1..=0x03C1 => 26 + character as u32 - 0x03B1,
|
||||
0x03C2 => 43,
|
||||
0x03C3..=0x03C9 => 44 + character as u32 - 0x03C3,
|
||||
0x2202 => 51,
|
||||
0x03F5 => 52,
|
||||
0x03D1 => 53,
|
||||
0x03F0 => 54,
|
||||
0x03D5 => 55,
|
||||
0x03F1 => 56,
|
||||
0x03D6 => 57,
|
||||
_ => return None,
|
||||
};
|
||||
char::from_u32(style_base + offset)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{MathClass, MathCode};
|
||||
|
||||
static DEFAULT_MATH_CODE: MathCode = MathCode(0);
|
||||
static UNSET_UNICODE_MATH_CODE: i32 = -1;
|
||||
static UNSET_DELIMITER_CODE: i32 = -1;
|
||||
|
||||
/// Character math codes owned by the Rust TeX engine.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MathCodeTable {
|
||||
low: Vec<MathCode>,
|
||||
high: HashMap<usize, MathCode>,
|
||||
groups: Vec<MathCodeGroup>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
struct MathCodeGroup {
|
||||
values: HashMap<usize, Option<MathCode>>,
|
||||
}
|
||||
|
||||
impl MathCodeTable {
|
||||
pub fn get_index_ref(&self, index: usize) -> &MathCode {
|
||||
self.low
|
||||
.get(index)
|
||||
.or_else(|| self.high.get(&index))
|
||||
.unwrap_or(&DEFAULT_MATH_CODE)
|
||||
}
|
||||
|
||||
pub fn get_index_mut_ref(&mut self, index: usize) -> &mut MathCode {
|
||||
if let Some(math_code) = self.low.get_mut(index) {
|
||||
return math_code;
|
||||
}
|
||||
self.high.entry(index).or_default()
|
||||
}
|
||||
|
||||
pub fn prepare_assignment(&mut self, index: usize, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.values.remove(&index);
|
||||
}
|
||||
} else if !self.groups.is_empty() {
|
||||
let previous = self.stored_value(index);
|
||||
self.groups
|
||||
.last_mut()
|
||||
.expect("math code group exists")
|
||||
.values
|
||||
.entry(index)
|
||||
.or_insert(previous);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(MathCodeGroup::default());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (index, value) in group.values {
|
||||
self.set_index(index, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_value(&self, index: usize) -> Option<MathCode> {
|
||||
self.low
|
||||
.get(index)
|
||||
.copied()
|
||||
.or_else(|| self.high.get(&index).copied())
|
||||
}
|
||||
|
||||
fn set_index(&mut self, index: usize, value: Option<MathCode>) {
|
||||
if let Some(math_code) = self.low.get_mut(index) {
|
||||
if let Some(value) = value {
|
||||
*math_code = value;
|
||||
}
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Some(math_code) => {
|
||||
self.high.insert(index, math_code);
|
||||
}
|
||||
None => {
|
||||
self.high.remove(&index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for MathCodeTable {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
low: vec![MathCode::default(); 128],
|
||||
high: HashMap::new(),
|
||||
groups: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct UnicodeMathCode {
|
||||
pub class: u8,
|
||||
pub family: u8,
|
||||
pub glyph_slot: u32,
|
||||
}
|
||||
|
||||
impl UnicodeMathCode {
|
||||
pub fn pack(self) -> u32 {
|
||||
(u32::from(self.family) << 24) | (u32::from(self.class) << 21) | self.glyph_slot
|
||||
}
|
||||
|
||||
pub fn unpack(code: u32) -> Self {
|
||||
Self {
|
||||
class: ((code >> 21) & 0x7) as u8,
|
||||
family: (code >> 24) as u8,
|
||||
glyph_slot: code & 0x1F_FFFF,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn character(self) -> char {
|
||||
char::from_u32(self.glyph_slot)
|
||||
.expect("Unicode math glyph slots contain valid scalar values")
|
||||
}
|
||||
|
||||
pub fn math_class(self) -> MathClass {
|
||||
match self.class {
|
||||
0 | 7 => MathClass::Ordinary,
|
||||
1 => MathClass::Operator,
|
||||
2 => MathClass::Binary,
|
||||
3 => MathClass::Relation,
|
||||
4 => MathClass::Opening,
|
||||
5 => MathClass::Closing,
|
||||
6 => MathClass::Punctuation,
|
||||
_ => unreachable!("math character classes use three bits"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn math_family(self, active_family: Option<i32>) -> u8 {
|
||||
if self.class == 7 {
|
||||
active_family
|
||||
.filter(|family| (0..=255).contains(family))
|
||||
.map(|family| family as u8)
|
||||
.unwrap_or(self.family)
|
||||
} else {
|
||||
self.family
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct UnicodeMathCodeTable {
|
||||
values: HashMap<usize, i32>,
|
||||
groups: Vec<UnicodeMathCodeGroup>,
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
struct UnicodeMathCodeGroup {
|
||||
values: HashMap<usize, Option<i32>>,
|
||||
}
|
||||
|
||||
impl UnicodeMathCodeTable {
|
||||
pub fn get(&self, codepoint: usize) -> Option<UnicodeMathCode> {
|
||||
let value = self.values.get(&codepoint).copied()?;
|
||||
(value != UNSET_UNICODE_MATH_CODE).then(|| UnicodeMathCode::unpack(value as u32))
|
||||
}
|
||||
|
||||
pub fn get_index_ref(&self, codepoint: usize) -> &i32 {
|
||||
self.values
|
||||
.get(&codepoint)
|
||||
.unwrap_or(&UNSET_UNICODE_MATH_CODE)
|
||||
}
|
||||
|
||||
pub fn get_index_mut_ref(&mut self, codepoint: usize) -> &mut i32 {
|
||||
self.values
|
||||
.entry(codepoint)
|
||||
.or_insert(UNSET_UNICODE_MATH_CODE)
|
||||
}
|
||||
|
||||
pub fn prepare_assignment(&mut self, codepoint: usize, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.values.remove(&codepoint);
|
||||
}
|
||||
} else if !self.groups.is_empty() {
|
||||
let previous = self.values.get(&codepoint).copied();
|
||||
self.groups
|
||||
.last_mut()
|
||||
.expect("Unicode math code group exists")
|
||||
.values
|
||||
.entry(codepoint)
|
||||
.or_insert(previous);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(UnicodeMathCodeGroup::default());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (codepoint, value) in group.values {
|
||||
match value {
|
||||
Some(value) => {
|
||||
self.values.insert(codepoint, value);
|
||||
}
|
||||
None => {
|
||||
self.values.remove(&codepoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct DelimiterCodeTable {
|
||||
values: HashMap<usize, i32>,
|
||||
groups: Vec<DelimiterCodeGroup>,
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
struct DelimiterCodeGroup {
|
||||
values: HashMap<usize, Option<i32>>,
|
||||
}
|
||||
|
||||
impl DelimiterCodeTable {
|
||||
pub fn get_index_ref(&self, codepoint: usize) -> &i32 {
|
||||
self.values.get(&codepoint).unwrap_or(&UNSET_DELIMITER_CODE)
|
||||
}
|
||||
|
||||
pub fn get_index_mut_ref(&mut self, codepoint: usize) -> &mut i32 {
|
||||
self.values.entry(codepoint).or_insert(UNSET_DELIMITER_CODE)
|
||||
}
|
||||
|
||||
pub fn prepare_assignment(&mut self, codepoint: usize, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.values.remove(&codepoint);
|
||||
}
|
||||
} else if !self.groups.is_empty() {
|
||||
let previous = self.values.get(&codepoint).copied();
|
||||
self.groups
|
||||
.last_mut()
|
||||
.expect("delimiter code group exists")
|
||||
.values
|
||||
.entry(codepoint)
|
||||
.or_insert(previous);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(DelimiterCodeGroup::default());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (codepoint, value) in group.values {
|
||||
match value {
|
||||
Some(value) => {
|
||||
self.values.insert(codepoint, value);
|
||||
}
|
||||
None => {
|
||||
self.values.remove(&codepoint);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn assign(&mut self, codepoint: usize, value: i32) {
|
||||
self.values.insert(codepoint, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
/// OpenType MATH constants, retained in the font's design units.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MathConstants {
|
||||
pub script_percent_scale_down: i16,
|
||||
pub script_script_percent_scale_down: i16,
|
||||
pub display_operator_min_height: u16,
|
||||
pub axis_height: i16,
|
||||
pub accent_base_height: i16,
|
||||
pub subscript_top_max: i16,
|
||||
pub subscript_baseline_drop_min: i16,
|
||||
pub subscript_shift_down: i16,
|
||||
pub superscript_bottom_min: i16,
|
||||
pub superscript_baseline_drop_max: i16,
|
||||
pub superscript_bottom_max_with_subscript: i16,
|
||||
pub superscript_shift_up: i16,
|
||||
pub superscript_shift_up_cramped: i16,
|
||||
pub sub_superscript_gap_min: i16,
|
||||
pub upper_limit_gap_min: i16,
|
||||
pub upper_limit_baseline_rise_min: i16,
|
||||
pub lower_limit_gap_min: i16,
|
||||
pub lower_limit_baseline_drop_min: i16,
|
||||
pub space_after_script: i16,
|
||||
pub stack_top_shift_up: i16,
|
||||
pub stack_bottom_shift_down: i16,
|
||||
pub stack_gap_min: i16,
|
||||
pub stack_display_style_gap_min: i16,
|
||||
pub fraction_numerator_shift_up: i16,
|
||||
pub fraction_numerator_display_style_shift_up: i16,
|
||||
pub fraction_denominator_shift_down: i16,
|
||||
pub fraction_denominator_display_style_shift_down: i16,
|
||||
pub fraction_numerator_gap_min: i16,
|
||||
pub fraction_num_display_style_gap_min: i16,
|
||||
pub fraction_rule_thickness: i16,
|
||||
pub fraction_denominator_gap_min: i16,
|
||||
pub fraction_denom_display_style_gap_min: i16,
|
||||
pub overbar_vertical_gap: i16,
|
||||
pub overbar_rule_thickness: i16,
|
||||
pub overbar_extra_ascender: i16,
|
||||
pub underbar_vertical_gap: i16,
|
||||
pub underbar_rule_thickness: i16,
|
||||
pub underbar_extra_descender: i16,
|
||||
pub radical_vertical_gap: i16,
|
||||
pub radical_display_style_vertical_gap: i16,
|
||||
pub radical_rule_thickness: i16,
|
||||
pub radical_kern_before_degree: i16,
|
||||
pub radical_kern_after_degree: i16,
|
||||
pub radical_degree_bottom_raise_percent: i16,
|
||||
}
|
||||
|
||||
/// TeX fraction parameters expressed as fractions of the math font's em.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathFractionParameters {
|
||||
pub numerator_shift_up: f64,
|
||||
pub denominator_shift_down: f64,
|
||||
pub numerator_gap_min: f64,
|
||||
pub denominator_gap_min: f64,
|
||||
pub rule_thickness: f64,
|
||||
pub stack_gap_min: f64,
|
||||
pub axis_height: f64,
|
||||
}
|
||||
|
||||
/// TeX script parameters expressed as fractions of the math font's em.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathScriptParameters {
|
||||
pub subscript_top_max: f64,
|
||||
pub subscript_baseline_drop_min: f64,
|
||||
pub subscript_shift_down: f64,
|
||||
pub superscript_bottom_min: f64,
|
||||
pub superscript_baseline_drop_max: f64,
|
||||
pub superscript_bottom_max_with_subscript: f64,
|
||||
pub superscript_shift_up: f64,
|
||||
pub superscript_shift_up_cramped: f64,
|
||||
pub sub_superscript_gap_min: f64,
|
||||
pub space_after_script: f64,
|
||||
}
|
||||
|
||||
/// TeX operator-limit parameters expressed as fractions of the math font's em.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathLimitParameters {
|
||||
pub upper_gap_min: f64,
|
||||
pub upper_baseline_rise_min: f64,
|
||||
pub lower_gap_min: f64,
|
||||
pub lower_baseline_drop_min: f64,
|
||||
pub outer_padding: f64,
|
||||
}
|
||||
|
||||
/// OpenType MATH and XeTeX fallback values for a radical, expressed in ems.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathRadicalParameters {
|
||||
pub clearance: f64,
|
||||
pub rule_thickness: f64,
|
||||
pub extra_ascender: f64,
|
||||
}
|
||||
|
||||
/// Radical-index placement parameters, with lengths expressed in ems.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathRadicalDegreeParameters {
|
||||
pub kern_before_degree: f64,
|
||||
pub kern_after_degree: f64,
|
||||
pub bottom_raise_percent: f64,
|
||||
}
|
||||
|
||||
/// Overbar or underbar parameters, expressed as em fractions.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MathBarParameters {
|
||||
pub vertical_gap: f64,
|
||||
pub rule_thickness: f64,
|
||||
pub extra_extent: f64,
|
||||
}
|
||||
|
||||
/// Selects the OpenType MATH or TeX fallback values for a fraction.
|
||||
pub fn fraction_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
display_style: bool,
|
||||
has_rule: bool,
|
||||
) -> MathFractionParameters {
|
||||
let numerator_shift_up = constants.map(|constants| {
|
||||
if display_style {
|
||||
constants.fraction_numerator_display_style_shift_up
|
||||
} else if has_rule {
|
||||
constants.fraction_numerator_shift_up
|
||||
} else {
|
||||
constants.stack_top_shift_up
|
||||
}
|
||||
});
|
||||
let denominator_shift_down = constants.map(|constants| {
|
||||
if display_style {
|
||||
constants.fraction_denominator_display_style_shift_down
|
||||
} else if has_rule {
|
||||
constants.fraction_denominator_shift_down
|
||||
} else {
|
||||
constants.stack_bottom_shift_down
|
||||
}
|
||||
});
|
||||
let (numerator_gap_min, denominator_gap_min) = constants
|
||||
.map(|constants| {
|
||||
if display_style {
|
||||
(
|
||||
Some(constants.fraction_num_display_style_gap_min),
|
||||
Some(constants.fraction_denom_display_style_gap_min),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Some(constants.fraction_numerator_gap_min),
|
||||
Some(constants.fraction_denominator_gap_min),
|
||||
)
|
||||
}
|
||||
})
|
||||
.unwrap_or((None, None));
|
||||
let rule_thickness = signed_em(
|
||||
constants.map(|constants| constants.fraction_rule_thickness),
|
||||
units_per_em,
|
||||
0.04,
|
||||
);
|
||||
let numerator_gap_min = signed_em(numerator_gap_min, units_per_em, 0.0);
|
||||
let denominator_gap_min = signed_em(denominator_gap_min, units_per_em, 0.0);
|
||||
let numerator_gap_min = if constants.is_some() {
|
||||
numerator_gap_min
|
||||
} else {
|
||||
rule_thickness * if display_style { 3.0 } else { 1.0 }
|
||||
};
|
||||
let denominator_gap_min = if constants.is_some() {
|
||||
denominator_gap_min
|
||||
} else {
|
||||
rule_thickness * if display_style { 3.0 } else { 1.0 }
|
||||
};
|
||||
let stack_gap_min = constants
|
||||
.map(|constants| {
|
||||
if display_style {
|
||||
constants.stack_display_style_gap_min
|
||||
} else {
|
||||
constants.stack_gap_min
|
||||
}
|
||||
})
|
||||
.map(|gap| signed_em(Some(gap), units_per_em, 0.0))
|
||||
.unwrap_or(rule_thickness * if display_style { 7.0 } else { 3.0 });
|
||||
|
||||
MathFractionParameters {
|
||||
numerator_shift_up: signed_em(numerator_shift_up, units_per_em, 0.0),
|
||||
denominator_shift_down: signed_em(denominator_shift_down, units_per_em, 0.0),
|
||||
numerator_gap_min,
|
||||
denominator_gap_min,
|
||||
rule_thickness,
|
||||
stack_gap_min,
|
||||
axis_height: signed_em(
|
||||
constants.map(|constants| constants.axis_height),
|
||||
units_per_em,
|
||||
0.25,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the OpenType MATH or TeX fallback values for scripts.
|
||||
pub fn script_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
) -> MathScriptParameters {
|
||||
let value = |select: fn(MathConstants) -> i16, fallback| {
|
||||
signed_em(constants.map(select), units_per_em, fallback)
|
||||
};
|
||||
MathScriptParameters {
|
||||
subscript_top_max: value(|c| c.subscript_top_max, 0.36),
|
||||
subscript_baseline_drop_min: value(|c| c.subscript_baseline_drop_min, 0.0),
|
||||
subscript_shift_down: value(|c| c.subscript_shift_down, 0.2),
|
||||
superscript_bottom_min: value(|c| c.superscript_bottom_min, 0.1125),
|
||||
superscript_baseline_drop_max: value(|c| c.superscript_baseline_drop_max, 0.0),
|
||||
superscript_bottom_max_with_subscript: value(
|
||||
|c| c.superscript_bottom_max_with_subscript,
|
||||
0.36,
|
||||
),
|
||||
superscript_shift_up: value(|c| c.superscript_shift_up, 0.35),
|
||||
superscript_shift_up_cramped: value(|c| c.superscript_shift_up_cramped, 0.35),
|
||||
sub_superscript_gap_min: value(|c| c.sub_superscript_gap_min, 0.15),
|
||||
space_after_script: value(|c| c.space_after_script, 0.0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the OpenType MATH or XeTeX fallback values for operator limits.
|
||||
pub fn limit_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
) -> MathLimitParameters {
|
||||
let value = |select: fn(MathConstants) -> i16, fallback| {
|
||||
signed_em(constants.map(select), units_per_em, fallback)
|
||||
};
|
||||
MathLimitParameters {
|
||||
upper_gap_min: value(|c| c.upper_limit_gap_min, 0.05),
|
||||
upper_baseline_rise_min: value(|c| c.upper_limit_baseline_rise_min, 0.3),
|
||||
lower_gap_min: value(|c| c.lower_limit_gap_min, 0.05),
|
||||
lower_baseline_drop_min: value(|c| c.lower_limit_baseline_drop_min, 0.3),
|
||||
// XeTeX maps BigOpSpacing5 to StackGapMin for OpenType MATH fonts.
|
||||
outer_padding: value(|c| c.stack_gap_min, 0.1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the OpenType MATH or XeTeX fallback values for a radical.
|
||||
pub fn radical_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
display_style: bool,
|
||||
x_height: Option<i16>,
|
||||
) -> MathRadicalParameters {
|
||||
let rule_thickness = signed_em(
|
||||
constants.map(|constants| constants.radical_rule_thickness),
|
||||
units_per_em,
|
||||
0.04,
|
||||
);
|
||||
let clearance = match constants {
|
||||
Some(constants) => signed_em(
|
||||
Some(if display_style {
|
||||
constants.radical_display_style_vertical_gap
|
||||
} else {
|
||||
constants.radical_vertical_gap
|
||||
}),
|
||||
units_per_em,
|
||||
0.0,
|
||||
),
|
||||
None if display_style => rule_thickness + signed_em(x_height, units_per_em, 0.45) / 4.0,
|
||||
None => rule_thickness + rule_thickness / 4.0,
|
||||
};
|
||||
MathRadicalParameters {
|
||||
clearance,
|
||||
rule_thickness,
|
||||
// XeTeX starts the radical overbar with a kern equal to rule thickness.
|
||||
extra_ascender: rule_thickness,
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects the OpenType MATH or XeTeX fallback values for a radical index.
|
||||
pub fn radical_degree_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
) -> MathRadicalDegreeParameters {
|
||||
let kern_before_degree = signed_em(
|
||||
constants.map(|constants| constants.radical_kern_before_degree),
|
||||
units_per_em,
|
||||
5.0 / 18.0,
|
||||
);
|
||||
let kern_after_degree = signed_em(
|
||||
constants.map(|constants| constants.radical_kern_after_degree),
|
||||
units_per_em,
|
||||
-10.0 / 18.0,
|
||||
);
|
||||
let bottom_raise_percent = constants
|
||||
.map(|constants| constants.radical_degree_bottom_raise_percent)
|
||||
.unwrap_or(60)
|
||||
.clamp(0, 100);
|
||||
MathRadicalDegreeParameters {
|
||||
kern_before_degree,
|
||||
kern_after_degree,
|
||||
bottom_raise_percent: f64::from(bottom_raise_percent) / 100.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects OpenType MATH or XeTeX fallback parameters for an overbar.
|
||||
pub fn overbar_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
) -> MathBarParameters {
|
||||
MathBarParameters {
|
||||
vertical_gap: signed_em(
|
||||
constants.map(|constants| constants.overbar_vertical_gap),
|
||||
units_per_em,
|
||||
0.1,
|
||||
),
|
||||
rule_thickness: signed_em(
|
||||
constants.map(|constants| constants.overbar_rule_thickness),
|
||||
units_per_em,
|
||||
0.04,
|
||||
),
|
||||
extra_extent: signed_em(
|
||||
constants.map(|constants| constants.overbar_extra_ascender),
|
||||
units_per_em,
|
||||
0.0,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects OpenType MATH or XeTeX fallback parameters for an underbar.
|
||||
pub fn underbar_parameters(
|
||||
constants: Option<MathConstants>,
|
||||
units_per_em: f64,
|
||||
) -> MathBarParameters {
|
||||
MathBarParameters {
|
||||
vertical_gap: signed_em(
|
||||
constants.map(|constants| constants.underbar_vertical_gap),
|
||||
units_per_em,
|
||||
0.1,
|
||||
),
|
||||
rule_thickness: signed_em(
|
||||
constants.map(|constants| constants.underbar_rule_thickness),
|
||||
units_per_em,
|
||||
0.04,
|
||||
),
|
||||
extra_extent: signed_em(
|
||||
constants.map(|constants| constants.underbar_extra_descender),
|
||||
units_per_em,
|
||||
0.0,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn signed_em(value: Option<i16>, units_per_em: f64, fallback_em: f64) -> f64 {
|
||||
value
|
||||
.map(|value| f64::from(value) / units_per_em)
|
||||
.unwrap_or(fallback_em)
|
||||
}
|
||||
|
||||
impl MathConstants {
|
||||
pub fn from_ttf(constants: ttf_parser::math::Constants<'_>) -> Self {
|
||||
Self {
|
||||
script_percent_scale_down: constants.script_percent_scale_down(),
|
||||
script_script_percent_scale_down: constants.script_script_percent_scale_down(),
|
||||
display_operator_min_height: constants.display_operator_min_height(),
|
||||
axis_height: constants.axis_height().value,
|
||||
accent_base_height: constants.accent_base_height().value,
|
||||
subscript_top_max: constants.subscript_top_max().value,
|
||||
subscript_baseline_drop_min: constants.subscript_baseline_drop_min().value,
|
||||
subscript_shift_down: constants.subscript_shift_down().value,
|
||||
superscript_bottom_min: constants.superscript_bottom_min().value,
|
||||
superscript_baseline_drop_max: constants.superscript_baseline_drop_max().value,
|
||||
superscript_bottom_max_with_subscript: constants
|
||||
.superscript_bottom_max_with_subscript()
|
||||
.value,
|
||||
superscript_shift_up: constants.superscript_shift_up().value,
|
||||
superscript_shift_up_cramped: constants.superscript_shift_up_cramped().value,
|
||||
sub_superscript_gap_min: constants.sub_superscript_gap_min().value,
|
||||
upper_limit_gap_min: constants.upper_limit_gap_min().value,
|
||||
upper_limit_baseline_rise_min: constants.upper_limit_baseline_rise_min().value,
|
||||
lower_limit_gap_min: constants.lower_limit_gap_min().value,
|
||||
lower_limit_baseline_drop_min: constants.lower_limit_baseline_drop_min().value,
|
||||
space_after_script: constants.space_after_script().value,
|
||||
stack_top_shift_up: constants.stack_top_shift_up().value,
|
||||
stack_bottom_shift_down: constants.stack_bottom_shift_down().value,
|
||||
stack_gap_min: constants.stack_gap_min().value,
|
||||
stack_display_style_gap_min: constants.stack_display_style_gap_min().value,
|
||||
fraction_numerator_shift_up: constants.fraction_numerator_shift_up().value,
|
||||
fraction_numerator_display_style_shift_up: constants
|
||||
.fraction_numerator_display_style_shift_up()
|
||||
.value,
|
||||
fraction_denominator_shift_down: constants.fraction_denominator_shift_down().value,
|
||||
fraction_denominator_display_style_shift_down: constants
|
||||
.fraction_denominator_display_style_shift_down()
|
||||
.value,
|
||||
fraction_numerator_gap_min: constants.fraction_numerator_gap_min().value,
|
||||
fraction_num_display_style_gap_min: constants
|
||||
.fraction_num_display_style_gap_min()
|
||||
.value,
|
||||
fraction_rule_thickness: constants.fraction_rule_thickness().value,
|
||||
fraction_denominator_gap_min: constants.fraction_denominator_gap_min().value,
|
||||
fraction_denom_display_style_gap_min: constants
|
||||
.fraction_denom_display_style_gap_min()
|
||||
.value,
|
||||
overbar_vertical_gap: constants.overbar_vertical_gap().value,
|
||||
overbar_rule_thickness: constants.overbar_rule_thickness().value,
|
||||
overbar_extra_ascender: constants.overbar_extra_ascender().value,
|
||||
underbar_vertical_gap: constants.underbar_vertical_gap().value,
|
||||
underbar_rule_thickness: constants.underbar_rule_thickness().value,
|
||||
underbar_extra_descender: constants.underbar_extra_descender().value,
|
||||
radical_vertical_gap: constants.radical_vertical_gap().value,
|
||||
radical_display_style_vertical_gap: constants
|
||||
.radical_display_style_vertical_gap()
|
||||
.value,
|
||||
radical_rule_thickness: constants.radical_rule_thickness().value,
|
||||
radical_kern_before_degree: constants.radical_kern_before_degree().value,
|
||||
radical_kern_after_degree: constants.radical_kern_after_degree().value,
|
||||
radical_degree_bottom_raise_percent: constants.radical_degree_bottom_raise_percent(),
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,137 @@
|
||||
use crate::MathClass;
|
||||
|
||||
/// The corner of a math glyph used to query an OpenType MATH kern.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MathKernCorner {
|
||||
TopRight,
|
||||
TopLeft,
|
||||
BottomRight,
|
||||
BottomLeft,
|
||||
}
|
||||
|
||||
/// The slant selected by TeX's ordinary math-atom family rules.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MathAtomFontShape {
|
||||
Inherited,
|
||||
Upright,
|
||||
Italic,
|
||||
}
|
||||
|
||||
/// Selects the font shape for a math atom before backend style conversion.
|
||||
pub fn math_atom_font_shape(class: MathClass, math_family: Option<u8>) -> MathAtomFontShape {
|
||||
if class != MathClass::Ordinary {
|
||||
return MathAtomFontShape::Upright;
|
||||
}
|
||||
match math_family {
|
||||
Some(1) => MathAtomFontShape::Italic,
|
||||
Some(_) => MathAtomFontShape::Upright,
|
||||
None => MathAtomFontShape::Inherited,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the characters represented by a math atom's stored source and slots.
|
||||
pub fn math_atom_glyph_text(text: &str, math_family: Option<u8>, math_slots: &[u8]) -> String {
|
||||
if math_family.is_some()
|
||||
&& math_slots.len() == text.chars().count()
|
||||
&& math_slots.iter().all(|slot| (b' '..=b'~').contains(slot))
|
||||
{
|
||||
math_slots.iter().map(|slot| char::from(*slot)).collect()
|
||||
} else {
|
||||
text.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this atom's character is selected from the OpenType math face.
|
||||
pub fn prefers_math_font(
|
||||
class: MathClass,
|
||||
character: char,
|
||||
math_family: Option<u8>,
|
||||
bold: bool,
|
||||
italic: bool,
|
||||
) -> bool {
|
||||
let greek = is_greek_letter(character);
|
||||
let unicode_math_alphanumeric = is_math_alphanumeric_character(character);
|
||||
let is_math_symbol = !character.is_alphanumeric() || unicode_math_alphanumeric;
|
||||
let is_math_italic_letter = class == MathClass::Ordinary
|
||||
&& character.is_ascii_alphabetic()
|
||||
&& (math_family == Some(1) || italic);
|
||||
(is_math_symbol || greek || is_math_italic_letter)
|
||||
&& (!bold || unicode_math_alphanumeric)
|
||||
&& (!italic
|
||||
|| !character.is_alphanumeric()
|
||||
|| greek
|
||||
|| unicode_math_alphanumeric
|
||||
|| is_math_italic_letter)
|
||||
}
|
||||
|
||||
fn is_math_alphanumeric_character(character: char) -> bool {
|
||||
matches!(character as u32, 0x1D400..=0x1D7FF)
|
||||
|| matches!(
|
||||
character as u32,
|
||||
0x2102
|
||||
| 0x210A..=0x210E
|
||||
| 0x2110..=0x2115
|
||||
| 0x2119..=0x211D
|
||||
| 0x2124
|
||||
| 0x212C..=0x212F
|
||||
| 0x2130..=0x2131
|
||||
| 0x2133..=0x2134
|
||||
)
|
||||
}
|
||||
|
||||
fn is_greek_letter(character: char) -> bool {
|
||||
character.is_alphabetic() && matches!(character as u32, 0x0370..=0x03FF | 0x1F00..=0x1FFF)
|
||||
}
|
||||
|
||||
/// Engine-owned kern breakpoints and values, measured in font design units.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MathKernTable {
|
||||
pub correction_heights: Vec<Option<i16>>,
|
||||
pub values: Vec<Option<i16>>,
|
||||
}
|
||||
|
||||
/// MATH metrics for one glyph, independent of the font parser's table types.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct MathGlyphMetrics {
|
||||
/// Italic correction. `Some(0)` means a correction table was present but
|
||||
/// had no explicit entry for this glyph.
|
||||
pub italic_correction: Option<i16>,
|
||||
pub top_accent_attachment: Option<i16>,
|
||||
pub top_right_kern: Option<MathKernTable>,
|
||||
pub top_left_kern: Option<MathKernTable>,
|
||||
pub bottom_right_kern: Option<MathKernTable>,
|
||||
pub bottom_left_kern: Option<MathKernTable>,
|
||||
}
|
||||
|
||||
/// Return a glyph's MATH italic correction in design units.
|
||||
pub fn italic_correction(metrics: &MathGlyphMetrics) -> Option<i16> {
|
||||
metrics.italic_correction
|
||||
}
|
||||
|
||||
/// Return a glyph's top accent attachment point in design units.
|
||||
pub fn top_accent_attachment(metrics: &MathGlyphMetrics) -> Option<i16> {
|
||||
metrics.top_accent_attachment
|
||||
}
|
||||
|
||||
/// Select the MATH kern value for a corner and correction height.
|
||||
///
|
||||
/// `correction_height` is expressed in the font's design units. OpenType kern
|
||||
/// tables select the value following every breakpoint at or below that height.
|
||||
pub fn math_kern_at_height(
|
||||
metrics: &MathGlyphMetrics,
|
||||
corner: MathKernCorner,
|
||||
correction_height: f64,
|
||||
) -> Option<i16> {
|
||||
let kern = match corner {
|
||||
MathKernCorner::TopRight => metrics.top_right_kern.as_ref(),
|
||||
MathKernCorner::TopLeft => metrics.top_left_kern.as_ref(),
|
||||
MathKernCorner::BottomRight => metrics.bottom_right_kern.as_ref(),
|
||||
MathKernCorner::BottomLeft => metrics.bottom_left_kern.as_ref(),
|
||||
}?;
|
||||
let kern_index = kern
|
||||
.correction_heights
|
||||
.iter()
|
||||
.take_while(|height| height.is_some_and(|height| f64::from(height) <= correction_height))
|
||||
.count();
|
||||
kern.values.get(kern_index).copied().flatten()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,403 @@
|
||||
use crate::{
|
||||
MathClass, MathStyle, MathStyleCommand,
|
||||
glue::TeXGlue,
|
||||
math_expr::{MathExpr, MathLineBreakPenalties, MathMuGlue, MathSpacingSettings},
|
||||
};
|
||||
|
||||
/// TeX's inter-atom spacing category for one pair of math classes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MathSpacingKind {
|
||||
None,
|
||||
ThinConditional,
|
||||
Thin,
|
||||
MediumConditional,
|
||||
ThickConditional,
|
||||
}
|
||||
|
||||
/// The first and last math classes contributed by one item in a math list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct MathBoundary {
|
||||
pub leading: Option<MathClass>,
|
||||
pub trailing: Option<MathClass>,
|
||||
}
|
||||
|
||||
/// Neighboring classes that constrain a nested math list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct MathListContext {
|
||||
pub previous: Option<MathClass>,
|
||||
pub next: Option<MathClass>,
|
||||
}
|
||||
|
||||
/// One engine-planned item for the application inline-math line breaker.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MathInlineItemPlan<'a> {
|
||||
Formula {
|
||||
expression: &'a MathExpr,
|
||||
math_style: MathStyle,
|
||||
spacing: MathSpacingSettings,
|
||||
child_context: MathListContext,
|
||||
spacing_before: Option<MathMuGlue>,
|
||||
break_after: Option<i32>,
|
||||
},
|
||||
Glue(TeXGlue),
|
||||
Penalty(i32),
|
||||
}
|
||||
|
||||
/// Plan the top-level items and break opportunities for an inline math list.
|
||||
///
|
||||
/// The core resolves math styles, mu glue, explicit penalties, and automatic
|
||||
/// relation/binary break penalties. The caller remains responsible for
|
||||
/// measuring each formula and converting mu glue for its line-break backend.
|
||||
pub fn plan_inline_math<'a>(
|
||||
expression: &'a MathExpr,
|
||||
math_style: MathStyle,
|
||||
spacing: MathSpacingSettings,
|
||||
line_break_penalties: MathLineBreakPenalties,
|
||||
allow_trailing_break: bool,
|
||||
) -> Vec<MathInlineItemPlan<'a>> {
|
||||
if let Some(penalty) = explicit_math_break_penalty(expression) {
|
||||
return vec![MathInlineItemPlan::Penalty(penalty)];
|
||||
}
|
||||
if let MathExpr::Glue(glue) = expression {
|
||||
return vec![MathInlineItemPlan::Glue(*glue)];
|
||||
}
|
||||
let MathExpr::Sequence(items) = expression else {
|
||||
return vec![MathInlineItemPlan::Formula {
|
||||
expression,
|
||||
math_style,
|
||||
spacing,
|
||||
child_context: MathListContext::default(),
|
||||
spacing_before: None,
|
||||
break_after: None,
|
||||
}];
|
||||
};
|
||||
|
||||
let classes = normalized_classes(items, math_style, MathListContext::default());
|
||||
let mut current_math_style = math_style;
|
||||
let mut current_spacing = spacing;
|
||||
let mut current_line_break_penalties = line_break_penalties;
|
||||
let mut previous_class = None;
|
||||
let mut planned = Vec::with_capacity(items.len());
|
||||
|
||||
for (index, expression) in items.iter().enumerate() {
|
||||
if let MathExpr::MathSpacingChange(settings) = expression {
|
||||
current_spacing = *settings;
|
||||
continue;
|
||||
}
|
||||
if let MathExpr::MathLineBreakPenaltiesChange(penalties) = expression {
|
||||
current_line_break_penalties = *penalties;
|
||||
continue;
|
||||
}
|
||||
if let Some(penalty) = explicit_math_break_penalty(expression) {
|
||||
planned.push(MathInlineItemPlan::Penalty(penalty));
|
||||
continue;
|
||||
}
|
||||
if let MathExpr::Glue(glue) = expression {
|
||||
planned.push(MathInlineItemPlan::Glue(*glue));
|
||||
previous_class = classes[index].trailing.or(previous_class);
|
||||
continue;
|
||||
}
|
||||
|
||||
let boundary = classes[index];
|
||||
if let Some(command) = math_style_command(expression) {
|
||||
current_math_style = MathStyle::from_command(command);
|
||||
continue;
|
||||
}
|
||||
|
||||
let spacing_before = previous_class
|
||||
.zip(boundary.leading)
|
||||
.map(|(previous, next)| {
|
||||
inter_atom_spacing(previous, next, current_math_style, current_spacing)
|
||||
});
|
||||
let break_after = automatic_math_break_after(
|
||||
items,
|
||||
&classes,
|
||||
index,
|
||||
boundary,
|
||||
current_line_break_penalties,
|
||||
allow_trailing_break,
|
||||
);
|
||||
planned.push(MathInlineItemPlan::Formula {
|
||||
expression,
|
||||
math_style: current_math_style,
|
||||
spacing: current_spacing,
|
||||
child_context: child_context(&classes, index, MathListContext::default()),
|
||||
spacing_before,
|
||||
break_after,
|
||||
});
|
||||
previous_class = boundary.trailing.or(previous_class);
|
||||
}
|
||||
|
||||
planned
|
||||
}
|
||||
|
||||
fn automatic_math_break_after(
|
||||
items: &[MathExpr],
|
||||
classes: &[MathBoundary],
|
||||
index: usize,
|
||||
boundary: MathBoundary,
|
||||
penalties: MathLineBreakPenalties,
|
||||
allow_trailing_break: bool,
|
||||
) -> Option<i32> {
|
||||
let penalty = match boundary.trailing {
|
||||
Some(MathClass::Relation) => penalties.relation,
|
||||
Some(MathClass::Binary) => penalties.binary,
|
||||
_ => return None,
|
||||
};
|
||||
let next_blocks_automatic_break = items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(index + 1)
|
||||
.find(|(_, item)| !is_math_layout_metadata(item))
|
||||
.is_some_and(|(next_index, next)| {
|
||||
classes[next_index].leading == Some(MathClass::Relation)
|
||||
|| explicit_math_break_penalty(next).is_some()
|
||||
});
|
||||
if (index + 1 < items.len() || allow_trailing_break)
|
||||
&& !next_blocks_automatic_break
|
||||
&& penalty < 10_000
|
||||
{
|
||||
Some(penalty)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn explicit_math_break_penalty(expression: &MathExpr) -> Option<i32> {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } => explicit_math_break_penalty(expression),
|
||||
MathExpr::BreakPenalty(penalty) => Some(*penalty),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_math_layout_metadata(expression: &MathExpr) -> bool {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } => is_math_layout_metadata(expression),
|
||||
MathExpr::MathStyleChange(_)
|
||||
| MathExpr::MathSpacingChange(_)
|
||||
| MathExpr::MathLineBreakPenaltiesChange(_) => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Find a style command wrapped only in source metadata.
|
||||
pub fn math_style_command(expression: &MathExpr) -> Option<MathStyleCommand> {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } => math_style_command(expression),
|
||||
MathExpr::MathStyleChange(command) => Some(*command),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the active `\\mathchoice` branch for a TeX math style.
|
||||
pub fn math_choice_variant(expression: &MathExpr, math_style: MathStyle) -> &MathExpr {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } => math_choice_variant(expression, math_style),
|
||||
MathExpr::MathChoice {
|
||||
display,
|
||||
text,
|
||||
script,
|
||||
scriptscript,
|
||||
} => math_choice_variant(
|
||||
match math_style {
|
||||
MathStyle::Display | MathStyle::DisplayCramped => display,
|
||||
MathStyle::Text | MathStyle::TextCramped => text,
|
||||
MathStyle::Script | MathStyle::ScriptCramped => script,
|
||||
MathStyle::ScriptScript | MathStyle::ScriptScriptCramped => scriptscript,
|
||||
},
|
||||
math_style,
|
||||
),
|
||||
expression => expression,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert a parsed math sequence into class boundaries, including TeX's
|
||||
/// style-sensitive `\\mathchoice` selection and binary-operator normalization.
|
||||
pub fn normalized_classes(
|
||||
items: &[MathExpr],
|
||||
math_style: MathStyle,
|
||||
list_context: MathListContext,
|
||||
) -> Vec<MathBoundary> {
|
||||
let mut current_math_style = math_style;
|
||||
let mut classes = items
|
||||
.iter()
|
||||
.map(|item| {
|
||||
if let Some(command) = math_style_command(item) {
|
||||
current_math_style = MathStyle::from_command(command);
|
||||
}
|
||||
let item = math_choice_variant(item, current_math_style);
|
||||
MathBoundary {
|
||||
leading: math_list_leading_class(item, current_math_style),
|
||||
trailing: math_list_trailing_class(item, current_math_style),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
normalize_binary_operators(&mut classes, list_context);
|
||||
classes
|
||||
}
|
||||
|
||||
/// Get the first visible math class contributed by an expression.
|
||||
pub fn math_list_leading_class(expression: &MathExpr, math_style: MathStyle) -> Option<MathClass> {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => {
|
||||
math_list_leading_class(expression, math_style)
|
||||
}
|
||||
MathExpr::Sequence(items) => {
|
||||
let mut current_math_style = math_style;
|
||||
for item in items {
|
||||
if let Some(command) = math_style_command(item) {
|
||||
current_math_style = MathStyle::from_command(command);
|
||||
} else if let Some(class) = math_list_leading_class(item, current_math_style) {
|
||||
return Some(class);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
MathExpr::MathChoice { .. } => {
|
||||
math_list_leading_class(math_choice_variant(expression, math_style), math_style)
|
||||
}
|
||||
MathExpr::MathStyleChange(_)
|
||||
| MathExpr::Space(_)
|
||||
| MathExpr::Glue(_)
|
||||
| MathExpr::Kern(_) => None,
|
||||
_ => expression.leading_class(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the last visible math class contributed by an expression.
|
||||
pub fn math_list_trailing_class(expression: &MathExpr, math_style: MathStyle) -> Option<MathClass> {
|
||||
match expression {
|
||||
MathExpr::Spanned { expression, .. } | MathExpr::Styled { expression, .. } => {
|
||||
math_list_trailing_class(expression, math_style)
|
||||
}
|
||||
MathExpr::Sequence(items) => {
|
||||
let mut current_math_style = math_style;
|
||||
let mut trailing_class = None;
|
||||
for item in items {
|
||||
if let Some(command) = math_style_command(item) {
|
||||
current_math_style = MathStyle::from_command(command);
|
||||
} else {
|
||||
trailing_class =
|
||||
math_list_trailing_class(item, current_math_style).or(trailing_class);
|
||||
}
|
||||
}
|
||||
trailing_class
|
||||
}
|
||||
MathExpr::MathChoice { .. } => {
|
||||
math_list_trailing_class(math_choice_variant(expression, math_style), math_style)
|
||||
}
|
||||
MathExpr::MathStyleChange(_)
|
||||
| MathExpr::Space(_)
|
||||
| MathExpr::Glue(_)
|
||||
| MathExpr::Kern(_) => None,
|
||||
_ => expression.trailing_class(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve TeX's eight-class math spacing table.
|
||||
pub fn spacing_kind(left: MathClass, right: MathClass) -> MathSpacingKind {
|
||||
const TABLE: &[u8; 64] = b"0234000122*4000133**3**344*0400400*000000234000111*1111112341011";
|
||||
match TABLE[left.index() * 8 + right.index()] {
|
||||
b'1' => MathSpacingKind::ThinConditional,
|
||||
b'2' => MathSpacingKind::Thin,
|
||||
b'3' => MathSpacingKind::MediumConditional,
|
||||
b'4' => MathSpacingKind::ThickConditional,
|
||||
_ => MathSpacingKind::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Select the TeX math glue for a class pair and math style.
|
||||
pub fn inter_atom_spacing(
|
||||
left: MathClass,
|
||||
right: MathClass,
|
||||
math_style: MathStyle,
|
||||
settings: MathSpacingSettings,
|
||||
) -> MathMuGlue {
|
||||
let glue = match spacing_kind(left, right) {
|
||||
MathSpacingKind::ThinConditional if math_style.conditional_math_spacing() => {
|
||||
settings.thin.0
|
||||
}
|
||||
MathSpacingKind::Thin => settings.thin.0,
|
||||
MathSpacingKind::MediumConditional if math_style.conditional_math_spacing() => {
|
||||
settings.medium.0
|
||||
}
|
||||
MathSpacingKind::ThickConditional if math_style.conditional_math_spacing() => {
|
||||
settings.thick.0
|
||||
}
|
||||
_ => common::Glue::ZERO,
|
||||
};
|
||||
MathMuGlue(glue)
|
||||
}
|
||||
|
||||
/// Apply TeX's binary-operator-to-ordinary-atom rule to a math list.
|
||||
pub fn normalize_binary_operators(boundaries: &mut [MathBoundary], context: MathListContext) {
|
||||
for index in 0..boundaries.len() {
|
||||
if boundaries[index].leading != Some(MathClass::Binary) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let previous = boundaries[..index]
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|boundary| boundary.trailing)
|
||||
.or(context.previous);
|
||||
if previous.is_none_or(|class| {
|
||||
matches!(
|
||||
class,
|
||||
MathClass::Binary
|
||||
| MathClass::Operator
|
||||
| MathClass::Relation
|
||||
| MathClass::Opening
|
||||
| MathClass::Punctuation
|
||||
)
|
||||
}) {
|
||||
boundaries[index].leading = Some(MathClass::Ordinary);
|
||||
if boundaries[index].trailing == Some(MathClass::Binary) {
|
||||
boundaries[index].trailing = Some(MathClass::Ordinary);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for index in (0..boundaries.len()).rev() {
|
||||
if boundaries[index].trailing != Some(MathClass::Binary) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let next = boundaries[index + 1..]
|
||||
.iter()
|
||||
.find_map(|boundary| boundary.leading)
|
||||
.or(context.next);
|
||||
if next.is_none_or(|class| {
|
||||
matches!(
|
||||
class,
|
||||
MathClass::Relation | MathClass::Closing | MathClass::Punctuation
|
||||
)
|
||||
}) {
|
||||
boundaries[index].trailing = Some(MathClass::Ordinary);
|
||||
if boundaries[index].leading == Some(MathClass::Binary) {
|
||||
boundaries[index].leading = Some(MathClass::Ordinary);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Carry the nearest visible classes across an item into its nested list.
|
||||
pub fn child_context(
|
||||
boundaries: &[MathBoundary],
|
||||
index: usize,
|
||||
parent: MathListContext,
|
||||
) -> MathListContext {
|
||||
MathListContext {
|
||||
previous: boundaries[..index]
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|boundary| boundary.trailing)
|
||||
.or(parent.previous),
|
||||
next: boundaries[index + 1..]
|
||||
.iter()
|
||||
.find_map(|boundary| boundary.leading)
|
||||
.or(parent.next),
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,344 @@
|
||||
use crate::{
|
||||
expanded::{ExpandedTokenStream, FrontendEventKind},
|
||||
math_expr::MathInfixFractionKind,
|
||||
source::{SourceLocation, SourceOrigin},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MathScope {
|
||||
Display,
|
||||
Inline,
|
||||
Environment(String),
|
||||
}
|
||||
|
||||
impl MathScope {
|
||||
pub fn from_start_event(kind: &FrontendEventKind) -> Option<Self> {
|
||||
match kind {
|
||||
FrontendEventKind::DisplayMathStart => Some(Self::Display),
|
||||
FrontendEventKind::InlineMathStart => Some(Self::Inline),
|
||||
FrontendEventKind::BeginEnvironment { name, .. }
|
||||
if is_display_math_environment(name) =>
|
||||
{
|
||||
Some(Self::Environment(name.clone()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_end_event(kind: &FrontendEventKind) -> Option<Self> {
|
||||
match kind {
|
||||
FrontendEventKind::DisplayMathEnd(_) => Some(Self::Display),
|
||||
FrontendEventKind::InlineMathEnd(_) => Some(Self::Inline),
|
||||
FrontendEventKind::EndEnvironment { name, .. } if is_display_math_environment(name) => {
|
||||
Some(Self::Environment(name.clone()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_display(&self) -> bool {
|
||||
!matches!(self, Self::Inline)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum TeXMode {
|
||||
Vertical,
|
||||
Horizontal,
|
||||
InlineMath,
|
||||
DisplayMath,
|
||||
}
|
||||
|
||||
pub struct TeXModeState {
|
||||
mode: TeXMode,
|
||||
math_scope: Option<MathScope>,
|
||||
math_opened_at: Option<SourceLocation>,
|
||||
}
|
||||
|
||||
impl Default for TeXModeState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: TeXMode::Vertical,
|
||||
math_scope: None,
|
||||
math_opened_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeXModeState {
|
||||
pub fn enter_math(&mut self, scope: MathScope, location: SourceLocation) {
|
||||
self.mode = if scope.is_display() {
|
||||
TeXMode::DisplayMath
|
||||
} else {
|
||||
TeXMode::InlineMath
|
||||
};
|
||||
self.math_scope = Some(scope);
|
||||
self.math_opened_at = Some(location);
|
||||
}
|
||||
|
||||
pub fn leave_math(&mut self) {
|
||||
self.mode = match self.mode {
|
||||
TeXMode::InlineMath => TeXMode::Horizontal,
|
||||
TeXMode::DisplayMath => TeXMode::Vertical,
|
||||
TeXMode::Vertical | TeXMode::Horizontal => self.mode,
|
||||
};
|
||||
self.math_scope = None;
|
||||
self.math_opened_at = None;
|
||||
}
|
||||
|
||||
pub fn is_math(&self) -> bool {
|
||||
matches!(self.mode, TeXMode::InlineMath | TeXMode::DisplayMath)
|
||||
}
|
||||
|
||||
pub fn is_display_math(&self) -> bool {
|
||||
self.mode == TeXMode::DisplayMath
|
||||
}
|
||||
|
||||
pub fn math_scope(&self) -> Option<&MathScope> {
|
||||
self.math_scope.as_ref()
|
||||
}
|
||||
|
||||
pub fn math_opened_at(&self) -> Option<&SourceLocation> {
|
||||
self.math_opened_at.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_display_math_environment(environment: &str) -> bool {
|
||||
matches!(
|
||||
environment,
|
||||
"equation"
|
||||
| "equation*"
|
||||
| "align"
|
||||
| "align*"
|
||||
| "alignat"
|
||||
| "alignat*"
|
||||
| "flalign"
|
||||
| "flalign*"
|
||||
| "eqnarray"
|
||||
| "eqnarray*"
|
||||
| "gather"
|
||||
| "gather*"
|
||||
| "multline"
|
||||
| "multline*"
|
||||
| "displaymath"
|
||||
)
|
||||
}
|
||||
|
||||
type Delimiter = MathScope;
|
||||
|
||||
pub fn validate_math_delimiters(source: &ExpandedTokenStream) -> Result<(), String> {
|
||||
use FrontendEventKind as Event;
|
||||
|
||||
let mut mode = TeXModeState::default();
|
||||
let mut active_math: Option<(Vec<SourceLocation>, Vec<usize>)> = None;
|
||||
for event in &source.events {
|
||||
if mode.is_math() {
|
||||
let (left_delimiters, fraction_scopes) = active_math
|
||||
.as_mut()
|
||||
.expect("active math mode has its delimiter validation state");
|
||||
if Delimiter::from_end_event(&event.kind).as_ref() == mode.math_scope() {
|
||||
if let Some(location) = left_delimiters.last() {
|
||||
return Err(math_delimiter_error(
|
||||
location,
|
||||
"missing `\\right` for this `\\left`",
|
||||
));
|
||||
}
|
||||
mode.leave_math();
|
||||
active_math = None;
|
||||
continue;
|
||||
}
|
||||
if Delimiter::from_end_event(&event.kind).is_some() {
|
||||
return Err(math_delimiter_error(
|
||||
mode.math_opened_at().unwrap_or(&event.location),
|
||||
"the math-mode closing delimiter does not match its opening delimiter",
|
||||
));
|
||||
}
|
||||
if Delimiter::from_start_event(&event.kind).is_some() {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"math mode cannot be started inside math mode",
|
||||
));
|
||||
}
|
||||
if matches!(event.kind, Event::ParagraphBreak) {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"`\\par` is not allowed in math mode",
|
||||
));
|
||||
}
|
||||
if matches!(event.kind, Event::VerticalGlue(_)) {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"vertical glue is not allowed in math mode",
|
||||
));
|
||||
}
|
||||
if matches!(event.kind, Event::EquationTag(_)) && !mode.is_display_math() {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"`\\tag` must appear inside display math",
|
||||
));
|
||||
}
|
||||
|
||||
match &event.kind {
|
||||
Event::MathDelimiterStart { .. } => {
|
||||
left_delimiters.push(event.location.clone());
|
||||
fraction_scopes.push(0);
|
||||
}
|
||||
Event::MathDelimiterMiddle { .. } if left_delimiters.is_empty() => {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"`\\middle` must appear between `\\left` and `\\right`",
|
||||
));
|
||||
}
|
||||
Event::MathDelimiterEnd { .. } if left_delimiters.is_empty() => {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"`\\right` has no matching `\\left`",
|
||||
));
|
||||
}
|
||||
Event::MathDelimiterEnd { .. } => {
|
||||
left_delimiters.pop();
|
||||
if fraction_scopes.len() > 1 {
|
||||
fraction_scopes.pop();
|
||||
}
|
||||
}
|
||||
Event::MathManualDelimiter { .. } => {}
|
||||
Event::MathUnicodeDelimiter { .. } => {}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match &event.kind {
|
||||
Event::MathInfixFraction(..) => {
|
||||
let count = fraction_scopes
|
||||
.last_mut()
|
||||
.expect("math scope always has a fraction counter");
|
||||
*count += 1;
|
||||
if *count > 1 {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"Ambiguous; you need another `{` and `}`",
|
||||
));
|
||||
}
|
||||
}
|
||||
Event::GroupStart
|
||||
| Event::MathFractionStart { .. }
|
||||
| Event::MathRootStart { .. }
|
||||
| Event::MathAccentStart { .. }
|
||||
| Event::MathFontStart(_)
|
||||
| Event::MathOperatorStart
|
||||
| Event::MathClassStart(_) => fraction_scopes.push(0),
|
||||
Event::GroupEnd
|
||||
| Event::MathFractionEnd
|
||||
| Event::MathRootEnd
|
||||
| Event::MathAccentEnd
|
||||
| Event::MathFontEnd
|
||||
| Event::MathOperatorEnd
|
||||
| Event::MathClassEnd => {
|
||||
if fraction_scopes.len() > 1 {
|
||||
fraction_scopes.pop();
|
||||
}
|
||||
}
|
||||
Event::MathFractionSeparator | Event::MathRootSeparator => {
|
||||
*fraction_scopes
|
||||
.last_mut()
|
||||
.expect("math scope always has a fraction counter") = 0;
|
||||
}
|
||||
Event::MathCell | Event::RowBreak => {
|
||||
*fraction_scopes
|
||||
.last_mut()
|
||||
.expect("math scope always has a fraction counter") = 0;
|
||||
}
|
||||
Event::MathChoiceStart => fraction_scopes.push(0),
|
||||
Event::MathChoiceBranch(_) => {
|
||||
*fraction_scopes
|
||||
.last_mut()
|
||||
.expect("math scope always has a fraction counter") = 0;
|
||||
}
|
||||
Event::MathChoiceEnd => {
|
||||
if fraction_scopes.len() > 1 {
|
||||
fraction_scopes.pop();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if Delimiter::from_end_event(&event.kind).is_some() {
|
||||
return Err(math_delimiter_error(
|
||||
&event.location,
|
||||
"math-mode closing delimiter has no matching opening delimiter",
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(scope) = Delimiter::from_start_event(&event.kind) {
|
||||
mode.enter_math(scope, event.location.clone());
|
||||
active_math = Some((Vec::new(), vec![0]));
|
||||
continue;
|
||||
}
|
||||
|
||||
let message = match &event.kind {
|
||||
Event::MathDelimiterStart { .. } => Some("`\\left` must appear inside math mode"),
|
||||
Event::MathDelimiterMiddle { .. } => {
|
||||
Some("`\\middle` must appear between `\\left` and `\\right`")
|
||||
}
|
||||
Event::MathDelimiterEnd { .. } => Some("`\\right` has no matching `\\left`"),
|
||||
Event::MathInfixFraction(kind, _) => Some(match kind {
|
||||
MathInfixFractionKind::Over => "`\\over` must appear inside math mode",
|
||||
MathInfixFractionKind::Atop => "`\\atop` must appear inside math mode",
|
||||
MathInfixFractionKind::Choose(_) => "`\\choose` must appear inside math mode",
|
||||
MathInfixFractionKind::Above(_) => "`\\above` must appear inside math mode",
|
||||
MathInfixFractionKind::OverWithDelims(_) => {
|
||||
"`\\overwithdelims` must appear inside math mode"
|
||||
}
|
||||
MathInfixFractionKind::AtopWithDelims(_) => {
|
||||
"`\\atopwithdelims` must appear inside math mode"
|
||||
}
|
||||
MathInfixFractionKind::AboveWithDelims { .. } => {
|
||||
"`\\abovewithdelims` must appear inside math mode"
|
||||
}
|
||||
}),
|
||||
Event::MathManualDelimiter { .. } => {
|
||||
Some("manual delimiter size commands must appear inside math mode")
|
||||
}
|
||||
Event::MathCharacter { .. } | Event::MathUnicodeCharacter { .. } => {
|
||||
Some("math characters must appear inside math mode")
|
||||
}
|
||||
Event::MathUnicodeDelimiter { .. } => {
|
||||
Some("Unicode math delimiters must appear inside math mode")
|
||||
}
|
||||
Event::MathStyleChange(_) => Some("math style commands must appear inside math mode"),
|
||||
Event::MathChoiceStart | Event::MathChoiceBranch(_) | Event::MathChoiceEnd => {
|
||||
Some("\\mathchoice must appear inside math mode")
|
||||
}
|
||||
Event::EquationTag(_) => Some("`\\tag` must appear inside display math"),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(message) = message {
|
||||
return Err(math_delimiter_error(&event.location, message));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((left_delimiters, _)) = active_math
|
||||
&& let Some(location) = left_delimiters.last()
|
||||
{
|
||||
return Err(math_delimiter_error(
|
||||
location,
|
||||
"missing `\\right` for this `\\left`",
|
||||
));
|
||||
}
|
||||
if let Some(location) = mode.math_opened_at() {
|
||||
return Err(math_delimiter_error(
|
||||
location,
|
||||
"math mode has no matching closing delimiter",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn math_delimiter_error(location: &SourceLocation, message: &str) -> String {
|
||||
let origin = match &location.origin {
|
||||
SourceOrigin::File(path) => path.display().to_string(),
|
||||
SourceOrigin::Terminal => "<input>".to_string(),
|
||||
};
|
||||
format!("{origin}:{}:{}: {message}", location.line, location.column)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,97 @@
|
||||
/// Explicit math-style command encountered in a TeX math list.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum MathStyleCommand {
|
||||
Display,
|
||||
Text,
|
||||
Script,
|
||||
ScriptScript,
|
||||
}
|
||||
|
||||
/// TeX's eight math styles, including the cramped variants.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum MathStyle {
|
||||
Display,
|
||||
DisplayCramped,
|
||||
Text,
|
||||
TextCramped,
|
||||
Script,
|
||||
ScriptCramped,
|
||||
ScriptScript,
|
||||
ScriptScriptCramped,
|
||||
}
|
||||
|
||||
impl MathStyle {
|
||||
pub fn from_command(command: MathStyleCommand) -> Self {
|
||||
match command {
|
||||
MathStyleCommand::Display => Self::Display,
|
||||
MathStyleCommand::Text => Self::Text,
|
||||
MathStyleCommand::Script => Self::Script,
|
||||
MathStyleCommand::ScriptScript => Self::ScriptScript,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cramped(self) -> Self {
|
||||
match self {
|
||||
Self::Display | Self::DisplayCramped => Self::DisplayCramped,
|
||||
Self::Text | Self::TextCramped => Self::TextCramped,
|
||||
Self::Script | Self::ScriptCramped => Self::ScriptCramped,
|
||||
Self::ScriptScript | Self::ScriptScriptCramped => Self::ScriptScriptCramped,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn numerator_child(self) -> Self {
|
||||
match self {
|
||||
Self::Display => Self::Text,
|
||||
Self::DisplayCramped => Self::TextCramped,
|
||||
Self::Text => Self::Script,
|
||||
Self::TextCramped => Self::ScriptCramped,
|
||||
Self::Script => Self::ScriptScript,
|
||||
Self::ScriptCramped => Self::ScriptScriptCramped,
|
||||
Self::ScriptScript | Self::ScriptScriptCramped => self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn denominator_child(self) -> Self {
|
||||
self.numerator_child().cramped()
|
||||
}
|
||||
|
||||
pub fn superscript_child(self) -> Self {
|
||||
match self {
|
||||
Self::Display | Self::Text => Self::Script,
|
||||
Self::DisplayCramped | Self::TextCramped => Self::ScriptCramped,
|
||||
Self::Script | Self::ScriptScript => Self::ScriptScript,
|
||||
Self::ScriptCramped | Self::ScriptScriptCramped => Self::ScriptScriptCramped,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn subscript_child(self) -> Self {
|
||||
self.superscript_child().cramped()
|
||||
}
|
||||
|
||||
pub fn is_cramped(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::DisplayCramped
|
||||
| Self::TextCramped
|
||||
| Self::ScriptCramped
|
||||
| Self::ScriptScriptCramped
|
||||
)
|
||||
}
|
||||
|
||||
pub fn is_display(self) -> bool {
|
||||
matches!(self, Self::Display | Self::DisplayCramped)
|
||||
}
|
||||
|
||||
pub fn is_text_size(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Display | Self::DisplayCramped | Self::Text | Self::TextCramped
|
||||
)
|
||||
}
|
||||
|
||||
pub fn conditional_math_spacing(self) -> bool {
|
||||
self.is_text_size()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{CatCode as EngineCatCode, EngineTokenValue};
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct CatCodeTable {
|
||||
low: Vec<EngineCatCode>,
|
||||
high: HashMap<usize, EngineCatCode>,
|
||||
end_line_char: i32,
|
||||
groups: Vec<CatCodeGroup>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
|
||||
struct CatCodeGroup {
|
||||
catcodes: HashMap<usize, Option<EngineCatCode>>,
|
||||
end_line_char: Option<i32>,
|
||||
}
|
||||
|
||||
impl CatCodeTable {
|
||||
pub fn latex_defaults() -> Self {
|
||||
let mut table = Self {
|
||||
low: EngineCatCode::PLAIN_TEX_DEFAULTS.to_vec(),
|
||||
high: HashMap::new(),
|
||||
end_line_char: '\r' as i32,
|
||||
groups: Vec::new(),
|
||||
};
|
||||
// LaTeX class and package files are read with `@` as a letter. The
|
||||
// engine keeps that convention for every source so that `\@foo`
|
||||
// commands tokenize as single control sequences; ordinary text
|
||||
// containing `@` is unaffected because letter characters still print.
|
||||
table.low['@' as usize] = EngineCatCode::Letter;
|
||||
table
|
||||
}
|
||||
|
||||
pub fn assign(&mut self, index: usize, catcode: EngineCatCode, global: bool) {
|
||||
self.prepare_assignment(index, global);
|
||||
*self.get_index_mut_ref(index) = catcode;
|
||||
}
|
||||
|
||||
pub fn get(&self, character: char) -> EngineCatCode {
|
||||
self.get_index(character as usize)
|
||||
}
|
||||
|
||||
pub fn get_index(&self, index: usize) -> EngineCatCode {
|
||||
*self.get_index_ref(index)
|
||||
}
|
||||
|
||||
pub fn get_index_ref(&self, index: usize) -> &EngineCatCode {
|
||||
self.low
|
||||
.get(index)
|
||||
.or_else(|| self.high.get(&index))
|
||||
.unwrap_or(&EngineCatCode::Other)
|
||||
}
|
||||
|
||||
pub fn get_index_mut_ref(&mut self, index: usize) -> &mut EngineCatCode {
|
||||
if let Some(catcode) = self.low.get_mut(index) {
|
||||
return catcode;
|
||||
}
|
||||
self.high.entry(index).or_insert(EngineCatCode::Other)
|
||||
}
|
||||
|
||||
pub fn prepare_assignment(&mut self, index: usize, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.catcodes.remove(&index);
|
||||
}
|
||||
} else if !self.groups.is_empty() {
|
||||
let previous = self.stored_value(index);
|
||||
self.groups
|
||||
.last_mut()
|
||||
.expect("catcode group exists")
|
||||
.catcodes
|
||||
.entry(index)
|
||||
.or_insert(previous);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.groups.push(CatCodeGroup::default());
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
let Some(group) = self.groups.pop() else {
|
||||
return;
|
||||
};
|
||||
for (index, value) in group.catcodes {
|
||||
self.set_index(index, value);
|
||||
}
|
||||
if let Some(end_line_char) = group.end_line_char {
|
||||
self.end_line_char = end_line_char;
|
||||
}
|
||||
}
|
||||
|
||||
/// XeTeX disables `\endlinechar` outside the 8-bit character range.
|
||||
pub fn end_line_char(&self) -> Option<char> {
|
||||
u32::try_from(self.end_line_char)
|
||||
.ok()
|
||||
.filter(|value| *value <= 255)
|
||||
.and_then(char::from_u32)
|
||||
}
|
||||
|
||||
pub fn end_line_char_value(&self) -> &i32 {
|
||||
&self.end_line_char
|
||||
}
|
||||
|
||||
pub fn end_line_char_value_mut_ref(&mut self, global: bool) -> &mut i32 {
|
||||
self.save_end_line_char_scope(global);
|
||||
&mut self.end_line_char
|
||||
}
|
||||
|
||||
pub fn assign_end_line_char(&mut self, value: i32, global: bool) {
|
||||
self.save_end_line_char_scope(global);
|
||||
self.end_line_char = value;
|
||||
}
|
||||
|
||||
fn save_end_line_char_scope(&mut self, global: bool) {
|
||||
if global {
|
||||
for group in &mut self.groups {
|
||||
group.end_line_char = None;
|
||||
}
|
||||
} else if let Some(group) = self.groups.last_mut() {
|
||||
group.end_line_char.get_or_insert(self.end_line_char);
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_value(&self, index: usize) -> Option<EngineCatCode> {
|
||||
self.low
|
||||
.get(index)
|
||||
.copied()
|
||||
.or_else(|| self.high.get(&index).copied())
|
||||
}
|
||||
|
||||
fn set_index(&mut self, index: usize, value: Option<EngineCatCode>) {
|
||||
if let Some(catcode) = self.low.get_mut(index) {
|
||||
if let Some(value) = value {
|
||||
*catcode = value;
|
||||
}
|
||||
return;
|
||||
}
|
||||
match value {
|
||||
Some(catcode) => {
|
||||
self.high.insert(index, catcode);
|
||||
}
|
||||
None => {
|
||||
self.high.remove(&index);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CatCodeTable {
|
||||
fn default() -> Self {
|
||||
Self::latex_defaults()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct SourceSpan {
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct Token {
|
||||
pub value: EngineTokenValue,
|
||||
pub span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct InvalidCharacter {
|
||||
pub value: char,
|
||||
pub span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum ScannerState {
|
||||
NewLine,
|
||||
MidLine,
|
||||
SkipBlanks,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct InputChar {
|
||||
value: char,
|
||||
span: SourceSpan,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct InputLine {
|
||||
chars: Vec<InputChar>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RawChar {
|
||||
input: InputChar,
|
||||
catcode: EngineCatCode,
|
||||
}
|
||||
|
||||
pub struct Mouth {
|
||||
source: String,
|
||||
next_line_start: usize,
|
||||
next_line_number: usize,
|
||||
current_line: Option<InputLine>,
|
||||
finished: bool,
|
||||
state: ScannerState,
|
||||
pending: Option<Token>,
|
||||
}
|
||||
|
||||
impl Mouth {
|
||||
pub fn new(source: &str) -> Self {
|
||||
Self {
|
||||
source: source.to_string(),
|
||||
next_line_start: 0,
|
||||
next_line_number: 1,
|
||||
current_line: None,
|
||||
finished: false,
|
||||
state: ScannerState::NewLine,
|
||||
pending: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_token(
|
||||
&mut self,
|
||||
catcodes: &CatCodeTable,
|
||||
) -> Result<Option<Token>, InvalidCharacter> {
|
||||
if let Some(token) = self.pending.take() {
|
||||
return Ok(Some(token));
|
||||
}
|
||||
|
||||
loop {
|
||||
let Some(raw) = self.next_raw(catcodes) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let character = raw.input.value;
|
||||
let token = match raw.catcode {
|
||||
EngineCatCode::Escape => {
|
||||
let (name, state, end) = self.read_control_sequence(raw.input, catcodes);
|
||||
self.state = state;
|
||||
Token {
|
||||
value: EngineTokenValue::ControlSequence(name),
|
||||
span: SourceSpan {
|
||||
end,
|
||||
..raw.input.span
|
||||
},
|
||||
}
|
||||
}
|
||||
EngineCatCode::EndOfLine => {
|
||||
self.end_current_line();
|
||||
let token = match self.state {
|
||||
ScannerState::NewLine => Token {
|
||||
value: EngineTokenValue::ControlSequence("par".to_string()),
|
||||
span: raw.input.span,
|
||||
},
|
||||
ScannerState::MidLine => Token {
|
||||
value: EngineTokenValue::Character {
|
||||
value: ' ',
|
||||
catcode: EngineCatCode::Space,
|
||||
},
|
||||
span: raw.input.span,
|
||||
},
|
||||
ScannerState::SkipBlanks => continue,
|
||||
};
|
||||
self.state = ScannerState::NewLine;
|
||||
token
|
||||
}
|
||||
EngineCatCode::Space => match self.state {
|
||||
ScannerState::NewLine | ScannerState::SkipBlanks => continue,
|
||||
ScannerState::MidLine => {
|
||||
self.state = ScannerState::SkipBlanks;
|
||||
Token {
|
||||
value: EngineTokenValue::Character {
|
||||
value: ' ',
|
||||
catcode: EngineCatCode::Space,
|
||||
},
|
||||
span: raw.input.span,
|
||||
}
|
||||
}
|
||||
},
|
||||
EngineCatCode::BeginGroup
|
||||
| EngineCatCode::EndGroup
|
||||
| EngineCatCode::MathShift
|
||||
| EngineCatCode::AlignmentTab
|
||||
| EngineCatCode::Parameter
|
||||
| EngineCatCode::Subscript
|
||||
| EngineCatCode::Letter
|
||||
| EngineCatCode::Other => {
|
||||
self.state = ScannerState::MidLine;
|
||||
Token {
|
||||
value: EngineTokenValue::Character {
|
||||
value: character,
|
||||
catcode: raw.catcode,
|
||||
},
|
||||
span: raw.input.span,
|
||||
}
|
||||
}
|
||||
EngineCatCode::Superscript => {
|
||||
if self.maybe_apply_caret_notation(character, true) {
|
||||
continue;
|
||||
}
|
||||
self.state = ScannerState::MidLine;
|
||||
Token {
|
||||
value: EngineTokenValue::Character {
|
||||
value: character,
|
||||
catcode: raw.catcode,
|
||||
},
|
||||
span: raw.input.span,
|
||||
}
|
||||
}
|
||||
EngineCatCode::Active => {
|
||||
self.state = ScannerState::MidLine;
|
||||
Token {
|
||||
value: EngineTokenValue::Active(character),
|
||||
span: raw.input.span,
|
||||
}
|
||||
}
|
||||
EngineCatCode::Comment => {
|
||||
self.end_current_line();
|
||||
continue;
|
||||
}
|
||||
EngineCatCode::Ignored => continue,
|
||||
EngineCatCode::Invalid => {
|
||||
return Err(InvalidCharacter {
|
||||
value: character,
|
||||
span: raw.input.span,
|
||||
});
|
||||
}
|
||||
};
|
||||
return Ok(Some(token));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unread_token(&mut self, token: Token) {
|
||||
debug_assert!(self.pending.is_none());
|
||||
self.pending = Some(token);
|
||||
}
|
||||
|
||||
fn next_raw(&mut self, catcodes: &CatCodeTable) -> Option<RawChar> {
|
||||
loop {
|
||||
let line_is_exhausted = self
|
||||
.current_line
|
||||
.as_ref()
|
||||
.is_none_or(|line| line.position >= line.chars.len());
|
||||
if line_is_exhausted {
|
||||
self.state = ScannerState::NewLine;
|
||||
if !self.start_new_line(catcodes) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
let line = self.current_line.as_mut()?;
|
||||
let input = *line.chars.get(line.position)?;
|
||||
line.position += 1;
|
||||
return Some(RawChar {
|
||||
input,
|
||||
catcode: catcodes.get(input.value),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn start_new_line(&mut self, catcodes: &CatCodeTable) -> bool {
|
||||
if self.finished || self.source.is_empty() || self.next_line_start >= self.source.len() {
|
||||
self.finished = true;
|
||||
return false;
|
||||
}
|
||||
|
||||
let start = self.next_line_start;
|
||||
let (source_end, next_line_start) = match self.source[start..].find('\n') {
|
||||
Some(offset) => (start + offset, start + offset + 1),
|
||||
None => (self.source.len(), self.source.len()),
|
||||
};
|
||||
let has_line_feed = next_line_start > source_end;
|
||||
let line_number = self.next_line_number;
|
||||
let mut chars = Vec::new();
|
||||
let mut column = 1;
|
||||
for (byte_offset, value) in self.source[start..source_end].char_indices() {
|
||||
let absolute_start = start + byte_offset;
|
||||
let mut end = absolute_start + value.len_utf8();
|
||||
if value == '\r' && has_line_feed && end == source_end {
|
||||
end = next_line_start;
|
||||
}
|
||||
chars.push(InputChar {
|
||||
value,
|
||||
span: SourceSpan {
|
||||
start: absolute_start,
|
||||
end,
|
||||
line: line_number,
|
||||
column,
|
||||
},
|
||||
});
|
||||
column += 1;
|
||||
}
|
||||
while chars.last().is_some_and(|character| character.value == ' ') {
|
||||
chars.pop();
|
||||
}
|
||||
let end_of_trimmed_source = chars.last().map_or(start, |character| {
|
||||
character.span.start + character.value.len_utf8()
|
||||
});
|
||||
if let Some(end_line_char) = catcodes.end_line_char() {
|
||||
chars.push(InputChar {
|
||||
value: end_line_char,
|
||||
span: SourceSpan {
|
||||
start: end_of_trimmed_source,
|
||||
end: next_line_start,
|
||||
line: line_number,
|
||||
column: chars.len() + 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
self.current_line = Some(InputLine { chars, position: 0 });
|
||||
self.next_line_start = next_line_start;
|
||||
self.next_line_number += 1;
|
||||
true
|
||||
}
|
||||
|
||||
fn end_current_line(&mut self) {
|
||||
if let Some(line) = &mut self.current_line {
|
||||
line.position = line.chars.len();
|
||||
}
|
||||
}
|
||||
|
||||
fn read_control_sequence(
|
||||
&mut self,
|
||||
escape: InputChar,
|
||||
catcodes: &CatCodeTable,
|
||||
) -> (String, ScannerState, usize) {
|
||||
let first = loop {
|
||||
let Some(first) = self.next_raw(catcodes) else {
|
||||
return (String::new(), ScannerState::NewLine, escape.span.end);
|
||||
};
|
||||
if first.catcode == EngineCatCode::Superscript
|
||||
&& self.maybe_apply_caret_notation(first.input.value, true)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
break first;
|
||||
};
|
||||
|
||||
let mut name = String::new();
|
||||
name.push(first.input.value);
|
||||
if first.catcode == EngineCatCode::Letter {
|
||||
loop {
|
||||
let Some(next) = self.peek_raw(catcodes) else {
|
||||
break;
|
||||
};
|
||||
if next.catcode == EngineCatCode::Superscript
|
||||
&& self.maybe_apply_caret_notation(next.input.value, false)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if next.catcode != EngineCatCode::Letter {
|
||||
break;
|
||||
}
|
||||
let next = self
|
||||
.next_raw(catcodes)
|
||||
.expect("peeked input character exists");
|
||||
name.push(next.input.value);
|
||||
}
|
||||
}
|
||||
let state = match first.catcode {
|
||||
EngineCatCode::Letter | EngineCatCode::Space => ScannerState::SkipBlanks,
|
||||
_ => ScannerState::MidLine,
|
||||
};
|
||||
let end = self.last_consumed_end().unwrap_or(first.input.span.end);
|
||||
(name, state, end.max(escape.span.end))
|
||||
}
|
||||
|
||||
fn peek_raw(&mut self, catcodes: &CatCodeTable) -> Option<RawChar> {
|
||||
let line_is_exhausted = self
|
||||
.current_line
|
||||
.as_ref()
|
||||
.is_none_or(|line| line.position >= line.chars.len());
|
||||
if line_is_exhausted {
|
||||
return None;
|
||||
}
|
||||
let line = self.current_line.as_ref()?;
|
||||
let input = *line.chars.get(line.position)?;
|
||||
Some(RawChar {
|
||||
input,
|
||||
catcode: catcodes.get(input.value),
|
||||
})
|
||||
}
|
||||
|
||||
fn last_consumed_end(&self) -> Option<usize> {
|
||||
let line = self.current_line.as_ref()?;
|
||||
line.position
|
||||
.checked_sub(1)
|
||||
.and_then(|index| line.chars.get(index))
|
||||
.map(|input| input.span.end)
|
||||
}
|
||||
|
||||
fn maybe_apply_caret_notation(&mut self, caret: char, caret_consumed: bool) -> bool {
|
||||
let Some(line) = &mut self.current_line else {
|
||||
return false;
|
||||
};
|
||||
let first_caret_index = if caret_consumed {
|
||||
line.position.checked_sub(1)
|
||||
} else {
|
||||
Some(line.position)
|
||||
};
|
||||
let Some(first_caret_index) = first_caret_index else {
|
||||
return false;
|
||||
};
|
||||
let second_caret_index = first_caret_index + 1;
|
||||
let third_character_index = second_caret_index + 1;
|
||||
let (Some(first), Some(second), Some(third)) = (
|
||||
line.chars.get(first_caret_index),
|
||||
line.chars.get(second_caret_index),
|
||||
line.chars.get(third_character_index),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
if first.value != caret || second.value != caret {
|
||||
return false;
|
||||
}
|
||||
|
||||
line.position = third_character_index;
|
||||
let Some(byte) = u8::try_from(third.value as u32).ok().filter(u8::is_ascii) else {
|
||||
return true;
|
||||
};
|
||||
let transformed = match byte {
|
||||
0x00..=0x3f => byte + 0x40,
|
||||
0x40..=0x7f => byte - 0x40,
|
||||
_ => return true,
|
||||
};
|
||||
if let Some(character) = char::from_u32(u32::from(transformed)) {
|
||||
if let Some(input) = line.chars.get_mut(third_character_index) {
|
||||
input.value = character;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Token {
|
||||
pub fn control_sequence(&self) -> Option<&str> {
|
||||
match &self.value {
|
||||
EngineTokenValue::ControlSequence(name) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn character(&self) -> Option<(char, EngineCatCode)> {
|
||||
match self.value {
|
||||
EngineTokenValue::Character { value, catcode } => Some((value, catcode)),
|
||||
EngineTokenValue::Active(value) => Some((value, EngineCatCode::Active)),
|
||||
EngineTokenValue::ControlSequence(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::document::{Block, DocumentModel, ListBlock, ParsedDocument, Run, UnresolvedReference};
|
||||
|
||||
/// Resolves document references after parsing has collected all labels and citations.
|
||||
pub fn resolve(parsed: ParsedDocument) -> DocumentModel {
|
||||
let mut document = parsed.0;
|
||||
fn resolve_runs(
|
||||
runs: &mut [Run],
|
||||
labels: &HashMap<String, String>,
|
||||
citations: &HashMap<String, usize>,
|
||||
) {
|
||||
for run in runs {
|
||||
let Some(reference) = run.unresolved_reference.take() else {
|
||||
continue;
|
||||
};
|
||||
run.text = match reference {
|
||||
UnresolvedReference::Label(key) => labels
|
||||
.get(&key)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| "??".to_string()),
|
||||
UnresolvedReference::Citation(keys) => {
|
||||
let formatted = keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
citations
|
||||
.get(key)
|
||||
.map(usize::to_string)
|
||||
.unwrap_or_else(|| key.clone())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!("[{formatted}]")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_list(
|
||||
list: &mut ListBlock,
|
||||
labels: &HashMap<String, String>,
|
||||
citations: &HashMap<String, usize>,
|
||||
) {
|
||||
for item in &mut list.items {
|
||||
resolve_runs(&mut item.runs, labels, citations);
|
||||
for nested in &mut item.nested {
|
||||
resolve_list(nested, labels, citations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let labels = &document.labels;
|
||||
let citations = &document.citations;
|
||||
for block in &mut document.blocks {
|
||||
match block {
|
||||
Block::Paragraph(runs) | Block::Heading { runs, .. } => {
|
||||
resolve_runs(runs, labels, citations)
|
||||
}
|
||||
Block::List(list) => resolve_list(list, labels, citations),
|
||||
Block::Table { rows, caption, .. } => {
|
||||
for cell in rows.iter_mut().flatten() {
|
||||
resolve_runs(cell, labels, citations);
|
||||
}
|
||||
if let Some(caption) = caption {
|
||||
resolve_runs(caption, labels, citations);
|
||||
}
|
||||
}
|
||||
Block::Image { caption, .. } => {
|
||||
if let Some(caption) = caption {
|
||||
resolve_runs(caption, labels, citations);
|
||||
}
|
||||
}
|
||||
Block::FramedBox { runs, .. } | Block::Centered { runs } => {
|
||||
resolve_runs(runs, labels, citations)
|
||||
}
|
||||
Block::Bibliography(items) => {
|
||||
for (_, runs) in items {
|
||||
resolve_runs(runs, labels, citations);
|
||||
}
|
||||
}
|
||||
Block::HorizontalRule { .. }
|
||||
| Block::Math { .. }
|
||||
| Block::VerticalKern(_)
|
||||
| Block::VerticalGlue(_)
|
||||
| Block::Penalty(_)
|
||||
| Block::PageBreak => {}
|
||||
}
|
||||
}
|
||||
document
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Where a TeX source location originated.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum SourceOrigin {
|
||||
File(PathBuf),
|
||||
Terminal,
|
||||
}
|
||||
|
||||
/// A one-based source position owned independently of a runtime adapter.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SourceLocation {
|
||||
pub origin: SourceOrigin,
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use crate::{
|
||||
EngineCommandName,
|
||||
assignment_scope::AssignmentScope,
|
||||
command::{EngineCommandMeaning, NativeCommandTable},
|
||||
environment::EnvironmentStack,
|
||||
macros::MacroTable,
|
||||
math_code::{DelimiterCodeTable, MathCodeTable, UnicodeMathCodeTable},
|
||||
mouth::CatCodeTable,
|
||||
};
|
||||
|
||||
/// Mutable TeX language state shared across tokenization and execution phases.
|
||||
///
|
||||
/// Runtime adapters may hold this state, but the values and group semantics are
|
||||
/// owned by the Rust engine core.
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EngineSemanticState {
|
||||
pub catcodes: CatCodeTable,
|
||||
pub math_codes: MathCodeTable,
|
||||
pub unicode_math_codes: UnicodeMathCodeTable,
|
||||
pub delimiter_codes: DelimiterCodeTable,
|
||||
pub assignment_scope: AssignmentScope,
|
||||
pub pending_global_assignment: bool,
|
||||
pub environments: EnvironmentStack,
|
||||
pub macros: MacroTable,
|
||||
#[serde(default)]
|
||||
pub native_commands: NativeCommandTable,
|
||||
group_depth: usize,
|
||||
}
|
||||
|
||||
impl EngineSemanticState {
|
||||
/// Resolve a control sequence using engine-owned macro and primitive meanings.
|
||||
pub fn command_meaning(&self, name: &EngineCommandName) -> Option<EngineCommandMeaning> {
|
||||
if self.macros.get(name).is_some() {
|
||||
Some(EngineCommandMeaning::Macro)
|
||||
} else {
|
||||
self.native_commands
|
||||
.get(name)
|
||||
.map(EngineCommandMeaning::Native)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_group(&mut self) {
|
||||
self.group_depth += 1;
|
||||
self.catcodes.begin_group();
|
||||
self.math_codes.begin_group();
|
||||
self.unicode_math_codes.begin_group();
|
||||
self.delimiter_codes.begin_group();
|
||||
self.assignment_scope.begin_group();
|
||||
self.macros.begin_group();
|
||||
self.native_commands.begin_group();
|
||||
}
|
||||
|
||||
pub fn end_group(&mut self) {
|
||||
self.group_depth = self.group_depth.saturating_sub(1);
|
||||
self.catcodes.end_group();
|
||||
self.math_codes.end_group();
|
||||
self.unicode_math_codes.end_group();
|
||||
self.delimiter_codes.end_group();
|
||||
self.assignment_scope.end_group();
|
||||
self.macros.end_group();
|
||||
self.native_commands.end_group();
|
||||
}
|
||||
|
||||
pub fn is_safe_document_checkpoint(&self) -> bool {
|
||||
if self.group_depth != 0 {
|
||||
return false;
|
||||
}
|
||||
match self.environments.as_slice() {
|
||||
[] => true,
|
||||
[environment] => environment == "document",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user