latexml_core/binding/virtual_files.rs
1//! The in-memory virtual file store — TeX's write-out/read-back round trip.
2//!
3//! Real TeX documents constantly write auxiliary files and read them back:
4//! `\openout`/`\write`/`\closeout` streams, `{filecontents}` environments,
5//! fancyvrb-style `{VerbatimOut}` captures, memoir `\writeverbatim`, and then
6//! `\input`/`\openin`/`\verbatiminput`/`\IfFileExists` on the produced files.
7//! Our conversion never touches the user's disk for these (the design
8//! requirement allows writing only into the DESTINATION directory); instead
9//! every virtual write lands in this store and every file read consults it
10//! before kpathsea. The store is the single owner of the `VIRTUAL_FILES`
11//! state key (Perl keeps one `<name>_contents` string value per file) — do
12//! not reach into that map elsewhere.
13//!
14//! Contents live in ONE owned `HashMap<name, contents>` mutated in place,
15//! NOT as interned strings: the interner never frees, so re-pinning the whole
16//! file on every `\write` line (the earlier shape) grew the arena
17//! quadratically in the line count — a `{VerbatimOut}` left unterminated at
18//! end of input (fancyvrb `\FV@Scan` re-runs `\write` per empty read) walked
19//! the interner's buffer offset past its `u32` range and aborted on a
20//! `get_unchecked` precondition (witness: fancyvrb/fancyvrb-doc cut at the
21//! open `{SideBySideExample}`, `eof1.tex` in the batch-48 guards).
22//!
23//! Scope is per-conversion GLOBAL state (Scope::Global), reset with the rest
24//! of State between runs.
25
26use rustc_hash::FxHashMap as HashMap;
27
28use crate::{
29 common::store::Stored,
30 state::{Scope, assign_value, checkin_value, checkout_value, with_value},
31};
32
33/// The single state key holding the `name → contents` map.
34const VFS_KEY: &str = "VIRTUAL_FILES";
35
36/// Take the map out of State for in-place mutation (creating it on first use),
37/// apply `f`, and put it back.
38fn with_vfs_mut<R>(f: impl FnOnce(&mut HashMap<String, String>) -> R) -> R {
39 let mut map = match checkout_value(VFS_KEY) {
40 Some(Stored::HashString(map)) => map,
41 Some(_) | None => {
42 // Not yet assigned (or a foreign value under our key): establish the
43 // map globally so a later checkin has a slot to land in.
44 assign_value(
45 VFS_KEY,
46 Stored::HashString(HashMap::default()),
47 Some(Scope::Global),
48 );
49 match checkout_value(VFS_KEY) {
50 Some(Stored::HashString(map)) => map,
51 _ => HashMap::default(),
52 }
53 },
54 };
55 let result = f(&mut map);
56 checkin_value(VFS_KEY, Stored::HashString(map));
57 result
58}
59
60/// The VFS key for a file name: a leading `./` is dropped on EVERY side of
61/// the store, the way one directory holds `./foo.tex` and `foo.tex`. The
62/// read side (`find_file_aux`) stripped it while `\openout ./foo.tex` +
63/// `\write` stored the raw name, so fancyvrb's `{VerbatimOut}{./x}` →
64/// `\VerbatimInput{./x}` (xpicture-doc ×6, checklistings ×4; RUST-ONLY,
65/// pdflatex and Perl clean) missed its own file. Guard:
66/// `perfect_kernel_batch56::verbatimout_dotslash_round_trips_through_the_vfs`.
67fn vfs_key(name: &str) -> &str { name.strip_prefix("./").unwrap_or(name) }
68
69/// The name TeX writes an output file under. `\openout` completes a name
70/// without an extension to `<name>.tex` (tex.web §1374 "if cur_ext="" then
71/// cur_ext:=".tex"", tex.web:24928), and the extension is what follows the
72/// LAST `.` after the last `/` (web2c's `more_name`); TeX Live reads a braced
73/// name `{…}` as its group's content (`scan_file_name_braced`). Reads look for
74/// `<name>.tex` first as well (§537), so `\openout\f=notes` + `\input{notes}`
75/// meet in the store either way, while `\IfFileExists{notes.tex}` only finds
76/// the completed name. Every writer that stands in for `\openout` — the
77/// primitive, `{filecontents}` (latex.ltx:18998, :19023), expl3's
78/// `\iow_open:Nn` for tcolorbox's `\tcbverbatimwrite`, listings'
79/// `\lst@WFBegin` (lstmisc.sty:61) — names its file through this. Perl stores
80/// the bare name (TeX_FileIO.pool.ltxml:120-126; KNOWN_PERL_ERRORS #279).
81/// Witness latex4wp (latexdemo.sty:97-101 `{filecontents*}{democode}` then
82/// `\IfFileExists{democode.tex}`: 98 of 105 words of its examples missing).
83pub fn output_file_name(name: &str) -> String {
84 let name = name
85 .strip_prefix('{')
86 .and_then(|inner| inner.strip_suffix('}'))
87 .unwrap_or(name);
88 let base = name.rsplit('/').next().unwrap_or(name);
89 if base.is_empty() || base.contains('.') {
90 name.to_string()
91 } else {
92 format!("{name}.tex")
93 }
94}
95
96/// Create/overwrite a virtual file with `content`.
97pub fn vfs_store(name: &str, content: &str) {
98 with_vfs_mut(|map| {
99 map.insert(vfs_key(name).to_string(), content.to_string());
100 });
101}
102
103/// Append one line (newline-terminated) to a virtual file, creating it if
104/// absent — the `\write`-to-stream shape.
105pub fn vfs_append_line(name: &str, line: &str) {
106 with_vfs_mut(|map| {
107 let contents = map.entry(vfs_key(name).to_string()).or_default();
108 contents.push_str(line);
109 contents.push('\n');
110 });
111}
112
113/// Drop a virtual file, so later reads fall through to the real file system
114/// (the LSP overlay retracts an editor buffer this way).
115pub fn vfs_remove(name: &str) {
116 with_vfs_mut(|map| {
117 map.remove(vfs_key(name));
118 });
119}
120
121/// Read a virtual file's full content.
122pub fn vfs_read(name: &str) -> Option<String> {
123 with_value(VFS_KEY, |v| match v {
124 Some(Stored::HashString(map)) => map.get(vfs_key(name)).cloned(),
125 _ => None,
126 })
127}
128
129/// Does a virtual file exist?
130pub fn vfs_exists(name: &str) -> bool {
131 with_value(VFS_KEY, |v| match v {
132 Some(Stored::HashString(map)) => map.contains_key(vfs_key(name)),
133 _ => false,
134 })
135}
136
137#[cfg(test)]
138mod tests {
139 use super::output_file_name;
140
141 /// tex.web §1374: only a name without an extension is completed, the
142 /// extension being what follows the last `.` of the last path component.
143 #[test]
144 fn output_file_name_completes_as_openout_does() {
145 assert_eq!(output_file_name("democode"), "democode.tex");
146 assert_eq!(output_file_name("notes.aux"), "notes.aux");
147 assert_eq!(output_file_name("my.notes.txt"), "my.notes.txt");
148 assert_eq!(output_file_name("dir.d/notes"), "dir.d/notes.tex");
149 assert_eq!(output_file_name("./notes"), "./notes.tex");
150 assert_eq!(output_file_name("{notes}"), "notes.tex");
151 assert_eq!(output_file_name(""), "");
152 }
153}