pub(super) mod source_relocation; use hashbrown::HashMap; use std::collections::BTreeMap; use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; use std::sync::{Arc, OnceLock}; 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, /// Preserved in token lists before the ordinary token naming the operand. FrozenPrimitivePrefix, /// The selected primitive meaning, which survives putting a token back. FrozenPrimitive(String), } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum Primitive { Relax, Ignorespaces, UsePrimitive, DeferredPrimitive, 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, Pdffiledump, Pdfmdfivesum, Pdfxform, Pdfrefxform, Pdflastxform, Pdfximage, Pdfrefximage, Pdflastximage, Pdfximagebbox, Pdfinsertht, Pdflastximagepages, Pdflastximagecolordepth, Jobname, Pdfcreationdate, Pdfshellescape, Pdftexversion, Pdftexrevision, Ifpdfabsnum, Ifpdfabsdim, Pdfstrcmp, Pdfcolorstackinit, Pdfcolorstack, Pdfsave, Pdfstartlink, Pdfannot, Pdfthread, Pdfstartthread, Pdfendthread, 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, Ifprimitive, Ifpdfprimitive, // 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, Nonscript, Overline, Underline, Eqno, Leqno, Parshape, Parshapelength, Parshapeindent, Parshapedimen, LinePenalties(LinePenaltyKind), Spacefactor, Setbox, Box, Copy, Hbox, Halign, Valign, Cr, Crcr, Span, Omit, Noalign, Showbox, Show, Showthe, Showtokens, 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, Middle, 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, Pdfnoligatures, Tagcode, Pdfobj, Pdfrefobj, Pdflastobj, Pdfrandomseed, Pdfsetrandomseed, Pdfuniformdeviate, Pdfnormaldeviate, Pdfpageref, Pdffontobjnum, Partokenname, Pdfliteral, Leftmarginkern, Rightmarginkern, Pdflastlink, Pdflastannot, 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 { 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 | UsePrimitive | Expandafter | Number | Uchar | Ucharcat | Romannumeral | Fontname | The | String | MeaningOf | Unexpanded | Expanded | Detokenize | Etexrevision | Pdffilesize | Pdffilemoddate | Pdffiledump | Pdfmdfivesum | Jobname | Pdfcreationdate | Pdftexrevision | XeTeXrevision | XeTeXglyphname | XeTeXfeaturename | XeTeXselectorname | Pdfstrcmp | Pdfximagebbox | Pdfinsertht | Pdfmatch | Pdflastmatch | Pdfuniformdeviate | Pdfnormaldeviate | Pdfpageref | Pdffontobjnum | 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::Ifprimitive | Self::Ifpdfprimitive | 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(u32), MathCharGiven(u16), Register(Register), Parameter(Parameter), Font(FontId), UnicodeMathCharGiven(super::MathCode), } /// The four indexed e-TeX penalties used between typeset paragraph lines. #[derive( Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, )] pub enum LinePenaltyKind { Interline, Club, Widow, DisplayWidow, } impl LinePenaltyKind { const ALL: [Self; 4] = [Self::Interline, Self::Club, Self::Widow, Self::DisplayWidow]; pub(super) fn name(self) -> &'static str { match self { Self::Interline => "interlinepenalties", Self::Club => "clubpenalties", Self::Widow => "widowpenalties", Self::DisplayWidow => "displaywidowpenalties", } } pub(super) fn for_widow_parameter(parameter: Parameter) -> Self { match parameter { Parameter::Widowpenalty => Self::Widow, Parameter::Displaywidowpenalty => Self::DisplayWidow, _ => unreachable!("paragraph has a widow penalty parameter"), } } } /// 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, LinePenalties(LinePenaltyKind), 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), Catcode(Option), Integer(i32), Tokens(Option>), Hook(Option>), Job(Option), Register(Option), Parameter(Option), ParagraphShape(std::sync::Arc<[super::paragraph::ParagraphShapeLine]>), LinePenalties(Option>), Font(FontId), Box(Option), Mathcode(Option), Delcode(Option), Sfcode(Option, Option), XeInterCharTokens(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, 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, } const COMMAND_SHARDS: usize = 32; type CommandEntries = HashMap, Meaning, RandomState>; #[derive(Clone, Debug)] struct CommandShard { entries: CommandEntries, // Bounds may retain ranges of replaced or removed entries. Their only // use is to prove that every surviving token is before an edit. source_bounds: OnceLock>>, } impl CommandShard { fn new(entries: CommandEntries) -> Self { Self { entries, source_bounds: OnceLock::new() } } fn insert(&mut self, name: Arc, meaning: Meaning) -> Option { if let Some(bounds) = self.source_bounds.get_mut() { source_relocation::include_meaning_bounds(bounds, &meaning); } self.entries.insert(name, meaning) } fn insert_if_absent(&mut self, name: Arc, meaning: Meaning) -> bool { let hashbrown::hash_map::Entry::Vacant(entry) = self.entries.entry(name) else { return false; }; if let Some(bounds) = self.source_bounds.get_mut() { source_relocation::include_meaning_bounds(bounds, &meaning); } entry.insert(meaning); true } } impl PartialEq for CommandShard { fn eq(&self, other: &Self) -> bool { self.entries == other.entries } } impl Eq for CommandShard {} type OrderedCommandNames = Arc, u64)>>>; pub(super) fn command_hasher() -> &'static RandomState { // Identical hashes feed the binding table and the executor's read cache. // The seed and partition are private to this process. static HASHER: OnceLock = OnceLock::new(); HASHER.get_or_init(RandomState::new) } #[derive(Clone, Debug)] struct CommandBindings { shards: [Arc; COMMAND_SHARDS], revisions: [u64; COMMAND_SHARDS], // Cache names only so redefinitions can share the same order. ordered_names: OrderedCommandNames, } impl Default for CommandBindings { fn default() -> Self { let hasher = command_hasher(); Self { shards: std::array::from_fn(|_| { Arc::new(CommandShard::new(CommandEntries::with_hasher(hasher.clone()))) }), revisions: [0; COMMAND_SHARDS], ordered_names: Arc::default(), } } } impl PartialEq for CommandBindings { fn eq(&self, other: &Self) -> bool { self.shards == other.shards } } impl Eq for CommandBindings {} impl CommandBindings { fn shard_index(hash: u64) -> usize { // Use bits separate from the table's bucket index and control tag. ((hash >> 32) as usize) % COMMAND_SHARDS } fn get(&self, name: &CommandName) -> Option<&Meaning> { self.get_hashed(name, command_hasher().hash_one(name)) } fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> { self.shards[Self::shard_index(hash)] .entries .raw_entry() .from_key_hashed_nocheck(hash, name) .map(|(_, meaning)| meaning) } fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard { let index = Self::shard_index(command_hasher().hash_one(name)); self.revisions[index] += 1; Arc::make_mut(&mut self.shards[index]) } fn insert(&mut self, name: Arc, meaning: Meaning) { if self.shard_mut(&name).insert(name, meaning).is_none() { self.invalidate_order(); } } fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) { if self.shard_mut(&name).insert_if_absent(name.into(), meaning) { self.invalidate_order(); } } fn remove(&mut self, name: &CommandName) { if self.shard_mut(name).entries.remove(name).is_some() { self.invalidate_order(); } } fn invalidate_order(&mut self) { if let Some(order) = Arc::get_mut(&mut self.ordered_names) { order.take(); } else { self.ordered_names = Arc::default(); } } fn len(&self) -> usize { self.shards.iter().map(|shard| shard.entries.len()).sum() } fn iter(&self) -> impl Iterator, &Meaning)> { self.shards.iter().flat_map(|shard| shard.entries.iter()) } fn ordered(&self) -> impl ExactSizeIterator, &Meaning)> { self.ordered_names .get_or_init(|| { let hasher = command_hasher(); let mut names = Vec::with_capacity(self.len()); names.extend( self.iter() .map(|(name, _)| (name.clone(), hasher.hash_one(name))), ); names.sort_unstable_by(|(left, _), (right, _)| left.cmp(right)); names }) .iter() .map(|(name, hash)| { let meaning = self .get_hashed(name, *hash) .expect("ordered command names match the binding table"); (name, meaning) }) } } impl Hash for CommandBindings { fn hash(&self, hasher: &mut H) { let entries = self.ordered(); entries.len().hash(hasher); for entry in entries { entry.hash(hasher); } } } impl serde::Serialize for CommandBindings { fn serialize(&self, serializer: S) -> Result { serializer.collect_seq(self.ordered()) } } impl<'de> serde::Deserialize<'de> for CommandBindings { fn deserialize>(deserializer: D) -> Result { let entries = , Meaning)> as serde::Deserialize>::deserialize( deserializer, )?; let mut bindings = Self::default(); for (name, meaning) in entries { bindings.insert(name, meaning); } Ok(bindings) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct State { // Checkpoints share the table. A write copies just its command shard. // Formats and fingerprints use key order. commands: Arc, catcodes: BTreeMap, counts: BTreeMap, toks: BTreeMap>, #[serde(with = "ordered_map")] pub(super) token_parameters: BTreeMap>, profile: Profile, #[serde(default)] pdftex_revision: PdftexRevision, initex: bool, #[serde(default)] input_profile: super::InputProfile, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) byte_translation: Option>, #[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, pub endlinechar: i32, pub newlinechar: i32, pub escapechar: i32, pub globaldefs: i32, #[serde(default, skip_serializing_if = "Option::is_none")] paragraph_token: Option, groups: Vec, job_parameters: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_creation_date: Option, #[serde(default, skip_serializing_if = "Option::is_none")] initial_random_seed: Option, #[serde(default, skip_serializing_if = "Option::is_none")] random: Option>, #[serde(with = "ordered_map")] registers: BTreeMap, parameters: BTreeMap, paragraph_shape: std::sync::Arc<[super::paragraph::ParagraphShapeLine]>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] line_penalties: BTreeMap>, 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(default, skip_serializing_if = "BTreeMap::is_empty")] xe_char_classes: BTreeMap, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] xe_inter_char_tokens: 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, #[serde(default)] pub(super) pdf_last_position: [i32; 2], /// TeX prepare_mag freeze, independent of ordinary grouping/assignments. pub(super) magnification_set: Option, pub(super) output_mode_set: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_header_options: Option, pub(super) pdf_file_options: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_copy_imported_fonts: Option, #[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>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_catalog: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub(super) pdf_objects: Option>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(super) pdf_forms: BTreeMap, pub(super) pdf_info: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) pdf_pages_attributes: 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 FingerprintHasher { #[inline] fn write_fixed(&mut self, bytes: [u8; N]) { if N > self.buffer.len() - self.used { self.hasher.write(&self.buffer[..self.used]); self.used = 0; } let end = self.used + N; self.buffer[self.used..end].copy_from_slice(&bytes); self.used = end; } } impl Hasher for FingerprintHasher { #[inline] fn write_u8(&mut self, value: u8) { self.write_fixed(value.to_ne_bytes()); } #[inline] fn write_u16(&mut self, value: u16) { self.write_fixed(value.to_ne_bytes()); } #[inline] fn write_u32(&mut self, value: u32) { self.write_fixed(value.to_ne_bytes()); } #[inline] fn write_u64(&mut self, value: u64) { self.write_fixed(value.to_ne_bytes()); } #[inline] fn write_usize(&mut self, value: usize) { self.write_fixed(value.to_ne_bytes()); } 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()); let mut ordered_hash = DefaultHasher::new(); let mut table_hash = DefaultHasher::new(); let ordered: BTreeMap<_, _> = state.commands.iter().collect(); ordered.hash(&mut ordered_hash); state.commands.hash(&mut table_hash); assert_eq!(table_hash.finish(), ordered_hash.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); } #[test] fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() { let mut state = State::initex().with_etex(); let name = CommandName::Control("checkpointbinding".into()); state.define(name.clone(), Meaning::Count(3), true); let fingerprint = state.fingerprint(); let snapshot = state.clone(); state.define(name.clone(), Meaning::Count(7), true); assert_eq!(snapshot.meaning(&name), Meaning::Count(3)); assert_eq!(state.meaning(&name), Meaning::Count(7)); let shared = state.commands.shards.iter().zip(&snapshot.commands.shards) .filter(|(current, saved)| Arc::ptr_eq(current, saved)).count(); assert_eq!(shared, COMMAND_SHARDS - 1); assert!(Arc::ptr_eq( &state.commands.ordered_names, &snapshot.commands.ordered_names, )); let (_, redefined) = state .commands .ordered() .find(|(key, _)| key.as_ref() == &name) .unwrap(); assert_eq!(*redefined, Meaning::Count(7)); let added = CommandName::Control("checkpointorderadded".into()); let bindings = state.command_bindings_mut(); let before_insertion = bindings.clone(); bindings.insert_if_absent(name.clone(), Meaning::Count(100)); assert!(Arc::ptr_eq( &bindings.ordered_names, &before_insertion.ordered_names, )); bindings.insert_if_absent(added.clone(), Meaning::Count(9)); assert!(!Arc::ptr_eq( &bindings.ordered_names, &before_insertion.ordered_names, )); let ordered: BTreeMap<_, _> = bindings.iter().collect(); let expected: Vec<_> = ordered.into_iter().collect(); assert!(bindings.ordered().eq(expected.iter().copied())); assert_eq!( serde_json::to_vec(bindings).unwrap(), serde_json::to_vec(&expected).unwrap(), ); let with_added = bindings.clone(); bindings.remove(&added); assert!(bindings.ordered().eq(before_insertion.ordered())); assert!(with_added.ordered().any(|(key, _)| key.as_ref() == &added)); state.define(name, Meaning::Count(3), true); assert_eq!(state, snapshot); assert_eq!(state.fingerprint(), fingerprint); assert_eq!(serde_json::to_vec(&state).unwrap(), serde_json::to_vec(&snapshot).unwrap()); } // 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), ("pdfnoligatures", Pdfnoligatures), ("tagcode", Tagcode), ("letterspacefont", Letterspacefont), ("pdffilesize", Pdffilesize), ("pdffilemoddate", Pdffilemoddate), ("pdffiledump", Pdffiledump), ("pdfmdfivesum", Pdfmdfivesum), ("pdfxform", Pdfxform), ("pdfrefxform", Pdfrefxform), ("pdflastxform", Pdflastxform), ("pdfximage", Pdfximage), ("pdfrefximage", Pdfrefximage), ("pdflastximage", Pdflastximage), ("pdfximagebbox", Pdfximagebbox), ("pdfinsertht", Pdfinsertht), ("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), ("pdflastannot", Pdflastannot), ("pdfrandomseed", Pdfrandomseed), ("pdfsetrandomseed", Pdfsetrandomseed), ("pdfuniformdeviate", Pdfuniformdeviate), ("pdfnormaldeviate", Pdfnormaldeviate), ("pdfpageref", Pdfpageref), ("pdffontobjnum", Pdffontobjnum), ("pdfliteral", Pdfliteral), ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), ("pdfstartlink", Pdfstartlink), ("pdfannot", Pdfannot), ("pdfthread", Pdfthread), ("pdfstartthread", Pdfstartthread), ("pdfendthread", Pdfendthread), ("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), ("filedump", Pdffiledump), ("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: Arc::default(), 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(), byte_translation: None, 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(), line_penalties: BTreeMap::new(), 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, pdf_forms: BTreeMap::new(), 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), ("nonscript", Nonscript), ("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.command_bindings_mut().insert( CommandName::Control(name.into()).into(), Meaning::Primitive(primitive), ); } state.command_bindings_mut().insert( CommandName::Control(" ".into()).into(), Meaning::Primitive(Explicitspace), ); for p in TokenParameter::ALL { if *p == TokenParameter::Everyeof { continue; } state .command_bindings_mut() .insert(CommandName::Control(p.name()).into(), Meaning::TokenParameter(*p)); } for p in Parameter::ALL { if matches!( p, Parameter::Tracinggroups | Parameter::Tracingifs | Parameter::Tracingscantokens | Parameter::Tracingnesting | Parameter::Tracingassigns | Parameter::Savingvdiscards | Parameter::Ignoreprimitiveerror | Parameter::TeXXeTstate | Parameter::Lastlinefit | Parameter::Savinghyphcodes ) || Parameter::XETEX.contains(p) { continue; } state .command_bindings_mut() .insert(CommandName::Control(p.name()).into(), Meaning::Parameter(*p)); } state.command_bindings_mut().insert( CommandName::Control("nullfont".into()).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_primitive_commands(); state.install_unicode_commands(); state } } impl State { pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) { if !c.material_only() { c.usage.state.command_entries = self.commands.len(); for (name, meaning) in self.commands.iter() { Self::collect_command_statistics(c, name, meaning); } } self.collect_state_storage(c); } pub(super) fn collect_compared_statistics( &self, old: &Self, current_usage: &mut super::statistics::Collector, old_usage: &mut super::statistics::Collector, ) -> Option<()> { if !current_usage.material_only() { let entries = old.commands.len(); current_usage.usage.state.command_entries = entries; old_usage.usage.state.command_entries = entries; // The alias proof needs corresponding visits, so both sides // walk the donor's binding order. Hashing and serialization // still use the independent, sorted command order. for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) { if current.entries.len() != prior.entries.len() { return None; } let shared = Arc::ptr_eq(current, prior); for (name, old_meaning) in &prior.entries { let meaning = if shared { old_meaning } else { current.entries.get(name)? }; Self::collect_command_statistics(current_usage, name, meaning); Self::collect_command_statistics(old_usage, name, old_meaning); } } } self.collect_state_storage(current_usage); old.collect_state_storage(old_usage); Some(()) } fn collect_command_statistics( c: &mut super::statistics::Collector, name: &CommandName, meaning: &Meaning, ) { if let CommandName::Control(name) = name { c.usage.state.control_name_bytes += name.len(); } if let Meaning::Macro(macro_definition) = meaning { c.usage.state.macro_bindings += 1; c.macro_body(macro_definition); } } fn collect_state_storage(&self, c: &mut super::statistics::Collector) { use super::statistics::Ownership::Active; for b in self.boxes.values() { c.native_box(b, Active); } if c.material_only() { for saved in self.groups.iter().flat_map(|group| group.saved.values()) { if let Saved::Box(Some(b)) = saved { c.native_box(b, Active); } } return; } 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.hyphenation.saved_code_count() + 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 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 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); } pub(super) fn disable_draft_stream_compression(&mut self) { // This is a device update to the current eqtb value. Existing save // entries still restore the enclosing group's compression setting. self.parameters .insert(Parameter::Pdfcompresslevel, ParameterValue::Integer(0)); } /// 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(super) fn ignored_depth(&self) -> i32 { if self.input_profile() == super::InputProfile::XeTeX { super::parameters::IGNORE_DEPTH } else { self.parameter(Parameter::Pdfignoreddimen).width() } } 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 line_penalties(&self, kind: LinePenaltyKind) -> &[i32] { self.line_penalties.get(&kind).map_or(&[], |values| values.as_ref()) } pub(super) fn assign_line_penalties( &mut self, kind: LinePenaltyKind, values: Vec, global: bool, ) { self.save(Key::LinePenalties(kind), global); if values.is_empty() { self.line_penalties.remove(&kind); } else { self.line_penalties.insert(kind, values.into()); } } 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.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 { 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; self.install_line_penalty_primitives(); self.install_middle_command(); self.install_primitive_commands(); let hook = TokenParameter::Everyeof; self.command_bindings_mut().insert( CommandName::Control(hook.name()).into(), Meaning::TokenParameter(hook), ); for parameter in [ Parameter::Tracinggroups, Parameter::Tracingifs, Parameter::Tracingscantokens, Parameter::Tracingnesting, Parameter::Tracingassigns, Parameter::Savingvdiscards, Parameter::Ignoreprimitiveerror, Parameter::Lastlinefit, Parameter::Savinghyphcodes, ] { self.command_bindings_mut().insert( CommandName::Control(parameter.name()).into(), 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.command_bindings_mut().insert( CommandName::Control(name.into()).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 { self.toks.get(&index).cloned().unwrap_or_default() } pub(super) fn group_kind(&self) -> Option { 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_objects) { self.pdf_objects = None; } use crate::pdf_device::forms::FormContents; for form in self.pdf_forms.values_mut() { if form.contents == FormContents::Shipped { form.contents = FormContents::DiscardedAtDump; } } self.pdf_info.clear(); self.pdf_pages_attributes.clear(); self.fonts.reset_format_font_state(); self.discard_format_letterspace_programs(); self } pub(super) fn rebind_format_images( &mut self, images: &[std::sync::Arc], ) -> Result<(), String> { for b in self.boxes.values_mut() { super::format_image::boxes::rebind(b, images)?; } for form in self.pdf_forms.values_mut() { if let crate::pdf_device::forms::FormContents::Pending(body) = &mut form.contents { super::format_image::boxes::rebind(&mut std::sync::Arc::make_mut(body).box_node, images)?; } } Ok(()) } pub(super) fn validate_format_pdf_forms(&self) -> bool { use crate::pdf_device::forms::FormContents; let registered = self.pdf_objects.iter().flat_map(|objects| objects.form_numbers()); registered.eq(self.pdf_forms.keys().copied()) && self.pdf_forms.iter().all(|(&number, form)| { number == form.form.number && match &form.contents { FormContents::Pending(body) => { let b = &body.box_node; [form.form.width, form.form.height, form.form.depth] == [b.width, b.height, b.depth] } FormContents::DiscardedAtDump => true, FormContents::Shipped => false, } }) } fn visit_format_fonts_mut( &mut self, mut visit: impl FnMut(&mut std::sync::Arc), ) { for b in self.boxes.values_mut() { b.visit_format_fonts_mut(&mut visit); } for form in self.pdf_forms.values_mut() { if let crate::pdf_device::forms::FormContents::Pending(body) = &mut form.contents { std::sync::Arc::make_mut(body).box_node.visit_format_fonts_mut(&mut visit); } } } pub(super) fn discard_format_letterspace_programs(&mut self) { // The format retains the widened TeX metrics. The generated virtual // packets belong to the job that defined the letter-spaced font. if self.fonts.discard_letterspace_programs() { self.visit_format_fonts_mut(|font| { crate::native_font::NativeFont::discard_letterspace_program(font); }); } } pub(super) fn rebind_format_font_resources( &mut self, bindings: &BTreeMap, ) { if self.fonts.rebind_format_resources(bindings) { self.visit_format_fonts_mut(|font| { crate::native_font::NativeFont::rebind_resource_path(font, bindings); }); } } pub(super) fn restore_legacy_format_fonts(&mut self) -> Result<(), String> { let replacements = self.fonts.restore_legacy_synthesized_fonts()?; if !replacements.is_empty() { self.visit_format_fonts_mut(|font| { if let Some(logical) = replacements.get(&(font.id, font.expansion)) { *font = logical.clone(); } }); } 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.command_bindings_mut() .insert_if_absent(CommandName::Control(name.into()), 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(super) fn install_line_penalty_primitives(&mut self) { if self.profile == Profile::EtexBootstrap { for kind in LinePenaltyKind::ALL { self.command_bindings_mut() .insert_if_absent(CommandName::Control(kind.name().into()), Meaning::Primitive(Primitive::LinePenalties(kind))); } } } pub(super) fn install_nonscript_command(&mut self) { self.update_profile_command("nonscript", Meaning::Primitive(Primitive::Nonscript), true); } pub(super) fn install_middle_command(&mut self) { self.update_profile_command( "middle", Meaning::Primitive(Primitive::Middle), self.profile == Profile::EtexBootstrap, ); } pub(super) fn restore_legacy_etex_parameter(&mut self, parameter: Parameter) { if self.profile == Profile::EtexBootstrap { self.command_bindings_mut() .insert_if_absent(CommandName::Control(parameter.name()), Meaning::Parameter(parameter)); } } pub fn is_initex(&self) -> bool { self.initex } /// Whether this job has started PDF output in TeX's draft mode. pub fn pdf_draft_mode(&self) -> bool { self.pdf_header_options.is_some_and(|options| options.draft_mode) } /// 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, ptex_banner_separator: (self.input_profile == super::InputProfile::TeX8Bit && self.parameter(Parameter::Pdfsuppressptexinfo).width() & 1 == 0) .then(|| if self.parameter(Parameter::Pdfptexuseunderscore).width() == 0 { '.' } else { '_' }), glyph_unicode: &self.glyph_unicode, fonts: &self.fonts, page_tree_attributes: &self.pdf_pages_attributes, xdv_glyph_names: None, font_cache: 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.install_primitive_commands(); self } pub(super) fn install_primitive_commands(&mut self) { let xe = self.input_profile == super::InputProfile::XeTeX; self.update_profile_command("ifprimitive", Meaning::Primitive(Primitive::Ifprimitive), xe); self.update_profile_command("ifpdfprimitive", Meaning::Primitive(Primitive::Ifpdfprimitive), !xe); self.update_profile_command("primitive", Meaning::Primitive(Primitive::UsePrimitive), xe); self.update_profile_command("pdfprimitive", Meaning::Primitive(Primitive::UsePrimitive), !xe); self.update_profile_command( "showtokens", Meaning::Primitive(Primitive::Showtokens), self.profile == Profile::EtexBootstrap, ); } fn update_profile_command(&mut self, name: &str, meaning: Meaning, enabled: bool) { let name = CommandName::Control(name.into()); if enabled { self.command_bindings_mut().insert_if_absent(name, meaning); } else if self.commands.get(&name) == Some(&meaning) { self.command_bindings_mut().remove(&name); } } pub(super) fn install_pdf_annotation_commands(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; for (name, primitive) in [ ("pdfannot", Primitive::Pdfannot), ("pdflastannot", Primitive::Pdflastannot), ] { self.update_profile_command(name, Meaning::Primitive(primitive), enabled); } } pub(super) fn install_pdf_thread_commands(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; for (name, primitive) in [ ("pdfthread", Primitive::Pdfthread), ("pdfstartthread", Primitive::Pdfstartthread), ("pdfendthread", Primitive::Pdfendthread), ] { self.update_profile_command(name, Meaning::Primitive(primitive), enabled); } self.update_profile_command("pdfthreadmargin", Meaning::Parameter(Parameter::Pdfthreadmargin), enabled); } pub(super) fn install_pdf_image_query_command(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; self.update_profile_command("pdfximagebbox", Meaning::Primitive(Primitive::Pdfximagebbox), enabled); } pub(super) fn install_pdf_insertion_query_command(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; self.update_profile_command("pdfinsertht", Meaning::Primitive(Primitive::Pdfinsertht), enabled); } pub(super) fn install_pdf_font_tag_commands(&mut self) { let enabled = self.input_profile != super::InputProfile::XeTeX; for (name, primitive) in [ ("pdfnoligatures", Primitive::Pdfnoligatures), ("tagcode", Primitive::Tagcode), ] { self.update_profile_command(name, Meaning::Primitive(primitive), enabled); } } pub(super) fn install_filedump_command(&mut self) { let name = if self.input_profile == super::InputProfile::XeTeX { "filedump" } else { "pdffiledump" }; self.update_profile_command(name, Meaning::Primitive(Primitive::Pdffiledump), true); } 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 primitive_prefix_name(&self) -> &'static str { if self.input_profile == super::InputProfile::XeTeX { "primitive" } else { "pdfprimitive" } } pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> { if matches!(primitive, Primitive::UsePrimitive | Primitive::DeferredPrimitive) { return Some(self.primitive_prefix_name()); } 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.command_bindings_mut().insert(name.into(), meaning); } else if self.commands.get(&name) == Some(&meaning) { self.command_bindings_mut().remove(&name); } } } pub fn input_profile(&self) -> super::InputProfile { self.input_profile } pub(super) fn translate_input_character(&self, value: char) -> char { if let Some(table) = &self.byte_translation && self.input_profile == super::InputProfile::TeX8Bit && let Ok(byte) = u8::try_from(value as u32) { return char::from(table.input(byte)); } value } 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, }) } /// Built-in meanings before any macro, alias or format assignments. pub(super) fn original_primitive<'a>( &self, name: &'a CommandName, ) -> Option<(&'a str, &'static Meaning)> { use super::InputProfile; use std::sync::OnceLock; type CommandCatalogue = OnceLock>; static CATALOGUES: [[CommandCatalogue; 2]; 3] = [const { [const { OnceLock::new() }; 2] }; 3]; let input = match self.input_profile { InputProfile::TeX8Bit => 0, InputProfile::UnicodeScalar => 1, InputProfile::XeTeX => 2, }; let name = match name { CommandName::Control(name) | CommandName::FrozenPrimitive(name) => name.as_str(), CommandName::FrozenPrimitivePrefix => self.primitive_prefix_name(), CommandName::FrozenRelax => "relax", CommandName::Font(FontId::NULL) => "nullfont", _ => return None, }; let extended = self.profile == Profile::EtexBootstrap; CATALOGUES[input][usize::from(extended)] .get_or_init(|| { let state = Self::initex().with_input_profile(self.input_profile); let state = if extended { state.with_etex() } else { state }; Arc::unwrap_or_clone(state.commands) .shards .into_iter() .flat_map(|shard| Arc::unwrap_or_clone(shard).entries) .filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) { CommandName::Control(name) => Some((name, meaning)), _ => None, }) .collect() }) .get(name) .map(|meaning| (name, meaning)) } fn command_bindings_mut(&mut self) -> &mut CommandBindings { Arc::make_mut(&mut self.commands) } pub(super) fn command_revision(&self, hash: u64) -> u64 { self.commands.revisions[CommandBindings::shard_index(hash)] } pub fn meaning(&self, name: &CommandName) -> Meaning { self.meaning_hashed(name, command_hasher().hash_one(name)) } pub(super) fn meaning_hashed(&self, name: &CommandName, hash: u64) -> Meaning { match name { CommandName::FrozenRelax => Meaning::Primitive(Primitive::Relax), CommandName::FrozenPrimitivePrefix => Meaning::Primitive(Primitive::DeferredPrimitive), CommandName::FrozenPrimitive(_) => self.original_primitive(name) .map(|(_, meaning)| meaning.clone()).unwrap_or(Meaning::Undefined), CommandName::Font(font) => Meaning::Font(*font), _ => self.commands.get_hashed(name, hash).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, 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, 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(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)> + 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.command_bindings_mut().insert(name.into(), value); } None => { self.command_bindings_mut().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::LinePenalties(kind), Saved::LinePenalties(values)) => match values { Some(values) => { self.line_penalties.insert(kind, values); } None => { self.line_penalties.remove(&kind); } }, (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::LinePenalties(kind) => Saved::LinePenalties(self.line_penalties.get(kind).cloned()), 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.command_bindings_mut().insert(name.into(), 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); } } }