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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
//! The `texrs` driver.
//!
//! Running a file prints the `\message` stream the way `tex` prints it on the
//! terminal — `(./file.tex <messages> )` — which is the comparison
//! `cargo run --bin parity` makes against the real engine. The introspection flags
//! stop earlier in the same pipeline: `--dump-tokens` after the mouth,
//! `--disasm` after lowering, so each stage can be read on its own.
use std::path::{Path, PathBuf};
use std::process::ExitCode;
fn main() -> ExitCode {
struct Stats;
impl Drop for Stats {
fn drop(&mut self) {
if std::env::var_os("TEXRS_PRELEX_STATS").is_some() {
prelex_stats();
}
}
}
let _stats = Stats;
// The document commands come first: `-X` takes over the whole invocation,
// as tectonic's V2 interface does, so nothing below has to know about them.
let args: Vec<String> = std::env::args().skip(1).collect();
if args.first().map(String::as_str) == Some("-X") {
// `TEXRS_THREADS` sizes the workers here too: `-X bibtex` walks a
// style in parallel.
texrs::parallel::configure(None);
return run_document(&args[1..]);
}
let cli = match texrs::cli::parse(&args) {
Ok(c) => c,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(1);
}
};
// Where `\openout` writes a relative name, as tex's own option says.
texrs::write::set_output_directory(cli.output_directory.clone());
// A web2c engine takes its personality from the program name it runs
// as (`pdftex -progname=pdflatex`). Run as a LuaTeX -- `-progname=luatex`,
// `lualatex` or `luahbtex`, or with a format of one of those names --
// texrs has LuaTeX's register ranges; otherwise TeX82's.
texrs::expand::set_luatex_registers(cli.is_luatex());
match cli.mode {
texrs::cli::Mode::Help => {
// Colour on a terminal, plain bytes down a pipe -- the same rule the
// rest of the fleet's help follows, and what keeps an escape out of
// a file someone is grepping.
let colored = texrs::banner::colored_stdout();
texrs::banner::print_banner(colored);
print!(
"{}",
texrs::banner::render_usage(texrs::cli::USAGE, colored)
);
return ExitCode::SUCCESS;
}
texrs::cli::Mode::Version => {
println!("{}", texrs::banner::version_banner());
return ExitCode::SUCCESS;
}
texrs::cli::Mode::Repl => {
return match texrs::repl::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::Lsp => {
return match texrs::lsp::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::Dap => {
return match texrs::dap::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
texrs::cli::Mode::CacheStats => return cache_stats(),
texrs::cli::Mode::CacheClear => return cache_clear(),
texrs::cli::Mode::Run => {}
}
let (build, dump_tokens, disasm, aot, tiers, no_cache, jobs) = (
cli.build,
cli.dump_tokens,
cli.disasm,
cli.aot,
cli.tiers,
cli.no_cache,
cli.jobs,
);
let mut paths = cli.files.clone();
texrs::parallel::configure(jobs);
// `texrs '\message{hi}\end'` -- tex's second invocation form, where the
// arguments ARE the input. There is no file, so there is no `(./name.tex …)`
// wrapper either: tex prints the messages bare, and so does this.
if paths.is_empty() {
if let Some(src) = cli.command_line_source() {
return run_command_line(&src, cli.interaction);
}
}
// No file and nothing on the command line: the prompt. `tex` prompts for
// input here too -- an engine invoked with nothing to do should ask, not
// print its usage and quit.
if paths.is_empty() {
return match texrs::repl::run() {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e),
};
}
// More than one document is the case that actually parallelises. Each is an
// independent compile -- its own mouth, macro table and chunk -- sharing
// nothing but the on-disk bytecode cache, so running them together is a
// straight fan-out. `tex` cannot do this at all: one process compiles one
// file, and a user wanting more reaches for `make -j`.
if paths.len() > 1 && !dump_tokens && !cli.dump_ast && !disasm && !tiers {
return run_many(&paths, jobs);
}
let path = paths.remove(0);
// The document is opened through the provider stack rather than read
// directly: the stack is what `\input` will search, and opening the primary
// through it means the run's record of what it read starts with the
// document itself.
let mut inputs = texrs::io::ProviderStack::new();
inputs.push(Box::new(
texrs::io::FilesystemProvider::with_roots(Vec::new()).with_primary(&path),
));
let src = match texrs::io::InputProvider::input_open_primary(&mut inputs) {
texrs::io::OpenResult::Ok(input) => input.content,
texrs::io::OpenResult::NotAvailable => {
eprintln!("texrs: {path}: no such file");
return ExitCode::from(1);
}
texrs::io::OpenResult::Err(e) => {
eprintln!("texrs: {path}: {e}");
return ExitCode::from(1);
}
};
if cli.dump_ast {
// The stage between the two that already print: the mouth's tokens are
// before expansion, the disassembly is after code generation, and this
// is what the frontend actually produced -- expansion done, nothing
// lowered to bytecode yet. It does NOT go to the bytecode cache,
// because it never reaches the code generator.
return match texrs::commands(&src) {
Ok(cmds) => {
print!("{}", texrs::ir::render(&cmds));
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if dump_tokens {
// The mouth alone: no expansion, so what prints is what the category
// codes made of the bytes and nothing more.
let cats = texrs::catcode::CatTable::new();
let mut lx = texrs::lexer::Lexer::new(&src);
while let Some(t) = lx.next_token(&cats) {
println!("{t:?}");
}
return ExitCode::SUCCESS;
}
if disasm {
// The same bytecode an ordinary run would execute, so it goes to the
// cache like one: a listing is a compile, and the next run should not
// have to do it again.
let compiled = match no_cache {
true => texrs::compile(&src),
false => texrs::compile_cached(std::path::Path::new(&path), &src),
};
return match compiled {
Ok(chunk) => {
print!("{}", chunk.disassemble());
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if aot {
// The executable sits beside the document, named after it: `doc.tex`
// compiles to `doc`, the way a C file compiles to a program.
let out = output_path(&cli, &path, "");
return match texrs::aot::compile_executable(&path, &out) {
Ok(p) => {
println!("{}", p.display());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if build {
// Compile into the bytecode cache and stop. `\rust{ … }` blocks and
// `\message` are RUN-time effects, so a build has neither -- which is
// the point: it warms the cache in a build step, and the run that
// follows starts from bytecode.
return match texrs::compile_cached(std::path::Path::new(&path), &src) {
Ok(chunk) => {
println!(
"built {path}: {} ops -> {}",
chunk.ops.len(),
texrs::script_cache::default_cache_path().display()
);
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
if tiers {
// The report runs the document, so its own output comes first: what is
// measured is what an ordinary run does. It compiles rather than
// reading the cache, because the question is about this bytecode.
return match texrs::tiers::report(&src) {
Ok(r) => {
println!("{r}");
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
// tex reads the command line as more input AFTER the file -- but only if
// the file did not end the run. `\end` inside it stops everything, and the
// trailing arguments are never seen.
let trailing = cli
.command_line_source()
.filter(|_| !texrs::source_ends_run(&src));
if let Some(extra) = trailing {
return run_with_trailing(&path, &src, &extra, cli.interaction);
}
// The cache keys on the file, so it is only used when there is one and the
// run has not asked to go without it.
if cli.pdf_out {
return match texrs::run_pdf_with_messages(Some(std::path::Path::new(&path)), &src) {
Ok((texrs::Pdf { bytes, pages }, _)) => {
let out = output_path(&cli, &path, "pdf");
// A document with nothing on it gets no file. Measured, that is
// what luatex does -- `luatex empty_document.tex` says
// `warning (pdf backend): no pages of output.` and leaves the
// directory holding only the log -- and what tex and pdftex do
// for the same document. texrs wrote a valid PDF declaring zero
// pages instead, which poppler answers with `Syntax Error:
// Invalid page count 0`: a file no reader will open is worse
// than the absence of one, and the absence is also the answer
// the reference engine gives.
if pages == 0 {
println!("({path} -> no pages of output)");
return ExitCode::SUCCESS;
}
match std::fs::write(&out, &bytes) {
Ok(()) => {
println!("({path} -> {} [{} bytes])", out.display(), bytes.len());
ExitCode::SUCCESS
}
Err(e) => fail(&format!("{}: {e}", out.display())),
}
}
Err(e) => fail(&e.0),
};
}
if cli.dvi_out {
// A page, at last. The font is plain TeX's own; without a .tfm there
// are no widths and so no line breaking, which is why a missing one is
// an error rather than a silent fallback to guessed metrics.
// cmr10 sets the text; cmsy10 carries the arrows and set operators it
// has no slot for. This is the per-glyph fallback that made LuaTeX a
// requirement for these documents.
let chain = match texrs::typeset::FontChain::load("cmr10", &["cmsy10", "cmmi10"]) {
Ok(c) => c,
Err(e) => return fail(&format!("--dvi: {e} (is a TeX installation present?)")),
};
let layout = texrs::typeset::Layout::default();
let keyed = match no_cache {
true => None,
false => Some(std::path::Path::new(&path)),
};
let built = texrs::run_dvi_fallback(keyed, &src, &chain, &layout);
return match built {
// tex.web §642: a run that shipped no page writes no file, only
// the line saying so: the DVI is opened by the first `ship_out` (§617).
Ok(bytes) if texrs::dvi::Dvi::parse(&bytes).is_ok_and(|d| d.pages() == 0) => {
println!("No pages of output.");
ExitCode::SUCCESS
}
Ok(bytes) => {
let out = output_path(&cli, &path, "dvi");
match std::fs::write(&out, &bytes) {
Ok(()) => {
println!("({path} -> {} [{} bytes])", out.display(), bytes.len());
ExitCode::SUCCESS
}
Err(e) => fail(&format!("{}: {e}", out.display())),
}
}
Err(e) => fail(&e.0),
};
}
if cli.text {
// The document's own words, after expansion. Printed as-is: this is not
// a typeset page and does not pretend to be one. Told which FILE it is,
// so a cross reference is answered out of the `.aux` beside the
// document -- run with a string and nothing else, every `\ref` in it
// stays `??`.
let at = std::path::Path::new(&path);
let run = match no_cache {
true => texrs::run_text_at(at, &src),
false => texrs::run_text_cached(at, &src),
};
return match run {
Ok(text) => {
print!("{text}");
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
};
}
// The ordinary invocation writes a PDF, because that is the job: texrs
// stands in for lualatex in a pipeline, and `lualatex FILE` leaves a
// FILE.pdf behind. It prints what tex prints as well — the file line with
// the document's messages in it — so a script reading either engine's
// terminal output sees the same thing, and then the line lualatex writes to
// announce the file.
match texrs::run_pdf_with_messages(Some(std::path::Path::new(&path)), &src) {
Ok((pdf, msgs)) => {
let tail = match write_pdf(&path, &pdf) {
Ok(t) => t,
Err(e) => return fail(&e),
};
if cli.interaction.prints() {
println!(
"{}",
texrs::file_line(&path, &msgs.join(" "), texrs::source_ends_run(&src))
);
println!("{tail}");
}
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
}
}
/// Compile and run several documents at once, one per core.
///
/// Each document is wholly independent -- its own mouth, catcode table, macro
/// table and chunk -- so this is a fan-out with nothing to synchronise but the
/// bytecode cache, which takes a writer lock of its own. `tex` has no
/// equivalent: one process compiles one file, and a user who wants more runs
/// `make -j` and gets a process per document instead of a thread.
///
/// Output is printed in ARGUMENT order however the threads finish, because a
/// build log that reorders itself between runs is not a log anyone can diff.
/// The exit code is the worst of the runs: one bad document fails the batch.
fn run_many(paths: &[String], jobs: Option<usize>) -> ExitCode {
let workers = jobs
.unwrap_or_else(texrs::parallel::default_threads)
.max(1)
.min(paths.len());
let next = std::sync::atomic::AtomicUsize::new(0);
let results: Vec<std::sync::Mutex<Option<Result<String, String>>>> = (0..paths.len())
.map(|_| std::sync::Mutex::new(None))
.collect();
std::thread::scope(|scope| {
for _ in 0..workers {
scope.spawn(|| {
// A shared cursor rather than a fixed slice each: documents
// differ in size by orders of magnitude, so handing out equal
// COUNTS would leave one worker with the big one and the rest
// idle. Taking the next index as each finishes balances it.
loop {
let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
if i >= paths.len() {
break;
}
*results[i].lock().expect("result slot") = Some(one_document(&paths[i]));
}
});
}
});
let mut code = ExitCode::SUCCESS;
let mut failed = false;
for (i, slot) in results.iter().enumerate() {
match slot.lock().expect("result slot").take() {
Some(Ok(line)) => println!("{line}"),
Some(Err(e)) => {
eprintln!("! {e}.");
failed = true;
}
None => {
eprintln!("texrs: {}: not run", paths[i]);
failed = true;
}
}
}
if failed {
code = ExitCode::from(1);
}
code
}
/// Where an output file goes: beside the input, or in the directory the run
/// asked for.
///
/// `-output-directory=DIR` was parsed and then read by nothing. Four mentions
/// of it existed -- the field, its default, the parse arm and a test asserting
/// that the parse succeeds -- and not one consumer, so every file landed next
/// to its input whatever the flag said.
///
/// That is not a missing convenience. It is how a render of a corpus document
/// overwrote the reference PDF it was being compared against: the command
/// pointed its output somewhere else, was told nothing, and wrote over the
/// input's neighbour. A flag that is accepted and ignored is worse than one
/// that is refused, because the caller has no way to find out.
fn output_path(cli: &texrs::cli::Cli, input: &str, extension: &str) -> PathBuf {
let named = Path::new(input).with_extension(extension);
match &cli.output_directory {
// The basename travels; the directory is the one that was asked for.
Some(dir) => match named.file_name() {
Some(base) => dir.join(base),
None => named,
},
None => named,
}
}
/// Write the PDF a run produced and say what became of it, the way lualatex
/// does: the file line first, then `Output written on …`.
///
/// A document that ships no page gets no file and says so. tex and lualatex
/// both behave that way, and writing an empty PDF for a document with nothing
/// on it is the divergence `pdf-parity` reports for `empty_document.tex` — it
/// would have become the everyday behaviour the moment the ordinary invocation
/// started writing.
fn write_pdf(path: &str, pdf: &texrs::Pdf) -> Result<String, String> {
let out = Path::new(path).with_extension("pdf");
if pdf.pages > 0 {
std::fs::write(&out, &pdf.bytes).map_err(|e| format!("{}: {e}", out.display()))?;
}
// The wording lives in the library so the `--aot` binary, which has no main
// of its own to keep in step, reports the same line.
Ok(texrs::pdf_output_line(&out, pdf.pages, &pdf.bytes))
}
/// One document, as the single-file path runs it, returning the line to print.
/// A typesetting run does not consult the bytecode shard: the cache holds
/// compiled chunks, and the fonts, page colour and layout a page needs are read
/// while lowering and are not in it. `--no-cache` has nothing to turn off here.
fn one_document(path: &str) -> Result<String, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
let (pdf, msgs) = texrs::run_pdf_with_messages(Some(Path::new(path)), &src).map_err(|e| e.0)?;
let joined = msgs.join(" ");
let body = match joined.is_empty() {
true => String::new(),
false => format!(" {joined}"),
};
let tail = write_pdf(path, &pdf)?;
Ok(format!("(./{path}{body} )\n{tail}"))
}
/// `texrs -X …`: the document commands, ported in shape from tectonic's V2
/// interface — a document is a directory with a `Texrs.toml` in it, and the
/// commands act on the document rather than on a file.
fn run_document(args: &[String]) -> ExitCode {
let Some(command) = args.first().map(String::as_str) else {
eprint!("{}", texrs::banner::render_usage(texrs::cli::USAGE, false));
return ExitCode::from(1);
};
match command {
"new" | "init" => {
// `new` takes a directory; `init` is `new .` under the name
// tectonic gives it, since "make one here" is what a user reaches
// for in a directory that already exists.
let dir = match command {
"init" => PathBuf::from("."),
_ => args
.get(1)
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from(".")),
};
// The document is named after its directory, which is what the
// user has already chosen by making one.
let name = std::fs::canonicalize(&dir)
.ok()
.as_deref()
.and_then(Path::file_name)
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "document".to_string());
match texrs::document::scaffold(&dir, &name) {
Ok(path) => {
println!("wrote {}", path.display());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"bundle" => match args.get(1).map(String::as_str) {
Some("fetch") => {
let Some(url) = args.get(2) else {
return fail("`-X bundle fetch` needs a URL");
};
// The one place texrs uses the network, and only because it was
// asked to. A build never comes here.
match texrs::geturl::fetch(url) {
Ok(got) => {
println!("fetched {} bytes → {}", got.bytes, got.path.display());
println!(
"name it in Texrs.toml as: bundle = \"sha256:{}\"",
got.digest
);
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
Some("list") => {
let fetched = texrs::geturl::fetched();
if fetched.is_empty() {
println!("no bundles fetched");
}
for digest in fetched {
match texrs::geturl::path_for(&digest) {
Some(path) => println!("sha256:{digest} {}", path.display()),
None => println!("sha256:{digest}"),
}
}
ExitCode::SUCCESS
}
other => {
eprintln!(
"texrs: `-X bundle` takes fetch or list, not {}",
other.unwrap_or("nothing")
);
ExitCode::from(1)
}
},
"bib" => {
let Some(file) = args.get(1) else {
return fail("`-X bib` needs a .bib or .aux file");
};
// An `.aux` asks a different question: not "what is in this
// database" but "what does this document cite, and is it there".
if std::path::Path::new(file)
.extension()
.is_some_and(|e| e == "aux")
{
return bib_citations(std::path::Path::new(file));
}
match texrs::bib::Bib::open(file) {
Ok(bib) => {
print!("{}", bib.summary());
// A database that could not be read whole is worth an exit
// status: a harness should not have to grep for "warning".
match bib.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
Err(e) => fail(&e),
}
}
"bibtex" => {
let Some(file) = args.get(1) else {
return fail("`-X bibtex` needs a .aux file");
};
bibtex_run(std::path::Path::new(file))
}
"special" => {
let text = args[1..].join(" ");
if text.trim().is_empty() {
return fail("`-X special` needs the text of a \\special");
}
println!("{}", texrs::special::parse(&text));
ExitCode::SUCCESS
}
"itar" => {
let Some(file) = args.get(1) else {
return fail("`-X itar` needs a .tar bundle");
};
match texrs::itar::Itar::open(file) {
Ok(itar) => match args.get(2) {
// A second argument reads one file out of the archive,
// which is a seek and a read rather than a walk.
Some(name) => match itar.read(name) {
Ok(bytes) => {
use std::io::Write;
match std::io::stdout().write_all(&bytes) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => fail(&e.to_string()),
}
}
Err(e) => fail(&e),
},
None => {
print!("{}", itar.summary());
print!("{}", itar.index());
ExitCode::SUCCESS
}
},
Err(e) => fail(&e),
}
}
"map" => {
let Some(file) = args.get(1) else {
return fail("`-X map` needs a font map, or a map and a TeX font name");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(file),
};
match texrs::fontmap::FontMap::open(&found) {
Ok(map) => match args.get(2) {
// A second argument asks about one TeX font name: what a
// driver would go and read for it.
Some(name) => match map.lookup(name) {
Some(entry) => {
print!("{entry}");
ExitCode::SUCCESS
}
None => fail(&format!("{found}: no entry for {name}")),
},
None => {
print!("{}", map.summary());
ExitCode::SUCCESS
}
},
Err(e) => fail(&e),
}
}
"enc" => {
let Some(file) = args.get(1) else {
return fail("`-X enc` needs an encoding file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
// An encoding is not on the ordinary search path.
false => kpsewhich_format("enc files", file),
};
match texrs::fontmap::Encoding::open(&found) {
Ok(encoding) => {
print!("{}", encoding.summary());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"pfb" => {
let Some(file) = args.get(1) else {
return fail("`-X pfb` needs a Type 1 font");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(&match file.contains('.') {
true => file.to_string(),
false => format!("{file}.pfb"),
}),
};
match texrs::type1::Type1::open(&found) {
Ok(font) => {
match args.get(2).and_then(|c| c.chars().next()) {
// A second argument asks what one character is: which
// glyph the font's own encoding gives, and how wide.
Some(c) if c.is_ascii() => print!("{}", font.describe(c as u8)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", font.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"otf" => {
let Some(file) = args.get(1) else {
return fail("`-X otf` needs an OpenType or TrueType font");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(file),
};
match texrs::sfnt::Sfnt::open(&found) {
Ok(font) => {
match args.get(2).and_then(|c| c.chars().next()) {
// A second argument asks what one character becomes:
// which glyph, called what, and how wide.
Some(c) => print!("{}", font.describe(c as u32)),
None => print!("{}", font.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"pk" => {
let Some(file) = args.get(1) else {
return fail("`-X pk` needs a .pk file");
};
// A packed font is made for one resolution, so a bare name needs
// one: `cmr10.600pk` is how kpsewhich knows which to hand back.
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_format("pk", file),
};
match texrs::pk::Pk::open(&found) {
Ok(pk) => {
match args.get(2).and_then(|c| c.chars().next()) {
// A second argument draws one character.
Some(c) if c.is_ascii() => print!("{}", pk.describe(c as u32)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", pk.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"vf" => {
let Some(file) = args.get(1) else {
return fail("`-X vf` needs a .vf file");
};
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich_named(&match file.ends_with(".vf") {
true => file.to_string(),
false => format!("{file}.vf"),
}),
};
match texrs::vf::Vf::open(&found) {
Ok(vf) => {
match args.get(2).and_then(|c| c.chars().next()) {
// A second argument asks about one character: what it
// really sets, and where.
Some(c) if c.is_ascii() => print!("{}", vf.describe(c as u32)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", vf.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"tfm" => {
let Some(file) = args.get(1) else {
return fail("`-X tfm` needs a .tfm file");
};
// A bare name is a font to look up, so `-X tfm cmr10` works the way
// a person would type it.
let found = match std::path::Path::new(file).exists() {
true => file.to_string(),
false => kpsewhich(file),
};
match texrs::tfm::Tfm::open(&found) {
Ok(tfm) => {
match args.get(2).and_then(|c| c.chars().next()) {
// A second argument asks about one character, with the
// ligatures and kerns it takes part in.
Some(c) if c.is_ascii() => print!("{}", tfm.describe(c as u8)),
Some(c) => return fail(&format!("{c} is not an 8-bit character")),
None => print!("{}", tfm.summary()),
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"bst" => {
let Some(file) = args.get(1) else {
return fail("`-X bst` needs a .bst file");
};
match texrs::bst::Style::open(file) {
Ok(style) => {
print!("{}", style.summary());
// A style that calls a name nothing defines fails at run
// time, one name per bibtex run; saying so here is the
// point of reading it.
match style.undefined().is_empty() && style.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
Err(e) => fail(&e),
}
}
"dvi" => {
let Some(file) = args.get(1) else {
return fail("`-X dvi` needs a .dvi file");
};
let dvi = match texrs::dvi::Dvi::open(file) {
Ok(dvi) => dvi,
Err(e) => return fail(&e),
};
// With a second file, the question is whether the two are the same
// document rather than what one of them holds.
let Some(other) = args.get(2) else {
print!("{}", dvi.summary());
return ExitCode::SUCCESS;
};
let against = match texrs::dvi::Dvi::open(other) {
Ok(dvi) => dvi,
Err(e) => return fail(&e),
};
let differences = dvi.compare(&against);
if differences.is_empty() {
println!("the same document");
return ExitCode::SUCCESS;
}
for difference in &differences {
println!("{difference:?}");
}
// A divergence is a failure: this is what a harness calls.
ExitCode::from(1)
}
"show" => {
let here = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
match texrs::document::Document::find_from(here) {
Ok(document) => {
print!("{}", document.show());
ExitCode::SUCCESS
}
Err(e) => fail(&e),
}
}
"build" | "watch" | "dump" => {
let mut profile: Option<String> = None;
let mut interval = texrs::document::WATCH_INTERVAL;
let mut rest = args[1..].iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--profile" => match rest.next() {
Some(name) => profile = Some(name.clone()),
None => return fail("--profile needs a name"),
},
"--interval" => match rest.next().and_then(|ms| ms.parse().ok()) {
Some(ms) => interval = std::time::Duration::from_millis(ms),
None => return fail("--interval needs a number of milliseconds"),
},
// `-X build --help` asks what the command takes, which is
// in the usage text with everything else. Reporting it as
// an unknown argument is the one answer that is never what
// someone typing it wanted.
"-h" | "--help" => {
print!("{}", texrs::cli::USAGE);
return ExitCode::SUCCESS;
}
other => return fail(&format!("unknown argument: {other}")),
}
}
let here = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let document = match texrs::document::Document::find_from(here) {
Ok(d) => d,
Err(e) => return fail(&e),
};
if command == "dump" {
return match document.dump(profile.as_deref()) {
Ok(text) => {
print!("{text}");
if !text.ends_with('\n') {
println!();
}
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
if command == "build" {
return match document.build(profile.as_deref()) {
Ok(built) => {
println!(
"built {} from {} input(s) → {}",
built.profile,
built.inputs.len(),
built.path.display()
);
ExitCode::SUCCESS
}
Err(e) => fail(&e),
};
}
// Watch until the terminal interrupts it: the loop has no other
// ending, which is what a watch is.
let mut status = texrs::status::TexStatus::new();
match document.watch(profile.as_deref(), interval, &mut status, &|| false) {
Ok(_) => ExitCode::SUCCESS,
Err(e) => fail(&e),
}
}
// An unknown command is looked for on PATH as `texrs-<name>`, which is
// how tectonic lets a command be added without changing the binary.
other => match external_command(other, &args[1..]) {
Some(code) => code,
None => {
eprintln!("texrs: unknown document command: {other}");
eprint!("{}", texrs::banner::render_usage(texrs::cli::USAGE, false));
ExitCode::from(1)
}
},
}
}
/// Run `texrs-<name>` from PATH with `args`, if there is one.
///
/// The extension point tectonic has: a command nobody built into the binary is
/// a program on PATH, so `texrs -X lint` runs `texrs-lint`. `None` means there
/// is no such program, which is what keeps the unknown-command error reachable.
fn external_command(name: &str, args: &[String]) -> Option<ExitCode> {
let program = format!("texrs-{name}");
match std::process::Command::new(&program).args(args).status() {
Ok(status) => Some(match status.code() {
Some(0) => ExitCode::SUCCESS,
Some(code) => ExitCode::from(code.min(255) as u8),
// Killed by a signal. Any non-zero code beats reporting success.
None => ExitCode::from(1),
}),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => {
eprintln!("texrs: {program}: {e}");
Some(ExitCode::from(1))
}
}
}
/// The same, for a file whose kind `kpsewhich` needs telling: a `.pk` is not
/// on the ordinary search path, because a font is kept in a directory named
/// after the resolution it was made for.
fn kpsewhich_format(format: &str, name: &str) -> String {
let named = match (format, name.contains('.')) {
// A packed font is kept in a directory named after its resolution, so
// a bare name needs the one TeX Live ships Computer Modern at.
("pk", false) => format!("{name}.600pk"),
("enc files", false) => format!("{name}.enc"),
_ => name.to_string(),
};
let found = std::process::Command::new("kpsewhich")
.arg(format!("-format={format}"))
.arg(&named)
.output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
/// Where TeX keeps a file of any kind, asked of `kpsewhich`.
fn kpsewhich_named(name: &str) -> String {
let found = std::process::Command::new("kpsewhich").arg(name).output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
/// Where TeX keeps a file, asked of `kpsewhich`. A font is named `cmr10`, not
/// by its path, and every TeX installation puts it somewhere different.
fn kpsewhich(name: &str) -> String {
let named = match name.ends_with(".tfm") {
true => name.to_string(),
false => format!("{name}.tfm"),
};
let found = std::process::Command::new("kpsewhich").arg(&named).output();
match found {
Ok(out) => {
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
match path.is_empty() {
// Nothing found: hand back what was asked for, so the error
// names what the user typed rather than a lookup they did not.
true => name.to_string(),
false => path,
}
}
Err(_) => name.to_string(),
}
}
/// `-X bibtex FILE.aux`: the whole of what `bibtex` does. Read the `.aux` for
/// the citations, the style and the databases; read the databases with the
/// style's own `MACRO`s defined, because that is where `month = jan` gets its
/// meaning; run the style; write the `.bbl` beside the `.aux`.
fn bibtex_run(path: &Path) -> ExitCode {
let aux = match texrs::bib::Aux::open(path) {
Ok(aux) => aux,
Err(e) => return fail(&e),
};
let dir = path.parent().unwrap_or(Path::new("."));
let Some(name) = &aux.style else {
return fail(&format!("{}: no \\bibstyle", path.display()));
};
// A style is named without its extension, and lives beside the document or
// in the installation.
let beside = dir.join(format!("{name}.bst"));
let found = match beside.exists() {
true => beside.to_string_lossy().to_string(),
false => kpsewhich_named(&format!("{name}.bst")),
};
let style = match texrs::bst::Style::open(&found) {
Ok(style) => style,
Err(e) => return fail(&e),
};
for missing in style.undefined() {
eprintln!("texrs: {name}.bst calls {missing}, which nothing defines");
}
let mut database = texrs::bib::Bib::default();
if aux.databases.is_empty() {
return fail(&format!("{}: no \\bibdata", path.display()));
}
for part in &aux.databases {
let file = dir.join(format!("{part}.bib"));
let text = match std::fs::read_to_string(&file) {
Ok(text) => text,
Err(e) => return fail(&format!("cannot read {}: {e}", file.display())),
};
let read = texrs::bib::Bib::parse_with(&text, &style.macros());
database.entries.extend(read.entries);
database.strings.extend(read.strings);
database.preamble.push_str(&read.preamble);
database.warnings.extend(read.warnings);
}
let (bbl, warnings) = texrs::bstvm::run(&aux, &style, &database);
let out = path.with_extension("bbl");
if let Err(e) = std::fs::write(&out, &bbl) {
return fail(&format!("cannot write {}: {e}", out.display()));
}
for warning in database.warnings.iter().chain(warnings.iter()) {
eprintln!("texrs: {warning}");
}
// A bibliography with a warning in it is one a person has to look at: a
// missing entry becomes a `?` in the document.
match warnings.is_empty() && database.warnings.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
/// `-X bib FILE.aux`: what a document cites, resolved against the databases its
/// own `.aux` names.
fn bib_citations(path: &Path) -> ExitCode {
let aux = match texrs::bib::Aux::open(path) {
Ok(aux) => aux,
Err(e) => return fail(&e),
};
let dir = path.parent().unwrap_or(Path::new("."));
let mut database = texrs::bib::Bib::default();
if aux.databases.is_empty() {
return fail(&format!("{}: no \\bibdata", path.display()));
}
for name in &aux.databases {
// `\bibdata` names files without their extension, beside the document.
let file = dir.join(format!("{name}.bib"));
match texrs::bib::Bib::open(&file) {
Ok(part) => {
database.entries.extend(part.entries);
database.strings.extend(part.strings);
database.warnings.extend(part.warnings);
}
Err(e) => return fail(&e),
}
}
let selected = database.select(&aux);
for entry in &selected.cited {
let title = entry.field("title").unwrap_or("");
println!("cited {:<20} {title}", entry.key);
}
for key in &selected.missing {
println!("MISSING {key}");
}
for entry in &selected.uncited {
println!("uncited {}", entry.key);
}
// A citation nothing defines becomes a `?` in the typeset bibliography, so
// it is worth an exit status of its own.
match selected.missing.is_empty() {
true => ExitCode::SUCCESS,
false => ExitCode::from(1),
}
}
/// `--cache-stats`: what the cache holds and where it is, for a user asking why
/// a run was fast, or whether the cache is being used at all.
fn cache_stats() -> ExitCode {
let path = texrs::script_cache::default_cache_path();
if !texrs::script_cache::cache_enabled() {
println!("cache: off (TEXRS_CACHE)");
println!("would be: {}", path.display());
return ExitCode::SUCCESS;
}
let Ok(cache) = texrs::script_cache::ScriptCache::open(&path) else {
eprintln!("texrs: cannot open {}", path.display());
return ExitCode::from(1);
};
let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
println!("cache: {}", path.display());
println!("documents: {}", cache.len());
println!("size: {size} bytes");
ExitCode::SUCCESS
}
/// `--cache-clear`: delete the shard. The next run of every document compiles.
fn cache_clear() -> ExitCode {
let path = texrs::script_cache::default_cache_path();
let Ok(cache) = texrs::script_cache::ScriptCache::open(&path) else {
eprintln!("texrs: cannot open {}", path.display());
return ExitCode::from(1);
};
match cache.clear() {
Ok(()) => {
println!("cleared {}", path.display());
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("texrs: {}: {e}", path.display());
ExitCode::from(1)
}
}
}
/// A file, then the command line as more input after it.
///
/// The file is run twice: once alone, to learn where its own output ends, and
/// once with the trailing input appended, because the two have to print on
/// opposite sides of the closing paren and the engine reports one message list.
/// It costs a second compile in the one case that asks for it -- a document
/// followed by command-line input -- and nothing at all otherwise.
fn run_with_trailing(
path: &str,
src: &str,
extra: &str,
interaction: texrs::cli::Interaction,
) -> ExitCode {
let from_file = match texrs::run_messages_list(src) {
Ok(m) => m,
Err(e) => return fail(&e.0),
};
let all = match texrs::run_messages_list(&format!("{src}\n{extra}")) {
Ok(m) => m,
Err(e) => return fail(&e.0),
};
if interaction.prints() {
let after = all[from_file.len().min(all.len())..].join(" ");
let line = texrs::file_line(path, &from_file.join(" "), false);
match after.is_empty() {
true => println!("{line}"),
false => println!("{line} {after}"),
}
}
ExitCode::SUCCESS
}
/// Run TeX source that came from the command line rather than from a file.
///
/// tex prints the messages bare here — there is no file to open, so there is no
/// `(./name.tex …)` to print — which is what makes
/// `texrs '\catcode`\{=1 \message{hi}\end'` usable from a Makefile.
fn run_command_line(src: &str, interaction: texrs::cli::Interaction) -> ExitCode {
match texrs::run_messages(src) {
Ok(msgs) => {
if interaction.prints() && !msgs.is_empty() {
println!("{msgs}");
}
ExitCode::SUCCESS
}
Err(e) => fail(&e.0),
}
}
/// tex writes its errors as `! <reason>.`; so does this.
fn fail(reason: &str) -> ExitCode {
eprintln!("! {reason}.");
ExitCode::from(1)
}
/// Print how often the parallel read-ahead ran, for `TEXRS_PRELEX_STATS`.
pub fn prelex_stats() {
use std::sync::atomic::Ordering;
eprintln!(
"prelex calls={} chars={} drop_gen={} drop_exhaust={}",
texrs::parallel::PRELEX_CALLS.load(Ordering::Relaxed),
texrs::parallel::PRELEX_CHARS.load(Ordering::Relaxed),
texrs::parallel::DROP_GEN.load(Ordering::Relaxed),
texrs::parallel::DROP_EXHAUST.load(Ordering::Relaxed)
);
}