Files
texrra-engine/crates/texrra-tex-core/src/execution/state.rs
T

3557 lines
124 KiB
Rust

mod fingerprint;
pub(super) mod source_relocation;
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::{HashMap, hash_map::RawEntryMut};
use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
use std::sync::{Arc, Mutex, 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<usize> {
use Primitive::*;
Some(match self {
Pagegoal => 0,
Pagetotal => 1,
Pagestretch => 2,
Pagefilstretch => 3,
Pagefillstretch => 4,
Pagefilllstretch => 5,
Pageshrink => 6,
Pagedepth => 7,
_ => return None,
})
}
pub(super) fn expandable(self) -> bool {
use Primitive::*;
self.conditional()
|| matches!(
self,
Splitfirstmark
| Splitbotmark
| Splitfirstmarks
| Splitbotmarks
| Topmark
| Firstmark
| Botmark
| Topmarks
| Firstmarks
| Botmarks
| Noexpand
| 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<TokenKind>,
/// One delimiter per argument; an empty delimiter means undelimited.
pub parameters: Vec<Vec<TokenKind>>,
pub parameter_chars: Vec<char>,
pub replacement: Vec<Replacement>,
pub long: bool,
pub outer: bool,
pub protected: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum Meaning {
Undefined,
Primitive(Primitive),
Macro(std::sync::Arc<Macro>),
Character(TokenKind),
Count(u16),
Toks(u16),
TokenParameter(TokenParameter),
CharGiven(u32),
MathCharGiven(u16),
Register(Register),
Parameter(Parameter),
Font(FontId),
UnicodeMathCharGiven(super::MathCode),
}
/// 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<Meaning>),
Catcode(Option<CatCode>),
Integer(i32),
Tokens(Option<Vec<Token>>),
Hook(Option<std::sync::Arc<[Token]>>),
Job(Option<i32>),
Register(Option<RegisterValue>),
Parameter(Option<ParameterValue>),
ParagraphShape(std::sync::Arc<[super::paragraph::ParagraphShapeLine]>),
LinePenalties(Option<std::sync::Arc<[i32]>>),
Font(FontId),
Box(Option<NativeBox>),
Mathcode(Option<super::MathCode>),
Delcode(Option<i32>),
Sfcode(Option<u16>, Option<u16>),
XeInterCharTokens(Option<std::sync::Arc<[Token]>>),
CaseCode(Option<u32>),
Mathfont(Option<FontId>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) enum GroupKind {
Simple,
SemiSimple,
Hbox,
AdjustedHbox,
Vbox,
Vtop,
MathShift,
MathGroup,
MathChoice,
MathLeft,
Discretionary,
Insertion,
Output,
Align,
NoAlign,
Vcenter,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
struct Group {
kind: GroupKind,
#[serde(default)]
origin: Option<(usize, usize)>,
after: Vec<Token>,
#[serde(with = "ordered_map")]
saved: BTreeMap<Key, Saved>,
#[serde(default)]
save_order: Vec<Key>,
}
pub(super) struct GroupRestore {
pub entries: Vec<(Key, Option<Saved>)>,
pub after: Vec<Token>,
}
// JSON objects cannot represent enum keys. Sequence encoding preserves the
// separate active/control namespaces and deterministic order for state images.
mod ordered_map {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
pub fn serialize<K: Serialize, V: Serialize, S: Serializer>(
map: &BTreeMap<K, V>,
serializer: S,
) -> Result<S::Ok, S::Error> {
map.iter().collect::<Vec<_>>().serialize(serializer)
}
pub fn deserialize<
'de,
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
D: Deserializer<'de>,
>(
deserializer: D,
) -> Result<BTreeMap<K, V>, D::Error> {
Ok(Vec::<(K, V)>::deserialize(deserializer)?
.into_iter()
.collect())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
enum PdftexRevision {
// A format created before revision identity was stored bootstrapped with 22.
#[default]
#[serde(rename = "22")]
R22,
#[serde(rename = "24")]
R24,
}
// A single definition after a checkpoint copies its shard. Smaller shards
// keep that copy proportional to the modified part of the command table.
const COMMAND_SHARDS: usize = 128;
type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)]
struct CommandShard {
entries: CommandEntries,
// Keep conservative bounds as each meaning is installed. Checkpoints
// share the bounds along with the entries, so proving a source move does
// not have to discover them from every macro body in each donor.
// Replacing or removing an entry may retain its bound.
source_bounds: BTreeMap<usize, Option<usize>>,
}
impl CommandShard {
fn new(hasher: RandomState) -> Self {
Self { entries: CommandEntries::with_hasher(hasher), source_bounds: BTreeMap::new() }
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) -> Option<Meaning> {
let hash = self.entries.hasher().hash_one(name.as_ref());
self.insert_hashed(name, meaning, hash)
}
fn insert_hashed(
&mut self,
name: Arc<CommandName>,
meaning: Meaning,
hash: u64,
) -> Option<Meaning> {
source_relocation::include_meaning_bounds(&mut self.source_bounds, &meaning);
match self.entries.raw_entry_mut().from_key_hashed_nocheck(hash, name.as_ref()) {
RawEntryMut::Occupied(mut entry) => Some(std::mem::replace(entry.get_mut(), meaning)),
RawEntryMut::Vacant(entry) => {
entry.insert_hashed_nocheck(hash, name, meaning);
None
}
}
}
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning) -> bool {
let hashbrown::hash_map::Entry::Vacant(entry) = self.entries.entry(name) else {
return false;
};
source_relocation::include_meaning_bounds(&mut self.source_bounds, &meaning);
entry.insert(meaning);
true
}
}
impl PartialEq for CommandShard {
fn eq(&self, other: &Self) -> bool {
if self.entries.len() != other.entries.len() {
return false;
}
// Copy-on-write shards with only value changes can keep their bucket
// order. Verify each key before comparing its meaning.
for ((name, meaning), (other_name, other_meaning)) in self.entries.iter().zip(&other.entries) {
if name != other_name {
return self.entries == other.entries;
}
if meaning != other_meaning {
return false;
}
}
true
}
}
impl Eq for CommandShard {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
const COMMAND_HASH_CHECKPOINT_STRIDE: usize = 128;
#[derive(Debug)]
struct CommandHashCheckpoints {
blocks: Vec<DefaultHasher>,
end: DefaultHasher,
}
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<RandomState> = OnceLock::new();
HASHER.get_or_init(RandomState::new)
}
#[derive(Clone, Debug)]
struct CommandBindings {
shards: [Arc<CommandShard>; COMMAND_SHARDS],
revisions: [u64; COMMAND_SHARDS],
// Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
hash_checkpoints: OnceLock<Arc<CommandHashCheckpoints>>,
}
impl Default for CommandBindings {
fn default() -> Self {
let hasher = command_hasher();
Self {
shards: std::array::from_fn(|_| {
Arc::new(CommandShard::new(hasher.clone()))
}),
revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(),
fingerprint_inputs: Arc::default(),
hash_checkpoints: OnceLock::new(),
}
}
}
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.get_hashed_entry(name, hash).map(|(_, meaning)| meaning)
}
fn get_hashed_entry(
&self,
name: &CommandName,
hash: u64,
) -> Option<(&Arc<CommandName>, &Meaning)> {
self.shards[Self::shard_index(hash)]
.entries
.raw_entry()
.from_key_hashed_nocheck(hash, name)
}
fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard {
let index = Self::shard_index(command_hasher().hash_one(name));
self.revisions[index] += 1;
self.hash_checkpoints.take();
Arc::make_mut(&mut self.shards[index])
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) {
let hash = command_hasher().hash_one(name.as_ref());
let index = Self::shard_index(hash);
let shard = &mut self.shards[index];
// The caller already saved or cleared the group entry. The shared
// shard can stay in place when the installed binding is identical.
if Arc::strong_count(shard) > 1
&& shard.entries.raw_entry().from_key_hashed_nocheck(hash, name.as_ref())
.is_some_and(|(_, previous)| match (previous, &meaning) {
(Meaning::Macro(previous), Meaning::Macro(body)) => Arc::ptr_eq(previous, body),
(previous, meaning) => previous == meaning,
})
{
return;
}
self.revisions[index] += 1;
self.hash_checkpoints.take();
if Arc::make_mut(shard).insert_hashed(name, meaning, hash).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<Item = (&Arc<CommandName>, &Meaning)> {
self.shards.iter().flat_map(|shard| shard.entries.iter())
}
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &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 CommandBindings {
fn first_changed_binding(&self, prior: &Self) -> Option<usize> {
// Value overwrites can retain the order object. Insertion and
// removal replace it before a different ordered key set is used.
if !Arc::ptr_eq(&self.ordered_names, &prior.ordered_names) {
return None;
}
let names = prior.ordered_names.get()?;
let mut first = None;
for (current, old) in self.shards.iter().zip(&prior.shards) {
if Arc::ptr_eq(current, old) {
continue;
}
for (name, meaning) in &current.entries {
if first.is_some_and(|first| name >= first) {
continue;
}
let unchanged = match (meaning, old.entries.get(name)?) {
(Meaning::Macro(current), Meaning::Macro(old)) => Arc::ptr_eq(current, old),
(current, old) => current == old,
};
if !unchanged {
first = Some(name);
}
}
}
match first {
Some(name) => names.binary_search_by(|(key, _)| key.cmp(name)).ok(),
None => Some(names.len()),
}
}
fn hash_fingerprint(&self, hasher: &mut FingerprintHasher, prior: Option<&Self>) {
if let Some(checkpoints) = self.hash_checkpoints.get() {
hasher.restore(&checkpoints.end);
return;
}
let entries = self.ordered();
let count = entries.len();
let donor = prior.and_then(|prior| {
let checkpoints = prior.hash_checkpoints.get()?;
Some((self.first_changed_binding(prior)?, checkpoints))
});
if let Some((first, donor)) = donor
&& first == count
{
hasher.restore(&donor.end);
let _ = self.hash_checkpoints.set(donor.clone());
return;
}
let mut blocks = Vec::with_capacity(count / COMMAND_HASH_CHECKPOINT_STRIDE + 1);
let offset = if let Some((first, donor)) = donor {
let index = first / COMMAND_HASH_CHECKPOINT_STRIDE;
blocks.extend_from_slice(&donor.blocks[..=index]);
hasher.restore(&donor.blocks[index]);
index * COMMAND_HASH_CHECKPOINT_STRIDE
} else {
count.hash(hasher);
blocks.push(hasher.checkpoint());
0
};
let mut inputs = self.fingerprint_inputs.try_lock().ok();
if let Some(inputs) = &mut inputs {
inputs.prune_if_full();
}
for (index, (name, meaning)) in entries.enumerate().skip(offset) {
name.hash(hasher);
if let Some(inputs) = &mut inputs {
inputs.hash_meaning(meaning, hasher);
} else {
meaning.hash(hasher);
}
if (index + 1) % COMMAND_HASH_CHECKPOINT_STRIDE == 0 {
blocks.push(hasher.checkpoint());
}
}
let end = hasher.checkpoint();
let _ = self.hash_checkpoints.set(Arc::new(CommandHashCheckpoints { blocks, end }));
}
}
impl Hash for CommandBindings {
fn hash<H: Hasher>(&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<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.ordered())
}
}
impl<'de> serde::Deserialize<'de> for CommandBindings {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let entries = <Vec<(Arc<CommandName>, Meaning)> as serde::Deserialize>::deserialize(
deserializer,
)?;
let mut bindings = Self::default();
for (name, meaning) in entries {
bindings.insert(name, meaning);
}
Ok(bindings)
}
}
// Derive the ordinary hash and emit the specialized fingerprint in the
// same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state {
($( $(#[$metadata:meta])* $access:vis $field:ident: $ty:ty, )*) => {
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard.
commands: Arc<CommandBindings>,
$( $(#[$metadata])* $access $field: $ty, )*
}
impl State {
pub fn fingerprint(&self) -> u64 {
self.fingerprint_with_prior(None)
}
pub(super) fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 {
let mut hash = FingerprintHasher::default();
self.commands.hash_fingerprint(&mut hash, prior.map(|prior| prior.commands.as_ref()));
$(self.$field.hash(&mut hash);)*
hash.finish()
}
}
};
}
define_state! {
catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>,
toks: BTreeMap<u16, Vec<Token>>,
#[serde(with = "ordered_map")]
pub(super) token_parameters: BTreeMap<TokenParameter, std::sync::Arc<[Token]>>,
profile: Profile,
#[serde(default)]
pdftex_revision: PdftexRevision,
initex: bool,
#[serde(default)]
input_profile: super::InputProfile,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) byte_translation: Option<std::sync::Arc<super::ByteTranslation>>,
#[serde(default)]
pub(super) xe_default_encoding: super::xe_encoding::Encoding,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) xe_line_break_locale: Option<String>,
pub endlinechar: i32,
pub newlinechar: i32,
pub escapechar: i32,
pub globaldefs: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
paragraph_token: Option<CommandName>,
groups: Vec<Group>,
job_parameters: BTreeMap<JobParameter, i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_creation_date: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
initial_random_seed: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
random: Option<Box<super::random::Random>>,
#[serde(with = "ordered_map")]
registers: BTreeMap<Register, RegisterValue>,
parameters: BTreeMap<Parameter, ParameterValue>,
paragraph_shape: std::sync::Arc<[super::paragraph::ParagraphShapeLine]>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
line_penalties: BTreeMap<LinePenaltyKind, std::sync::Arc<[i32]>>,
pub(super) text_font: FontId,
pub(super) fonts: super::FontCatalog,
boxes: BTreeMap<u16, NativeBox>,
pub(super) split_marks: BTreeMap<u16, super::SplitMarks>,
pub(super) page_marks: BTreeMap<u16, super::PageMarks>,
mathcodes: BTreeMap<u32, super::MathCode>,
delcodes: BTreeMap<u32, i32>,
#[serde(default)]
sfcodes: BTreeMap<u32, u16>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
xe_char_classes: BTreeMap<u32, u16>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
xe_inter_char_tokens: BTreeMap<u32, std::sync::Arc<[Token]>>,
#[serde(with = "ordered_map")]
case_codes: BTreeMap<(super::CaseCode, char), u32>,
#[serde(with = "ordered_map")]
mathfonts: BTreeMap<(u8, u8), FontId>,
pub(super) last_badness: i32,
#[serde(default)]
pub(super) pdf_last_position: [i32; 2],
/// TeX prepare_mag freeze, independent of ordinary grouping/assignments.
pub(super) magnification_set: Option<i32>,
pub(super) output_mode_set: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_header_options: Option<crate::pdf_device::PdfHeaderOptions>,
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_copy_imported_fonts: Option<bool>,
#[serde(default, skip_serializing_if = "crate::pdf_device::xdv_destination::Setup::is_default")]
pub(super) xdv_setup: crate::pdf_device::xdv_destination::Setup,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) xdv_navigation: Option<std::sync::Arc<crate::pdf_device::xdv_navigation::Navigation>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_objects: Option<Box<crate::pdf_device::page_resources::PdfObjects>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub(super) pdf_forms: BTreeMap<u32, crate::pdf_device::forms::RegisteredForm>,
pub(super) pdf_info: Vec<u8>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) pdf_pages_attributes: Vec<u8>,
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
#[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 state_fingerprint_resumes_before_the_first_changed_binding() {
let direct = |state: &State| {
let mut hasher = DefaultHasher::new();
state.hash(&mut hasher);
hasher.finish()
};
let mut original = State { commands: Arc::default(), ..State::default() };
let stride = COMMAND_HASH_CHECKPOINT_STRIDE;
let name = |index| CommandName::Control(format!("binding-{index:04}"));
for index in 0..stride * 3 {
original.define(name(index), Meaning::Count(0), true);
}
let original_hash = original.fingerprint();
let mut registers_only = original.clone();
registers_only.counts.insert(101, 7);
assert_eq!(registers_only.fingerprint(), direct(&registers_only));
assert_ne!(registers_only.fingerprint(), original_hash);
let mut revised = original.clone();
let edited = stride * 2 + 3;
revised.define(name(edited), Meaning::Count(1), true);
assert!(revised.commands.hash_checkpoints.get().is_none());
assert_eq!(revised.commands.first_changed_binding(&original.commands), Some(edited));
let revised_hash = revised.fingerprint_with_prior(Some(&original));
assert_eq!(revised_hash, direct(&revised));
assert_ne!(revised_hash, original_hash);
assert_eq!(revised.fingerprint(), revised_hash);
assert_eq!(original.fingerprint(), original_hash);
// A mutation in place must clear the computed checkpoints as well.
revised.define(name(0), Meaning::Count(2), true);
assert!(revised.commands.hash_checkpoints.get().is_none());
assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised));
revised.command_bindings_mut().remove(&name(0));
assert!(revised.commands.first_changed_binding(&original.commands).is_none());
assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised));
}
#[test]
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
use super::Span;
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
let fingerprint = state.fingerprint();
assert_eq!(fingerprint, direct.finish());
fingerprint
};
let first = CommandName::Control("测试命令".into());
let alias = CommandName::Control("命令别名".into());
let mut token = Token::new(
TokenKind::Command(CommandName::Control("αβγ".into())),
Span { source: 2, start: 40, end: 44 },
);
token.invocation = Some(Span { source: 3, start: 99, end: 101 });
let mut body = Arc::new(Macro {
prefix: vec![TokenKind::Character('木', CatCode::Letter)],
parameters: vec![vec![TokenKind::Character('λ', CatCode::Other)]],
parameter_chars: vec!['#'],
replacement: vec![Replacement::Token(token.clone()); 80],
long: true,
outer: false,
protected: true,
});
let mut state = State::default();
state.define(first.clone(), Meaning::Macro(body.clone()), true);
state.define(alias, Meaning::Macro(body.clone()), true);
let original = check(&state);
assert_eq!(Arc::weak_count(&body), 1);
assert_eq!(check(&state), original);
let donor = state.clone();
token.invocation = Some(Span { source: 3, start: 111, end: 113 });
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token.clone());
state.define(first.clone(), Meaning::Macro(body.clone()), true);
assert_ne!(check(&state), original);
assert_eq!(check(&donor), original);
assert_eq!(Arc::weak_count(&body), 1);
token.kind = TokenKind::Command(CommandName::Control("λ".repeat(40_000)));
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
state.define(first, Meaning::Macro(body), true);
let uncached = check(&state);
state.command_bindings_mut().hash_checkpoints.take();
let _held = state.commands.fingerprint_inputs.lock().unwrap();
assert_eq!(state.fingerprint(), uncached);
}
#[test]
fn paired_statistics_keep_aliases_from_changed_to_shared_command_shards() {
use super::statistics::Collector;
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let independent = Arc::new(body.as_ref().clone());
let first = CommandName::Control("common-definition".into());
let second = CommandName::Control("other-common-definition".into());
let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name));
let shared_shards = [shard(&first), shard(&second)];
let edited = (0..COMMAND_SHARDS)
.map(|index| CommandName::Control(format!("edited-alias-{index}")))
.find(|name| !shared_shards.contains(&shard(name)))
.unwrap();
let mut prior = State::default();
prior.define(first, Meaning::Macro(body.clone()), true);
prior.define(second, Meaning::Macro(independent.clone()), true);
prior.define(edited.clone(), Meaning::Macro(body), true);
let mut current = prior.clone();
current.define(edited, Meaning::Macro(independent), true);
assert_eq!(current, prior);
let history = Collector::default();
let (new_counts, old_counts) = current
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert_eq!(new_counts.usage, old_counts.usage);
assert!(!new_counts.has_equivalent_history(&old_counts, &history, &history));
let (same, old_counts) = prior
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert!(same.has_equivalent_history(&old_counts, &history, &history));
}
#[test]
fn paired_statistics_keep_aliases_within_changed_command_shards() {
use super::statistics::Collector;
let first_body = Arc::new(Macro {
prefix: vec![TokenKind::Character('P', CatCode::Letter)],
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let second_body = Arc::new(first_body.as_ref().clone());
let mut names_by_shard: [Vec<CommandName>; COMMAND_SHARDS] = std::array::from_fn(|_| Vec::new());
// At least one shard gets nine names, regardless of the process hash seed.
for index in 0..=8 * COMMAND_SHARDS {
let name = CommandName::Control(format!("paired-binding-{index}"));
let shard = CommandBindings::shard_index(command_hasher().hash_one(&name));
names_by_shard[shard].push(name);
}
let (index, names) = names_by_shard
.into_iter()
.enumerate()
.find(|(_, names)| names.len() >= 9)
.unwrap();
let mut prior = State::default();
let [first, second, edited, rest @ ..] = names.as_slice() else {
unreachable!();
};
prior.define(first.clone(), Meaning::Macro(first_body.clone()), true);
prior.define(second.clone(), Meaning::Macro(second_body.clone()), true);
prior.define(edited.clone(), Meaning::Macro(first_body), true);
for name in rest {
prior.define(name.clone(), Meaning::Count(0), true);
}
let original = &prior.commands.shards[index];
let mut matching = prior.clone();
let matching_shard = Arc::make_mut(&mut matching.command_bindings_mut().shards[index]);
assert!(original.entries.keys().eq(matching_shard.entries.keys()));
let mut reordered = matching.clone();
let changed = Arc::make_mut(&mut reordered.command_bindings_mut().shards[index]);
for capacity in [32, 64, 128, 256, 512, 1024] {
changed.entries.reserve(capacity);
if !original.entries.keys().eq(changed.entries.keys()) {
break;
}
}
assert!(!original.entries.keys().eq(changed.entries.keys()));
let history = Collector::default();
let counts = |state: &State| {
let (live, old_live) = state
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
let mut expected = Collector::default();
state.collect_statistics(&mut expected);
assert_eq!(live.usage, expected.usage);
assert_eq!(live.usage, old_live.usage);
live.has_equivalent_history(&old_live, &history, &history)
};
for (mut current, expect_same_order) in [(matching, true), (reordered, false)] {
assert!(!Arc::ptr_eq(original, &current.commands.shards[index]));
assert_eq!(current, prior);
assert!(counts(&current));
let changed = Arc::make_mut(&mut current.command_bindings_mut().shards[index]);
*changed.entries.get_mut(edited).unwrap() = Meaning::Macro(second_body.clone());
assert_eq!(original.entries.keys().eq(changed.entries.keys()), expect_same_order);
assert_eq!(current, prior);
assert!(!counts(&current));
}
}
#[test]
fn command_shard_equality_checks_values_in_matching_bucket_order() {
let mut before = CommandShard::new(command_hasher().clone());
let name = Arc::new(CommandName::Control("first".into()));
before.insert(name.clone(), Meaning::Count(3));
before.insert(Arc::new(CommandName::Control("second".into())), Meaning::Count(7));
let mut after = before.clone();
assert_eq!(before, after);
*after.entries.get_mut(&name).unwrap() = Meaning::Count(7);
assert!(before.entries.keys().eq(after.entries.keys()));
assert_ne!(before, after);
}
#[test]
fn command_shard_equality_matches_keys_when_bucket_order_differs() {
let mut before = CommandShard::new(command_hasher().clone());
for index in 0..32 {
before.insert(
Arc::new(CommandName::Control(format!("binding-{index}"))),
Meaning::Count(index),
);
}
// Find a genuinely different iteration order for these same bindings
// without depending on a particular hashbrown bucket layout.
let mut after = (0..16)
.find_map(|_| {
let mut candidate = CommandShard::new(RandomState::new());
for (name, meaning) in &before.entries {
candidate.insert(name.clone(), meaning.clone());
}
(!before.entries.keys().eq(candidate.entries.keys())).then_some(candidate)
})
.expect("different hash seeds should give different bucket orders");
assert_eq!(before, after);
let (name, _) = before.entries.keys().zip(after.entries.keys())
.find(|(name, other_name)| name != other_name)
.unwrap();
*after.entries.get_mut(name).unwrap() = Meaning::Count(100);
assert_ne!(before, after);
}
#[test]
fn reinstalling_a_shared_binding_preserves_its_allocation_and_epoch() {
let name = CommandName::Control("sharedbinding".into());
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let mut state = State::default();
state.define(name.clone(), Meaning::Macro(body.clone()), true);
let prior = state.clone();
let hash = command_hasher().hash_one(&name);
let index = CommandBindings::shard_index(hash);
let key = state.commands.get_hashed_entry(&name, hash).unwrap().0.clone();
assert!(Arc::ptr_eq(&key, &state.cache_meaning_hashed(&name, hash).0));
state.define(name.clone(), Meaning::Macro(body.clone()), true);
assert!(Arc::ptr_eq(&state.commands.shards[index], &prior.commands.shards[index]));
assert_eq!(state.command_revision(hash), prior.command_revision(hash));
let independent = Arc::new(body.as_ref().clone());
state.define(name.clone(), Meaning::Macro(independent.clone()), true);
assert!(!Arc::ptr_eq(&state.commands.shards[index], &prior.commands.shards[index]));
assert_eq!(state.command_revision(hash), prior.command_revision(hash) + 1);
let Meaning::Macro(installed) = state.meaning(&name) else { panic!("expected macro") };
assert!(Arc::ptr_eq(&installed, &independent));
assert_eq!(state, prior);
state.begin_group(GroupKind::Simple, None);
state.define(name.clone(), Meaning::Count(5), false);
let local = state.clone();
let saved = Key::Command(name.clone());
assert!(state.groups.last().unwrap().saved.contains_key(&saved));
state.define(name, Meaning::Count(5), true);
assert!(Arc::ptr_eq(&state.commands.shards[index], &local.commands.shards[index]));
assert!(!state.groups.last().unwrap().saved.contains_key(&saved));
}
#[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,
mut current_usage: super::statistics::Collector,
) -> Option<(super::statistics::Collector, super::statistics::Collector)> {
let mut old_usage = if current_usage.material_only() {
current_usage.clone()
} else {
current_usage.usage.state.command_entries = old.commands.len();
let mut changed_macros = Vec::new();
for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) {
if current.entries.len() != prior.entries.len() {
return None;
}
if Arc::ptr_eq(current, prior) {
for (name, meaning) in &prior.entries {
Self::collect_command_statistics(&mut current_usage, name, meaning);
}
continue;
}
let mut ordered = Some(current.entries.iter());
for (name, old_meaning) in &prior.entries {
let meaning = match ordered.as_mut().and_then(Iterator::next) {
Some((current_name, meaning)) if name == current_name => meaning,
_ => {
ordered = None;
current.entries.get(name)?
}
};
if let CommandName::Control(name) = name.as_ref() {
current_usage.usage.state.control_name_bytes += name.len();
}
match (meaning, old_meaning) {
(Meaning::Macro(body), Meaning::Macro(old_body)) => {
current_usage.usage.state.macro_bindings += 1;
if Arc::ptr_eq(body, old_body) {
current_usage.macro_body(body);
} else {
changed_macros.push((body, old_body));
}
}
// Settled suffixes already require equal live meanings.
(Meaning::Macro(_), _) | (_, Meaning::Macro(_)) => return None,
_ => {}
}
}
}
// The same permutation on both sides leaves the alias proof
// intact. Record common allocations first so a later reference
// to any of them still has the original ordinal on both sides.
let mut old_usage = current_usage.clone();
for (body, old_body) in changed_macros {
current_usage.macro_body(body);
old_usage.macro_body(old_body);
}
old_usage
};
self.collect_state_storage(&mut current_usage);
old.collect_state_storage(&mut old_usage);
Some((current_usage, old_usage))
}
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(&parameter)
.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<i32>,
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<super::paragraph::ParagraphShapeLine>,
global: bool,
) {
self.save(Key::ParagraphShape, global);
self.paragraph_shape = shape.into();
}
pub fn text_font(&self) -> FontId {
self.text_font
}
pub(super) fn assign_font(&mut self, font: FontId, global: bool) {
self.save(Key::Font, global);
self.text_font = font;
}
pub fn register(&self, register: Register) -> RegisterValue {
self.registers.get(&register).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(&register);
} else {
self.registers.insert(register, value);
}
}
pub fn with_job_time(mut self, time: JobTime) -> Self {
self.job_parameters.extend(time.parameters());
self.pdf_creation_date = time.pdf_creation_date();
self.initial_random_seed = time.random_seed;
self.random = None;
self
}
pub(super) fn random_seed(&self) -> i32 {
self.random.as_deref().map_or_else(
|| self.initial_random_seed.unwrap_or_default(),
super::random::Random::seed,
)
}
pub(super) fn reseed_random(&mut self, seed: i32) {
self.random = Some(Box::new(super::random::Random::new(seed)));
}
pub(super) fn random(&mut self) -> &mut super::random::Random {
self.random.get_or_insert_with(|| {
Box::new(super::random::Random::new(self.initial_random_seed.unwrap_or_default()))
})
}
pub fn job_parameter(&self, parameter: JobParameter) -> Option<i32> {
self.job_parameters.get(&parameter).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<Token> {
self.toks.get(&index).cloned().unwrap_or_default()
}
pub(super) fn group_kind(&self) -> Option<GroupKind> {
self.groups.last().map(|group| group.kind)
}
pub(super) fn group_type(&self) -> i32 {
match self.group_kind() {
None => 0,
Some(GroupKind::Simple) => 1,
Some(GroupKind::SemiSimple) => 14,
Some(GroupKind::Hbox) => 3,
Some(GroupKind::AdjustedHbox) => 2,
Some(GroupKind::Vbox) => 4,
Some(GroupKind::Vtop) => 5,
Some(GroupKind::MathShift) => 15,
Some(GroupKind::MathGroup) => 9,
Some(GroupKind::MathChoice) => 13,
Some(GroupKind::MathLeft) => 16,
Some(GroupKind::Discretionary) => 10,
Some(GroupKind::Insertion) => 11,
Some(GroupKind::Output) => 8,
Some(GroupKind::Align) => 6,
Some(GroupKind::NoAlign) => 7,
Some(GroupKind::Vcenter) => 12,
}
}
/// INITEX categories before a format establishes normal TeX syntax.
pub fn initex() -> Self {
let mut state = Self::default();
state.initex = true;
state.parameters.clear();
state.text_font = FontId::NULL;
state.newlinechar = 0;
for c in ['{', '}', '$', '&', '#', '^', '_', '~', '\t'] {
state.catcodes.insert(c, CatCode::Other);
}
state
}
pub(super) fn into_format_state(mut self) -> Self {
self.initex = false;
self.job_parameters.clear();
self.pdf_creation_date = None;
self.initial_random_seed = None;
self.random = None;
self.split_marks.clear();
self.page_marks.clear();
self.last_badness = 0;
self.pdf_last_position = [0, 0];
self.magnification_set = None;
self.output_mode_set = None;
self.pdf_header_options = None;
self.pdf_file_options = None;
self.pdf_copy_imported_fonts = None;
self.xdv_setup = Default::default();
self.xdv_navigation = None;
self.pdf_catalog = None;
if !self
.pdf_objects
.as_deref_mut()
.is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_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<crate::pdf_image::PdfImageUse>],
) -> 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<crate::native_font::NativeFont>),
) {
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<std::path::PathBuf, std::path::PathBuf>,
) {
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 &parameter in parameters {
self.update_profile_command(&parameter.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(
&parameter.name(),
Meaning::TokenParameter(parameter),
enabled,
);
}
for &parameter in Parameter::ALL {
if parameter.pdftex_only() {
self.update_profile_command(
&parameter.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(
&parameter.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<BTreeMap<String, Meaning>>;
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 {
self.resolve_meaning_hashed(name, hash).1
}
pub(super) fn cache_meaning_hashed(
&self,
name: &CommandName,
hash: u64,
) -> (Arc<CommandName>, Meaning) {
let (key, meaning) = self.resolve_meaning_hashed(name, hash);
(key.cloned().unwrap_or_else(|| Arc::new(name.clone())), meaning)
}
fn resolve_meaning_hashed(
&self,
name: &CommandName,
hash: u64,
) -> (Option<&Arc<CommandName>>, Meaning) {
let 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),
_ => {
if let Some((key, meaning)) = self.commands.get_hashed_entry(name, hash) {
return (Some(key), meaning.clone());
}
Meaning::Undefined
}
};
(None, meaning)
}
/// Classic projection for byte-table consumers. A code outside the
/// representable classic range has TeX's recovery value of zero.
pub fn mathcode(&self, character: u8) -> u16 {
self.math_code(u32::from(character)).legacy().unwrap_or(0)
}
pub fn math_code(&self, character: u32) -> super::MathCode {
self.mathcodes
.get(&character)
.copied()
.unwrap_or_else(|| super::MathCode::default_for(character))
}
pub(super) fn restore_legacy_mathcodes(&mut self) -> Result<(), String> {
for value in self.mathcodes.values_mut() {
let legacy = u16::try_from(value.word())
.ok()
.filter(|&code| code <= 0x8000)
.ok_or("invalid legacy mathcode in native format")?;
*value = super::MathCode::from_legacy(legacy);
}
Ok(())
}
pub(super) fn math_family_count(&self) -> i32 {
match self.input_profile {
super::InputProfile::TeX8Bit => 16,
super::InputProfile::UnicodeScalar | super::InputProfile::XeTeX => 256,
}
}
pub fn math_font(&self, size: u8, family: u8) -> FontId {
self.mathfonts
.get(&(size, family))
.copied()
.unwrap_or(FontId::NULL)
}
pub fn sfcode(&self, c: u8) -> u16 {
self.space_factor_code(u32::from(c))
}
pub(super) fn space_factor_code(&self, c: u32) -> u16 {
self.sfcodes
.get(&c)
.copied()
.unwrap_or(if (u32::from(b'A')..=u32::from(b'Z')).contains(&c) {
999
} else {
1000
})
}
pub(super) fn assign_sfcode(&mut self, c: u32, value: u16, global: bool) {
self.save(Key::Sfcode(c), global);
self.sfcodes.insert(c, value);
}
pub(super) fn xe_char_class(&self, c: u32) -> u16 {
self.xe_char_classes.get(&c).copied().unwrap_or(0)
}
pub(super) fn assign_xe_char_class(&mut self, c: u32, value: u16, global: bool) {
// XeTeX groups both halves of its space-factor table as one entry.
self.save(Key::Sfcode(c), global);
if value == 0 {
self.xe_char_classes.remove(&c);
} else {
self.xe_char_classes.insert(c, value);
}
}
pub(super) fn xe_inter_char_tokens(&self, index: u32) -> Option<&std::sync::Arc<[Token]>> {
self.xe_inter_char_tokens.get(&index)
}
pub(super) fn assign_xe_inter_char_tokens(
&mut self,
index: u32,
tokens: Vec<Token>,
global: bool,
) {
self.save(Key::XeInterCharTokens(index), global);
if tokens.is_empty() {
self.xe_inter_char_tokens.remove(&index);
} else {
self.xe_inter_char_tokens.insert(index, tokens.into());
}
}
pub fn case_code(&self, kind: super::CaseCode, c: char) -> u32 {
self.case_codes.get(&(kind, c)).copied().unwrap_or_else(|| {
if !c.is_ascii_alphabetic() {
0
} else {
match kind {
super::CaseCode::Lower => c.to_ascii_lowercase() as u32,
super::CaseCode::Upper => c.to_ascii_uppercase() as u32,
}
}
})
}
pub(super) fn assign_case_code(
&mut self,
kind: super::CaseCode,
c: char,
value: u32,
global: bool,
) {
self.save(Key::CaseCode(kind, c), global);
self.case_codes.insert((kind, c), value);
}
pub fn delcode(&self, c: u8) -> i32 {
self.delimiter_code(u32::from(c))
}
pub(super) fn delimiter_code(&self, c: u32) -> i32 {
self.delcodes
.get(&c)
.copied()
.unwrap_or(if c == u32::from(b'.') { 0 } else { -1 })
}
pub(super) fn assign_delcode(&mut self, c: u32, n: i32, global: bool) {
self.save(Key::Delcode(c), global);
self.delcodes.insert(c, n);
}
pub(super) fn assign_mathcode(&mut self, c: u32, n: super::MathCode, global: bool) {
self.save(Key::Mathcode(c), global);
self.mathcodes.insert(c, n);
}
pub(super) fn assign_mathfont(&mut self, size: u8, family: u8, font: FontId, global: bool) {
self.save(Key::Mathfont(size, family), global);
self.mathfonts.insert((size, family), font);
}
pub fn box_register(&self, index: u16) -> Option<&NativeBox> {
self.boxes.get(&index)
}
pub fn split_marks(&self, class: u16) -> Option<&super::SplitMarks> {
self.split_marks.get(&class)
}
pub fn page_marks(&self, class: u16) -> Option<&super::PageMarks> {
self.page_marks.get(&class)
}
pub fn last_badness(&self) -> i32 {
self.last_badness
}
pub(super) fn assign_box(&mut self, index: u16, value: Option<NativeBox>, global: bool) {
self.save(Key::Box(index), global);
self.set_box(index, value);
}
pub(super) fn set_box(&mut self, index: u16, value: Option<NativeBox>) {
if let Some(b) = value {
self.boxes.insert(index, b);
} else {
self.boxes.remove(&index);
}
}
pub(super) fn take_box(&mut self, index: u16) -> Option<NativeBox> {
self.boxes.remove(&index)
}
pub(super) fn box_dimension(&mut self, index: u16, which: Primitive, value: i32) {
if let Some(b) = self.boxes.get_mut(&index) {
match which {
Primitive::Wd => b.width = value as i64,
Primitive::Ht => b.height = value as i64,
Primitive::Dp => b.depth = value as i64,
_ => unreachable!(),
}
}
}
pub fn count(&self, index: u16) -> i32 {
self.counts.get(&index).copied().unwrap_or(0)
}
pub(super) fn set_paragraph_token(&mut self, name: CommandName) {
self.paragraph_token = match &name {
CommandName::Control(value) if value == "par" => None,
_ => Some(name),
};
}
pub(super) fn paragraph_token(&self) -> TokenKind {
let name = self
.paragraph_token
.clone()
.unwrap_or_else(|| CommandName::Control("par".into()));
TokenKind::Command(name)
}
pub(super) fn is_paragraph_token(&self, token: &TokenKind) -> bool {
match (token, &self.paragraph_token) {
(TokenKind::Command(name), Some(paragraph)) => name == paragraph,
(TokenKind::Command(CommandName::Control(name)), None) => name == "par",
_ => false,
}
}
pub fn group_depth(&self) -> usize {
self.groups.len()
}
pub(super) fn font_defaults(&self) -> super::FontIntegers {
super::FontIntegers {
hyphen: self.parameter(Parameter::Defaulthyphenchar).width(),
skew: self.parameter(Parameter::Defaultskewchar).width(),
}
}
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
self.groups.push(Group {
kind,
origin,
after: Vec::new(),
saved: BTreeMap::new(),
save_order: Vec::new(),
});
}
pub(super) fn open_groups(
&self,
) -> impl DoubleEndedIterator<Item = (GroupKind, Option<(usize, usize)>)> + ExactSizeIterator + '_
{
self.groups.iter().map(|group| (group.kind, group.origin))
}
pub(super) fn group_origin(&self) -> Option<(usize, usize)> {
self.groups.last().and_then(|group| group.origin)
}
pub(super) fn save_for_after(&mut self, token: Token) -> bool {
if let Some(group) = self.groups.last_mut() {
group.after.push(token);
true
} else {
false
}
}
pub(super) fn pop_group(&mut self, kind: GroupKind) -> Result<GroupRestore, &'static str> {
let Some(group) = self.groups.last() else {
return Err("extra end group");
};
if group.kind != kind {
return Err("mismatched native group kind");
}
let mut group = self.groups.pop().unwrap();
let mut entries = Vec::with_capacity(group.save_order.len());
for key in group.save_order.into_iter().rev() {
let saved = group.saved.remove(&key);
entries.push((key, saved));
}
// Older execution snapshots had only the keyed saved values.
entries.extend(
group
.saved
.into_iter()
.map(|(key, saved)| (key, Some(saved))),
);
Ok(GroupRestore {
entries,
after: group.after,
})
}
pub(super) fn restore_saved(&mut self, key: Key, value: Saved) {
match (key, value) {
(Key::Command(name), Saved::Command(value)) => match value {
Some(value) => {
self.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(&register);
}
},
(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(&parameter);
}
},
_ => 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<Token>, global: bool) {
self.save(Key::Toks(index), global);
if tokens.is_empty() {
self.toks.remove(&index);
} else {
self.toks.insert(index, tokens);
}
}
fn set_count(&mut self, index: u16, value: i32) {
if value == 0 {
self.counts.remove(&index);
} else {
self.counts.insert(index, value);
}
}
}