Skip to main content

latexml/
bib_session.rs

1//! The recursive BibTeX session behind post-processing's bibliography.
2//!
3//! Port of `LaTeXML::Post::MakeBibliography::convertBibliography`
4//! (`MakeBibliography.pm` L171-242): a raw `.bib` is not parsed by a bespoke
5//! reader, it is **converted** — by the same engine, through `BibTeX.pool`, with
6//! the article's own class and packages preloaded so the fields mean what the
7//! article meant.
8//!
9//! It lives here rather than in `latexml_post` because a conversion needs
10//! `convert_document`, which needs this crate's model loader; `latexml_post`
11//! depending on `latexml_oxide` would be a cycle. `latexml_post` declares the
12//! hook, this module fills it in — see [`install`].
13
14use std::rc::Rc;
15
16use latexml_core::{
17  Core, CoreOptions,
18  binding::content::{InputDefinitionOptions, input_definitions},
19  common::{DigestionMode, error::*},
20  s,
21};
22// The post-phase diagnostic macros: plain reporters, with none of the
23// too-many-errors escalation the engine-side `Error!` carries. This module runs
24// inside post-processing, and an inner-session failure must not itself become a
25// document Fatal — the failure is already reported as an error, and Perl's
26// convertBibliography likewise just returns empty-handed (L240-242).
27use latexml_post::{
28  Error, Info,
29  document::{PostDocument, PostDocumentOptions},
30  make_bibliography::{BibConversionRequest, RawBibSource, set_bib_converter},
31};
32
33use crate::core_interface::{DigestionAPI, DigestionOptions};
34
35/// The commands a real `.bst`-generated `.bbl` provides before its entries.
36///
37/// BibTeX copies a field into the `.bbl`, whose preamble opens with a block of
38/// `\providecommand`s so `\url{…}` in a `note` renders even in a document that
39/// loads neither `hyperref` nor `url.sty`. We convert the `.bib` directly, one
40/// step earlier, so without this block we raise `undefined:\url` where real
41/// LaTeX renders text.
42///
43/// It is also what makes the percent-encoded-URL family work at all, and that is
44/// the deeper reason to keep it: `\url` is declared with a **Semiverbatim**
45/// parameter, so once it is defined, `\url{…/B130936%20Law%20of%20War.pdf}` reads
46/// its argument with `%` at catcode 12. Measured against same-host Perl on the
47/// same input: with `url.sty` present both engines emit 0 errors and identical
48/// XML; without it both mis-read the `%`. So this block is not a Rust patch
49/// papering over the engine — it is the condition under which the engine's own
50/// parameter types can act.
51///
52/// `\providecommand` is the right primitive precisely because it defers: a
53/// document that DOES load `hyperref` keeps hyperref's `\url`. Bodies mirror the
54/// conventional `.bbl` definitions (plain/natbib/revtex all ship these shapes).
55const BBL_STANDARD_FALLBACKS: &str = concat!(
56  r"\providecommand{\url}[1]{\texttt{#1}}",
57  r"\providecommand{\urlprefix}{URL }",
58  r"\providecommand{\doi}[1]{doi:#1}",
59  r"\providecommand{\bibinfo}[2]{#2}",
60  r"\providecommand{\eprint}[2][]{\url{#2}}",
61  r"\providecommand{\selectlanguage}[1]{\relax}",
62  r"\providecommand{\newblock}{}",
63);
64
65/// Install this crate's recursive-session implementation into `latexml_post`.
66///
67/// Call once per thread before running the post-processing pipeline.
68pub fn install() { set_bib_converter(convert); }
69
70/// Assemble the sources into one conversion payload.
71///
72/// Perl `MakeBibliography.pm` L147-163: a lone file is converted as-is (so
73/// locators name it), and several are concatenated into one `literal:` payload —
74/// each followed by `%\n` — so that a single session sees them all and `@string`
75/// macros defined in one file are in scope for the next.
76///
77/// The file reading deliberately does NOT use `read_to_string`: a strict UTF-8
78/// read hard-errors on the first stray Cp1252 byte and would silently lose the
79/// whole bibliography (witness 2605.00490). `decode_input_bytes` is the shared
80/// decoder — UTF-8, else a lossless Latin-1 passthrough — that both `.bib` read
81/// sites already use.
82fn payload(sources: &[RawBibSource]) -> Option<String> {
83  if let [RawBibSource::Path(path)] = sources {
84    return Some(path.clone());
85  }
86  let mut combined = String::from("literal:");
87  for source in sources {
88    match source {
89      RawBibSource::Literal(data) => combined.push_str(data),
90      RawBibSource::Path(path) => match std::fs::read(path) {
91        Ok(bytes) => combined.push_str(&latexml_core::mouth::decode_input_bytes(&bytes)),
92        // Perl L162: `Info("open", ...)` — one unreadable file must not sink
93        // the bibliographies that ARE readable.
94        Err(e) => Info!(
95          "open",
96          path,
97          "Couldn't open bibliography file {}: {}",
98          path,
99          e
100        ),
101      },
102    }
103    combined.push_str("%\n");
104  }
105  if combined == "literal:" {
106    None
107  } else {
108    Some(combined)
109  }
110}
111
112/// Make this thread's engine ready to digest BibTeX, **keeping the document's
113/// own definitions**.
114///
115/// Perl spins a brand-new converter and rebuilds an approximation of the
116/// article's environment from `[options]class.cls` + `[options]pkg.sty` preloads
117/// recovered from the `<?latexml?>` PIs — and says so in a comment right above
118/// `convertBibliography` (`MakeBibliography.pm` L174-177):
119///
120/// > In general, it should use the same STATE information as the main document,
121/// > so IF that state is still around, we should use it! That's for future
122/// > enhancement!!!
123///
124/// It is still around: post-processing runs in the same thread, right after
125/// digestion. Using it is the enhancement Perl asks for, and it is strictly more
126/// faithful to the *document*: preloads recover the class and packages but not
127/// the author's own preamble macros, which is precisely what a `howpublished` or
128/// `note` field tends to use (Perl's L184 comment — "custom macros often used in
129/// e.g. howpublished field" — is the stated reason for preloading at all).
130///
131/// It also avoids two concrete hazards. A second `initialize_singletons` on one
132/// thread re-runs the pools' `Let!`s (WISDOM #67 — that is a *non-unwinding*
133/// abort, not a catchable failure), and it resets the `REPORT` the outer
134/// document is still counting into, so Perl's `MergeStatus` would have to be
135/// re-implemented by hand. Sharing the state makes both moot.
136///
137/// So all this needs is `BibTeX.pool` on top. The preloads are still consulted —
138/// but only for the fallback path below, where there is no live session to
139/// share (a `--post`-only run over an existing `.xml`, where nothing was ever
140/// digested in this process).
141fn ensure_session(request: &BibConversionRequest) -> Result<()> {
142  if latexml_core::state::has_value("LATEXML_VERSION") {
143    // Live session: add the pool the document never needed. Idempotent —
144    // `input_definitions` early-returns on its own `_loaded` flag.
145    input_definitions("BibTeX", InputDefinitionOptions {
146      extension: Some("pool".into()),
147      ..InputDefinitionOptions::default()
148    })
149  } else {
150    // No conversion happened in this process (XML input). This IS the thread's
151    // first initialization, so it is the safe case for `initialize_singletons`,
152    // and Perl's preload reconstruction is exactly right here.
153    let mut preloads = vec![s!("TeX.pool"), s!("BibTeX.pool")];
154    preloads.extend(request.preloads.iter().cloned());
155    // Perl's `convertBibliography` (MakeBibliography.pm:180-235) spins a FULL
156    // converter — `get_converter` + `prepare_session` (`includestyles=1`) —
157    // so the pools and the document's class resolve through the bindings.
158    // `Core::new` resets the State, which starts with NO binding dispatch
159    // (`State::new` → `bindings_dispatch: None`): without the chain that
160    // `Converter::initialize_session` installs, `input_definitions` finds
161    // neither `TeX.pool` nor `BibTeX.pool`, the kernel never bootstraps, the
162    // preloaded class is read raw against an empty state (100 errors →
163    // TooManyErrors) and the bibliography comes back empty. Witness: TeX Live
164    // aomart/aomsample, `--whatsin=xml … --sourcedirectory=<bundle>`.
165    let mut core = Core::new(CoreOptions {
166      preload: Some(request.preloads.clone()),
167      search_paths: Some(request.search_paths.clone()),
168      include_styles: Some(true),
169      ..CoreOptions::default()
170    });
171    crate::converter::install_default_binding_chain(Some(Rc::new(latexml_contrib::dispatch)));
172    core.initialize_singletons(preloads)
173  }
174}
175
176/// Ensure `\url` exists, and exists with its REAL definition.
177///
178/// [`BBL_STANDARD_FALLBACKS`] alone would define it as
179/// `\providecommand{\url}[1]{\texttt{#1}}` — an ordinary `{}` argument, which
180/// renders but gives no catcode protection. Its argument is then read with `%`
181/// at catcode 14, so a percent-encoded URL (`…/B130936%20Law%20of%20War.pdf` —
182/// entirely routine in a `howpublished`) is truncated at the first `%`, taking
183/// the closing brace with it.
184///
185/// Loading LaTeXML's own `url.sty` binding instead gives `\url` the
186/// **Semiverbatim** parameter it is supposed to have (`url_sty.rs`), and the
187/// truncation disappears. That is what a document which actually uses `\url`
188/// would have had: a `.bst` emitting `\url{…}` into the `.bbl` assumes the
189/// document loads `url` or `hyperref`, and nearly all do.
190///
191/// SURPASS-PERL, and deliberately: same-host Perl truncates this input (measured
192/// — `latexmlc` renders `https://example.org/B130936` and spills the raw entry
193/// into the note), because it defines nothing here at all. So does pdflatex
194/// without a url package. This continues the beyond-Perl content-recovery line
195/// already taken by the `.bbl` fallback block itself; it does not silence any
196/// diagnostic Perl raises for a *correct* document, since a document that loads
197/// `url`/`hyperref` keeps its own definition — `input_definitions` early-returns
198/// on the `_loaded` flag, and `\providecommand` defers.
199fn provide_url_command() -> Result<()> {
200  if latexml_core::state::lookup_meaning(&latexml_core::T_CS!("\\url")).is_some() {
201    return Ok(());
202  }
203  input_definitions("url", InputDefinitionOptions {
204    extension: Some("sty".into()),
205    handleoptions: true,
206    ..InputDefinitionOptions::default()
207  })
208}
209
210/// Run the recursive session and hand back its document.
211fn convert(request: &BibConversionRequest) -> Option<PostDocument> {
212  let source = payload(&request.sources)?;
213  let stage = if source.starts_with("literal:") {
214    s!("Recursive MakeBibliography Anonymous Bib String")
215  } else {
216    s!("Recursive MakeBibliography {source}")
217  };
218  note_begin(&stage);
219
220  // The document's OWN state, still live, is the session — see the module docs
221  // for why that is both better and cheaper than a fresh one. `Core` is a thin
222  // handle over the thread-local engine (`Core::new` would install a *new*
223  // State and throw the document's away), so it is constructed directly.
224  let mut core = Core {
225    preload: request.preloads.clone(),
226  };
227
228  let result = (|| -> Result<PostDocument> {
229    ensure_session(request)?;
230    // Perl builds a FRESH `catcodes => 'standard'` State per `.bib` (`Core.pm:39`),
231    // where `@` is catcode OTHER. We REUSE the live document State (module docs),
232    // so any catcode the document left non-standard leaks into the `.bib`
233    // digestion. `@` is the one that matters: the emitted
234    // `\begin{bibtex@bibliography}` wrapper carries `@` in its environment name, so
235    // a document that leaves `@` ACTIVE — e.g. an unmatched `\makeatletter` or the
236    // `\catcode`@=\active`+`\def@#1@{…}` red-annotation shorthand of
237    // arXiv:2606.03480 (an unmatched `\shorthandon`) — makes that `@` EXPAND
238    // mid-name, giving `readBalanced ran out of input` and losing the whole
239    // bibliography. Reset `@` to its standard catcode to match Perl's fresh state.
240    // Guard: `active_at_catcode_does_not_corrupt_bibtex_wrapper`.
241    latexml_core::state::assign_catcode(
242      '@',
243      latexml_core::token::Catcode::OTHER,
244      Some(latexml_core::state::Scope::Global),
245    );
246    // Give the fields what a `.bbl` would have given them, once the session is
247    // ready and before any entry is digested.
248    provide_url_command()?;
249    latexml_core::stomach::digest(latexml_core::mouth::tokenize(BBL_STANDARD_FALLBACKS))?;
250    // The entries are digested in the DOCUMENT's default font. Perl's fresh
251    // per-`.bib` state (Core.pm:39) starts at the default font; the live
252    // session here inherits whatever NFSS state the body left — abntexto's
253    // doc-point `\ttfamily` (leaked through an unbounded `\hyperlink`) made
254    // every field a `<text font="typewriter">` wrapper that broke the
255    // `<bibentry>` nesting: 99 `#PCDATA isn't allowed in <ltx:bibentry>`.
256    // `\normalfont` here keeps every live definition (the point of the
257    // monolithic pass) and only normalizes the typographic state. Guard:
258    // `06_cluster_bibliography::bib_entries_digest_in_the_default_font`. The defaults are those in force where
259    // `\bibliography` stands (`lx@bibliography@normalfont`, recorded by sect11.rs `\lx@bibliography`), not at the
260    // document's end: cmpj3's `\ukrainianpart` after the bibliography makes the rest sans, while pdflatex's
261    // bibliography stays serif (2603.23615; OXIDIZED_DESIGN_DIVERGENCES #779). Guard
262    // `06_cluster_bibliography::bib_entries_take_the_defaults_where_the_bibliography_stands`.
263    let normalfont = match latexml_core::state::lookup_value("lx@bibliography@normalfont") {
264      Some(latexml_core::state::Stored::Tokens(tokens)) => tokens,
265      _ => latexml_core::mouth::tokenize(r"\normalfont"),
266    };
267    latexml_core::stomach::digest(normalfont)?;
268
269    // Digest only what the document cites — a `.bib` is a library, and
270    // `bibtex(1)` reads the `.aux`'s `\citation` records rather than the whole
271    // file. Set around `digest_file` only: the filter lives in the same
272    // thread-local State the outer document uses, so leaving it installed
273    // would leak into any later `.bib` in this process.
274    struct BibSessionGuard {
275      outer_n_bibliographies: i64,
276    }
277    impl Drop for BibSessionGuard {
278      fn drop(&mut self) {
279        latexml_core::state::assign_value(
280          "n_bibliographies",
281          self.outer_n_bibliographies,
282          Some(latexml_core::state::Scope::Global),
283        );
284        latexml_engine::pre_bibtex::clear_wanted_keys();
285      }
286    }
287    let outer_n_bibliographies = latexml_core::state::lookup_int("n_bibliographies");
288    latexml_engine::pre_bibtex::set_wanted_keys(request.wanted_keys.clone());
289    let _bib_guard = BibSessionGuard { outer_n_bibliographies };
290    latexml_core::state::assign_value(
291      "n_bibliographies",
292      0,
293      Some(latexml_core::state::Scope::Global),
294    );
295    let digested = core.digest_file(source.clone(), DigestionOptions {
296      mode: Some(DigestionMode::BibTeX),
297      noinitialize: Some(true),
298      ..DigestionOptions::default()
299    });
300    drop(_bib_guard);
301    let digested = digested?;
302    let document = core.convert_document(digested)?;
303    Ok(PostDocument::new(document.document, PostDocumentOptions {
304      source_directory: Some(".".to_string()),
305      ..PostDocumentOptions::default()
306    }))
307  })();
308
309  // Perl `MergeStatus` (L237) ADDS the inner session's tally to the outer
310  // document's (Common/Error.pm L669-686) — a `.bib` that raises errors makes
311  // the document an error document, which is what the corpus signal depends on.
312  // Sharing the live state gives that for free: the counters never left.
313  note_end(&stage);
314
315  match result {
316    Ok(bibdoc) => Some(bibdoc),
317    Err(e) => {
318      Error!(
319        "bibliography",
320        "convert",
321        "Recursive bibliography conversion failed: {}",
322        e
323      );
324      None
325    },
326  }
327}