Deduplicate native dependency reads on the execution path

This commit is contained in:
gloamxun committed 2026-11-29 04:46:22 +08:00
1 parent c23dabb449
commit 4791c42403
9 files changed
+139 -38

No files matched your search

@@ -0,0 +1,74 @@
//! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency;
use std::collections::{BTreeSet, HashSet};
#[derive(Clone, Default)]
pub(super) struct DependencyReads {
byte_catcodes: [u64; 4],
other: HashSet<Dependency>,
}
impl DependencyReads {
pub(super) fn catcode(&mut self, character: char) {
let index = character as usize;
if let Some(bits) = self.byte_catcodes.get_mut(index / 64) {
*bits |= 1 << (index % 64);
} else {
self.other.insert(Dependency::CatCode(character));
}
}
pub(super) fn insert(&mut self, dependency: Dependency) {
if let Dependency::CatCode(character) = dependency {
self.catcode(character);
} else {
self.other.insert(dependency);
}
}
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
let byte_catcodes = (0..=u8::MAX)
.filter(|&index| {
let index = usize::from(index);
self.byte_catcodes[index / 64] & (1 << (index % 64)) != 0
})
.map(|index| Dependency::CatCode(char::from(index)));
self.other.into_iter().chain(byte_catcodes).collect()
}
}
impl Extend<Dependency> for DependencyReads {
fn extend<T: IntoIterator<Item = Dependency>>(&mut self, dependencies: T) {
for dependency in dependencies {
self.insert(dependency);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default();
for character in ['\0', '@', 'ÿ', 'Ā', '文'] {
read.catcode(character);
read.insert(Dependency::CatCode(character));
}
read.insert(Dependency::EndLineChar);
let early = read.clone();
read.extend([Dependency::EndLineChar, Dependency::ParagraphToken]);
let mut expected = BTreeSet::from([
Dependency::CatCode('\0'),
Dependency::CatCode('@'),
Dependency::CatCode('ÿ'),
Dependency::CatCode('Ā'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
]);
assert_eq!(early.into_ordered(), expected);
expected.insert(Dependency::ParagraphToken);
assert_eq!(read.into_ordered(), expected);
}
}
+11 -10
View File
@@ -215,7 +215,7 @@ pub struct Executor {
sources: Vec<Arc<SourceFile>>,
stream_sources: BTreeSet<usize>,
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
reads: BTreeSet<Dependency>,
reads: DependencyReads,
meaning_reads: HashSet<CommandName>,
reads_tracing_macros: bool,
conditionals: Vec<Conditional>,
@@ -410,7 +410,7 @@ impl Executor {
sources: Vec::new(),
stream_sources: BTreeSet::new(),
generated_inputs: Default::default(),
reads: BTreeSet::new(),
reads: DependencyReads::default(),
meaning_reads: HashSet::new(),
reads_tracing_macros: false,
conditionals: Vec::new(),
@@ -647,9 +647,10 @@ impl Executor {
}
}
fn collect_meaning_reads(&mut self) {
self.reads
.extend(self.meaning_reads.drain().map(Dependency::Meaning));
fn take_dependency_reads(&mut self) -> BTreeSet<Dependency> {
let mut reads = std::mem::take(&mut self.reads).into_ordered();
reads.extend(self.meaning_reads.drain().map(Dependency::Meaning));
reads
}
fn meaning(&mut self, token: &Token) -> Meaning {
@@ -3369,7 +3370,7 @@ impl Executor {
for node in nodes {
self.output_node(node, files)?;
}
self.collect_meaning_reads();
let reads = self.take_dependency_reads();
let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution {
format_dumped: self.format_dumped,
@@ -3392,7 +3393,7 @@ impl Executor {
sources: self.sources,
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
reads,
events: self.events.into_vec(),
steps: self.steps,
})
@@ -3802,7 +3803,7 @@ impl Executor {
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
self.collect_meaning_reads();
let reads = self.take_dependency_reads();
let result = result.and_then(|()| {
if self.shipped_pages > 0 && !self.format_dumped
&& let Some(objects) = self.state.pdf_objects.as_deref_mut()
@@ -3828,7 +3829,7 @@ impl Executor {
source_versions,
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
reads,
events: self.events.into_vec(),
input_position: self.input_position,
incoming_state,
@@ -3871,7 +3872,7 @@ impl Executor {
sources: self.sources,
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
reads,
incoming_state,
steps: self.steps,
})
@@ -1,6 +1,6 @@
use super::page_builder::PageObservation;
use super::*;
use std::collections::{BTreeMap, BTreeSet};
use std::collections::BTreeMap;
/// Insertion material and the values captured inside its restricted group.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -80,7 +80,7 @@ impl PageInsertions {
at: usize,
dims: &mut [i64; 8],
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut super::DependencyReads,
steps: &mut usize,
limit: usize,
observations: &mut Vec<PageObservation>,
@@ -198,7 +198,7 @@ impl PageInsertions {
&mut self,
page: Vec<NativeVerticalNode>,
state: &mut State,
reads: &mut BTreeSet<Dependency>,
reads: &mut super::DependencyReads,
steps: &mut usize,
limit: usize,
) -> Result<Vec<NativeVerticalNode>, String> {
@@ -7,6 +7,8 @@ mod cancellation;
mod case;
mod context;
mod device;
mod dependency_reads;
use dependency_reads::DependencyReads;
mod diagnostics;
mod direction;
mod dvi;
+20 -20
View File
@@ -1,5 +1,5 @@
use super::{CatCode, CommandName, Dependency, Span, State, Token, TokenKind};
use std::{collections::BTreeSet, sync::Arc};
use super::{CatCode, CommandName, Dependency, DependencyReads, Span, State, Token, TokenKind};
use std::sync::Arc;
use super::xe_encoding::{Character, Encoding};
@@ -18,7 +18,7 @@ mod tests {
fn tokens(text: &str) -> Vec<Token> {
let mut mouth = Mouth::new(0, text.into(), super::super::InputProfile::UnicodeScalar);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
let mut tokens = Vec::new();
while let Some(token) = mouth.next(&State::default(), &mut reads).unwrap() {
tokens.push(token);
@@ -52,7 +52,7 @@ mod tests {
let mut mouth = Mouth::new(0, "\\~ A\\ B".into(), super::super::InputProfile::TeX8Bit);
let mut state = State::default();
state.assign_catcode('~', CatCode::Space, false);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
let mut kinds = Vec::new();
while let Some(token) = mouth.next(&state, &mut reads).unwrap() {
kinds.push(token.kind);
@@ -77,7 +77,7 @@ mod tests {
super::super::InputProfile::UnicodeScalar,
);
let mut state = State::default();
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
assert_eq!(
mouth.next(&state, &mut reads).unwrap().unwrap().kind,
TokenKind::Command(CommandName::Control("set".into()))
@@ -96,7 +96,7 @@ mod tests {
super::super::InputProfile::UnicodeScalar,
);
let mut state = State::default();
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
assert_eq!(
mouth.next(&state, &mut reads).unwrap().unwrap().kind,
TokenKind::Character('A', CatCode::Letter)
@@ -122,7 +122,7 @@ mod tests {
state.assign_catcode(mark, CatCode::Letter, false);
}
let mut mouth = Mouth::new(0, "é\n\\a\u{0315}\u{0300}!\na\u{0315}\u{0300}é".into(), InputProfile::XeTeX);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
let first = mouth.next(&state, &mut reads).unwrap().unwrap();
assert!(matches!(first.kind, TokenKind::Character('é', _)));
assert_eq!((first.span.start, first.span.end), (0, 2));
@@ -142,7 +142,7 @@ mod tests {
assert!(matches!(token.kind, TokenKind::Character(c, _) if c == value));
assert_eq!((token.span.start, token.span.end), range);
}
assert!(reads.contains(&Dependency::Parameter(Parameter::XeTeXinputnormalization)));
assert!(reads.into_ordered().contains(&Dependency::Parameter(Parameter::XeTeXinputnormalization)));
}
#[test]
@@ -154,7 +154,7 @@ mod tests {
);
let mut state = State::default();
state.assign_integer(super::super::state::Key::Endlinechar, -1, false);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
assert_eq!(
mouth.next(&state, &mut reads).unwrap().unwrap().kind,
TokenKind::Command(CommandName::Control("word".into()))
@@ -191,7 +191,7 @@ mod tests {
state.assign_catcode('中', CatCode::Letter, false);
state.assign_catcode('😀', CatCode::Letter, false);
let mut mouth = Mouth::new(0, text.into(), InputProfile::XeTeX);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
let prime = mouth.next(&state, &mut reads).unwrap().unwrap();
assert_eq!(prime.kind, TokenKind::Character('′', state.catcode('′')));
assert_eq!((prime.span.start, prime.span.end), (0, 8));
@@ -230,7 +230,7 @@ mod tests {
.collect::<Vec<_>>()
};
let state = State::default().with_input_profile(InputProfile::XeTeX);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
let mut mouth = Mouth::new(8, utf16("A\r\n😀\r\n"), InputProfile::XeTeX);
let first = mouth.next(&state, &mut reads).unwrap().unwrap();
assert_eq!(first.span, Span { source: 8, start: 2, end: 4 });
@@ -442,7 +442,7 @@ impl Mouth {
pub(super) fn load_line(
&mut self,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut DependencyReads,
) -> Result<bool, (Span, String)> {
if self.end_after_line || self.offset == self.data.len() {
return Ok(false);
@@ -538,7 +538,7 @@ impl Mouth {
fn load_xe_line(
&mut self,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut DependencyReads,
) -> Result<bool, (Span, String)> {
let xe = self.xe.as_mut().unwrap();
let framing = xe.encoding.framing();
@@ -578,7 +578,7 @@ impl Mouth {
content_end: usize,
end: usize,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut DependencyReads,
) {
reads.insert(Dependency::EndLineChar);
if let Ok(value) = u32::try_from(state.endlinechar)
@@ -594,8 +594,8 @@ impl Mouth {
self.cursor = 0;
self.state = LineState::New;
}
fn catcode(state: &State, reads: &mut BTreeSet<Dependency>, c: char) -> CatCode {
reads.insert(Dependency::CatCode(c));
fn catcode(state: &State, reads: &mut DependencyReads, c: char) -> CatCode {
reads.catcode(c);
state.catcode(c)
}
// next points at the second superscript mark. The returned length
@@ -640,7 +640,7 @@ impl Mouth {
/// Decode TeX's ^^ form before category lookup. Category changes affect
/// unread characters; tokens already in macro bodies are never retokenized.
fn peek(&mut self, state: &State, reads: &mut BTreeSet<Dependency>) -> Option<Character> {
fn peek(&mut self, state: &State, reads: &mut DependencyReads) -> Option<Character> {
loop {
let c = *self.line.get(self.cursor)?;
if Self::catcode(state, reads, c.value) != CatCode::Superscript {
@@ -659,7 +659,7 @@ impl Mouth {
/// get_next's ordinary ^^ conversion changes cur_chr and advances loc.
/// Only the control-sequence scanner rewrites the input buffer (peek).
/// Keeping these paths distinct also preserves TeX's displayed context.
fn next_character(&mut self, state: &State, reads: &mut BTreeSet<Dependency>) -> Character {
fn next_character(&mut self, state: &State, reads: &mut DependencyReads) -> Character {
let mut c = self.line[self.cursor];
self.cursor += 1;
while Self::catcode(state, reads, c.value) == CatCode::Superscript {
@@ -677,7 +677,7 @@ impl Mouth {
pub fn next(
&mut self,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut DependencyReads,
) -> Result<Option<Token>, (Span, String)> {
loop {
while self.cursor == self.line.len() {
@@ -777,7 +777,7 @@ mod byte_tests {
}
state.assign_integer(crate::execution::state::Key::Endlinechar, -1, false);
let mut mouth = Mouth::new(7, (0..=255u8).collect(), InputProfile::TeX8Bit);
let mut reads = BTreeSet::new();
let mut reads = DependencyReads::default();
for b in (0..=255u8).filter(|b| !matches!(b, b'\r' | b'\n')) {
let t = mouth.next(&state, &mut reads).unwrap().unwrap();
assert_eq!(t.kind, TokenKind::Character(char::from(b), CatCode::Other));
@@ -1,6 +1,6 @@
//! Online TeX page construction over owned contributions, independent of paint.
use super::*;
use std::collections::{BTreeSet, VecDeque};
use std::collections::VecDeque;
const AWFUL: i64 = 1_073_741_823;
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -178,7 +178,7 @@ impl NativePageState {
pub(super) fn advance(
&mut self,
state: &mut State,
reads: &mut BTreeSet<Dependency>,
reads: &mut super::DependencyReads,
steps: &mut usize,
limit: usize,
observations: &mut Vec<PageObservation>,
@@ -34,7 +34,7 @@ pub(super) fn find_break(
height: i64,
max_depth: i32,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut super::DependencyReads,
steps: &mut usize,
limit: usize,
mut ignored_shrink: impl FnMut() -> Result<(), String>,
@@ -1,5 +1,5 @@
//! XeTeX physical input encodings. Decoded units retain their source bytes.
use std::{collections::BTreeSet, sync::Arc};
use std::sync::Arc;
use super::{Dependency, Parameter, ParameterValue, State};
@@ -121,7 +121,7 @@ impl Encoding {
data: &[u8],
base: usize,
state: &State,
reads: &mut BTreeSet<Dependency>,
reads: &mut super::DependencyReads,
) -> Result<(Vec<Character>, usize), String> {
let (mut characters, warnings) = self.decode(data, base)?;
let parameter = Parameter::XeTeXinputnormalization;