1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! What the frontend knows of the registers while it is lowering.
//!
//! A register is a VM slot, so its value is the run's -- except that a
//! straight-line program is run in the order it is lowered, and `\dimen0=3pt`
//! followed by `\kern\dimen0` is a kern of 3pt whatever else the program does.
//! TeX itself has no such split: `tex.web` §413's `scan_something_internal`
//! reads `eqtb` at the moment the mouth reaches the register, which is the
//! moment this follows. So this table is the engine's `eqtb` for the
//! registers, as far as it can be followed, and it is the one both halves of
//! the frontend read: the lowerer, deciding a `\ifnum` while lowering when
//! both operands are known, and the expander, freezing `\number\count2` into
//! an `\edef` body or a `\csname` as §366 does.
//!
//! Three states per register. Never assigned, so INITEX's zero (the code
//! generator writes zero into every slot first). Assigned to a value this
//! tracked. Assigned to something it could not follow -- a `\rustcall`, whose
//! value only the run has -- which is unknown and makes whatever depends on it
//! a run-time branch rather than a guess.
use crate::ir::{Arith, Cmd, Num};
#[derive(Default, Clone)]
pub struct Known {
map: rustc_hash::FxHashMap<i64, Option<i64>>,
/// Every change, with what it replaced, so a group or a conditional arm
/// can put the state back without cloning the table.
trail: Vec<(i64, Option<Option<i64>>)>,
/// The value each register's last `\global` assignment left (§283): what
/// a group that assigned it globally leaves behind when it ends, however
/// a later local assignment in the group changed it.
globals: rustc_hash::FxHashMap<i64, Option<i64>>,
/// Know nothing at all, for code that runs at a time the lowerer cannot
/// place: the output routine, which the page builder fires.
opaque: bool,
}
impl Known {
/// Know nothing (or know again), returning which it was.
pub fn set_opaque(&mut self, on: bool) -> bool {
std::mem::replace(&mut self.opaque, on)
}
/// The value of `slot`, if it is known.
pub fn get(&self, slot: i64) -> Option<i64> {
// The stomach writes its slots while the program runs
// (`crate::stomach::Mirror`), so nothing here can know them.
if self.opaque || crate::compiler::is_stomach_slot(slot) {
return None;
}
match self.map.get(&slot) {
Some(v) => *v,
None => Some(crate::params::initial_value(slot)),
}
}
pub fn set(&mut self, slot: i64, value: Option<i64>) {
let old = self.map.insert(slot, value);
self.trail.push((slot, old));
}
/// Where the trail stands, for [`Known::undo_to`].
pub fn mark(&self) -> usize {
self.trail.len()
}
/// Put back everything changed since `mark`, or only `only` of it.
pub fn undo_to(&mut self, mark: usize, only: Option<&[i64]>) {
while self.trail.len() > mark {
let (slot, old) = self.trail.pop().expect("longer than the mark");
if only.is_some_and(|set| !set.contains(&slot)) {
continue;
}
match old {
Some(v) => self.map.insert(slot, v),
None => self.map.remove(&slot),
};
}
}
/// Forget every value, back to INITEX's zeros: what a format load does
/// before it puts its own registers in.
pub fn clear(&mut self) {
self.map.clear();
self.trail.clear();
self.globals.clear();
}
/// What register `slot`'s last `\global` assignment left, if one was
/// followed.
pub fn global_value(&self, slot: i64) -> Option<i64> {
self.globals.get(&slot).copied().flatten()
}
/// The known count registers that are not zero, in register order -- what
/// a format dumps and what a `\directlua` chunk's `tex.count` reads.
pub fn counts(&self) -> Vec<(i64, i64)> {
let mut out: Vec<(i64, i64)> = self
.map
.iter()
.filter(|(slot, _)| crate::compiler::is_count_slot(**slot))
.filter_map(|(slot, v)| v.filter(|v| *v != 0).map(|v| (*slot, v)))
.collect();
out.sort_unstable();
out
}
/// Every slot whose value is known and not zero: the whole slot file, so
/// a `\directlua` chunk's `tex.dimen` and `tex.skip` read from the same
/// table its `tex.count` does.
pub fn values(&self) -> std::collections::HashMap<i64, i64> {
self.map
.iter()
.filter_map(|(slot, v)| v.filter(|v| *v != 0).map(|v| (*slot, v)))
.collect()
}
/// What a number is, if every register it reads is known.
///
/// The products are the run's own (`b_scale_dimen` and the checked
/// multiply the code generator emits for a negated factor): a value
/// computed here that differed from the one the VM computes would decide
/// a conditional the run then contradicts. A product the run would report
/// as too large is not followed.
pub fn num(&self, n: &Num) -> Option<i64> {
match n {
Num::Literal(v) => Some(*v),
Num::Count(s) => self.get(*s),
Num::Neg(s) => self.get(*s).map(|v| -v),
Num::Scaled { int, frac, reg } => {
crate::dimen::scale_by_factor_checked(*int, *frac, self.get(*reg)?).ok()
}
Num::ByCount { factor, sign, unit } => {
let unit = self.num(unit)?;
let factor = match *sign < 0 {
true => self.get(*factor)?.checked_mul(-1)?,
false => self.get(*factor)?,
};
crate::dimen::scale_by_factor_checked(factor, 0, unit).ok()
}
Num::Rust { .. } => None,
// The run's own arithmetic (`b_expr_step`), and an expression
// the run would report as overflowing is not followed.
Num::Expr { op, max, args } => {
let values: Option<Vec<i64>> = args.iter().map(|a| self.num(a)).collect();
Some(crate::etex_arith::apply(*op, *max, &values?))
}
Num::ExprEnd { value, .. } => match self.num(value)? {
crate::etex_arith::ERROR => None,
v => Some(v),
},
}
}
/// Follow one lowered command.
#[inline(never)]
pub fn apply(&mut self, cmd: &Cmd) {
const LIMIT: i64 = i32::MAX as i64;
match cmd {
Cmd::SetCount(reg, n) => {
let v = self.num(n);
self.set(*reg, v);
}
Cmd::Arith(op, reg, n) => {
let next = match (self.get(*reg), self.num(n)) {
(Some(cur), Some(by)) => match op {
Arith::Add => Some(cur.wrapping_add(by)),
Arith::Mul => cur.checked_mul(by),
Arith::Div if by != 0 => Some(cur / by),
Arith::Div => None,
},
_ => None,
};
self.set(*reg, next.filter(|v| v.abs() <= LIMIT));
}
// All three components or none (§1236), by the run's own rule.
Cmd::GlueArith(op, base, n) => {
let which = match op {
Arith::Div => 1,
_ => 2,
};
let by = self.num(n);
let parts: Vec<Option<i64>> = (0..3)
.map(|k| crate::runtime::arith_checked(self.get(base + k)?, by?, which))
.collect();
let unknown = parts.iter().any(|p| p.is_none());
for (k, p) in (0..3).zip(parts) {
let next = match unknown {
// An overflow leaves the glue as it was; a component
// that was not known leaves nothing known.
true if by.is_some() && (0..3).all(|j| self.get(base + j).is_some()) => {
self.get(base + k)
}
true => None,
false => p,
};
self.set(base + k, next);
}
}
// A group puts its registers back itself, where it is lowered.
Cmd::Group { .. } => {}
// Just after a `\global` assignment: its value is the one the
// groups around it leave.
Cmd::KeepGlobal { reg, .. } => {
let v = self.get(*reg);
self.globals.insert(*reg, v);
}
// The output routine runs whenever the page builder fires it, so
// what it assigns is not known after any point of the document.
Cmd::OutputRoutine(Some(body)) => {
for reg in crate::lower::assigned_counts(body) {
self.set(reg, None);
}
}
// Which arm runs, and how often, is the run's.
Cmd::IfNum { .. } | Cmd::IfOdd { .. } | Cmd::Loop { .. } => {
for reg in crate::lower::assigned_counts(std::slice::from_ref(cmd)) {
self.set(reg, None);
}
}
_ => {}
}
}
}