retex-engine 1.3.0

The TeX typesetting engine for retex
Documentation
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! TeX dimension arithmetic as pgfmath's basic functions perform it.
//!
//! pgfmath passes numbers between its functions as *strings* (the digits
//! of `\the\dimen` without `pt`, or the digits the user typed) and turns
//! them back into dimensions with assignments like `\pgfmath@x=#1pt`.
//! This module reproduces those assignments ([`scan_unit`], [`scan_factor`],
//! after TeX's `scan_dimen`) and the functions of
//! `pgfmathfunctions.basic.code.tex` built from them, operation by
//! operation. Every case in which TeX would report an error ("Dimension too
//! large", "Missing number", "Arithmetic overflow", a pgfmath error) is a
//! [`Decline`]: the caller then lets the TeX code run.

use retex_arith::{self as arith, UNITY};

/// The TeX code must run instead (it would report an error, or the case is
/// not implemented).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Decline;

/// Result of a native step.
pub type R<T> = Result<T, Decline>;

/// `2^30`: dimensions must stay below this in absolute value.
const DIMEN_LIMIT: i64 = 0o10000000000;
/// TeX's `infinity` for integers.
const INFINITY: i64 = 0o17777777777;

/// A unit after a decimal number in `scan_dimen`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unit {
    /// `pt`.
    Pt,
    /// A unit given by a ratio (`in`, `cm`, …): numerator, denominator.
    Ratio(i32, i32),
    /// `sp`.
    Sp,
    /// A unit that is an internal dimension: `em`, `ex`, `px`, or a
    /// dimension register.
    Internal(i32),
}

impl Unit {
    /// The unit named by two letters, among the ones pgfmath recognizes
    /// (`em`, `ex` and `px` need the font or `\pdfpxdimen`, so they are
    /// handled by the caller).
    pub fn from_name(a: u8, b: u8) -> Option<Unit> {
        Some(match (a, b) {
            (b'p', b't') => Unit::Pt,
            (b'i', b'n') => Unit::Ratio(7227, 100),
            (b'p', b'c') => Unit::Ratio(12, 1),
            (b'c', b'm') => Unit::Ratio(7227, 254),
            (b'm', b'm') => Unit::Ratio(7227, 2540),
            (b'b', b'p') => Unit::Ratio(7227, 7200),
            (b'd', b'd') => Unit::Ratio(1238, 1157),
            (b'c', b'c') => Unit::Ratio(14856, 1157),
            (b'n', b'd') => Unit::Ratio(685, 642),
            (b'n', b'c') => Unit::Ratio(1370, 107),
            (b's', b'p') => Unit::Sp,
            _ => return None,
        })
    }
}

/// The parts of a decimal number as `scan_dimen` reads them.
struct Decimal {
    negative: bool,
    /// `None`: no digits and no point (only signs).
    int: Option<i64>,
    /// The scaled fraction (`round_decimals`).
    frac: i32,
}

/// Reads `[+-]* digits [. digits]` (TeX also accepts `.digits`); the
/// whole string must be used.
fn decimal(s: &[u8]) -> R<Decimal> {
    let mut i = 0;
    let mut negative = false;
    while i < s.len() && (s[i] == b'+' || s[i] == b'-') {
        if s[i] == b'-' {
            negative = !negative;
        }
        i += 1;
    }
    if i == s.len() {
        return Ok(Decimal {
            negative,
            int: None,
            frac: 0,
        });
    }
    let mut int: i64 = 0;
    if s[i] == b'.' {
        // `cur_val := 0`; the point starts the fraction.
    } else {
        let start = i;
        while i < s.len() && s[i].is_ascii_digit() {
            int = int * 10 + i64::from(s[i] - b'0');
            if int > INFINITY {
                return Err(Decline); // Number too big
            }
            i += 1;
        }
        if i == start {
            return Err(Decline); // Missing number
        }
    }
    let mut frac = 0;
    if i < s.len() && s[i] == b'.' {
        i += 1;
        let mut digits: Vec<u8> = Vec::new();
        while i < s.len() && s[i].is_ascii_digit() {
            if digits.len() < 17 {
                digits.push(s[i] - b'0');
            }
            i += 1;
        }
        frac = arith::round_decimals(&digits);
    }
    if i != s.len() {
        return Err(Decline); // Illegal unit of measure
    }
    Ok(Decimal {
        negative,
        int: Some(int),
        frac,
    })
}

fn finish(v: i64, negative: bool) -> R<i32> {
    if v.abs() >= DIMEN_LIMIT {
        return Err(Decline); // Dimension too large
    }
    let v = v as i32;
    Ok(if negative { -v } else { v })
}

/// `\dimen=<s><unit>`: the decimal string `s` followed by `unit`.
pub fn scan_unit(s: &[u8], unit: Unit) -> R<i32> {
    let d = decimal(s)?;
    let Some(int) = d.int else {
        if let Unit::Internal(v) = unit {
            // Signs followed by an internal dimension.
            return finish(i64::from(v), d.negative);
        }
        return Err(Decline); // Missing number
    };
    let mut f = i64::from(d.frac);
    match unit {
        Unit::Pt => {}
        Unit::Ratio(num, denom) => {
            let r = arith::xn_over_d(int as i32, num, denom).map_err(|_| Decline)?;
            let mut cur = i64::from(r.quotient);
            f = (i64::from(num) * f + 0o200000 * i64::from(r.remainder)) / i64::from(denom);
            cur += f / 0o200000;
            f %= 0o200000;
            return attach_fraction(cur, f, d.negative);
        }
        Unit::Sp => return finish(int, d.negative),
        Unit::Internal(v) => {
            let frac = arith::xn_over_d(v, d.frac, 0o200000)
                .map_err(|_| Decline)?
                .quotient;
            let cur = arith::nx_plus_y(int as i32, v, frac).map_err(|_| Decline)?;
            return finish(i64::from(cur), d.negative);
        }
    }
    attach_fraction(int, f, d.negative)
}

fn attach_fraction(int: i64, f: i64, negative: bool) -> R<i32> {
    if int >= 0o40000 {
        return Err(Decline);
    }
    finish(int * i64::from(UNITY) + f, negative)
}

/// `\dimen=<s>pt`.
pub fn scan_pt(s: &[u8]) -> R<i32> {
    scan_unit(s, Unit::Pt)
}

/// `\dimen=<s>\otherdimen` (a factor times an internal dimension `v`).
pub fn scan_factor(s: &[u8], v: i32) -> R<i32> {
    scan_unit(s, Unit::Internal(v))
}

/// `\the` of a dimension without `pt` (`\pgfmath@tonumber`).
pub fn print(v: i32) -> Vec<u8> {
    let mut s = String::new();
    arith::print_scaled(&mut s, v);
    s.into_bytes()
}

/// `\pgfmath@returnone\pgfmath@x`: `\pgfmath@x\pgfmath@x` re-checks the
/// range, then the value is printed.
pub fn returnone(x: i32) -> R<Vec<u8>> {
    if i64::from(x).abs() >= DIMEN_LIMIT {
        return Err(Decline);
    }
    Ok(print(x))
}

/// Reads an integer as `\count=<s>\relax` does (the whole string).
pub fn scan_int(s: &[u8]) -> R<i64> {
    let mut i = 0;
    let mut negative = false;
    while i < s.len() && (s[i] == b'+' || s[i] == b'-') {
        if s[i] == b'-' {
            negative = !negative;
        }
        i += 1;
    }
    if i == s.len() {
        return Err(Decline);
    }
    let mut v: i64 = 0;
    for &c in &s[i..] {
        if !c.is_ascii_digit() {
            return Err(Decline);
        }
        v = v * 10 + i64::from(c - b'0');
        if v > INFINITY {
            return Err(Decline);
        }
    }
    Ok(if negative { -v } else { v })
}

/// `\divide<count>by<n>` / `\divide<dimen>by<n>`: truncation towards
/// zero; zero is an arithmetic overflow.
pub fn tex_divide(x: i64, n: i64) -> R<i64> {
    if n == 0 {
        return Err(Decline);
    }
    let q = x.abs() / n.abs();
    Ok(if (x < 0) != (n < 0) { -q } else { q })
}

/// `\multiply<count>by<n>`, with TeX's overflow check.
pub fn tex_multiply(x: i64, n: i64) -> R<i64> {
    let p = x * n;
    if p.abs() > INFINITY {
        return Err(Decline);
    }
    Ok(p)
}

/// Splits `\the` output (`-12.345`) at the point.
pub fn split_point(s: &[u8]) -> (&[u8], &[u8]) {
    let p = s.iter().position(|&c| c == b'.').unwrap_or(s.len());
    (&s[..p], s.get(p + 1..).unwrap_or(&[]))
}

/// `\c@pgfmath@counta\the\dimen\relax` with `\afterassignment`
/// `\pgfmath@xa`: the integer part (a count) and the fraction (`.ddd pt`).
pub fn int_and_fraction(v: i32) -> R<(i64, i32)> {
    let s = print(v);
    let (int, frac) = split_point(&s);
    let i = scan_int(int)?;
    let mut f = vec![b'.'];
    f.extend_from_slice(frac);
    Ok((i, scan_pt(&f)?))
}

/// `\advance<dimen>by<dimen>`. TeX does not check the sum; here a sum
/// outside the range of dimensions declines (the TeX code would report an
/// error later, or compute with a value no dimension can hold).
pub fn adv(x: i32, y: i32) -> R<i32> {
    let r = i64::from(x) + i64::from(y);
    if r.abs() >= DIMEN_LIMIT {
        return Err(Decline);
    }
    Ok(r as i32)
}

/// `\advance<count>by<n>` (declining outside the range of integers).
pub fn cadv(x: i64, y: i64) -> R<i64> {
    let r = x + y;
    if r.abs() > INFINITY {
        return Err(Decline);
    }
    Ok(r)
}

/// `\multiply<dimen>by<n>`: `nx_plus_y`, an arithmetic overflow beyond
/// `2^30 - 1`.
pub fn dmul(x: i32, n: i64) -> R<i32> {
    let n = i32::try_from(n).map_err(|_| Decline)?;
    arith::nx_plus_y(n, x, 0).map_err(|_| Decline)
}

/// `\divide<dimen>by<n>`.
pub fn ddiv(x: i32, n: i64) -> R<i32> {
    Ok(tex_divide(i64::from(x), n)? as i32)
}

/// The integer part of `\the<dimen>` as a count reads it (`-0.5pt` is 0).
pub fn int_part(x: i32) -> i64 {
    let v = i64::from(x).abs() / i64::from(UNITY);
    if x < 0 { -v } else { v }
}

/// `\count=<s>` where the integer is followed by other text: the value and
/// the number of bytes it takes (signs and digits).
pub fn scan_int_prefix(s: &[u8]) -> R<(i64, usize)> {
    let mut i = 0;
    let mut negative = false;
    while i < s.len() && (s[i] == b'+' || s[i] == b'-') {
        if s[i] == b'-' {
            negative = !negative;
        }
        i += 1;
    }
    let start = i;
    let mut v: i64 = 0;
    while i < s.len() && s[i].is_ascii_digit() {
        v = v * 10 + i64::from(s[i] - b'0');
        if v > INFINITY {
            return Err(Decline);
        }
        i += 1;
    }
    if i == start {
        return Err(Decline); // Missing number (or an octal/hex/char prefix)
    }
    Ok((if negative { -v } else { v }, i))
}

/// `\pgfmathadd@`.
pub fn add(a: &[u8], b: &[u8]) -> R<Vec<u8>> {
    let x = scan_pt(a)?;
    let y = scan_pt(b)?;
    returnone(x + y)
}

/// `\pgfmathsubtract@`.
pub fn subtract(a: &[u8], b: &[u8]) -> R<Vec<u8>> {
    let x = scan_pt(a)?;
    let y = scan_pt(b)?;
    returnone(x - y)
}

/// `\pgfmathneg@`: `\pgfmath@x=-#1pt`, printed (no range re-check).
pub fn neg(a: &[u8]) -> R<Vec<u8>> {
    let mut s = vec![b'-'];
    s.extend_from_slice(a);
    Ok(print(scan_pt(&s)?))
}

/// `\pgfmathmultiply@`.
pub fn multiply(a: &[u8], b: &[u8]) -> R<Vec<u8>> {
    let x = scan_pt(a)?;
    let y = scan_pt(b)?;
    returnone(scan_factor(&print(y), x)?)
}

/// `\pgfmathreciprocal@`.
pub fn reciprocal(a: &[u8]) -> R<Vec<u8>> {
    let x = scan_pt(a)?;
    if x == 0 {
        return Err(Decline); // pgfmath error
    }
    let tmp = print(x);
    let (int, frac) = split_point(&tmp);
    let mut d: Vec<u8> = frac.to_vec();
    d.extend_from_slice(b"0000000");
    let d = &d[..5];
    let counta = scan_int(d)?;
    let int_v = scan_int(int)?;
    let x = if counta == 0 {
        // `\pgfmath@x1pt \divide\pgfmath@x#1`.
        tex_divide(i64::from(UNITY), int_v)?
    } else {
        let digits = if int_v > 100 { &d[..3] } else { d };
        let mut s = int.to_vec();
        s.extend_from_slice(digits);
        let counta = scan_int(&s)?;
        let countb = tex_divide(1_000_000_000, counta)?;
        let counta = tex_divide(countb, 10000)?;
        let x = count_pt(counta)?;
        let counta = tex_multiply(counta, -10000)?;
        let countb = countb + counta;
        let mut y = count_pt(countb)?;
        if int_v > 100 {
            y = tex_divide(i64::from(y), 1_000_000)? as i32;
        } else {
            for _ in 0..4 {
                y = scan_factor(b".1", y)?;
            }
        }
        i64::from(x) + i64::from(y)
    };
    returnone(x as i32)
}

/// `\dimen=\count pt`: an internal integer followed by `pt`.
pub fn count_pt(c: i64) -> R<i32> {
    let negative = c < 0;
    attach_fraction(c.abs(), 0, negative)
}

/// `\pgfmathdivide@dimenbyten`.
fn dimen_by_ten(y: i32) -> R<i32> {
    let s = print(y);
    let (int, frac) = split_point(&s);
    let i = scan_int(int)?;
    let q = tex_divide(i, 10)?;
    let r = i - q * 10;
    let mut t = format!("{q}.{r}").into_bytes();
    t.extend_from_slice(frac);
    scan_pt(&t)
}

/// `\pgfmathdivide@advance@last@digit`.
fn advance_last_digit(result: &[u8]) -> R<Vec<u8>> {
    let (_, frac) = split_point(result);
    let ya = scan_pt(result)?;
    let xa: &[u8] = match frac.len() {
        0 => b"1",
        1 => b".1",
        2 => b".01",
        3 => b".001",
        4 => b".0001",
        _ => b".00001",
    };
    let ya = ya + scan_pt(xa)?;
    // `\pgfmath@tonumber@notrailingzero`.
    let s = print(ya);
    let (int, frac) = split_point(&s);
    let mut out = int.to_vec();
    out.push(b'.');
    if scan_int(frac)? != 0 {
        out.extend_from_slice(frac);
    }
    Ok(out)
}

/// `\pgfmathdivide@@`: long division of positive `x` by `y ≥ 1pt`.
fn long_division(mut x: i32, mut y: i32) -> R<Vec<u8>> {
    let small = scan_pt(b"0.00002")?;
    let mut result = b"0".to_vec();
    let mut period = true;
    while small < x && small < y {
        if y > x {
            if period {
                result.push(b'.');
                period = false;
            }
            y = dimen_by_ten(y)?;
            if y > x {
                result.push(b'0');
            }
        } else {
            let mut q = tex_divide(i64::from(x), i64::from(y))?;
            let ya = arith::nx_plus_y(q as i32, y, 0).map_err(|_| Decline)?;
            x -= ya;
            let mut append = true;
            if !period && q > 9 {
                result = advance_last_digit(&result)?;
                q -= 10;
                if q == 0 {
                    append = false;
                }
            }
            if append {
                result.extend_from_slice(q.to_string().as_bytes());
            }
        }
    }
    Ok(result)
}

/// `\pgfmathdivide@`.
pub fn divide(a: &[u8], b: &[u8]) -> R<Vec<u8>> {
    let mut x = scan_pt(a)?;
    let mut y = scan_pt(b)?;
    if y == 0 {
        return Err(Decline); // pgfmath error
    }
    let (counta, xa) = int_and_fraction(y)?;
    if xa == 0 {
        return returnone(tex_divide(i64::from(x), counta)? as i32);
    }
    let mut sign: Vec<u8> = Vec::new();
    if x < 0 {
        sign.push(b'-');
        x = -x;
    }
    if y < 0 {
        sign.push(b'-');
        y = -y;
    }
    if y < UNITY {
        let r = reciprocal(&print(y))?;
        sign.extend_from_slice(&r);
        returnone(scan_factor(&sign, x)?)
    } else {
        let r = long_division(x, y)?;
        sign.extend_from_slice(&r);
        returnone(scan_pt(&sign)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(v: R<Vec<u8>>) -> String {
        String::from_utf8(v.unwrap()).unwrap()
    }

    #[test]
    fn scanning() {
        assert_eq!(scan_pt(b"1.5"), Ok(98304));
        assert_eq!(scan_pt(b"--.5"), Ok(32768));
        assert_eq!(scan_pt(b"16384"), Err(Decline));
        assert_eq!(scan_pt(b"1.2.3"), Err(Decline));
        assert_eq!(scan_pt(b""), Err(Decline));
        assert_eq!(scan_pt(b"."), Ok(0));
        assert_eq!(scan_factor(b"-", 5), Ok(-5));
        assert_eq!(scan_factor(b"", 5), Ok(5));
        assert_eq!(scan_unit(b"1", Unit::Ratio(7227, 254)), Ok(1864679));
    }

    #[test]
    fn functions() {
        assert_eq!(s(add(b"1", b"2")), "3.0");
        assert_eq!(s(multiply(b"1.5", b"2")), "3.0");
        assert_eq!(s(divide(b"1", b"3")), "0.33333");
        assert_eq!(s(divide(b"10", b"4")), "2.5");
        assert_eq!(s(divide(b"1", b"0.5")), "2.0");
        assert_eq!(s(neg(b"-2")), "2.0");
        assert_eq!(divide(b"1", b"0"), Err(Decline));
    }
}