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
//! The command stream a TeX file compiles to.
//!
//! TeX has no expression grammar to parse into a tree — the mouth and the
//! expander hand the stomach a flat run of primitive commands. That run IS this
//! frontend's AST, and it is what `crate::compiler` lowers to fusevm bytecode.
//!
//! Macro expansion happens BEFORE this, in the expander, exactly as a
//! conventional frontend runs its parser before lowering. What survives to here
//! is only what has to happen at run time: register writes, arithmetic,
//! branches, and output.
pub mod list;
/// Where a number comes from at run time.
#[derive(Clone, Debug)]
pub enum Num {
Literal(i64),
/// `\count<n>` — a register read.
Count(i64),
/// A register read, negated: §440's `-\count<n>`, where an odd number of
/// minus signs stands before an internal quantity.
Neg(i64),
/// `tex.web` §453's `<factor><internal unit>` — size10.clo's `10\p@`.
///
/// The unit is a REGISTER, so the product cannot be taken while lowering:
/// `\p@` is a slot whose value the program decides. A variant rather than a
/// scratch-register `Cmd::Arith` sequence because a `Num` stands where an
/// expression does -- an `\ifdim` condition and a `\message` body have
/// nowhere to put a statement, and a scratch register would clobber one the
/// document can see.
Scaled {
/// The factor's integer part, carrying §453's sign.
int: i64,
/// The factor's fraction in 65536ths, carrying the same sign.
frac: i64,
/// The slot the internal dimension lives in.
reg: i64,
},
/// `tex.web` §449's other half, where the FACTOR is an internal integer:
/// size10.clo's `\setlength\textheight{\@tempcnta\baselineskip}`. Both
/// operands are slots, so the product waits for the program the same way
/// `Scaled`'s does.
ByCount {
/// The slot the integer factor lives in.
factor: i64,
/// §453's sign, which rides on the factor.
sign: i64,
/// What it multiplies: another slot, or a written unit's own value.
unit: Box<Num>,
},
/// `\rustcall <name> <args>\endrust` — a call into a compiled `\rust{ … }`
/// block. It is a `Num` rather than a command of its own because that is
/// where a value is useful: anywhere TeX reads a number, which is a register
/// assignment, an arithmetic operand, a conditional, or a `\message` body.
Rust {
name: String,
args: Vec<Num>,
},
/// One step of e-TeX's `scan_expr` (`\numexpr`, `\dimexpr`): `op` applied
/// to the operands under the bound `max`, by `crate::etex_arith::apply`.
/// A `Num` because an operand may be a register, whose value is the run's;
/// the lowerer folds a step whose operands it knows. An out-of-range step
/// is `etex_arith::ERROR`, and so is every step that reads one.
Expr {
op: crate::etex_arith::Op,
max: i64,
args: Vec<Num>,
},
/// The end of an expression: its value, or zero and `report` -- `!
/// Arithmetic overflow` with the context where the expression ended,
/// taken while lowering -- if a step went out of range.
ExprEnd {
value: Box<Num>,
report: String,
},
}
#[derive(Clone, Copy, Debug)]
pub enum Rel {
Less,
Equal,
Greater,
}
#[derive(Clone, Copy, Debug)]
pub enum Arith {
Add,
Mul,
Div,
}
/// One step of building a `\message`.
///
/// A message is assembled at RUN time, not folded to a string while lowering,
/// because a conditional inside one tests registers the VM holds. `\ifnum`
/// there becomes a real branch around the pieces it selects, exactly as it does
/// in running text.
#[derive(Clone, Debug)]
pub enum MsgOp {
Text(String),
/// A report -- `! ...` or `\show`'s `> ...` with its context -- made while
/// lowering. Printed like `Text`, except that tex starts it on a fresh line
/// (§62's `print_nl`), so a message that opens with one carries no space.
Report(String),
Number(Num),
/// A number rendered as a DIMENSION -- `\the\dimen0` gives `1.0pt`, not
/// `65536`. The value is scaled points either way; what differs is how it
/// is written, so this carries the same `Num` and asks the runtime for
/// TeX's `print_scaled` instead of a plain integer.
Dimen(Num),
/// A number written as lowercase roman numerals (`\romannumeral`), which
/// a register's run-time value needs as much as `\number` does.
Roman(Num),
/// A glue, rendered from its four slots: natural, stretch, shrink and the
/// packed orders.
Glue([Num; 4]),
/// The same four slots, written in MATH units: `\the\muskip0` gives
/// `3.0mu`, not `3.0pt`. The numbers are identical -- a mu is 65536ths as a
/// point is -- so this differs from `Glue` only in what §1060 prints after
/// each finite component.
MuGlue([Num; 4]),
/// A number computed and thrown away, for a call made for its effect —
/// `\rustcall` in running text rather than inside a message body. It rides
/// the message machinery because that is where a run-time value already has
/// somewhere to be evaluated; nothing is appended.
Discard(Num),
If {
left: Num,
rel: Rel,
right: Num,
then_ops: Vec<MsgOp>,
else_ops: Vec<MsgOp>,
},
IfOdd {
value: Num,
then_ops: Vec<MsgOp>,
else_ops: Vec<MsgOp>,
},
/// §1296's `show_box` of box register `n`, as the program holds it:
/// `void`, or the box displayed as §198 displays one.
ShowBox(u16),
/// §1293's `show_activities`: the semantic nest as the program holds it.
ShowLists,
}
#[derive(Clone, Debug)]
pub enum Cmd {
/// `\rustcompile <base64>\endrust` — compile and register the functions a
/// `\rust{ … }` block exported. It is a run-time command, not a compile-time
/// one: compiling calls `rustc`, and doing that while LOWERING would mean a
/// document could not be lowered on a machine that only has to run it.
RustCompile(String),
/// The source line the commands after this one came from.
///
/// A line directive, the way any compiler carries one: the lowerer emits it
/// when the line changes, and the code generator stamps it onto every op it
/// emits afterwards. Without it every op in the chunk reports line 0, which
/// makes a disassembly unreadable and a source-line debugger impossible.
/// It generates no code.
Line(u32),
/// `\count<n>=<num>`
SetCount(i64, Num),
/// `\advance`/`\multiply`/`\divide` on a count register.
Arith(Arith, i64, Num),
/// `\multiply` or `\divide` of the glue register whose width is in the
/// slot given (`tex.web` §1240): width, stretch and shrink scaled by the
/// same integer, and §1236's ONE test of `arith_error` after all three --
/// an overflow in any component reports once and leaves the whole glue as
/// it was. The orders are not touched.
GlueArith(Arith, i64, Num),
/// Where the next command would be reported from, as `tex.web` §311's
/// context display for that point in the source.
///
/// An interpreter reads the display off the input stack at the moment the
/// error happens. A compiled engine has no input stack left by then --
/// `\multiply` overflows on the VM, long after the mouth closed the file --
/// so the display is taken while lowering and carried to the run. Emitted
/// only in front of a command that can report, which is the checked
/// arithmetic of §1236 and nothing else so far.
ErrorSite(String),
/// `tex.web` §1335's `(see the transcript file for additional information)`,
/// printed at the END of a run that reported anything.
///
/// Carries the `(\end occurred ...)` lines §1335 prints before it, which
/// are facts about where `\end` stood and so are known while lowering.
///
/// A command rather than text because §1335 consults `history`, which is a
/// fact about the whole run: an error the VM reported is as much a reason
/// to print it as one the lowerer reported, and only the VM knows whether
/// one happened. Emits nothing when the run was clean.
TranscriptNotice {
notes: Vec<String>,
/// LuaTeX's `final_cleanup` closes the file with `)` hard against what
/// was printed last (`report_stop_file`); tex.web §1335 prints ` )`.
glued: bool,
},
/// A run of the document's own text.
///
/// Ordinary characters -- the words of the document, as opposed to what
/// `\message` prints -- used to be dropped while lowering, because an
/// engine with no stomach has nowhere to put them. That made a 15,000-line
/// book compile to a program that printed nothing: it "ran" and produced 66
/// bytes. This carries them instead, so `--text` can emit what the document
/// says. It is not typesetting: no line breaking, no pages, no fonts. It is
/// the text, in order.
Text(String),
/// Text set in a colour.
///
/// DVI has no colour of its own: a driver is told about it through a
/// `\special`, and `color push rgb R G B` / `color pop` is the pair
/// dvipdfmx and dvips both understand. The body is nested rather than
/// flattened so the pop always matches its push -- colour in TeX is a
/// stack, and a document that opens two and closes one should come out
/// with the outer one still in force.
Color {
rgb: (f64, f64, f64),
body: Vec<Cmd>,
},
/// `\message{...}` — built piece by piece at run time.
Message(Vec<MsgOp>),
/// Reports the lowerer made, printed where they stand: added to the message
/// being built, as a report the VM makes is, so that what is printed next
/// begins hard against them -- tex ends an error's context with `print_ln`.
Reports(Vec<MsgOp>),
/// `\immediate\write` to the terminal, built as a message is. §1370's
/// `write_out` starts it with `print_nl` and ends it with `print_ln`, so it
/// sits on a line of its own: nothing between it and what came before, and
/// no space in front of the `\message` after it.
Write(Vec<MsgOp>),
/// `\openout`, done now: the stream and the name of the file
/// (`crate::write::out_file_name`), which the run creates. See
/// `crate::write` for why the run and not the lowerer holds the file.
OpenOut { stream: usize, name: String },
/// `\write` to one of the 128 streams, which the run may or may not have
/// open -- a conditional the run decides can open or close one -- so both
/// lines are lowered and the run picks: `file`, built as a message is and
/// written to the stream's file (`crate::write::file_ops`), or `otherwise`,
/// what §1370 does for a closed stream, which is the terminal's `Write`.
WriteOut {
stream: usize,
file: Vec<MsgOp>,
otherwise: Vec<Cmd>,
},
/// `\closeout`, done now.
CloseOut(usize),
/// A `\special` whose text reads what only the run knows (§1354):
/// the text built as a message's is, then appended to the current list
/// as `ListOp::Whatsit`. One whose text the lowerer knows is a
/// `Cmd::List` of that action directly.
Special(Vec<MsgOp>),
/// `\openout`, `\write` or `\closeout` without `\immediate`, on the list
/// path: `body` is what §1374 does with the whatsit, compiled into a
/// sub-chunk the run calls when the page holding the node is shipped,
/// and the node goes on the current list as `ListOp::OutWhatsit`.
OutWhatsit { display: String, body: Vec<Cmd> },
/// The `)` that closes an `\input` file, attached to the message before it.
///
/// tex writes `(./inner.tex [msg])` with no space in front of the paren,
/// while it puts one before every message. The message stream here is a list
/// joined by spaces, so the paren cannot be a message of its own -- it has to
/// be appended to the one already there, which is what this asks the runtime
/// to do. A file that printed nothing closes its own open paren the same way,
/// giving `(./inner.tex)`.
FileClose,
/// A group: the listed count registers are saved on entry and restored on
/// exit, which is what `{\count0=99}` needs and the macro table alone
/// cannot give — a register lives in a VM slot, not in the frontend.
///
/// `keeps` are the registers the body also assigns `\global`ly, each with
/// a scratch slot of its own. `tex.web` §283 restores such a register to
/// the value its LAST global assignment left (a local assignment after it
/// saved that value, and `unsave` throws away a save whose level a global
/// reset), or to its value on entry if no global assignment ran. So the
/// scratch slot takes the entry value, every [`Cmd::KeepGlobal`] for the
/// register refreshes it, and the `}` writes it back.
Group {
saves: Vec<i64>,
keeps: Vec<(i64, u16)>,
body: Vec<Cmd>,
},
/// Just after a `\global` assignment to `reg`: copy its new value into the
/// scratch slot of every enclosing group that keeps it (see `Cmd::Group`).
/// With no such group it generates no code.
KeepGlobal { reg: i64, into: Vec<u16> },
/// `\ifnum<a><rel><b>` … `\else` … `\fi`
IfNum {
left: Num,
rel: Rel,
right: Num,
then_branch: Vec<Cmd>,
else_branch: Vec<Cmd>,
},
/// A tail-recursive macro, as a run-time loop.
///
/// `\def\r{BODY \ifnum A<B \r \fi}` is TeX's loop idiom: run the body,
/// test, and invoke yourself again while the test holds. Inlining that is
/// what used to run the lowerer out of stack, because the copy contains the
/// call that gets copied. As a loop it is finite bytecode AND faster than a
/// call would be -- a backward `Jump` with no frame to push, which is a
/// shape the JIT already recognises.
///
/// The test runs AFTER the body, matching the idiom: the body always
/// executes once, exactly as the first `\r` does before reaching its own
/// conditional.
Loop {
body: Vec<Cmd>,
left: Num,
rel: Rel,
right: Num,
},
/// `\ifodd<num>` … `\else` … `\fi`
IfOdd {
value: Num,
then_branch: Vec<Cmd>,
else_branch: Vec<Cmd>,
},
/// A list action: one of `main_control`'s cases, dispatched while
/// lowering and carried out by `crate::stomach` when the program runs.
List(list::ListOp),
/// `\output` as the page builder will run it (§1025): the routine,
/// lowered as one group, compiled into a sub-chunk of its own; `None`
/// for an empty `\output`, which is §1023's default.
OutputRoutine(Option<Vec<Cmd>>),
}
/// The command stream as an indented tree, for `--dump-ast`.
///
/// `{:#?}` would also print it, but as Rust: field names, `Some(...)`, a line
/// per brace. This prints the shape a reader of the DOCUMENT is looking for --
/// one node per line, children indented under the construct that owns them --
/// so a `\ifnum` shows its two branches and a tail-recursive macro shows the
/// loop it lowered to rather than the call it was written as.
pub fn render(cmds: &[Cmd]) -> String {
let mut out = String::new();
render_into(cmds, 0, &mut out);
out
}
fn render_into(cmds: &[Cmd], depth: usize, out: &mut String) {
for cmd in cmds {
let pad = " ".repeat(depth);
match cmd {
Cmd::RustCompile(_) => out.push_str(&format!("{pad}RustCompile <block>\n")),
Cmd::Line(n) => out.push_str(&format!("{pad}Line {n}\n")),
Cmd::List(op) => out.push_str(&format!("{pad}List {op:?}\n")),
Cmd::OutputRoutine(None) => out.push_str(&format!("{pad}OutputRoutine none\n")),
Cmd::OutputRoutine(Some(body)) => {
out.push_str(&format!("{pad}OutputRoutine\n"));
render_into(body, depth + 1, out);
}
Cmd::Color { rgb, body } => {
let (r, g, b) = rgb;
out.push_str(&format!("{pad}Color rgb {r} {g} {b}\n"));
render_into(body, depth + 1, out);
}
Cmd::SetCount(reg, num) => {
out.push_str(&format!("{pad}SetCount \\count{reg} = {}\n", num_text(num)))
}
Cmd::Arith(op, reg, num) => {
out.push_str(&format!("{pad}{op:?} \\count{reg} by {}\n", num_text(num)))
}
Cmd::GlueArith(op, reg, num) => {
out.push_str(&format!("{pad}{op:?} glue at {reg} by {}\n", num_text(num)))
}
Cmd::ErrorSite(site) => out.push_str(&format!("{pad}ErrorSite {site:?}\n")),
Cmd::TranscriptNotice { notes, .. } => {
out.push_str(&format!("{pad}TranscriptNotice {notes:?}\n"))
}
Cmd::Text(t) => out.push_str(&format!("{pad}Text {t:?}\n")),
Cmd::FileClose => out.push_str(&format!("{pad}FileClose\n")),
Cmd::Message(ops) => {
out.push_str(&format!("{pad}Message\n"));
render_msg(ops, depth + 1, out);
}
Cmd::Reports(ops) => {
out.push_str(&format!("{pad}Reports\n"));
render_msg(ops, depth + 1, out);
}
Cmd::Write(ops) => {
out.push_str(&format!("{pad}Write\n"));
render_msg(ops, depth + 1, out);
}
Cmd::OpenOut { stream, name } => {
out.push_str(&format!("{pad}OpenOut {stream} {name:?}\n"))
}
Cmd::WriteOut {
stream,
file,
otherwise,
} => {
out.push_str(&format!("{pad}WriteOut {stream}\n"));
render_msg(file, depth + 1, out);
out.push_str(&format!("{pad}closed\n"));
render_into(otherwise, depth + 1, out);
}
Cmd::CloseOut(stream) => out.push_str(&format!("{pad}CloseOut {stream}\n")),
Cmd::Special(ops) => {
out.push_str(&format!("{pad}Special\n"));
render_msg(ops, depth + 1, out);
}
Cmd::OutWhatsit { display, body } => {
out.push_str(&format!("{pad}OutWhatsit {display:?}\n"));
render_into(body, depth + 1, out);
}
Cmd::KeepGlobal { reg, into } => {
out.push_str(&format!("{pad}KeepGlobal \\count{reg} into={into:?}\n"))
}
Cmd::Group { saves, keeps, body } => {
match keeps.is_empty() {
true => out.push_str(&format!("{pad}Group saves={saves:?}\n")),
false => out.push_str(&format!("{pad}Group saves={saves:?} keeps={keeps:?}\n")),
}
render_into(body, depth + 1, out);
}
Cmd::IfNum {
left,
rel,
right,
then_branch,
else_branch,
} => {
out.push_str(&format!(
"{pad}IfNum {} {} {}\n",
num_text(left),
rel_text(*rel),
num_text(right)
));
render_branches(then_branch, else_branch, depth, out);
}
Cmd::IfOdd {
value,
then_branch,
else_branch,
} => {
out.push_str(&format!("{pad}IfOdd {}\n", num_text(value)));
render_branches(then_branch, else_branch, depth, out);
}
Cmd::Loop {
body,
left,
rel,
right,
} => {
// The test prints after the body because that is when it runs:
// the body always executes once, as the first call does before
// reaching its own conditional.
out.push_str(&format!("{pad}Loop\n"));
render_into(body, depth + 1, out);
out.push_str(&format!(
"{pad} while {} {} {}\n",
num_text(left),
rel_text(*rel),
num_text(right)
));
}
}
}
}
/// The two arms of a conditional, each named, and an empty one said to be empty
/// rather than left out -- `\ifnum` with no `\else` and `\ifnum` whose `\else`
/// lowered to nothing are different documents.
fn render_branches(then_branch: &[Cmd], else_branch: &[Cmd], depth: usize, out: &mut String) {
let pad = " ".repeat(depth + 1);
out.push_str(&format!("{pad}then\n"));
render_into(then_branch, depth + 2, out);
out.push_str(&format!("{pad}else\n"));
render_into(else_branch, depth + 2, out);
}
fn render_msg(ops: &[MsgOp], depth: usize, out: &mut String) {
for op in ops {
let pad = " ".repeat(depth);
match op {
MsgOp::Text(t) => out.push_str(&format!("{pad}Text {t:?}\n")),
MsgOp::Report(t) => out.push_str(&format!("{pad}Report {t:?}\n")),
MsgOp::Number(n) => out.push_str(&format!("{pad}Number {}\n", num_text(n))),
MsgOp::Dimen(n) => out.push_str(&format!("{pad}Dimen {}\n", num_text(n))),
MsgOp::Roman(n) => out.push_str(&format!("{pad}Roman {}\n", num_text(n))),
MsgOp::Glue(parts) => out.push_str(&format!("{pad}Glue {}\n", num_text(&parts[0]))),
MsgOp::MuGlue(parts) => out.push_str(&format!("{pad}MuGlue {}\n", num_text(&parts[0]))),
MsgOp::Discard(n) => out.push_str(&format!("{pad}Discard {}\n", num_text(n))),
MsgOp::ShowBox(n) => out.push_str(&format!("{pad}ShowBox \\box{n}\n")),
MsgOp::ShowLists => out.push_str(&format!("{pad}ShowLists\n")),
MsgOp::If {
left,
rel,
right,
then_ops,
else_ops,
} => {
out.push_str(&format!(
"{pad}IfNum {} {} {}\n",
num_text(left),
rel_text(*rel),
num_text(right)
));
out.push_str(&format!("{pad} then\n"));
render_msg(then_ops, depth + 2, out);
out.push_str(&format!("{pad} else\n"));
render_msg(else_ops, depth + 2, out);
}
MsgOp::IfOdd {
value,
then_ops,
else_ops,
} => {
out.push_str(&format!("{pad}IfOdd {}\n", num_text(value)));
out.push_str(&format!("{pad} then\n"));
render_msg(then_ops, depth + 2, out);
out.push_str(&format!("{pad} else\n"));
render_msg(else_ops, depth + 2, out);
}
}
}
}
/// A number written the way the document wrote it: a literal as itself, a
/// register as `\count<n>`, a call as its name and arguments.
fn num_text(num: &Num) -> String {
match num {
Num::Literal(v) => v.to_string(),
Num::Count(n) => format!("\\count{n}"),
Num::Neg(n) => format!("-\\count{n}"),
// The factor as the document wrote it, then the register it scales.
Num::Scaled { int, frac, reg } => format!(
"{}\\count{reg}",
crate::dimen::print_scaled(int * crate::dimen::UNITY + frac)
),
// The factor is a register here, so it is written as one.
Num::ByCount { factor, sign, unit } => format!(
"{}\\count{factor}{}",
match sign {
s if *s < 0 => "-",
_ => "",
},
num_text(unit)
),
Num::Rust { name, args } => {
let args: Vec<String> = args.iter().map(num_text).collect();
format!("\\rustcall {name} {}", args.join(" "))
}
Num::Expr { op, args, .. } => {
let args: Vec<String> = args.iter().map(num_text).collect();
format!("{op:?}({})", args.join(", "))
}
Num::ExprEnd { value, .. } => format!("\\numexpr {}\\relax", num_text(value)),
}
}
fn rel_text(rel: Rel) -> &'static str {
match rel {
Rel::Less => "<",
Rel::Equal => "=",
Rel::Greater => ">",
}
}
/// `tex.web` §59's `print` of one string to the terminal or the log: the
/// character `\newlinechar` names ends the line, and an unprintable character
/// is written in §49's `^^` notation (`^^M` for 13, `^^?` for 127).
/// texrs's own in-band markers ([`crate::typeset::is_marker`]) pass through
/// raw for `without_marks` to remove, so a document's own `^^Q` is written
/// raw too.
///
/// Characters from 128 up are written as they are. Knuth's `tex` would write
/// them as `^^e9`, but texrs holds its input as decoded Unicode, where a
/// UTF-8 `é` and a `^^e9` are the same character, and TeX Live's 8-bit engines
/// print both raw under their default `cp227.tcx`.
pub fn printed(text: &str, new_line_char: i64) -> String {
let nl = u32::try_from(new_line_char).ok().filter(|n| *n <= 255);
let mut out = String::with_capacity(text.len());
for c in text.chars() {
let code = u32::from(c);
if Some(code) == nl {
out.push('\n');
} else if crate::typeset::is_marker(c) {
out.push(c);
} else if code < 32 {
out.push_str("^^");
out.push(char::from(code as u8 + 64));
} else if code == 127 {
out.push_str("^^?");
} else {
out.push(c);
}
}
out
}
/// [`printed`] over every piece of text a message writes. The numbers,
/// dimensions and glue it renders at run time are printable already.
pub fn printed_ops(ops: Vec<MsgOp>, new_line_char: i64) -> Vec<MsgOp> {
ops.into_iter()
.map(|op| match op {
MsgOp::Text(t) => MsgOp::Text(printed(&t, new_line_char)),
MsgOp::If {
left,
rel,
right,
then_ops,
else_ops,
} => MsgOp::If {
left,
rel,
right,
then_ops: printed_ops(then_ops, new_line_char),
else_ops: printed_ops(else_ops, new_line_char),
},
MsgOp::IfOdd {
value,
then_ops,
else_ops,
} => MsgOp::IfOdd {
value,
then_ops: printed_ops(then_ops, new_line_char),
else_ops: printed_ops(else_ops, new_line_char),
},
other => other,
})
.collect()
}