Implement pdfTeX random primitives with checkpointed state
This commit is contained in:
1 parent
a958954308
commit
5c2ba9fad0
13 files changed
+230
-8
No files matched your search
@@ -876,6 +876,22 @@ impl Executor {
|
||||
return self
|
||||
.fail("pdfTeX regular expressions are unavailable on this host");
|
||||
}
|
||||
Pdfuniformdeviate => {
|
||||
let bound = self.integer(files)?;
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
let value = self.state.random().uniform(bound);
|
||||
self.print_tokens(&value.to_string(), token)?;
|
||||
}
|
||||
Pdfnormaldeviate => {
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
let value = loop {
|
||||
self.tick()?;
|
||||
if let Some(value) = self.state.random().normal_trial() {
|
||||
break value;
|
||||
}
|
||||
};
|
||||
self.print_tokens(&value.to_string(), token)?;
|
||||
}
|
||||
Pdfcolorstackinit => {
|
||||
let stack = self.init_pdf_color_stack(files)?;
|
||||
self.print_tokens(&stack.to_string(), token)?;
|
||||
@@ -2098,6 +2114,10 @@ impl Executor {
|
||||
Meaning::Primitive(Primitive::Interactionmode) => Ok(self.interaction_mode_value()),
|
||||
Meaning::Primitive(Primitive::Pdftexversion) => Ok(Self::PDFTEX_VERSION),
|
||||
Meaning::Primitive(Primitive::Pdfshellescape) => Ok(Self::SHELL_ESCAPE),
|
||||
Meaning::Primitive(Primitive::Pdfrandomseed) => {
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
Ok(self.state.random_seed())
|
||||
}
|
||||
Meaning::Primitive(Primitive::Pdflastobj) => {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last()))
|
||||
@@ -3717,6 +3737,11 @@ impl Executor {
|
||||
Pdfstartlink | Pdfendlink | Pdfdest => {
|
||||
self.scan_pdf_link(primitive, token.span, files)?;
|
||||
}
|
||||
Pdfsetrandomseed => {
|
||||
let seed = self.integer(files)?;
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
self.state.reseed_random(seed);
|
||||
}
|
||||
Pdfobj => self.scan_pdf_object(false, files)?,
|
||||
Pdfrefobj => self.scan_pdf_object_reference(token.span, files)?,
|
||||
Pdfcatalog => self.scan_pdf_catalog(files)?,
|
||||
|
||||
@@ -207,6 +207,7 @@ impl Executor {
|
||||
| Primitive::Month
|
||||
| Primitive::Year
|
||||
| Primitive::Inputlineno
|
||||
| Primitive::Pdfrandomseed
|
||||
| Primitive::Pdflastobj
|
||||
| Primitive::Pdflastximage
|
||||
| Primitive::Pdflastximagepages
|
||||
|
||||
@@ -8,8 +8,8 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 34;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 6] = [27, 28, 31, 32, 33, SCHEMA];
|
||||
const SCHEMA: u32 = 35;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 7] = [27, 28, 31, 32, 33, 34, SCHEMA];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -26,6 +26,8 @@ pub struct JobTime {
|
||||
pdf_clock: Option<(u8, i16)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pdf_calendar: Option<(i32, i32, i32, i32)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) random_seed: Option<i32>,
|
||||
}
|
||||
impl JobTime {
|
||||
pub fn new(year: i32, month: i32, day: i32, minutes: i32) -> Result<Self, &'static str> {
|
||||
@@ -47,8 +49,15 @@ impl JobTime {
|
||||
minutes,
|
||||
pdf_clock: None,
|
||||
pdf_calendar: None,
|
||||
random_seed: None,
|
||||
})
|
||||
}
|
||||
/// Fix the job's initial pdfTeX random sequence across equivalent runs.
|
||||
pub fn with_random_seed(mut self, seed: i32) -> Self {
|
||||
self.random_seed = Some(seed.saturating_abs());
|
||||
self
|
||||
}
|
||||
|
||||
/// Add the seconds and UTC offset supplied by the job host.
|
||||
pub fn with_pdf_clock(
|
||||
mut self,
|
||||
|
||||
@@ -33,6 +33,7 @@ mod page_builder;
|
||||
mod paragraph;
|
||||
mod paragraph_trace;
|
||||
mod parameters;
|
||||
mod random;
|
||||
mod reconstitute;
|
||||
mod registers;
|
||||
mod rule;
|
||||
@@ -409,6 +410,7 @@ pub enum Dependency {
|
||||
JobParameter(JobParameter),
|
||||
JobName,
|
||||
PdfCreationDate,
|
||||
PdfRandomState,
|
||||
FileLookup {
|
||||
name: String,
|
||||
from: String,
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! The pdfTeX random primitives share a job-owned fixed-point sequence.
|
||||
//! Both draws and explicit reseeding become part of a saved continuation.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const FRACTION: i64 = 1 << 28;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct Random {
|
||||
seed: i32,
|
||||
values: Vec<i64>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl Random {
|
||||
pub(super) fn new(seed: i32) -> Self {
|
||||
let seed = seed.saturating_abs();
|
||||
let mut previous = i64::from(seed);
|
||||
while previous >= FRACTION {
|
||||
previous /= 2;
|
||||
}
|
||||
let mut delta = 1;
|
||||
let mut state = Self {
|
||||
seed,
|
||||
values: vec![0; 55],
|
||||
position: 0,
|
||||
};
|
||||
for index in 0..55 {
|
||||
(previous, delta) = (delta, (previous - delta).rem_euclid(FRACTION));
|
||||
state.values[(index * 21) % 55] = previous;
|
||||
}
|
||||
for _ in 0..3 {
|
||||
state.advance();
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub(super) fn seed(&self) -> i32 {
|
||||
self.seed
|
||||
}
|
||||
|
||||
fn advance(&mut self) {
|
||||
for i in 0..55 {
|
||||
let offset = if i < 24 { i + 31 } else { i - 24 };
|
||||
self.values[i] = (self.values[i] - self.values[offset]).rem_euclid(FRACTION);
|
||||
}
|
||||
self.position = 54;
|
||||
}
|
||||
|
||||
fn next(&mut self) -> i64 {
|
||||
if self.position == 0 {
|
||||
self.advance();
|
||||
} else {
|
||||
self.position -= 1;
|
||||
}
|
||||
self.values[self.position]
|
||||
}
|
||||
|
||||
pub(super) fn uniform(&mut self, bound: i32) -> i32 {
|
||||
let value = rounded_quotient(i64::from(bound) * self.next(), FRACTION) as i32;
|
||||
if value == bound { 0 } else { value }
|
||||
}
|
||||
|
||||
/// One trial of the ratio method. The executor can cancel or charge work
|
||||
/// between trials, including trials rejected before the logarithm.
|
||||
pub(super) fn normal_trial(&mut self) -> Option<i32> {
|
||||
let offset = self.next() - FRACTION / 2;
|
||||
let x = rounded_quotient(112_429 * offset, FRACTION);
|
||||
let uniform = self.next();
|
||||
if x.abs() >= uniform {
|
||||
return None;
|
||||
}
|
||||
let sample = rounded_quotient(x * FRACTION, uniform);
|
||||
let log = 139_548_960 - fixed_log(uniform);
|
||||
(sample * sample <= 1024 * log).then_some(sample as i32)
|
||||
}
|
||||
}
|
||||
|
||||
fn rounded_quotient(numerator: i64, denominator: i64) -> i64 {
|
||||
numerator.signum() * ((numerator.abs() + denominator / 2) / denominator)
|
||||
}
|
||||
|
||||
/// Fixed-point logarithm used by the ratio acceptance test. Computing a
|
||||
/// floating-point log here can select a different trial and change later draws.
|
||||
fn fixed_log(mut sample: i64) -> i64 {
|
||||
const LOGARITHMS: [i64; 13] = [
|
||||
93_032_640, 38_612_034, 17_922_280, 8_662_214, 4_261_238, 2_113_709, 1_052_693, 525_315,
|
||||
262_400, 131_136, 65_552, 32_772, 16_385,
|
||||
];
|
||||
const FLOOR: i64 = 4 * FRACTION;
|
||||
let mut result = 1_302_456_860 - 100;
|
||||
let mut remainder = 27_595 + 6_553_600;
|
||||
while sample < FLOOR {
|
||||
sample *= 2;
|
||||
result -= 93_032_639;
|
||||
remainder -= 48_782;
|
||||
}
|
||||
result += remainder / 65_536;
|
||||
let mut bit = 2;
|
||||
while sample > FLOOR + 4 {
|
||||
let mut amount = ((sample - 1) >> bit) + 1;
|
||||
while sample < FLOOR + amount {
|
||||
amount = (amount + 1) / 2;
|
||||
bit += 1;
|
||||
}
|
||||
result += match bit {
|
||||
1..=13 => LOGARITHMS[bit - 1],
|
||||
14..=27 => 1 << (27 - bit),
|
||||
_ => 1,
|
||||
};
|
||||
sample -= amount;
|
||||
}
|
||||
result / 8
|
||||
}
|
||||
@@ -322,6 +322,10 @@ pub enum Primitive {
|
||||
Pdfobj,
|
||||
Pdfrefobj,
|
||||
Pdflastobj,
|
||||
Pdfrandomseed,
|
||||
Pdfsetrandomseed,
|
||||
Pdfuniformdeviate,
|
||||
Pdfnormaldeviate,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -374,6 +378,8 @@ impl Primitive {
|
||||
| Pdfstrcmp
|
||||
| Pdfmatch
|
||||
| Pdflastmatch
|
||||
| Pdfuniformdeviate
|
||||
| Pdfnormaldeviate
|
||||
| Pdfcolorstackinit
|
||||
| Csname
|
||||
| Unless
|
||||
@@ -590,6 +596,10 @@ pub struct State {
|
||||
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>,
|
||||
@@ -718,6 +728,8 @@ impl Default for State {
|
||||
pdf_file_options: None,
|
||||
pdf_catalog: None,
|
||||
pdf_objects: None,
|
||||
initial_random_seed: None,
|
||||
random: None,
|
||||
pdf_info: Vec::new(),
|
||||
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
|
||||
hyphenation: super::hyphenation::HyphenationData::default(),
|
||||
@@ -946,6 +958,10 @@ impl Default for State {
|
||||
("pdfobj", Pdfobj),
|
||||
("pdfrefobj", Pdfrefobj),
|
||||
("pdflastobj", Pdflastobj),
|
||||
("pdfrandomseed", Pdfrandomseed),
|
||||
("pdfsetrandomseed", Pdfsetrandomseed),
|
||||
("pdfuniformdeviate", Pdfuniformdeviate),
|
||||
("pdfnormaldeviate", Pdfnormaldeviate),
|
||||
("pdfcolorstack", Pdfcolorstack),
|
||||
("pdfsave", Pdfsave),
|
||||
("pdfstartlink", Pdfstartlink),
|
||||
@@ -1212,8 +1228,24 @@ impl State {
|
||||
pub fn with_job_time(mut self, time: JobTime) -> Self {
|
||||
self.job_parameters.extend(time.parameters());
|
||||
self.pdf_creation_date = time.pdf_creation_date();
|
||||
self.initial_random_seed = time.random_seed;
|
||||
self.random = None;
|
||||
self
|
||||
}
|
||||
pub(super) fn random_seed(&self) -> i32 {
|
||||
self.random.as_deref().map_or_else(
|
||||
|| self.initial_random_seed.unwrap_or_default(),
|
||||
super::random::Random::seed,
|
||||
)
|
||||
}
|
||||
pub(super) fn reseed_random(&mut self, seed: i32) {
|
||||
self.random = Some(Box::new(super::random::Random::new(seed)));
|
||||
}
|
||||
pub(super) fn random(&mut self) -> &mut super::random::Random {
|
||||
self.random.get_or_insert_with(|| {
|
||||
Box::new(super::random::Random::new(self.initial_random_seed.unwrap_or_default()))
|
||||
})
|
||||
}
|
||||
pub fn job_parameter(&self, parameter: JobParameter) -> Option<i32> {
|
||||
self.job_parameters.get(¶meter).copied()
|
||||
}
|
||||
@@ -1336,6 +1368,8 @@ impl State {
|
||||
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;
|
||||
|
||||
Reference in new issue
Block a user