2387 lines
78 KiB
Rust
2387 lines
78 KiB
Rust
use std::collections::BTreeMap;
|
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
|
|
|
use super::{
|
|
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
|
|
RegisterKind, RegisterValue, Token, TokenKind, TokenParameter,
|
|
};
|
|
|
|
#[derive(
|
|
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
|
|
)]
|
|
pub enum CommandName {
|
|
Control(String),
|
|
Active(char),
|
|
/// TeX's frozen font identifier, emitted by the/font-family quantities.
|
|
/// It retains the loaded font even when the spelling selector is redefined.
|
|
Font(FontId),
|
|
FrozenRelax,
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum Primitive {
|
|
Relax,
|
|
Ignorespaces,
|
|
Explicitspace,
|
|
Par,
|
|
BeginGroup,
|
|
EndGroup,
|
|
Global,
|
|
Long,
|
|
Outer,
|
|
Protected,
|
|
Def,
|
|
Gdef,
|
|
Edef,
|
|
Xdef,
|
|
Let,
|
|
Futurelet,
|
|
Afterassignment,
|
|
Aftergroup,
|
|
Chardef,
|
|
Mathchardef,
|
|
Inputlineno,
|
|
Catcode,
|
|
Lccode,
|
|
Uccode,
|
|
Lowercase,
|
|
Uppercase,
|
|
Endlinechar,
|
|
Newlinechar,
|
|
Escapechar,
|
|
Interactionmode,
|
|
Batchmode,
|
|
Nonstopmode,
|
|
Scrollmode,
|
|
Errorstopmode,
|
|
Time,
|
|
Day,
|
|
Month,
|
|
Year,
|
|
Globaldefs,
|
|
Count,
|
|
Countdef,
|
|
Dimen,
|
|
Dimendef,
|
|
Skip,
|
|
Skipdef,
|
|
Muskip,
|
|
Muskipdef,
|
|
Toks,
|
|
Toksdef,
|
|
Advance,
|
|
Multiply,
|
|
Divide,
|
|
The,
|
|
Number,
|
|
Romannumeral,
|
|
String,
|
|
MeaningOf,
|
|
Noexpand,
|
|
Unexpanded,
|
|
Expanded,
|
|
Detokenize,
|
|
Numexpr,
|
|
Dimexpr,
|
|
Glueexpr,
|
|
Muexpr,
|
|
Etexversion,
|
|
Etexrevision,
|
|
Pdffilesize,
|
|
Pdffilemoddate,
|
|
Pdfmdfivesum,
|
|
Pdfximage,
|
|
Pdfrefximage,
|
|
Pdflastximage,
|
|
Pdflastximagepages,
|
|
Pdflastximagecolordepth,
|
|
Jobname,
|
|
Pdfcreationdate,
|
|
Pdfshellescape,
|
|
Pdftexversion,
|
|
Pdftexrevision,
|
|
Ifpdfabsnum,
|
|
Ifpdfabsdim,
|
|
Pdfstrcmp,
|
|
Pdfcolorstackinit,
|
|
Pdfcolorstack,
|
|
Pdfsave,
|
|
Pdfstartlink,
|
|
Pdfendlink,
|
|
Pdfrunninglinkoff,
|
|
Pdfrunninglinkon,
|
|
Pdfinterwordspaceon,
|
|
Pdfinterwordspaceoff,
|
|
Pdffakespace,
|
|
Pdfspacefont,
|
|
Pdfdest,
|
|
Pdfcatalog,
|
|
Pdfoutline,
|
|
Pdfinfo,
|
|
Pdfsetmatrix,
|
|
Pdfsavepos,
|
|
Pdflastxpos,
|
|
Pdflastypos,
|
|
Pdfrestore,
|
|
Pdfglyphtounicode,
|
|
Pdfmapfile,
|
|
Pdfmapline,
|
|
Pdffontattr,
|
|
Pdfnobuiltintounicode,
|
|
Currentgrouplevel,
|
|
Currentgrouptype,
|
|
Unless,
|
|
Expandafter,
|
|
Csname,
|
|
Endcsname,
|
|
Iftrue,
|
|
Iffalse,
|
|
Ifx,
|
|
Ifnum,
|
|
Ifdefined,
|
|
// Conditional commands also nest in skipped input without evaluating it.
|
|
If,
|
|
Ifcat,
|
|
Ifdim,
|
|
Ifodd,
|
|
Ifvmode,
|
|
Ifhmode,
|
|
Ifmmode,
|
|
Ifinner,
|
|
Ifvoid,
|
|
Ifhbox,
|
|
Ifvbox,
|
|
Ifcase,
|
|
Ifeof,
|
|
Ifcsname,
|
|
Ifincsname,
|
|
Iffontchar,
|
|
Else,
|
|
Or,
|
|
Fi,
|
|
Input,
|
|
Endinput,
|
|
Scantokens,
|
|
Openin,
|
|
Closein,
|
|
Read,
|
|
Readline,
|
|
Openout,
|
|
Closeout,
|
|
Write,
|
|
Immediate,
|
|
Message,
|
|
Errmessage,
|
|
End,
|
|
Dump,
|
|
Indent,
|
|
Noindent,
|
|
Hskip,
|
|
Leaders,
|
|
Cleaders,
|
|
Xleaders,
|
|
Hfil,
|
|
Hfill,
|
|
Hss,
|
|
Hfilneg,
|
|
Kern,
|
|
Penalty,
|
|
Unskip,
|
|
Unkern,
|
|
Unpenalty,
|
|
Lastskip,
|
|
Lastkern,
|
|
Lastpenalty,
|
|
Lastnodetype,
|
|
Gluestretch,
|
|
Glueshrink,
|
|
Gluestretchorder,
|
|
Glueshrinkorder,
|
|
ItalicCorrection,
|
|
DiscretionaryHyphen,
|
|
Discretionary,
|
|
Hyphenation,
|
|
Patterns,
|
|
Setlanguage,
|
|
Font,
|
|
Fontname,
|
|
Letterspacefont,
|
|
Fontdimen,
|
|
Fontcharwd,
|
|
Fontcharht,
|
|
Fontchardp,
|
|
Fontcharic,
|
|
Hyphenchar,
|
|
Skewchar,
|
|
Mathaccent,
|
|
Mathchoice,
|
|
Overline,
|
|
Underline,
|
|
Eqno,
|
|
Leqno,
|
|
Parshape,
|
|
Parshapelength,
|
|
Parshapeindent,
|
|
Parshapedimen,
|
|
Spacefactor,
|
|
Setbox,
|
|
Box,
|
|
Copy,
|
|
Hbox,
|
|
Halign,
|
|
Valign,
|
|
Cr,
|
|
Crcr,
|
|
Span,
|
|
Omit,
|
|
Noalign,
|
|
Showbox,
|
|
Show,
|
|
Showthe,
|
|
Showlists,
|
|
Showgroups,
|
|
Showifs,
|
|
Vbox,
|
|
Vtop,
|
|
Vcenter,
|
|
Vskip,
|
|
Vfil,
|
|
Vfill,
|
|
Vss,
|
|
Vfilneg,
|
|
Hrule,
|
|
Vrule,
|
|
Raise,
|
|
Lower,
|
|
Moveleft,
|
|
Moveright,
|
|
Unhbox,
|
|
Unhcopy,
|
|
Unvbox,
|
|
Unvcopy,
|
|
Pagediscards,
|
|
Splitdiscards,
|
|
Lastbox,
|
|
Vsplit,
|
|
Mark,
|
|
Vadjust,
|
|
Insert,
|
|
Insertpenalties,
|
|
Marks,
|
|
Splitfirstmark,
|
|
Splitbotmark,
|
|
Splitfirstmarks,
|
|
Splitbotmarks,
|
|
Topmark,
|
|
Firstmark,
|
|
Botmark,
|
|
Topmarks,
|
|
Firstmarks,
|
|
Botmarks,
|
|
Shipout,
|
|
Deadcycles,
|
|
Pagegoal,
|
|
Pagetotal,
|
|
Pagestretch,
|
|
Pagefilstretch,
|
|
Pagefillstretch,
|
|
Pagefilllstretch,
|
|
Pageshrink,
|
|
Pagedepth,
|
|
Prevdepth,
|
|
Prevgraf,
|
|
Wd,
|
|
Ht,
|
|
Dp,
|
|
Badness,
|
|
Mathcode,
|
|
Delcode,
|
|
Sfcode,
|
|
Delimiter,
|
|
Radical,
|
|
Left,
|
|
Right,
|
|
Mathchar,
|
|
Char,
|
|
Noboundary,
|
|
Textfont,
|
|
Scriptfont,
|
|
Scriptscriptfont,
|
|
Mathord,
|
|
Mathop,
|
|
Mathbin,
|
|
Mathrel,
|
|
Mathopen,
|
|
Mathclose,
|
|
Mathpunct,
|
|
Mathinner,
|
|
Limits,
|
|
Nolimits,
|
|
Displaylimits,
|
|
Displaystyle,
|
|
Textstyle,
|
|
Scriptstyle,
|
|
Scriptscriptstyle,
|
|
Mskip,
|
|
Mkern,
|
|
Over,
|
|
Atop,
|
|
Above,
|
|
Overwithdelims,
|
|
Atopwithdelims,
|
|
Abovewithdelims,
|
|
Accent,
|
|
Pdfmatch,
|
|
Pdflastmatch,
|
|
Lpcode,
|
|
Rpcode,
|
|
Knbccode,
|
|
Knaccode,
|
|
Efcode,
|
|
Pdffontexpand,
|
|
Pdfobj,
|
|
Pdfrefobj,
|
|
Pdflastobj,
|
|
Pdfrandomseed,
|
|
Pdfsetrandomseed,
|
|
Pdfuniformdeviate,
|
|
Pdfnormaldeviate,
|
|
Pdfpageref,
|
|
Partokenname,
|
|
Pdfliteral,
|
|
Leftmarginkern,
|
|
Rightmarginkern,
|
|
Pdflastlink,
|
|
Special,
|
|
Umathcode,
|
|
Umathcodenum,
|
|
Umathchar,
|
|
Umathcharnum,
|
|
Umathchardef,
|
|
Umathcharnumdef,
|
|
Uchar,
|
|
Ucharcat,
|
|
XeTeXversion,
|
|
XeTeXrevision,
|
|
XeTeXpdffile,
|
|
XeTeXpdfpagecount,
|
|
XeTeXpicfile,
|
|
XeTeXfonttype,
|
|
XeTeXcountglyphs,
|
|
XeTeXcharglyph,
|
|
XeTeXglyphindex,
|
|
XeTeXOTcountscripts,
|
|
XeTeXOTscripttag,
|
|
XeTeXOTcountlanguages,
|
|
XeTeXOTlanguagetag,
|
|
XeTeXOTcountfeatures,
|
|
XeTeXOTfeaturetag,
|
|
Udelcode,
|
|
Udelcodenum,
|
|
Udelimiter,
|
|
Uradical,
|
|
Umathaccent,
|
|
BeginL,
|
|
EndL,
|
|
BeginR,
|
|
EndR,
|
|
XeTeXinputencoding,
|
|
XeTeXdefaultencoding,
|
|
XeTeXcharclass,
|
|
XeTeXinterchartoks,
|
|
XeTeXglyph,
|
|
XeTeXglyphbounds,
|
|
XeTeXglyphname,
|
|
XeTeXfirstfontchar,
|
|
XeTeXlastfontchar,
|
|
XeTeXlinebreaklocale,
|
|
XeTeXcountfeatures,
|
|
XeTeXfeaturecode,
|
|
XeTeXfindfeaturebyname,
|
|
XeTeXisexclusivefeature,
|
|
XeTeXcountselectors,
|
|
XeTeXselectorcode,
|
|
XeTeXfindselectorbyname,
|
|
XeTeXisdefaultselector,
|
|
XeTeXfeaturename,
|
|
XeTeXselectorname,
|
|
}
|
|
|
|
impl Primitive {
|
|
const XETEX_FONT_QUERIES: [Self; 20] = [
|
|
Self::XeTeXfonttype,
|
|
Self::XeTeXcountglyphs,
|
|
Self::XeTeXcharglyph,
|
|
Self::XeTeXglyphindex,
|
|
Self::XeTeXfirstfontchar,
|
|
Self::XeTeXlastfontchar,
|
|
Self::XeTeXOTcountscripts,
|
|
Self::XeTeXOTscripttag,
|
|
Self::XeTeXOTcountlanguages,
|
|
Self::XeTeXOTlanguagetag,
|
|
Self::XeTeXOTcountfeatures,
|
|
Self::XeTeXOTfeaturetag,
|
|
Self::XeTeXcountfeatures,
|
|
Self::XeTeXfeaturecode,
|
|
Self::XeTeXfindfeaturebyname,
|
|
Self::XeTeXisexclusivefeature,
|
|
Self::XeTeXcountselectors,
|
|
Self::XeTeXselectorcode,
|
|
Self::XeTeXfindselectorbyname,
|
|
Self::XeTeXisdefaultselector,
|
|
];
|
|
|
|
pub(super) fn xetex_font_query_name(self) -> Option<&'static str> {
|
|
Some(match self {
|
|
Self::XeTeXfonttype => "XeTeXfonttype",
|
|
Self::XeTeXcountglyphs => "XeTeXcountglyphs",
|
|
Self::XeTeXcharglyph => "XeTeXcharglyph",
|
|
Self::XeTeXglyphindex => "XeTeXglyphindex",
|
|
Self::XeTeXfirstfontchar => "XeTeXfirstfontchar",
|
|
Self::XeTeXlastfontchar => "XeTeXlastfontchar",
|
|
Self::XeTeXOTcountscripts => "XeTeXOTcountscripts",
|
|
Self::XeTeXOTscripttag => "XeTeXOTscripttag",
|
|
Self::XeTeXOTcountlanguages => "XeTeXOTcountlanguages",
|
|
Self::XeTeXOTlanguagetag => "XeTeXOTlanguagetag",
|
|
Self::XeTeXOTcountfeatures => "XeTeXOTcountfeatures",
|
|
Self::XeTeXOTfeaturetag => "XeTeXOTfeaturetag",
|
|
Self::XeTeXcountfeatures => "XeTeXcountfeatures",
|
|
Self::XeTeXfeaturecode => "XeTeXfeaturecode",
|
|
Self::XeTeXfindfeaturebyname => "XeTeXfindfeaturebyname",
|
|
Self::XeTeXisexclusivefeature => "XeTeXisexclusivefeature",
|
|
Self::XeTeXcountselectors => "XeTeXcountselectors",
|
|
Self::XeTeXselectorcode => "XeTeXselectorcode",
|
|
Self::XeTeXfindselectorbyname => "XeTeXfindselectorbyname",
|
|
Self::XeTeXisdefaultselector => "XeTeXisdefaultselector",
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
pub(super) fn page_dimension(self) -> Option<usize> {
|
|
use Primitive::*;
|
|
Some(match self {
|
|
Pagegoal => 0,
|
|
Pagetotal => 1,
|
|
Pagestretch => 2,
|
|
Pagefilstretch => 3,
|
|
Pagefillstretch => 4,
|
|
Pagefilllstretch => 5,
|
|
Pageshrink => 6,
|
|
Pagedepth => 7,
|
|
_ => return None,
|
|
})
|
|
}
|
|
pub(super) fn expandable(self) -> bool {
|
|
use Primitive::*;
|
|
self.conditional()
|
|
|| matches!(
|
|
self,
|
|
Splitfirstmark
|
|
| Splitbotmark
|
|
| Splitfirstmarks
|
|
| Splitbotmarks
|
|
| Topmark
|
|
| Firstmark
|
|
| Botmark
|
|
| Topmarks
|
|
| Firstmarks
|
|
| Botmarks
|
|
| Noexpand
|
|
| Expandafter
|
|
| Number
|
|
| Uchar
|
|
| Ucharcat
|
|
| Romannumeral
|
|
| Fontname
|
|
| The
|
|
| String
|
|
| MeaningOf
|
|
| Unexpanded
|
|
| Expanded
|
|
| Detokenize
|
|
| Etexrevision
|
|
| Pdffilesize
|
|
| Pdffilemoddate
|
|
| Pdfmdfivesum
|
|
| Jobname
|
|
| Pdfcreationdate
|
|
| Pdftexrevision
|
|
| XeTeXrevision
|
|
| XeTeXglyphname
|
|
| XeTeXfeaturename
|
|
| XeTeXselectorname
|
|
| Pdfstrcmp
|
|
| Pdfmatch
|
|
| Pdflastmatch
|
|
| Pdfuniformdeviate
|
|
| Pdfnormaldeviate
|
|
| Pdfpageref
|
|
| Leftmarginkern
|
|
| Rightmarginkern
|
|
| Pdfcolorstackinit
|
|
| Csname
|
|
| Unless
|
|
| Else
|
|
| Or
|
|
| Fi
|
|
| Scantokens
|
|
| Input
|
|
)
|
|
}
|
|
pub(super) fn conditional(self) -> bool {
|
|
matches!(
|
|
self,
|
|
Self::Iftrue
|
|
| Self::Iffalse
|
|
| Self::Ifx
|
|
| Self::Ifnum
|
|
| Self::Ifpdfabsnum
|
|
| Self::Ifpdfabsdim
|
|
| Self::Ifdefined
|
|
| Self::If
|
|
| Self::Ifcat
|
|
| Self::Ifdim
|
|
| Self::Ifodd
|
|
| Self::Ifvmode
|
|
| Self::Ifhmode
|
|
| Self::Ifmmode
|
|
| Self::Ifinner
|
|
| Self::Ifvoid
|
|
| Self::Ifhbox
|
|
| Self::Ifvbox
|
|
| Self::Ifcase
|
|
| Self::Ifeof
|
|
| Self::Ifcsname
|
|
| Self::Ifincsname
|
|
| Self::Iffontchar
|
|
)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum Replacement {
|
|
Token(Token),
|
|
Parameter(usize),
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct Macro {
|
|
pub prefix: Vec<TokenKind>,
|
|
/// One delimiter per argument; an empty delimiter means undelimited.
|
|
pub parameters: Vec<Vec<TokenKind>>,
|
|
pub parameter_chars: Vec<char>,
|
|
pub replacement: Vec<Replacement>,
|
|
pub long: bool,
|
|
pub outer: bool,
|
|
pub protected: bool,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub enum Meaning {
|
|
Undefined,
|
|
Primitive(Primitive),
|
|
Macro(std::sync::Arc<Macro>),
|
|
Character(TokenKind),
|
|
Count(u16),
|
|
Toks(u16),
|
|
TokenParameter(TokenParameter),
|
|
CharGiven(u32),
|
|
MathCharGiven(u16),
|
|
Register(Register),
|
|
Parameter(Parameter),
|
|
Font(FontId),
|
|
UnicodeMathCharGiven(super::MathCode),
|
|
}
|
|
|
|
/// Explicit bootstrap language selection. EtexBootstrap implements the native
|
|
/// extended macro/integer language below; it does not claim full e-TeX mode,
|
|
/// marks, glue/dimension expression or format-image conformance.
|
|
#[derive(
|
|
Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
|
|
)]
|
|
pub enum Profile {
|
|
#[default]
|
|
Bootstrap,
|
|
EtexBootstrap,
|
|
}
|
|
|
|
#[derive(
|
|
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
|
|
)]
|
|
pub(super) enum Key {
|
|
Command(CommandName),
|
|
Catcode(char),
|
|
Count(u16),
|
|
Toks(u16),
|
|
TokenParameter(TokenParameter),
|
|
Endlinechar,
|
|
Newlinechar,
|
|
Escapechar,
|
|
Globaldefs,
|
|
Job(JobParameter),
|
|
Register(Register),
|
|
Parameter(Parameter),
|
|
Font,
|
|
ParagraphShape,
|
|
Spacefactor,
|
|
Box(u16),
|
|
Mathcode(u32),
|
|
Delcode(u32),
|
|
Sfcode(u32),
|
|
XeInterCharTokens(u32),
|
|
CaseCode(super::CaseCode, char),
|
|
Mathfont(u8, u8),
|
|
Mathcodenum(u32),
|
|
Delcodenum(u32),
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub(super) enum Saved {
|
|
Command(Option<Meaning>),
|
|
Catcode(Option<CatCode>),
|
|
Integer(i32),
|
|
Tokens(Option<Vec<Token>>),
|
|
Hook(Option<std::sync::Arc<[Token]>>),
|
|
Job(Option<i32>),
|
|
Register(Option<RegisterValue>),
|
|
Parameter(Option<ParameterValue>),
|
|
ParagraphShape(std::sync::Arc<[super::paragraph::ParagraphShapeLine]>),
|
|
Font(FontId),
|
|
Box(Option<NativeBox>),
|
|
Mathcode(Option<super::MathCode>),
|
|
Delcode(Option<i32>),
|
|
Sfcode(Option<u16>, Option<u16>),
|
|
XeInterCharTokens(Option<std::sync::Arc<[Token]>>),
|
|
CaseCode(Option<u32>),
|
|
Mathfont(Option<FontId>),
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub(super) enum GroupKind {
|
|
Simple,
|
|
SemiSimple,
|
|
Hbox,
|
|
AdjustedHbox,
|
|
Vbox,
|
|
Vtop,
|
|
MathShift,
|
|
MathGroup,
|
|
MathChoice,
|
|
MathLeft,
|
|
Discretionary,
|
|
Insertion,
|
|
Output,
|
|
Align,
|
|
NoAlign,
|
|
Vcenter,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
struct Group {
|
|
kind: GroupKind,
|
|
#[serde(default)]
|
|
origin: Option<(usize, usize)>,
|
|
after: Vec<Token>,
|
|
#[serde(with = "ordered_map")]
|
|
saved: BTreeMap<Key, Saved>,
|
|
#[serde(default)]
|
|
save_order: Vec<Key>,
|
|
}
|
|
|
|
pub(super) struct GroupRestore {
|
|
pub entries: Vec<(Key, Option<Saved>)>,
|
|
pub after: Vec<Token>,
|
|
}
|
|
|
|
// JSON objects cannot represent enum keys. Sequence encoding preserves the
|
|
// separate active/control namespaces and deterministic order for state images.
|
|
mod ordered_map {
|
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
use std::collections::BTreeMap;
|
|
pub fn serialize<K: Serialize, V: Serialize, S: Serializer>(
|
|
map: &BTreeMap<K, V>,
|
|
serializer: S,
|
|
) -> Result<S::Ok, S::Error> {
|
|
map.iter().collect::<Vec<_>>().serialize(serializer)
|
|
}
|
|
pub fn deserialize<
|
|
'de,
|
|
K: Deserialize<'de> + Ord,
|
|
V: Deserialize<'de>,
|
|
D: Deserializer<'de>,
|
|
>(
|
|
deserializer: D,
|
|
) -> Result<BTreeMap<K, V>, D::Error> {
|
|
Ok(Vec::<(K, V)>::deserialize(deserializer)?
|
|
.into_iter()
|
|
.collect())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
enum PdftexRevision {
|
|
// A format created before revision identity was stored bootstrapped with 22.
|
|
#[default]
|
|
#[serde(rename = "22")]
|
|
R22,
|
|
#[serde(rename = "24")]
|
|
R24,
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
|
pub struct State {
|
|
#[serde(with = "ordered_map")]
|
|
commands: BTreeMap<CommandName, Meaning>,
|
|
catcodes: BTreeMap<char, CatCode>,
|
|
counts: BTreeMap<u16, i32>,
|
|
toks: BTreeMap<u16, Vec<Token>>,
|
|
#[serde(with = "ordered_map")]
|
|
pub(super) token_parameters: BTreeMap<TokenParameter, std::sync::Arc<[Token]>>,
|
|
profile: Profile,
|
|
#[serde(default)]
|
|
pdftex_revision: PdftexRevision,
|
|
initex: bool,
|
|
#[serde(default)]
|
|
input_profile: super::InputProfile,
|
|
#[serde(default)]
|
|
pub(super) xe_default_encoding: super::xe_encoding::Encoding,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) xe_line_break_locale: Option<String>,
|
|
pub endlinechar: i32,
|
|
pub newlinechar: i32,
|
|
pub escapechar: i32,
|
|
pub globaldefs: i32,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
paragraph_token: Option<CommandName>,
|
|
groups: Vec<Group>,
|
|
job_parameters: BTreeMap<JobParameter, i32>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) pdf_creation_date: Option<String>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
initial_random_seed: Option<i32>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
random: Option<Box<super::random::Random>>,
|
|
#[serde(with = "ordered_map")]
|
|
registers: BTreeMap<Register, RegisterValue>,
|
|
parameters: BTreeMap<Parameter, ParameterValue>,
|
|
paragraph_shape: std::sync::Arc<[super::paragraph::ParagraphShapeLine]>,
|
|
pub(super) text_font: FontId,
|
|
pub(super) fonts: super::FontCatalog,
|
|
boxes: BTreeMap<u16, NativeBox>,
|
|
pub(super) split_marks: BTreeMap<u16, super::SplitMarks>,
|
|
pub(super) page_marks: BTreeMap<u16, super::PageMarks>,
|
|
mathcodes: BTreeMap<u32, super::MathCode>,
|
|
delcodes: BTreeMap<u32, i32>,
|
|
#[serde(default)]
|
|
sfcodes: BTreeMap<u32, u16>,
|
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
|
xe_char_classes: BTreeMap<u32, u16>,
|
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
|
xe_inter_char_tokens: BTreeMap<u32, std::sync::Arc<[Token]>>,
|
|
#[serde(with = "ordered_map")]
|
|
case_codes: BTreeMap<(super::CaseCode, char), u32>,
|
|
#[serde(with = "ordered_map")]
|
|
mathfonts: BTreeMap<(u8, u8), FontId>,
|
|
pub(super) last_badness: i32,
|
|
#[serde(default)]
|
|
pub(super) pdf_last_position: [i32; 2],
|
|
/// TeX prepare_mag freeze, independent of ordinary grouping/assignments.
|
|
pub(super) magnification_set: Option<i32>,
|
|
pub(super) output_mode_set: Option<i32>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) pdf_header_options: Option<crate::pdf_device::PdfHeaderOptions>,
|
|
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) pdf_copy_imported_fonts: Option<bool>,
|
|
#[serde(default, skip_serializing_if = "crate::pdf_device::xdv_destination::Setup::is_default")]
|
|
pub(super) xdv_setup: crate::pdf_device::xdv_destination::Setup,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) xdv_navigation: Option<std::sync::Arc<crate::pdf_device::xdv_navigation::Navigation>>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub(super) pdf_objects: Option<Box<crate::pdf_device::page_resources::PdfObjects>>,
|
|
pub(super) pdf_info: Vec<u8>,
|
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
|
pub(super) pdf_pages_attributes: Vec<u8>,
|
|
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
|
|
pub(super) hyphenation: super::hyphenation::HyphenationData,
|
|
}
|
|
|
|
// Batch the many small token and integer writes in a state fingerprint.
|
|
// The ordered bytes still go through the native state fingerprint's hasher.
|
|
struct FingerprintHasher {
|
|
hasher: DefaultHasher,
|
|
buffer: [u8; 4096],
|
|
used: usize,
|
|
}
|
|
|
|
impl Default for FingerprintHasher {
|
|
fn default() -> Self {
|
|
Self {
|
|
hasher: DefaultHasher::new(),
|
|
buffer: [0; 4096],
|
|
used: 0,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Hasher for FingerprintHasher {
|
|
fn write(&mut self, bytes: &[u8]) {
|
|
if bytes.len() > self.buffer.len() - self.used {
|
|
self.hasher.write(&self.buffer[..self.used]);
|
|
self.used = 0;
|
|
}
|
|
if bytes.len() > self.buffer.len() {
|
|
self.hasher.write(bytes);
|
|
} else {
|
|
let end = self.used + bytes.len();
|
|
self.buffer[self.used..end].copy_from_slice(bytes);
|
|
self.used = end;
|
|
}
|
|
}
|
|
|
|
fn finish(&self) -> u64 {
|
|
let mut hasher = self.hasher.clone();
|
|
hasher.write(&self.buffer[..self.used]);
|
|
hasher.finish()
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn buffered_fingerprint_matches_the_ordered_state_hash() {
|
|
let mut state = State::initex().with_etex();
|
|
let check = |state: &State| {
|
|
let mut direct = DefaultHasher::new();
|
|
state.hash(&mut direct);
|
|
assert_eq!(state.fingerprint(), direct.finish());
|
|
};
|
|
check(&state);
|
|
state.begin_group(GroupKind::Simple, None);
|
|
state.define(
|
|
CommandName::Control("断字".repeat(1024)),
|
|
Meaning::Primitive(Primitive::Relax),
|
|
false,
|
|
);
|
|
state.define(CommandName::Control("μ".into()), Meaning::Count(123), true);
|
|
check(&state);
|
|
}
|
|
|
|
// These primitives belong to the pdfTeX command surface. Position queries,
|
|
// page dimensions and the shared margin-kern extension are installed separately.
|
|
const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = {
|
|
use Primitive::*;
|
|
&[
|
|
("knbccode", Knbccode),
|
|
("knaccode", Knaccode),
|
|
("efcode", Efcode),
|
|
("pdffontexpand", Pdffontexpand),
|
|
("letterspacefont", Letterspacefont),
|
|
("pdffilesize", Pdffilesize),
|
|
("pdffilemoddate", Pdffilemoddate),
|
|
("pdfmdfivesum", Pdfmdfivesum),
|
|
("pdfximage", Pdfximage),
|
|
("pdfrefximage", Pdfrefximage),
|
|
("pdflastximage", Pdflastximage),
|
|
("pdflastximagepages", Pdflastximagepages),
|
|
("pdflastximagecolordepth", Pdflastximagecolordepth),
|
|
("pdfcreationdate", Pdfcreationdate),
|
|
("pdfshellescape", Pdfshellescape),
|
|
("pdfstrcmp", Pdfstrcmp),
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
("pdfmatch", Pdfmatch),
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
("pdflastmatch", Pdflastmatch),
|
|
("pdfcolorstackinit", Pdfcolorstackinit),
|
|
("pdfobj", Pdfobj),
|
|
("pdfrefobj", Pdfrefobj),
|
|
("pdflastobj", Pdflastobj),
|
|
("pdflastlink", Pdflastlink),
|
|
("pdfrandomseed", Pdfrandomseed),
|
|
("pdfsetrandomseed", Pdfsetrandomseed),
|
|
("pdfuniformdeviate", Pdfuniformdeviate),
|
|
("pdfnormaldeviate", Pdfnormaldeviate),
|
|
("pdfpageref", Pdfpageref),
|
|
("pdfliteral", Pdfliteral),
|
|
("pdfcolorstack", Pdfcolorstack),
|
|
("pdfsave", Pdfsave),
|
|
("pdfstartlink", Pdfstartlink),
|
|
("pdfendlink", Pdfendlink),
|
|
("pdfrunninglinkoff", Pdfrunninglinkoff),
|
|
("pdfrunninglinkon", Pdfrunninglinkon),
|
|
("pdfinterwordspaceon", Pdfinterwordspaceon),
|
|
("pdfinterwordspaceoff", Pdfinterwordspaceoff),
|
|
("pdffakespace", Pdffakespace),
|
|
("pdfspacefont", Pdfspacefont),
|
|
("pdfdest", Pdfdest),
|
|
("pdfcatalog", Pdfcatalog),
|
|
("pdfoutline", Pdfoutline),
|
|
("pdfinfo", Pdfinfo),
|
|
("pdfsetmatrix", Pdfsetmatrix),
|
|
("pdfrestore", Pdfrestore),
|
|
("pdfglyphtounicode", Pdfglyphtounicode),
|
|
("pdfmapfile", Pdfmapfile),
|
|
("pdfmapline", Pdfmapline),
|
|
("pdffontattr", Pdffontattr),
|
|
("pdfnobuiltintounicode", Pdfnobuiltintounicode),
|
|
]
|
|
};
|
|
|
|
const XETEX_PRIMITIVE_ALIASES: &[(&str, Primitive)] = {
|
|
use Primitive::*;
|
|
&[
|
|
("creationdate", Pdfcreationdate),
|
|
("filemoddate", Pdffilemoddate),
|
|
("filesize", Pdffilesize),
|
|
("mdfivesum", Pdfmdfivesum),
|
|
("normaldeviate", Pdfnormaldeviate),
|
|
("randomseed", Pdfrandomseed),
|
|
("setrandomseed", Pdfsetrandomseed),
|
|
("shellescape", Pdfshellescape),
|
|
("strcmp", Pdfstrcmp),
|
|
("uniformdeviate", Pdfuniformdeviate),
|
|
("Udelcode", Udelcode),
|
|
("XeTeXdelcode", Udelcode),
|
|
("Udelcodenum", Udelcodenum),
|
|
("XeTeXdelcodenum", Udelcodenum),
|
|
("Udelimiter", Udelimiter),
|
|
("XeTeXdelimiter", Udelimiter),
|
|
("Uradical", Uradical),
|
|
("XeTeXradical", Uradical),
|
|
("Umathaccent", Umathaccent),
|
|
("XeTeXmathaccent", Umathaccent),
|
|
]
|
|
};
|
|
|
|
impl Default for State {
|
|
fn default() -> Self {
|
|
use Primitive::*;
|
|
let mut state = Self {
|
|
commands: BTreeMap::new(),
|
|
catcodes: BTreeMap::new(),
|
|
counts: BTreeMap::new(),
|
|
toks: BTreeMap::new(),
|
|
token_parameters: BTreeMap::new(),
|
|
profile: Profile::Bootstrap,
|
|
pdftex_revision: PdftexRevision::R24,
|
|
initex: false,
|
|
input_profile: super::InputProfile::default(),
|
|
xe_default_encoding: super::xe_encoding::Encoding::Auto,
|
|
xe_line_break_locale: None,
|
|
endlinechar: 13,
|
|
newlinechar: -1,
|
|
escapechar: 92,
|
|
globaldefs: 0,
|
|
groups: Vec::new(),
|
|
paragraph_token: None,
|
|
job_parameters: BTreeMap::new(),
|
|
pdf_creation_date: None,
|
|
registers: BTreeMap::new(),
|
|
parameters: BTreeMap::new(),
|
|
paragraph_shape: std::sync::Arc::default(),
|
|
text_font: FontId::NULL,
|
|
fonts: super::FontCatalog::default(),
|
|
boxes: BTreeMap::new(),
|
|
split_marks: BTreeMap::new(),
|
|
page_marks: BTreeMap::new(),
|
|
mathcodes: BTreeMap::new(),
|
|
delcodes: BTreeMap::new(),
|
|
sfcodes: BTreeMap::new(),
|
|
xe_char_classes: BTreeMap::new(),
|
|
xe_inter_char_tokens: BTreeMap::new(),
|
|
case_codes: BTreeMap::new(),
|
|
mathfonts: BTreeMap::new(),
|
|
last_badness: 0,
|
|
pdf_last_position: [0, 0],
|
|
magnification_set: None,
|
|
output_mode_set: None,
|
|
pdf_header_options: None,
|
|
pdf_file_options: None,
|
|
pdf_copy_imported_fonts: None,
|
|
xdv_setup: Default::default(),
|
|
xdv_navigation: None,
|
|
pdf_catalog: None,
|
|
pdf_objects: None,
|
|
initial_random_seed: None,
|
|
random: None,
|
|
pdf_info: Vec::new(),
|
|
pdf_pages_attributes: Vec::new(),
|
|
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
|
|
hyphenation: super::hyphenation::HyphenationData::default(),
|
|
};
|
|
for (name, primitive) in [
|
|
("mathcode", Mathcode),
|
|
("showbox", Showbox),
|
|
("show", Show),
|
|
("showthe", Showthe),
|
|
("showlists", Showlists),
|
|
("delcode", Delcode),
|
|
("sfcode", Sfcode),
|
|
("lccode", Lccode),
|
|
("uccode", Uccode),
|
|
("lowercase", Lowercase),
|
|
("uppercase", Uppercase),
|
|
("delimiter", Delimiter),
|
|
("radical", Radical),
|
|
("left", Left),
|
|
("right", Right),
|
|
("accent", Accent),
|
|
("mathaccent", Mathaccent),
|
|
("mathchoice", Mathchoice),
|
|
("overline", Overline),
|
|
("underline", Underline),
|
|
("eqno", Eqno),
|
|
("leqno", Leqno),
|
|
("hyphenchar", Hyphenchar),
|
|
("lpcode", Lpcode),
|
|
("rpcode", Rpcode),
|
|
("fontname", Fontname),
|
|
("fontdimen", Fontdimen),
|
|
("skewchar", Skewchar),
|
|
("mathchar", Mathchar),
|
|
("char", Char),
|
|
("noboundary", Noboundary),
|
|
("textfont", Textfont),
|
|
("scriptfont", Scriptfont),
|
|
("scriptscriptfont", Scriptscriptfont),
|
|
("mathord", Mathord),
|
|
("mathop", Mathop),
|
|
("mathbin", Mathbin),
|
|
("mathrel", Mathrel),
|
|
("mathopen", Mathopen),
|
|
("mathclose", Mathclose),
|
|
("mathpunct", Mathpunct),
|
|
("mathinner", Mathinner),
|
|
("limits", Limits),
|
|
("nolimits", Nolimits),
|
|
("displaylimits", Displaylimits),
|
|
("displaystyle", Displaystyle),
|
|
("textstyle", Textstyle),
|
|
("scriptstyle", Scriptstyle),
|
|
("scriptscriptstyle", Scriptscriptstyle),
|
|
("mskip", Mskip),
|
|
("mkern", Mkern),
|
|
("over", Over),
|
|
("atop", Atop),
|
|
("above", Above),
|
|
("overwithdelims", Overwithdelims),
|
|
("atopwithdelims", Atopwithdelims),
|
|
("abovewithdelims", Abovewithdelims),
|
|
("setbox", Setbox),
|
|
("box", Box),
|
|
("copy", Copy),
|
|
("hbox", Hbox),
|
|
("halign", Halign),
|
|
("valign", Valign),
|
|
("cr", Cr),
|
|
("crcr", Crcr),
|
|
("span", Span),
|
|
("omit", Omit),
|
|
("noalign", Noalign),
|
|
("vbox", Vbox),
|
|
("vtop", Vtop),
|
|
("vcenter", Vcenter),
|
|
("vskip", Vskip),
|
|
("vfil", Vfil),
|
|
("vfill", Vfill),
|
|
("vss", Vss),
|
|
("vfilneg", Vfilneg),
|
|
("hrule", Hrule),
|
|
("vrule", Vrule),
|
|
("raise", Raise),
|
|
("lower", Lower),
|
|
("moveleft", Moveleft),
|
|
("moveright", Moveright),
|
|
("unhbox", Unhbox),
|
|
("unhcopy", Unhcopy),
|
|
("unvbox", Unvbox),
|
|
("unvcopy", Unvcopy),
|
|
("lastbox", Lastbox),
|
|
("vsplit", Vsplit),
|
|
("mark", Mark),
|
|
("vadjust", Vadjust),
|
|
("insert", Insert),
|
|
("insertpenalties", Insertpenalties),
|
|
("splitfirstmark", Splitfirstmark),
|
|
("splitbotmark", Splitbotmark),
|
|
("topmark", Topmark),
|
|
("firstmark", Firstmark),
|
|
("botmark", Botmark),
|
|
("shipout", Shipout),
|
|
("deadcycles", Deadcycles),
|
|
("pagegoal", Pagegoal),
|
|
("pagetotal", Pagetotal),
|
|
("pagestretch", Pagestretch),
|
|
("pagefilstretch", Pagefilstretch),
|
|
("pagefillstretch", Pagefillstretch),
|
|
("pagefilllstretch", Pagefilllstretch),
|
|
("pageshrink", Pageshrink),
|
|
("pagedepth", Pagedepth),
|
|
("prevdepth", Prevdepth),
|
|
("prevgraf", Prevgraf),
|
|
("wd", Wd),
|
|
("ht", Ht),
|
|
("dp", Dp),
|
|
("badness", Badness),
|
|
("relax", Relax),
|
|
("ignorespaces", Ignorespaces),
|
|
("par", Par),
|
|
("parshape", Parshape),
|
|
("begingroup", BeginGroup),
|
|
("endgroup", EndGroup),
|
|
("global", Global),
|
|
("long", Long),
|
|
("outer", Outer),
|
|
("def", Def),
|
|
("gdef", Gdef),
|
|
("edef", Edef),
|
|
("xdef", Xdef),
|
|
("let", Let),
|
|
("futurelet", Futurelet),
|
|
("afterassignment", Afterassignment),
|
|
("aftergroup", Aftergroup),
|
|
("chardef", Chardef),
|
|
("mathchardef", Mathchardef),
|
|
("inputlineno", Inputlineno),
|
|
("catcode", Catcode),
|
|
("endlinechar", Endlinechar),
|
|
("newlinechar", Newlinechar),
|
|
("escapechar", Escapechar),
|
|
("batchmode", Batchmode),
|
|
("nonstopmode", Nonstopmode),
|
|
("scrollmode", Scrollmode),
|
|
("errorstopmode", Errorstopmode),
|
|
("time", Time),
|
|
("day", Day),
|
|
("month", Month),
|
|
("year", Year),
|
|
("globaldefs", Globaldefs),
|
|
("count", Count),
|
|
("countdef", Countdef),
|
|
("dimen", Dimen),
|
|
("dimendef", Dimendef),
|
|
("skip", Skip),
|
|
("skipdef", Skipdef),
|
|
("muskip", Muskip),
|
|
("muskipdef", Muskipdef),
|
|
("toks", Toks),
|
|
("toksdef", Toksdef),
|
|
("advance", Advance),
|
|
("multiply", Multiply),
|
|
("divide", Divide),
|
|
("the", The),
|
|
("number", Number),
|
|
("romannumeral", Romannumeral),
|
|
("string", String),
|
|
("meaning", MeaningOf),
|
|
("noexpand", Noexpand),
|
|
("expandafter", Expandafter),
|
|
("csname", Csname),
|
|
("endcsname", Endcsname),
|
|
("iftrue", Iftrue),
|
|
("iffalse", Iffalse),
|
|
("ifx", Ifx),
|
|
("ifnum", Ifnum),
|
|
("ifdefined", Ifdefined),
|
|
("if", If),
|
|
("ifcat", Ifcat),
|
|
("ifdim", Ifdim),
|
|
("ifodd", Ifodd),
|
|
("ifvmode", Ifvmode),
|
|
("ifhmode", Ifhmode),
|
|
("ifmmode", Ifmmode),
|
|
("ifinner", Ifinner),
|
|
("ifvoid", Ifvoid),
|
|
("ifhbox", Ifhbox),
|
|
("ifvbox", Ifvbox),
|
|
("ifcase", Ifcase),
|
|
("ifeof", Ifeof),
|
|
("ifcsname", Ifcsname),
|
|
("iffontchar", Iffontchar),
|
|
("else", Else),
|
|
("or", Or),
|
|
("fi", Fi),
|
|
("input", Input),
|
|
("endinput", Endinput),
|
|
("openin", Openin),
|
|
("closein", Closein),
|
|
("read", Read),
|
|
("openout", Openout),
|
|
("closeout", Closeout),
|
|
("write", Write),
|
|
("special", Special),
|
|
("immediate", Immediate),
|
|
("message", Message),
|
|
("errmessage", Errmessage),
|
|
("end", End),
|
|
("jobname", Jobname),
|
|
("partokenname", Partokenname),
|
|
("leftmarginkern", Leftmarginkern),
|
|
("rightmarginkern", Rightmarginkern),
|
|
("pdfsavepos", Pdfsavepos),
|
|
("pdflastxpos", Pdflastxpos),
|
|
("pdflastypos", Pdflastypos),
|
|
("dump", Dump),
|
|
("indent", Indent),
|
|
("noindent", Noindent),
|
|
("hskip", Hskip),
|
|
("leaders", Leaders),
|
|
("cleaders", Cleaders),
|
|
("xleaders", Xleaders),
|
|
("hfil", Hfil),
|
|
("hfill", Hfill),
|
|
("hss", Hss),
|
|
("hfilneg", Hfilneg),
|
|
("kern", Kern),
|
|
("penalty", Penalty),
|
|
("unskip", Unskip),
|
|
("unkern", Unkern),
|
|
("unpenalty", Unpenalty),
|
|
("lastskip", Lastskip),
|
|
("lastkern", Lastkern),
|
|
("lastpenalty", Lastpenalty),
|
|
("/", ItalicCorrection),
|
|
("-", DiscretionaryHyphen),
|
|
("discretionary", Discretionary),
|
|
("hyphenation", Hyphenation),
|
|
("patterns", Patterns),
|
|
("setlanguage", Setlanguage),
|
|
("font", Font),
|
|
("spacefactor", Spacefactor),
|
|
] {
|
|
state.commands.insert(
|
|
CommandName::Control(name.into()),
|
|
Meaning::Primitive(primitive),
|
|
);
|
|
}
|
|
state.commands.insert(
|
|
CommandName::Control(" ".into()),
|
|
Meaning::Primitive(Explicitspace),
|
|
);
|
|
for p in TokenParameter::ALL {
|
|
if *p == TokenParameter::Everyeof {
|
|
continue;
|
|
}
|
|
state
|
|
.commands
|
|
.insert(CommandName::Control(p.name()), Meaning::TokenParameter(*p));
|
|
}
|
|
for p in Parameter::ALL {
|
|
if matches!(
|
|
p,
|
|
Parameter::Tracinggroups
|
|
| Parameter::Tracingifs
|
|
| Parameter::Tracingscantokens
|
|
| Parameter::Tracingnesting
|
|
| Parameter::Tracingassigns
|
|
| Parameter::Savingvdiscards
|
|
| Parameter::TeXXeTstate
|
|
) || Parameter::XETEX.contains(p) {
|
|
continue;
|
|
}
|
|
state
|
|
.commands
|
|
.insert(CommandName::Control(p.name()), Meaning::Parameter(*p));
|
|
}
|
|
state.commands.insert(
|
|
CommandName::Control("nullfont".into()),
|
|
Meaning::Font(FontId::NULL),
|
|
);
|
|
// Explicit text-bootstrap environment, not INITEX defaults or a format.
|
|
for (p, v) in [
|
|
(Parameter::Hsize, ParameterValue::dimension(468 * 65536)),
|
|
(Parameter::Baselineskip, ParameterValue::skip(12 * 65536)),
|
|
(Parameter::Parfillskip, ParameterValue::fill()),
|
|
] {
|
|
state.parameters.insert(p, v);
|
|
}
|
|
state.install_pdftex_primitives();
|
|
state.install_unicode_commands();
|
|
state
|
|
}
|
|
}
|
|
|
|
impl State {
|
|
pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) {
|
|
use super::statistics::Ownership::Active;
|
|
c.usage.state.command_entries = self.commands.len();
|
|
c.usage.state.control_name_bytes = self
|
|
.commands
|
|
.keys()
|
|
.map(|n| match n {
|
|
CommandName::Control(n) => n.len(),
|
|
_ => 0,
|
|
})
|
|
.sum();
|
|
c.usage.state.macro_bindings = self
|
|
.commands
|
|
.values()
|
|
.filter(|m| matches!(m, Meaning::Macro(_)))
|
|
.count();
|
|
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
|
|
c.usage.state.parameter_entries =
|
|
self.parameters.len() + self.token_parameters.len() + self.job_parameters.len();
|
|
c.usage.state.register_entries =
|
|
self.counts.len() + self.registers.len() + self.boxes.len();
|
|
c.usage.state.code_entries = self.catcodes.len()
|
|
+ self.mathcodes.len()
|
|
+ self.delcodes.len()
|
|
+ self.sfcodes.len()
|
|
+ self.xe_char_classes.len()
|
|
+ self.case_codes.len()
|
|
+ self.mathfonts.len();
|
|
c.usage.state.save_entries = self.groups.iter().map(|g| g.saved.len()).sum();
|
|
c.usage.state.font_instances = self.fonts.fonts().len() - 1;
|
|
c.usage.state.font_parameter_cells = self.fonts.parameter_words();
|
|
c.usage.state.tfm_resources = self.fonts.resources().len();
|
|
c.usage.state.tfm_resource_bytes =
|
|
self.fonts.resources().iter().map(|r| r.version.bytes).sum();
|
|
c.usage.state.hyphenation_exceptions =
|
|
self.hyphenation.exceptions.values().map(|v| v.len()).sum();
|
|
let (nodes, edges, weights) = self.hyphenation.resource_counts();
|
|
c.usage.state.hyphenation_trie_nodes = nodes;
|
|
c.usage.state.hyphenation_edges = edges;
|
|
c.usage.state.pattern_weight_cells = weights;
|
|
for m in self.commands.values() {
|
|
if let Meaning::Macro(m) = m {
|
|
c.macro_body(m);
|
|
}
|
|
}
|
|
for v in self.toks.values() {
|
|
c.usage.token_list_cells += v.len();
|
|
}
|
|
for v in self.token_parameters.values().chain(self.xe_inter_char_tokens.values()) {
|
|
c.shared_tokens(v);
|
|
}
|
|
for b in self.boxes.values() {
|
|
c.native_box(b, Active);
|
|
}
|
|
for m in self.split_marks.values() {
|
|
c.shared_tokens(&m.first);
|
|
c.shared_tokens(&m.bottom);
|
|
}
|
|
for m in self.page_marks.values() {
|
|
for v in [&m.top, &m.first, &m.bottom].into_iter().flatten() {
|
|
c.shared_tokens(v);
|
|
}
|
|
}
|
|
for g in &self.groups {
|
|
c.usage.token_list_cells += g.after.len();
|
|
for v in g.saved.values() {
|
|
match v {
|
|
Saved::Command(Some(Meaning::Macro(m))) => c.macro_body(m),
|
|
Saved::Tokens(Some(v)) => c.usage.token_list_cells += v.len(),
|
|
Saved::Hook(Some(v)) | Saved::XeInterCharTokens(Some(v)) => c.shared_tokens(v),
|
|
Saved::Box(Some(b)) => c.native_box(b, Active),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
pub(super) fn initialize_pdf_pk_resolution(&mut self, value: i32) {
|
|
self.parameters
|
|
.insert(Parameter::Pdfpkresolution, ParameterValue::Integer(value));
|
|
}
|
|
pub(super) fn migrate_pdf_parameter(&mut self, old: Parameter, new: Parameter, value: i32) {
|
|
// pdfTeX updates the two eqtb values in place, keeping their save levels.
|
|
self.parameters.insert(new, ParameterValue::Integer(value));
|
|
self.parameters.remove(&old);
|
|
}
|
|
|
|
/// Explicit host selection of the PDF driver (INITEX itself defaults to
|
|
/// pdfoutput=0). The source can still assign the real parameter.
|
|
pub fn with_pdf_output(mut self) -> Self {
|
|
self.assign_parameter(Parameter::Pdfoutput, ParameterValue::Integer(1), true);
|
|
self
|
|
}
|
|
pub fn parameter(&self, parameter: Parameter) -> ParameterValue {
|
|
self.parameters
|
|
.get(¶meter)
|
|
.copied()
|
|
.unwrap_or_else(|| parameter.initial())
|
|
}
|
|
pub(super) fn assign_parameter(&mut self, p: Parameter, value: ParameterValue, global: bool) {
|
|
let value = match value {
|
|
ParameterValue::Quantity(RegisterValue::Glue(g)) => {
|
|
ParameterValue::Quantity(RegisterValue::Glue(g.trapped()))
|
|
}
|
|
value => value,
|
|
};
|
|
// e-TeX eq_word_define returns before saving an unchanged fullword.
|
|
// Glue parameters use reference-counted eq_define instead.
|
|
if !global
|
|
&& self.profile == Profile::EtexBootstrap
|
|
&& matches!(
|
|
value,
|
|
ParameterValue::Integer(_) | ParameterValue::Quantity(RegisterValue::Dimension(_))
|
|
)
|
|
&& self.parameter(p) == value
|
|
{
|
|
return;
|
|
}
|
|
self.save(Key::Parameter(p), global);
|
|
if value == p.initial() {
|
|
self.parameters.remove(&p);
|
|
} else {
|
|
self.parameters.insert(p, value);
|
|
}
|
|
}
|
|
pub(super) fn paragraph_shape(&self) -> &[super::paragraph::ParagraphShapeLine] {
|
|
&self.paragraph_shape
|
|
}
|
|
pub(super) fn assign_paragraph_shape(
|
|
&mut self,
|
|
shape: Vec<super::paragraph::ParagraphShapeLine>,
|
|
global: bool,
|
|
) {
|
|
self.save(Key::ParagraphShape, global);
|
|
self.paragraph_shape = shape.into();
|
|
}
|
|
pub fn text_font(&self) -> FontId {
|
|
self.text_font
|
|
}
|
|
pub(super) fn assign_font(&mut self, font: FontId, global: bool) {
|
|
self.save(Key::Font, global);
|
|
self.text_font = font;
|
|
}
|
|
pub fn register(&self, register: Register) -> RegisterValue {
|
|
self.registers.get(®ister).copied().unwrap_or_else(|| {
|
|
if register.kind == RegisterKind::Dimen {
|
|
RegisterValue::Dimension(0)
|
|
} else {
|
|
RegisterValue::Glue(Glue::default())
|
|
}
|
|
})
|
|
}
|
|
pub(super) fn assign_register(
|
|
&mut self,
|
|
register: Register,
|
|
value: RegisterValue,
|
|
global: bool,
|
|
) {
|
|
self.save(Key::Register(register), global);
|
|
self.set_register(register, value);
|
|
}
|
|
fn set_register(&mut self, register: Register, value: RegisterValue) {
|
|
let value = match value {
|
|
RegisterValue::Glue(g) => RegisterValue::Glue(g.trapped()),
|
|
value => value,
|
|
};
|
|
let zero = if register.kind == RegisterKind::Dimen {
|
|
RegisterValue::Dimension(0)
|
|
} else {
|
|
RegisterValue::Glue(Glue::default())
|
|
};
|
|
if value == zero {
|
|
self.registers.remove(®ister);
|
|
} else {
|
|
self.registers.insert(register, value);
|
|
}
|
|
}
|
|
pub fn with_job_time(mut self, time: JobTime) -> Self {
|
|
self.job_parameters.extend(time.parameters());
|
|
self.pdf_creation_date = time.pdf_creation_date();
|
|
self.initial_random_seed = time.random_seed;
|
|
self.random = None;
|
|
self
|
|
}
|
|
pub(super) fn random_seed(&self) -> i32 {
|
|
self.random.as_deref().map_or_else(
|
|
|| self.initial_random_seed.unwrap_or_default(),
|
|
super::random::Random::seed,
|
|
)
|
|
}
|
|
pub(super) fn reseed_random(&mut self, seed: i32) {
|
|
self.random = Some(Box::new(super::random::Random::new(seed)));
|
|
}
|
|
pub(super) fn random(&mut self) -> &mut super::random::Random {
|
|
self.random.get_or_insert_with(|| {
|
|
Box::new(super::random::Random::new(self.initial_random_seed.unwrap_or_default()))
|
|
})
|
|
}
|
|
pub fn job_parameter(&self, parameter: JobParameter) -> Option<i32> {
|
|
self.job_parameters.get(¶meter).copied()
|
|
}
|
|
/// Install actual extended-language implementations, not LaTeX macros or
|
|
/// guard rewrites. Version/revision are read-only internal quantities.
|
|
pub fn with_etex(mut self) -> Self {
|
|
use Primitive::*;
|
|
self.profile = Profile::EtexBootstrap;
|
|
let hook = TokenParameter::Everyeof;
|
|
self.commands.insert(
|
|
CommandName::Control(hook.name()),
|
|
Meaning::TokenParameter(hook),
|
|
);
|
|
for parameter in [
|
|
Parameter::Tracinggroups,
|
|
Parameter::Tracingifs,
|
|
Parameter::Tracingscantokens,
|
|
Parameter::Tracingnesting,
|
|
Parameter::Tracingassigns,
|
|
Parameter::Savingvdiscards,
|
|
] {
|
|
self.commands.insert(
|
|
CommandName::Control(parameter.name()),
|
|
Meaning::Parameter(parameter),
|
|
);
|
|
}
|
|
for (name, primitive) in [
|
|
("interactionmode", Interactionmode),
|
|
("protected", Protected),
|
|
("scantokens", Scantokens),
|
|
("marks", Marks),
|
|
("splitfirstmarks", Splitfirstmarks),
|
|
("splitbotmarks", Splitbotmarks),
|
|
("topmarks", Topmarks),
|
|
("firstmarks", Firstmarks),
|
|
("botmarks", Botmarks),
|
|
("unexpanded", Unexpanded),
|
|
("expanded", Expanded),
|
|
("detokenize", Detokenize),
|
|
("numexpr", Numexpr),
|
|
("dimexpr", Dimexpr),
|
|
("glueexpr", Glueexpr),
|
|
("muexpr", Muexpr),
|
|
("unless", Unless),
|
|
("ifincsname", Ifincsname),
|
|
("eTeXversion", Etexversion),
|
|
("eTeXrevision", Etexrevision),
|
|
("currentgrouplevel", Currentgrouplevel),
|
|
("showgroups", Showgroups),
|
|
("showifs", Showifs),
|
|
("currentgrouptype", Currentgrouptype),
|
|
("lastnodetype", Lastnodetype),
|
|
("pagediscards", Pagediscards),
|
|
("splitdiscards", Splitdiscards),
|
|
("parshapelength", Parshapelength),
|
|
("parshapeindent", Parshapeindent),
|
|
("parshapedimen", Parshapedimen),
|
|
("gluestretch", Gluestretch),
|
|
("glueshrink", Glueshrink),
|
|
("gluestretchorder", Gluestretchorder),
|
|
("glueshrinkorder", Glueshrinkorder),
|
|
("readline", Readline),
|
|
("fontcharwd", Fontcharwd),
|
|
("fontcharht", Fontcharht),
|
|
("fontchardp", Fontchardp),
|
|
("fontcharic", Fontcharic),
|
|
] {
|
|
self.commands.insert(
|
|
CommandName::Control(name.into()),
|
|
Meaning::Primitive(primitive),
|
|
);
|
|
}
|
|
self.install_xetex_etex_commands();
|
|
self.install_direction_commands();
|
|
self
|
|
}
|
|
pub fn register_limit(&self) -> u16 {
|
|
if self.profile == Profile::EtexBootstrap {
|
|
32767
|
|
} else {
|
|
255
|
|
}
|
|
}
|
|
pub fn profile(&self) -> Profile {
|
|
self.profile
|
|
}
|
|
pub(super) fn pdftex_revision(&self) -> &'static str {
|
|
match self.pdftex_revision {
|
|
PdftexRevision::R22 => "22",
|
|
PdftexRevision::R24 => "24",
|
|
}
|
|
}
|
|
pub fn tokens(&self, index: u16) -> Vec<Token> {
|
|
self.toks.get(&index).cloned().unwrap_or_default()
|
|
}
|
|
pub(super) fn group_kind(&self) -> Option<GroupKind> {
|
|
self.groups.last().map(|group| group.kind)
|
|
}
|
|
pub(super) fn group_type(&self) -> i32 {
|
|
match self.group_kind() {
|
|
None => 0,
|
|
Some(GroupKind::Simple) => 1,
|
|
Some(GroupKind::SemiSimple) => 14,
|
|
Some(GroupKind::Hbox) => 3,
|
|
Some(GroupKind::AdjustedHbox) => 2,
|
|
Some(GroupKind::Vbox) => 4,
|
|
Some(GroupKind::Vtop) => 5,
|
|
Some(GroupKind::MathShift) => 15,
|
|
Some(GroupKind::MathGroup) => 9,
|
|
Some(GroupKind::MathChoice) => 13,
|
|
Some(GroupKind::MathLeft) => 16,
|
|
Some(GroupKind::Discretionary) => 10,
|
|
Some(GroupKind::Insertion) => 11,
|
|
Some(GroupKind::Output) => 8,
|
|
Some(GroupKind::Align) => 6,
|
|
Some(GroupKind::NoAlign) => 7,
|
|
Some(GroupKind::Vcenter) => 12,
|
|
}
|
|
}
|
|
/// INITEX categories before a format establishes normal TeX syntax.
|
|
pub fn initex() -> Self {
|
|
let mut state = Self::default();
|
|
state.initex = true;
|
|
state.parameters.clear();
|
|
state.text_font = FontId::NULL;
|
|
state.newlinechar = 0;
|
|
for c in ['{', '}', '$', '&', '#', '^', '_', '~', '\t'] {
|
|
state.catcodes.insert(c, CatCode::Other);
|
|
}
|
|
state
|
|
}
|
|
pub(super) fn into_format_state(mut self) -> Self {
|
|
self.initex = false;
|
|
self.job_parameters.clear();
|
|
self.pdf_creation_date = None;
|
|
self.initial_random_seed = None;
|
|
self.random = None;
|
|
self.split_marks.clear();
|
|
self.page_marks.clear();
|
|
self.last_badness = 0;
|
|
self.pdf_last_position = [0, 0];
|
|
self.magnification_set = None;
|
|
self.output_mode_set = None;
|
|
self.pdf_header_options = None;
|
|
self.pdf_file_options = None;
|
|
self.pdf_copy_imported_fonts = None;
|
|
self.xdv_setup = Default::default();
|
|
self.xdv_navigation = None;
|
|
self.pdf_catalog = None;
|
|
if !self
|
|
.pdf_objects
|
|
.as_deref_mut()
|
|
.is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_links)
|
|
{
|
|
self.pdf_objects = None;
|
|
}
|
|
self.pdf_info.clear();
|
|
self.pdf_pages_attributes.clear();
|
|
self.fonts.reset_format_font_state();
|
|
self
|
|
}
|
|
pub(super) fn restore_legacy_format_fonts(&mut self) -> Result<(), String> {
|
|
let replacements = self.fonts.restore_legacy_synthesized_fonts()?;
|
|
if !replacements.is_empty() {
|
|
for b in self.boxes.values_mut() {
|
|
b.rebind_legacy_expansion_fonts(&replacements);
|
|
}
|
|
}
|
|
self.fonts.reset_format_font_state();
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn restore_legacy_font_map_commands(&mut self) {
|
|
for (name, meaning) in [
|
|
("pdfmapfile", Meaning::Primitive(Primitive::Pdfmapfile)),
|
|
("pdfmapline", Meaning::Primitive(Primitive::Pdfmapline)),
|
|
(
|
|
"pdfsuppresswarningdupmap",
|
|
Meaning::Parameter(Parameter::Pdfsuppresswarningdupmap),
|
|
),
|
|
] {
|
|
self.commands
|
|
.entry(CommandName::Control(name.into()))
|
|
.or_insert(meaning);
|
|
}
|
|
}
|
|
|
|
pub(super) fn restore_legacy_pdf_parameters(&mut self, parameters: &[Parameter]) {
|
|
if self.input_profile != super::InputProfile::XeTeX {
|
|
for ¶meter in parameters {
|
|
self.update_profile_command(¶meter.name(), Meaning::Parameter(parameter), true);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn is_initex(&self) -> bool {
|
|
self.initex
|
|
}
|
|
/// Final PDF output uses the live state after the last page ships out.
|
|
pub fn pdf_final_options(&self) -> crate::pdf_unicode::PdfFinalOptions<'_> {
|
|
crate::pdf_unicode::PdfFinalOptions {
|
|
compression: self.parameter(Parameter::Pdfcompresslevel).width(),
|
|
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
|
|
omit_charset: self.parameter(Parameter::Pdfomitcharset).width() != 0,
|
|
omit_info: self.parameter(Parameter::Pdfomitinfodict).width() != 0,
|
|
glyph_unicode: &self.glyph_unicode,
|
|
fonts: &self.fonts,
|
|
page_tree_attributes: &self.pdf_pages_attributes,
|
|
xdv_glyph_names: None,
|
|
xdv_font_unicode: self.input_profile == super::InputProfile::XeTeX,
|
|
xdv_keep_destinations: self.xdv_setup.keep_destinations,
|
|
xdv_outline_open_depth: self.xdv_setup.outline_open_depth.unwrap_or_default(),
|
|
xdv_navigation: self.xdv_navigation.as_deref(),
|
|
catalog: self.pdf_catalog.as_deref(),
|
|
objects: self.pdf_objects.as_deref(),
|
|
info: crate::pdf_device::PdfInfo {
|
|
entries: &self.pdf_info,
|
|
date: (self.parameter(Parameter::Pdfinfoomitdate).width() == 0)
|
|
.then_some(self.pdf_creation_date.as_deref())
|
|
.flatten(),
|
|
},
|
|
}
|
|
}
|
|
/// Job-wide decoding choice; it is not a scoped TeX assignment.
|
|
pub fn with_input_profile(mut self, profile: super::InputProfile) -> Self {
|
|
self.input_profile = profile;
|
|
for (name, primitive) in [
|
|
("pdftexversion", Primitive::Pdftexversion),
|
|
("pdftexrevision", Primitive::Pdftexrevision),
|
|
("ifpdfabsnum", Primitive::Ifpdfabsnum),
|
|
("ifpdfabsdim", Primitive::Ifpdfabsdim),
|
|
] {
|
|
self.update_profile_command(
|
|
name,
|
|
Meaning::Primitive(primitive),
|
|
profile == super::InputProfile::TeX8Bit,
|
|
);
|
|
}
|
|
self.install_pdftex_primitives();
|
|
for &(name, primitive) in XETEX_PRIMITIVE_ALIASES {
|
|
self.update_profile_command(
|
|
name,
|
|
Meaning::Primitive(primitive),
|
|
profile == super::InputProfile::XeTeX,
|
|
);
|
|
}
|
|
self.install_unicode_commands();
|
|
self.install_xetex_etex_commands();
|
|
self.install_direction_commands();
|
|
self
|
|
}
|
|
|
|
fn update_profile_command(&mut self, name: &str, meaning: Meaning, enabled: bool) {
|
|
let name = CommandName::Control(name.into());
|
|
if enabled {
|
|
self.commands.entry(name).or_insert(meaning);
|
|
} else if self.commands.get(&name) == Some(&meaning) {
|
|
self.commands.remove(&name);
|
|
}
|
|
}
|
|
|
|
fn install_pdftex_primitives(&mut self) {
|
|
let enabled = self.input_profile != super::InputProfile::XeTeX;
|
|
for &(name, primitive) in PDFTEX_ONLY_PRIMITIVES {
|
|
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
|
|
}
|
|
for parameter in [
|
|
TokenParameter::Pdfpageresources,
|
|
TokenParameter::Pdfpageattr,
|
|
TokenParameter::Pdfpagesattr,
|
|
] {
|
|
self.update_profile_command(
|
|
¶meter.name(),
|
|
Meaning::TokenParameter(parameter),
|
|
enabled,
|
|
);
|
|
}
|
|
for ¶meter in Parameter::ALL {
|
|
if parameter.pdftex_only() {
|
|
self.update_profile_command(
|
|
¶meter.name(),
|
|
Meaning::Parameter(parameter),
|
|
enabled,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn install_xetex_etex_commands(&mut self) {
|
|
let enabled = self.input_profile == super::InputProfile::XeTeX
|
|
&& self.profile == Profile::EtexBootstrap;
|
|
for (name, primitive) in [
|
|
("XeTeXversion", Primitive::XeTeXversion),
|
|
("XeTeXrevision", Primitive::XeTeXrevision),
|
|
("XeTeXpdffile", Primitive::XeTeXpdffile),
|
|
("XeTeXpicfile", Primitive::XeTeXpicfile),
|
|
("XeTeXglyph", Primitive::XeTeXglyph),
|
|
("XeTeXglyphbounds", Primitive::XeTeXglyphbounds),
|
|
("XeTeXglyphname", Primitive::XeTeXglyphname),
|
|
("XeTeXfeaturename", Primitive::XeTeXfeaturename),
|
|
("XeTeXselectorname", Primitive::XeTeXselectorname),
|
|
("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount),
|
|
("XeTeXinputencoding", Primitive::XeTeXinputencoding),
|
|
("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding),
|
|
("XeTeXlinebreaklocale", Primitive::XeTeXlinebreaklocale),
|
|
("XeTeXcharclass", Primitive::XeTeXcharclass),
|
|
("XeTeXinterchartoks", Primitive::XeTeXinterchartoks),
|
|
] {
|
|
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
|
|
}
|
|
for primitive in Primitive::XETEX_FONT_QUERIES {
|
|
self.update_profile_command(
|
|
primitive.xetex_font_query_name().unwrap(),
|
|
Meaning::Primitive(primitive),
|
|
enabled,
|
|
);
|
|
}
|
|
for parameter in Parameter::XETEX {
|
|
self.update_profile_command(
|
|
¶meter.name(),
|
|
Meaning::Parameter(parameter),
|
|
enabled,
|
|
);
|
|
}
|
|
}
|
|
|
|
fn install_direction_commands(&mut self) {
|
|
let enabled = self.profile == Profile::EtexBootstrap
|
|
&& matches!(self.input_profile, super::InputProfile::TeX8Bit | super::InputProfile::XeTeX);
|
|
for (name, primitive) in [
|
|
("beginL", Primitive::BeginL),
|
|
("endL", Primitive::EndL),
|
|
("beginR", Primitive::BeginR),
|
|
("endR", Primitive::EndR),
|
|
] {
|
|
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
|
|
}
|
|
self.update_profile_command(
|
|
&Parameter::TeXXeTstate.name(),
|
|
Meaning::Parameter(Parameter::TeXXeTstate),
|
|
enabled,
|
|
);
|
|
}
|
|
|
|
pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> {
|
|
if self.input_profile == super::InputProfile::XeTeX {
|
|
return XETEX_PRIMITIVE_ALIASES
|
|
.iter()
|
|
.find_map(|&(name, meaning)| (meaning == primitive).then_some(name));
|
|
}
|
|
None
|
|
}
|
|
|
|
fn install_unicode_commands(&mut self) {
|
|
use Primitive::*;
|
|
for (name, primitive) in [
|
|
("Uchar", Uchar),
|
|
("Ucharcat", Ucharcat),
|
|
("Umathcode", Umathcode),
|
|
("XeTeXmathcode", Umathcode),
|
|
("Umathcodenum", Umathcodenum),
|
|
("XeTeXmathcodenum", Umathcodenum),
|
|
("Umathchar", Umathchar),
|
|
("XeTeXmathchar", Umathchar),
|
|
("Umathcharnum", Umathcharnum),
|
|
("XeTeXmathcharnum", Umathcharnum),
|
|
("Umathchardef", Umathchardef),
|
|
("XeTeXmathchardef", Umathchardef),
|
|
("Umathcharnumdef", Umathcharnumdef),
|
|
("XeTeXmathcharnumdef", Umathcharnumdef),
|
|
] {
|
|
let name = CommandName::Control(name.into());
|
|
let meaning = Meaning::Primitive(primitive);
|
|
if self.input_profile != super::InputProfile::TeX8Bit {
|
|
self.commands.insert(name, meaning);
|
|
} else if self.commands.get(&name) == Some(&meaning) {
|
|
self.commands.remove(&name);
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn input_profile(&self) -> super::InputProfile {
|
|
self.input_profile
|
|
}
|
|
pub fn catcode(&self, character: char) -> CatCode {
|
|
self.catcodes
|
|
.get(&character)
|
|
.copied()
|
|
.unwrap_or_else(|| match character {
|
|
'\\' => CatCode::Escape,
|
|
'{' => CatCode::BeginGroup,
|
|
'}' => CatCode::EndGroup,
|
|
'$' => CatCode::MathShift,
|
|
'&' => CatCode::Alignment,
|
|
'\r' => CatCode::EndLine,
|
|
'#' => CatCode::Parameter,
|
|
'^' => CatCode::Superscript,
|
|
'_' => CatCode::Subscript,
|
|
'\0' => CatCode::Ignored,
|
|
' ' | '\t' => CatCode::Space,
|
|
'~' => CatCode::Active,
|
|
'%' => CatCode::Comment,
|
|
'\u{7f}' => CatCode::Invalid,
|
|
c if c.is_ascii_alphabetic() => CatCode::Letter,
|
|
_ => CatCode::Other,
|
|
})
|
|
}
|
|
pub fn meaning(&self, name: &CommandName) -> Meaning {
|
|
if *name == CommandName::FrozenRelax {
|
|
return Meaning::Primitive(Primitive::Relax);
|
|
}
|
|
if let CommandName::Font(font) = name {
|
|
return Meaning::Font(*font);
|
|
}
|
|
self.commands
|
|
.get(name)
|
|
.cloned()
|
|
.unwrap_or(Meaning::Undefined)
|
|
}
|
|
/// Classic projection for byte-table consumers. A code outside the
|
|
/// representable classic range has TeX's recovery value of zero.
|
|
pub fn mathcode(&self, character: u8) -> u16 {
|
|
self.math_code(u32::from(character)).legacy().unwrap_or(0)
|
|
}
|
|
|
|
pub fn math_code(&self, character: u32) -> super::MathCode {
|
|
self.mathcodes
|
|
.get(&character)
|
|
.copied()
|
|
.unwrap_or_else(|| super::MathCode::default_for(character))
|
|
}
|
|
|
|
pub(super) fn restore_legacy_mathcodes(&mut self) -> Result<(), String> {
|
|
for value in self.mathcodes.values_mut() {
|
|
let legacy = u16::try_from(value.word())
|
|
.ok()
|
|
.filter(|&code| code <= 0x8000)
|
|
.ok_or("invalid legacy mathcode in native format")?;
|
|
*value = super::MathCode::from_legacy(legacy);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn math_family_count(&self) -> i32 {
|
|
match self.input_profile {
|
|
super::InputProfile::TeX8Bit => 16,
|
|
super::InputProfile::UnicodeScalar | super::InputProfile::XeTeX => 256,
|
|
}
|
|
}
|
|
pub fn math_font(&self, size: u8, family: u8) -> FontId {
|
|
self.mathfonts
|
|
.get(&(size, family))
|
|
.copied()
|
|
.unwrap_or(FontId::NULL)
|
|
}
|
|
pub fn sfcode(&self, c: u8) -> u16 {
|
|
self.space_factor_code(u32::from(c))
|
|
}
|
|
|
|
pub(super) fn space_factor_code(&self, c: u32) -> u16 {
|
|
self.sfcodes
|
|
.get(&c)
|
|
.copied()
|
|
.unwrap_or(if (u32::from(b'A')..=u32::from(b'Z')).contains(&c) {
|
|
999
|
|
} else {
|
|
1000
|
|
})
|
|
}
|
|
pub(super) fn assign_sfcode(&mut self, c: u32, value: u16, global: bool) {
|
|
self.save(Key::Sfcode(c), global);
|
|
self.sfcodes.insert(c, value);
|
|
}
|
|
pub(super) fn xe_char_class(&self, c: u32) -> u16 {
|
|
self.xe_char_classes.get(&c).copied().unwrap_or(0)
|
|
}
|
|
pub(super) fn assign_xe_char_class(&mut self, c: u32, value: u16, global: bool) {
|
|
// XeTeX groups both halves of its space-factor table as one entry.
|
|
self.save(Key::Sfcode(c), global);
|
|
if value == 0 {
|
|
self.xe_char_classes.remove(&c);
|
|
} else {
|
|
self.xe_char_classes.insert(c, value);
|
|
}
|
|
}
|
|
pub(super) fn xe_inter_char_tokens(&self, index: u32) -> Option<&std::sync::Arc<[Token]>> {
|
|
self.xe_inter_char_tokens.get(&index)
|
|
}
|
|
pub(super) fn assign_xe_inter_char_tokens(
|
|
&mut self,
|
|
index: u32,
|
|
tokens: Vec<Token>,
|
|
global: bool,
|
|
) {
|
|
self.save(Key::XeInterCharTokens(index), global);
|
|
if tokens.is_empty() {
|
|
self.xe_inter_char_tokens.remove(&index);
|
|
} else {
|
|
self.xe_inter_char_tokens.insert(index, tokens.into());
|
|
}
|
|
}
|
|
pub fn case_code(&self, kind: super::CaseCode, c: char) -> u32 {
|
|
self.case_codes.get(&(kind, c)).copied().unwrap_or_else(|| {
|
|
if !c.is_ascii_alphabetic() {
|
|
0
|
|
} else {
|
|
match kind {
|
|
super::CaseCode::Lower => c.to_ascii_lowercase() as u32,
|
|
super::CaseCode::Upper => c.to_ascii_uppercase() as u32,
|
|
}
|
|
}
|
|
})
|
|
}
|
|
pub(super) fn assign_case_code(
|
|
&mut self,
|
|
kind: super::CaseCode,
|
|
c: char,
|
|
value: u32,
|
|
global: bool,
|
|
) {
|
|
self.save(Key::CaseCode(kind, c), global);
|
|
self.case_codes.insert((kind, c), value);
|
|
}
|
|
pub fn delcode(&self, c: u8) -> i32 {
|
|
self.delimiter_code(u32::from(c))
|
|
}
|
|
pub(super) fn delimiter_code(&self, c: u32) -> i32 {
|
|
self.delcodes
|
|
.get(&c)
|
|
.copied()
|
|
.unwrap_or(if c == u32::from(b'.') { 0 } else { -1 })
|
|
}
|
|
pub(super) fn assign_delcode(&mut self, c: u32, n: i32, global: bool) {
|
|
self.save(Key::Delcode(c), global);
|
|
self.delcodes.insert(c, n);
|
|
}
|
|
pub(super) fn assign_mathcode(&mut self, c: u32, n: super::MathCode, global: bool) {
|
|
self.save(Key::Mathcode(c), global);
|
|
self.mathcodes.insert(c, n);
|
|
}
|
|
pub(super) fn assign_mathfont(&mut self, size: u8, family: u8, font: FontId, global: bool) {
|
|
self.save(Key::Mathfont(size, family), global);
|
|
self.mathfonts.insert((size, family), font);
|
|
}
|
|
pub fn box_register(&self, index: u16) -> Option<&NativeBox> {
|
|
self.boxes.get(&index)
|
|
}
|
|
pub fn split_marks(&self, class: u16) -> Option<&super::SplitMarks> {
|
|
self.split_marks.get(&class)
|
|
}
|
|
pub fn page_marks(&self, class: u16) -> Option<&super::PageMarks> {
|
|
self.page_marks.get(&class)
|
|
}
|
|
pub fn last_badness(&self) -> i32 {
|
|
self.last_badness
|
|
}
|
|
pub(super) fn assign_box(&mut self, index: u16, value: Option<NativeBox>, global: bool) {
|
|
self.save(Key::Box(index), global);
|
|
self.set_box(index, value);
|
|
}
|
|
pub(super) fn set_box(&mut self, index: u16, value: Option<NativeBox>) {
|
|
if let Some(b) = value {
|
|
self.boxes.insert(index, b);
|
|
} else {
|
|
self.boxes.remove(&index);
|
|
}
|
|
}
|
|
pub(super) fn take_box(&mut self, index: u16) -> Option<NativeBox> {
|
|
self.boxes.remove(&index)
|
|
}
|
|
pub(super) fn box_dimension(&mut self, index: u16, which: Primitive, value: i32) {
|
|
if let Some(b) = self.boxes.get_mut(&index) {
|
|
match which {
|
|
Primitive::Wd => b.width = value as i64,
|
|
Primitive::Ht => b.height = value as i64,
|
|
Primitive::Dp => b.depth = value as i64,
|
|
_ => unreachable!(),
|
|
}
|
|
}
|
|
}
|
|
pub fn count(&self, index: u16) -> i32 {
|
|
self.counts.get(&index).copied().unwrap_or(0)
|
|
}
|
|
pub(super) fn set_paragraph_token(&mut self, name: CommandName) {
|
|
self.paragraph_token = match &name {
|
|
CommandName::Control(value) if value == "par" => None,
|
|
_ => Some(name),
|
|
};
|
|
}
|
|
pub(super) fn paragraph_token(&self) -> TokenKind {
|
|
let name = self
|
|
.paragraph_token
|
|
.clone()
|
|
.unwrap_or_else(|| CommandName::Control("par".into()));
|
|
TokenKind::Command(name)
|
|
}
|
|
pub(super) fn is_paragraph_token(&self, token: &TokenKind) -> bool {
|
|
match (token, &self.paragraph_token) {
|
|
(TokenKind::Command(name), Some(paragraph)) => name == paragraph,
|
|
(TokenKind::Command(CommandName::Control(name)), None) => name == "par",
|
|
_ => false,
|
|
}
|
|
}
|
|
pub fn group_depth(&self) -> usize {
|
|
self.groups.len()
|
|
}
|
|
pub(super) fn font_defaults(&self) -> super::FontIntegers {
|
|
super::FontIntegers {
|
|
hyphen: self.parameter(Parameter::Defaulthyphenchar).width(),
|
|
skew: self.parameter(Parameter::Defaultskewchar).width(),
|
|
}
|
|
}
|
|
|
|
pub fn fingerprint(&self) -> u64 {
|
|
let mut hash = FingerprintHasher::default();
|
|
self.hash(&mut hash);
|
|
hash.finish()
|
|
}
|
|
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
|
|
self.groups.push(Group {
|
|
kind,
|
|
origin,
|
|
after: Vec::new(),
|
|
saved: BTreeMap::new(),
|
|
save_order: Vec::new(),
|
|
});
|
|
}
|
|
pub(super) fn open_groups(
|
|
&self,
|
|
) -> impl DoubleEndedIterator<Item = (GroupKind, Option<(usize, usize)>)> + ExactSizeIterator + '_
|
|
{
|
|
self.groups.iter().map(|group| (group.kind, group.origin))
|
|
}
|
|
pub(super) fn group_origin(&self) -> Option<(usize, usize)> {
|
|
self.groups.last().and_then(|group| group.origin)
|
|
}
|
|
pub(super) fn save_for_after(&mut self, token: Token) -> bool {
|
|
if let Some(group) = self.groups.last_mut() {
|
|
group.after.push(token);
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
}
|
|
pub(super) fn pop_group(&mut self, kind: GroupKind) -> Result<GroupRestore, &'static str> {
|
|
let Some(group) = self.groups.last() else {
|
|
return Err("extra end group");
|
|
};
|
|
if group.kind != kind {
|
|
return Err("mismatched native group kind");
|
|
}
|
|
let mut group = self.groups.pop().unwrap();
|
|
let mut entries = Vec::with_capacity(group.save_order.len());
|
|
for key in group.save_order.into_iter().rev() {
|
|
let saved = group.saved.remove(&key);
|
|
entries.push((key, saved));
|
|
}
|
|
// Older execution snapshots had only the keyed saved values.
|
|
entries.extend(
|
|
group
|
|
.saved
|
|
.into_iter()
|
|
.map(|(key, saved)| (key, Some(saved))),
|
|
);
|
|
Ok(GroupRestore {
|
|
entries,
|
|
after: group.after,
|
|
})
|
|
}
|
|
pub(super) fn restore_saved(&mut self, key: Key, value: Saved) {
|
|
match (key, value) {
|
|
(Key::Command(name), Saved::Command(value)) => match value {
|
|
Some(value) => {
|
|
self.commands.insert(name, value);
|
|
}
|
|
None => {
|
|
self.commands.remove(&name);
|
|
}
|
|
},
|
|
(Key::Catcode(c), Saved::Catcode(value)) => match value {
|
|
Some(value) => {
|
|
self.catcodes.insert(c, value);
|
|
}
|
|
None => {
|
|
self.catcodes.remove(&c);
|
|
}
|
|
},
|
|
(Key::Count(index), Saved::Integer(value)) => {
|
|
self.set_count(index, value);
|
|
}
|
|
(Key::Endlinechar, Saved::Integer(value)) => self.endlinechar = value,
|
|
(Key::Newlinechar, Saved::Integer(value)) => self.newlinechar = value,
|
|
(Key::Escapechar, Saved::Integer(value)) => self.escapechar = value,
|
|
(Key::Toks(index), Saved::Tokens(value)) => match value {
|
|
Some(value) => {
|
|
self.toks.insert(index, value);
|
|
}
|
|
None => {
|
|
self.toks.remove(&index);
|
|
}
|
|
},
|
|
(Key::TokenParameter(p), Saved::Hook(value)) => match value {
|
|
Some(value) => {
|
|
self.token_parameters.insert(p, value);
|
|
}
|
|
None => {
|
|
self.token_parameters.remove(&p);
|
|
}
|
|
},
|
|
(Key::Globaldefs, Saved::Integer(value)) => self.globaldefs = value,
|
|
(Key::Register(register), Saved::Register(value)) => match value {
|
|
Some(value) => self.set_register(register, value),
|
|
None => {
|
|
self.registers.remove(®ister);
|
|
}
|
|
},
|
|
(Key::Parameter(p), Saved::Parameter(v)) => match v {
|
|
Some(v) => {
|
|
self.parameters.insert(p, v);
|
|
}
|
|
None => {
|
|
self.parameters.remove(&p);
|
|
}
|
|
},
|
|
(Key::ParagraphShape, Saved::ParagraphShape(shape)) => self.paragraph_shape = shape,
|
|
(Key::Mathcode(c), Saved::Mathcode(v)) => {
|
|
if let Some(v) = v {
|
|
self.mathcodes.insert(c, v);
|
|
} else {
|
|
self.mathcodes.remove(&c);
|
|
}
|
|
}
|
|
(Key::Sfcode(c), Saved::Sfcode(factor, class)) => {
|
|
if let Some(v) = factor {
|
|
self.sfcodes.insert(c, v);
|
|
} else {
|
|
self.sfcodes.remove(&c);
|
|
}
|
|
if let Some(v) = class {
|
|
self.xe_char_classes.insert(c, v);
|
|
} else {
|
|
self.xe_char_classes.remove(&c);
|
|
}
|
|
}
|
|
(Key::XeInterCharTokens(index), Saved::XeInterCharTokens(tokens)) => {
|
|
if let Some(tokens) = tokens {
|
|
self.xe_inter_char_tokens.insert(index, tokens);
|
|
} else {
|
|
self.xe_inter_char_tokens.remove(&index);
|
|
}
|
|
}
|
|
(Key::Delcode(c), Saved::Delcode(v)) => {
|
|
if let Some(v) = v {
|
|
self.delcodes.insert(c, v);
|
|
} else {
|
|
self.delcodes.remove(&c);
|
|
}
|
|
}
|
|
(Key::CaseCode(kind, c), Saved::CaseCode(v)) => {
|
|
if let Some(v) = v {
|
|
self.case_codes.insert((kind, c), v);
|
|
} else {
|
|
self.case_codes.remove(&(kind, c));
|
|
}
|
|
}
|
|
(Key::Mathfont(s, f), Saved::Mathfont(v)) => {
|
|
if let Some(v) = v {
|
|
self.mathfonts.insert((s, f), v);
|
|
} else {
|
|
self.mathfonts.remove(&(s, f));
|
|
}
|
|
}
|
|
(Key::Box(n), Saved::Box(b)) => self.set_box(n, b),
|
|
(Key::Font, Saved::Font(font)) => self.text_font = font,
|
|
(Key::Job(parameter), Saved::Job(value)) => match value {
|
|
Some(value) => {
|
|
self.job_parameters.insert(parameter, value);
|
|
}
|
|
None => {
|
|
self.job_parameters.remove(¶meter);
|
|
}
|
|
},
|
|
_ => unreachable!("save-stack entry matches its key"),
|
|
}
|
|
}
|
|
pub(super) fn global(&self, prefix: bool) -> bool {
|
|
if self.globaldefs == 0 {
|
|
prefix
|
|
} else {
|
|
self.globaldefs > 0
|
|
}
|
|
}
|
|
pub(super) fn save(&mut self, key: Key, global: bool) {
|
|
if global {
|
|
for group in &mut self.groups {
|
|
group.saved.remove(&key);
|
|
}
|
|
return;
|
|
}
|
|
if self
|
|
.groups
|
|
.last()
|
|
.is_none_or(|group| group.saved.contains_key(&key))
|
|
{
|
|
return;
|
|
}
|
|
let value = match &key {
|
|
Key::Command(name) => Saved::Command(self.commands.get(name).cloned()),
|
|
Key::Catcode(c) => Saved::Catcode(self.catcodes.get(c).copied()),
|
|
Key::Count(index) => Saved::Integer(self.count(*index)),
|
|
Key::Endlinechar => Saved::Integer(self.endlinechar),
|
|
Key::Newlinechar => Saved::Integer(self.newlinechar),
|
|
Key::Escapechar => Saved::Integer(self.escapechar),
|
|
Key::Toks(index) => Saved::Tokens(self.toks.get(index).cloned()),
|
|
Key::TokenParameter(p) => Saved::Hook(self.token_parameters.get(p).cloned()),
|
|
Key::Globaldefs => Saved::Integer(self.globaldefs),
|
|
Key::Job(parameter) => Saved::Job(self.job_parameter(*parameter)),
|
|
Key::Register(register) => Saved::Register(self.registers.get(register).copied()),
|
|
Key::Parameter(p) => Saved::Parameter(self.parameters.get(p).copied()),
|
|
Key::ParagraphShape => Saved::ParagraphShape(self.paragraph_shape.clone()),
|
|
Key::Font => Saved::Font(self.text_font),
|
|
Key::Box(n) => Saved::Box(self.boxes.get(n).cloned()),
|
|
Key::Mathcode(c) => Saved::Mathcode(self.mathcodes.get(c).copied()),
|
|
Key::Mathcodenum(_) | Key::Delcodenum(_) => {
|
|
unreachable!("packed code reads do not create save records")
|
|
}
|
|
Key::Delcode(c) => Saved::Delcode(self.delcodes.get(c).copied()),
|
|
Key::Sfcode(c) => Saved::Sfcode(
|
|
self.sfcodes.get(c).copied(),
|
|
self.xe_char_classes.get(c).copied(),
|
|
),
|
|
Key::XeInterCharTokens(index) => {
|
|
Saved::XeInterCharTokens(self.xe_inter_char_tokens.get(index).cloned())
|
|
}
|
|
Key::CaseCode(kind, c) => Saved::CaseCode(self.case_codes.get(&(*kind, *c)).copied()),
|
|
Key::Mathfont(s, f) => Saved::Mathfont(self.mathfonts.get(&(*s, *f)).copied()),
|
|
Key::Spacefactor => unreachable!("spacefactor belongs to the horizontal list"),
|
|
};
|
|
let group = self.groups.last_mut().unwrap();
|
|
group.save_order.push(key.clone());
|
|
group.saved.insert(key, value);
|
|
}
|
|
pub(super) fn define(&mut self, name: CommandName, meaning: Meaning, global: bool) {
|
|
self.save(Key::Command(name.clone()), global);
|
|
self.commands.insert(name, meaning);
|
|
}
|
|
pub(super) fn assign_catcode(&mut self, c: char, value: CatCode, global: bool) {
|
|
self.save(Key::Catcode(c), global);
|
|
self.catcodes.insert(c, value);
|
|
}
|
|
pub(super) fn assign_integer(&mut self, key: Key, value: i32, global: bool) {
|
|
self.save(key.clone(), global);
|
|
match key {
|
|
Key::Count(index) => {
|
|
self.set_count(index, value);
|
|
}
|
|
Key::Endlinechar => self.endlinechar = value,
|
|
Key::Newlinechar => self.newlinechar = value,
|
|
Key::Escapechar => self.escapechar = value,
|
|
Key::Globaldefs => self.globaldefs = value,
|
|
Key::Job(parameter) => {
|
|
self.job_parameters.insert(parameter, value);
|
|
}
|
|
Key::Parameter(p) => {
|
|
self.assign_parameter(p, ParameterValue::Integer(value), global);
|
|
}
|
|
_ => unreachable!("integer assignment has integer key"),
|
|
}
|
|
}
|
|
pub(super) fn assign_tokens(&mut self, index: u16, tokens: Vec<Token>, global: bool) {
|
|
self.save(Key::Toks(index), global);
|
|
if tokens.is_empty() {
|
|
self.toks.remove(&index);
|
|
} else {
|
|
self.toks.insert(index, tokens);
|
|
}
|
|
}
|
|
fn set_count(&mut self, index: u16, value: i32) {
|
|
if value == 0 {
|
|
self.counts.remove(&index);
|
|
} else {
|
|
self.counts.insert(index, value);
|
|
}
|
|
}
|
|
}
|