//! Real token scheduling, not parameters registered to pass startup guards. #[path = "support/font_world.rs"] mod font_world; use std::{ fs, process::Command, sync::atomic::{AtomicU64, Ordering}, }; use texrra_tex_core::execution::*; const HEADER: &str = r"\catcode123=1\catcode125=2\catcode35=6\def\report#1{\immediate\write16{AUDIT=#1;}}"; #[derive(Default)] struct Host { output: Vec, } impl SourceProvider for Host { font_world::font_resources!(); fn read(&mut self, _: &str, _: &str) -> Result { Err("no input source".into()) } fn diagnostic(&mut self, _: WriteDestination, text: &str) -> Result<(), String> { self.output.push(text.into()); Ok(()) } } fn run(source: &str) -> Execution { Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap() } fn marks(e: &Execution) -> Vec { e.events .iter() .filter_map(|e| { if let Event::Write { text, .. } = e { text.strip_prefix("AUDIT=") .map(|s| s.trim_end_matches('\n').to_owned()) } else { None } }) .collect() } fn compare(label: &str, body: &str) -> Execution { static ID: AtomicU64 = AtomicU64::new(0); let dir = std::env::temp_dir().join(format!( "texrra-schedule-{}-{}", std::process::id(), ID.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&dir).unwrap(); let source = format!("{HEADER}\n{body}\n\\end\n"); fs::write(dir.join("probe.tex"), &source).unwrap(); let e = run(&source); let o = Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&dir) .output() .expect("real INITEX required"); let terminal = String::from_utf8(o.stdout).unwrap(); assert!(o.status.success(), "{label}: {terminal}"); let expected: Vec<_> = terminal .lines() .filter_map(|l| l.strip_prefix("AUDIT=").map(str::to_owned)) .collect(); assert!(!expected.is_empty(), "{label}: {terminal}"); assert_eq!(marks(&e), expected, "{label}: {source}\n{terminal}"); fs::remove_dir_all(dir).unwrap(); e } #[test] fn futurelet_copies_raw_meanings_preserves_both_tokens_and_honors_scope() { for (name, body) in [ ( "primitive", r"\def\A{\ifx\peek\relax\report{YES}\else\report{BAD}\fi}\futurelet\peek\A\relax", ), ( "raw-macro", r"\def\value{\relax}\def\A{\ifx\peek\value\report{RAW}\else\report{BAD}\fi}\futurelet\peek\A\value", ), ( "active", r"\catcode33=13\def\A{\ifx!\relax\report{ACTIVE}\else\report{BAD}\fi}\futurelet!\A\relax", ), ( "local", r"\def\peek{OLD}\let\old\peek\def\A{\report{IN}}{\futurelet\peek\A\relax}\ifx\peek\old\report{LOCAL}\else\report{BAD}\fi", ), ( "global", r"\def\A{\report{IN}}{\global\futurelet\peek\A\relax}\ifx\peek\relax\report{GLOBAL}\else\report{BAD}\fi", ), ( "globaldefs-negative", r"\def\peek{OLD}\let\old\peek\def\A{\report{IN}}{\globaldefs=-1\global\futurelet\peek\A\relax}\ifx\peek\old\report{LOCAL}\else\report{BAD}\fi", ), ] { compare(name, body); } } #[test] fn afterassignment_runs_after_actual_assignments_including_box_entry_and_early_return_paths() { for (name, body) in [ ( "integer", r"\def\A{\report{FIRE=\the\count0}}\afterassignment\A\count0=13\relax\report{DONE}", ), ( "definition", r"\def\A{\report{\meaning\x}}\afterassignment\A\def\x{DEFINED}", ), ( "toks-alias", r"\toksdef\t=0\def\A{\report{\the\t}}\afterassignment\A\t={TOKENS}", ), ( "register-arithmetic", r"\skip0=1pt\def\A{\report{\the\skip0}}\afterassignment\A\advance\skip0 by2pt", ), ( "parameter-arithmetic", r"\hsize=1pt\def\A{\report{\the\hsize}}\afterassignment\A\advance\hsize by2pt", ), ( "font-selection", r"\font\rm=cmr10\def\A{\report{FONT}}\afterassignment\A\rm\report{DONE}", ), ( "box-entry", r"\def\A{\report{FIRE=\the\currentgrouplevel}\count0=9}\afterassignment\A\setbox0=\hbox{\report{BODY=\the\count0}}\report{OUT=\the\count0}", ), ( "box-copy", r"\setbox0=\hbox{}\def\A{\report{FIRE=\the\currentgrouplevel}}\afterassignment\A\setbox1=\copy0\report{DONE}", ), ( "global-slot", r"\def\A{\report{FIRE=\the\currentgrouplevel}}{\afterassignment\A}\count0=7\relax\report{DONE}", ), ( "replace", r"\def\A{\report{A}}\def\B{\report{B}}\afterassignment\A\afterassignment\B\count0=1\relax", ), ( "relax-is-not-assignment", r"\def\A{\report{AFTER}}\afterassignment\A\relax\report{BEFORE}\count0=1\relax", ), ( "futurelet-assignment", r"\def\callback{\report{AFTER}}\def\A{\report{FIRST}}\afterassignment\callback\futurelet\peek\A\relax", ), ] { compare(name, body); } } #[test] fn aftergroup_runs_in_registration_order_after_unsave_for_native_group_types() { for (name, body) in [ ( "simple", r"\def\A{\report{A=\the\count0}}\def\B{\report{B}}{\count0=7\aftergroup\A\aftergroup\B}", ), ( "nested", r"\def\A{\report{A=\the\count0}}\def\B{\report{B=\the\count0}}\begingroup\count0=4 {\count0=7\aftergroup\A}\aftergroup\B\endgroup", ), ("outside", r"\aftergroup\undefined\report{IGNORED}"), ( "hbox", r"\def\A{\report{AFTER=\the\currentgrouplevel/\the\count0}}\setbox0=\hbox{\count0=7\aftergroup\A}\report{BOX=\the\wd0}", ), ( "vbox", r"\def\A{\report{AFTER=\the\currentgrouplevel/\the\count0}}\setbox0=\vbox{\count0=7\aftergroup\A}", ), ( "vtop", r"\def\A{\report{AFTER=\the\currentgrouplevel/\the\count0}}\setbox0=\vtop{\count0=7\aftergroup\A}", ), ] { compare(name, body); } let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); for body in [ r"\def\A{\report{MATH=\the\currentgrouplevel}}\setbox0=\hbox{$x\aftergroup\A$}", r"\def\A{\report{GROUP=\the\currentgrouplevel}}\setbox0=\hbox{${x\aftergroup\A}$}", r"\delcode40=164608\delcode41=168705\def\A{\report{LEFT=\the\currentgrouplevel}}\setbox0=\hbox{$\left(x\aftergroup\A\right)$}", ] { compare("math-groups", &format!("{fonts}\n{body}")); } } #[test] fn pending_assignment_roundtrips_and_errors_and_group_queues_are_bounded() { let bootstrap = run(&format!( "{HEADER}\\def\\A{{\\report{{RESUMED=\\the\\count0}}}}\\afterassignment\\A" )); assert!(bootstrap.after_assignment.is_some()); let copy: Execution = serde_json::from_slice(&serde_json::to_vec(&bootstrap).unwrap()).unwrap(); assert_eq!(copy, bootstrap); let result = Executor::from_execution(copy, Limits::default()) .run( SourceFile { name: "next.tex".into(), data: (r"\count0=8 \end").as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap(); assert_eq!(marks(&result), ["RESUMED=8;"]); let source = format!("{HEADER}{{{} }}", "\\aftergroup\\relax ".repeat(25)); let error = Executor::new( State::initex().with_etex(), Limits { tokens: 20, ..Limits::default() }, ) .run( SourceFile { name: "queue.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!( error.message.contains("aftergroup token capacity"), "{}", error.message ); let error = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "callback.tex".into(), data: (format!("{HEADER}\\afterassignment\\undefined\\count0=5 \\end")) .as_bytes() .to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!(error.message.contains("undefined native control sequence")); assert!( error .context .frames .iter() .any(|f| matches!(f.kind, ContextKind::BackedUp { .. })) ); } #[test] fn scheduled_error_contexts_are_actual_backed_up_frames_like_initex() { static ID: AtomicU64 = AtomicU64::new(0); for body in [ r"\afterassignment\bad\count0=5\relax", r"{\aftergroup\bad}", r"\def\A{\bad\relax}{\aftergroup\A}", r"\def\A{\relax}\futurelet\peek\A\bad", ] { let source = format!("{HEADER}\\errorcontextlines=100\n{body}\n\\end\n"); let error = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_err(); let dir = std::env::temp_dir().join(format!( "texrra-schedule-fatal-{}-{}", std::process::id(), ID.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("probe.tex"), source).unwrap(); let o = Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&dir) .output() .expect("real INITEX required"); assert_eq!(o.status.code(), Some(1)); let terminal = String::from_utf8(o.stdout).unwrap(); let exact = terminal .split_once("! Undefined control sequence.\n") .unwrap() .1 .split_once("No pages of output.") .unwrap() .0; assert_eq!(error.context.text, exact, "{body}: {terminal}"); fs::remove_dir_all(dir).unwrap(); } } #[test] fn mode_hooks_execute_at_actual_entry_and_preserve_scope_and_assignment_order() { let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); for (name, body) in [ ( "everypar", r"\everypar={\report{EP=\the\currentgrouplevel}}\noindent A\par B\par\setbox0=\hbox{C}\report{DONE}", ), ( "empty-explicit-par", r"\everypar={\report{EP}}\noindent\par\indent\par\par\report{DONE}", ), ( "everybox", r"\everyhbox={\report{EH=\the\currentgrouplevel}}\everyvbox={\report{EV=\the\currentgrouplevel}}\setbox0=\hbox{A}\setbox1=\vbox{\hbox{B}}\setbox2=\vtop{}", ), ( "everymath-display", r"\everypar={\report{EP}}\everymath={\report{EM=\the\currentgrouplevel}}\everydisplay={\report{ED=\the\currentgrouplevel}}\noindent A$x$B\par\noindent C$$y$$D\par", ), ( "box-callback-order", r"\everyhbox={\report{EVERY}}\def\A{\report{AFTER}}\afterassignment\A\setbox0=\hbox{\report{BODY}}", ), ( "scope", r"\everyhbox={\report{OUTER}}{\everyhbox={\report{INNER}}\setbox0=\hbox{}}\setbox0=\hbox{}", ), ( "global", r"{\global\everyhbox={\report{GLOBAL}}}\setbox0=\hbox{}\everyhbox={}\setbox0=\hbox{}\report{DONE}", ), ( "globaldefs-negative", r"\everyhbox={\report{OUTER}}{\globaldefs=-1\global\everyhbox={\report{LOCAL}}\setbox0=\hbox{}}\setbox0=\hbox{}", ), ( "token-alias", r"\let\h\everyhbox\toks0={\report{TOKS}}\h=\toks0\setbox0=\hbox{}\toks1=\h\h={}\everyhbox=\toks1\setbox0=\hbox{}", ), ( "self-replacement", r"\everyhbox={\report{OLD}\everyhbox={\report{NEW}}\report{OLDREST}}\setbox0=\hbox{}\setbox0=\hbox{}", ), ( "hook-assignment-callback", r"\def\A{\report{ASSIGNED=\the\everypar}}\afterassignment\A\everypar={\relax}\report{DONE}", ), ] { compare(name, &format!("{fonts}\n{body}")); } } #[test] fn mode_hook_assignments_change_first_glyph_lists_and_measured_geometry() { let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); for body in [ r"\nullfont\everypar={\tenrm\hsize=50pt}\setbox0=\vbox{\noindent ABC words to break into more lines.\par}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", r"\chardef\first=65\everypar={\chardef\first=66}\setbox0=\vbox{\first\par}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", r"\count0=65\everypar={\count0=66}\setbox0=\vbox{\char\count0\par}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", r"\everyhbox={A}\setbox0=\hbox{BC}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", r"\everyvbox={\hbox{A}}\setbox0=\vbox{\hbox{B}}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", r"\everymath={\fam=0}\setbox0=\hbox{$x$}\report{BOX=\the\wd0/\the\ht0/\the\dp0}", ] { let e = compare("hook-geometry", &format!("{fonts}\n{body}")); assert!(!e.events.iter().any(|e| matches!(e, Event::MissingGlyph(_)))); } } #[test] fn hook_state_snapshots_use_shared_bodies_and_recursive_entry_is_bounded() { let e = run(&format!( "{HEADER}\\everyhbox={{\\report{{HOOK}}}}\\let\\h\\everyhbox" )); let copy: Execution = serde_json::from_slice(&serde_json::to_vec(&e).unwrap()).unwrap(); assert_eq!(copy, e); let e = Executor::from_execution(copy, Limits::default()) .run( SourceFile { name: "hook-next.tex".into(), data: (r"\setbox0=\hbox{}\end").as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap(); assert_eq!(marks(&e), ["HOOK;"]); assert!( e.reads .contains(&Dependency::TokenParameter(TokenParameter::Everyhbox)) ); let error = Executor::new( State::initex().with_etex(), Limits { steps: 2000, tokens: 10_000, input_depth: 40, }, ) .run( SourceFile { name: "recursive-hook.tex".into(), data: (format!("{HEADER}\\everypar={{\\par}}A")) .as_bytes() .to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!(error.message.contains("step limit"), "{}", error.message); let error = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "recursive-box.tex".into(), data: (format!("{HEADER}\\everyhbox={{\\hbox{{}}}}\\setbox0=\\hbox{{}}")) .as_bytes() .to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!( error.message.contains("capacity") || error.message.contains("limit"), "{}", error.message ); } #[test] fn mode_hook_error_frames_match_actual_initex_input_state() { static ID: AtomicU64 = AtomicU64::new(0); let fonts = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); for (parameter, body) in [ (TokenParameter::Everypar, r"\everypar={\bad}A"), ( TokenParameter::Everyhbox, r"\everyhbox={\bad}\setbox0=\hbox{A}", ), ( TokenParameter::Everyvbox, r"\everyvbox={\bad}\setbox0=\vbox{A}", ), (TokenParameter::Everymath, r"\everymath={\bad}\noindent$x$"), ( TokenParameter::Everydisplay, r"\everydisplay={\bad}\noindent$$x$$", ), ] { let source = format!("{HEADER}{fonts}\\errorcontextlines=100\n{body}\n\\end\n"); let error = Executor::new(State::initex().with_etex(), Limits::default()) .run( SourceFile { name: "probe.tex".into(), data: source.as_bytes().to_vec(), }, &mut Host::default(), ) .unwrap_err(); assert!( error .context .frames .iter() .any(|f| f.kind == ContextKind::Hook(parameter)) ); let dir = std::env::temp_dir().join(format!( "texrra-hook-fatal-{}-{}", std::process::id(), ID.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join("probe.tex"), source).unwrap(); let o = Command::new("pdftex") .args([ "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "probe.tex", ]) .current_dir(&dir) .output() .expect("real INITEX required"); assert_eq!(o.status.code(), Some(1)); let terminal = String::from_utf8(o.stdout).unwrap(); let exact = terminal .split_once("! Undefined control sequence.\n") .unwrap() .1 .split_once("No pages of output.") .unwrap() .0; assert_eq!(error.context.text, exact, "{body}: {terminal}"); fs::remove_dir_all(dir).unwrap(); } } #[test] fn ignorespaces_scans_expanded_spacers_without_discarding_explicit_space() { compare( "expanded spacers and explicit space", r"\font\rm=cmr10\rm \def\spacers{ }\def\aliasmaker#1{\let\spaceralias= #1}\aliasmaker{ } \let\explicit=\ \relax \setbox0=\hbox{A\ignorespaces\spacers\spaceralias B} \setbox1=\hbox{A\ignorespaces\spacers\explicit B} \setbox2=\hbox{AB} \setbox3=\hbox{A B} \setbox4=\hbox{A\spacefactor=3000 \ignorespaces\spacers\explicit B} \setbox5=\hbox{A\ignorespaces\relax\spacers B} \report{\number\wd0,\number\wd1,\number\wd2,\number\wd3,\number\wd4,\number\wd5}", ); } #[test] fn explicit_space_in_math_uses_normal_glue_in_each_style() { let setup = include_str!("../../../examples/native-bootstrap/math-fonts.tex"); compare( "explicit space in math", &format!( r"{setup} \spaceskip=2pt plus1pt \let\explicit=\ \relax \setbox0=\hbox{{$ab$}} \setbox1=\hbox{{$a\ignorespaces\explicit b$}} \setbox2=\hbox{{$\scriptstyle ab$}} \setbox3=\hbox{{$\scriptstyle a\ignorespaces\explicit b$}} \report{{\number\wd0,\number\wd1,\number\wd2,\number\wd3}}" ), ); }