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, Pdfximage, Pdfrefximage, Pdflastximage, Pdflastximagepages, Pdflastximagecolordepth, Jobname, Pdfcreationdate, Pdfshellescape, Pdftexversion, Pdftexrevision, Ifpdfabsnum, Ifpdfabsdim, Pdfstrcmp, Pdfcolorstackinit, Pdfcolorstack, Pdfsave, Pdfstartlink, Pdfendlink, Pdfdest, Pdfcatalog, Pdfoutline, Pdfinfo, Pdfsetmatrix, Pdfrestore, Pdfglyphtounicode, 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, 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, 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, } impl Primitive { pub(super) fn page_dimension(self) -> Option { 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 | Romannumeral | Fontname | The | String | MeaningOf | Unexpanded | Expanded | Detokenize | Etexrevision | Pdffilesize | Pdffilemoddate | Jobname | Pdfcreationdate | Pdftexrevision | Pdfstrcmp | Pdfmatch | Pdflastmatch | 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, /// One delimiter per argument; an empty delimiter means undelimited. pub parameters: Vec>, pub parameter_chars: Vec, pub replacement: Vec, 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), Character(TokenKind), Count(u16), Toks(u16), TokenParameter(TokenParameter), CharGiven(u8), MathCharGiven(u16), Register(Register), Parameter(Parameter), Font(FontId), } /// 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(u8), Delcode(u8), Sfcode(u8), CaseCode(super::CaseCode, char), Mathfont(u8, u8), } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(super) enum Saved { Command(Option), Catcode(Option), Integer(i32), Tokens(Option>), Hook(Option>), Job(Option), Register(Option), Parameter(Option), ParagraphShape(std::sync::Arc<[super::paragraph::ParagraphShapeLine]>), Font(FontId), Box(Option), Mathcode(Option), Delcode(Option), Sfcode(Option), CaseCode(Option), Mathfont(Option), } #[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, #[serde(with = "ordered_map")] saved: BTreeMap, #[serde(default)] save_order: Vec, } pub(super) struct GroupRestore { pub entries: Vec<(Key, Option)>, pub after: Vec, } // 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( map: &BTreeMap, serializer: S, ) -> Result { map.iter().collect::>().serialize(serializer) } pub fn deserialize< 'de, K: Deserialize<'de> + Ord, V: Deserialize<'de>, D: Deserializer<'de>, >( deserializer: D, ) -> Result, D::Error> { Ok(Vec::<(K, V)>::deserialize(deserializer)? .into_iter() .collect()) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct State { #[serde(with = "ordered_map")] commands: BTreeMap, catcodes: BTreeMap, counts: BTreeMap, toks: BTreeMap>, #[serde(with = "ordered_map")] pub(super) token_parameters: BTreeMap>, profile: Profile, initex: bool, #[serde(default)] input_profile: super::InputProfile, pub endlinechar: i32, pub newlinechar: i32, pub escapechar: i32, pub globaldefs: i32, groups: Vec, job_parameters: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_creation_date: Option, #[serde(with = "ordered_map")] registers: BTreeMap, parameters: BTreeMap, paragraph_shape: std::sync::Arc<[super::paragraph::ParagraphShapeLine]>, pub(super) text_font: FontId, pub(super) fonts: super::FontCatalog, boxes: BTreeMap, pub(super) split_marks: BTreeMap, pub(super) page_marks: BTreeMap, mathcodes: BTreeMap, delcodes: BTreeMap, #[serde(default)] sfcodes: BTreeMap, #[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, /// TeX prepare_mag freeze, independent of ordinary grouping/assignments. pub(super) magnification_set: Option, pub(super) output_mode_set: Option, pub(super) pdf_file_options: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_catalog: Option>, pub(super) pdf_info: Vec, 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); } 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, initex: false, input_profile: super::InputProfile::default(), endlinechar: 13, newlinechar: -1, escapechar: 92, globaldefs: 0, groups: Vec::new(), 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(), case_codes: BTreeMap::new(), mathfonts: BTreeMap::new(), last_badness: 0, magnification_set: None, output_mode_set: None, pdf_file_options: None, pdf_catalog: None, pdf_info: 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), ("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), ("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), ("immediate", Immediate), ("message", Message), ("errmessage", Errmessage), ("end", End), ("pdffilesize", Pdffilesize), ("pdffilemoddate", Pdffilemoddate), ("pdfximage", Pdfximage), ("pdfrefximage", Pdfrefximage), ("pdflastximage", Pdflastximage), ("pdflastximagepages", Pdflastximagepages), ("pdflastximagecolordepth", Pdflastximagecolordepth), ("jobname", Jobname), ("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), ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), ("pdfstartlink", Pdfstartlink), ("pdfendlink", Pdfendlink), ("pdfdest", Pdfdest), ("pdfcatalog", Pdfcatalog), ("pdfoutline", Pdfoutline), ("pdfinfo", Pdfinfo), ("pdfsetmatrix", Pdfsetmatrix), ("pdfrestore", Pdfrestore), ("pdfglyphtounicode", Pdfglyphtounicode), ("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 ) { 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 } } 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(); 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.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 .fonts() .iter() .map(|f| f.parameters().len()) .sum(); 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() { 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)) => 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)); } /// 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, 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 } pub fn job_parameter(&self, parameter: JobParameter) -> Option { 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), ("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 } pub fn register_limit(&self) -> u16 { if self.profile == Profile::EtexBootstrap { 32767 } else { 255 } } pub fn profile(&self) -> Profile { self.profile } pub fn tokens(&self, index: u16) -> Vec { self.toks.get(&index).cloned().unwrap_or_default() } pub(super) fn group_type(&self) -> i32 { match self.groups.last().map(|g| g.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.split_marks.clear(); self.page_marks.clear(); self.last_badness = 0; self.magnification_set = None; self.output_mode_set = None; self.pdf_file_options = None; self.pdf_catalog = None; self.pdf_info.clear(); self } pub fn is_initex(&self) -> bool { self.initex } /// Final font output uses the live table and parameters, not the values /// captured at a page's shipout. The table is global and survives a dump. 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(), glyph_unicode: &self.glyph_unicode, catalog: self.pdf_catalog.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), ] { let name = CommandName::Control(name.into()); match profile { super::InputProfile::TeX8Bit => { self.commands.insert(name, Meaning::Primitive(primitive)); } super::InputProfile::UnicodeScalar => { if self.commands.get(&name) == Some(&Meaning::Primitive(primitive)) { self.commands.remove(&name); } } } } self } 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) } pub fn mathcode(&self, c: u8) -> u16 { self.mathcodes.get(&c).copied().unwrap_or_else(|| { if c.is_ascii_alphabetic() { 0x7100 + c as u16 } else if c.is_ascii_digit() { 0x7000 + c as u16 } else { c as u16 } }) } 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.sfcodes .get(&c) .copied() .unwrap_or(if c.is_ascii_uppercase() { 999 } else { 1000 }) } pub(super) fn assign_sfcode(&mut self, c: u8, value: u16, global: bool) { self.save(Key::Sfcode(c), global); self.sfcodes.insert(c, value); } 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.delcodes .get(&c) .copied() .unwrap_or(if c == b'.' { 0 } else { -1 }) } pub(super) fn assign_delcode(&mut self, c: u8, n: i32, global: bool) { self.save(Key::Delcode(c), global); self.delcodes.insert(c, n); } pub(super) fn assign_mathcode(&mut self, c: u8, n: u16, 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, global: bool) { self.save(Key::Box(index), global); self.set_box(index, value); } pub(super) fn set_box(&mut self, index: u16, value: Option) { 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 { 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 fn group_depth(&self) -> usize { self.groups.len() } 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)> + 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 { 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(v)) => { if let Some(v) = v { self.sfcodes.insert(c, v); } else { self.sfcodes.remove(&c); } } (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::Delcode(c) => Saved::Delcode(self.delcodes.get(c).copied()), Key::Sfcode(c) => Saved::Sfcode(self.sfcodes.get(c).copied()), 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, 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); } } }