use std::collections::BTreeMap;
use std::path::Path;
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Aux {
pub labels: BTreeMap<String, (String, String)>,
pub citations: BTreeMap<String, String>,
}
impl Aux {
pub fn is_empty(&self) -> bool {
self.labels.is_empty() && self.citations.is_empty()
}
}
pub fn parse(text: &str) -> Aux {
let mut aux = Aux::default();
for line in text.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("\\newlabel") {
let Some((key, rest)) = group(rest) else {
continue;
};
let Some((body, _)) = group(rest) else {
continue;
};
let Some((value, rest)) = group(&body) else {
continue;
};
let page = group(rest).map(|(p, _)| p).unwrap_or_default();
aux.labels.insert(key, (value, page));
} else if let Some(rest) = line.strip_prefix("\\bibcite") {
let Some((key, rest)) = group(rest) else {
continue;
};
let Some((value, _)) = group(rest) else {
continue;
};
aux.citations.insert(key, value);
}
}
aux
}
fn group(text: &str) -> Option<(String, &str)> {
let start = text.find('{')?;
let mut depth = 0usize;
for (offset, ch) in text[start..].char_indices() {
match ch {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
let inner = &text[start + 1..start + offset];
return Some((inner.to_string(), &text[start + offset + 1..]));
}
}
_ => {}
}
}
None
}
pub fn read(path: &Path) -> Aux {
match std::fs::read_to_string(path) {
Ok(text) => parse(&text),
Err(_) => Aux::default(),
}
}
pub fn path_for(document: &Path) -> std::path::PathBuf {
document.with_extension("aux")
}
pub fn seeds(aux: &Aux, src: &str) -> String {
let mut out = String::new();
for (key, (value, page)) in &aux.labels {
out.push_str(&format!("\\newlabel{{{key}}}{{{{{value}}}{{{page}}}}}\n"));
}
for key in referenced(src) {
if !aux.labels.contains_key(&key) {
out.push_str(&format!("\\newlabel{{{key}}}{{{{??}}{{??}}}}\n"));
}
}
for (key, value) in &aux.citations {
out.push_str(&format!("\\bibcite{{{key}}}{{{value}}}\n"));
}
for key in cited(src) {
if !aux.citations.contains_key(&key) {
out.push_str(&format!("\\bibcite{{{key}}}{{?}}\n"));
}
}
out
}
pub fn cited(src: &str) -> Vec<String> {
let mut out = Vec::new();
for group in keys_after(src, &["\\cite", "\\citep", "\\citet", "\\nocite"]) {
for key in group.split(',') {
let key = key.trim();
if !key.is_empty() && !out.iter().any(|k| k == key) {
out.push(key.to_string());
}
}
}
out
}
pub fn referenced(src: &str) -> Vec<String> {
keys_after(
src,
&["\\ref", "\\pageref", "\\eqref", "\\autoref", "\\nameref"],
)
}
pub fn defined(src: &str) -> Vec<String> {
keys_after(src, &["\\label"])
}
fn keys_after(src: &str, commands: &[&str]) -> Vec<String> {
let mut out = Vec::new();
for command in commands {
let mut rest = src;
while let Some(at) = rest.find(command) {
let after = &rest[at + command.len()..];
rest = after;
if after.starts_with(|c: char| c.is_ascii_alphabetic()) {
continue;
}
let after = after.trim_start_matches(['*', ' ']);
let Some(body) = after.strip_prefix('{') else {
continue;
};
let Some(end) = body.find('}') else { continue };
let key = body[..end].trim();
if !key.is_empty() && !out.iter().any(|k| k == key) {
out.push(key.to_string());
}
}
}
out
}
pub fn pass(src: &str) -> Result<Aux, crate::TexError> {
let src_d = crate::rust_ffi::desugar(src);
let mut lowerer = crate::lower::Lowerer::new().passing_over_formulas();
lowerer.preload(&super::preamble(&src_d))?;
lowerer.preload(
"\\makeatletter\\let\\label\\@auxlabel\\let\\bibitem\\@auxbibitem\\makeatother\n",
)?;
let cmds = lowerer.lower(&src_d)?;
let chunk = crate::compiler::Compiler::new().compile(&cmds)?;
let messages = crate::runtime::run(chunk).map_err(crate::TexError)?;
let mut aux = Aux::default();
for message in messages {
let parsed = parse(&crate::text_without_marks(&message));
aux.labels.extend(parsed.labels.into_iter().filter(settled));
aux.citations
.extend(parsed.citations.into_iter().filter(|(_, v)| is_settled(v)));
}
Ok(aux)
}
fn settled(entry: &(String, (String, String))) -> bool {
let (_, (value, page)) = entry;
is_settled(value) && is_settled(page)
}
fn is_settled(value: &str) -> bool {
!value.contains('\\')
}
pub fn write(path: &Path, aux: &Aux) -> std::io::Result<()> {
std::fs::write(path, render(aux))
}
fn render(aux: &Aux) -> String {
let mut text = String::from("\\relax \n");
for (key, (value, page)) in &aux.labels {
text.push_str(&format!("\\newlabel{{{key}}}{{{{{value}}}{{{page}}}}}\n"));
}
for (key, value) in &aux.citations {
text.push_str(&format!("\\bibcite{{{key}}}{{{value}}}\n"));
}
text
}
pub fn rerun_needed(old: &Aux, new: &Aux) -> bool {
if old.labels.len() != new.labels.len() {
return true;
}
new.labels
.iter()
.any(|(key, value)| old.labels.get(key) != Some(value))
}
pub const RERUN: &str = "LaTeX Warning: Label(s) may have changed. \
Rerun to get cross-references right.";
pub fn update(document: &Path, src: &str) -> bool {
let src = &super::include::gathered(src);
if !wants_pass(src) {
return false;
}
let path = path_for(document);
let previous = read(&path);
let Ok(now) = pass(src) else { return false };
settle(&path, &previous, &now)
}
fn wants_pass(src: &str) -> bool {
let refs = !defined(src).is_empty() && !referenced(src).is_empty();
let bib = src.contains("\\bibitem") && !cited(src).is_empty();
refs || bib
}
fn settle(path: &Path, previous: &Aux, now: &Aux) -> bool {
let again = rerun_needed(previous, now);
let _ = write(path, now);
if again {
eprintln!("texrs: {RERUN}");
}
again
}
pub fn update_then<T>(document: &Path, src: &str, run: impl Fn() -> T) -> T {
let gathered = super::include::gathered(src);
if !wants_pass(&gathered) {
return run();
}
let path = path_for(document);
let previous = read(&path);
let overlap = crate::parallel::default_threads() > 1
&& !previous.is_empty()
&& !has_shared_effects(&gathered);
if !overlap {
if let Ok(now) = pass(&gathered) {
settle(&path, &previous, &now);
}
return run();
}
let ((found, pass_said), (speculative, run_said)) = std::thread::scope(|s| {
let labels = std::thread::Builder::new()
.name("texrs-aux-pass".into())
.stack_size(PASS_STACK)
.spawn_scoped(s, || super::held_reports(|| pass(&gathered)))
.expect("spawn the label pass");
let speculative = super::held_reports(&run);
match labels.join() {
Ok(found) => (found, speculative),
Err(panic) => std::panic::resume_unwind(panic),
}
});
super::release_reports(&pass_said);
let Ok(now) = found else {
super::release_reports(&run_said);
return speculative;
};
settle(&path, &previous, &now);
match parse(&render(&now)) == previous {
true => {
super::release_reports(&run_said);
speculative
}
false => run(),
}
}
const PASS_STACK: usize = 64 << 20;
fn has_shared_effects(src: &str) -> bool {
["\\directlua", "\\lua", "\\latelua", "\\rustcompile", "://"]
.iter()
.any(|needle| src.contains(needle))
}
pub fn stamp(document: &Path) -> String {
use std::hash::{Hash, Hasher};
let text = std::fs::read_to_string(path_for(document)).unwrap_or_default();
if text.is_empty() {
return String::new();
}
let mut hasher = std::collections::hash_map::DefaultHasher::new();
text.hash(&mut hasher);
format!("-aux{:x}", hasher.finish())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_two_field_newlabel_and_a_hyperref_five_field_one_read_the_same() {
let aux = parse(
"\\relax\n\
\\newlabel{sec:a}{{2.1}{17}}\n\
\\newlabel{fig:b}{{3.4}{92}{A figure}{figure.3.4}{}}\n\
\\bibcite{knuth84}{1}\n",
);
assert_eq!(aux.labels["sec:a"], ("2.1".to_string(), "17".to_string()));
assert_eq!(aux.labels["fig:b"], ("3.4".to_string(), "92".to_string()));
assert_eq!(aux.citations["knuth84"], "1");
}
#[test]
fn a_referenced_label_the_aux_does_not_carry_is_seeded_as_two_question_marks() {
let aux = parse("\\newlabel{known}{{1}{2}}\n");
let seeded = seeds(&aux, "see \\ref{known} and \\pageref{missing}");
assert!(seeded.contains("\\newlabel{known}{{1}{2}}"));
assert!(seeded.contains("\\newlabel{missing}{{??}{??}}"));
}
#[test]
fn a_changed_value_is_a_rerun_and_an_unchanged_one_is_not() {
let old = parse("\\newlabel{a}{{1}{1}}\n");
let same = parse("\\newlabel{a}{{1}{1}}\n");
let moved = parse("\\newlabel{a}{{1}{2}}\n");
assert!(!rerun_needed(&old, &same));
assert!(rerun_needed(&old, &moved));
assert!(rerun_needed(&old, &Aux::default()));
}
}