//! Native job state and I/O ordering. Memory streams are host test doubles; //! separate CLI/pdfTeX tests exercise real filesystem handles and byte output. #[path = "support/font_world.rs"] mod font_world; use font_world::FontFiles; use std::collections::BTreeMap; use texrra_tex_core::execution::*; #[derive(Default)] struct Files { data: BTreeMap, inputs: BTreeMap, outputs: BTreeMap, diagnostics: Vec<(WriteDestination, String)>, } impl SourceProvider for Files { font_world::font_resources!(); fn read(&mut self, name: &str, _: &str) -> Result { Ok(SourceFile { name: name.into(), data: (self.data.get(name).ok_or("missing source")?.clone()) .as_bytes() .to_vec(), }) } fn open_in(&mut self, stream: u8, name: &str, _: &str) -> Result, String> { if name == "denied" { return Err("input denied".into()); } if !self.data.contains_key(name) { return Ok(None); } self.inputs.insert(stream, (name.into(), 0)); Ok(Some(name.into())) } fn read_line(&mut self, stream: u8) -> Result>, String> { let (name, offset) = self.inputs.get_mut(&stream).ok_or("closed input")?; let text = &self.data[name]; if *offset == text.len() { return Ok(None); } let remaining = &text[*offset..]; let mut length = remaining.find(['\r', '\n']).unwrap_or(remaining.len()); if remaining.as_bytes().get(length) == Some(&b'\r') { length += 1; } if remaining.as_bytes().get(length) == Some(&b'\n') { length += 1; } let line = remaining[..length].to_owned(); *offset += length; Ok(Some(line.into_bytes())) } fn close_in(&mut self, stream: u8) -> Result<(), String> { self.inputs.remove(&stream); Ok(()) } fn open_out(&mut self, stream: u8, name: &str, _: &str) -> Result { if name == "denied" { return Err("output denied".into()); } self.data.insert(name.into(), String::new()); self.outputs.insert(stream, name.into()); Ok(name.into()) } fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> { let name = self.outputs.get(&stream).ok_or("closed output")?; self.data.get_mut(name).unwrap().push_str(text); Ok(()) } fn close_out(&mut self, stream: u8) -> Result<(), String> { self.outputs.remove(&stream); Ok(()) } fn diagnostic(&mut self, destination: WriteDestination, text: &str) -> Result<(), String> { self.diagnostics.push((destination, text.into())); Ok(()) } } fn file(text: &str) -> SourceFile { SourceFile { name: "job.tex".into(), data: text.as_bytes().to_vec(), } } fn run(text: &str, files: &mut Files) -> Execution { Executor::new(State::default().with_etex(), Limits::default()) .run(file(text), files) .unwrap() } fn messages(e: &Execution) -> Vec { e.events .iter() .filter_map(|e| match e { Event::Message { text, .. } => Some(text.clone()), _ => None, }) .collect() } #[test] fn job_time_is_required_validated_scoped_and_tracked() { let error = Executor::default() .run(file(r"\number\time"), &mut FontFiles) .unwrap_err(); assert!(error.message.contains("host job time was not provided")); assert!(JobTime::new(2100, 2, 29, 0).is_err()); assert!(JobTime::new(2032, 2, 29, 1440).is_err()); let time = JobTime::new(2032, 2, 29, 1439).unwrap(); let e = Executor::new(State::default().with_job_time(time), Limits::default()) .run( file(r"{\time=1 {\global\year=2040}}\message{\the\year/\the\month/\the\day/\the\time}"), &mut FontFiles, ) .unwrap(); assert_eq!(messages(&e), ["2040/2/29/1439"]); assert!( e.reads .contains(&Dependency::JobParameter(JobParameter::Time)) ); let copy: Execution = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); assert_eq!(copy, e); } #[test] fn read_distinguishes_just_open_last_line_eof_and_missing_file() { let mut files = Files::default(); files .data .insert("data".into(), "one\r\ntwo\rthree\n".into()); let e = run( concat!( r"\openin0=data \ifeof0\errmessage{premature EOF}\fi ", r"\read0 to\a \read0 to\b \read0 to\c \ifeof0\errmessage{premature EOF}\fi ", r"\read0 to\d \def\blank{\par}\ifx\blank\d\else\errmessage{bad EOF line}\fi ", r"\ifeof0\message{EOF}\else\errmessage{missing EOF}\fi ", r"\openin1=missing \ifeof1\message{MISSING}\fi \message{\a/\b/\c}" ), &mut files, ); assert_eq!(messages(&e), ["EOF", "MISSING", "one /two /three "]); assert!(e.reads.contains(&Dependency::InputStream(0))); let input = e.sources.iter().find(|s| s.name == "data").unwrap(); assert_eq!(input.data, b"one\r\ntwo\rthree\n"); assert!(e.reads.contains(&Dependency::FileLookup { name: "missing".into(), from: "job.tex".into() })); } #[test] fn read_balances_lines_preserves_tokens_and_honors_global_definition() { let mut files = Files::default(); files .data .insert("data".into(), "{A\nB}\n#1\\undefined%comment\n".into()); let e = run( r"\openin0=data {\global\read0 to\a}\catcode65=12 \read0 to\b \message{\meaning\a/\meaning\b}", &mut files, ); assert_eq!(messages(&e), [r"macro:->{A B} /macro:->##1\undefined "]); let Meaning::Macro(a) = e.state.meaning(&CommandName::Control("a".into())) else { panic!() }; assert!(a.replacement.iter().any(|r| matches!( r, Replacement::Token(Token { kind: TokenKind::Character('A', CatCode::Letter), .. }) ))); let continued = Executor::from_execution(e, Limits::default()) .run(file(r"\read0 to\eof\ifeof0\message{DONE}\fi"), &mut files) .unwrap(); assert_eq!(messages(&continued), ["DONE"]); } #[test] fn readline_is_raw_and_eof_is_a_physical_read_attempt() { let mut files = Files::default(); files.data.insert("raw".into(), "%\\x {^^41 \n".into()); let e = run( r"\openin2=raw \endlinechar=-1 \readline2 to\a \message{\meaning\a}\readline2 to\b\ifeof2\message{DONE}\fi", &mut files, ); assert_eq!(messages(&e), [r"macro:->%\x {^^41", "DONE"]); let Meaning::Macro(a) = e.state.meaning(&CommandName::Control("a".into())) else { panic!() }; assert!(a.replacement.iter().all(|r| matches!( r, Replacement::Token(Token { kind: TokenKind::Character(_, CatCode::Other | CatCode::Space), .. }) ))); } #[test] fn immediate_streams_roundtrip_and_route_terminal_log_separately() { let mut files = Files::default(); let e = run( r"\def\a{DATA}\immediate\openout0=result \immediate\write0{\a}\immediate\closeout0 \openin1=result \endlinechar=-1 \read1 to\b \message{\b}\closein1 \immediate\write16{TERM}\immediate\write-1{LOG}\immediate\write3{CLOSED}", &mut files, ); assert_eq!(files.data["result"], "DATA\n"); assert_eq!(messages(&e), ["DATA"]); assert_eq!( files.diagnostics, [ (WriteDestination::TerminalAndLog, "TERM\n".into()), (WriteDestination::Log, "LOG\n".into()), (WriteDestination::TerminalAndLog, "CLOSED\n".into()) ] ); } #[test] fn deferred_whatsits_execute_only_when_shipped_and_expand_at_shipout() { let mut files = Files::default(); let e = run( r"\def\a{EARLY}\openout0=result \write0{\a}\closeout0 \def\a{LATE}", &mut files, ); assert!(!files.data.contains_key("result")); assert!(e.document().unwrap_err().message.contains("native shipout")); let nodes: Vec<_> = e .events .iter() .filter_map(|e| match e { Event::DeferredOutput(n) => Some(n.clone()), _ => None, }) .collect(); let shipped = Executor::from_execution(e, Limits::default()) .shipout_io(&nodes, &mut files) .unwrap(); assert_eq!(files.data["result"], "LATE\n"); // TeX independently ships one box and discards another. Native mode/list // integration is pending; this checks the real native shipout-I/O API. let directory = std::env::temp_dir().join(format!("texrra-shipout-{}", std::process::id())); std::fs::create_dir_all(&directory).unwrap(); std::fs::write( directory.join("probe.tex"), concat!( "\\catcode123=1 \\catcode125=2\n", r"\pdfpagewidth=100pt \pdfpageheight=100pt \def\a{EARLY}", r"\setbox0=\hbox{\openout0=result.dat \write0{\a}\closeout0}", r"\setbox1=\hbox{\openout1=discard.dat \write1{BAD}}", r"\def\a{LATE}\shipout\box0\end" ), ) .unwrap(); match std::process::Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&directory) .output() { Ok(output) => { assert!( output.status.success(), "{}", String::from_utf8_lossy(&output.stdout) ); assert_eq!( std::fs::read_to_string(directory.join("result.dat")).unwrap(), files.data["result"] ); assert!(!directory.join("discard.dat").exists()); eprintln!("native deferred shipout/discard matches real pdfTeX"); } Err(e) if e.kind() == std::io::ErrorKind::NotFound => { eprintln!("pdftex unavailable: shipout oracle skipped") } Err(e) => panic!("{e}"), } std::fs::remove_dir_all(directory).unwrap(); let e = Executor::from_execution(shipped, Limits::default()) .run(file(r"\def\a{AGAIN}"), &mut files) .unwrap(); Executor::from_execution(e, Limits::default()) .shipout_io(&nodes, &mut files) .unwrap(); assert_eq!(files.data["result"], "AGAIN\n"); } #[test] fn actual_io_failures_bad_streams_and_runaway_reads_are_errors() { for source in [ r"\openin16=x", r"\immediate\openout16=x", r"\openin0=denied", r"\immediate\openout0=denied", r"\read0 to\x", r"\read-1 to\x", r"\openin0=data \read0 to\x", ] { let mut files = Files::default(); files.data.insert("data".into(), "{unclosed\n".into()); assert!( Executor::default().run(file(source), &mut files).is_err(), "{source}" ); } assert!( Executor::default() .run(file(r"\immediate\write0{X}"), &mut FontFiles) .unwrap_err() .message .contains("diagnostic sink unavailable") ); }