retex-lua 1.3.0-alpha.1

Embedded Lua and the LuaTeX Lua API 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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
//! The `pdf` library (LuaTeX manual, chapter "The backend libraries").
//!
//! Most functions read or set the backend variables that `\pdfvariable`
//! also reaches (integer and dimension parameters in eqtb) or the
//! `\pdfextension` state ([`retex_engine::pdfext::PdfState`]): objects,
//! annotations, links, colour stacks and the document dictionaries.
//!
//! Argument handling follows what LuaTeX 1.22 does, established black-box
//! by calling each function from `\directlua` and `\latelua` and looking at
//! the results, at `\pdfvariable`/`\pdffeedback` and at the PDF output:
//!
//! * integer setters accept only Lua numbers: an integer-valued float
//!   counts as that integer, any other float as 0, and the value is
//!   truncated to 32 bits; anything else leaves the variable unchanged.
//!   Some variables are clamped or validated (see [`INT_VARS`]);
//! * dimension setters round numbers with `floor(x + 0.5)`; results outside
//!   the 32-bit range become −2³¹; non-numbers are ignored;
//! * setters change the current value without touching the save stack, so
//!   a value set inside a group survives it unless TeX assigned the same
//!   variable inside that group;
//! * string setters use their last argument, and only if it is a string;
//!   the getters return `nil` until a value was set. These texts are kept
//!   apart from the `\pdfextension catalog`/`\pdfvariable pageattr`, …
//!   token lists and go into the PDF after them;
//! * argument errors are raised as plain strings, with LuaTeX's messages.
//!
//! Not supported yet, because the PDF backend lacks the parts: the texts
//! set from Lua, map files, font attributes, registered annotations and
//! objects written with `pdf.immediateobj` are recorded but not written
//! to the PDF; `getmatrix` always returns the identity; `getxformname` is
//! `nil` (no form XObjects); `includechar`, `includefont`, `setforcefile`
//! and `settypeonewidemode` do nothing; `includeimage` raises an error.
//! LuaTeX ends the run with a fatal error in some cases where this
//! library raises a Lua error or returns `nil` instead (unknown object
//! numbers, unknown fonts, `immediateobj` in DVI mode).

use mlua::{Lua, MultiValue, Table, Value};
use retex_engine::Engine;
use retex_engine::backend as bk;
use retex_engine::pdfext::{LuaPdfTexts, ObjKind, PdfObject, literal_mode};

use crate::{create_function_plain_errors, with_engine};

/// How an integer setter treats its value.
#[derive(Clone, Copy)]
enum IntRule {
    /// Stored as is.
    Any,
    /// Clamped to the range.
    Clamp(i32, i32),
    /// Ignored unless in the range.
    Accept(i32, i32),
}

/// Integer variables with plain `get…`/`set…` functions: the Lua name, the
/// parameter index (as for `\pdfvariable`) and the setter's rule.
const INT_VARS: &[(&str, u32, IntRule)] = &[
    ("compresslevel", bk::COMPRESS_LEVEL, IntRule::Clamp(0, 9)),
    (
        "decimaldigits",
        bk::DECIMAL_DIGITS,
        IntRule::Clamp(0, i32::MAX),
    ),
    ("imageresolution", 139, IntRule::Any),
    ("majorversion", bk::MAJOR_VERSION, IntRule::Accept(1, 2)),
    ("minorversion", bk::MINOR_VERSION, IntRule::Accept(0, 9)),
    ("inclusionerrorlevel", 145, IntRule::Any),
    ("ignoreunknownimages", 146, IntRule::Any),
    (
        "objcompresslevel",
        bk::OBJ_COMPRESS_LEVEL,
        IntRule::Clamp(0, 9),
    ),
    ("gentounicode", 154, IntRule::Any),
    ("suppressoptionalinfo", 156, IntRule::Any),
    ("omitcidset", 157, IntRule::Any),
    ("recompress", 158, IntRule::Clamp(0, 9)),
    ("omitcharset", 159, IntRule::Any),
    ("omitinfo", 160, IntRule::Any),
    ("omitmediabox", 161, IntRule::Any),
    ("omitprocset", 163, IntRule::Any),
    ("ptexprefix", 164, IntRule::Any),
];

use retex_engine::backend::{PK_FIXED_DPI, PK_RESOLUTION};

/// Dimension variables: the Lua name and the parameter index.
const DIMEN_VARS: &[(&str, u32)] = &[
    ("threadmargin", 30),
    ("destmargin", 31),
    ("linkmargin", 32),
    ("xformmargin", 33),
];

/// String variables set from Lua.
type TextField = fn(&mut LuaPdfTexts) -> &mut Option<Vec<u8>>;
const TEXT_VARS: &[(&str, TextField)] = &[
    ("catalog", |t| &mut t.catalog),
    ("info", |t| &mut t.info),
    ("names", |t| &mut t.names),
    ("trailer", |t| &mut t.trailer),
    ("trailerid", |t| &mut t.trailer_id),
    ("pageattributes", |t| &mut t.page_attributes),
    ("pageresources", |t| &mut t.page_resources),
    ("pagesattributes", |t| &mut t.pages_attributes),
    ("xformattributes", |t| &mut t.xform_attributes),
    ("xformresources", |t| &mut t.xform_resources),
];

/// Literal modes accepted by `pdf.print` and `pdf.newcolorstack`.
pub(crate) const MODES: &[(&str, u8)] = &[
    ("origin", literal_mode::ORIGIN),
    ("page", literal_mode::PAGE),
    ("direct", literal_mode::DIRECT),
    ("raw", literal_mode::RAW),
    ("text", 4),
];

/// A Lua error with message `msg` (shown as is, without location).
fn err<T>(msg: impl Into<String>) -> mlua::Result<T> {
    Err(mlua::Error::runtime(msg.into()))
}

/// The value of an integer setter's argument (see the module docs).
fn int_value(v: &Value) -> Option<i32> {
    match *v {
        Value::Integer(i) => Some(i as i32),
        Value::Number(f) => Some(exact_integer(f).unwrap_or(0) as i32),
        _ => None,
    }
}

/// `f` as an integer if it has an exact integer representation.
fn exact_integer(f: f64) -> Option<i64> {
    (f.fract() == 0.0 && f >= -(2f64.powi(63)) && f < 2f64.powi(63)).then_some(f as i64)
}

/// The value of a dimension setter's argument (see the module docs).
fn dimen_value(v: &Value) -> Option<i32> {
    let x = match *v {
        Value::Integer(i) => i as f64,
        Value::Number(f) => f,
        _ => return None,
    };
    let r = (x + 0.5).floor();
    Some(
        if r.is_nan() || r < f64::from(i32::MIN) || r > f64::from(i32::MAX) {
            i32::MIN
        } else {
            r as i32
        },
    )
}

/// An integer-valued Lua number (integer, or float with an exact value).
fn integer_number(v: &Value) -> Option<i64> {
    match *v {
        Value::Integer(i) => Some(i),
        Value::Number(f) => exact_integer(f),
        _ => None,
    }
}

/// `luaL_checkinteger` for argument `argn` of function `fname`.
pub(crate) fn check_integer(
    lua: &Lua,
    v: Option<&Value>,
    argn: usize,
    fname: &str,
) -> mlua::Result<i64> {
    let bad = |msg: String| err(format!("bad argument #{argn} to '{fname}' ({msg})"));
    let Some(v) = v else {
        return bad("number expected, got no value".into());
    };
    if let Some(i) = lua.coerce_integer(v.clone())? {
        return Ok(i);
    }
    if lua.coerce_number(v.clone())?.is_some() {
        return bad("number has no integer representation".into());
    }
    bad(format!("number expected, got {}", v.type_name()))
}

/// A string argument the way `lua_isstring` sees it (numbers count).
pub(crate) fn coerce_bytes(lua: &Lua, v: &Value) -> mlua::Result<Option<Vec<u8>>> {
    Ok(match v {
        Value::String(s) => Some(s.as_bytes().to_vec()),
        Value::Integer(_) | Value::Number(_) => {
            lua.coerce_string(v.clone())?.map(|s| s.as_bytes().to_vec())
        }
        _ => None,
    })
}

/// A font id argument: a number (non-integral floats count as 0) naming an
/// existing font.
fn font_arg(lua: &Lua, args: &MultiValue) -> mlua::Result<Option<u32>> {
    let Some(f) = args.front().and_then(int_value) else {
        return Ok(None);
    };
    with_engine(lua, |e| {
        (f >= 0 && (f == 0 || e.font_exists(f))).then_some(f as u32)
    })
}

/// Installs `pdf`.
pub fn install(lua: &Lua) -> mlua::Result<()> {
    let t = lua.create_table()?;
    install_variables(lua, &t)?;
    install_feedback(lua, &t)?;
    install_objects(lua, &t)?;
    install_output(lua, &t)?;
    lua.globals().set("pdf", t)?;
    Ok(())
}

/// The `get…`/`set…` pairs of the backend variables.
fn install_variables(lua: &Lua, t: &Table) -> mlua::Result<()> {
    for &(name, index, rule) in INT_VARS {
        t.set(
            format!("get{name}"),
            create_function_plain_errors(lua, move |lua, ()| {
                with_engine(lua, |e| i64::from(e.eqtb.int(index)))
            })?,
        )?;
        t.set(
            format!("set{name}"),
            create_function_plain_errors(lua, move |lua, args: MultiValue| {
                let Some(v) = args.front().and_then(int_value) else {
                    return Ok(());
                };
                let v = match rule {
                    IntRule::Any => v,
                    IntRule::Clamp(lo, hi) => v.clamp(lo, hi),
                    IntRule::Accept(lo, hi) if (lo..=hi).contains(&v) => v,
                    IntRule::Accept(..) => return Ok(()),
                };
                with_engine(lua, |e| e.eqtb.int_par[index as usize].val = v)
            })?,
        )?;
    }
    t.set(
        "getpkresolution",
        create_function_plain_errors(lua, |lua, ()| {
            with_engine(lua, |e| {
                (
                    i64::from(e.eqtb.int(PK_RESOLUTION)),
                    i64::from(e.eqtb.int(PK_FIXED_DPI)),
                )
            })
        })?,
    )?;
    t.set(
        "setpkresolution",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let Some(v) = args.front().and_then(int_value) else {
                return Ok(());
            };
            // Observed: with a numeric second argument, `pkfixeddpi`
            // receives the resolution as given (before clamping).
            let fixed = matches!(args.get(1), Some(Value::Integer(_) | Value::Number(_)));
            with_engine(lua, |e| {
                e.eqtb.int_par[PK_RESOLUTION as usize].val = v.clamp(72, 8000);
                if fixed {
                    e.eqtb.int_par[PK_FIXED_DPI as usize].val = v;
                }
            })
        })?,
    )?;
    for &(name, index) in DIMEN_VARS {
        t.set(
            format!("get{name}"),
            create_function_plain_errors(lua, move |lua, ()| {
                with_engine(lua, |e| i64::from(e.eqtb.dimen(index)))
            })?,
        )?;
        t.set(
            format!("set{name}"),
            create_function_plain_errors(lua, move |lua, args: MultiValue| {
                let Some(v) = args.front().and_then(dimen_value) else {
                    return Ok(());
                };
                with_engine(lua, |e| e.eqtb.dimen_par[index as usize].val = v)
            })?,
        )?;
    }
    t.set(
        "getorigin",
        create_function_plain_errors(lua, |lua, ()| {
            with_engine(lua, |e| {
                (
                    i64::from(e.eqtb.dimen(bk::H_ORIGIN)),
                    i64::from(e.eqtb.dimen(bk::V_ORIGIN)),
                )
            })
        })?,
    )?;
    t.set(
        "setorigin",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            // Observed: no numeric first argument sets both to 0; a missing
            // second one copies the first.
            let (h, v) = match args.front().and_then(dimen_value) {
                Some(h) => (h, args.get(1).and_then(dimen_value).unwrap_or(h)),
                None => (0, 0),
            };
            with_engine(lua, |e| {
                e.eqtb.dimen_par[bk::H_ORIGIN as usize].val = h;
                e.eqtb.dimen_par[bk::V_ORIGIN as usize].val = v;
            })
        })?,
    )?;
    for &(name, field) in TEXT_VARS {
        t.set(
            format!("get{name}"),
            create_function_plain_errors(lua, move |lua, ()| {
                let v = with_engine(lua, |e| field(&mut e.pdf.lua).clone())?;
                v.map(|b| lua.create_string(&b)).transpose()
            })?,
        )?;
        t.set(
            format!("set{name}"),
            create_function_plain_errors(lua, move |lua, args: MultiValue| {
                let Some(Value::String(s)) = args.back() else {
                    return Ok(());
                };
                let s = s.as_bytes().to_vec();
                with_engine(lua, |e| *field(&mut e.pdf.lua) = Some(s))
            })?,
        )?;
    }
    t.set(
        "getcreationdate",
        create_function_plain_errors(lua, |lua, ()| with_engine(lua, |e| e.start_time.pdf_date()))?,
    )?;
    Ok(())
}

/// Status values (the `\pdffeedback` counterparts) and introspection.
fn install_feedback(lua: &Lua, t: &Table) -> mlua::Result<()> {
    type Getter = fn(&Engine) -> i32;
    let ints: &[(&str, Getter)] = &[
        ("getlastobj", |e| e.pdf.last_obj),
        ("getlastlink", |e| e.pdf.last_link),
        ("getlastannot", |e| e.pdf.last_annot),
        ("getretval", |e| e.pdf.retval),
        ("getmaxobjnum", |e| e.pdf.max_obj()),
        ("gethpos", |e| e.pdf.pos.0),
        ("getvpos", |e| e.pdf.pos.1),
    ];
    for &(name, get) in ints {
        t.set(
            name,
            create_function_plain_errors(lua, move |lua, ()| {
                with_engine(lua, |e| i64::from(get(e)))
            })?,
        )?;
    }
    t.set("maxobjnum", t.get::<mlua::Function>("getmaxobjnum")?)?;
    t.set(
        "getpos",
        create_function_plain_errors(lua, |lua, ()| {
            with_engine(lua, |e| (i64::from(e.pdf.pos.0), i64::from(e.pdf.pos.1)))
        })?,
    )?;
    t.set(
        "getnofobjects",
        create_function_plain_errors(lua, |lua, ()| {
            with_engine(lua, |e| {
                let written = e.pdf.objects.values().filter(|o| o.written).count() as i64;
                (written, i64::from(e.pdf.max_obj()) - written)
            })
        })?,
    )?;
    // The transformation matrix is not tracked: always the identity.
    t.set(
        "getmatrix",
        create_function_plain_errors(lua, |_, ()| Ok((1, 0, 0, 1, 0, 0)))?,
    )?;
    t.set(
        "hasmatrix",
        create_function_plain_errors(lua, |_, ()| Ok(false))?,
    )?;
    let objtype = create_function_plain_errors(lua, |lua, args: MultiValue| {
        let Some(n) = args.front().and_then(integer_number) else {
            return Ok(None);
        };
        let n = i32::try_from(n).unwrap_or(0);
        with_engine(lua, |e| e.pdf_obj_kind(n).map(ObjKind::name))
    })?;
    t.set("getobjtype", objtype.clone())?;
    t.set("objtype", objtype)?;
    let pageref = create_function_plain_errors(lua, |lua, args: MultiValue| {
        let Some(n) = args.front().and_then(integer_number) else {
            return Ok(None);
        };
        if n < 1 || n > i64::from(i32::MAX) {
            return Ok(None);
        }
        with_engine(lua, |e| Some(i64::from(e.pdf_page_ref(n as i32))))
    })?;
    t.set("getpageref", pageref.clone())?;
    t.set("pageref", pageref)?;
    // No form XObjects exist yet.
    let xformname = create_function_plain_errors(lua, |_, _: MultiValue| Ok(Value::Nil))?;
    t.set("getxformname", xformname.clone())?;
    t.set("xformname", xformname)?;
    let fontname = create_function_plain_errors(lua, |lua, args: MultiValue| {
        let Some(f) = font_arg(lua, &args)? else {
            return Ok(None);
        };
        with_engine(lua, |e| Some(i64::from(e.pdf_font(f).0)))
    })?;
    t.set("getfontname", fontname.clone())?;
    t.set("fontname", fontname)?;
    let fontobjnum = create_function_plain_errors(lua, |lua, args: MultiValue| {
        let Some(f) = font_arg(lua, &args)? else {
            return Ok(None);
        };
        with_engine(lua, |e| Some(i64::from(e.pdf_font(f).1)))
    })?;
    t.set("getfontobjnum", fontobjnum.clone())?;
    t.set("fontobjnum", fontobjnum)?;
    let fontsize = create_function_plain_errors(lua, |lua, args: MultiValue| {
        let Some(f) = font_arg(lua, &args)? else {
            return Ok(None);
        };
        with_engine(lua, |e| Some(i64::from(e.font(f).size)))
    })?;
    t.set("getfontsize", fontsize.clone())?;
    t.set("fontsize", fontsize)?;
    Ok(())
}

/// An object number given to `pdf.obj`/`pdf.immediateobj`: a reserved
/// object that has no content yet.
fn reserved_obj(e: &Engine, n: i64, fname: &str) -> Result<i32, String> {
    let n = i32::try_from(n).map_err(|_| format!("{fname} invalid object number"))?;
    match (e.pdf_obj_kind(n), e.pdf.objects.get(&n)) {
        (Some(ObjKind::Obj), Some(o)) if !o.defined => Ok(n),
        (Some(ObjKind::Obj), _) => Err(format!("{fname} object in use")),
        _ => Err(format!("{fname} invalid object number")),
    }
}

/// Objects can be written immediately only in PDF mode (a fatal error in
/// LuaTeX, a Lua error here).
fn check_pdf_mode(lua: &Lua) -> mlua::Result<()> {
    let mode = with_engine(lua, |e| {
        e.eqtb
            .int(retex_engine::primitives_gen::assign_int::OUTPUTMODE)
    })?;
    if mode <= 0 {
        return err("immediateobj() not allowed in DVI mode (outputmode = 0)");
    }
    Ok(())
}

/// [`reserved_obj`], then marks the object as used.
fn claim_reserved(e: &mut Engine, n: i64, fname: &str) -> Result<i32, String> {
    let n = reserved_obj(e, n, fname)?;
    if let Some(o) = e.pdf.objects.get_mut(&n) {
        o.defined = true;
    }
    Ok(n)
}

/// Allocates an object for `pdf.obj`/`pdf.immediateobj` (it becomes
/// `lastobj` even if the call then fails, as in LuaTeX).
fn alloc_obj(e: &mut Engine) -> i32 {
    let n = e.pdf_alloc_obj(ObjKind::Obj);
    e.pdf.last_obj = n;
    n
}

/// `pdf.obj(…)` and `pdf.immediateobj(…)` with positional arguments.
fn positional_obj(lua: &Lua, args: &[Value], immediate: bool) -> mlua::Result<i64> {
    let fname = if immediate {
        "pdf.immediateobj()"
    } else {
        "pdf.obj()"
    };
    if immediate {
        check_pdf_mode(lua)?;
    }
    let (given, rest) = match args.first() {
        Some(v @ (Value::Integer(_) | Value::Number(_))) => {
            (Some(integer_number(v).unwrap_or(0)), &args[1..])
        }
        _ => (None, args),
    };
    // The object number is taken before the other arguments are checked
    // (observed: failing calls still use up a number, and a reserved
    // object passed to a failing call counts as used).
    let num = match given {
        Some(n) => match with_engine(lua, |e| claim_reserved(e, n, fname))? {
            Ok(n) => n,
            Err(m) => return err(m),
        },
        None => with_engine(lua, alloc_obj)?,
    };
    if rest.is_empty() {
        return err(format!("{fname} needs at least one argument"));
    }
    if rest.len() > 3 {
        return err(format!("{fname} allows max. 3 arguments"));
    }
    let ordinal = ["1st", "2nd", "3rd"];
    let mut strings = Vec::new();
    for (i, v) in rest.iter().enumerate() {
        match coerce_bytes(lua, v)? {
            Some(s) => strings.push(s),
            None => return err(format!("{fname} {} argument must be string", ordinal[i])),
        }
    }
    let mut obj = PdfObject {
        num,
        defined: true,
        ..Default::default()
    };
    match (strings[0].as_slice(), strings.len()) {
        (_, 1) => obj.data = strings.remove(0),
        (b"file", 2) => {
            obj.file = true;
            obj.data = strings.remove(1);
        }
        (b"stream" | b"streamfile", _) => {
            obj.stream = true;
            obj.file = strings[0] == b"streamfile";
            obj.attr = strings.get(2).cloned().unwrap_or_default();
            obj.data = strings.swap_remove(1);
        }
        _ => {
            if immediate {
                // Observed: LuaTeX has already written the (empty) object
                // when it rejects the arguments (`pdf.getnofobjects`).
                with_engine(lua, |e| e.pdf_define_object(obj, true))?;
            }
            return err(format!("{fname} invalid argument"));
        }
    }
    with_engine(lua, |e| e.pdf_define_object(obj, immediate))?;
    Ok(i64::from(num))
}

/// `pdf.obj{…}`.
fn table_obj(lua: &Lua, t: &Table) -> mlua::Result<i64> {
    let stream = match t.get::<Value>("type")? {
        Value::Nil => return err("pdf.obj(): object \"type\" missing"),
        Value::String(s) => match s.as_bytes().as_ref() {
            b"raw" => false,
            b"stream" => true,
            other => {
                return err(format!(
                    "pdf.obj(): \"{}\" is not a valid object type",
                    String::from_utf8_lossy(other)
                ));
            }
        },
        _ => return err("pdf.obj(): object \"type\" must be string"),
    };
    let immediate = matches!(t.get::<Value>("immediate")?, Value::Boolean(true));
    if immediate {
        check_pdf_mode(lua)?;
    }
    let num = match integer_number(&t.get::<Value>("objnum")?) {
        Some(n) => match with_engine(lua, |e| claim_reserved(e, n, "pdf.obj()"))? {
            Ok(n) => n,
            Err(m) => return err(m),
        },
        None => with_engine(lua, alloc_obj)?,
    };
    let string = coerce_bytes(lua, &t.get::<Value>("string")?)?;
    let file = coerce_bytes(lua, &t.get::<Value>("file")?)?;
    let attr = coerce_bytes(lua, &t.get::<Value>("attr")?)?;
    if string.is_some() && file.is_some() {
        return err("pdf.obj(): \"string\" and \"file\" must not be given together");
    }
    if attr.is_some() && !stream {
        return err("pdf.obj(): \"attr\" key not allowed for non-stream object");
    }
    if let Some(l) = integer_number(&t.get::<Value>("compresslevel")?)
        && l > 9
    {
        return err("pdf.obj(): \"compresslevel\" must be <= 9");
    }
    let (data, is_file) = match (string, file) {
        (Some(s), None) => (s, false),
        (None, Some(f)) => (f, true),
        _ => return err("pdf.obj(): no \"string\" or \"file\" given"),
    };
    let obj = PdfObject {
        num,
        data,
        stream,
        attr: attr.unwrap_or_default(),
        file: is_file,
        uncompressed: matches!(t.get::<Value>("objcompression")?, Value::Boolean(false)),
        defined: true,
        written: false,
    };
    with_engine(lua, |e| e.pdf_define_object(obj, immediate))?;
    Ok(i64::from(num))
}

/// Objects, annotations and colour stacks.
fn install_objects(lua: &Lua, t: &Table) -> mlua::Result<()> {
    t.set(
        "obj",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let args = args.into_vec();
            with_engine(lua, |e| e.pdf.output_opened = true)?;
            match args.first() {
                Some(Value::Table(t)) if args.len() == 1 => table_obj(lua, t),
                _ => positional_obj(lua, &args, false),
            }
        })?,
    )?;
    t.set(
        "immediateobj",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            positional_obj(lua, &args.into_vec(), true)
        })?,
    )?;
    t.set(
        "reserveobj",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let annot = match args.len() {
                0 => false,
                1 => match args.front() {
                    Some(Value::String(s)) if s.as_bytes().as_ref() == b"annot" => true,
                    Some(Value::String(_)) => {
                        return err("pdf.reserveobj() optional string must be \"annot\"");
                    }
                    _ => return err("pdf.reserveobj() optional argument must be string"),
                },
                _ => return err("pdf.reserveobj() allows max. 1 argument"),
            };
            with_engine(lua, |e| {
                if annot {
                    let n = e.pdf_alloc_obj(ObjKind::Annot);
                    e.pdf.last_annot = n;
                    i64::from(n)
                } else {
                    let n = e.pdf_alloc_obj(ObjKind::Obj);
                    e.pdf.objects.insert(
                        n,
                        PdfObject {
                            num: n,
                            ..Default::default()
                        },
                    );
                    e.pdf.last_obj = n;
                    i64::from(n)
                }
            })
        })?,
    )?;
    t.set(
        "refobj",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            if args.len() != 1 {
                return err("pdf.refobj() needs exactly 1 argument");
            }
            let n = check_integer(lua, args.front(), 1, "pdf.refobj")?;
            let n = i32::try_from(n).unwrap_or(0);
            with_engine(lua, |e| {
                if e.pdf.late.is_some() {
                    // In `\latelua`: written with the current page.
                    e.pdf_write_object(n);
                } else {
                    e.pdf_append_refobj(n);
                }
            })
        })?,
    )?;
    t.set(
        "registerannot",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            if args.len() != 1 {
                return err("pdf.registerannot() needs exactly 1 argument");
            }
            let n = check_integer(lua, args.front(), 1, "pdf.registerannot")?;
            let n = i32::try_from(n).unwrap_or(0);
            with_engine(lua, |e| match e.pdf.late.as_mut() {
                Some(ctx) => {
                    ctx.annots.push(n);
                    Ok(())
                }
                None => err("pdf.registerannot() can only be used in late lua"),
            })?
        })?,
    )?;
    t.set(
        "newcolorstack",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let Some(Value::String(init)) = args.front() else {
                return err("pdf.newcolorstack() expects a string as first argument");
            };
            let init = init.as_bytes().to_vec();
            let mut lmode = literal_mode::ORIGIN;
            if let Some(Value::String(m)) = args.get(1) {
                match MODES
                    .iter()
                    .find(|(n, _)| n.as_bytes() == m.as_bytes().as_ref())
                {
                    Some(&(_, mode)) => lmode = mode,
                    None => return err("invalid literal mode in pdf.newcolorstack()"),
                }
            }
            let page = matches!(args.get(2), Some(Value::Boolean(true)));
            with_engine(lua, |e| i64::from(e.pdf_new_colorstack(init, page, lmode)))
        })?,
    )?;
    Ok(())
}

/// Page content, fonts, map files and images.
fn install_output(lua: &Lua, t: &Table) -> mlua::Result<()> {
    t.set(
        "print",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let args = args.into_vec();
            let (mode, text) = match args.as_slice() {
                [s] => (literal_mode::ORIGIN, s),
                [Value::String(m), s] => {
                    match MODES
                        .iter()
                        .find(|(n, _)| n.as_bytes() == m.as_bytes().as_ref())
                    {
                        Some(&(_, mode)) => (mode, s),
                        None => return err("invalid first argument for print literal mode"),
                    }
                }
                [_, _] => return err("invalid first argument for print literal mode"),
                [] => return err("no string to print"),
                _ => return err("invalid number of arguments"),
            };
            let Some(text) = coerce_bytes(lua, text)? else {
                return err("no string to print");
            };
            // Outside `\latelua` there is no page stream to write to.
            with_engine(lua, |e| {
                if let Some(ctx) = e.pdf.late.as_mut() {
                    ctx.prints.push((mode, text));
                }
            })
        })?,
    )?;
    for name in ["mapfile", "mapline"] {
        t.set(
            name,
            create_function_plain_errors(lua, |lua, args: MultiValue| {
                let Some(Value::String(s)) = args.front() else {
                    return Ok(());
                };
                let s = s.as_bytes().to_vec();
                with_engine(lua, |e| e.pdf.map_entries.push(s))
            })?,
        )?;
    }
    t.set(
        "setfontattributes",
        create_function_plain_errors(lua, |lua, args: MultiValue| {
            let f = check_integer(lua, args.front(), 1, "pdf.setfontattributes")?;
            let Some(s) = args
                .get(1)
                .map(|v| coerce_bytes(lua, v))
                .transpose()?
                .flatten()
            else {
                return err(format!(
                    "bad argument #2 to 'pdf.setfontattributes' (string expected, got {})",
                    args.get(1).map_or("no value", Value::type_name)
                ));
            };
            let f = u32::try_from(f).unwrap_or(0);
            with_engine(lua, |e| {
                e.pdf.font_attrs.insert(f, s);
            })
        })?,
    )?;
    // Accepted without effect: the backend embeds the characters used and
    // has no Type 1 or bitmap fonts.
    for name in [
        "includechar",
        "includefont",
        "setforcefile",
        "settypeonewidemode",
    ] {
        t.set(
            name,
            create_function_plain_errors(lua, |_, _: MultiValue| Ok(()))?,
        )?;
    }
    t.set(
        "includeimage",
        create_function_plain_errors(lua, |_, _: MultiValue| -> mlua::Result<()> {
            err("pdf.includeimage(): images are not supported yet")
        })?,
    )?;
    Ok(())
}

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

    #[test]
    fn number_conversions() {
        assert_eq!(int_value(&Value::Integer(7)), Some(7));
        assert_eq!(int_value(&Value::Number(3.0)), Some(3));
        assert_eq!(int_value(&Value::Number(2.7)), Some(0));
        assert_eq!(int_value(&Value::Number(1e300)), Some(0));
        assert_eq!(int_value(&Value::Number(f64::NAN)), Some(0));
        assert_eq!(int_value(&Value::Integer(4_294_967_301)), Some(5));
        assert_eq!(int_value(&Value::Integer(2_147_483_648)), Some(i32::MIN));
        assert_eq!(int_value(&Value::Boolean(true)), None);
        assert_eq!(dimen_value(&Value::Number(2.5)), Some(3));
        assert_eq!(dimen_value(&Value::Number(-2.5)), Some(-2));
        assert_eq!(dimen_value(&Value::Number(-1.5)), Some(-1));
        assert_eq!(dimen_value(&Value::Number(0.49)), Some(0));
        assert_eq!(dimen_value(&Value::Integer(4_294_967_301)), Some(i32::MIN));
        assert_eq!(dimen_value(&Value::Number(f64::NAN)), Some(i32::MIN));
        assert_eq!(dimen_value(&Value::Nil), None);
    }
}